예제 #1
0
 public override void SpawnSetup(Map map, bool respawningAfterLoad)
 {
     base.SpawnSetup(map, respawningAfterLoad);
     if (this.RaceProps.Humanlike)
     {
         /* Fixes any improperly-configured psychologies. */
         if (this.psyche == null || this.psyche.PersonalityNodes == null)
         {
             this.psyche = new Pawn_PsycheTracker(this);
             this.psyche.Initialize();
         }
         foreach (PersonalityNode node in this.psyche.PersonalityNodes)
         {
             if (node.rawRating < 0)
             {
                 node.Initialize();
             }
         }
         /* Same for sexuality. */
         if (this.sexuality == null && PsychologyBase.ActivateKinsey())
         {
             this.sexuality = new Pawn_SexualityTracker(this);
             this.sexuality.GenerateSexuality();
         }
     }
 }
예제 #2
0
        public override void Tick()
        {
            base.Tick();
            SettlementBase colony = Find.WorldObjects.ObjectsAt(worldTileElectedOn).OfType <SettlementBase>().FirstOrDefault();

            if (this.pawn.Dead || !PsychologyBase.ActivateElections() || colony == null || colony.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null)
            {
                this.pawn.health.RemoveHediff(this);
            }
        }
예제 #3
0
 public float AdjustGender(float rating)
 {
     if (this.def.femaleModifier > 0f && this.pawn.gender == Gender.Female && PsychologyBase.ActivateKinsey())
     {
         rating = (Rand.ValueSeeded(pawn.HashOffset()) < 0.8f ? rating * Mathf.Lerp(this.def.femaleModifier, 1f, (this.pawn.GetComp <CompPsychology>().Sexuality.kinseyRating / 6)) : rating);
     }
     else if (this.def.femaleModifier > 0f && this.pawn.gender == Gender.Female)
     {
         rating = (this.pawn.story.traits.HasTrait(TraitDefOf.Gay) ? rating : rating * this.def.femaleModifier);
     }
     return(rating);
 }
예제 #4
0
        private static void DrawSexuality(Rect rect, Pawn pawn, bool notOnMenu)
        {
            float width = rect.width - 26f - 3f;

            GUI.color = Color.white;
            if (PsychologyBase.ActivateKinsey())
            {
                Text.Font = GameFont.Medium;
                Rect rect2 = rect;
                rect2.yMax = rect2.y + 30f;
                Widgets.Label(rect2, "Sexuality".Translate());
                Text.Font = GameFont.Small;
                Rect rect3 = rect;
                rect3.y = rect2.yMax + RowTopPadding;
                string text = "KinseyRating".Translate() + "    " + PsycheHelper.Comp(pawn).Sexuality.kinseyRating;
                float  num4 = Mathf.Max(50f, Text.CalcHeight(text, width));
                rect3.yMax = rect3.y + num4;
                Widgets.Label(rect3, text);
                bool asexual = false;
                Rect rect4   = rect;
                if (PsycheHelper.Comp(pawn).Sexuality.sexDrive < 0.1f)
                {
                    rect4.y = rect3.yMax;
                    string text2 = "Asexual".Translate();
                    float  num5  = Mathf.Max(26f, Text.CalcHeight(text2, width));
                    rect4.yMax = rect4.y + num5;
                    Widgets.Label(rect4, text2);
                    TooltipHandler.TipRegion(rect4, () => "AsexualDescription".Translate(), 613261 + (int)(100 * PsycheHelper.Comp(pawn).Sexuality.sexDrive));
                    asexual = true;
                }
                if (PsycheHelper.Comp(pawn).Sexuality.romanticDrive < 0.1f)
                {
                    Rect rect5 = rect;
                    rect5.y = (asexual ? rect4.yMax : rect3.yMax);
                    string text2 = "Aromantic".Translate();
                    float  num5  = Mathf.Max(26f, Text.CalcHeight(text2, width));
                    rect5.yMax = rect5.y + num5;
                    Widgets.Label(rect5, text2);
                    TooltipHandler.TipRegion(rect5, () => "AromanticDescription".Translate(), 613261 + (int)(100 * PsycheHelper.Comp(pawn).Sexuality.romanticDrive));
                }
            }
            else if (notOnMenu)
            {
                GUI.color = Color.red;
                string text = "SexualityDisabledWarning".Translate();
                Widgets.Label(rect, text);
                GUI.color = Color.white;
            }
        }
예제 #5
0
 public Dialog_EditPsyche(PsychologyPawn editFor)
 {
     pawn = editFor;
     if (PsychologyBase.ActivateKinsey())
     {
         pawnKinseyRating  = pawn.sexuality.kinseyRating;
         pawnSexDrive      = pawn.sexuality.sexDrive;
         pawnRomanticDrive = pawn.sexuality.romanticDrive;
     }
     foreach (PersonalityNode node in this.pawn.psyche.PersonalityNodes)
     {
         cachedList.Add(new Pair <string, float>(node.def.label.CapitalizeFirst(), node.rawRating));
         descriptions.Add(node.def.label.CapitalizeFirst(), node.def.description);
     }
     cachedList.SortBy(n => n.First);
 }
예제 #6
0
 /*
  * Average roll: 0.989779
  * Percent chance of rolling each number:
  * 0: 62.4949 %
  * 1: 11.3289 %
  * 2: 9.2658 %
  * 3: 6.8466 %
  * 4: 4.522 %
  * 5: 2.7612 %
  * 6: 2.7806 %
  * Percent chance of being predominantly straight: 83.08959999999999 %
  * Percent chance of being predominantly gay: 10.0638 %
  * Percent chance of being more or less straight: 73.82379999999999 %
  * Percent chance of being more or less bisexual: 20.6344 %
  * Percent chance of being more or less gay: 5.5418 %
  * Sample size: 100,000
  */
 public int RandKinsey()
 {
     if (PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Realistic)
     {
         return(Mathf.Clamp((int)Rand.GaussianAsymmetric(0f, 1f, 3.13f), 0, 6));
     }
     else if (PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Invisible)
     {
         return(Mathf.Clamp((int)Rand.GaussianAsymmetric(3.5f, 1.7f, 1.7f), 0, 6));
     }
     else if (PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Gaypocalypse)
     {
         return(Mathf.Clamp((int)Rand.GaussianAsymmetric(7f, 3.13f, 1f), 0, 6));
     }
     throw new NotImplementedException();
 }
예제 #7
0
        public override bool TryExecute(IncidentParms parms)
        {
            Map         map  = (Map)parms.target;
            List <Pawn> list = (from p in map.mapPawns.AllPawnsSpawned
                                where p.RaceProps.Humanlike && p.Faction.IsPlayer
                                select p).ToList();

            if (list.Count < 3 || !PsychologyBase.SabotageOn())
            {
                return(false);
            }
            Pawn   pawn   = list.RandomElement();
            Hediff hediff = HediffMaker.MakeHediff(HediffDefOfPsychology.Saboteur, pawn, null);

            pawn.health.AddHediff(hediff, null, null);
            return(true);
        }
예제 #8
0
 public override void MapLoaded(Map map)
 {
     if (ModIsActive && PsychologyBase.ActivateKinsey())
     {
         /* Remove Gay trait from pawns if Kinsey scale is enabled */
         IEnumerable <Pawn> gayPawns = (from p in map.mapPawns.AllPawns
                                        where p.story != null && p.story.traits.HasTrait(TraitDefOf.Gay)
                                        select p);
         foreach (Pawn pawn in gayPawns)
         {
             RemoveTrait(pawn, TraitDefOf.Gay);
             if (PsycheHelper.PsychologyEnabled(pawn) && PsycheHelper.Comp(pawn).Sexuality.kinseyRating < 5)
             {
                 PsycheHelper.Comp(pawn).Sexuality.kinseyRating = Rand.RangeInclusive(5, 6);
             }
         }
     }
 }
