public void ResolveHamonTab()
 {
     if (!this.Pawn.story.traits.HasTrait(JJBRDefOf.JJBR_HamonWielder))
     {
         InspectTabBase inspectTabsx = base.AbilityUser.GetInspectTabs().FirstOrDefault((InspectTabBase x) => x.labelKey == "JJBR_TabHamon");
         IEnumerable <InspectTabBase> inspectTabs = base.AbilityUser.GetInspectTabs();
         bool flag = inspectTabs != null && inspectTabs.Count <InspectTabBase>() > 0;
         if (flag)
         {
             if (inspectTabsx == null)
             {
                 try
                 {
                     base.AbilityUser.def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Hamon)));
                 }
                 catch (Exception ex)
                 {
                     Log.Error(string.Concat(new object[]
                     {
                         "Could not instantiate inspector tab of type ",
                         typeof(ITab_Hamon),
                         ": ",
                         ex
                     }));
                 }
             }
         }
     }
 }
Esempio n. 2
0
        static void Inject()
        {
            var defs = DefDatabase <ThingDef> .AllDefs.Where(InjectPredicate).ToList();

            var tabType        = typeof(ITab_Infused);
            var tab            = InspectTabManager.GetSharedInstance(tabType);
            var compProperties = new Verse.CompProperties {
                compClass = typeof(CompInfused)
            };

            foreach (var def in defs)
            {
                def.comps.Add(compProperties);
                #if DEBUG
                Log.Message("Infused :: Component added to " + def.label);
                #endif

                if (def.inspectorTabs == null || def.inspectorTabs.Count == 0)
                {
                    def.inspectorTabs         = new List <Type>();
                    def.inspectorTabsResolved = new List <InspectTabBase>();
                }

                def.inspectorTabs.Add(tabType);
                def.inspectorTabsResolved.Add(tab);
            }
            #if DEBUG
            Log.Message("Infused :: Injected " + defs.Count + "/" + DefDatabase <ThingDef> .AllDefs.Count());
            #endif
        }
Esempio n. 3
0
 public void ResolveITab()
 {
     if (!this.ResolvedITTab)
     {
         this.ResolvedITTab = true;
         //PostExposeData();
         //Make the ITab
         IEnumerable <InspectTabBase> tabs = this.Pawn.GetInspectTabs();
         if (tabs != null && tabs.Count <InspectTabBase>() > 0)
         {
             if (tabs.FirstOrDefault((InspectTabBase x) => x is ITab_Passengers) == null)
             {
                 try
                 {
                     this.Pawn.def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Passengers)));
                 }
                 catch (Exception ex)
                 {
                     Log.Error(string.Concat(new object[]
                     {
                         "Could not instantiate inspector tab of type ",
                         typeof(ITab_Passengers),
                         ": ",
                         ex
                     }));
                 }
             }
         }
     }
 }
Esempio n. 4
0
 public override void PostLoad()
 {
     base.PostLoad();
     if (this.inspectorTabs != null)
     {
         for (int i = 0; i < this.inspectorTabs.Count; i++)
         {
             if (this.inspectorTabsResolved == null)
             {
                 this.inspectorTabsResolved = new List <InspectTabBase>();
             }
             try
             {
                 this.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(this.inspectorTabs[i]));
             }
             catch (Exception ex)
             {
                 Log.Error(string.Concat(new object[]
                 {
                     "Could not instantiate inspector tab of type ",
                     this.inspectorTabs[i],
                     ": ",
                     ex
                 }), false);
             }
         }
     }
 }
Esempio n. 5
0
        static RestrictedStorage()
        {
            var harmony = new HarmonyLib.Harmony("net.littlewhitemouse.RimWorld.RestrictedStorage");

            harmony.PatchAll();
            // Add ITab and Comp to proper storage buildings:
            //   Add to all Building_Storage but not ones in Production (hoppers?)
            // This should be slightly faster than xpath xml patching.
            var desigProduction = DefDatabase <DesignationCategoryDef> .GetNamed("Production");

            var itabResolved = InspectTabManager.GetSharedInstance(typeof(ITab_RestrictedStorage));

            foreach (var b in DefDatabase <ThingDef> .AllDefs
                     .Where(d => (d?.thingClass != null &&
                                  (d.thingClass == typeof(Building_Storage) ||
                                   d.thingClass.IsSubclassOf(typeof(Building_Storage)))))
                     .Where(d => d.designationCategory != desigProduction))
            {
                // This should be the equivalent of
                //   <comps>
                //     <li>
                //       <compClass>CompRestrictedStorage</compClass>etc
                if (b.comps != null)
                {
                    b.comps.Add(new CompProperties {
                        compClass = typeof(CompRestrictedStorage)
                    });
                }
                else
                {
                    Log.Message("LWM.Restricted Storage: " + b + " does not have comps");
                    continue;
                }
                // but....we don't actually want to add this comp to EVERYTHING - I mean, why
                // bother?  It's not going to be used in the majority of cases.  Except...
                // the game won't load save-game-data unless the comp is already there.  Yes...
                // So we do add it to everything.
                //
                // On the other hand, we DO want to use the ITab for all storage buildings:
                // This mirrors ThingDef's resolve references - I didn't want to take the time
                //   to do a ResolveReferences for every single ThingDef, but if anything
                //   breaks, that's always an option...
                if (b.inspectorTabs != null)
                {
                    b.inspectorTabs.Add(typeof(ITab_RestrictedStorage));
                    if (b.inspectorTabsResolved != null)
                    {
                        b.inspectorTabsResolved.Add(itabResolved);
                    }
                    else
                    {
                        Log.Message("LWM.Restricted Storage: " + b + " does not have inspectorTabsResolved");
                    }
                }
                else
                {
                    Log.Message("LWM.Restricted Storage: " + b + " does not have inspectorTabs");
                }
            }
        }
Esempio n. 6
0
 public void ResolveITab()
 {
     if (!ResolvedITTab)
     {
         ResolvedITTab = true;
         //PostExposeData();
         //Make the ITab
         var tabs = Pawn.GetInspectTabs();
         if (tabs != null && tabs.Count() > 0)
         {
             if (tabs.FirstOrDefault(x => x is ITab_Passengers) == null)
             {
                 try
                 {
                     Pawn.def.inspectorTabsResolved.Add(
                         InspectTabManager.GetSharedInstance(typeof(ITab_Passengers)));
                 }
                 catch (Exception ex)
                 {
                     Log.Error(string.Concat("Could not instantiate inspector tab of type ",
                                             typeof(ITab_Passengers), ": ", ex));
                 }
             }
         }
     }
 }
Esempio n. 7
0
        private static void Inject()
        {
            var defs = (
                from def in DefDatabase <ThingDef> .AllDefs
                where (def.IsMeleeWeapon || def.IsRangedWeapon || def.IsApparel) &&
                def.HasComp(typeof(CompQuality)) && !def.HasComp(typeof(CompInfusion))
                select def
                );

            var tabType        = typeof(ITab_Infusion);
            var tab            = InspectTabManager.GetSharedInstance(tabType);
            var compProperties = new CompProperties {
                compClass = typeof(CompInfusion)
            };

            foreach (var def in defs)
            {
                def.comps.Add(compProperties);
                                #if DEBUG
                Log.Message("Infused :: Component added to " + def.label);
                                #endif

                if (def.inspectorTabs == null || def.inspectorTabs.Count == 0)
                {
                    def.inspectorTabs         = new List <Type> ();
                    def.inspectorTabsResolved = new List <InspectTabBase> ();
                }

                def.inspectorTabs.Add(tabType);
                def.inspectorTabsResolved.Add(tab);
            }
                        #if DEBUG
            Log.Message("Infused :: Injected " + defs.Count() + " " + DefDatabase <ThingDef> .AllDefs.Count());
                        #endif
        }
        public override void DefsLoaded()
        {
            if (!this.ModIsActive)
            {
                return;
            }
            IEnumerable <ThingDef> thingDefs = DefDatabase <ThingDef> .AllDefs.Where <ThingDef>((Func <ThingDef, bool>)(def =>
            {
                RaceProperties race = def.race;
                if ((race != null ? (race.intelligence == Intelligence.Humanlike ? 1 : 0) : 0) == 0)
                {
                    return(false);
                }
                return(true);
            }));

            foreach (ThingDef thingDef in thingDefs)
            {
                if (thingDef.inspectorTabsResolved == null)
                {
                    thingDef.inspectorTabsResolved = new List <InspectTabBase>(1);
                }
                thingDef.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Religion)));
                if (thingDef.comps == null)
                {
                    thingDef.comps = new List <CompProperties>(1);
                }
                thingDef.comps.Add((CompProperties) new CompProperties_ReligionComp());
            }
        }
