public override void CompTick()
        {
            base.CompTick();
            if (AnimalBehaviours_Settings.flagDigPeriodically)
            {
                diggingCounter++;
                //Only do every ticksToDig
                if (diggingCounter > Props.ticksToDig)
                {
                    Pawn pawn = this.parent as Pawn;

                    //Null map check. Also check that the animal isn't sleeping, downed or dead, and if onlyWhenTamed is true, that the animal is tamed
                    if ((pawn.Map != null) && pawn.Awake() && !pawn.Downed && !pawn.Dead && (!Props.onlyWhenTamed || (Props.onlyWhenTamed && pawn.Faction != null && pawn.Faction.IsPlayer)))
                    {
                        if (pawn.Position.GetTerrain(pawn.Map).affordances.Contains(TerrainAffordanceDefOf.Diggable))
                        {
                            string   thingToDig = "";
                            int      amount     = 1;
                            ThingDef newThing   = null;
                            if (!Props.digBiomeRocks)
                            {
                                //This could have been done with a Dictionary
                                thingToDig = this.Props.customThingToDig.RandomElement();
                                int index = Props.customThingToDig.IndexOf(thingToDig);
                                amount   = Props.customAmountToDig[index];
                                newThing = ThingDef.Named(thingToDig);
                            }
                            else
                            {
                                amount = Props.customAmountToDigIfRocksOrBricks;
                                IEnumerable <ThingDef> rocksInThisBiome  = Find.World.NaturalRockTypesIn(this.parent.Map.Tile);
                                List <ThingDef>        chunksInThisBiome = new List <ThingDef>();
                                foreach (ThingDef rock in rocksInThisBiome)
                                {
                                    chunksInThisBiome.Add(rock.building.mineableThing);
                                }
                                if (!Props.digBiomeBricks)
                                {
                                    newThing = Find.World.NaturalRockTypesIn(this.parent.Map.Tile).RandomElementWithFallback().building.mineableThing;
                                }
                                else
                                {
                                    newThing = Find.World.NaturalRockTypesIn(this.parent.Map.Tile).RandomElementWithFallback().building.mineableThing.butcherProducts.FirstOrFallback().thingDef;
                                }
                            }
                            Thing newDugThing;
                            if (Props.resultIsCorpse)
                            {
                                PawnKindDef pawnkind = PawnKindDef.Named(thingToDig);
                                newDugThing = PawnGenerator.GeneratePawn(new PawnGenerationRequest(pawnkind));
                                newDugThing.Kill();
                                IntVec3 near        = CellFinder.StandableCellNear(this.parent.Position, this.parent.Map, 1f);
                                Thing   spawnedPawn = GenSpawn.Spawn(newDugThing, near, this.parent.Map, WipeMode.Vanish);
                            }
                            else
                            {
                                newDugThing            = GenSpawn.Spawn(newThing, pawn.Position, pawn.Map, WipeMode.Vanish);
                                newDugThing.stackCount = amount;
                            }


                            if (Props.spawnForbidden)
                            {
                                newDugThing.SetForbidden(true);
                            }
                            if (this.effecter == null)
                            {
                                this.effecter = EffecterDefOf.Mine.Spawn();
                            }
                            this.effecter.Trigger(pawn, newDugThing);
                        }
                    }
                    diggingCounter = 0;
                }
            }
        }
        public override void GenerateForces(Map map, ResolveParams rp, ScatterOptions options)
        {
            Debug.Log(Debug.ForceGen, "Generating mechanoid forces");

            CellRect rect = rp.rect;

            /*if (rect.minX < 15 || rect.minZ < 15 || rect.maxX > map.Size.x - 15 || rect.maxZ > map.Size.z - 15) {
             *  return; //do not add enemies if we're on the map edge
             * }
             *
             * if (!CellFinder.TryFindRandomCellInsideWith(rect, (IntVec3 x) => x.Standable(map) && options.roomMap[x.x - rect.BottomLeft.x, x.z - rect.BottomLeft.z] > 1, out IntVec3 testCell)) {
             *  return; //interrupt if there are no closed cells available
             * }*/

            PawnKindDef pawnKindDef = null;

            if (powerMax == 0)
            {
                powerMax = rect.Area / 30.0f;
            }

            powerMax = ScalePointsToDifficulty(powerMax);

            float powerThreshold  = (Math.Abs(Rand.Gaussian(0.5f, 1)) * powerMax) + 1;
            float cumulativePower = 0;

            Faction faction = Faction.OfMechanoids;

            Lord lord = LordMaker.MakeNewLord(lordJob: new LordJob_DefendPoint(rect.CenterCell), faction: faction, map: map, startingPawns: null);
            int  tile = map.Tile;

            while (cumulativePower <= powerThreshold)
            {
                PawnKindDef currentPawnKindDef = (from kind in DefDatabase <PawnKindDef> .AllDefsListForReading
                                                  where kind.RaceProps.IsMechanoid
                                                  select kind).RandomElementByWeight((PawnKindDef kind) => 1f / kind.combatPower);

                PawnGenerationRequest request =
                    new PawnGenerationRequest(currentPawnKindDef, faction, PawnGenerationContext.NonPlayer, tile, true, false, false, //allowDead is last
                                              false, true, true, 1f,
                                              false, true, true, true,
                                              false, false, false,
                                              true, 0, null, 1, null, null, null,
                                              null, null, null, null);

                IntVec3 cell = IntVec3.Invalid;
//                if (!CellFinder.TryFindRandomCellInsideWith(rect, (IntVec3 x) => x.Standable(map) && options.roomMap[x.x - rect.minX, x.z - rect.minZ] > 1, out cell)) {
                CellFinder.TryFindRandomSpawnCellForPawnNear(rect.CenterCell, map, out cell);
//                }

                if (cell != IntVec3.Invalid)
                {
                    Pawn pawn = PawnGenerator.GeneratePawn(request);

                    FilthMaker.TryMakeFilth(cell, map, ThingDefOf.Filth_Blood, 5);
                    GenSpawn.Spawn(pawn, cell, map, WipeMode.Vanish);

                    lord.AddPawn(pawn);
                    cumulativePower += pawn.kindDef.combatPower;
                }
                else
                {
                    break; //no more suitable cells
                }
                Debug.Log(Debug.ForceGen, "Spawned mechanoid of faction {0}", faction.Name);
            }
        }
예제 #3
0
        public virtual bool TrySpawnPawns(Pawn harvester = null)
        {
            if (this.HarvestableNow)
            {
                int squigs     = Squigs.Count();
                int snots      = Snots.Count();
                int grots      = Grots.Count();
                int orks       = Orks.Count();
                int greenskins = squigs + snots + grots + orks;
                Rand.PushState(this.thingIDNumber);
                var spawnRoll = Rand.ValueSeeded(this.thingIDNumber);
                Rand.PopState();
                if (spawnRoll < (SpawnChance * (/*HealthTuning.DeathOnDownedChance_NonColonyHumanlikeFromPopulationIntentCurve.Evaluate(StorytellerUtilityPopulation.PopulationIntent + greenskins) **/ Find.Storyteller.difficulty.enemyDeathOnDownedChanceFactor) * this.Growth))
                {
                    PawnKindDef pawnKindDef;
                    bool        OrkoidHarvester = harvester == null || harvester.isOrkoid();
                    if (OrkoidHarvester)
                    {
                        List <PawnGenOption> options = new List <PawnGenOption>()
                        {
                            new PawnGenOption(AdeptusPawnKindDefOf.OG_Squig, SquigChance * (OrkoidFungalUtility.SquigSpawnCurve.Evaluate(squigs))),
                            new PawnGenOption(AdeptusPawnKindDefOf.OG_Snotling, SnotlingChance * (OrkoidFungalUtility.SnotSpawnCurve.Evaluate(snots))),
                            new PawnGenOption(AdeptusPawnKindDefOf.OG_Grot_Wild, GrotChance * ((this.ageInt / this.def.plant.LifespanTicks) + OrkoidFungalUtility.GrotSpawnCurve.Evaluate(grots))),
                            new PawnGenOption(AdeptusPawnKindDefOf.OG_Ork_Wild, OrkChance * ((this.ageInt / this.def.plant.LifespanTicks) + OrkoidFungalUtility.OrkSpawnCurve.Evaluate(orks)))
                        };
                        pawnKindDef = options.InRandomOrder().RandomElementByWeight(x => x.selectionWeight).kind;
                        Rand.PushState();
                        if (pawnKindDef == AdeptusPawnKindDefOf.OG_Squig)
                        {
                            Rand.PushState();
                            pawnKindDef = DefDatabase <PawnKindDef> .AllDefsListForReading.Where(x => x.RaceProps.Animal && x.defName.Contains("OG_") && x.defName.Contains("_Squig")).RandomElementByWeight(x => AdeptusMath.Inverse(x.race.BaseMarketValue));

                            Rand.PopState();
                        }
                        Rand.PopState();
                        StringBuilder builder = new StringBuilder();
                        builder.Append(pawnKindDef.LabelCap + " Spawned");
                        builder.AppendLine();

                        foreach (var item in options)
                        {
                            builder.Append(" " + item.kind.LabelCap + " weighted at " + item.selectionWeight);
                        }
                        if (Prefs.DevMode)
                        {
                            Log.Message(builder.ToString());
                        }
                    }
                    else
                    {
                        pawnKindDef = AdeptusPawnKindDefOf.OG_Squig;
                    }
                    Faction faction = FungalProps.spawnwild || !OrkoidHarvester ? null : Faction.OfPlayer;
                    PawnGenerationRequest pawnGenerationRequest = new PawnGenerationRequest(pawnKindDef, faction, PawnGenerationContext.NonPlayer, -1, true, true, false, false, true, true, 0f, fixedGender: Gender.None, fixedBiologicalAge: Age, fixedChronologicalAge: Age);

                    Pawn pawn = PawnGenerator.GeneratePawn(pawnGenerationRequest);

                    if (pawnKindDef.RaceProps.Humanlike)
                    {
                        /*
                         * if (pawn.kindDef == OGOrkPawnKindDefOf.OG_Ork_Wild)
                         * {
                         *  pawn.story.childhood.identifier = "Ork_Base_Child";
                         * }
                         * else if (pawn.kindDef == OGOrkPawnKindDefOf.OG_Grot_Wild)
                         * {
                         *  pawn.story.childhood.identifier = "Grot_Base_Child";
                         * }
                         */
                        if (!FungalProps.spawnwild && (Faction.OfPlayer.def == AdeptusFactionDefOf.OG_Ork_PlayerTribe || Faction.OfPlayer.def == AdeptusFactionDefOf.OG_Ork_PlayerColony))
                        {
                            PawnKindDef pawnKind;
                            if (Faction.OfPlayer.def == AdeptusFactionDefOf.OG_Ork_PlayerTribe)
                            {
                                pawnKind = pawn.def.defName.Contains("Alien_Grot") ? AdeptusPawnKindDefOf.Tribesperson_OG_Grot : DefDatabase <PawnKindDef> .AllDefsListForReading.Where(x => x.defName.Contains("Tribesperson_OG_Ork")).RandomElementByWeight(x => AdeptusMath.Inverse(x.combatPower));
                            }
                            else
                            {
                                pawnKind = pawn.def.defName.Contains("Alien_Grot") ? AdeptusPawnKindDefOf.Colonist_OG_Grot : DefDatabase <PawnKindDef> .AllDefsListForReading.Where(x => x.defName.Contains("Colonist_OG_Ork")).RandomElementByWeight(x => AdeptusMath.Inverse(x.combatPower));
                            }
                            pawn.ChangeKind(pawnKind);
                        }
                        else
                        {
                            pawn.ChangeKind(PawnKindDefOf.WildMan);
                        }
                        pawn.story.bodyType = pawn.story.childhood.BodyTypeFor(pawn.gender);
                    }
                    if (GrowthRateFactor_Fertility < 1f)
                    {
                        foreach (Need need in pawn.needs.AllNeeds)
                        {
                            if (need.def != NeedDefOf.Rest)
                            {
                                need.CurLevel = 0.1f;
                            }
                        }
                    }
                    else
                    {
                        float level = GrowthRateFactor_Fertility - 1f;
                        pawn.needs.food.CurLevel = level;
                        pawn.needs.rest.CurLevel = 1f;
                        if (pawn.RaceProps.Humanlike)
                        {
                            pawn.needs.mood.CurLevel = level;
                        }
                    }
                    Hediff hediff = HediffMaker.MakeHediff(HediffDefOf.Malnutrition, pawn);
                    hediff.Severity = Math.Min(1f - GrowthRateFactor_Fertility, 0.8f);
                    pawn.health.AddHediff(hediff);
                    GenSpawn.Spawn(pawn, this.Position, this.Map, 0);
                    if (harvester != null && harvester.Faction == Faction.OfPlayer)
                    {
                        TaggedString taggedString = "AdeptusMechanicus.Ork.FungalHarvest_SuccessMessage".Translate(harvester.Name, pawn.Label);
                        Messages.Message(taggedString, pawn, MessageTypeDefOf.PositiveEvent, true);
                    }
                    return(true);
                }
            }
            return(false);
        }
        public static Pawn MakePawnFromGenomeSequence(GenomeSequence genomeSequence, Thing creator)
        {
            //int adultAge = (int)genome.pawnKindDef.RaceProps.lifeStageAges.Last().minAge;

            QEEMod.TryLog("Generating pawn...");
            PawnGenerationRequest request = new PawnGenerationRequest(
                genomeSequence.pawnKindDef,
                faction: creator.Faction,
                forceGenerateNewPawn: true,
                canGeneratePawnRelations: false,
                fixedGender: genomeSequence.gender,
                fixedBiologicalAge: 0,
                fixedChronologicalAge: 0,
                allowFood: false);
            Pawn pawn = PawnGenerator.GeneratePawn(request);

            //No pregenerated equipment.
            pawn?.equipment?.DestroyAllEquipment();
            pawn?.apparel?.DestroyAll();
            pawn?.inventory?.DestroyAll();

            //No pregenerated hediffs.
            pawn.health.hediffSet.Clear();

            //Add Hediff marking them as a clone.
            QEEMod.TryLog("Adding hediffs to generated pawn");
            pawn.health.AddHediff(QEHediffDefOf.QE_CloneStatus);

            if (genomeSequence.hediffInfos != null && genomeSequence.hediffInfos.Count > 0)
            {
                //add hediffs to pawn from defs in HediffInfo class
                foreach (HediffInfo h in genomeSequence.hediffInfos)
                {
                    pawn.health.AddHediff(h.def, h.part);
                }
            }

            //Set everything else.
            if (pawn.story is Pawn_StoryTracker storyTracker)
            {
                QEEMod.TryLog("Setting Pawn_StoryTracker attributes for generated pawn...");
                storyTracker.bodyType  = genomeSequence.bodyType;
                storyTracker.crownType = genomeSequence.crownType;
                storyTracker.hairColor = genomeSequence.hairColor;
                storyTracker.hairDef   = genomeSequence.hair ?? PawnHairChooser.RandomHairDefFor(pawn, pawn.Faction.def);
                storyTracker.melanin   = genomeSequence.skinMelanin;

                //headGraphicPath is private, so we need Harmony to set its value
                if (genomeSequence.headGraphicPath != null)
                {
                    QEEMod.TryLog("Setting headGraphicPath for generated pawn");
                    AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker, genomeSequence.headGraphicPath);
                }
                else
                {
                    //could use this code to make a random head, instead of the static graphic paths.
                    //AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker,
                    //GraphicDatabaseHeadRecords.GetHeadRandom(genomeSequence.gender, PawnSkinColors.GetSkinColor(genomeSequence.skinMelanin), genomeSequence.crownType).GraphicPath);
                    QEEMod.TryLog("No headGraphicPath in genome template, setting to default head");
                    string path = genomeSequence.gender == Gender.Male ? "Things/Pawn/Humanlike/Heads/Male/Male_Average_Normal" :
                                  "Things/Pawn/Humanlike/Heads/Female/Female_Narrow_Normal";
                    AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker, path);
                }

                storyTracker.traits.allTraits.Clear();
                QEEMod.TryLog("Setting traits for generated pawn");
                foreach (ExposedTraitEntry trait in genomeSequence.traits)
                {
                    //storyTracker.traits.GainTrait(new Trait(trait.def, trait.degree));
                    storyTracker.traits.allTraits.Add(new Trait(trait.def, trait.degree));
                    if (pawn.workSettings != null)
                    {
                        pawn.workSettings.Notify_DisabledWorkTypesChanged();
                    }
                    if (pawn.skills != null)
                    {
                        pawn.skills.Notify_SkillDisablesChanged();
                    }
                    if (!pawn.Dead && pawn.RaceProps.Humanlike)
                    {
                        pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty();
                    }
                }

                QEEMod.TryLog("Setting backstory for generated pawn");
                //Give random vatgrown backstory.
                storyTracker.childhood = DefDatabase <BackstoryDef> .GetNamed("Backstory_ColonyVatgrown").GetFromDatabase();

                storyTracker.adulthood = null;
            }

            if (pawn.skills is Pawn_SkillTracker skillsTracker)
            {
                foreach (SkillRecord skill in skillsTracker.skills)
                {
                    skill.Level   = 0;
                    skill.passion = Passion.None;
                    skill.Notify_SkillDisablesChanged();
                }


                List <SkillRecord> skillPassions = new List <SkillRecord>();
                int skillsPicked = 0;
                int iterations   = 0;
                //Pick 4 random skills to give minor passions to.
                while (skillsPicked < 4 && iterations < 1000)
                {
                    SkillRecord randomSkill = skillsTracker.skills.RandomElement();
                    if (!skillPassions.Contains(randomSkill))
                    {
                        skillPassions.Add(randomSkill);
                        randomSkill.passion = Passion.Minor;
                        skillsPicked++;
                    }

                    iterations++;
                }

                skillsPicked = 0;
                iterations   = 0;
                //Pick 2 random skills to give major passions to.
                while (skillsPicked < 2 && iterations < 1000)
                {
                    SkillRecord randomSkill = skillsTracker.skills.RandomElement();
                    if (!skillPassions.Contains(randomSkill))
                    {
                        skillPassions.Add(randomSkill);
                        randomSkill.passion = Passion.Major;
                        skillsPicked++;
                    }

                    iterations++;
                }
            }

            if (pawn.workSettings is Pawn_WorkSettings workSettings)
            {
                workSettings.EnableAndInitialize();
            }

            //Alien Races compatibility.
            if (CompatibilityTracker.AlienRacesActive)
            {
                AlienRaceCompat.SetFieldsToAlienComp(pawn, genomeSequence);
            }

            PortraitsCache.SetDirty(pawn);
            PortraitsCache.PortraitsCacheUpdate();

            return(pawn);
        }
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = pawn.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        newPawn                = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.Spawner        = this.Caster;
                        newPawn.Temporary      = true;
                        newPawn.TicksToDestroy = this.duration;
                        //if (newPawn.Faction != Faction.OfPlayerSilentFail)
                        //{
                        //    newPawn.SetFaction(this.Caster.Faction, null);
                        //}
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map);
                        }
                        catch
                        {
                            pawn.GetComp <CompAbilityUserMagic>().Mana.CurLevel += pawn.GetComp <CompAbilityUserMagic>().ActualManaCost(TorannMagicDefOf.TM_SummonElemental);
                            Log.Message("TM_Exception".Translate(new object[]
                            {
                                pawn.LabelShort,
                                this.def.defName
                            }));
                            this.Destroy(DestroyMode.Vanish);
                        }
                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            Lord lord = null;
                            if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                            {
                                Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                lord = p2.GetLord();
                            }
                            bool flag4 = lord == null;
                            if (flag4)
                            {
                                LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                lord = LordMaker.MakeNewLord(faction, lordJob, map, null);
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
예제 #6
0
        private void TrySpawnHive(Map map)
        {
            IntVec3 intVec;

            if (!TryFindQueenSpawnCell(map, out intVec))
            {
                return;
            }
            possibleSpawnCells.Remove(intVec);

            Faction     faction = HiveUtility.GetRandomInsectFaction();
            PawnKindDef kindDef = HiveUtility.GetFactionKindDef(PawnKindDef.Named("BI_Queen_Brown"), faction);
            Queen       queen   = PawnGenerator.GeneratePawn(kindDef, faction) as Queen;

            queen.hiveLocation = intVec;
            GenSpawn.Spawn(queen, CellFinder.RandomClosewalkCellNear(intVec, map, 4, null), map);
            spawnedQueens.Add(queen);
            Lord lord = queen.Lord;

            if (lord == null)
            {
                lord = queen.CreateNewLord();
            }
            int count = Rand.Range(4, 5);

            for (int i = 0; i < count; i++)
            {
                kindDef = HiveUtility.GetFactionKindDef(PawnKindDef.Named("BI_Megascarab_Brown"), faction);
                Pawn pawn = PawnGenerator.GeneratePawn(kindDef, faction);
                GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(intVec, map, 4, null), map);
                queen.spawnedInsects.Add(pawn);
                lord.AddPawn(pawn);
            }
            IntVec3 c;
            int     foodAmt = 0;

            for (int i = 0; i < Rand.Range(4, 7); i++)
            {
                if (CellFinder.TryFindRandomReachableCellNear(intVec, map, 8, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 x) => x.Walkable(map), (Region x) => true, out c, 999999))
                {
                    Egg egg = ThingMaker.MakeThing(HiveUtility.ThingDefOfEgg, null) as Egg;
                    egg.SetFaction(queen.Faction, null);
                    egg.eggLayer = queen;
                    GenPlace.TryPlaceThing(egg, c, map, ThingPlaceMode.Direct, out Thing t, null, null);
                    queen.spawnedEggs.Add(egg);
                    CompInsectSpawner comp = egg.TryGetComp <CompInsectSpawner>();
                    if (comp != null)
                    {
                        comp.jellyStores = Rand.Range(50, comp.jellyMax);
                    }
                    if (Rand.Range(1, 4) < 4)
                    {
                        CompSpawner comp2 = egg.TryGetComp <CompSpawner>();
                        if (comp2 != null)
                        {
                            comp2.TryDoSpawn();
                        }
                    }
                    if (foodAmt < (BetterInfestationsMod.settings.foodStorage + 100))
                    {
                        IntVec3 c2;
                        if (CellFinder.TryFindRandomReachableCellNear(intVec, map, 2, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 x) => x.Walkable(map), (Region x) => true, out c2, 999999))
                        {
                            Thing thing2 = ThingMaker.MakeThing(ThingDefOf.InsectJelly, null);
                            thing2.stackCount = Rand.Range(15, 75);
                            GenPlace.TryPlaceThing(thing2, c2, map, ThingPlaceMode.Direct, out Thing food, null);
                            if (food != null)
                            {
                                food.SetForbidden(true);
                            }
                        }
                    }
                }
            }
        }
