Exemplo n.º 1
0
        private void HandleSprinkleOfElement(WorldGenSettings settings, Tag targetTag, Chunk world, SetValuesFunction SetValues, float temperatureMin, float temperatureRange, SeededRandom rnd)
        {
            FeatureSettings feature  = settings.GetFeature(targetTag.Name);
            string          element  = feature.GetOneWeightedSimHash("SprinkleOfElementChoices", rnd).element;
            Element         element2 = ElementLoader.FindElementByName(element);

            ProcGen.Room value = null;
            SettingsCache.rooms.TryGetValue(targetTag.Name, out value);
            SampleDescriber sampleDescriber = value;

            Sim.PhysicsData defaultValues = element2.defaultValues;
            Sim.DiseaseCell invalid       = Sim.DiseaseCell.Invalid;
            for (int i = 0; i < terrainPositions.Count; i++)
            {
                if (!(terrainPositions[i].Value != targetTag))
                {
                    float           radius       = rnd.RandomRange(sampleDescriber.blobSize.min, sampleDescriber.blobSize.max);
                    Vector2         center       = Grid.CellToPos2D(terrainPositions[i].Key);
                    List <Vector2I> filledCircle = ProcGen.Util.GetFilledCircle(center, radius);
                    for (int j = 0; j < filledCircle.Count; j++)
                    {
                        Vector2I vector2I  = filledCircle[j];
                        int      x         = vector2I.x;
                        Vector2I vector2I2 = filledCircle[j];
                        int      num       = Grid.XYToCell(x, vector2I2.y);
                        if (Grid.IsValidCell(num))
                        {
                            defaultValues.mass        = GetDensityMassForCell(world, num, element2.defaultValues.mass);
                            defaultValues.temperature = temperatureMin + world.heatOffset[num] * temperatureRange;
                            SetValues(num, element2, defaultValues, invalid);
                        }
                    }
                }
            }
        }
            private static void Postfix(ProcGen.MutatedWorldData __instance)
            {
                var densityModifier = SizeNotIncludedOptions.Instance.Density();

                foreach (KeyValuePair <string, ElementBandConfiguration> bandConfiguration in __instance.biomes.BiomeBackgroundElementBandConfigurations)
                {
                    foreach (ElementGradient elementGradient in bandConfiguration.Value)
                    {
                        ProcGen.WorldTrait.ElementBandModifier modifier = new ProcGen.WorldTrait.ElementBandModifier();
                        Traverse.Create(modifier).Property("element").SetValue(elementGradient.content);
                        var element = ElementLoader.FindElementByName(elementGradient.content);
                        if (element != null && element.id == SimHashes.Magma)
                        {
                            // no modifier for magma. breaks the bottom of the world
                            Traverse.Create(modifier).Property("massMultiplier").SetValue(1f);
                        }
                        else if (element != null && element.IsLiquid)
                        {
                            // give the player at most 2x liquids otherwise they really break out of the pockets they spawn in
                            Traverse.Create(modifier).Property("massMultiplier").SetValue((float)Math.Min(maxLiquidModifier, densityModifier));
                        }
                        else
                        {
                            // everything else - gasses and solid tiles should just use whatever density modifier the game has
                            Traverse.Create(modifier).Property("massMultiplier").SetValue((float)densityModifier);
                        }
                        elementGradient.Mod(modifier);
                    }
                }
            }
Exemplo n.º 3
0
        public static bool AddRecipe(string Fabricatorid, List <string> ingredients, List <float> ingredientsamount, List <string> results, List <float> resultsamount, float recipetime = 40f)
        {
            int ingreds = ingredients.Count;

            if (ingredientsamount.Count < ingredients.Count)
            {
                ingreds = ingredientsamount.Count;
            }
            int resus = results.Count;

            if (resultsamount.Count < results.Count)
            {
                resus = resultsamount.Count;
            }
            List <ComplexRecipe.RecipeElement> ingredientslist = new List <ComplexRecipe.RecipeElement>();
            List <ComplexRecipe.RecipeElement> resultslist     = new List <ComplexRecipe.RecipeElement>();

            foreach (var i in ingreds.Enumerate())
            {
                ingredientslist.Add(new ComplexRecipe.RecipeElement(ElementLoader.FindElementByName(ingredients.ElementAt(i)).tag, ingredientsamount.ElementAt(i)));
            }
            foreach (var i in resus.Enumerate())
            {
                resultslist.Add(new ComplexRecipe.RecipeElement(ElementLoader.FindElementByName(ingredients.ElementAt(i)).tag, ingredientsamount.ElementAt(i)));
            }
            Co.Add.Recipe(Fabricatorid, ingredientslist.ToArray(), resultslist.ToArray(), recipetime);
            return(true);
        }
Exemplo n.º 4
0
        public void CheckStudyable()
        {
            if (!KMonoBehaviour.isLoadingScene)
            {
                Studyable s = geyser.GetComponent <Studyable>();
                if (s != null && s.Studied)
                {
                    if (s != null)
                    {
                        s.Refresh();
                    }

                    // add delivery task
                    ManualDeliveryKG deliver = geyser.gameObject.AddOrGet <ManualDeliveryKG>();
                    deliver.SetStorage(geyser.GetComponent <Storage>());
                    deliver.requestedItemTag = ElementLoader.FindElementByName("Sulfur").tag;
                    deliver.refillMass       = SingletonOptions <ConfigData> .Instance.KgPerCrack;
                    deliver.capacity         = SingletonOptions <ConfigData> .Instance.KgPerCrack;
                    // deliver.choreTags = GameTags.ChoreTypes.ResearchChores;
                    deliver.choreTypeIDHash = Db.Get().ChoreTypes.ResearchFetch.IdHash;

                    button           = geyser.gameObject.AddOrGet <CrackableButton>();
                    button.crackable = this;
                    UpdateUI();

                    return;
                }
            }
            Invoke("CheckStudyable", 1f);
        }
Exemplo n.º 5
0
            public static void Postfix()
            {
                foreach (ElementEntry entry in elementEntries)
                {
                    var element = ElementLoader.FindElementByName(entry.elementId);
                    if (element == null)
                    {
                        Log.Error($"Element {entry.elementId} was never created");
                        continue;
                    }

                    if (entry.attributeModifiers != null)
                    {
                        foreach (AttributeModifierEntry attr in entry.attributeModifiers)
                        {
                            Log.Spam($"Adding attribute {attr.attributeId} to {entry.elementId}");

                            attr.description = attr.description ?? element.name;
                            element.attributeModifiers.Add(MakeAttributeModifier(attr));
                        }
                    }

                    var exists = ElementLoader.elements.Exists(x => x.id == (SimHashes)Hash.SDBMLower(entry.elementId));
                    if (!exists)
                    {
                        Log.Error($"Element {entry.elementId} was not added to list, only hashtable");
                        continue;
                    }

                    Traverse.Create(element.substance).Field("nameTag").SetValue(element.tag);

                    Log.Spam($"{entry.elementId}: {element.nameUpperCase}, {element.tag} | {Traverse.Create(element.substance).Field("nameTag").GetValue<Tag>()}");
                }
            }
Exemplo n.º 6
0
        internal static void Postfix(ref BuildingDef __result)
        {
            isGas = ElementLoader.FindElementByName(CustomizeBuildingsState.StateManager.State.SteamTurbineOutputElement)?.IsGas ?? false;
            __result.OutputConduitType = isGas ? ConduitType.Gas : ConduitType.Liquid;

            if (CustomizeBuildingsState.StateManager.State.SteamTurbineWattage != SteamTurbineConfig2.MAX_WATTAGE) //850f
            {
                __result.GeneratorWattageRating = CustomizeBuildingsState.StateManager.State.SteamTurbineWattage;
                __result.GeneratorBaseCapacity  = CustomizeBuildingsState.StateManager.State.SteamTurbineWattage;
            }
        }
