public override bool ActivateOn(Lord lord, TriggerSignal signal)
        {
            if (signal.type == TriggerSignalType.Tick && Find.TickManager.TicksGame% GenTicks.TickRareInterval == 0)
            {
                var tradeCenters =
                    Find.ListerBuildings.AllBuildingsColonistOfClass<TradeCenter>()
                        .Where(building => building.trader == null);
                var trader = TraderCaravanUtility.FindTrader(lord);
                var carrier = lord.ownedPawns.FirstOrDefault(pawn => pawn.GetCaravanRole() == TraderCaravanRole.Carrier);

                if (tradeCenters.Any() && trader != null && carrier != null)
                {
                    if (trader.CanReach(tradeCenters.FirstOrDefault(), PathEndMode.InteractionCell, trader.NormalMaxDanger()) &&
                        carrier.CanReach(tradeCenters.FirstOrDefault(), PathEndMode.InteractionCell, trader.NormalMaxDanger()))
                        return true;
                }
            }
            return false;
        }
        private bool TryAccept()
        {
            List <Pawn> pawnsFromTransferables = TransferableUtility.GetPawnsFromTransferables(this.transferables);

            if (!this.CheckForErrors(pawnsFromTransferables))
            {
                return(false);
            }
            int transportersGroup = this.CreateAndAssignNewTransportersGroup();

            this.AssignTransferablesToRandomTransporters();
            IEnumerable <Pawn> enumerable = from x in pawnsFromTransferables
                                            where x.IsColonist && !x.Downed
                                            select x;

            if (enumerable.Any <Pawn>())
            {
                foreach (Pawn pawn in enumerable)
                {
                    Lord lord = pawn.GetLord();
                    if (lord != null)
                    {
                        lord.Notify_PawnLost(pawn, PawnLostCondition.ForcedToJoinOtherLord, null);
                    }
                }
                LordMaker.MakeNewLord(Faction.OfPlayer, new LordJob_LoadAndEnterTransporters(transportersGroup), this.map, enumerable);
                foreach (Pawn pawn2 in enumerable)
                {
                    if (pawn2.Spawned)
                    {
                        pawn2.jobs.EndCurrentJob(JobCondition.InterruptForced, true);
                    }
                }
            }
            Messages.Message("MessageTransportersLoadingProcessStarted".Translate(), this.transporters[0].parent, MessageTypeDefOf.TaskCompletion, false);
            return(true);
        }
Пример #3
0
        public override bool TryExecute(IncidentParms parms)
        {
            Map map = (Map)parms.target;

            if (!this.TryResolveParms(parms))
            {
                return(false);
            }

            Pawn pawn = PawnGenerator.GeneratePawn(DefOfs.C_PawnKindDefOf.IoM_WanderingTrader, parms.faction);

            if (pawn == null)
            {
                return(false);
            }
            IntVec3 loc;

            RCellFinder.TryFindRandomPawnEntryCell(out loc, map);
            GenSpawn.Spawn(pawn, loc, map);
            IntVec3 chillSpot;

            RCellFinder.TryFindRandomSpotJustOutsideColony(pawn, out chillSpot);
            LordJob_IntrusiveWanderer lordJob = new LordJob_IntrusiveWanderer(chillSpot, pawn, ChatType);
            Lord lord = LordMaker.MakeNewLord(parms.faction, lordJob, map);

            lord.AddPawn(pawn);
            this.TryConvertOnePawnToSmallTrader(pawn, parms.faction, map);
            string label = "LetterLabelSingleVisitorArrives".Translate();
            string text3 = "IoM_WandererArrives".Translate(new object[]
            {
                pawn.Name
            });

            text3 = text3.AdjustedFor(pawn);
            Find.LetterStack.ReceiveLetter(label, text3, LetterType.Good, pawn, null);
            return(true);
        }
Пример #4
0
        private bool TrySpawnPawn(out Pawn pawn, float limitPoint)
        {
            if (!canSpawnPawns)
            {
                pawn = null;
                return(false);
            }
            float curPoints = SpawnedPawnsPoints;
            IEnumerable <PawnKindDef> source = from x in RatkinTunnelUtility.spawnableElitePawnKinds
                                               where curPoints + x.combatPower <= limitPoint
                                               select x;
            PawnKindDef kindDef;

            if (!source.TryRandomElement(out kindDef))
            {
                pawn = null;
                return(false);
            }
            pawn = PawnGenerator.GeneratePawn(kindDef, Faction);
            spawnedPawns.Add(pawn);
            GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(Position, Map, 2, null), Map, WipeMode.Vanish);
            Lord lord = Lord;

            if (lord == null)
            {
                lord = CreateNewLord();
            }
            lord.AddPawn(pawn);
            SoundDefOf.DropPod_Open.PlayOneShot(this);
            Need rest = pawn.needs.TryGetNeed(NeedDefOf.Rest);

            rest.CurLevel = rest.MaxLevel;
            Need food = pawn.needs.TryGetNeed(NeedDefOf.Food);

            food.CurLevel = food.MaxLevel;
            return(true);
        }
Пример #5
0
        public override void CompTickRare()
        {
            base.CompTickRare();
            bool    selected = Find.Selector.SelectedObjects.Contains(pawn);
            Lord    lord     = pawn.GetLord();
            Faction xenos    = Find.FactionManager.FirstFactionOfDef(XenomorphDefOf.RRY_Xenomorph);

            if (pawn != null && pawn.Map != null && !pawn.Dead && pawn.kindDef != XenomorphDefOf.RRY_Xenomorph_FaceHugger && pawn.kindDef != XenomorphDefOf.RRY_Xenomorph_RoyaleHugger)
            {
                LifeStageDef stage = pawn.ageTracker.CurLifeStage;
                if (stage == pawn.RaceProps.lifeStageAges[pawn.RaceProps.lifeStageAges.Count - 1].def)
                {
                    if (pawn.health.hediffSet.HasHediff(XenomorphDefOf.RRY_Hediff_Xenomorph_Hidden))
                    {
                        string text   = TranslatorFormattedStringExtensions.Translate("Xeno_Chestburster_Matures", pawn.LabelCap);
                        Hediff hediff = pawn.health.hediffSet.GetFirstHediffOfDef(XenomorphDefOf.RRY_Hediff_Xenomorph_Hidden);
                        MoteMaker.ThrowText(pawn.Position.ToVector3(), pawn.Map, text, 3f);
                        hidden = false;
                        pawn.health.RemoveHediff(hediff);
                    }
                    XenoLordTick();
                }
                else
                {
                    Thing thing = GenClosest.ClosestThingReachable(this.parent.Position, this.parent.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.Touch, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), 6f, x => ((Pawn)this.parent).HostileTo((Pawn)x) && !((Pawn)x).health.hediffSet.HasHediff(XenomorphDefOf.RRY_Hediff_Cocooned), null, 0, -1, false, RegionType.Set_Passable, false);
                    if (!((Pawn)this.parent).health.hediffSet.HasHediff(XenomorphDefOf.RRY_Hediff_Xenomorph_Hidden) && thing == null)
                    {
                        string text = TranslatorFormattedStringExtensions.Translate("Xeno_Chestburster_Hides");

                        MoteMaker.ThrowText(base.parent.Position.ToVector3(), base.parent.Map, text, 3f);
                        ((Pawn)this.parent).health.AddHediff(XenomorphDefOf.RRY_Hediff_Xenomorph_Hidden);
                        hidden = true;
                    }
                }
            }
        }
Пример #6
0
        private Pawn FindBestCarrier(bool onlyAnimals)
        {
            Lord  lord = base.job.lord;
            Pawn  pawn = null;
            float num  = 0f;

            if (lord != null)
            {
                for (int i = 0; i < lord.ownedPawns.Count; i++)
                {
                    Pawn pawn2 = lord.ownedPawns[i];
                    if (pawn2 != base.pawn && (!onlyAnimals || pawn2.RaceProps.Animal) && JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(pawn2, base.pawn, false))
                    {
                        float carrierScore = this.GetCarrierScore(pawn2);
                        if (pawn == null || carrierScore > num)
                        {
                            pawn = pawn2;
                            num  = carrierScore;
                        }
                    }
                }
            }
            return(pawn);
        }
