public GraveDiggerDef Named(string name) => DefDatabase <GraveDiggerDef> .GetNamed(name);
        public static Pawn MakePawnFromGenomeSequence(GenomeSequence genomeSequence, Thing creator)
        {
            //int adultAge = (int)genome.pawnKindDef.RaceProps.lifeStageAges.Last().minAge;

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

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

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

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

                //headGraphicPath is private, so we need Harmony to set its value
                if (genomeSequence.headGraphicPath != null)
                {
                    AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker, genomeSequence.headGraphicPath);
                }
                else
                {
                    //could use this code to make a random head, instead of the static graphic paths.
                    //AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker,
                    //GraphicDatabaseHeadRecords.GetHeadRandom(genomeSequence.gender, PawnSkinColors.GetSkinColor(genomeSequence.skinMelanin), genomeSequence.crownType).GraphicPath);

                    string path = genomeSequence.gender == Gender.Male ? "Things/Pawn/Humanlike/Heads/Male/Male_Average_Normal" :
                                  "Things/Pawn/Humanlike/Heads/Female/Female_Narrow_Normal";
                    AccessTools.Field(typeof(Pawn_StoryTracker), "headGraphicPath").SetValue(storyTracker, path);
                }

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

                //Give random vatgrown backstory.
                storyTracker.childhood = DefDatabase <BackstoryDef> .GetNamed("Backstory_ColonyVatgrown").GetFromDatabase();

                storyTracker.adulthood = null;

                //Dirty hack ahoy!
                AccessTools.Field(typeof(Pawn_StoryTracker), "cachedDisabledWorkTypes").SetValue(storyTracker, null);
                //typeof(Pawn_StoryTracker).GetField("cachedDisabledWorkTypes", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(storyTracker, null);
                //typeof(PawnGenerator).GetMethod("GenerateSkills", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod).Invoke(null, new object[] { pawn });
            }

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


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

                    iterations++;
                }

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

                    iterations++;
                }
            }

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

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

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

            //Add Hediff marking them as a clone.
            pawn.health.AddHediff(QEHediffDefOf.QE_CloneStatus);

            return(pawn);
        }
Esempio n. 3
0
 public static StatDef Named(string defName)
 {
     return(DefDatabase <StatDef> .GetNamed(defName));
 }
        public static void DestroyConduitWithHF(Building __instance, DestroyMode mode)
        {
            Thing thing = __instance?.Position.GetThingList(__instance.Map).Find(x => x.def == DefDatabase <ThingDef> .GetNamed("PowerConduitHF"));

            if (thing != null && mode == DestroyMode.Deconstruct)
            {
                thing.DeSpawn(DestroyMode.Vanish);
            }
        }
        public override IEnumerable <FloatMenuOption> GetFloatMenuOptions(Pawn myPawn)
        {
            List <FloatMenuOption>        list = new List <FloatMenuOption>();
            IEnumerable <FloatMenuOption> result;

            if (!myPawn.CanReserve(this))
            {
                FloatMenuOption item = new FloatMenuOption("CannotUseReserved".Translate(), null);
                result = new List <FloatMenuOption>
                {
                    item
                };
            }
            else
            {
                if (!myPawn.CanReach(this, PathEndMode.Touch, Danger.Some))
                {
                    FloatMenuOption item2 = new FloatMenuOption("CannotUseNoPath".Translate(), null);
                    result = new List <FloatMenuOption>
                    {
                        item2
                    };
                }
                else
                {
                    List <Thing> allspawnedbooks = this.Map.listerThings.AllThings.FindAll(x => x.GetType() == typeof(ReadableBooks));
                    for (int i = 0; i < allspawnedbooks.Count; i++)
                    {
                        Thing current = allspawnedbooks[i];

                        Action storebook = delegate
                        {
                            Job newjob = new Job(DefDatabase <JobDef> .GetNamed("AddBookToLibrary"), current, this);
                            myPawn.QueueJob(newjob);
                            myPawn.jobs.StopAll();
                            myPawn.Reserve(this);
                        };
                        list.Add(new FloatMenuOption("AddBookToLibrary".Translate(new object[] { current.LabelCap }), storebook));
                    }
                    if (StoredBooks.Count <= 0)
                    {
                        FloatMenuOption item3 = new FloatMenuOption("NoStoryBooks".Translate(), null);
                        list.Add(item3);
                    }
                    else
                    {
                        Action action = delegate
                        {
                            Job newJob = new Job(DefDatabase <JobDef> .GetNamed("SitAndRead"), this);
                            myPawn.QueueJob(newJob);
                            myPawn.jobs.StopAll();
                            pawn = myPawn;
                            myPawn.Reserve(this);
                        };
                        list.Add(new FloatMenuOption("ReadABook".Translate(), action));
                    }
                }
            }

            result = list;
            return(result);
        }
        protected override IEnumerable <Toil> MakeNewToils()
        {
            // Just on the off-chance the rock is on fire...
            this.FailOnBurningImmobile(TargetIndex.A);
            // Reserve the target
            yield return(Toils_Reserve.Reserve(TargetIndex.A));

            // Go to the target
            Toil toilGoto = Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch);

            // Fail going to the target if it becomes unreachable
            ToilFailConditions.FailOn <Toil>(toilGoto, (Func <bool>)(() =>
            {
                if (Reachability.CanReach(pawn, (TargetInfo)TargetLocA, PathEndMode.Touch, pawn.NormalMaxDanger()))
                {
                    return(false);
                }
                return(true);
            }));
            yield return(toilGoto);

            // Now the work toil itself
            Toil toilWork = new Toil
            {
                // Continue until done
                defaultCompleteMode = ToilCompleteMode.Never,
                // When the job starts...
                initAction = new Action(() =>
                {
                    smoothTicks = 0;
                }),
                // The work tick
                tickAction = new Action(() =>
                {
                    if (pawn.skills != null)
                    {
                        const float constructionXP = 0.11f / 5f;
                        const float miningXP       = 0.11f / 5f;
                        const float artisticXP     = 0.11f / 5f;
                        pawn.skills.Learn(SkillDefOf.Construction, constructionXP);
                        pawn.skills.Learn(SkillDefOf.Mining, miningXP);
                        pawn.skills.Learn(SkillDefOf.Artistic, artisticXP);
                    }
                    smoothTicks += 1;
                    if (smoothTicks < nextSmoothStrike)
                    {
                        return;
                    }
                    // Reset counter, damage rock
                    smoothTicks         = 0;
                    mineable.HitPoints -= DamagePerStrike;
                })
            };

            // When should we stop?
            toilWork.endConditions.Add((Func <JobCondition>)(() =>
            {
                // Go until the rock is fully damaged
                if (mineable.HitPoints > 0)
                {
                    return(JobCondition.Ongoing);
                }
                return(JobCondition.Succeeded);
            }));
            // Do something when done
            toilWork.AddFinishAction(new Action(() =>
            {
                // If the job failed, abort
                if (mineable.HitPoints > 0)
                {
                    return;
                }
                // Clear the designation at this cell
                Common.RemoveDesignationDefOfAt(SmoothWall.designationDef, TargetA.Cell);
                // Better have associated stone blocks...
                string blocksDef     = "Blocks" + mineable.def.defName;
                ThingDef stoneBlocks = DefDatabase <ThingDef> .GetNamed(blocksDef, true);
                // Replace the rock with a stone wall
                var wallThing = ThingMaker.MakeThing(SmoothWall.thingDef, stoneBlocks);
                if (wallThing != null)
                {
                    var wall = GenSpawn.Spawn(wallThing, TargetA.Cell);
                    if (wall != null)
                    {
                        wall.SetFaction(Faction.OfColony);
                    }
                }
            }));
            // Some fun sounds while working
            ToilEffects.WithSustainer(toilWork, (Func <SoundDef>)(() =>
            {
                return(SmoothWall.soundDef);
            }));
            // Some fun effects while working
            ToilEffects.WithEffect(toilWork, "Mine", TargetIndex.A);
            yield return(toilWork);

            // And we're done.
            yield break;
        }
Esempio n. 7
0
 public CorpseJobDef Named(string searchedDN) => DefDatabase <CorpseJobDef> .GetNamed(searchedDN);