Exemplo n.º 7
0
        public void ConvertToMap(Chunk world, TerrainCell.SetValuesFunction SetValues, float temperatureMin, float temperatureRange, SeededRandom rnd)
        {
            Element element = ElementLoader.FindElementByName(base.backgroundElement);

            Sim.PhysicsData defaultValues = element.defaultValues;
            Element         element2      = ElementLoader.FindElementByName(base.element);

            Sim.PhysicsData defaultValues2 = element2.defaultValues;
            defaultValues2.temperature = base.temperature;
            Sim.DiseaseCell invalid = Sim.DiseaseCell.Invalid;
            for (int i = 0; i < pathElements.Count; i++)
            {
                Segment         segment    = pathElements[i];
                Vector2         vector     = segment.e1 - segment.e0;
                Vector2         normalized = new Vector2(0f - vector.y, vector.x).normalized;
                List <Vector2I> line       = ProcGen.Util.GetLine(segment.e0, segment.e1);
                for (int j = 0; j < line.Count; j++)
                {
                    for (float num = 0.5f; num <= base.widthCenter; num += 1f)
                    {
                        Vector2 vector2 = (Vector2)line[j] + normalized * num;
                        int     num2    = Grid.XYToCell((int)vector2.x, (int)vector2.y);
                        if (Grid.IsValidCell(num2))
                        {
                            SetValues(num2, element2, defaultValues2, invalid);
                        }
                        Vector2 vector3 = (Vector2)line[j] - normalized * num;
                        num2 = Grid.XYToCell((int)vector3.x, (int)vector3.y);
                        if (Grid.IsValidCell(num2))
                        {
                            SetValues(num2, element2, defaultValues2, invalid);
                        }
                    }
                    for (float num3 = 0.5f; num3 <= base.widthBorder; num3 += 1f)
                    {
                        Vector2 vector4 = (Vector2)line[j] + normalized * (base.widthCenter + num3);
                        int     num4    = Grid.XYToCell((int)vector4.x, (int)vector4.y);
                        if (Grid.IsValidCell(num4))
                        {
                            defaultValues.temperature = temperatureMin + world.heatOffset[num4] * temperatureRange;
                            SetValues(num4, element, defaultValues, invalid);
                        }
                        Vector2 vector5 = (Vector2)line[j] - normalized * (base.widthCenter + num3);
                        num4 = Grid.XYToCell((int)vector5.x, (int)vector5.y);
                        if (Grid.IsValidCell(num4))
                        {
                            defaultValues.temperature = temperatureMin + world.heatOffset[num4] * temperatureRange;
                            SetValues(num4, element, defaultValues, invalid);
                        }
                    }
                }
            }
        }
 public bool FindElement(string elementi, float chanceinpercenti = 100, int targetlayeri = -1, string biomei = "PASS")
 {
     if (coroutineRunning)
     {
         return(false);
     }
     if (coroutinesuccess)
     {
         return(true);
     }
     if (elementi == "PASS")
     {
         return(true);
     }
     if (biomei != "PASS" || string.IsNullOrEmpty(biomei))
     {
         searchbiome = true; biome = biomei;
     }
     this.elementi = elementi;
     targetlayer   = targetlayeri;
     //ExternalFiles.DebugLog(" FindElement  " + elementi + " cr " + coroutineRunning + " ch " + chanceinpercenti + " ro " + revealedtilesonly + " tl " + targetlayeri + " bio " + biomei + searchbiome);
     if (elementi == "ALL")
     {
         if (allpos.Count < 1)
         {
             for (int i = 0; i < Grid.CellCount; i++)
             {
                 allpos[i] = -1;
             }
         }
         foundpos = allpos;
         return(true);
     }
     else
     {
         try { element = ElementLoader.FindElementByName(elementi); } catch { Debug.Log("failed to find the element " + elementi); return(true); }
     }
     chanceinpercent = chanceinpercenti;
     //if (thread == null)
     //{
     //internalelementfinder();
     //return;
     thread          = new System.Threading.Thread(new ThreadStart(this.internalelementfinder));
     thread.Priority = System.Threading.ThreadPriority.BelowNormal;
     thread.Start();
     return(false);
     //}
     //else { thread.Resume(); }
     //ExternalFiles.Log("tried to start thread sucess: " + thread.ThreadState.ToString());
     //this.tmpfinder();
     //Global.Instantiate(Global.FindObjectOfType<GameObject>()).AddComponent<GridOperations>();
     //this.StartCoroutine ("Coroutine");
 }
Exemplo n.º 9
0
    public void SetSprite(Tag t)
    {
        Element element = ElementLoader.FindElementByName(Resource.Name);

        if (element != null)
        {
            Sprite uISpriteFromMultiObjectAnim = Def.GetUISpriteFromMultiObjectAnim(element.substance.anim, "ui", false, string.Empty);
            if ((Object)uISpriteFromMultiObjectAnim != (Object)null)
            {
                image.sprite = uISpriteFromMultiObjectAnim;
            }
        }
    }
Exemplo n.º 10
0
 public void ConvertToMap(Chunk world, TerrainCell.SetValuesFunction SetValues, float temperatureMin, float temperatureRange, SeededRandom rnd)
 {
     Sim.DiseaseCell invalid = Sim.DiseaseCell.Invalid;
     for (int i = 0; i < pathElements.Count; i++)
     {
         Segment         segment    = pathElements[i];
         Vector2         e          = segment.e1;
         Segment         segment2   = pathElements[i];
         Vector2         vector     = e - segment2.e0;
         Vector2         normalized = new Vector2(0f - vector.y, vector.x).normalized;
         Segment         segment3   = pathElements[i];
         Vector2         e2         = segment3.e0;
         Segment         segment4   = pathElements[i];
         List <Vector2I> line       = ProcGen.Util.GetLine(e2, segment4.e1);
         for (int j = 0; j < line.Count; j++)
         {
             Vector2I vector2I  = line[j];
             int      x         = vector2I.x;
             Vector2I vector2I2 = line[j];
             int      num       = Grid.XYToCell(x, vector2I2.y);
             if (Grid.IsValidCell(num))
             {
                 Element         element       = ElementLoader.FindElementByName(WeightedRandom.Choose(this.element, rnd).element);
                 Sim.PhysicsData defaultValues = element.defaultValues;
                 defaultValues.temperature = temperatureMin + world.heatOffset[num] * temperatureRange;
                 SetValues(num, element, defaultValues, invalid);
             }
             for (float num2 = 0.5f; num2 <= width; num2 += 1f)
             {
                 Vector2 vector2 = (Vector2)line[j] + normalized * num2;
                 num = Grid.XYToCell((int)vector2.x, (int)vector2.y);
                 if (Grid.IsValidCell(num))
                 {
                     Element         element2       = ElementLoader.FindElementByName(WeightedRandom.Choose(this.element, rnd).element);
                     Sim.PhysicsData defaultValues2 = element2.defaultValues;
                     defaultValues2.temperature = temperatureMin + world.heatOffset[num] * temperatureRange;
                     SetValues(num, element2, defaultValues2, invalid);
                 }
                 Vector2 vector3 = (Vector2)line[j] - normalized * num2;
                 num = Grid.XYToCell((int)vector3.x, (int)vector3.y);
                 if (Grid.IsValidCell(num))
                 {
                     Element         element3       = ElementLoader.FindElementByName(WeightedRandom.Choose(this.element, rnd).element);
                     Sim.PhysicsData defaultValues3 = element3.defaultValues;
                     defaultValues3.temperature = temperatureMin + world.heatOffset[num] * temperatureRange;
                     SetValues(num, element3, defaultValues3, invalid);
                 }
             }
         }
     }
 }
    private string GetSpawnableName()
    {
        GameObject prefab = Assets.GetPrefab(info.id);

        if ((UnityEngine.Object)prefab == (UnityEngine.Object)null)
        {
            Element element = ElementLoader.FindElementByName(info.id);
            if (element != null)
            {
                return(element.substance.name);
            }
            return(string.Empty);
        }
        return(prefab.GetProperName());
    }
 public override void InitializeStates(out BaseState default_state)
 {
     default_state = idle;
     idle.ToggleMainStatusItem(Db.Get().BuildingStatusItems.Baited).Enter(delegate(StatesInstance smi)
     {
         Element element                    = ElementLoader.FindElementByName(smi.master.baitElement.ToString());
         KAnim.Build build                  = element.substance.anim.GetData().build;
         KAnim.Build.Symbol symbol          = build.GetSymbol(new KAnimHashedString(build.name));
         HashedString target_symbol         = "snapTo_bait";
         SymbolOverrideController component = smi.GetComponent <SymbolOverrideController>();
         component.AddSymbolOverride(target_symbol, symbol, 0);
     }).TagTransition(GameTags.LureUsed, destroy, false);
     destroy.PlayAnim("use").EventHandler(GameHashes.AnimQueueComplete, delegate(StatesInstance smi)
     {
         Util.KDestroyGameObject(smi.master.gameObject);
     });
 }
