public static void QuickFilterPawnKind( PawnKindDef def )
 {
     ResetFilter();
     FilterAllPawnKinds();
     FilterPawnKind.Add( def );
     EnableFilter();
 }
        public MapCondition_Migration()
        {
            animalPawnDef = MigrationUtilities.GetMigrationAnimalDef();

            migrationEnterVec = MigrationUtilities.FindMigrationEnterVec();
            migrationExitVec = MigrationUtilities.FindMigrationExitVec(migrationEnterVec);

            ticksUntilNextWave = GenerateTicksUntilNexWave(true);
        }
 public static void SpawnPawnCorpse(IntVec3 spawnCell, PawnKindDef pawnKindDef, Faction faction, float rotProgressInTicks, bool removeEquipment = false)
 {
     Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction);
     GenSpawn.Spawn(pawn, spawnCell);
     if (removeEquipment)
     {
         pawn.equipment.DestroyAllEquipment();
         pawn.inventory.DestroyAll();
     }
     KillAndRotPawn(pawn, rotProgressInTicks);
 }
 public void TryToCaptureOutpost(string eventTitle, string eventText, LetterType letterType, Faction turretsNewFaction, bool deactivateTurrets,
     Faction doorsNewFaction, bool deactivateDoors, int dropPodsNumber, PawnKindDef securityForcesDef)
 {
     SetOutpostSecurityForcesHostileToColony();
     this.outpostThingList = OG_Util.RefreshThingList(this.outpostThingList);
     ChangeOutpostThingsFaction(null);
     ChangeOutpostTurretsFaction(turretsNewFaction, deactivateTurrets);
     ChangeOutpostDoorsFaction(doorsNewFaction, deactivateDoors);
     LaunchSecurityDropPods(dropPodsNumber, securityForcesDef, true);
     OG_Util.DestroyOutpostArea();
     Find.LetterStack.ReceiveLetter(eventTitle, eventText, letterType, new TargetInfo(this.Position));
 }