Esempio n. 8
0
        public override void DefsLoaded()
        {
            if (ModIsActive)
            {
                /* Mod settings */

                toggleEmpathy        = Settings.GetHandle <bool>("EnableEmpathy", "EmpathyChangesTitle".Translate(), "EmpathyChangesTooltip".Translate(), true);
                toggleKinsey         = Settings.GetHandle <bool>("EnableSexuality", "SexualityChangesTitle".Translate(), "SexualityChangesTooltip".Translate(), true);
                kinseyMode           = Settings.GetHandle <KinseyMode>("KinseyMode", "KinseyModeTitle".Translate(), "KinseyModeTooltip".Translate(), KinseyMode.Realistic, null, "KinseyMode_");
                toggleIndividuality  = Settings.GetHandle <bool>("EnableIndividuality", "IndividualityTitle".Translate(), "IndividualityTooltip".Translate(), true);
                toggleElections      = Settings.GetHandle <bool>("EnableElections", "ElectionsTitle".Translate(), "ElectionsTooltip".Translate(), true);
                conversationDuration = Settings.GetHandle <float>("ConversationDuration", "DurationTitle".Translate(), "DurationTooltip".Translate(), 60f, (String s) => float.Parse(s) >= 15f && float.Parse(s) <= 180f);
                toggleDateLetters    = Settings.GetHandle <bool>("SendDateLetters", "SendDateLettersTitle".Translate(), "SendDateLettersTooltip".Translate(), true);
                toggleBenchmarking   = Settings.GetHandle <bool>("Benchmarking", "BenchmarkingTitle".Translate(), "BenchmarkingTooltip".Translate(), false);

                kinsey        = toggleKinsey.Value;
                notBabyMode   = toggleIndividuality.Value;
                elections     = toggleElections.Value;
                dateLetters   = toggleDateLetters.Value;
                benchmark     = toggleBenchmarking.Value;
                convoDuration = conversationDuration.Value;

                if (PsychologyBase.ActivateKinsey())
                {
                    mode = kinseyMode.Value;
                }

                /* Mod conflict detection */

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

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

                if (bisexual != null || asexual != null || !toggleKinsey)
                {
                    if (toggleKinsey)
                    {
                        Logger.Message("KinseyDisable".Translate());
                    }
                    kinsey = false;
                }

                /* Conditional vanilla Def edits */

                ThoughtDef knowGuestExecuted = AddNullifyingTraits("KnowGuestExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestExecuted != null && toggleEmpathy)
                {
                    knowGuestExecuted = ModifyThoughtStages(knowGuestExecuted, new int[] { -1, -2, -4, -5 });
                }
                ThoughtDef knowColonistExecuted = AddNullifyingTraits("KnowColonistExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistExecuted != null && toggleEmpathy)
                {
                    knowColonistExecuted = ModifyThoughtStages(knowColonistExecuted, new int[] { -1, -2, -4, -5 });
                }
                ThoughtDef knowPrisonerDiedInnocent = AddNullifyingTraits("KnowPrisonerDiedInnocent", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerDiedInnocent != null && toggleEmpathy)
                {
                    knowPrisonerDiedInnocent = ModifyThoughtStages(knowPrisonerDiedInnocent, new int[] { -4 });
                }
                ThoughtDef knowColonistDied = AddNullifyingTraits("KnowColonistDied", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistDied != null && toggleEmpathy)
                {
                    knowColonistDied = ModifyThoughtStages(knowColonistDied, new int[] { -2 });
                }
                ThoughtDef colonistAbandoned = AddNullifyingTraits("ColonistBanished", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandoned != null && toggleEmpathy)
                {
                    colonistAbandoned = ModifyThoughtStages(colonistAbandoned, new int[] { -2 });
                }
                ThoughtDef colonistAbandonedToDie = AddNullifyingTraits("ColonistBanishedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (colonistAbandonedToDie != null && toggleEmpathy)
                {
                    colonistAbandonedToDie = ModifyThoughtStages(colonistAbandonedToDie, new int[] { -4 });
                }
                ThoughtDef prisonerAbandonedToDie = AddNullifyingTraits("PrisonerBanishedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (prisonerAbandonedToDie != null && toggleEmpathy)
                {
                    prisonerAbandonedToDie = ModifyThoughtStages(prisonerAbandonedToDie, new int[] { -3 });
                }
                ThoughtDef knowPrisonerSold = AddNullifyingTraits("KnowPrisonerSold", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowPrisonerSold != null && toggleEmpathy)
                {
                    knowPrisonerSold = ModifyThoughtStages(knowPrisonerSold, new int[] { -4 });
                }
                ThoughtDef knowGuestOrganHarvested = AddNullifyingTraits("KnowGuestOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowGuestOrganHarvested != null && toggleEmpathy)
                {
                    knowGuestOrganHarvested = ModifyThoughtStages(knowGuestOrganHarvested, new int[] { -4 });
                }
                ThoughtDef knowColonistOrganHarvested = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistOrganHarvested != null && toggleEmpathy)
                {
                    knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 });
                }
                ThoughtDef beauty = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart });
                if (knowColonistOrganHarvested != null && toggleEmpathy)
                {
                    knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 });
                }

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

                IEnumerable <ThingDef> things = (
                    from def in DefDatabase <ThingDef> .AllDefs
                    where typeof(Pawn).IsAssignableFrom(def.thingClass) &&
                    def.race?.intelligence == Intelligence.Humanlike &&
                    !def.defName.Contains("AIPawn") &&
                    (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree)
                    select def
                    );

                List <string> registered = new List <string>();
                foreach (ThingDef t in things)
                {
                    if (t.inspectorTabsResolved == null)
                    {
                        t.inspectorTabsResolved = new List <InspectTabBase>(1);
                    }
                    t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Psyche)));

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

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

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

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

            // Reference the tick manager so Find isn't constantly called
            TickManager tickMan = Find.TickManager;

            // Go to the bench
            yield return(Toils_Goto.GotoCell(BenchInd, PathEndMode.OnCell));

            // Set up the toil
            JobDef joyJob = DefDatabase <JobDef> .GetNamed("ZEN_SitAtScenicBench");

            Toil sitAtBench = new Toil()
            {
                socialMode = RandomSocialMode.Normal,
                initAction = () => { surroundingBeauty = BeautyUtility.AverageBeautyPerceptible(pawn.Position, Map); },
                tickAction = () => {
                    pawn.needs.joy.GainJoy(joyJob.joyGainRate * 0.000144f, joyJob.joyKind);
                    pawn.needs.joy.GainJoy(Mathf.Min(Mathf.Max(surroundingBeauty / 2f, 0.3f), 2.5f) * 0.000144f, joyJob.joyKind);
                    // Gain comfort from sitting on the bench
                    pawn.GainComfortFromCellIfPossible();

                    // Occasionally look in a different direction, observing the surroundings
                    if (tickMan.TicksGame % 250 == 0)
                    {
                        pawn.rotationTracker.FaceCell(GenAdj.RandomAdjacentCellCardinal(pawn.Position));
                    }

                    // End this job once the pawn has maxed out their joy
                    if (pawn.needs.joy.CurLevel > 0.9999f)
                    {
                        pawn.jobs.curDriver.EndJobWith(JobCondition.Succeeded);
                    }
                },
                defaultCompleteMode = ToilCompleteMode.Delay,
                defaultDuration     = job.def.joyDuration
            };

            sitAtBench.AddFinishAction(() => {
                Thought_Memory memory;
                // If the scenery was very beautiful, give a better memory,
                if (surroundingBeauty > 5f)
                {
                    memory = (Thought_Memory)ThoughtMaker.MakeThought(ThoughtDef.Named("ZEN_EnjoyedBeautifulScenery"));
                }
                // or if the scenery was okay, give a normal memory,
                else if (surroundingBeauty > 0)
                {
                    memory = (Thought_Memory)ThoughtMaker.MakeThought(ThoughtDef.Named("ZEN_EnjoyedScenery"));
                }
                // otherwise, give a bad memory
                else
                {
                    memory = (Thought_Memory)ThoughtMaker.MakeThought(ThoughtDef.Named("ZEN_DidNotEnjoyScenery"));
                }
                pawn.needs.mood.thoughts.memories.TryGainMemory(memory);
            });

            // Sit at the bench, enjoying the scenery
            yield return(sitAtBench);
        }
Esempio n. 10
0
        public static Comparison <Thing> GetBMixComparer(Thing billGiver, IntVec3 rootCell, Bill bill, out bool rnd)
        {
            rnd = false;
            string BMixMode       = "DIS";
            bool   BMixDebugBench = false;

            if (IsValidForComp(billGiver))
            {
                CompBestMix compBM = billGiver.TryGetComp <CompBestMix>();
                if (compBM != null)
                {
                    //BMixMode = compBM.CurMode;
                    BMixMode       = BMBillUtility.UseBMixMode(compBM, billGiver, bill);
                    BMixDebugBench = compBM.BMixDebug;
                }
            }

            Comparison <Thing> comparison = null;

            switch (BMixMode)
            {
            case "DIS":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (t1.Position - rootCell).LengthHorizontalSquared;
                    float value = (t2.Position - rootCell).LengthHorizontalSquared;
                    return(num.CompareTo(value));
                };
                break;

            case "DTR":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float        maxdtr = 72000000;
                    float        t1dtr  = maxdtr;
                    CompRottable t1comp = t1.TryGetComp <CompRottable>();
                    if (t1comp != null)
                    {
                        t1dtr = t1comp.TicksUntilRotAtCurrentTemp;
                    }
                    float        t2dtr  = maxdtr;
                    CompRottable t2comp = t2.TryGetComp <CompRottable>();
                    if (t2comp != null)
                    {
                        t2dtr = t2comp.TicksUntilRotAtCurrentTemp;
                    }
                    float num   = (t1dtr);
                    float value = (t2dtr);
                    return(num.CompareTo(value));
                };
                break;

            case "HPT":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num = 0f;
                    if (t2.def.useHitPoints)
                    {
                        num = (((float)(t2.MaxHitPoints - t2.HitPoints)) / ((float)(Math.Max(1, t2.MaxHitPoints))));
                    }
                    float value = 0f;
                    if (t1.def.useHitPoints)
                    {
                        value = (((float)(t1.MaxHitPoints - t1.HitPoints)) / ((float)(Math.Max(1, t1.MaxHitPoints))));
                    }
                    return(num.CompareTo(value));
                };
                break;

            case "RHP":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num = 0f;
                    if (t2.def.useHitPoints)
                    {
                        num = (((float)(t2.HitPoints)) / ((float)(Math.Max(1, t2.MaxHitPoints))));
                    }
                    float value = 0f;
                    if (t1.def.useHitPoints)
                    {
                        value = (((float)(t1.HitPoints)) / ((float)(Math.Max(1, t1.MaxHitPoints))));
                    }
                    return(num.CompareTo(value));
                };
                break;

            case "VLC":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (0f - t2.MarketValue);
                    float value = (0f - t1.MarketValue);
                    return(num.CompareTo(value));
                };
                break;

            case "VLE":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.MarketValue;
                    float value = t1.MarketValue;
                    return(num.CompareTo(value));
                };
                break;

            case "TMP":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.AmbientTemperature;
                    float value = t1.AmbientTemperature;
                    return(num.CompareTo(value));
                };
                break;

            case "FRZ":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (0f - t2.AmbientTemperature);
                    float value = (0f - t1.AmbientTemperature);
                    return(num.CompareTo(value));
                };
                break;

            case "BIT":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (((float)(t2.def.stackLimit)) / ((float)(Math.Max(1, t2.stackCount))));
                    float value = (((float)(t1.def.stackLimit)) / ((float)(Math.Max(1, t1.stackCount))));
                    return(num.CompareTo(value));
                };
                break;

            case "MST":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = GetStockAmount(t2, billGiver, rootCell, bill);
                    float value = GetStockAmount(t1, billGiver, rootCell, bill);
                    return(num.CompareTo(value));
                };
                break;

            case "LST":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = GetStockAmount(t1, billGiver, rootCell, bill);
                    float value = GetStockAmount(t2, billGiver, rootCell, bill);
                    return(num.CompareTo(value));
                };
                break;

            case "RND":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = RNDFloat();
                    float value = RNDFloat();
                    return(num.CompareTo(value));
                };
                rnd = true;
                break;

            case "BTY":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num = (t2.GetStatValue(StatDefOf.Beauty));
                    if ((t2.def?.stuffProps != null) && (t2.def?.stuffProps?.statOffsets != null))
                    {
                        if (t2.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                        {
                            num += t2.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                        }
                    }
                    float value = (t1.GetStatValue(StatDefOf.Beauty));
                    if ((t1.def?.stuffProps != null) && (t1.def?.stuffProps?.statOffsets != null))
                    {
                        if (t1.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                        {
                            value += t1.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                        }
                    }
                    return(num.CompareTo(value));
                };
                break;

            case "UGY":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num = (0f - (t2.GetStatValue(StatDefOf.Beauty)));
                    if ((t2.def?.stuffProps != null) && (t2.def?.stuffProps?.statOffsets != null))
                    {
                        if (t2.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                        {
                            num -= t2.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                        }
                    }
                    float value = (0f - (t1.GetStatValue(StatDefOf.Beauty)));
                    if ((t1.def?.stuffProps != null) && (t1.def?.stuffProps?.statOffsets != null))
                    {
                        if (t1.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                        {
                            value -= t1.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                        }
                    }
                    return(num.CompareTo(value));
                };
                break;

            case "HVY":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.Mass);
                    float value = t1.GetStatValue(StatDefOf.Mass);
                    return(num.CompareTo(value));
                };
                break;

            case "LGT":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (0f - t2.GetStatValue(StatDefOf.Mass));
                    float value = (0f - t1.GetStatValue(StatDefOf.Mass));
                    return(num.CompareTo(value));
                };
                break;

            case "FLM":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.Flammability);
                    float value = t1.GetStatValue(StatDefOf.Flammability);
                    return(num.CompareTo(value));
                };
                break;

            case "PTB":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.StuffPower_Armor_Blunt);
                    float value = t1.GetStatValue(StatDefOf.StuffPower_Armor_Blunt);
                    return(num.CompareTo(value));
                };
                break;

            case "PTS":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.StuffPower_Armor_Sharp);
                    float value = t1.GetStatValue(StatDefOf.StuffPower_Armor_Sharp);
                    return(num.CompareTo(value));
                };
                break;

            case "PTH":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.StuffPower_Armor_Heat);
                    float value = t1.GetStatValue(StatDefOf.StuffPower_Armor_Heat);
                    return(num.CompareTo(value));
                };
                break;

            case "PTE":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float   num          = 0f;
                    float   value        = 0f;
                    StatDef protElectric = DefDatabase <StatDef> .GetNamed(ProtElectricStat, false);

                    if (protElectric != null)
                    {
                        num   = t2.GetStatValue(protElectric);
                        value = t1.GetStatValue(protElectric);
                    }
                    return(num.CompareTo(value));
                };
                break;

            case "INH":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.StuffPower_Insulation_Heat);
                    float value = t1.GetStatValue(StatDefOf.StuffPower_Insulation_Heat);
                    return(num.CompareTo(value));
                };
                break;

            case "INC":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.StuffPower_Insulation_Cold);
                    float value = t1.GetStatValue(StatDefOf.StuffPower_Insulation_Cold);
                    return(num.CompareTo(value));
                };
                break;

            case "WSP":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.SharpDamageMultiplier);
                    float value = t1.GetStatValue(StatDefOf.SharpDamageMultiplier);
                    return(num.CompareTo(value));
                };
                break;

            case "WBT":
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = t2.GetStatValue(StatDefOf.BluntDamageMultiplier);
                    float value = t1.GetStatValue(StatDefOf.BluntDamageMultiplier);
                    return(num.CompareTo(value));
                };
                break;

            default:
                comparison = delegate(Thing t1, Thing t2)
                {
                    float num   = (t1.Position - rootCell).LengthHorizontalSquared;
                    float value = (t2.Position - rootCell).LengthHorizontalSquared;
                    return(num.CompareTo(value));
                };
                break;
            }

            return(comparison);
        }
