Beispiel #1
0
        private static void DoPlayLoad()
        {
            DeepProfiler.Start("GraphicDatabase.Clear()");
            try
            {
                GraphicDatabase.Clear();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load all active mods.");
            try
            {
                LoadedModManager.LoadAllActiveMods();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load language metadata.");
            try
            {
                LanguageDatabase.InitAllMetadata();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.SetCurrentEventText("LoadingDefs".Translate());
            DeepProfiler.Start("Copy all Defs from mods to global databases.");
            try
            {
                foreach (Type item in typeof(Def).AllSubclasses())
                {
                    GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item, "AddAllInMods");
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between non-implied Defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind defs (early).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: true);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("TKeySystem.BuildMappings()");
            try
            {
                TKeySystem.BuildMappings();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Inject selected language data into game data (early pass).");
            try
            {
                LanguageDatabase.activeLanguage.InjectIntoData_BeforeImpliedDefs();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (pre-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PreResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between Defs made by the implied defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
            }
            finally
            {
                DirectXmlCrossRefLoader.Clear();
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind DefOfs (final).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: false);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (pre-resolve).");
            try
            {
                PlayerKnowledgeDatabase.ReloadAndRebind();
                LessonAutoActivator.Reset();
                CostListCalculator.Reset();
                Pawn.ResetStaticData();
                PawnApparelGenerator.Reset();
                RestUtility.Reset();
                ThoughtUtility.Reset();
                ThinkTreeKeyAssigner.Reset();
                ThingCategoryNodeDatabase.FinalizeInit();
                TrainableUtility.Reset();
                HaulAIUtility.Reset();
                GenConstruct.Reset();
                MedicalCareUtility.Reset();
                InspectPaneUtility.Reset();
                GraphicDatabaseHeadRecords.Reset();
                DateReadout.Reset();
                ResearchProjectDef.GenerateNonOverlappingCoordinates();
                BaseGen.Reset();
                ResourceCounter.ResetDefs();
                ApparelProperties.ResetStaticData();
                WildPlantSpawner.ResetStaticData();
                PawnGenerator.Reset();
                TunnelHiveSpawner.ResetStaticData();
                Hive.ResetStaticData();
                ExpectationsUtility.Reset();
                WealthWatcher.ResetStaticData();
                SkillUI.Reset();
                QuestNode_GetThingPlayerCanProduce.ResetStaticData();
                Pawn_PsychicEntropyTracker.ResetStaticData();
                ColoredText.ResetStaticData();
                QuestNode_GetRandomNegativeGameCondition.ResetStaticData();
                RoyalTitleUtility.ResetStaticData();
                RewardsGenerator.ResetStaticData();
                WorkGiver_FillFermentingBarrel.ResetStaticData();
                WorkGiver_DoBill.ResetStaticData();
                WorkGiver_InteractAnimal.ResetStaticData();
                WorkGiver_Warden_DoExecution.ResetStaticData();
                WorkGiver_GrowerSow.ResetStaticData();
                WorkGiver_Miner.ResetStaticData();
                WorkGiver_FixBrokenDownBuilding.ResetStaticData();
                WorkGiver_ConstructDeliverResources.ResetStaticData();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve references.");
            try
            {
                DeepProfiler.Start("ThingCategoryDef resolver");
                try
                {
                    DefDatabase <ThingCategoryDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("RecipeDef resolver");
                try
                {
                    DeepProfiler.enabled = false;
                    DefDatabase <RecipeDef> .ResolveAllReferences(onlyExactlyMyType : true, parallel : true);

                    DeepProfiler.enabled = true;
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Static resolver calls");
                try
                {
                    foreach (Type item2 in typeof(Def).AllSubclasses())
                    {
                        if (!(item2 == typeof(ThingDef)) && !(item2 == typeof(ThingCategoryDef)) && !(item2 == typeof(RecipeDef)))
                        {
                            GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item2, "ResolveAllReferences", true, false);
                        }
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("ThingDef resolver");
                try
                {
                    DefDatabase <ThingDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (post-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PostResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (post-resolve).");
            try
            {
                PawnWeaponGenerator.Reset();
                BuildingProperties.FinalizeInit();
                ThingSetMakerUtility.Reset();
            }
            finally
            {
                DeepProfiler.End();
            }
            if (Prefs.DevMode)
            {
                DeepProfiler.Start("Error check all defs.");
                try
                {
                    foreach (Type item3 in typeof(Def).AllSubclasses())
                    {
                        GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item3, "ErrorCheckAllDefs");
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            LongEventHandler.SetCurrentEventText("Initializing".Translate());
            DeepProfiler.Start("Load keyboard preferences.");
            try
            {
                KeyPrefs.Init();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Short hash giving.");
            try
            {
                ShortHashGiver.GiveAllShortHashes();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Load backstories.");
                try
                {
                    BackstoryDatabase.ReloadAllBackstories();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Inject selected language data into game data.");
                try
                {
                    LanguageDatabase.activeLanguage.InjectIntoData_AfterImpliedDefs();
                    GenLabel.ClearCache();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Static constructor calls");
                try
                {
                    StaticConstructorOnStartupUtility.CallAll();
                    if (Prefs.DevMode)
                    {
                        StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes();
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Garbage Collection");
                try
                {
                    AbstractFilesystem.ClearAllCache();
                    GC.Collect(int.MaxValue, GCCollectionMode.Forced);
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
        }
Beispiel #2
0
        static RemoveSpacerStuff()
        {
            DebugString.AppendLine("RemoveSpacerStuff - Start Removal Log");
            DebugString.AppendLine("Tech Max Level = " + MAX_TECHLEVEL);

            removedDefs = 0;
            IEnumerable <ResearchProjectDef> projects = new List <ResearchProjectDef>();

            if (ModStuff.Settings.LimitResearch)
            {
                projects = DefDatabase <ResearchProjectDef> .AllDefs.Where(rpd => rpd.techLevel > MAX_TECHLEVEL);
            }


            if (ModStuff.Settings.LimitItems)
            {
                things = new HashSet <ThingDef>(DefDatabase <ThingDef> .AllDefs.Where(td =>
                                                                                      td.techLevel > MAX_TECHLEVEL ||
                                                                                      (td.researchPrerequisites?.Any(rpd => projects.Contains(rpd)) ?? false)));
            }

            DebugString.AppendLine("RecipeDef Removal List");


            foreach (var thing in from thing in things where thing.tradeTags != null select thing)
            {
                var tags = thing.tradeTags.ToArray();
                foreach (var tag in tags)
                {
                    if (tag.StartsWith("CE_AutoEnableCrafting"))
                    {
                        thing.tradeTags.Remove(tag);
                    }
                }
            }

            //var recipeDefsToRemove = DefDatabase<RecipeDef>.AllDefs.Where(rd =>
            //    rd.products.Any(tcc => things.Contains(tcc.thingDef)) ||
            //    rd.AllRecipeUsers.All(td => things.Contains(td)) ||
            //    projects.Contains(rd.researchPrerequisite)).Cast<Def>().ToList();
            //recipeDefsToRemove?.RemoveAll(x =>
            //    x.defName == "ExtractMetalFromSlag" ||
            //    x.defName == "SmeltWeapon" ||
            //    x.defName == "DestroyWeapon" ||
            //    x.defName == "OfferingOfPlants_Meagre" ||
            //    x.defName == "OfferingOfPlants_Decent" ||
            //    x.defName == "OfferingOfPlants_Sizable" ||
            //    x.defName == "OfferingOfPlants_Worthy" ||
            //    x.defName == "OfferingOfPlants_Impressive" ||
            //    x.defName == "OfferingOfMeat_Meagre" ||
            //    x.defName == "OfferingOfMeat_Decent" ||
            //    x.defName == "OfferingOfMeat_Sizable" ||
            //    x.defName == "OfferingOfMeat_Worthy" ||
            //    x.defName == "OfferingOfMeat_Impressive" ||
            //    x.defName == "OfferingOfMeals_Meagre" ||
            //    x.defName == "OfferingOfMeals_Decent" ||
            //    x.defName == "OfferingOfMeals_Sizable" ||
            //    x.defName == "OfferingOfMeals_Worthy" ||
            //    x.defName == "OfferingOfMeals_Impressive" ||
            //    x.defName == "ROMV_ExtractBloodVial" ||
            //    x.defName == "ROMV_ExtractBloodPack"
            //    );
            //RemoveStuffFromDatabase(typeof(DefDatabase<RecipeDef>), recipeDefsToRemove);

            DebugString.AppendLine("ResearchProjectDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ResearchProjectDef>), projects);

            DebugString.AppendLine("Scenario Part Removal List");
            var getThingInfo =
                typeof(ScenPart_ThingCount).GetField("thingDef", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var def in DefDatabase <ScenarioDef> .AllDefs)
            {
                foreach (var sp in def.scenario.AllParts)
                {
                    if (!(sp is ScenPart_ThingCount) || !things.Contains((ThingDef)getThingInfo?.GetValue(sp)))
                    {
                        continue;
                    }

                    def.scenario.RemovePart(sp);
                    DebugString.AppendLine("- " + sp.Label + " " + ((ThingDef)getThingInfo?.GetValue(sp))?.label +
                                           " from " + def.label);
                }
            }

            foreach (var thingCategoryDef in DefDatabase <ThingCategoryDef> .AllDefs)
            {
                thingCategoryDef.childThingDefs.RemoveAll(things.Contains);
            }

            DebugString.AppendLine("Stock Generator Part Cleanup");
            foreach (var tkd in DefDatabase <TraderKindDef> .AllDefs)
            {
                for (var i = tkd.stockGenerators.Count - 1; i >= 0; i--)
                {
                    var stockGenerator = tkd.stockGenerators[i];

                    switch (stockGenerator)
                    {
                    case StockGenerator_SingleDef sd when things.Contains(Traverse.Create(sd).Field("thingDef")
                                                                          .GetValue <ThingDef>()):
                        var def = Traverse.Create(sd).Field("thingDef")
                                  .GetValue <ThingDef>();

                        tkd.stockGenerators.Remove(stockGenerator);
                        DebugString.AppendLine("- " + def.label + " from " + tkd.label +
                                               "'s StockGenerator_SingleDef");
                        break;

                    case StockGenerator_MultiDef md:
                        var thingListTraverse = Traverse.Create(md).Field("thingDefs");
                        var thingList         = thingListTraverse.GetValue <List <ThingDef> >();
                        var removeList        = thingList.FindAll(things.Contains);
                        removeList.ForEach(x =>
                                           DebugString.AppendLine("- " + x.label + " from " + tkd.label +
                                                                  "'s StockGenerator_MultiDef"));
                        thingList.RemoveAll(things.Contains);

                        if (thingList.NullOrEmpty())
                        {
                            tkd.stockGenerators.Remove(stockGenerator);
                        }
                        else
                        {
                            thingListTraverse.SetValue(thingList);
                        }

                        break;
                    }
                }
            }


            //DebugString.AppendLine("IncidentDef Removal List");

            //var removedDefNames = new List<string>
            //{
            //    "Disease_FibrousMechanites",
            //    "Disease_SensoryMechanites",
            //    "ResourcePodCrash",
            //    "PsychicSoothe",
            //    "RefugeePodCrash",
            //    "RansomDemand",
            //    "MeteoriteImpact",
            //    "PsychicDrone",
            //    "ShortCircuit",
            //    "ShipChunkDrop",
            //    "OrbitalTraderArrival",
            //    "StrangerInBlackJoin",
            //    "DefoliatorShipPartCrash",
            //    "PsychicEmanatorShipPartCrash",
            //    "MechCluster",
            //    "AnimalInsanityMass"
            //};

            //IEnumerable<IncidentDef> incidents = from IncidentDef incident in DefDatabase<IncidentDef>.AllDefs
            //                                     where removedDefNames.Contains(incident.defName)
            //                                     select incident;


            //foreach (IncidentDef incident in incidents)
            //{
            //    incident.targetTags?.Clear();
            //    incident.baseChance = 0f;
            //    incident.allowedBiomes?.Clear();
            //    incident.earliestDay = int.MaxValue;
            //}

            //RemoveStuffFromDatabase(typeof(DefDatabase<IncidentDef>), incidents.Cast<Def>());

            //DebugString.AppendLine("Replaced Ancient Asphalt Road / Ancient Asphalt Highway with Stone Road");
            //RoadDef[] targetRoads = { RoadDefOf.AncientAsphaltRoad, RoadDefOf.AncientAsphaltHighway };
            //RoadDef originalRoad = DefDatabase<RoadDef>.GetNamed("StoneRoad");

            //List<string> fieldNames = AccessTools.GetFieldNames(typeof(RoadDef));
            //fieldNames.Remove("defName");
            //foreach (FieldInfo fi in fieldNames.Select(name => AccessTools.Field(typeof(RoadDef), name)))
            //{
            //    object fieldValue = fi.GetValue(originalRoad);
            //    foreach (RoadDef targetRoad in targetRoads) fi.SetValue(targetRoad, fieldValue);
            //}

            //DebugString.AppendLine("Special Hediff Removal List");
            //RemoveStuffFromDatabase(typeof(DefDatabase<HediffDef>), (hediffs = new[] { HediffDefOf.Gunshot }).Cast<Def>());

            //DebugString.AppendLine("RaidStrategyDef Removal List");
            //RemoveStuffFromDatabase(typeof(DefDatabase<RaidStrategyDef>),
            //    DefDatabase<RaidStrategyDef>.AllDefs
            //        .Where(rs => typeof(ScenPart_ThingCount).IsAssignableFrom(rs.workerClass)).Cast<Def>());

            ////            ItemCollectionGeneratorUtility.allGeneratableItems.RemoveAll(match: things.Contains);
            ////
            ////            foreach (Type type in typeof(ItemCollectionGenerator_Standard).AllSubclassesNonAbstract())
            ////                type.GetMethod(name: "Reset")?.Invoke(obj: null, parameters: null);

            DebugString.AppendLine("ThingDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ThingDef>), things.ToArray());

            DebugString.AppendLine("ThingSetMaker Reset");
            ThingSetMakerUtility.Reset();

            //DebugString.AppendLine("TraitDef Removal List");
            //RemoveStuffFromDatabase(typeof(DefDatabase<TraitDef>),
            //    //                                                                   { nameof(TraitDefOf.Prosthophobe), "Prosthophile" } ?
            //    DefDatabase<TraitDef>.AllDefs
            //        .Where(td => new[] { nameof(TraitDefOf.BodyPurist), "Transhumanist" }.Contains(td.defName))
            //        .Cast<Def>());

            DebugString.AppendLine("Designators Resolved Again");
            var resolveDesignatorsAgain = typeof(DesignationCategoryDef).GetMethod("ResolveDesignators",
                                                                                   BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var dcd in DefDatabase <DesignationCategoryDef> .AllDefs)
            {
                resolveDesignatorsAgain?.Invoke(dcd, null);
            }

            if (ModStuff.Settings.LimitPawns)
            {
                DebugString.AppendLine("PawnKindDef Removal List");
                RemoveStuffFromDatabase(typeof(DefDatabase <PawnKindDef>),
                                        DefDatabase <PawnKindDef> .AllDefs
                                        .Where(pkd =>
                                               (!pkd.defaultFactionType?.isPlayer ?? false) &&
                                               (pkd.race.techLevel > MAX_TECHLEVEL || pkd.defaultFactionType?.techLevel > MAX_TECHLEVEL)));
            }

            if (ModStuff.Settings.LimitFactions)
            {
                DebugString.AppendLine("FactionDef Removal List");
                RemoveStuffFromDatabase(typeof(DefDatabase <FactionDef>),
                                        DefDatabase <FactionDef> .AllDefs.Where(fd => !fd.isPlayer && fd.techLevel > MAX_TECHLEVEL));
                if (ModLister.RoyaltyInstalled)
                {
                    var incident = DefDatabase <IncidentDef> .GetNamedSilentFail("CaravanArrivalTributeCollector");

                    if (incident != null)
                    {
                        RemoveStuffFromDatabase(typeof(DefDatabase <IncidentDef>),
                                                new List <Def> {
                            incident
                        });
                    }
                }
            }

            if (ModStuff.Settings.LogRemovals)
            {
                Log.Message(DebugString.ToString());
            }
            else
            {
                Log.Message("Removed " + removedDefs + " spacer defs");
            }

            PawnWeaponGenerator.Reset();
            PawnApparelGenerator.Reset();

            Debug.Log(DebugString.ToString());
            DebugString = new StringBuilder();
        }
Beispiel #3
0
        static RemoveModernStuff()
        {
            if (!ModStuff.Settings.LimitTechnology)
            {
                MAX_TECHLEVEL = TechLevel.Archotech;
                return;
            }

            DebugString.AppendLine("Lord of the Rings - The Third Age - Start Removal Log");
            DebugString.AppendLine("Tech Limiter Active: Max Level = " + MAX_TECHLEVEL.ToString());
            GiveApproppriateTechLevels();

            removedDefs = 0;

            IEnumerable <ResearchProjectDef> projects =
                DefDatabase <ResearchProjectDef> .AllDefs.Where(rpd => rpd.techLevel > MAX_TECHLEVEL);

            var extraDefsToRemove = new List <string>();

            things = new HashSet <ThingDef>(DefDatabase <ThingDef> .AllDefs.Where(td =>
                                                                                  td.techLevel > MAX_TECHLEVEL ||
                                                                                  extraDefsToRemove.Contains(td.defName) ||
                                                                                  (td.researchPrerequisites?.Any(rpd => projects.Contains(rpd)) ?? false) || new[]
            {
                "Gun_Revolver", "VanometricPowerCell", "PsychicEmanator", "InfiniteChemreactor", "Joywire",
                "Painstopper"
            }.Contains(td.defName)));

            DebugString.AppendLine("RecipeDef Removal List");


            foreach (var thing in from thing in things where thing.tradeTags != null select thing)
            {
                var tags = thing.tradeTags.ToArray();
                foreach (var tag in tags)
                {
                    if (tag.StartsWith("CE_AutoEnableCrafting"))
                    {
                        thing.tradeTags.Remove(tag);
                    }
                }
            }

            var recipeDefsToRemove = DefDatabase <RecipeDef> .AllDefs.Where(rd =>
                                                                            rd.products.Any(tcc => things.Contains(tcc.thingDef)) ||
                                                                            rd.AllRecipeUsers.All(td => things.Contains(td)) ||
                                                                            projects.Contains(rd.researchPrerequisite)).Cast <Def>().ToList();

            recipeDefsToRemove?.RemoveAll(x =>
                                          x.defName == "ExtractMetalFromSlag" ||
                                          x.defName == "SmeltWeapon" ||
                                          x.defName == "DestroyWeapon" ||
                                          x.defName == "OfferingOfPlants_Meagre" ||
                                          x.defName == "OfferingOfPlants_Decent" ||
                                          x.defName == "OfferingOfPlants_Sizable" ||
                                          x.defName == "OfferingOfPlants_Worthy" ||
                                          x.defName == "OfferingOfPlants_Impressive" ||
                                          x.defName == "OfferingOfMeat_Meagre" ||
                                          x.defName == "OfferingOfMeat_Decent" ||
                                          x.defName == "OfferingOfMeat_Sizable" ||
                                          x.defName == "OfferingOfMeat_Worthy" ||
                                          x.defName == "OfferingOfMeat_Impressive" ||
                                          x.defName == "OfferingOfMeals_Meagre" ||
                                          x.defName == "OfferingOfMeals_Decent" ||
                                          x.defName == "OfferingOfMeals_Sizable" ||
                                          x.defName == "OfferingOfMeals_Worthy" ||
                                          x.defName == "OfferingOfMeals_Impressive" ||
                                          x.defName == "ROMV_ExtractBloodVial" ||
                                          x.defName == "ROMV_ExtractBloodPack"
                                          );
            RemoveStuffFromDatabase(typeof(DefDatabase <RecipeDef>), recipeDefsToRemove);

            DebugString.AppendLine("ResearchProjectDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ResearchProjectDef>), projects.Cast <Def>());


            DebugString.AppendLine("Scenario Part Removal List");
            FieldInfo getThingInfo =
                typeof(ScenPart_ThingCount).GetField("thingDef", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (ScenarioDef def in DefDatabase <ScenarioDef> .AllDefs)
            {
                foreach (ScenPart sp in def.scenario.AllParts)
                {
                    if (sp is ScenPart_ThingCount && things.Contains((ThingDef)getThingInfo?.GetValue(sp)))
                    {
                        def.scenario.RemovePart(sp);
                        DebugString.AppendLine("- " + sp.Label + " " + ((ThingDef)getThingInfo?.GetValue(sp)).label +
                                               " from " + def.label);
                    }
                }
            }

            foreach (ThingCategoryDef thingCategoryDef in DefDatabase <ThingCategoryDef> .AllDefs)
            {
                thingCategoryDef.childThingDefs.RemoveAll(things.Contains);
            }

            DebugString.AppendLine("Stock Generator Part Cleanup");
            foreach (TraderKindDef tkd in DefDatabase <TraderKindDef> .AllDefs)
            {
                for (var i = tkd.stockGenerators.Count - 1; i >= 0; i--)
                {
                    StockGenerator stockGenerator = tkd.stockGenerators[i];

                    switch (stockGenerator)
                    {
                    case StockGenerator_SingleDef sd when things.Contains(Traverse.Create(sd).Field("thingDef")
                                                                          .GetValue <ThingDef>()):
                        ThingDef def = Traverse.Create(sd).Field("thingDef")
                                       .GetValue <ThingDef>();

                        tkd.stockGenerators.Remove(stockGenerator);
                        DebugString.AppendLine("- " + def.label + " from " + tkd.label +
                                               "'s StockGenerator_SingleDef");
                        break;

                    case StockGenerator_MultiDef md:
                        Traverse        thingListTraverse = Traverse.Create(md).Field("thingDefs");
                        List <ThingDef> thingList         = thingListTraverse.GetValue <List <ThingDef> >();
                        var             removeList        = thingList.FindAll(things.Contains);
                        removeList?.ForEach(x =>
                                            DebugString.AppendLine("- " + x.label + " from " + tkd.label +
                                                                   "'s StockGenerator_MultiDef"));
                        thingList.RemoveAll(things.Contains);

                        if (thingList.NullOrEmpty())
                        {
                            tkd.stockGenerators.Remove(stockGenerator);
                        }
                        else
                        {
                            thingListTraverse.SetValue(thingList);
                        }

                        break;
                    }
                }
            }


            DebugString.AppendLine("IncidentDef Removal List");

            var removedDefNames = new List <string>
            {
                "Disease_FibrousMechanites",
                "Disease_SensoryMechanites",
                "ResourcePodCrash",
                "PsychicSoothe",
                "RefugeePodCrash",
                "RansomDemand",
                "MeteoriteImpact",
                "PsychicDrone",
                "ShortCircuit",
                "ShipChunkDrop",
                "OrbitalTraderArrival",
                "StrangerInBlackJoin",
                "DefoliatorShipPartCrash",
                "PsychicEmanatorShipPartCrash",
                "MechCluster",
                "AnimalInsanityMass"
            };

            IEnumerable <IncidentDef> incidents = from IncidentDef incident in DefDatabase <IncidentDef> .AllDefs
                                                  where removedDefNames.Contains(incident.defName)
                                                  select incident;


            foreach (IncidentDef incident in incidents)
            {
                incident.targetTags?.Clear();
                incident.baseChance = 0f;
                incident.allowedBiomes?.Clear();
                incident.earliestDay = int.MaxValue;
            }

            RemoveStuffFromDatabase(typeof(DefDatabase <IncidentDef>), incidents.Cast <Def>());

            DebugString.AppendLine("Replaced Ancient Asphalt Road / Ancient Asphalt Highway with Stone Road");
            RoadDef[] targetRoads  = { RoadDefOf.AncientAsphaltRoad, RoadDefOf.AncientAsphaltHighway };
            RoadDef   originalRoad = DefDatabase <RoadDef> .GetNamed("StoneRoad");

            List <string> fieldNames = AccessTools.GetFieldNames(typeof(RoadDef));

            fieldNames.Remove("defName");
            foreach (FieldInfo fi in fieldNames.Select(name => AccessTools.Field(typeof(RoadDef), name)))
            {
                var fieldValue = fi.GetValue(originalRoad);
                foreach (RoadDef targetRoad in targetRoads)
                {
                    fi.SetValue(targetRoad, fieldValue);
                }
            }

            DebugString.AppendLine("Special Hediff Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <HediffDef>), (hediffs = new[] { HediffDefOf.Gunshot }).Cast <Def>());

            DebugString.AppendLine("RaidStrategyDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <RaidStrategyDef>),
                                    DefDatabase <RaidStrategyDef> .AllDefs
                                    .Where(rs => typeof(ScenPart_ThingCount).IsAssignableFrom(rs.workerClass)).Cast <Def>());

            //            ItemCollectionGeneratorUtility.allGeneratableItems.RemoveAll(match: things.Contains);
            //
            //            foreach (Type type in typeof(ItemCollectionGenerator_Standard).AllSubclassesNonAbstract())
            //                type.GetMethod(name: "Reset")?.Invoke(obj: null, parameters: null);

            DebugString.AppendLine("ThingDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ThingDef>), things.ToArray());

            DebugString.AppendLine("ThingSetMaker Reset");
            ThingSetMakerUtility.Reset();

            DebugString.AppendLine("TraitDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <TraitDef>),
                                    //                                                                   { nameof(TraitDefOf.Prosthophobe), "Prosthophile" } ?
                                    DefDatabase <TraitDef> .AllDefs
                                    .Where(td => new[] { nameof(TraitDefOf.BodyPurist), "Transhumanist" }.Contains(td.defName))
                                    .Cast <Def>());

            DebugString.AppendLine("Designators Resolved Again");
            MethodInfo resolveDesignatorsAgain = typeof(DesignationCategoryDef).GetMethod("ResolveDesignators",
                                                                                          BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (DesignationCategoryDef dcd in DefDatabase <DesignationCategoryDef> .AllDefs)
            {
                resolveDesignatorsAgain?.Invoke(dcd, null);
            }

            DebugString.AppendLine("PawnKindDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <PawnKindDef>),
                                    DefDatabase <PawnKindDef> .AllDefs
                                    .Where(pkd =>
                                           (!pkd.defaultFactionType?.isPlayer ?? false) &&
                                           (pkd.race.techLevel > MAX_TECHLEVEL || pkd.defaultFactionType?.techLevel > MAX_TECHLEVEL))
                                    .Cast <Def>());

            DebugString.AppendLine("FactionDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <FactionDef>),
                                    DefDatabase <FactionDef> .AllDefs.Where(fd => !fd.isPlayer && fd.techLevel > MAX_TECHLEVEL).Cast <Def>());

            DebugString.AppendLine("BackstoryDef Removal List");
            BackstoryHandler.RemoveIncompatibleBackstories(DebugString);

            DebugString.AppendLine("MapGeneratorDef Removal List");
            DebugString.AppendLine("- GenStep_SleepingMechanoids");
            DebugString.AppendLine("- GenStep_Turrets");
            DebugString.AppendLine("- GenStep_Power");
            foreach (MapGeneratorDef mgd in DefDatabase <MapGeneratorDef> .AllDefs)
            {
                mgd.genSteps.RemoveAll(gs =>
                                       gs.genStep is GenStep_SleepingMechanoids || gs.genStep is GenStep_Turrets ||
                                       gs.genStep is GenStep_Power);
            }

            DebugString.AppendLine("RuleDef Removal List");
            DebugString.AppendLine("- SymbolResolver_AncientCryptosleepCasket");
            DebugString.AppendLine("- SymbolResolver_ChargeBatteries");
            DebugString.AppendLine("- SymbolResolver_EdgeMannedMortor");
            DebugString.AppendLine("- SymbolResolver_FirefoamPopper");
            DebugString.AppendLine("- SymbolResolver_MannedMortar");
            DebugString.AppendLine("- SymbolResolver_");
            foreach (RuleDef rd in DefDatabase <RuleDef> .AllDefs)
            {
                rd.resolvers.RemoveAll(sr =>
                                       sr is SymbolResolver_AncientCryptosleepCasket || sr is SymbolResolver_ChargeBatteries ||
                                       sr is SymbolResolver_EdgeMannedMortar || sr is SymbolResolver_FirefoamPopper ||
                                       sr is SymbolResolver_MannedMortar || sr is SymbolResolver_OutdoorLighting);
                if (rd.resolvers.Count == 0)
                {
                    rd.resolvers.Add(new SymbolResolver_AddWortToFermentingBarrels());
                }
            }

            Log.Message("Removed " + removedDefs + " modern defs");

            PawnWeaponGenerator.Reset();
            PawnApparelGenerator.Reset();

            Debug.Log(DebugString.ToString());
            DebugString = new StringBuilder();
        }
 private static void DoPlayLoad()
 {
     GraphicDatabase.Clear();
     DeepProfiler.Start("Load all active mods.");
     try
     {
         LoadedModManager.LoadAllActiveMods();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Load language metadata.");
     try
     {
         LanguageDatabase.LoadAllMetadata();
     }
     finally
     {
         DeepProfiler.End();
     }
     LongEventHandler.SetCurrentEventText("LoadingDefs".Translate());
     DeepProfiler.Start("Copy all Defs from mods to global databases.");
     try
     {
         foreach (Type genericParam in typeof(Def).AllSubclasses())
         {
             GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), genericParam, "AddAllInMods");
         }
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve cross-references between non-implied Defs.");
     try
     {
         DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Rebind defs (early).");
     try
     {
         DefOfHelper.RebindAllDefOfs(true);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Inject selected language data into game data (early pass).");
     try
     {
         LanguageDatabase.activeLanguage.InjectIntoData_BeforeImpliedDefs();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Generate implied Defs (pre-resolve).");
     try
     {
         DefGenerator.GenerateImpliedDefs_PreResolve();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve cross-references between Defs made by the implied defs.");
     try
     {
         DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Rebind DefOfs (final).");
     try
     {
         DefOfHelper.RebindAllDefOfs(false);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Other def binding, resetting and global operations (pre-resolve).");
     try
     {
         PlayerKnowledgeDatabase.ReloadAndRebind();
         LessonAutoActivator.Reset();
         CostListCalculator.Reset();
         Pawn.ResetStaticData();
         PawnApparelGenerator.Reset();
         RestUtility.Reset();
         ThoughtUtility.Reset();
         PawnWeaponGenerator.Reset();
         ThinkTreeKeyAssigner.Reset();
         ThingCategoryNodeDatabase.FinalizeInit();
         TrainableUtility.Reset();
         HaulAIUtility.Reset();
         GenConstruct.Reset();
         MedicalCareUtility.Reset();
         InspectPaneUtility.Reset();
         GraphicDatabaseHeadRecords.Reset();
         DateReadout.Reset();
         ResearchProjectDef.GenerateNonOverlappingCoordinates();
         BaseGen.Reset();
         ResourceCounter.ResetDefs();
         ApparelProperties.ResetStaticData();
         WildPlantSpawner.ResetStaticData();
         PawnGenerator.Reset();
         TunnelHiveSpawner.ResetStaticData();
         Hive.ResetStaticData();
         ExpectationsUtility.Reset();
         WealthWatcher.ResetStaticData();
         WorkGiver_FillFermentingBarrel.ResetStaticData();
         WorkGiver_DoBill.ResetStaticData();
         WorkGiver_InteractAnimal.ResetStaticData();
         WorkGiver_Warden_DoExecution.ResetStaticData();
         WorkGiver_GrowerSow.ResetStaticData();
         WorkGiver_Miner.ResetStaticData();
         WorkGiver_FixBrokenDownBuilding.ResetStaticData();
         WorkGiver_ConstructDeliverResources.ResetStaticData();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve references.");
     try
     {
         foreach (Type type in typeof(Def).AllSubclasses())
         {
             if (type != typeof(ThingDef))
             {
                 GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), type, "ResolveAllReferences", new object[]
                 {
                     true
                 });
             }
         }
         DefDatabase <ThingDef> .ResolveAllReferences(true);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Generate implied Defs (post-resolve).");
     try
     {
         DefGenerator.GenerateImpliedDefs_PostResolve();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Other def binding, resetting and global operations (post-resolve).");
     try
     {
         BuildingProperties.FinalizeInit();
         ThingSetMakerUtility.Reset();
     }
     finally
     {
         DeepProfiler.End();
     }
     if (Prefs.DevMode)
     {
         DeepProfiler.Start("Error check all defs.");
         try
         {
             foreach (Type genericParam2 in typeof(Def).AllSubclasses())
             {
                 GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), genericParam2, "ErrorCheckAllDefs");
             }
         }
         finally
         {
             DeepProfiler.End();
         }
     }
     LongEventHandler.SetCurrentEventText("Initializing".Translate());
     DeepProfiler.Start("Load keyboard preferences.");
     try
     {
         KeyPrefs.Init();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Short hash giving.");
     try
     {
         ShortHashGiver.GiveAllShortHashes();
     }
     finally
     {
         DeepProfiler.End();
     }
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         DeepProfiler.Start("Load backstories.");
         try
         {
             BackstoryDatabase.ReloadAllBackstories();
         }
         finally
         {
             DeepProfiler.End();
         }
     });
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         DeepProfiler.Start("Inject selected language data into game data.");
         try
         {
             LanguageDatabase.activeLanguage.InjectIntoData_AfterImpliedDefs();
             GenLabel.ClearCache();
         }
         finally
         {
             DeepProfiler.End();
         }
     });
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         StaticConstructorOnStartupUtility.CallAll();
         if (Prefs.DevMode)
         {
             StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes();
         }
     });
 }
Beispiel #5
0
        static RemoveIndustrialStuff()
        {
            DebugString.AppendLine("RemoveIndustrialStuff - Start Removal Log");
            DebugString.AppendLine("Tech Max Level = " + MAX_TECHLEVEL);

            removedDefs = 0;
            IEnumerable <ResearchProjectDef> projects = new List <ResearchProjectDef>();

            if (ModStuff.Settings.LimitResearch)
            {
                projects = DefDatabase <ResearchProjectDef> .AllDefs.Where(rpd => rpd.techLevel > MAX_TECHLEVEL);
            }


            if (ModStuff.Settings.LimitItems)
            {
                things = new HashSet <ThingDef>(DefDatabase <ThingDef> .AllDefs.Where(td =>
                                                                                      td.techLevel > MAX_TECHLEVEL ||
                                                                                      (td.researchPrerequisites?.Any(rpd => projects.Contains(rpd)) ?? false)));
            }

            DebugString.AppendLine("RecipeDef Removal List");

            foreach (var thing in from thing in things where thing.tradeTags != null select thing)
            {
                var tags = thing.tradeTags.ToArray();
                foreach (var tag in tags)
                {
                    if (tag.StartsWith("CE_AutoEnableCrafting"))
                    {
                        thing.tradeTags.Remove(tag);
                    }
                }
            }

            DebugString.AppendLine("ResearchProjectDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ResearchProjectDef>), projects);

            DebugString.AppendLine("Scenario Part Removal List");
            var getThingInfo =
                typeof(ScenPart_ThingCount).GetField("thingDef", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var def in DefDatabase <ScenarioDef> .AllDefs)
            {
                foreach (var sp in def.scenario.AllParts)
                {
                    if (!(sp is ScenPart_ThingCount) || !things.Contains((ThingDef)getThingInfo?.GetValue(sp)))
                    {
                        continue;
                    }

                    def.scenario.RemovePart(sp);
                    DebugString.AppendLine("- " + sp.Label + " " + ((ThingDef)getThingInfo?.GetValue(sp))?.label +
                                           " from " + def.label);
                }
            }

            foreach (var thingCategoryDef in DefDatabase <ThingCategoryDef> .AllDefs)
            {
                thingCategoryDef.childThingDefs.RemoveAll(things.Contains);
            }

            DebugString.AppendLine("Stock Generator Part Cleanup");
            foreach (var tkd in DefDatabase <TraderKindDef> .AllDefs)
            {
                for (var i = tkd.stockGenerators.Count - 1; i >= 0; i--)
                {
                    var stockGenerator = tkd.stockGenerators[i];

                    switch (stockGenerator)
                    {
                    case StockGenerator_SingleDef sd
                        when things.Contains(Traverse.Create(sd).Field("thingDef").GetValue <ThingDef>()):
                        var def = Traverse.Create(sd).Field("thingDef").GetValue <ThingDef>();

                        tkd.stockGenerators.Remove(stockGenerator);
                        DebugString.AppendLine("- " + def.label + " from " + tkd.label +
                                               "'s StockGenerator_SingleDef");
                        break;

                    case StockGenerator_MultiDef md:
                        var thingListTraverse = Traverse.Create(md).Field("thingDefs");
                        var thingList         = thingListTraverse.GetValue <List <ThingDef> >();
                        var removeList        = thingList.FindAll(things.Contains);
                        removeList.ForEach(x =>
                                           DebugString.AppendLine("- " + x.label + " from " + tkd.label +
                                                                  "'s StockGenerator_MultiDef"));
                        thingList.RemoveAll(things.Contains);

                        if (thingList.NullOrEmpty())
                        {
                            tkd.stockGenerators.Remove(stockGenerator);
                        }
                        else
                        {
                            thingListTraverse.SetValue(thingList);
                        }

                        break;
                    }
                }
            }

            DebugString.AppendLine("ThingDef Removal List");
            RemoveStuffFromDatabase(typeof(DefDatabase <ThingDef>), things.ToArray());

            DebugString.AppendLine("ThingSetMaker Reset");
            ThingSetMakerUtility.Reset();

            DebugString.AppendLine("Designators Resolved Again");
            var resolveDesignatorsAgain = typeof(DesignationCategoryDef).GetMethod("ResolveDesignators",
                                                                                   BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var dcd in DefDatabase <DesignationCategoryDef> .AllDefs)
            {
                resolveDesignatorsAgain?.Invoke(dcd, null);
            }

            if (ModStuff.Settings.LimitPawns)
            {
                DebugString.AppendLine("PawnKindDef Removal List");
                RemoveStuffFromDatabase(typeof(DefDatabase <PawnKindDef>),
                                        DefDatabase <PawnKindDef> .AllDefs.Where(pkd =>
                                                                                 (!pkd.defaultFactionType?.isPlayer ?? false) && pkd.race.techLevel > MAX_TECHLEVEL));
            }

            if (ModStuff.Settings.LimitFactions)
            {
                DebugString.AppendLine("FactionDef Removal List");

                foreach (var factionDef in DefDatabase <FactionDef> .AllDefsListForReading.Where(def =>
                                                                                                 def.defName.ToLower().Contains("refugee") && def.techLevel > MAX_TECHLEVEL))
                {
                    DebugString.AppendLine(
                        $"Lowering tech-level of {factionDef.label} since its a refugee-faction needed for quests");
                    factionDef.techLevel = MAX_TECHLEVEL;
                }

                RemoveStuffFromDatabase(typeof(DefDatabase <FactionDef>),
                                        DefDatabase <FactionDef> .AllDefs.Where(fd => !fd.isPlayer && fd.techLevel > MAX_TECHLEVEL));
                if (ModLister.RoyaltyInstalled)
                {
                    var incident = DefDatabase <IncidentDef> .GetNamedSilentFail("CaravanArrivalTributeCollector");

                    if (incident != null)
                    {
                        RemoveStuffFromDatabase(typeof(DefDatabase <IncidentDef>), new List <Def> {
                            incident
                        });
                    }
                }

                // foreach (var factionDef in DefDatabase<FactionDef>.AllDefs.Where(fd => !fd.isPlayer && fd.techLevel > MAX_TECHLEVEL))
                // {
                // factionDef.hidden = true;
                // factionDef.canMakeRandomly = false;
                // factionDef.maxCountAtGameStart = 0;
                // }
            }

            if (ModStuff.Settings.LogRemovals)
            {
                Log.Message(DebugString.ToString());
            }
            else
            {
                Log.Message("Removed " + removedDefs + " industrial defs");
            }

            PawnWeaponGenerator.Reset();
            PawnApparelGenerator.Reset();

            Debug.Log(DebugString.ToString());
            DebugString = new StringBuilder();
        }