Exemple #1
0
        public Pawn FromRealmPawn(RealmData realmData)
        {
            // This code is mainly a copy/paste of what happens in
            // PawnGenerator.DoGenerateNakedPawn()
            PawnKindDef kindDef = DefDatabase <PawnKindDef> .GetNamed(kindDefName);

            Pawn pawn = (Pawn)ThingMaker.MakeThing(kindDef.race);

            pawn.kindDef = kindDef;
            pawn.SetFactionDirect(Faction.OfPlayer);
            PawnComponentsUtility.CreateInitialComponents(pawn);
            pawn.gender = gender;

            // What is done in GenerateRandomAge()
            pawn.ageTracker.AgeBiologicalTicks    = ageBiologicalTicks;
            pawn.ageTracker.AgeChronologicalTicks = ageChronologicalTicks;

            // Ignored SetInitialLevels()
            // Ignored GenerateInitialHediffs()
            // Ignored GeneratePawnRelations()

            Pawn_StoryTracker story = pawn.story;

            story.melanin   = melanin;
            story.crownType = crownType;
            story.hairColor = new Color(hairColor[0], hairColor[1], hairColor[2], hairColor[3]);

            // What is done in GiveAppropriateBio()
            Name nameObj = pawn.Name;

            switch (name.Count())
            {
            case 1:
                nameObj = new NameSingle(name[0]);
                break;

            case 2:
                nameObj = new NameTriple(name[0], name[1], name[1]);
                break;

            case 3:
                nameObj = new NameTriple(name[0], name[1], name[2]);
                break;
            }
            pawn.Name = nameObj;

            if (!BackstoryDatabase.TryGetWithIdentifier(childhoodKey, out story.childhood))
            {
                throw new Exception(string.Format("Couldn't find backstory '{0}'", childhoodKey));
            }
            if (!BackstoryDatabase.TryGetWithIdentifier(adulthoodKey, out story.adulthood))
            {
                throw new Exception(string.Format("Couldn't find backstory '{0}'", adulthoodKey));
            }

            story.hairDef = DefDatabase <HairDef> .GetNamed(hairDefName);

            // Done in GiveRandomTraits()
            foreach (RealmTrait trait in traits)
            {
                TraitDef traitDef = DefDatabase <TraitDef> .GetNamed(trait.traitDefName);

                story.traits.GainTrait(new Trait(traitDef, trait.degree));
            }

            // We attribute the skills level
            foreach (RealmSkillRecord rec in skills.AsEnumerable())
            {
                SkillDef skillDef = DefDatabase <SkillDef> .AllDefs.First((def) => def.label == rec.skillDefLabel);

                SkillRecord skill = pawn.skills.GetSkill(skillDef);
                skill.Level   = rec.level;
                skill.passion = rec.passion;
            }

            pawn.workSettings.EnableAndInitialize();

            // Once we've generated a new solid pawn, we generate the gear of it
            // GenerateStartingApparelFor()
            Pawn_ApparelTracker apparelTracker = pawn.apparel;

            foreach (RealmThing realmThing in apparels)
            {
                Apparel apparel = (Apparel)realmData.FromRealmThing(realmThing);

                apparelTracker.Wear(apparel);
            }

            // TryGenerateWeaponFor()
            Pawn_EquipmentTracker equipmentTracker = pawn.equipment;

            foreach (RealmThing realmThing in equipments)
            {
                ThingWithComps thingWithComps = (ThingWithComps)realmData.FromRealmThing(realmThing);

                equipmentTracker.AddEquipment(thingWithComps);
            }

            // GenerateInventoryFor()
            Pawn_InventoryTracker inventoryTracker = pawn.inventory;

            foreach (RealmThing realmThing in inventory)
            {
                Thing thing = realmData.FromRealmThing(realmThing);

                inventoryTracker.innerContainer.TryAdd(thing);
            }

            return(pawn);
        }
Exemple #2
0
        public static void Resurrect(Pawn pawn)
        {
            if (!pawn.Dead)
            {
                Log.Error("Tried to resurrect a pawn who is not dead: " + pawn.ToStringSafe <Pawn>(), false);
                return;
            }
            if (pawn.Discarded)
            {
                Log.Error("Tried to resurrect a discarded pawn: " + pawn.ToStringSafe <Pawn>(), false);
                return;
            }
            Corpse  corpse = pawn.Corpse;
            bool    flag   = false;
            IntVec3 loc    = IntVec3.Invalid;
            Map     map    = null;

            if (corpse != null)
            {
                flag             = corpse.Spawned;
                loc              = corpse.Position;
                map              = corpse.Map;
                corpse.InnerPawn = null;
                corpse.Destroy(DestroyMode.Vanish);
            }
            if (flag && pawn.IsWorldPawn())
            {
                Find.WorldPawns.RemovePawn(pawn);
            }
            pawn.ForceSetStateToUnspawned();
            PawnComponentsUtility.CreateInitialComponents(pawn);
            pawn.health.Notify_Resurrected();
            if (pawn.Faction != null && pawn.Faction.IsPlayer)
            {
                if (pawn.workSettings != null)
                {
                    pawn.workSettings.EnableAndInitialize();
                }
                Find.StoryWatcher.watcherPopAdaptation.Notify_PawnEvent(pawn, PopAdaptationEvent.GainedColonist);
            }
            if (flag)
            {
                GenSpawn.Spawn(pawn, loc, map, WipeMode.Vanish);
                for (int i = 0; i < 10; i++)
                {
                    MoteMaker.ThrowAirPuffUp(pawn.DrawPos, map);
                }
                if (pawn.Faction != null && pawn.Faction != Faction.OfPlayer && pawn.HostileTo(Faction.OfPlayer))
                {
                    LordMaker.MakeNewLord(pawn.Faction, new LordJob_AssaultColony(pawn.Faction, true, true, false, false, true), pawn.Map, Gen.YieldSingle <Pawn>(pawn));
                }
                if (pawn.apparel != null)
                {
                    List <Apparel> wornApparel = pawn.apparel.WornApparel;
                    for (int j = 0; j < wornApparel.Count; j++)
                    {
                        wornApparel[j].Notify_PawnResurrected();
                    }
                }
            }
            PawnDiedOrDownedThoughtsUtility.RemoveDiedThoughts(pawn);
        }
        public static Zombie GeneratePawn()
        {
            var kindDef = ZombieDefOf.Zombie;

            var zombie = (Zombie)ThingMaker.MakeThing(kindDef.race, null);

            zombie.gender = Rand.Bool ? Gender.Male : Gender.Female;
            var factionDef = ZombieDefOf.Zombies;
            var faction    = FactionUtility.DefaultFactionFrom(factionDef);

            zombie.kindDef = kindDef;
            zombie.SetFactionDirect(faction);

            PawnComponentsUtility.CreateInitialComponents(zombie);

            zombie.ageTracker.AgeBiologicalTicks    = ((long)(Rand.Range(0, 0x9c4 + 1) * 3600000f)) + Rand.Range(0, 0x36ee80);
            zombie.ageTracker.AgeChronologicalTicks = zombie.ageTracker.AgeBiologicalTicks;
            zombie.ageTracker.BirthAbsTicks         = GenTicks.TicksAbs - zombie.ageTracker.AgeBiologicalTicks;

            zombie.needs.SetInitialLevels();
            zombie.needs.mood = new Need_Mood(zombie);

            var name = PawnNameDatabaseSolid.GetListForGender((zombie.gender == Gender.Female) ? GenderPossibility.Female : GenderPossibility.Male).RandomElement();
            var n1   = name.First.Replace('s', 'z').Replace('S', 'Z');
            var n2   = name.Last.Replace('s', 'z').Replace('S', 'Z');
            var n3   = name.Nick.Replace('s', 'z').Replace('S', 'Z');

            zombie.Name = new NameTriple(n1, n3, n2);

            // faster: use MinimalBackstory()
            zombie.story.childhood = BackstoryDatabase.allBackstories
                                     .Where(kvp => kvp.Value.slot == BackstorySlot.Childhood)
                                     .RandomElement().Value;
            if (zombie.ageTracker.AgeBiologicalYearsFloat >= 20f)
            {
                zombie.story.adulthood = BackstoryDatabase.allBackstories
                                         .Where(kvp => kvp.Value.slot == BackstorySlot.Adulthood)
                                         .RandomElement().Value;
            }

            zombie.story.melanin   = 0.01f * Rand.Range(10, 91);
            zombie.story.crownType = Rand.Bool ? CrownType.Average : CrownType.Narrow;

            zombie.story.hairColor = HairColor();
            zombie.story.hairDef   = PawnHairChooser.RandomHairDefFor(zombie, factionDef);
            zombie.story.bodyType  = (zombie.gender == Gender.Female) ? BodyType.Female : BodyType.Male;
            if (zombie.story.bodyType == BodyType.Male)
            {
                switch (Rand.Range(1, 6))
                {
                case 1:
                    zombie.story.bodyType = BodyType.Thin;
                    break;

                case 2:
                    zombie.story.bodyType = BodyType.Fat;
                    break;

                case 3:
                    zombie.story.bodyType = BodyType.Hulk;
                    break;
                }
            }

            if (ZombieSettings.Values.useCustomTextures)
            {
                AssignNewCustomGraphics(zombie);
            }

            zombie.Drawer.leaner = new ZombieLeaner(zombie);

            return(zombie);
        }
        private static Pawn TryGenerateNewNakedPawn(ref PawnGenerationRequest request, out string error, bool ignoreScenarioRequirements)
        {
            error = null;
            Pawn pawn = (Pawn)ThingMaker.MakeThing(request.KindDef.race, null);

            PawnGenerator.pawnsBeingGenerated.Add(new PawnGenerationStatus(pawn, null));
            try
            {
                pawn.kindDef = request.KindDef;
                pawn.SetFactionDirect(request.Faction);
                PawnComponentsUtility.CreateInitialComponents(pawn);
                if (request.FixedGender.HasValue)
                {
                    pawn.gender = request.FixedGender.Value;
                }
                else if (pawn.RaceProps.hasGenders)
                {
                    if (Rand.Value < 0.5)
                    {
                        pawn.gender = Gender.Male;
                    }
                    else
                    {
                        pawn.gender = Gender.Female;
                    }
                }
                else
                {
                    pawn.gender = Gender.None;
                }
                PawnGenerator.GenerateRandomAge(pawn, request);
                pawn.needs.SetInitialLevels();
                if (!request.Newborn && request.CanGeneratePawnRelations)
                {
                    PawnGenerator.GeneratePawnRelations(pawn, ref request);
                }
                if (pawn.RaceProps.Humanlike)
                {
                    pawn.story.melanin   = ((!request.FixedMelanin.HasValue) ? PawnSkinColors.RandomMelanin(request.Faction) : request.FixedMelanin.Value);
                    pawn.story.crownType = (CrownType)((Rand.Value < 0.5) ? 1 : 2);
                    pawn.story.hairColor = PawnHairColors.RandomHairColor(pawn.story.SkinColor, pawn.ageTracker.AgeBiologicalYears);
                    PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo(pawn, request.FixedLastName);
                    pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, request.Faction.def);
                    PawnGenerator.GenerateTraits(pawn, request);
                    PawnGenerator.GenerateBodyType(pawn);
                    PawnGenerator.GenerateSkills(pawn);
                }
                PawnGenerator.GenerateInitialHediffs(pawn, request);
                if (pawn.workSettings != null && request.Faction.IsPlayer)
                {
                    pawn.workSettings.EnableAndInitialize();
                }
                if (request.Faction != null && pawn.RaceProps.Animal)
                {
                    pawn.GenerateNecessaryName();
                }
                if (!request.AllowDead && (pawn.Dead || pawn.Destroyed))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error = "Generated dead pawn.";
                    return(null);
                }
                if (!request.AllowDowned && pawn.Downed)
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error = "Generated downed pawn.";
                    return(null);
                }
                if (request.MustBeCapableOfViolence)
                {
                    if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent))
                    {
                        goto IL_02b0;
                    }
                    if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
                    {
                        goto IL_02b0;
                    }
                }
                if (!ignoreScenarioRequirements && request.Context == PawnGenerationContext.PlayerStarter && !Find.Scenario.AllowPlayerStartingPawn(pawn))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error = "Generated pawn doesn't meet scenario requirements.";
                    return(null);
                }
                if (request.Validator != null && !request.Validator(pawn))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error = "Generated pawn didn't pass validator check.";
                    return(null);
                }
                for (int i = 0; i < PawnGenerator.pawnsBeingGenerated.Count - 1; i++)
                {
                    if (PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime == null)
                    {
                        PawnGenerator.pawnsBeingGenerated[i] = new PawnGenerationStatus(PawnGenerator.pawnsBeingGenerated[i].Pawn, new List <Pawn>());
                    }
                    PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime.Add(pawn);
                }
                return(pawn);