Beispiel #5
0
 public static void TogglePawnKindFilter(PawnKindDef pawnKind, bool remove = true)
 {
     if (remove)
     {
         FilterPawnKind.Remove(pawnKind);
     }
     else
     {
         if (FilterPawnKind == null) ResetPawnKindFilter();
         // ReSharper disable once PossibleNullReferenceException
         FilterPawnKind.Add(pawnKind);
     }
     if (!Filter) EnableFilter();
     FilterPossible = true;
 }
 public AcceptanceReport CanBeTrained( PawnKindDef pawnKind, TrainableDef td, out bool visible )
 {
     if ( pawnKind.RaceProps.untrainableTags != null )
     {
         for ( int index = 0; index < pawnKind.RaceProps.untrainableTags.Count; ++index )
         {
             if ( td.MatchesTag( pawnKind.RaceProps.untrainableTags[index] ) )
             {
                 visible = false;
                 return false;
             }
         }
     }
     if ( pawnKind.RaceProps.trainableTags != null )
     {
         for ( int index = 0; index < pawnKind.RaceProps.trainableTags.Count; ++index )
         {
             if ( td.MatchesTag( pawnKind.RaceProps.trainableTags[index] ) )
             {
                 if ( pawnKind.RaceProps.baseBodySize < (double)td.minBodySize )
                 {
                     visible = true;
                     return new AcceptanceReport( "CannotTrainTooSmall".Translate( (object)pawnKind.LabelCap ) );
                 }
                 visible = true;
                 return true;
             }
         }
     }
     if ( !td.defaultTrainable )
     {
         visible = false;
         return false;
     }
     if ( pawnKind.RaceProps.baseBodySize < (double)td.minBodySize )
     {
         visible = true;
         return new AcceptanceReport( "CannotTrainTooSmall".Translate( (object)pawnKind.LabelCap ) );
     }
     if ( pawnKind.RaceProps.trainableIntelligence < td.requiredTrainableIntelligence )
     {
         visible = true;
         return
             new AcceptanceReport(
                 "CannotTrainNotSmartEnough".Translate( (object)td.requiredTrainableIntelligence ) );
     }
     visible = true;
     return true;
 }
        private void DrawAvailableJobList( Rect outRect, Rect viewRect )
        {
            // set sizes
            viewRect.height = _availablePawnKinds.Count * _listEntryHeight;
            if ( viewRect.height > outRect.height )
            {
                viewRect.width -= 16f;
            }

            Widgets.BeginScrollView( outRect, ref _scrollPosition, viewRect );
            GUI.BeginGroup( viewRect );

            for ( var i = 0; i < _availablePawnKinds.Count; i++ )
            {
                // set up rect
                var row = new Rect( 0f, _listEntryHeight * i, viewRect.width, _listEntryHeight );

                // highlights
                Widgets.DrawHighlightIfMouseover( row );
                if ( i % 2 == 0 )
                {
                    Widgets.DrawAltRect( row );
                }
                if ( _availablePawnKinds[i] == _selectedAvailable )
                {
                    Widgets.DrawHighlightSelected( row );
                }

                // draw label
                string label = _availablePawnKinds[i].LabelCap + "\n<i>" +
                               "FML.TameWildCount".Translate(
                                                             _availablePawnKinds[i].GetTame( manager ).Count,
                                                             _availablePawnKinds[i].GetWild( manager ).Count ) + "</i>";
                Utilities.Label( row, label, null, TextAnchor.MiddleLeft, Utilities.Margin * 2 );

                // button
                if ( Widgets.ButtonInvisible( row ) )
                {
                    _selectedAvailable = _availablePawnKinds[i]; // for highlighting to work
                    Selected = new ManagerJob_Livestock( _availablePawnKinds[i], manager ); // for details
                }
            }

            GUI.EndGroup();
            Widgets.EndScrollView();
        }
 private void DrawPawnKindRow( PawnKindDef pawnKind )
 {
     var rectRow = new Rect( _x, _y, ColWidth, _rowHeight );
     var rectLabel = new Rect( _x, _y, LabWidth, _rowHeight );
     if ( pawnKind != null )
     {
         Widgets.Label( rectLabel, pawnKind.LabelCap );
         var rectIcon = new Rect( _x2 + _iconWidthOffset, _y, _iconSize, _iconSize );
         bool inList = Widgets_Filter.FilterPawnKind.Contains( pawnKind );
         GUI.DrawTexture( rectIcon, inList ? Widgets.CheckboxOnTex : Widgets.CheckboxOffTex );
         if ( Mouse.IsOver( rectRow ) )
         {
             GUI.DrawTexture( rectRow, TexUI.HighlightTex );
         }
         if ( Widgets.ButtonInvisible( rectRow ) )
         {
             if ( inList )
             {
                 SoundDefOf.CheckboxTurnedOff.PlayOneShotOnCamera();
             }
             else
             {
                 SoundDefOf.CheckboxTurnedOn.PlayOneShotOnCamera();
             }
             Widgets_Filter.TogglePawnKindFilter( pawnKind, inList );
             MainTabWindow_Animals.IsDirty = true;
         }
     }
     _y += _rowHeight;
 }
        static FactionControl()
        {
            RimeffectRacesSettings settings = RimeffectRacesMod.mod.settings;

            if (!settings.AsariFaction)
            {
                RimeffectRacesDefOf.AsariFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.AsariFaction.maxCountAtGameStart      = 0;
                PawnKindDef AsariPlayer   = PawnKindDef.Named("AsariPlayer");
                PawnKindDef AsariSlave    = PawnKindDef.Named("AsariSlave");
                PawnKindDef AsariRefugee  = PawnKindDef.Named("AsariRefugee");
                PawnKindDef AsariColonist = PawnKindDef.Named("AsariColonist");
                RimeffectRacesDefOf.AsariRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(AsariPlayer)).First().chance = 0f;
                RimeffectRacesDefOf.AsariRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(AsariSlave)).First().chance     = 0f;
                RimeffectRacesDefOf.AsariRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(AsariRefugee)).First().chance = 0f;
                RimeffectRacesDefOf.AsariRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(AsariColonist)).First().chance = 0f;
            }

            if (!settings.BatarianFaction)
            {
                RimeffectRacesDefOf.BatarianFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.BatarianFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerBatarian     = PawnKindDef.Named("PlayerBatarian");
                PawnKindDef BatarianSlave01    = PawnKindDef.Named("BatarianSlave01");
                PawnKindDef BatarianColonist01 = PawnKindDef.Named("BatarianColonist01");
                PawnKindDef BatarianSoldier01  = PawnKindDef.Named("BatarianSoldier01");
                RimeffectRacesDefOf.batarianRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerBatarian)).First().chance = 0f;
                RimeffectRacesDefOf.batarianRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(BatarianSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.batarianRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(BatarianColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.batarianRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(BatarianSoldier01)).First().chance = 0f;
            }

            if (!settings.EnkindlerFaction)
            {
                RimeffectRacesDefOf.EnkindlerFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.EnkindlerFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerDrell     = PawnKindDef.Named("PlayerDrell");
                PawnKindDef DrellSlave01    = PawnKindDef.Named("DrellSlave01");
                PawnKindDef DrellColonist01 = PawnKindDef.Named("DrellColonist01");
                PawnKindDef DrellSoldier01  = PawnKindDef.Named("DrellSoldier01");
                PawnKindDef PlayerHanar     = PawnKindDef.Named("PlayerHanar");
                PawnKindDef HanarSlave01    = PawnKindDef.Named("HanarSlave01");
                PawnKindDef HanarColonist01 = PawnKindDef.Named("HanarColonist01");
                RimeffectRacesDefOf.drellRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerDrell)).First().chance = 0f;
                RimeffectRacesDefOf.drellRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(DrellSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.drellRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(DrellColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.drellRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(DrellSoldier01)).First().chance = 0f;
                RimeffectRacesDefOf.hanarRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerHanar)).First().chance     = 0f;
                RimeffectRacesDefOf.hanarRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(HanarSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.hanarRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(HanarColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.hanarRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(HanarColonist01)).First().chance = 0f;
            }

            if (!settings.KroganFaction)
            {
                RimeffectRacesDefOf.KroganFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.KroganFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerKrogan     = PawnKindDef.Named("PlayerKrogan");
                PawnKindDef KroganSlave01    = PawnKindDef.Named("KroganSlave01");
                PawnKindDef KroganColonist01 = PawnKindDef.Named("KroganColonist01");
                PawnKindDef KroganSoldier01  = PawnKindDef.Named("KroganSoldier01");
                RimeffectRacesDefOf.kroganRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerKrogan)).First().chance = 0f;
                RimeffectRacesDefOf.kroganRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(KroganSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.kroganRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(KroganColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.kroganRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(KroganSoldier01)).First().chance = 0f;
            }

            if (!settings.QuarianFaction)
            {
                RimeffectRacesDefOf.QuarianFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.QuarianFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerQuarian     = PawnKindDef.Named("PlayerQuarian");
                PawnKindDef QuarianSlave01    = PawnKindDef.Named("QuarianSlave01");
                PawnKindDef QuarianColonist01 = PawnKindDef.Named("QuarianColonist01");
                PawnKindDef QuarianSoldier01  = PawnKindDef.Named("QuarianSoldier01");
                RimeffectRacesDefOf.quarianRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerQuarian)).First().chance = 0f;
                RimeffectRacesDefOf.quarianRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(QuarianSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.quarianRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(QuarianColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.quarianRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(QuarianSoldier01)).First().chance = 0f;
            }

            if (!settings.SalarianFaction)
            {
                RimeffectRacesDefOf.SalarianFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.SalarianFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerSalarian     = PawnKindDef.Named("PlayerSalarian");
                PawnKindDef SalarianSlave01    = PawnKindDef.Named("SalarianSlave01");
                PawnKindDef SalarianColonist01 = PawnKindDef.Named("SalarianColonist01");
                PawnKindDef SalarianSoldier01  = PawnKindDef.Named("SalarianSoldier01");
                RimeffectRacesDefOf.salarianRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerSalarian)).First().chance = 0f;
                RimeffectRacesDefOf.salarianRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(SalarianSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.salarianRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(SalarianColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.salarianRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(SalarianSoldier01)).First().chance = 0f;
            }

            if (!settings.TurianFaction)
            {
                RimeffectRacesDefOf.TurianFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.TurianFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerTurian     = PawnKindDef.Named("PlayerTurian");
                PawnKindDef TurianSlave01    = PawnKindDef.Named("TurianSlave01");
                PawnKindDef TurianColonist01 = PawnKindDef.Named("TurianColonist01");
                PawnKindDef TurianSoldier01  = PawnKindDef.Named("TurianSoldier01");
                RimeffectRacesDefOf.turianRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerTurian)).First().chance = 0f;
                RimeffectRacesDefOf.turianRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(TurianSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.turianRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(TurianColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.turianRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(TurianSoldier01)).First().chance = 0f;
            }

            if (!settings.VorchaFaction)
            {
                RimeffectRacesDefOf.VorchaFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.VorchaFaction.maxCountAtGameStart      = 0;
                PawnKindDef PlayerVorcha     = PawnKindDef.Named("PlayerVorcha");
                PawnKindDef VorchaSlave01    = PawnKindDef.Named("VorchaSlave01");
                PawnKindDef VorchaColonist01 = PawnKindDef.Named("VorchaColonist01");
                PawnKindDef VorchaSoldier01  = PawnKindDef.Named("VorchaSoldier01");
                RimeffectRacesDefOf.vorchaRaceSettings.pawnKindSettings.startingColonists.First().pawnKindEntries.Where(x => x.kindDefs.Contains(PlayerVorcha)).First().chance = 0f;
                RimeffectRacesDefOf.vorchaRaceSettings.pawnKindSettings.alienslavekinds.Where(x => x.kindDefs.Contains(VorchaSlave01)).First().chance      = 0f;
                RimeffectRacesDefOf.vorchaRaceSettings.pawnKindSettings.alienrefugeekinds.Where(x => x.kindDefs.Contains(VorchaColonist01)).First().chance = 0f;
                RimeffectRacesDefOf.vorchaRaceSettings.pawnKindSettings.alienwandererkinds.First().pawnKindEntries.Where(x => x.kindDefs.Contains(VorchaSoldier01)).First().chance = 0f;
            }

            if (!settings.WhiteHandFaction)
            {
                RimeffectRacesDefOf.WhiteHandFaction.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.WhiteHandFaction.maxCountAtGameStart      = 0;
            }

            if (!settings.GethRER)
            {
                RimeffectRacesDefOf.GethRER.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.GethRER.maxCountAtGameStart      = 0;
            }

            if (!settings.Reapers)
            {
                RimeffectRacesDefOf.Reapers.requiredCountAtGameStart = 0;
                RimeffectRacesDefOf.Reapers.maxCountAtGameStart      = 0;
            }
        }
        public static IEnumerable <PawnKindDef> ImpliedPawnKindDefs()
        {
            Log.Message("[KK]Generating pawnKind");
            var i = 0;

            //generating Foreach
            foreach (var metal in from def in DefDatabase <ThingDef> .AllDefs.ToList()
                     where def.stuffProps != null && def.stuffProps.categories.Contains(StuffCategoryDefOf.Metallic)
                     select def)
            {
                //referencing Template
                var bug     = ThingDef.Named("Bug_" + metal.defName);
                var bugKind = new PawnKindDef();


                //aux floats
                var maxHitPoints = metal.stuffProps.statFactors.GetStatFactorFromList(StatDefOf.MaxHitPoints);
                var meleeWeapon_CooldownMultiplier =
                    metal.stuffProps.statFactors.GetStatFactorFromList(StatDefOf.MeleeWeapon_CooldownMultiplier);
                var sharpDamageMultiplier = metal.statBases.GetStatFactorFromList(StatDefOf.SharpDamageMultiplier);
                var bluntDamageMultiplier = metal.statBases.GetStatFactorFromList(StatDefOf.BluntDamageMultiplier);


                //Defining General Value/Rarity float of generated PawnKind
                var valueMultiplier =
                    (float)Math.Round(
                        maxHitPoints * sharpDamageMultiplier * bluntDamageMultiplier / meleeWeapon_CooldownMultiplier,
                        2);

                //Defining PawnKindDef
                bugKind.defName            = "Bug_" + metal.defName;
                bugKind.label              = metal.label + " scarab";
                bugKind.description        = "Metal scarab. Quite valuable and it's carapace can be smelted";
                bugKind.race               = bug;
                bugKind.combatPower        = 40 * valueMultiplier;
                bugKind.canArriveManhunter = false;


                bugKind.lifeStages = new List <PawnKindLifeStage>
                {
                    new PawnKindLifeStage
                    {
                        bodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Megascarab",
                            drawSize = new Vector2(1.26f, 1.26f),
                            color    = metal.stuffProps.color
                        },
                        dessicatedBodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Dessicated_Megascarab",
                            drawSize = new Vector2(1, 1)
                        }
                    },
                    new PawnKindLifeStage
                    {
                        bodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Megascarab",
                            drawSize = new Vector2(1.57f, 1.57f),
                            color    = metal.stuffProps.color
                        },
                        dessicatedBodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Dessicated_Megascarab",
                            drawSize = new Vector2(1.13f, 1.13f)
                        }
                    },
                    new PawnKindLifeStage
                    {
                        bodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Megascarab",
                            drawSize = new Vector2(1.89f, 1.89f),
                            color    = metal.stuffProps.color
                        },
                        dessicatedBodyGraphicData = new GraphicData
                        {
                            texPath  = "Things/Pawn/Animal/Megascarab/Dessicated_Megascarab",
                            drawSize = new Vector2(1.26f, 1.26f)
                        }
                    }
                };
                yield return(bugKind);

                i++;
            }

            Log.Message("[KK]Pawns generated: " + i);
        }
        private static PawnBio TryGetRandomUnusedSolidBioFor(List <string> backstoryCategories, PawnKindDef kind, Gender gender, string requiredLastName)
        {
            NameTriple prefName = null;

            if (Rand.Value < 0.5f)
            {
                prefName = Prefs.RandomPreferredName();
                if (prefName != null && (prefName.UsedThisGame || (requiredLastName != null && prefName.Last != requiredLastName)))
                {
                    prefName = null;
                }
            }
            PawnBio result;

            while (true)
            {
                result = null;
                if (SolidBioDatabase.allBios.TakeRandom(20).Where(delegate(PawnBio bio)
                {
                    if (bio.gender != GenderPossibility.Either)
                    {
                        if (gender == Gender.Male && bio.gender != GenderPossibility.Male)
                        {
                            return(false);
                        }
                        if (gender == Gender.Female && bio.gender != GenderPossibility.Female)
                        {
                            return(false);
                        }
                    }
                    if (!requiredLastName.NullOrEmpty() && bio.name.Last != requiredLastName)
                    {
                        return(false);
                    }
                    if (prefName != null && !bio.name.Equals(prefName))
                    {
                        return(false);
                    }
                    if (kind.factionLeader && !bio.pirateKing)
                    {
                        return(false);
                    }
                    bool flag = false;
                    for (int i = 0; i < bio.adulthood.spawnCategories.Count; i++)
                    {
                        if (backstoryCategories.Contains(bio.adulthood.spawnCategories[i]))
                        {
                            flag = true;
                            break;
                        }
                    }
                    return(flag && !bio.name.UsedThisGame);
                }).TryRandomElementByWeight(new Func <PawnBio, float>(PawnBioAndNameGenerator.BioSelectionWeight), out result) || prefName == null)
                {
                    break;
                }
                prefName = null;
            }
            return(result);
        }
        public CustomPawn LoadPawn(SaveRecordPawnV4 record)
        {
            PawnKindDef pawnKindDef = null;

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

                if (pawnKindDef == null)
                {
                    Log.Warning("Prepare Carefully could not find the pawn kind definition for the saved character: \"" + record.pawnKindDef + "\"");
                    return(null);
                }
            }

            ThingDef pawnThingDef = ThingDefOf.Human;

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

                if (thingDef != null)
                {
                    pawnThingDef = thingDef;
                }
            }

            Pawn source;

            if (pawnKindDef != null)
            {
                source = new Randomizer().GenerateKindOfColonist(pawnKindDef);
            }
            else
            {
                source = new Randomizer().GenerateColonist();
            }
            source.health.Reset();

            CustomPawn pawn = new CustomPawn(source);

            if (pawn.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 (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
                                {
                                    Log.Warning("Prepare Carefully 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
                        {
                            Log.Warning("Prepare Carefully could not place at least one preset character into a saved faction because that faction is not available in the world");
                        }
                    }
                }
            }

            HairDef h = FindHairDef(record.hairDef);

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

            pawn.HeadGraphicPath      = record.headGraphicPath;
            pawn.Pawn.story.hairColor = record.hairColor;

            if (record.melanin >= 0.0f)
            {
                pawn.MelaninLevel = record.melanin;
            }
            else
            {
                pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor);
            }
            // Set the skin color (only for Alien Races).
            if (pawn.AlienRace != null)
            {
                pawn.SkinColor = record.skinColor;
            }

            Backstory backstory = FindBackstory(record.childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            else
            {
                Log.Warning("Could not load childhood backstory definition \"" + record.childhood + "\"");
                Failed = true;
            }
            if (record.adulthood != null)
            {
                backstory = FindBackstory(record.adulthood);
                if (backstory != null)
                {
                    pawn.Adulthood = backstory;
                }
                else
                {
                    Log.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\"");
                    Failed = 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;
            }

            pawn.ClearTraits();
            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
                {
                    Log.Warning("Could not load trait definition \"" + traitName + "\"");
                    Failed = true;
                }
            }

            foreach (var skill in record.skills)
            {
                SkillDef def = FindSkillDef(pawn.Pawn, skill.name);
                if (def == null)
                {
                    Log.Warning("Could not load skill definition \"" + skill.name + "\" from saved preset");
                    Failed = 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)
                {
                    Log.Warning("Could not find a matching pawn layer for the saved apparel \"" + apparelRecord.layer + "\"");
                    Failed = true;
                    continue;
                }
                if (apparelRecord.apparel.NullOrEmpty())
                {
                    Log.Warning("Saved apparel entry for layer \"" + apparelRecord.layer + "\" had an empty apparel def");
                    Failed = 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)
                {
                    Log.Warning("Could not load thing definition for apparel \"" + apparelRecord.apparel + "\"");
                    Failed = true;
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(apparelRecord.stuff))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.stuff);

                    if (stuffDef == null)
                    {
                        Log.Warning("Could not load stuff definition \"" + apparelRecord.stuff + "\" for apparel \"" + apparelRecord.apparel + "\"");
                        Failed = 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)
                {
                    Log.Warning("Prepare Carefully could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\""
                                + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : ""));
                    Failed = true;
                    continue;
                }
                BodyPartRecord bodyPart = uniqueBodyPart.Record;
                if (implantRecord.recipe != null)
                {
                    RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe);
                    if (recipeDef == null)
                    {
                        Log.Warning("Prepare Carefully could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\"");
                        Failed = true;
                        continue;
                    }
                    bool found = false;
                    foreach (var p in recipeDef.appliedOnFixedBodyParts)
                    {
                        if (p.defName.Equals(bodyPart.def.defName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Log.Warning("Prepare carefully could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\".  Recipe does not support that part.");
                        Failed = 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)
                {
                    Log.Warning("Prepare Carefully could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\"");
                    Failed = true;
                    continue;
                }
                InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def);
                if (option == null)
                {
                    Log.Warning("Prepare Carefully could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\"");
                    Failed = 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)
                    {
                        Log.Warning("Prepare Carefully could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\""
                                    + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : ""));
                        Failed = 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);
        }