예제 #9
0
 public override void MapLoaded(Map map)
 {
     if (ModIsActive && PsychologyBase.ActivateKinsey())
     {
         List <Pawn> gayPawns = (from p in map.mapPawns.AllPawns
                                 where p.RaceProps.Humanlike && p.story.traits.HasTrait(TraitDefOf.Gay)
                                 select p).ToList();
         foreach (Pawn pawn in gayPawns)
         {
             PsychologyBase.RemoveTrait(pawn, TraitDefOf.Gay);
             PsychologyPawn realPawn = pawn as PsychologyPawn;
             if (realPawn != null && realPawn.sexuality.kinseyRating < 5)
             {
                 realPawn.sexuality.kinseyRating = Rand.RangeInclusive(5, 6);
             }
         }
     }
 }
        public override void Interacted(Pawn initiator, Pawn recipient, List <RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef)
        {
            letterText  = null;
            letterLabel = null;
            letterDef   = null;
            //Choose a time that works with their schedule, based on their personality
            Dictionary <int, float> possibleHours = new Dictionary <int, float>();

            for (int i = 0; i < GenDate.HoursPerDay; i++)
            {
                possibleHours.Add(i, 0f);
            }
            foreach (PersonalityNodeDef d in DefDatabase <PersonalityNodeDef> .AllDefsListForReading)
            {
                if (d.preferredDateHours != null)
                {
                    foreach (int h in d.preferredDateHours)
                    {
                        possibleHours[h] += (Mathf.Pow(Mathf.Abs(0.5f - PsycheHelper.Comp(initiator).Psyche.GetPersonalityRating(d)), 2) / (1.3f - PsycheHelper.Comp(initiator).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) + Mathf.Pow(Mathf.Abs(0.5f - PsycheHelper.Comp(recipient).Psyche.GetPersonalityRating(d)), 2) / (1.3f - PsycheHelper.Comp(recipient).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) / 2f);
                    }
                }
            }
            int hour = possibleHours.Keys.RandomElementByWeight(h => possibleHours[h] * RendezvousUtility.TimeAssignmentFactor(initiator, h) * RendezvousUtility.TimeAssignmentFactor(recipient, h));
            //More Spontaneous couples will plan their dates sooner; possibly even immediately!
            int day = Find.TickManager.TicksAbs + Mathf.RoundToInt(GenDate.TicksPerDay * 5 * (((1f - PsycheHelper.Comp(initiator).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous)) + (1f - PsycheHelper.Comp(recipient).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous))) / 2f));
            Hediff_PlannedDate plannedDate = HediffMaker.MakeHediff(HediffDefOfPsychology.PlannedDate, initiator) as Hediff_PlannedDate;

            plannedDate.partner = recipient;
            plannedDate.day     = day;
            plannedDate.hour    = hour;
            initiator.health.AddHediff(plannedDate);
            PsycheHelper.Comp(initiator).Psyche.lastDateTick = day;
            PsycheHelper.Comp(recipient).Psyche.lastDateTick = day;
            if (PsychologyBase.SendDateLetters())
            {
                int    hourDiscrepancy = GenDate.HourOfDay(day, Find.WorldGrid.LongLatOf(initiator.Map.Tile).x) - hour;
                int    accurateTime    = day + (Math.Abs(hourDiscrepancy) * GenDate.TicksPerHour);
                String dateTime        = GenDate.QuadrumDateStringAt(accurateTime, Find.WorldGrid.LongLatOf(initiator.Map.Tile).x);
                Letter dateLetter      = LetterMaker.MakeLetter("LetterLabelDatePlanned".Translate(), "LetterDatePlanned".Translate(initiator, recipient, dateTime, hour), LetterDefOf.PositiveEvent);
                Find.LetterStack.ReceiveLetter(dateLetter);
            }
        }
예제 #11
0
 public Dialog_EditPsyche(Pawn editFor)
 {
     pawn = editFor;
     if (PsychologyBase.ActivateKinsey())
     {
         pawnKinseyRating  = PsycheHelper.Comp(pawn).Sexuality.kinseyRating;
         pawnSexDrive      = PsycheHelper.Comp(pawn).Sexuality.sexDrive;
         pawnRomanticDrive = PsycheHelper.Comp(pawn).Sexuality.romanticDrive;
     }
     foreach (PersonalityNode node in PsycheHelper.Comp(pawn).Psyche.PersonalityNodes)
     {
         cachedList.Add(new Pair <string, float>(node.def.label.CapitalizeFirst(), node.rawRating));
         try
         {
             descriptions.Add(node.def.label.CapitalizeFirst(), node.def.description);
         }
         catch (ArgumentException e)
         {
             Log.Error("[Psychology] " + "DuplicateDefLabel".Translate(node.def.defName));
             descriptions.Add(node.def.defName.CapitalizeFirst(), node.def.description);
         }
     }
     cachedList.SortBy(n => n.First);
 }
