using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using HarmonyLib; using Verse; namespace BlaxCastes { /// /// The weapon loadout slot's link to [1001] Weapons Tab Reborn (packageId papercrane1001.WeaponsTab). /// Bound by reflection to the static API it publishes for Better Pawn Control, in /// WeaponsTabReborn.LoadoutDictionary (read from its 1.6 assembly, which 1.7 loads): /// - int BPC_GetLoadoutId(Pawn): the pawn's loadout id; a pawn without one gets the default loadout. /// - void BPC_SetLoadoutId(Pawn, int): an id that does not exist clears the pawn's loadout, so Castes /// checks the id first. /// - int BPC_GetDefaultLoadoutId(): the first loadout. /// - string BPC_GetLoadoutNamebyId(int): throws InvalidOperationException for an id that does not exist. /// - Dictionary<string, int> BPC_GetWeaponsLoadoutsDatabase(): label to id. It only ever grows /// (deleted and renamed loadouts stay in it, and a new loadout whose label is already a key is left /// out), so every id in it is checked by name, and the ids just above the highest one are probed. /// Loadout ids are the highest id plus one, so an id freed by deleting the newest loadout can come back. /// A missing type or method turns the slot off for the session; a call that throws anything else turns /// it off for the rest of the game. Either logs one warning and never throws. /// The loadout database is null after loading a save that has none (the mod added mid-save, or saved /// without it), until the mod's own tab or job giver creates it through GetCurrentLoadoutDatabase(). The /// BPC methods read the field directly and would throw, so every call goes through that public method /// first, which creates the database the same way the mod does. /// public static class WeaponsTab { public const string ApiTypeName = "WeaponsTabReborn.LoadoutDictionary"; /// How many ids above the highest known one Loadouts() checks. private const int ProbeAhead = 16; private static bool? modActive; private static bool bound; private static bool bindFailed; private static bool callFailed; private static Func getLoadoutId; private static Action setLoadoutId; private static Func getDefaultLoadoutId; private static Func getLoadoutName; private static Func> getDatabase; /// LoadoutDictionary.GetCurrentLoadoutDatabase(): returns the database, creating it if it is null. Optional. private static Func ensureDatabase; /// Weapons Tab Reborn is in the active mod list. The manager hides the loadout row without it. public static bool ModActive => modActive ??= Compat.IsActive(Compat.WeaponsTab); /// The mod is active and its API is bound and has not failed in this game. public static bool Available => ModActive && Bind() && !callFailed; public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWeaponLoadout; /// The slot is written: the API works and the manageWeaponLoadout setting is on. public static bool Active => SettingOn && Available; /// Called when a game starts or loads, so a call that failed in an earlier game is tried again. internal static void ResetForGame() => callFailed = false; // ---- binding ----------------------------------------------------------------------------- private static bool Bind() { if (bound) return !bindFailed; bound = true; try { Type api = AccessTools.TypeByName(ApiTypeName); if (api == null) return BindFailed("type " + ApiTypeName + " not found"); getLoadoutId = Make>(api, "BPC_GetLoadoutId", typeof(int), typeof(Pawn)); setLoadoutId = Make>(api, "BPC_SetLoadoutId", typeof(void), typeof(Pawn), typeof(int)); getDefaultLoadoutId = Make>(api, "BPC_GetDefaultLoadoutId", typeof(int)); getLoadoutName = Make>(api, "BPC_GetLoadoutNamebyId", typeof(string), typeof(int)); getDatabase = Make>>(api, "BPC_GetWeaponsLoadoutsDatabase", typeof(Dictionary)); MethodInfo ensure = api.GetMethod("GetCurrentLoadoutDatabase", BindingFlags.Public | BindingFlags.Static, null, Type.EmptyTypes, null); if (ensure != null && !ensure.ReturnType.IsValueType && ensure.ReturnType != typeof(void)) ensureDatabase = (Func)Delegate.CreateDelegate(typeof(Func), ensure, throwOnBindFailure: false); var missing = new List(); if (getLoadoutId == null) missing.Add("BPC_GetLoadoutId"); if (setLoadoutId == null) missing.Add("BPC_SetLoadoutId"); if (getDefaultLoadoutId == null) missing.Add("BPC_GetDefaultLoadoutId"); if (getLoadoutName == null) missing.Add("BPC_GetLoadoutNamebyId"); if (getDatabase == null) missing.Add("BPC_GetWeaponsLoadoutsDatabase"); return missing.Count == 0 || BindFailed(string.Join(", ", missing) + " not found"); } catch (Exception e) { return BindFailed(e.GetType().Name + ": " + e.Message); } } private static TDelegate Make(Type api, string name, Type returnType, params Type[] parameters) where TDelegate : Delegate { MethodInfo method = api.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameters, null); if (method == null || method.ReturnType != returnType) return null; return (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), method, throwOnBindFailure: false); } private static bool BindFailed(string why) { bindFailed = true; Log.Warning("[Blax Castes] Weapons Tab Reborn is active, but its loadout API could not be used (" + why + "). The weapon loadout slot is off."); return false; } private static void CallFailed(string call, Exception e) { if (callFailed) return; callFailed = true; Log.Warning("[Blax Castes] Weapons Tab Reborn's " + call + " failed (" + e.GetType().Name + ": " + e.Message + "). The weapon loadout slot is off until the next game is loaded."); } // ---- calls ------------------------------------------------------------------------------- /// Creates Weapons Tab Reborn's loadout database if it is null, the way the mod itself does. Call inside the try. private static void EnsureDatabase() => ensureDatabase?.Invoke(); /// The pawn's loadout id, or null when the API is not available. public static int? LoadoutOf(Pawn pawn) { if (pawn == null || !Available) return null; try { EnsureDatabase(); return getLoadoutId(pawn); } catch (Exception e) { CallFailed("BPC_GetLoadoutId", e); return null; } } /// Sets the pawn's loadout. False when the API is not available or the id does not exist. public static bool SetLoadout(Pawn pawn, int id) { if (pawn == null || !Exists(id)) return false; try { EnsureDatabase(); setLoadoutId(pawn, id); return true; } catch (Exception e) { CallFailed("BPC_SetLoadoutId", e); return false; } } /// The default loadout's id (what a pawn without one uses), or null. public static int? DefaultLoadoutId() { if (!Available) return null; try { EnsureDatabase(); return getDefaultLoadoutId(); } catch (Exception e) { CallFailed("BPC_GetDefaultLoadoutId", e); return null; } } /// The loadout's label, or null when it does not exist or the API is not available. public static string NameOf(int id) { if (id < 0 || !Available) return null; try { EnsureDatabase(); return getLoadoutName(id); } catch (InvalidOperationException) { // Enumerable.First found no loadout with that id: it was deleted. return null; } catch (Exception e) { CallFailed("BPC_GetLoadoutNamebyId", e); return null; } } public static bool Exists(int id) => NameOf(id) != null; /// The loadouts that exist now, as (id, label), by id. public static List> Loadouts() { var result = new List>(); if (!Available) return result; Dictionary database; try { EnsureDatabase(); database = getDatabase(); } catch (Exception e) { CallFailed("BPC_GetWeaponsLoadoutsDatabase", e); return result; } if (database == null) return result; // A loadout whose label an older entry already holds never gets into the database dictionary. // New loadouts get the highest id plus one, so the ids just above the known ones are probed too. int highest = database.Count == 0 ? 0 : database.Values.Max(); IEnumerable ids = database.Values.Concat(Enumerable.Range(0, Math.Max(0, highest) + ProbeAhead + 1)); foreach (int id in ids.Where(i => i >= 0).Distinct().OrderBy(i => i)) { string name = NameOf(id); if (name != null) result.Add(new KeyValuePair(id, name)); } return result; } } }