Beispiel #13
0
        public static bool isAvPSynth(PawnKindDef pawn)
        {
            bool Result = pawn.RaceProps.FleshType.defName == "RRY_SynthFlesh";

            return(Result);
        }
 public RowEntry(PawnKindDef pkDef)
 {
     label            = pkDef.label;
     storageSpaceUsed = pkDef.GetRequiredStorage();
     def = pkDef;
 }
        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));
            }
        }
Beispiel #16
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);
                            }
                        }
                    }
                }
            }
        }
Beispiel #17
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));
        }
        protected override bool TryCastShot()
        {
            Pawn caster = base.CasterPawn;

            CompAbilityUserMagic comp = caster.GetComp <CompAbilityUserMagic>();

            verVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_ver").level;
            pwrVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_pwr").level;
            effVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_eff").level;
            this.duration = Mathf.RoundToInt((this.duration + (360 * effVal)) * comp.arcaneDmg);
            bool flag = caster != null && !caster.Dead;

            if (flag)
            {
                CompPolymorph compPoly = caster.GetComp <CompPolymorph>();
                if (compPoly != null && compPoly.Original != null && compPoly.TicksLeft > 0)
                {
                    compPoly.Temporary = true;
                    compPoly.TicksLeft = 0;
                }
                else
                {
                    FactionDef fDef = TorannMagicDefOf.TM_SummonedFaction;
                    if (caster.Faction != null)
                    {
                        fDef = caster.Faction.def;
                    }
                    SpawnThings spawnThing = new SpawnThings();
                    spawnThing.factionDef = fDef;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    GetPolyMinMax(caster);

                    spawnThing = TM_Action.AssignRandomCreatureDef(spawnThing, this.min, this.max);
                    if (spawnThing.def == null || spawnThing.kindDef == null)
                    {
                        spawnThing.def     = ThingDef.Named("Rat");
                        spawnThing.kindDef = PawnKindDef.Named("Rat");
                        Log.Message("random creature was null");
                    }

                    Pawn polymorphedPawn = TM_Action.PolymorphPawn(this.CasterPawn, caster, caster, spawnThing, caster.Position, true, duration);

                    if (this.effVal >= 3)
                    {
                        polymorphedPawn.GetComp <CompPolymorph>().Temporary = false;
                    }

                    MoteMaker.ThrowSmoke(polymorphedPawn.DrawPos, caster.Map, 2);
                    MoteMaker.ThrowMicroSparks(polymorphedPawn.DrawPos, caster.Map);
                    MoteMaker.ThrowHeatGlow(polymorphedPawn.Position, caster.Map, 2);
                    //caster.DeSpawn();

                    HealthUtility.AdjustSeverity(polymorphedPawn, HediffDef.Named("TM_ShapeshiftHD"), .5f + (1f * pwrVal));
                }

                //SoundInfo info = SoundInfo.InMap(new TargetInfo(caster.Position, caster.Map, false), MaintenanceType.None);
                //info.pitchFactor = 1.0f;
                //info.volumeFactor = 1.0f;
                //TorannMagicDefOf.TM_FastReleaseSD.PlayOneShot(info);
                //TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PowerWave"), caster.DrawPos, caster.Map, .8f, .2f, .1f, .1f, 0, 1f, 0, Rand.Chance(.5f) ? 0 : 180);
            }
            return(true);
        }