Esempio n. 9
0
        public override void Initialize(CompProperties props)
        {
            base.Initialize(props);

            var inspectTabs = parent.GetInspectTabs();

            if (inspectTabs != null && inspectTabs.Count() > 0 && inspectTabs.FirstOrDefault(x => x is ITab_Skills) == null)
            {
                int bioIndex   = inspectTabs.FirstIndexOf(x => x is ITab_Pawn_Character);
                int skillIndex = Math.Min(bioIndex + 1, inspectTabs.Count());
                try
                {
                    parent.def.inspectorTabsResolved.Insert(skillIndex, InspectTabManager.GetSharedInstance(typeof(ITab_Skills)));
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Could not instantiate inspector tab of type ",
                        typeof(ITab_Skills),
                        ": ",
                        ex
                    }), false);
                }
            }
        }
Esempio n. 10
0
        public static void EditDefs()
        {
            IEnumerable <ThingDef> things = (
                from def in DefDatabase <ThingDef> .AllDefs
                where def.race?.intelligence == Intelligence.Humanlike
                select def
                );

            foreach (ThingDef t in things)
            {
                // add badge tab to pawns
                if (t.inspectorTabsResolved == null)
                {
                    t.inspectorTabsResolved = new List <InspectTabBase>(1);
                }
                t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Badge)));

                // add Badge component property to all humanlike pawns
                if (t.comps == null)
                {
                    t.comps = new List <CompProperties>(1);
                }
                t.comps.Add(new CompProperties_Badge());
            }
        }
        // ReSharper disable once UnusedMember.Global
        public GameComponent_Outfitter(Game game)
        {
            this._game = game;
            if (Controller.Settings.UseEyes)
            {
                foreach (BodyDef bodyDef in DefDatabase <BodyDef> .AllDefsListForReading)
                {
                    if (bodyDef.defName != "Human")
                    {
                        continue;
                    }

                    BodyPartRecord neck = bodyDef.corePart.parts.FirstOrDefault(x => x.def == BodyPartDefOf.Neck);
                    BodyPartRecord head = neck?.parts.FirstOrDefault(x => x.def == BodyPartDefOf.Head);
                    if (head == null)
                    {
                        continue;
                    }
                    //    if (!head.groups.Contains(BodyPartGroupDefOf.Eyes))
                    {
                        //     head.groups.Add(BodyPartGroupDefOf.Eyes);
                        //BodyPartRecord leftEye = head.parts.FirstOrDefault(x => x.def == BodyPartDefOf.LeftEye);
                        //BodyPartRecord rightEye = head.parts.FirstOrDefault(x => x.def == BodyPartDefOf.RightEye);
                        BodyPartRecord jaw = head.parts.FirstOrDefault(x => x.def == BodyPartDefOf.Jaw);
                        //leftEye?.groups.Remove(BodyPartGroupDefOf.FullHead);
                        //rightEye?.groups.Remove(BodyPartGroupDefOf.FullHead);
                        jaw?.groups.Remove(BodyPartGroupDefOf.FullHead);
                        Log.Message("Outfitter patched Human eyes and jaw.");
                        break;
                    }
                }
            }

            foreach (ThingDef def in DefDatabase <ThingDef> .AllDefsListForReading.Where(
                         td => td.category == ThingCategory.Pawn && td.race.Humanlike))
            {
                // if (def.inspectorTabs == null)
                // {
                //     def.inspectorTabs = new List<Type>();
                // }
                //
                // if (def.inspectorTabsResolved == null)
                // {
                //     def.inspectorTabsResolved = new List<InspectTabBase>();
                // }
                if (def.inspectorTabs == null || def.inspectorTabsResolved == null)
                {
                    return;
                }

                if (def.inspectorTabs.Contains(typeof(Tab_Pawn_Outfitter)))
                {
                    return;
                }

                def.inspectorTabs.Add(typeof(Tab_Pawn_Outfitter));
                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(Tab_Pawn_Outfitter)));
            }
        }
Esempio n. 12
0
 private static void SyncITab(SyncWorker sync, ref ITab_Pawn_Gear gearITab)
 {
     if (sync.isWriting)
     {
         sync.Write(gearITab.GetType());
     }
     else
     {
         gearITab = (ITab_Pawn_Gear)InspectTabManager.GetSharedInstance(sync.Read <Type>());
     }
 }
Esempio n. 13
0
        private static void AddComp()
        {
            //unrelated, single time load mod check
            //foreach (ModContentPack p in LoadedModManager.RunningMods)
            //{
            //    Log.Message(p.Name + "");
            //}

            //&& def.HasComp(typeof(CompQuality))
            IEnumerable <ThingDef> enumerable = from def in DefDatabase <ThingDef> .AllDefs
                                                where (def.IsMeleeWeapon || def.IsRangedWeapon || def.IsApparel) && !def.HasComp(typeof(CompEnchantedItem))
                                                select def;
            Type           typeFromHandle = typeof(ITab_Enchantment);
            InspectTabBase sharedInstance = InspectTabManager.GetSharedInstance(typeFromHandle);

            foreach (ThingDef current in enumerable)
            {
                //if (current.defName != "TM_ThrumboAxe" && current.defName != "TM_FireWand" && current.defName != "TM_IceWand" && current.defName != "TM_LightningWand" &&
                //    current.defName != "TM_BlazingPowerStaff" && current.defName != "TM_DefenderStaff")
                if (!current.defName.Contains("TM_"))
                {
                    CompProperties_EnchantedItem item = new CompProperties_EnchantedItem
                    {
                        compClass = typeof(CompEnchantedItem)
                    };
                    current.comps.Add(item);

                    if (current.inspectorTabs == null || current.inspectorTabs.Count == 0)
                    {
                        current.inspectorTabs         = new List <Type>();
                        current.inspectorTabsResolved = new List <InspectTabBase>();
                    }
                    current.inspectorTabs.Add(typeFromHandle);
                    current.inspectorTabsResolved.Add(sharedInstance);
                }
            }

            //IEnumerable<ThingDef> enumerable1 = from def in DefDatabase<ThingDef>.AllDefs
            //                                   where (def.race != null && def.race.Humanlike && !def.HasComp(typeof(CompEnchant)))
            //                                    select def;
            //foreach (ThingDef current1 in enumerable1)
            //{
            //    CompProperties_Enchant enchanting = new CompProperties_Enchant
            //    {
            //        compClass = typeof(CompEnchant)
            //    };
            //    current1.comps.Add(enchanting);
            //}
        }
Esempio n. 14
0
        public Func <XmlNode, object> makeParser(params Type[] arguments)
        {
            return(delegate(XmlNode node) {
                Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(node.InnerText);
                if (typeInAnyAssembly != null && typeof(Type).IsAssignableFrom(typeInAnyAssembly))
                {
                    Type iTabType = (Type)Activator.CreateInstance(typeInAnyAssembly);

                    return InspectTabManager.GetSharedInstance(iTabType);
                }
                else
                {
                    return null;
                }
            });
        }
