rimworld-blax-defaults/Source/BlaxDefaults/ForbidHooks.cs

514 lines
19 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxDefaults
{
/// <summary>
/// One downing or death in progress: the pawn, its group read while it was alive, and every thing the game
/// forbade inside the call (allowed before, forbidden after). Never saved.
/// </summary>
public sealed class ForbidScope
{
public readonly Pawn Pawn;
public readonly ForbidGroup Group;
/// <summary>True for Pawn_HealthTracker.MakeDowned, false for Pawn.Kill.</summary>
public readonly bool Downing;
public readonly List<Thing> Recorded = new List<Thing>();
public ForbidScope(Pawn pawn, ForbidGroup group, bool downing)
{
Pawn = pawn;
Group = group;
Downing = downing;
}
}
/// <summary>
/// The forbid rules' hooks. Work package "forbid" (design.md, 1.1 "Gear rules for your colony and for
/// enemies", "Stripping forbids what doesn't match", "Corpses outside the home area stay allowed").
///
/// Scopes: prefixes on Pawn.Kill(DamageInfo?, Hediff) and the private Pawn_HealthTracker.MakeDowned(DamageInfo?,
/// Hediff) push the pawn and its group onto a [ThreadStatic] stack while the game is playing, no map is being
/// made and a rule or corpse switch could act; a finalizer pops it, even on an exception. Recorder: a prefix and
/// a postfix on the CompForbiddable.Forbidden setter add a thing that went from allowed to forbidden to the
/// innermost scope. So a scope holds exactly what the game forbade in that call. Apply, in the postfixes of
/// Kill and MakeDowned: a corpse goes to the corpse switches, any other thing is allowed when its group's rule
/// acts, its cell passes "Where" and the filter allows it: at once when the map has no active threat, else
/// through ForbidWaitList. A downed colonist's remembered weapon always waits (ForbidWaitList keeps it while
/// the colonist still remembers it). Strip: a prefix records what the pawn wears, holds and carries, and the
/// postfix forbids each of those now on a map, inside "Where", that the filter refuses; nothing while
/// butchering's ingredient step (Toils_Recipe.CalculateIngredients) runs. Never patched:
/// ForbidUtility.SetForbidden, which player designators use, and SetForbiddenIfOutsideHomeArea, five lines
/// the JIT may inline.
/// </summary>
public static class ForbidHooks
{
[ThreadStatic] private static List<ForbidScope> stack;
[ThreadStatic] private static int butchering;
/// <summary>True while a downing or death scope is open on this thread.</summary>
public static bool ScopeOpen
{
get
{
List<ForbidScope> s = stack;
return s != null && s.Count > 0;
}
}
/// <summary>True while butchering's ingredient step runs on this thread: stripping stays vanilla then.</summary>
public static bool Butchering => butchering > 0;
/// <summary>A scope opens while the game plays, no map is being made, and a rule or corpse switch could act.</summary>
public static bool ShouldOpen =>
Current.ProgramState == ProgramState.Playing && MapGenerator.mapBeingGenerated == null && ForbidRules.AnyDropRuleOn;
public static ForbidScope Push(Pawn pawn, bool downing)
{
var scope = new ForbidScope(pawn, ForbidRules.GroupOf(pawn), downing);
(stack ??= new List<ForbidScope>()).Add(scope);
return scope;
}
public static void Pop(ForbidScope scope)
{
List<ForbidScope> s = stack;
if (s == null || scope == null)
return;
int i = s.LastIndexOf(scope);
if (i >= 0)
s.RemoveAt(i);
}
/// <summary>The recorder: a thing the game just forbade inside a scope goes to the innermost one.</summary>
public static void Record(Thing t)
{
List<ForbidScope> s = stack;
if (t == null || s == null || s.Count == 0)
return;
List<Thing> recorded = s[s.Count - 1].Recorded;
if (!recorded.Contains(t))
recorded.Add(t);
}
internal static void EnterButchering() => butchering++;
internal static void LeaveButchering()
{
if (butchering > 0)
butchering--;
}
/// <summary>
/// What the postfix of Kill or MakeDowned does with the things its scope recorded. A thing no longer
/// spawned or no longer forbidden is skipped; a corpse goes to the corpse switches; any other thing to its
/// group's rule. A downed colonist's remembered weapon goes on the wait list with its owner.
/// </summary>
public static void Apply(ForbidScope scope)
{
if (scope == null || scope.Recorded.Count == 0)
return;
ForbidRule rule = ForbidRules.For(scope.Group);
Thing remembered = scope.Downing && scope.Group == ForbidGroup.Colony ? scope.Pawn?.mindState?.droppedWeapon : null;
foreach (Thing thing in scope.Recorded.ToList())
{
if (thing == null || thing.Destroyed || !thing.Spawned || !ForbidRules.IsForbiddenFlag(thing))
continue;
if (thing is Corpse corpse)
{
ApplyCorpse(corpse, scope);
continue;
}
if (rule == null || !rule.Active)
continue;
if (thing == remembered)
{
ForbidWaitList.Add(thing, rule, null, scope.Pawn);
continue;
}
if (rule.InsideWhere(thing) && rule.Allows(thing))
AllowOrWait(thing, rule, null);
}
}
private static void ApplyCorpse(Corpse corpse, ForbidScope scope)
{
Map map = corpse.Map;
if (map == null || map.areaManager.Home[corpse.Position])
return;
Pawn inner = corpse.InnerPawn;
CorpseKind kind = inner == scope.Pawn
? ForbidRules.CorpseKindOf(inner, scope.Group)
: ForbidRules.CorpseKindOf(inner, ForbidRules.GroupOfDead(inner));
if (ForbidRules.CorpseSwitch(kind))
AllowOrWait(corpse, null, kind);
}
/// <summary>Allows the thing now when its map has no active threat, else puts it on the wait list.</summary>
private static void AllowOrWait(Thing thing, ForbidRule rule, CorpseKind? corpse)
{
if (GenHostility.AnyHostileActiveThreatToPlayer(thing.Map))
ForbidWaitList.Add(thing, rule, corpse, null);
else
thing.SetForbidden(false, warnOnFail: false);
}
/// <summary>What the strip prefix recorded: the rule of the stripped pawn's group and what it had.</summary>
public sealed class StripRecord
{
public ForbidRule Rule;
public List<Thing> Things;
}
/// <summary>The strip prefix: null when the pawn's group has no strip switch acting.</summary>
public static StripRecord BeforeStrip(Pawn pawn)
{
if (pawn == null || Butchering || Current.ProgramState != ProgramState.Playing || !ForbidRules.On)
return null;
if (!ForbidRules.Colony.StripActive && !ForbidRules.Enemies.StripActive)
return null;
ForbidGroup group = pawn.Dead ? ForbidRules.GroupOfDead(pawn) : ForbidRules.GroupOf(pawn);
ForbidRule rule = ForbidRules.For(group);
if (rule == null || !rule.StripActive)
return null;
var things = new List<Thing>();
if (pawn.equipment != null)
things.AddRange(pawn.equipment.AllEquipmentListForReading);
if (pawn.apparel != null)
things.AddRange(pawn.apparel.WornApparel);
if (pawn.inventory != null)
things.AddRange(pawn.inventory.innerContainer);
return things.Count == 0 ? null : new StripRecord { Rule = rule, Things = things };
}
/// <summary>The strip postfix: forbids each recorded thing now on a map, inside "Where", that the filter refuses.</summary>
public static void AfterStrip(StripRecord record)
{
if (record?.Rule == null || !record.Rule.StripActive)
return;
foreach (Thing t in record.Things)
{
if (t == null || t.Destroyed || !t.Spawned || ForbidRules.IsForbiddenFlag(t))
continue;
if (record.Rule.InsideWhere(t) && !record.Rule.Allows(t))
t.SetForbidden(true, warnOnFail: false);
}
}
}
/// <summary>
/// Things a rule allows wait here while an enemy that can still fight is on their map. Work package "forbid"
/// (design.md, 1.1 "Wait until the fight is over"). An unsaved list of thing, rule (or corpse switch) and, for
/// a remembered weapon, its owner, with the Game it belongs to: a different Current.Game clears it, so a save
/// and reload forgets it and things still waiting stay forbidden, as in vanilla.
///
/// Every 250 ticks, per map with entries (Map.MapPostTick postfix, which returns at once while the list is
/// empty): an entry whose thing is no longer spawned on that map leaves; a remembered weapon stays while
/// owner.mindState.droppedWeapon is still that weapon; if any other entry is left and
/// GenHostility.AnyHostileActiveThreatToPlayer(map) is false, each whose rule still acts, that is still
/// forbidden, inside "Where" and allowed by the current filter is allowed, and all of them leave the list.
/// Changing a waiting thing's flag outside a scope (the player, a mod) takes it off the list.
/// </summary>
public static class ForbidWaitList
{
public const int CheckInterval = 250;
public sealed class Entry
{
public Thing Thing;
/// <summary>The gear rule, or null for a corpse.</summary>
public ForbidRule Rule;
/// <summary>The corpse switch, for a corpse.</summary>
public CorpseKind? Corpse;
/// <summary>The colonist that remembers this weapon, or null.</summary>
public Pawn Owner;
public Map Map;
}
private static readonly List<Entry> entries = new List<Entry>();
private static Game game;
/// <summary>No entries: the tick postfix returns at once.</summary>
public static bool IsEmpty => entries.Count == 0;
public static int Count
{
get
{
CheckGame();
return entries.Count;
}
}
/// <summary>True while the thing waits.</summary>
public static bool Contains(Thing t)
{
CheckGame();
return t != null && entries.Any(e => e.Thing == t);
}
/// <summary>The waiting entry of the thing, or null.</summary>
public static Entry EntryOf(Thing t)
{
CheckGame();
return t == null ? null : entries.FirstOrDefault(e => e.Thing == t);
}
public static void Add(Thing thing, ForbidRule rule, CorpseKind? corpse, Pawn owner)
{
if (thing == null || thing.Map == null)
return;
CheckGame();
game = Current.Game;
entries.RemoveAll(e => e.Thing == thing);
entries.Add(new Entry { Thing = thing, Rule = rule, Corpse = corpse, Owner = owner, Map = thing.Map });
}
public static void Remove(Thing thing)
{
if (thing == null || entries.Count == 0)
return;
entries.RemoveAll(e => e.Thing == thing);
}
/// <summary>Empties the list. Tests only (and a game change).</summary>
public static void Clear()
{
entries.Clear();
game = null;
}
private static void CheckGame()
{
if (entries.Count > 0 && game != Current.Game)
Clear();
}
/// <summary>The tick postfix: every CheckInterval ticks, the check for this map.</summary>
public static void MapTick(Map map)
{
if (entries.Count == 0 || map == null)
return;
CheckGame();
if (entries.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0)
return;
Check(map);
}
/// <summary>The check for one map, as described above.</summary>
public static void Check(Map map)
{
CheckGame();
List<Map> maps = Find.Maps;
entries.RemoveAll(e => e.Map == null || !maps.Contains(e.Map));
var ready = new List<Entry>();
foreach (Entry e in entries.Where(x => x.Map == map).ToList())
{
if (e.Thing == null || e.Thing.Destroyed || !e.Thing.Spawned || e.Thing.Map != map)
{
entries.Remove(e);
continue;
}
if (e.Owner != null && e.Owner.mindState != null && e.Owner.mindState.droppedWeapon == e.Thing)
continue;
ready.Add(e);
}
if (ready.Count == 0 || GenHostility.AnyHostileActiveThreatToPlayer(map))
return;
foreach (Entry e in ready)
{
entries.Remove(e);
if (ShouldAllow(e))
e.Thing.SetForbidden(false, warnOnFail: false);
}
}
private static bool ShouldAllow(Entry e)
{
if (!ForbidRules.IsForbiddenFlag(e.Thing))
return false;
if (e.Corpse.HasValue)
return ForbidRules.CorpseSwitch(e.Corpse.Value);
ForbidRule rule = e.Rule;
return rule != null && rule.Active && rule.InsideWhere(e.Thing) && rule.Allows(e.Thing);
}
}
// ---- patches ---------------------------------------------------------------------
[HarmonyPatch(typeof(Pawn), nameof(Pawn.Kill), new[] { typeof(DamageInfo?), typeof(Hediff) })]
public static class Patch_Pawn_Kill
{
public static void Prefix(Pawn __instance, out ForbidScope __state)
{
__state = null;
try
{
if (ForbidHooks.ShouldOpen)
__state = ForbidHooks.Push(__instance, downing: false);
}
catch (Exception e)
{
HookGuard.Report("Pawn.Kill prefix", e);
}
}
public static void Postfix(ForbidScope __state)
{
if (__state == null)
return;
try
{
ForbidHooks.Apply(__state);
}
catch (Exception e)
{
HookGuard.Report("Pawn.Kill", e);
}
}
public static void Finalizer(ForbidScope __state)
{
if (__state != null)
ForbidHooks.Pop(__state);
}
}
[HarmonyPatch(typeof(Pawn_HealthTracker), "MakeDowned", new[] { typeof(DamageInfo?), typeof(Hediff) })]
public static class Patch_Pawn_HealthTracker_MakeDowned
{
public static void Prefix(Pawn ___pawn, out ForbidScope __state)
{
__state = null;
try
{
if (ForbidHooks.ShouldOpen)
__state = ForbidHooks.Push(___pawn, downing: true);
}
catch (Exception e)
{
HookGuard.Report("Pawn_HealthTracker.MakeDowned prefix", e);
}
}
public static void Postfix(ForbidScope __state)
{
if (__state == null)
return;
try
{
ForbidHooks.Apply(__state);
}
catch (Exception e)
{
HookGuard.Report("Pawn_HealthTracker.MakeDowned", e);
}
}
public static void Finalizer(ForbidScope __state)
{
if (__state != null)
ForbidHooks.Pop(__state);
}
}
/// <summary>The recorder. It never changes a flag: it only reads the old value and notes the change.</summary>
[HarmonyPatch(typeof(CompForbiddable), nameof(CompForbiddable.Forbidden), MethodType.Setter)]
public static class Patch_CompForbiddable_Forbidden
{
public static void Prefix(CompForbiddable __instance, out bool __state)
{
__state = false;
if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty)
return;
__state = __instance.Forbidden;
}
public static void Postfix(CompForbiddable __instance, bool __state)
{
if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty)
return;
try
{
bool now = __instance.Forbidden;
if (ForbidHooks.ScopeOpen)
{
if (!__state && now)
ForbidHooks.Record(__instance.parent);
}
else if (__state != now)
{
ForbidWaitList.Remove(__instance.parent);
}
}
catch (Exception e)
{
HookGuard.Report("CompForbiddable.Forbidden", e);
}
}
}
[HarmonyPatch(typeof(Pawn), nameof(Pawn.Strip))]
public static class Patch_Pawn_Strip
{
public static void Prefix(Pawn __instance, out ForbidHooks.StripRecord __state)
{
__state = null;
try
{
__state = ForbidHooks.BeforeStrip(__instance);
}
catch (Exception e)
{
HookGuard.Report("Pawn.Strip prefix", e);
}
}
public static void Postfix(ForbidHooks.StripRecord __state)
{
if (__state == null)
return;
try
{
ForbidHooks.AfterStrip(__state);
}
catch (Exception e)
{
HookGuard.Report("Pawn.Strip", e);
}
}
}
/// <summary>Butchering's ingredient step strips corpses (autoStripCorpses); the strip switch leaves that vanilla.</summary>
[HarmonyPatch(typeof(Toils_Recipe), "CalculateIngredients")]
public static class Patch_Toils_Recipe_CalculateIngredients
{
public static void Prefix() => ForbidHooks.EnterButchering();
public static void Finalizer() => ForbidHooks.LeaveButchering();
}
[HarmonyPatch(typeof(Map), nameof(Map.MapPostTick))]
public static class Patch_Map_MapPostTick
{
public static void Postfix(Map __instance)
{
if (ForbidWaitList.IsEmpty)
return;
try
{
ForbidWaitList.MapTick(__instance);
}
catch (Exception e)
{
HookGuard.Report("Map.MapPostTick", e);
}
}
}
}