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

492 lines
25 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// Reads and writes a pawn's slots through the vanilla setters (and Weapons Tab Reborn's API for the
/// loadout), with the checks that decide which slots a pawn can take. CasteManager decides when to
/// write; nothing else should call Apply.
/// </summary>
public static class CasteUtility
{
/// <summary>Every slot, in the order Apply writes them.</summary>
public static readonly CasteSlot[] AllSlots =
{
CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug, CasteSlot.Reading, CasteSlot.MedCare,
CasteSlot.Schedule, CasteSlot.Work, CasteSlot.Loadout,
};
/// <summary>The policy and medical care slots: the ones a No caste row resets and the manager draws as plain rows.</summary>
public static readonly CasteSlot[] PolicySlots = { CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug, CasteSlot.Reading, CasteSlot.MedCare };
public static bool IsPolicySlot(CasteSlot slot) => slot <= CasteSlot.MedCare;
/// <summary>Player faction (colonists, slaves, dead colonists) or a prisoner of the player.</summary>
public static bool IsPlayerSide(Pawn pawn)
{
if (pawn == null)
return false;
return pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony;
}
/// <summary>Humanlike, still around, and player-side.</summary>
public static bool CanBeMember(Pawn pawn) =>
pawn != null && !GameComponent_BlaxCastes.IsGone(pawn) && pawn.RaceProps != null && pawn.RaceProps.Humanlike && IsPlayerSide(pawn);
/// <summary>The pawn's mutant def (Anomaly), or null for a normal pawn and for a mutant whose def is gone.</summary>
private static MutantDef MutantDefFor(Pawn pawn) => pawn.IsMutant ? pawn.mutant.Def : null;
/// <summary>
/// A mutant whose def is gone: a save made with Anomaly, loaded without it. The game's own policy, food
/// and work getters read mutant.Def and throw for such a pawn, so Castes leaves it alone: it takes no
/// slot (CanUse) and joins no caste (JoinDefaults.Eligible).
/// </summary>
internal static bool IsMutantWithoutDef(Pawn pawn) => pawn != null && pawn.IsMutant && pawn.mutant.Def == null;
/// <summary>A mutant that takes no policies (Anomaly ghouls and the like).</summary>
internal static bool PoliciesDisabled(Pawn pawn) => MutantDefFor(pawn)?.disablePolicies == true;
/// <summary>A mutant the vanilla Schedule tab leaves out. Pawn.IsSubhuman throws for a mutant whose def is gone.</summary>
private static bool IsSubhumanMutant(Pawn pawn) => MutantDefFor(pawn)?.consideredSubhuman == true;
/// <summary>Apparel, drug, reading and schedule: not a quest lodger, not a prisoner, no policy-less mutant.</summary>
private static bool CanTakeOwnPolicies(Pawn pawn) =>
!pawn.IsQuestLodger() && !pawn.IsPrisoner && !PoliciesDisabled(pawn);
/// <summary>Work and loadout: colonists and slaves of the player, with the same exclusions.</summary>
private static bool IsColonistOrSlave(Pawn pawn) =>
pawn.Faction == Faction.OfPlayer && pawn.RaceProps != null && pawn.RaceProps.Humanlike && CanTakeOwnPolicies(pawn);
/// <summary>
/// The slot is written at all: work priorities need the manageWorkPriorities setting and no automatic
/// work manager; the loadout needs Weapons Tab Reborn and the manageWeaponLoadout setting.
/// </summary>
public static bool SlotActive(CasteSlot slot)
{
switch (slot)
{
case CasteSlot.Work: return WorkSlot.Active;
case CasteSlot.Loadout: return WeaponsTab.Active;
default: return true;
}
}
/// <summary>Whether the slot can be written on this pawn right now.</summary>
public static bool CanUse(Pawn pawn, CasteSlot slot)
{
if (pawn == null || (pawn.Destroyed && !pawn.Dead) || IsMutantWithoutDef(pawn))
return false;
switch (slot)
{
case CasteSlot.Apparel:
return pawn.outfits != null && CanTakeOwnPolicies(pawn) && MutantDefFor(pawn)?.disableApparel != true;
case CasteSlot.Drug:
return pawn.drugs != null && CanTakeOwnPolicies(pawn);
case CasteSlot.Reading:
return pawn.reading != null && CanTakeOwnPolicies(pawn);
case CasteSlot.Food:
return pawn.foodRestriction != null && pawn.foodRestriction.Configurable
&& !pawn.DevelopmentalStage.Baby() && !PoliciesDisabled(pawn);
case CasteSlot.MedCare:
return pawn.playerSettings != null && pawn.RaceProps != null && pawn.RaceProps.IsFlesh;
case CasteSlot.Schedule:
// Like the vanilla Schedule tab: a timetable, and not a subhuman mutant.
return ScheduleSlot.HasTimetable(pawn) && CanTakeOwnPolicies(pawn) && !IsSubhumanMutant(pawn);
case CasteSlot.Work:
return WorkSlot.Active && WorkSlot.HasWorkSettings(pawn) && IsColonistOrSlave(pawn);
case CasteSlot.Loadout:
return WeaponsTab.Active && IsColonistOrSlave(pawn);
default:
return false;
}
}
/// <summary>
/// The pawn's current value for a slot, or null if it has none: a Policy, a boxed int for MedCare and
/// Loadout, the 24 schedule defNames, or the priorities of the work types that are on.
/// </summary>
public static object CurrentValue(Pawn pawn, CasteSlot slot)
{
if (pawn == null)
return null;
switch (slot)
{
case CasteSlot.Apparel: return pawn.outfits?.CurrentApparelPolicy;
case CasteSlot.Food: return pawn.foodRestriction?.CurrentFoodPolicy;
case CasteSlot.Drug: return pawn.drugs?.CurrentPolicy;
case CasteSlot.Reading: return pawn.reading?.CurrentPolicy;
case CasteSlot.MedCare: return pawn.playerSettings == null ? (object)null : (int)pawn.playerSettings.medCare;
case CasteSlot.Schedule: return ScheduleSlot.Of(pawn);
case CasteSlot.Work: return WorkSlot.Of(pawn, activeOnly: true);
case CasteSlot.Loadout: return CanUse(pawn, CasteSlot.Loadout) ? WeaponsTab.LoadoutOf(pawn) : null;
default: return null;
}
}
/// <summary>
/// Equality for slot values: policies by reference, med care and loadout by value, schedules hour by
/// hour, work priorities type by type.
/// </summary>
public static bool SameValue(object a, object b)
{
if (a is int ia && b is int ib)
return ia == ib;
if (a is IReadOnlyList<string> la && b is IReadOnlyList<string> lb)
return la.SequenceEqual(lb);
if (a is IReadOnlyDictionary<string, int> da && b is IReadOnlyDictionary<string, int> db)
return da.Count == db.Count && da.All(kv => db.TryGetValue(kv.Key, out int v) && v == kv.Value);
return ReferenceEquals(a, b);
}
/// <summary>
/// The pawn already has the caste's value for the slot (so it follows the caste). Schedules compare the
/// whole day; work priorities compare each listed type the pawn can do, as the game treats them now.
/// </summary>
public static bool Matches(Pawn pawn, CasteSlot slot, object casteValue)
{
switch (slot)
{
case CasteSlot.Schedule:
return ScheduleSlot.Matches(pawn, casteValue as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.MatchesAll(pawn, casteValue as IReadOnlyDictionary<string, int>);
case CasteSlot.Loadout:
return casteValue is int id && WeaponsTab.LoadoutOf(pawn) == id;
default:
return SameValue(CurrentValue(pawn, slot), casteValue);
}
}
/// <summary>
/// Writes every managed slot of the caste the pawn can take and returns those slots. A policy that is
/// no longer in its database, or a loadout Weapons Tab Reborn no longer has, is skipped and unmanaged.
/// Work priorities honour the caste's "Start from nothing". Does nothing while the "enabled" setting is off.
/// </summary>
public static List<CasteSlot> Apply(Pawn pawn, Caste caste)
{
var applied = new List<CasteSlot>();
if (!BlaxCastesMod.Enabled || pawn == null || caste == null || GameComponent_BlaxCastes.IsGone(pawn))
return applied;
bool missing = false;
foreach (CasteSlot slot in AllSlots)
{
if (!caste.IsManaged(slot))
continue;
object value = caste.GetSlot(slot);
if (IsPolicySlot(slot) && slot != CasteSlot.MedCare && !PolicyExists(value as Policy))
{
missing = true;
continue;
}
if (slot == CasteSlot.Loadout && CanUse(pawn, slot) && !WeaponsTab.Exists(caste.LoadoutId))
{
missing = true;
continue;
}
bool wrote = slot == CasteSlot.Work
? CanUse(pawn, slot) && WorkSlot.Write(pawn, caste.WorkPriorities, caste.WorkStartFromNothing)
: WriteSlot(pawn, slot, value);
if (wrote)
applied.Add(slot);
}
if (missing)
CasteManager.UnmanageMissingPolicies(caste);
return applied;
}
/// <summary>
/// Writes one slot value if the pawn can take it. Null policies, medCare and loadout -1 and a null
/// schedule are never written. Work writes only the listed types (no "Start from nothing").
/// </summary>
internal static bool WriteSlot(Pawn pawn, CasteSlot slot, object value)
{
if (!CanUse(pawn, slot))
return false;
switch (slot)
{
case CasteSlot.Apparel:
if (!(value is ApparelPolicy apparel))
return false;
pawn.outfits.CurrentApparelPolicy = apparel;
return true;
case CasteSlot.Food:
if (!(value is FoodPolicy food))
return false;
pawn.foodRestriction.CurrentFoodPolicy = food;
return true;
case CasteSlot.Drug:
if (!(value is DrugPolicy drug))
return false;
pawn.drugs.CurrentPolicy = drug;
return true;
case CasteSlot.Reading:
if (!(value is ReadingPolicy reading))
return false;
pawn.reading.CurrentPolicy = reading;
return true;
case CasteSlot.MedCare:
int care = ToMedCare(value);
if (care < 0)
return false;
pawn.playerSettings.medCare = (MedicalCareCategory)care;
return true;
case CasteSlot.Schedule:
return ScheduleSlot.Write(pawn, value as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.Write(pawn, value as IReadOnlyDictionary<string, int>, startFromNothing: false);
case CasteSlot.Loadout:
int id = ToLoadoutId(value);
return id >= 0 && WeaponsTab.SetLoadout(pawn, id);
default:
return false;
}
}
// ---- former-caste records ----------------------------------------------------------------
/// <summary>
/// Fills a former-caste record with the pawn's own settings (the slots it can take now), with the
/// slots and work types of its caste where it has the caste's value, and with the slots the caste
/// manages and the work types it lists now. caste is null for a pawn that is casteless by choice.
/// </summary>
internal static void Snapshot(Pawn pawn, Caste caste, FormerCaste record)
{
if (pawn == null || record == null)
return;
record.managed = caste == null ? new List<CasteSlot>() : AllSlots.Where(caste.IsManaged).ToList();
record.listedWork = caste == null ? new List<string>() : caste.WorkPriorities.Keys.ToList();
foreach (CasteSlot slot in AllSlots)
{
if (!CanUse(pawn, slot))
continue;
switch (slot)
{
case CasteSlot.Apparel: record.apparel = pawn.outfits.CurrentApparelPolicy; break;
case CasteSlot.Food: record.food = pawn.foodRestriction.CurrentFoodPolicy; break;
case CasteSlot.Drug: record.drug = pawn.drugs.CurrentPolicy; break;
case CasteSlot.Reading: record.reading = pawn.reading.CurrentPolicy; break;
case CasteSlot.MedCare: record.medCare = (int)pawn.playerSettings.medCare; break;
case CasteSlot.Schedule: record.schedule = ScheduleSlot.Of(pawn)?.ToList(); break;
case CasteSlot.Work: record.work = WorkSlot.Of(pawn); break;
case CasteSlot.Loadout: record.loadoutId = WeaponsTab.LoadoutOf(pawn) ?? Caste.Unmanaged; break;
}
if (caste == null || !caste.IsManaged(slot) || slot == CasteSlot.Work)
continue;
if (Matches(pawn, slot, caste.GetSlot(slot)))
record.followed.Add(slot);
}
Dictionary<string, int> decided = WorkSlot.Decided(caste);
if (decided != null && CanUse(pawn, CasteSlot.Work))
{
foreach (KeyValuePair<string, int> kv in decided)
{
if (WorkSlot.Matches(pawn, kv.Key, kv.Value))
record.followedWork.Add(kv.Key);
}
}
}
/// <summary>
/// The pawn's own value for a slot from a former-caste record, or null where the record has none or
/// its policy is gone. A policy counts only while that very policy is still in its database, so a
/// new policy that got a deleted one's id is never mistaken for it.
/// </summary>
internal static object OwnValue(FormerCaste record, CasteSlot slot)
{
switch (slot)
{
case CasteSlot.Apparel: return PolicyExists(record.apparel) ? record.apparel : null;
case CasteSlot.Food: return PolicyExists(record.food) ? record.food : null;
case CasteSlot.Drug: return PolicyExists(record.drug) ? record.drug : null;
case CasteSlot.Reading: return PolicyExists(record.reading) ? record.reading : null;
case CasteSlot.MedCare: return ToMedCare(record.medCare) < 0 ? null : (object)record.medCare;
case CasteSlot.Schedule: return record.schedule != null && record.schedule.Count == ScheduleSlot.Hours ? ScheduleSlot.Normalize(record.schedule) : null;
case CasteSlot.Loadout: return record.loadoutId >= 0 ? (object)record.loadoutId : null;
default: return null;
}
}
/// <summary>
/// Gives a returning pawn its own settings back (JoinDefaults.Restore). previous is the caste it
/// returns to (null for No caste), away the caste it got while it was gone (null when none, or the
/// same caste). A slot previous manages gets the caste's current value if the pawn followed it when
/// it left or the caste did not manage it then (the Follow rule: a slot that becomes managed reaches
/// every member), else the pawn's own value from then. A slot only away manages, where the pawn
/// still has away's value, gets the pawn's own value from then. Everything else stays. Does nothing
/// while the "enabled" setting is off.
/// </summary>
internal static void Restore(Pawn pawn, Caste previous, Caste away, FormerCaste record)
{
if (!BlaxCastesMod.Enabled || pawn == null || record == null || GameComponent_BlaxCastes.IsGone(pawn))
return;
bool missing = false;
foreach (CasteSlot slot in AllSlots)
{
if (!CanUse(pawn, slot))
continue;
if (slot == CasteSlot.Work)
{
RestoreWork(pawn, previous, away, record);
continue;
}
object own = OwnValue(record, slot);
object target;
if (previous != null && previous.IsManaged(slot))
target = record.Followed(slot) || !record.WasManaged(slot) || own == null ? previous.GetSlot(slot) : own;
else if (away != null && away.IsManaged(slot) && Matches(pawn, slot, away.GetSlot(slot)))
target = own;
else
continue;
if (target == null)
continue;
if (IsPolicySlot(slot) && slot != CasteSlot.MedCare && !PolicyExists(target as Policy))
{
missing = true;
continue;
}
if (slot == CasteSlot.Loadout && !WeaponsTab.Exists(ToLoadoutId(target)))
{
missing = true;
continue;
}
if (!Matches(pawn, slot, target))
WriteSlot(pawn, slot, target);
}
if (missing && previous != null)
CasteManager.UnmanageMissingPolicies(previous);
}
/// <summary>
/// Restore for work priorities, type by type over the types previous or away decide (WorkSlot.Decided).
/// A type previous lists now but did not list when the pawn left gets the caste's value, as the
/// Follow rule gives a newly listed type to every member; a type only "Start from nothing" decides
/// moves nobody when it is ticked, so it keeps the pawn's own value unless the pawn followed it.
/// </summary>
private static void RestoreWork(Pawn pawn, Caste previous, Caste away, FormerCaste record)
{
Dictionary<string, int> mine = WorkSlot.Decided(previous);
Dictionary<string, int> theirs = WorkSlot.Decided(away);
if (mine == null && theirs == null)
return;
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
string name = def.defName;
int own = 0;
bool hasOwn = record.work != null && record.work.TryGetValue(name, out own);
int target;
bool casteValue = false;
if (mine != null && mine.TryGetValue(name, out int value))
{
bool listedSince = previous.WorkPriorities.ContainsKey(name) && !record.WasListed(name);
casteValue = record.FollowedWork(name) || listedSince || !hasOwn;
target = casteValue ? value : own;
}
else if (theirs != null && hasOwn && theirs.TryGetValue(name, out int awayValue) && WorkSlot.Matches(pawn, name, awayValue))
{
target = own;
}
else
{
continue;
}
// With manual priorities off the game hides the stored number, so a caste value is stored even when it already reads the same.
if (!WorkSlot.Matches(pawn, name, target) || (casteValue && !WorkSlot.ManualPriorities))
WorkSlot.WriteType(pawn, name, target);
}
}
/// <summary>True if the policy is still in its game database.</summary>
public static bool PolicyExists(Policy policy)
{
Game game = Current.Game;
if (policy == null || game == null)
return false;
switch (policy)
{
case ApparelPolicy a: return game.outfitDatabase?.AllOutfits?.Contains(a) == true;
case FoodPolicy f: return game.foodRestrictionDatabase?.AllFoodRestrictions?.Contains(f) == true;
case DrugPolicy d: return game.drugPolicyDatabase?.AllPolicies?.Contains(d) == true;
case ReadingPolicy r: return game.readingPolicyDatabase?.AllReadingPolicies?.Contains(r) == true;
default: return false;
}
}
/// <summary>A med care slot value: -1 for unmanaged, otherwise a valid MedicalCareCategory.</summary>
public static int ToMedCare(object value)
{
int v;
switch (value)
{
case null: return Caste.Unmanaged;
case MedicalCareCategory c: v = (int)c; break;
case int i: v = i; break;
case byte b: v = b; break;
default: return Caste.Unmanaged;
}
return v >= (int)MedicalCareCategory.NoCare && v <= (int)MedicalCareCategory.Best ? v : Caste.Unmanaged;
}
/// <summary>A loadout slot value: -1 for unmanaged, otherwise the id (never negative).</summary>
public static int ToLoadoutId(object value) => value is int i && i >= 0 ? i : Caste.Unmanaged;
/// <summary>Which slot type a value belongs in; false for a value that fits no slot.</summary>
public static bool FitsSlot(CasteSlot slot, object value)
{
if (value == null)
return true;
switch (slot)
{
case CasteSlot.Apparel: return value is ApparelPolicy;
case CasteSlot.Food: return value is FoodPolicy;
case CasteSlot.Drug: return value is DrugPolicy;
case CasteSlot.Reading: return value is ReadingPolicy;
case CasteSlot.MedCare: return value is int || value is MedicalCareCategory || value is byte;
case CasteSlot.Schedule: return ScheduleSlot.Fits(value);
case CasteSlot.Work: return WorkSlot.Fits(value);
case CasteSlot.Loadout: return value is int;
default: return false;
}
}
/// <summary>A value in the form the caste stores it: med care and loadout as int, a schedule as 24 known names, work priorities without bad entries.</summary>
public static object NormalizeSlotValue(CasteSlot slot, object value)
{
switch (slot)
{
case CasteSlot.MedCare: return ToMedCare(value);
case CasteSlot.Schedule: return ScheduleSlot.Normalize(value);
case CasteSlot.Work: return WorkSlot.Normalize(value);
case CasteSlot.Loadout: return ToLoadoutId(value);
default: return value;
}
}
public static string SlotLabel(CasteSlot slot) => ("BlaxCastes_Slot" + slot).Translate();
/// <summary>A slot value as the player sees it: the policy label, the med care label, a schedule or priority summary, the loadout name, or "leave alone".</summary>
public static string ValueLabel(CasteSlot slot, object value)
{
switch (slot)
{
case CasteSlot.MedCare:
int care = ToMedCare(value);
return care < 0 ? (string)"BlaxCastes_Unmanaged".Translate() : ((MedicalCareCategory)care).GetLabel();
case CasteSlot.Schedule:
return ScheduleSlot.Summary(value as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.Summary(value as IReadOnlyDictionary<string, int>);
case CasteSlot.Loadout:
int id = ToLoadoutId(value);
if (id < 0)
return "BlaxCastes_Unmanaged".Translate();
return WeaponsTab.NameOf(id) ?? (string)"BlaxCastes_LoadoutUnknown".Translate(id);
default:
return value is Policy p ? p.label : (string)"BlaxCastes_Unmanaged".Translate();
}
}
}
}