Exemplo n.º 13
0
    public List <Descriptor> GetDescriptors(BuildingDef def)
    {
        List <Descriptor> list = new List <Descriptor>();
        string            formattedTemperature = GameUtil.GetFormattedTemperature(temperatureDelta, GameUtil.TimeSlice.None, GameUtil.TemperatureInterpretation.Relative, true, false);
        Element           element = ElementLoader.FindElementByName((!isLiquidConditioner) ? "Oxygen" : "Water");
        float             num     = Mathf.Abs(temperatureDelta * element.specificHeatCapacity);
        float             dtu_s   = num * 1f;
        Descriptor        item    = default(Descriptor);
        string            txt     = string.Format((!isLiquidConditioner) ? UI.BUILDINGEFFECTS.HEATGENERATED_AIRCONDITIONER : UI.BUILDINGEFFECTS.HEATGENERATED_LIQUIDCONDITIONER, GameUtil.GetFormattedHeatEnergyRate(dtu_s, GameUtil.HeatEnergyFormatterUnit.Automatic));
        string            tooltip = string.Format((!isLiquidConditioner) ? UI.BUILDINGEFFECTS.TOOLTIPS.HEATGENERATED_AIRCONDITIONER : UI.BUILDINGEFFECTS.TOOLTIPS.HEATGENERATED_LIQUIDCONDITIONER, GameUtil.GetFormattedHeatEnergy(num, GameUtil.HeatEnergyFormatterUnit.Automatic));

        item.SetupDescriptor(txt, tooltip, Descriptor.DescriptorType.Effect);
        list.Add(item);
        Descriptor item2 = default(Descriptor);

        item2.SetupDescriptor(string.Format((!isLiquidConditioner) ? UI.BUILDINGEFFECTS.GASCOOLING : UI.BUILDINGEFFECTS.LIQUIDCOOLING, formattedTemperature), string.Format((!isLiquidConditioner) ? UI.BUILDINGEFFECTS.TOOLTIPS.GASCOOLING : UI.BUILDINGEFFECTS.TOOLTIPS.LIQUIDCOOLING, formattedTemperature), Descriptor.DescriptorType.Effect);
        list.Add(item2);
        return(list);
    }
Exemplo n.º 14
0
 public override void InitializeStates(out BaseState default_state)
 {
     default_state = idle;
     idle.PlayAnim("off", KAnim.PlayMode.Loop).Enter(delegate(StatesInstance smi)
     {
         if (smi.master.activeBaitSetting != Tag.Invalid)
         {
             if (smi.master.baitStorage.IsEmpty())
             {
                 smi.master.CreateFetchChore();
             }
             else if (smi.master.operational.IsOperational)
             {
                 smi.GoTo(working);
             }
         }
     }).EventTransition(GameHashes.OnStorageChange, working, (StatesInstance smi) => !smi.master.baitStorage.IsEmpty() && smi.master.activeBaitSetting != Tag.Invalid && smi.master.operational.IsOperational)
     .EventTransition(GameHashes.OperationalChanged, working, (StatesInstance smi) => !smi.master.baitStorage.IsEmpty() && smi.master.activeBaitSetting != Tag.Invalid && smi.master.operational.IsOperational);
     working.Enter(delegate(StatesInstance smi)
     {
         smi.master.GetComponent <KSelectable>().RemoveStatusItem(Db.Get().BuildingStatusItems.AwaitingBaitDelivery, false);
         HashedString batchTag              = ElementLoader.FindElementByName(smi.master.activeBaitSetting.ToString()).substance.anim.batchTag;
         KAnim.Build build                  = ElementLoader.FindElementByName(smi.master.activeBaitSetting.ToString()).substance.anim.GetData().build;
         KAnim.Build.Symbol symbol          = build.GetSymbol(new KAnimHashedString(build.name));
         HashedString target_symbol         = "slime_mold";
         SymbolOverrideController component = smi.GetComponent <SymbolOverrideController>();
         component.TryRemoveSymbolOverride(target_symbol, 0);
         component.AddSymbolOverride(target_symbol, symbol, 0);
         smi.GetSMI <Lure.Instance>().SetActiveLures(new Tag[1]
         {
             smi.master.activeBaitSetting
         });
     }).Exit(ClearBait).QueueAnim("working_pre", false, null)
     .QueueAnim("working_loop", true, null)
     .EventTransition(GameHashes.OnStorageChange, empty, (StatesInstance smi) => smi.master.baitStorage.IsEmpty() && smi.master.activeBaitSetting != Tag.Invalid)
     .EventTransition(GameHashes.OperationalChanged, idle, (StatesInstance smi) => !smi.master.operational.IsOperational && !smi.master.baitStorage.IsEmpty());
     empty.QueueAnim("working_pst", false, null).QueueAnim("off", false, null).Enter(delegate(StatesInstance smi)
     {
         smi.master.CreateFetchChore();
     })
     .EventTransition(GameHashes.OnStorageChange, working, (StatesInstance smi) => !smi.master.baitStorage.IsEmpty() && smi.master.operational.IsOperational)
     .EventTransition(GameHashes.OperationalChanged, working, (StatesInstance smi) => !smi.master.baitStorage.IsEmpty() && smi.master.operational.IsOperational);
 }
Exemplo n.º 15
0
            // add a recipe in the kiln to make charcoal/ash from wood
            public static void Postfix()
            {
                var charcoalInput1  = Mod.Tags.Log;
                var charcoalOutput1 = TagManager.Create("Charcoal");
                var charcoalOutput2 = TagManager.Create("Ash");
                var amountIn        = 100f;
                var amountOutMost   = 90f;
                var amountOutLeast  = 10f;

                foreach (var element in ElementLoader.elements.FindAll(e => e.IsSolid && e.HasTag(charcoalInput1)))
                {
                    var charcoalInputs = new ComplexRecipe.RecipeElement[1] {
                        new ComplexRecipe.RecipeElement(element.tag, amountIn)
                    };
                    var charcoalOutputs = new ComplexRecipe.RecipeElement[2] {
                        new ComplexRecipe.RecipeElement(charcoalOutput1, amountOutMost),
                        new ComplexRecipe.RecipeElement(charcoalOutput2, amountOutLeast)
                    };

                    var idObsolete = ComplexRecipeManager.MakeObsoleteRecipeID(KilnConfig.ID, charcoalOutput1);
                    var id         = ComplexRecipeManager.MakeRecipeID(KilnConfig.ID, charcoalInputs, charcoalOutputs);

                    var charcoalRecipe = new ComplexRecipe(id, charcoalInputs, charcoalOutputs)
                    {
                        time        = TUNING.BUILDINGS.FABRICATION_TIME_SECONDS.SHORT,
                        description = string.Format(
                            STRINGS.BUILDINGS.PREFABS.METALREFINERY.RECIPE_BYPRODUCT,
                            element.name,
                            ElementLoader.FindElementByName(charcoalOutput1.Name).name,
                            ElementLoader.FindElementByName(charcoalOutput2.Name).name),
                        fabricators = new List <Tag>()
                        {
                            TagManager.Create(KilnConfig.ID)
                        },
                        nameDisplay = ComplexRecipe.RecipeNameDisplay.IngredientToResult
                    };
                    ComplexRecipeManager.Get().AddObsoleteIDMapping(idObsolete, id);
                }
            }
    public override bool Calculate()
    {
        if (!allInputsReady() || base.settings == null)
        {
            return(false);
        }
        IModule3D value = Inputs[0].GetValue <IModule3D>();

        if (value == null)
        {
            return(false);
        }
        InitSettings();
        Vector2f             lowerBound           = base.settings.lowerBound;
        Vector2f             upperBound           = base.settings.upperBound;
        NoiseMapBuilderPlane noiseMapBuilderPlane = new NoiseMapBuilderPlane(lowerBound.x, upperBound.x, lowerBound.y, upperBound.y, base.settings.seamless);

        noiseMapBuilderPlane.SetSize(256, 256);
        noiseMapBuilderPlane.SourceModule = value;
        Vector2 zero = Vector2.zero;

        float[] noise = WorldGen.GenerateNoise(zero, base.settings.zoom, noiseMapBuilderPlane, 256, 256, null);
        if (base.settings.normalise)
        {
            WorldGen.Normalise(noise);
        }
        GetColourDelegate getColourDelegate = null;

        switch (displayType)
        {
        case DisplayType.DefaultColour:
            getColourDelegate = ((int cell) => Color.HSVToRGB((40f + 320f * noise[cell]) / 360f, 1f, 1f));
            break;

        case DisplayType.ElementColourBiome:
        case DisplayType.ElementColourFeature:
            getColourDelegate = delegate(int cell)
            {
                if (biome == null)
                {
                    return(Color.black);
                }
                float   num     = noise[cell];
                Element element = ElementLoader.FindElementByName(biome[biome.Count - 1].content);
                for (int i = 0; i < biome.Count; i++)
                {
                    if (num < biome[i].maxValue)
                    {
                        element = ElementLoader.FindElementByName(biome[i].content);
                        break;
                    }
                }
                return(element.substance.uiColour);
            };
            break;
        }
        if (getColourDelegate != null)
        {
            SetColours(getColourDelegate);
        }
        return(true);
    }
