public static Name GeneratePawnName(Pawn pawn, NameStyle style = NameStyle.Full, string forcedLastName = null) { if (style == NameStyle.Full) { RulePackDef nameGenerator = pawn.RaceProps.GetNameGenerator(pawn.gender); if (nameGenerator != null) { string name = NameGenerator.GenerateName(nameGenerator, (string x) => !new NameSingle(x, false).UsedThisGame, false, null); return(new NameSingle(name, false)); } if (pawn.Faction != null && pawn.Faction.def.pawnNameMaker != null) { string rawName = NameGenerator.GenerateName(pawn.Faction.def.pawnNameMaker, delegate(string x) { NameTriple nameTriple4 = NameTriple.FromString(x); nameTriple4.ResolveMissingPieces(forcedLastName); return(!nameTriple4.UsedThisGame); }, false, null); NameTriple nameTriple = NameTriple.FromString(rawName); nameTriple.CapitalizeNick(); nameTriple.ResolveMissingPieces(forcedLastName); return(nameTriple); } if (pawn.RaceProps.nameCategory != PawnNameCategory.NoName) { if (Rand.Value < 0.5f) { NameTriple nameTriple2 = PawnBioAndNameGenerator.TryGetRandomUnusedSolidName(pawn.gender, forcedLastName); if (nameTriple2 != null) { return(nameTriple2); } } return(PawnBioAndNameGenerator.GeneratePawnName_Shuffled(pawn, forcedLastName)); } Log.Error("No name making method for " + pawn); NameTriple nameTriple3 = NameTriple.FromString(pawn.def.label); nameTriple3.ResolveMissingPieces(null); return(nameTriple3); } else { if (style == NameStyle.Numeric) { int num = 1; string text; while (true) { text = pawn.KindLabel + " " + num.ToString(); if (!NameUseChecker.NameSingleIsUsed(text)) { break; } num++; } return(new NameSingle(text, true)); } throw new InvalidOperationException(); } }
//Unmodified public override void Tick() { base.Tick(); if (landed) { return; } Vector3 exactPosition = ExactPosition; ticksToImpact--; if (!ExactPosition.InBounds(base.Map)) { ticksToImpact++; Position = ExactPosition.ToIntVec3(); Destroy(DestroyMode.Vanish); return; } Vector3 exactPosition2 = ExactPosition; if (!def.projectile.flyOverhead && canFreeIntercept && CheckForFreeInterceptBetween(exactPosition, exactPosition2)) { return; } Position = ExactPosition.ToIntVec3(); if (ticksToImpact == 60f && Find.TickManager.CurTimeSpeed == TimeSpeed.Normal && def.projectile.soundImpactAnticipate != null) { def.projectile.soundImpactAnticipate.PlayOneShot(this); } if (ticksToImpact <= 0) { if (DestinationCell.InBounds(base.Map)) { Position = DestinationCell; } ImpactSomething(); return; } if (ambientSustainer != null) { ambientSustainer.Maintain(); } // attack shooting expression if (this.launcher is Building_TurretGunCR == false) { if (Rand.Value > 0.7 && this.launcher.def.race.Humanlike && !robotBodyList.Contains(this.launcher.def.race.body.defName) && Gen.IsHashIntervalTick(launcher, Rand.Range(280, 700))) { AGAIN : string rndswear = RulePackDef.Named("AttackMote").Rules.RandomElement().Generate(); if (rndswear == "[swear]" || rndswear == "" || rndswear == " ") { goto AGAIN; } MoteMaker.ThrowText(launcher.Position.ToVector3Shifted(), this.launcher.Map, rndswear); } } }
public Pawn CreatePawn(ThingDef def, ThingDef stuffDef, Gender gender) { PawnKindDef kindDef = (from td in DefDatabase <PawnKindDef> .AllDefs where td.race == def select td).FirstOrDefault(); RulePackDef nameGenerator = kindDef.RaceProps.GetNameGenerator(gender); if (nameGenerator == null) { return(null); } if (kindDef != null) { Faction faction = Faction.OfPlayer; PawnGenerationRequest request = new PawnGenerationRequest(kindDef); Pawn pawn = PawnGenerator.GeneratePawn(request); if (pawn.Dead || pawn.Downed) { return(null); } pawn.gender = gender; pawn.Drawer.renderer.graphics.ResolveAllGraphics(); return(pawn); } else { return(null); } }
public static void CleanBite(Pawn actor, Pawn victim) { HediffWithComps fangs = actor.GetVampFangs(); string dmgLabel; float dmgAmount; DamageDef dmgDef; RulePackDef dmgRules; if (fangs != null && TryGetFangsDmgInfo(fangs, out dmgLabel, out dmgAmount, out dmgDef, out dmgRules)) { Hediff_Injury neckInjury = (Hediff_Injury)victim.health.hediffSet.hediffs.FirstOrDefault(x => x is Hediff_Injury y && !y.IsPermanent() && y?.Part?.def == BodyPartDefOf.Neck); if (neckInjury == null) { neckInjury = (Hediff_Injury)victim.health.hediffSet.hediffs.FirstOrDefault(x => x is Hediff_Injury y && !y.IsPermanent()); } if (neckInjury != null) { neckInjury.Heal((int)neckInjury.Severity + 1); Find.BattleLog.Add( new BattleLogEntry_StateTransition(victim, RulePackDef.Named("ROMV_BiteCleaned"), actor, null, null) ); if (victim.IsGhoul() && victim?.VampComp()?.ThrallData?.BondStage == BondStage.Thrall) { TryRemoveHarmedMemory(actor, victim); } else if (!victim.health.capacities.CanBeAwake) { TryRemoveHarmedMemory(actor, victim); } } } }
static void Prefix(ref Tale tale, RulePackDef extraInclude) { if (extraInclude.defName == "ArtDescription_Plushie") { tale = null; } }
public void TryThrowTaunt(RulePackDef rulePack, Pawn pawn) { if (!AllowThrowTauntNow(pawn)) { return; } string taunt = GrammarResolver.Resolve(rulePack.Rules[0].keyword, rulePack.Rules); if (taunt.NullOrEmpty()) { Log.Warning("CE tried throwing invalid taunt for " + pawn.ToString()); } else { MoteMaker.ThrowText(pawn.Position.ToVector3Shifted(), pawn.Map, taunt); } var curTick = Find.TickManager.TicksGame; if (!tauntTickTracker.ContainsKey(pawn)) { tauntTickTracker.Add(pawn, curTick); } else { tauntTickTracker[pawn] = curTick; } }
/// <summary> /// called when the initiator interacts with the specified recipient. /// </summary> /// <param name="initiator">The initiator.</param> /// <param name="recipient">The recipient.</param> /// <param name="extraSentencePacks">The extra sentence packs.</param> /// <param name="letterText">The letter text.</param> /// <param name="letterLabel">The letter label.</param> /// <param name="letterDef">The letter definition.</param> /// <param name="lookTargets">The look targets.</param> public override void Interacted(Pawn initiator, Pawn recipient, List <RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets) { base.Interacted(initiator, recipient, extraSentencePacks, out letterText, out letterLabel, out letterDef, out lookTargets); letterText = null; letterLabel = null; letterDef = null; SapienceLevel?saLevel = recipient?.GetQuantizedSapienceLevel(); if (saLevel == null) { return; } var saVariants = interaction.GetModExtension <SapientRulePackVariant>(); RulePackDef rulePackVariant = saVariants ?.GetRulePackVariant(saLevel.Value); //check if any variants are attached, if so add them to extra rule packs if (rulePackVariant != null) { extraSentencePacks.Add(rulePackVariant); } }
private static void Prefix(Thing subject, ref RulePackDef transitionDef, Hediff culpritHediff) { if (!(subject is Pawn pawn) || !Evaluator.IsExplosive(pawn) || Evaluator.IsExploding(pawn, culpritHediff)) { return; } transitionDef = RulePackDefOf.Transition_Died; }
public override void Initialize(CompProperties pro) { name = NameGenerator.GenerateName(RulePackDef.Named("EngravedName")); key = ""; for (int i = 0; i < 16; ++i) { key += random_hex_byte(); } }
/// <summary> /// Creates a cutebold name. /// </summary> /// <param name="nameMaker">The given name rules.</param> /// <param name="forcedLastName">The forced last name.</param> /// <returns>Returns a new cutebold name.</returns> private static NameTriple CuteboldNameResolver(RulePackDef nameMaker, string forcedLastName) { NameTriple name = NameTriple.FromString(NameGenerator.GenerateName(nameMaker, null, false, null, null)); name.CapitalizeNick(); name.ResolveMissingPieces(forcedLastName); return(name); }
public void Initialize() { bool unexpected = workTypes == null; ageTracker.AgeBiologicalTicks = 0; ageTracker.SetChronologicalBirthDate(GenDate.CurrentYear, GenDate.DayOfYear); RaceType = def.label; RaceProps.nameGenerator = RulePackDef.Named("NamerAnimalGeneric"); GiveRandomName(); InitStory(); // Skills skills = new Pawn_SkillTracker(this); skills.GetSkill(SkillDefOf.Melee); skills.Learn(SkillDefOf.Melee, KindDef.minSkillPoints); if (!DisplayThoughtTab) { //def.inspectorTabs.Remove(typeof (ITab_Pawn_Needs)); } // Talker talker = new Pawn_Converted_TalkTracker(this); SpawnSetupWorkSettings(); //needs.beauty = new Need_Beauty_Mechanoid(this); needs.food = new Need_Food(this); needs.rest = new Need_Rest(this); needs.mood = new Need_Mood(this); //needs.space = new Need_Space_Mechanoid(this); apparel = new Pawn_ApparelTracker(this); UpdateWorkCapacity(); // Job (should go last!) if (jobs.curJob == null) { var jobPackage = thinker.ThinkNodeRoot.TryIssueJobPackage(this); mindState.lastJobGiver = jobPackage.SourceNode; //.finalNode; jobs.StartJob(jobPackage.Job); } Log.Message(Label + " initialized."); if (unexpected) { TakeDamage(new DamageInfo(DamageDefOf.Crush, Rand.Range(15000, 20000))); } }
public static string GenerateName(RulePackDef rootPack, Predicate <string> validator = null, bool appendNumberIfNameUsed = false, string rootKeyword = null, string testPawnNameSymbol = null) { GrammarRequest grammarRequest = default(GrammarRequest); grammarRequest.Includes.Add(rootPack); if (testPawnNameSymbol != null) { grammarRequest.Rules.Add(new Rule_String("ANYPAWN_nameDef", testPawnNameSymbol)); grammarRequest.Rules.Add(new Rule_String("ANYPAWN_nameIndef", testPawnNameSymbol)); } string text = (rootKeyword == null) ? rootPack.FirstRuleKeyword : rootKeyword; string text2 = (rootKeyword == null) ? rootPack.FirstUntranslatedRuleKeyword : rootKeyword; if (appendNumberIfNameUsed) { string text3; GrammarRequest request; string text4; for (int i = 0; i < 100; i++) { for (int j = 0; j < 5; j++) { text3 = text; request = grammarRequest; text4 = text2; string text5 = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(text3, request, null, false, text4)); if (i != 0) { text5 = text5 + " " + (i + 1); } if (validator == null || validator(text5)) { return(text5); } } } text4 = text; request = grammarRequest; text3 = text2; return(GenText.ToTitleCaseSmart(GrammarResolver.Resolve(text4, request, null, false, text3))); } for (int k = 0; k < 150; k++) { string text3 = text; GrammarRequest request = grammarRequest; string text4 = text2; string text6 = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(text3, request, null, false, text4)); if (validator == null || validator(text6)) { return(text6); } } Log.Error("Could not get new name (rule pack: " + rootPack + ")", false); return("Errorname"); }
private void ApplyInteractionAndThought(Pawn thoughtReceiver, Pawn thoughtTarget, string defName, List <RulePackDef> extraSentencePacks) { var rulePack = RulePackDef.Named(defName); extraSentencePacks.Add(rulePack); if (!defName.Contains("NoPassion")) { ApplyThought(thoughtReceiver, thoughtTarget, defName); } }
public override void CompTick() { base.CompTick(); //Apply decay once per second if (parent.IsHashIntervalTick(60)) { //Decay global suppression if (currentSuppressionInt > suppressionDecayRate) { currentSuppressionInt -= suppressionDecayRate; //Check if pawn is still suppressed if (isSuppressed && currentSuppressionInt <= suppressionThreshold) { isSuppressed = false; } } else if (currentSuppressionInt > 0) { currentSuppressionInt = 0; isSuppressed = false; } //Decay location suppression if (locSuppressionAmount > suppressionDecayRate) { locSuppressionAmount -= suppressionDecayRate; } else if (locSuppressionAmount > 0) { locSuppressionAmount = 0; } } //Throw mote at set interval if (Gen.IsHashIntervalTick(parent, ticksPerMote + Rand.Range(30, 300)) && parent.def.race.Humanlike && !robotBodyList.Contains(parent.def.race.body.defName)) { if (isHunkering || isSuppressed) { AGAIN : string rndswearsuppressed = RulePackDef.Named("SuppressedMote").Rules.RandomElement().Generate(); if (rndswearsuppressed == "[suppressed]" || rndswearsuppressed == "" || rndswearsuppressed == " ") { goto AGAIN; } MoteMaker.ThrowText(this.parent.Position.ToVector3Shifted(), Find.VisibleMap, rndswearsuppressed); } //standard MoteMaker.ThrowText(parent.Position.ToVector3Shifted(), "CR_SuppressedMote".Translate()); } }
public override void Interacted(Pawn recruiter, Pawn guest, List <RulePackDef> extraSentencePacks) { if (recruiter == null || guest == null || guest.guest == null) { return; } // TODO: pawn.records.Increment(RecordDefOf.GuestsCharmAttempts); //recruiter.skills.Learn(SkillDefOf.Social, 35f); float pleaseChance = recruiter.GetStatValue(statPleaseGuestChance); pleaseChance = GuestUtility.AdjustPleaseChance(pleaseChance, recruiter, guest); pleaseChance = Mathf.Clamp01(pleaseChance); if (Rand.Value > pleaseChance) { var isAbrasive = recruiter.story.traits.HasTrait(TraitDefOf.Abrasive); int multiplier = isAbrasive ? 2 : 1; string multiplierText = multiplier > 1 ? " x" + multiplier : string.Empty; string textAnger = recruiter.gender == Gender.Female ? "RecruitAngerSelfF" : "RecruitAngerSelfM"; Messages.Message( textAnger.Translate(new object[] { recruiter.NameStringShort, guest.NameStringShort, (1 - pleaseChance).ToStringPercent(), multiplierText }), guest, MessageSound.Negative); extraSentencePacks.Add(RulePackDef.Named("Sentence_CharmAttemptRejected")); for (int i = 0; i < multiplier; i++) { GuestUtility.GainSocialThought(recruiter, guest, ThoughtDef.Named("GuestOffended")); } } else { var statValue = recruiter.GetStatValue(statRecruitEffectivity); var floor = Mathf.FloorToInt(statValue); int multiplier = floor + (Rand.Value < statValue - floor ? 1 : 0); string multiplierText = multiplier > 1 ? " x" + multiplier : string.Empty; string textPlease = recruiter.gender == Gender.Female ? "RecruitPleaseSelfF" : "RecruitPleaseSelfM"; Messages.Message( textPlease.Translate(new object[] { recruiter.NameStringShort, guest.NameStringShort, (pleaseChance).ToStringPercent(), multiplierText }), guest, MessageSound.Benefit); for (int i = 0; i < multiplier; i++) { GuestUtility.GainSocialThought(recruiter, guest, ThoughtDef.Named("GuestConvinced")); } extraSentencePacks.Add(RulePackDef.Named("Sentence_CharmAttemptAccepted")); } GuestUtility.GainSocialThought(recruiter, guest, ThoughtDef.Named("GuestDismissiveAttitude")); }
private static Name NameResolvedFrom(RulePackDef nameMaker, string forcedLastName) { NameTriple nameTriple = NameTriple.FromString(NameGenerator.GenerateName(nameMaker, delegate(string x) { NameTriple nameTriple2 = NameTriple.FromString(x); nameTriple2.ResolveMissingPieces(forcedLastName); return(!nameTriple2.UsedThisGame); })); nameTriple.CapitalizeNick(); nameTriple.ResolveMissingPieces(forcedLastName); return(nameTriple); }
public BattleLogEntry_MeleeCombat CreateCombatLog(RulePackDef rulePack) { if (this.maneuver == null) { return null; } if (this.tool == null) { return null; } BattleLogEntry_MeleeCombat battleLogEntry_MeleeCombat = new BattleLogEntry_MeleeCombat(rulePack, this.maneuver.combatLogRules, base.CasterPawn, this.currentTarget.Thing, this.implementOwnerType, (!this.tool.labelUsedInLogging) ? string.Empty : this.tool.label, (this.ownerEquipment != null) ? this.ownerEquipment.def : null, (this.ownerHediffComp != null) ? this.ownerHediffComp.Def : null); Find.BattleLog.Add(battleLogEntry_MeleeCombat); return battleLogEntry_MeleeCombat; }
public static string GenerateName(RulePackDef rootPack, Predicate <string> validator = null, bool appendNumberIfNameUsed = false, string rootKeyword = null, string testPawnNameSymbol = null) { GrammarRequest request = default(GrammarRequest); request.Includes.Add(rootPack); if (testPawnNameSymbol != null) { request.Rules.Add(new Rule_String("ANYPAWN_nameDef", testPawnNameSymbol)); request.Rules.Add(new Rule_String("ANYPAWN_nameIndef", testPawnNameSymbol)); } string rootKeyword2 = ((rootKeyword != null) ? rootKeyword : rootPack.FirstRuleKeyword); string untranslatedRootKeyword = ((rootKeyword != null) ? rootKeyword : rootPack.FirstUntranslatedRuleKeyword); return(GenerateName(request, validator, appendNumberIfNameUsed, rootKeyword2, untranslatedRootKeyword)); }
/// <summary> /// Makes a battle log using the RulePackDef of JT_GrappleSuccess. /// It's pretty cool, because we can see the character's grapple attempt in combat logs. /// </summary> /// <param name="victim"></param> /// <param name="grappler"></param> /// <param name="grapplingPart"></param> /// <returns></returns> public static bool TryMakeBattleLog(Pawn victim, Pawn grappler, BodyPartRecord grapplingPart) { try { Find.BattleLog.Add( new BattleLogEntry_StateTransition(victim, RulePackDef.Named("JT_GrappleSuccess"), grappler, null, grapplingPart.def) ); return(true); } catch (Exception e) { Log.Warning("TruMakeBattleLog Failed Due To :: " + e); } return(false); }
private void InitiateShipProperties() { DropShipUtility.currentShipTracker.AllWorldShips.Add(this); this.ShipNick = NameGenerator.GenerateName(RulePackDef.Named("NamerShipGeneric")); this.compShipCached = this.TryGetComp <CompShip>(); if (this.compShip == null) { Log.Error("DropShip is missing " + nameof(CompProperties_Ship) + "/n Defaulting."); this.compShipCached = new CompShip(); this.drawTickOffset = compShip.sProps.TicksToImpact; } if (this.installedTurrets.Count == 0) { this.InitiateInstalledTurrets(); } }
public Pawn CreatePawn(ThingDef def, ThingDef stuffDef, Gender gender) { PawnKindDef kindDef = (from td in DefDatabase <PawnKindDef> .AllDefs where td.race == def select td).FirstOrDefault(); RulePackDef nameGenerator = kindDef.RaceProps.GetNameGenerator(gender); if (nameGenerator == null) { return(null); } if (kindDef != null) { int messageCount; Faction faction = Faction.OfPlayer; PawnGenerationRequest request = new PawnGenerationRequestWrapper() { KindDef = kindDef, Faction = faction, MustBeCapableOfViolence = true }.Request; messageCount = ReflectionUtil.GetNonPublicStatic <int>(typeof(Log), "messageCount"); Pawn pawn = PawnGenerator.GeneratePawn(request); if (ReflectionUtil.GetNonPublicStatic <int>(typeof(Log), "messageCount") > messageCount) { Log.Warning("Prepare Carefully failed to generate a pawn/animal for the equipment list: " + def.defName); } if (pawn.Dead || pawn.Downed) { return(null); } pawn.gender = gender; messageCount = ReflectionUtil.GetNonPublicStatic <int>(typeof(Log), "messageCount"); pawn.Drawer.renderer.graphics.ResolveAllGraphics(); if (ReflectionUtil.GetNonPublicStatic <int>(typeof(Log), "messageCount") > messageCount) { Log.Warning("Prepare Carefully failed to load all graphics for equipment list pawn/animal: " + def.defName); } return(pawn); } else { return(null); } }
public static string GenerateName(RulePackDef rootPack, Predicate <string> validator = null, bool appendNumberIfNameUsed = false, string rootKeyword = null, string testPawnNameSymbol = null) { GrammarRequest request = default(GrammarRequest); request.Includes.Add(rootPack); if (testPawnNameSymbol != null) { request.Rules.Add(new Rule_String("ANYPAWN_nameDef", testPawnNameSymbol)); request.Rules.Add(new Rule_String("ANYPAWN_nameIndef", testPawnNameSymbol)); } rootKeyword = ((rootKeyword == null) ? rootPack.RulesPlusIncludes[0].keyword : rootKeyword); string result; if (appendNumberIfNameUsed) { for (int i = 0; i < 100; i++) { for (int j = 0; j < 5; j++) { string text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootKeyword, request, null, false)); if (i != 0) { text = text + " " + (i + 1); } if (validator == null || validator(text)) { return(text); } } } result = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootKeyword, request, null, false)); } else { for (int k = 0; k < 150; k++) { string text2 = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootKeyword, request, null, false)); if (validator == null || validator(text2)) { return(text2); } } Log.Error("Could not get new name (rule pack: " + rootPack + ")", false); result = "Errorname"; } return(result); }
public static TaggedString GenerateTextFromTale(TextGenerationPurpose purpose, Tale tale, int seed, RulePackDef extraInclude, CompBook compBook) { Rand.PushState(); Rand.Seed = seed; string rootKeyword = null; GrammarRequest request = default(GrammarRequest); request.Includes.Add(extraInclude); switch (purpose) { case TextGenerationPurpose.ArtDescription: rootKeyword = compBook.Props.nameMaker.RulesImmediate .Where(x => x.keyword != null && x.keyword.Length > 0).RandomElement().keyword; //Log.Message("rootKeyword for description: " + rootKeyword); if (tale != null && !Rand.Chance(0.2f)) { request.Includes.Add(RulePackDefOf.ArtDescriptionRoot_HasTale); request.IncludesBare.AddRange(tale.GetTextGenerationIncludes()); request.Rules.AddRange(tale.GetTextGenerationRules()); } else { request.Includes.Add(RulePackDefOf.ArtDescriptionRoot_Taleless); request.Includes.Add(RulePackDefOf.TalelessImages); } request.Includes.Add(RulePackDefOf.ArtDescriptionUtility_Global); break; case TextGenerationPurpose.ArtName: rootKeyword = compBook.Props.descriptionMaker.RulesImmediate .Where(x => x.keyword != null && x.keyword.Length > 0).RandomElement().keyword; //Log.Message("rootKeyword for name: " + rootKeyword); if (tale != null) { request.IncludesBare.AddRange(tale.GetTextGenerationIncludes()); request.Rules.AddRange(tale.GetTextGenerationRules()); } break; } string str = GrammarResolver.Resolve(rootKeyword, request, (tale != null) ? tale.def.defName : "null_tale"); Rand.PopState(); return(str); }
/// <summary> /// create the main log text /// </summary> /// <param name="pov">The pov.</param> /// <param name="forceLog">if set to <c>true</c> [force log].</param> /// <returns></returns> protected override string ToGameStringFromPOV_Worker(Thing pov, bool forceLog) { Assert(pov == _pawn, "pov == _pawn"); Rand.PushState(logID); // Does not need a MP-safe seed. try { GrammarRequest grammarRequest = GenerateGrammarRequest(); RulePackDef mutationRulePack = (_mutationDef as MutationDef)?.mutationLogRulePack; if (mutationRulePack != null) { grammarRequest.Includes.Add(mutationRulePack); } else { grammarRequest.Includes.Add(PMRulePackDefOf.GetDefaultPackForMutation(_mutationDef)); grammarRequest.Rules.Add(new Rule_String("DATE", GenDate.DateFullStringAt(ticksAbs, Vector2.zero))); } AddCustomRules(grammarRequest.Rules); IEnumerable <Rule> pawnR = GrammarUtility.RulesForPawn(PAWN_IDENTIFIER, _pawn, grammarRequest.Constants); BodyPartRecord partR = BodyDefOf.Human.AllParts.Where(r => _mutatedRecords.Contains(r.def)).RandomElement(); IEnumerable <Rule> partRules = GrammarUtility.RulesForBodyPartRecord(PART_LABEL, partR); IEnumerable <Rule> mutR = GrammarUtility.RulesForHediffDef(MUTATION_IDENTIFIER, _mutationDef, partR); // Add the rules. grammarRequest.Rules.AddRange(pawnR); grammarRequest.Rules.AddRange(mutR); grammarRequest.Rules.AddRange(partRules); return(GrammarResolver.Resolve(RP_ROOT_RULE, grammarRequest, "mutation log", forceLog)); } catch (Exception exception) { Log.Error($"encountered {exception.GetType().Name} exception while generating string for mutation log\n\t{exception}"); } finally { Rand.PopState(); // Make sure to always pop rand. } return(_mutationDef.LabelCap); //TODO generate string }
public static string GenerateName(RulePackDef rootPack, Predicate <string> validator = null, bool appendNumberIfNameUsed = false, string rootKeyword = null) { string text = null; GrammarRequest request = default(GrammarRequest); request.Includes.Add(rootPack); if (appendNumberIfNameUsed) { for (int i = 0; i < 100; i++) { int num = 0; while (num < 5) { text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve((rootKeyword == null) ? rootPack.RulesPlusIncludes[0].keyword : rootKeyword, request, null, false)); if (i != 0) { text = text + " " + (i + 1); } if (validator != null && !validator(text)) { num++; continue; } return(text); } } return(GenText.ToTitleCaseSmart(GrammarResolver.Resolve((rootKeyword == null) ? rootPack.RulesPlusIncludes[0].keyword : rootKeyword, request, null, false))); } int num2 = 0; while (num2 < 150) { text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve((rootKeyword == null) ? rootPack.RulesPlusIncludes[0].keyword : rootKeyword, request, null, false)); if (validator != null && !validator(text)) { num2++; continue; } return(text); } Log.Error("Could not get new name (rule pack: " + rootPack + ")"); return(text); }
public void ResolveReferences() { int num = Mathf.Abs(GenText.StableStringHash(baseDesc) % 100); string s = title.Replace('-', ' '); s = GenText.CapitalizedNoSpaces(s); identifier = GenText.RemoveNonAlphanumeric(s) + num.ToString(); foreach (KeyValuePair <string, int> skillGain in skillGains) { skillGainsResolved.Add(DefDatabase <SkillDef> .GetNamed(skillGain.Key), skillGain.Value); } skillGains = null; if (!bodyTypeGlobal.NullOrEmpty()) { bodyTypeGlobalResolved = DefDatabase <BodyTypeDef> .GetNamed(bodyTypeGlobal); } if (!bodyTypeFemale.NullOrEmpty()) { bodyTypeFemaleResolved = DefDatabase <BodyTypeDef> .GetNamed(bodyTypeFemale); } if (!bodyTypeMale.NullOrEmpty()) { bodyTypeMaleResolved = DefDatabase <BodyTypeDef> .GetNamed(bodyTypeMale); } if (!nameMaker.NullOrEmpty()) { nameMakerResolved = DefDatabase <RulePackDef> .GetNamed(nameMaker); } if (slot == BackstorySlot.Adulthood && bodyTypeGlobalResolved == null) { if (bodyTypeMaleResolved == null) { Log.Error("Adulthood backstory " + title + " is missing male body type. Defaulting..."); bodyTypeMaleResolved = BodyTypeDefOf.Male; } if (bodyTypeFemaleResolved == null) { Log.Error("Adulthood backstory " + title + " is missing female body type. Defaulting..."); bodyTypeFemaleResolved = BodyTypeDefOf.Female; } } }
/// <summary> /// Generates a name for a cutebold. May generate a name that has been used if unable to create a unique one. /// </summary> /// <param name="rulePack">The given name rules.</param> /// <param name="forcedLastName">The forced last name.</param> /// <returns>Returns a new cutebold name.</returns> private static NameTriple CuteboldNameGenerator(RulePackDef rulePack, string forcedLastName) { var name = CuteboldNameResolver(rulePack, forcedLastName); for (int i = 0; i < 100; i++) { if (!CuteboldNameChecker(name)) { //Log.Message(" Generated name: "+__result.ToStringFull+" after "+i+" tries."); return(name); } name = CuteboldNameResolver(rulePack, forcedLastName); } Log.Warning(string.Format("{0}: Failed at creating a unique name, using {1}.", new object[] { Cutebold_Assemblies.ModName, name.ToStringFull })); return(name); }
public static string GenerateSettlementName(Settlement factionBase, RulePackDef rulePack = null) { if (rulePack == null) { if (factionBase.Faction == null || factionBase.Faction.def.settlementNameMaker == null) { return(factionBase.def.label); } rulePack = factionBase.Faction.def.settlementNameMaker; } SettlementNameGenerator.usedNames.Clear(); List <Settlement> settlements = Find.WorldObjects.Settlements; for (int i = 0; i < settlements.Count; i++) { Settlement settlement = settlements[i]; if (settlement.Name != null) { SettlementNameGenerator.usedNames.Add(settlement.Name); } } return(NameGenerator.GenerateName(rulePack, SettlementNameGenerator.usedNames, true, null)); }
public static bool get_RulesPlusIncludes(RulePackDef __instance, ref List <Rule> __result) { if (__instance.cachedRules == null) { lock (__instance) { List <Rule> tmpCachedRules = new List <Rule>(); //changed if (__instance.rulePack != null) { tmpCachedRules.AddRange((IEnumerable <Rule>)__instance.rulePack.Rules); //changed } if (__instance.include != null) { for (int index = 0; index < __instance.include.Count; ++index) { tmpCachedRules.AddRange((IEnumerable <Rule>)__instance.include[index].RulesPlusIncludes); //changed } } __instance.cachedRules = tmpCachedRules; //changed } } __result = __instance.cachedRules; return(false); }
protected override bool TryExecuteWorker(IncidentParms parms) { Map map = parms.target as Map; Pawn closestCat = TryGetClosestCatOnMap(map); GuardianProperties guardianProps = def.GetModExtension <GuardianProperties>(); if (closestCat != null) { //Transform Cat //Generate guardian Pawn newGuardian = PawnGenerator.GeneratePawn(new PawnGenerationRequest( guardianProps.guardianDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, -1, true, false, false, false, false, true, 0f, false, true, true, false, false, false, false, false, 0, null, 0, null, null, null, null, null, closestCat.ageTracker.AgeBiologicalYears, closestCat.ageTracker.AgeChronologicalYears, closestCat.gender, null, null)); //Transfer over family trees and relations to guardian from old cat. Pawn_RelationsTracker oldRelations = closestCat.relations; Pawn_RelationsTracker newRelations = newGuardian.relations; //Transfer over relations. List <DirectPawnRelation> relationList = new List <DirectPawnRelation>(oldRelations.DirectRelations); foreach (DirectPawnRelation relation in relationList) { newRelations.AddDirectRelation(relation.def, relation.otherPawn); oldRelations.RemoveDirectRelation(relation); } //Fully train. foreach (TrainableDef trainableDef in DefDatabase <TrainableDef> .AllDefs) { for (int step = 0; step < trainableDef.steps; step++) { newGuardian.training.Train(trainableDef, null); } } //Make a new name. if (closestCat.Name != null) { if (closestCat.gender == Gender.Male) { newGuardian.Name = new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericMale")), false); } else { newGuardian.Name = new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericFemale")), false); } } //Dump inventory, if any. closestCat?.inventory.DropAllNearPawn(closestCat.Position); Letter letter = LetterMaker.MakeLetter("Cults_BastGuardianTransformationLabel".Translate(closestCat.Name.ToStringShort), "Cults_BastGuardianTransformationDescription".Translate(closestCat.Name.ToStringFull), LetterDefOf.PositiveEvent, new GlobalTargetInfo(newGuardian)); //Remove old cat. IntVec3 catPosition = closestCat.Position; closestCat.Destroy(DestroyMode.Vanish); //Spawn in guardian. GenSpawn.Spawn(newGuardian, catPosition, map); MoteMaker.MakePowerBeamMote(catPosition, map); Current.Game.letterStack.ReceiveLetter(letter); } return(true); }