Changeset - 78ecf5feebe4
[Not reviewed]
default
0 2 0
Jason Maltzen - 9 years ago 2015-12-23 23:52:36
jason@hiddenachievement.com
Fix a crash with potential multi-threaded access to paint recipes.
2 files changed with 17 insertions and 1 deletions:
0 comments (0 inline, 0 general)
PaintRecipe.cs
Show inline comments
 
/*
 
 * 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.Collections.Generic;
 

	
 
namespace DesertPaintLab
 
{
 
    public class PaintRecipe
 
    {
 
        public struct RGB
 
        {
 
            public int r;
 
            public int g;
 
            public int b;
 
        };
 

	
 
        public class RecipeIngredient
 
        {
 
            public string name;
 
            public uint quantity;
 

	
 
            public RecipeIngredient(string name, uint quantity)
 
            {
 
                this.name = name;
 
                this.quantity = quantity;
 
            }
 
        };
 

	
 
        private List<RecipeIngredient> recipe = new List<RecipeIngredient>();
 
        private List<string> reagents = new List<string>();
 

	
 
        private bool dirty = false;
 
        private PaintColor reactedColor = new PaintColor();
 
        private PaintColor baseColor = new PaintColor();
 
        private ReactionSet reactions;
 

	
 
        public PaintRecipe()
 
        {
 
        }
 

	
 
        public PaintRecipe(PaintRecipe other)
 
        {
 
            this.dirty = true;
 
            this.reactions = other.reactions;
 
            foreach (string reagentName in other.reagents)
 
            {
 
                this.reagents.Add(reagentName);
 
            }
 
            foreach (RecipeIngredient copyIngredient in other.recipe)
 
            {
 
                RecipeIngredient ingredient = new RecipeIngredient(copyIngredient.name, copyIngredient.quantity);
 
                this.recipe.Add(ingredient);
 
            }
 
        }
 

	
 
        public List<RecipeIngredient> Ingredients
 
        {
 
            get {
 
                return recipe;
 
            }
 
        }
 

	
 
        public ReactionSet Reactions
 
        {
 
            get
 
            {
 
                return reactions;
 
            }
 
            set
 
            {
 
                dirty = true;
 
                reactions = value;
 
            }
 
        }
 

	
 
        public PaintColor ReactedColor
 
        {
 
            get
 
            {
 
                if (dirty)
 
                {
 
                    ComputeBaseColor();
 
                    ComputeReactedColor();
 
                    dirty = false;
 
                }
 
                return reactedColor;
 
            }
 
        }
 

	
 
        public PaintColor BaseColor
 
        {
 
            get
 
            {
 
                if (dirty)
 
                {
 
                    ComputeBaseColor();
 
                    ComputeReactedColor();
 
                    dirty = false;
 
                }
 
                return baseColor;
 
            }
 
        }
 

	
 
        public void AddReagent(String reagentName)
 
        {
 
            AddReagent(reagentName, 1);
 
        }
 

	
 
        public void AddReagent(String reagentName, uint quantity)
 
        {
 
            if (quantity == 0)
 
            {
 
                return;
 
            }
 
            Reagent reagent = ReagentManager.GetReagent(reagentName);
 
            if (reagent == null)
 
            {
 
                Console.WriteLine("ERROR: invalid reagent {0}", reagentName);
 
                return;
 
            }
 

	
 
            RecipeIngredient ingredient = recipe.Find(x => x.name.Equals(reagentName));
 
            if (ingredient != null)
 
            {
 
                if (!reagent.IsCatalyst)
 
                {
 
                    ingredient.quantity += quantity;
 
                    dirty = true;
 
                }
 
            }
 
            else
 
            {
 
                RecipeIngredient newIngredient = new RecipeIngredient(reagentName, reagent.IsCatalyst ? 1 : quantity);
 
                recipe.Add(newIngredient);
 
                dirty = true;
 
            }
 
            reagents.Add(reagentName);
 
        }
 

	
 
        public void Clear()
 
        {
 
            reagents.Clear();
 
            recipe.Clear();
 
        }
 

	
 
        byte CalculateColor(int baseSum, uint pigmentCount, int reactSum)
 
        {
 
            // Changed to Math.Floor from Math.Round, since Round appears to be incorrect.
 
            return (byte)Math.Max(Math.Min(Math.Floor((((float)baseSum / (float)pigmentCount) + (float)reactSum)), 255), 0);
 
        }
 

	
RecipeGeneratorWindow.cs
Show inline comments
...
 
@@ -107,204 +107,205 @@ namespace DesertPaintLab
 
        {
 
            // TODO: save profile setting
 
            // TODO: no longer permit resume
 
        }
 

	
 
        protected void OnBegin(object sender, EventArgs e)
 
        {
 
            maxIngredientsSpinButton.Sensitive = false;
 
            ExportAction.Sensitive = false;
 
            SettingsAction.Sensitive = false;
 
            maxRecipeSpinButton.Sensitive = false;
 
            beginButton.Sensitive = false; // TODO: change to "pause"?
 
            stopResumeButton.Sensitive = true;
 
            fullQuantitySpinButton.Sensitive = false;
 
            fullQuantityDepthSpinButton.Sensitive = false;
 

	
 
            generator = new RecipeGenerator();
 

	
 
            generator.InitRecipes(profile.Recipes, profile.Reactions);
 
            countLabel.Text = String.Format("{0} / {1}", generator.Recipes.Count, Palette.Count);
 

	
 
            generator.Progress += OnProgress;
 
            generator.Finished += OnFinished;
 
            generator.NewRecipe += OnNewRecipe;
 
            // TODO: hook up event notifications
 
            // - progress
 
            // - complete
 
            // - new recipe / recipe update
 

	
 
            // Total recipe search count
 
            //int current = ReagentManager.Names.Count;
 
            //long recipePermutations = 1;
 
            //for (int i = 0; i < maxIngredientsSpinButton.ValueAsInt; ++i)
 
            //{
 
            //    recipePermutations *= current;
 
            //    --current;
 
            //}
 
            //System.Console.WriteLine("Will search {0} reagent permutations.", recipePermutations);
 

	
 
            lastProgressUpdate = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
 
            lastStatusUpdate = lastProgressUpdate;
 

	
 
            running = true;
 
            stopResumeButton.Label = "Stop";
 

	
 
            generator.BeginRecipeGeneration(profile.Reactions, (uint)maxRecipeSpinButton.ValueAsInt, (uint)maxIngredientsSpinButton.ValueAsInt, (uint)fullQuantityDepthSpinButton.ValueAsInt, (uint)fullQuantitySpinButton.ValueAsInt);
 
        }
 

	
 
        protected void OnStopResume(object sender, EventArgs e)
 
        {
 
            if (generator != null)
 
            {
 
                if (running)
 
                {
 
                    canceling = true;
 
                    generator.Stop();
 
                }
 
                else
 
                {
 
                    // this must be a resume
 
                    lastProgressUpdate = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
 
                    lastStatusUpdate = lastProgressUpdate;
 

	
 
                    canceling = false;
 
                    running = true;
 
        
 
                    stopResumeButton.Label = "Stop";
 
                    generator.BeginRecipeGeneration(profile.Reactions, (uint)maxRecipeSpinButton.ValueAsInt, (uint)maxIngredientsSpinButton.ValueAsInt, (uint)fullQuantityDepthSpinButton.ValueAsInt, (uint)fullQuantitySpinButton.ValueAsInt);
 
                }
 
            }
 
        }
 

	
 
        protected void OnFinished(object sender, EventArgs args)
 
        {
 
            Gtk.Application.Invoke(delegate {
 
                running = false;
 
                beginButton.Sensitive = true;
 
                ExportAction.Sensitive = true;
 
                SettingsAction.Sensitive = true;
 
                stopResumeButton.Sensitive = false;
 
                maxIngredientsSpinButton.Sensitive = true;
 
                maxRecipeSpinButton.Sensitive = true;
 
                fullQuantitySpinButton.Sensitive = true;
 
                fullQuantityDepthSpinButton.Sensitive = true;
 
                //generator = null; // don't. Hang on to generator for resume.
 
                profile.SaveRecipes();
 
                if (canceling)
 
                {
 
                    stopResumeButton.Label = "Resume";
 
                    stopResumeButton.Sensitive = true;
 
                }
 
            });
 
        }
 

	
 
        protected void OnNewRecipe(object sender, NewRecipeEventArgs args)
 
        {
 
            PaintRecipe recipe = new PaintRecipe(args.Recipe); // copy it
 
            Gtk.Application.Invoke(delegate
 
            {
 
                progressBar.Pulse();
 
                // TODO: Add item to recipe list only if not already listed
 
                bool exists = false;
 
                Gtk.TreeIter iter;
 
                if (colorStore.GetIterFirst(out iter))
 
                {
 
                    do
 
                    {
 
                        string color = (string)colorStore.GetValue(iter, 0);
 
                        if (color.Equals(args.Color))
 
                        {
 
                            exists = true;
 
                            break;
 
                        }
 
                    } while (colorStore.IterNext(ref iter));
 
                }
 
                if (!exists)
 
                {
 
                    Console.WriteLine("Add new recipe for {0}", args.Color);
 
                    //    bool isMissingReactions = args.Recipe.CheckMissingReactions(ref missingReactions);
 
                    //    string missingReactionLabel = isMissingReactions ? "X" : "";
 
                    colorStore.AppendValues(args.Color); // , missingReactionLabel);
 
                    countLabel.Text = String.Format("{0} / {1}", generator.Recipes.Count, Palette.Count);
 
                }
 
                profile.SetRecipe(args.Recipe);
 
                profile.SetRecipe(recipe);
 
            });
 
        }
 

	
 
        protected void OnProgress(object sender, EventArgs args)
 
        {
 
            Gtk.Application.Invoke(delegate
 
            {
 
                // TODO: based on time rather than count
 
                long progressTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
 
                long delta = progressTime - lastProgressUpdate;
 
                if (delta > 30)
 
                {
 
                    progressBar.Pulse();
 
                    lastProgressUpdate = progressTime;
 
                }
 
                delta = progressTime - lastStatusUpdate;
 
                if (delta > 500)
 
                {
 
                    // Update recipe count label as well
 
                    statusLabel.Text = String.Format("Recipes searched: {0:N00}", generator.RecipeCount);
 
                    lastStatusUpdate = progressTime;
 
                }
 
                //progressBar.Fraction = (double)((generator.RecipeCount / 10000) % 100) / 100.0;
 
            });
 
        }
 

	
 
        protected void OnColorSelected(object o, EventArgs args)
 
        {
 
            Gtk.TreeModel model;
 
            Gtk.TreeIter iter;
 
            Gtk.TreeSelection selection = recipeList.Selection;
 
            if ((selection != null) && selection.GetSelected(out model, out iter))
 
            {
 
                string colorName = (string)colorStore.GetValue(iter, 0);
 
                PaintRecipe recipe;
 
                if (profile.Recipes.TryGetValue(colorName, out recipe))
 
                {
 
                    foreach (Gtk.Widget child in recipeListBox.AllChildren)
 
                    {
 
                        recipeListBox.Remove(child);
 
                    }
 
                    if (recipe.CheckMissingReactions(ref missingReactions))
 
                    {
 
                        statusLabel.Text = "WARNING: This recipe includes reactions that have not yet been recorded.";
 
                    }
 
                    foreach (PaintRecipe.RecipeIngredient ingredient in recipe.Ingredients)
 
                    {
 
                        Gtk.Label label = new Gtk.Label(ingredient.quantity.ToString() + " " + ingredient.name);
 
                        recipeListBox.PackStart(label);
 
                        label.Show();
 
                    }
 
                }
 
                paintSwatch.Color = recipe.ReactedColor;
 
            }
 
        }
 

	
 
        protected void OnExportToWiki(object sender, EventArgs e)
 
        {
 
            Gtk.FileChooserDialog fileDialog =
 
                new Gtk.FileChooserDialog("Select destination file.",
 
                        this, Gtk.FileChooserAction.Save,
 
                        Gtk.Stock.Cancel, Gtk.ResponseType.Cancel,
 
                        Gtk.Stock.Save, Gtk.ResponseType.Accept);
 
            Gtk.ResponseType resp = (Gtk.ResponseType)fileDialog.Run();
 
            if (resp == Gtk.ResponseType.Accept)
 
            {
 
                string fileName = fileDialog.Filename;
 
                string directory = fileDialog.CurrentFolder;
 
                profile.ExportWikiRecipes(System.IO.Path.Combine(directory, fileName));
 
            }
 
            fileDialog.Destroy();
 
        }
 

	
 
        protected void OnShowIngredients(object sender, EventArgs e)
 
        {
 
            ReagentWindow win = new ReagentWindow(profile);
 
            win.Show();
 
        }
 
    }
 
}
 

	
0 comments (0 inline, 0 general)