Exemplo n.º 17
0
        public static ElementOverride GetElementOverride(string element, SampleDescriber.Override overrides)
        {
            Debug.Assert(element != null && element.Length > 0);
            ElementOverride result = default(ElementOverride);

            result.element = ElementLoader.FindElementByName(element);
            Debug.Assert(result.element != null, "Couldn't find an element called " + element);
            result.pdelement   = result.element.defaultValues;
            result.dc          = Sim.DiseaseCell.Invalid;
            result.mass        = result.element.defaultValues.mass;
            result.temperature = result.element.defaultValues.temperature;
            if (overrides == null)
            {
                return(result);
            }
            result.overrideMass          = false;
            result.overrideTemperature   = false;
            result.overrideDiseaseIdx    = false;
            result.overrideDiseaseAmount = false;
            if (overrides.massOverride.HasValue)
            {
                result.mass         = overrides.massOverride.Value;
                result.overrideMass = true;
            }
            if (overrides.massMultiplier.HasValue)
            {
                result.mass        *= overrides.massMultiplier.Value;
                result.overrideMass = true;
            }
            if (overrides.temperatureOverride.HasValue)
            {
                result.temperature         = overrides.temperatureOverride.Value;
                result.overrideTemperature = true;
            }
            if (overrides.temperatureMultiplier.HasValue)
            {
                result.temperature        *= overrides.temperatureMultiplier.Value;
                result.overrideTemperature = true;
            }
            if (overrides.diseaseOverride != null)
            {
                result.diseaseIdx         = (byte)WorldGen.GetDiseaseIdx(overrides.diseaseOverride);
                result.overrideDiseaseIdx = true;
            }
            if (overrides.diseaseAmountOverride.HasValue)
            {
                result.diseaseAmount         = overrides.diseaseAmountOverride.Value;
                result.overrideDiseaseAmount = true;
            }
            if (result.overrideTemperature)
            {
                result.pdelement.temperature = result.temperature;
            }
            if (result.overrideMass)
            {
                result.pdelement.mass = result.mass;
            }
            if (result.overrideDiseaseIdx)
            {
                result.dc.diseaseIdx = result.diseaseIdx;
            }
            if (result.overrideDiseaseAmount)
            {
                result.dc.elementCount = result.diseaseAmount;
            }
            return(result);
        }
        public List <StateMachine.BaseDef> chore_table; // TODO: fix exception with constructor

        public void PopulateDefs(GameObject go)
        {
            if (go == null)
            {
                Debug.LogError("PopulateDefs go shouldn't be null!");
            }

            //always
            Add(new DeathStates.Def());
            Add(new AnimInterruptStates.Def());
            Add(new BaggedStates.Def()
            {
                escapeTime = this.bag_escape_time ?? 300f
            });
            Add(new DebugGoToStates.Def());

            //has baby or adult form
            if (go.GetDef <BabyMonitor.Def>() != null || go.GetDef <FertilityMonitor.Def>() != null)
            {
                Add(new GrowUpStates.Def());
                Add(new IncubatingStates.Def());
                Add(new LayEggStates.Def());
            }

            //can fly
            if (go.HasTag(GameTags.Creatures.Flyer))//(go.GetDef<CreatureFallMonitor.Def>() != null)
            {
            }
            else
            {
                Add(new TrappedStates.Def());
                if (!go.HasTag(GameTags.SwimmingCreature))
                {
                    Add(new FallStates.Def());                                        //special case: fish
                }
            }

            //is fish
            if (go.HasTag(GameTags.SwimmingCreature))
            {
                Add(new FallStates.Def {
                    getLandAnim = new Func <FallStates.Instance, string>(GetLandAnim)
                });
                Add(new FlopStates.Def());
                Add(new FixedCaptureStates.Def());
            }
            else
            {
                Add(new StunnedStates.Def());
                Add(new FixedCaptureStates.Def());
                Add(new RanchedStates.Def());
            }

            //can drown
            if (go.GetComponent <DrowningMonitor>() != null)
            {
                Add(new DrowningStates.Def());
            }

            //eats solid
            if (go.GetDef <SolidConsumerMonitor.Def>() != null)
            {
                Add(new EatStates.Def());
            }

            //eats gas/liquids
            if (go.GetDef <GasAndLiquidConsumerMonitor.Def>() != null)
            {
                Add(new InhaleStates.Def());
            }

            //can get lured
            if (go.GetDef <LureableMonitor.Def>() != null)
            {
                Add(new MoveToLureStates.Def());
            }

            //can burrow
            if (go.GetDef <BurrowMonitor.Def>() != null && go.GetDef <FertilityMonitor.Def>() != null)
            {
                Add(new ExitBurrowStates.Def());

                //only adult
                if (go.GetDef <BabyMonitor.Def>() == null)
                {
                    Add(new PlayAnimsStates.Def(GameTags.Creatures.Burrowed, true, "idle_mound", STRINGS.CREATURES.STATUSITEMS.BURROWED.NAME, STRINGS.CREATURES.STATUSITEMS.BURROWED.TOOLTIP));
                    Add(new PlayAnimsStates.Def(GameTags.Creatures.WantsToEnterBurrow, false, "hide", STRINGS.CREATURES.STATUSITEMS.BURROWING.NAME, STRINGS.CREATURES.STATUSITEMS.BURROWING.TOOLTIP));
                }
            }

            //can tunnel
            if (go.GetDef <DiggerMonitor.Def>() != null)
            {
                Add(new DiggerStates.Def());
            }

            //can expulse
            if (go.GetDef <ElementDropperMonitor.Def>() != null)
            {
                Add(new DropElementStates.Def());
            }

            if (this.can_attack)
            {
                Add(new AttackStates.Def());
            }

            if (this.can_flee)
            {
                Add(new FleeStates.Def());
            }

            if (this.can_sleep)
            {
                Add(new CreatureSleepStates.Def());
            }

            if (this.can_call)
            {
                Add(new CallAdultStates.Def());
            }

            //species dependend!
            Tag species = go.GetComponent <CreatureBrain>().species;

            if (species == GameTags.Creatures.Species.MooSpecies || species == GameTags.Creatures.Species.PuftSpecies)
            {
                Add(new IdleStates.Def {
                    customIdleAnim = new IdleStates.Def.IdleAnimCallback(CustomIdleAnim_Moo_Puft)
                });
            }
            else if (species == GameTags.Creatures.Species.DreckoSpecies)
            {
                Add(new IdleStates.Def {
                    customIdleAnim = new IdleStates.Def.IdleAnimCallback(CustomIdleAnim_Drecko)
                });
            }
            else if (species == GameTags.Creatures.Species.MoleSpecies)
            {
                Add(new IdleStates.Def {
                    customIdleAnim = new IdleStates.Def.IdleAnimCallback(CustomIdleAnim_Mole)
                });
            }
            else
            {
                Add(new IdleStates.Def());
            }

            //Crabs
            if (species == GameTags.Creatures.Species.CrabSpecies)
            {
                Add(new DefendStates.Def());
            }

            //Squirrels
            if (species == GameTags.Creatures.Species.SquirrelSpecies)
            {
                Add(new TreeClimbStates.Def());
                Add(new SeedPlantingStates.Def());
            }

            //Pufts
            if (species == GameTags.Creatures.Species.PuftSpecies)
            {
                Add(new UpTopPoopStates.Def());
            }

            //Oilfloaters
            if (species == GameTags.Creatures.Species.OilFloaterSpecies)
            {
                Add(new SameSpotPoopStates.Def());
            }

            //Moles
            if (species == GameTags.Creatures.Species.MoleSpecies)
            {
                try
                {
                    Add((StateMachine.BaseDef)Activator.CreateInstance(Type.GetType("NestingPoopState+Def, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), nesting_poop != null ? nesting_poop.ToTag() : new Tag(0)));
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[CustomizeCritter] Critical error while generating NestingPoopState+Def " + e.Message);
                }
            }

            if (species == GameTags.Robots.Models.SweepBot)
            {
                Add(new SweepBotTrappedStates.Def());
                Add(new DeliverToSweepLockerStates.Def());
                Add(new ReturnToChargeStationStates.Def());
                Add(new SweepStates.Def());
            }

            //poop general rule: must NOT have InhaleStates; must have diet with output
            var diet = go.GetDef <CreatureCalorieMonitor.Def>()?.diet?.infos;

            if (ElementLoader.elements != null && diet != null && diet.Length > 0 && diet[0].producedElement.IsValid)
            {
                switch (ElementLoader.FindElementByName(diet[0].producedElement.ToString()).state)
                {
                case Element.State.Solid:
                    //Mole + Crab + Drecko + Hatch OR Pacu
                    Add(new PlayAnimsStates.Def(GameTags.Creatures.Poop, false, go.HasTag(GameTags.SwimmingCreature) ? "lay_egg_pre" : "poop", STRINGS.CREATURES.STATUSITEMS.EXPELLING_SOLID.NAME, STRINGS.CREATURES.STATUSITEMS.EXPELLING_SOLID.TOOLTIP));
                    break;

                case Element.State.Liquid:
                    //Moo
                    Add(new PlayAnimsStates.Def(GameTags.Creatures.Poop, false, "poop", STRINGS.CREATURES.STATUSITEMS.EXPELLING_GAS.NAME, STRINGS.CREATURES.STATUSITEMS.EXPELLING_GAS.TOOLTIP));
                    break;
                }
            }
            else if (ElementLoader.elements == null)
            {
                Debug.Log("Wups, elements are not loaded yet.");
            }
        }
Exemplo n.º 19
0
 public static Element GetElement(string elementname)
 {
     return(ElementLoader.FindElementByName(elementname));
 }
    private void SetAnimator()
    {
        GameObject prefab = Assets.GetPrefab(info.id.ToTag());

        EdiblesManager.FoodInfo foodInfo = Game.Instance.ediblesManager.GetFoodInfo(info.id);
        int num = (ElementLoader.FindElementByName(info.id) != null) ? 1 : ((foodInfo == null) ? ((int)info.quantity) : ((int)(info.quantity % foodInfo.CaloriesPerUnit)));

        if ((UnityEngine.Object)prefab != (UnityEngine.Object)null)
        {
            for (int i = 0; i < num; i++)
            {
                GameObject gameObject = Util.KInstantiateUI(contentBody, contentBody.transform.parent.gameObject, false);
                gameObject.SetActive(true);
                Image component = gameObject.GetComponent <Image>();
                Tuple <Sprite, Color> uISprite = Def.GetUISprite(prefab, "ui", false);
                component.sprite = uISprite.first;
                component.color  = uISprite.second;
                entryIcons.Add(gameObject);
                if (num > 1)
                {
                    int num2 = 0;
                    int num3 = 0;
                    int num4;
                    if (num % 2 == 1)
                    {
                        num4 = Mathf.CeilToInt((float)(num / 2));
                        num2 = num4 - i;
                        num3 = ((num2 > 0) ? 1 : (-1));
                        num2 = Mathf.Abs(num2);
                    }
                    else
                    {
                        num4 = num / 2 - 1;
                        if (i <= num4)
                        {
                            num2 = Mathf.Abs(num4 - i);
                            num3 = -1;
                        }
                        else
                        {
                            num2 = Mathf.Abs(num4 + 1 - i);
                            num3 = 1;
                        }
                    }
                    int num5 = 0;
                    if (num % 2 == 0)
                    {
                        num5 = ((i > num4) ? 6 : (-6));
                        gameObject.transform.SetPosition(gameObject.transform.position += new Vector3((float)num5, 0f, 0f));
                    }
                    gameObject.transform.localScale = new Vector3(1f - (float)num2 * 0.1f, 1f - (float)num2 * 0.1f, 1f);
                    gameObject.transform.Rotate(0f, 0f, 3f * (float)num2 * (float)num3);
                    gameObject.transform.SetPosition(gameObject.transform.position + new Vector3(25f * (float)num2 * (float)num3, 5f * (float)num2) + new Vector3((float)num5, 0f, 0f));
                    gameObject.GetComponent <Canvas>().sortingOrder = num - num2;
                }
            }
        }
        else
        {
            GameObject gameObject2 = Util.KInstantiateUI(contentBody, contentBody.transform.parent.gameObject, false);
            gameObject2.SetActive(true);
            Image component2 = gameObject2.GetComponent <Image>();
            component2.sprite = Def.GetUISpriteFromMultiObjectAnim(ElementLoader.GetElement(info.id.ToTag()).substance.anim, "ui", false, string.Empty);
            component2.color  = ElementLoader.GetElement(info.id.ToTag()).substance.uiColour;
            entryIcons.Add(gameObject2);
        }
    }
Exemplo n.º 21
0
        public static void Postfix(ref List <GeyserGenericConfig.GeyserPrefabParams> __result)
        {
            GeyserInfo.config = __result;

            for (int j = 0; j < CustomizeGeyserState.StateManager.State.Geysers.Count; j++)
            {
                CustomizeGeyserState.GeyserStruct modifier = CustomizeGeyserState.StateManager.State.Geysers[j];
                if (modifier.id == null)
                {
                    continue;
                }

                Debug.Log("[GeyserModifier] Processing " + modifier.id + " ...");

                #region Error checks
                {
                    if (modifier.anim != null && !GeyserKAnims.Any(s => s == modifier.anim))
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has non standard kAnim type " + modifier.anim));
                        modifier.anim = null;    // TODO: find a way to validate custom kAnims
                    }
                    if (modifier.width != null && modifier.width < 1 || modifier.width > 10)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad width"));
                        modifier.width = null;
                    }
                    if (modifier.height != null && modifier.height < 1 || modifier.height > 10)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad height"));
                        modifier.height = null;
                    }
                    if (modifier.element != null && ElementLoader.FindElementByName(modifier.element) == null)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " element " + modifier.element + " does not exist"));
                        modifier.element = null;
                    }
                    if (modifier.temperature != null && modifier.temperature < 1f || modifier.temperature > 8000f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad temperature"));
                        modifier.temperature = null;
                    }
                    if (modifier.minRatePerCycle != null && modifier.minRatePerCycle < 0f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad minRatePerCycle"));
                        modifier.minRatePerCycle = null;
                    }
                    // maxRatePerCycle later check for min
                    if (modifier.maxPressure != null && modifier.maxPressure < 0f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad maxPressure"));
                        modifier.maxPressure = null;
                    }
                    if (modifier.minIterationLength != null && modifier.minIterationLength < 0f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad minIterationLength"));
                        modifier.minIterationLength = null;
                    }
                    // maxIterationLength later check for min
                    if (modifier.minIterationPercent != null && modifier.minIterationPercent < 0f || modifier.minIterationPercent > 1f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad minIterationPercent"));
                        modifier.minIterationPercent = null;
                    }
                    if (modifier.maxIterationPercent != null && modifier.maxIterationPercent > 1f) // maxIterationPercent later check for min
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad maxIterationPercent"));
                        modifier.maxIterationPercent = null;
                    }
                    if (modifier.minYearLength != null && modifier.minYearLength < 10f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad minYearLength"));
                        modifier.minYearLength = null;
                    }
                    // maxYearLength later check for min
                    if (modifier.minYearPercent != null && modifier.minYearPercent < 0f || modifier.minYearPercent > 1f)
                    {
                        Debug.LogWarning(ToDialog("Warning: Geyser " + modifier.id + " has bad minYearPercent"));
                        modifier.minYearPercent = null;
                    }
                    // maxYearPercent later check for min
                }
                #endregion

                int i = __result.FindIndex(x => x.geyserType.id == modifier.id);

                #region existing geyser
                if (i >= 0)  //edit existing geyser
                {
                    if (modifier.anim != null || modifier.width != null || modifier.height != null)
                    {
                        GeyserGenericConfig.GeyserPrefabParams copy = __result[i];
                        if (modifier.anim != null)
                        {
                            copy.anim = modifier.anim;
                        }
                        if (modifier.width != null)
                        {
                            copy.width = (int)modifier.width;
                        }
                        if (modifier.height != null)
                        {
                            copy.height = (int)modifier.height;
                        }

                        __result[i] = copy;
                    }

                    if (modifier.element != null)
                    {
                        __result[i].geyserType.element = (SimHashes)Hash.SDBMLower(modifier.element);
                    }
                    if (modifier.temperature != null)
                    {
                        __result[i].geyserType.temperature = (float)modifier.temperature;
                    }
                    if (modifier.minRatePerCycle != null)
                    {
                        __result[i].geyserType.minRatePerCycle = (float)modifier.minRatePerCycle;
                    }
                    if (modifier.maxRatePerCycle != null)
                    {
                        __result[i].geyserType.maxRatePerCycle = Math.Max((float)modifier.maxRatePerCycle, __result[i].geyserType.minRatePerCycle);
                    }
                    if (modifier.maxPressure != null)
                    {
                        __result[i].geyserType.maxPressure = (float)modifier.maxPressure;
                    }
                    if (modifier.minIterationLength != null)
                    {
                        __result[i].geyserType.minIterationLength = (float)modifier.minIterationLength;
                    }
                    if (modifier.maxIterationLength != null)
                    {
                        __result[i].geyserType.maxIterationLength = Math.Max((float)modifier.maxIterationLength, __result[i].geyserType.minIterationLength);
                    }
                    if (modifier.minIterationPercent != null)
                    {
                        __result[i].geyserType.minIterationPercent = (float)modifier.minIterationPercent;
                    }
                    if (modifier.maxIterationPercent != null)
                    {
                        __result[i].geyserType.maxIterationPercent = Math.Max((float)modifier.maxIterationPercent, __result[i].geyserType.minIterationPercent);
                    }
                    if (modifier.minYearLength != null)
                    {
                        __result[i].geyserType.minYearLength = (float)modifier.minYearLength;
                    }
                    if (modifier.maxYearLength != null)
                    {
                        __result[i].geyserType.maxYearLength = Math.Max((float)modifier.maxYearLength, __result[i].geyserType.minYearLength);
                    }
                    if (modifier.minYearPercent != null)
                    {
                        __result[i].geyserType.minYearPercent = (float)modifier.minYearPercent;
                    }
                    if (modifier.maxYearPercent != null)
                    {
                        __result[i].geyserType.maxYearPercent = Math.Max((float)modifier.maxYearPercent, __result[i].geyserType.minYearPercent);
                    }

                    if (modifier.Name != null)
                    {
                        Strings.Add("STRINGS.CREATURES.SPECIES.GEYSER." + modifier.id.ToUpper() + ".NAME", modifier.Name);
                    }
                    if (modifier.Description != null)
                    {
                        Strings.Add("STRINGS.CREATURES.SPECIES.GEYSER." + modifier.id.ToUpper() + ".DESC", modifier.Description);
                    }

                    if (modifier.Disease != null || modifier.DiseaseCount != null)
                    {
                        byte diseaseIndex;
                        if (modifier.Disease == null)
                        {
                            diseaseIndex = __result[i].geyserType.diseaseInfo.idx;
                        }
                        else
                        {
                            diseaseIndex = Db.Get().Diseases.GetIndex((HashedString)modifier.Disease);
                        }

                        if (modifier.DiseaseCount == null)
                        {
                            modifier.DiseaseCount = __result[i].geyserType.diseaseInfo.count;
                        }

                        if (diseaseIndex == byte.MaxValue || modifier.DiseaseCount <= 0)
                        {
                            __result[i].geyserType.diseaseInfo = Klei.SimUtil.DiseaseInfo.Invalid;
                        }
                        else
                        {
                            __result[i].geyserType.diseaseInfo = new Klei.SimUtil.DiseaseInfo()
                            {
                                idx = diseaseIndex, count = (int)modifier.DiseaseCount
                            }
                        };
                    }

                    Debug.Log("[GeyserModifier] Changed geyser with id: " + modifier.id);
                }
                #endregion
                #region new geyser
                else    //make new geyser
                {
                    if (modifier.element == null)
                    {
                        Debug.LogWarning(ToDialog("[GeyserModifier] Cannot add geyser with no element: " + modifier.id));
                        continue;
                    }

                    if (ElementLoader.FindElementByName(modifier.element) == null)
                    {
                        Debug.LogWarning(ToDialog("[GeyserModifier] Could not add geyser " + modifier.id + " because element does not exist: " + modifier.element));
                        continue;
                    }

                    if (modifier.anim == null)
                    {
                        Element element = ElementLoader.FindElementByName(modifier.element);
                        if (element.IsGas)
                        {
                            modifier.anim = "geyser_gas_steam_kanim";
                        }
                        else if (element.name.ToLower().Contains("molten"))
                        {
                            modifier.anim = "geyser_molten_iron_kanim";
                        }
                        else
                        {
                            modifier.anim = "geyser_liquid_water_slush_kanim";
                        }
                    }

                    if (modifier.width == null || modifier.height == null)
                    {
                        if (modifier.anim.Contains("_gas_"))
                        {
                            modifier.width  = 2;
                            modifier.height = 4;
                        }
                        else if (modifier.anim.Contains("_molten_"))
                        {
                            modifier.width  = 3;
                            modifier.height = 3;
                        }
                        else
                        {
                            modifier.width  = 4;
                            modifier.height = 2;
                        }
                    }

                    if (modifier.temperature == null)
                    {
                        modifier.temperature = 373.15f;
                    }

                    if (modifier.minRatePerCycle == null)
                    {
                        modifier.minRatePerCycle = 3000f;
                    }

                    if (modifier.maxRatePerCycle == null || modifier.maxRatePerCycle < modifier.minRatePerCycle)
                    {
                        modifier.maxRatePerCycle = modifier.minRatePerCycle;
                    }

                    if (modifier.maxPressure == null)
                    {
                        modifier.maxPressure = 500f;
                    }

                    if (modifier.minIterationLength == null)
                    {
                        modifier.minIterationLength = 600f;
                    }

                    if (modifier.maxIterationLength == null || modifier.maxIterationLength < modifier.minIterationLength)
                    {
                        modifier.maxIterationLength = modifier.minIterationLength;
                    }

                    if (modifier.minIterationPercent == null)
                    {
                        modifier.minIterationPercent = 0.5f;
                    }

                    if (modifier.maxIterationPercent == null || modifier.maxIterationPercent < modifier.minIterationPercent)
                    {
                        modifier.maxIterationPercent = modifier.minIterationPercent;
                    }

                    if (modifier.minYearLength == null)
                    {
                        modifier.minYearLength = 75000f;
                    }

                    if (modifier.maxYearLength == null || modifier.maxYearLength < modifier.minYearLength)
                    {
                        modifier.maxYearLength = modifier.minYearLength;
                    }

                    if (modifier.minYearPercent == null)
                    {
                        modifier.minYearPercent = 0.6f;
                    }

                    if (modifier.maxYearPercent == null || modifier.maxYearPercent < modifier.minYearPercent || modifier.maxYearPercent > 1f)
                    {
                        modifier.maxYearPercent = modifier.minYearPercent;
                    }

                    if (modifier.Name != null)
                    {
                        Strings.Add("STRINGS.CREATURES.SPECIES.GEYSER." + modifier.id.ToUpper() + ".NAME", modifier.Name);
                    }
                    if (modifier.Description != null)
                    {
                        Strings.Add("STRINGS.CREATURES.SPECIES.GEYSER." + modifier.id.ToUpper() + ".DESC", modifier.Description);
                    }

                    Klei.SimUtil.DiseaseInfo diseaseInfo;
                    if (modifier.Disease == null || modifier.DiseaseCount == null)
                    {
                        diseaseInfo = Klei.SimUtil.DiseaseInfo.Invalid;
                    }
                    else
                    {
                        byte diseaseIndex = Db.Get().Diseases.GetIndex((HashedString)modifier.Disease);
                        if (diseaseIndex == byte.MaxValue || modifier.DiseaseCount <= 0)
                        {
                            diseaseInfo = Klei.SimUtil.DiseaseInfo.Invalid;
                        }
                        else
                        {
                            diseaseInfo = new Klei.SimUtil.DiseaseInfo()
                            {
                                idx = diseaseIndex, count = (int)modifier.DiseaseCount
                            }
                        };
                    }

                    __result.Add(
                        new GeyserGenericConfig.GeyserPrefabParams(
                            modifier.anim,
                            (int)modifier.width,
                            (int)modifier.height,
                            new GeyserConfigurator.GeyserType(
                                modifier.id,
                                (SimHashes)Hash.SDBMLower(modifier.element),
                                (float)modifier.temperature,
                                (float)modifier.minRatePerCycle,
                                (float)modifier.maxRatePerCycle,
                                (float)modifier.maxPressure,
                                (float)modifier.minIterationLength,
                                (float)modifier.maxIterationLength,
                                (float)modifier.minIterationPercent,
                                (float)modifier.maxIterationPercent,
                                (float)modifier.minYearLength,
                                (float)modifier.maxYearLength,
                                (float)modifier.minYearPercent,
                                (float)modifier.maxYearPercent).AddDisease(diseaseInfo)
                            ));

                    Debug.Log("[GeyserModifier] Added geyser " + modifier.id + " : " + modifier.element);
                }
                #endregion
            }
        }
    }
}
Exemplo n.º 22
0
        };                                                                                                                                                                                     //wilt1, grow_seed

        public static void ProcessPlant(GameObject plant)
        {
            PlantData setting = CustomizePlantsState.StateManager.State.PlantSettings?.FirstOrDefault(t => t.id == plant.name);

            if (setting == null)
            {
                return;
            }

            #region decor plant fixes
            if (setting.fruitId != null)    //decor plant fixes
            {
                PrickleGrass grass = plant.GetComponent <PrickleGrass>();
                if (grass != null || plant.name == ColdBreatherConfig.ID || plant.name == EvilFlowerConfig.ID)
                {
                    UnityEngine.Object.DestroyImmediate(grass); //what happens if this is null?
                    plant.AddOrGet <StandardCropPlant>();

                    KPrefabID prefab = plant.GetComponent <KPrefabID>();
                    prefab.prefabInitFn += (inst =>
                    {
                        StandardCropPlant stdcrop2 = inst.GetComponent <StandardCropPlant>();
                        stdcrop2.anims = PlantHelper.DecorAnim;
                    });

                    //KBatchedAnimController kbatchedAnimController = plant.AddOrGet<KBatchedAnimController>();
                    //kbatchedAnimController.AnimFiles = new KAnimFile[1]
                    //{
                    //  Assets.GetAnim("bristleblossom_kanim")
                    //};
                    //kbatchedAnimController.initialAnim = "idle_empty";
                }

                SeedProducer seed = plant.GetComponent <SeedProducer>();
                if (seed != null)
                {
                    seed.seedInfo.productionType   = SeedProducer.ProductionType.Harvest;
                    seed.seedInfo.newSeedsProduced = 1;
                }
            }
            #endregion
            #region fruitId
            if (setting.fruitId != null || setting.fruit_grow_time != null || setting.fruit_amount != null)    //actual setting fruit
            {
                Crop         crop    = plant.AddOrGet <Crop>();
                Crop.CropVal cropval = crop.cropVal;   //this is a copy
                if (setting.fruitId != null)
                {
                    cropval.cropId = setting.fruitId;
                }
                if (cropval.cropId == "")
                {
                    cropval.cropId = "WoodLog";
                }
                if (setting.fruit_grow_time != null)
                {
                    cropval.cropDuration = (float)setting.fruit_grow_time;
                }
                if (cropval.cropDuration < 1f)
                {
                    cropval.cropDuration = 1f;
                }
                if (setting.fruit_amount != null)
                {
                    cropval.numProduced = (int)setting.fruit_amount;
                }
                if (cropval.numProduced < 1)
                {
                    cropval.numProduced = 1;
                }
                crop.Configure(cropval);

                KPrefabID prefab = plant.GetComponent <KPrefabID>();
                GeneratedBuildings.RegisterWithOverlay(OverlayScreen.HarvestableIDs, prefab.PrefabID().ToString());
                Growing growing = plant.AddOrGet <Growing>();
                growing.growthTime = cropval.cropDuration;
                if (setting.id != ForestTreeConfig.ID)  // don't harvest arbor trees directly
                {
                    plant.AddOrGet <Harvestable>();
                }
                plant.AddOrGet <HarvestDesignatable>();
                plant.AddOrGet <StandardCropPlant>();
            }
            #endregion
            #region irrigation
            if (setting.irrigation != null)
            {
                RemoveIrrigation(plant);

                List <PlantElementAbsorber.ConsumeInfo> irrigation    = new List <PlantElementAbsorber.ConsumeInfo>(3);
                List <PlantElementAbsorber.ConsumeInfo> fertilization = new List <PlantElementAbsorber.ConsumeInfo>(3);
                foreach (KeyValuePair <string, float> entry in setting.irrigation)
                {
                    if (GameTags.LiquidElements.Contains(entry.Key))
                    {
                        irrigation.Add(new PlantElementAbsorber.ConsumeInfo(entry.Key, entry.Value / 600f));
                    }
                    else if (GameTags.SolidElements.Contains(entry.Key))
                    {
                        fertilization.Add(new PlantElementAbsorber.ConsumeInfo(entry.Key, entry.Value / 600f));
                    }
                    else
                    {
                        Debug.Log(ToDialog("Irrigation for " + setting.id + " defines bad element: " + entry.Key));
                    }
                }
                if (irrigation.Count > 0)
                {
                    EntityTemplates.ExtendPlantToIrrigated(plant, irrigation.ToArray());
                }
                if (fertilization.Count > 0)
                {
                    EntityTemplates.ExtendPlantToFertilizable(plant, fertilization.ToArray());
                }
            }
            #endregion
            #region illumination
            if (setting.illumination != null)
            {
                IlluminationVulnerable  illumination = plant.GetComponent <IlluminationVulnerable>();
                CropSleepingMonitor.Def cropSleep    = plant.GetDef <CropSleepingMonitor.Def>();

                if (setting.illumination == 0f)
                {
                    if (illumination != null)
                    {
                        UnityEngine.Object.DestroyImmediate(illumination);
                    }
                    if (cropSleep != null)
                    {
                        FumLib.FumTools.RemoveDef(plant, cropSleep);
                    }
                }
                else if (setting.illumination < 0f)
                {
                    if (illumination == null)
                    {
                        illumination = plant.AddOrGet <IlluminationVulnerable>();
                    }
                    if (cropSleep != null)
                    {
                        FumLib.FumTools.RemoveDef(plant, cropSleep);
                    }

                    illumination.SetPrefersDarkness(true);
                }
                else if (setting.illumination == 1f)
                {
                    if (illumination == null)
                    {
                        illumination = plant.AddOrGet <IlluminationVulnerable>();
                    }
                    if (cropSleep != null)
                    {
                        FumLib.FumTools.RemoveDef(plant, cropSleep);
                    }

                    illumination.SetPrefersDarkness(false);
                }
                else
                {
                    if (illumination != null)
                    {
                        UnityEngine.Object.DestroyImmediate(illumination);
                    }
                    if (cropSleep == null)
                    {
                        cropSleep = plant.AddOrGetDef <CropSleepingMonitor.Def>();
                    }

                    cropSleep.lightIntensityThreshold = (float)setting.illumination;
                    cropSleep.prefersDarkness         = false;
                }
            }
            #endregion
            #region safe_elements
            if (setting.safe_elements != null)
            {
                plant.GetComponent <KPrefabID>().prefabInitFn += (inst =>
                {
                    PressureVulnerable pressure = inst.GetComponent <PressureVulnerable>();
                    pressure.safe_atmospheres.Clear();

                    foreach (string safe_element in setting.safe_elements)
                    {
                        pressure.safe_atmospheres.Add(ElementLoader.FindElementByName(safe_element));
                    }
                });
            }
            #endregion
            #region pressure
            if (setting.pressures != null)
            {
                PressureVulnerable pressure = plant.AddOrGet <PressureVulnerable>();
                pressure.pressureLethal_Low   = 0f;
                pressure.pressureWarning_Low  = 0f;
                pressure.pressureWarning_High = float.MaxValue;
                pressure.pressureLethal_High  = float.MaxValue;
                pressure.pressure_sensitive   = false;

                for (int i = 0; i < setting.pressures.Length; i++)
                {
                    switch (i)
                    {
                    case 0: pressure.pressureLethal_Low = setting.pressures[i]; pressure.pressure_sensitive = true; break;

                    case 1: pressure.pressureWarning_Low = setting.pressures[i]; break;

                    case 2: pressure.pressureWarning_High = setting.pressures[i]; break;

                    case 3: pressure.pressureLethal_High = setting.pressures[i]; break;
                    }
                }
            }
            #endregion
            #region decor
            try {
                if (setting.decor_value != null)
                {
                    plant.GetComponent <DecorProvider>().baseDecor = (float)setting.decor_value;
                }

                if (setting.decor_radius != null)
                {
                    plant.GetComponent <DecorProvider>().baseRadius = (float)setting.decor_radius;
                }
            } catch (Exception) {
                Debug.LogWarning("[CustomizePlants] For some weird reason " + plant.name + " has no DecorProvider.");
            }
            #endregion
            #region temperatures
            if (setting.temperatures != null)
            {
                TemperatureVulnerable temperature = plant.AddOrGet <TemperatureVulnerable>();

                for (int i = 0; i < setting.temperatures.Length; i++)
                {
                    switch (i)
                    {
                    case 0: temperature.internalTemperatureLethal_Low = setting.temperatures[i]; break;

                    case 1: temperature.internalTemperatureWarning_Low = setting.temperatures[i]; break;

                    case 2: temperature.internalTemperatureWarning_High = setting.temperatures[i]; break;

                    case 3: temperature.internalTemperatureLethal_High = setting.temperatures[i]; break;
                    }
                }
            }
            #endregion
            #region submerged_threshold
            if (setting.submerged_threshold != null)
            {
                DrowningMonitor drowning = plant.AddOrGet <DrowningMonitor>();

                if (setting.submerged_threshold == 0f)   //doesn't care about water
                {
                    UnityEngine.Object.DestroyImmediate(drowning);
                }
                else if (setting.submerged_threshold < 0f)   //needs water
                {
                    drowning.livesUnderWater = true;
                    drowning.canDrownToDeath = false;
                }
                else    //if(setting.submerged_threshold > 0f)  //hates water
                {
                    drowning.livesUnderWater = false;
                    drowning.canDrownToDeath = false;
                }
            }
            #endregion
            #region can_tinker
            if (setting.can_tinker != null)
            {
                if (setting.can_tinker == true)
                {
                    Tinkerable.MakeFarmTinkerable(plant);
                }
            }
            #endregion
            #region require_solid_tile
            if (setting.require_solid_tile != null)
            {
                UprootedMonitor uproot = plant.AddOrGet <UprootedMonitor>();
                if (setting.require_solid_tile == false)
                {
                    UnityEngine.Object.DestroyImmediate(uproot);
                }
            }
            #endregion
            #region max_age
            if (setting.max_age != null && plant.GetComponent <StandardCropPlant>() != null) //only if plant has fruit
            {
                Growing growing = plant.AddOrGet <Growing>();
                if (setting.max_age <= 0)
                {
                    growing.shouldGrowOld = false;
                }
                else
                {
                    growing.shouldGrowOld = true;
                    growing.maxAge        = (float)setting.max_age;
                }
            }
            #endregion
            #region disease
            if (setting.disease != null || setting.disease_amount != null)
            {
                DiseaseDropper.Def def = plant.AddOrGetDef <DiseaseDropper.Def>();
                if (setting.disease != null)
                {
                    def.diseaseIdx = Db.Get().Diseases.GetIndex(setting.disease);
                }
                if (setting.disease_amount != null)
                {
                    def.singleEmitQuantity = (int)setting.disease_amount;
                }

                if (def.diseaseIdx == byte.MaxValue || def.singleEmitQuantity == 0)
                {
                    FumLib.FumTools.RemoveDef(plant, def);
                }
            }
            #endregion
            #region input_element
            if (setting.input_element != null)
            {
                ElementConsumer consumer = plant.AddOrGet <ElementConsumer>();
                Element         element  = ElementLoader.FindElementByName(setting.input_element);

                if (element == null || element.IsSolid)                //invalid element
                {
                    Debug.Log(ToDialog("input_element is bad element: " + setting.input_element));
                    UnityEngine.Object.DestroyImmediate(consumer);
                }
                else if (setting.input_rate <= 0f)   //delete consumer
                {
                    UnityEngine.Object.DestroyImmediate(consumer);
                }
                else
                {
                    consumer.configuration     = ElementConsumer.Configuration.Element;
                    consumer.consumptionRadius = 2;
                    consumer.sampleCellOffset  = new Vector3(0f, 0f);
                    consumer.EnableConsumption(true);
                    consumer.showInStatusPanel = true;
                    consumer.storeOnConsume    = false; //consumer deletes elements; output_element might overrides this
                    consumer.consumptionRate   = (float)setting.input_rate;
                    consumer.elementToConsume  = element.id;
                    consumer.capacityKG        = (float)setting.input_rate * 10;

                    plant.AddOrGet <Storage>().capacityKg = consumer.capacityKG;
                    plant.AddOrGet <SaltPlant>();
                }
            }
            #endregion
            #region output_element
            if (setting.output_element != null)
            {
                ElementConsumer  consumer  = plant.GetComponent <ElementConsumer>();
                ElementConverter converter = plant.AddOrGet <ElementConverter>();
                Element          element   = ElementLoader.FindElementByName(setting.output_element);

                if (element == null)                //invalid element
                {
                    Debug.Log(ToDialog("output_element is bad element: " + setting.output_element));
                    UnityEngine.Object.DestroyImmediate(converter);
                }
                else if (setting.output_rate <= 0f)  //delete converter
                {
                    UnityEngine.Object.DestroyImmediate(converter);
                    if (consumer != null)
                    {
                        consumer.storeOnConsume = false;
                    }
                }
                else
                {
                    if (consumer != null)   //transform elements
                    {
                        consumer.storeOnConsume    = true;
                        converter.consumedElements = new ElementConverter.ConsumedElement[1] {
                            new ElementConverter.ConsumedElement(consumer.elementToConsume.CreateTag(), consumer.consumptionRate)
                        };
                        converter.OutputMultiplier = (float)setting.output_rate / consumer.consumptionRate;
                        //Debug.Log("TAG is: " + consumer.elementToConsume.CreateTag().Name + " SimHash is: " + consumer.elementToConsume.ToString());
                    }
                    else    //create from nothing
                    {
                        converter.consumedElements = new ElementConverter.ConsumedElement[0];
                        converter.OutputMultiplier = 1f;
                    }
                    converter.outputElements = new ElementConverter.OutputElement[1] {
                        new ElementConverter.OutputElement((float)setting.output_rate, element.id, 0f, true, false, 0f, 1f)
                    };

                    plant.AddOrGet <Storage>();
                    plant.AddOrGet <SaltPlant>();
                }
            }
            #endregion
        }