IL_02b0:
                PawnGenerator.DiscardGeneratedPawn(pawn);
                error = "Generated pawn incapable of violence.";
                return(null);
            }
            finally
            {
                PawnGenerator.pawnsBeingGenerated.RemoveLast();
            }
        }
Exemple #5
0
        public Pawn FromRealmPawn(RealmData realmData)
        {
            // This code is mainly a copy/paste of what happens in
            // PawnGenerator.DoGenerateNakedPawn()
            PawnKindDef kindDef = DefDatabase <PawnKindDef> .GetNamed(kindDefName);

            Pawn pawn = (Pawn)ThingMaker.MakeThing(kindDef.race);

            pawn.kindDef = kindDef;
            pawn.SetFactionDirect(Faction.OfPlayer);
            PawnComponentsUtility.CreateInitialComponents(pawn);
            pawn.gender = gender;

            // What is done in GenerateRandomAge()
            pawn.ageTracker.AgeBiologicalTicks    = ageBiologicalTicks;
            pawn.ageTracker.AgeChronologicalTicks = ageChronologicalTicks;

            // Ignored SetInitialLevels()
            // Ignored GenerateInitialHediffs()
            // Ignored GeneratePawnRelations()

            Pawn_StoryTracker story = pawn.story;

            story.melanin   = melanin;
            story.crownType = crownType;
            story.hairColor = new Color(hairColor[0], hairColor[1], hairColor[2], hairColor[3]);

            // What is done in GiveAppropriateBio()
            Name nameObj = pawn.Name;

            switch (name.Count())
            {
            case 1:
                nameObj = new NameSingle(name[0]);
                break;

            case 2:
                nameObj = new NameTriple(name[0], name[1], name[1]);
                break;

            case 3:
                nameObj = new NameTriple(name[0], name[1], name[2]);
                break;
            }
            pawn.Name = nameObj;

            if (!BackstoryDatabase.TryGetWithIdentifier(childhoodKey, out story.childhood))
            {
                throw new Exception(string.Format("Couldn't find backstory '{0}'", childhoodKey));
            }
            if (!string.IsNullOrEmpty(adulthoodKey) && !BackstoryDatabase.TryGetWithIdentifier(adulthoodKey, out story.adulthood))
            {
                throw new Exception(string.Format("Couldn't find backstory '{0}'", adulthoodKey));
            }

            story.hairDef = DefDatabase <HairDef> .GetNamed(hairDefName);

            // Done in GiveRandomTraits()
            foreach (RealmTrait trait in traits)
            {
                TraitDef traitDef = DefDatabase <TraitDef> .GetNamed(trait.traitDefName);

                story.traits.GainTrait(new Trait(traitDef, trait.degree));
            }

            // We attribute the skills level
            foreach (RealmSkillRecord rec in skills.AsEnumerable())
            {
                SkillDef skillDef = DefDatabase <SkillDef> .AllDefs.First((def) => def.label == rec.skillDefLabel);

                SkillRecord skill = pawn.skills.GetSkill(skillDef);
                skill.Level   = rec.level;
                skill.passion = rec.passion;
            }

            pawn.workSettings.EnableAndInitialize();

            // Once we've generated a new solid pawn, we generate the gear of it
            // GenerateStartingApparelFor()
            Pawn_ApparelTracker apparelTracker = pawn.apparel;

            foreach (RealmThing realmThing in apparels)
            {
                Apparel apparel = (Apparel)realmData.FromRealmThing(realmThing);

                apparelTracker.Wear(apparel);
            }

            // TryGenerateWeaponFor()
            Pawn_EquipmentTracker equipmentTracker = pawn.equipment;

            foreach (RealmThing realmThing in equipments)
            {
                ThingWithComps thingWithComps = (ThingWithComps)realmData.FromRealmThing(realmThing);

                equipmentTracker.AddEquipment(thingWithComps);
            }

            // GenerateInventoryFor()
            Pawn_InventoryTracker inventoryTracker = pawn.inventory;

            foreach (RealmThing realmThing in inventory)
            {
                Thing thing = realmData.FromRealmThing(realmThing);

                inventoryTracker.innerContainer.TryAdd(thing);
            }

            // GenerateHediffsFor()
            if (hediffs == null)
            {
                Log.Warning("RealmHediffs is null in received colonist");
            }

            foreach (RealmHediff hediff in hediffs ?? new List <RealmHediff>())
            {
                var definition = DefDatabase <HediffDef> .GetNamed(hediff.hediffDefName);

                BodyPartRecord bodypart = null;
                if (hediff.bodyPartIndex != -1)
                {
                    bodypart = pawn.RaceProps.body.GetPartAtIndex(hediff.bodyPartIndex);
                }

                pawn.health.AddHediff(definition, bodypart);
                var newdiff = pawn.health.hediffSet.hediffs.Last();
                newdiff.source   = (hediff.sourceDefName == null ? null : DefDatabase <ThingDef> .GetNamedSilentFail(hediff.sourceDefName));
                newdiff.ageTicks = hediff.ageTicks;
                newdiff.Severity = hediff.severity;

                if (!float.IsNaN(hediff.immunity) && !pawn.health.immunity.ImmunityRecordExists(definition))
                {
                    var handler = pawn.health.immunity;
                    handler.GetType().GetMethod("TryAddImmunityRecord", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(handler, new object[] { definition });
                    var record = handler.GetImmunityRecord(definition);
                    record.immunity = hediff.immunity;
                }
            }

            var healthStateField = pawn.health.GetType().GetField("healthState", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (healthStateField == null)
            {
                Log.Error("Unable to find healthState field");
            }
            else
            {
                healthStateField.SetValue(pawn.health, healthState);
            }

            // GenerateHediffsFor()
            if (workPriorities == null)
            {
                Log.Warning("WorkPriorities is null in received colonist");
            }

            foreach (KeyValuePair <string, int> priority in workPriorities ?? new Dictionary <string, int>())
            {
                var def = DefDatabase <WorkTypeDef> .GetNamedSilentFail(priority.Key);

                if (def == null)
                {
                    Log.Warning(String.Format("Ignoring unknown workType: {0}", priority.Key));
                    continue;
                }
                pawn.workSettings.SetPriority(def, priority.Value);
            }

            return(pawn);
        }
Exemple #6
0
        /// <summary>
        /// Creates a Droid template.
        /// </summary>
        /// <param name="raceDef">ThingDef to use as race.</param>
        /// <param name="pawnKindDef">PawnKindDef to use as kind.</param>
        /// <param name="faction">Faction that owns this Droid.</param>
        /// <param name="map">Map to spawn in.</param>
        /// <returns>New Pawn if successful. Null if not.</returns>
        public static Pawn MakeDroidTemplate(PawnKindDef pawnKindDef, Faction faction, int tile, List <SkillRequirement> skills = null, int defaultSkillLevel = 6)
        {
            Map map = null;

            if (tile > -1)
            {
                map = Current.Game?.FindMap(tile);
            }

            //Log.Message("Map: " + map);

            //Manually craft a Droid Pawn.
            Pawn pawnBeingCrafted = (Pawn)ThingMaker.MakeThing(pawnKindDef.race);

            if (pawnBeingCrafted == null)
            {
                return(null);
            }

            //Kind, Faction and initial Components.
            pawnBeingCrafted.kindDef = pawnKindDef;
            if (faction != null)
            {
                pawnBeingCrafted.SetFactionDirect(faction);
            }
            PawnComponentsUtility.CreateInitialComponents(pawnBeingCrafted);

            //Gender
            pawnBeingCrafted.gender = Gender.Male;

            //Set Needs at initial levels.
            pawnBeingCrafted.needs.SetInitialLevels();

            //Set age
            pawnBeingCrafted.ageTracker.AgeBiologicalTicks    = 0;
            pawnBeingCrafted.ageTracker.AgeChronologicalTicks = 0;

            //Set Story
            if (pawnBeingCrafted.RaceProps.Humanlike)
            {
                DroidSpawnProperties spawnProperties = pawnKindDef.race.GetModExtension <DroidSpawnProperties>();

                if (spawnProperties != null)
                {
                    pawnBeingCrafted.gender = spawnProperties.gender;
                    pawnBeingCrafted.playerSettings.hostilityResponse = spawnProperties.hostileResponse;
                }

                //Appearance
                pawnBeingCrafted.story.melanin   = 1f;
                pawnBeingCrafted.story.crownType = CrownType.Average;

                if (spawnProperties != null && spawnProperties.generateHair)
                {
                    IEnumerable <HairDef> source = from hair in DefDatabase <HairDef> .AllDefs
                                                   where hair.hairTags.SharesElementWith(spawnProperties.hairTags)
                                                   select hair;
                    HairDef resultHair = source.RandomElementByWeightWithFallback((hair) => HairChoiceLikelihoodFor(hair, pawnBeingCrafted), DefDatabase <HairDef> .GetNamed("Shaved"));

                    pawnBeingCrafted.story.hairDef = resultHair;

                    if (pawnBeingCrafted.def is ThingDef_AlienRace alienRaceDef)
                    {
                        pawnBeingCrafted.story.hairColor = alienRaceDef.alienRace?.generalSettings?.alienPartGenerator?.colorChannels.FirstOrDefault(channel => channel.name == "hair").first?.NewRandomizedColor() ?? new UnityEngine.Color(1f, 1f, 1f, 1f);
                    }
                }
                else
                {
                    pawnBeingCrafted.story.hairColor = new UnityEngine.Color(1f, 1f, 1f, 1f);
                    pawnBeingCrafted.story.hairDef   = DefDatabase <HairDef> .GetNamed("Shaved");
                }


                if (spawnProperties != null && spawnProperties.bodyType != null)
                {
                    pawnBeingCrafted.story.bodyType = spawnProperties.bodyType;
                }
                else
                {
                    pawnBeingCrafted.story.bodyType = BodyTypeDefOf.Thin;
                }

                PortraitsCache.SetDirty(pawnBeingCrafted);

                //Backstory
                Backstory backstory = null;
                if (spawnProperties != null && spawnProperties.backstory != null)
                {
                    BackstoryDatabase.TryGetWithIdentifier(spawnProperties.backstory.defName, out backstory);
                }
                else
                {
                    BackstoryDatabase.TryGetWithIdentifier("ChJAndroid_Droid", out backstory);
                }

                pawnBeingCrafted.story.childhood = backstory;

                //Skills
                if (skills == null || skills.Count <= 0)
                {
                    if (spawnProperties != null)
                    {
                        //Set all skills to default first.
                        foreach (SkillDef skillDef in DefDatabase <SkillDef> .AllDefsListForReading)
                        {
                            SkillRecord skill = pawnBeingCrafted.skills.GetSkill(skillDef);
                            skill.Level = spawnProperties.defaultSkillLevel;
                        }

                        //Set skills and passions.
                        foreach (DroidSkill droidSkill in spawnProperties.skills)
                        {
                            SkillRecord skill = pawnBeingCrafted.skills.GetSkill(droidSkill.def);
                            if (skill != null)
                            {
                                skill.Level   = droidSkill.level;
                                skill.passion = droidSkill.passion;
                            }
                        }
                    }
                    else
                    {
                        List <SkillDef> allDefsListForReading = DefDatabase <SkillDef> .AllDefsListForReading;
                        for (int i = 0; i < allDefsListForReading.Count; i++)
                        {
                            SkillDef    skillDef = allDefsListForReading[i];
                            SkillRecord skill    = pawnBeingCrafted.skills.GetSkill(skillDef);

                            if (skillDef == SkillDefOf.Shooting || skillDef == SkillDefOf.Melee || skillDef == SkillDefOf.Mining || skillDef == SkillDefOf.Plants)
                            {
                                skill.Level = 8;
                            }
                            else
                            if (skillDef == SkillDefOf.Medicine || skillDef == SkillDefOf.Crafting || skillDef == SkillDefOf.Cooking)
                            {
                                skill.Level = 4;
                            }
                            else
                            {
                                skill.Level = 6;
                            }
                            skill.passion = Passion.None;
                        }
                    }
                }
                else
                {
                    List <SkillDef> allDefsListForReading = DefDatabase <SkillDef> .AllDefsListForReading;
                    for (int i = 0; i < allDefsListForReading.Count; i++)
                    {
                        SkillDef    skillDef = allDefsListForReading[i];
                        SkillRecord skill    = pawnBeingCrafted.skills.GetSkill(skillDef);

                        SkillRequirement skillRequirement = skills.First(sr => sr.skill == skillDef);
                        if (skillRequirement != null)
                        {
                            skill.Level = skillRequirement.minLevel;
                        }
                        else
                        {
                            skill.Level = defaultSkillLevel;
                        }

                        skill.passion = Passion.None;
                    }
                }
            }

            //Work settings
            if (pawnBeingCrafted.workSettings != null)
            {
                pawnBeingCrafted.workSettings.EnableAndInitialize();
            }

            //Name
            if (map != null && faction.IsPlayer)
            {
                var names = from pawn in map.mapPawns.FreeColonists
                            select pawn.Name;

                if (names != null)
                {
                    int    droidNameCount = names.Count(name => name.ToStringShort.ToLower().StartsWith(pawnKindDef.race.label.ToLower()));
                    string finalShortName = pawnKindDef.race.LabelCap + " " + droidNameCount;
                    pawnBeingCrafted.Name = MakeDroidName(finalShortName);
                }
                else
                {
                    pawnBeingCrafted.Name = MakeDroidName(null);
                }
            }
            else
            {
                pawnBeingCrafted.Name = MakeDroidName(null);
            }

            return(pawnBeingCrafted);
        }
        //public static AIPawn GeneratePawn(PawnKindDef kindDef, Faction faction, Map map, Gender gender = Gender.Female, int tries = 0)
        public static AIPawn GenerateAIPawn(ref PawnGenerationRequest request, Map map, int tries = 0)
        {
            BackstoryHelper.AddNewBackstoriesToDatabase(); // First add the new backstories to the database

            //Log.Error("0");

            AIPawn pawnAI = (AIPawn)ThingMaker.MakeThing(request.KindDef.race, null);

            //Log.Error("1");
            GetXMLData(pawnAI);

            //request.EnsureNonNullFaction();

            pawnAI.kindDef = request.KindDef;
            pawnAI.SetFactionDirect(request.Faction);

            PawnComponentsUtility.CreateInitialComponents(pawnAI);

            //Log.Error("2");

            // Needs to be set because of not flesh user
            if (pawnAI.ownership == null)
            {
                pawnAI.ownership = new Pawn_Ownership(pawnAI);
            }

            pawnAI.relations = new Pawn_RelationsTracker(pawnAI);
            pawnAI.guest     = new Pawn_GuestTracker(pawnAI);

            pawnAI.guilt     = new Pawn_GuiltTracker();
            pawnAI.royalty   = new Pawn_RoyaltyTracker(pawnAI);
            pawnAI.abilities = new Pawn_AbilityTracker(pawnAI);
            pawnAI.relations = new Pawn_RelationsTracker(pawnAI);

            if (request.FixedGender.HasValue)
            {
                pawnAI.gender = request.FixedGender.Value;
            }
            else if (pawnAI.RaceProps.hasGenders)
            {
                if (Rand.Value < 0.5f)
                {
                    pawnAI.gender = Gender.Male;
                }
                else
                {
                    pawnAI.gender = Gender.Female;
                }
            }
            else
            {
                pawnAI.gender = Gender.Female;
            }

            SetBirthday(pawnAI);
            pawnAI.needs.SetInitialLevels();


            //Log.Error("3");

            AIPawnGenerator.GenerateInitialHediffs(pawnAI);


            if (pawnAI.RaceProps.Humanlike)
            {
                pawnAI.story.melanin   = 0.1f;
                pawnAI.story.crownType = CrownType.Average;
                pawnAI.story.hairColor = PawnHairColors.RandomHairColor(pawnAI.story.SkinColor, pawnAI.ageTracker.AgeBiologicalYears);

                pawnAI.story.childhood = GetBackstory();
                //pawnAI.story.adulthood = GetBackstory();

                string headGraphicPath = GraphicDatabaseHeadRecords.GetHeadRandom(pawnAI.gender, pawnAI.story.SkinColor, pawnAI.story.crownType).GraphicPath;
                // With this Reflection you can access a private variable! Here: The private string "headGraphicPath" is set
                System.Reflection.FieldInfo fi = typeof(Pawn_StoryTracker).GetField("headGraphicPath", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                fi.SetValue(pawnAI.story, headGraphicPath);

                pawnAI.story.hairDef = GetHair();

                pawnAI.story.bodyType = ((pawnAI.gender != Gender.Female) ? BodyTypeDefOf.Male : BodyTypeDefOf.Female);

                MakeSkillsFromBackstory(pawnAI);
                GiveTraitsTo(pawnAI);

                if (pawnAI.workSettings != null && (request.Faction == Faction.OfPlayer))
                {
                    pawnAI.workSettings.EnableAndInitialize();
                }
            }

            if (pawnAI.RaceProps.ToolUser)
            {
                GenerateBaseApparel(pawnAI);
            }

            pawnAI.Name = GetName(pawnAI.def, map);

            pawnAI.royalty = null;

            //Log.Error("4");
            //PawnGenerationRequest request = new PawnGenerationRequest(pawnAI.kindDef , Faction.OfPlayer, PawnGenerationContext.All, true, true, false,false, false, false, 0, false, false, false,null, 0,0, pawnAI.gender, null, null);

            //PawnInventoryGenerator.GenerateInventoryFor(pawnAI, request);

            if (!pawnAI.Dead)
            {
                return(pawnAI);
            }

            if (tries < 10)
            {
                return(GenerateAIPawn(ref request, map, tries + 1));
            }

            return(null);
        }
        private static Pawn TryGenerateNewPawnInternal(ref PawnGenerationRequest request, out string error, bool ignoreScenarioRequirements, bool ignoreValidator)
        {
            error = null;
            Pawn pawn = (Pawn)ThingMaker.MakeThing(request.KindDef.race, null);

            PawnGenerator.pawnsBeingGenerated.Add(new PawnGenerator.PawnGenerationStatus(pawn, null));
            Pawn result;

            try
            {
                pawn.kindDef = request.KindDef;
                pawn.SetFactionDirect(request.Faction);
                PawnComponentsUtility.CreateInitialComponents(pawn);
                if (request.FixedGender.HasValue)
                {
                    pawn.gender = request.FixedGender.Value;
                }
                else if (pawn.RaceProps.hasGenders)
                {
                    if (Rand.Value < 0.5f)
                    {
                        pawn.gender = Gender.Male;
                    }
                    else
                    {
                        pawn.gender = Gender.Female;
                    }
                }
                else
                {
                    pawn.gender = Gender.None;
                }
                PawnGenerator.GenerateRandomAge(pawn, request);
                pawn.needs.SetInitialLevels();
                if (!request.Newborn && request.CanGeneratePawnRelations)
                {
                    PawnGenerator.GeneratePawnRelations(pawn, ref request);
                }
                if (pawn.RaceProps.Humanlike)
                {
                    FactionDef def;
                    Faction    faction;
                    if (request.Faction != null)
                    {
                        def = request.Faction.def;
                    }
                    else if (Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out faction, false, true, TechLevel.Undefined))
                    {
                        def = faction.def;
                    }
                    else
                    {
                        def = Faction.OfAncients.def;
                    }
                    pawn.story.melanin   = ((!request.FixedMelanin.HasValue) ? PawnSkinColors.RandomMelanin(request.Faction) : request.FixedMelanin.Value);
                    pawn.story.crownType = ((Rand.Value >= 0.5f) ? CrownType.Narrow : CrownType.Average);
                    pawn.story.hairColor = PawnHairColors.RandomHairColor(pawn.story.SkinColor, pawn.ageTracker.AgeBiologicalYears);
                    PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo(pawn, request.FixedLastName, def);
                    pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, def);
                    PawnGenerator.GenerateTraits(pawn, request);
                    PawnGenerator.GenerateBodyType(pawn);
                    PawnGenerator.GenerateSkills(pawn);
                }
                if (pawn.RaceProps.Animal && request.Faction != null && request.Faction.IsPlayer)
                {
                    pawn.training.SetWantedRecursive(TrainableDefOf.Tameness, true);
                    pawn.training.Train(TrainableDefOf.Tameness, null, true);
                }
                PawnGenerator.GenerateInitialHediffs(pawn, request);
                if (pawn.workSettings != null && request.Faction != null && request.Faction.IsPlayer)
                {
                    pawn.workSettings.EnableAndInitialize();
                }
                if (request.Faction != null && pawn.RaceProps.Animal)
                {
                    pawn.GenerateNecessaryName();
                }
                if (Find.Scenario != null)
                {
                    Find.Scenario.Notify_NewPawnGenerating(pawn, request.Context);
                }
                if (!request.AllowDead && (pawn.Dead || pawn.Destroyed))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error  = "Generated dead pawn.";
                    result = null;
                }
                else if (!request.AllowDowned && pawn.Downed)
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error  = "Generated downed pawn.";
                    result = null;
                }
                else if (request.MustBeCapableOfViolence && ((pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) || (pawn.RaceProps.ToolUser && !pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error  = "Generated pawn incapable of violence.";
                    result = null;
                }
                else if (!ignoreScenarioRequirements && request.Context == PawnGenerationContext.PlayerStarter && Find.Scenario != null && !Find.Scenario.AllowPlayerStartingPawn(pawn, false, request))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error  = "Generated pawn doesn't meet scenario requirements.";
                    result = null;
                }
                else if (!ignoreValidator && request.ValidatorPreGear != null && !request.ValidatorPreGear(pawn))
                {
                    PawnGenerator.DiscardGeneratedPawn(pawn);
                    error  = "Generated pawn didn't pass validator check (pre-gear).";
                    result = null;
                }
                else
                {
                    if (!request.Newborn)
                    {
                        PawnGenerator.GenerateGearFor(pawn, request);
                    }
                    if (!ignoreValidator && request.ValidatorPostGear != null && !request.ValidatorPostGear(pawn))
                    {
                        PawnGenerator.DiscardGeneratedPawn(pawn);
                        error  = "Generated pawn didn't pass validator check (post-gear).";
                        result = null;
                    }
                    else
                    {
                        for (int i = 0; i < PawnGenerator.pawnsBeingGenerated.Count - 1; i++)
                        {
                            if (PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime == null)
                            {
                                PawnGenerator.pawnsBeingGenerated[i] = new PawnGenerator.PawnGenerationStatus(PawnGenerator.pawnsBeingGenerated[i].Pawn, new List <Pawn>());
                            }
                            PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime.Add(pawn);
                        }
                        result = pawn;
                    }
                }
            }
            finally
            {
                PawnGenerator.pawnsBeingGenerated.RemoveLast <PawnGenerator.PawnGenerationStatus>();
            }
            return(result);
        }
