Files @ 38bffbeef7d8
Branch filter:

Location: ATITD-Tools/Desert-Paint-Lab/RecipeGenerator.cs

jmaltzen
Fix warning on overwrite from import to warn about the right location
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
/*
 * Copyright (c) 2015, Jason Maltzen

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using System.Threading;

namespace DesertPaintLab
{
    public class NewRecipeEventArgs : EventArgs
    {
        string color;
        PaintRecipe recipe;

        public NewRecipeEventArgs(string color, PaintRecipe recipe)
        {
            this.color = color;
            this.recipe = recipe;
        }

        public string Color
        {
            get {
                return color;
            }
        }

        public PaintRecipe Recipe
        {
            get {
                return recipe;
            }
        }
    }

    public class RecipeGenerator
    {
        protected class SearchNode
        {
            //int initialReagentCount;
            List<uint> reagents;
            public List<uint> Reagents
            {
                get
                {
                    return reagents;
                }
            }

            HashSet<uint> reagentInUse = new HashSet<uint>();
            List<Reagent> costSortedReagents;
            PaintRecipe testRecipe = null;
            public PaintRecipe TestRecipe
            {
                get
                {
                    return testRecipe;
                }
                set
                {
                    testRecipe = value;
                }
            }

            public int InitialCount { get; private set; }
            public uint CurrentTargetQuantity { get; set; }
            public uint MaxQuantity { get; set; }
            public uint UsedQuantity { get; private set; }
            public uint CatalystCount { get; set; }

            uint maxReagents;
            public uint MaxReagents
            {
                get
                {
                    return maxReagents;
                }
                set
                {
                    maxReagents = value;
                    currentWeights = new uint[maxReagents];
                }
            }

            uint[] currentWeights;
            public uint[] CurrentWeights
            {
                get
                {
                    return currentWeights;
                }
            }

            public SearchNode(List<Reagent> costSortedReagents, List<uint> reagents)
            {
                this.costSortedReagents = new List<Reagent>(costSortedReagents);
                this.reagents = new List<uint>(reagents);
                foreach (uint reagentIdx in reagents)
                {
                    reagentInUse.Add(reagentIdx);
                }
                InitialCount = this.reagents.Count;
                MaxReagents = (uint)this.reagents.Count; // better set this later!
                UsedQuantity = 0;
            }

            // top-level search
            public SearchNode(List<Reagent> costSortedReagents, uint startReagent)
            {
                this.costSortedReagents = new List<Reagent>(costSortedReagents);
                this.reagents = new List<uint>();
                this.reagents.Add(NextFreeReagent(startReagent));
                InitialCount = 1; // don't iterate up beyond the start reagent
                MaxReagents = 1;
                UsedQuantity = 0;
            }

            public SearchNode(List<Reagent> costSortedReagents)
            {
                this.costSortedReagents = costSortedReagents;
                this.reagents = new List<uint>();
                this.reagents.Add(NextFreeReagent(0));
                InitialCount = 0;
                MaxReagents = 1;
                UsedQuantity = 0;
            }

            public Reagent Reagent(int idx)
            {
                return costSortedReagents[(int)reagents[idx]];
            }

            public uint LastReagent
            {
                get
                {
                    return reagents[reagents.Count - 1];
                }
            }

            public void RemoveLastReagent()
            {
                uint reagentIdx = reagents[reagents.Count-1];
                ReleaseReagent(reagentIdx);
                if (costSortedReagents[(int)reagentIdx].IsCatalyst)
                {
                    --CatalystCount;
                }
                reagents.RemoveAt(reagents.Count-1);
            }

            public void ReplaceLastReagent(uint reagentIdx)
            {
                uint oldReagentIdx = reagents[reagents.Count-1];
                ReleaseReagent(oldReagentIdx);
                reagents[reagents.Count-1] = reagentIdx;
                if (costSortedReagents[(int)oldReagentIdx].IsCatalyst)
                {
                    --CatalystCount;
                }
                if (costSortedReagents[(int)reagentIdx].IsCatalyst)
                {
                    ++CatalystCount;
                }
            }

            public uint NextFreeReagent(uint startIdx)
            {
                uint idx = startIdx;
                for (; idx < costSortedReagents.Count; ++idx)
                {
                    bool inUse = reagentInUse.Contains(idx);
                    if (inUse == false)
                    {
                        //Console.WriteLine("Found free reagent idx {0}", idx);
                        reagentInUse.Add(idx);
                        return idx;
                    }
                }
                //Console.WriteLine("Failed to find free reagent.");
                return (uint)costSortedReagents.Count;
            }
    
            private void ReleaseReagent(uint reagentIdx)
            {
                reagentInUse.Remove(reagentIdx);
            }
    
            public bool AddNextReagent()
            {
                bool ok = (reagents.Count < MaxReagents);
                if (ok)
                {
                    uint nextReagent = NextFreeReagent(0);
                    reagents.Add(nextReagent);
                    if (costSortedReagents[(int)nextReagent].IsCatalyst)
                    {
                        ++CatalystCount;
                    }
                    InitForQuantity(CurrentTargetQuantity);
                }
                return ok;
            }

            public void InitForQuantity(uint quantity)
            {
                //System.Console.WriteLine("Target quantity: {0}, reagent count: {1}", quantity, reagents.Count);
                CurrentTargetQuantity = quantity;
                if (CurrentTargetQuantity < (10 + CatalystCount))
                {
                    return;
                }
                UsedQuantity = 0;
                uint remainingReagents = ((uint)reagents.Count - CatalystCount);
                uint remainingWeight = CurrentTargetQuantity - CatalystCount;
                for (int i = 0; i < reagents.Count; ++i)
                {
                    Reagent reagent = Reagent(i);
    
                    if (reagent.IsCatalyst)
                    {
                        currentWeights[i] = 1;
                        ++UsedQuantity;
                    }
                    else
                    {
                        uint weight = (uint)Math.Min(remainingWeight - (remainingReagents-1), reagent.RecipeMax);
                        remainingWeight -= weight;
                        currentWeights[i] = weight;
                        UsedQuantity += weight;
                    }
                    --remainingReagents;
                }
            }

            public void SetWeight(int idx, uint quantity)
            {
                UsedQuantity -= currentWeights[idx];
                currentWeights[idx] = quantity;
                UsedQuantity += quantity;
            }

            public void SaveState(StreamWriter writer)
            {
                writer.WriteLine("---SearchNode---");
                writer.WriteLine("MaxReagents: {0}", MaxReagents);
                writer.WriteLine("Reagents: {0}", reagents.Count);
                for (int i = 0; i < reagents.Count; ++i)
                {
                    uint idx = reagents[i];
                    uint weight = currentWeights[i];
                    writer.WriteLine("Reagent: {0},{1},{2}", idx, reagentInUse.Contains(idx) ? 1 : 0, weight);
                }
                // pulled from parent: List<Reagent> costSortedReagents;
                // new on construct: PaintRecipe testRecipe = null;
                writer.WriteLine("CurrentTargetQuantity: {0}", CurrentTargetQuantity);
                writer.WriteLine("MaxQuantity: {0}", MaxQuantity);
                writer.WriteLine("UsedQuantity: {0}", UsedQuantity);
                writer.WriteLine("CatalystCount: {0}", CatalystCount);
                writer.WriteLine("InitialCount: {0}", InitialCount);
                writer.WriteLine("---EndNode---");
                
            }

            static Regex keyValueRegex = new Regex(@"(\w+)\:\s*(.*)\s*$");
            static Regex reagentPartsRegex = new Regex(@"(?<id>\d+),(?<inUse>\d+),(?<weight>\d+)");
            public bool LoadState(StreamReader reader)
            {
                string line = reader.ReadLine();
                if (!line.Equals("---SearchNode---"))
                {
                    return false;
                }

                bool success = true;
                Match match;
                int reagentIdx = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Equals("---EndNode---"))
                    {
                        break;
                    }
                    match = keyValueRegex.Match(line);
                    if (match.Success)
                    {
                        switch (match.Groups[1].Value)
                        {
                            case "Reagents":
                                {
                                    int reagentCount = int.Parse(match.Groups[2].Value);
                                    reagents = new List<uint>(reagentCount);
                                    reagentInUse.Clear();
                                    reagentIdx = 0;
                                }
                                break;
                            case "Reagent":
                                {
                                    Match reagentInfo = reagentPartsRegex.Match(match.Groups[2].Value);
                                    if (reagentInfo.Success)
                                    {
                                        uint reagentId = uint.Parse(reagentInfo.Groups["id"].Value);
                                        int isInUse = int.Parse(reagentInfo.Groups["inUse"].Value);
                                        uint weight = uint.Parse(reagentInfo.Groups["weight"].Value);
                                        reagents.Add(reagentId);
                                        currentWeights[reagentIdx] = weight;
                                        if (isInUse != 0)
                                        {
                                            reagentInUse.Add(reagentId);
                                        }
                                    }
                                    else
                                    {
                                        success = false;
                                    }
                                }
                                break;
                            case "CurrentTargetQuantity":
                                {
                                    uint value = uint.Parse(match.Groups[2].Value);
                                    CurrentTargetQuantity = value;
                                }
                                break;
                            case "MaxQuantity":
                                {
                                    uint value = uint.Parse(match.Groups[2].Value);
                                    MaxQuantity = value;
                                }
                                break;
                            case "MaxReagents":
                                {
                                    uint value = uint.Parse(match.Groups[2].Value);
                                    MaxReagents = value;
                                }
                                break;
                            case "UsedQuantity":
                                {
                                    uint value = uint.Parse(match.Groups[2].Value);
                                    UsedQuantity = value;
                                }
                                break;
                            case "CatalystCount":
                                {
                                    uint value = uint.Parse(match.Groups[2].Value);
                                    CatalystCount = value;
                                }
                                break;
                            case "InitialCount":
                                {
                                    int value = int.Parse(match.Groups[2].Value);
                                    InitialCount = value;
                                }
                                break;
                            default:
                                success = false;
                                break;
                        }
                    }
                    else
                    {
                        success = false;
                        break;
                    }
                }
                return success;
            }
        }

        const uint DEFAULT_MAX_QUANTITY = 14; // minimum recipe: 10 base + 4 catalysts
        const uint DEFAULT_MAX_REAGENTS = 5;

        //uint maxQuantity; // maximum number of total ingredients
        uint maxReagents; // maximum number of reagents to use in the recipe
        uint fullQuantityDepth; // at or equal this number of reagents, ignore ingredient settings for max quantity
        uint fullQuantity;  // The max number of a reagent to use at full quantity

        ReactionSet reactions;
        bool running = false;

        int runningThreads = 0;
        
        SortedDictionary<string, uint> recipeCosts = new SortedDictionary<string, uint>();
        SortedDictionary<string, PaintRecipe> recipes = new SortedDictionary<string, PaintRecipe>();

        uint totalReagents;

        List<Reagent> costSortedReagents = new List<Reagent>();

        ConcurrentQueue<SearchNode> searchQueue = new ConcurrentQueue<SearchNode>();

        int recipeCount = 0;

        List<Thread> generatorThreads = new List<Thread>();
        Object workerLock = new Object();

        bool requestCancel = false;

        // events
        public event EventHandler Finished;
        public event EventHandler Progress;
        public event EventHandler<NewRecipeEventArgs> NewRecipe;

        public RecipeGenerator(ReactionSet reactions)
        {
            this.reactions = reactions;
        }

        public SortedDictionary<string, PaintRecipe> Recipes
        {
            get
            {
                return recipes;
            }
        }

        public int RecipeCount
        {
            get
            {
                return recipeCount;
            }
        }

        public bool CanResume
        {
            get
            {
                return (!running && (searchQueue.Count > 0));
            }
        }

        private class ReagentCostSort : IComparer<Reagent>
        {
            public int Compare(Reagent reagent1, Reagent reagent2)
            {
                return (int)reagent1.Cost - (int)reagent2.Cost;
            }
        }

        public void InitRecipes(SortedDictionary<string, PaintRecipe> recipes)
        {
            if (running)
            {
                return;
            }
            foreach (PaintRecipe recipe in recipes.Values)
            {
                PaintRecipe recipeCopy = new PaintRecipe(recipe);
                AddCheapestRecipe(recipeCopy);
            }
        }

        private void InitSortedReagents()
        {
            costSortedReagents.Clear();
            foreach (string name in ReagentManager.Names)
            {
                Reagent reagent = ReagentManager.GetReagent(name);
                if (reagent.Enabled)
                {
                    costSortedReagents.Add(reagent);
                }
            }
            costSortedReagents.Sort(new ReagentCostSort());
        }

        public void BeginRecipeGeneration(uint maxQuantity, uint maxReagents, uint fullQuantityDepth, uint fullQuantity)
        {
            if (running)
            {
                // Already running - don't start again
                return;
            }

            //this.maxQuantity = maxQuantity;
            this.maxReagents = maxReagents;
            this.fullQuantity = fullQuantity;
            this.fullQuantityDepth = fullQuantityDepth;

            // first, sort reagents by cost.
            InitSortedReagents();
            this.maxReagents = (uint)Math.Min(costSortedReagents.Count, this.maxReagents);

            totalReagents = (uint)costSortedReagents.Count;

            // Pre-populate recipes list with:
            // 1) 1-ingredient recipes @ 10db for all enabled ingredients with a count >= 10
            // 2) any previously-generated recipes
            foreach (Reagent reagent in costSortedReagents)
            {
                if (!reagent.IsCatalyst && reagent.RecipeMax >= 10)
                {
                    PaintRecipe recipe = new PaintRecipe();
                    recipe.Reactions = reactions;
                    recipe.AddReagent(reagent.Name, 10);
                    AddCheapestRecipe(recipe);
                }
            }

            while (!searchQueue.IsEmpty)
            {
                SearchNode node;
                searchQueue.TryDequeue(out node);
            }
            for (uint reagentIdx = 0; reagentIdx < costSortedReagents.Count; ++reagentIdx)
            {
                SearchNode initialNode = new SearchNode(costSortedReagents, reagentIdx);
                initialNode.MaxQuantity = maxQuantity;
                initialNode.MaxReagents = maxReagents;
                searchQueue.Enqueue(initialNode);
            }
            
            // start worker threads to do the actual work

            ResumeRecipeGeneration();
        }

        public void ResumeRecipeGeneration()
        {
            if (running)
            {
                // Already running - don't start again
                return;
            }
            running = true;
            requestCancel = false;

            //System.Console.WriteLine("Resuming recipe generation: pre-threads={0} reagent count={1} search queue={2}", runningThreads, costSortedReagents.Count, searchQueue.Count);
            runningThreads = 0; // presumably!

            int threadCount = Math.Min(costSortedReagents.Count, searchQueue.Count);
            if (threadCount == 0)
            {
                if (Finished != null)
                {
                    Finished(this, null);
                }
            }
            generatorThreads.Clear();
            for (int i = 0; i < threadCount; ++i)
            {
                Thread thr = new Thread(new ThreadStart(this.Generate));
                generatorThreads.Add(thr);
            }
            foreach (Thread thr in generatorThreads)
            {
                thr.Start();
            }
        }

        public bool SaveState(string file)
        {
            if (running)
            {
                // can't save state while running
                return false;
            }

            using (StreamWriter writer = new StreamWriter(file, false))
            {
                writer.WriteLine("MaxReagents: {0}", maxReagents);
                writer.WriteLine("FullQuantityDepth: {0}", fullQuantityDepth);
                writer.WriteLine("FullQuantity: {0}", fullQuantity);
                writer.WriteLine("TotalReagents: {0}", totalReagents);
                writer.WriteLine("RecipeCount: {0}", recipeCount);
                foreach (KeyValuePair<string, PaintRecipe> pair in recipes)
                {
                    PaintRecipe recipe = pair.Value;
                    string colorName = Palette.FindNearest(recipe.ReactedColor);
                    writer.WriteLine("BeginRecipe: {0}", colorName);
                    foreach (PaintRecipe.RecipeIngredient ingredient in recipe.Ingredients)
                    {
                        writer.WriteLine("Ingredient: {0}={1}", ingredient.name, ingredient.quantity);
                    }
                    writer.WriteLine("EndRecipe: {0}", colorName);
                }
                writer.WriteLine("SearchNodes: {0}", searchQueue.Count);
                foreach (SearchNode node in searchQueue)
                {
                    node.SaveState(writer);
               }
            }
            return true;
        }

        static Regex keyValueRegex = new Regex(@"(?<key>\w+)\:\s*(?<value>.+)\s*");
        static Regex ingredientRegex = new Regex(@"(?<ingredient>(\w+\s)*\w+)\s*=\s*(?<quantity>\d)\s*");
        public bool LoadState(string file)
        {
            // cannot be running, and reactions must be set
            if (running)
            {
                return false;
            }

            InitSortedReagents();
            bool success = true;

            PaintRecipe currentRecipe = null;
            Match match;
            string line;
            using (StreamReader reader = new StreamReader(file, false))
            {
                while (success && ((line = reader.ReadLine()) != null))
                {
                    match = keyValueRegex.Match(line);
                    if (match.Success)
                    {
                        string value = match.Groups["value"].Value;
                        switch(match.Groups["key"].Value)
                        {
                            case "MaxReagents":
                                maxReagents = uint.Parse(value);
                                break;
                            case "FullQuantityDepth":
                                fullQuantityDepth = uint.Parse(value);
                                break;
                            case "FullQuantity":
                                fullQuantity = uint.Parse(value);
                                break;
                            case "TotalReagents":
                                totalReagents = uint.Parse(value);
                                break;
                            case "RecipeCount":
                                recipeCount = int.Parse(value);
                                break;
                            case "BeginRecipe":
                                currentRecipe = new PaintRecipe();
                                currentRecipe.Reactions = reactions;
                                break;
                            case "EndRecipe":
                                if (currentRecipe != null)
                                {
                                    PaintColor color = currentRecipe.ReactedColor;
                                    uint cost = currentRecipe.Cost;
                                    recipes[color.Name] = currentRecipe; // replace
                                    recipeCosts[color.Name] = cost;
                                    currentRecipe = null;
                                }
                                break;
                            case "Ingredient":
                                if (currentRecipe != null)
                                {
                                    Match ingredientMatch = ingredientRegex.Match(match.Groups["value"].Value);
                                    if (ingredientMatch.Success)
                                    {
                                        uint quantity = uint.Parse(ingredientMatch.Groups["quantity"].Value);
                                        currentRecipe.AddReagent(ingredientMatch.Groups["ingredient"].Value, quantity);
                                    }
                                    else
                                    {
                                        success = false;
                                    }
                                }
                                break;
                            case "SearchNodes":
                                int nodeCount = int.Parse(match.Groups["value"].Value);
                                for (int i = 0; i < nodeCount; ++i)
                                {
                                    SearchNode node = new SearchNode(costSortedReagents);
                                    success = success && node.LoadState(reader);
                                    if (success)
                                    {
                                        searchQueue.Enqueue(node);
                                    }
                                }
                                break;
                            default:
                                success = false;
                                break;
                        }
                    }
                    else
                    {
                        success = false;
                        break;
                    }
                }
                return success;
            }
        }

        private void Generate()
        {
            SearchNode node;

            lock(workerLock)
            {
                ++runningThreads;
            }

            bool ok = true;
            do
            {
                lock (workerLock)
                {
                    ok = searchQueue.TryDequeue(out node);
                }
                if (ok)
                {
                    uint targetQuantity = node.MaxQuantity + 1;
                    do {
                        --targetQuantity;
                        node.InitForQuantity(targetQuantity);
                    } while (targetQuantity > 10 && (node.CurrentTargetQuantity != node.UsedQuantity));

                    while ((ok = Iterate(node)) && !requestCancel)
                    {
                        if (Progress != null)
                        {
                            Progress(this, null);
                        }
                    }
                    if (ok)
                    {
                        // stopped because cancel was requested - requeue the node in its current state for resume
                        searchQueue.Enqueue(node);
                    }
                }
            } while (!requestCancel && ok);

            bool done = false;
            lock(workerLock)
            {
                --runningThreads;
                //generatorThreads.Remove(Thread.CurrentThread);

                done = (runningThreads == 0);
            }
            if (done)
            {
                running = false;
                requestCancel = false;
                if (Finished != null)
                {
                    Finished(this, null);
                }
            }
        }

        // Add the cheapest recipe to the recipe list
        // returns the discarded recipe from the pair (or null if no original recipe to replace)
        private PaintRecipe AddCheapestRecipe(PaintRecipe recipe)
        {
            PaintRecipe discarded = recipe;
            if (recipe.IsValid)
            {
                recipe.Reactions = reactions;

                string colorName = Palette.FindNearest(recipe.ReactedColor);
                //System.Console.WriteLine("Recipe: {0} {1}:", colorName, recipe.Cost);
                //foreach (PaintRecipe.RecipeIngredient ingr in recipe.Ingredients)
                //{
                //    System.Console.WriteLine("    -> {0} {1}", ingr.quantity, ingr.name);
                //}
                uint cost;
                lock (workerLock)
                {
                    if (recipeCosts.TryGetValue(colorName, out cost))
                    {
                        if (cost > recipe.Cost)
                        {
                            discarded = recipes[colorName];
                            recipeCosts[colorName] = recipe.Cost;
                            recipes[colorName] = recipe;
                            if (NewRecipe != null)
                            {
                                NewRecipeEventArgs args = new NewRecipeEventArgs(colorName, recipe);
                                NewRecipe(this, args);
                            }
                        }
                    }
                    else
                    {
                        discarded = null;
                        recipeCosts.Add(colorName, recipe.Cost);
                        recipes.Add(colorName, recipe);
                        if (NewRecipe != null)
                        {
                            NewRecipeEventArgs args = new NewRecipeEventArgs(colorName, recipe);
                            NewRecipe(this, args);
                        }
                    }
                }
            }
            //else
            //{
            //    string msg = String.Format("Recipe is invalid ({0} ingredients)\n", recipe.Ingredients.Count);
            //    foreach (PaintRecipe.RecipeIngredient ingr in recipe.Ingredients)
            //    {
            //        msg += String.Format("    -> {0} {1}", ingr.quantity, ingr.name);
            //    }
            //    lock (workerLock) {
            //        Console.WriteLine(msg);
            //    }
            //}
            
            return discarded;
        }

        private bool Iterate(SearchNode node)
        {
            // pick recipe quantities at current recipe ingredients/size
            if (NextRecipe(node))
            {
                lock(workerLock)
                {
                    ++recipeCount;
                }
                //System.Console.WriteLine("Found next recipe at size {0} qty {1}", node.Reagents.Count, node.CurrentTargetQuantity);
                return true;
            }

            if (NextRecipeSize(node))
            {
                //System.Console.WriteLine("Found next recipee size {0}", node.CurrentTargetQuantity);
                return true;
            }

            // Search for next ingredient combo - all quantity combos for previous were searched
            //System.Console.WriteLine("Finding next ingredient combo");
            do
            {
                if (!node.AddNextReagent())
                {
                    while ((node.Reagents.Count > node.InitialCount) && (node.LastReagent == (totalReagents-1)))
                    {
                        node.RemoveLastReagent();
                    }
                    if (node.Reagents.Count == node.InitialCount)
                    {
                        // done
                        return false;
                    }
                    uint nextReagent = node.NextFreeReagent(node.LastReagent);
                    while ((node.Reagents.Count > node.InitialCount) && (nextReagent >= totalReagents))
                    {
                        // No more reagents to try at this level
                        node.RemoveLastReagent();
                        if (node.Reagents.Count > node.InitialCount)
                        {
                            nextReagent = node.NextFreeReagent(node.LastReagent);
                        }
                    }
                    if (node.Reagents.Count == node.InitialCount)
                    {
                        // done
                        return false;
                    }
                    node.ReplaceLastReagent(nextReagent);
                }
            } while (node.MaxQuantity < (10 + node.CatalystCount));
            node.InitForQuantity(node.MaxQuantity);

            //string outStr = "{0} : {1} : ";
            //for (int i = 0; i < currentReagents.Count; ++i)
            //{
            //    Reagent reagent = costSortedReagents[(int)currentReagents[i]];
            //    if (i > 0)
            //    {
            //        outStr += ", ";
            //    }
            //    outStr += reagent.Name + " (" + reagent.Cost + ")";
            //}
            //Console.WriteLine(outStr, currentReagents.Count, recipeCount);
            return true;
        }

        private bool NextRecipe(SearchNode node)
        {
            // First, run the current recipe
            if (node.TestRecipe == null)
            {
                node.TestRecipe = new PaintRecipe();
                node.TestRecipe.Reactions = reactions;
            }
            node.TestRecipe.Clear();
            for (int i = 0; i < node.Reagents.Count; ++i)
            {
                node.TestRecipe.AddReagent(node.Reagent(i).Name, node.CurrentWeights[i]);
            }
            PaintRecipe replacement = AddCheapestRecipe(node.TestRecipe);
            if (replacement == null)
            {
                node.TestRecipe = new PaintRecipe();
                node.TestRecipe.Reactions = reactions;
            }
            else
            {
                node.TestRecipe = replacement;
            }
            
            // check for the next recipe
            uint remainingWeight = node.CurrentTargetQuantity - node.CatalystCount;
            if (remainingWeight < 10)
            {
                // not possible to make a valid recipe
                return false;
            }
            //uint remainingReagents = (uint)node.Reagents.Count - node.CatalystCount;

            uint depth = (uint)node.Reagents.Count;
            uint weightToConsume = 0;
            uint spaceBelow = 0;
            int reagentsBelow = 0;
            for (int i = (int)depth-1 ; i >= 0; --i)
            {
                uint currentWeight = node.CurrentWeights[i];

                if ((spaceBelow >= (weightToConsume+1)) && (currentWeight > 1))
                {
                    // reduce this node by 1, allocate remaining weight to reagents below it
                    node.SetWeight(i, currentWeight-1);
                    weightToConsume += 1;
                    for (int j = i+1; j < depth; ++j)
                    {
                        --reagentsBelow;
                        Reagent reagent = node.Reagent(j);
                        uint allocated = (uint)Math.Min(reagent.IsCatalyst ? 1 : (depth <= fullQuantityDepth ? fullQuantity : reagent.RecipeMax), weightToConsume - reagentsBelow);
                        if (allocated > 100)
                        {
                            Console.WriteLine("ACK: allocated = {0}", allocated);
                        }
                        node.SetWeight(j, allocated);
                        weightToConsume -= allocated;
                    }
                    break;
                }
                else
                {
                    Reagent reagent = node.Reagent(i);
                    spaceBelow += (reagent.IsCatalyst ? 1 : (depth <= fullQuantityDepth ? fullQuantity : reagent.RecipeMax));
                    weightToConsume += currentWeight;
                    ++reagentsBelow;
                }
            }

            //int recipeWeight = 0;
            //foreach (int weight in node.CurrentWeights)
            //{
            //    recipeWeight += weight;
            //}
            //if ((weightToConsume != 0) || (recipeWeight != node.CurrentTargetQuantity))
            //{
            //    Console.WriteLine("Failed recipe with leftover weight {0} ({1}/{2}):", weightToConsume, recipeWeight, node.CurrentTargetQuantity);
            //    for (int i = 0; i < node.Reagents.Count; ++i)
            //    {
            //        Console.WriteLine("   > {0} {1}", node.Reagent(i).Name, node.CurrentWeights[i]);
            //    }
            //}
            
            return (weightToConsume == 0);
        }

        private bool NextRecipeSize(SearchNode node)
        {
            uint newQuantity = node.CurrentTargetQuantity - 1;
            if (newQuantity < (10 + node.CatalystCount))
            {
                return false;
            }

            node.InitForQuantity(newQuantity);
            if (node.CurrentTargetQuantity > node.UsedQuantity)
            {
                return false;
            }

            return true;
        }

        public void Wait()
        {
            if (generatorThreads.Count > 0)
            {
                foreach (Thread thr in generatorThreads)
                {
                    thr.Join();
                }
                generatorThreads.Clear();
            }
        }

        public void Stop()
        {
            this.requestCancel = true;
        }

        public void Reset()
        {
            recipes.Clear();
            recipeCosts.Clear();
        }
    }
}