Esempio n. 11
0
        public static string MakeDebugString(int indx, Thing thing, Thing billGiver, IntVec3 rootCell, Bill bill, string BMixMode)
        {
            float stat = 0f;

            switch (BMixMode)
            {
            case "DIS": stat = (thing.Position - rootCell).LengthHorizontalSquared; break;

            case "DTR":
                float        maxdtr    = 72000000;
                float        thingdtr  = maxdtr;
                CompRottable thingcomp = thing.TryGetComp <CompRottable>();
                if (thingcomp != null)
                {
                    thingdtr = thingcomp.TicksUntilRotAtCurrentTemp;
                }
                stat = (maxdtr - thingdtr);
                break;

            case "HPT":
                stat = 0f;
                if (thing.def.useHitPoints)
                {
                    stat = (((float)(thing.MaxHitPoints - thing.HitPoints)) / ((float)(Math.Max(1, thing.MaxHitPoints))));
                }
                break;

            case "RHP":
                stat = 0f;
                if (thing.def.useHitPoints)
                {
                    stat = (((float)(thing.HitPoints)) / ((float)(Math.Max(1, thing.MaxHitPoints))));
                }
                break;

            case "VLC": stat = (0f - thing.MarketValue); break;

            case "VLE": stat = thing.MarketValue; break;

            case "TMP": stat = thing.AmbientTemperature; break;

            case "FRZ": stat = (0f - thing.AmbientTemperature); break;

            case "BIT": stat = ((float)thing.def.stackLimit / (float)(Math.Max(1, thing.stackCount))); break;

            case "MST": stat = GetStockAmount(thing, billGiver, rootCell, bill); break;

            case "LST": stat = (0f - GetStockAmount(thing, billGiver, rootCell, bill)); break;

            case "RND": stat = RNDFloat(); break;

            case "BTY": stat = thing.GetStatValue(StatDefOf.Beauty);
                if ((thing.def?.stuffProps != null) && (thing.def?.stuffProps?.statOffsets != null))
                {
                    if (thing.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                    {
                        stat += thing.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                    }
                }
                break;

            case "UGY": stat = (0f - (thing.GetStatValue(StatDefOf.Beauty)));
                if ((thing.def?.stuffProps != null) && (thing.def?.stuffProps?.statOffsets != null))
                {
                    if (thing.def.stuffProps.statOffsets.StatListContains(StatDefOf.Beauty))
                    {
                        stat -= thing.def.stuffProps.statOffsets.GetStatOffsetFromList(StatDefOf.Beauty);
                    }
                }
                ;
                break;

            case "HVY": stat = thing.GetStatValue(StatDefOf.Mass); break;

            case "LGT": stat = (0f - thing.GetStatValue(StatDefOf.Mass)); break;

            case "FLM": stat = thing.GetStatValue(StatDefOf.Flammability); break;

            case "PTB": stat = thing.GetStatValue(StatDefOf.StuffPower_Armor_Blunt); break;

            case "PTS": stat = thing.GetStatValue(StatDefOf.StuffPower_Armor_Sharp); break;

            case "PTH": stat = thing.GetStatValue(StatDefOf.StuffPower_Armor_Heat); break;

            case "PTE":
                StatDef protElectric = DefDatabase <StatDef> .GetNamed(ProtElectricStat, false);

                if (protElectric != null)
                {
                    stat = thing.GetStatValue(protElectric);
                }
                break;

            case "INH": stat = thing.GetStatValue(StatDefOf.StuffPower_Insulation_Heat); break;

            case "INC": stat = thing.GetStatValue(StatDefOf.StuffPower_Insulation_Cold); break;

            case "WSP": stat = thing.GetStatValue(StatDefOf.SharpDamageMultiplier); break;

            case "WBT": stat = thing.GetStatValue(StatDefOf.BluntDamageMultiplier); break;

            default: stat = 0f; break;
            }

            string debugPos = "(" + thing.Position.x.ToString() + ", " + thing.Position.z.ToString() + ")";
            string debugMsg = "Debug " + BMixMode + " " + indx.ToString() + " " + billGiver.ThingID + " " + thing.LabelShort + " " + debugPos + " " + stat.ToString("F2");

            return(debugMsg);
        }
        public override IEnumerable <StatDrawEntry> SpecialDisplayStats(StatRequest req)
        {
            foreach (StatDrawEntry s in base.SpecialDisplayStats(req))
            {
                yield return(s);
            }
            if (DeepStorageCategory == null)
            {
                DeepStorageCategory = DefDatabase <StatCategoryDef> .GetNamed("LWM_DS_Stats");

                if (DeepStorageCategory == null)
                {
                    Log.Warning("LWM.DeepStorage: Stat Category FAILED to load.");
                    yield break;
                }
            }
            yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_maxNumStacks".Translate().ToString(),
                                           (size > 1?
                                            "LWM_DS_TotalAndPerCell".Translate(maxNumberStacks * size, maxNumberStacks).ToString()
                                           :maxNumberStacks.ToString()),
                                           "LWM_DS_maxNumStacksDesc".Translate(),
                                           11 /*display priority*/));

            if (minNumberStacks > 2)
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_minNumStacks".Translate(),
                                               size > 1?
                                               "LWM_DS_TotalAndPerCell".Translate(minNumberStacks * size, minNumberStacks).ToString()
                                           :minNumberStacks.ToString(),
                                               "LWM_DS_minNumStacksDesc".Translate(minNumberStacks * size),
                                               10 /*display priority*/));//todo: more info here would be good!
            }
            if (maxTotalMass > 0f)
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_maxTotalMass".Translate(),
                                               size > 1?
                                               "LWM_DS_TotalAndPerCell".Translate(kg(maxTotalMass * size), kg(maxTotalMass)).ToString()
                                       :kg(maxTotalMass),
                                               "LWM_DS_maxTotalMassDesc".Translate(), 9));
            }
            if (maxMassOfStoredItem > 0f)
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_maxMassOfStoredItem".Translate(),
                                               kg(maxMassOfStoredItem),
                                               "LWM_DS_maxMassOfStoredItemDesc".Translate(), 8));
            }
            if (AllowedCategoriesString != "")
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_allowedCategories".Translate(),
                                               AllowedCategoriesString,
                                               "LWM_DS_allowedCategoriesDesc".Translate(), 7));
            }
            if (AllowedDefsString != "")
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_allowedDefs".Translate(),
                                               AllowedDefsString,
                                               "LWM_DS_allowedDefsDesc".Translate(), 6));
            }
            if (DisallowedString != "")
            {
                yield return(new StatDrawEntry(DeepStorageCategory, "LWM_DS_disallowedStuff".Translate(),
                                               DisallowedString,
                                               "LWM_DS_disallowedStuffDesc".Translate(), 5));
            }
//            if (parent?.building?.fixedStorageSettings?.filter
            yield break;
        }
Esempio n. 13
0
        public static bool AddSimpleIncidentCaravan(InterceptedIncident incident, int DelayTick, int revealTick, bool InitialDetected = false)
        {
            TravelingIncidentCaravan_Simple travalingCaravan = (TravelingIncidentCaravan_Simple)WorldObjectMaker.MakeWorldObject(DefDatabase <WorldObjectDef> .GetNamed("PES_RaidingCaravan_Simple", true));

            travalingCaravan.Tile                = 0;
            travalingCaravan.remainingTick       = DelayTick;
            travalingCaravan.RemainingRevealTick = revealTick;
            travalingCaravan.incident            = incident;
            travalingCaravan.detected            = false;
            incident.parentCaravan               = travalingCaravan;
            if (InitialDetected)
            {
                travalingCaravan.detected = true;
            }
            Find.WorldObjects.Add(travalingCaravan);
            return(true);
        }
Esempio n. 14
0
        public static bool AddNewIncidentCaravan(InterceptedIncident incident)
        {
            TravelingIncidentCaravan travalingCaravan = (TravelingIncidentCaravan)WorldObjectMaker.MakeWorldObject(DefDatabase <WorldObjectDef> .GetNamed("PES_RaidingCaravan", true));

            if (!TryFindTile(incident.parms.target.Tile, out int sourceTile))
            {
                Log.Error("Fail to create incident caravan: no available tile found");
                return(false);
            }
            travalingCaravan.Tile = sourceTile;
            //travalingCaravan.SetFaction(incident.parms.faction);
            travalingCaravan.destinationTile = incident.parms.target.Tile;

            int approxTileDist = Mathf.CeilToInt(Find.WorldGrid.ApproxDistanceInTiles(travalingCaravan.Tile, travalingCaravan.destinationTile));

            travalingCaravan.remainingTick = Mod.PES_Settings.TickForIncidentCaravanCoverOneTile * approxTileDist;
            travalingCaravan.incident      = incident;
            incident.parentCaravan         = travalingCaravan;
            Find.WorldObjects.Add(travalingCaravan);
            return(true);
        }
