rimworld-blax-castes/Source/BlaxCastes/JoinScopes.cs

62 lines
2.2 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// Where a join happens, as a stack of scopes. A hook pushes a scope in a prefix and pops it in a
/// Harmony finalizer, so an exception inside the scope never leaves the stack dirty. When a pawn's
/// status changes, the innermost scope that covers the pawn names the join reason; without one,
/// the reason is the status fallback, resolved from the final status when the join is applied.
/// Only touched from the main thread.
/// </summary>
public static class JoinScopes
{
/// <summary>Pawn.PreTraded while the player buys. Resolves to bought as slave or bought as colonist.</summary>
public const string Bought = "bought";
private struct Scope
{
public string reason;
public Pawn pawn;
}
private static readonly List<Scope> stack = new List<Scope>();
/// <summary>Open scopes. 0 outside every hooked call.</summary>
public static int Depth => stack.Count;
/// <summary>
/// Opens a scope. With a pawn it covers only that pawn, without one it covers every pawn.
/// Returns the token Pop needs.
/// </summary>
public static int Push(string reason, Pawn pawn = null)
{
stack.Add(new Scope { reason = reason, pawn = pawn });
return stack.Count;
}
/// <summary>
/// Closes the scope the token came from and any scope opened inside it that was not closed.
/// Token 0 (nothing was pushed) does nothing.
/// </summary>
public static void Pop(int token)
{
if (token <= 0 || token > stack.Count)
return;
stack.RemoveRange(token - 1, stack.Count - token + 1);
}
/// <summary>The reason of the innermost scope that covers the pawn, or null.</summary>
public static string ReasonFor(Pawn pawn)
{
for (int i = stack.Count - 1; i >= 0; i--)
{
if (stack[i].pawn == null || stack[i].pawn == pawn)
return stack[i].reason;
}
return null;
}
}
}