Beispiel #19
0
 private float SelectionChance(PawnKindDef k)
 {
     return(StockGenerator_Animals.SelectionChanceFromWildnessCurve.Evaluate(k.RaceProps.wildness));
 }
        /*private static void AddJoyAndComfortNeed(Pawn pawn)
        {
            // TODO: does not work anymore...
            Log.Message("Try to add joy to " + pawn.Name.ToStringShort);
            if (pawn.needs.TryGetNeed(NeedDefOf.Joy) == null)
            {
                MethodInfo addNeed = typeof(Pawn_NeedsTracker).GetMethod("AddNeed", BindingFlags.Instance | BindingFlags.NonPublic);
                addNeed.Invoke(pawn.needs, new object[]
                {
                    DefDatabase<NeedDef>.GetNamed("Joy", true)
                });
                pawn.needs.joy.CurLevel = Rand.Range(0.5f, 1f);
            }
            if (pawn.needs.comfort == null)
            {
                MethodInfo addNeed = typeof(Pawn_NeedsTracker).GetMethod("AddNeed", BindingFlags.Instance | BindingFlags.NonPublic);
                addNeed.Invoke(pawn.needs, new object[]
                {
                    DefDatabase<NeedDef>.GetNamed("Comfort", true)
                });
                pawn.needs.comfort.CurLevel = Rand.Range(0.75f, 1f);
            }
        }*/

        public static Pawn GeneratePawn(PawnKindDef kindDef)
        {
            Pawn pawn = null;

            // Generate a new pawn until it respects all criteria.
            PawnGenerationRequest request = new PawnGenerationRequest(
                kind: kindDef,
                faction: OG_Util.FactionOfMiningCo,
                forceGenerateNewPawn: true,
                mustBeCapableOfViolence: true,
                canGeneratePawnRelations: false);
            for (int tryIndex = 0; tryIndex <= 20; tryIndex++)
            { 
                pawn = PawnGenerator.GeneratePawn(kindDef, OG_Util.FactionOfMiningCo);
                if (kindDef == OG_Util.OutpostTechnicianDef)
                {
                    if (pawn.story.WorkTagIsDisabled(WorkTags.Hauling)
                        || pawn.story.WorkTagIsDisabled(WorkTags.Cleaning)
                        || pawn.story.WorkTagIsDisabled(WorkTags.ManualDumb)
                        || pawn.story.WorkTagIsDisabled(WorkTags.PlantWork)
                        || pawn.story.WorkTagIsDisabled(WorkTags.Firefighting)
                        || pawn.story.WorkTagIsDisabled(WorkTags.Scary))
                    {
                        pawn.Destroy();
                        pawn = null;
                        if (tryIndex == 20)
                        {
                            Log.Message("MiningCo. OutpostGenerator: cannot generate requested technician pawn.");
                        }
                    }
                }
                else
                {
                    if (pawn.story.WorkTagIsDisabled(WorkTags.Violent)
                        || pawn.story.WorkTagIsDisabled(WorkTags.Firefighting))
                    {
                        pawn.Destroy();
                        pawn = null;
                        if (tryIndex == 20)
                        {
                            Log.Message("MiningCo. OutpostGenerator: cannot generate requested soldier pawn.");
                        }
                    }
                }
                if (pawn != null)
                {
                    break;
                }
            };
            // Generate apparel and weapon.
            GeneratePawnApparelAndWeapon(ref pawn, kindDef);
            
            // TODO: add joy and comfort needs.

            // Enable work settings.
            pawn.workSettings.EnableAndInitialize();
            if (kindDef == OG_Util.OutpostTechnicianDef)
            {
                List<WorkTypeDef> allDefsListForReading = DefDatabase<WorkTypeDef>.AllDefsListForReading;
                for (int workTypeIndex = 0; workTypeIndex < allDefsListForReading.Count; workTypeIndex++)
                {
                    // Ensure doctor, repair and growing are enabled.
                    WorkTypeDef workTypeDef = allDefsListForReading[workTypeIndex];
                    if (workTypeDef.alwaysStartActive
                        || (workTypeDef == WorkTypeDefOf.Doctor)
                        || (workTypeDef == WorkTypeDefOf.Repair)
                        || (workTypeDef == WorkTypeDefOf.Growing))
                    {
                        if (pawn.story.WorkTypeIsDisabled(workTypeDef) == false)
                        {
                            pawn.workSettings.SetPriority(workTypeDef, 3);
                            if (workTypeDef == WorkTypeDefOf.Repair)
                            {
                                pawn.workSettings.SetPriority(workTypeDef, 4); // So dead bodies are hauled away before repairing walls.
                            }
                        }
                    }
                    else
                    {
                        pawn.workSettings.Disable(workTypeDef);
                    }
                }
            }
            // For soldiers, restrict allowed works to only firefighting and doctor (to rescue downed pawns).
            else
            {
                List<WorkTypeDef> allDefsListForReading = DefDatabase<WorkTypeDef>.AllDefsListForReading;
                for (int workTypeIndex = 0; workTypeIndex < allDefsListForReading.Count; workTypeIndex++)
                {
                    WorkTypeDef workTypeDef = allDefsListForReading[workTypeIndex];
                    if ((workTypeDef == WorkTypeDefOf.Firefighter)
                        || (workTypeDef == WorkTypeDefOf.Doctor))
                    {
                        if (pawn.story.WorkTypeIsDisabled(workTypeDef) == false)
                        {
                            pawn.workSettings.SetPriority(workTypeDef, 3);
                        }
                    }
                    else
                    {
                        pawn.workSettings.Disable(workTypeDef);
                    }
                }
            }
            // Set allowed area.
            pawn.playerSettings = new Pawn_PlayerSettings(pawn);
            pawn.playerSettings.AreaRestriction = OG_Util.FindOutpostArea();
            // Add a bonus mood boost.
            pawn.needs.mood.thoughts.memories.TryGainMemoryThought(OG_Util.MiningCoEmployeeThoughtDef);
            return 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);
        }