Esempio n. 15
0
        private void InjectTab(Type tabType, Func <ThingDef, bool> qualifier)
        {
            var defs = DefDatabase <ThingDef> .AllDefs.Where(qualifier).ToList();

            defs.RemoveDuplicates();

            foreach (var def in defs)
            {
                if (!def.inspectorTabs.Contains(tabType))
                {
                    def.inspectorTabs.Add(tabType);
                    def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(tabType));
                    //Log.Message(def.defName+": "+def.inspectorTabsResolved.Select(d=>d.GetType().Name).Aggregate((a,b)=>a+", "+b));
                }
            }
        }
        public override void DefsLoaded()
        {
            if (!base.ModIsActive)
            {
                return;
            }
            IEnumerable <ThingDef> allPawns = DefDatabase <ThingDef> .AllDefs.Where((ThingDef def) => def.thingClass == typeof(Pawn));

            foreach (ThingDef pawnThing in allPawns)
            {
                if (pawnThing.inspectorTabsResolved == null)
                {
                    pawnThing.inspectorTabsResolved = new List <InspectTabBase>(1);
                }
                pawnThing.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Hope)));
            }
        }
Esempio n. 17
0
        public override bool Inject()
        {
            // get reference to lists of itabs
            List <Type>           itabs         = ThingDefOf.Human.inspectorTabs;
            List <InspectTabBase> itabsResolved = ThingDefOf.Human.inspectorTabsResolved;

            /*
             *
             #if DEBUG
             * Log.Message( "Inspector tab types on humans:" );
             * foreach ( var tab in itabs )
             * {
             *  Log.Message( "\t" + tab.Name );
             * }
             * Log.Message( "Resolved tab instances on humans:" );
             * foreach ( var tab in itabsResolved )
             * {
             *  Log.Message( "\t" + tab.labelKey.Translate() );
             * }
             #endif
             */

            // replace ITab in the unresolved list
            int index = itabs.IndexOf(typeof(ITab_Pawn_Gear));

            if (index != -1)
            {
                itabs.Remove(typeof(ITab_Pawn_Gear));
                itabs.Insert(index, typeof(ITab_Inventory));
            }

            // replace resolved ITab, if needed.
            InspectTabBase oldGearTab = InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Gear));
            InspectTabBase newGearTab = InspectTabManager.GetSharedInstance(typeof(ITab_Inventory));

            if (!itabsResolved.NullOrEmpty() && itabsResolved.Contains(oldGearTab))
            {
                int resolvedIndex = itabsResolved.IndexOf(oldGearTab);
                itabsResolved.Insert(resolvedIndex, newGearTab);
                itabsResolved.Remove(oldGearTab);
            }

            return(true);
        }
Esempio n. 18
0
 static AddITabOnStartup()
 {
     foreach (var def in DefDatabase <ThingDef> .AllDefsListForReading)
     {
         if (def.category == ThingCategory.Pawn && def.inspectorTabsResolved is List <InspectTabBase> tabs)
         {
             var toggleDefTab = InspectTabManager.GetSharedInstance(typeof(ITab_ToggleDef));
             var gearTabIndex = tabs.FindIndex(tab => tab is ITab_Pawn_Gear);
             if (gearTabIndex < 0)
             {
                 tabs.Add(toggleDefTab);
             }
             else
             {
                 tabs.Insert(gearTabIndex + 1, toggleDefTab);
             }
         }
     }
 }
        public static IEnumerable <InspectTabBase> Postfix(IEnumerable <InspectTabBase> tabBases, Thing __instance)
        {
            if (tabBases.EnumerableNullOrEmpty())
            {
                yield break;
            }

            if (AwesomeInvnetoryMod.Settings.PatchAllRaces && __instance is Pawn pawn && pawn.IsColonist)
            {
                foreach (InspectTabBase tabBase in tabBases)
                {
                    if (tabBase is ITab_Pawn_Gear)
                    {
                        yield return(InspectTabManager.GetSharedInstance(AwesomeInventoryServiceProvider.GetService <AwesomeInventoryTabBase>().GetType()));
                    }
                    else
                    {
                        yield return(tabBase);
                    }
                }
            }
        static PsiTechAlienRacesPatcherUtility()
        {
            if (!PsiTechSettings.Get().PatchAllRaces)
            {
                return;
            }

            // This approach has some serious start-up time implications but at least it doesn't impact
            // runtime performance. I'd choose seconds on a load over constant overhead any day.
            var allThings = DefDatabase <ThingDef> .AllDefs;

            foreach (var def in allThings)
            {
                if (!(def.inspectorTabsResolved?.Any(tab => tab is ITab_Pawn_Needs) ?? false) ||
                    def.inspectorTabsResolved.Any(tab => tab is ITab_Pawn_Psi))
                {
                    continue;
                }

                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Psi)));
            }
        }
Esempio n. 21
0
 public override void PostLoad()
 {
     base.PostLoad();
     if (inspectorTabs != null)
     {
         for (int i = 0; i < inspectorTabs.Count; i++)
         {
             if (inspectorTabsResolved == null)
             {
                 inspectorTabsResolved = new List <InspectTabBase>();
             }
             try
             {
                 inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(inspectorTabs[i]));
             }
             catch (Exception ex)
             {
                 Log.Error("Could not instantiate inspector tab of type " + inspectorTabs[i] + ": " + ex);
             }
         }
     }
 }
Esempio n. 22
0
        public static void PatchDefs()
        {
            if (Prefs.DevMode)
            {
                Log.Message($"Patching DivineJobs to Humanlike ThingDefs with '{nameof(CompProperties_DivineJobs)}' and '{nameof(ITab_DivineJobs)}'.");
            }
            //Patch all compatible ThingDefs.
            //Requires: Can be Colonist
            foreach (ThingDef thingDef in DefDatabase <ThingDef> .AllDefs)
            {
                if (thingDef?.race?.Humanlike ?? false)
                {
                    if (thingDef.comps == null)
                    {
                        thingDef.comps = new List <CompProperties>();
                    }
                    thingDef.comps.Add(new CompProperties_DivineJobs());

                    if (thingDef.inspectorTabs == null)
                    {
                        thingDef.inspectorTabs = new List <Type>();
                    }
                    //Insert next to Bio tab.
                    int bioTabPos = thingDef.inspectorTabs.IndexOf(typeof(ITab_Pawn_Character));
                    if (bioTabPos < 0)
                    {
                        bioTabPos = 0;
                    }
                    thingDef.inspectorTabs.Insert(bioTabPos, typeof(ITab_DivineJobs));
                    thingDef.inspectorTabsResolved.Insert(bioTabPos, InspectTabManager.GetSharedInstance(typeof(ITab_DivineJobs)));

                    if (Prefs.DevMode)
                    {
                        Log.Message($"=>{thingDef.defName} Patched");
                    }
                }
            }
        }
Esempio n. 23
0
 static DoHorrifyingThingsToDefDatabase()
 {
     foreach (var d in DefDatabase <ThingDef> .AllDefs)
     {
         if (d.comps != null)
         {
             foreach (var c in d.comps)
             {
                 if (c is CompProperties_Refuelable cpr /*&& cpr.fuelFilter.AllowedDefCount > 1*/)
                 {
                     //                                   some mods allow def editing in-game
                     #if DEBUG
                     Log.Message("LWM Fuel Filter patching " + d.defName + " for fuels "
                                 + String.Join(", ", cpr.fuelFilter.AllowedThingDefs.Select(a => a.ToString())));
                     #endif
                     d.comps.Add(new CompProperties()
                     {
                         compClass = typeof(Comp_FuelFilter)
                     });
                     if (d.inspectorTabs == null)
                     {
                         d.inspectorTabs = new System.Collections.Generic.List <Type>();
                     }
                     d.inspectorTabs.Add(typeof(ITab_FuelFilter));
                     // But ITabs are "Resolved," and stored internally in inspectorTabsResolved -
                     //   because we are doing this via C# rather than XML patching, we have to do
                     //   the resolving ourselvs:
                     if (d.inspectorTabsResolved == null)
                     {
                         d.inspectorTabsResolved = new System.Collections.Generic.List <InspectTabBase>();
                     }
                     d.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_FuelFilter)));
                     break;
                 }
             }
         }
     }
 }