Esempio n. 15
0
        private Thing MakeThingFromItemTile(ItemTile itemTile, bool enableLogging = false)
        {
            try {
                if (enableLogging)
                {
                    //Debug.Message("Trying to create new inner item {0}", itemTile.defName);
                }

                if (itemTile.defName.ToLower() == "pawn")
                {
                    //Debug.Message("Now need to instantiate pawn");
                    return(MakePawnWithRawXml(itemTile.itemXml));
                }

                if (itemTile.defName.ToLower() == "corpse")
                {
                    if (itemTile.innerItems != null)
                    {
                        //Debug.Message("Creating corpse");
                        Pawn   p      = (Pawn)MakeThingFromItemTile(itemTile.innerItems.First());
                        Corpse corpse = null;
                        if (p.Corpse != null)
                        {
                            corpse = p.Corpse;
                        }
                        else
                        {
                            corpse           = (Corpse)ThingMaker.MakeThing(p.RaceProps.corpseDef);
                            corpse.InnerPawn = p;
                        }
                        corpse.timeOfDeath = (int)(itemTile.corpseDeathTime + (ticksInYear * blueprint.dateShift));

                        CompRottable rottable = corpse.TryGetComp <CompRottable>();
                        if (rottable != null)
                        {
                            rottable.RotProgress = ticksInYear * (-blueprint.dateShift);
                        }
                        return(corpse);
                    }
                    return(null);
                }

                if (itemTile.defName.ToLower().Contains("corpse") || itemTile.defName.ToLower().Contains("minified"))   //should bypass older minified things and corpses
                {
                    if ((!itemTile.innerItems?.Any()) ?? true)
                    {
                        return(null);
                    }
                }

                if (itemTile.defName == "Hive")
                {
                    return(null);                                                              //Ignore hives, probably should add more comprehensive ignore list here.
                }
                ThingDef thingDef = DefDatabase <ThingDef> .GetNamed(itemTile.defName, false); //here thingDef is definitely not null because it was checked earlier

                if (thingDef.category == ThingCategory.Ethereal)
                {
                    return(null);                                        //don't spawn ethereals like drop pod landing sites and so on
                }
                ThingDef stuffDef = null;                                //but stuff can still be null, or can be missing, so we have to check and use default just in case.
                if (itemTile.stuffDef != null && thingDef.MadeFromStuff) //some mods may alter thing and add stuff parameter to it. this will result in a bug on a vanilla, so need to double-check here
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamed(itemTile.stuffDef, false);
                }

                if (stuffDef == null)
                {
                    if (itemTile.isWall && thingDef.MadeFromStuff)
                    {
                        stuffDef = ThingDefOf.BlocksGranite; //walls from modded materials becomes granite walls.
                    }
                    else
                    {
                        stuffDef = GenStuff.DefaultStuffFor(thingDef);
                    }
                }

                Thing thing = ThingMaker.MakeThing(thingDef, stuffDef);


                if (thing != null)
                {
                    if (itemTile.innerItems != null && thing is IThingHolder)
                    {
                        //Debug.Message("Found inners");
                        foreach (ItemTile innerTile in itemTile.innerItems)
                        {
                            Thing innerThing = MakeThingFromItemTile(innerTile, true);
                            if (innerThing != null)
                            {
                                ((IThingHolder)thing).GetDirectlyHeldThings().TryAdd(innerThing);
                            }
                        }
                        if (thing.GetInnerIfMinified() == null)
                        {
                            return(null);
                        }
                    }

                    if (thingDef.CanHaveFaction)
                    {
                        thing.SetFaction(rp.faction);
                    }

                    //Check quality and attach art
                    CompQuality q = thing.TryGetComp <CompQuality>();
                    if (q != null)
                    {
                        byte category = (byte)Math.Abs(Math.Round(Rand.Gaussian(0, 2)));

                        if (itemTile.art != null)
                        {
                            if (category > 6)
                            {
                                category = 6;
                            }
                            q.SetQuality((QualityCategory)category, ArtGenerationContext.Outsider); //setquality resets art, so it should go before actual setting art
                            thing.TryGetComp <CompArt>()?.InitializeArt(itemTile.art.author, itemTile.art.title, itemTile.art.TextWithDatesShiftedBy(blueprint.dateShift));
                        }
                        else
                        {
                            if (category > 6)
                            {
                                category = 6;
                            }
                            q.SetQuality((QualityCategory)category, ArtGenerationContext.Outsider);
                        }
                    }


                    if (itemTile.stackCount > 1)
                    {
                        thing.stackCount = itemTile.stackCount;


                        //Spoil things that can be spoiled. You shouldn't find a fresh meat an the old ruins.
                        CompRottable rottable = thing.TryGetComp <CompRottable>();
                        if (rottable != null)
                        {
                            //if deterioration degree is > 0.5 you definitely won't find any food.
                            //anyway, there is a chance that you also won't get any food even if deterioriation is relatively low. animalr, raiders, you know.
                            if (options.canHaveFood)
                            {
                                rottable.RotProgress = (Rand.Value * 0.5f + options.deteriorationMultiplier) * (rottable.PropsRot.TicksToRotStart);
                            }
                            else
                            {
                                rottable.RotProgress = rottable.PropsRot.TicksToRotStart + 1;
                            }
                        }
                    }

                    if (itemTile.attachedText != null && thing is ThingWithComps)
                    {
                        ThingWithComps thingWithComps = thing as ThingWithComps;
                        Type           CompTextClass  = Type.GetType("SaM.CompText, Signs_and_Memorials");
                        if (CompTextClass != null)
                        {
                            System.Object textComp = null;
                            for (int i = 0; i < thingWithComps.AllComps.Count; i++)
                            {
                                var val = thingWithComps.AllComps[i];
                                if (val.GetType() == CompTextClass)
                                {
                                    textComp = val;
                                }
                            }

                            //var textComp = Activator.CreateInstance(CompTextClass);
                            if (textComp != null)
                            {
                                textComp?.GetType()?.GetField("text").SetValue(textComp, itemTile.attachedText);
                            }
                            //thingWithComps.
                        }
                    }

                    if (thing is UnfinishedThing)
                    {
                        ((UnfinishedThing)thing).workLeft = 10000;
                        ((UnfinishedThing)thing).Creator  = Find.WorldPawns.AllPawnsAliveOrDead.RandomElement();
                    }

                    //Substract some hit points. Most lilkely below 400 (to make really strudy structures stay almost untouched. No more 1% beta poly walls)
                    var maxDeltaHP = 0;
                    if (!options.forceFullHitPoints)
                    {
                        maxDeltaHP = Math.Min(thing.MaxHitPoints - 1, (int)Math.Abs(Rand.Gaussian(0, 200)));
                    }
                    thing.HitPoints = thing.MaxHitPoints - Rand.Range(0, maxDeltaHP);

                    //Forbid haulable stuff
                    if (thing.def.EverHaulable)
                    {
                        thing.SetForbidden(true, false);
                    }

                    if (thing is Building_Storage)
                    {
                        ((Building_Storage)thing).settings.Priority = StoragePriority.Unstored;
                    }
                }
                return(thing);
            } catch (Exception e) {
                Debug.Log(Debug.BlueprintTransfer, "Failed to spawn item {0} because of {1}", itemTile.defName, e);
                return(null);
            }
        }
Esempio n. 16
0
        // Architect Menu:
        public static void ArchitectMenu_ChangeLocation(string newDefName, bool loadingOnStartup = false)
        {
//          Utils.Warn(Utils.DBF.Settings, "SettingsChanged()");
            var prevDesignationCatDef = loadingOnStartup
                ? DefDatabase <DesignationCategoryDef> .GetNamed(architectMenuDefaultDesigCatDef)
                : DefDatabase <DesignationCategoryDef> .GetNamed(architectMenuDesigCatDef, false);

            // If switching to default, put default into def database.
            if (newDefName == architectMenuDefaultDesigCatDef)
            {
                ArchitectMenu_Show();
            }
            // Compatibility Logic:
            //   If certain mods are loaded and all storage units are to go in one menu,
            //   maybe we want to remove the other menu?  Or maybe we want to use that
            //   one by default:
            // For Deep Storage, if the player also has Quantum Storage, use their menu insead:
            if (architectMenuMoveALLStorageItems && !architectMenuAlwaysShowCategory &&
                newDefName == architectMenuDefaultDesigCatDef &&
                ModLister.GetActiveModWithIdentifier("Cheetah.QuantumStorageRedux") != null)
            {
                newDefName = "QSRStorage";
            }
            var newDesignationCatDef = DefDatabase <DesignationCategoryDef> .GetNamed(newDefName);

            if (newDesignationCatDef == null)
            {
                Log.Warning("LWM.DeepStorage: Failed to find menu category " + newDefName + " - reverting to default");
                newDefName = architectMenuDefaultDesigCatDef;
                ArchitectMenu_Show();
                newDesignationCatDef = DefDatabase <DesignationCategoryDef> .GetNamed(newDefName);
            }

            // Architect Menu: Specify all your buildings/etc:
            //   var allMyBuildings=DefDatabase<ThingDef>.AllDefsListForReading.FindAll(x=>x.HasComp(etc)));
            var itemsToMove = allDeepStorageUnits;

            Utils.Mess(Utils.DBF.Settings, "Moving these units to 'Storage' menu: " + string.Join(", ", itemsToMove));
            // We can move ALL the storage buildings!  If the player wants.  I do.
            if (architectMenuMoveALLStorageItems)
            {
//                Log.Error("Trying to mvoe everythign:");
                var desigProduction = DefDatabase <DesignationCategoryDef> .GetNamed("Production");

                // Interesting detail: apparently it IS possible to have thingDefs with null thingClass... weird.
                itemsToMove = DefDatabase <ThingDef> .AllDefsListForReading.FindAll(x => x?.thingClass != null && (x.thingClass == typeof(Building_Storage) ||
                                                                                                                   x.thingClass.IsSubclassOf(typeof(Building_Storage))) &&
                                                                                    x.designationCategory != desigProduction);

                // testing:
//                itemsToMove.AddRange(DefDatabase<ThingDef>.AllDefsListForReading.FindAll(x=>x.defName.Contains("MURWallLight")));
            }

            var _resolvedDesignatorsField = typeof(DesignationCategoryDef)
                                            .GetField("resolvedDesignators", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var d in itemsToMove.Where(d => d.designationCategory != null))
            {
                //                Log.Error("Moving item "+d.defName+" (category: "+(d.designationCategory!=null?d.designationCategory.ToString():"NONE"));
                if (_resolvedDesignatorsField != null)
                {
                    var resolvedDesignators = (List <Designator>)_resolvedDesignatorsField.GetValue(d.designationCategory);
                    if (d.designatorDropdown == null)
                    {
//                    Log.Message("No dropdown");
                        // easy case:
//                    Log.Message("  Removed this many entries in "+d.designationCategory+": "+
                        resolvedDesignators.RemoveAll(x => x is Designator_Build &&
                                                      ((Designator_Build)x).PlacingDef == d);
//                        );
                        // Now do new:
                        resolvedDesignators = (List <Designator>)_resolvedDesignatorsField.GetValue(newDesignationCatDef);
                        // To make sure there are no duplicates:
                        resolvedDesignators.RemoveAll(x => x is Designator_Build &&
                                                      ((Designator_Build)x).PlacingDef == d);
                        resolvedDesignators.Add(new Designator_Build(d));
                    }
                    else
                    {
//                    Log.Warning("LWM.DeepStorage: ThingDef "+d.defName+" has a dropdown Designator.");
                        // Hard case: Designator_Dropdowns!
                        var dd = (Designator_Dropdown)resolvedDesignators.Find(x => x is Designator_Dropdown &&
                                                                               ((Designator_Dropdown)x).Elements
                                                                               .Find(y => y is Designator_Build &&
                                                                                     ((Designator_Build)y).PlacingDef == d) != null);
                        if (dd != null)
                        {
//                        Log.Message("Found dropdown designator for "+d.defName);
                            resolvedDesignators.Remove(dd);
                            // Switch to new category:
                            resolvedDesignators = (List <Designator>)_resolvedDesignatorsField.GetValue(newDesignationCatDef);
                            if (!resolvedDesignators.Contains(dd)) //                            Log.Message("  Adding to new category "+newDesignationCatDef);
                            {
                                resolvedDesignators.Add(dd);
                            }
//                    } else { //debug
//                        Log.Message("   ThingDef "+d.defName+" has designator_dropdown "+d.designatorDropdown.defName+
//                            ", but cannot find it in "+d.designationCategory+" - this is okay if something else added it.");
                        }
                    }
                }

                d.designationCategory = newDesignationCatDef;
            }
            // Flush designation category defs:.....dammit
//            foreach (var x in DefDatabase<DesignationCategoryDef>.AllDefs) {
//                x.ResolveReferences();
//            }
//            prevDesignationCatDef?.ResolveReferences();
//            newDesignationCatDef.ResolveReferences();
            //ArchitectMenu_ClearCache(); // we do this later one way or another

            // To remove the mod's DesignationCategoryDef from Architect menu:
            //   remove it from RimWorld.MainTabWindow_Architect's desPanelsCached.
            // To do that, we remove it from the DefDatabase and then rebuild the cache.
            //   Removing only the desPanelsCached entry does work: the entry is
            //   recreated when a new game is started.  So if the options are changed
            //   and then a new game started...the change gets lost.
            // So we have to update the DefsDatabase.
            // This is potentially difficult: the .index can get changed, and that
            //   can cause problems.  But nothing seems to use the .index for any
            //   DesignationCategoryDef except for the menu, so manually adjusting
            //   the DefsDatabase is safe enough:
            if (!architectMenuAlwaysShowCategory && newDefName != architectMenuDefaultDesigCatDef)
            {
                ArchitectMenu_Hide();
            }
            // ArchitectMenu_ClearCache(); //hide flushes cache
//                    if (tmp.AllResolvedDesignators.Count <= tmp.specialDesignatorClasses.Count)
//                        isCategoryEmpty=false;

/*
 * //                    Log.Message("Removing old menu!");
 *                  // DefDatabase<DesignationCategoryDef>.Remove(tmp);
 *                  if (!tmp.AllResolvedDesignators.NullOrEmpty()) {
 *                      foreach (var d in tmp.AllResolvedDesignators) {
 *                          if (!tmp.specialDesignatorClasses.Contains(d)) {
 *                              isCategoryEmpty=false;
 *                              break;
 *                          }
 *                      }
 *                  }
 */
//                    if (isCategoryEmpty)
            else // Simply flush cache:
            {
                ArchitectMenu_ClearCache();
            }
            // Note that this is not perfect: if the default menu was already open, it will still be open (and
            //   empty) when the settings windows are closed.  Whatever.


            // Oh, and actually change the setting that's stored:
            architectMenuDesigCatDef = newDefName;

/*            List<ArchitectCategoryTab> archMenu=(List<ArchitectCategoryTab>)Harmony.AccessTools
 *              .Field(typeof(RimWorld.MainTabWindow_Architect), "desPanelsCached")
 *              .GetValue((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow);
 *          archMenu.RemoveAll(t=>t.def.defName==architectMenuDefaultDesigCatDef);
 *
 *          archMenu.Add(new ArchitectCategoryTab(newDesignationCatDef));
 *          archMenu.Sort((a,b)=>a.def.order.CompareTo(b.def.order));
 *          archMenu.SortBy(a=>a.def.order, b=>b.def.order); // May need (type of var a)=>...
 *
 */


/*            Harmony.AccessTools.Method(typeof(RimWorld.MainTabWindow_Architect), "CacheDesPanels")
 *              .Invoke(((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow), null);*/


/*
 *
 *          if (architectMenuDesignationCatDefDefName=="LWM_DS_Storage") { // default
 *              if (DefDatabase<DesignationCategoryDef>.GetNamedSilentFail("LWM_DS_Storage") == null) {
 *                  Utils.Mess(Utils.DBF.Settings,"Adding 'Storage' to the architect menu.");
 *                  DefDatabase<DesignationCategoryDef>.Add(architectLWM_DS_Storage_DesignationCatDef);
 *              } else {
 *                  Utils.Mess(Utils.DBF.Settings, "No need to add 'Storage' to the architect menu.");
 *              }
 *              architectCurrentDesignationCatDef=architectLWM_DS_Storage_DesignationCatDef;
 *          } else {
 *              // remove our "Storage" from the architect menu:
 *              Utils.Mess(Utils.DBF.Settings,"Removing 'Storage' from the architect menu.");
 *              DefDatabase<DesignationCategoryDef>.AllDefsListForReading.Remove(architectLWM_DS_Storage_DesignationCatDef);
 *              if (DefDatabase<DesignationCategoryDef>.GetNamedSilentFail("LWM_DS_Storage") != null) {
 *                  Log.Error("Failed to remove LWM_DS_Storage :("+DefDatabase<DesignationCategoryDef>.GetNamedSilentFail("LWM_DS_Storage"));
 *              }
 *
 *              architectCurrentDesignationCatDef=DefDatabase<DesignationCategoryDef>.GetNamed(architectMenuDesignationCatDefDefName);
 *          }
 *          prevDesignationCatDef?.ResolveReferences();
 *          architectCurrentDesignationCatDef.ResolveReferences();
 *
 *          Harmony.AccessTools.Method(typeof(RimWorld.MainTabWindow_Architect), "CacheDesPanels")
 *              .Invoke((), null);
 */
            Utils.Warn(Utils.DBF.Settings, "Settings changed architect menu");
        }