예제 #12
0
 static PerformanceSetup()
 {
     if (PsychologyBase.EnablePerformanceTesting())
     {
         Log.Warning("Psychology :: Performance reporting is ON. Benchmarking itself has a performance impact. Unless you are opting into performance testing, disable it in the mod options.");
         HarmonyInstance harmony = HarmonyInstance.Create("rimworld.psychology.benchmarking");
         foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
         {
             if (t.AssemblyQualifiedName.Contains("Optional"))
             {
                 continue;
             }
             foreach (MethodInfo m in t.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
             {
                 if (DoLogPerformance(m))
                 {
                     harmony.Patch(AccessTools.Method(t, m.Name),
                                   new HarmonyMethod(AccessTools.Method(typeof(PerformancePatches), nameof(PerformancePatches.StopwatchStart))),
                                   new HarmonyMethod(AccessTools.Method(typeof(PerformancePatches), nameof(PerformancePatches.StopwatchEnd))));
                 }
             }
         }
     }
 }
예제 #13
0
 protected override ThoughtState CurrentStateInternal(Pawn p)
 {
     if (!p.Spawned)
     {
         return(ThoughtState.Inactive);
     }
     if (!p.RaceProps.Humanlike)
     {
         return(ThoughtState.Inactive);
     }
     if (p.Map == null)
     {
         return(ThoughtState.Inactive);
     }
     if (!p.Faction.IsPlayer)
     {
         return(ThoughtState.Inactive);
     }
     if (p.apparel.PsychologicallyNude)
     {
         return(ThoughtState.Inactive);
     }
     if (GenDate.MonthsPassed < 2)
     {
         return(ThoughtState.Inactive);
     }
     if (!PsychologyBase.IndividualityOn())
     {
         return(ThoughtState.Inactive);
     }
     if (!lastTick.ContainsKey(p) || Find.TickManager.TicksGame - 250 > lastTick[p][0])
     {
         Func <Apparel, bool> identical = delegate(Apparel x)
         {
             foreach (Apparel a in p.apparel.WornApparel)
             {
                 if (a.def == x.def && a.Stuff == x.Stuff && a.DrawColor == x.DrawColor)
                 {
                     return(true);
                 }
             }
             return(false);
         };
         List <Pawn> colonists = (from c in p.Map.mapPawns.AllPawnsSpawned
                                  where c.RaceProps.Humanlike && c.Faction.IsPlayer && c != p
                                  select c).ToList <Pawn>();
         List <Pawn> sameClothes = (from c in colonists
                                    where (from a in c.apparel.WornApparel
                                           where identical(a)
                                           select a).ToList <Apparel>().Count == p.apparel.WornApparelCount
                                    select c).ToList <Pawn>();
         if (sameClothes.Count == colonists.Count && colonists.Count > 3)
         {
             lastTick[p] = new int[] { Find.TickManager.TicksGame, 3 };
         }
         else if (sameClothes.Count >= (colonists.Count / 2) && colonists.Count > 3)
         {
             lastTick[p] = new int[] { Find.TickManager.TicksGame, 2 };
         }
         else if (sameClothes.Count > 1)
         {
             lastTick[p] = new int[] { Find.TickManager.TicksGame, 1 };
         }
         else if (sameClothes.Count > 0)
         {
             lastTick[p] = new int[] { Find.TickManager.TicksGame, 0 };
         }
         else
         {
             lastTick[p] = new int[] { Find.TickManager.TicksGame, -1 };
         }
     }
     if (lastTick[p][1] >= 0)
     {
         return(ThoughtState.ActiveAtStage(lastTick[p][1]));
     }
     return(ThoughtState.Inactive);
 }
        protected override ThoughtState CurrentStateInternal(Pawn p)
        {
            if (!p.Spawned)
            {
                return(ThoughtState.Inactive);
            }
            if (p.Map == null)
            {
                return(ThoughtState.Inactive);
            }
            if (!p.IsColonist)
            {
                return(ThoughtState.Inactive);
            }
            if (p.apparel.PsychologicallyNude)
            {
                return(ThoughtState.Inactive);
            }
            List <Thought> tmpThoughts = new List <Thought>();

            p.needs.mood.thoughts.GetAllMoodThoughts(tmpThoughts);
            if (tmpThoughts.Find(t => t.def.defName == "LowExpectations") != null)
            {
                return(ThoughtState.Inactive);
            }
            if (!PsychologyBase.IndividualityOn())
            {
                return(ThoughtState.Inactive);
            }
            if (!lastTick.ContainsKey(p) || Find.TickManager.TicksGame - 250 > lastTick[p][0])
            {
                Func <Apparel, bool> identical = delegate(Apparel x)
                {
                    foreach (Apparel a in p.apparel.WornApparel)
                    {
                        if (a.def == x.def && a.Stuff == x.Stuff && a.DrawColor == x.DrawColor)
                        {
                            return(true);
                        }
                    }
                    return(false);
                };
                IEnumerable <Pawn> colonists = (from c in p.Map.mapPawns.FreeColonistsSpawned
                                                where c != p
                                                select c);
                IEnumerable <Pawn> sameClothes = (from c in colonists
                                                  where (from a in c.apparel.WornApparel
                                                         where identical(a)
                                                         select a).Count() == p.apparel.WornApparelCount && p.apparel.WornApparelCount == c.apparel.WornApparelCount
                                                  select c);
                if (sameClothes.Count() == colonists.Count() && colonists.Count() > 5)
                {
                    lastTick[p] = new int[] { Find.TickManager.TicksGame, 3 };
                }
                else if (sameClothes.Count() >= (colonists.Count() / 2) && colonists.Count() > 5)
                {
                    lastTick[p] = new int[] { Find.TickManager.TicksGame, 2 };
                }
                else if (sameClothes.Count() > 1)
                {
                    lastTick[p] = new int[] { Find.TickManager.TicksGame, 1 };
                }
                else if (sameClothes.Count() > 0)
                {
                    lastTick[p] = new int[] { Find.TickManager.TicksGame, 0 };
                }
                else
                {
                    lastTick[p] = new int[] { Find.TickManager.TicksGame, -1 };
                }
            }
            if (lastTick[p][1] >= 0)
            {
                return(ThoughtState.ActiveAtStage(lastTick[p][1]));
            }
            return(ThoughtState.Inactive);
        }
예제 #15
0
 public override void Tick(int currentTick)
 {
     //Constituent tick
     if (currentTick % GenDate.TicksPerHour * 2 == 0)
     {
         Map playerFactionMap            = Find.WorldObjects.FactionBases.Find(b => b.Faction.IsPlayer).Map;
         IEnumerable <Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned
                                            where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake()
                                            select p);
         if (constituents.Count() > 0)
         {
             Pawn potentialConstituent       = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2));
             IEnumerable <Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile &&
                                                m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake()
                                                select m);
             if (potentialConstituent != null && activeMayors.Count() > 0)
             {
                 Pawn           mayor = activeMayors.RandomElement(); //There should only be one.
                 PsychologyPawn psychologyConstituent = potentialConstituent as PsychologyPawn;
                 IntVec3        gather   = default(IntVec3);
                 bool           foundBed = false;
                 if (mayor.ownership != null && mayor.ownership.OwnedBed != null)
                 {
                     gather   = mayor.ownership.OwnedBed.Position;
                     foundBed = true;
                 }
                 if ((psychologyConstituent == null || Rand.Value < (1f - psychologyConstituent.psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (foundBed || RCellFinder.TryFindPartySpot(mayor, out gather)))
                 {
                     List <Pawn> pawns = new List <Pawn>();
                     pawns.Add(mayor);
                     pawns.Add(potentialConstituent);
                     Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < 0.4f)), mayor.Map, pawns);
                     if (!foundBed)
                     {
                         mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom);
                     }
                 }
             }
         }
     }
     //Election tick
     if (currentTick % (GenDate.TicksPerDay / 4f) == 0)
     {
         foreach (FactionBase factionBase in Find.WorldObjects.FactionBases)
         {
             //If the base isn't owned or named by the player, no election can be held.
             if (!factionBase.Faction.IsPlayer || !factionBase.namedByPlayer)
             {
                 continue;
             }
             //Self-explanatory.
             if (!PsychologyBase.ActivateElections())
             {
                 continue;
             }
             //If the base is not at least a year old, no election will be held.
             if ((Find.TickManager.TicksGame - factionBase.creationGameTicks) / GenDate.TicksPerYear < 1)
             {
                 continue;
             }
             //A base must have at least 7 people in it to hold an election.
             if (factionBase.Map.mapPawns.FreeColonistsSpawnedCount < 7)
             {
                 continue;
             }
             //If an election is already being held, don't start a new one.
             if (factionBase.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || factionBase.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null)
             {
                 continue;
             }
             //Elections are held in the fall and during the day.
             if (GenLocalDate.Season(factionBase.Map) != Season.Fall || (GenLocalDate.HourOfDay(factionBase.Map) < 7 || GenLocalDate.HourOfDay(factionBase.Map) > 20))
             {
                 continue;
             }
             //If an election has already been completed this year, don't start a new one.
             IEnumerable <Pawn> activeMayors = (from m in factionBase.Map.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == factionBase.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(factionBase.Map.Tile)
                                                select m);
             if (activeMayors.Count() > 0)
             {
                 continue;
             }
             //Try to space out the elections so they don't all proc at once.
             if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfSeason(factionBase.Map.Tile)) > 1)
             {
                 continue;
             }
             IncidentParms parms = new IncidentParms();
             parms.target  = factionBase.Map;
             parms.faction = factionBase.Faction;
             FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms);
             Find.Storyteller.TryFire(fi);
         }
     }
 }
예제 #16
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);
            }
        }
