using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; using Verse.AI; using Verse.Sound; namespace BlaxLaws { /// /// The subdue part of a case (design: "Subdue"): who is sent, what happens when the pawn goes down or the /// beating gives up, and what a Subdue row does when the break is already over. The Subdue and "Subdue /// then jail" workers and JobDriver_Subdue call in here. /// public static class SubdueFlow { /// /// The offender is still in the break the case is about: the recorded break for a break case, any /// break for a case outside one (a slave's jail row falls back to subdue only while it is in a break). /// public static bool InBreak(LawCase c) { Pawn o = c?.offender; if (o == null || o.Dead) return false; return c.IsBreakCase ? CaseFiler.StillInBreak(c) : o.InMentalState; } /// The case's enforcer runs the subdue job on the offender right now. public static bool Runs(LawCase c) => c?.enforcer != null && c.offender != null && EnforcerJobs.Runs(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); /// The open case whose subdue this enforcer carries out on this target, or null. public static LawCase CaseFor(Pawn enforcer, Pawn target) { GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; if (comp == null || enforcer == null || target == null) return null; IReadOnlyList list = comp.CasesOf(target); for (int i = list.Count - 1; i >= 0; i--) { LawCase c = list[i]; if (!c.IsClosed && c.enforcer == enforcer && IsSubduePunishment(c.activePunishment)) return c; } return null; } /// "Subdue" or "Subdue then jail". public static bool IsSubduePunishment(string defName) => defName != null && (defName == BlaxLawsDefOf.Subdue?.defName || defName == BlaxLawsDefOf.SubdueThenJail?.defName); /// /// Sends an enforcer on the subdue job, or leaves the case waiting with its reason (danger, nobody /// free, nobody able: a letter once). Returns whether the job runs. /// public static bool TryIssue(LawCase c, EnforcerNeed need) { Pawn o = c?.offender; if (o == null || !o.Spawned) { WaitReasons.Set(c, WaitReasons.Away); return false; } if (Enforcers.DangerBlocks(o)) { WaitReasons.Set(c, WaitReasons.Danger); return false; } Pawn e = Enforcers.Pick(c, need, out string reason); if (e == null) { if (WaitReasons.Set(c, reason) && reason == WaitReasons.NoEnforcer && CaseLetters.Once(c, CaseLetters.KindNoEnforcer)) CaseLetters.NoEnforcer(c); return false; } return TryStartWith(c, e); } /// /// Starts the subdue job with this enforcer, no pick and no danger check: the hook point for a subdue /// the player starts ("Subdue a pawn that fights back", Enforcement step 3). Returns whether it runs. /// Step 3 must also leave its offender out of CallOffInDanger. /// public static bool TryStartWith(LawCase c, Pawn enforcer) { if (c?.offender == null || enforcer == null || BlaxLawsDefOf.BlaxLaws_Subdue == null) return false; Job job = JobMaker.MakeJob(BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); c.enforcer = enforcer; c.status = CaseStatus.Enforcing; c.waitReason = null; if (EnforcerJobs.Start(enforcer, job)) return true; WaitReasons.Set(c, WaitReasons.Busy); return false; } /// Ends the running subdue job of the case, if any. Keeps the enforcer for a hand-over. public static void End(LawCase c) { if (c?.enforcer != null && c.offender != null) EnforcerJobs.End(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); } /// /// A running subdue meets danger (a raid lands, a colonist goes berserk): the job ends and the case waits /// for Danger, so the sweep sends someone again after the fight. The job is player-forced, so vanilla /// never pulls the enforcer off it when it is hit (Pawn_JobTracker.cs:982) and the hostility response /// skips it (PawnUtility.cs:377-385). Returns whether it was called off. /// public static bool CallOffInDanger(LawCase c) { if (!Runs(c) || !Enforcers.DangerBlocks(c.offender)) return false; End(c); WaitReasons.Set(c, WaitReasons.Danger); return true; } /// /// A later stage of the case is queued and dispatches within a tick (a did-it act filed during the /// subdue), and its punishment replaces the subdue (a Jail). The subdue then leaves the case open, so /// Enforcement hands over to that stage's punishment (design: "One enforcement per case") instead of the /// stage being dropped on a closed case. A queued Warn, Guilty or same subdue is no hand-over: /// RunQueuedAlongside carries it out before the case closes. /// public static bool HandOverDue(LawCase c) { if (c == null || !BlaxLawsMod.S.enforceLaws || !Enforcement.IsQueued(c, CaseTask.Punish)) return false; foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt }) { if (c.HasPunished(s)) continue; PunishmentDef p = c.LawFor(s)?.PunishmentDef; if (p != null && !p.runsAlongside && p.defName != c.activePunishment) return true; } return false; } /// /// Before the subdue closes its case: a queued stage that runs alongside (Warn, Guilty) runs now, and with /// sameToo one with this same subdue punishment too, so it is carried out and logged instead of dropped /// on the closed case. While the subdue job runs, a same-punishment stage starts nothing; from the sweep /// its Start closes the downed offender's case as Subdued. A stage with another punishment (a Jail) /// stays queued and HandOverDue keeps the case open for it. /// internal static void RunQueuedAlongside(LawCase c, bool sameToo) { if (c == null || c.IsClosed || !BlaxLawsMod.S.enforceLaws) return; string active = c.activePunishment; Enforcement.DispatchNow(c, p => p.runsAlongside || (sameToo && p.defName == active)); } /// Closes the case as Warned with a message saying why it wasn't a subdue. public static void WarnInstead(LawCase c, string messageKey) { if (c == null || c.IsClosed) return; CaseMessages.Post(c, messageKey.Translate(c.OffenderLabel)); GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Warned); } /// /// The break is over before a subdue could act: a planning case closes as "break ended" (nothing was /// done), a did-it Subdue row warns (design: "Defaults I picked"). /// public static void BreakOver(LawCase c) { if (c == null || c.IsClosed) return; if (c.activeStage == LawStage.Planning) GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.BreakEnded); else WarnInstead(c, "BlaxLaws_MsgWarnedAfterBreak"); } /// /// The hit downed the offender. Subdue closes the case; "Subdue then jail" queues the vanilla Capture /// at the front of the enforcer's queue (JailFlow.CaptureAfterSubdue). Called by the driver inside /// its toil, so nothing here starts a job. A later stage already queued (HandOverDue) keeps the case open /// for its hand-over. /// internal static void OnDowned(LawCase c, Pawn enforcer) { if (c == null || c.IsClosed) return; if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName) { JailFlow.CaptureAfterSubdue(c, enforcer); return; } CaseMessages.Post(c, "BlaxLaws_MsgSubdued".Translate(c.OffenderLabel, enforcer.LabelShort)); RunQueuedAlongside(c, sameToo: Runs(c)); if (c.IsClosed) return; if (HandOverDue(c)) return; // The queued stage takes over next tick: a Jail captures the downed offender. GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Subdued); } /// /// Three hits in a row caused no pain, or the ceiling was reached: one message. Subdue closes the case /// as not subdued; "Subdue then jail" arrests instead, from the next sweep (the driver is still inside /// its toil, so no job starts here). A later stage already queued (HandOverDue) keeps the case open for /// its hand-over. /// internal static void OnGaveUp(LawCase c, Pawn enforcer) { if (c == null || c.IsClosed) return; CaseMessages.Post(c, "BlaxLaws_MsgSubdueGaveUp".Translate(c.OffenderLabel, enforcer.LabelShort)); if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName) { JailFlow.Become(c); return; } // A queued same-punishment stage is no hand-over: it is done here while the job still runs (or dropped // with the closed case), so it never starts a second beating of a pawn the subdue just gave up on. RunQueuedAlongside(c, sameToo: Runs(c)); if (c.IsClosed) return; if (HandOverDue(c)) return; // The queued stage takes over next tick. GameComponent_BlaxLaws.Instance?.CloseCase(c, EnforcementOutcomes.NotSubdued); } } /// /// One hit of the subdue (design: "Subdue", the hit). Blunt damage on a random part of the torso or the /// limbs: not missing, depth Outside, skin covered, not solid, not in the head or neck branch, not /// carrying or below an added part (HediffSet.cs:1225; an injury there gives no pain, Hediff_Injury.cs: /// 132-135). The injury is 4 to 8 points, capped so the part keeps at least half its HP and the pawn's /// injuries, old scars included, stay at nine tenths of the sum that kills it: vanilla kills a pawn whose /// injury severities add up to 150 times its health scale (Pawn_HealthTracker.cs:73, 705-719), and the /// part caps alone add up to more (a human's torso and limbs to about 235). A normal adult goes down at /// about 64 points of bruises, one with halved pain (Biotech's reduced pain gene) at about 128; one that isn't /// down at the total cap gets the "no pain" ending. /// /// The caps hold whatever vanilla multiplies in on the way from the DamageInfo to the injury: the race's /// damage multiplier, rounded to a whole number (Thing.cs:1487-1497), the genes' and hediffs' damage /// factors (Pawn.cs:1919-1927), and IncomingDamageFactor, which applies even with armour ignored /// (DamageWorker_AddInjury.cs:164-167; Tough is 0.5). The amount is divided by all of them; with /// propagation off the injury's severity is exactly what is left (:181-183, 199-221). The part's HP is /// counted unrounded: HediffSet.GetPartHealth rounds to a whole point (HediffSet.cs:581-605), which /// would let a hit take a part with an odd maximum (a foot has 25) half a point below its share. A /// rounding or another mod's damage factor that still takes the hit past a cap is healed back on the /// hit's own bruise (Hediff_Injury.Heal, Hediff_Injury.cs:201-212). /// /// SetAllowDamagePropagation(false) makes AddInjury skip ApplySpecialEffectsToPart, so there is no inner /// bone crack and no stun (DamageWorker_Blunt.cs:18-78): Blunt on a skin-covered, non-solid part is a /// Bruise (HealthUtility.cs:519-531). instigatorGuilty false skips the guilt for harming a player pawn /// (Pawn_HealthTracker.cs:323-329); TakeDamage sets no meleeThreat, so the target never turns on the /// enforcer, and gives the target HarmedMe toward it (:379-382). /// public static class SubdueHits { public const float MinDamage = 4f; public const float MaxDamage = 8f; /// A part keeps at least this share of its HP. public const float KeepHealthShare = 0.5f; /// The pawn's injuries stay at or below this share of the injury sum that kills it. public const float LethalShare = 0.9f; public const float MeleeXpPerHit = 40f; private static readonly List parts = new List(); /// /// Hits once. Returns the pain the new injury carries before pain factors (its PainOffset), or 0 when /// nothing could be hit: every allowed part at its cap, the pawn at the total cap, or a damage factor of 0. /// public static float Hit(Pawn enforcer, Pawn target) { if (enforcer == null || target == null || target.Dead || !target.Spawned) return 0f; BodyPartRecord part = PickPart(target, out float headroom); if (part == null) return 0f; var dinfo = new DamageInfo(DamageDefOf.Blunt, 1f, armorPenetration: 0f, angle: -1f, instigator: enforcer, hitPart: part, weapon: enforcer.def, category: DamageInfo.SourceCategory.ThingOrUnknown, intendedTarget: target, instigatorGuilty: false); dinfo.SetAllowDamagePropagation(false); dinfo.SetIgnoreArmor(true); float factor = DamageFactor(target, dinfo); if (factor <= 0.001f) return 0f; float injury = Mathf.Min(Rand.Range(MinDamage, MaxDamage), headroom); if (injury < 0.5f) return 0f; dinfo.SetAmount(injury / factor); DamageWorker.DamageResult result = target.TakeDamage(dinfo); KeepShare(target, part, result); if (enforcer.Spawned) enforcer.Drawer.Notify_MeleeAttackOn(target); if (target.Spawned) SoundDefOf.Pawn_Melee_Punch_HitPawn.PlayOneShot(new TargetInfo(target.Position, target.Map)); enforcer.skills?.Learn(SkillDefOf.Melee, MeleeXpPerHit); float pain = 0f; if (result?.hediffs != null) { foreach (Hediff h in result.hediffs) pain += h.PainOffset; } return pain; } /// /// What vanilla multiplies a damage amount by before it becomes the injury's severity, armour ignored: /// the race's multiplier for the damage (Thing.cs:1487-1497, which also rounds the amount), the genes' /// factor with Biotech and the hediffs' factor (Pawn.cs:1919-1927), and IncomingDamageFactor for /// external violence (DamageWorker_AddInjury.cs:164-167). /// public static float DamageFactor(Pawn target, DamageInfo dinfo) { float factor = 1f; List multipliers = target.def.damageMultipliers; if (multipliers != null) { for (int i = 0; i < multipliers.Count; i++) { if (multipliers[i].damageDef == dinfo.Def) factor *= multipliers[i].multiplier; } } if (ModsConfig.BiotechActive && target.genes != null) factor *= target.genes.FactorForDamage(dinfo); factor *= target.health.FactorForDamage(dinfo); if (dinfo.Def.ExternalViolenceFor(target)) factor *= target.GetStatValue(StatDefOf.IncomingDamageFactor); return factor; } /// /// After the hit: when the part ended below its share or the pawn past the total cap anyway (the race /// multiplier's rounding, or a damage factor another mod adds), the hit's bruise there heals back the /// difference. The bruise is the new injury, or the one it merged into (HediffSet.cs:325-331; /// Hediff_Injury.cs:214-221). /// private static void KeepShare(Pawn target, BodyPartRecord part, DamageWorker.DamageResult result) { if (target.Dead) return; float deficit = Mathf.Max(Floor(target, part) - PartHealth(target, part), -RoomToLive(target)); if (deficit <= 0f) return; List set = target.health.hediffSet.hediffs; Hediff_Injury bruise = null; HediffDef def = null; if (result?.hediffs != null) { foreach (Hediff h in result.hediffs) { if (h is Hediff_Injury injury && injury.Part == part) { def = injury.def; if (set.Contains(injury)) bruise = injury; } } } for (int i = set.Count - 1; bruise == null && def != null && i >= 0; i--) { if (set[i] is Hediff_Injury merged && merged.Part == part && merged.def == def && !merged.IsPermanent() && !merged.IsTended()) bruise = merged; } bruise?.Heal(Mathf.Min(deficit, bruise.Severity)); } /// /// A part the subdue may hit, weighted by coverage, and how much injury it can still take: its own /// headroom, at most what the pawn has left below the total cap. Null when no part or no total is left. /// public static BodyPartRecord PickPart(Pawn target, out float headroom) { headroom = 0f; HediffSet hs = target?.health?.hediffSet; if (hs == null) return null; float room = RoomToLive(target); if (room < 1f) return null; parts.Clear(); try { foreach (BodyPartRecord part in hs.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Outside)) { if (Allowed(target, part) && Headroom(target, part) >= 1f) parts.Add(part); } if (!parts.TryRandomElementByWeight(p => p.coverageAbs, out BodyPartRecord chosen)) return null; headroom = Mathf.Min(Headroom(target, chosen), room); return chosen; } finally { parts.Clear(); } } /// A part of the torso or the limbs the subdue may ever hit (see the class summary). public static bool Allowed(Pawn target, BodyPartRecord part) { HediffSet hs = target.health.hediffSet; if (part == null || part.depth != BodyPartDepth.Outside || part.coverageAbs <= 0f) return false; if (hs.PartIsMissing(part) || part.def.IsSolid(part, hs.hediffs) || !part.def.IsSkinCovered(part, hs)) return false; if (hs.PartOrAnyAncestorHasDirectlyAddedParts(part)) return false; return !InHeadOrNeck(target, part); } /// The part sits in the head: in the FullHead or UpperHead group, or in the brain's branch below the core part (the neck). public static bool InHeadOrNeck(Pawn target, BodyPartRecord part) { for (BodyPartRecord p = part; p != null; p = p.parent) { if (p.IsInGroup(BodyPartGroupDefOf.FullHead) || p.IsInGroup(BodyPartGroupDefOf.UpperHead)) return true; } BodyPartRecord branch = TopBranch(part); if (branch.parent == null) return false; foreach (BodyPartRecord brain in target.RaceProps.body.GetPartsWithTag(BodyPartTagDefOf.ConsciousnessSource)) { if (TopBranch(brain) == branch) return true; } return false; } /// HP the part may still lose and keep its share: current HP minus half the maximum. public static float Headroom(Pawn target, BodyPartRecord part) => PartHealth(target, part) - Floor(target, part); /// /// Injury the pawn can still take before its injuries, old scars included, reach the total cap: the /// share of the sum vanilla kills at (LethalDamageThreshold, Pawn_HealthTracker.cs:73, 705-719). /// public static float RoomToLive(Pawn target) { float sum = 0f; List list = target.health.hediffSet.hediffs; for (int i = 0; i < list.Count; i++) { if (list[i] is Hediff_Injury injury) sum += injury.Severity; } return target.health.LethalDamageThreshold * LethalShare - sum; } /// The HP the part always keeps: half its maximum (BodyPartDef.cs:138-141, scaled by the pawn's health scale). public static float Floor(Pawn target, BodyPartRecord part) => part.def.GetMaxHealth(target) * KeepHealthShare; /// /// The part's HP as HediffSet.GetPartHealth counts it, its maximum minus the injuries on it, 0 when it /// is missing (HediffSet.cs:581-605), but not rounded to a whole point. /// public static float PartHealth(Pawn target, BodyPartRecord part) { float hp = part.def.GetMaxHealth(target); List list = target.health.hediffSet.hediffs; for (int i = 0; i < list.Count; i++) { Hediff h = list[i]; if (h.Part != part) continue; if (h is Hediff_MissingPart) return 0f; if (h is Hediff_Injury injury) hp = injury.destroysBodyParts ? hp - injury.Severity : Mathf.Max(hp - injury.Severity, 1f); } return Mathf.Max(hp, 0f); } /// The part's ancestor right below the core part (the core part itself for the core). private static BodyPartRecord TopBranch(BodyPartRecord part) { BodyPartRecord p = part; while (p.parent != null && p.parent.parent != null) p = p.parent; return p; } } }