Esempio n. 17
0
        public void RemoveIncompatibleItems()
        {
            //Each item should be checked if it can be placed or not. This should help preventing situations when simulated scavenging removes things which anyway won't be placed.
            //For each placed item it's cost should be calculated
            if (blueprint.roofMap == null)
            {
                Debug.Log(Debug.BlueprintTransfer, "Trying to process blueprint with empty roof map");
            }
            if (map == null)
            {
                Debug.Log(Debug.BlueprintTransfer, "Trying to process blueprint but map is still null");
            }

            try {
                int totalItems   = 0;
                int removedItems = 0;
                for (int x = 0; x < blueprint.width; x++)
                {
                    for (int z = 0; z < blueprint.height; z++)
                    {
                        Debug.Extra(Debug.BlueprintTransfer, "Starting cell {0} {1}...", x, z);
                        if (blueprint.itemsMap[x, z] == null)
                        {
                            blueprint.itemsMap[x, z] = new List <ItemTile>();
                        }                                                                                         //to make thngs easier add empty list to every cell

                        IntVec3 mapLocation = new IntVec3(x + mapOriginX, 0, z + mapOriginZ);
                        if (!mapLocation.InBounds(map))
                        {
                            continue;
                        }

                        List <ItemTile> items      = blueprint.itemsMap[x, z];
                        TerrainTile     terrain    = blueprint.terrainMap[x, z];
                        TerrainDef      terrainDef = null;

                        if (terrain != null)
                        {
                            terrainDef = DefDatabase <TerrainDef> .GetNamed(terrain.defName, false);

                            if (terrainDef == null)
                            {
                                blueprint.terrainMap[x, z] = null; //no terrain def means terrain can't be generated.
                                terrain = null;
                            }
                        }

                        TerrainDef existingTerrain = map.terrainGrid?.TerrainAt(mapLocation);
                        if (existingTerrain != null && terrainDef != null &&
                            existingTerrain.affordances != null &&
                            terrainDef.terrainAffordanceNeeded != null && !existingTerrain.affordances.Contains(terrainDef.terrainAffordanceNeeded))
                        {
                            terrainDef = null;
                            blueprint.terrainMap[x, z] = null;  //erase terrain if underlying terrain can't support it.
                            blueprint.roofMap[x, z]    = false; //removing roof as well just in case
                        }

                        Debug.Extra(Debug.BlueprintTransfer, "Preprocessed cell {0} {1}, moving to items...", x, z);
                        List <ItemTile> itemsToRemove = new List <ItemTile>();
                        foreach (ItemTile item in items)
                        {
                            totalItems++;

                            ThingDef thingDef = DefDatabase <ThingDef> .GetNamed(item.defName, false);

                            if (thingDef == null)
                            {
                                itemsToRemove.Add(item);
                                continue;
                            }

                            Debug.Extra(Debug.BlueprintTransfer, "Making thorough check for thing {0}", item.defName);
                            if (!options.overwritesEverything && thingDef.terrainAffordanceNeeded != null)
                            {
                                if (thingDef.EverTransmitsPower && options.shouldKeepDefencesAndPower)
                                {
                                    continue;                                                                    //ignore affordances for power transmitters if we need to keep defence systems
                                }
                                if (terrainDef != null && terrainDef.terrainAffordanceNeeded != null && existingTerrain.affordances.Contains(terrainDef.terrainAffordanceNeeded))
                                {
                                    if (!terrainDef.affordances.Contains(thingDef.terrainAffordanceNeeded))   //if new terrain can be placed over existing terrain, checking if an item can be placed over a new terrain
                                    {
                                        itemsToRemove.Add(item);
                                        blueprint.roofMap[x, z] = false;
                                    }
                                }
                                else
                                {
                                    if (!(existingTerrain.affordances?.Contains(thingDef.terrainAffordanceNeeded) ?? true))  //otherwise checking if the item can be placed over the existing terrain.
                                    {
                                        itemsToRemove.Add(item);
                                        blueprint.roofMap[x, z] = false;
                                    }
                                }
                            }
                        }

                        foreach (ItemTile item in itemsToRemove)
                        {
                            if (item.isWall || item.isDoor)
                            {
                                blueprint.RemoveWall(item.location.x, item.location.z);
                            }

                            items.Remove(item);
                            removedItems++;
                        }
                    }
                }


                Debug.Extra(Debug.BlueprintTransfer, "Finished check, recalculating stats");
                blueprint.UpdateBlueprintStats(true);
                Debug.Log(Debug.BlueprintTransfer, "Blueprint transfer utility did remove {0}/{1} incompatible items. New cost: {2}", removedItems, totalItems, blueprint.totalCost);
            } catch (Exception e) {
                Debug.Error(Debug.BlueprintTransfer, "Exception while trying to cleanup blueprint details. This should not normally happen, so please report this case: {0}", e.ToString());
            }
        }
