using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; namespace BlaxCastes { /// /// Every change to castes, memberships, join rows and the default caste goes through here, so the /// rules (member sync, delete fallbacks, the enabled switch) hold no matter which window or hook /// made the change. Methods do nothing and return false or null when no game is loaded. /// public static class CasteManager { private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance; private static int Now => Find.TickManager?.TicksGame ?? 0; // ---- castes ------------------------------------------------------------------------ /// A new caste with the next free id, labelled "Caste N", managing nothing. public static Caste CreateCaste(string label = null) { GameComponent_BlaxCastes comp = Comp; if (comp == null) return null; int id = comp.TakeNextId(); var caste = new Caste(id, label.NullOrEmpty() ? (string)"BlaxCastes_NewCasteLabel".Translate(id) : label); comp.AddCaste(caste); return caste; } /// A new caste with every slot copied from the source, the vanilla duplicate way. public static Caste DuplicateCaste(Caste source) { GameComponent_BlaxCastes comp = Comp; if (comp == null || source == null) return null; Caste copy = CreateCaste(); copy.CopyFrom(source); return copy; } /// /// Removes the caste. Its members become casteless and keep their current policies, join rows /// that point at it fall back to No caste, it stops being the default, and former-caste records /// that point at it are dropped. /// public static bool DeleteCaste(Caste caste) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste)) return false; comp.RemoveFormerCastesOf(caste.id); foreach (Pawn member in comp.MembersOf(caste)) { if (CasteUtility.CanBeMember(member)) comp.SetMembership(member, new CasteMembership(null, false, JoinReason.CasteDeleted, Now)); else comp.RemoveMembership(member); } foreach (JoinRow row in comp.JoinRows) { if (row.mode == JoinRowMode.SpecificCaste && row.caste == caste) comp.SetRowRaw(row.reason, JoinRowMode.NoCaste, null); } if (comp.DefaultCaste == caste) comp.SetDefaultRaw(null); comp.RemoveCaste(caste); return true; } /// Sets the caste that "Default caste" rows use. Null clears it, so those rows act as No caste. public static bool SetDefault(Caste caste) { GameComponent_BlaxCastes comp = Comp; if (comp == null || (caste != null && !comp.HasCaste(caste))) return false; comp.SetDefaultRaw(caste); return true; } /// /// Changes one slot. Members still on the old value get the new one; members on another value /// keep it (the Follow rule). A slot that was unmanaged had no old value, so every member gets /// the new one. Unmanaging a slot changes no pawn. The schedule compares the whole day; work /// priorities go type by type (see SetWorkPriority). Returns how many members were moved. /// public static int SetSlot(Caste caste, CasteSlot slot, object newValue) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste)) return 0; if (!CasteUtility.FitsSlot(slot, newValue)) { Log.Warning("[Blax Castes] " + newValue.GetType().Name + " does not fit the " + slot + " slot of " + caste.label + "."); return 0; } newValue = CasteUtility.NormalizeSlotValue(slot, newValue); if (CasteUtility.IsPolicySlot(slot) && slot != CasteSlot.MedCare && newValue != null && !CasteUtility.PolicyExists((Policy)newValue)) { Log.Warning("[Blax Castes] Policy " + ((Policy)newValue).label + " is not in the game's database; " + caste.label + " keeps its " + slot + " slot."); return 0; } if (slot == CasteSlot.Loadout && newValue is int id && id >= 0 && !WeaponsTab.Exists(id)) { Log.Warning("[Blax Castes] Weapon loadout " + id + " is not one of Weapons Tab Reborn's loadouts; " + caste.label + " keeps its loadout slot."); return 0; } object oldValue = caste.GetSlot(slot); bool wasManaged = caste.IsManaged(slot); if (CasteUtility.SameValue(oldValue, newValue)) return 0; caste.SetSlotRaw(slot, newValue); if (!caste.IsManaged(slot) || !BlaxCastesMod.Enabled) return 0; if (slot == CasteSlot.Work) return SyncWork(comp, caste, oldValue as IReadOnlyDictionary); int moved = 0; foreach (Pawn member in comp.MembersOf(caste)) { if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, slot)) continue; if (wasManaged && !CasteUtility.Matches(member, slot, oldValue)) continue; if (CasteUtility.WriteSlot(member, slot, newValue)) moved++; } return moved; } /// /// The Follow rule per work type: for each type whose priority changed, members whose priority equals /// the old one get the new one; a type that was not listed before reaches every member. A type that /// is no longer listed moves nobody. /// private static int SyncWork(GameComponent_BlaxCastes comp, Caste caste, IReadOnlyDictionary oldValues) { int moved = 0; foreach (Pawn member in comp.MembersOf(caste)) { if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work)) continue; bool wrote = false; foreach (KeyValuePair kv in caste.WorkPriorities) { if (oldValues != null && oldValues.TryGetValue(kv.Key, out int old)) { if (old == kv.Value || !WorkSlot.Matches(member, kv.Key, old)) continue; } if (WorkSlot.WriteType(member, kv.Key, kv.Value)) wrote = true; } if (wrote) moved++; } return moved; } /// /// Sets one work type's priority (0 to 4), or leaves it alone with null. Members follow per type. /// Returns how many members were moved. /// public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority) { if (caste == null || workTypeDefName.NullOrEmpty()) return 0; var values = new Dictionary(caste.WorkPriorities); if (priority == null) values.Remove(workTypeDefName); else values[workTypeDefName] = priority.Value; return SetSlot(caste, CasteSlot.Work, values); } /// /// The members that follow one work type of the caste right now: those whose priority equals the /// caste's value, or every member while the caste leaves the type alone (the next value reaches them /// all). The manager's cycle button takes them before its first click on a type, so the clicks after /// it move only them, never a pawn that happens to sit on a value the cycle passes through. /// public static List WorkFollowers(Caste caste, string workTypeDefName) { var result = new List(); GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty()) return result; int? value = caste.WorkPriorityOf(workTypeDefName); foreach (Pawn member in comp.MembersOf(caste)) { if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work)) continue; if (value == null || WorkSlot.Matches(member, workTypeDefName, value.Value)) result.Add(member); } return result; } /// /// Sets one work type's priority (0 to 4, or null to leave it alone) and writes it to the given /// members only, those WorkFollowers listed before a run of edits to this type. Members that left the /// caste since are skipped. Returns how many members were moved. /// public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority, IEnumerable followers) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty()) return 0; if (priority != null && (priority.Value < WorkSlot.Off || priority.Value > WorkSlot.Lowest)) return 0; var values = new Dictionary(caste.WorkPriorities); if (priority == null) values.Remove(workTypeDefName); else values[workTypeDefName] = priority.Value; caste.SetSlotRaw(CasteSlot.Work, WorkSlot.Normalize(values)); if (priority == null || followers == null || !BlaxCastesMod.Enabled) return 0; int moved = 0; foreach (Pawn member in followers) { if (GameComponent_BlaxCastes.IsGone(member) || comp.CasteOf(member) != caste || !CasteUtility.CanUse(member, CasteSlot.Work)) continue; if (WorkSlot.WriteType(member, workTypeDefName, priority.Value)) moved++; } return moved; } /// /// "Start from nothing": applying the caste turns every work type off before writing its listed ones. /// Moves no member now; it takes effect on the next assign, Reset to caste or Apply to all members. /// public static bool SetWorkStartFromNothing(Caste caste, bool value) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste)) return false; caste.SetWorkStartFromNothingRaw(value); return true; } // ---- memberships ------------------------------------------------------------------- /// /// Puts the pawn into the caste and writes every managed slot it can take. auto: a join row did /// it, not the player. A null caste makes the pawn casteless. False if the pawn can't be a member /// (not humanlike, gone, or not player faction or player prisoner) or the caste isn't in this game. /// public static bool Assign(Pawn pawn, Caste caste, bool auto, string reason) { if (caste == null) return MakeCasteless(pawn, auto, reason); GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste) || !CasteUtility.CanBeMember(pawn)) return false; comp.SetMembership(pawn, new CasteMembership(caste, auto, reason ?? JoinReason.Manual, Now)); CasteUtility.Apply(pawn, caste); return true; } /// Casteless by choice: the pawn leaves its caste and keeps its current policies. public static bool MakeCasteless(Pawn pawn, bool auto = false, string reason = JoinReason.Manual) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !CasteUtility.CanBeMember(pawn)) return false; comp.SetMembership(pawn, new CasteMembership(null, auto, reason ?? JoinReason.Manual, Now)); return true; } /// Re-writes every managed slot of the pawn's caste, clearing its overrides. public static bool ResetToCaste(Pawn pawn) { GameComponent_BlaxCastes comp = Comp; Caste caste = comp?.CasteOf(pawn); if (caste == null || !CasteUtility.CanBeMember(pawn)) return false; CasteUtility.Apply(pawn, caste); return true; } /// Removes the pawn's record, as if it never had a caste. Its policies stay as they are. public static bool EndMembership(Pawn pawn) { GameComponent_BlaxCastes comp = Comp; return comp != null && comp.RemoveMembership(pawn); } /// The caste's members that are alive and player-side (the manager's member count). public static List LiveMembers(Caste caste) { var result = new List(); GameComponent_BlaxCastes comp = Comp; if (comp == null || caste == null) return result; foreach (Pawn p in comp.MembersOf(caste)) { if (!p.Dead && CasteUtility.CanBeMember(p)) result.Add(p); } return result; } /// /// "Apply to all members": writes every managed slot of the caste to every live member, clearing /// their hand changes. Returns how many members it wrote to. /// public static int ApplyToAll(Caste caste) { GameComponent_BlaxCastes comp = Comp; if (comp == null || !comp.HasCaste(caste) || !BlaxCastesMod.Enabled) return 0; int count = 0; foreach (Pawn p in LiveMembers(caste)) { if (CasteUtility.Apply(p, caste).Count > 0) count++; } return count; } /// /// The pawns "Assign by status" would place: player colonists, slaves and prisoners that can join a /// caste, have no membership record (casteless-by-choice pawns have one), are not waiting for a join, /// and whose status row resolves to a caste. /// public static List PawnsToAssignByStatus() { var result = new List(); GameComponent_BlaxCastes comp = Comp; if (comp == null || Current.Game == null) return result; var seen = new HashSet(); foreach (Pawn p in PlayerSidePawns()) { if (!seen.Add(p) || p.Dead || comp.MembershipOf(p) != null || JoinDefaults.IsQueued(p)) continue; if (!JoinDefaults.Eligible(p) || !CasteUtility.CanBeMember(p)) continue; string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p); if (row != null && comp.ResolveRow(row) != null) result.Add(p); } return result; } private static IEnumerable PlayerSidePawns() { foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction.ToArray()) yield return p; foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_PrisonersOfColony.ToArray()) yield return p; } /// /// "Assign pawns without a caste by status": puts each pawn of PawnsToAssignByStatus into the caste /// of its new colonist, new slave or new prisoner row. Returns how many were assigned; assigned, when /// given, gets each of them. /// public static int AssignByStatus(ICollection assigned = null) { GameComponent_BlaxCastes comp = Comp; if (comp == null) return 0; int count = 0; foreach (Pawn p in PawnsToAssignByStatus()) { string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p); Caste caste = row == null ? null : comp.ResolveRow(row); if (caste != null && Assign(p, caste, true, row)) { count++; assigned?.Add(p); } } return count; } /// /// The managed slots of the pawn's caste where the pawn has another value (a hand change or a /// vanilla reset). Slots the pawn can't take are never overrides. /// public static List Overrides(Pawn pawn) { var result = new List(); Caste caste = Comp?.CasteOf(pawn); if (caste == null) return result; foreach (CasteSlot slot in CasteUtility.AllSlots) { if (!caste.IsManaged(slot) || !CasteUtility.CanUse(pawn, slot)) continue; if (!CasteUtility.Matches(pawn, slot, caste.GetSlot(slot))) result.Add(slot); } return result; } /// The work types of the pawn's caste where the pawn's priority differs, in the Work tab's order. public static List WorkOverrides(Pawn pawn) { Caste caste = Comp?.CasteOf(pawn); if (caste == null || !caste.IsManaged(CasteSlot.Work) || !CasteUtility.CanUse(pawn, CasteSlot.Work)) return new List(); return WorkSlot.Differences(pawn, caste.WorkPriorities); } // ---- join rows --------------------------------------------------------------------- /// Sets what a join row does. SpecificCaste needs a caste of this game. public static bool SetJoinRow(string reason, JoinRowMode mode, Caste caste = null) { GameComponent_BlaxCastes comp = Comp; if (comp == null || reason.NullOrEmpty()) return false; if (mode == JoinRowMode.SpecificCaste && !comp.HasCaste(caste)) return false; comp.SetRowRaw(reason, mode, caste); return true; } // ---- save safety ------------------------------------------------------------------- /// /// Checks every caste's slots after a load, before a save and while the manager is open: a policy /// that left its database or a loadout Weapons Tab Reborn no longer has becomes unmanaged, a schedule /// hour with an unknown time assignment becomes Anything, and a work type that no longer exists is /// dropped. One warning per caste and problem. /// internal static void CheckSlots(GameComponent_BlaxCastes comp) { if (comp == null) return; foreach (Caste caste in comp.Castes) { UnmanageMissingPolicies(caste); FixScheduleAndWork(caste); } } /// /// Unmanages the caste's slots whose policy is no longer in its database, and its loadout when Weapons /// Tab Reborn is active and no longer has it (without the mod the id is kept). The loadout is checked /// first and the mod's availability after: a call that fails inside the check turns the slot off, and /// must not count as a deleted loadout. Returns how many. /// internal static int UnmanageMissingPolicies(Caste caste) { if (caste == null || Current.Game == null) return 0; List missing = null; foreach (CasteSlot slot in CasteUtility.PolicySlots) { if (slot == CasteSlot.MedCare || !(caste.GetSlot(slot) is Policy policy)) continue; if (CasteUtility.PolicyExists(policy)) continue; (missing ??= new List()).Add(slot + " (" + policy.label + ")"); caste.SetSlotRaw(slot, null); } if (caste.IsManaged(CasteSlot.Loadout) && !WeaponsTab.Exists(caste.LoadoutId) && WeaponsTab.Available) { (missing ??= new List()).Add("weapon loadout (id " + caste.LoadoutId + ")"); caste.SetSlotRaw(CasteSlot.Loadout, Caste.Unmanaged); } if (missing == null) return 0; Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": " + string.Join(", ", missing) + " no longer in the game. The slot is now unmanaged."); return missing.Count; } /// /// Schedule hours whose time assignment no longer exists (a removed mod, Meditate without Royalty) /// become Anything, and work types that no longer exist are dropped, each with one warning. /// internal static void FixScheduleAndWork(Caste caste) { if (caste == null) return; IReadOnlyList schedule = caste.Schedule; if (schedule != null && schedule.Any(n => !ScheduleSlot.IsKnown(n))) { List unknown = schedule.Where(n => !ScheduleSlot.IsKnown(n)).Distinct().ToList(); caste.SetSlotRaw(CasteSlot.Schedule, schedule.ToList()); // Normalize turns unknown names into Anything Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": time assignment " + string.Join(", ", unknown) + " no longer in the game. Those schedule hours are now Anything."); } if (caste.WorkPriorities.Keys.Any(k => WorkSlot.Resolve(k) == null)) { List gone = caste.WorkPriorities.Keys.Where(k => WorkSlot.Resolve(k) == null).ToList(); var kept = caste.WorkPriorities.Where(kv => !gone.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value); caste.SetSlotRaw(CasteSlot.Work, kept); Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": work type " + string.Join(", ", gone) + " no longer in the game. The caste leaves it alone now."); } } } }