Exemple #9
0
        public static Pawn Copy(this Pawn source)
        {
            PawnHealthState savedHealthState = source.health.State;

            Pawn result = (Pawn)ThingMaker.MakeThing(source.kindDef.race, null);

            result.kindDef = source.kindDef;
            result.SetFactionDirect(source.Faction);
            PawnComponentsUtility.CreateInitialComponents(result);

            // Copy gender.
            result.gender = source.gender;

            // Copy name;
            NameTriple nameTriple = source.Name as NameTriple;
            NameSingle nameSingle = source.Name as NameSingle;

            if (nameTriple != null)
            {
                result.Name = new NameTriple(nameTriple.First, nameTriple.Nick, nameTriple.Last);
            }
            else if (nameSingle != null)
            {
                result.Name = new NameSingle(nameSingle.Name, nameSingle.Numerical);
            }

            // Copy trackers.
            object[] constructorArgs = new object[] { result };
            result.ageTracker = UtilityCopy.CopyExposable(source.ageTracker, constructorArgs);
            result.story      = UtilityCopy.CopyExposable(source.story, constructorArgs);
            result.skills     = UtilityCopy.CopyExposable(source.skills, constructorArgs);
            result.health     = UtilityCopy.CopyExposable(source.health, constructorArgs);
            result.apparel    = UtilityCopy.CopyExposable(source.apparel, constructorArgs);

            // Copy alien comps
            ThingComp sourceAlienComp = ProviderAlienRaces.FindAlienCompForPawn(source);
            ThingComp resultAlienComp = ProviderAlienRaces.FindAlienCompForPawn(result);

            if (sourceAlienComp != null && resultAlienComp != null)
            {
                ProviderAlienRaces.SetCrownTypeOnComp(resultAlienComp, ProviderAlienRaces.GetCrownTypeFromComp(sourceAlienComp));
                ProviderAlienRaces.SetSkinColorOnComp(resultAlienComp, ProviderAlienRaces.GetSkinColorFromComp(sourceAlienComp));
                ProviderAlienRaces.SetSkinColorSecondOnComp(resultAlienComp, ProviderAlienRaces.GetSkinColorSecondFromComp(sourceAlienComp));
                ProviderAlienRaces.SetHairColorSecondOnComp(resultAlienComp, ProviderAlienRaces.GetHairColorSecondFromComp(sourceAlienComp));
            }

            // Copy properties added to pawns by mods.
            CopyModdedProperties(source, result);

            // Verify the pawn health state.
            if (result.health.State != savedHealthState)
            {
                Log.Warning("Mismatched health state on copied pawn: " + savedHealthState + " != " + result.health.State + ";  Resetting value to match.");
                result.SetHealthState(savedHealthState);
            }

            // Clear all of the pawn caches.
            source.ClearCaches();

            return(result);
        }
