using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using HarmonyLib; using RimWorld; using Verse; namespace BlaxZones { /// /// Package Orbital. A caller-scoped transpiler on TradeShip.GiveSoldThingToPlayer replaces its one /// TradeUtility.SpawnDropPod call with DeliveryRouter.DeliverFromOrbit. DropCellFinder.TradeDropSpot /// is never patched (center-drop raids, ransom and lent colonists use it too). /// [HarmonyPatch(typeof(TradeShip), nameof(TradeShip.GiveSoldThingToPlayer))] public static class Patch_TradeShip_GiveSoldThingToPlayer { public static readonly MethodInfo SpawnDropPod = AccessTools.Method(typeof(TradeUtility), nameof(TradeUtility.SpawnDropPod), new[] { typeof(IntVec3), typeof(Map), typeof(Thing) }); public static readonly MethodInfo DeliverFromOrbit = AccessTools.Method(typeof(DeliveryRouter), nameof(DeliveryRouter.DeliverFromOrbit), new[] { typeof(IntVec3), typeof(Map), typeof(Thing) }); /// Calls of SpawnDropPod the last transpiler run found. The test checks it is exactly 1. public static int LastCallCount = -1; /// /// Exactly one SpawnDropPod call: replace it. Any other count: log an error ("unexpected call /// count") and return the instructions unchanged. /// public static IEnumerable Transpiler(IEnumerable instructions) { List list = instructions.ToList(); try { if (SpawnDropPod == null || DeliverFromOrbit == null) { LastCallCount = -1; Log.Error("[Blax Zones] Orbital routing is off: TradeUtility.SpawnDropPod or DeliveryRouter.DeliverFromOrbit not found. Orbital purchases land at the vanilla drop spot."); return list; } int count = 0; int at = -1; for (int i = 0; i < list.Count; i++) { if (list[i].Calls(SpawnDropPod)) { count++; at = i; } } LastCallCount = count; if (count != 1) { Log.Error("[Blax Zones] Orbital routing is off: unexpected call count " + count + " of TradeUtility.SpawnDropPod in TradeShip.GiveSoldThingToPlayer, expected 1. Orbital purchases land at the vanilla drop spot."); return list; } // Same signature, static: only the target changes. Labels and exception blocks stay on the instruction. list[at].opcode = OpCodes.Call; list[at].operand = DeliverFromOrbit; return list; } catch (Exception e) { Log.Error("[Blax Zones] Orbital routing is off: the TradeShip.GiveSoldThingToPlayer transpiler failed: " + e); return instructions; } } } }