Esempio n. 24
0
        public static void Initialize()
        {
            // Make evil people immune to thoughts listed below
            List<ThoughtDef> nullifiedThoughts = new List<ThoughtDef>();
            nullifiedThoughts.Add(ThoughtDefOf.KnowGuestExecuted);
            nullifiedThoughts.Add(ThoughtDefOf.KnowPrisonerDiedInnocent);
            nullifiedThoughts.Add(ThoughtDefOf.KnowPrisonerSold);
            nullifiedThoughts.Add(ThoughtDefOf.KnowGuestOrganHarvested);
            nullifiedThoughts.Add(ThoughtDefOf.WitnessedDeathNonAlly);

            foreach (var thought in nullifiedThoughts)
            {
                thought.nullifyingTraits?.Add(BPDefOf.BadPeople_Evil);
                thought.ResolveReferences();
            }

            // Ensure psychopath can't be evil person
            var psychopathTrait = TraitDefOf.Psychopath;
            if (psychopathTrait.conflictingTraits == null)
                psychopathTrait.conflictingTraits = new List<TraitDef>();
            if (!psychopathTrait.conflictingTraits.Contains(BPDefOf.BadPeople_Evil))
                psychopathTrait.conflictingTraits.Add(BPDefOf.BadPeople_Evil);
            psychopathTrait.ResolveReferences();

            KinslayerInitialize();

            // Adding Debug tab to all pawns, visibility resolved internally, later.
            foreach (ThingDef t in DefDatabase<ThingDef>.AllDefs.Where(def => def.race != null && def.race.intelligence == Intelligence.Humanlike))
            {
                if (t.inspectorTabsResolved == null)
                {
                    t.inspectorTabsResolved = new List<InspectTabBase>(1);
                }
                t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_DebugActivityLog)));
            }
            InspectPaneUtility.Reset();
        }