Exemple #10
0
        // Credit goes to Justin C for the Zombie Apocalypse code.
        // Taken from Verse.ZombieMod_Utility
        public static Pawn GenerateZombiePawnFromSource(Pawn sourcePawn)
        {
            PawnKindDef pawnKindDef   = PawnKindDef.Named("ReanimatedCorpse");
            Faction     factionDirect = Find.FactionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile);
            Pawn        pawn          = (Pawn)ThingMaker.MakeThing(pawnKindDef.race, null);

            pawn.kindDef = pawnKindDef;
            pawn.SetFactionDirect(factionDirect);
            pawn.pather     = new Pawn_PathFollower(pawn);
            pawn.ageTracker = new Pawn_AgeTracker(pawn);
            pawn.health     = new Pawn_HealthTracker(pawn);
            pawn.jobs       = new Pawn_JobTracker(pawn);
            pawn.mindState  = new Pawn_MindState(pawn);
            pawn.filth      = new Pawn_FilthTracker(pawn);
            pawn.needs      = new Pawn_NeedsTracker(pawn);
            pawn.stances    = new Pawn_StanceTracker(pawn);
            pawn.natives    = new Pawn_NativeVerbs(pawn);
            PawnComponentsUtility.CreateInitialComponents(pawn);
            if (pawn.RaceProps.ToolUser)
            {
                pawn.equipment    = new Pawn_EquipmentTracker(pawn);
                pawn.carryTracker = new Pawn_CarryTracker(pawn);
                pawn.apparel      = new Pawn_ApparelTracker(pawn);
                pawn.inventory    = new Pawn_InventoryTracker(pawn);
            }
            if (pawn.RaceProps.Humanlike)
            {
                pawn.ownership    = new Pawn_Ownership(pawn);
                pawn.skills       = new Pawn_SkillTracker(pawn);
                pawn.relations    = new Pawn_RelationsTracker(pawn);
                pawn.story        = new Pawn_StoryTracker(pawn);
                pawn.workSettings = new Pawn_WorkSettings(pawn);
            }
            if (pawn.RaceProps.intelligence <= Intelligence.ToolUser)
            {
                pawn.caller = new Pawn_CallTracker(pawn);
            }
            //pawn.gender = Gender.None;
            pawn.gender = sourcePawn.gender;
            Cthulhu.Utility.GenerateRandomAge(pawn, pawn.Map);
            pawn.needs.SetInitialLevels();
            if (pawn.RaceProps.Humanlike)
            {
                string headGraphicPath = sourcePawn.story.HeadGraphicPath;
                typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(pawn.story, headGraphicPath);
                pawn.story.melanin   = sourcePawn.story.melanin;
                pawn.story.crownType = sourcePawn.story.crownType;
                pawn.story.hairColor = sourcePawn.story.hairColor;
                NameTriple name = sourcePawn.Name as NameTriple;
                pawn.Name            = name;
                pawn.story.childhood = sourcePawn.story.childhood;
                pawn.story.adulthood = sourcePawn.story.adulthood;
                pawn.story.hairDef   = sourcePawn.story.hairDef;
                foreach (Trait current in sourcePawn.story.traits.allTraits)
                {
                    pawn.story.traits.GainTrait(current);
                }
                //pawn.story.GenerateSkillsFromBackstory();
            }
            GenerateZombieApparelFromSource(pawn, sourcePawn);
            PawnGenerationRequest con = new PawnGenerationRequest();

            PawnInventoryGenerator.GenerateInventoryFor(pawn, con);
            //Graphic nakedBodyGraphic = GraphicGetter_NakedHumanlike.GetNakedBodyGraphic(sourcePawn.story.bodyType, ShaderDatabase.CutoutSkin, new Color(0.37f, 0.48f, 0.35f, 1f));
            Graphic nakedBodyGraphic = GraphicDatabase.Get <Graphic_Multi>(sourcePawn.story.bodyType.bodyNakedGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, new Color(0.37f, 0.48f, 0.35f, 1f));
            Graphic headGraphic      = GraphicDatabase.Get <Graphic_Multi>(sourcePawn.story.HeadGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, new Color(0.37f, 0.48f, 0.35f, 1f));
            Graphic hairGraphic      = GraphicDatabase.Get <Graphic_Multi>(sourcePawn.story.hairDef.texPath, ShaderDatabase.Cutout, Vector2.one, sourcePawn.story.hairColor);

            pawn.Drawer.renderer.graphics.headGraphic  = headGraphic;
            pawn.Drawer.renderer.graphics.nakedGraphic = nakedBodyGraphic;
            pawn.Drawer.renderer.graphics.hairGraphic  = hairGraphic;
            return(pawn);
        }