Esempio n. 18
0
        private static Rect viewRect          = new Rect(0, 0, 100f, 10000f); // OMG OMG OMG I got scrollView in Listing_Standard to work!

        public static void DoSettingsWindowContents(Rect inRect)
        {
            var outerRect = inRect.ContractedBy(10f);

            Widgets.DrawHighlight(outerRect);
            var l = new Listing_Standard(GameFont.Medium); // my tiny high-resolution monitor :p

            l.BeginScrollView(outerRect, ref scrollPosition, ref viewRect);

            //l.GapLine();  // Who can haul to Deep Storage (robots, animals, etc)
            l.CheckboxLabeled("LWMDSrobotsCanUse".Translate(), ref robotsCanUse, "LWMDSrobotsCanUseDesc".Translate());
            string[] intLabels =
            {
                "LWM_DS_Int_Animal".Translate(),
                "LWM_DS_Int_ToolUser".Translate(),
                "LWM_DS_Int_Humanlike".Translate()
            };
            // Setting to allow bionic racoons to haul to Deep Storage:
            l.EnumRadioButton(ref Patch_IsGoodStoreCell.NecessaryIntelligenceToUseDeepStorage, "LWM_DS_IntTitle".Translate(),
                              "LWM_DS_IntDesc".Translate(), false, intLabels);
            l.GapLine(); //Storing Delay Settings
            l.Label("LWMDSstoringDelaySettings".Translate());
            l.CheckboxLabeled("LWMDSstoringTakesTimeLabel".Translate(),
                              ref storingTakesTime, "LWMDSstoringTakesTimeDesc".Translate());
            l.Label("LWMDSstoringGlobalScale".Translate((storingGlobalScale * 100f).ToString("0.")));
            storingGlobalScale = l.Slider(storingGlobalScale, 0f, 2f);
            l.CheckboxLabeled("LWMDSstoringTimeConsidersStackSize".Translate(),
                              ref storingTimeConsidersStackSize, "LWMDSstoringTimeConsidersStackSizeDesc".Translate());
            // Reset storing delay settings to defaults
            if (l.ButtonText("LWMDSstoringDelaySettings".Translate() + ": " + "ResetBinding".Translate() /*Reset to Default*/))
            {
                storingTakesTime              = true;
                storingGlobalScale            = 1f;
                storingTimeConsidersStackSize = true;
            }

            l.GapLine(); // default Storing Priority
            if (l.ButtonTextLabeled("LWM_DS_defaultStoragePriority".Translate(),
                                    defaultStoragePriority.Label()))
            {
                var mlist = (from StoragePriority p in Enum.GetValues(typeof(StoragePriority))
                             select new FloatMenuOption(p.Label(), delegate
                {
                    defaultStoragePriority = p;
                    foreach (var d in allDeepStorageUnits)
                    {
                        d.building.defaultStorageSettings.Priority = p;
                    }
                })).ToList();
                Find.WindowStack.Add(new FloatMenu(mlist));
            }

            l.GapLine();
            l.Label("LWM_DS_userInterface".Translate());
            l.CheckboxLabeled("LWM_DS_useDSRightClick".Translate(), ref useDeepStorageRightClickLogic,
                              "LWM_DS_useDSRightClickDesc".Translate());

            l.Gap();
            // TODO: WIP
            l.CheckboxLabeled("LWM_DS_useNewRightClick".Translate(), ref useDeepStorageNewRightClick,
                              "LWM_DS_useNewRightClickDesc".Translate());

            if (useDeepStorageNewRightClick)
            {
                l.TextFieldNumericLabeled("LWM_DS_newNRC_IconScaling".Translate(), ref newNRC_IconScaling, ref newNRC_IconScalingBuff, 0.1f);
                l.TextFieldNumericLabeled("LWM_DS_newNRC_BoxHeight".Translate(), ref newNRC_BoxHeight, ref newNRC_BoxHeightBuff, 10f);
            }

            // Architect Menu:
            l.GapLine(); //Architect Menu location

/*
 * //            string archLabel=
 * //            if (archLabel==n
 * //            l.Label("LWMDSarchitectMenuSettings".Translate());
 *          if (architectMenuDesigCatDef==architectMenuDefaultDesigCatDef) {
 * //                if (architectLWM_DS_Storage_DesignationCatDef==null) {
 * //                    Log.Error("LWM.DeepStorage: architectLWM_DS_Storage_DesignationCatDef was null; this should never happen.");
 * //                    tmp="ERROR";
 * //                } else {
 * //                    tmp=architectCurrentDesignationCatDef.LabelCap; // todo: (default)
 * //                }
 *              archLabel+=" ("+
 *          } else {
 *              var x=DefDatabase<DesignationCategoryDef>.GetNamed(architectMenuDesignationCatDefDefName, false);
 *              if (x==null) {
 *                  // TODO
 *              }
 *              tmp=x.LabelCap; // todo: (<menuname>)
 *          }*/
            if (l.ButtonTextLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuSettings").Translate(), // Label
                                                                                                              // value of dropdown button:
                                    DefDatabase <DesignationCategoryDef> .GetNamed(architectMenuDesigCatDef)?.LabelCap
                                    ?? "--ERROR--"))
            {
                // error display text
//                                     , DefDatabase<DesigarchitectMenuDesigCatDef) ) {
                // Float menu for architect Menu choice:
                var alist = new List <FloatMenuOption>();
                var arl   = DefDatabase <DesignationCategoryDef> .AllDefsListForReading; //all reading list
                //oops:
//                alist.Add(new FloatMenuOption(DefDatabase<DesignationCategoryDef>.GetNamed(architectMenuDefaultDesigCatDef).LabelCap
                alist.Add(new FloatMenuOption(architectMenuActualDef.LabelCap +
                                              " (" + "default".Translate() + " - " + architectMenuActualDef.defName + ")",
                                              delegate
                {
                    Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to default Storage");
                    ArchitectMenu_ChangeLocation(architectMenuDefaultDesigCatDef);
//                                                  architectCurrentDesignationCatDef=architectLWM_DS_Storage_DesignationCatDef;
//                                                  architectMenuDesignationCatDefDefName="LWM_DS_Storage";
//
//                                                  SettingsChanged();
                }));
                // Architect Menu:  You may remove the "Furniture" references here if you wish
                alist.Add(new FloatMenuOption(DefDatabase <DesignationCategoryDef> .GetNamed("Furniture").LabelCap +
                                              " (Furniture)", // I know what this one's defName is!
                                              delegate
                {
                    Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to Furniture.");
                    ArchitectMenu_ChangeLocation("Furniture");
                }));
                alist.AddRange(from adcd in arl
                               where adcd.defName != architectMenuDefaultDesigCatDef && adcd.defName != "Furniture"
                               select new FloatMenuOption(adcd.LabelCap + " (" + adcd.defName + ")", delegate
                {
                    Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to " + adcd);
                    ArchitectMenu_ChangeLocation(adcd.defName);
                }));
                Find.WindowStack.Add(new FloatMenu(alist));
            }

            l.CheckboxLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuAlwaysShowCategory").Translate(),
                              ref architectMenuAlwaysShowCategory,
                              (architectMenuDefaultDesigCatDef + "_ArchitectMenuAlwaysShowDesc").Translate());
            // Do we always display?  If so, display:
            if (architectMenuAlwaysShowCategory != architectMenuAlwaysShowTmp)
            {
                if (architectMenuAlwaysShowCategory)
                {
                    ArchitectMenu_Show();
                }
                else if (architectMenuDesigCatDef != architectMenuDefaultDesigCatDef)
                {
                    ArchitectMenu_Hide();
                }
                architectMenuAlwaysShowTmp = architectMenuAlwaysShowCategory;
            }

            l.CheckboxLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuMoveALL").Translate(),
                              ref architectMenuMoveALLStorageItems,
                              (architectMenuDefaultDesigCatDef + "_ArchitectMenuMoveALLDesc").Translate());
            if (architectMenuMoveALLStorageItems != architectMenuMoveALLTmp)
            {
                //  If turning off "all things in Storage", make sure to
                //    dump all the items into Furniture, to make sure they
                //    can at least be found somewhere.
                var ctmp = architectMenuDesigCatDef;
                if (architectMenuMoveALLStorageItems == false)
                {
                    architectMenuMoveALLStorageItems = true;
                    ArchitectMenu_ChangeLocation("Furniture");
                    architectMenuMoveALLStorageItems = false;
                }

                ArchitectMenu_ChangeLocation(ctmp);
                architectMenuMoveALLTmp = architectMenuMoveALLStorageItems;
            }

            // finished drawing settings for Architect Menu
            // -------------------
            // Allow player to turn of Over-Capacity check.
            //   Turn it off automatically for Project RimFactory and Extended Storage
            //   Note: should turn it off automatically for any other storage mods, too
            l.GapLine();
            var origColor = GUI.color; // make option gray if ignored
            var tmpMod    = ModLister.GetActiveModWithIdentifier("spdskatr.projectrimfactory");

            if (tmpMod != null)
            {
                GUI.color = Color.gray;
                // This setting is disabled due to mod Extended Storage
                l.Label("LWMDSignoredDueTo".Translate(tmpMod.Name));
            }

            if ((tmpMod = ModLister.GetActiveModWithIdentifier("Skullywag.ExtendedStorage")) != null)
            {
                GUI.color = Color.gray;
                l.Label("LWMDSignoredDueTo".Translate(tmpMod.Name));
            }

            l.CheckboxLabeled("LWMDSoverCapacityCheck".Translate(), ref checkOverCapacity,
                              "LWMDSoverCapacityCheckDesc".Translate());
            GUI.color = origColor;
            // Per DSU settings - let players change them around...
            l.GapLine();
            if (allowPerDSUSettings)
            {
                if (l.ButtonText("LWMDSperDSUSettings".Translate()))
                {
                    Find.WindowStack.Add(new Dialog_DS_Settings());
                }
            }
            else
            {
                l.CheckboxLabeled("LWMDSperDSUturnOn".Translate(), ref allowPerDSUSettings,
                                  "LWMDSperDSUturnOnDesc".Translate());
            }

            l.GapLine(); // End. Finis. Looks pretty having a line at the end.
            l.EndScrollView(ref viewRect);
        }
Esempio n. 19
0
 public static FactionDef Named(string defName)
 {
     return(DefDatabase <FactionDef> .GetNamed(defName, true));
 }
Esempio n. 20
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Settings.DebugString("== Enter IncidentWorker_Paranoia ==");
            var rand = Rand.Value;

            if (rand < 0.25f)
            {
                /*
                 * Mass Paranoia
                 *
                 * Every colonist will experience a range of sanity loss,
                 * ranging from minor to severe.
                 * 10% chance that two colonists will trigger a social fight.
                 *
                 */
                Settings.DebugString("Mass Paranoia");
                if (parms.target is not Map map ||
                    map.mapPawns.FreeColonistsAndPrisoners is not IEnumerable <Pawn> pawns || !pawns.Any())
                {
                    return(true);
                }

                var difficultyCalc = DIFFICULTYMODIFIER * Find.Storyteller.difficulty.threatScale;
                SanityLossReport.ApplySanityLossAndShowReport(new List <Pawn>(pawns), SANITYLOSSRANGE,
                                                              difficultyCalc);
                //bool socialFightStarted = false;
                //foreach (Pawn pawn in pawns)
                //{
                //    if (pawn?.story?.traits?.GetTrait(TraitDefOf.Nerves) is Trait nerves && nerves.Degree > 0)
                //    {
                //        continue;
                //    }
                //    Cthulhu.Utility.ApplySanityLoss(pawn, Rand.Range(0.3f, 0.7f), 1);

                //    if (!socialFightStarted && !pawn.IsPrisoner && Rand.Value > 0.9f && pawn?.mindState?.mentalStateHandler is MentalStateHandler mentalStateHandler)
                //    {
                //        socialFightStarted = true;
                //        var otherPawn = pawns.FirstOrDefault(x => x != pawn && !x.IsPrisoner);
                //        if (otherPawn != null && otherPawn?.mindState?.mentalStateHandler is MentalStateHandler otherMind)
                //        {
                //            mentalStateHandler.TryStartMentalState(MentalStateDefOf.SocialFighting, "ROM_OmenParanaoiaResult".Translate(), false, false, otherPawn);
                //            otherMind.TryStartMentalState(MentalStateDefOf.SocialFighting, "ROM_OmenParanaoiaResult".Translate(), false, false, pawn);
                //        }
                //    }
                //}
            }
            else if (rand < 0.5f)
            {
                /*
                 * Single Paranoia
                 *
                 * A single colonist will experience severe sanity loss.
                 * 80% chance of the character wandering in a psychotic state.
                 * If it's a prisoner, enter the berserk state.
                 *
                 */

                Settings.DebugString("Single Paranoia");
                if (parms.target is not Map map ||
                    map.mapPawns.FreeColonistsAndPrisoners is not IEnumerable <Pawn> pawns || !pawns.Any() ||
                    pawns.RandomElement() is not {
                } pawn)
                {
                    return(true);
                }

                var difficultyCalc = DIFFICULTYMODIFIER * Find.Storyteller.difficulty.threatScale;
                SanityLossReport.ApplySanityLossAndShowReport(new List <Pawn> {
                    pawn
                }, SANITYLOSSRANGE,
                                                              difficultyCalc);
                //if (pawn?.story?.traits?.GetTrait(TraitDefOf.Nerves) is Trait nerves && nerves.Degree > 0)
                //{
                //    flavorDesc = "ROM_OmenParanaoiaDesc2b".Translate(pawn);
                //}
                //else
                //{
                //    Cthulhu.Utility.ApplySanityLoss(pawn, Rand.Range(0.7f, 0.9f), 1);

                //    if (Rand.Value > 0.2f && pawn?.mindState?.mentalStateHandler is MentalStateHandler mentalStateHandler)
                //    {
                //        if (pawn.IsPrisoner) mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, "ROM_OmenParanaoiaResult".Translate());
                //        else mentalStateHandler.TryStartMentalState(MentalStateDefOf.Wander_Psychotic, "ROM_OmenParanaoiaResult".Translate());
                //    }
                //    flavorDesc = "ROM_OmenParanaoiaDesc2".Translate(pawn);
                //}
            }
            else if (rand < 0.75f)
            {
                /*
                 * Visions
                 *
                 * A single colonist will experience minor sanity loss.
                 * 90% chance of the character wandering in their own room.
                 *
                 */
                Settings.DebugString("Visions");
                if (parms.target is not Map map ||
                    map.mapPawns.FreeColonistsAndPrisoners is not IEnumerable <Pawn> pawns || !pawns.Any() ||
                    pawns.RandomElement() is not {
                } pawn)
                {
                    return(true);
                }

                var difficultyCalc = DIFFICULTYMODIFIER * Find.Storyteller.difficulty.threatScale;
                SanityLossReport.ApplySanityLossAndShowReport(new List <Pawn> {
                    pawn
                }, SANITYLOSSRANGE,
                                                              difficultyCalc, "HPLovecraft_Vision");
                if (Rand.Value > 0.1f && pawns.Count() > 3 &&
                    pawn.mindState?.mentalStateHandler is { } mentalStateHandler)
                {
                    mentalStateHandler.TryStartMentalState(DefDatabase <MentalStateDef> .GetNamed("WanderOwnRoom"),
                                                           "ROM_OmenParanaoiaResult".Translate());
                }
            }
            else
            {
                /*
                 * Plagued Senses
                 *
                 * A single colonist's eye, ear, nose, or mouth becomes "disoriented."
                 *
                 */
                Settings.DebugString("Plagued Senses");
                if (parms.target is not Map map || map.mapPawns.FreeColonists is not IEnumerable <Pawn> pawns ||
                    !pawns.Any() || pawns.RandomElement() is not {
                } pawn ||
                    pawn.health?.hediffSet is not {
                } parts)
                {
                    return(true);
                }

                Utility.ApplySanityLoss(pawn, Rand.Range(0.3f, 0.5f));

                var unused            = Rand.Value;
                var disorientedHediff =
                    HediffMaker.MakeHediff(DefDatabase <HediffDef> .GetNamed("ROM_Disoriented"), pawn);
                var senseParts = new List <BodyPartRecord>
                {
                    Utility.GetEar(parts),
                    Utility.GetEye(parts),
                    Utility.GetNose(parts),
                    Utility.GetMouth(parts)
                };
                disorientedHediff.Part     = parts.GetNotMissingParts().FirstOrDefault(x => senseParts.Contains(x));
                disorientedHediff.Severity = Rand.Range(0.7f, 0.9f);
                parts.AddDirect(disorientedHediff);
                string flavorDesc = "ROM_OmenParanaoiaDesc4".Translate(pawn);
                Find.LetterStack.ReceiveLetter(def.label.CapitalizeFirst(), flavorDesc,
                                               DefDatabase <LetterDef> .GetNamed("ROM_Omen"), new GlobalTargetInfo(pawn));
            }

            return(true);
        }