예제 #7
0
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = this.launcher.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        TMPawnSummoned newPawn = new TMPawnSummoned();
                        newPawn = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.validSummoning = true;
                        newPawn.Spawner        = this.casterPawn;
                        newPawn.Temporary      = true;
                        newPawn.TicksToDestroy = this.duration;
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map);
                            this.demonPawn = newPawn;
                        }
                        catch
                        {
                            this.age = this.duration;
                            Log.Message("TM_Exception".Translate(
                                            this.casterPawn.LabelShort,
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }
                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            Lord lord = null;
                            if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                            {
                                Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                lord = p2.GetLord();
                            }
                            bool flag4 = lord == null;
                            if (flag4)
                            {
                                LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                lord = LordMaker.MakeNewLord(faction, lordJob, map, null);
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
        //
        // Methods
        //
        public void DoBirthSpawn(Pawn mother, Pawn father, float chance_successful = 1.0f)
        {
            if (mother == null)
            {
                Log.Error("No mother defined");
                return;
            }
            if (father == null)
            {
                Log.Warning("No father defined");
            }

            float birthing_quality = mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("GivingBirth")).TryGetComp <HediffComp_TendDuration> ().tendQuality;

            mother.health.AddHediff(HediffDef.Named("PostPregnancy"), null, null);
            mother.health.AddHediff(HediffDef.Named("Lactating"), ChildrenUtility.GetPawnBodyPart(pawn, "Torso"), null);

            int num = (mother.RaceProps.litterSizeCurve == null) ? 1 : Mathf.RoundToInt(Rand.ByCurve(mother.RaceProps.litterSizeCurve, 300));

            if (num < 1)
            {
                num = 1;
            }

            // Make sure the pawn looks like mommy and daddy
            float skin_whiteness = Rand.Range(0, 1);
            // Pool of "genetic traits" the baby can inherit
            List <Trait> traitpool = new List <Trait>();

            if (mother.RaceProps.Humanlike)
            {
                // Add mom's traits to the pool
                foreach (Trait momtrait in mother.story.traits.allTraits)
                {
                    traitpool.Add(momtrait);
                }
                if (father != null)
                {
                    // Add dad's traits to the pool
                    foreach (Trait dadtrait in father.story.traits.allTraits)
                    {
                        traitpool.Add(dadtrait);
                    }
                    // Blend skin colour between mom and dad
                    skin_whiteness = Rand.Range(mother.story.melanin, father.story.melanin);
                }
                else
                {
                    // If dad doesn't exist, just use mom's skin colour
                    skin_whiteness = mother.story.melanin;
                }

                // Clear out any traits that aren't genetic from the list
                if (traitpool.Count > 0)
                {
                    foreach (Trait trait in traitpool.ToArray())
                    {
                        bool is_genetic = false;
                        foreach (TraitDef gentrait in genetic_traits)
                        {
                            if (gentrait.defName == trait.def.defName)
                            {
                                is_genetic = true;
                            }
                        }
                        if (!is_genetic)
                        {
                            traitpool.Remove(trait);
                        }
                    }
                }
            }

            // Todo: Perhaps add a way to pass on the parent's body build
            // Best way to do it might be to represent thin/fat/normal/hulk
            // as a pair of two values, strength and weight
            // For example, if the mother has an average body type, she would
            // have a strength of .5f and a weight of .5f. A fat pawn would have
            // a strength of .5f and a weight of .75f. A thin pawn would have a
            // strength of .25f and a weight of .25f. A hulk pawn would have
            // strength of .75f and weight of .75f
            //List<float> strength_pool = new List<float>();
            //List<float> weight_pool = new List<float>();

            //// Get mother and fathers info here if possible

            //float avg_strength = strength_pool.Average();
            //float avg_weight = weight_pool.Average();

            // Surname passing
            string last_name = null;

            if (mother.RaceProps.Humanlike)
            {
                if (father == null)
                {
                    last_name = NameTriple.FromString(mother.Name.ToStringFull).Last;
                }
                else
                {
                    last_name = NameTriple.FromString(father.Name.ToStringFull).Last;
                }
                //Log.Message ("Debug: Newborn is born to the " + last_name + " family.");
            }

            //A16//PawnGenerationRequest request = new PawnGenerationRequest (mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, mother.Map, false, true, false, false, true, false, 1, false, true, true, null, 0, 0, null, skin_whiteness, last_name);
            //A17//PawnGenerationRequest request = new PawnGenerationRequest (mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, mother.Map.Tile, false, true, false, false, false, false, 1, false, true, true, false, false, null, 0, 0, null, skin_whiteness, last_name);
            PawnGenerationRequest request = new PawnGenerationRequest(mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, mother.Map.Tile, true, true, false, false, false, false, 0f, false, true, false, false, false, false, false, null, 0f, 0f, 0f, default(Gender?), skin_whiteness, last_name);

            Pawn baby = null;

            for (int i = 0; i < num; i++)
            {
                baby = PawnGenerator.GeneratePawn(request);
                if (PawnUtility.TrySpawnHatchedOrBornPawn(baby, mother))
                {
                    if (baby.playerSettings != null && mother.playerSettings != null)
                    {
                        baby.playerSettings.AreaRestriction = mother.playerSettings.AreaRestriction;
                    }
                    if (baby.RaceProps.IsFlesh)
                    {
                        baby.relations.AddDirectRelation(PawnRelationDefOf.Parent, mother);
                        if (father != null)
                        {
                            baby.relations.AddDirectRelation(PawnRelationDefOf.Parent, father);
                        }
                    }

                    // Good until otherwise proven bad
                    bool successful_birth = true;
                    var  disabledBaby     = BackstoryDatabase.allBackstories ["CustomBackstory_NA_Childhood_Disabled"];
                    if (disabledBaby != null)
                    {
                        baby.story.childhood = disabledBaby;
                    }
                    else
                    {
                        Log.Error("Couldn't find the required Backstory: CustomBackstory_NA_Childhood_Disabled!");
                        baby.story.childhood = null;
                    }
                    baby.story.adulthood = null;
                    baby.workSettings.Disable(WorkTypeDefOf.Hunting);                      //hushes up the "has no ranged weapon" alert
                    // remove all traits
                    baby.story.traits.allTraits.Clear();

                    // Add some genetic traits
                    if (traitpool.Count > 0)
                    {
                        for (int j = 0; j != 2; j++)
                        {
                            Trait gentrait = traitpool.RandomElement();
                            if (!baby.story.traits.HasTrait(gentrait.def))
                            {
                                baby.story.traits.GainTrait(gentrait);
                            }
                        }
                    }
                    // Move the baby in front of the mother, rather than on top
                    if (mother.CurrentBed() != null)
                    {
                        baby.Position = baby.Position + new IntVec3(0, 0, 1).RotatedBy(mother.CurrentBed().Rotation);
                    }
                    // else {
                    //	 baby.Position = baby.Position + new IntVec3 (0, 0, 1).RotatedBy (mother.Rotation);
                    // }

                    // The baby died from bad chance of success
                    if (Rand.Value > chance_successful || chance_successful == 0)
                    {
                        successful_birth = false;
                    }

                    // Birth defects via drugs or alcohol
                    if (mother.health.hediffSet.HasHediff(HediffDef.Named("BirthDefectTracker")))
                    {
                        Hediff_BirthDefectTracker tracker = (Hediff_BirthDefectTracker)mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("BirthDefectTracker"));
                        // The baby died in utero from chemical affect
                        if (tracker.stillbirth)
                        {
                            successful_birth = false;
                        }
                        // The baby lived! So far, anyways
                        else
                        {
                            // Should the baby get fetal alcohol syndrome?
                            if (tracker.fetal_alcohol)
                            {
                                baby.health.AddHediff(HediffDef.Named("FetalAlcoholSyndrome"));
                            }
                            // If the mother got high while pregnant, crongrats retard
                            // now your baby is addicted to crack
                            if (tracker.drug_addictions.Count > 0)
                            {
                                foreach (HediffDef addiction in tracker.drug_addictions)
                                {
                                    baby.health.AddHediff(addiction, null, null);
                                }
                            }
                        }
                    }

                    // Inbred?
                    if (father != null && mother.relations.FamilyByBlood.Contains <Pawn> (father))
                    {
                        // 50% chance to get a birth defect from inbreeding
                        if (Rand.Range(0, 1) == 1)
                        {
                            GiveRandomBirthDefect(baby);
                            if (baby.health.hediffSet.HasHediff(HediffDef.Named("DefectStillborn")))
                            {
                                successful_birth = false;
                            }
                        }
                    }



                    // The baby was born! Yay!
                    if (successful_birth == true)
                    {
                        // Give father a happy memory if the birth was successful and he's not dead
                        if (father != null && !father.health.Dead)
                        {
                            // The father is happy the baby was born
                            father.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("PartnerGaveBirth"));
                        }

                        // Send a message that the baby was born
                        if (mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("HumanPregnancy")).Visible&& PawnUtility.ShouldSendNotificationAbout(mother))
                        {
                            //Messages.Message ("MessageGaveBirth".Translate (new object[] {mother.LabelIndefinite ()}).CapitalizeFirst (), mother, MessageSound.Benefit);
                            Find.LetterStack.ReceiveLetter("LabelGaveBirth".Translate(new object[] { baby.LabelIndefinite() }), "MessageHumanBirth".Translate(new object[] {
                                mother.LabelIndefinite(),
                                baby.Name.ToStringShort
                            }), LetterDefOf.PositiveEvent, baby, null);
                        }

                        // Try to give PPD. If not, give "New baby" thought
                        float chance = 0.2f;
                        if (mother.story.traits.HasTrait(TraitDefOf.Psychopath))
                        {
                            chance -= 1;
                        }
                        if (mother.story.traits.HasTrait(TraitDef.Named("Nerves")))
                        {
                            chance -= 0.2f * mother.story.traits.GetTrait(TraitDef.Named("Nerves")).Degree;
                        }
                        else if (mother.story.traits.HasTrait(TraitDef.Named("NaturalMood")))
                        {
                            if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == 2)
                            {
                                chance -= 1;
                            }
                            if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == -2)
                            {
                                chance += 0.6f;
                            }
                            // For some reason this is broken

                            /*} else if (mother.story.traits.HasTrait (TraitDef.Named ("Neurotic"))) {
                             * if (mother.story.traits.GetTrait (TraitDef.Named ("Neurotic")).Degree == 1) {
                             *      chance += 0.2f;
                             * } else
                             *      chance += 0.4f;*/
                        }

                        // Because for whatever dumb reason the Math class doesn't have a Clamp method
                        if (chance < 0)
                        {
                            chance = 0;
                        }

                        if (chance > 1)
                        {
                            chance = 1;
                        }
                        Log.Message("Debugging: Chance of PPD is " + chance * 100 + "%");


                        // Try to give PPD
                        if (Rand.Value < chance)
                        {
                            mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("PostPartumDepression"), null);
                            bool verybad = false;
                            if (mother.story.traits.HasTrait(TraitDef.Named("NaturalMood")))
                            {
                                if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == -2)
                                {
                                    verybad = true;
                                }
                            }
                            else if (mother.story.traits.HasTrait(TraitDef.Named("Neurotic")))
                            {
                                if (mother.story.traits.GetTrait(TraitDef.Named("Neurotic")).Degree == 2)
                                {
                                    verybad = true;
                                }
                            }
                            // This pawn gets an exceptionally bad case of PPD
                            if (verybad)
                            {
                                foreach (Thought_Memory thought in mother.needs.mood.thoughts.memories.Memories)
                                {
                                    if (thought.def.defName == "PostPartumDepression")
                                    {
                                        thought.SetForcedStage(thought.CurStageIndex + 1);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // If we didn't get PPD, then the pawn gets a mood buff
                            if (mother.health.hediffSet.HasHediff(HediffDef.Named("GaveBirthFlag")) == false)
                            {
                                mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("IGaveBirthFirstTime"));
                            }
                            else
                            {
                                mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("IGaveBirth"));
                            }
                        }
                    }
                    else
                    {
                        bool aborted = false;
                        if (chance_successful < 0f)
                        {
                            aborted = true;
                        }
                        if (baby != null)
                        {
                            Miscarry(baby, aborted);
                        }
                    }
                }
                else
                {
                    Find.WorldPawns.PassToWorld(baby, PawnDiscardDecideMode.Discard);
                }
            }
            // Post birth
            if (mother.Spawned)
            {
                // Spawn guck
                FilthMaker.MakeFilth(mother.Position, mother.Map, ThingDefOf.FilthAmnioticFluid, mother.LabelIndefinite(), 5);
                if (mother.caller != null)
                {
                    mother.caller.DoCall();
                }
                if (baby != null)
                {
                    if (baby.caller != null)
                    {
                        baby.caller.DoCall();
                    }
                }

                Log.Message("Birth quality = " + birthing_quality);
                // Possible tearing from pregnancy
                if (birthing_quality < 0.75f)
                {
                    if (birthing_quality < Rand.Value)
                    {
                        // Add a tear from giving birth
                        if (birthing_quality < Rand.Value)
                        {
                            mother.health.AddHediff(HediffDef.Named("PregnancyTearMajor"), ChildrenUtility.GetPawnBodyPart(mother, "Torso"), null);
                        }
                        else
                        {
                            mother.health.AddHediff(HediffDef.Named("PregnancyTear"), ChildrenUtility.GetPawnBodyPart(mother, "Torso"), null);
                        }
                    }
                }
            }
            pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("GivingBirth")));
            pawn.health.RemoveHediff(this);
        }
 public static void GenStaticPawn()
 {
     PRF_StaticPawn      = PawnGenerator.GeneratePawn(PRFDefOf.PRFSlavePawn, Faction.OfPlayer);
     PRF_StaticPawn.Name = new NameTriple("...", "PRF_Static", "...");
 }