Beispiel #22
0
 private bool TryFindAnimalKind(int tile, out PawnKindDef animalKind)
 {
     return((from k in DefDatabase <PawnKindDef> .AllDefs
             where k.RaceProps.CanDoHerdMigration && Find.World.tileTemperatures.SeasonAndOutdoorTemperatureAcceptableFor(tile: tile, animalRace: k.race)
             select k).TryRandomElementByWeight(weightSelector: (PawnKindDef x) => x.RaceProps.wildness, result: out animalKind));
 }
Beispiel #23
0
 public static bool isPotentialHost(this PawnKindDef p, out string FailReason, bool setDefaults = false)
 {
     return(p.race.isPotentialHost(out FailReason, setDefaults));
 }
Beispiel #24
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);
        }
Beispiel #25
0
        public static PawnKindDef resultingXenomorph(this PawnKindDef p)
        {
            PawnKindDef kindDef = null;

            if (!p.isPotentialHost() || p.RaceProps.baseBodySize > 0.63f)
            {
                return(null);
            }
            bool human   = p.race.defName.Contains("Human") || HMSUtility.GetMark(p) == YautjaDefOf.HMS_Hediff_BloodedMHuman;
            bool yautja  = p.race.defName.Contains("Yautja");
            bool thrumbo = p.race.defName.Contains("Human") || HMSUtility.GetMark(p) == YautjaDefOf.HMS_Hediff_BloodedMThrumbo;
            bool hound   = HMSUtility.GetMark(p).defName.Contains("BloodedMHound");

            bool humanlike = p.RaceProps.Humanlike;

            bool large = humanlike ? p.RaceProps.baseBodySize > 1f : p.RaceProps.baseBodySize > 4f;
            bool small = p.RaceProps.baseBodySize > 1f;

            if (humanlike)
            {
                if (human)
                {
                    if (large)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                    }
                    else
                    {
                        if (small)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                        }
                        else
                        {
                            kindDef = p.isFighter ? XenomorphDefOf.RRY_Xenomorph_Warrior : XenomorphDefOf.RRY_Xenomorph_Drone;
                        }
                    }
                }
                else
                {
                    if (yautja)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Predalien;
                    }
                    else
                    {
                        if (large)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                        }
                        else
                        {
                            if (small)
                            {
                                kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                            }
                            else
                            {
                                kindDef = p.RaceProps.predator ? XenomorphDefOf.RRY_Xenomorph_Warrior : XenomorphDefOf.RRY_Xenomorph_Drone;
                            }
                        }
                    }
                }
            }
            else
            {
                if (large)
                {
                    if (thrumbo)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Thrumbomorph;
                    }
                    else
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                    }
                }
                else
                {
                    if (hound)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Runner;
                    }
                    else
                    {
                        if (small)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Runner;
                        }
                        else
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                        }
                    }
                }
            }
            return(kindDef);
        }
Beispiel #26
0
 public static bool isNeomorph(this PawnKindDef p)
 {
     return(p.RaceProps.FleshType == XenomorphRacesDefOf.RRY_Neomorph);
 }
 private static bool <GenerateRandom> m__0(PawnKindDef d)
 {
     return(d.trader);
 }