예제 #17
0
        public override void DefsLoaded()
        {
            if (ModIsActive)
            {
                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_");
                toggleSabotage      = Settings.GetHandle <bool>("EnableSabotage", "SabotageIncidentTitle".Translate(), "SabotageIncidentTooltip".Translate(), false);
                toggleIndividuality = Settings.GetHandle <bool>("EnableIndividuality", "IndividualityTitle".Translate(), "IndividualityTooltip".Translate(), true);

                sabotabby   = toggleSabotage.Value;
                notBabyMode = toggleIndividuality.Value;

                if (!detoursMedical)
                {
                    Logger.Warning("MedicalDetourDisable".Translate());
                }

                //Vanilla Defs will be edited at load to improve compatibility with other mods.
                AddConflictingTraits("Nudist", new TraitDef[] { TraitDefOfPsychology.Prude });
                AddConflictingTraits("Bloodlust", new TraitDef[] { TraitDefOfPsychology.BleedingHeart, TraitDefOfPsychology.Desensitized });
                AddConflictingTraits("Psychopath", new TraitDef[] { TraitDefOfPsychology.BleedingHeart, TraitDefOfPsychology.Desensitized, TraitDefOfPsychology.OpenMinded });
                AddConflictingTraits("Cannibal", new TraitDef[] { TraitDefOfPsychology.BleedingHeart, TraitDefOfPsychology.Gourmet });
                AddConflictingTraits("Ascetic", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddConflictingTraits("Neurotic", new TraitDef[] { TraitDefOfPsychology.HeavySleeper });
                AddConflictingTraits("DislikesMen", new TraitDef[] { TraitDefOfPsychology.OpenMinded });
                AddConflictingTraits("DislikesWomen", new TraitDef[] { TraitDefOfPsychology.OpenMinded });
                AddConflictingTraits("Prosthophobe", new TraitDef[] { TraitDefOfPsychology.OpenMinded });

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

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

                if (bisexual != null || asexual != null || !toggleKinsey || !detoursSexual)
                {
                    if (toggleKinsey)
                    {
                        Logger.Message("KinseyDisable".Translate());
                        if (!detoursSexual)
                        {
                            Logger.Warning("KinseyDetourDisable".Translate());
                            TraitDefOfPsychology.Codependent.SetCommonality(0f);
                            TraitDefOfPsychology.Lecher.SetCommonality(0f);
                            TraitDefOfPsychology.OpenMinded.SetCommonality(0f);
                            TraitDefOfPsychology.Polygamous.SetCommonality(0f);
                        }
                    }
                    kinsey = false;
                }

                if (PsychologyBase.ActivateKinsey())
                {
                    mode = kinseyMode.Value;
                    TraitDef gay = TraitDef.Named("Gay");
                    if (gay != null)
                    {
                        gay.SetCommonality(0f);
                    }
                    foreach (ThingDef t in DefDatabase <ThingDef> .AllDefsListForReading)
                    {
                        if (t.thingClass == typeof(Pawn))
                        {
                            t.thingClass = typeof(PsychologyPawn);
                        }
                    }
                }

                AddNullifyingTraits("AteLavishMeal", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteFineMeal", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteAwfulMeal", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteRawFood", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteInsectMeatAsIngredient", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteInsectMeatDirect", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("AteRottenFood", new TraitDef[] { TraitDefOfPsychology.Gourmet });
                AddNullifyingTraits("SleepDisturbed", new TraitDef[] { TraitDefOfPsychology.HeavySleeper });
                AddNullifyingTraits("ObservedLayingCorpse", new TraitDef[] { TraitDefOfPsychology.Desensitized });
                AddNullifyingTraits("WitnessedDeathAlly", new TraitDef[] { TraitDefOfPsychology.BleedingHeart, TraitDefOfPsychology.Desensitized });
                AddNullifyingTraits("WitnessedDeathNonAlly", new TraitDef[] { TraitDefOfPsychology.BleedingHeart, TraitDefOfPsychology.Desensitized });
                AddNullifyingTraits("FeelingRandom", new TraitDef[] { TraitDefOfPsychology.Unstable });
                AddNullifyingTraits("ApparelDamaged", new TraitDef[] { TraitDefOfPsychology.Prude });
                AddNullifyingTraits("EnvironmentDark", new TraitDef[] { TraitDefOfPsychology.Photosensitive });
                AddNullifyingTraits("DeadMansApparel", new TraitDef[] { TraitDefOfPsychology.Desensitized });
                AddNullifyingTraits("Naked", new TraitDef[] { TraitDefOfPsychology.Prude });
                AddNullifyingTraits("ColonistLeftUnburied", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                AddNullifyingTraits("CheatedOnMe", new TraitDef[] { TraitDefOfPsychology.Polygamous });
                AddNullifyingTraits("Affair", new TraitDef[] { TraitDefOfPsychology.Polygamous });
                AddNullifyingTraits("Disfigured", new TraitDef[] { TraitDefOfPsychology.OpenMinded });
                AddNullifyingTraits("Pretty", new TraitDef[] { TraitDefOfPsychology.OpenMinded });
                AddNullifyingTraits("Ugly", new TraitDef[] { TraitDefOfPsychology.OpenMinded });
                AddNullifyingTraits("SleptOutside", new TraitDef[] { TraitDefOfPsychology.Outdoorsy });

                ThoughtDef knowGuestExecuted = AddNullifyingTraits("KnowGuestExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestExecuted != null && toggleEmpathy)
                {
                    if (knowGuestExecuted.stages.Count >= 1) //We can't assume that other mods won't remove stages from this thought, so we'll try to avoid OutOfBounds exceptions.
                    {
                        knowGuestExecuted.stages[0].baseMoodEffect = -1;
                    }
                    if (knowGuestExecuted.stages.Count >= 2)
                    {
                        knowGuestExecuted.stages[1].baseMoodEffect = -2;
                    }
                    if (knowGuestExecuted.stages.Count >= 3)
                    {
                        knowGuestExecuted.stages[2].baseMoodEffect = -4;
                    }
                    if (knowGuestExecuted.stages.Count >= 4)
                    {
                        knowGuestExecuted.stages[3].baseMoodEffect = -5;
                    }
                }

                ThoughtDef knowColonistExecuted = AddNullifyingTraits("KnowColonistExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistExecuted != null && toggleEmpathy)
                {
                    if (knowColonistExecuted.stages.Count >= 1)
                    {
                        knowColonistExecuted.stages[0].baseMoodEffect = -1;
                    }
                    if (knowColonistExecuted.stages.Count >= 2)
                    {
                        knowColonistExecuted.stages[1].baseMoodEffect = -2;
                    }
                    if (knowColonistExecuted.stages.Count >= 3)
                    {
                        knowColonistExecuted.stages[2].baseMoodEffect = -4;
                    }
                    if (knowColonistExecuted.stages.Count >= 4)
                    {
                        knowColonistExecuted.stages[3].baseMoodEffect = -5;
                    }
                }

                ThoughtDef knowPrisonerDiedInnocent = AddNullifyingTraits("KnowPrisonerDiedInnocent", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerDiedInnocent != null && toggleEmpathy)
                {
                    if (knowPrisonerDiedInnocent.stages.Count >= 1)
                    {
                        knowPrisonerDiedInnocent.stages[0].baseMoodEffect = -4;
                    }
                }

                ThoughtDef knowColonistDied = AddNullifyingTraits("KnowColonistDied", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistDied != null && toggleEmpathy)
                {
                    if (knowColonistDied.stages.Count >= 1)
                    {
                        knowColonistDied.stages[0].baseMoodEffect = -2;
                    }
                }

                ThoughtDef colonistAbandoned = AddNullifyingTraits("ColonistAbandoned", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandoned != null && toggleEmpathy)
                {
                    if (colonistAbandoned.stages.Count >= 1)
                    {
                        colonistAbandoned.stages[0].baseMoodEffect = -2;
                    }
                }

                ThoughtDef colonistAbandonedToDie = AddNullifyingTraits("ColonistAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandonedToDie != null && toggleEmpathy)
                {
                    if (colonistAbandonedToDie.stages.Count >= 1)
                    {
                        colonistAbandonedToDie.stages[0].baseMoodEffect = -4;
                    }
                }

                ThoughtDef prisonerAbandonedToDie = AddNullifyingTraits("PrisonerAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (prisonerAbandonedToDie != null && toggleEmpathy)
                {
                    if (prisonerAbandonedToDie.stages.Count >= 1)
                    {
                        prisonerAbandonedToDie.stages[0].baseMoodEffect = -3;
                    }
                }

                ThoughtDef knowPrisonerSold = AddNullifyingTraits("KnowPrisonerSold", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerSold != null && toggleEmpathy)
                {
                    if (knowPrisonerSold.stages.Count >= 1)
                    {
                        knowPrisonerSold.stages[0].baseMoodEffect = -4;
                    }
                }

                ThoughtDef knowGuestOrganHarvested = AddNullifyingTraits("KnowGuestOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestOrganHarvested != null && toggleEmpathy)
                {
                    if (knowGuestOrganHarvested.stages.Count >= 1)
                    {
                        knowGuestOrganHarvested.stages[0].baseMoodEffect = -4;
                    }
                }

                ThoughtDef knowColonistOrganHarvested = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistOrganHarvested != null && toggleEmpathy)
                {
                    if (knowColonistOrganHarvested.stages.Count >= 1)
                    {
                        knowColonistOrganHarvested.stages[0].baseMoodEffect = -4;
                    }
                }

                ReplaceThoughtWorker("CabinFever", typeof(ThoughtWorker_CabinFever));
                ReplaceThoughtWorker("Disfigured", typeof(ThoughtWorker_Disfigured));
                ReplaceThoughtWorker("Ugly", typeof(ThoughtWorker_Ugly));
                ReplaceThoughtWorker("AnnoyingVoice", typeof(ThoughtWorker_AnnoyingVoice));
                ReplaceThoughtWorker("CreepyBreathing", typeof(ThoughtWorker_CreepyBreathing));
                ReplaceThoughtWorker("Pretty", typeof(ThoughtWorker_Pretty));
                ReplaceIncidentWorker("RaidEnemy", typeof(IncidentWorker_RaidEnemy));

                // Credit to FluffierThanThou for the code.
                var livingRaces = DefDatabase <ThingDef>
                                  .AllDefsListForReading
                                  .Where(t => !t.race?.hediffGiverSets?.NullOrEmpty() ?? false);

                foreach (ThingDef alive in livingRaces)
                {
                    if (alive.race.hediffGiverSets.Contains(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicStandard")))
                    {
                        alive.race.hediffGiverSets.Add(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicPsychology"));
                        alive.recipes.Add(RecipeDefOfPsychology.TreatPyromania);
                    }
                }

                MentalBreakDef berserk = DefDatabase <MentalBreakDef> .GetNamed("Berserk");

                berserk.baseCommonality = 0f;
                MentalStateDef fireStartingSpree = DefDatabase <MentalStateDef> .GetNamed("FireStartingSpree");

                fireStartingSpree.workerClass = typeof(MentalStateWorker_FireStartingSpree);

                /*
                 * 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);
            }
        }
        internal static float _LovePartnerRelationGenerationChance(Pawn generated, Pawn other, PawnGenerationRequest request, bool ex)
        {
            if (generated.ageTracker.AgeBiologicalYearsFloat < 14f)
            {
                return(0f);
            }
            if (other.ageTracker.AgeBiologicalYearsFloat < 14f)
            {
                return(0f);
            }
            if (!PsychologyBase.ActivateKinsey())
            {
                if (generated.gender == other.gender && (!other.story.traits.HasTrait(TraitDefOf.Gay) || !request.AllowGay))
                {
                    return(0f);
                }
                if (generated.gender != other.gender && other.story.traits.HasTrait(TraitDefOf.Gay))
                {
                    return(0f);
                }
            }
            else if (generated.gender == other.gender && !request.AllowGay)
            {
                return(0f);
            }
            float num = 1f;

            if (ex)
            {
                int num2 = 0;
                List <DirectPawnRelation> directRelations = other.relations.DirectRelations;
                for (int i = 0; i < directRelations.Count; i++)
                {
                    if (LovePartnerRelationUtility.IsExLovePartnerRelation(directRelations[i].def))
                    {
                        num2++;
                    }
                }
                num = Mathf.Pow(0.2f, (float)num2);
            }
            else if (LovePartnerRelationUtility.HasAnyLovePartner(other))
            {
                return(0f);
            }
            float          num3          = 1f;
            PsychologyPawn realGenerated = generated as PsychologyPawn;
            PsychologyPawn realOther     = other as PsychologyPawn;

            if (PsychologyBase.ActivateKinsey() && realGenerated != null && realOther != null)
            {
                float kinsey  = 3 - realGenerated.sexuality.kinseyRating;
                float kinsey2 = 3 - realOther.sexuality.kinseyRating;
                float h**o    = (generated.gender == other.gender) ? 1f : -1f;
                num3 *= Mathf.InverseLerp(3f, 0f, kinsey * h**o);
                num3 *= Mathf.InverseLerp(3f, 0f, kinsey2 * h**o);
            }
            else
            {
                num3 = (generated.gender != other.gender) ? 1f : 0.01f;
            }
            var   GetGenerationChanceAgeFactor    = typeof(LovePartnerRelationUtility).GetMethod("GetGenerationChanceAgeFactor", BindingFlags.Static | BindingFlags.NonPublic);
            var   GetGenerationChanceAgeGapFactor = typeof(LovePartnerRelationUtility).GetMethod("GetGenerationChanceAgeGapFactor", BindingFlags.Static | BindingFlags.NonPublic);
            float generationChanceAgeFactor       = (float)GetGenerationChanceAgeFactor.Invoke(null, new object[] { generated });
            float generationChanceAgeFactor2      = (float)GetGenerationChanceAgeFactor.Invoke(null, new object[] { other });
            float generationChanceAgeGapFactor    = (float)GetGenerationChanceAgeGapFactor.Invoke(null, new object[] { generated, other, ex });
            float num4 = 1f;

            if (generated.GetRelations(other).Any((PawnRelationDef x) => x.familyByBloodRelation))
            {
                num4 = 0.01f;
            }
            float num5;

            if (request.FixedMelanin.HasValue)
            {
                num5 = ChildRelationUtility.GetMelaninSimilarityFactor(request.FixedMelanin.Value, other.story.melanin);
            }
            else
            {
                num5 = PawnSkinColors.GetMelaninCommonalityFactor(other.story.melanin);
            }
            return(num * generationChanceAgeFactor * generationChanceAgeFactor2 * generationChanceAgeGapFactor * num3 * num5 * num4);
        }
예제 #19
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);
                conversationDuration = Settings.GetHandle <float>("ConversationDuration", "DurationTitle".Translate(), "DurationTooltip".Translate(), 60f, (String s) => float.Parse(s) >= 15f && float.Parse(s) <= 180f);
                toggleDateLetters    = Settings.GetHandle <bool>("SendDateLetters", "SendDateLettersTitle".Translate(), "SendDateLettersTooltip".Translate(), true);
                toggleBenchmarking   = Settings.GetHandle <bool>("Benchmarking", "BenchmarkingTitle".Translate(), "BenchmarkingTooltip".Translate(), false);

                kinsey        = toggleKinsey.Value;
                notBabyMode   = toggleIndividuality.Value;
                elections     = toggleElections.Value;
                dateLetters   = toggleDateLetters.Value;
                benchmark     = toggleBenchmarking.Value;
                convoDuration = conversationDuration.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("ColonistBanished", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandoned != null && toggleEmpathy)
                {
                    colonistAbandoned = ModifyThoughtStages(colonistAbandoned, new int[] { -2 });
                }
                ThoughtDef colonistAbandonedToDie = AddNullifyingTraits("ColonistBanishedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandonedToDie != null && toggleEmpathy)
                {
                    colonistAbandonedToDie = ModifyThoughtStages(colonistAbandonedToDie, new int[] { -4 });
                }
                ThoughtDef prisonerAbandonedToDie = AddNullifyingTraits("PrisonerBanishedToDie", 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 });
                }

                /* ThingDef injection reworked by notfood */
                var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie");

                IEnumerable <ThingDef> things = (
                    from def in DefDatabase <ThingDef> .AllDefs
                    where typeof(Pawn).IsAssignableFrom(def.thingClass) &&
                    def.race?.intelligence == Intelligence.Humanlike &&
                    !def.defName.Contains("AIPawn") &&
                    (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_Pawn_Psyche)));

                    if (t.recipes == null)
                    {
                        t.recipes = new List <RecipeDef>(6);
                    }
                    t.recipes.Add(RecipeDefOfPsychology.TreatPyromania);
                    t.recipes.Add(RecipeDefOfPsychology.TreatChemicalInterest);
                    t.recipes.Add(RecipeDefOfPsychology.TreatChemicalFascination);
                    t.recipes.Add(RecipeDefOfPsychology.TreatDepression);
                    t.recipes.Add(RecipeDefOfPsychology.TreatInsomnia);
                    t.recipes.Add(RecipeDefOfPsychology.CureAnxiety);

                    if (t.comps == null)
                    {
                        t.comps = new List <CompProperties>(1);
                    }
                    t.comps.Add(new CompProperties_Psychology());

                    if (!t.race.hediffGiverSets.NullOrEmpty())
                    {
                        if (t.race.hediffGiverSets.Contains(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicStandard")))
                        {
                            t.race.hediffGiverSets.Add(DefDatabase <HediffGiverSetDef> .GetNamed("OrganicPsychology"));
                        }
                    }
                    registered.Add(t.defName);
                }
                if (Prefs.DevMode && Prefs.LogVerbose)
                {
                    Log.Message("Psychology :: Registered " + string.Join(", ", registered.ToArray()));
                }

                /*
                 * Now to enjoy the benefits of having made a popular mod!
                 * This will be our little secret.
                 */
                Traverse.Create(child).Field("bodyTypeMale").SetValue("Male");
                Traverse.Create(child).Field("bodyTypeFemale").SetValue("Female");
                child.slot = BackstorySlot.Childhood;
                child.SetTitle("Child soldier", "Child soldier");
                child.SetTitleShort("Scout", "Scout");
                child.baseDesc = "[PAWN_nameDef] was born into a dictatorial outlander society on a nearby rimworld. Their chief export was war, and [PAWN_pronoun] was conscripted at a young age into the military to serve as a scout due to [PAWN_possessive] runner's build. [PAWN_pronoun] learned how to use a gun, patch wounds on the battlefield, and communicate with [PAWN_possessive] squad. It was there [PAWN_pronoun] earned [PAWN_possessive] nickname.";
                Traverse.Create(child).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Shooting", 4);
                Traverse.Create(child).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Medicine", 2);
                Traverse.Create(child).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Social", 1);
                child.requiredWorkTags = WorkTags.Violent;
                child.shuffleable      = false;
                child.PostLoad();
                child.ResolveReferences();
                Backstory adultMale = new Backstory();
                Traverse.Create(adultMale).Field("bodyTypeMale").SetValue("Male");
                Traverse.Create(adultMale).Field("bodyTypeFemale").SetValue("Female");
                adultMale.slot = BackstorySlot.Adulthood;
                adultMale.SetTitle("Missing in action", "Missing in action");
                adultMale.SetTitleShort("Ex-P.O.W.", "Ex-P.O.W.");
                adultMale.baseDesc = "Eventually, [PAWN_pronoun] was captured on a mission by one of [PAWN_possessive] faction's many enemies. [PAWN_pronoun] was tortured for information, the techniques of which [PAWN_pronoun] never forgot. When they could get no more out of [PAWN_objective], [PAWN_pronoun] was sent to a prison camp, where [PAWN_pronoun] worked for years before staging an escape and fleeing into civilization.";
                Traverse.Create(adultMale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Crafting", 4);
                Traverse.Create(adultMale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Construction", 3);
                Traverse.Create(adultMale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Mining", 2);
                Traverse.Create(adultMale).Field("skillGains").GetValue <Dictionary <string, int> >().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();
                Traverse.Create(adultFemale).Field("bodyTypeMale").SetValue("Male");
                Traverse.Create(adultFemale).Field("bodyTypeFemale").SetValue("Female");
                adultFemale.slot = BackstorySlot.Adulthood;
                adultFemale.SetTitle("Battlefield medic", "Battlefield medic");
                adultFemale.SetTitleShort("Medic", "Medic");
                adultFemale.baseDesc = "[PAWN_pronoun] continued to serve in the military, being promoted through the ranks as [PAWN_possessive] skill increased. [PAWN_pronoun] learned how to treat more serious wounds as [PAWN_possessive] role slowly transitioned from scout to medic, as well as how to make good use of army rations. [PAWN_pronoun] built good rapport with [PAWN_possessive] squad as a result.";
                Traverse.Create(adultFemale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Shooting", 4);
                Traverse.Create(adultFemale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Medicine", 3);
                Traverse.Create(adultFemale).Field("skillGains").GetValue <Dictionary <string, int> >().Add("Cooking", 2);
                Traverse.Create(adultFemale).Field("skillGains").GetValue <Dictionary <string, int> >().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 male = new PawnBio();
                male.childhood = child;
                male.adulthood = adultMale;
                male.gender    = GenderPossibility.Male;
                male.name      = NameTriple.FromString("Jason 'Jackal' Tarai");
                male.PostLoad();
                SolidBioDatabase.allBios.Add(male);
                PawnBio female = new PawnBio();
                female.childhood = child;
                female.adulthood = adultFemale;
                female.gender    = GenderPossibility.Female;
                female.name      = NameTriple.FromString("Elizabeth 'Eagle' Tarai");
                female.PostLoad();
                SolidBioDatabase.allBios.Add(female);
                BackstoryDatabase.AddBackstory(child);
                BackstoryDatabase.AddBackstory(adultMale);
                BackstoryDatabase.AddBackstory(adultFemale);
            }
        }
예제 #20
0
        public override void DoWindowContents(Rect inRect)
        {
            bool flag = false;

            if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
            {
                flag = true;
                Event.current.Use();
            }
            bool flag2 = false;

            if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
            {
                flag2 = true;
                Event.current.Use();
            }
            Rect windowRect = inRect.ContractedBy(17f);
            Rect mainRect   = new Rect(windowRect.x, windowRect.y, windowRect.width, windowRect.height - 20f);
            Rect okRect     = new Rect(inRect.width / 4 - 20f, mainRect.yMax + 10f, inRect.width / 4f, 30f);
            Rect cancelRect = new Rect(okRect.xMax + 40f, mainRect.yMax + 10f, inRect.width / 4f, 30f);

            Text.Font = GameFont.Medium;
            Widgets.Label(mainRect, "PsycheEditor".Translate(pawn.LabelShort));
            mainRect.yMin += 35f;
            Text.Font      = GameFont.Small;
            float warningSize = Mathf.Max(50f, Text.CalcHeight("PersonalityNodeWarning".Translate(), mainRect.width));

            Widgets.Label(mainRect, "PersonalityNodeWarning".Translate());
            mainRect.yMin += warningSize;
            float labelSize         = Mathf.Max(26f, Text.CalcHeight("SexDrive".Translate(), mainRect.width));
            Rect  nodeRect          = new Rect(mainRect.x, mainRect.y, mainRect.width, mainRect.height - labelSize * 3 - 20f);
            Rect  sexDriveRect      = new Rect(mainRect.x, nodeRect.yMax + 10f, mainRect.width, labelSize);
            Rect  romanticDriveRect = new Rect(mainRect.x, sexDriveRect.yMax, mainRect.width, labelSize);
            Rect  kinseyRect        = new Rect(mainRect.x, romanticDriveRect.yMax, mainRect.width, labelSize + 10f);

            Widgets.DrawLineHorizontal(nodeRect.x, nodeRect.yMax, nodeRect.width);
            float num = 0f;

            foreach (PersonalityNode node in this.pawn.psyche.PersonalityNodes)
            {
                num += Mathf.Max(26f, Text.CalcHeight(node.def.label, nodeRect.width));
            }
            Rect viewRect = new Rect(0f, 0f, nodeRect.width - 20f, num);

            Widgets.BeginScrollView(nodeRect, ref nodeScrollPosition, viewRect);
            float num3 = 0f;

            for (int i = 0; i < cachedList.Count; i++)
            {
                string label = cachedList[i].First;
                float  num4  = Mathf.Max(26f, Text.CalcHeight(label, viewRect.width));
                Rect   rect  = new Rect(10f, num3, viewRect.width / 3, num4);
                Rect   rect2 = new Rect(10f + viewRect.width / 3, num3, ((2 * viewRect.width) / 3) - 20f, num4);
                Widgets.DrawHighlightIfMouseover(rect);
                Widgets.Label(rect, label);
                TooltipHandler.TipRegion(rect, () => descriptions[label], 436532 + Mathf.RoundToInt(num3));
                float newVal = Widgets.HorizontalSlider(rect2, cachedList[i].Second, 0f, 1f, true);
                cachedList[i] = new Pair <string, float>(cachedList[i].First, newVal);
                num3         += num4;
            }
            GUI.EndScrollView();
            if (PsychologyBase.ActivateKinsey())
            {
                Rect sexDriveLabelRect  = new Rect(sexDriveRect.x, sexDriveRect.y, sexDriveRect.width / 3, sexDriveRect.height);
                Rect sexDriveSliderRect = new Rect(sexDriveRect.x + (sexDriveRect.width / 3), sexDriveRect.y, (2 * sexDriveRect.width) / 3, sexDriveRect.height);
                Widgets.Label(sexDriveLabelRect, "SexDrive".Translate());
                pawnSexDrive = Widgets.HorizontalSlider(sexDriveSliderRect, pawnSexDrive, 0f, 1f, true);
                Rect romanticDriveLabelRect  = new Rect(romanticDriveRect.x, romanticDriveRect.y, romanticDriveRect.width / 3, romanticDriveRect.height);
                Rect romanticDriveSliderRect = new Rect(romanticDriveRect.x + (romanticDriveRect.width / 3), romanticDriveRect.y, (2 * romanticDriveRect.width) / 3, romanticDriveRect.height);
                Widgets.Label(romanticDriveLabelRect, "RomanticDrive".Translate());
                pawnRomanticDrive = Widgets.HorizontalSlider(romanticDriveSliderRect, pawnRomanticDrive, 0f, 1f, true);
                Rect kinseyRatingLabelRect  = new Rect(kinseyRect.x, kinseyRect.y, kinseyRect.width / 3, kinseyRect.height);
                Rect kinseyRatingSliderRect = new Rect(kinseyRect.x + (kinseyRect.width / 3), kinseyRect.y, (2 * kinseyRect.width) / 3, kinseyRect.height);
                Widgets.Label(kinseyRatingLabelRect, "KinseyRating".Translate());
                pawnKinseyRating = Mathf.RoundToInt(Widgets.HorizontalSlider(kinseyRatingSliderRect, pawnKinseyRating, 0f, 6f, true, leftAlignedLabel: "0", rightAlignedLabel: "6"));
            }
            else
            {
                GUI.color = Color.red;
                Rect warningRect = new Rect(mainRect.x, nodeRect.yMax + 10f, mainRect.width, labelSize * 3);
                Widgets.Label(warningRect, "SexualityDisabledWarning".Translate());
                GUI.color = Color.white;
            }
            if (Widgets.ButtonText(okRect, "AcceptButton".Translate(), true, false, true) || flag)
            {
                foreach (PersonalityNode node in this.pawn.psyche.PersonalityNodes)
                {
                    node.rawRating = (from n in cachedList
                                      where n.First == node.def.label.CapitalizeFirst()
                                      select n).First().Second;
                }
                if (PsychologyBase.ActivateKinsey())
                {
                    pawn.sexuality.sexDrive      = pawnSexDrive;
                    pawn.sexuality.romanticDrive = pawnRomanticDrive;
                    pawn.sexuality.kinseyRating  = pawnKinseyRating;
                }
                this.Close(false);
            }
            if (Widgets.ButtonText(cancelRect, "CancelButton".Translate(), true, false, true) || flag2)
            {
                this.Close(true);
            }
        }
예제 #21
0
        private ThoughtDef CreateSocialThought(out float opinionMod)
        {
            //We create a dynamic def to hold this thought so that the game won't worry about it being used anywhere else.
            ThoughtDef def = new ThoughtDef();

            def.defName          = this.pawn.GetHashCode() + "Conversation" + topic.defName;
            def.label            = topic.defName;
            def.durationDays     = PsychologyBase.ConvoDuration();
            def.nullifyingTraits = new List <TraitDef>();
            def.nullifyingTraits.Add(TraitDefOf.Psychopath);
            def.thoughtClass = typeof(Thought_MemorySocialDynamic);
            ThoughtStage stage = new ThoughtStage();

            /* Base opinion mod is 5 to the power of controversiality.
             * Controversiality varies from 0.7 (~3.09) to 1.5 (~11.18).
             */
            opinionMod = Mathf.Pow(5f, topic.controversiality);

            /* That opinion mod is weighted by the difference in their personality. 1 is identical, 0 is polar opposites.
             * Here's the math on how this works:
             *
             * The weighting is on a heavily customized cubic curve. It looks like this: https://www.wolframalpha.com/input/?i=(9.5((x-0.5)%5E3))%2B(2x%2F3)%5E2-0.3+from+0+to+1
             * The maximum positive weight is 1.27x. The maximum negative weight is -1.4875x. The neutral weight (0x) is at an opinion diff of 0.706.
             * This means that to have a positive thought from a conversation, pawns need to have a <31% difference in personality on that topic.
             * However, since it's a cubic curve, the negative modifier builds gradually. Pawns will need a >79% difference in personality to have a -0.5x weight.
             * But they'll also need a <23% difference to have a 0.5x weight. Normal agreement is at ~0.962, and normal disagreement is at ~0.073.
             * Pawns are unlikely to have huge differences in opinion. There are more ways for them to be close to each other than far apart. Here's the proof: https://anydice.com/program/1177b4
             * The approximate likelihood for them to agree on something with this weighting is 49.89%.
             *
             * Pawns' differences are exacerbated when they are in a relationship, but their similarities are also magnified.
             * The neutral conversation weight (0x) moves from 0.706 to 0.759, so the threshold for agreement is ~5% higher.
             * Normal disagreement moves from 0.073 to 0.127, and normal agreement moves from 0.962 to 0.946.
             * The maximum positive weight moves from 1.27x to 1.4986x. The maximum negative weight moves from -1.425x to -1.9875x.
             * The approximate likelihood for them to agree on something with this weighting is 42.63%.
             */
            float rawOpinionDiff = 1f - Mathf.Abs(PsycheHelper.Comp(pawn).Psyche.GetPersonalityRating(topic) - PsycheHelper.Comp(otherPawn).Psyche.GetPersonalityRating(topic));

            if (LovePartnerRelationUtility.LovePartnerRelationExists(this.pawn, this.otherPawn))
            {
                opinionMod *= (13.5f * (Mathf.Pow(rawOpinionDiff - 0.5f, 3))) + Mathf.Pow(((3f * rawOpinionDiff) / 9f), 2) - 0.3f;
            }
            else
            {
                opinionMod *= (9.5f * (Mathf.Pow(rawOpinionDiff - 0.5f, 3))) + Mathf.Pow(((2f * rawOpinionDiff) / 3f), 2) - 0.3f;
            }
            //Old cubic interpolation weighting.
            //opinionMod *= Mathf.Lerp((LovePartnerRelationUtility.LovePartnerRelationExists(pawn, otherPawn) ? -2f : -1.5f), (LovePartnerRelationUtility.LovePartnerRelationExists(pawn, otherPawn) ? 1.5f : 1.25f), weightedOpinionDiff);

            /* The Cool modifier ranges from 3^(0.7) ~ 2.16 to 3^(1.5) ~ 5.2.
             * If a pawn is Cool, that modifier is a positive one added to all conversational thoughts. Otherwise, it's subtracted.
             * On average, Cool pawns will be liked better, and non-Cool pawns will be disliked more.
             */
            opinionMod += Mathf.Pow(3f, topic.controversiality) * (PsycheHelper.Comp(otherPawn).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Cool) - 0.5f);

            /* The length of the talk has a large impact on how much the pawn cares.
             * A conversation is considered "full impact" at 1,125 ticks, or less than half an hour in-game.
             * A short talk (500 ticks or less) has a maximum 0.53x impact. The max opinion this could give (for non-lovers) is 7.5/-8.8.
             * A normal talk (half an hour or less) has a maximum 1.33x impact. The max opinion this could give is 18.9/-22.1.
             * A long talk (2.5 hours or less) has a maximum 6.67x impact. The max opinion this could give is 94.7/-110.9.
             * An epic talk (2.5+ hours) has no maximum impact, but after 2 hours the MTB to end the conversation becomes half an hour, so it's unlikely they will ever have an epic talk.
             * An average conversation is 1-2 hours, so on average the max opinion (not counting Cool modifier) is 37.9/-44.3 to 75.7/-88.7.
             * Again, it's unlikely the numbers will get that high. This is assuming identical or polar opposite personalities.
             */
            opinionMod *= 6f * ((float)this.ageTicks / (float)(GenDate.TicksPerHour * 2.25f));
            // Negative opinions are tempered by how Polite the other pawn is. An extremely impolite pawn will make a bad opinion 1.5x worse. A very polite pawn will make it half as bad.
            opinionMod *= (opinionMod < 0f ? 0.5f + (1f - PsycheHelper.Comp(otherPawn).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Polite)) : 1f);
            // Positive opinions are bolstered by how Friendly the other pawn is. An extremely friendly pawn will make a positive opinion 1.5x better. A very unfriendly pawn will halve it.
            opinionMod *= (opinionMod > 0f ? 0.5f + PsycheHelper.Comp(otherPawn).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Friendly) : 1f);
            // The more Judgmental the pawn, the more they're affected by all conversations.
            opinionMod *= 0.5f + PsycheHelper.Comp(pawn).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Judgmental);
            // In low-population colonies, pawns will put aside their differences.
            if (opinionMod < 0f)
            {
                opinionMod *= PopulationModifier;
            }
            else if (LovePartnerRelationUtility.LovePartnerRelationExists(this.pawn, this.otherPawn) && this.pawn.story.traits.HasTrait(TraitDefOfPsychology.Codependent))
            {
                //If it's a positive thought about their lover, Codependent pawns are always 1.25x as affected by it.
                opinionMod *= 1.25f;
            }
            stage.label             = "ConversationStage".Translate() + " " + convoTopic;
            stage.baseOpinionOffset = Mathf.RoundToInt(opinionMod);
            def.stages.Add(stage);
            return(def);
        }
예제 #22
0
 public override void Tick(int currentTick)
 {
     //Performance reporting tick
     if (EnablePerformanceTesting() && currentTick % GenDate.TicksPerDay == 0 && PerformanceSetup.performanceTotals.Keys.Count > 0)
     {
         Dictionary <string, float> averages = PerformanceSetup.performanceTotals.ToDictionary(x => x.Key, x => (float)x.Value / (float)PerformanceSetup.performanceCalls[x.Key]);
         int topAmt = Math.Min(10, averages.Count);
         List <KeyValuePair <string, float> > avgTicks = (from avg in averages orderby avg.Value descending select avg).Take(topAmt).ToList();
         List <KeyValuePair <string, float> > topTicks = (from avg in averages orderby avg.Value * PerformanceSetup.performanceCalls[avg.Key] descending select avg).Take(topAmt).ToList();
         StringBuilder avgString = new StringBuilder();
         foreach (KeyValuePair <string, float> t in avgTicks)
         {
             avgString.AppendLine(t.Key + " (" + t.Value + ")");
         }
         StringBuilder topString = new StringBuilder();
         foreach (KeyValuePair <string, float> t in topTicks)
         {
             topString.AppendLine(t.Key + " (" + avgTicks.Find(x => x.Key == t.Key).Value + ")");
         }
         Log.Message("Psychology :: Performance Report :: Top " + topAmt + " average tick consumers:\n" + avgString.ToString() + "\nTop " + topAmt + " weighted tick consumers: " + topString.ToString());
     }
     //Constituent tick
     if (currentTick % GenDate.TicksPerHour * 2 == 0)
     {
         Map playerFactionMap            = Find.WorldObjects.SettlementBases.Find(b => b.Faction.IsPlayer).Map;
         IEnumerable <Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned
                                            where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetLord() == null && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake()
                                            select p);
         if (constituents.Count() > 0)
         {
             Pawn potentialConstituent       = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2));
             IEnumerable <Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile &&
                                                m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake() && m.GetLord() == null
                                                select m);
             if (potentialConstituent != null && !potentialConstituent.Downed && !potentialConstituent.Drafted && potentialConstituent.health.summaryHealth.SummaryHealthPercent >= 1f && potentialConstituent.GetTimeAssignment() != TimeAssignmentDefOf.Work && activeMayors.Count() > 0)
             {
                 Pawn    mayor  = activeMayors.RandomElement(); //There should only be one.
                 IntVec3 gather = default(IntVec3);
                 String  found  = null;
                 if (mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable != null)
                 {
                     gather = mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable.parent.Position;
                     found  = "office";
                 }
                 else if (mayor.ownership != null && mayor.ownership.OwnedBed != null)
                 {
                     gather = mayor.ownership.OwnedBed.Position;
                     found  = "bed";
                 }
                 if (PsycheHelper.PsychologyEnabled(potentialConstituent) && Rand.Chance((1f - PsycheHelper.Comp(potentialConstituent).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (found != null || RCellFinder.TryFindPartySpot(mayor, out gather)) &&
                     (!mayor.Drafted && !mayor.Downed && mayor.health.summaryHealth.SummaryHealthPercent >= 1f && mayor.GetTimeAssignment() != TimeAssignmentDefOf.Work && (mayor.CurJob == null || mayor.CurJob.def != JobDefOf.TendPatient)))
                 {
                     List <Pawn> pawns = new List <Pawn>();
                     pawns.Add(mayor);
                     pawns.Add(potentialConstituent);
                     Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < (potentialConstituent.mindState.mentalBreaker.BreakThresholdMinor * 1.25f))), mayor.Map, pawns);
                     mayor.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced);
                     potentialConstituent.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced);
                     if (found == "bed")
                     {
                         mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoOffice);
                     }
                     else if (found == null)
                     {
                         mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom);
                     }
                 }
             }
         }
     }
     //Election tick
     if (currentTick % (GenDate.TicksPerDay / 4f) == 0)
     {
         foreach (Settlement settlement in Find.WorldObjects.Settlements)
         {
             //Self-explanatory.
             if (!PsychologyBase.ActivateElections())
             {
                 continue;
             }
             //If the base isn't owned or named by the player, no election can be held.
             if (!settlement.Faction.IsPlayer || !settlement.namedByPlayer)
             {
                 continue;
             }
             //If the base is not at least a year old, no election will be held.
             if ((Find.TickManager.TicksGame - settlement.creationGameTicks) / GenDate.TicksPerYear < 1)
             {
                 continue;
             }
             //A base must have at least 7 people in it to hold an election.
             if (settlement.Map.mapPawns.FreeColonistsSpawnedCount < 7)
             {
                 continue;
             }
             //If an election is already being held, don't start a new one.
             if (settlement.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || settlement.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null)
             {
                 continue;
             }
             //Elections are held in Septober (because I guess some maps don't have fall?) and during the day.
             if (GenDate.Quadrum(Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(settlement.Tile).x) != Quadrum.Septober || (GenLocalDate.HourOfDay(settlement.Map) < 7 || GenLocalDate.HourOfDay(settlement.Map) > 20))
             {
                 continue;
             }
             //If an election has already been completed this year, don't start a new one.
             IEnumerable <Pawn> activeMayors = (from m in settlement.Map.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == settlement.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(settlement.Map.Tile)
                                                select m);
             if (activeMayors.Count() > 0)
             {
                 continue;
             }
             //Try to space out the elections so they don't all proc at once.
             if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfQuadrum(settlement.Map.Tile)) > 1)
             {
                 continue;
             }
             IncidentParms parms = new IncidentParms();
             parms.target  = settlement.Map;
             parms.faction = settlement.Faction;
             FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms);
             Find.Storyteller.TryFire(fi);
         }
     }
 }