Пример #7
0
        public void Mutate()
        {
            mutationActive = true;
            this.Severity  = 1f;

            foreach (var tool in pawn.Tools)
            {
                if (tool.power > 0)
                {
                    tool.power *= 1.25f;
                }
            }
            if (this.pawn.Faction != PurpleIvyData.AlienFaction)
            {
                this.pawn.SetFaction(PurpleIvyData.AlienFaction);
            }
            this.pawn.RaceProps.thinkTreeMain = PurpleIvyDefOf.PI_HumanlikeMutant;
            Lord lord = null;

            if (this.pawn.Map.mapPawns.SpawnedPawnsInFaction(pawn.Faction).Any((Pawn p) =>
                                                                               p != this.pawn))
            {
                lord = ((Pawn)GenClosest.ClosestThing_Global(this.pawn.Position,
                                                             this.pawn.Map.mapPawns.SpawnedPawnsInFaction(this.pawn.Faction), 99999f,
                                                             (Thing p) => p != this.pawn && ((Pawn)p).GetLord() != null, null)).GetLord();
            }
            if (lord == null)
            {
                var lordJob = new LordJob_AssaultColony(this.pawn.Faction);
                lord = LordMaker.MakeNewLord(this.pawn.Faction, lordJob, this.pawn.Map, null);
            }
            if (!lord.ownedPawns.Contains(this.pawn))
            {
                lord.AddPawn(this.pawn);
            }
        }
Пример #8
0
        private void GeneratePrisoners(Map map)
        {
            int prisonersCount = Rand.Range(2, 6);

            for (int i = 0; i < prisonersCount; i++)
            {
                Faction faction = Faction.OfAncientsHostile;

                Pawn pawn = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, faction);

                Find.WorldPawns.PassToWorld(pawn);

                DropedPawns.Add(pawn);

                IntVec3 spawnPos = CellFinder.RandomClosewalkCellNear(map.Center, map, 99999);

                GenSpawn.Spawn(pawn, spawnPos, map);

                LordJob_DefendBase lordJob_DefendBase = new LordJob_DefendBase(faction, spawnPos);
                Lord lord = LordMaker.MakeNewLord(faction, lordJob_DefendBase, map);

                lord.AddPawn(pawn);
            }
        }
Пример #9
0
 private void TrySpawnMechanoids()
 {
     if (!(this.pointsLeft <= 0.0) && base.parent.Spawned)
     {
         if (this.lord == null)
         {
             IntVec3 invalid = default(IntVec3);
             if (!CellFinder.TryFindRandomCellNear(base.parent.Position, base.parent.Map, 5, (Predicate <IntVec3>)((IntVec3 c) => c.Standable(base.parent.Map) && base.parent.Map.reachability.CanReach(c, base.parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))), out invalid))
             {
                 Log.Error("Found no place for mechanoids to defend " + this);
                 invalid = IntVec3.Invalid;
             }
             LordJob_MechanoidsDefendShip lordJob = new LordJob_MechanoidsDefendShip(base.parent, base.parent.Faction, 21f, invalid);
             this.lord = LordMaker.MakeNewLord(Faction.OfMechanoids, lordJob, base.parent.Map, null);
         }
         PawnKindDef kindDef = default(PawnKindDef);
         IntVec3     center  = default(IntVec3);
         while ((from def in DefDatabase <PawnKindDef> .AllDefs
                 where def.RaceProps.IsMechanoid && def.isFighter && def.combatPower <= this.pointsLeft
                 select def).TryRandomElement <PawnKindDef>(out kindDef) && (from cell in GenAdj.CellsAdjacent8Way(base.parent)
                                                                             where this.CanSpawnMechanoidAt(cell)
                                                                             select cell).TryRandomElement <IntVec3>(out center))
         {
             Pawn pawn = PawnGenerator.GeneratePawn(kindDef, Faction.OfMechanoids);
             if (!GenPlace.TryPlaceThing(pawn, center, base.parent.Map, ThingPlaceMode.Near, null))
             {
                 Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard);
                 break;
             }
             this.lord.AddPawn(pawn);
             this.pointsLeft -= pawn.kindDef.combatPower;
         }
         this.pointsLeft = 0f;
         SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(base.parent.Map);
     }
 }
Пример #10
0
        public override void Resolve(ResolveParams rp)
        {
            int  num  = rp.mechanoidsCount ?? DefaultMechanoidCountRange.RandomInRange;
            Lord lord = rp.singlePawnLord;

            if (lord == null && num > 0)
            {
                Map map = BaseGen.globalSettings.map;
                lord = LordMaker.MakeNewLord(lordJob: (!Rand.Bool || !rp.rect.Cells.Where((IntVec3 x) => !x.Impassable(map)).TryRandomElement(out IntVec3 result)) ? ((LordJob) new LordJob_AssaultColony(Faction.OfMechanoids, canKidnap: false, canTimeoutOrFlee: false, sappers: false, useAvoidGridSmart: false, canSteal: false)) : ((LordJob) new LordJob_DefendPoint(result)), faction: Faction.OfMechanoids, map: map);
            }
            for (int i = 0; i < num; i++)
            {
                PawnKindDef pawnKindDef = rp.singlePawnKindDef;
                if (pawnKindDef == null)
                {
                    pawnKindDef = DefDatabase <PawnKindDef> .AllDefsListForReading.Where((PawnKindDef kind) => kind.RaceProps.IsMechanoid).RandomElementByWeight((PawnKindDef kind) => 1f / kind.combatPower);
                }
                ResolveParams resolveParams = rp;
                resolveParams.singlePawnKindDef = pawnKindDef;
                resolveParams.singlePawnLord    = lord;
                resolveParams.faction           = Faction.OfMechanoids;
                BaseGen.symbolStack.Push("pawn", resolveParams);
            }
        }
Пример #11
0
        protected override Job TryGiveJob(Pawn pawn)
        {
            Need_Rest    rest = pawn.needs.rest;
            Building_Bed building_Bed;

            if (rest != null && (int)rest.CurCategory >= (int)this.minCategory)
            {
                if (RestUtility.DisturbancePreventsLyingDown(pawn))
                {
                    return(null);
                }
                Lord lord = pawn.GetLord();
                if (lord != null && lord.CurLordToil != null && !lord.CurLordToil.AllowRestingInBed)
                {
                    goto IL_0065;
                }
                if (pawn.IsWildMan())
                {
                    goto IL_0065;
                }
                building_Bed = RestUtility.FindBedFor(pawn);
                goto IL_0073;
            }
            return(null);

IL_0073:
            if (building_Bed != null)
            {
                return(new Job(JobDefOf.LayDown, building_Bed));
            }
            return(new Job(JobDefOf.LayDown, this.FindGroundSleepSpotFor(pawn)));

IL_0065:
            building_Bed = null;
            goto IL_0073;
        }