Exemple #11
0
        public static ReanimatedPawn DoGenerateZombiePawnFromSource(Pawn sourcePawn, bool isBerserk = true, bool oathOfHastur = false)
        {
            PawnKindDef    pawnKindDef   = PawnKindDef.Named("ReanimatedCorpse");
            Faction        factionDirect = isBerserk ? Find.FactionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile) : Faction.OfPlayer;
            ReanimatedPawn pawn          = (ReanimatedPawn)ThingMaker.MakeThing(pawnKindDef.race, null);

            try
            {
                pawn.kindDef = pawnKindDef;
                pawn.SetFactionDirect(factionDirect);
                PawnComponentsUtility.CreateInitialComponents(pawn);
                pawn.gender = sourcePawn.gender;
                pawn.ageTracker.AgeBiologicalTicks    = sourcePawn.ageTracker.AgeBiologicalTicks;
                pawn.ageTracker.AgeChronologicalTicks = sourcePawn.ageTracker.AgeChronologicalTicks;
                pawn.workSettings = new Pawn_WorkSettings(pawn);
                if (pawn.workSettings != null && sourcePawn.Faction.IsPlayer)
                {
                    pawn.workSettings.EnableAndInitialize();
                }

                pawn.needs.SetInitialLevels();
                //Add hediffs?
                //Add relationships?
                if (pawn.RaceProps.Humanlike)
                {
                    pawn.story.melanin   = sourcePawn.story.melanin;
                    pawn.story.crownType = sourcePawn.story.crownType;
                    pawn.story.hairColor = sourcePawn.story.hairColor;
                    pawn.story.childhood = sourcePawn.story.childhood;
                    pawn.story.adulthood = sourcePawn.story.adulthood;
                    pawn.story.bodyType  = sourcePawn.story.bodyType;
                    pawn.story.hairDef   = sourcePawn.story.hairDef;
                    if (!oathOfHastur)
                    {
                        foreach (Trait current in sourcePawn.story.traits.allTraits)
                        {
                            pawn.story.traits.GainTrait(current);
                        }
                    }
                    else
                    {
                        pawn.story.traits.GainTrait(new Trait(TraitDef.Named("Cults_OathtakerHastur2"), 0, true));
                        pawn.story.traits.GainTrait(new Trait(TraitDefOf.Psychopath, 0, true));

                        SkillFixer(pawn, sourcePawn);
                        RelationshipFixer(pawn, sourcePawn);
                        AddedPartFixer(pawn, sourcePawn);
                    }
                    //pawn.story.GenerateSkillsFromBackstory();
                    NameTriple nameTriple = sourcePawn.Name as NameTriple;
                    if (!oathOfHastur)
                    {
                        pawn.Name = new NameTriple(nameTriple.First, string.Concat(new string[]
                        {
                            "* ",
                            Translator.Translate("Reanimated"),
                            " ",
                            nameTriple.Nick,
                            " *"
                        }), nameTriple.Last);
                    }
                    else
                    {
                        pawn.Name = nameTriple;
                    }
                }
                string headGraphicPath = sourcePawn.story.HeadGraphicPath;
                typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(pawn.story, headGraphicPath);
                GenerateZombieApparelFromSource(pawn, sourcePawn);
                PawnGenerationRequest con = new PawnGenerationRequest();
                PawnInventoryGenerator.GenerateInventoryFor(pawn, con);
                GiveZombieSkinEffect(pawn, sourcePawn as ReanimatedPawn, oathOfHastur);
                if (isBerserk)
                {
                    pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk);
                }
                //Log.Message(pawn.Name.ToStringShort);
                return(pawn);
            }
            catch (Exception e)
            {
                Cthulhu.Utility.DebugReport(e.ToString());
            }
            return(null);
        }
        private static Pawn TryGenerateNewPawnInternal(ref PawnGenerationRequest request, out string error, bool ignoreScenarioRequirements, bool ignoreValidator)
        {
            error = null;
            Pawn pawn = (Pawn)ThingMaker.MakeThing(request.KindDef.race);

            pawnsBeingGenerated.Add(new PawnGenerationStatus(pawn, null));
            try
            {
                pawn.kindDef = request.KindDef;
                pawn.SetFactionDirect(request.Faction);
                PawnComponentsUtility.CreateInitialComponents(pawn);
                if (request.FixedGender.HasValue)
                {
                    pawn.gender = request.FixedGender.Value;
                }
                else if (pawn.RaceProps.hasGenders)
                {
                    if (Rand.Value < 0.5f)
                    {
                        pawn.gender = Gender.Male;
                    }
                    else
                    {
                        pawn.gender = Gender.Female;
                    }
                }
                else
                {
                    pawn.gender = Gender.None;
                }
                GenerateRandomAge(pawn, request);
                pawn.needs.SetInitialLevels();
                if (!request.Newborn && request.CanGeneratePawnRelations)
                {
                    GeneratePawnRelations(pawn, ref request);
                }
                if (pawn.RaceProps.Humanlike)
                {
                    Faction    faction;
                    FactionDef factionType = ((request.Faction != null) ? request.Faction.def : ((!Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction_NewTemp(out faction, tryMedievalOrBetter: false, allowDefeated: true)) ? Faction.OfAncients.def : faction.def));
                    pawn.story.melanin   = (request.FixedMelanin.HasValue ? request.FixedMelanin.Value : PawnSkinColors.RandomMelanin(request.Faction));
                    pawn.story.crownType = ((Rand.Value < 0.5f) ? CrownType.Average : CrownType.Narrow);
                    pawn.story.hairColor = PawnHairColors.RandomHairColor(pawn.story.SkinColor, pawn.ageTracker.AgeBiologicalYears);
                    PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo(pawn, request.FixedLastName, factionType);
                    if (pawn.story != null)
                    {
                        if (request.FixedBirthName != null)
                        {
                            pawn.story.birthLastName = request.FixedBirthName;
                        }
                        else if (pawn.Name is NameTriple)
                        {
                            pawn.story.birthLastName = ((NameTriple)pawn.Name).Last;
                        }
                    }
                    pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, factionType);
                    GenerateTraits(pawn, request);
                    GenerateBodyType_NewTemp(pawn, request);
                    GenerateSkills(pawn);
                }
                if (pawn.RaceProps.Animal && request.Faction != null && request.Faction.IsPlayer)
                {
                    pawn.training.SetWantedRecursive(TrainableDefOf.Tameness, checkOn: true);
                    pawn.training.Train(TrainableDefOf.Tameness, null, complete: true);
                }
                GenerateInitialHediffs(pawn, request);
                if (!request.ForbidAnyTitle)
                {
                    RoyalTitleDef royalTitleDef = request.FixedTitle;
                    if (royalTitleDef == null)
                    {
                        if (request.KindDef.titleRequired != null)
                        {
                            royalTitleDef = request.KindDef.titleRequired;
                        }
                        else if (!request.KindDef.titleSelectOne.NullOrEmpty() && Rand.Chance(request.KindDef.royalTitleChance))
                        {
                            royalTitleDef = request.KindDef.titleSelectOne.RandomElementByWeight((RoyalTitleDef t) => t.commonality);
                        }
                    }
                    if (request.KindDef.minTitleRequired != null && (royalTitleDef == null || royalTitleDef.seniority < request.KindDef.minTitleRequired.seniority))
                    {
                        royalTitleDef = request.KindDef.minTitleRequired;
                    }
                    if (royalTitleDef != null)
                    {
                        Faction faction2 = ((request.Faction != null && request.Faction.def.HasRoyalTitles) ? request.Faction : Find.FactionManager.RandomRoyalFaction());
                        pawn.royalty.SetTitle(faction2, royalTitleDef, grantRewards: false);
                        if (request.Faction != null && !request.Faction.IsPlayer)
                        {
                            PurchasePermits(pawn, faction2);
                        }
                        int amount = 0;
                        if (royalTitleDef.GetNextTitle(faction2) != null)
                        {
                            amount = Rand.Range(0, royalTitleDef.GetNextTitle(faction2).favorCost - 1);
                        }
                        pawn.royalty.SetFavor_NewTemp(faction2, amount);
                        if (royalTitleDef.maxPsylinkLevel > 0)
                        {
                            Hediff_ImplantWithLevel hediff_ImplantWithLevel = HediffMaker.MakeHediff(HediffDefOf.PsychicAmplifier, pawn, pawn.health.hediffSet.GetBrain()) as Hediff_ImplantWithLevel;
                            pawn.health.AddHediff(hediff_ImplantWithLevel);
                            hediff_ImplantWithLevel.SetLevelTo(royalTitleDef.maxPsylinkLevel);
                        }
                    }
                }
                if (pawn.royalty != null)
                {
                    pawn.royalty.allowRoomRequirements    = request.KindDef.allowRoyalRoomRequirements;
                    pawn.royalty.allowApparelRequirements = request.KindDef.allowRoyalApparelRequirements;
                }
                if (pawn.workSettings != null && request.Faction != null && request.Faction.IsPlayer)
                {
                    pawn.workSettings.EnableAndInitialize();
                }
                if (request.Faction != null && pawn.RaceProps.Animal)
                {
                    pawn.GenerateNecessaryName();
                }
                if (Find.Scenario != null)
                {
                    Find.Scenario.Notify_NewPawnGenerating(pawn, request.Context);
                }
                if (!request.AllowDead && (pawn.Dead || pawn.Destroyed))
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated dead pawn.";
                    return(null);
                }
                if (!request.AllowDowned && pawn.Downed)
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated downed pawn.";
                    return(null);
                }
                if (request.MustBeCapableOfViolence && ((pawn.story != null && pawn.WorkTagIsDisabled(WorkTags.Violent)) || (pawn.RaceProps.ToolUser && !pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))))
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated pawn incapable of violence.";
                    return(null);
                }
                if (request.KindDef != null && !request.KindDef.skills.NullOrEmpty())
                {
                    List <SkillRange> skills = request.KindDef.skills;
                    for (int i = 0; i < skills.Count; i++)
                    {
                        if (pawn.skills.GetSkill(skills[i].Skill).TotallyDisabled)
                        {
                            error = "Generated pawn incapable of required skill: " + skills[i].Skill.defName;
                            return(null);
                        }
                    }
                }
                if (request.KindDef.requiredWorkTags != 0 && (pawn.CombinedDisabledWorkTags & request.KindDef.requiredWorkTags) != 0)
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated pawn with disabled requiredWorkTags.";
                    return(null);
                }
                if (!ignoreScenarioRequirements && request.Context == PawnGenerationContext.PlayerStarter && Find.Scenario != null && !Find.Scenario.AllowPlayerStartingPawn(pawn, tryingToRedress: false, request))
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated pawn doesn't meet scenario requirements.";
                    return(null);
                }
                if (!ignoreValidator && request.ValidatorPreGear != null && !request.ValidatorPreGear(pawn))
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated pawn didn't pass validator check (pre-gear).";
                    return(null);
                }
                if (!request.Newborn)
                {
                    GenerateGearFor(pawn, request);
                }
                if (!ignoreValidator && request.ValidatorPostGear != null && !request.ValidatorPostGear(pawn))
                {
                    DiscardGeneratedPawn(pawn);
                    error = "Generated pawn didn't pass validator check (post-gear).";
                    return(null);
                }
                for (int j = 0; j < pawnsBeingGenerated.Count - 1; j++)
                {
                    if (pawnsBeingGenerated[j].PawnsGeneratedInTheMeantime == null)
                    {
                        pawnsBeingGenerated[j] = new PawnGenerationStatus(pawnsBeingGenerated[j].Pawn, new List <Pawn>());
                    }
                    pawnsBeingGenerated[j].PawnsGeneratedInTheMeantime.Add(pawn);
                }
                return(pawn);
            }
            finally
            {
                pawnsBeingGenerated.RemoveLast();
            }
        }