Beispiel #28
0
        public static PawnKindDef resultingXenomorph(this Pawn p)
        {
            PawnKindDef kindDef = null;

            if (!p.isPotentialHost() || p.BodySize > 0.63f)
            {
                return(null);
            }
            bool human   = p.def.defName.Contains("Human") || HMSUtility.GetMark(p.kindDef) == YautjaDefOf.HMS_Hediff_BloodedMHuman;
            bool yautja  = p.def.defName.Contains("Yautja");
            bool thrumbo = p.def.defName.Contains("Human") || HMSUtility.GetMark(p.kindDef) == YautjaDefOf.HMS_Hediff_BloodedMThrumbo;
            bool hound   = HMSUtility.GetMark(p.kindDef) == YautjaDefOf.HMS_Hediff_BloodedMHound;

            bool humanlike = p.RaceProps.Humanlike;

            bool large = humanlike ? p.BodySize > 1f : p.BodySize > 4f;
            bool small = p.BodySize > 1f;

            bool predalienEmbryo = p.health.hediffSet.hediffs.Any(x => x.def.defName.Contains("XenomorphImpregnation")) && ((XenoHediffWithComps)p.health.hediffSet.hediffs.Find(x => x.def.defName.Contains("XenomorphImpregnation"))).TryGetComp <HediffComp_XenoSpawner>().predalienImpregnation;
            bool royaleEmbryo    = p.health.hediffSet.hediffs.Any(x => x.def.defName.Contains("XenomorphImpregnation")) && ((XenoHediffWithComps)p.health.hediffSet.hediffs.Find(x => x.def.defName.Contains("XenomorphImpregnation"))).TryGetComp <HediffComp_XenoSpawner>().RoyaleEmbryo;

            if (humanlike)
            {
                if (human)
                {
                    if (predalienEmbryo)
                    {
                        kindDef = p.kindDef.isFighter ? XenomorphDefOf.RRY_Xenomorph_Warrior : XenomorphDefOf.RRY_Xenomorph_Drone;
                    }
                    else
                    {
                        if (royaleEmbryo)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Queen;
                        }
                        else
                        {
                            if (large)
                            {
                                kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                            }
                            else
                            {
                                if (small)
                                {
                                    kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                                }
                                else
                                {
                                    kindDef = p.kindDef.isFighter ? XenomorphDefOf.RRY_Xenomorph_Warrior : XenomorphDefOf.RRY_Xenomorph_Drone;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (yautja)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Predalien;
                    }
                    else
                    {
                        if (royaleEmbryo)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Queen;
                        }
                        else
                        {
                            if (large)
                            {
                                kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                            }
                            else
                            {
                                if (small)
                                {
                                    kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                                }
                                else
                                {
                                    kindDef = p.kindDef.RaceProps.predator ? XenomorphDefOf.RRY_Xenomorph_Warrior : XenomorphDefOf.RRY_Xenomorph_Drone;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (large)
                {
                    if (thrumbo)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Thrumbomorph;
                    }
                    else
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Warrior;
                    }
                }
                else
                {
                    if (hound)
                    {
                        kindDef = XenomorphDefOf.RRY_Xenomorph_Runner;
                    }
                    else
                    {
                        if (small)
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Runner;
                        }
                        else
                        {
                            kindDef = XenomorphDefOf.RRY_Xenomorph_Drone;
                        }
                    }
                }
            }

            bool selected = Find.Selector.SingleSelectedThing == p;

            if (selected && Prefs.DevMode)
            {
                //    Log.Message(string.Format("{0} will spawn from {1}", kindDef, p.LabelShortCap));
            }
            return(kindDef);
        }
Beispiel #29
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);
            }
        }
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);

            if (!initialized)
            {
                SpawnThings spawnThing = new SpawnThings();
                pawn = this.launcher as Pawn;
                MagicPowerSkill        pwr         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonElemental.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonElemental_pwr");
                MagicPowerSkill        ver         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonElemental.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonElemental_ver");
                ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
                pwrVal = pwr.level;
                verVal = ver.level;
                if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
                {
                    MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                    MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                    pwrVal = mpwr.level;
                    verVal = mver.level;
                }
                if (settingsRef.AIHardMode && !pawn.IsColonist)
                {
                    pwrVal = 3;
                    verVal = 3;
                }
                CellRect cellRect = CellRect.CenteredOn(this.Position, 1);
                cellRect.ClipInsideMap(map);

                IntVec3       centerCell = cellRect.CenterCell;
                System.Random random     = new System.Random();
                random = new System.Random();

                duration += (verVal * 900);

                int rnd = GenMath.RoundRandom(random.Next(0, 8));
                if (rnd < 2)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterEarth_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterEarth_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_Earth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Earth_Elemental");
                    }
                    else
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    SoundDefOf.AmbientAltitudeWind.sustainFadeoutTime.Equals(30.0f);
                }
                else if (rnd >= 2 && rnd < 4)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterFire_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterFire_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_Fire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Fire_Elemental");
                    }
                    else
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    MoteMaker.ThrowFireGlow(centerCell, map, pwrVal);
                    MoteMaker.ThrowHeatGlow(centerCell, map, pwrVal);
                }
                else if (rnd >= 4 && rnd < 6)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWater_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWater_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_Water_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Water_Elemental");
                    }
                    else
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    SoundDefOf.AmbientAltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                }
                else
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWind_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWind_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_Wind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Wind_Elemental");
                    }
                    else
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, 1 + pwrVal * 2);
                    SoundDefOf.AmbientAltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.white);
                }

                SingleSpawnLoop(spawnThing, centerCell, map);

                this.age         = this.duration;
                this.initialized = true;
            }
        }
        public static Pawn Copy(Pawn sourcePawn, PawnKindDef kindDef, Faction faction, bool forceBodyVisual = false, bool forceApparel = false, bool forceWeapon = false)
        {
            Pawn pawn = (Pawn)ThingMaker.MakeThing(kindDef.race, null);

            pawn.kindDef = kindDef;
            pawn.SetFactionDirect(faction);
            pawn.pather     = new Pawn_PathFollower(pawn);
            pawn.ageTracker = new Pawn_AgeTracker(pawn);
            pawn.health     = new Pawn_HealthTracker(pawn);
            pawn.jobs       = new Pawn_JobTracker(pawn);
            pawn.mindState  = new Pawn_MindState(pawn);
            pawn.filth      = new Pawn_FilthTracker(pawn);
            pawn.needs      = new Pawn_NeedsTracker(pawn);
            pawn.stances    = new Pawn_StanceTracker(pawn);
            pawn.InitUnsavedUniversalComponents();

            if (pawn.RaceProps.ToolUser)
            {
                pawn.equipment = new Pawn_EquipmentTracker(pawn);
                pawn.carrier   = new Pawn_CarryTracker(pawn);
                pawn.apparel   = new Pawn_ApparelTracker(pawn);
                pawn.inventory = new Pawn_InventoryTracker(pawn);
            }
            if (pawn.RaceProps.Humanlike)
            {
                pawn.ownership    = new Pawn_Ownership(pawn);
                pawn.skills       = new Pawn_SkillTracker(pawn);
                pawn.talker       = new Pawn_TalkTracker(pawn);
                pawn.story        = new Pawn_StoryTracker(pawn);
                pawn.workSettings = new Pawn_WorkSettings(pawn);
            }
            if (pawn.RaceProps.intelligence <= Intelligence.ToolUser)
            {
                pawn.caller = new Pawn_CallTracker(pawn);
            }
            PawnUtility.AddAndRemoveComponentsAsAppropriate(pawn);
            if (pawn.RaceProps.hasGenders)
            {
                if ((sourcePawn != null) &&
                    (sourcePawn.RaceProps.hasGenders) &&
                    (sourcePawn.gender != Gender.None))
                {
                    pawn.gender = sourcePawn.gender;
                }
                else
                {
                    if (Rand.Value < 0.5f)
                    {
                        pawn.gender = Gender.Male;
                    }
                    else
                    {
                        pawn.gender = Gender.Female;
                    }
                }
            }
            else
            {
                pawn.gender = Gender.None;
            }

            AbilityEffect_Revive.GenerateRandomAge_Coping(pawn, sourcePawn);
            AbilityEffect_Revive.GenerateInitialHediffs_Coping(pawn, sourcePawn);
            if (pawn.RaceProps.Humanlike)
            {
                if ((sourcePawn != null) &&
                    (forceBodyVisual))
                {
                    pawn.story.skinColor       = sourcePawn.story.skinColor;
                    pawn.story.crownType       = sourcePawn.story.crownType;
                    pawn.story.headGraphicPath = sourcePawn.story.headGraphicPath;
                    pawn.story.hairColor       = sourcePawn.story.hairColor;

                    AbilityEffect_Revive.GiveAppropriateBioTo_Coping(pawn, sourcePawn);
                    pawn.story.hairDef = sourcePawn.story.hairDef;
                    AbilityEffect_Revive.GiveRandomTraitsTo_Coping(pawn, sourcePawn);
                    pawn.story.GenerateSkillsFromBackstory();
                }
                else
                {
                    pawn.story.skinColor       = PawnSkinColors.RandomSkinColor();
                    pawn.story.crownType       = ((Rand.Value >= 0.5f) ? CrownType.Narrow : CrownType.Average);
                    pawn.story.headGraphicPath = GraphicDatabaseHeadRecords.GetHeadRandom(pawn.gender, pawn.story.skinColor, pawn.story.crownType).GraphicPath;
                    pawn.story.hairColor       = PawnHairColors.RandomHairColor(pawn.story.skinColor, pawn.ageTracker.AgeBiologicalYears);

                    PawnBioGenerator.GiveAppropriateBioTo(pawn, faction.def);
                    pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, faction.def);
                    AbilityEffect_Revive.GiveRandomTraitsTo(pawn);
                    pawn.story.GenerateSkillsFromBackstory();
                }
            }

            AbilityEffect_Revive.GenerateStartingApparelFor_Coping(pawn, sourcePawn, forceApparel);
            AbilityEffect_Revive.TryGenerateWeaponFor_Coping(pawn, sourcePawn, forceWeapon);
            AbilityEffect_Revive.GenerateInventoryFor_Coping(pawn, sourcePawn);
            PawnUtility.AddAndRemoveComponentsAsAppropriate(pawn);
            return(pawn);
        }
 public void ApplyCollarEffects( Pawn pawn, Apparel collar )
 {
     if( originalFaction == null )
     {
         if( pawn.Faction == Faction.OfPlayer )
         {
             originalFaction = Find.FactionManager.FirstFactionOfDef( FactionDefOf.Spacer );
         }
         else
         {
             originalFaction = pawn.Faction;
         }
     }
     if( originalPawnKind == null )
     {
         originalPawnKind = pawn.kindDef;
     }
     pawn.kindDef = Data.PawnKindDefOf.Slave;
     if(
         ( pawn.story != null )&&
         ( pawn.story.traits != null )&&
         ( !pawn.story.traits.HasTrait( Data.TraitDefOf.Enslaved ) )
     )
     {
         pawn.story.traits.GainTrait( new Trait( Data.TraitDefOf.Enslaved ) );
     }
 }