Пример #12
0
 public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt)
 {
     if (dinfo.Def.externalViolence && dinfo.Instigator != null && dinfo.Instigator.Faction != null)
     {
         if (this.ticksToSpawnInitialPawns > 0)
         {
             this.SpawnInitialPawnsNow();
         }
         Lord lord = this.Lord;
         if (lord != null)
         {
             lord.ReceiveMemo(Hive.MemoAttackedByEnemy);
         }
     }
     if (dinfo.Def == DamageDefOf.Flame && (float)this.HitPoints < (float)base.MaxHitPoints * 0.30000001192092896)
     {
         Lord lord2 = this.Lord;
         if (lord2 != null)
         {
             lord2.ReceiveMemo(Hive.MemoBurnedBadly);
         }
     }
     base.PostApplyDamage(dinfo, totalDamageDealt);
 }
 public override bool ActivateOn(Lord lord, TriggerSignal signal)
 {
     if (signal.type == TriggerSignalType.Tick && Find.TickManager.TicksGame % 800 == 0)
     {
         TriggerData_PawnCycleInd data = this.Data;
         data.pawnCycleInd++;
         if (data.pawnCycleInd >= lord.ownedPawns.Count)
         {
             data.pawnCycleInd = 0;
         }
         if (lord.ownedPawns.Any <Pawn>())
         {
             Pawn pawn = lord.ownedPawns[data.pawnCycleInd];
             if (pawn.Spawned && !pawn.Downed && !pawn.InMentalState)
             {
                 if (KidnapAIUtility.ReachableWoundedGuest(pawn) != null)
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
        private Pawn FindBestCarrier(bool onlyAnimals)
        {
            Lord  lord = job.lord;
            Pawn  pawn = null;
            float num  = 0f;

            if (lord != null)
            {
                for (int i = 0; i < lord.ownedPawns.Count; i++)
                {
                    Pawn pawn2 = lord.ownedPawns[i];
                    if (pawn2 != base.pawn && (!onlyAnimals || pawn2.RaceProps.Animal) && IsUsableCarrier(pawn2, base.pawn, allowColonists: false))
                    {
                        float carrierScore = GetCarrierScore(pawn2);
                        if (pawn == null || carrierScore > num)
                        {
                            pawn = pawn2;
                            num  = carrierScore;
                        }
                    }
                }
            }
            return(pawn);
        }
Пример #15
0
        public void SpawnSurvivingPawns()
        {
            List <Pawn> survivingPawns = new List <Pawn>();

            foreach (Pawn pawn in this.pawnsAboard)
            {
                GenSpawn.Spawn(pawn, this.OccupiedRect().Cells.RandomElement(), this.Map);
                Expedition.RandomlyDamagePawn(pawn, Rand.RangeInclusive(1, 4), Rand.RangeInclusive(4, 16));
                if (pawn.Dead == false)
                {
                    survivingPawns.Add(pawn);
                }
            }
            this.pawnsAboard.Clear();
            if (survivingPawns.Count > 0)
            {
                IntVec3 exitSpot        = IntVec3.Invalid;
                bool    exitSpotIsValid = RCellFinder.TryFindBestExitSpot(survivingPawns.First(), out exitSpot, TraverseMode.PassAllDestroyableThings);
                if (exitSpotIsValid)
                {
                    Lord lord = LordMaker.MakeNewLord(Util_Faction.MiningCoFaction, new LordJob_ExitMap(exitSpot), this.Map, survivingPawns);
                }
            }
        }
Пример #16
0
 public override void Notify_QuestSignalReceived(Signal signal)
 {
     base.Notify_QuestSignalReceived(signal);
     if (signal.tag == inSignal && Map != null)
     {
         pawns.RemoveAll((Pawn x) => x.MapHeld != Map);
         for (int i = 0; i < pawns.Count; i++)
         {
             pawns[i].GetLord()?.Notify_PawnLost(pawns[i], PawnLostCondition.ForcedByQuest);
         }
         Lord lord = MakeLord();
         for (int j = 0; j < pawns.Count; j++)
         {
             if (!pawns[j].Dead)
             {
                 lord.AddPawn(pawns[j]);
             }
         }
     }
     if (signal.tag == inSignalRemovePawn && signal.args.TryGetArg("SUBJECT", out Pawn arg) && pawns.Contains(arg))
     {
         pawns.Remove(arg);
     }
 }
Пример #17
0
        public virtual void Enter(Caravan caravan)
        {
            if (!mapParent.HasMap)
            {
                return;
            }

            Map map = mapParent.Map;

            List <Pawn> pawns      = new List <Pawn>(caravan.PawnsListForReading);
            Pawn        randomPawn = pawns[0];

            Faction faction = randomPawn.Faction;

            if (CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => !c.Roofed(map) && c.Walkable(map) && c.Standable(map), map, 0f, out IntVec3 pos))
            {
                foreach (var pawn in pawns)
                {
                    GenSpawn.Spawn(pawn, pos, map);

                    if (pawn.trader != null)
                    {
                        pawn.trader = null;
                    }
                }
            }

            Find.WorldObjects.Remove(caravan);

            Find.LetterStack.ReceiveLetter("AssistCaravan_GifterArrivedTitle".Translate(), "AssistCaravan_GifterArrived".Translate(), LetterDefOf.PositiveEvent, new LookTargets(randomPawn));

            RCellFinder.TryFindRandomSpotJustOutsideColony(randomPawn, out IntVec3 result);

            LordJob_CaravanBringItems lordJob = new LordJob_CaravanBringItems(result, pawns);
            Lord lord = LordMaker.MakeNewLord(faction, lordJob, map, pawns);
        }
Пример #18
0
        private bool TrySpawnPawn(ThingOwner thingOwner, out Pawn pawn)
        {
            if (!this.canSpawnPawns)
            {
                pawn = null;
                return(false);
            }
            float       curPoints = this.SpawnedPawnsPoints;
            List <Pawn> sourced   = null;

            foreach (Pawn p in innerContainer)
            {
                sourced.Add(p);
            }
            IEnumerable <Pawn> source = from x in sourced
                                        where curPoints + x.kindDef.combatPower <= MaxSpawnedPawnsPoints
                                        select x;

            if (!source.TryRandomElement(out Pawn kind))
            {
                pawn = null;
                return(false);
            }
            pawn = kind;
            this.spawnedPawns.Add(pawn);
            GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(base.Position, base.Map, 2, null), base.Map, WipeMode.Vanish);
            Lord lord = this.Lord;

            if (lord == null)
            {
                lord = this.CreateNewLord();
            }
            lord.AddPawn(pawn);
            SoundDefOf.Hive_Spawn.PlayOneShot(this);
            return(true);
        }
Пример #19
0
        public IEnumerable <Gizmo> GetGizmos()
        {
            foreach (Gizmo g in this.priorityWork.GetGizmos())
            {
                yield return(g);
            }
            Lord lord = this.pawn.GetLord();

            if (lord != null && lord.LordJob is LordJob_FormAndSendCaravan)
            {
                yield return(new Command_Action
                {
                    defaultLabel = "CommandCancelFormingCaravan".Translate(),
                    defaultDesc = "CommandCancelFormingCaravanDesc".Translate(),
                    icon = TexCommand.ClearPrioritizedWork,
                    activateSound = SoundDefOf.TickLow,
                    action = delegate
                    {
                        CaravanFormingUtility.StopFormingCaravan(lord);
                    },
                    hotKey = KeyBindingDefOf.DesignatorCancel
                });
            }
        }
Пример #20
0
 // Token: 0x06002678 RID: 9848 RVA: 0x0012427C File Offset: 0x0012267C
 public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt)
 {
     if (dinfo.Def.ExternalViolenceFor(this) && dinfo.Instigator != null && dinfo.Instigator.Faction != null)
     {
         Lord lord = this.Lord;
         if (lord != null)
         {
             lord.ReceiveMemo(HiveLike.MemoAttackedByEnemy);
         }
     }
     if (dinfo.Def == DamageDefOf.Flame && (float)this.HitPoints < (float)base.MaxHitPoints * 0.3f)
     {
         Lord lord2 = this.Lord;
         if (lord2 != null)
         {
             lord2.ReceiveMemo(HiveLike.MemoBurnedBadly);
         }
     }
     if (this.innerContainer.Count > 0)
     {
         this.EjectContents();
     }
     base.PostApplyDamage(dinfo, totalDamageDealt);
 }
Пример #21
0
        public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate <Thing> validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = float.MaxValue, bool canBash = false, bool canTakeTargetsCloserThanEffectiveMinRange = true)
        {
            Thing searcherThing = searcher.Thing;
            Pawn  searcherPawn  = searcher as Pawn;
            Verb  verb          = searcher.CurrentEffectiveVerb;

            if (verb == null)
            {
                Log.Error("BestAttackTarget with " + searcher.ToStringSafe() + " who has no attack verb.");
                return(null);
            }
            bool  onlyTargetMachines = verb.IsEMP();
            float minDistSquared     = minDist * minDist;
            float num = maxTravelRadiusFromLocus + verb.verbProps.range;
            float maxLocusDistSquared         = num * num;
            Func <IntVec3, bool> losValidator = null;

            if ((flags & TargetScanFlags.LOSBlockableByGas) != 0)
            {
                losValidator = delegate(IntVec3 vec3)
                {
                    Gas gas = vec3.GetGas(searcherThing.Map);
                    return(gas == null || !gas.def.gas.blockTurretTracking);
                };
            }
            Predicate <IAttackTarget> innerValidator = delegate(IAttackTarget t)
            {
                Thing thing = t.Thing;
                if (t == searcher)
                {
                    return(false);
                }
                if (minDistSquared > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistSquared)
                {
                    return(false);
                }
                if (!canTakeTargetsCloserThanEffectiveMinRange)
                {
                    float num2 = verb.verbProps.EffectiveMinRange(thing, searcherThing);
                    if (num2 > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < num2 * num2)
                    {
                        return(false);
                    }
                }
                if (maxTravelRadiusFromLocus < 9999f && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared)
                {
                    return(false);
                }
                if (!searcherThing.HostileTo(thing))
                {
                    return(false);
                }
                if (validator != null && !validator(thing))
                {
                    return(false);
                }
                if (searcherPawn != null)
                {
                    Lord lord = searcherPawn.GetLord();
                    if (lord != null && !lord.LordJob.ValidateAttackTarget(searcherPawn, thing))
                    {
                        return(false);
                    }
                }
                if ((flags & TargetScanFlags.NeedLOSToAll) != 0)
                {
                    if (losValidator != null && (!losValidator(searcherThing.Position) || !losValidator(thing.Position)))
                    {
                        return(false);
                    }
                    if (!searcherThing.CanSee(thing, losValidator))
                    {
                        if (t is Pawn)
                        {
                            if ((flags & TargetScanFlags.NeedLOSToPawns) != 0)
                            {
                                return(false);
                            }
                        }
                        else if ((flags & TargetScanFlags.NeedLOSToNonPawns) != 0)
                        {
                            return(false);
                        }
                    }
                }
                if (((flags & TargetScanFlags.NeedThreat) != 0 || (flags & TargetScanFlags.NeedAutoTargetable) != 0) && t.ThreatDisabled(searcher))
                {
                    return(false);
                }
                if ((flags & TargetScanFlags.NeedAutoTargetable) != 0 && !IsAutoTargetable(t))
                {
                    return(false);
                }
                if ((flags & TargetScanFlags.NeedActiveThreat) != 0 && !GenHostility.IsActiveThreatTo(t, searcher.Thing.Faction))
                {
                    return(false);
                }
                Pawn pawn = t as Pawn;
                if (onlyTargetMachines && pawn != null && pawn.RaceProps.IsFlesh)
                {
                    return(false);
                }
                if ((flags & TargetScanFlags.NeedNonBurning) != 0 && thing.IsBurning())
                {
                    return(false);
                }
                if (searcherThing.def.race != null && (int)searcherThing.def.race.intelligence >= 2)
                {
                    CompExplosive compExplosive = thing.TryGetComp <CompExplosive>();
                    if (compExplosive != null && compExplosive.wickStarted)
                    {
                        return(false);
                    }
                }
                if (thing.def.size.x == 1 && thing.def.size.z == 1)
                {
                    if (thing.Position.Fogged(thing.Map))
                    {
                        return(false);
                    }
                }
                else
                {
                    bool flag2 = false;
                    foreach (IntVec3 item in thing.OccupiedRect())
                    {
                        if (!item.Fogged(thing.Map))
                        {
                            flag2 = true;
                            break;
                        }
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                }
                return(true);
            };

            if (HasRangedAttack(searcher) && (searcherPawn == null || !searcherPawn.InAggroMentalState))
            {
                tmpTargets.Clear();
                tmpTargets.AddRange(searcherThing.Map.attackTargetsCache.GetPotentialTargetsFor(searcher));
                if ((flags & TargetScanFlags.NeedReachable) != 0)
                {
                    Predicate <IAttackTarget> oldValidator2 = innerValidator;
                    innerValidator = ((IAttackTarget t) => oldValidator2(t) && CanReach(searcherThing, t.Thing, canBash));
                }
                bool flag = false;
                for (int i = 0; i < tmpTargets.Count; i++)
                {
                    IAttackTarget attackTarget = tmpTargets[i];
                    if (attackTarget.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) && innerValidator(attackTarget) && CanShootAtFromCurrentPosition(attackTarget, searcher, verb))
                    {
                        flag = true;
                        break;
                    }
                }
                IAttackTarget result;
                if (flag)
                {
                    tmpTargets.RemoveAll((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x));
                    result = GetRandomShootingTargetByScore(tmpTargets, searcher, verb);
                }
                else
                {
                    result = (IAttackTarget)GenClosest.ClosestThing_Global(validator: ((flags & TargetScanFlags.NeedReachableIfCantHitFromMyPos) == 0 || (flags & TargetScanFlags.NeedReachable) != 0) ? ((Predicate <Thing>)((Thing t) => innerValidator((IAttackTarget)t))) : ((Predicate <Thing>)((Thing t) => innerValidator((IAttackTarget)t) && (CanReach(searcherThing, t, canBash) || CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb)))), center: searcherThing.Position, searchSet: tmpTargets, maxDistance: maxDist);
                }
                tmpTargets.Clear();
                return(result);
            }
            if (searcherPawn != null && searcherPawn.mindState.duty != null && searcherPawn.mindState.duty.radius > 0f && !searcherPawn.InMentalState)
            {
                Predicate <IAttackTarget> oldValidator = innerValidator;
                innerValidator = delegate(IAttackTarget t)
                {
                    if (!oldValidator(t))
                    {
                        return(false);
                    }
                    return(t.Thing.Position.InHorDistOf(searcherPawn.mindState.duty.focus.Cell, searcherPawn.mindState.duty.radius) ? true : false);
                };
            }
            IAttackTarget attackTarget2 = (IAttackTarget)GenClosest.ClosestThingReachable(searcherThing.Position, searcherThing.Map, ThingRequest.ForGroup(ThingRequestGroup.AttackTarget), PathEndMode.Touch, TraverseParms.For(searcherPawn, Danger.Deadly, TraverseMode.ByPawn, canBash), maxDist, (Thing x) => innerValidator((IAttackTarget)x), null, 0, (maxDist > 800f) ? (-1) : 40);

            if (attackTarget2 != null && PawnUtility.ShouldCollideWithPawns(searcherPawn))
            {
                IAttackTarget attackTarget3 = FindBestReachableMeleeTarget(innerValidator, searcherPawn, maxDist, canBash);
                if (attackTarget3 != null)
                {
                    float lengthHorizontal  = (searcherPawn.Position - attackTarget2.Thing.Position).LengthHorizontal;
                    float lengthHorizontal2 = (searcherPawn.Position - attackTarget3.Thing.Position).LengthHorizontal;
                    if (Mathf.Abs(lengthHorizontal - lengthHorizontal2) < 50f)
                    {
                        attackTarget2 = attackTarget3;
                    }
                }
            }
            return(attackTarget2);
        }