Exemple #13
0
        public static Zombie GeneratePawn(ZombieType overwriteType)
        {
            var thing  = ThingMaker.MakeThing(ZombieDefOf.Zombie.race, null);
            var zombie = thing as Zombie;

            if (zombie == null)
            {
                Log.Error("ThingMaker.MakeThing(ZombieDefOf.Zombie.race, null) unexpectedly returned " + thing);
                return(null);
            }

            var bodyType = PrepareZombieType(zombie, overwriteType);

            zombie.kindDef = ZombieDefOf.Zombie;
            zombie.SetFactionDirect(FactionUtility.DefaultFactionFrom(ZombieDefOf.Zombies));

            PawnComponentsUtility.CreateInitialComponents(zombie);
            zombie.health.hediffSet.Clear();

            var ageInYears = (long)Rand.Range(14, 130);

            zombie.ageTracker.AgeBiologicalTicks    = (ageInYears * 3600000);
            zombie.ageTracker.AgeChronologicalTicks = zombie.ageTracker.AgeBiologicalTicks;
            zombie.ageTracker.BirthAbsTicks         = GenTicks.TicksAbs - zombie.ageTracker.AgeBiologicalTicks;
            var idx = zombie.ageTracker.CurLifeStageIndex;             // trigger calculations

            zombie.needs.SetInitialLevels();
            zombie.needs.mood = new Need_Mood(zombie);

            var name = PawnNameDatabaseSolid.GetListForGender((zombie.gender == Gender.Female) ? GenderPossibility.Female : GenderPossibility.Male).RandomElement();
            var n1   = name.First.Replace('s', 'z').Replace('S', 'Z');
            var n2   = name.Last.Replace('s', 'z').Replace('S', 'Z');
            var n3   = name.Nick.Replace('s', 'z').Replace('S', 'Z');

            zombie.Name = new NameTriple(n1, n3, n2);

            zombie.story.childhood = BackstoryDatabase.allBackstories
                                     .Where(kvp => kvp.Value.slot == BackstorySlot.Childhood)
                                     .RandomElement().Value;
            if (zombie.ageTracker.AgeBiologicalYearsFloat >= 20f)
            {
                zombie.story.adulthood = BackstoryDatabase.allBackstories
                                         .Where(kvp => kvp.Value.slot == BackstorySlot.Adulthood)
                                         .RandomElement().Value;
            }

            zombie.story.melanin   = 0.01f * Rand.Range(10, 91);
            zombie.story.bodyType  = bodyType;
            zombie.story.crownType = Rand.Bool ? CrownType.Average : CrownType.Narrow;

            zombie.story.hairColor = HairColor();
            zombie.story.hairDef   = PawnHairChooser.RandomHairDefFor(zombie, ZombieDefOf.Zombies);

            if (ZombieSettings.Values.useCustomTextures)
            {
                var it = AssignNewGraphics(zombie);
                while (it.MoveNext())
                {
                    ;
                }
            }

            zombie.Drawer.leaner = new ZombieLeaner(zombie);

            if (zombie.pather == null)
            {
                zombie.pather = new Pawn_PathFollower(zombie);
            }
            GetterSetters.destinationByRef(zombie.pather) = IntVec3.Invalid;

            return(zombie);
        }