Esempio n. 21
0
 public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false)
 {
     return(new Job(DefDatabase <JobDef> .GetNamed("RB_TakeThingsOutOfBeehouseJob", true), t));
 }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Settings.DebugString("== Enter IncidentWorker_Crows ==");
            var   flavorDesc = "";
            Thing crow       = null;
            var   rand       = Rand.Value;
            var   target     = new GlobalTargetInfo();

            if (rand < 0.25f)
            {
                /*
                 * Dead Crow
                 *
                 * One dead crow appears.
                 *
                 */
                Settings.DebugString("Dead Crow");
                RCellFinder.TryFindRandomPawnEntryCell(out var loc, (Map)parms.target,
                                                       CellFinder.EdgeRoadChance_Animal);
                var newThing = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                crow = GenSpawn.Spawn(newThing, loc, (Map)parms.target);
                ((Pawn)crow).Kill(null);
                flavorDesc = "ROM_OmenCatDesc1".Translate();
                target     = new GlobalTargetInfo(loc, (Map)parms.target);
            }
            else if (rand < 0.5f)
            {
                /*
                 * Murder of Crows
                 *
                 * A group of crows appears outside your colony.
                 * One crow is dead in the center.
                 *
                 */
                Settings.DebugString("Murder of Crows");
                RCellFinder.TryFindRandomPawnEntryCell(out var loc, (Map)parms.target,
                                                       CellFinder.EdgeRoadChance_Animal);
                var newThing = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                crow = GenSpawn.Spawn(newThing, loc, (Map)parms.target);
                var crows = new List <Thing>();
                for (var i = 0; i < 2; i++)
                {
                    var newCrow = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                    crows.Add(GenSpawn.Spawn(newCrow, loc, (Map)parms.target));
                }

                crows.Add(crow);
                crow.Kill();
                flavorDesc = "ROM_OmenCrowDesc1".Translate();
                target     = new GlobalTargetInfo(crows.FirstOrDefault(x => x is Pawn y && !y.Dead));
            }
            else if (rand < 0.75f)
            {
                /*
                 * Flock of Crows
                 *
                 * A group of crows spawn outside the colony.
                 *
                 */
                Settings.DebugString("Flock of Crows");
                RCellFinder.TryFindRandomPawnEntryCell(out var loc, (Map)parms.target,
                                                       CellFinder.EdgeRoadChance_Animal);
                var newThing = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                crow = GenSpawn.Spawn(newThing, loc, (Map)parms.target);
                var crows = new List <Thing>();
                for (var i = 0; i < 2; i++)
                {
                    var newCrow = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                    crows.Add(GenSpawn.Spawn(newCrow, loc, (Map)parms.target));
                }

                crows.Add(crow);
                flavorDesc = "ROM_OmenCrowDesc2".Translate();
                target     = new GlobalTargetInfo(crow);
            }
            else
            {
                /*
                 * Solitary Crow
                 *
                 * A single crow watches the colony.
                 *
                 */
                Settings.DebugString("Solitary Crow");
                RCellFinder.TryFindRandomPawnEntryCell(out var loc, (Map)parms.target,
                                                       CellFinder.EdgeRoadChance_Animal);
                var newThing = PawnGenerator.GeneratePawn(HPLDefOf.HPLovecraft_CrowKind);
                crow       = GenSpawn.Spawn(newThing, loc, (Map)parms.target);
                flavorDesc = "ROM_OmenCrowDesc3".Translate();
                target     = new GlobalTargetInfo(crow);
            }

            Find.LetterStack.ReceiveLetter(def.label.CapitalizeFirst(), flavorDesc,
                                           DefDatabase <LetterDef> .GetNamed("ROM_Omen"), target);
            return(true);
        }
Esempio n. 23
0
        public void TryStartReload()
        {
            if (!hasMagazine)
            {
                return;
            }
            IntVec3 position;

            if (wielder == null)
            {
                if (turret == null)
                {
                    return;
                }
                turret.isReloading = true;
                position           = turret.Position;
            }
            else
            {
                position = wielder.Position;
            }

            if (useAmmo)
            {
                // Add remaining ammo back to inventory
                if (curMagCountInt > 0)
                {
                    Thing ammoThing = ThingMaker.MakeThing(currentAmmoInt);
                    ammoThing.stackCount = curMagCountInt;
                    curMagCountInt       = 0;

                    if (compInventory != null)
                    {
                        compInventory.container.TryAdd(ammoThing, ammoThing.stackCount);
                    }
                    else
                    {
                        Thing outThing;
                        GenThing.TryDropAndSetForbidden(ammoThing, position, ThingPlaceMode.Near, out outThing, turret.Faction != Faction.OfPlayer);
                    }
                }
                // Check for ammo
                if (wielder != null && !hasAmmo)
                {
                    this.DoOutOfAmmoAction();
                    return;
                }
            }

            // Throw mote
            if (Props.throwMote)
            {
                MoteThrower.ThrowText(position.ToVector3Shifted(), "CR_ReloadingMote".Translate());
            }

            // Issue reload job
            if (wielder != null)
            {
                var reloadJob = new Job(DefDatabase <JobDef> .GetNamed("ReloadWeapon"), wielder, parent)
                {
                    playerForced = true
                };

                // Store the current job so we can reassign it later
                if (this.wielder.Faction == Faction.OfPlayer &&
                    this.wielder.CurJob != null &&
                    (this.wielder.CurJob.def == JobDefOf.AttackStatic || this.wielder.CurJob.def == JobDefOf.Goto || wielder.CurJob.def == JobDefOf.Hunt))
                {
                    this.storedTarget = this.wielder.CurJob.targetA.HasThing ? new TargetInfo(this.wielder.CurJob.targetA.Thing) : new TargetInfo(this.wielder.CurJob.targetA.Cell);
                    this.storedJobDef = this.wielder.CurJob.def;
                }
                else
                {
                    storedTarget = null;
                    storedJobDef = null;
                }
                this.AssignJobToWielder(reloadJob);
            }
        }
Esempio n. 24
0
 public static BiomeDef Named(string defName)
 {
     return(DefDatabase <BiomeDef> .GetNamed(defName, true));
 }
Esempio n. 25
0
 public static bool IsChunk(this Thing thing)
 {
     return(thing != null &&
            (thing.def.thingCategories.Contains(DefDatabase <ThingCategoryDef> .GetNamed("StoneChunks")) ||
             thing.def.thingCategories.Contains(DefDatabase <ThingCategoryDef> .GetNamed("Chunks"))));
 }
Esempio n. 26
0
        private void CentaurAlphaShipPostProcess(Map spaceMap)
        {
            spaceMap.fogGrid.ClearAllFog();

            /*foreach (Letter letter in Find.LetterStack.LettersListForReading)
             * {
             *  Find.LetterStack.RemoveLetter(letter);
             * }*/
            List <Thing> things            = spaceMap.listerThings.AllThings;
            Thing        targetTorpedo     = null;
            IntVec3      torpedoToLocation = new IntVec3(0, 0, 0);
            IntVec3?     sunLampLocation   = null;

            foreach (Thing thing in things)
            {
                try
                {
                    if (thing.def == ThingDefOf.MinifiedThing)
                    {
                        Thing thingInside = ((MinifiedThing)thing).InnerThing;
                        if (thingInside.TryGetComp <CompPowerBattery>() != null)
                        {
                            thingInside?.TryGetComp <CompPowerBattery>()?.AddEnergy(float.PositiveInfinity);
                        }
                    }
                    if (sunLampLocation == null && thing.def == DefDatabase <ThingDef> .GetNamed("SunLamp"))
                    {
                        sunLampLocation = thing.Position;
                    }
                    if (thing?.TryGetComp <CompForbiddable>() != null)
                    {
                        thing.TryGetComp <CompForbiddable>().Forbidden = false;
                    }
                    if (thing?.TryGetComp <CompQuality>() != null)
                    {
                        thing.TryGetComp <CompQuality>().SetQuality(QualityCategory.Legendary, ArtGenerationContext.Colony);
                    }
                    if (thing?.TryGetComp <CompArt>() != null)
                    {
                        thing.TryGetComp <CompArt>().JustCreatedBy(spaceMap.mapPawns.AllPawns.RandomElement());
                    }
                    if (thing?.TryGetComp <CompRefuelable>() != null)
                    {
                        //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine_Small") ||
                        //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine") ||
                        //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine_Large")
                        CompRefuelable fuelTarget = thing?.TryGetComp <CompRefuelable>();
                        fuelTarget?.Refuel(fuelTarget.Props.fuelCapacity);
                    }
                    if (thing?.TryGetComp <CompTempControl>() != null)
                    {
                        thing.TryGetComp <CompTempControl>().targetTemperature = 19f;
                    }
                    if (thing?.TryGetComp <CompBreakdownable>() != null)
                    {
                    }
                    if (thing?.TryGetComp <CompPower>() != null)
                    {
                    }
                    if (
                        thing?.def?.building?.buildingTags?.Contains("Production") == true &&
                        thing?.TryGetComp <CompFlickable>() != null &&
                        thing.def != DefDatabase <ThingDef> .GetNamed("HydroponicsBasin")
                        )
                    {
                        thing.TryGetComp <CompFlickable>().SwitchIsOn = false;
                    }
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("HydroponicsBasin"))
                    {
                        ((Building_PlantGrower)thing)?.SetPlantDefToGrow(ThingDefOf.Plant_Potato);
                        thing.TryGetComp <CompForbiddable>().Forbidden = true;
                    }
                    if (thing.def == ThingDefOf.Blight)
                    {
                        ((Blight)thing).Severity = 0.05f;
                    }
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("ShipCombatShieldGenerator"))
                    {
                        thing.TryGetComp <CompFlickable>().SwitchIsOn = false;
                        thing.TryGetComp <CompBreakdownable>()?.DoBreakdown();
                    }
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("ShipTurret_Laser"))
                    {
                        ((Building_ShipTurret)thing).PointDefenseMode = true;
                    }
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("Plant_Potato"))
                    {
                        ((Plant)thing).Growth = 0.85f;
                    }

                    /*if (thing.def == DefDatabase<ThingDef>.GetNamed("ShipTorpedoOne"))
                     * {
                     *  foreach (Thing thingInside in ((Building_ShipTurretTorpedo)thing).Contents.innerContainer)
                     *  {
                     *      if (thing.def == DefDatabase<ThingDef>.GetNamed("ShipTorpedo_HighExplosive"))
                     *      {
                     *          thing.def = DefDatabase<ThingDef>.GetNamed("ShipTorpedo_EMP");
                     *      }
                     *  }
                     * }*/
                    if (
                        thing.def == DefDatabase <ThingDef> .GetNamed("ComponentIndustrial") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("ShipTorpedo_HighExplosive") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("ShipTorpedo_EMP") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("Chemfuel") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("ShuttleFuelPods") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("WoodLog") ||
                        thing.def == DefDatabase <ThingDef> .GetNamed("Shell_EMP")
                        )
                    {
                        //Log.Message("[Explorite]Patching stack.");
                        thing.stackCount = thing.def.stackLimit;

                        foreach (Thing thingInGrid in spaceMap.thingGrid.ThingsAt(thing.Position))
                        {
                            if (thingInGrid.def == DefDatabase <ThingDef> .GetNamed("Shelf"))
                            {
                                ((Building_Storage)thingInGrid).settings.filter.SetDisallowAll();
                                ((Building_Storage)thingInGrid).settings.filter.SetAllow(thing.def, true);
                            }
                        }
                    }

                    /*if (thing.def == DefDatabase<ThingDef>.GetNamed("ShipTorpedo_HighExplosive"))
                     * {
                     *  //Log.Message("[Explorite]Patching HE.");
                     *  thing.stackCount = 1;
                     *  //thing.def = DefDatabase<ThingDef>.GetNamed("ShipTorpedo_EMP");
                     * }*/
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("Shelf"))
                    {
                        torpedoToLocation.z = Math.Max(thing.Position.z, torpedoToLocation.z);
                    }
                    if (thing.def == DefDatabase <ThingDef> .GetNamed("ShipTorpedo_HighExplosive"))
                    {
                        torpedoToLocation.x = Math.Max(thing.Position.x, torpedoToLocation.x);
                        if (targetTorpedo == null)
                        {
                            targetTorpedo = thing;
                        }
                        else if (thing.Position.z > targetTorpedo.Position.z)
                        {
                            targetTorpedo = thing;
                        }
                    }
                    for (int i = -4; i < 5; i++)
                    {
                        for (int j = -4; j < 5; j++)
                        {
                            spaceMap.areaManager.Home[new IntVec3(i, 0, j) + thing.Position] = true;
                        }
                    }
                }
                catch { }
            }
            targetTorpedo.Position = torpedoToLocation;


            /*
             * Thing InterplanetaryEngineL = ThingMaker.MakeThing(ThingDef.Named("Ship_Engine_Interplanetary"));
             * InterplanetaryEngineL.SetFaction(Faction.OfPlayer);
             * GenSpawn.Spawn(InterplanetaryEngineL, new IntVec3(-18,0,-28), spaceMap);
             * Thing InterplanetaryEngineR = ThingMaker.MakeThing(ThingDef.Named("Ship_Engine_Interplanetary"));
             * InterplanetaryEngineR.SetFaction(Faction.OfPlayer);
             * GenSpawn.Spawn(InterplanetaryEngineR, new IntVec3(18,0,-28), spaceMap);
             *  //((Blueprint_Build)InterplanetaryEngineL).;
             */

            if (false && sunLampLocation.HasValue)
            {
                IntVec3 leftEngine = new IntVec3(sunLampLocation.Value.ToVector3());
                leftEngine.x -= 18;
                leftEngine.z -= 17;
                IntVec3 rightEngine = new IntVec3(sunLampLocation.Value.ToVector3());
                leftEngine.x  += 18;
                rightEngine.z -= 17;

                Thing InterplanetaryEngineL = ThingMaker.MakeThing(ThingDef.Named("Blueprint_Ship_Engine_Interplanetary"));
                InterplanetaryEngineL.SetFaction(Faction.OfPlayer);
                GenSpawn.Spawn(InterplanetaryEngineL, leftEngine, spaceMap);

                Thing InterplanetaryEngineR = ThingMaker.MakeThing(ThingDef.Named("Blueprint_Ship_Engine_Interplanetary"));
                InterplanetaryEngineR.SetFaction(Faction.OfPlayer);
                GenSpawn.Spawn(InterplanetaryEngineR, rightEngine, spaceMap);
            }


            /*
             * List<Building> thingsRocket = spaceMap.listerBuildings.allBuildingsColonist;
             * foreach (Building thing in thingsBatteryIn)
             * {
             *  try
             *  {
             *      if (
             *          thing?.TryGetComp<CompRefuelable>() != null
             *          //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine_Small") ||
             *          //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine") ||
             *          //thing.def == DefDatabase<ThingDef>.GetNamed("Ship_Engine_Large")
             *          )
             *      {
             *          CompRefuelable fuelTarget = thing?.TryGetComp<CompRefuelable>();
             *          fuelTarget.ConsumeFuel(
             *              fuelTarget.Fuel -
             *              fuelTarget.Props.fuelCapacity
             *              );
             *      }
             *  }
             *  catch { }
             * }*/
        }