Пример #22
0
        private static void SendHomeDialog(Lord lord)
        {
            var text = txtSendAwayQuestion.Translate(new NamedArgument(lord.faction, "FACTION"));

            Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(text, () => SendHome(lord)));
        }
Пример #23
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.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[0];
                            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[0]);
                            if (!dismissMinion.Destroyed)
                            {
                                dismissMinion.Destroy();
                                Messages.Message("TM_SummonedCreatureLimitExceeded".Translate(new object[]
                                {
                                    this.launcher.LabelShort
                                }), MessageTypeDefOf.NeutralEvent);
                            }
                            if (comp.summonedMinions.Count > 4)
                            {
                                while (comp.summonedMinions.Count > 4)
                                {
                                    Pawn excessMinion = comp.summonedMinions[comp.summonedMinions.Count - 1] 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(new object[]
                            {
                                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);
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
Пример #24
0
        private static void MakeBlueprintObject(Map map, Faction faction, CellRect mapRect, BaseBlueprintDef blueprint, ThingDef stuffDef, out Dictionary <Pawn, LordType> pawns, out float totalThreat, bool useOneFaction = false, bool useAddtionalThreat = false, float additionalPoints = 0f)
        {
            blueprint.buildingData    = GetCleanedBlueprintData(blueprint.buildingData);
            blueprint.nonbuildingData = GetCleanedBlueprintData(blueprint.nonbuildingData);
            blueprint.floorData       = GetCleanedBlueprintData(blueprint.floorData);
            blueprint.pawnData        = GetCleanedBlueprintData(blueprint.pawnData);
            blueprint.itemData        = GetCleanedBlueprintData(blueprint.itemData);

            pawns       = null;
            totalThreat = 0;

            if (blueprint.buildingData == null && blueprint.nonbuildingData == null && blueprint.floorData == null)
            {
                Log.ErrorOnce(string.Format("After cleaning the BlueprintData and FloorData of blueprint {0} -> both are null, nothing will be done!", blueprint.defName), 313001);
                return;
            }

            IntVec3 spawnBaseCell = new IntVec3(mapRect.BottomLeft.x, mapRect.TopRight.y, mapRect.TopRight.z);
            IntVec3 spawnCell;

            //// Check all cells and abort if there is something indestructible found -> disabled
            //foreach (IntVec3 cell in mapRect)
            //{
            //    if (!CheckCell(cell, map))
            //        return;
            //}

            //allSpawnedPawns = null;


            // Disable automatic room updating
            map.regionAndRoomUpdater.Enabled = false;

            int step = 1;

            while (step <= 5)
            {
                //Log.Warning("Current step: " + step);

                // Work through blueprint - Note: top-left to bottom-right
                // Work step by step: 1st all floors, 2nd all things, 3rd all items, 4th all pawns
                for (int zn = 0; zn < blueprint.size.z; zn++)
                {
                    for (int x = 0; x < blueprint.size.x; x++)
                    {
                        //// map can be clipped, don't work with the clipped parts
                        //if (x > mapRect.Width - 1 || zn > mapRect.Height - 1)
                        //    continue;

                        if (blueprint.canHaveHoles && Rand.Value < 0.08f)
                        {
                            continue;
                        }

                        spawnCell = spawnBaseCell + new IntVec3(x, 0, -zn);

                        if (!TrySetCell_prepare_CheckCell(spawnCell, map))
                        {
                            continue;
                        }


                        int itemPos = x + blueprint.size.x * zn;

                        try
                        {
                            ThingData thingData    = TryGetThingDefFromBuildingData(blueprint, itemPos);
                            Rot4      thingRot     = TryGetRotationFromBuildingData(blueprint, itemPos);
                            ThingData nonthingData = TryGetThingDefFromNonBuildingData(blueprint, itemPos);
                            ThingData terrainData  = TryGetTerrainDefFromFloorData(blueprint, itemPos);
                            ThingData pawnKindData = TryGetPawnKindDefFromPawnData(blueprint, itemPos);
                            ThingData itemData     = TryGetItemDefFromItemData(blueprint, itemPos);

                            //List<Thing> list = map.thingGrid.ThingsListAt(spawnCell);
                            //for (int i = 0; i < list.Count; i++)
                            //{
                            //    if (list[i].def == thingDef)
                            //        continue;
                            //}


                            //Only clear the space, if something will be made here
                            // Do only in step 1:
                            if (step == 1)
                            {
                                if (thingData?.Thing != null || terrainData?.Terrain != null || pawnKindData?.Kind != null || itemData?.Thing != null)
                                {
                                    ClearCell(spawnCell, map);
                                }
                            }

                            switch (step)
                            {
                            case 1:     // Terrain
                                TrySetCell_1_SetFloor(spawnCell, map, terrainData, thingData?.Thing, stuffDef);
                                break;

                            case 2:     // non-Building
                                TrySetCell_3_SetNonThing(spawnCell, map, nonthingData, stuffDef);
                                break;

                            case 3:     // Building
                                TrySetCell_2_SetThing(spawnCell, map, faction, thingData, thingRot, stuffDef);
                                break;

                            case 4:     // Item
                                TrySetCell_4_SetItem(spawnCell, map, itemData);
                                break;

                            case 5:     // Pawn
                                TrySetCell_5_SetPawn(spawnCell, map, faction, pawnKindData, useOneFaction);
                                break;

                            default:
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Warning("MapGeneratorFactionBase - Error while creating the blueprint (" + blueprint.defName + ")\n" + ex.Message + "\n" + ex.StackTrace);
                        }
                    }
                }
                step++;
            }

            // Update the powernets
            map.powerNetManager.UpdatePowerNetsAndConnections_First();

            // Enable automatic room updating and rebuild all rooms
            map.regionAndRoomUpdater.Enabled = true;
            map.regionAndRoomUpdater.RebuildAllRegionsAndRooms();

            HashSet <Room> rooms = new HashSet <Room>();

            foreach (IntVec3 current in mapRect.Cells)
            {
                // Find all created rooms
                Room room = current.GetRoom(map);
                if (room != null && !room.TouchesMapEdge)
                {
                    rooms.Add(room);
                }
                else
                {
                    map.fogGrid.Unfog(current);
                }
            }

            if (!blueprint.FogRooms)
            {
                AddRoomCentersToRootsToUnfog(rooms.ToList());
            }
            else
            {
                AddRoomsToFog(rooms.ToList(), map);
            }

            Lord lordDefend = null;
            Lord lordAttack = null;

            foreach (var pair in allSpawnedPawns)
            {
                switch (pair.Value)
                {
                case LordType.Defend:
                {
                    if (lordDefend == null)
                    {
                        lordDefend = LordMaker.MakeNewLord(faction, new LordJob_DefendBase(faction, mapRect.CenterCell), map, null);
                        lordDefend.numPawnsLostViolently = int.MaxValue;
                    }

                    lordDefend.AddPawn(pair.Key);

                    break;
                }

                case LordType.Attack:
                {
                    if (lordAttack == null)
                    {
                        lordAttack = LordMaker.MakeNewLord(faction, new LordJob_AssaultColony(faction, canTimeoutOrFlee: false), map, null);
                        lordAttack.numPawnsLostViolently = int.MaxValue;
                    }

                    lordAttack.AddPawn(pair.Key);

                    break;
                }
                }

                totalThreat += (int)pair.Key.kindDef.combatPower;
            }


            // Make additional pawns if these are not enough!
            if (useAddtionalThreat || blueprint.UseAdditionalThreat)
            {
                if (lordDefend == null)
                {
                    lordDefend = LordMaker.MakeNewLord(faction, new LordJob_DefendBase(faction, mapRect.CenterCell), map, null);
                    lordDefend.numPawnsLostViolently = int.MaxValue;
                }

                float total = blueprint.ThreatsPoints + additionalPoints;

                //Log.Warning("Info: Creating base pawns..");
                PrepareBaseGen_PawnGroup(map, mapRect, faction, rooms.ToList(), lordDefend, total);
            }

            PrepareBaseGen_CampFires(map, mapRect, faction);

            BaseGen.Generate();

            /*
             * if (allSpawnedPawns != null)
             * {
             *  foreach (Pawn pawn in allSpawnedPawns)
             *      pawnLord.AddPawn(pawn);
             * }
             */

            pawns = allSpawnedPawns;

            //allSpawnedPawns = null;
        }
Пример #25
0
        private static void PrepareBaseGen_PawnGroup(Map map, CellRect rect, Faction faction, List <Room> rooms, Lord lord, float pointsUsed)
        {
            ResolveParams resolveParams = default(ResolveParams);

            resolveParams.rect             = rect;
            resolveParams.faction          = faction;
            resolveParams.singlePawnLord   = lord;
            resolveParams.pawnGroupKindDef = PawnGroupKindDefOf.Settlement;
            resolveParams.singlePawnSpawnCellExtraPredicate = ((IntVec3 x) => CanReachARoom(map, x, rooms));

            resolveParams.pawnGroupMakerParams         = new PawnGroupMakerParms();
            resolveParams.pawnGroupMakerParams.tile    = map.Tile;
            resolveParams.pawnGroupMakerParams.faction = faction;
            resolveParams.pawnGroupMakerParams.points  = pointsUsed;

            BaseGen.globalSettings.map = map;
            BaseGen.symbolStack.Push("pawnGroup", resolveParams);
        }
        public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, Verb verb, TargetScanFlags flags, Predicate <Thing> validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = 3.40282347E+38f, bool canBash = false, bool canTakeTargetsCloserThanEffectiveMinRange = true)
        {
            Thing searcherThing = searcher.Thing;
            Pawn  searcherPawn  = searcher as Pawn;

            if (verb == null)
            {
                Log.Error("BestAttackTarget with " + searcher.ToStringSafe <IAttackTargetSearcher>() + " who has no attack verb.", false);
                return(null);
            }
            bool  onlyTargetMachines = verb.IsEMP();
            float minDistSquared     = minDist * minDist;
            float num = maxTravelRadiusFromLocus + verb.verbProps.range;
            float maxLocusDistSquared         = num * num;
            Func <IntVec3, bool> losValidator = null;

            if ((byte)(flags & TargetScanFlags.LOSBlockableByGas) != 0)
            {
                losValidator = delegate(IntVec3 vec3)
                {
                    Gas gas = vec3.GetGas(searcherThing.Map);
                    return(gas == null || !gas.def.gas.blockTurretTracking);
                };
            }
            Predicate <IAttackTarget> innerValidator = delegate(IAttackTarget t)
            {
                Thing thing = t.Thing;
                if (t == searcher)
                {
                    return(false);
                }
                if (minDistSquared > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistSquared)
                {
                    return(false);
                }
                if (!canTakeTargetsCloserThanEffectiveMinRange)
                {
                    float num2 = verb.verbProps.EffectiveMinRange(thing, searcherThing);
                    if (num2 > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < num2 * num2)
                    {
                        return(false);
                    }
                }
                if (maxTravelRadiusFromLocus < 9999f && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared)
                {
                    return(false);
                }
                if (!searcherThing.HostileTo(thing))
                {
                    return(false);
                }
                if (validator != null && !validator(thing))
                {
                    return(false);
                }
                if (searcherPawn != null)
                {
                    Lord lord = searcherPawn.GetLord();
                    if (lord != null && !lord.LordJob.ValidateAttackTarget(searcherPawn, thing))
                    {
                        return(false);
                    }
                }
                if ((byte)(flags & TargetScanFlags.NeedLOSToAll) != 0 && !searcherThing.CanSee(thing, losValidator))
                {
                    if (t is Pawn)
                    {
                        if ((byte)(flags & TargetScanFlags.NeedLOSToPawns) != 0)
                        {
                            return(false);
                        }
                    }
                    else if ((byte)(flags & TargetScanFlags.NeedLOSToNonPawns) != 0)
                    {
                        return(false);
                    }
                }
                if ((byte)(flags & TargetScanFlags.NeedThreat) != 0 && t.ThreatDisabled(searcher))
                {
                    return(false);
                }
                if (onlyTargetMachines && t is Pawn pawn && pawn.RaceProps.IsFlesh)
                {
                    return(false);
                }
                if ((byte)(flags & TargetScanFlags.NeedNonBurning) != 0 && thing.IsBurning())
                {
                    return(false);
                }
                if (searcherThing.def.race != null && searcherThing.def.race.intelligence >= Intelligence.Humanlike)
                {
                    CompExplosive compExplosive = thing.TryGetComp <CompExplosive>();
                    if (compExplosive != null && compExplosive.wickStarted)
                    {
                        return(false);
                    }
                }
                if (thing.def.size.x == 1 && thing.def.size.z == 1)
                {
                    if (thing.Position.Fogged(thing.Map))
                    {
                        return(false);
                    }
                }
                else
                {
                    bool flag2 = false;
                    foreach (IntVec3 cellRect in thing.OccupiedRect())
                    {
                        if (cellRect.Fogged(thing.Map))
                        {
                            flag2 = true;
                            break;
                        }
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                }
                return(true);
            };

            if (PCF_AttackTargetFinder.HasRangedAttack(searcher, verb))
            {
                PCF_AttackTargetFinder.tmpTargets.Clear();
                PCF_AttackTargetFinder.tmpTargets.AddRange(searcherThing.Map.attackTargetsCache.GetPotentialTargetsFor(searcher));
                if ((byte)(flags & TargetScanFlags.NeedReachable) != 0)
                {
                    Predicate <IAttackTarget> oldValidator = innerValidator;
                    innerValidator = ((IAttackTarget t) => oldValidator(t) && PCF_AttackTargetFinder.CanReach(searcherThing, t.Thing, canBash));
                }
                bool flag = false;
                for (int i = 0; i < PCF_AttackTargetFinder.tmpTargets.Count; i++)
                {
                    IAttackTarget attackTarget = PCF_AttackTargetFinder.tmpTargets[i];
                    if (attackTarget.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) && innerValidator(attackTarget) && PCF_AttackTargetFinder.CanShootAtFromCurrentPosition(attackTarget, searcher, verb))
                    {
                        flag = true;
                        break;
                    }
                }
                IAttackTarget result;
                if (flag)
                {
                    PCF_AttackTargetFinder.tmpTargets.RemoveAll((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x));
                    result = PCF_AttackTargetFinder.GetRandomShootingTargetByScore(PCF_AttackTargetFinder.tmpTargets, searcher, verb);
                }
                else
                {
                    Predicate <Thing> validator2;
                    if ((byte)(flags & TargetScanFlags.NeedReachableIfCantHitFromMyPos) != 0 && (byte)(flags & TargetScanFlags.NeedReachable) == 0)
                    {
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t) && (PCF_AttackTargetFinder.CanReach(searcherThing, t, canBash) || PCF_AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb)));
                    }
                    else
                    {
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t));
                    }
                    result = (IAttackTarget)GenClosest.ClosestThing_Global(searcherThing.Position, PCF_AttackTargetFinder.tmpTargets, maxDist, validator2, null);
                }
                PCF_AttackTargetFinder.tmpTargets.Clear();
                return(result);
            }
            if (searcherPawn != null && searcherPawn.mindState.duty != null && searcherPawn.mindState.duty.radius > 0f && !searcherPawn.InMentalState)
            {
                Predicate <IAttackTarget> oldValidator = innerValidator;
                innerValidator = ((IAttackTarget t) => oldValidator(t) && t.Thing.Position.InHorDistOf(searcherPawn.mindState.duty.focus.Cell, searcherPawn.mindState.duty.radius));
            }
            IntVec3       position       = searcherThing.Position;
            Map           map            = searcherThing.Map;
            ThingRequest  thingReq       = ThingRequest.ForGroup(ThingRequestGroup.AttackTarget);
            PathEndMode   peMode         = PathEndMode.Touch;
            Pawn          searcherPawn2  = searcherPawn;
            Danger        maxDanger      = Danger.Deadly;
            bool          canBash2       = canBash;
            TraverseParms traverseParams = TraverseParms.For(searcherPawn2, maxDanger, TraverseMode.ByPawn, canBash2);
            float         maxDist2       = maxDist;

            bool validator3(Thing x) => innerValidator((IAttackTarget)x);

            int           searchRegionsMax = (maxDist <= 800f) ? 40 : -1;
            IAttackTarget attackTarget2    = (IAttackTarget)GenClosest.ClosestThingReachable(position, map, thingReq, peMode, traverseParams, maxDist2, validator3, null, 0, searchRegionsMax, false, RegionType.Set_Passable, false);

            if (attackTarget2 != null && PawnUtility.ShouldCollideWithPawns(searcherPawn))
            {
                IAttackTarget attackTarget3 = PCF_AttackTargetFinder.FindBestReachableMeleeTarget(innerValidator, searcherPawn, maxDist, canBash);
                if (attackTarget3 != null)
                {
                    float lengthHorizontal  = (searcherPawn.Position - attackTarget2.Thing.Position).LengthHorizontal;
                    float lengthHorizontal2 = (searcherPawn.Position - attackTarget3.Thing.Position).LengthHorizontal;
                    if (Mathf.Abs(lengthHorizontal - lengthHorizontal2) < 50f)
                    {
                        attackTarget2 = attackTarget3;
                    }
                }
            }
            return(attackTarget2);
        }