Esempio n. 25
0
        private static void AddComp()
        {
            IEnumerable <ThingDef> enumerable = from def in DefDatabase <ThingDef> .AllDefs
                                                where (def.IsMeleeWeapon || def.IsRangedWeapon || def.IsApparel) && def.HasComp(typeof(CompQuality)) && !def.HasComp(typeof(CompEnchantedItem))
                                                select def;
            Type           typeFromHandle = typeof(ITab_Enchantment);
            InspectTabBase sharedInstance = InspectTabManager.GetSharedInstance(typeFromHandle);

            foreach (ThingDef current in enumerable)
            {
                CompProperties_EnchantedItem item = new CompProperties_EnchantedItem
                {
                    compClass = typeof(CompEnchantedItem)
                };
                current.comps.Add(item);

                if (current.inspectorTabs == null || current.inspectorTabs.Count == 0)
                {
                    current.inspectorTabs         = new List <Type>();
                    current.inspectorTabsResolved = new List <InspectTabBase>();
                }
                current.inspectorTabs.Add(typeFromHandle);
                current.inspectorTabsResolved.Add(sharedInstance);
            }

            //IEnumerable<ThingDef> enumerable1 = from def in DefDatabase<ThingDef>.AllDefs
            //                                   where (def.race != null && def.race.Humanlike && !def.HasComp(typeof(CompEnchant)))
            //                                    select def;
            //foreach (ThingDef current1 in enumerable1)
            //{
            //    CompProperties_Enchant enchanting = new CompProperties_Enchant
            //    {
            //        compClass = typeof(CompEnchant)
            //    };
            //    current1.comps.Add(enchanting);
            //}
        }
        private void processDefs()
        {
            var modsList = new List <ModContentPack>();

            // ----------- Injecting tabs -----------

            //{
            //	var caravanDef = DefDatabase<WorldObjectDef>.GetNamed("Caravan");
            //	var newTabType = typeof(UI.WITab_Caravan_Needs);
            //	var oldTabType = typeof(ITab_Pawn_Needs);
            //	if (caravanDef.inspectorTabs.Remove(oldTabType))
            //	{
            //		caravanDef.inspectorTabsResolved.Remove(InspectTabManager.GetSharedInstance(oldTabType));
            //caravanDef.inspectorTabs.Add(newTabType);
            //caravanDef.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(newTabType));
            //	}
            //	else
            //	{
            //		//TODO: disaster error message
            //	}
            //}

            foreach (var current in DefDatabase <ThingDef> .AllDefs.Where((ThingDef arg) => arg.race != null))
            {
                current.inspectorTabs.Add(typeof(UI.ITab_Pawn_Food));
                current.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(UI.ITab_Pawn_Food)));

                ////Tab inject
                //var newTabType = typeof(UI.ITab_Pawn_Needs);
                //var oldTabType = typeof(ITab_Pawn_Needs);

                //int index = current.inspectorTabs.IndexOf(oldTabType);

                //if (index != -1)
                //{
                //	current.inspectorTabs[index] = newTabType;

                //	int index2 = current.inspectorTabsResolved.IndexOf(InspectTabManager.GetSharedInstance(oldTabType));

                //	if (index2 != -1)
                //	{
                //		current.inspectorTabsResolved[index2] = InspectTabManager.GetSharedInstance(newTabType);
                //	}
                //}
            }

            // ----------- Processing policies and patches -----------

            foreach (CompabilityDef def in ModCore.patches)
            {
                def.TryApplyPatch();
            }

            // Hardcoded policies
            DefDatabase <Policy> .Add(Policies.Unrestricted);

            DefDatabase <Policy> .Add(Policies.Taming);

            DefDatabase <Policy> .Add(Policies.FriendlyPets);

            DefDatabase <Policy> .Add(Policies.Friendly);

            //Policies.FriendlyPets.DefsLoaded();

            foreach (MyDefClass current in Policies.AllPolicies)
            {
                current.DefsLoaded();
            }

            Policies.BuildMaskTree();

            // ----------- Processing food categories and races -----------

            foreach (ThingDef current in DefDatabaseHelper.AllDefsIngestibleNAnimals)
            {
                if (current.ingestible != null)
                {
                    current.DetermineFoodCategory(true);
                }
                else if (current.race != null && current.race.IsFlesh)
                {
                    if (current.race.meatDef != null)
                    {
                        current.race.meatDef.DetermineFoodCategory(true);
                    }

                    if (current.race.corpseDef != null)
                    {
                        current.race.corpseDef.DetermineFoodCategory(true);
                    }
                }
            }

            // ----------- Processing recipes for food cost factors -----------

            //TODO: manage intermediate recipes + handle side products
            foreach (RecipeDef recipeDef in DefDatabase <RecipeDef> .AllDefs)
            {
                if (recipeDef.products == null || recipeDef.products.Count > 1 || recipeDef.ingredients == null || !recipeDef.products.Any((obj) => obj.thingDef.ingestible != null))
                {
                    continue;
                }

                float nutritionCost = recipeDef.ingredients.Sum((arg) => arg.GetBaseCount());
                var   singleProduct = recipeDef.products.FirstOrDefault().thingDef;

                if (!recipeDef.products.All((arg) => arg.thingDef == singleProduct))
                {
                    continue;
                }

                float nutritionOutput = recipeDef.products.Sum((arg) => arg.thingDef.ingestible.nutrition * arg.count);

                if (nutritionOutput <= 0f)
                {
                    continue;
                }

                float costFactor = nutritionCost / nutritionOutput;

                FoodDefRecord record;

                if (FoodCategoryUtils.FoodRecords.TryGetValue(singleProduct, out record))
                {
                    record.costFactor = Math.Min(record.costFactor, costFactor);
                }
            }

            // Dispenser(s)
            //TODO: make more reliable
            {
                FoodDefRecord record;
                var           dispensableDef = ThingDefOf.MealNutrientPaste;
                if (FoodCategoryUtils.FoodRecords.TryGetValue(dispensableDef, out record))
                {
                    float costFactor = 0.3f / dispensableDef.ingestible.nutrition;
                    record.costFactor = Math.Min(record.costFactor, costFactor);
                }
            }


            //foreach (ThingDef dispenser in DefDatabase<ThingDef>.AllDefs.Where(arg => arg.IsFoodDispenser))

            //ThingDef meal = null;
            //float foodCost = 0;

            //if (dispenser.thingClass == typeof(Building_NutrientPasteDispenser))
            //{
            //	var dummy = new Building_NutrientPasteDispenser();
            //	meal = dummy.DispensableDef;
            //	foodCost = (dummy.def.building.foodCostPerDispense * 0.05f);
            //}

            //if (meal != null)
            //{
            //	float costFactor = foodCost / meal.ingestible.nutrition;
            //	FoodDefRecord record;
            //	if (FoodCategoryUtils.FoodRecords.TryGetValue(meal, out record))
            //	{
            //		record.costFactor = Math.Min(record.costFactor, costFactor);
            //	}
            //}
            //}

            // ----------- Reporting -----------

            var loadedPaches = patches.Where((arg) => arg.Loaded);

            Logger.Message(string.Format("Loaded - {0} food categorized - {1} pawn diets - {2} compatibility patches ({3} fixes) - {4} policies.", FoodCategoryUtils.TotalFoodPrefsCount, FoodCategoryUtils.TotalAnimalsDietsCount, loadedPaches.Count(), loadedPaches.Sum((arg) => arg.DefsCount), Policies.AllPolicies.Count()));

            if (FoodCategoryUtils.NullPrefFoodsCount > 0)
            {
                Logger.Warning(string.Format("Could not determine food category for {0} Defs. Restricted pawns will ignore them. Are you using unsupported food mods ? ({1})", FoodCategoryUtils.NullPrefFoodsCount, string.Join(" ; ", FoodCategoryUtils.NullPrefFoods.Select((ThingDef arg) => arg.defName + " (" + arg.label + ")").ToArray())));
            }
        }
        public override void DefsLoaded()
        {
            //1. Preparing settings
            UpdateSettings();

            //2. Adding Tech Tab to Pawns
            //ThingDef injection stolen from the work of notfood for Psychology
            var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie");

            IEnumerable <ThingDef> things = (from def in DefDatabase <ThingDef> .AllDefs
                                             where def.race?.intelligence == Intelligence.Humanlike && (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree)
                                             select def);
            List <string> registered = new List <string>();

            foreach (ThingDef t in things)
            {
                if (t.inspectorTabsResolved == null)
                {
                    t.inspectorTabsResolved = new List <InspectTabBase>(1);
                }
                t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_PawnKnowledge)));
                if (t.comps == null)
                {
                    t.comps = new List <CompProperties>(1);
                }
                t.comps.Add(new CompProperties_Knowledge());
                registered.Add(t.defName);
            }
            InspectPaneUtility.Reset();

            //3. Preparing knowledge support infrastructure

            //a. Things everyone knows
            UniversalWeapons.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWeapon));
            UniversalCrops.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.plant != null && x.plant.Sowable));

            //b. Minus things unlocked on research
            ThingFilter lateFilter = new ThingFilter();

            foreach (ResearchProjectDef tech in DefDatabase <ResearchProjectDef> .AllDefs)
            {
                tech.InferSkillBias();
                tech.CreateStuff(lateFilter, unlocked);
                foreach (ThingDef weapon in tech.UnlockedWeapons())
                {
                    UniversalWeapons.Remove(weapon);
                }
                foreach (ThingDef plant in tech.UnlockedPlants())
                {
                    UniversalCrops.Remove(plant);
                }
            }
            ;

            //c. Also removing atipical weapons
            List <string> ForbiddenWeaponTags = TechDefOf.WeaponsNotBasic.weaponTags;

            UniversalWeapons.RemoveAll(x => SplitSimpleWeapons(x, ForbiddenWeaponTags));
            List <ThingDef> garbage = new List <ThingDef>();

            garbage.Add(TechDefOf.WeaponsNotBasic);

            //d. Classifying pawn backstories
            PawnBackgroundUtility.BuildCache();

            //e. Telling humans what's going on
            ThingCategoryDef       knowledgeCat = TechDefOf.Knowledge;
            IEnumerable <ThingDef> codifiedTech = DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWithinCategory(knowledgeCat));

            if (Prefs.LogVerbose || FullStartupReport)
            {
                Log.Message($"[HumanResources] Codified technologies: {codifiedTech.Select(x => x.label).ToStringSafeEnumerable()}");
                Log.Message($"[HumanResources] Basic crops: {UniversalCrops.ToStringSafeEnumerable()}");
                Log.Message($"[HumanResources] Basic weapons: {UniversalWeapons.ToStringSafeEnumerable()}");
                Log.Message($"[HumanResources] Basic weapons that require training: {SimpleWeapons.ToStringSafeEnumerable()}");
                Log.Warning($"[HumanResources] Basic weapons tags: {SimpleWeapons.Where(x => !x.weaponTags.NullOrEmpty()).SelectMany(x => x.weaponTags).Distinct().ToStringSafeEnumerable()}");
                if (FullStartupReport)
                {
                    Log.Warning("[HumanResources] Backstories classified by TechLevel:");
                    for (int i = 0; i < 8; i++)
                    {
                        TechLevel            level = (TechLevel)i;
                        IEnumerable <string> found = PawnBackgroundUtility.TechLevelByBackstory.Where(e => e.Value == level).Select(e => e.Key);
                        if (!found.EnumerableNullOrEmpty())
                        {
                            Log.Message($"- {level.ToString().CapitalizeFirst()} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}");
                        }
                    }
                    Log.Warning("[HumanResources] Techs classified by associated skill:");
                    var skills = DefDatabase <SkillDef> .AllDefsListForReading.GetEnumerator();

                    while (skills.MoveNext())
                    {
                        SkillDef             skill = skills.Current;
                        IEnumerable <string> found = TechTracker.FindTechs(skill).Select(x => x.Tech.label);
                        Log.Message($"- {skill.LabelCap} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}");
                    }
                }
            }
            else
            {
                Log.Message($"[HumanResources] This is what we know: {codifiedTech.EnumerableCount()} technologies processed, {UniversalCrops.Count()} basic crops, {UniversalWeapons.Count()} basic weapons + {SimpleWeapons.Count()} that require training.");
            }

            //4. Filling gaps on the database

            //a. TechBook dirty trick, but only now this is possible!
            TechDefOf.TechBook.stuffCategories  = TechDefOf.UnfinishedTechBook.stuffCategories = TechDefOf.LowTechCategories.stuffCategories;
            TechDefOf.TechDrive.stuffCategories = TechDefOf.HiTechCategories.stuffCategories;
            garbage.Add(TechDefOf.LowTechCategories);
            garbage.Add(TechDefOf.HiTechCategories);

            //b. Filling main tech category with subcategories
            foreach (ThingDef t in lateFilter.AllowedThingDefs.Where(t => !t.thingCategories.NullOrEmpty()))
            {
                foreach (ThingCategoryDef c in t.thingCategories)
                {
                    c.childThingDefs.Add(t);
                    if (!knowledgeCat.childCategories.NullOrEmpty() && !knowledgeCat.childCategories.Contains(c))
                    {
                        knowledgeCat.childCategories.Add(c);
                    }
                }
            }

            //c. Populating knowledge recipes and book shelves
            foreach (RecipeDef r in DefDatabase <RecipeDef> .AllDefs.Where(x => x.ingredients.Count == 1 && x.fixedIngredientFilter.AnyAllowedDef == null))
            {
                r.fixedIngredientFilter.ResolveReferences();
                r.defaultIngredientFilter.ResolveReferences();
            }
            foreach (ThingDef t in DefDatabase <ThingDef> .AllDefs.Where(x => x.thingClass == typeof(Building_BookStore)))
            {
                t.building.fixedStorageSettings.filter.ResolveReferences();
                t.building.defaultStorageSettings.filter.ResolveReferences();
            }

            //d. Removing temporary defs from database.
            foreach (ThingDef def in garbage)
            {
                AccessTools.Method(typeof(DefDatabase <ThingDef>), "Remove").Invoke(this, new object[] { def });
            }
        }
        static HarmonyPatchesFS()
        {
            HarmonyInstance harmony = HarmonyInstance.Create("rimworld.facialstuff.mod");

            harmony.PatchAll(Assembly.GetExecutingAssembly());


            // if (ModsConfig.ActiveModsInLoadOrder.Any(x => x.Name.Contains("Giddy")))
            // {
            //     harmony.Patch(
            //                   AccessTools.Method(typeof(Pawn), "DrawAt"),
            //                   new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(DrawAtGiddy)),
            //                   null);
            // }

            // harmony.Patch(AccessTools.Method(typeof(PawnRenderer), "RenderPawnInternal", new Type[] { typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(Rot4), typeof(Rot4), typeof(RotDrawMode), typeof(bool), typeof(bool) }), null, null, new HarmonyMethod(typeof(Alien), nameof(Alien.RenderPawnInternalTranspiler)));

            // harmony.Patch(
            // AccessTools.Method(typeof(Dialog_Options), nameof(Dialog_Options.DoWindowContents)),
            // null,
            // null,
            // new HarmonyMethod(
            // typeof(Dialog_Options_DoWindowContents_Patch),
            // nameof(Dialog_Options_DoWindowContents_Patch.Transpiler)));

            harmony.Patch(
                AccessTools.Method(typeof(Page_ConfigureStartingPawns), "DrawPortraitArea"),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(AddFaceEditButton)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnGraphicSet), nameof(PawnGraphicSet.ResolveAllGraphics)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(ResolveAllGraphics_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnGraphicSet), nameof(PawnGraphicSet.ResolveApparelGraphics)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(ResolveApparelGraphics_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnRenderer), nameof(PawnRenderer.DrawEquipmentAiming)),
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(DrawEquipmentAiming_Prefix)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS),
                                  nameof(DrawEquipmentAiming_Transpiler)));

            // harmony.Patch(
            // AccessTools.Method(
            // typeof(PawnRenderer),
            // "RenderPawnInternal",
            // new[]
            // {
            // typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(Rot4), typeof(Rot4),
            // typeof(RotDrawMode), typeof(bool), typeof(bool)
            // }),
            // new HarmonyMethod(
            // typeof(HarmonyPatch_PawnRenderer),
            // nameof(HarmonyPatch_PawnRenderer.RenderPawnInternal_Prefix)),
            // null);
            // harmony.Patch(
            // AccessTools.Method(
            // typeof(Pawn_HealthTracker),
            // nameof(Pawn_HealthTracker.AddHediff),
            // new[] { typeof(Hediff), typeof(BodyPartRecord), typeof(DamageInfo) }),
            // null,
            // new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(AddHediff_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnRenderer), nameof(PawnRenderer.RenderPawnAt),
                                   new[] { typeof(Vector3), typeof(RotDrawMode), typeof(bool) }),

                // new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(HarmonyPatchesFS.RenderPawnAt)),
                null,
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(RenderPawnAt_Transpiler))
                );

            //    harmony.Patch(
            //                  AccessTools.Method(typeof(Pawn_PathFollower), nameof(Pawn_PathFollower.StartPath)),
            //                  null,
            //                  new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(StartPath_Postfix)));
            //
            //    harmony.Patch(
            //                  AccessTools.Method(typeof(Pawn_PathFollower), "PatherArrived"),
            //                  null,
            //                  new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(PatherArrived_Postfix)));

            //  harmony.Patch(
            //    AccessTools.Method(typeof(PortraitsCache), "get_IsAnimated"),
            //    new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(IsAnimated_Prefix)),
            //    null);


            harmony.Patch(
                AccessTools.Method(typeof(HediffSet), nameof(HediffSet.DirtyCache)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(DirtyCache_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(GraphicDatabaseHeadRecords),
                                   nameof(GraphicDatabaseHeadRecords.Reset)),
                null,
                new HarmonyMethod(
                    typeof(GraphicDatabaseHeadRecordsModded),
                    nameof(GraphicDatabaseHeadRecordsModded.Reset)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnHairChooser), nameof(PawnHairChooser.RandomHairDefFor)),
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(RandomHairDefFor_PreFix)),
                null);

            // if (!skinPatched)
            // {
            // AccessTools.Field(typeof(PawnSkinColors), "SkinColors").SetValue(
            // typeof(PawnSkinColors_FS.SkinColorData),
            // PawnSkinColors_FS.SkinColors);
            // skinPatched = true;
            // }
            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), "GetSkinDataIndexOfMelanin"),
                new HarmonyMethod(
                    typeof(PawnSkinColors_FS),
                    nameof(PawnSkinColors_FS.GetSkinDataIndexOfMelanin_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), nameof(PawnSkinColors.GetSkinColor)),
                new HarmonyMethod(typeof(PawnSkinColors_FS), nameof(PawnSkinColors_FS.GetSkinColor_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), nameof(PawnSkinColors.RandomMelanin)),
                new HarmonyMethod(typeof(PawnSkinColors_FS), nameof(PawnSkinColors_FS.RandomMelanin_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors),
                                   nameof(PawnSkinColors.GetMelaninCommonalityFactor)),
                new HarmonyMethod(
                    typeof(PawnSkinColors_FS),
                    nameof(PawnSkinColors_FS.GetMelaninCommonalityFactor_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(Pawn_InteractionsTracker),
                                   nameof(Pawn_InteractionsTracker.TryInteractWith)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(TryInteractWith_Postfix)));

            Log.Message(
                "Facial Stuff successfully completed " + harmony.GetPatchedMethods().Count()
                + " patches with harmony.");

            foreach (ThingDef def in DefDatabase <ThingDef> .AllDefsListForReading.Where(
                         td => td.category ==
                         ThingCategory.Pawn &&
                         td.race.Humanlike))
            {
                if (def.inspectorTabs == null || def.inspectorTabs.Count == 0)
                {
                    def.inspectorTabs         = new List <Type>();
                    def.inspectorTabsResolved = new List <InspectTabBase>();
                }

                if (def.inspectorTabs.Contains(typeof(ITab_Pawn_Weapons)))
                {
                    return;
                }

                def.inspectorTabs.Add(typeof(ITab_Pawn_Weapons));
                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Weapons)));

                def.inspectorTabs.Add(typeof(ITab_Pawn_Face));
                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Face)));
            }

            CheckAllInjected();
        }