Esempio n. 27
0
        public ThingDef GetHybridBee()
        {
            Building_HybridizationChamber buildinghybridizationchamber = (Building_HybridizationChamber)this.job.GetTarget(TargetIndex.A).Thing;

            return(DefDatabase <ThingDef> .GetNamed("RB_Bee_" + buildinghybridizationchamber.hybridizedBee + "_Queen", true));
        }
Esempio n. 28
0
        public override void PostGameStart()
        {
            if (SoS2Reflection.inaccessible)
            {
                return;
            }

            if (WorldSwitchUtility.SelectiveWorldGenFlag)
            {
                return;
            }
            ShipCombatManager.CanSalvageEnemyShip    = false;
            ShipCombatManager.ShouldSalvageEnemyShip = false;
            ShipCombatManager.InCombat    = false;
            ShipCombatManager.InEncounter = false;
            List <Pawn> startingPawns = Find.CurrentMap.mapPawns.PawnsInFaction(Faction.OfPlayer);
            int         newTile       = -1;

            for (int i = 0; i < 420; i++)
            {
                if (!Find.World.worldObjects.AnyMapParentAt(i))
                {
                    newTile = i;
                    break;
                }
            }
            Map spaceMap = GetOrGenerateMapUtility.GetOrGenerateMap(newTile, DefDatabase <WorldObjectDef> .GetNamed("ShipOrbiting"));

            ((WorldObjectOrbitingShip)spaceMap.Parent).radius = 150;
            ((WorldObjectOrbitingShip)spaceMap.Parent).theta  = 2.75f;
            //Building core = null;
            Current.ProgramState = ProgramState.MapInitializing;
            SoS2Reflection.GenerateShip(DefDatabase <EnemyShipDef> .GetNamed("CentaursScenarioRetroCruise"), spaceMap, null, Faction.OfPlayer, null, out _);
            Current.ProgramState = ProgramState.Playing;
            IntVec2 secs = (IntVec2)typeof(MapDrawer).GetProperty("SectionCount", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(spaceMap.mapDrawer);

            Section[,] secArray = new Section[secs.x, secs.z];
            typeof(MapDrawer).GetField("sections", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(spaceMap.mapDrawer, secArray);
            for (int i = 0; i < secs.x; i++)
            {
                for (int j = 0; j < secs.z; j++)
                {
                    if (secArray[i, j] == null)
                    {
                        secArray[i, j] = new Section(new IntVec3(i, 0, j), spaceMap);
                    }
                }
            }
            List <IntVec3> cryptoPos = GetAllCryptoCells(spaceMap);

            foreach (Pawn p in startingPawns)
            {
                if (p.InContainerEnclosed)
                {
                    p.ParentHolder.GetDirectlyHeldThings().Remove(p);
                }
                else
                {
                    p.DeSpawn();
                    p.SpawnSetup(spaceMap, true);
                }
            }
            List <List <Thing> > list = new List <List <Thing> >();

            foreach (Pawn startingAndOptionalPawn in Find.GameInitData.startingAndOptionalPawns)
            {
                List <Thing> list2 = new List <Thing>
                {
                    startingAndOptionalPawn
                };
                list.Add(list2);
            }
            List <Thing> list3 = new List <Thing>();

            foreach (ScenPart allPart in Find.Scenario.AllParts)
            {
                list3.AddRange(allPart.PlayerStartingThings());
            }
            int num = 0;

            foreach (Thing item in list3)
            {
                if (!(item is Pawn))
                {
                    if (item.def.CanHaveFaction)
                    {
                        item.SetFactionDirect(Faction.OfPlayer);
                    }
                    list[num].Add(item);
                    num++;
                    if (num >= list.Count)
                    {
                        num = 0;
                    }
                }
            }
            foreach (List <Thing> thingies in list)
            {
                IntVec3 casketPos = cryptoPos.RandomElement();
                cryptoPos.Remove(casketPos);
                if (cryptoPos.Count() == 0)
                {
                    cryptoPos = GetAllCryptoCells(spaceMap); //Out of caskets, time to start double-dipping
                }
                foreach (Thing thingy in thingies)
                {
                    thingy.SetForbidden(true, false);
                    GenPlace.TryPlaceThing(thingy, casketPos, spaceMap, ThingPlaceMode.Near);
                }
                FloodFillerFog.FloodUnfog(casketPos, spaceMap);
            }
            Find.CurrentMap.Parent.Destroy();
            CameraJumper.TryJump(spaceMap.Center, spaceMap);
            spaceMap.weatherManager.curWeather  = WeatherDef.Named("OuterSpaceWeather");
            spaceMap.weatherManager.lastWeather = WeatherDef.Named("OuterSpaceWeather");
            H_Vacuum_PathFinder.ResetMap(spaceMap);
            Find.MapUI.Notify_SwitchedMap();

            CentaurAlphaShipPostProcess(spaceMap);
        }
        public void Hatch()
        {
            try
            {
                PawnGenerationRequest request = new PawnGenerationRequest(this.Props.hatcherPawn, this.hatcheeFaction, PawnGenerationContext.NonPlayer, -1, false, true, false, false, true, false, 1f, false, true, true, true, false, false, false, false, 0f, null, 1f, null, null, null, null, null, null, null, null, null, null, null, null);
                for (int i = 0; i < this.parent.stackCount; i++)
                {
                    Pawn pawn = PawnGenerator.GeneratePawn(request);
                    if (PawnUtility.TrySpawnHatchedOrBornPawn(pawn, this.parent))
                    {
                        if (pawn != null)
                        {
                            if (this.hatcheeParent != null)
                            {
                                if (pawn.playerSettings != null && this.hatcheeParent.playerSettings != null && this.hatcheeParent.Faction == this.hatcheeFaction)
                                {
                                    pawn.playerSettings.AreaRestriction = this.hatcheeParent.playerSettings.AreaRestriction;
                                }
                                if (pawn.RaceProps.IsFlesh)
                                {
                                    pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, this.hatcheeParent);
                                }
                            }
                            if (this.otherParent != null && (this.hatcheeParent == null || this.hatcheeParent.gender != this.otherParent.gender) && pawn.RaceProps.IsFlesh)
                            {
                                pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, this.otherParent);
                            }
                            if (parent.Map != null)
                            {
                                List <Thing> ignoredThings   = new List <Thing>();
                                List <Pawn>  allPawnsSpawned = pawn.Map.mapPawns.AllPawnsSpawned;

                                for (int k = 0; k < allPawnsSpawned.Count; k++)
                                {
                                    if (allPawnsSpawned[k] != null && allPawnsSpawned[k].def.defName == pawn.def.defName)
                                    {
                                        ignoredThings.Add(allPawnsSpawned[k]);
                                    }
                                }
                                Thing pawnThing = pawn as Thing;
                                ignoredThings.Add(pawnThing);
                                // Log.Message(DefDatabase<DamageDef>.GetNamed(Props.damageDef).defName);
                                GenExplosion.DoExplosion(parent.Position, parent.Map, Props.range, DefDatabase <DamageDef> .GetNamed(Props.damageDef), parent, Props.damage, -1, SoundDef.Named(Props.soundDef), null, null, null, null, 0f, 1, false, null, 0f, 1, 0, false, null, ignoredThings);
                            }
                        }
                        if (this.parent.Spawned)
                        {
                            FilthMaker.TryMakeFilth(this.parent.Position, this.parent.Map, ThingDefOf.Filth_AmnioticFluid, 1, FilthSourceFlags.None);
                        }
                    }
                    else
                    {
                        Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard);
                    }
                }
            }
            finally
            {
                this.parent.Destroy(DestroyMode.Vanish);
            }
        }
Esempio n. 30
0
 public bool isThereAConstructionSiteHere()
 {
     return(Find.WorldObjects.AnyWorldObjectOfDefAt(DefDatabase <WorldObjectDef> .GetNamed("RoadConstructionSite", true), GetCaravan().Tile));
 }