Пример #27
0
 public Unit(Lord lord)
 {
     this.lord = lord;
 }
Пример #28
0
        // Token: 0x0600018D RID: 397 RVA: 0x0000EE2C File Offset: 0x0000D02C
        public override void Resolve(ResolveParams rp)
        {
            Map     map           = BaseGen.globalSettings.map;
            Faction parentFaction = map.ParentFaction;
            int     dist          = 0;
            bool    flag          = rp.edgeDefenseWidth != null;

            if (flag)
            {
                dist = rp.edgeDefenseWidth.Value;
            }
            else
            {
                Rand.PushState();
                bool flag2 = rp.rect.Width >= 20 && rp.rect.Height >= 20 && (parentFaction.def.techLevel >= TechLevel.Industrial || Rand.Bool);
                Rand.PopState();
                if (flag2)
                {
                    Rand.PushState();
                    dist = (Rand.Bool ? 2 : 4);
                    Rand.PopState();
                }
            }
            float num = (float)rp.rect.Area / 144f * 0.17f;

            //	Log.Message("SymbolResolver_Hivebase "+ rp.rect.Width+", "+ rp.rect.Width);
            //	BaseGen.symbolStack.Push("basePart_outdoors", resolveParams4, null);
            BaseGen.globalSettings.minEmptyNodes = ((num < 1f) ? 0 : GenMath.RoundRandom(num));
            Lord          singlePawnLord = rp.singlePawnLord ?? LordMaker.MakeNewLord(parentFaction, new LordJob_DefendHiveBase(parentFaction, GenRadial.RadialCellsAround(rp.rect.CenterCell, 5, true).Where(x => x.Walkable(map)).RandomElement()), map, null);
            TraverseParms traverseParms  = TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false);
            ResolveParams resolveParams  = rp;

            resolveParams.rect             = rp.rect;
            resolveParams.faction          = parentFaction;
            resolveParams.singlePawnLord   = singlePawnLord;
            resolveParams.pawnGroupKindDef = (rp.pawnGroupKindDef ?? RimWorld.PawnGroupKindDefOf.Settlement);
            resolveParams.singlePawnSpawnCellExtraPredicate = (rp.singlePawnSpawnCellExtraPredicate ?? ((IntVec3 x) => map.reachability.CanReachMapEdge(x, traverseParms)));
            if (resolveParams.pawnGroupMakerParams == null)
            {
                resolveParams.pawnGroupMakerParams             = new PawnGroupMakerParms();
                resolveParams.pawnGroupMakerParams.tile        = map.Tile;
                resolveParams.pawnGroupMakerParams.faction     = parentFaction;
                resolveParams.pawnGroupMakerParams.points      = (rp.settlementPawnGroupPoints ?? SymbolResolver_Settlement.DefaultPawnsPoints.RandomInRange);
                resolveParams.pawnGroupMakerParams.inhabitants = true;
                resolveParams.pawnGroupMakerParams.groupKind   = RimWorld.PawnGroupKindDefOf.Settlement;
                resolveParams.pawnGroupMakerParams.seed        = rp.settlementPawnGroupSeed;
            }
            else
            {
                //	Log.Message("Points " + resolveParams.pawnGroupMakerParams.points);
            }
            BaseGen.symbolStack.Push("ExtraHives_PawnGroup", resolveParams, null);
            PawnGenerationRequest value          = new PawnGenerationRequest(parentFaction.def.pawnGroupMakers.Where(x => x.kindDef == PawnGroupKindDefOf.Hive_ExtraHives || x.kindDef == RimWorld.PawnGroupKindDefOf.Combat).RandomElement().options.RandomElementByWeight(x => x.Cost).kind, parentFaction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, true, false, false, false, false, 0f, null, 1f, null, null, null, null, null, null, null, null, null, null, null, null);
            ResolveParams         resolveParams2 = rp;

            resolveParams2.faction = parentFaction;
            resolveParams2.singlePawnGenerationRequest = new PawnGenerationRequest?(value);
            resolveParams2.rect           = rp.rect;
            resolveParams2.singlePawnLord = singlePawnLord;
            BaseGen.symbolStack.Push("ExtraHives_Pawn", resolveParams2, null);
            ResolveParams resolveParams3 = rp;

            resolveParams3.rect    = rp.rect.ContractedBy(dist);
            resolveParams3.faction = parentFaction;
            BaseGen.symbolStack.Push("ensureCanReachMapEdge", resolveParams3, null);

            ResolveParams resolveParams5 = rp;

            BaseGen.symbolStack.Push("ExtraHives_HiveRandomCorpse", rp, null);

            ResolveParams resolveParams4 = rp;

            resolveParams4.rect    = rp.rect.ContractedBy(dist);
            resolveParams4.faction = parentFaction;
            resolveParams4.floorOnlyIfTerrainSupports = new bool?(rp.floorOnlyIfTerrainSupports ?? true);
            resolveParams4.wallStuff             = (rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, true));
            resolveParams4.chanceToSkipWallBlock = new float?(rp.chanceToSkipWallBlock ?? 0.1f);
            resolveParams4.clearEdificeOnly      = new bool?(rp.clearEdificeOnly ?? true);
            resolveParams4.noRoof             = new bool?(rp.noRoof ?? true);
            resolveParams4.chanceToSkipFloor  = new float?(rp.chanceToSkipFloor ?? 0.1f);
            resolveParams4.filthDef           = RimWorld.ThingDefOf.Filth_Slime;
            resolveParams4.filthDensity       = new FloatRange?(new FloatRange(0.5f, 1f));
            resolveParams4.cultivatedPlantDef = null;

            BaseGen.symbolStack.Push("ExtraHives_HiveInterals", resolveParams4, null);

            BaseGen.symbolStack.Push("ExtraHives_HiveMoundMaker", resolveParams4, null);
        }