Beispiel #33
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);
            }
        }
        void LaunchSecurityDropPods(int dropPodsNumber, PawnKindDef securityForcesDef, bool assaultColony)
        {
            IntVec3 dropPodSpot;
            List<Pawn> securityForcesList = new List<Pawn>();

            if ((dropPodsNumber == 0) || (securityForcesDef == null))
            {
                return;
            }
            OG_Inhabitants.InitializeUniformColorAccordingToBiome(); // Necessary in case of small outpost (no inhabitants were generated).
            for (int soldierIndex = 0; soldierIndex < dropPodsNumber; soldierIndex++)
            {
                bool validDropPodCellIsFound = DropCellFinder.TryFindDropSpotNear(this.dropZoneCenter, out dropPodSpot, true, false);
                if (validDropPodCellIsFound)
                {
                    Pawn soldier = OG_Inhabitants.GeneratePawn(securityForcesDef);
                    securityForcesList.Add(soldier);
                    DropPodUtility.MakeDropPodAt(dropPodSpot, new DropPodInfo
                    {
                        SingleContainedThing = soldier,
                        openDelay = 240,
                        leaveSlag = false
                    });
                }
            }

            LordJob lordJob;
            if (assaultColony)
            {
                lordJob = new LordJob_AssaultColony(OG_Util.FactionOfMiningCo, true, true, false);
            }
            else
            {
                lordJob = new LordJob_DefendPoint(this.dropZoneCenter);
            }
            Lord lord = LordMaker.MakeNewLord(OG_Util.FactionOfMiningCo, lordJob, securityForcesList);
        }
 private bool <TrySpawnMechanoids> m__1(PawnKindDef def)
 {
     return(def.RaceProps.IsMechanoid && def.isFighter && def.combatPower <= this.pointsLeft);
 }
        private void DrawAnimalListheader( ref Vector2 cur, Vector2 size, PawnKindDef pawnKind, string header )
        {
            // use a third of available screenspace for labels
            var headerRect = new Rect( cur.x, cur.y, size.x / 3f, size.y );
            Utilities.Label( headerRect, header, anchor: TextAnchor.MiddleCenter, font: GameFont.Tiny );
            cur.x += size.x / 3f;

            // gender, lifestage, current meat (and if applicable, milking + shearing)
            var cols = 3;

            // extra columns?
            bool milk = pawnKind.Milkable();
            bool wool = pawnKind.Shearable();
            if ( milk )
            {
                cols++;
            }
            if ( wool )
            {
                cols++;
            }
            float colwidth = size.x * 2 / 3 / cols;

            // gender header
            var genderRect = new Rect( cur.x, cur.y, colwidth, size.y );
            Rect genderMale =
                new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( genderRect, -_smallIconSize / 2 );
            Rect genderFemale =
                new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( genderRect, _smallIconSize / 2 );
            GUI.DrawTexture( genderMale, Resources.MaleIcon );
            GUI.DrawTexture( genderFemale, Resources.FemaleIcon );
            TooltipHandler.TipRegion( genderRect, "FML.GenderHeader".Translate() );
            cur.x += colwidth;

            // lifestage header
            var ageRect = new Rect( cur.x, cur.y, colwidth, size.y );
            Rect ageRectC = new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( ageRect, _smallIconSize / 2 );
            Rect ageRectB = new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( ageRect );
            Rect ageRectA = new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( ageRect, -_smallIconSize / 2 );
            GUI.DrawTexture( ageRectC, Resources.LifeStages[2] );
            GUI.DrawTexture( ageRectB, Resources.LifeStages[1] );
            GUI.DrawTexture( ageRectA, Resources.LifeStages[0] );
            TooltipHandler.TipRegion( ageRect, "FML.AgeHeader".Translate() );
            cur.x += colwidth;

            // meat header
            var meatRect = new Rect( cur.x, cur.y, colwidth, size.y );
            Rect meatIconRect =
                new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( meatRect );
            GUI.DrawTexture( meatIconRect, Resources.MeatIcon );
            TooltipHandler.TipRegion( meatRect, "FML.MeatHeader".Translate() );
            cur.x += colwidth;

            // milk header
            if ( milk )
            {
                var milkRect = new Rect( cur.x, cur.y, colwidth, size.y );
                Rect milkIconRect =
                    new Rect( 0f, 0f, _smallIconSize, _smallIconSize ).CenteredIn( milkRect );
                GUI.DrawTexture( milkIconRect, Resources.MilkIcon );
                TooltipHandler.TipRegion( milkRect, "FML.MilkHeader".Translate() );
                cur.x += colwidth;
            }

            // wool header
            if ( wool )
            {
                var woolRect = new Rect( cur.x, cur.y, colwidth, size.y );
                Rect woolIconRect =
                    new Rect( 0f, 0f, Utilities.MediumIconSize, Utilities.MediumIconSize ).CenteredIn( woolRect );
                GUI.DrawTexture( woolIconRect, Resources.WoolIcon );
                TooltipHandler.TipRegion( woolRect, "FML.WoolHeader".Translate() );
                cur.x += colwidth;
            }

            // start next row
            cur.x = 0f;
            cur.y += size.y;
        }
Beispiel #37
0
        public void DoDamageToThings()
        {
            List <Thing> list = new List <Thing>();

            try
            {
                if (GenGrid.InBounds(this.Position, this.Map))
                {
                    list = this.Map.thingGrid.ThingsListAt(this.Position);
                }
            }
            catch
            {
                return;
            }

            if (list == null || list.Count <= 0)
            {
                return;
            }
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == null || list[i].Faction == PurpleIvyData.AlienFaction)
                {
                    continue;
                }
                if (list[i].def.IsCorpse)
                {
                    this.DoDamageToCorpse((Corpse)list[i]);
                }
                else
                {
                    switch (list[i])
                    {
                    case Pawn _:
                    {
                        this.DoDamageToPawn((Pawn)list[i]);
                        break;
                    }

                    case StickyGoo stickyGoo:
                    {
                        if (stickyGoo.HasAnyContents)
                        {
                            var thing = stickyGoo.ContainedThing;
                            if (thing is Pawn pawn)
                            {
                                var damageInfo = new DamageInfo(DamageDefOf.Scratch, 1, 0f, -1f, this, null, null);
                                pawn.TakeDamage(damageInfo);
                                this.Growth += 0.001f;
                                if (pawn.TryGetComp <AlienInfection>() == null)
                                {
                                    var hediff = (AlienInfectionHediff)HediffMaker.MakeHediff
                                                     (PurpleIvyDefOf.PI_AlienInfection, pawn);
                                    hediff.instigator = PawnKindDef.Named("Genny_ParasiteOmega");
                                    pawn.health.AddHediff(hediff);
                                }
                                if (Rand.Chance(0.1f) && pawn.health.hediffSet.GetFirstHediffOfDef(PurpleIvyDefOf.PI_AlienMutation) == null)
                                {
                                    var hediff3 = HediffMaker.MakeHediff(PurpleIvyDefOf.PI_AlienMutation, pawn, null);
                                    pawn.health.AddHediff(hediff3, null, null, null);
                                }
                            }
                            else if (thing is Corpse corpse)
                            {
                                this.DoDamageToCorpse(corpse);
                                stickyGoo.EjectContents();
                            }
                        }
                        break;
                    }

                    case Plant _:
                    {
                        if (list[i].def != PurpleIvyDefOf.PurpleIvy &&
                            list[i].def != PurpleIvyDefOf.PI_Nest &&
                            list[i].def != PurpleIvyDefOf.PlantVenomousToothwort &&
                            list[i].def != PurpleIvyDefOf.PI_CorruptedTree)
                        {
                            PurpleIvyMoteMaker.ThrowToxicSmoke(this.Position.ToVector3Shifted(), this.Map);
                            //FilthMaker.TryMakeFilth(this.Position, this.Map, PurpleIvyDefOf.PI_ToxicFilth);
                            list[i].TakeDamage(new DamageInfo(PurpleIvyDefOf.PI_ToxicBurn, 1));
                        }
                        break;
                    }
                    }
                }
            }
        }
        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);
            }
        }
Beispiel #39
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;
                        }
                    }
                }
            }
        }
        public static Pawn Copy(Pawn sourcePawn, PawnKindDef kindDef, Faction faction, bool forceBodyVisual = false, bool forceApparel = false, bool forceWeapon = false)
        {
            Pawn pawn = (Pawn)ThingMaker.MakeThing(kindDef.race, null);
            pawn.kindDef = kindDef;
            pawn.SetFactionDirect(faction);
            pawn.pather = new Pawn_PathFollower(pawn);
            pawn.ageTracker = new Pawn_AgeTracker(pawn);
            pawn.health = new Pawn_HealthTracker(pawn);
            pawn.jobs = new Pawn_JobTracker(pawn);
            pawn.mindState = new Pawn_MindState(pawn);
            pawn.filth = new Pawn_FilthTracker(pawn);
            pawn.needs = new Pawn_NeedsTracker(pawn);
            pawn.stances = new Pawn_StanceTracker(pawn);
            pawn.InitUnsavedUniversalComponents();

            if (pawn.RaceProps.ToolUser)
            {
                pawn.equipment = new Pawn_EquipmentTracker(pawn);
                pawn.carrier = new Pawn_CarryTracker(pawn);
                pawn.apparel = new Pawn_ApparelTracker(pawn);
                pawn.inventory = new Pawn_InventoryTracker(pawn);
            }
            if (pawn.RaceProps.Humanlike)
            {
                pawn.ownership = new Pawn_Ownership(pawn);
                pawn.skills = new Pawn_SkillTracker(pawn);
                pawn.talker = new Pawn_TalkTracker(pawn);
                pawn.story = new Pawn_StoryTracker(pawn);
                pawn.workSettings = new Pawn_WorkSettings(pawn);
            }
            if (pawn.RaceProps.intelligence <= Intelligence.ToolUser)
            {
                pawn.caller = new Pawn_CallTracker(pawn);
            }
            PawnUtility.AddAndRemoveComponentsAsAppropriate(pawn);
            if (pawn.RaceProps.hasGenders)
            {
                if ((sourcePawn != null) &&
                    (sourcePawn.RaceProps.hasGenders) &&
                    (sourcePawn.gender != Gender.None))
                    pawn.gender = sourcePawn.gender;
                else
                {
                    if (Rand.Value < 0.5f)
                        pawn.gender = Gender.Male;
                    else
                        pawn.gender = Gender.Female;
                }
            }
            else
                pawn.gender = Gender.None;

            AbilityEffect_Revive.GenerateRandomAge_Coping(pawn, sourcePawn);
            AbilityEffect_Revive.GenerateInitialHediffs_Coping(pawn, sourcePawn);
            if (pawn.RaceProps.Humanlike)
            {
                if ((sourcePawn != null) &&
                    (forceBodyVisual))
                {
                    pawn.story.skinColor = sourcePawn.story.skinColor;
                    pawn.story.crownType = sourcePawn.story.crownType;
                    pawn.story.headGraphicPath = sourcePawn.story.headGraphicPath;
                    pawn.story.hairColor = sourcePawn.story.hairColor;

                    AbilityEffect_Revive.GiveAppropriateBioTo_Coping(pawn, sourcePawn);
                    pawn.story.hairDef = sourcePawn.story.hairDef;
                    AbilityEffect_Revive.GiveRandomTraitsTo_Coping(pawn, sourcePawn);
                    pawn.story.GenerateSkillsFromBackstory();
                }
                else
                {
                    pawn.story.skinColor = PawnSkinColors.RandomSkinColor();
                    pawn.story.crownType = ((Rand.Value >= 0.5f) ? CrownType.Narrow : CrownType.Average);
                    pawn.story.headGraphicPath = GraphicDatabaseHeadRecords.GetHeadRandom(pawn.gender, pawn.story.skinColor, pawn.story.crownType).GraphicPath;
                    pawn.story.hairColor = PawnHairColors.RandomHairColor(pawn.story.skinColor, pawn.ageTracker.AgeBiologicalYears);

                    PawnBioGenerator.GiveAppropriateBioTo(pawn, faction.def);
                    pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, faction.def);
                    AbilityEffect_Revive.GiveRandomTraitsTo(pawn);
                    pawn.story.GenerateSkillsFromBackstory();
                }
            }

            AbilityEffect_Revive.GenerateStartingApparelFor_Coping(pawn, sourcePawn, forceApparel);
            AbilityEffect_Revive.TryGenerateWeaponFor_Coping(pawn, sourcePawn, forceWeapon);
            AbilityEffect_Revive.GenerateInventoryFor_Coping(pawn, sourcePawn);
            PawnUtility.AddAndRemoveComponentsAsAppropriate(pawn);
            return pawn;
        }
