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

527 lines
24 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>Which player-side status a pawn has, for join classification.</summary>
public enum JoinSide
{
None,
Colonist,
Slave,
Prisoner,
}
/// <summary>
/// Join defaults: puts a pawn that joins, or changes status, into the caste of its join row.
///
/// The join hooks (JoinHooks: Pawn.SetFaction, Pawn_GuestTracker.SetGuestStatus, Pawn.PreTraded)
/// classify the join where it happens and call Enqueue with the innermost scope's reason, or with
/// StatusFallback. The queue lives in GameComponent_BlaxCastes.JoinQueue, so it survives a save.
/// GameComponentTick calls ApplyQueue every tick, which applies entries queued on an earlier tick:
/// never inside SetFaction or SetGuestStatus, and only while the pawn is still player-side.
///
/// Order at apply time: a caste picked by hand after the join was queued, then the previous caste or
/// No caste (a former-caste record with the same status, younger than formerCasteDays; the pawn's own
/// settings from when it left come back with it), then the row. Reason
/// to row, first match wins: the scope ("bought": the final status picks bought as slave or bought
/// as colonist; a row id is used as it is), then the status fallback from the final status: new
/// colonist, new slave or new prisoner.
/// </summary>
public static class JoinDefaults
{
/// <summary>Queue reason when no scope covered the join: the final status picks the row.</summary>
public const string StatusFallback = "status";
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
private static int Now => Find.TickManager?.TicksGame ?? 0;
/// <summary>Castes is on and the join defaults setting is on.</summary>
public static bool Active =>
BlaxCastesMod.Enabled && (BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.enableJoinDefaults);
private static bool ReturnToPrevious => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.returnToPreviousCaste;
private static int FormerCasteDays => BlaxCastesMod.Settings?.formerCasteDays ?? BlaxCastesSettings.DefaultFormerCasteDays;
// ---- classification ----------------------------------------------------------------
public static JoinSide SideOf(Pawn pawn)
{
if (pawn == null)
return JoinSide.None;
Pawn_GuestTracker guest = pawn.guest;
return Classify(pawn.Faction, guest != null, guest != null ? guest.guestStatusInt : GuestStatus.Guest, guest?.HostFaction);
}
/// <summary>
/// Player faction: slave, prisoner of the colony (an arrested colonist) or colonist (also one held
/// by another faction, so it keeps its caste when it comes back). Another faction: prisoner of the
/// colony or nothing.
/// </summary>
internal static JoinSide Classify(Faction faction, bool hasGuest, GuestStatus status, Faction host)
{
Faction player = Faction.OfPlayerSilentFail;
if (player == null)
return JoinSide.None;
bool prisonerOfColony = hasGuest && status == GuestStatus.Prisoner && host == player;
if (faction == player)
{
if (hasGuest && status == GuestStatus.Slave)
return JoinSide.Slave;
return prisonerOfColony ? JoinSide.Prisoner : JoinSide.Colonist;
}
return prisonerOfColony ? JoinSide.Prisoner : JoinSide.None;
}
/// <summary>
/// Humanlike, not a baby, not a quest lodger, not a mutant without policies or without its def (a save made
/// with Anomaly, loaded without it). Others never join a caste.
/// </summary>
public static bool Eligible(Pawn pawn) =>
pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike
&& !pawn.DevelopmentalStage.Baby() && !pawn.IsQuestLodger()
&& !CasteUtility.IsMutantWithoutDef(pawn) && !CasteUtility.PoliciesDisabled(pawn);
/// <summary>A scope reason or a row id, as opposed to the status fallback.</summary>
public static bool IsSpecific(string reason) => !reason.NullOrEmpty() && reason != StatusFallback;
/// <summary>
/// The join row a queued reason resolves to for the pawn's status now, or null when the pawn has
/// no player-side status.
/// </summary>
public static string RowFor(string reason, Pawn pawn)
{
JoinSide side = SideOf(pawn);
if (reason == JoinScopes.Bought)
{
if (side == JoinSide.Slave)
return JoinReason.BoughtSlave;
if (side == JoinSide.Colonist)
return JoinReason.BoughtColonist;
}
else if (JoinReason.IsRow(reason))
{
return reason;
}
switch (side)
{
case JoinSide.Colonist: return JoinReason.NewColonist;
case JoinSide.Slave: return JoinReason.NewSlave;
case JoinSide.Prisoner: return JoinReason.NewPrisoner;
default: return null;
}
}
// ---- previous caste ----------------------------------------------------------------
/// <summary>A former-caste record older than formerCasteDays.</summary>
public static bool FormerExpired(FormerCaste record, int now) =>
record == null || now - record.tick > FormerCasteDays * GenDate.TicksPerDay;
/// <summary>
/// The former-caste record the pawn would leave right now: its caste, or No caste when it is casteless
/// by choice, the status (colonist or slave), and its own settings with the caste's slots it follows.
/// Null for another status or a pawn with no membership record (it never had a caste, so a status
/// change moves it by its row). The join hooks take it before a status change, because the game
/// resets medical care inside the change.
/// </summary>
internal static FormerCaste Capture(Pawn pawn, JoinSide side)
{
if (side != JoinSide.Colonist && side != JoinSide.Slave)
return null;
GameComponent_BlaxCastes comp = Comp;
CasteMembership m = comp?.MembershipOf(pawn);
if (m == null || (m.caste != null && !comp.HasCaste(m.caste)))
return null;
var record = new FormerCaste(m.caste?.id ?? Caste.Unmanaged, side, m.auto, Now) { casteless = m.caste == null };
CasteUtility.Snapshot(pawn, m.caste, record);
return record;
}
/// <summary>
/// Writes the pawn's former-caste record: it had this status (colonist or slave) and is leaving the
/// player side, being sold or becoming a prisoner. captured is the record taken before the change
/// (Capture); without one it is taken now. A pawn with no membership record writes none.
/// </summary>
internal static void NoteFormer(Pawn pawn, JoinSide side, FormerCaste captured = null)
{
if (side != JoinSide.Colonist && side != JoinSide.Slave)
return;
GameComponent_BlaxCastes comp = Comp;
if (comp == null || pawn == null)
return;
FormerCaste record = captured != null && captured.side == side ? captured : Capture(pawn, side);
if (record == null)
return;
record.tick = Now;
comp.SetFormer(pawn, record);
}
/// <summary>
/// The pawn's former-caste record when it applies now: it has the pawn's current status (colonist or
/// slave), is younger than formerCasteDays, and its caste still exists (a No caste record always
/// does). Null otherwise, or while returnToPreviousCaste is off.
/// </summary>
public static FormerCaste UsableFormer(Pawn pawn)
{
if (!ReturnToPrevious || pawn == null)
return null;
GameComponent_BlaxCastes comp = Comp;
FormerCaste record = comp?.FormerOf(pawn);
if (record == null || FormerExpired(record, Now))
return null;
JoinSide side = SideOf(pawn);
if ((side != JoinSide.Colonist && side != JoinSide.Slave) || record.side != side)
return null;
if (!record.casteless && comp.CasteById(record.casteId) == null)
return null;
return record;
}
/// <summary>
/// The caste a returning pawn gets back (UsableFormer). Null when there is none, and when the pawn
/// goes back to No caste.
/// </summary>
public static Caste PreviousCasteFor(Pawn pawn)
{
FormerCaste record = UsableFormer(pawn);
return record == null || record.casteless ? null : Comp.CasteById(record.casteId);
}
// ---- queue -------------------------------------------------------------------------
/// <summary>The pawn's waiting join, or null.</summary>
public static QueuedJoin QueuedFor(Pawn pawn)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || pawn == null)
return null;
List<QueuedJoin> queue = comp.JoinQueue;
for (int i = 0; i < queue.Count; i++)
{
if (queue[i] != null && queue[i].pawn == pawn)
return queue[i];
}
return null;
}
/// <summary>True while the pawn waits for its join to be applied.</summary>
public static bool IsQueued(Pawn pawn) => QueuedFor(pawn) != null;
/// <summary>
/// True while the pawn waits for a join that will change its caste: the previous caste or the row
/// gives it one, or a No caste row will take it out of a caste a join row put it in. The column
/// shows "(pending)" only then.
/// </summary>
public static bool WillChange(Pawn pawn)
{
QueuedJoin q = QueuedFor(pawn);
GameComponent_BlaxCastes comp = Comp;
if (q == null || comp == null || !Active || !Eligible(pawn) || !CasteUtility.IsPlayerSide(pawn))
return false;
CasteMembership m = comp.MembershipOf(pawn);
if (HandPickedSince(m, q))
return false;
FormerCaste record = UsableFormer(pawn);
if (record != null)
return record.casteless ? m == null || m.caste != null : m?.caste == null || m.caste.id != record.casteId;
string row = RowFor(q.reason, pawn);
if (row == null)
return false;
if (comp.ResolveRow(row) != null)
return true;
return m?.caste != null && m.auto;
}
/// <summary>
/// A caste (or No caste) picked by hand after the join was queued: a manual membership that is
/// not the one the pawn had when the join was queued (after a load, one set on or after the
/// queueing tick). A restored previous caste or a deleted caste never counts as a pick.
/// </summary>
private static bool HandPickedSince(CasteMembership m, QueuedJoin q)
{
if (m == null || m.auto || m.reason == JoinReason.CasteDeleted || m.reason == JoinReason.PreviousCaste)
return false;
if (q.seenKnown)
return !ReferenceEquals(m, q.seen);
return m.tick >= q.tick;
}
/// <summary>
/// Queues a join for the next tick: a scope reason, a row id or StatusFallback. One entry per pawn;
/// a specific reason replaces a status fallback, never the other way round. Does nothing while
/// Castes or the join defaults are off, and for pawns that never join a caste.
/// </summary>
public static void Enqueue(Pawn pawn, string reason)
{
if (!Active || pawn == null)
return;
GameComponent_BlaxCastes comp = Comp;
if (comp == null || GameComponent_BlaxCastes.IsGone(pawn) || !Eligible(pawn))
return;
if (reason.NullOrEmpty())
reason = StatusFallback;
comp.LeftPawns.Remove(pawn);
int now = Now;
QueuedJoin queued = QueuedFor(pawn);
if (queued == null)
{
queued = new QueuedJoin(pawn, reason, now);
comp.JoinQueue.Add(queued);
}
else
{
if (IsSpecific(reason) || !IsSpecific(queued.reason))
queued.reason = reason;
if (now > queued.tick)
queued.tick = now;
}
// A pick made before this status change is not a pick "after the join": the new status moves the pawn.
queued.seen = comp.MembershipOf(pawn);
queued.seenKnown = true;
}
/// <summary>A pawn left the player side. Its membership ends on the next tick if it has not come back.</summary>
internal static void NoteLeft(Pawn pawn)
{
if (pawn == null)
return;
Comp?.LeftPawns.Add(pawn);
}
/// <summary>
/// A pawn walked off the map for good while the game still counts it as player-side (JoinHooks.AfterLeaving):
/// it leaves its caste now, with a former-caste record if it was a colonist or slave, and a join waiting
/// for it is dropped. Nothing else would end the membership, since the pawn stays player-side.
/// </summary>
internal static void NoteGone(Pawn pawn, JoinSide side, FormerCaste captured)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || pawn == null)
return;
NoteFormer(pawn, side, captured);
comp.JoinQueue.RemoveAll(q => q != null && q.pawn == pawn);
comp.LeftPawns.Remove(pawn);
CasteManager.EndMembership(pawn);
}
/// <summary>
/// Applies the joins queued on an earlier tick and ends the memberships of pawns that left.
/// Called by GameComponent_BlaxCastes every tick.
/// </summary>
public static void ApplyQueue()
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || Find.TickManager == null)
return;
EndLeftMemberships(comp);
List<QueuedJoin> queue = comp.JoinQueue;
if (queue.Count == 0)
return;
int now = Now;
List<QueuedJoin> due = null;
foreach (QueuedJoin q in queue)
{
if (q == null || q.tick < now)
(due ??= new List<QueuedJoin>()).Add(q);
}
if (due == null)
return;
queue.RemoveAll(q => q == null || q.tick < now);
Dictionary<Caste, List<Pawn>> joined = null;
foreach (QueuedJoin q in due)
{
if (q == null)
continue;
try
{
Caste caste = ApplyOne(comp, q);
if (caste != null)
{
joined ??= new Dictionary<Caste, List<Pawn>>();
if (!joined.TryGetValue(caste, out List<Pawn> pawns))
joined[caste] = pawns = new List<Pawn>();
pawns.Add(q.pawn);
}
}
catch (Exception e)
{
JoinHooks.LogOnce("Applying a join", e);
}
}
if (joined != null)
SendMessages(joined);
}
/// <summary>Applies one join. Returns the caste the pawn joined, or null.</summary>
private static Caste ApplyOne(GameComponent_BlaxCastes comp, QueuedJoin q)
{
Pawn pawn = q.pawn;
if (GameComponent_BlaxCastes.IsGone(pawn) || pawn.Dead || pawn.Destroyed)
return null;
if (!CasteUtility.IsPlayerSide(pawn))
{
// Sold, released or gone over to another faction before the join was applied.
CasteManager.EndMembership(pawn);
return null;
}
if (!Active || !Eligible(pawn))
return null;
CasteMembership membership = comp.MembershipOf(pawn);
if (HandPickedSince(membership, q))
return null;
FormerCaste record = UsableFormer(pawn);
if (record != null)
{
comp.RemoveFormer(pawn);
return Restore(comp, pawn, record, membership);
}
string row = RowFor(q.reason, pawn);
if (row == null)
return null;
Caste caste = comp.ResolveRow(row);
bool rowSet = membership?.caste != null && membership.auto;
if (caste != null)
{
// Moving on from a caste a join row gave it: what that caste set and the new one leaves alone goes back.
if (rowSet && membership.caste != caste)
RevertSlots(pawn, membership.caste, caste);
return CasteManager.Assign(pawn, caste, true, row) ? caste : null;
}
// A No caste row only undoes what a join row did; a caste picked by hand stays.
if (rowSet)
LeaveCaste(pawn, membership.caste);
return null;
}
/// <summary>
/// A returning pawn gets its former caste, or No caste, back, and its own settings from when it
/// left: each slot of that caste it followed gets the caste's current value (edits made while it was
/// away included), each one it had changed by hand gets that value back. A slot the caste leaves
/// alone is touched only to undo the caste the pawn got while it was away (the new-prisoner caste's
/// food): while the pawn still has that caste's value, it gets its own from when it left. So an
/// arrest and release, or a sale and buy-back, keeps the pawn's hand changes. Returns the caste for
/// the join message, or null when the pawn's caste does not change or it goes back to No caste.
/// </summary>
private static Caste Restore(GameComponent_BlaxCastes comp, Pawn pawn, FormerCaste record, CasteMembership membership)
{
if (!CasteUtility.CanBeMember(pawn))
return null;
Caste previous = record.casteless ? null : comp.CasteById(record.casteId);
Caste away = membership?.caste;
comp.SetMembership(pawn, new CasteMembership(previous, record.auto, JoinReason.PreviousCaste, Now));
CasteUtility.Restore(pawn, previous, away == previous ? null : away, record);
return previous != null && previous != away ? previous : null;
}
/// <summary>
/// The pawn's join row is No caste while a join row had put it in a caste: it leaves the caste and
/// RevertSlots runs with no new caste.
/// </summary>
private static void LeaveCaste(Pawn pawn, Caste caste)
{
CasteManager.EndMembership(pawn);
RevertSlots(pawn, caste, null);
}
/// <summary>
/// A join row takes the pawn out of a caste a join row had put it in, to No caste or to another
/// caste. With revertOnLeave, each policy and medical care slot the old caste manages and the new
/// one leaves alone, where the pawn still has the old caste's value, goes back to the database
/// default (medical care to the game's default for its status), so a recruited prisoner does not
/// keep the prisoner food. Slots changed by hand stay (the Follow rule). The schedule, work
/// priorities and loadout have no database default and stay as they are.
/// </summary>
private static void RevertSlots(Pawn pawn, Caste from, Caste to)
{
if (from == null || !BlaxCastesMod.Enabled || (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.revertOnLeave))
return;
foreach (CasteSlot slot in CasteUtility.PolicySlots)
{
if (!from.IsManaged(slot) || (to != null && to.IsManaged(slot)) || !CasteUtility.CanUse(pawn, slot))
continue;
if (!CasteUtility.SameValue(CasteUtility.CurrentValue(pawn, slot), from.GetSlot(slot)))
continue;
if (slot == CasteSlot.MedCare)
{
pawn.playerSettings.ResetMedicalCare();
continue;
}
object value = DatabaseDefault(slot);
if (value != null)
CasteUtility.WriteSlot(pawn, slot, value);
}
}
private static object DatabaseDefault(CasteSlot slot)
{
Game game = Current.Game;
switch (slot)
{
case CasteSlot.Apparel: return game?.outfitDatabase?.DefaultOutfit();
case CasteSlot.Food: return game?.foodRestrictionDatabase?.DefaultFoodRestriction();
case CasteSlot.Drug: return game?.drugPolicyDatabase?.DefaultDrugPolicy();
case CasteSlot.Reading: return game?.readingPolicyDatabase?.DefaultReadingPolicy();
default: return null;
}
}
private static void EndLeftMemberships(GameComponent_BlaxCastes comp)
{
HashSet<Pawn> left = comp.LeftPawns;
if (left.Count == 0)
return;
List<Pawn> pawns = left.ToList();
left.Clear();
foreach (Pawn pawn in pawns)
{
try
{
if (!GameComponent_BlaxCastes.IsGone(pawn) && !pawn.Dead && !CasteUtility.IsPlayerSide(pawn))
CasteManager.EndMembership(pawn);
}
catch (Exception e)
{
JoinHooks.LogOnce("Ending a membership", e);
}
}
}
/// <summary>One message per caste per tick, so buying ten slaves does not post ten messages.</summary>
private static void SendMessages(Dictionary<Caste, List<Pawn>> joined)
{
if (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.joinMessages)
return;
foreach (KeyValuePair<Caste, List<Pawn>> kv in joined)
{
List<Pawn> pawns = kv.Value;
string text = MessageText(kv.Key, pawns);
if (!text.NullOrEmpty())
Messages.Message(text, new LookTargets(pawns), MessageTypeDefOf.NeutralEvent, historical: false);
}
}
/// <summary>The join message for pawns that joined one caste.</summary>
public static string MessageText(Caste caste, List<Pawn> pawns)
{
if (caste == null || pawns == null || pawns.Count == 0)
return null;
if (pawns.Count == 1)
return "BlaxCastes_JoinedCaste".Translate(pawns[0].Named("PAWN"), caste.label.Named("CASTE"));
string names = pawns.Select(p => p.LabelShort).ToCommaList(useAnd: true);
return "BlaxCastes_JoinedCasteMany".Translate(pawns.Count.Named("COUNT"), caste.label.Named("CASTE"), names.Named("PAWNS"));
}
}
}