Пример #29
0
        public override bool TryExecuteWorker(IncidentParms parms)
        {
            if (Settings.disableSkyMindSecurityStuff)
            {
                return(false);
            }

            List <Pawn>   victims;
            List <string> cryptolockedThings = new List <string>();
            string        title = "";
            string        msg   = "";
            int           nbConnectedClients   = Utils.GCATPP.getNbThingsConnected();
            int           nbSurrogates         = Utils.GCATPP.getNbSurrogateAndroids();
            int           nbUnsecurisedClients = nbConnectedClients - Utils.GCATPP.getNbSlotSecurisedAvailable();

            LetterDef letter;
            //Selection type virus
            int attackType = 1;
            int fee        = 0;

            //Check si sur lensemble des clients connecté il y a quand meme des surrogates
            if (nbSurrogates <= 0)
            {
                return(false);
            }

            //Attaque virale faible
            if (nbUnsecurisedClients <= 0)
            {
                if (!Rand.Chance(Settings.riskSecurisedSecuritySystemGetVirus))
                {
                    return(false);
                }

                int nb = 0;


                nb = nbSurrogates / 2;
                if (nb != 0)
                {
                    nb = Rand.Range(1, nb + 1);
                }
                else
                {
                    nb = 1;
                }

                letter = LetterDefOf.ThreatSmall;
                //Obtention des victimes
                victims = Utils.GCATPP.getRandomSurrogateAndroids(nb);
                if (victims.Count == 0)
                {
                    return(false);
                }

                foreach (var v in victims)
                {
                    CompSkyMind      csm = v.TryGetComp <CompSkyMind>();
                    CompAndroidState cas = v.ATCompState;
                    if (csm == null || cas == null)
                    {
                        continue;
                    }

                    csm.Infected = 4;

                    //Deconnection du contorlleur le cas echeant
                    if (cas.surrogateController != null)
                    {
                        CompSurrogateOwner cso = cas.surrogateController.ATCompSurrogateOwner;
                        if (cso != null)
                        {
                            cso.disconnectControlledSurrogate(null);
                        }
                    }

                    Hediff he = v.health.hediffSet.GetFirstHediffOfDef(Utils.hediffNoHost);
                    if (he != null)
                    {
                        v.health.RemoveHediff(he);
                    }

                    Utils.ignoredPawnNotifications = v;
                    Utils.VirusedRandomMentalBreak.RandomElement().Worker.TryStart(v, null, false);
                    Utils.ignoredPawnNotifications = null;
                    //v.mindState.mentalStateHandler.TryStartMentalState(  , null, false, false, null, false);
                }


                title = "ATPP_IncidentSurrogateHackingVirus".Translate();
                msg   = "ATPP_IncidentSurrogateHackingLiteDesc".Translate(nb);
            }
            else
            {
                letter = LetterDefOf.ThreatBig;

                attackType = Rand.Range(1, 4);

                int nb = 0;
                LordJob_AssaultColony lordJob;
                Lord lord = null;

                if (attackType != 3)
                {
                    //Attaque virale douce
                    //Obtention des victimes (qui peut allez de 1 victime a N/2 victimes
                    nb = nbSurrogates / 2;
                    if (nb != 0)
                    {
                        nb = Rand.Range(1, nb + 1);
                    }
                    else
                    {
                        nb = 1;
                    }

                    lordJob = new LordJob_AssaultColony(Faction.OfAncientsHostile, false, false, false, false, false);

                    if (lordJob != null)
                    {
                        lord = LordMaker.MakeNewLord(Faction.OfAncientsHostile, lordJob, Current.Game.CurrentMap, null);
                    }
                }
                else
                {
                    nb = nbSurrogates;
                }

                msg = "ATPP_IncidentSurrogateHackingHardDesc".Translate(nb) + "\n";

                switch (attackType)
                {
                case 1:
                    title = "ATPP_IncidentSurrogateHackingVirus".Translate();
                    msg  += "ATPP_IncidentVirusedDesc".Translate();
                    break;

                case 2:
                    title = "ATPP_IncidentSurrogateHackingExplosiveVirus".Translate();
                    msg  += "ATPP_IncidentVirusedExplosiveDesc".Translate();
                    break;

                case 3:
                    title = "ATPP_IncidentSurrogateHackingCryptolocker".Translate();
                    msg  += "ATPP_IncidentCryptolockerDesc".Translate();
                    break;
                }

                victims = Utils.GCATPP.getRandomSurrogateAndroids(nb);
                if (victims.Count != nb)
                {
                    return(false);
                }

                foreach (var v in victims)
                {
                    CompSkyMind csm = v.TryGetComp <CompSkyMind>();

                    v.mindState.canFleeIndividual = false;
                    csm.Infected = attackType;
                    if (v.jobs != null)
                    {
                        v.jobs.StopAll();
                        v.jobs.ClearQueuedJobs();
                    }
                    if (v.mindState != null)
                    {
                        v.mindState.Reset(true);
                    }


                    switch (attackType)
                    {
                    //Virus
                    case 1:
                        //Devient hostile
                        if (lord != null)
                        {
                            lord.AddPawn(v);
                        }
                        break;

                    //Virus explosif
                    case 2:
                        //Devient hostile
                        if (lord != null)
                        {
                            lord.AddPawn(v);
                        }
                        break;

                    //Virus cryptolocker
                    case 3:
                        cryptolockedThings.Add(v.GetUniqueLoadID());

                        switch (v.def.defName)
                        {
                        case Utils.T2:
                            fee += Settings.ransomCostT2;
                            break;

                        case Utils.T3:
                            fee += Settings.ransomCostT3;
                            break;

                        case Utils.T4:
                            fee += Settings.ransomCostT4;
                            break;

                        case Utils.T5:
                            fee += Settings.ransomCostT5;
                            break;

                        case Utils.T1:
                        default:
                            fee += Settings.ransomCostT1;
                            break;
                        }
                        break;
                    }

                    if (attackType == 1 || attackType == 2)
                    {
                        //On va attribuer aleatoirement des poids d'attaque aux surrogate
                        SkillRecord shooting = v.skills.GetSkill(SkillDefOf.Shooting);
                        if (shooting != null && !shooting.TotallyDisabled)
                        {
                            shooting.levelInt = Rand.Range(3, 19);
                        }
                        SkillRecord melee = v.skills.GetSkill(SkillDefOf.Melee);
                        if (melee != null && !melee.TotallyDisabled)
                        {
                            melee.levelInt = Rand.Range(3, 19);
                        }
                    }
                }
            }

            Find.LetterStack.ReceiveLetter(title, msg, letter, (LookTargets)victims, null, null);


            if (attackType == 3)
            {
                //Déduction faction ennemis au hasard
                Faction faction = Find.FactionManager.RandomEnemyFaction();

                ChoiceLetter_RansomDemand ransom = (ChoiceLetter_RansomDemand)LetterMaker.MakeLetter(DefDatabase <LetterDef> .GetNamed("ATPP_CLPayCryptoRansom"));
                ransom.label              = "ATPP_CryptolockerNeedPayRansomTitle".Translate();
                ransom.text               = "ATPP_CryptolockerNeedPayRansom".Translate(faction.Name, fee);
                ransom.faction            = faction;
                ransom.radioMode          = true;
                ransom.fee                = fee;
                ransom.cryptolockedThings = cryptolockedThings;
                ransom.StartTimeout(60000);
                Find.LetterStack.ReceiveLetter(ransom, null);
            }

            return(true);
        }
        private void CloseMapImmediate()
        {
            MapParent mapParent = this.parent as MapParent;

            if (mapParent != null)
            {
                if (Dialog_FormCaravan.AllSendablePawns(mapParent.Map, true).Any((Pawn x) => x.IsColonist || x.IsPrisonerOfColony || x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer))
                {
                    foreach (Pawn pawn in mapParent.Map.mapPawns.AllPawnsSpawned)
                    {
                        if (pawn.RaceProps.Humanlike)
                        {
                            Lord lord = pawn.GetLord();
                            if (lord != null)
                            {
                                lord.Notify_PawnLost(pawn, PawnLostCondition.ExitedMap);
                                pawn.ClearMind(false);
                            }
                        }
                    }
                    Messages.Message("MessageYouHaveToReformCaravanNow".Translate(), new GlobalTargetInfo(mapParent.Tile), MessageTypeDefOf.NeutralEvent);
                    Current.Game.CurrentMap = mapParent.Map;
                    Dialog_FormCaravan window = new Dialog_FormCaravan(mapParent.Map, true, delegate()
                    {
                        if (mapParent.HasMap)
                        {
                            Find.WorldObjects.Remove(mapParent);
                        }
                    }, false);
                    List <Pawn> list = mapParent.Map.mapPawns.AllPawnsSpawned.ToList <Pawn>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        Pawn pawn2 = list[i];
                        if (!pawn2.HostileTo(Faction.OfPlayer) && (pawn2.Faction == Faction.OfPlayer || pawn2.IsPrisonerOfColony))
                        {
                            Log.Message(pawn2.Label + " Meets criteria in CaravanUtility.");
                        }
                        else
                        {
                            Log.Message(pawn2.Label + " NOT ALLOWED by in CaravanUtility.");
                        }
                    }
                    Find.WindowStack.Add(window);
                }
                else
                {
                    List <Pawn> list2 = new List <Pawn>();
                    list2.AddRange(from x in mapParent.Map.mapPawns.AllPawns
                                   where x.IsColonist || x.IsPrisonerOfColony || x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer
                                   select x);
                    if (list2.Any <Pawn>())
                    {
                        if (list2.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer)))
                        {
                            //TODO: check if it works
                            CaravanExitMapUtility.ExitMapAndCreateCaravan(list2, Faction.OfPlayer,
                                                                          mapParent.Tile, mapParent.Tile, mapParent.Tile, false);
                            Messages.Message("MessageReformedCaravan".Translate(),
                                             MessageTypeDefOf.PositiveEvent);
                        }
                        else
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int j = 0; j < list2.Count; j++)
                            {
                                stringBuilder.AppendLine("    " + list2[j].LabelCap);
                            }
                            Find.LetterStack.ReceiveLetter("RD_LetterLabelPawnsLostDueToMapCountdown".Translate(),
                                                           TranslatorFormattedStringExtensions.Translate("RD_LetterPawnsLostDueToMapCountdown",
                                                                                                         new NamedArgument[]
                            {
                                stringBuilder.ToString().TrimEndNewlines()
                            }), LetterDefOf.ThreatSmall, new GlobalTargetInfo(mapParent.Tile), null);
                        }
                        list2.Clear();
                    }
                    Find.WorldObjects.Remove(mapParent);
                }
            }
        }