Beispiel #41
0
        public static string BestKindLabel(PawnKindDef kindDef, Gender gender, bool plural = false, int pluralCount = -1)
        {
            bool genderNoted;

            return(BestKindLabel(kindDef, gender, out genderNoted, plural, pluralCount));
        }
 // set defaults
 public ManagerJob_Livestock( PawnKindDef pawnKindDef )
     : this()
 {
     // set pawnkind and get list of current colonist pawns of that def.
     Trigger.pawnKind = pawnKindDef;
 }
Beispiel #43
0
        public static string BestKindLabel(PawnKindDef kindDef, Gender gender, out bool genderNoted, bool plural = false, int pluralCount = -1)
        {
            if (plural && pluralCount == 1)
            {
                plural = false;
            }
            string text = null;

            genderNoted = false;
            switch (gender)
            {
            case Gender.None:
                if (plural && kindDef.labelPlural != null)
                {
                    text = kindDef.labelPlural;
                    break;
                }
                text = kindDef.label;
                if (plural)
                {
                    text = Find.ActiveLanguageWorker.Pluralize(text, gender, pluralCount);
                }
                break;

            case Gender.Male:
                if (plural && kindDef.labelMalePlural != null)
                {
                    text        = kindDef.labelMalePlural;
                    genderNoted = true;
                }
                else if (kindDef.labelMale != null)
                {
                    text        = kindDef.labelMale;
                    genderNoted = true;
                    if (plural)
                    {
                        text = Find.ActiveLanguageWorker.Pluralize(text, gender, pluralCount);
                    }
                }
                else if (plural && kindDef.labelPlural != null)
                {
                    text = kindDef.labelPlural;
                }
                else
                {
                    text = kindDef.label;
                    if (plural)
                    {
                        text = Find.ActiveLanguageWorker.Pluralize(text, gender, pluralCount);
                    }
                }
                break;

            case Gender.Female:
                if (plural && kindDef.labelFemalePlural != null)
                {
                    text        = kindDef.labelFemalePlural;
                    genderNoted = true;
                }
                else if (kindDef.labelFemale != null)
                {
                    text        = kindDef.labelFemale;
                    genderNoted = true;
                    if (plural)
                    {
                        text = Find.ActiveLanguageWorker.Pluralize(text, gender, pluralCount);
                    }
                }
                else if (plural && kindDef.labelPlural != null)
                {
                    text = kindDef.labelPlural;
                }
                else
                {
                    text = kindDef.label;
                    if (plural)
                    {
                        text = Find.ActiveLanguageWorker.Pluralize(text, gender, pluralCount);
                    }
                }
                break;
            }
            return(text);
        }
        private static void GeneratePawnApparelAndWeapon(ref Pawn pawn, PawnKindDef kindDef)
        {
            if (kindDef == OG_Util.OutpostOfficerDef)
            {
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Pants"), ThingDef.Named("Hyperweave"), pantColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_CollarShirt"), ThingDef.Named("Hyperweave"), shirtColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_VestPlate"), null, Color.black, false);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Duster"), ThingDef.Named("Hyperweave"), armorColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_CowboyHat"), ThingDef.Named("Hyperweave"), helmetColor);
                GeneratePawnWeapon(ref pawn, kindDef.itemQuality, ThingDef.Named("Gun_SniperRifle"));
            }
            else if ((kindDef == OG_Util.OutpostHeavyGuardDef)
                || (kindDef == OG_Util.OutpostGuardDef))
            {
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Pants"), ThingDef.Named("Synthread"), pantColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_BasicShirt"), ThingDef.Named("Synthread"), shirtColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_PowerArmor"), null, armorColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_PowerArmorHelmet"), null, helmetColor);
                if (kindDef == OG_Util.OutpostHeavyGuardDef)
                {
                    GeneratePawnWeapon(ref pawn, kindDef.itemQuality, ThingDef.Named("Gun_Minigun"));
                }
                else
                {
                    GeneratePawnWeapon(ref pawn, kindDef.itemQuality, ThingDef.Named("Gun_ChargeRifle"));
                }
            }
            else if (kindDef == OG_Util.OutpostScoutDef)
            {
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Pants"), ThingDef.Named("Synthread"), pantColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_BasicShirt"), ThingDef.Named("Synthread"), shirtColor);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_VestPlate"), null, Color.black, false);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_KevlarHelmet"), null, helmetColor);
                if (needParka)
                {
                    GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Parka"), ThingDef.Named("Synthread"), armorColor);
                }
                GeneratePawnWeapon(ref pawn, kindDef.itemQuality, ThingDef.Named("Gun_AssaultRifle"));
            }
            else if (kindDef == OG_Util.OutpostTechnicianDef)
            {
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Pants"), ThingDef.Named("Synthread"), colorCivilGrey);
                GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_CollarShirt"), ThingDef.Named("Synthread"), colorCivilGrey);

                if (OG_Util.IsModActive("MiningCo. MiningHelmet"))
                {
                    GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("MiningHelmet"), null, Color.black, false);
                }
                else
                {
                    if (Find.MapWorldSquare.temperature < 20f)
                    {
                        // Only give a tuque if temperature is low enough.
                        GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Tuque"), ThingDef.Named("Synthread"), colorCivilGrey);
                    }
                }
                if (needParka)
                {
                    GeneratePawnApparel(ref pawn, kindDef.itemQuality, ThingDef.Named("Apparel_Parka"), ThingDef.Named("Synthread"), armorColor);
                }
                GeneratePawnWeapon(ref pawn, kindDef.itemQuality, ThingDef.Named("Gun_Pistol"));
            }

        }
Beispiel #45
0
 /// <summary>
 /// Simple check to determine wheth the PawnKindDef is a Apini or not.
 /// </summary>
 /// <param name="def">Supplied Def.</param>
 /// <returns>True if it is a Apini.</returns>
 public static bool IsApini(this PawnKindDef def)
 {
     return(ApiniTracker.apiniKind.Contains(def));
 }