예제 #10
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map         map          = (Map)parms.target;
            Pawn        pawn         = null;
            Pawn        pawn2        = null;
            PawnKindDef pawnKindDef  = PawnKindDef.Named("Spelopede");
            PawnKindDef pawnKindDef2 = PawnKindDef.Named("Megaspider");
            bool        flag         = pawnKindDef == null && pawnKindDef2 == null;
            bool        flag2        = flag;
            bool        result;

            if (flag2)
            {
                Log.Error("Can't spawn any insects");
                result = false;
            }
            else
            {
                IEnumerable <Pawn> source = map.mapPawns.AllPawns.Cast <Pawn>();
                Func <Pawn, bool>  predicate;
                bool flag3 = (predicate = MOIncidentWorker_Insect.insect.isInsect) == null;
                if (flag3)
                {
                    predicate = (MOIncidentWorker_Insect.insect.isInsect = new Func <Pawn, bool>(MOIncidentWorker_Insect.insect.insects.TryExecute));
                }
                List <Pawn> source2 = source.Where(predicate).ToList <Pawn>();
                double      value   = (double)(source2.Count <Pawn>() / 3);
                int         num     = (int)Math.Round(value, 1);
                bool        flag4   = num <= 1;
                bool        flag5   = flag4;
                if (flag5)
                {
                    num = 2;
                }
                IntVec3 intVec = new IntVec3();
                bool    flag6  = !RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, 0f);
                bool    flag7  = flag6;
                if (flag7)
                {
                    result = false;
                }
                else
                {
                    IntVec3 intVec2 = CellFinder.RandomClosewalkCellNear(intVec, map, 10);
                    int     num2;
                    for (int i = 0; i < num; i = num2 + 1)
                    {
                        pawn = PawnGenerator.GeneratePawn(pawnKindDef, MOIncidentWorker_Insect.OfInsectoid);
                        pawn.needs.food.CurLevel = 0.01f;
                        pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, false, false, null);
                        GenSpawn.Spawn(pawn, intVec2, map);
                        num2 = i;
                    }
                    for (int j = 0; j < num; j = num2 + 1)
                    {
                        pawn2 = PawnGenerator.GeneratePawn(pawnKindDef2, MOIncidentWorker_Insect.OfInsectoid);
                        pawn2.needs.food.CurLevel = 0.01f;
                        pawn2.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, false, false, null);
                        GenSpawn.Spawn(pawn2, intVec2, map);
                        num2 = j;
                    }
                    Find.LetterStack.ReceiveLetter("MO_Insects".Translate(), "MO_InsectsDesc".Translate(), LetterDefOf.ThreatBig, new TargetInfo(intVec, map, false), null);                     //"A group of hungry insects have entered your area. They'll do anything to get your food!"
                    pawn.mindState.exitMapAfterTick  = Find.TickManager.TicksGame + Rand.Range(90000, 130000);
                    pawn2.mindState.exitMapAfterTick = Find.TickManager.TicksGame + Rand.Range(90000, 130000);
                    Find.TickManager.slower.SignalForceNormalSpeedShort();
                    result = true;
                }
            }
            return(result);
        }
        protected List <Pawn> SpawnPawns(IncidentParms parms)
        {
            var map  = (Map)parms.target;
            var list = new List <Pawn>();

            var listBugs = new List <PawnKindDef>
            {
                PawnKindDefOf.Megascarab,
                PawnKindDefOf.Spelopede,
                PawnKindDefOf.Megaspider
            };
            var source = from x in listBugs
                         where x.combatPower <= 500f
                         select x;
            var maxPawns = NUMTOSPAWN;

            for (var i = 0; i < maxPawns; i++)
            {
                if (Utility.IsCosmicHorrorsLoaded())
                {
                    var pawn = PawnGenerator.GeneratePawn(PawnKindDef.Named("ROM_DeepOne"), parms.faction);
                    if (pawn == null)
                    {
                        continue;
                    }

                    list.Add(pawn);
                }
                else
                {
                    if (!source.TryRandomElement(out var kindDef))
                    {
                        Log.Error("Unable to get pawnkind for Defend the Brood.");
                        break;
                    }

                    var pawn = PawnGenerator.GeneratePawn(kindDef, parms.faction);
                    if (pawn != null)
                    {
                        list.Add(pawn);
                    }
                }
            }

            foreach (var current in list)
            {
                var loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, (Map)parms.target, 5);


                if (GenPlace.TryPlaceThing(current, loc, (Map)parms.target, ThingPlaceMode.Near))
                {
                    continue;
                }

                Find.WorldPawns.PassToWorld(current, PawnDiscardDecideMode.Discard);

                //GenSpawn.Spawn(current, loc, (Map)parms.target);
            }

            //PawnRelationUtility.Notify_PawnsSeenByPlayer(list, out "LetterRelatedPawnsNeutralGroup".Translate(), true);
            return(list);
        }
예제 #12
0
        public override void Tick()
        {
            if (!base.Spawned)
            {
                return;
            }
            sustainer.Maintain();
            Vector3 vector = base.Position.ToVector3Shifted();

            if (Rand.MTBEventOccurs(FilthSpawnMTB, 1f, 1.TicksToSeconds()) && CellFinder.TryFindRandomReachableCellNear(base.Position, base.Map, FilthSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors), null, null, out IntVec3 result))
            {
                FilthMaker.TryMakeFilth(result, base.Map, filthTypes.RandomElement());
            }
            if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 1f, 1.TicksToSeconds()))
            {
                Vector3 loc = new Vector3(vector.x, 0f, vector.z);
                loc.y = AltitudeLayer.MoteOverhead.AltitudeFor();
                MoteMaker.ThrowDustPuffThick(loc, base.Map, Rand.Range(1.5f, 3f), new Color(1f, 1f, 1f, 2.5f));
            }
            if (secondarySpawnTick > Find.TickManager.TicksGame)
            {
                return;
            }
            sustainer.End();
            Map     map      = base.Map;
            IntVec3 position = base.Position;

            Destroy();
            if (spawnHive)
            {
                Hive obj = (Hive)GenSpawn.Spawn(ThingMaker.MakeThing(ThingDefOf.Hive), position, map);
                obj.SetFaction(Faction.OfInsects);
                obj.questTags = questTags;
                foreach (CompSpawner comp in obj.GetComps <CompSpawner>())
                {
                    if (comp.PropsSpawner.thingToSpawn == ThingDefOf.InsectJelly)
                    {
                        comp.TryDoSpawn();
                        break;
                    }
                }
            }
            if (!(insectsPoints > 0f))
            {
                return;
            }
            insectsPoints = Mathf.Max(insectsPoints, Hive.spawnablePawnKinds.Min((PawnKindDef x) => x.combatPower));
            float       pointsLeft = insectsPoints;
            List <Pawn> list       = new List <Pawn>();
            int         num        = 0;
            PawnKindDef result2;

            for (; pointsLeft > 0f; pointsLeft -= result2.combatPower)
            {
                num++;
                if (num > 1000)
                {
                    Log.Error("Too many iterations.");
                    break;
                }
                if (!Hive.spawnablePawnKinds.Where((PawnKindDef x) => x.combatPower <= pointsLeft).TryRandomElement(out result2))
                {
                    break;
                }
                Pawn pawn = PawnGenerator.GeneratePawn(result2, Faction.OfInsects);
                GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(position, map, 2), map);
                pawn.mindState.spawnedByInfestationThingComp = spawnedByInfestationThingComp;
                list.Add(pawn);
            }
            if (list.Any())
            {
                LordMaker.MakeNewLord(Faction.OfInsects, new LordJob_AssaultColony(Faction.OfInsects, canKidnap: true, canTimeoutOrFlee: false), map, list);
            }
        }
예제 #13
0
        public CustomPawn ConvertSaveRecordToPawn(SaveRecordPawnV5 record)
        {
            bool partialFailure = false;

            PawnKindDef pawnKindDef = null;

            if (record.pawnKindDef != null)
            {
                pawnKindDef = DefDatabase <PawnKindDef> .GetNamedSilentFail(record.pawnKindDef);

                if (pawnKindDef == null)
                {
                    Logger.Warning("Pawn kind definition for the saved character (" + record.pawnKindDef + ") not found.  Picking a random player colony pawn kind definition.");
                    pawnKindDef = PrepareCarefully.Instance.Providers.Factions.GetPawnKindsForFactionDef(FactionDefOf.PlayerColony).RandomElement();
                    if (pawnKindDef == null)
                    {
                        return(null);
                    }
                }
            }

            ThingDef pawnThingDef = ThingDefOf.Human;

            if (record.thingDef != null)
            {
                ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.thingDef);

                if (thingDef != null)
                {
                    pawnThingDef = thingDef;
                }
                else
                {
                    Logger.Warning("Pawn's thing definition {" + record.thingDef + "} was not found.  Defaulting to the thing definition for humans.");
                }
            }
            else
            {
                Logger.Warning("Pawn's thing definition was null.  Defaulting to the thing definition for humans.");
            }

            // Create the pawn generation request.
            PawnGenerationRequestWrapper generationRequest = new PawnGenerationRequestWrapper()
            {
                FixedBiologicalAge    = record.biologicalAge,
                FixedChronologicalAge = record.chronologicalAge,
                FixedGender           = record.gender
            };

            // Add a faction to the generation request, if possible.
            if (record.originalFactionDef != null)
            {
                FactionDef factionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.originalFactionDef);

                if (factionDef != null)
                {
                    Faction faction = PrepareCarefully.Instance.Providers.Factions.GetFaction(factionDef);
                    if (faction != null)
                    {
                        generationRequest.Faction = faction;
                    }
                    else
                    {
                        Logger.Warning("No faction found for faction definition {" + record.originalFactionDef + "}");
                    }
                }
                else
                {
                    Logger.Warning("No faction defition defition found for {" + record.originalFactionDef + "}");
                }
            }
            // Add a pawn kind definition to the generation request, if possible.
            if (pawnKindDef != null)
            {
                generationRequest.KindDef = pawnKindDef;
            }

            // Create the pawn.
            Pawn source = null;

            try {
                source = PawnGenerator.GeneratePawn(generationRequest.Request);
            }
            catch (Exception e) {
                Logger.Warning("Failed to generate a pawn from preset for pawn {" + (record.nickName) + "}. Will try to create it using fallback settings", e);
                generationRequest = new PawnGenerationRequestWrapper()
                {
                    FixedBiologicalAge    = record.biologicalAge,
                    FixedChronologicalAge = record.chronologicalAge,
                    FixedGender           = record.gender
                };
                try {
                    source = PawnGenerator.GeneratePawn(generationRequest.Request);
                }
                catch (Exception) {
                    Logger.Warning("Failed to generate a pawn using fallback settings from preset for pawn {" + (record.nickName) + "}", e);
                    return(null);
                }
            }

            if (source.health != null)
            {
                source.health.Reset();
            }

            CustomPawn pawn = new CustomPawn(source);

            if (record.id == null)
            {
                pawn.GenerateId();
            }
            else
            {
                pawn.Id = record.id;
            }

            if (record.type != null)
            {
                try {
                    pawn.Type = (CustomPawnType)Enum.Parse(typeof(CustomPawnType), record.type);
                }
                catch (Exception) {
                    pawn.Type = CustomPawnType.Colonist;
                }
            }
            else
            {
                pawn.Type = CustomPawnType.Colonist;
            }

            pawn.Gender = record.gender;
            if (record.age > 0)
            {
                pawn.ChronologicalAge = record.age;
                pawn.BiologicalAge    = record.age;
            }
            if (record.chronologicalAge > 0)
            {
                pawn.ChronologicalAge = record.chronologicalAge;
            }
            if (record.biologicalAge > 0)
            {
                pawn.BiologicalAge = record.biologicalAge;
            }

            pawn.FirstName = record.firstName;
            pawn.NickName  = record.nickName;
            pawn.LastName  = record.lastName;

            if (record.originalFactionDef != null)
            {
                pawn.OriginalFactionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.originalFactionDef);
            }
            pawn.OriginalKindDef = pawnKindDef;

            if (pawn.Type == CustomPawnType.Colonist)
            {
                Faction playerFaction = Faction.OfPlayerSilentFail;
                if (playerFaction != null)
                {
                    pawn.Pawn.SetFactionDirect(playerFaction);
                }
            }
            else if (pawn.Type == CustomPawnType.World)
            {
                if (record.faction != null)
                {
                    if (record.faction.def != null)
                    {
                        FactionDef factionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.faction.def);

                        if (factionDef != null)
                        {
                            bool randomFaction = false;
                            if (record.faction.index != null)
                            {
                                CustomFaction customFaction = null;
                                if (!record.faction.leader)
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionByIndex(factionDef, record.faction.index.Value);
                                }
                                else
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionWithLeaderOptionByIndex(factionDef, record.faction.index.Value);
                                }
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                                else
                                {
                                    Logger.Warning("Could not place at least one preset character into a saved faction because there were not enough available factions of that type in the world");
                                    randomFaction = true;
                                }
                            }
                            else
                            {
                                randomFaction = true;
                            }
                            if (randomFaction)
                            {
                                CustomFaction customFaction = PrepareCarefully.Instance.Providers.Factions.FindRandomCustomFactionByDef(factionDef);
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                            }
                        }
                        else
                        {
                            Logger.Warning("Could not place at least one preset character into a saved faction because that faction is not available in the world");
                        }
                    }
                }
            }

            HairDef h = DefDatabase <HairDef> .GetNamedSilentFail(record.hairDef);

            if (h != null)
            {
                pawn.HairDef = h;
            }
            else
            {
                Logger.Warning("Could not load hair definition \"" + record.hairDef + "\"");
                partialFailure = true;
            }

            pawn.HeadGraphicPath = record.headGraphicPath;
            if (pawn.Pawn.story != null)
            {
                pawn.Pawn.story.hairColor = record.hairColor;
            }

            if (record.melanin >= 0.0f)
            {
                pawn.MelaninLevel = record.melanin;
            }
            else
            {
                pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor);
            }

            Backstory backstory = FindBackstory(record.childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            else
            {
                Logger.Warning("Could not load childhood backstory definition \"" + record.childhood + "\"");
                partialFailure = true;
            }
            if (record.adulthood != null)
            {
                backstory = FindBackstory(record.adulthood);
                if (backstory != null)
                {
                    pawn.Adulthood = backstory;
                }
                else
                {
                    Logger.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\"");
                    partialFailure = true;
                }
            }

            BodyTypeDef bodyType = null;

            try {
                bodyType = DefDatabase <BodyTypeDef> .GetNamedSilentFail(record.bodyType);
            }
            catch (Exception) {
            }
            if (bodyType == null)
            {
                if (pawn.Adulthood != null)
                {
                    bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender);
                }
                else
                {
                    bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender);
                }
            }
            if (bodyType != null)
            {
                pawn.BodyType = bodyType;
            }

            // Load pawn comps
            //Logger.Debug("pre-copy comps xml: " + record.compsXml);
            String compsXml = "<saveable Class=\"" + typeof(PawnCompsLoader).FullName + "\">" + record.compsXml + "</saveable>";
            PawnCompInclusionRules rules = new PawnCompInclusionRules();

            rules.IncludeComps(record.savedComps);
            UtilityCopy.DeserializeExposable <PawnCompsLoader>(compsXml, new object[] { pawn.Pawn, rules });
            Dictionary <string, ThingComp> compLookup = new Dictionary <string, ThingComp>();

            foreach (var c in pawn.Pawn.AllComps)
            {
                if (!compLookup.ContainsKey(c.GetType().FullName))
                {
                    //Logger.Debug("Added comp to comp lookup with key: " + c.GetType().FullName);
                    compLookup.Add(c.GetType().FullName, c);
                }
            }
            HashSet <string> savedComps = record.savedComps != null ? new HashSet <string>(record.savedComps) : new HashSet <string>();

            DefaultPawnCompRules.PostLoadModifiers.Apply(pawn.Pawn, compLookup, savedComps);

            pawn.ClearTraits();
            if (record.traits != null)
            {
                for (int i = 0; i < record.traits.Count; i++)
                {
                    string traitName = record.traits[i].def;
                    Trait  trait     = FindTrait(traitName, record.traits[i].degree);
                    if (trait != null)
                    {
                        pawn.AddTrait(trait);
                    }
                    else
                    {
                        Logger.Warning("Could not load trait definition \"" + traitName + "\"");
                        partialFailure = true;
                    }
                }
            }
            else if (record.traitNames != null && record.traitDegrees != null && record.traitNames.Count == record.traitDegrees.Count)
            {
                for (int i = 0; i < record.traitNames.Count; i++)
                {
                    string traitName = record.traitNames[i];
                    Trait  trait     = FindTrait(traitName, record.traitDegrees[i]);
                    if (trait != null)
                    {
                        pawn.AddTrait(trait);
                    }
                    else
                    {
                        Logger.Warning("Could not load trait definition \"" + traitName + "\"");
                        partialFailure = true;
                    }
                }
            }

            foreach (var skill in record.skills)
            {
                SkillDef def = FindSkillDef(pawn.Pawn, skill.name);
                if (def == null)
                {
                    Logger.Warning("Could not load skill definition \"" + skill.name + "\" from saved preset");
                    partialFailure = true;
                    continue;
                }
                pawn.currentPassions[def]  = skill.passion;
                pawn.originalPassions[def] = skill.passion;
                pawn.SetOriginalSkillLevel(def, skill.value);
                pawn.SetUnmodifiedSkillLevel(def, skill.value);
            }

            foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn))
            {
                if (layer.Apparel)
                {
                    pawn.SetSelectedApparel(layer, null);
                    pawn.SetSelectedStuff(layer, null);
                }
            }
            List <PawnLayer> apparelLayers = PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn).FindAll((layer) => { return(layer.Apparel); });

            foreach (var apparelRecord in record.apparel)
            {
                // Find the pawn layer for the saved apparel record.
                PawnLayer layer = apparelLayers.FirstOrDefault((apparelLayer) => { return(apparelLayer.Name == apparelRecord.layer); });
                if (layer == null)
                {
                    Logger.Warning("Could not find a matching pawn layer for the saved apparel \"" + apparelRecord.layer + "\"");
                    partialFailure = true;
                    continue;
                }
                if (apparelRecord.apparel.NullOrEmpty())
                {
                    Logger.Warning("Saved apparel entry for layer \"" + apparelRecord.layer + "\" had an empty apparel def");
                    partialFailure = true;
                    continue;
                }
                // Set the defaults.
                pawn.SetSelectedApparel(layer, null);
                pawn.SetSelectedStuff(layer, null);
                pawn.SetColor(layer, Color.white);

                ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.apparel);

                if (def == null)
                {
                    Logger.Warning("Could not load thing definition for apparel \"" + apparelRecord.apparel + "\"");
                    partialFailure = true;
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(apparelRecord.stuff))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.stuff);

                    if (stuffDef == null)
                    {
                        Logger.Warning("Could not load stuff definition \"" + apparelRecord.stuff + "\" for apparel \"" + apparelRecord.apparel + "\"");
                        partialFailure = true;
                        continue;
                    }
                }
                pawn.SetSelectedApparel(layer, def);
                pawn.SetSelectedStuff(layer, stuffDef);
                pawn.SetColor(layer, apparelRecord.color);
            }

            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            for (int i = 0; i < record.implants.Count; i++)
            {
                SaveRecordImplantV3 implantRecord  = record.implants[i];
                UniqueBodyPart      uniqueBodyPart = healthOptions.FindBodyPartByName(implantRecord.bodyPart, implantRecord.bodyPartIndex != null ? implantRecord.bodyPartIndex.Value : 0);
                if (uniqueBodyPart == null)
                {
                    uniqueBodyPart = FindReplacementBodyPart(healthOptions, implantRecord.bodyPart);
                }
                if (uniqueBodyPart == null)
                {
                    Logger.Warning("Could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\""
                                   + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : ""));
                    partialFailure = true;
                    continue;
                }
                BodyPartRecord bodyPart = uniqueBodyPart.Record;
                if (implantRecord.recipe != null)
                {
                    RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe);
                    if (recipeDef == null)
                    {
                        Logger.Warning("Could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\"");
                        partialFailure = true;
                        continue;
                    }
                    bool found = false;
                    foreach (var p in recipeDef.appliedOnFixedBodyParts)
                    {
                        if (p.defName.Equals(bodyPart.def.defName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Logger.Warning("Could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\".  Recipe does not support that part.");
                        partialFailure = true;
                        continue;
                    }
                    Implant implant = new Implant();
                    implant.BodyPartRecord = bodyPart;
                    implant.recipe         = recipeDef;
                    implant.label          = implant.Label;
                    pawn.AddImplant(implant);
                }
            }

            foreach (var injuryRecord in record.injuries)
            {
                HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef);

                if (def == null)
                {
                    Logger.Warning("Could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\"");
                    partialFailure = true;
                    continue;
                }
                InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def);
                if (option == null)
                {
                    Logger.Warning("Could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\"");
                    partialFailure = true;
                    continue;
                }
                BodyPartRecord bodyPart = null;
                if (injuryRecord.bodyPart != null)
                {
                    UniqueBodyPart uniquePart = healthOptions.FindBodyPartByName(injuryRecord.bodyPart,
                                                                                 injuryRecord.bodyPartIndex != null ? injuryRecord.bodyPartIndex.Value : 0);
                    if (uniquePart == null)
                    {
                        uniquePart = FindReplacementBodyPart(healthOptions, injuryRecord.bodyPart);
                    }
                    if (uniquePart == null)
                    {
                        Logger.Warning("Could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\""
                                       + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : ""));
                        partialFailure = true;
                        continue;
                    }
                    bodyPart = uniquePart.Record;
                }
                Injury injury = new Injury();
                injury.Option         = option;
                injury.BodyPartRecord = bodyPart;
                if (injuryRecord.severity != null)
                {
                    injury.Severity = injuryRecord.Severity;
                }
                if (injuryRecord.painFactor != null)
                {
                    injury.PainFactor = injuryRecord.PainFactor;
                }
                pawn.AddInjury(injury);
            }

            pawn.CopySkillsAndPassionsToPawn();
            pawn.ClearPawnCaches();

            return(pawn);
        }