Exemple #14
0
        public static IEnumerator SpawnZombieIterativ(IntVec3 cell, Map map, ZombieType zombieType, Action <Zombie> callback)
        {
            ZombiesSpawning++;
            var thing = ThingMaker.MakeThing(ZombieDefOf.Zombie.race, null);

            yield return(null);

            var zombie   = thing as Zombie;
            var bodyType = PrepareZombieType(zombie, zombieType);

            zombie.kindDef = ZombieDefOf.Zombie;
            zombie.SetFactionDirect(FactionUtility.DefaultFactionFrom(ZombieDefOf.Zombies));
            yield return(null);

            PawnComponentsUtility.CreateInitialComponents(zombie);
            yield return(null);

            zombie.health.hediffSet.Clear();
            var ageInYears = (long)Rand.Range(14, 130);

            zombie.ageTracker.AgeBiologicalTicks    = (ageInYears * 3600000);
            zombie.ageTracker.AgeChronologicalTicks = zombie.ageTracker.AgeBiologicalTicks;
            zombie.ageTracker.BirthAbsTicks         = GenTicks.TicksAbs - zombie.ageTracker.AgeBiologicalTicks;
            var idx = zombie.ageTracker.CurLifeStageIndex;             // trigger calculations

            yield return(null);

            zombie.needs.SetInitialLevels();
            yield return(null);

            zombie.needs.mood = new Need_Mood(zombie);
            yield return(null);

            var name = PawnNameDatabaseSolid.GetListForGender((zombie.gender == Gender.Female) ? GenderPossibility.Female : GenderPossibility.Male).RandomElement();

            yield return(null);

            var n1 = name.First.Replace('s', 'z').Replace('S', 'Z');
            var n2 = name.Last.Replace('s', 'z').Replace('S', 'Z');
            var n3 = name.Nick.Replace('s', 'z').Replace('S', 'Z');

            zombie.Name = new NameTriple(n1, n3, n2);
            yield return(null);

            zombie.story.childhood = BackstoryDatabase.allBackstories
                                     .Where(kvp => kvp.Value.slot == BackstorySlot.Childhood)
                                     .RandomElement().Value;
            yield return(null);

            if (zombie.ageTracker.AgeBiologicalYearsFloat >= 20f)
            {
                zombie.story.adulthood = BackstoryDatabase.allBackstories
                                         .Where(kvp => kvp.Value.slot == BackstorySlot.Adulthood)
                                         .RandomElement().Value;
            }
            yield return(null);

            zombie.story.melanin   = 0.01f * Rand.Range(10, 91);
            zombie.story.bodyType  = bodyType;
            zombie.story.crownType = Rand.Bool ? CrownType.Average : CrownType.Narrow;
            zombie.story.hairColor = HairColor();
            zombie.story.hairDef   = PawnHairChooser.RandomHairDefFor(zombie, ZombieDefOf.Zombies);
            yield return(null);

            var it = AssignNewGraphics(zombie);

            while (it.MoveNext())
            {
                yield return(null);
            }
            zombie.Drawer.leaner = new ZombieLeaner(zombie);
            if (zombie.pather == null)
            {
                zombie.pather = new Pawn_PathFollower(zombie);
            }
            GetterSetters.destinationByRef(zombie.pather) = IntVec3.Invalid;
            yield return(null);

            if (zombie.IsTanky == false)
            {
                var it2 = GenerateStartingApparelFor(zombie);
                while (it2.MoveNext())
                {
                    yield return(null);
                }
            }
            if (zombie.IsSuicideBomber)
            {
                zombie.lastBombTick = Find.TickManager.TicksAbs + Rand.Range(0, (int)zombie.bombTickingInterval);
            }
            GenPlace.TryPlaceThing(zombie, cell, map, ThingPlaceMode.Direct);
            yield return(null);

            if (callback != null)
            {
                callback(zombie);
            }
            ZombiesSpawning--;
            switch (Find.TickManager.CurTimeSpeed)
            {
            case TimeSpeed.Paused:
                break;

            case TimeSpeed.Normal:
                yield return(new WaitForSeconds(0.1f));

                break;

            case TimeSpeed.Fast:
                yield return(new WaitForSeconds(0.25f));

                break;

            case TimeSpeed.Superfast:
                yield return(new WaitForSeconds(0.5f));

                break;

            case TimeSpeed.Ultrafast:
                yield return(new WaitForSeconds(1f));

                break;
            }
        }
        public static Zombie DoGenerateZombiePawnFromSource(Pawn sourcePawn, string pawnKind, string factionName)
        {
            PawnKindDef pawnKindDef   = PawnKindDef.Named(pawnKind);
            Faction     factionDirect = Find.FactionManager.FirstFactionOfDef(FactionDef.Named(factionName));
            Zombie      pawn          = (Zombie)ThingMaker.MakeThing(pawnKindDef.race, null);

            try
            {
                pawn.kindDef = pawnKindDef;
                pawn.SetFactionDirect(factionDirect);
                PawnComponentsUtility.CreateInitialComponents(pawn);
                pawn.gender = sourcePawn.gender;
                pawn.ageTracker.AgeBiologicalTicks    = sourcePawn.ageTracker.AgeBiologicalTicks;
                pawn.ageTracker.AgeChronologicalTicks = sourcePawn.ageTracker.AgeChronologicalTicks;
                pawn.workSettings = new Pawn_WorkSettings(pawn);
                if (pawn.workSettings != null && sourcePawn.Faction.IsPlayer)
                {
                    pawn.workSettings.EnableAndInitialize();
                }

                pawn.needs.SetInitialLevels();
                //Add hediffs?
                //Add relationships?
                if (pawn.RaceProps.Humanlike)
                {
                    pawn.story.melanin   = sourcePawn.story.melanin;
                    pawn.story.crownType = sourcePawn.story.crownType;
                    pawn.story.hairColor = sourcePawn.story.hairColor;
                    pawn.story.childhood = sourcePawn.story.childhood;
                    pawn.story.adulthood = sourcePawn.story.adulthood;
                    pawn.story.bodyType  = sourcePawn.story.bodyType;
                    pawn.story.hairDef   = sourcePawn.story.hairDef;

                    SkillFixer(pawn, sourcePawn);
                    RelationshipFixer(pawn, sourcePawn);
                    AddedPartFixer(pawn, sourcePawn);
                    //pawn.story.GenerateSkillsFromBackstory();
                    NameTriple nameTriple = sourcePawn.Name as NameTriple;
                    pawn.Name = new NameTriple(nameTriple.First, string.Concat(new string[]
                    {
                        "* ",
                        Translator.Translate("RE_Zombie"),
                        " ",
                        nameTriple.Nick,
                        " *"
                    }), nameTriple.Last);
                }
                string headGraphicPath = sourcePawn.story.HeadGraphicPath;
                typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(pawn.story, headGraphicPath);
                GenerateZombieApparelFromSource(pawn, sourcePawn);
                PawnGenerationRequest con = new PawnGenerationRequest();
                PawnInventoryGenerator.GenerateInventoryFor(pawn, con);
                GiveZombieSkinEffect(pawn, sourcePawn as Zombie);
                //if (isBerserk)
                //{
                //    pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk);
                //}
                //Log.Message(pawn.Name.ToStringShort);
                return(pawn);
            }
            catch (Exception e)
            {
                //Cthulhu.Utility.DebugReport(e.ToString());
            }
            return(null);
        }
