rimworld-blax-laws/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs

102 lines
4.1 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook U: a pawn uses an item (category Used). Prefix, postfix and finalizer on CompUsable.UsedBy
/// (RimWorld/CompUsable.cs:161) and on every subclass that overrides it, found by reflection at startup
/// (in the game code only CompUseableDatacore, which calls base, RimWorld/CompUseableDatacore.cs:28-32). A
/// depth count makes an override that calls base file once. UsedBy returns with no effect when
/// CanBeUsedBy(p, false, true) refuses (:163-166), so the prefix asks the same question and files only
/// when it was accepted and the item is a target of the pawn's own job: JobDriver_UseItem uses its target
/// A (RimWorld/JobDriver_UseItem.cs:95-96) and IngestionOutcomeDoer_UseThing the ingested thing
/// (RimWorld/IngestionOutcomeDoer_UseThing.cs:10). A patient a doctor gives a healer mech serum
/// (RimWorld/Recipe_AdministerUsableItem.cs:15) lies in bed on its own job and files nothing.
/// </summary>
[HarmonyPatch]
public static class Patch_CompUsable_UsedBy
{
public const string Where = "hook U, CompUsable.UsedBy";
// __state: 0 the call isn't counted, 1 counted, 2 counted and files.
[ThreadStatic]
private static int depth;
public static IEnumerable<MethodBase> TargetMethods()
{
MethodInfo baseMethod = AccessTools.DeclaredMethod(typeof(CompUsable), nameof(CompUsable.UsedBy), new[] { typeof(Pawn) });
if (baseMethod != null)
yield return baseMethod;
foreach (Type t in typeof(CompUsable).AllSubclasses())
{
if (t.ContainsGenericParameters)
continue;
MethodInfo m = AccessTools.DeclaredMethod(t, nameof(CompUsable.UsedBy), new[] { typeof(Pawn) });
if (m != null && !m.IsAbstract && m.GetMethodBody() != null)
yield return m;
}
}
// The user is bound by position (__0): a modded override may name its parameter otherwise.
public static void Prefix(CompUsable __instance, Pawn __0, out int __state)
{
__state = 0;
if (!Watch.Used)
return;
depth++;
__state = 1;
if (depth == 1 && Files(__instance, __0))
__state = 2;
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Files(CompUsable __instance, Pawn p)
{
try
{
ThingWithComps item = __instance?.parent;
if (p == null || item?.def == null || !Watch.MayMatch(ActCategories.Used, item.def))
return false;
if (!Offenders.IsCovered(p) || !DetectionHooks.OnOwnJob(p, item))
return false;
return __instance.CanBeUsedBy(p, forced: false, ignoreReserveAndReachable: true).Accepted;
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
return false;
}
}
public static void Postfix(CompUsable __instance, Pawn __0, int __state)
{
if (__state != 2)
return;
try
{
ThingWithComps item = __instance.parent;
CaseFiler.Report(new ActEvent(ActCategories.Used, item.def, __0) { thing = item });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
/// <summary>Balances the depth count even when UsedBy throws. Returns void, so other mods' stack traces stay whole.</summary>
public static void Finalizer(int __state)
{
if (__state != 0 && depth > 0)
depth--;
}
}
}