예제 #14
0
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = pawn.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        newPawn = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.validSummoning = true;
                        newPawn.Spawner        = this.Caster;
                        newPawn.Temporary      = true;
                        newPawn.TicksToDestroy = this.duration;
                        //if (newPawn.Faction != Faction.OfPlayerSilentFail)
                        //{
                        //    newPawn.SetFaction(this.Caster.Faction, null);
                        //}
                        //newPawn.playerSettings.master = this.Caster;
                        if (comp.summonedMinions.Count >= 4)
                        {
                            Thing dismissMinion = comp.summonedMinions.First();
                            if (dismissMinion != null && dismissMinion.Position.IsValid)
                            {
                                MoteMaker.ThrowSmoke(dismissMinion.Position.ToVector3(), base.Map, 1);
                                MoteMaker.ThrowHeatGlow(dismissMinion.Position, base.Map, 1);
                            }
                            comp.summonedMinions.Remove(comp.summonedMinions.First());
                            if (!dismissMinion.Destroyed)
                            {
                                dismissMinion.Destroy();
                                Messages.Message("TM_SummonedCreatureLimitExceeded".Translate(
                                                     this.launcher.LabelShort
                                                     ), MessageTypeDefOf.NeutralEvent);
                            }
                            if (comp.summonedMinions.Count > 4)
                            {
                                while (comp.summonedMinions.Count > 4)
                                {
                                    Pawn excessMinion = comp.summonedMinions.First() as Pawn;
                                    comp.summonedMinions.Remove(excessMinion);
                                    if (excessMinion != null && !excessMinion.Dead && !excessMinion.Destroyed)
                                    {
                                        excessMinion.Destroy();
                                    }
                                }
                            }
                        }
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, this.Map);
                        }
                        catch
                        {
                            this.age            = this.duration;
                            comp.Mana.CurLevel += comp.ActualManaCost(TorannMagicDefOf.TM_SummonMinion);
                            Log.Message("TM_Exception".Translate(
                                            pawn.LabelShort,
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }

                        comp.summonedMinions.Add(newPawn);
                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            Lord lord = null;
                            if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                            {
                                Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                lord = p2.GetLord();
                            }
                            bool flag4 = lord == null;
                            if (flag4)
                            {
                                LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                lord = LordMaker.MakeNewLord(faction, lordJob, this.Map, null);
                            }
                            else
                            {
                                try
                                {
                                    //PawnDuty duty = this.pawn.mindState.duty;
                                    //newPawn.mindState.duty = duty;
                                    newPawn.mindState.duty = new PawnDuty(DutyDefOf.Defend);
                                }
                                catch
                                {
                                    Log.Message("error attempting to assign a duty to minion");
                                }
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
 // Token: 0x06002627 RID: 9767 RVA: 0x00122210 File Offset: 0x00120610
 public override void Tick()
 {
     if (base.Spawned)
     {
         HiveLike hive = (HiveLike)ThingMaker.MakeThing(hiveDef, null);
         this.sustainer.Maintain();
         Vector3 vector = base.Position.ToVector3Shifted();
         ResetStaticData();
         if (Rand.MTBEventOccurs(FilthSpawnMTB, 1f, 1.TicksToSeconds()) && CellFinder.TryFindRandomReachableCellNear(base.Position, base.Map, TunnelHiveLikeSpawner.FilthSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), null, null, out IntVec3 c, 999999))
         {
             FilthMaker.MakeFilth(c, base.Map, filthTypes.RandomElement <ThingDef>(), 1);
         }
         if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 1f, 1.TicksToSeconds()))
         {
             MoteMaker.ThrowDustPuffThick(new Vector3(vector.x, 0f, vector.z)
             {
                 y = AltitudeLayer.MoteOverhead.AltitudeFor()
             }, base.Map, Rand.Range(1.5f, 3f), new Color(1f, 1f, 1f, 2.5f));
         }
         if (this.secondarySpawnTick <= Find.TickManager.TicksGame)
         {
             this.sustainer.End();
             Map     map      = base.Map;
             IntVec3 position = base.Position;
             this.Destroy(DestroyMode.Vanish);
             if (this.spawnHive)
             {
                 if (Def.strikespreexplode)
                 {
                     FireEvent(map, position);
                     EventDraw(map, position);
                 }
                 if (Def.explodesprespawn)
                 {
                     GenExplosion.DoExplosion(position, map, Def.blastradius, Def.damageDef, null, -1, -1f, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false);
                 }
                 hive = (HiveLike)GenSpawn.Spawn(ThingMaker.MakeThing(hiveDef, null), position, map, WipeMode.Vanish);
                 hive.SetFaction(faction, null);
                 foreach (CompSpawnerLike compSpawner in hive.GetComps <CompSpawnerLike>())
                 {
                     if (compSpawner.PropsSpawner.thingToSpawn == ThingDefOf.InsectJelly)
                     {
                         compSpawner.TryDoSpawn();
                         break;
                     }
                 }
             }
             if (this.hivePoints > 0f)
             {
                 this.hivePoints = Mathf.Max(this.hivePoints, pawnKinds.Min((PawnKindDef x) => x.combatPower));
                 float       pointsLeft = this.hivePoints;
                 List <Pawn> list       = new List <Pawn>();
                 int         num        = 0;
                 while (pointsLeft > 0f)
                 {
                     num++;
                     if (num > 1000)
                     {
                         //    Log.Error("Too many iterations.", false);
                         break;
                     }
                     IEnumerable <PawnKindDef> source = from x in pawnKinds
                                                        where x.combatPower <= pointsLeft
                                                        select x;
                     if (!source.TryRandomElement(out PawnKindDef pawnKindDef))
                     {
                         break;
                     }
                     Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction);
                     GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(position, map, 2, null), map, WipeMode.Vanish);
                     pawn.mindState.spawnedByInfestationThingComp = this.spawnedByInfestationThingComp;
                     list.Add(pawn);
                     pointsLeft -= pawnKindDef.combatPower;
                 }
                 if (list.Any <Pawn>())
                 {
                     LordMaker.MakeNewLord(faction, new LordJob_AssaultColony(faction, true, false, false, false, true), map, list);
                 }
             }
         }
     }
 }