Exemple #16
0
        // Token: 0x06000037 RID: 55 RVA: 0x00003458 File Offset: 0x00001658
        public static Pawn MakeDroidTemplate(ThingDef raceDef, PawnKindDef pawnKindDef, Faction faction, Map map, List <SkillRequirement> skills = null, int defaultSkillLevel = 6)
        {
            Pawn pawn2 = (Pawn)ThingMaker.MakeThing(raceDef, null);
            bool flag  = pawn2 == null;
            Pawn result;

            if (flag)
            {
                result = null;
            }
            else
            {
                pawn2.kindDef = pawnKindDef;
                pawn2.SetFactionDirect(faction);
                PawnComponentsUtility.CreateInitialComponents(pawn2);
                pawn2.gender = Gender.Male;
                pawn2.needs.SetInitialLevels();
                bool humanlike = pawn2.RaceProps.Humanlike;
                if (humanlike)
                {
                    pawn2.story.melanin   = 1f;
                    pawn2.story.crownType = CrownType.Average;
                    pawn2.story.hairColor = new Color(1f, 1f, 1f, 1f);
                    pawn2.story.hairDef   = DefDatabase <HairDef> .GetNamed("Shaved", true);

                    pawn2.story.bodyType = BodyType.Thin;
                    PortraitsCache.SetDirty(pawn2);
                    Backstory childhood = null;
                    BackstoryDatabase.TryGetWithIdentifier("ChJAndroid_Droid", out childhood);
                    pawn2.story.childhood = childhood;
                    bool flag2 = skills == null || skills.Count <= 0;
                    if (flag2)
                    {
                        List <SkillDef> allDefsListForReading = DefDatabase <SkillDef> .AllDefsListForReading;
                        for (int i = 0; i < allDefsListForReading.Count; i++)
                        {
                            SkillDef    skillDef2 = allDefsListForReading[i];
                            SkillRecord skill     = pawn2.skills.GetSkill(skillDef2);
                            bool        flag3     = skillDef2 == SkillDefOf.Shooting || skillDef2 == SkillDefOf.Melee || skillDef2 == SkillDefOf.Mining || skillDef2 == SkillDefOf.Growing;
                            if (flag3)
                            {
                                skill.Level = 8;
                            }
                            else
                            {
                                bool flag4 = skillDef2 == SkillDefOf.Medicine || skillDef2 == SkillDefOf.Crafting || skillDef2 == SkillDefOf.Cooking;
                                if (flag4)
                                {
                                    skill.Level = 4;
                                }
                                else
                                {
                                    skill.Level = 6;
                                }
                            }
                            skill.passion = Passion.None;
                        }
                    }
                    else
                    {
                        List <SkillDef> allDefsListForReading2 = DefDatabase <SkillDef> .AllDefsListForReading;
                        for (int j = 0; j < allDefsListForReading2.Count; j++)
                        {
                            SkillDef         skillDef         = allDefsListForReading2[j];
                            SkillRecord      skill2           = pawn2.skills.GetSkill(skillDef);
                            SkillRequirement skillRequirement = skills.First((SkillRequirement sr) => sr.skill == skillDef);
                            bool             flag5            = skillRequirement != null;
                            if (flag5)
                            {
                                skill2.Level = skillRequirement.minLevel;
                            }
                            else
                            {
                                skill2.Level = defaultSkillLevel;
                            }
                            skill2.passion = Passion.None;
                        }
                    }
                }
                bool flag6 = pawn2.workSettings != null;
                if (flag6)
                {
                    pawn2.workSettings.EnableAndInitialize();
                }
                bool flag7 = map != null;
                if (flag7)
                {
                    IEnumerable <Name> enumerable = from pawn in map.mapPawns.FreeColonists
                                                    select pawn.Name;
                    bool flag8 = enumerable != null;
                    if (flag8)
                    {
                        int    num      = enumerable.Count((Name name) => name.ToStringShort.ToLower().StartsWith("droid"));
                        string nickName = "Droid " + num;
                        pawn2.Name = DroidUtility.MakeDroidName(nickName);
                    }
                    else
                    {
                        pawn2.Name = DroidUtility.MakeDroidName(null);
                    }
                }
                else
                {
                    pawn2.Name = DroidUtility.MakeDroidName(null);
                }
                result = pawn2;
            }
            return(result);
        }