Esempio n. 29
0
        public override void DefsLoaded()
        {
            if (ModIsActive)
            {
                /* Mod settings */

                toggleEmpathy       = Settings.GetHandle <bool>("EnableEmpathy", "EmpathyChangesTitle".Translate(), "EmpathyChangesTooltip".Translate(), true);
                toggleKinsey        = Settings.GetHandle <bool>("EnableSexuality", "SexualityChangesTitle".Translate(), "SexualityChangesTooltip".Translate(), true);
                kinseyMode          = Settings.GetHandle <KinseyMode>("KinseyMode", "KinseyModeTitle".Translate(), "KinseyModeTooltip".Translate(), KinseyMode.Realistic, null, "KinseyMode_");
                toggleIndividuality = Settings.GetHandle <bool>("EnableIndividuality", "IndividualityTitle".Translate(), "IndividualityTooltip".Translate(), true);
                toggleElections     = Settings.GetHandle <bool>("EnableElections", "ElectionsTitle".Translate(), "ElectionsTooltip".Translate(), true);

                notBabyMode = toggleIndividuality.Value;
                elections   = toggleElections.Value;

                if (PsychologyBase.ActivateKinsey())
                {
                    mode = kinseyMode.Value;
                }

                /* Mod conflict detection */

                TraitDef bisexual = DefDatabase <TraitDef> .GetNamedSilentFail("Bisexual");

                TraitDef asexual = DefDatabase <TraitDef> .GetNamedSilentFail("Asexual");

                if (bisexual != null || asexual != null || !toggleKinsey)
                {
                    if (toggleKinsey)
                    {
                        Logger.Message("KinseyDisable".Translate());
                    }
                    kinsey = false;
                }

                /* Conditional vanilla Def edits */

                ThoughtDef knowGuestExecuted = AddNullifyingTraits("KnowGuestExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestExecuted != null && toggleEmpathy)
                {
                    knowGuestExecuted = ModifyThoughtStages(knowGuestExecuted, new int[] { -1, -2, -4, -5 });
                }
                ThoughtDef knowColonistExecuted = AddNullifyingTraits("KnowColonistExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistExecuted != null && toggleEmpathy)
                {
                    knowColonistExecuted = ModifyThoughtStages(knowColonistExecuted, new int[] { -1, -2, -4, -5 });
                }
                ThoughtDef knowPrisonerDiedInnocent = AddNullifyingTraits("KnowPrisonerDiedInnocent", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerDiedInnocent != null && toggleEmpathy)
                {
                    knowPrisonerDiedInnocent = ModifyThoughtStages(knowPrisonerDiedInnocent, new int[] { -4 });
                }
                ThoughtDef knowColonistDied = AddNullifyingTraits("KnowColonistDied", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistDied != null && toggleEmpathy)
                {
                    knowColonistDied = ModifyThoughtStages(knowColonistDied, new int[] { -2 });
                }
                ThoughtDef colonistAbandoned = AddNullifyingTraits("ColonistAbandoned", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandoned != null && toggleEmpathy)
                {
                    colonistAbandoned = ModifyThoughtStages(colonistAbandoned, new int[] { -2 });
                }
                ThoughtDef colonistAbandonedToDie = AddNullifyingTraits("ColonistAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandonedToDie != null && toggleEmpathy)
                {
                    colonistAbandonedToDie = ModifyThoughtStages(colonistAbandonedToDie, new int[] { -4 });
                }
                ThoughtDef prisonerAbandonedToDie = AddNullifyingTraits("PrisonerAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (prisonerAbandonedToDie != null && toggleEmpathy)
                {
                    prisonerAbandonedToDie = ModifyThoughtStages(prisonerAbandonedToDie, new int[] { -3 });
                }
                ThoughtDef knowPrisonerSold = AddNullifyingTraits("KnowPrisonerSold", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerSold != null && toggleEmpathy)
                {
                    knowPrisonerSold = ModifyThoughtStages(knowPrisonerSold, new int[] { -4 });
                }
                ThoughtDef knowGuestOrganHarvested = AddNullifyingTraits("KnowGuestOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestOrganHarvested != null && toggleEmpathy)
                {
                    knowGuestOrganHarvested = ModifyThoughtStages(knowGuestOrganHarvested, new int[] { -4 });
                }
                ThoughtDef knowColonistOrganHarvested = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistOrganHarvested != null && toggleEmpathy)
                {
                    knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 });
                }
                ThoughtDef beauty = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistOrganHarvested != null && toggleEmpathy)
                {
                    knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 });
                }


                IEnumerable <ThingDef> things = (from m in LoadedModManager.RunningMods
                                                 from def in m.AllDefs.OfType <ThingDef>()
                                                 where typeof(Pawn).IsAssignableFrom(def.thingClass)
                                                 select def);
                foreach (ThingDef t in things)
                {
                    if (t.race.intelligence == Intelligence.Humanlike && (DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie") == null || t.race.thinkTreeMain != DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie")))
                    {
                        t.thingClass = typeof(PsychologyPawn);
                        t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Psyche)));
                        t.recipes.Add(RecipeDefOfPsychology.TreatPyromania);
                        t.recipes.Add(RecipeDefOfPsychology.TreatChemicalInterest);
                        t.recipes.Add(RecipeDefOfPsychology.TreatChemicalFascination);
                        t.recipes.Add(RecipeDefOfPsychology.TreatDepression);
                        if (!t.race?.hediffGiverSets?.NullOrEmpty() ?? false)
                        {
                            if (t.race.hediffGiverSets.Contains(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicStandard")))
                            {
                                t.race.hediffGiverSets.Add(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicPsychology"));
                            }
                        }
                    }
                }

                /*
                 * Now to enjoy the benefits of having made a popular mod!
                 * This will be our little secret.
                 */
                Backstory childMe = new Backstory();
                childMe.bodyTypeMale   = BodyType.Male;
                childMe.bodyTypeFemale = BodyType.Female;
                childMe.slot           = BackstorySlot.Childhood;
                childMe.SetTitle("Child soldier");
                childMe.SetTitleShort("Scout");
                childMe.baseDesc = "NAME was born into a dictatorial outlander society on a nearby rimworld. Their chief export was war, and HE was conscripted at a young age into the military to serve as a scout due to HIS runner's build. HECAP learned how to use a gun, patch wounds on the battlefield, and communicate with HIS squad. It was there HE earned HIS nickname.";
                childMe.skillGains.Add("Shooting", 4);
                childMe.skillGains.Add("Medicine", 2);
                childMe.skillGains.Add("Social", 1);
                childMe.requiredWorkTags = WorkTags.Violent;
                childMe.shuffleable      = false;
                childMe.PostLoad();
                childMe.ResolveReferences();
                //Disabled until I can be bothered to code it so they're actually siblings.

                /*Backstory adultMale = new Backstory();
                 * adultMale.bodyTypeMale = BodyType.Male;
                 * adultMale.bodyTypeFemale = BodyType.Female;
                 * adultMale.slot = BackstorySlot.Adulthood;
                 * adultMale.SetTitle("Missing in action");
                 * adultMale.SetTitleShort("P.O.W.");
                 * adultMale.baseDesc = "Eventually, HE was captured on a mission by one of his faction's many enemies. HECAP was tortured for information, the techniques of which HE never forgot. When they could get no more out of HIM, HE was sent to a prison camp, where HE worked for years before staging an escape and fleeing into civilization.";
                 * adultMale.skillGains.Add("Crafting", 4);
                 * adultMale.skillGains.Add("Construction", 3);
                 * adultMale.skillGains.Add("Mining", 2);
                 * adultMale.skillGains.Add("Social", 1);
                 * adultMale.spawnCategories = new List<string>();
                 * adultMale.spawnCategories.AddRange(new string[] { "Civil", "Raider", "Slave", "Trader", "Traveler" });
                 * adultMale.shuffleable = false;
                 * adultMale.PostLoad();
                 * adultMale.ResolveReferences();*/
                Backstory adultFemale = new Backstory();
                adultFemale.bodyTypeMale   = BodyType.Male;
                adultFemale.bodyTypeFemale = BodyType.Female;
                adultFemale.slot           = BackstorySlot.Adulthood;
                adultFemale.SetTitle("Battlefield medic");
                adultFemale.SetTitleShort("Medic");
                adultFemale.baseDesc = "HECAP continued to serve in the military, being promoted through the ranks as HIS skill increased. HECAP learned how to treat more serious wounds as HIS role slowly transitioned from scout to medic, as well as how to make good use of army rations. HECAP built good rapport with HIS squad as a result.";
                adultFemale.skillGains.Add("Shooting", 4);
                adultFemale.skillGains.Add("Medicine", 3);
                adultFemale.skillGains.Add("Cooking", 2);
                adultFemale.skillGains.Add("Social", 1);
                adultFemale.spawnCategories = new List <string>();
                adultFemale.spawnCategories.AddRange(new string[] { "Civil", "Raider", "Slave", "Trader", "Traveler" });
                adultFemale.shuffleable = false;
                adultFemale.PostLoad();
                adultFemale.ResolveReferences();

                /*PawnBio maleMe = new PawnBio();
                 * maleMe.childhood = childMe;
                 * maleMe.adulthood = adultMale;
                 * maleMe.gender = GenderPossibility.Male;
                 * maleMe.name = NameTriple.FromString("Nathan 'Jackal' Tarai");
                 * maleMe.PostLoad();
                 * SolidBioDatabase.allBios.Add(maleMe);*/
                PawnBio femaleMe = new PawnBio();
                femaleMe.childhood = childMe;
                femaleMe.adulthood = adultFemale;
                femaleMe.gender    = GenderPossibility.Female;
                femaleMe.name      = NameTriple.FromString("Elizabeth 'Eagle' Tarai");
                femaleMe.PostLoad();
                SolidBioDatabase.allBios.Add(femaleMe);
                BackstoryDatabase.AddBackstory(childMe);
                //BackstoryDatabase.AddBackstory(adultMale);
                BackstoryDatabase.AddBackstory(adultFemale);
            }
        }
        public override void DefsLoaded()
        {
            //1. Adding Tech Tab to Pawns
            //ThingDef injection stolen from the work of notfood for Psychology
            var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie");

            IEnumerable <ThingDef> things = (from def in DefDatabase <ThingDef> .AllDefs
                                             where def.race?.intelligence == Intelligence.Humanlike && !def.defName.Contains("Android") && !def.defName.Contains("Robot") && (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree)
                                             select def);
            List <string> registered = new List <string>();

            foreach (ThingDef t in things)
            {
                if (t.inspectorTabsResolved == null)
                {
                    t.inspectorTabsResolved = new List <InspectTabBase>(1);
                }
                t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_PawnKnowledge)));
                if (t.comps == null)
                {
                    t.comps = new List <CompProperties>(1);
                }
                t.comps.Add(new CompProperties_Knowledge());
                registered.Add(t.defName);
            }

            //2. Preparing knowledge support infrastructure

            //a. Things everyone knows
            UniversalWeapons.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWeapon));
            UniversalCrops.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.plant != null && x.plant.Sowable));

            //b. Minus things unlocked on research
            ThingFilter lateFilter = new ThingFilter();

            foreach (ResearchProjectDef tech in DefDatabase <ResearchProjectDef> .AllDefs)
            {
                tech.InferSkillBias();
                tech.CreateStuff(lateFilter, unlocked);
                foreach (ThingDef weapon in tech.UnlockedWeapons())
                {
                    UniversalWeapons.Remove(weapon);
                }
                foreach (ThingDef plant in tech.UnlockedPlants())
                {
                    UniversalCrops.Remove(plant);
                }
            }
            ;

            //b. Also removing atipical weapons
            ThingDef WeaponsNotBasicDef = DefDatabase <ThingDef> .GetNamed("NotBasic");

            List <string> ForbiddenWeaponTags = WeaponsNotBasicDef.weaponTags;

            UniversalWeapons.RemoveAll(x => SplitSimpleWeapons(x, ForbiddenWeaponTags));
            AccessTools.Method(typeof(DefDatabase <ThingDef>), "Remove").Invoke(this, new object[] { WeaponsNotBasicDef });

            //c. Telling humans what's going on
            ThingCategoryDef knowledgeCat = DefDatabase <ThingCategoryDef> .GetNamed("Knowledge");

            IEnumerable <ThingDef> codifiedTech = DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWithinCategory(knowledgeCat));

            if (Prefs.LogVerbose)
            {
                Log.Message("[HumanResources] Codified technologies:" + codifiedTech.Select(x => x.label).ToStringSafeEnumerable());
                Log.Message("[HumanResources] Basic crops: " + UniversalCrops.ToStringSafeEnumerable());
                Log.Message("[HumanResources] Basic weapons: " + UniversalWeapons.ToStringSafeEnumerable());
                Log.Message("[HumanResources] Basic weapons that require training: " + SimpleWeapons.ToStringSafeEnumerable());
                Log.Warning("[HumanResources] Basic weapons tags: " + SimpleWeapons.SelectMany(x => x.weaponTags).Distinct().ToStringSafeEnumerable());
            }
            else
            {
                Log.Message("[HumanResources] This is what we know: " + codifiedTech.EnumerableCount() + " technologies processed, " + UniversalCrops.Count() + " basic crops, " + UniversalWeapons.Count() + " basic weapons + " + SimpleWeapons.Count() + " that require training.");
            }

            //3. Filling gaps on the database

            //a. TechBook dirty trick, but only now this is possible!
            foreach (ThingDef t in DefDatabase <ThingDef> .AllDefsListForReading.Where(x => x.defName.EndsWith("TechBook") && x.modContentPack.Name.Contains("JPT")))
            {
                t.stuffCategories.Add(DefDatabase <StuffCategoryDef> .GetNamed("Technic"));
            }

            //b. Filling main tech category with subcategories
            foreach (ThingDef t in lateFilter.AllowedThingDefs.Where(t => !t.thingCategories.NullOrEmpty()))
            {
                foreach (ThingCategoryDef c in t.thingCategories)
                {
                    c.childThingDefs.Add(t);
                    if (!knowledgeCat.childCategories.NullOrEmpty() && !knowledgeCat.childCategories.Contains(c))
                    {
                        knowledgeCat.childCategories.Add(c);
                    }
                }
            }

            //c. Populating knowledge recipes and book shelves
            foreach (RecipeDef r in DefDatabase <RecipeDef> .AllDefs.Where(x => x.fixedIngredientFilter.AnyAllowedDef == null))
            {
                r.fixedIngredientFilter.ResolveReferences();
            }
            foreach (ThingDef t in DefDatabase <ThingDef> .AllDefs.Where(x => x.thingClass == typeof(Building_BookStore)))
            {
                t.building.fixedStorageSettings.filter.ResolveReferences();
                t.building.defaultStorageSettings.filter.ResolveReferences();
            }

            //4. Finally, preparing settings
            TechPoolMode                  = Settings.GetHandle("TechPoolMode", "TechPoolModeTitle".Translate(), "TechPoolModeDesc".Translate(), FactionTechPool.Both, null, "TechPoolMode_");
            TechPoolIncludesScenario      = Settings.GetHandle <bool>("TechPoolIncludesScenario", "TechPoolIncludesScenarioTitle".Translate(), "TechPoolIncludesScenarioDesc".Translate(), true);
            WeaponPoolMode                = Settings.GetHandle("WeaponPoolMode", "WeaponPoolModeTitle".Translate(), "WeaponPoolModeDesc".Translate(), FactionWeaponPool.Scenario, null, "WeaponPoolMode_");
            ResearchSpeedTiedToDifficulty = Settings.GetHandle <bool>("ResearchSpeedTiedToDifficulty", "ResearchSpeedTiedToDifficultyTitle".Translate(), "ResearchSpeedTiedToDifficultyDesc".Translate(), true);
            StudySpeedTiedToDifficulty    = Settings.GetHandle <bool>("StudySpeedTiedToDifficulty", "StudySpeedTiedToDifficultyTitle".Translate(), "StudySpeedTiedToDifficultyDesc".Translate(), true);
        }