예제 #16
0
        public static bool generateMounts(ref List <Pawn> list, IncidentParms parms, int inBiomeWeight, int outBiomeWeight, int nonWildWeight, int mountChance, int mountChanceTribal)
        {
            Map map = parms.target as Map;

            if (map == null)
            {
                Caravan caravan = (Caravan)parms.target;
                int     tile    = caravan.Tile;
                map = Current.Game.FindMap(tile);
                if (map == null)
                {
                    return(false);
                }
            }

            Predicate <PawnKindDef> isAnimal = (PawnKindDef d) => d.race != null && d.race.race.Animal;

            mountChance = getMountChance(parms, mountChance, mountChanceTribal);
            if (mountChance == -1)//wrong faction
            {
                return(false);
            }
            List <string> factionFarmAnimalRestrictions = new List <string>();
            List <string> factionWildAnimalRestrictions = new List <string>();

            if (parms.faction.def.HasModExtension <FactionRestrictionsPatch>())
            {
                FactionRestrictionsPatch factionRestrictions = parms.faction.def.GetModExtension <FactionRestrictionsPatch>();
                factionFarmAnimalRestrictions = factionRestrictions.getAllowedNonWildAnimalsAsList();
                factionWildAnimalRestrictions = factionRestrictions.getAllowedWildAnimalsAsList();

                if (factionRestrictions.mountChance > -1)
                {
                    mountChance = factionRestrictions.mountChance;
                }

                if (!factionWildAnimalRestrictions.NullOrEmpty() && factionFarmAnimalRestrictions.NullOrEmpty() && factionRestrictions.wildAnimalWeight >= 0)
                {
                    inBiomeWeight  = 0;
                    nonWildWeight  = 0;
                    outBiomeWeight = factionRestrictions.wildAnimalWeight;
                }
                if (factionWildAnimalRestrictions.NullOrEmpty() && !factionFarmAnimalRestrictions.NullOrEmpty() && factionRestrictions.nonWildAnimalWeight >= 0)
                {
                    inBiomeWeight  = 0;
                    outBiomeWeight = 0;
                    nonWildWeight  = factionRestrictions.nonWildAnimalWeight;
                }
                if (!factionWildAnimalRestrictions.NullOrEmpty() && !factionFarmAnimalRestrictions.NullOrEmpty())
                {
                    inBiomeWeight = 0;
                    if (factionRestrictions.wildAnimalWeight >= 0)
                    {
                        outBiomeWeight = factionRestrictions.wildAnimalWeight;
                    }
                    if (factionRestrictions.nonWildAnimalWeight >= 0)
                    {
                        nonWildWeight = factionRestrictions.nonWildAnimalWeight;
                    }
                }
            }

            int   totalWeight              = inBiomeWeight + outBiomeWeight + nonWildWeight;
            float inBiomeWeightNormalized  = (float)inBiomeWeight / (float)totalWeight * 100f;
            float outBiomeWeightNormalized = (float)outBiomeWeight / (float)totalWeight * 100f;

            List <Pawn> animals = new List <Pawn>();

            foreach (Pawn pawn in list)
            {
                //TODO add chance
                PawnKindDef pawnKindDef = null;



                if (!pawn.RaceProps.Humanlike || pawn.kindDef == PawnKindDefOf.Slave)
                {
                    continue;
                }

                //changing from System.Random to Verse.Rand for better multiplayer compatibility
                int rndInt = Rand.Range(1, 100);

                if (pawn.kindDef.HasModExtension <CustomMountsPatch>())
                {
                    CustomMountsPatch modExtension = pawn.kindDef.GetModExtension <CustomMountsPatch>();
                    if (modExtension.mountChance <= rndInt)
                    {
                        continue;
                    }

                    bool found = modExtension.possibleMounts.TryRandomElementByWeight((KeyValuePair <String, int> mount) => mount.Value, out KeyValuePair <String, int> selectedMount);
                    if (found)
                    {
                        pawnKindDef = DefDatabase <PawnKindDef> .GetNamed(selectedMount.Key);
                    }
                }
                else
                {
                    if (mountChance <= rndInt || !pawn.RaceProps.Humanlike)
                    {
                        continue;
                    }
                    int pawnHandlingLevel = pawn.skills.GetSkill(SkillDefOf.Animals).Level;

                    pawnKindDef = determinePawnKind(map, isAnimal, inBiomeWeightNormalized, outBiomeWeightNormalized, rndInt, pawnHandlingLevel, factionFarmAnimalRestrictions, factionWildAnimalRestrictions, parms);
                }
                if (pawnKindDef == null)
                {
                    return(false);
                }
                Pawn animal = PawnGenerator.GeneratePawn(pawnKindDef, parms.faction);
                GenSpawn.Spawn(animal, pawn.Position, map, parms.spawnRotation);
                ConfigureSpawnedAnimal(pawn, ref animal);
                animals.Add(animal);
            }
            list = list.Concat(animals).ToList();
            return(true);
        }
        private Pawn MakePawnWithRawXml(string xml)
        {
            try {
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                //Debug.Message("Pawn xml: {0}", xml);
                XmlNode root = document.FirstChild;

                string      pawnKind = root.SelectSingleNode("kind").InnerText;
                PawnKindDef kindDef  = PawnKindDef.Named(pawnKind);
                if (kindDef == null)
                {
                    kindDef = PawnKindDefOf.AncientSoldier;
                }

                Pawn p = PawnGenerator.GeneratePawn(kindDef, rp.faction);

                // ==== NAME AND AGE ====
                Name name      = null;
                var  nameNode  = root.SelectSingleNode("name");
                var  attrFirst = nameNode.Attributes.GetNamedItem("first");
                var  attrLast  = nameNode.Attributes.GetNamedItem("last");
                var  attrNick  = nameNode.Attributes.GetNamedItem("nick");
                if (attrFirst != null && attrLast != null)
                {
                    name = new NameTriple(attrFirst.Value, attrNick?.Value ?? "", attrLast.Value);
                }
                else
                {
                    name = new NameSingle(attrFirst?.Value ?? "Unknown");
                }
                p.Name = name;
                //Debug.Message("got name");

                string gender = root.SelectSingleNode("gender")?.InnerText;
                if (gender == "Male")
                {
                    p.gender = Gender.Male;
                }
                else if (gender == "Female")
                {
                    p.gender = Gender.Female;
                }

                string bioAgeString    = root.SelectSingleNode("biologicalAge")?.InnerText;
                string chronoAgeString = root.SelectSingleNode("chronologicalAge")?.InnerText;
                if (bioAgeString != null && chronoAgeString != null)
                {
                    long result = 0;
                    Int64.TryParse(bioAgeString, out result);
                    p.ageTracker.AgeBiologicalTicks = result;
                    Int64.TryParse(chronoAgeString, out result);
                    p.ageTracker.AgeChronologicalTicks = result + 3600000 * (-blueprint.dateShift); //+dateShift for dates, -dateShift for ages
                }
                //Debug.Message("got age");


                // ==== STORY AND APPEARANCE ====
                var storyNode = root.SelectSingleNode("saveable[@Class='Pawn_StoryTracker']");
                if (storyNode != null)
                {
                    Backstory bs           = null;
                    string    childhoodDef = storyNode.SelectSingleNode("childhood")?.InnerText;
                    if (BackstoryDatabase.TryGetWithIdentifier(childhoodDef, out bs))
                    {
                        p.story.childhood = bs;
                    }
                    string adulthoodDef = storyNode.SelectSingleNode("adulthood")?.InnerText;
                    if (BackstoryDatabase.TryGetWithIdentifier(adulthoodDef, out bs))
                    {
                        p.story.adulthood = bs;
                    }

                    string bodyTypeDefName = storyNode.SelectSingleNode("bodyType")?.InnerText;
                    if (bodyTypeDefName != null)
                    {
                        BodyTypeDef def = DefDatabase <BodyTypeDef> .GetNamedSilentFail(bodyTypeDefName);

                        if (def != null)
                        {
                            p.story.bodyType = def;
                        }

                        try {
                            string crownTypeName = storyNode.SelectSingleNode("crownType")?.InnerText;
                            p.story.crownType = (CrownType)Enum.Parse(typeof(CrownType), crownTypeName);
                        } catch (Exception) { }

                        string  hairDefName = storyNode.SelectSingleNode("hairDef")?.InnerText;
                        HairDef hairDef     = DefDatabase <HairDef> .GetNamedSilentFail(hairDefName);

                        if (hairDef != null)
                        {
                            p.story.hairDef = hairDef;
                        }

                        float melanin = 0;
                        if (float.TryParse(storyNode.SelectSingleNode("melanin")?.InnerText, out melanin))
                        {
                            p.story.melanin = melanin;
                        }

                        string hairColorString = storyNode.SelectSingleNode("hairColor")?.InnerText;
                        Color  hairColor       = (Color)ParseHelper.FromString(hairColorString, typeof(Color));
                        if (hairColor != null)
                        {
                            p.story.hairColor = hairColor;
                        }
                    }
                    XmlNodeList traitsList = storyNode.SelectNodes("traits/allTraits/li");
                    if (traitsList != null)
                    {
                        p.story.traits.allTraits.RemoveAll(_ => true);
                        foreach (XmlNode traitNode in traitsList)
                        {
                            string traitDefName = traitNode.SelectSingleNode("def")?.InnerText;
                            int    traitDegree  = 0;
                            int.TryParse(traitNode.SelectSingleNode("degree")?.InnerText, out traitDegree);

                            TraitDef traitDef = DefDatabase <TraitDef> .GetNamedSilentFail(traitDefName);

                            if (traitDef == null)
                            {
                                continue;
                            }

                            Trait t = new Trait(traitDef, traitDegree);
                            if (t == null)
                            {
                                continue;
                            }

                            p.story.traits.allTraits.Add(t);
                        }
                    }
                }

                // ==== SKILLS ====
                var skills = root.SelectSingleNode("saveable[@Class='Pawn_SkillTracker']");
                if (skills != null)
                {
                    XmlNodeList skillsList = storyNode.SelectNodes("skills/li");

                    foreach (XmlNode skillNode in skillsList)
                    {
                        string skillDefName = skillNode.SelectSingleNode("def")?.InnerText;
                        int    level        = 0;
                        int.TryParse(skillNode.SelectSingleNode("level")?.InnerText, out level);

                        float xp = 0;
                        float.TryParse(skillNode.SelectSingleNode("xpSinceLastLevel")?.InnerText, out xp);

                        SkillDef skillDef = DefDatabase <SkillDef> .GetNamedSilentFail(skillDefName);

                        if (skillDef == null)
                        {
                            continue;
                        }

                        SkillRecord skillRecord = p.skills.GetSkill(skillDef);
                        if (skillRecord == null)
                        {
                            skillRecord = new SkillRecord(p, skillDef);
                        }

                        skillRecord.Level            = level;
                        skillRecord.xpSinceLastLevel = xp;

                        try {
                            string passionTypeName = skillNode.SelectSingleNode("passion")?.InnerText;
                            if (passionTypeName != null)
                            {
                                skillRecord.passion = (Passion)Enum.Parse(typeof(Passion), passionTypeName);
                            }
                        } catch (Exception) { }
                    }
                }
                //Debug.Message("got traits and skills");

                // ==== HEALTH ====
                var healthNode = root.SelectSingleNode("saveable[@Class='Pawn_HealthTracker']");
                if (healthNode != null)
                {
                    XmlNode healthState = healthNode.SelectSingleNode("healthState");
                    if (healthState?.InnerText == "Dead")
                    {
                        p.health.SetDead();
                    }

                    XmlNodeList hediffsList = healthNode.SelectNodes("hediffSet/hediffs/li");
                    if (hediffsList != null)
                    {
                        Scribe.mode = LoadSaveMode.LoadingVars;
                        p.health?.hediffSet?.hediffs?.RemoveAll(_ => true);
                        //probably should pre-analyze hediffs prior to instantiating
                        foreach (XmlNode hediffNode in hediffsList)
                        {
                            var sourceNode = hediffNode.SelectSingleNode("source");
                            var source     = sourceNode?.InnerText;
                            //Debug.Message("Source is {0} in hediff {1}", source, hediffNode.OuterXml);
                            if (source != null)
                            {
                                ThingDef sourceThingDef = DefDatabase <ThingDef> .GetNamedSilentFail(source);

                                //Debug.Message("Found non-null source node: {0}. Def: {1}", sourceNode.OuterXml, sourceThingDef);
                                if (sourceThingDef == null)
                                {
                                    hediffNode.RemoveChild(sourceNode);
                                    //Debug.Message("def not found, removing node, result: {0}", hediffNode.OuterXml);
                                    //continue; //skip hediffs with unknown source
                                    //} else {
                                    //Debug.Message("def found: {0}", sourceThingDef);
                                }
                            }
                            try {
                                Hediff hediff = ScribeExtractor.SaveableFromNode <Hediff>(hediffNode, null);
                                if (hediff != null)
                                {
                                    if (hediff.source != null && hediff.Part != null)
                                    {
                                        p.health.AddHediff(hediff);
                                    }
                                }
                            } catch (Exception) {
                            }
                        }
                        Scribe.mode = LoadSaveMode.Inactive;
                    }
                }
                //Debug.Message("got health");

                // ==== APPAREL ====
                var apparelNode = root.SelectSingleNode("apparel");
                if (apparelNode != null)
                {
                    XmlNodeList apparelList = apparelNode.SelectNodes("item");
                    foreach (XmlNode item in apparelList)
                    {
                        string defName      = item.Attributes?.GetNamedItem("def")?.Value;
                        string stuffDefName = item.Attributes?.GetNamedItem("stuffDef")?.Value;

                        ThingDef stuffDef = null;
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(defName);

                        if (stuffDefName != null)
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(stuffDefName);
                        }

                        if (thingDef != null)
                        {
                            Apparel apparel = (Apparel)ThingMaker.MakeThing(thingDef, stuffDef);
                            apparel.HitPoints = Rand.Range(1, (int)(apparel.MaxHitPoints * 0.6));
                            if (apparel is Apparel)
                            {
                                p.apparel.Wear(apparel, false);
                            }
                        }
                    }
                }
                return(p);
            } catch (Exception e) {
                //Debug.Message("Exception while creating pawn: {0}", e);
                return(PawnGenerator.GeneratePawn(PawnKindDefOf.AncientSoldier, rp.faction));
            }
        }
        // Token: 0x06000020 RID: 32 RVA: 0x0000440C File Offset: 0x0000260C
        private void TrySetCellAs(IntVec3 c, ThingDef thingDef, Rot4 thingRot, Map map, ThingDef stuffDef = null,
                                  TerrainDef terrainDef = null, PawnKindDef pawnKindDef = null, ThingDef itemDef = null,
                                  MapGeneratorBlueprintDef blueprint = null)
        {
            if (!c.InBounds(map))
            {
                Log.Warning("GenStep_CreateBlueprint: Invalid Target-Cell: cell is null or out of bounds.");
            }
            else
            {
                var thingList = c.GetThingList(map);
                foreach (var thing in thingList)
                {
                    if (!thing.def.destroyable)
                    {
                        return;
                    }
                }

                if (terrainDef != null)
                {
                    map.terrainGrid.SetTerrain(c, terrainDef);
                }
                else
                {
                    if (thingDef != null && stuffDef != null)
                    {
                        map.terrainGrid.SetTerrain(c, CorrespondingTileDef(stuffDef));
                    }
                }

                if (thingDef != null)
                {
                    var stuff = stuffDef;
                    if (!thingDef.MadeFromStuff)
                    {
                        stuff = null;
                    }

                    var thing = ThingMaker.MakeThing(thingDef, stuff);
                    if (thingRot == Rot4.Invalid)
                    {
                        GenSpawn.Spawn(thing, c, map);
                    }
                    else
                    {
                        GenSpawn.Spawn(thing, c, map, thingRot);
                    }
                }

                if (blueprint == null)
                {
                    return;
                }

                if (itemDef != null && blueprint.itemSpawnChance / 100f > Rand.Value)
                {
                    var source = new List <string>
                    {
                        "Steel",
                        "Steel"
                    };
                    var stuffDef2 = DefDatabase <ThingDef> .GetNamedSilentFail(source.RandomElement());

                    if (!itemDef.MadeFromStuff)
                    {
                        stuffDef2 = null;
                    }

                    var thing2 = TryGetTreasure(itemDef, stuffDef2);
                    thing2 = GenSpawn.Spawn(thing2, c, map);
                    thing2.SetForbidden(true);
                }

                if (pawnKindDef == null || !(blueprint.pawnSpawnChance / 100f > Rand.Value))
                {
                    return;
                }

                if (faction == null)
                {
                    faction = Find.FactionManager.FirstFactionOfDef(blueprint.factionDef);
                }

                if (faction == null)
                {
                    switch (blueprint.factionSelection)
                    {
                    case FactionSelection.none:
                    {
                        faction = Find.FactionManager.AllFactions.RandomElementByWeight(fac =>
                                                                                        fac.def.settlementGenerationWeight);
                        if (faction == null)
                        {
                            faction = Faction.OfMechanoids;
                        }

                        break;
                    }

                    case FactionSelection.hostile:
                    {
                        faction = (from fac in Find.FactionManager.AllFactions
                                   where fac.HostileTo(Faction.OfPlayer)
                                   select fac).RandomElementByWeight(fac =>
                                                                     101f - fac.def.settlementGenerationWeight);
                        if (faction == null)
                        {
                            faction = Faction.OfMechanoids;
                        }

                        break;
                    }

                    case FactionSelection.friendly:
                    {
                        faction = (from fac in Find.FactionManager.AllFactions
                                   where !fac.HostileTo(Faction.OfPlayer) && fac.PlayerGoodwill > 0f &&
                                   fac != Faction.OfPlayer
                                   select fac).RandomElementByWeight(fac =>
                                                                     101f - fac.def.settlementGenerationWeight);
                        if (faction == null)
                        {
                            faction = Find.FactionManager.AllFactions.RandomElementByWeight(fac =>
                                                                                            fac.def.settlementGenerationWeight);
                        }

                        break;
                    }
                    }
                }

                var pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction);
                pawn.mindState.Active = false;
                pawn = GenSpawn.Spawn(pawn, c, map) as Pawn;
                if (pawn == null)
                {
                    return;
                }

                if (allSpawnedPawns == null)
                {
                    allSpawnedPawns = new List <Pawn>();
                }

                allSpawnedPawns.Add(pawn);
            }
        }
            public static void Listener(PawnGenerationRequest request, ref Pawn __result)
            {
                try {
                    bool isAndroidTier = __result.IsAndroidTier();

                    //Pas d'application de filtrage de creation d'androide si le mode est playerStarter avec le pawnkindDef de base du scenario de AT
                    if (!(request.Context == PawnGenerationContext.PlayerStarter && Utils.ExceptionPlayerStartingAndroidPawnKindList.Contains(request.KindDef.defName)))
                    {
                        //Vire chance generation android
                        if (Settings.androidsAreRare &&
                            __result.IsAndroidTier() &&
                            ((Current.ProgramState == ProgramState.Entry) || (Current.ProgramState == ProgramState.Playing && request.Faction != Faction.OfPlayer)) &&
                            Rand.Chance(0.95f))
                        {
                            PawnGenerationRequest r = new PawnGenerationRequest(PawnKindDefOf.AncientSoldier, request.Faction, request.Context, request.Tile, request.ForceGenerateNewPawn, request.Newborn,
                                                                                request.AllowDead, request.AllowDowned, request.CanGeneratePawnRelations, request.MustBeCapableOfViolence, request.ColonistRelationChanceFactor,
                                                                                request.ForceAddFreeWarmLayerIfNeeded, request.AllowGay, request.AllowFood, request.AllowAddictions, request.Inhabitant, request.CertainlyBeenInCryptosleep,
                                                                                request.ForceRedressWorldPawnIfFormerColonist, request.WorldPawnFactionDoesntMatter, request.BiocodeWeaponChance, request.ExtraPawnForExtraRelationChance,
                                                                                request.RelationWithExtraPawnChanceFactor, request.ValidatorPreGear, request.ValidatorPostGear, request.ForcedTraits, request.ProhibitedTraits, request.MinChanceToRedressWorldPawn, request.FixedBiologicalAge, request.FixedChronologicalAge, request.FixedGender, request.FixedMelanin, request.FixedLastName, request.FixedBirthName, request.FixedTitle);

                            __result = PawnGenerator.GeneratePawn(r);
                        }
                    }

                    //Remove illogiocal traits with androids
                    if (isAndroidTier)
                    {
                        if (__result.gender == Gender.Male)
                        {
                            BodyTypeDef bd = DefDatabase <BodyTypeDef> .GetNamed("Male", false);

                            if (bd != null)
                            {
                                __result.story.bodyType = bd;
                            }
                        }
                        else
                        {
                            BodyTypeDef bd = DefDatabase <BodyTypeDef> .GetNamed("Female", false);

                            if (bd != null)
                            {
                                __result.story.bodyType = bd;
                            }
                        }


                        bool isAndroidWithSkin = Utils.ExceptionAndroidWithSkinList.Contains(__result.def.defName);

                        if (isAndroidWithSkin)
                        {
                            //force not damaged face for skinned androids
                            Utils.changeHARCrownType(__result, "Average_Normal");

                            if (Utils.RIMMSQOL_LOADED && Utils.lastResolveAllGraphicsHeadGraphicPath != null)
                            {
                                __result.story.GetType().GetField("headGraphicPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(__result.story, Utils.lastResolveAllGraphicsHeadGraphicPath);
                                Utils.lastResolveAllGraphicsHeadGraphicPath = null;
                            }
                        }

                        Utils.removeMindBlacklistedTrait(__result);
                        //Chance that android can be painted (skinned androids excluded)
                        if (!isAndroidWithSkin && Rand.Chance(Settings.chanceGeneratedAndroidCanBePaintedOrRust))
                        {
                            CompAndroidState cas = __result.ATCompState;
                            if (cas != null)
                            {
                                if (Utils.forceGeneratedAndroidToBeDefaultPainted)
                                {
                                    cas.paintingIsRusted = false;
                                    cas.paintingRustGT   = (Rand.Range(Settings.minDaysAndroidPaintingCanRust, Settings.maxDaysAndroidPaintingCanRust) * 60000);
                                    cas.customColor      = (int)AndroidPaintColor.Default;
                                }
                                else
                                {
                                    if (Settings.androidsCanRust && Rand.Chance(0.35f))
                                    {
                                        cas.setRusted();
                                    }
                                    else
                                    {
                                        cas.customColor = Rand.Range((int)AndroidPaintColor.Black, ((int)AndroidPaintColor.Khaki) + 1);
                                    }
                                }
                            }
                        }
                    }

                    //Prevent generation M7/T5 dans ecran style EBDPrep carefully
                    if (Settings.preventM7T5AppearingInCharacterScreen && Current.ProgramState == ProgramState.Entry)
                    {
                        if (__result.def.defName == Utils.T5)
                        {
                            PawnGenerationRequest r = new PawnGenerationRequest(Utils.AndroidsPKDNeutral.RandomElement(), request.Faction, request.Context, request.Tile, request.ForceGenerateNewPawn, request.Newborn,
                                                                                request.AllowDead, request.AllowDowned, request.CanGeneratePawnRelations, request.MustBeCapableOfViolence, request.ColonistRelationChanceFactor,
                                                                                request.ForceAddFreeWarmLayerIfNeeded, request.AllowGay, request.AllowFood, request.AllowAddictions, request.Inhabitant, request.CertainlyBeenInCryptosleep,
                                                                                request.ForceRedressWorldPawnIfFormerColonist, request.WorldPawnFactionDoesntMatter, request.BiocodeWeaponChance, request.ExtraPawnForExtraRelationChance,
                                                                                request.RelationWithExtraPawnChanceFactor, request.ValidatorPreGear, request.ValidatorPostGear, request.ForcedTraits, request.ProhibitedTraits, request.MinChanceToRedressWorldPawn, request.FixedBiologicalAge, request.FixedChronologicalAge, request.FixedGender, request.FixedMelanin, request.FixedLastName, request.FixedBirthName, request.FixedTitle);

                            __result = PawnGenerator.GeneratePawn(r);
                        }
                    }

                    if (!Settings.notRemoveAllSkillPassionsForBasicAndroids)
                    {
                        //Si T1/T2
                        if (__result.IsBasicAndroidTier() && __result.def.defName != "M7Mech" && __result.skills != null && __result.skills.skills != null)
                        {
                            foreach (var sr in __result.skills.skills)
                            {
                                sr.passion = Passion.None;
                            }
                        }
                    }
                    if (!Settings.notRemoveAllTraitsFromT1T2)
                    {
                        //Si T1/T2
                        if (__result.IsBasicAndroidTier() && __result.def.defName != "M7Mech")
                        {
                            Utils.removeAllTraits(__result);
                        }
                    }

                    //Si GYNOID chargé changement sex android en fonction chance
                    if (Utils.ANDROIDTIERSGYNOID_LOADED &&
                        isAndroidTier &&
                        (__result.def.defName == Utils.T1 || __result.def.defName == Utils.T2 || __result.def.defName == Utils.T3 || __result.def.defName == Utils.T4) &&
                        Current.ProgramState == ProgramState.Playing && __result.Faction == Faction.OfPlayer)
                    {
                        if (Rand.Chance(Settings.percentageChanceMaleAndroidModel))
                        {
                            __result.gender         = Gender.Male;
                            __result.story.bodyType = BodyTypeDefOf.Male;
                        }
                        else
                        {
                            __result.gender         = Gender.Female;
                            __result.story.bodyType = BodyTypeDefOf.Female;
                        }
                    }

                    //Définiton des traits pour les androides générés a destination du player
                    if (Current.ProgramState == ProgramState.Playing && !Settings.basicAndroidsRandomSKills && __result.Faction == Faction.OfPlayer)
                    {
                        SkillRecord sr = null;

                        if (__result.def.defName == Utils.T1)
                        {
                            sr = __result.skills.GetSkill(SkillDefOf.Animals);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Animals;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Artistic);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Artistic;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Construction);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Construction;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Cooking);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Cooking;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Crafting);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Crafting;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Intellectual);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Intellectual;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Medicine);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Medical;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Melee);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Melee;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Mining);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Mining;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Plants);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Plants;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Shooting);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Shoot;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Social);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT1Social;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                        }
                        else if (__result.def.defName == Utils.T2)
                        {
                            sr = __result.skills.GetSkill(SkillDefOf.Animals);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Animals;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Artistic);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Artistic;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Construction);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Construction;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Cooking);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Cooking;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Crafting);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Crafting;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Intellectual);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Intellectual;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Medicine);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Medical;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Melee);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Melee;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Mining);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Mining;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Plants);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Plants;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Shooting);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Shoot;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                            sr = __result.skills.GetSkill(SkillDefOf.Social);
                            if (sr != null)
                            {
                                sr.levelInt         = Settings.defaultSkillT2Social;
                                sr.xpSinceLastLevel = 0;
                                sr.xpSinceMidnight  = 0;
                            }
                        }
                    }


                    //If TX3/4 then force not damaged head
                    if (__result.def.defName == Utils.TX3 || __result.def.defName == Utils.TX4)
                    {
                        Utils.changeHARCrownType(__result, "Average_Normal");

                        __result.Drawer.renderer.graphics.ResolveAllGraphics();
                    }
                }
                catch (Exception ex) {
                    Log.Message("[ATPP] PawnGenerator.GeneratePawn " + ex.Message + " " + ex.StackTrace);
                }
            }
