rimworld-blax-laws/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs

105 lines
3.8 KiB
C#
Raw Permalink Normal View History

using System;
using HarmonyLib;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The subdue job never enters a save (design: "The subdue job never enters a save"). A saved job with a
/// missing JobDef would break the enforcer after removal: Job.ExposeData saves the def (Job.cs:505), and
/// Pawn_JobTracker.ExposeData (Pawn_JobTracker.cs:90-109, virtual, deep-saves curJob, curDriver and the
/// queue) would then end a job whose def is null.
///
/// Prefix, only while Scribe.mode is Saving and only when the tracker holds a BlaxLaws_Subdue job: hides
/// curJob and curDriver from the scribe and swaps the queue for a copy without subdue entries (a
/// backstop: the JobDef isn't suspendable, so vanilla never queues it). The finalizer puts everything
/// back, also when saving throws. It returns void, so Harmony rethrows with the full stack trace.
/// </summary>
[HarmonyPatch(typeof(Pawn_JobTracker), nameof(Pawn_JobTracker.ExposeData))]
public static class Patch_Pawn_JobTracker_ExposeData
{
public sealed class Hidden
{
public bool hidCurrent;
public Job curJob;
public JobDriver curDriver;
public JobQueue queue;
}
public static void Prefix(Pawn_JobTracker __instance, out Hidden __state)
{
__state = null;
try
{
if (Scribe.mode != LoadSaveMode.Saving || __instance == null)
return;
JobDef ours = BlaxLawsDefOf.BlaxLaws_Subdue;
if (ours == null)
return;
bool current = __instance.curJob?.def == ours;
bool queued = AnyQueued(__instance.jobQueue, ours);
if (!current && !queued)
return;
var hidden = new Hidden();
if (current)
{
hidden.hidCurrent = true;
hidden.curJob = __instance.curJob;
hidden.curDriver = __instance.curDriver;
__instance.curJob = null;
__instance.curDriver = null;
}
if (queued)
{
hidden.queue = __instance.jobQueue;
var filtered = new JobQueue();
foreach (QueuedJob q in hidden.queue)
{
if (q?.job != null && q.job.def != ours)
filtered.EnqueueLast(q.job, q.tag);
}
__instance.jobQueue = filtered;
}
__state = hidden;
}
catch (Exception e)
{
HookGuard.Fail("Hiding the subdue job from the save", e);
}
}
public static void Finalizer(Pawn_JobTracker __instance, Hidden __state)
{
if (__state == null || __instance == null)
return;
try
{
if (__state.hidCurrent)
{
__instance.curJob = __state.curJob;
__instance.curDriver = __state.curDriver;
}
if (__state.queue != null)
__instance.jobQueue = __state.queue;
}
catch (Exception e)
{
HookGuard.Fail("Restoring the subdue job after the save", e);
}
}
private static bool AnyQueued(JobQueue queue, JobDef def)
{
if (queue == null)
return false;
for (int i = 0; i < queue.Count; i++)
{
if (queue[i]?.job?.def == def)
return true;
}
return false;
}
}
}