Пример #31
0
        public override void GenerateForces(Map map, ResolveParams rp)
        {
            Debug.Log(Debug.ForceGen, "Generating mechanoid forces");

            ScatterOptions options = rp.GetCustom <ScatterOptions>(Constants.ScatterOptions);
            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.OfAncientsHostile;

            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, false, 1f,
                                              false, true, true, false,
                                              false, false, false,
                                              null, 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.MakeFilth(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
                }
            }
        }
Пример #32
0
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = this.sustainerPawn.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.Temporary      = false;
                        //if (newPawn.Faction != Faction.OfPlayerSilentFail)
                        //{
                        //    newPawn.SetFaction(this.Caster.Faction, null);
                        //}
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map, Rot4.North, WipeMode.Vanish, false);
                            //GenPlace.TryPlaceThing(newPawn, position, map, ThingPlaceMode.Near, null, null);
                            CompSentinel compSentinel = newPawn.TryGetComp <CompSentinel>();
                            compSentinel.target        = this.hostilePawn;
                            compSentinel.sentinelLoc   = position;
                            compSentinel.rotation      = this.Rotation;
                            compSentinel.sustainerPawn = this.sustainerPawn;
                        }
                        catch
                        {
                            Log.Message("TM_Exception".Translate(
                                            "sentinel building",
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }

                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            try
                            {
                                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);
                            }
                            catch (NullReferenceException ex)
                            {
                                //
                            }
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
 private void TrySpawnMechanoids()
 {
     if (this.pointsLeft <= 0f)
     {
         return;
     }
     if (this.lord == null)
     {
         IntVec3 invalid;
         if (!CellFinder.TryFindRandomCellNear(base.Position, 5, (IntVec3 c) => c.Standable() && c.CanReach(this, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false)), out invalid))
         {
             Log.Error("Found no place for mechanoids to defend " + this);
             invalid = IntVec3.Invalid;
         }
         LordJob_MechanoidsDefendShip lordJob = new LordJob_MechanoidsDefendShip(this, base.Faction, 21f, invalid);
         this.lord = LordMaker.MakeNewLord(Faction.OfMechanoids, lordJob, null);
     }
     PawnKindDef kindDef;
     while ((
         from def in DefDatabase<PawnKindDef>.AllDefs
         where def.RaceProps.IsMechanoid && def.isFighter && def.combatPower <= this.pointsLeft
         select def).TryRandomElement(out kindDef))
     {
         IntVec3 center;
         if ((
             from cell in GenAdj.CellsAdjacent8Way(this)
             where this.CanSpawnMechanoidAt(cell)
             select cell).TryRandomElement(out center))
         {
             Pawn pawn = PawnGenerator.GeneratePawn(kindDef, Faction.OfMechanoids);
             if (GenPlace.TryPlaceThing(pawn, center, ThingPlaceMode.Near, null))
             {
                 this.lord.AddPawn(pawn);
                 this.pointsLeft -= pawn.kindDef.combatPower;
                 continue;
             }
             Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard);
         }
         this.pointsLeft = 0f;
         SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera();
         return;
     }
     this.pointsLeft = 0f;
     SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera();
     return;
 }