예제 #20
0
        public override void Tick()
        {
            base.Tick();
            bool flag  = this.mutjustspawned;
            bool flag2 = flag;

            if (flag2)
            {
                bool flag3 = this.timer > 0f;
                bool flag4 = flag3;
                if (flag4)
                {
                    this.timer -= 1f;
                }
                bool flag5 = this.timer == 690f;
                bool flag6 = flag5;
                if (flag6)
                {
                    this.intVec = CellFinderLoose.RandomCellWith((IntVec3 sq) => GenGrid.Standable(sq, base.Map) && !base.Map.roofGrid.Roofed(sq) && !base.Map.fogGrid.IsFogged(sq) && !GenGrid.CloseToEdge(sq, base.Map, 20) && GenGrid.InBounds(this.intVec, base.Map) && !base.Map.areaManager.Home[sq], base.Map, 1000);
                    Faction faction = Find.FactionManager.RandomNonHostileFaction(false, false, true, TechLevel.Spacer);
                    this.Face = (this.newThing = PawnGenerator.GeneratePawn(new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, -1, true, false, false, false, true, false, 1f, true, true, true, false, false, false, false, false, 0f,
                                                                                                      null, 1f, null, null, null, null, null, null)));
                    this.Face.RaceProps.thinkTreeMain = DefDatabase <ThinkTreeDef> .GetNamed("HumanlikeTheThing");
                }
                bool flag7 = this.timer == 0f;
                bool flag8 = flag7;
                if (flag8)
                {
                    bool flag9  = !this.doOnce;
                    bool flag10 = flag9;
                    if (flag10)
                    {
                        DropPodUtility.MakeDropPodAt(this.intVec, base.Map, new ActiveDropPodInfo
                        {
                            SingleContainedThing = this.Face,
                            openDelay            = 180,
                            leaveSlag            = true
                        });
                        HealthUtility.DamageUntilDowned(this.Face);
                        string text  = Translator.Translate("LetterLabelRefugeePodCrash");
                        string text2 = "RefugeePodCrash".Translate(this.Face.Named("PAWN")).AdjustedFor(this.Face, "PAWN", true);
                        Find.LetterStack.ReceiveLetter(text, text2, LetterDefOf.NeutralEvent, new TargetInfo(this.intVec, base.Map, false), null);
                        this.doOnce = true;
                    }
                }
            }
            int num = this.timemut;

            this.timemut     = num - 1;
            num              = this.intervalcut;
            this.intervalcut = num - 1;
            bool flag11 = this.Face != null && !this.Face.InContainerEnclosed && RestUtility.InBed(this.Face) && !this.doononce;
            bool flag12 = flag11;

            if (flag12)
            {
                this.doononce = true;
            }
            bool flag13 = this.timemut == 0;
            bool flag14 = flag13;

            if (flag14)
            {
                bool flag15 = this.Face != null;
                bool flag16 = flag15;
                if (flag16)
                {
                    bool flag17 = !this.facemutated;
                    bool flag18 = flag17;
                    if (flag18)
                    {
                        bool flag19 = !this.Face.Dead;
                        bool flag20 = flag19;
                        if (flag20)
                        {
                            this.mutplace = this.Face.Position;
                            IntVec3  intVec = CellFinder.RandomClosewalkCellNear(this.mutplace, base.Map, 4);
                            ThingDef named  = DefDatabase <ThingDef> .GetNamed("Filth_Blood", true);

                            FilthMaker.TryMakeFilth(intVec, base.Map, named, 4);
                            IEnumerable <Faction> allFactions = Find.FactionManager.AllFactions;
                            bool flag21 = Ticker_RTWorker.rt.isPawn == null;
                            if (flag21)
                            {
                                Ticker_RTWorker.rt.isPawn = new Func <Faction, bool>(Ticker_RTWorker.rt.IncidentRT.whichFac);
                            }
                            PawnGenerationRequest request = new PawnGenerationRequest(MODefOf.MO_AbominationPawnKind, null, PawnGenerationContext.NonPlayer, -1, true, false, false, false, true, false, 1f, true, true, true, false, false, false, false, false, 0f,
                                                                                      null, 1f, null, null, null, null, null, null);
                            this.theThing = PawnGenerator.GeneratePawn(request);
                            this.theThing.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, true, false, null);
                            GenSpawn.Spawn(this.theThing, this.mutplace, base.Map);
                            Find.LetterStack.ReceiveLetter("MO_Trojan".Translate(), "MO_TrojanDesc".Translate(this.Face.LabelShort, this.Face.Named("PAWN")), LetterDefOf.ThreatBig, this.theThing, null); //this.Face.LabelShort + "has turned into an Abomination!"
                            bool flag22 = !this.Face.Destroyed;
                            bool flag23 = flag22;
                            if (flag23)
                            {
                                this.Face.Destroy(0);
                            }
                            bool flag24 = !base.Destroyed;
                            bool flag25 = flag24;
                            if (flag25)
                            {
                                this.Destroy(0);
                            }
                            this.facemutated = true;
                        }
                        else
                        {
                            this.facemutated = true;
                        }
                        bool flag26 = !this.Face.Destroyed;
                        bool flag27 = flag26;
                        if (flag27)
                        {
                            this.Face.Destroy(0);
                        }
                        bool flag28 = !base.Destroyed;
                        bool flag29 = flag28;
                        if (flag29)
                        {
                            this.Destroy(0);
                        }
                    }
                    bool flag30 = !this.Face.Destroyed;
                    bool flag31 = flag30;
                    if (flag31)
                    {
                        this.Face.Destroy(0);
                    }
                    bool flag32 = !base.Destroyed;
                    bool flag33 = flag32;
                    if (flag33)
                    {
                        this.Destroy(0);
                    }
                }
                else
                {
                    bool flag34 = this.Face == null;
                    bool flag35 = flag34;
                    if (flag35)
                    {
                        bool flag36 = !base.Destroyed;
                        bool flag37 = flag36;
                        if (flag37)
                        {
                            this.Destroy(0);
                        }
                    }
                }
                bool flag38 = !base.Destroyed;
                bool flag39 = flag38;
                if (flag39)
                {
                    this.Destroy(0);
                }
            }
        }
예제 #21
0
 // Token: 0x060029EE RID: 10734 RVA: 0x0013DA2C File Offset: 0x0013BE2C
 private void TrySpawnPawns()
 {
     if (this.pointsLeft <= 0f)
     {
         return;
     }
     if (!this.parent.Spawned)
     {
         return;
     }
     //    Log.Message(string.Format("parent Spawned: {0}", this.parent.Spawned));
     if (this.lord == null)
     {
         IntVec3 invalid;
         if (!CellFinder.TryFindRandomCellNear(this.parent.Position, this.parent.Map, 5, (IntVec3 c) => c.Standable(this.parent.Map) && this.parent.Map.reachability.CanReach(c, this.parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false)), out invalid, -1))
         {
             Log.Error("Found no place for Pawns to defend " + this, false);
             invalid = IntVec3.Invalid;
         }
         LordJob_PawnsDefendShip lordJob = new LordJob_PawnsDefendShip(this.parent, this.parent.Faction, 21f, invalid);
         this.lord = LordMaker.MakeNewLord(OfFaction, lordJob, this.parent.Map, null);
     }
     try
     {
         while (this.pointsLeft > 0f)
         {
             PawnGenOption kindOption;
             PawnKindDef   kind;
             if (this.parent is Building_HiveLike_CrashedShipPart _HiveShip)
             {
                 _HiveShip.spawnablePawnKinds.TryRandomElement(out kind);
             }
             else
             if (!(from opt in PawnKinds
                   where opt.kind.combatPower <= this.pointsLeft
                   select opt).TryRandomElementByWeight((PawnGenOption x) => x.selectionWeight, out kindOption))
             {
                 if (PawnKinds.NullOrEmpty())
                 {
                     //    Log.Message(string.Format("PawnKinds.NullOrEmpty"));
                 }
                 //    Log.Message(string.Format("try spawn 2a"));
                 break;
             }
             else
             {
                 kind = kindOption.kind;
             }
             //    Log.Message(string.Format("try spawn 3"));
             IntVec3 center;
             if (!(from cell in GenAdj.CellsAdjacent8Way(this.parent)
                   where this.CanSpawnPawnAt(cell)
                   select cell).TryRandomElement(out center))
             {
                 break;
             }
             //    Log.Message(string.Format("try spawn 4"));
             PawnGenerationRequest request = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, -1, true, false, false, false, true, false, 1f);
             //    Log.Message(string.Format("try spawn 5"));
             Pawn pawn = PawnGenerator.GeneratePawn(request);
             //    Log.Message(string.Format("try spawn 6"));
             if (!GenPlace.TryPlaceThing(pawn, center, this.parent.Map, ThingPlaceMode.Near, null, null))
             {
                 //    Log.Message(string.Format("try spawn 6b"));
                 Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard);
                 break;
             }
             //    Log.Message(string.Format("try spawn 7"));
             this.lord.AddPawn(pawn);
             //    Log.Message(string.Format("pawn: {0} to Lord: {1}", pawn.LabelShortCap, this.lord));
             this.pointsLeft -= pawn.kindDef.combatPower;
         }
     }
     finally
     {
         //    Log.Message(string.Format("Finally {0} points left", this.pointsLeft));
         this.pointsLeft = 0f;
         //    Log.Message(string.Format("set points left to {0} ", this.pointsLeft));
     }
     SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(this.parent.Map);
 }
예제 #22
0
        public override void Resolve(ResolveParams rp)
        {
            if (rp.singlePawnToSpawn != null && rp.singlePawnToSpawn.Spawned)
            {
                return;
            }
            Map     map = BaseGen.globalSettings.map;
            IntVec3 loc;

            if (!SymbolResolver_SinglePawn.TryFindSpawnCell(rp, out loc))
            {
                if (rp.singlePawnToSpawn != null)
                {
                    Find.WorldPawns.PassToWorld(rp.singlePawnToSpawn, PawnDiscardDecideMode.Discard);
                }
                return;
            }
            Pawn pawn;

            if (rp.singlePawnToSpawn == null)
            {
                PawnGenerationRequest value;
                if (rp.singlePawnGenerationRequest.HasValue)
                {
                    value = rp.singlePawnGenerationRequest.Value;
                }
                else
                {
                    PawnKindDef arg_BE_0;
                    if ((arg_BE_0 = rp.singlePawnKindDef) == null)
                    {
                        arg_BE_0 = (from x in DefDatabase <PawnKindDef> .AllDefsListForReading
                                    where x.defaultFactionType == null || !x.defaultFactionType.isPlayer
                                    select x).RandomElement <PawnKindDef>();
                    }
                    PawnKindDef pawnKindDef = arg_BE_0;
                    Faction     faction     = rp.faction;
                    if (faction == null && pawnKindDef.RaceProps.Humanlike)
                    {
                        if (pawnKindDef.defaultFactionType != null)
                        {
                            faction = FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType);
                            if (faction == null)
                            {
                                return;
                            }
                        }
                        else if (!(from x in Find.FactionManager.AllFactions
                                   where !x.IsPlayer
                                   select x).TryRandomElement(out faction))
                        {
                            return;
                        }
                    }
                    PawnKindDef kind     = pawnKindDef;
                    Faction     faction2 = faction;
                    int         tile     = map.Tile;
                    value = new PawnGenerationRequest(kind, faction2, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, false, false, false, false, null, null, null, null, null, null, null);
                }
                pawn = PawnGenerator.GeneratePawn(value);
                if (rp.postThingGenerate != null)
                {
                    rp.postThingGenerate(pawn);
                }
            }
            else
            {
                pawn = rp.singlePawnToSpawn;
            }
            if (!pawn.Dead && rp.disableSinglePawn.HasValue && rp.disableSinglePawn.Value)
            {
                pawn.mindState.Active = false;
            }
            GenSpawn.Spawn(pawn, loc, map);
            if (rp.singlePawnLord != null)
            {
                rp.singlePawnLord.AddPawn(pawn);
            }
            if (rp.postThingSpawn != null)
            {
                rp.postThingSpawn(pawn);
            }
        }
        //returns pawns for compatibility reasons.
        public static List <Pawn> SpawnHackedMechanoids(List <Pawn> pawns, IncidentParms parms)
        {
            //only call Arrive method when sure it's not already called. (can happen due to other mods)
            if (pawns.Count > 0 && !pawns[0].Spawned)
            {
                parms.raidArrivalMode.Worker.Arrive(pawns, parms);
            }

            if (pawns.Count == 0)
            {
                return(pawns);
            }
            if (parms.faction == Faction.OfMechanoids)
            {
                return(pawns);
            }
            Random rand = new Random(DateTime.Now.Millisecond);

            if (rand.Next(0, 100) > Base.hackedMechChance)
            {
                return(pawns);
            }

            int         minHackedMechPoints = Math.Min(Base.minHackedMechPoints, Base.maxHackedMechPoints);
            float       maxMechPoints       = parms.points * ((float)rand.Next(minHackedMechPoints, Base.maxHackedMechPoints)) / 100f; //TODO: no magic numbers
            float       cumulativePoints    = 0;
            Map         map        = parms.target as Map;
            List <Pawn> addedPawns = new List <Pawn>();

            while (cumulativePoints < maxMechPoints)
            {
                PawnKindDef pawnKindDef = null;
                IEnumerable <PawnKindDef> selectedPawns = (from a in DefDatabase <PawnKindDef> .AllDefs
                                                           where a.RaceProps.IsMechanoid &&
                                                           cumulativePoints + a.combatPower < maxMechPoints &&
                                                           Utilities.IsAllowedInModOptions(a.race.defName, parms.faction) &&
                                                           (parms.raidArrivalMode == PawnsArrivalModeDefOf.EdgeWalkIn || a.RaceProps.baseBodySize <= 1) //Only allow small mechs to use drop pods
                                                           select a);

                if (selectedPawns != null)
                {
                    selectedPawns.TryRandomElement(out pawnKindDef);
                }
                if (pawnKindDef != null)
                {
                    Pawn mechanoid = PawnGenerator.GeneratePawn(pawnKindDef, parms.faction);
                    if (parms.raidArrivalMode == PawnsArrivalModeDefOf.EdgeWalkIn)
                    {
                        IntVec3 loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, map, 8, null);
                        GenSpawn.Spawn(mechanoid, loc, map, parms.spawnRotation);
                    }
                    mechanoid.health.AddHediff(WTH_DefOf.WTH_TargetingHacked);
                    mechanoid.health.AddHediff(WTH_DefOf.WTH_BackupBattery);
                    Need_Power powerNeed = (Need_Power)mechanoid.needs.TryGetNeed(WTH_DefOf.WTH_Mechanoid_Power);
                    powerNeed.CurLevel = powerNeed.MaxLevel;
                    addedPawns.Add(mechanoid);
                    cumulativePoints += pawnKindDef.combatPower;
                    AddModules(mechanoid);
                }
                else
                {
                    break;
                }
            }
            if (addedPawns.Count > 0 && !addedPawns[0].Spawned)
            {
                parms.raidArrivalMode.Worker.Arrive(addedPawns, parms);
            }
            pawns.AddRange(addedPawns);

            foreach (Pawn pawn in pawns)
            {
                if (pawn.equipment == null)
                {
                    pawn.equipment = new Pawn_EquipmentTracker(pawn);
                }
            }
            return(pawns);
        }
예제 #24
0
        // Token: 0x06000E6F RID: 3695 RVA: 0x0006B3B8 File Offset: 0x000697B8
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map    map    = (Map)parms.target;
            string logmsg = string.Format("");

            logmsg = string.Format("map : {0}", map);
            Log.Message(logmsg);
            IntVec3 spawnSpot;

            if (!this.TryFindSpawnSpot(map, out spawnSpot))
            {
                return(false);
            }
            Faction faction;

            if (!this.TryFindEnemyFaction(out faction))
            {
                return(false);
            }
            int           @int      = Rand.Int;
            IncidentParms raidParms = StorytellerUtility.DefaultParmsNow(IncidentCategoryDefOf.ThreatBig, map);

            raidParms.forced             = true;
            raidParms.faction            = faction;
            raidParms.raidStrategy       = RaidStrategyDefOf.ImmediateAttack;
            raidParms.raidArrivalMode    = PawnsArrivalModeDefOf.EdgeWalkIn;
            raidParms.spawnCenter        = spawnSpot;
            raidParms.points             = Mathf.Max(raidParms.points * IncidentWorker_RefugeeChased.RaidPointsFactorRange.RandomInRange, faction.def.MinPointsToGeneratePawnGroup(PawnGroupKindDefOf.Combat));
            raidParms.pawnGroupMakerSeed = new int?(@int);
            PawnGroupMakerParms defaultPawnGroupMakerParms = IncidentParmsUtility.GetDefaultPawnGroupMakerParms(PawnGroupKindDefOf.Combat, raidParms, false);

            defaultPawnGroupMakerParms.points = IncidentWorker_Raid.AdjustedRaidPoints(defaultPawnGroupMakerParms.points, raidParms.raidArrivalMode, raidParms.raidStrategy, defaultPawnGroupMakerParms.faction, PawnGroupKindDefOf.Combat);
            IEnumerable <PawnKindDef> pawnKinds = PawnGroupMakerUtility.GeneratePawnKindsExample(defaultPawnGroupMakerParms);
            PawnGenerationRequest     request   = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, null, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);
            Pawn refugee = PawnGenerator.GeneratePawn(request);

            refugee.relations.everSeenByPlayer = true;
            string text = "RefugeeChasedInitial".Translate(new object[]
            {
                refugee.Name.ToStringFull,
                refugee.story.Title,
                faction.def.pawnsPlural,
                faction.Name,
                refugee.ageTracker.AgeBiologicalYears,
                PawnUtility.PawnKindsToCommaList(pawnKinds, true)
            });

            text = text.AdjustedFor(refugee, "PAWN");
            PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, refugee);
            DiaNode   diaNode   = new DiaNode(text);
            DiaOption diaOption = new DiaOption("RefugeeChasedInitial_Accept".Translate());

            diaOption.action = delegate()
            {
                GenSpawn.Spawn(refugee, spawnSpot, map, WipeMode.Vanish);
                refugee.SetFaction(Faction.OfPlayer, null);
                CameraJumper.TryJump(refugee);
                QueuedIncident qi = new QueuedIncident(new FiringIncident(IncidentDefOf.RaidEnemy, null, raidParms), Find.TickManager.TicksGame + IncidentWorker_RefugeeChased.RaidDelay.RandomInRange, 0);
                Find.Storyteller.incidentQueue.Add(qi);
            };
            diaOption.resolveTree = true;
            diaNode.options.Add(diaOption);
            string text2 = "RefugeeChasedRejected".Translate(new object[]
            {
                refugee.LabelShort
            });
            DiaNode   diaNode2   = new DiaNode(text2);
            DiaOption diaOption2 = new DiaOption("OK".Translate());

            diaOption2.resolveTree = true;
            diaNode2.options.Add(diaOption2);
            DiaOption diaOption3 = new DiaOption("RefugeeChasedInitial_Reject".Translate());

            diaOption3.action = delegate()
            {
                Find.WorldPawns.PassToWorld(refugee, PawnDiscardDecideMode.Decide);
            };
            diaOption3.link = diaNode2;
            diaNode.options.Add(diaOption3);
            string title = "RefugeeChasedTitle".Translate(new object[]
            {
                map.Parent.Label
            });

            Find.WindowStack.Add(new Dialog_NodeTreeWithFactionInfo(diaNode, faction, true, true, title));
            Find.Archive.Add(new ArchivedDialog(diaNode.text, title, faction));
            return(true);
        }
예제 #25
0
        protected override void Impact(Thing hitThing)
        {
            base.Impact(hitThing);

            /*
             * Null checking is very important in RimWorld.
             * 99% of errors reported are from NullReferenceExceptions (NREs).
             * Make sure your code checks if things actually exist, before they
             * try to use the code that belongs to said things.
             */

            //only do stuff if it is a pawn.
            if (Def != null && hitThing != null && hitThing is Pawn hitPawn) //Fancy way to declare a variable inside an if statement. - Thanks Erdelf.
            {
                var rand = Rand.Value;                                       // This is a random percentage between 0% and 100%

                Map         thisMap           = hitThing.Map;
                PawnKindDef clonedPawnKindDef = hitPawn.kindDef;

                //Log.Message("pawnKindDef.ToString() = " + pawnKindDef.ToString(), true);
                Pawn newThing = PawnGenerator.GeneratePawn(clonedPawnKindDef);
                //newThing.gender = hitPawn.gender;
                Log.Message("ishuman = " + newThing.RaceProps.Humanlike, true);
                if (hitPawn.RaceProps.Humanlike)
                {
                    //newThing.kindDef.race = hitPawn.kindDef.race;
                    //make an exact copy of the hit pawn. I can't just set the pawn variables equal to each other because of random complications
                    //it's easier to do this than to work around the complications causing just "newthing = hitpawn" to not work
                    newThing.inventory      = hitPawn.inventory;
                    newThing.RaceProps.body = hitPawn.RaceProps.body;
                    newThing.gender         = hitPawn.gender;
                    newThing.skills         = hitPawn.skills;
                    newThing.story.traits   = hitPawn.story.traits;
                    newThing.apparel        = hitPawn.apparel;
                    newThing.ageTracker     = hitPawn.ageTracker;
                    newThing.SetFaction(hitPawn.Faction);
                    newThing.equipment       = hitPawn.equipment;
                    newThing.story.hairDef   = hitPawn.story.hairDef;
                    newThing.story.bodyType  = hitPawn.story.bodyType;
                    newThing.story.melanin   = hitPawn.story.melanin;
                    newThing.story.crownType = hitPawn.story.crownType;
                    newThing.story.hairColor = hitPawn.story.hairColor;
                    newThing.story.adulthood = hitPawn.story.adulthood;
                    newThing.story.childhood = hitPawn.story.childhood;

                    //fully heal the pawn. Give them a fresh start!
                    MiscCrap.FullyHealPawn(newThing);
                }
                else
                {
                    newThing.gender = hitPawn.gender;
                    newThing.SetFaction(hitPawn.Faction);
                }
                //Pawn newThing = hitPawn;
                //hitPawn.Name = NameGenerator.GenerateName()
                //newThing.records.AccumulateStoryEvent(StoryEventDef)
                IntVec3 clonedPawnPosition = new IntVec3(hitPawn.Position.x + (new Random().Next(-1, 1)), hitPawn.Position.y, hitPawn.Position.z + (new Random().Next(-1, 1)));
                GenSpawn.Spawn(newThing, clonedPawnPosition, thisMap);
                //Log.Message("newThing kind def = " + newThing.kindDef.ToString());
                //hitThing.Map.wildAnimalSpawner.SpawnRandomWildAnimalAt(hitThing.Position);
                //hitPawn.DeSpawn();
            }
            else
            {
                Pawn newPawn = PawnGenerator.GeneratePawn(DefDatabase <PawnKindDef> .GetNamed("Colonist"));
                if (this.launcher.Position.GetFirstPawn(this.launcher.Map) != null)
                {
                    newPawn.SetFaction(Faction.OfPlayer, this.launcher.Position.GetFirstPawn(this.launcher.Map));
                }
                else
                {
                    newPawn.SetFaction(Faction.OfPlayer);
                }
                MiscCrap.FilterTraits(newPawn);
                MiscCrap.FullyHealPawn(newPawn);
                GenSpawn.Spawn(newPawn, new IntVec3(base.Position.x + (new Random().Next(-1, 1)), base.Position.y, base.Position.z + (new Random().Next(-1, 1))), this.launcher.Map);
            }
        }
예제 #26
0
            public static void Listener(ref Pawn __result)
            {
                if (__result == null)
                {
                    return;
                }
                if (Faction.OfPlayer.def.basicMemberKind.defName != "AndroidT2ColonistGeneral")
                {
                    return;
                }
                else
                {
                    Random rnd = new Random();
                    PawnGenerationRequest request;
                    string pkd;
                    if (!Utils.TXSERIE_LOADED)
                    {
                        switch (rnd.Next(1, 3))
                        {
                        case 1:
                            pkd = "AndroidT2ColonistGeneral";
                            break;

                        case 2:
                            pkd = "AndroidT1ColonistGeneral";
                            break;

                        default:
                            pkd = Faction.OfPlayer.def.basicMemberKind.defName;
                            break;
                        }
                    }
                    else
                    {
                        switch (rnd.Next(1, 5))
                        {
                        case 1:
                            pkd = "AndroidT2ColonistGeneral";
                            break;

                        case 2:
                            pkd = "AndroidT1ColonistGeneral";
                            break;

                        case 3:
                            pkd = "ATPP_Android2ITXKind";
                            break;

                        case 4:
                            pkd = "ATPP_Android2TXKind";
                            break;

                        default:
                            pkd = Faction.OfPlayer.def.basicMemberKind.defName;
                            break;
                        }
                    }
                    request = new PawnGenerationRequest(DefDatabase <PawnKindDef> .GetNamed(pkd, false), Faction.OfPlayer, PawnGenerationContext.PlayerStarter, -1, true, false, false, false, true, TutorSystem.TutorialMode, 20f, false, true, true, false, false, false, false);
                    try
                    {
                        __result = PawnGenerator.GeneratePawn(request);
                    }
                    catch (Exception e)
                    {
                        Log.Error("[ATPP] StartingPawnUtility.NewGeneratedStartingPawn " + e.Message + " " + e.StackTrace, false);
                        __result = PawnGenerator.GeneratePawn(request);
                    }
                    __result.relations.everSeenByPlayer = true;
                    PawnComponentsUtility.AddComponentsForSpawn(__result);
                }
            }
예제 #27
0
        public override void Tick()
        {
            if (Spawned)
            {
                sustainer.Maintain();
                Vector3 vector = Position.ToVector3Shifted();
                IntVec3 c;
                if (Rand.MTBEventOccurs(FilthSpawnMTB, 1f, 1.TicksToSeconds()) && CellFinder.TryFindRandomReachableCellNear(Position, Map, FilthSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), null, null, out c, 999999))
                {
                    FilthMaker.MakeFilth(c, Map, filthTypes.RandomElement(), 1);
                }
                if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 1f, 1.TicksToSeconds()))
                {
                    MoteMaker.ThrowDustPuffThick(new Vector3(vector.x, 0f, vector.z)
                    {
                        y = AltitudeLayer.MoteOverhead.AltitudeFor()
                    }, Map, Rand.Range(1.5f, 3f), new Color(1f, 1f, 1f, 2.5f));
                }
                if (secondarySpawnTick <= Find.TickManager.TicksGame)
                {
                    sustainer.End();
                    Map     map      = Map;
                    IntVec3 position = Position;
                    Destroy(DestroyMode.Vanish);

                    PawnKindDef kindDef = HiveUtility.GetFactionKindDef(PawnKindDef.Named("BI_Queen_Brown"), queenFaction);
                    Queen       queen   = PawnGenerator.GeneratePawn(kindDef, queenFaction) as Queen;
                    queen.hiveLocation = position;
                    if (hiveLocation != null)
                    {
                        queen.hiveLocation = hiveLocation;
                    }
                    GenSpawn.Spawn(queen, CellFinder.RandomClosewalkCellNear(position, map, 4, null), map);
                    if (insectsPoints > 0f)
                    {
                        List <PawnKindDef> spawnablePawnKinds = HiveUtility.GetFactionKindDefs(queenFaction);
                        insectsPoints = Mathf.Max(insectsPoints, spawnablePawnKinds.Min((PawnKindDef x) => x.combatPower));
                        float       pointsLeft = insectsPoints;
                        List <Pawn> list       = new List <Pawn>();
                        int         num        = 0;
                        while (pointsLeft > 0f)
                        {
                            num++;
                            if (num > 1000)
                            {
                                Log.Error("Too many iterations.", false);
                                break;
                            }
                            IEnumerable <PawnKindDef> source = from x in spawnablePawnKinds
                                                               where x.combatPower <= pointsLeft
                                                               select x;
                            PawnKindDef pawnKindDef;
                            if (!source.TryRandomElement(out pawnKindDef))
                            {
                                break;
                            }
                            PawnGenerationRequest request = new PawnGenerationRequest(pawnKindDef, queenFaction, PawnGenerationContext.NonPlayer, -1, true, true, false, false, false, false, 1f, false, false, true, false, false, false, false, null, null, null, null, null, null, null, null);
                            Pawn pawn = PawnGenerator.GeneratePawn(request);
                            GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(position, map, 2, null), map, WipeMode.Vanish);
                            queen.spawnedInsects.Add(pawn);
                            Lord lord = queen.Lord;
                            if (lord == null)
                            {
                                lord = queen.CreateNewLord();
                            }
                            lord.AddPawn(pawn);
                            list.Add(pawn);
                            pointsLeft -= pawnKindDef.combatPower;
                        }
                    }
                }
            }
        }
예제 #28
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            const float baseFishingDuration = 2000f;

            int   fishingDuration            = (int)baseFishingDuration;
            float catchSomethingThreshold    = 0f;
            Building_FishingPier fishingPier = this.TargetThingA as Building_FishingPier;
            Passion     passion          = Passion.None;
            const float skillGainPerTick = 0.15f;

            this.AddEndCondition(() =>
            {
                var targ = this.pawn.jobs.curJob.GetTarget(fishingPierIndex).Thing;
                if (targ is Building && !targ.Spawned)
                {
                    return(JobCondition.Incompletable);
                }
                return(JobCondition.Ongoing);
            });

            this.FailOnBurningImmobile(fishingPierIndex); // Bill giver or product burning in carry phase.

            this.rotateToFace = TargetIndex.B;

            yield return(Toils_Reserve.Reserve(fishingPierIndex));

            float fishingSkillLevel = 0f;

            fishingSkillLevel = this.pawn.skills.AverageOfRelevantSkillsFor(WorkTypeDefOf.Hunting);
            float fishingSkillDurationFactor = fishingSkillLevel / 20f;

            fishingDuration = (int)(baseFishingDuration * (1.5f - fishingSkillDurationFactor));

            yield return(Toils_Goto.GotoThing(fishingPierIndex, fishingPier.riverCell).FailOnDespawnedOrNull(fishingPierIndex));

            Toil fishToil = new Toil()
            {
                initAction = () =>
                {
                    ThingDef moteDef = null;
                    if (fishingPier.Rotation == Rot4.North)
                    {
                        moteDef = Util_FishIndustry.MoteFishingRodNorthDef;
                    }
                    else if (fishingPier.Rotation == Rot4.East)
                    {
                        moteDef = Util_FishIndustry.MoteFishingRodEastDef;
                    }
                    else if (fishingPier.Rotation == Rot4.South)
                    {
                        moteDef = Util_FishIndustry.MoteFishingRodSouthDef;
                    }
                    else
                    {
                        moteDef = Util_FishIndustry.MoteFishingRodWestDef;
                    }
                    this.fishingRodMote = (Mote)ThingMaker.MakeThing(moteDef, null);
                    this.fishingRodMote.exactPosition = fishingPier.fishingSpotCell.ToVector3Shifted();
                    this.fishingRodMote.Scale         = 1f;
                    GenSpawn.Spawn(this.fishingRodMote, fishingPier.fishingSpotCell, this.Map);
                },
                tickAction = () =>
                {
                    if (passion == Passion.Minor)
                    {
                        this.pawn.needs.joy.GainJoy(NeedTunings.JoyPerXpForPassionMinor, JoyKindDefOf.Work);
                    }
                    else if (passion == Passion.Major)
                    {
                        this.pawn.needs.joy.GainJoy(NeedTunings.JoyPerXpForPassionMajor, JoyKindDefOf.Work);
                    }
                    this.pawn.skills.Learn(SkillDefOf.Shooting, skillGainPerTick);

                    if (this.ticksLeftThisToil == 1)
                    {
                        if (this.fishingRodMote != null)
                        {
                            this.fishingRodMote.Destroy();
                        }
                    }
                },
                defaultDuration     = fishingDuration,
                defaultCompleteMode = ToilCompleteMode.Delay
            };

            yield return(fishToil.WithProgressBarToilDelay(fishingPierIndex));

            Toil computeChanceToCatchToil = new Toil()
            {
                initAction = () =>
                {
                    catchSomethingThreshold = fishingSkillLevel / 20f;
                    // Reframe min and max chance (min 5%, max 75 % chance of success).
                    Mathf.Clamp(catchSomethingThreshold, 0.05f, 0.75f);
                },
                defaultCompleteMode = ToilCompleteMode.Instant
            };

            yield return(computeChanceToCatchToil);

            Toil catchFishToil = new Toil()
            {
                initAction = () =>
                {
                    Job   curJob       = this.pawn.jobs.curJob;
                    Thing fishingCatch = null;

                    // 90% chance to successfully catch something.
                    bool catchIsSuccessful = (Rand.Value >= 0.1f);
                    if (catchIsSuccessful == false)
                    {
                        MoteMaker.ThrowMetaIcon(this.pawn.Position, this.Map, ThingDefOf.Mote_IncapIcon);
                        this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
                        return;
                    }

                    float catchSelectorValue = Rand.Value;
                    if (catchSelectorValue > 0.04f)
                    {
                        // Catch a fish.
                        bool fishSpotIsOcean = (this.Map.terrainGrid.TerrainAt(fishingPier.fishingSpotCell) == TerrainDefOf.WaterOceanShallow) ||
                                               (this.Map.terrainGrid.TerrainAt(fishingPier.fishingSpotCell) == TerrainDefOf.WaterOceanDeep);
                        bool fishSpotIsMarshy = (this.Map.terrainGrid.TerrainAt(fishingPier.fishingSpotCell) == TerrainDef.Named("Marsh"));

                        PawnKindDef caugthFishDef = null;
                        if (fishSpotIsOcean)
                        {
                            caugthFishDef = (from fishSpecies in Util_FishIndustry.GetFishSpeciesList(this.Map.Biome)
                                             where fishSpecies.livesInOcean
                                             select fishSpecies).RandomElementByWeight((PawnKindDef_FishSpecies def) => def.commonality);
                        }
                        else if (fishSpotIsMarshy)
                        {
                            caugthFishDef = (from fishSpecies in Util_FishIndustry.GetFishSpeciesList(this.Map.Biome)
                                             where fishSpecies.livesInMarsh
                                             select fishSpecies).RandomElementByWeight((PawnKindDef_FishSpecies def) => def.commonality);
                        }
                        else
                        {
                            caugthFishDef = (from fishSpecies in Util_FishIndustry.GetFishSpeciesList(this.Map.Biome)
                                             where fishSpecies.livesInRiver
                                             select fishSpecies).RandomElementByWeight((PawnKindDef_FishSpecies def) => def.commonality);
                        }
                        Pawn caughtFish = PawnGenerator.GeneratePawn(caugthFishDef);
                        GenSpawn.Spawn(caughtFish, this.pawn.Position, this.Map);
                        HealthUtility.DamageUntilDead(caughtFish);
                        foreach (Thing thing in this.pawn.Position.GetThingList(this.Map))
                        {
                            Corpse fishCorpse = thing as Corpse;
                            if (fishCorpse != null)
                            {
                                fishingCatch = fishCorpse;
                                fishingCatch.SetForbidden(false);
                            }
                        }
                        if (caughtFish.BodySize >= 0.1f)
                        {
                            fishingPier.fishStock--;
                            fishingPier.ComputeMaxFishStockAndRespawnPeriod();
                        }
                    }
                    else if (catchSelectorValue > 0.02)
                    {
                        fishingCatch            = GenSpawn.Spawn(Util_FishIndustry.OysterDef, this.pawn.Position, this.Map);
                        fishingCatch.stackCount = Rand.RangeInclusive(5, 27);
                    }
                    else
                    {
                        float bonusCatchValue = Rand.Value;
                        if (bonusCatchValue < 0.01f)
                        {
                            // Really small chance to find a sunken treasure!!!
                            fishingCatch            = GenSpawn.Spawn(ThingDefOf.Gold, this.pawn.Position, this.Map);
                            fishingCatch.stackCount = Rand.RangeInclusive(58, 289);
                            Thing treasureSilver = GenSpawn.Spawn(ThingDefOf.Silver, fishingPier.middleCell, this.Map);
                            treasureSilver.stackCount = Rand.RangeInclusive(237, 2154);
                            Find.LetterStack.ReceiveLetter("FishIndustry.LetterLabelSunkenTreasure".Translate(), "FishIndustry.SunkenTreasure".Translate(this.pawn.Name.ToStringShort.CapitalizeFirst()),
                                                           LetterDefOf.Good, this.pawn);
                        }
                        else if (bonusCatchValue < 0.02f)
                        {
                            // Really small chance to find a complete power armor set + sniper or charge rifle.
                            Thing powerArmor = GenSpawn.Spawn(ThingDef.Named("Apparel_PowerArmor"), this.pawn.Position, this.Map);
                            fishingCatch = powerArmor; // Used to carry the power armor.
                            Thing powerArmorHelmet = GenSpawn.Spawn(ThingDef.Named("Apparel_PowerArmorHelmet"), this.pawn.Position, this.Map);
                            Thing rifle            = null;
                            if (Rand.Value < 0.5f)
                            {
                                rifle = GenSpawn.Spawn(ThingDef.Named("Gun_ChargeRifle"), this.pawn.Position, this.Map);
                            }
                            else
                            {
                                rifle = GenSpawn.Spawn(ThingDef.Named("Gun_SniperRifle"), this.pawn.Position, this.Map);
                            }
                            CompQuality qualityComp = powerArmor.TryGetComp <CompQuality>();
                            if (qualityComp != null)
                            {
                                qualityComp.SetQuality(QualityCategory.Masterwork, ArtGenerationContext.Outsider);
                            }
                            qualityComp = powerArmorHelmet.TryGetComp <CompQuality>();
                            if (qualityComp != null)
                            {
                                qualityComp.SetQuality(QualityCategory.Masterwork, ArtGenerationContext.Outsider);
                            }
                            qualityComp = rifle.TryGetComp <CompQuality>();
                            if (qualityComp != null)
                            {
                                qualityComp.SetQuality(QualityCategory.Masterwork, ArtGenerationContext.Outsider);
                            }

                            Faction faction    = Find.FactionManager.FirstFactionOfDef(FactionDefOf.SpacerHostile);
                            Pawn    deadMarine = PawnGenerator.GeneratePawn(PawnKindDefOf.SpaceSoldier, faction);
                            GenSpawn.Spawn(deadMarine, fishingPier.bankCell, this.Map);
                            HealthUtility.DamageUntilDead(deadMarine);
                            List <Thing> thingsList = deadMarine.Position.GetThingList(this.Map);
                            foreach (Thing thing in thingsList)
                            {
                                if (thing.def.defName.Contains("Corpse"))
                                {
                                    CompRottable rotComp = thing.TryGetComp <CompRottable>();
                                    if (rotComp != null)
                                    {
                                        rotComp.RotProgress = 20f * GenDate.TicksPerDay; // 20 days so the corpse is dessicated.
                                    }
                                }
                            }
                            string eventText = this.pawn.Name.ToStringShort.CapitalizeFirst() + " has cought a dead body while fishing!\n\n'This is really disgusting but look at his gear! This guy was probably a MiningCo. security member. I wonder what happend to him...'\n";
                            Find.LetterStack.ReceiveLetter("Dead marine", eventText, LetterDefOf.Good, this.pawn);
                        }
                        else
                        {
                            // Find a small amount of gold.
                            fishingCatch            = GenSpawn.Spawn(ThingDefOf.Gold, this.pawn.Position, this.Map);
                            fishingCatch.stackCount = Rand.RangeInclusive(1, 7);
                        }
                        // TODO: add chance to get hurt by a tailteeth (missing finger or even hand!).
                    }
                    IntVec3 storageCell;
                    if (StoreUtility.TryFindBestBetterStoreCellFor(fishingCatch, this.pawn, this.Map, StoragePriority.Unstored, this.pawn.Faction, out storageCell, true))
                    {
                        this.pawn.Reserve(fishingCatch, 1);
                        this.pawn.Reserve(storageCell, 1);
                        this.pawn.CurJob.SetTarget(TargetIndex.B, storageCell);
                        this.pawn.CurJob.SetTarget(TargetIndex.A, fishingCatch);
                        this.pawn.CurJob.count    = 1;
                        this.pawn.CurJob.haulMode = HaulMode.ToCellStorage;
                    }
                    else
                    {
                        this.pawn.jobs.EndCurrentJob(JobCondition.Succeeded);
                    }
                }
            };

            yield return(catchFishToil);

            yield return(Toils_Haul.StartCarryThing(TargetIndex.A));

            Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B);

            yield return(carryToCell);

            yield return(Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true));

            yield return(Toils_Reserve.Release(fishingPierIndex));
        }
예제 #29
0
        public override void PawnDied(Corpse corpse)
        {
            PawnGenerationRequest pawnGenerationRequest;
            PawnKindDef           pawnKindDef = corpse.InnerPawn.kindDef;
            Pawn           pawn        = corpse.InnerPawn;
            IntVec3        position    = corpse.Position;
            Map            map         = corpse.Map;
            Faction        faction     = pawn.Faction;
            float          bioyears    = pawn.ageTracker.AgeBiologicalYears;
            float          chronoyears = pawn.ageTracker.AgeChronologicalYears;
            Pawn_MindState mind        = pawn.mindState;
            Pawn           newPawn1    = null;
            Pawn           newPawn2    = null;
            bool           spawn       = false;
            Lord           lord        = pawn.GetLord();
            List <Thing>   spawned     = new List <Thing>();

            if (map != null)
            {
                if (corpse.InnerPawn.kindDef == AdeptusPawnKindDefOf.OG_Chaos_Deamon_Lessar_Horror_Blue)
                {
                    spawn       = true;
                    pawnKindDef = AdeptusPawnKindDefOf.OG_Chaos_Deamon_Lessar_Horror_Brimstone;
                }
                else if (corpse.InnerPawn.kindDef == AdeptusPawnKindDefOf.OG_Chaos_Deamon_Lessar_Horror_Pink)
                {
                    spawn       = true;
                    pawnKindDef = AdeptusPawnKindDefOf.OG_Chaos_Deamon_Lessar_Horror_Blue;
                }
                if (spawn)
                {
                    pawnGenerationRequest = new PawnGenerationRequest(pawnKindDef, corpse.InnerPawn.Faction, PawnGenerationContext.NonPlayer, -1, true, false, true, false, true, true, 20f, fixedBiologicalAge: bioyears, fixedChronologicalAge: chronoyears);
                    newPawn1 = PawnGenerator.GeneratePawn(pawnGenerationRequest);
                    newPawn2 = PawnGenerator.GeneratePawn(pawnGenerationRequest);
                    spawned  = new List <Thing>()
                    {
                        newPawn1,
                        newPawn2
                    };
                    if (pawn.Faction != null)
                    {
                        if (map.mapPawns.SpawnedPawnsInFaction(pawn.Faction).Any((Pawn p) => p != newPawn1 && p != newPawn2 && p.GetLord() != null))
                        {
                            bool validator(Thing p) => p != newPawn1 && p != newPawn2 && ((Pawn)p).GetLord() != null;

                            Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(position, map.mapPawns.SpawnedPawnsInFaction(newPawn1.Faction), 99999f, validator, null);
                            lord = p2.GetLord();
                        }
                    }
                    if (lord == null)
                    {
                        try
                        {
                            LordJob_AssaultColony lordJob = new LordJob_AssaultColony(faction, false, false);
                            lord = LordMaker.MakeNewLord((pawn.Faction), lordJob, map, null);
                        }
                        catch
                        {
                            //    newPawn1.mindState.mentalStateHandler.TryStartMentalState(OGChaosDeamonDefOf.MentalState_OGChaosDeamon);
                            //    newPawn2.mindState.mentalStateHandler.TryStartMentalState(OGChaosDeamonDefOf.MentalState_OGChaosDeamon);
                        }
                    }
                    else
                    {
                        try
                        {
                            newPawn1.mindState.duty = new PawnDuty(DutyDefOf.AssaultColony);
                            newPawn2.mindState.duty = new PawnDuty(DutyDefOf.AssaultColony);
                        }
                        catch
                        {
                            //    newPawn1.mindState.mentalStateHandler.TryStartMentalState(OGChaosDeamonDefOf.MentalState_OGChaosDeamon);
                            //    newPawn2.mindState.mentalStateHandler.TryStartMentalState(OGChaosDeamonDefOf.MentalState_OGChaosDeamon);
                        }
                    }
                    if (spawn)
                    {
                        Pawn p = (Pawn)GenClosest.ClosestThing_Global(position, map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, null, null);
                        if (p.InMentalState)
                        {
                            if (p.MentalStateDef == MentalStateDefOf.PanicFlee || p.GetLord() == null || p.GetLord().Map == null)
                            {
                                spawn = false;
                            }
                        }
                    }
                    if (spawn && pawnKindDef != corpse.InnerPawn.kindDef && lord != null && map != null)
                    {
                        if (newPawn1 != null)
                        {
                            GenSpawn.Spawn(newPawn1, position, map, 0);
                            if (lord != null)
                            {
                                lord.AddPawn(newPawn1);
                            }
                        }
                        if (newPawn2 != null)
                        {
                            GenSpawn.Spawn(newPawn2, position, map, 0);
                            if (lord != null)
                            {
                                lord.AddPawn(newPawn2);
                            }
                        }
                    }
                }
            }
            if (position != null && map != null)
            {
                GenExplosion.DoExplosion(position, map, 1.9f, AdeptusDamageDefOf.OG_Chaos_Deamon_WarpfireDeath, corpse.InnerPawn, -1, -1f, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false, null, spawned);
            }
            base.PawnDied(corpse);
        }
예제 #30
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def         = this.def;
            int      raisedPawns = 0;

            Pawn pawn   = this.launcher as Pawn;
            Pawn victim = hitThing as Pawn;
            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();

            pwr = comp.MagicData.MagicPowerSkill_RaiseUndead.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_RaiseUndead_pwr");
            ver = comp.MagicData.MagicPowerSkill_RaiseUndead.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_RaiseUndead_ver");

            Thing corpseThing = null;

            IntVec3 curCell;
            IEnumerable <IntVec3> targets = GenRadial.RadialCellsAround(base.Position, this.def.projectile.explosionRadius, true);

            for (int i = 0; i < targets.Count(); i++)
            {
                curCell = targets.ToArray <IntVec3>()[i];

                TM_MoteMaker.ThrowPoisonMote(curCell.ToVector3Shifted(), map, .3f);
                if (curCell.InBounds(map))
                {
                    Corpse       corpse = null;
                    List <Thing> thingList;
                    thingList = curCell.GetThingList(map);
                    int z = 0;
                    while (z < thingList.Count)
                    {
                        corpseThing = thingList[z];
                        if (corpseThing != null)
                        {
                            bool validator = corpseThing is Corpse;
                            if (validator)
                            {
                                corpse = corpseThing as Corpse;
                                Pawn         undeadPawn   = corpse.InnerPawn;
                                CompRottable compRottable = corpse.GetComp <CompRottable>();
                                float        rotStage     = 0;
                                if (compRottable != null && compRottable.Stage == RotStage.Dessicated)
                                {
                                    rotStage = 1f;
                                }
                                if (compRottable != null)
                                {
                                    rotStage += compRottable.RotProgressPct;
                                }
                                bool flag_SL = false;
                                if (undeadPawn.def.defName == "SL_Runner" || undeadPawn.def.defName == "SL_Peon" || undeadPawn.def.defName == "SL_Archer" || undeadPawn.def.defName == "SL_Hero")
                                {
                                    PawnGenerationRequest pgr = new PawnGenerationRequest(PawnKindDef.Named("Tribesperson"), pawn.Faction, PawnGenerationContext.NonPlayer, -1, true, false, false, false, false, true, 0, false, false, false, false, false, false, false, false, 0, null, 0);
                                    Pawn newUndeadPawn        = PawnGenerator.GeneratePawn(pgr);
                                    GenSpawn.Spawn(newUndeadPawn, corpse.Position, corpse.Map, WipeMode.Vanish);
                                    corpse.Strip();
                                    corpse.Destroy(DestroyMode.Vanish);
                                    rotStage   = 1f;
                                    flag_SL    = true;
                                    undeadPawn = newUndeadPawn;
                                }
                                if (!undeadPawn.def.defName.Contains("ROM_") && undeadPawn.RaceProps.IsFlesh && (undeadPawn.Dead || flag_SL) && undeadPawn.def.thingClass.FullName != "TorannMagic.TMPawnSummoned")
                                {
                                    bool wasVampire = false;

                                    IEnumerable <ThingDef> enumerable = from hd in DefDatabase <HediffDef> .AllDefs
                                                                        where (def.defName == "ROM_Vampirism")
                                                                        select def;
                                    if (enumerable.Count() > 0)
                                    {
                                        bool hasVampHediff = undeadPawn.health.hediffSet.HasHediff(HediffDef.Named("ROM_Vampirism")) || undeadPawn.health.hediffSet.HasHediff(HediffDef.Named("ROM_GhoulHediff"));
                                        if (hasVampHediff)
                                        {
                                            wasVampire = true;
                                        }
                                    }

                                    if (!wasVampire)
                                    {
                                        undeadPawn.SetFaction(pawn.Faction);
                                        if (undeadPawn.Dead)
                                        {
                                            ResurrectionUtility.Resurrect(undeadPawn);
                                        }
                                        raisedPawns++;
                                        comp.supportedUndead.Add(undeadPawn);
                                        if (undeadPawn.kindDef != null && undeadPawn.kindDef.RaceProps != null && undeadPawn.kindDef.RaceProps.Animal)
                                        {
                                            RemoveHediffsAddictionsAndPermanentInjuries(undeadPawn);
                                            HealthUtility.AdjustSeverity(undeadPawn, TorannMagicDefOf.TM_UndeadAnimalHD, -4f);
                                            HealthUtility.AdjustSeverity(undeadPawn, TorannMagicDefOf.TM_UndeadAnimalHD, .5f + ver.level);
                                            undeadPawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_UndeadAnimalHD).TryGetComp <HediffComp_Undead>().linkedPawn = pawn;
                                            HealthUtility.AdjustSeverity(undeadPawn, HediffDef.Named("TM_UndeadStageHD"), -2f);
                                            HealthUtility.AdjustSeverity(undeadPawn, HediffDef.Named("TM_UndeadStageHD"), rotStage);

                                            if (undeadPawn.training.CanAssignToTrain(TrainableDefOf.Tameness).Accepted)
                                            {
                                                while (!undeadPawn.training.HasLearned(TrainableDefOf.Tameness))
                                                {
                                                    undeadPawn.training.Train(TrainableDefOf.Tameness, pawn);
                                                }
                                            }

                                            if (undeadPawn.training.CanAssignToTrain(TrainableDefOf.Obedience).Accepted)
                                            {
                                                while (!undeadPawn.training.HasLearned(TrainableDefOf.Obedience))
                                                {
                                                    undeadPawn.training.Train(TrainableDefOf.Obedience, pawn);
                                                }
                                            }

                                            if (undeadPawn.training.CanAssignToTrain(TrainableDefOf.Release).Accepted)
                                            {
                                                while (!undeadPawn.training.HasLearned(TrainableDefOf.Release))
                                                {
                                                    undeadPawn.training.Train(TrainableDefOf.Release, pawn);
                                                }
                                            }

                                            if (undeadPawn.training.CanAssignToTrain(TorannMagicDefOf.Haul).Accepted)
                                            {
                                                while (!undeadPawn.training.HasLearned(TorannMagicDefOf.Haul))
                                                {
                                                    undeadPawn.training.Train(TorannMagicDefOf.Haul, pawn);
                                                }
                                            }

                                            if (undeadPawn.training.CanAssignToTrain(TorannMagicDefOf.Rescue).Accepted)
                                            {
                                                while (!undeadPawn.training.HasLearned(TorannMagicDefOf.Rescue))
                                                {
                                                    undeadPawn.training.Train(TorannMagicDefOf.Rescue, pawn);
                                                }
                                            }
                                            undeadPawn.playerSettings.medCare = MedicalCareCategory.NoMeds;
                                            undeadPawn.def.tradeability       = Tradeability.None;
                                        }
                                        else if (undeadPawn.story != null && undeadPawn.story.traits != null && undeadPawn.needs != null && undeadPawn.playerSettings != null)
                                        {
                                            CompAbilityUserMagic compMagic = undeadPawn.GetComp <CompAbilityUserMagic>();
                                            if (compMagic != null && TM_Calc.IsMagicUser(undeadPawn)) //(compMagic.IsMagicUser && !undeadPawn.story.traits.HasTrait(TorannMagicDefOf.Faceless)) ||
                                            {
                                                compMagic.Initialize();
                                                compMagic.RemovePowers(true);
                                            }
                                            CompAbilityUserMight compMight = undeadPawn.GetComp <CompAbilityUserMight>();
                                            if (compMight != null && TM_Calc.IsMightUser(undeadPawn)) //compMight.IsMightUser ||
                                            {
                                                compMight.Initialize();
                                                compMight.RemovePowers(true);
                                            }
                                            RemoveHediffsAddictionsAndPermanentInjuries(undeadPawn);
                                            RemovePsylinkAbilities(undeadPawn);
                                            HealthUtility.AdjustSeverity(undeadPawn, TorannMagicDefOf.TM_UndeadHD, -4f);
                                            HealthUtility.AdjustSeverity(undeadPawn, TorannMagicDefOf.TM_UndeadHD, .5f + ver.level);
                                            undeadPawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_UndeadHD).TryGetComp <HediffComp_Undead>().linkedPawn = pawn;
                                            HealthUtility.AdjustSeverity(undeadPawn, HediffDef.Named("TM_UndeadStageHD"), -2f);
                                            HealthUtility.AdjustSeverity(undeadPawn, HediffDef.Named("TM_UndeadStageHD"), rotStage);
                                            RedoSkills(undeadPawn, pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_LichHD")));
                                            if (undeadPawn.story.traits.HasTrait(TorannMagicDefOf.ChaosMage))
                                            {
                                                compMagic.RemovePawnAbility(TorannMagicDefOf.TM_ChaosTradition);
                                            }
                                            RemoveTraits(undeadPawn, undeadPawn.story.traits.allTraits);
                                            undeadPawn.story.traits.GainTrait(new Trait(TraitDef.Named("Undead"), 0, false));
                                            undeadPawn.story.traits.GainTrait(new Trait(TraitDef.Named("Psychopath"), 0, false));
                                            undeadPawn.needs.AddOrRemoveNeedsAsAppropriate();
                                            RemoveClassHediff(undeadPawn);
                                            if (undeadPawn.health.hediffSet.HasHediff(HediffDef.Named("DeathAcidifier")))
                                            {
                                                Hediff hd = undeadPawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DeathAcidifier"));
                                                undeadPawn.health.RemoveHediff(hd);
                                            }
                                            //Color undeadColor = new Color(.2f, .4f, 0);
                                            //undeadPawn.story.hairColor = undeadColor;
                                            //CompAbilityUserMagic undeadComp = undeadPawn.GetComp<CompAbilityUserMagic>();
                                            //if (undeadComp.IsMagicUser)
                                            //{
                                            //    undeadComp.ClearPowers();
                                            //}

                                            List <SkillRecord> skills = undeadPawn.skills.skills;
                                            for (int j = 0; j < skills.Count; j++)
                                            {
                                                skills[j].passion = Passion.None;
                                            }
                                            undeadPawn.playerSettings.hostilityResponse = HostilityResponseMode.Attack;
                                            undeadPawn.playerSettings.medCare           = MedicalCareCategory.NoMeds;
                                            for (int h = 0; h < 24; h++)
                                            {
                                                undeadPawn.timetable.SetAssignment(h, TimeAssignmentDefOf.Work);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Messages.Message("Vampiric powers have prevented undead reanimation of " + undeadPawn.LabelShort, MessageTypeDefOf.RejectInput);
                                    }
                                }
                            }
                        }
                        z++;
                    }
                }
                if (raisedPawns > pwr.level + 1)
                {
                    i = targets.Count();
                }
            }
        }