feat: works with any DLC combination

Meditate hours (Royalty) and work types of a DLC that is off (Childcare, Dark study, Fishing) stay in the caste with a "needs <DLC>" note and work again when the DLC is back; "Forget these" clears them. Without Ideology the slave rows show only while the colony has slaves or a row picks a caste, with a "Needs Ideology" note. A save seeded without Ideology gets the Slave caste once on its first load with Ideology, with a Slave outfit if the save has none. Mutants whose def is gone are left alone. Prisoners a gravship leaves behind (Odyssey) leave their caste.

Tests: new DLC tests; undeclared Castes warnings fail a run; fixture cleanup clears ritual obligations; the test mod drops its URL-less dependency. Full matrix green: core 123/0/25, all 142/0/6, compat 146/0/1, tasoc 142/0/5, compat on core only 126/0/21. docs/ingame-check.md gains the DLC checks.
This commit is contained in:
Fabian @ Blax Software 2026-11-29 17:07:51 +01:00
parent 221297b675
commit 2c1490a054
35 changed files with 1343 additions and 135 deletions

Binary file not shown.

Binary file not shown.

View File

@ -18,19 +18,20 @@
<loadAfter> <loadAfter>
<li>brrainz.harmony</li> <li>brrainz.harmony</li>
</loadAfter> </loadAfter>
<description>Policy bundles and join defaults. Works without DLCs; slaves need Ideology. <description>Policy bundles and join defaults. Works with any combination of DLCs, or none.
- A caste bundles an apparel, food, drug and reading policy, a medical care level, a daily schedule and work priorities. Putting a pawn in a caste sets every slot the caste manages in one step. - A caste bundles an apparel, food, drug and reading policy, a medical care level, a daily schedule and work priorities. Putting a pawn in a caste sets every slot the caste manages in one step.
- Work priorities: set only the work types you pick, such as Firefighting 1 for everyone or Growing 1 for field slaves. Work a pawn cannot do is skipped. Off while an automatic work manager (Work Tab, Free Will, Work Manager, AutoPriorities, WorkRoles) is active. - Work priorities: set only the work types you pick, such as Firefighting 1 for everyone or Growing 1 for field slaves. Work a pawn cannot do is skipped. Off while an automatic work manager (Work Tab, Free Will, Work Manager, AutoPriorities, WorkRoles) is active.
- With [1001] Weapons Tab Reborn, a caste can also set the weapon loadout. - With [1001] Weapons Tab Reborn, a caste can also set the weapon loadout.
- Change a caste's setting and its members follow, except pawns you changed by hand. - Change a caste's setting and its members follow, except pawns you changed by hand.
- Ready-made Colonist, Slave and Prisoner castes, already picked for the ways pawns join. Colonist copies your default policies, so in a new game colonists see no change. An existing save gets them too, and nobody moves until you click "Assign by status". - Ready-made Colonist, Slave (Ideology) and Prisoner castes, already picked for the ways pawns join. Colonist copies your default policies, so in a new game colonists see no change. An existing save gets them too, and nobody moves until you click "Assign by status".
- Every status change uses its join row: bought, recruited, enslaved, freed, arrested, released or captured. A pawn you buy arrives with its caste's outfit and food policy already set, and a message names the caste. - Every status change uses its join row: bought, recruited, enslaved or freed (Ideology), arrested, released or captured. A pawn you buy arrives with its caste's outfit and food policy already set, and a message names the caste.
- A colonist or slave that comes back within 60 days (released, bought back) gets its old caste back, with the changes you made by hand. - A colonist or slave that comes back within 60 days (released, bought back) gets its old caste back, with the changes you made by hand.
- Prisoners in a caste get its food policy and medical care only. - Prisoners in a caste get its food policy and medical care only.
- Assign, Schedule and Work tabs: a Caste column (click a cell, or drag down the column to give several pawns the same caste), with a "Manage castes" button above it and, in the Assign and Schedule tabs, "Defaults". The caste manager works like the vanilla policy windows, with a schedule painted like the Schedule tab, a member count, "Apply to all members" and "Assign by status". - Assign, Schedule and Work tabs: a Caste column (click a cell, or drag down the column to give several pawns the same caste), with a "Manage castes" button above it and, in the Assign and Schedule tabs, "Defaults". The caste manager works like the vanilla policy windows, with a schedule painted like the Schedule tab, a member count, "Apply to all members" and "Assign by status".
- A pawn that leaves your faction leaves its caste. - A pawn that leaves your faction leaves its caste.
- Covers Automatic Slave Outfit, PrisonerDefaults and the join, schedule and work defaults of Better Pawn Control and 1trickPwnyta's Defaults, and warns while one of them is active. - Covers Automatic Slave Outfit, PrisonerDefaults and the join, schedule and work defaults of Better Pawn Control and 1trickPwnyta's Defaults, and warns while one of them is active.
- DLCs: Meditate hours need Royalty, slaves Ideology, babies and Childcare Biotech, mutants and Dark study Anomaly, Fishing and gravships Odyssey. Without a DLC its part switches off and everything else keeps working. When a DLC is turned off for a save, Castes keeps its Meditate hours and work priorities from that DLC and uses them again once the DLC is back.
- Turn it off in the mod settings and castes stop changing pawns. Removing the mod leaves every pawn on its last settings. - Turn it off in the mod settings and castes stop changing pawns. Removing the mod leaves every pawn on its last settings.
Multiplayer: not supported yet. Multiplayer: not supported yet.

View File

@ -14,4 +14,5 @@
- A colonist or slave that leaves, is sold or becomes a prisoner and comes back within 60 days with the same status gets its old caste (or No caste) back, with the changes you made by hand; what the caste started managing while it was away reaches it, a policy deleted in the meantime is skipped, and what the caste it had while away set goes back to how it was. - A colonist or slave that leaves, is sold or becomes a prisoner and comes back within 60 days with the same status gets its old caste (or No caste) back, with the changes you made by hand; what the caste started managing while it was away reaches it, a policy deleted in the meantime is skipped, and what the caste it had while away set goes back to how it was.
- Warnings on the settings page and one message per save when Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active. - Warnings on the settings page and one message per save when Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active.
- A pawn that leaves your faction leaves its caste, and so does a freed slave from another faction that walks off, an escaped slave or prisoner, and a pawn left on a map that closes. A pawn that leaves in a caravan, a transport pod or a shuttle, or is kidnapped, keeps its caste. Deleting a caste leaves its members casteless on their current settings. - A pawn that leaves your faction leaves its caste, and so does a freed slave from another faction that walks off, an escaped slave or prisoner, and a pawn left on a map that closes. A pawn that leaves in a caravan, a transport pod or a shuttle, or is kidnapped, keeps its caste. Deleting a caste leaves its members casteless on their current settings.
- DLC support: works with any combination of DLCs, or with the core game alone, and lists no DLC as a dependency. Slaves and the Slave caste need Ideology, Meditate hours Royalty, babies and Childcare Biotech, mutants and Dark study Anomaly, Fishing and gravships Odyssey; without a DLC its part switches off and everything else keeps working. When a DLC is turned off for a save, Meditate hours and Childcare, Dark study or Fishing priorities stay in the caste with no warning, act as Anything or are skipped, and come back with the DLC; painting the hours over or "Forget these" under the work priorities drops them, and "Apply to all members" hides while they are all a caste manages. A mutant whose def is gone is left alone. Without Ideology the slave rows show only while a save still has slaves or a slave row picks a caste, with a "Needs Ideology" note, and the settings say the Slave caste needs Ideology; a save started without Ideology gets the Slave caste on its first load with it, with a Slave outfit if the save has none. A prisoner a gravship leaves behind leaves its caste.
- Settings: castes on or off, work priorities, weapon loadout, join defaults, join messages, reset policies a caste set when a join moves the pawn on, old caste on return and for how many days, starter castes, overlap warnings, the Caste column. While a game is loaded, the settings page also opens the caste manager and the join defaults. - Settings: castes on or off, work priorities, weapon loadout, join defaults, join messages, reset policies a caste set when a join moves the pawn on, old caste on return and for how many days, starter castes, overlap warnings, the Caste column. While a game is loaded, the settings page also opens the caste manager and the join defaults.

View File

@ -16,6 +16,7 @@
<BlaxCastes_WorkOff>off</BlaxCastes_WorkOff> <BlaxCastes_WorkOff>off</BlaxCastes_WorkOff>
<BlaxCastes_WorkLeaveAloneShort>-</BlaxCastes_WorkLeaveAloneShort> <BlaxCastes_WorkLeaveAloneShort>-</BlaxCastes_WorkLeaveAloneShort>
<BlaxCastes_WorkManagerActive>{0} is active and changes work priorities itself, so castes leave work priorities alone.</BlaxCastes_WorkManagerActive> <BlaxCastes_WorkManagerActive>{0} is active and changes work priorities itself, so castes leave work priorities alone.</BlaxCastes_WorkManagerActive>
<BlaxCastes_NeedsDlc>{WHAT} (needs {DLC})</BlaxCastes_NeedsDlc>
<!-- Starter castes --> <!-- Starter castes -->
<BlaxCastes_StarterColonist>Colonist</BlaxCastes_StarterColonist> <BlaxCastes_StarterColonist>Colonist</BlaxCastes_StarterColonist>
@ -24,6 +25,7 @@
<BlaxCastes_StarterSeededMessage>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet: open Assign &gt; Manage castes and click "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessage> <BlaxCastes_StarterSeededMessage>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet: open Assign &gt; Manage castes and click "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessage>
<BlaxCastes_StarterSeededMessageNoColumn>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet. The Caste column is turned off, so open the Blax Castes mod settings, click Manage castes and then "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessageNoColumn> <BlaxCastes_StarterSeededMessageNoColumn>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet. The Caste column is turned off, so open the Blax Castes mod settings, click Manage castes and then "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessageNoColumn>
<BlaxCastes_SlaveOutfitCold>The Slave outfit has no cold protection. In a cold biome, add warm clothes to it or pick another outfit.</BlaxCastes_SlaveOutfitCold> <BlaxCastes_SlaveOutfitCold>The Slave outfit has no cold protection. In a cold biome, add warm clothes to it or pick another outfit.</BlaxCastes_SlaveOutfitCold>
<BlaxCastes_StarterSlaveAddedMessage>Ideology is active now, so Blax Castes set up the {CASTE} caste and picked it for bought and new slaves.</BlaxCastes_StarterSlaveAddedMessage>
<!-- Overlap warnings --> <!-- Overlap warnings -->
<BlaxCastes_OverlapSettingsIntro>These active mods also set policies when a pawn joins:</BlaxCastes_OverlapSettingsIntro> <BlaxCastes_OverlapSettingsIntro>These active mods also set policies when a pawn joins:</BlaxCastes_OverlapSettingsIntro>
@ -56,16 +58,21 @@
<BlaxCastes_SettingWeaponLoadoutTip>A caste can set the Weapons Tab Reborn loadout of its colonists and slaves. A caste that sets it writes it one tick after a pawn joins, so its choice wins over Weapons Tab Reborn's default loadout; a caste that leaves it alone leaves Weapons Tab Reborn in charge. Off: castes never change loadouts.</BlaxCastes_SettingWeaponLoadoutTip> <BlaxCastes_SettingWeaponLoadoutTip>A caste can set the Weapons Tab Reborn loadout of its colonists and slaves. A caste that sets it writes it one tick after a pawn joins, so its choice wins over Weapons Tab Reborn's default loadout; a caste that leaves it alone leaves Weapons Tab Reborn in charge. Off: castes never change loadouts.</BlaxCastes_SettingWeaponLoadoutTip>
<BlaxCastes_SettingJoinDefaults>Join defaults</BlaxCastes_SettingJoinDefaults> <BlaxCastes_SettingJoinDefaults>Join defaults</BlaxCastes_SettingJoinDefaults>
<BlaxCastes_SettingJoinDefaultsTip>A pawn that joins or changes status (bought, recruited, enslaved, freed, arrested, released or captured) goes into the caste its join row picks.</BlaxCastes_SettingJoinDefaultsTip> <BlaxCastes_SettingJoinDefaultsTip>A pawn that joins or changes status (bought, recruited, enslaved, freed, arrested, released or captured) goes into the caste its join row picks.</BlaxCastes_SettingJoinDefaultsTip>
<BlaxCastes_SettingJoinDefaultsTipNoIdeology>A pawn that joins or changes status (bought, recruited, arrested, released or captured) goes into the caste its join row picks.</BlaxCastes_SettingJoinDefaultsTipNoIdeology>
<BlaxCastes_SettingJoinMessages>Message when a joining pawn gets a caste</BlaxCastes_SettingJoinMessages> <BlaxCastes_SettingJoinMessages>Message when a joining pawn gets a caste</BlaxCastes_SettingJoinMessages>
<BlaxCastes_SettingJoinMessagesTip>A message names the pawn and its new caste.</BlaxCastes_SettingJoinMessagesTip> <BlaxCastes_SettingJoinMessagesTip>A message names the pawn and its new caste.</BlaxCastes_SettingJoinMessagesTip>
<BlaxCastes_SettingRevertOnLeave>Reset policies a caste set when a join moves the pawn on</BlaxCastes_SettingRevertOnLeave> <BlaxCastes_SettingRevertOnLeave>Reset policies a caste set when a join moves the pawn on</BlaxCastes_SettingRevertOnLeave>
<BlaxCastes_SettingRevertOnLeaveTip>When a join row takes a pawn out of a caste a join row had put it in, to No caste or to a caste that leaves some policies alone, the policies it still has from the old caste go back to the defaults, and its medical care is reset if the old caste set it. A recruited prisoner then does not keep the prisoner food. Policies you changed by hand stay. Off: it keeps them all. A caste you picked by hand is never taken away by a No caste row.</BlaxCastes_SettingRevertOnLeaveTip> <BlaxCastes_SettingRevertOnLeaveTip>When a join row takes a pawn out of a caste a join row had put it in, to No caste or to a caste that leaves some policies alone, the policies it still has from the old caste go back to the defaults, and its medical care is reset if the old caste set it. A recruited prisoner then does not keep the prisoner food. Policies you changed by hand stay. Off: it keeps them all. A caste you picked by hand is never taken away by a No caste row.</BlaxCastes_SettingRevertOnLeaveTip>
<BlaxCastes_SettingReturnToPrevious>A pawn that comes back gets its old caste</BlaxCastes_SettingReturnToPrevious> <BlaxCastes_SettingReturnToPrevious>A pawn that comes back gets its old caste</BlaxCastes_SettingReturnToPrevious>
<BlaxCastes_SettingReturnToPreviousTip>When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste) and its own settings. If it comes back with the same status within the days below (a released colonist, a slave you buy back), it gets that caste back instead of its join row's, and keeps what you had changed by hand on it. What the caste it had while it was away set goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row.</BlaxCastes_SettingReturnToPreviousTip> <BlaxCastes_SettingReturnToPreviousTip>When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste) and its own settings. If it comes back with the same status within the days below (a released colonist, a slave you buy back), it gets that caste back instead of its join row's, and keeps what you had changed by hand on it. What the caste it had while it was away set goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row.</BlaxCastes_SettingReturnToPreviousTip>
<BlaxCastes_SettingReturnToPreviousTipNoIdeology>When a colonist leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste) and its own settings. If it comes back as a colonist within the days below (a released colonist, one you buy back), it gets that caste back instead of its join row's, and keeps what you had changed by hand on it. What the caste it had while it was away set goes back to how it was.</BlaxCastes_SettingReturnToPreviousTipNoIdeology>
<BlaxCastes_SettingFormerCasteDays>Days to remember the old caste: {0}</BlaxCastes_SettingFormerCasteDays> <BlaxCastes_SettingFormerCasteDays>Days to remember the old caste: {0}</BlaxCastes_SettingFormerCasteDays>
<BlaxCastes_SettingFormerCasteDaysTip>After this many days a pawn that comes back uses its join row again.</BlaxCastes_SettingFormerCasteDaysTip> <BlaxCastes_SettingFormerCasteDaysTip>After this many days a pawn that comes back uses its join row again.</BlaxCastes_SettingFormerCasteDaysTip>
<BlaxCastes_SettingSeedStarter>Starter castes: Colonist, Slave and Prisoner</BlaxCastes_SettingSeedStarter> <BlaxCastes_SettingSeedStarter>Starter castes: Colonist, Slave and Prisoner</BlaxCastes_SettingSeedStarter>
<BlaxCastes_SettingSeedStarterTip>A new game starts with Colonist, Slave and Prisoner castes, already picked in the join defaults, and the starting colonists in the Colonist caste. The Colonist caste copies your default policies, so in a new game colonists see no change. A save without castes gets them once, on load, and nobody moves until you click "Assign by status" in the caste manager; that gives each pawn its caste's policies in place of its own. Without Ideology there is no Slave caste.</BlaxCastes_SettingSeedStarterTip> <BlaxCastes_SettingSeedStarterTip>A new game starts with Colonist, Slave and Prisoner castes, already picked in the join defaults, and the starting colonists in the Colonist caste. The Colonist caste copies your default policies, so in a new game colonists see no change. A save without castes gets them once, on load, and nobody moves until you click "Assign by status" in the caste manager; that gives each pawn its caste's policies in place of its own. Without Ideology there is no Slave caste.</BlaxCastes_SettingSeedStarterTip>
<BlaxCastes_SettingSeedStarterNoIdeology>Starter castes: Colonist and Prisoner</BlaxCastes_SettingSeedStarterNoIdeology>
<BlaxCastes_SettingSeedStarterTipNoIdeology>A new game starts with Colonist and Prisoner castes, already picked in the join defaults, and the starting colonists in the Colonist caste. The Colonist caste copies your default policies, so in a new game colonists see no change. A save without castes gets them once, on load, and nobody moves until you click "Assign by status" in the caste manager; that gives each pawn its caste's policies in place of its own. The Slave caste needs Ideology: turn Ideology on later and the save gets it on its next load.</BlaxCastes_SettingSeedStarterTipNoIdeology>
<BlaxCastes_SettingSeedStarterSlaveNote>Slave caste: needs Ideology.</BlaxCastes_SettingSeedStarterSlaveNote>
<BlaxCastes_SettingWarnOverlaps>Warn about mods that also set join defaults</BlaxCastes_SettingWarnOverlaps> <BlaxCastes_SettingWarnOverlaps>Warn about mods that also set join defaults</BlaxCastes_SettingWarnOverlaps>
<BlaxCastes_SettingWarnOverlapsTip>Names active mods that also set policies when a pawn joins, here and in one message per save.</BlaxCastes_SettingWarnOverlapsTip> <BlaxCastes_SettingWarnOverlapsTip>Names active mods that also set policies when a pawn joins, here and in one message per save.</BlaxCastes_SettingWarnOverlapsTip>
<BlaxCastes_SettingShowAssignColumn>Caste column in the Assign, Schedule and Work tabs (needs a restart)</BlaxCastes_SettingShowAssignColumn> <BlaxCastes_SettingShowAssignColumn>Caste column in the Assign, Schedule and Work tabs (needs a restart)</BlaxCastes_SettingShowAssignColumn>

View File

@ -7,12 +7,15 @@
<BlaxCastes_JoinDefaultsNoCastes>There are no castes yet. Make one in the Assign tab with Manage castes (or in the mod settings).</BlaxCastes_JoinDefaultsNoCastes> <BlaxCastes_JoinDefaultsNoCastes>There are no castes yet. Make one in the Assign tab with Manage castes (or in the mod settings).</BlaxCastes_JoinDefaultsNoCastes>
<BlaxCastes_DefaultCasteNamed>Default caste ({CASTE})</BlaxCastes_DefaultCasteNamed> <BlaxCastes_DefaultCasteNamed>Default caste ({CASTE})</BlaxCastes_DefaultCasteNamed>
<BlaxCastes_DefaultCasteNone>Default caste (none set)</BlaxCastes_DefaultCasteNone> <BlaxCastes_DefaultCasteNone>Default caste (none set)</BlaxCastes_DefaultCasteNone>
<BlaxCastes_JoinSlaveRowsNoIdeology>Needs Ideology: the slave rows only place the slaves this save already has.</BlaxCastes_JoinSlaveRowsNoIdeology>
<BlaxCastes_RowTip_boughtSlave>A pawn you buy from a trader that joins as a slave.</BlaxCastes_RowTip_boughtSlave> <BlaxCastes_RowTip_boughtSlave>A pawn you buy from a trader that joins as a slave.</BlaxCastes_RowTip_boughtSlave>
<BlaxCastes_RowTip_boughtColonist>A pawn you buy from a trader that joins as a colonist.</BlaxCastes_RowTip_boughtColonist> <BlaxCastes_RowTip_boughtColonist>A pawn you buy from a trader that joins as a colonist.</BlaxCastes_RowTip_boughtColonist>
<BlaxCastes_RowTip_newColonist>Any other pawn that becomes a colonist: recruited prisoners, freed slaves, released colonists, rescued pawns, wanderers and quest joiners. A pawn that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it, for example a recruited prisoner leaves the prisoner caste.</BlaxCastes_RowTip_newColonist> <BlaxCastes_RowTip_newColonist>Any other pawn that becomes a colonist: recruited prisoners, freed slaves, released colonists, rescued pawns, wanderers and quest joiners. A pawn that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it, for example a recruited prisoner leaves the prisoner caste.</BlaxCastes_RowTip_newColonist>
<BlaxCastes_RowTip_newColonistNoIdeology>Any other pawn that becomes a colonist: recruited prisoners, released colonists, rescued pawns, wanderers and quest joiners. A pawn that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it, for example a recruited prisoner leaves the prisoner caste.</BlaxCastes_RowTip_newColonistNoIdeology>
<BlaxCastes_RowTip_newSlave>Any other pawn that becomes a slave: enslaved prisoners, children raised as slaves and returned runaways. A slave that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newSlave> <BlaxCastes_RowTip_newSlave>Any other pawn that becomes a slave: enslaved prisoners, children raised as slaves and returned runaways. A slave that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newSlave>
<BlaxCastes_RowTip_newPrisoner>Any pawn that becomes your prisoner: captured enemies, quest prisoners, arrested colonists and imprisoned slaves. Prisoners only take the food policy and medical care of a caste.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newPrisoner> <BlaxCastes_RowTip_newPrisoner>Any pawn that becomes your prisoner: captured enemies, quest prisoners, arrested colonists and imprisoned slaves. Prisoners only take the food policy and medical care of a caste.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newPrisoner>
<BlaxCastes_RowTip_newPrisonerNoIdeology>Any pawn that becomes your prisoner: captured enemies, quest prisoners and arrested colonists. Prisoners only take the food policy and medical care of a caste.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newPrisonerNoIdeology>
<!-- Join messages --> <!-- Join messages -->
<BlaxCastes_JoinedCaste>{PAWN_labelShort} joined the {CASTE} caste.</BlaxCastes_JoinedCaste> <BlaxCastes_JoinedCaste>{PAWN_labelShort} joined the {CASTE} caste.</BlaxCastes_JoinedCaste>

View File

@ -16,6 +16,7 @@
<BlaxCastes_ApplyToAllConfirm>Set everything {CASTE} manages on every member ({COUNT})? Changes you made by hand on those pawns are lost.</BlaxCastes_ApplyToAllConfirm> <BlaxCastes_ApplyToAllConfirm>Set everything {CASTE} manages on every member ({COUNT})? Changes you made by hand on those pawns are lost.</BlaxCastes_ApplyToAllConfirm>
<BlaxCastes_AssignByStatus>Assign by status ({0})</BlaxCastes_AssignByStatus> <BlaxCastes_AssignByStatus>Assign by status ({0})</BlaxCastes_AssignByStatus>
<BlaxCastes_AssignByStatusTip>Puts every pawn without a caste ({0}) into the caste of its status row in the join defaults: new colonist, new slave or new prisoner. Each pawn gets everything its caste manages, in place of its own policies. Pawns you set to No caste are skipped.</BlaxCastes_AssignByStatusTip> <BlaxCastes_AssignByStatusTip>Puts every pawn without a caste ({0}) into the caste of its status row in the join defaults: new colonist, new slave or new prisoner. Each pawn gets everything its caste manages, in place of its own policies. Pawns you set to No caste are skipped.</BlaxCastes_AssignByStatusTip>
<BlaxCastes_AssignByStatusTipNoIdeology>Puts every pawn without a caste ({0}) into the caste of its status row in the join defaults: new colonist or new prisoner. Each pawn gets everything its caste manages, in place of its own policies. Pawns you set to No caste are skipped.</BlaxCastes_AssignByStatusTipNoIdeology>
<BlaxCastes_AssignByStatusConfirm>Put every pawn without a caste ({COUNT}) into the caste of its status row? Each pawn gets everything its caste manages, such as apparel, food, drug and reading policy, in place of what it has now, including changes you made by hand. This cannot be undone.</BlaxCastes_AssignByStatusConfirm> <BlaxCastes_AssignByStatusConfirm>Put every pawn without a caste ({COUNT}) into the caste of its status row? Each pawn gets everything its caste manages, such as apparel, food, drug and reading policy, in place of what it has now, including changes you made by hand. This cannot be undone.</BlaxCastes_AssignByStatusConfirm>
<BlaxCastes_AssignByStatusDone>Pawns put into the caste of their status: {0}.</BlaxCastes_AssignByStatusDone> <BlaxCastes_AssignByStatusDone>Pawns put into the caste of their status: {0}.</BlaxCastes_AssignByStatusDone>
@ -31,6 +32,7 @@
<BlaxCastes_ScheduleCopyFromPawnTip>Gives this caste the schedule of one of your colonists or slaves. Members on the caste's old schedule get it too; while the caste left the schedule alone, every member gets it, in place of its own.</BlaxCastes_ScheduleCopyFromPawnTip> <BlaxCastes_ScheduleCopyFromPawnTip>Gives this caste the schedule of one of your colonists or slaves. Members on the caste's old schedule get it too; while the caste left the schedule alone, every member gets it, in place of its own.</BlaxCastes_ScheduleCopyFromPawnTip>
<BlaxCastes_ScheduleLeaveAloneTip>Stop setting the schedule. Every pawn keeps the schedule it has now.</BlaxCastes_ScheduleLeaveAloneTip> <BlaxCastes_ScheduleLeaveAloneTip>Stop setting the schedule. Every pawn keeps the schedule it has now.</BlaxCastes_ScheduleLeaveAloneTip>
<BlaxCastes_ScheduleNoPawns>No colonists or slaves with a schedule</BlaxCastes_ScheduleNoPawns> <BlaxCastes_ScheduleNoPawns>No colonists or slaves with a schedule</BlaxCastes_ScheduleNoPawns>
<BlaxCastes_ScheduleDlcOffNote>Kept for when its DLC is back: {LIST}. Until then those hours act as Anything.</BlaxCastes_ScheduleDlcOffNote>
<!-- Caste manager: work priorities --> <!-- Caste manager: work priorities -->
<BlaxCastes_WorkStartFromNothing>Start from nothing</BlaxCastes_WorkStartFromNothing> <BlaxCastes_WorkStartFromNothing>Start from nothing</BlaxCastes_WorkStartFromNothing>
@ -40,12 +42,16 @@
Click to cycle: leave alone (-), 1, 2, 3, 4, off. Members whose priority matched the caste's before your first click follow each click; pawns you changed by hand keep theirs. Pawns that cannot do this work are skipped.</BlaxCastes_WorkTypeTip> Click to cycle: leave alone (-), 1, 2, 3, 4, off. Members whose priority matched the caste's before your first click follow each click; pawns you changed by hand keep theirs. Pawns that cannot do this work are skipped.</BlaxCastes_WorkTypeTip>
<BlaxCastes_WorkSettingOff>Work priorities are turned off in the Blax Castes mod settings.</BlaxCastes_WorkSettingOff> <BlaxCastes_WorkSettingOff>Work priorities are turned off in the Blax Castes mod settings.</BlaxCastes_WorkSettingOff>
<BlaxCastes_WorkManualOff>Manual priorities are off in the Work tab, so any number turns the work on. Members keep the number for when you turn manual priorities on.</BlaxCastes_WorkManualOff> <BlaxCastes_WorkManualOff>Manual priorities are off in the Work tab, so any number turns the work on. Members keep the number for when you turn manual priorities on.</BlaxCastes_WorkManualOff>
<BlaxCastes_WorkDlcOffNote>Kept for when its DLC is back: {LIST}. Until then the caste leaves that work alone.</BlaxCastes_WorkDlcOffNote>
<BlaxCastes_WorkDlcOffForget>Forget these</BlaxCastes_WorkDlcOffForget>
<BlaxCastes_WorkDlcOffForgetTip>Removes these work types from the caste, for when you will not turn their DLC on again. Members keep their work as it is.</BlaxCastes_WorkDlcOffForgetTip>
<!-- Caste column in the Assign, Schedule and Work tabs --> <!-- Caste column in the Assign, Schedule and Work tabs -->
<BlaxCastes_ManageCastesButton>Manage castes</BlaxCastes_ManageCastesButton> <BlaxCastes_ManageCastesButton>Manage castes</BlaxCastes_ManageCastesButton>
<BlaxCastes_ManageCastesButtonTip>Make castes and choose the policies, schedule and work priorities each one sets.</BlaxCastes_ManageCastesButtonTip> <BlaxCastes_ManageCastesButtonTip>Make castes and choose the policies, schedule and work priorities each one sets.</BlaxCastes_ManageCastesButtonTip>
<BlaxCastes_JoinDefaultsButton>Defaults</BlaxCastes_JoinDefaultsButton> <BlaxCastes_JoinDefaultsButton>Defaults</BlaxCastes_JoinDefaultsButton>
<BlaxCastes_JoinDefaultsButtonTip>Choose the caste a pawn joins when it is bought, recruited, enslaved or captured.</BlaxCastes_JoinDefaultsButtonTip> <BlaxCastes_JoinDefaultsButtonTip>Choose the caste a pawn joins when it is bought, recruited, enslaved or captured.</BlaxCastes_JoinDefaultsButtonTip>
<BlaxCastes_JoinDefaultsButtonTipNoIdeology>Choose the caste a pawn joins when it is bought, recruited or captured.</BlaxCastes_JoinDefaultsButtonTipNoIdeology>
<BlaxCastes_CellNone>None</BlaxCastes_CellNone> <BlaxCastes_CellNone>None</BlaxCastes_CellNone>
<BlaxCastes_CellNoneTip>Not in a caste.</BlaxCastes_CellNoneTip> <BlaxCastes_CellNoneTip>Not in a caste.</BlaxCastes_CellNoneTip>
<BlaxCastes_CellCastelessTip>No caste, set by hand. The pawn keeps its current policies.</BlaxCastes_CellCastelessTip> <BlaxCastes_CellCastelessTip>No caste, set by hand. The pawn keeps its current policies.</BlaxCastes_CellCastelessTip>

View File

@ -4,10 +4,10 @@
[![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com) [![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com)
[![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077) [![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077)
[![No DLC needed](https://img.shields.io/badge/DLC-not_needed-5a6b5d)](#features-10) [![Any DLC combination](https://img.shields.io/badge/DLC-any_combination-5a6b5d)](#dlc-support)
[![Status: 1.0 in progress](https://img.shields.io/badge/status-1.0_in_progress-CDCDCD)](docs/design.md) [![Status: 1.0 in progress](https://img.shields.io/badge/status-1.0_in_progress-CDCDCD)](docs/design.md)
RimWorld mod (1.7) by Blax Gaming: policy bundles and join defaults. Every slave you buy needs its apparel, food, drug and reading policy, its schedule and its work priorities set by hand. Blax Castes bundles those settings into castes such as Slave or Miner slave, and puts each pawn into the right caste the moment it joins or changes status. Needs Harmony. Works without DLCs; slaves need Ideology. RimWorld mod (1.7) by Blax Gaming: policy bundles and join defaults. Every slave you buy needs its apparel, food, drug and reading policy, its schedule and its work priorities set by hand. Blax Castes bundles those settings into castes such as Slave or Miner slave, and puts each pawn into the right caste the moment it joins or changes status. Needs Harmony. Works with any combination of DLCs, or none: see [DLC support](#dlc-support) for what each one adds.
Design and roadmap: `docs/design.md`. Design and roadmap: `docs/design.md`.
@ -15,26 +15,26 @@ Design and roadmap: `docs/design.md`.
- 📦 **Castes.** A caste manages up to eight slots: apparel, food, drug and reading policy, medical care, schedule, work priorities and, with [1001] Weapons Tab Reborn, the weapon loadout. Each slot is set or left alone. Putting a pawn in a caste writes every managed slot through the vanilla setters (and Weapons Tab Reborn's own API for the loadout). `Source/BlaxCastes/Caste.cs`, `CasteUtility.cs` - 📦 **Castes.** A caste manages up to eight slots: apparel, food, drug and reading policy, medical care, schedule, work priorities and, with [1001] Weapons Tab Reborn, the weapon loadout. Each slot is set or left alone. Putting a pawn in a caste writes every managed slot through the vanilla setters (and Weapons Tab Reborn's own API for the loadout). `Source/BlaxCastes/Caste.cs`, `CasteUtility.cs`
- ✅ **Per-slot checks.** Apparel, drugs, reading and the schedule need the pawn's tracker and skip quest lodgers, prisoners and mutants without policies; apparel also skips mutants that wear no apparel, and the schedule skips the mutants the Schedule tab leaves out. Food needs a configurable food tracker and skips babies and mutants without policies. Medical care needs player settings and a flesh pawn. Work priorities and the loadout are for colonists and slaves only. So a prisoner in a caste gets its food policy and medical care only. - ✅ **Per-slot checks.** Apparel, drugs, reading and the schedule need the pawn's tracker and skip quest lodgers, prisoners and mutants without policies; apparel also skips mutants that wear no apparel, and the schedule skips the mutants the Schedule tab leaves out. Food needs a configurable food tracker and skips babies and mutants without policies. Medical care needs player settings and a flesh pawn. Work priorities and the loadout are for colonists and slaves only. So a prisoner in a caste gets its food policy and medical care only.
- 🕒 **Schedule.** A caste can carry a full day: 24 hours of anything, work, recreation, sleep or meditate. The manager paints it like the vanilla Schedule tab: pick the activity with the vanilla selector, then click or drag over the hours. A drag paints only when it starts on the hours, so dragging the scrollbar past them never paints. "Copy from pawn" takes the schedule of one of your colonists or slaves, and "Leave alone" stops managing it. While the caste leaves the schedule alone, the first painted hour (or a copy) gives every member the whole day; the tooltips say so. A pawn whose whole day matches the caste follows every change; one hour changed by hand and the pawn keeps its own. An hour whose activity no longer exists (Meditate without Royalty, a removed mod) becomes Anything. `Source/BlaxCastes/ScheduleSlot.cs` - 🕒 **Schedule.** A caste can carry a full day: 24 hours of anything, work, recreation, sleep or meditate (Royalty). The manager paints it like the vanilla Schedule tab: pick the activity with the vanilla selector, then click or drag over the hours. A drag paints only when it starts on the hours, so dragging the scrollbar past them never paints. "Copy from pawn" takes the schedule of one of your colonists or slaves, and "Leave alone" stops managing it. While the caste leaves the schedule alone, the first painted hour (or a copy) gives every member the whole day; the tooltips say so. A pawn whose whole day matches the caste follows every change; one hour changed by hand and the pawn keeps its own. Meditate hours need Royalty: without it they act as Anything, the caste keeps them for when Royalty is back, and a note under the grid names them. An hour whose activity came from a removed mod becomes Anything. `Source/BlaxCastes/ScheduleSlot.cs`
- 🛠️ **Work priorities.** A caste sets only the work types you pick, each to 1, 2, 3, 4 or off; the rest stay as they are. So every caste can set Firefighting to 1, and a Field slave caste Growing 1 and Plant cutting 2. Work types a pawn cannot do are skipped. With manual priorities off, any number means on; Castes still stores the caste's number, so turning manual priorities on later leaves every member following its caste. "Start from nothing" turns every other work type off first, for castes that should do only their listed work; Patient and Bed rest stay as they are, because they are how a hurt or sick colonist or slave goes to bed. The Follow rule works per work type. The slot turns itself off while Work Tab, Free Will, Work Manager, AutoPriorities or WorkRoles is active, because those set priorities all the time. `Source/BlaxCastes/WorkSlot.cs` - 🛠️ **Work priorities.** A caste sets only the work types you pick, each to 1, 2, 3, 4 or off; the rest stay as they are. So every caste can set Firefighting to 1, and a Field slave caste Growing 1 and Plant cutting 2. Work types a pawn cannot do are skipped. With manual priorities off, any number means on; Castes still stores the caste's number, so turning manual priorities on later leaves every member following its caste. "Start from nothing" turns every other work type off first, for castes that should do only their listed work; Patient and Bed rest stay as they are, because they are how a hurt or sick colonist or slave goes to bed. The Follow rule works per work type. Childcare (Biotech), Dark study (Anomaly) and Fishing (Odyssey) are listed while their DLC is on; while it is off a caste keeps their priorities, skips them and names them in a note with a "Forget these" button for a DLC you dropped for good, "Start from nothing" turns no work off when only such types are listed, and "Apply to all members" hides when they are all the caste manages. The slot turns itself off while Work Tab, Free Will, Work Manager, AutoPriorities or WorkRoles is active, because those set priorities all the time. `Source/BlaxCastes/WorkSlot.cs`
- 🗡️ **Weapon loadout.** With [1001] Weapons Tab Reborn active, a caste can set the pawn's weapon loadout: a Guard caste the rifle loadout, a Slave caste the unarmed one. Without the mod the row is hidden. Castes calls the API Weapons Tab Reborn publishes for Better Pawn Control, found by reflection; if that API is missing or fails, the slot turns itself off with one warning in the log, and a call that fails never counts as a deleted loadout. In a save made without Weapons Tab Reborn, Castes creates the mod's loadout database the way the mod does, so the slot works at once. A loadout deleted in Weapons Tab Reborn becomes unmanaged in the caste, with one warning. `Source/BlaxCastes/WeaponsTab.cs` - 🗡️ **Weapon loadout.** With [1001] Weapons Tab Reborn active, a caste can set the pawn's weapon loadout: a Guard caste the rifle loadout, a Slave caste the unarmed one. Without the mod the row is hidden. Castes calls the API Weapons Tab Reborn publishes for Better Pawn Control, found by reflection; if that API is missing or fails, the slot turns itself off with one warning in the log, and a call that fails never counts as a deleted loadout. In a save made without Weapons Tab Reborn, Castes creates the mod's loadout database the way the mod does, so the slot works at once. A loadout deleted in Weapons Tab Reborn becomes unmanaged in the caste, with one warning. `Source/BlaxCastes/WeaponsTab.cs`
- 🔗 **Members follow their caste.** Change a caste's slot and every member still on the old value gets the new one. Members you changed by hand keep theirs. A slot that was left alone and becomes managed reaches every member; a slot that stops being managed changes nobody. Edits inside a policy (the Slave outfit's filter) reach members through the vanilla reference. `Source/BlaxCastes/CasteManager.cs` - 🔗 **Members follow their caste.** Change a caste's slot and every member still on the old value gets the new one. Members you changed by hand keep theirs. A slot that was left alone and becomes managed reaches every member; a slot that stops being managed changes nobody. Edits inside a policy (the Slave outfit's filter) reach members through the vanilla reference. `Source/BlaxCastes/CasteManager.cs`
- 🌱 **Starter castes.** A new game starts with three castes, already picked in the join defaults: Colonist (your current default apparel, food, drug and reading policy, medical care left alone), Slave (the Slave outfit, Simple food, No drugs; reading and medical care left alone) and Prisoner (Simple food). Bought and new colonists use Default caste, which is Colonist; bought and new slaves use Slave; new prisoners use Prisoner. The starting colonists go into Colonist, so their policies do not change. Policies are found by their starting names (No drugs by its source def); one that was renamed or deleted leaves its slot alone. Without Ideology there is no Slave caste and the slave rows stay at No caste. A save without castes gets the starter castes once, on load, with one message (it points to the mod settings while the Caste column is off); nobody moves until you click "Assign by status", which gives each pawn its caste's policies in place of its own. `Source/BlaxCastes/StarterCastes.cs` - 🌱 **Starter castes.** A new game starts with three castes, already picked in the join defaults: Colonist (your current default apparel, food, drug and reading policy, medical care left alone), Slave (the Slave outfit, Simple food, No drugs; reading and medical care left alone) and Prisoner (Simple food). Bought and new colonists use Default caste, which is Colonist; bought and new slaves use Slave; new prisoners use Prisoner. The starting colonists go into Colonist, so their policies do not change. Policies are found by their starting names (No drugs by its source def); one that was renamed or deleted leaves its slot alone. Without Ideology there is no Slave caste and the slave rows stay at No caste; the settings say so under the starter castes option. A save started without Ideology gets the Slave caste on its first load with Ideology, wired to the slave rows that are still at No caste, with one message; such a save has no Slave outfit (the game makes it only in a new game with Ideology), so Castes makes one for that caste, the only policy it creates without a click. A save without castes gets the starter castes once, on load, with one message (it points to the mod settings while the Caste column is off); nobody moves until you click "Assign by status", which gives each pawn its caste's policies in place of its own. `Source/BlaxCastes/StarterCastes.cs`
- 🗂️ **Caste manager.** Assign tab > "Manage castes" above the Caste column. It is the vanilla policy manager: the caste list with new, duplicate, rename, delete and make default on the left, and on the right a scrolling list of the slots: one row per policy with a "managed" checkbox, a dropdown and a pencil that opens the vanilla editor for that policy, the weapon loadout row while Weapons Tab Reborn is active, the schedule grid and a cycle button per work type (leave alone, 1, 2, 3, 4, off) with "Start from nothing". Clicking a cycle button several times in a row moves only the members that followed the work type before the first click, so a pawn you set by hand to a value the cycle passes through keeps it; pawns "Assign by status" puts into the caste in between start on the caste's value and follow the next clicks too. Ticking a slot starts it at the game's default policy (or the colonist default medical care, or Weapons Tab Reborn's default loadout). The work priorities are greyed out, with a note, while the setting is off or an automatic work manager is active. Below the slots: the member count and "Apply to all members", which asks first, naming the count, and then sets every managed slot on every member, hand changes included. Next to the close button, "Assign by status (N)" shows while pawns without a caste exist: it asks first, because it replaces those pawns' own policies with their caste's, then puts each into the caste of its new colonist, new slave or new prisoner row, and skips pawns you set to No caste. "Make default" explains the default caste in its tooltip. When the game has no Slave outfit, a "Create Slave outfit" button makes one. A caste using the Slave outfit warns that it has no cold protection. Deleting a caste leaves its members casteless on their current policies, and join rows that pointed at it fall back to No caste. `Source/BlaxCastes/Dialog_ManageCastes.cs` - 🗂️ **Caste manager.** Assign tab > "Manage castes" above the Caste column. It is the vanilla policy manager: the caste list with new, duplicate, rename, delete and make default on the left, and on the right a scrolling list of the slots: one row per policy with a "managed" checkbox, a dropdown and a pencil that opens the vanilla editor for that policy, the weapon loadout row while Weapons Tab Reborn is active, the schedule grid and a cycle button per work type (leave alone, 1, 2, 3, 4, off) with "Start from nothing". Clicking a cycle button several times in a row moves only the members that followed the work type before the first click, so a pawn you set by hand to a value the cycle passes through keeps it; pawns "Assign by status" puts into the caste in between start on the caste's value and follow the next clicks too. Ticking a slot starts it at the game's default policy (or the colonist default medical care, or Weapons Tab Reborn's default loadout). The work priorities are greyed out, with a note, while the setting is off or an automatic work manager is active. Below the slots: the member count and "Apply to all members", which asks first, naming the count, and then sets every managed slot on every member, hand changes included. Next to the close button, "Assign by status (N)" shows while pawns without a caste exist: it asks first, because it replaces those pawns' own policies with their caste's, then puts each into the caste of its new colonist, new slave or new prisoner row, and skips pawns you set to No caste. "Make default" explains the default caste in its tooltip. When the game has no Slave outfit, a "Create Slave outfit" button makes one. A caste using the Slave outfit warns that it has no cold protection. Deleting a caste leaves its members casteless on their current policies, and join rows that pointed at it fall back to No caste. `Source/BlaxCastes/Dialog_ManageCastes.cs`
- 📋 **Caste column.** A Caste column in the Assign tab, left of hostility, medical care and the policy columns; the same column sits right of the timetable in the Schedule tab (clear of the tab's activity selector) and left of the work columns in the Work tab. In the Work tab only "Manage castes" sits above it, so the header keeps the work columns' height. Click a cell for the menu (No caste, every caste, Reset to caste, Edit caste), or drag down the column to give several pawns the same caste; pawns already in that caste keep their hand changes while you drag. The cell shows the caste, the caste with "*" when one of the pawn's managed slots differs (the tooltip names each slot with both values; for the schedule it says "Schedule", for work priorities it names each work type that differs), "No caste" when you took the pawn out by hand or its caste was deleted, "None" when it is not in a caste, "(pending)" while a join will change its caste on the next tick, and "Unchangeable" for quest lodgers. The first click on the header sorts by caste, pawns without one last; the second click reverses it. `Source/BlaxCastes/PawnColumnWorker_BlaxCaste.cs`, `CasteColumns.cs`, `Patches/BlaxCastes_Assign.xml`, `Patches/BlaxCastes_ScheduleWork.xml` - 📋 **Caste column.** A Caste column in the Assign tab, left of hostility, medical care and the policy columns; the same column sits right of the timetable in the Schedule tab (clear of the tab's activity selector) and left of the work columns in the Work tab. In the Work tab only "Manage castes" sits above it, so the header keeps the work columns' height. Click a cell for the menu (No caste, every caste, Reset to caste, Edit caste), or drag down the column to give several pawns the same caste; pawns already in that caste keep their hand changes while you drag. The cell shows the caste, the caste with "*" when one of the pawn's managed slots differs (the tooltip names each slot with both values; for the schedule it says "Schedule", for work priorities it names each work type that differs), "No caste" when you took the pawn out by hand or its caste was deleted, "None" when it is not in a caste, "(pending)" while a join will change its caste on the next tick, and "Unchangeable" for quest lodgers. The first click on the header sorts by caste, pawns without one last; the second click reverses it. `Source/BlaxCastes/PawnColumnWorker_BlaxCaste.cs`, `CasteColumns.cs`, `Patches/BlaxCastes_Assign.xml`, `Patches/BlaxCastes_ScheduleWork.xml`
- 🚪 **Join defaults and status changes.** Assign tab > "Defaults" above the Caste column. Five rows pick a caste for bought as slave, bought as colonist, new colonist, new slave and new prisoner: No caste, Default caste (the one marked default in the manager) or a specific caste. Without Ideology the two slave rows are hidden. `Source/BlaxCastes/JoinDefaults.cs`, `Dialog_JoinDefaults.cs` - 🚪 **Join defaults and status changes.** Assign tab > "Defaults" above the Caste column. Five rows pick a caste for bought as slave, bought as colonist, new colonist, new slave and new prisoner: No caste, Default caste (the one marked default in the manager) or a specific caste. The two slave rows need Ideology: without it they are hidden, unless a save made with Ideology still has slaves or a slave row picks a caste; then they show with a "Needs Ideology" note. `Source/BlaxCastes/JoinDefaults.cs`, `Dialog_JoinDefaults.cs`
- Buying a pawn from a trader uses the bought rows; the pawn's final status picks slave or colonist. Every other change between colonist, slave and prisoner goes by the final status: recruiting, freeing a slave and releasing an arrested colonist to new colonist; enslaving and returned runaways to new slave; capturing, quest prisoners, arresting a colonist and imprisoning a slave to new prisoner. - Buying a pawn from a trader uses the bought rows; the pawn's final status picks slave or colonist. Every other change between colonist, slave and prisoner goes by the final status: recruiting, freeing a slave and releasing an arrested colonist to new colonist; enslaving and returned runaways to new slave; capturing, quest prisoners, arresting a colonist and imprisoning a slave to new prisoner.
- Castes applies a join one tick after it happens, after the game's own status-change resets, so its choice wins over mods that set policies in the same call. A bought slave arrives with its caste's outfit and food policy already set, and a message names the caste. - Castes applies a join one tick after it happens, after the game's own status-change resets, so its choice wins over mods that set policies in the same call. A bought slave arrives with its caste's outfit and food policy already set, and a message names the caste.
- A caste you pick by hand before the join is applied wins over the row. A pawn sold or released before then is dropped. - A caste you pick by hand before the join is applied wins over the row. A pawn sold or released before then is dropped.
- A No caste row takes a pawn out of a caste a join row had put it in; a caste you picked by hand stays. With "Reset policies" on, the policies it still has from that caste go back to the game defaults (medical care to the game's default for its status, if the caste set it); policies you changed by hand stay. The same happens when a row moves a pawn on from a row-set caste to a caste that leaves some of those policies alone, so a recruited prisoner does not keep the prisoner food. The schedule, work priorities and loadout have no game default and stay as they are. - A No caste row takes a pawn out of a caste a join row had put it in; a caste you picked by hand stays. With "Reset policies" on, the policies it still has from that caste go back to the game defaults (medical care to the game's default for its status, if the caste set it); policies you changed by hand stay. The same happens when a row moves a pawn on from a row-set caste to a caste that leaves some of those policies alone, so a recruited prisoner does not keep the prisoner food. The schedule, work priorities and loadout have no game default and stay as they are.
- Babies, quest lodgers and mutants without policies are skipped. - Babies (Biotech), quest lodgers and mutants without policies (Anomaly) are skipped. A mutant whose def is gone (a save made with Anomaly, loaded without it) is left alone.
- ↩️ **The old caste comes back.** When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste, if you set that) and its own settings from just before the change. If it comes back within 60 days (a setting) with the same status, it gets that caste back instead of its row's: an arrested Miner who is released is a Miner again, a Miner slave you sell and buy back is a Miner slave again, and a pawn you set to No caste is back at No caste. It keeps what you had changed by hand: settings that followed the caste get the caste's current value, settings you had changed get your value back, and a setting the caste started managing while it was away (a schedule, a work type) gets the caste's value, as it did for every member. A policy you deleted in the meantime is skipped, even if a new policy got its number. What the caste it had while it was away set (the prisoner caste's food) goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row. Records are saved with the game, keyed by the pawn's ID, and dropped when they are older than the setting or their caste is deleted. - ↩️ **The old caste comes back.** When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste, if you set that) and its own settings from just before the change. If it comes back within 60 days (a setting) with the same status, it gets that caste back instead of its row's: an arrested Miner who is released is a Miner again, a Miner slave you sell and buy back is a Miner slave again, and a pawn you set to No caste is back at No caste. It keeps what you had changed by hand: settings that followed the caste get the caste's current value, settings you had changed get your value back, and a setting the caste started managing while it was away (a schedule, a work type) gets the caste's value, as it did for every member. A policy you deleted in the meantime is skipped, even if a new policy got its number. What the caste it had while it was away set (the prisoner caste's food) goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row. Records are saved with the game, keyed by the pawn's ID, and dropped when they are older than the setting or their caste is deleted.
- 👋 **Leaving.** A pawn that leaves your faction (sold, released, gone to another faction) leaves its caste on the next tick, and a check every 2500 ticks catches the rest. Its policies stay as they are. Leaving the map counts by where the pawn ends up: a freed slave from another faction that walks off, an escaped slave or prisoner, or a pawn left on a map that closes leaves its caste (a slave with its slave caste remembered), and nothing joins a caste on the way out. A pawn that leaves in a caravan, a transport pod or a shuttle, or is kidnapped, is still yours and keeps its caste. - 👋 **Leaving.** A pawn that leaves your faction (sold, released, gone to another faction) leaves its caste on the next tick, and a check every 2500 ticks catches the rest. Its policies stay as they are. Leaving the map counts by where the pawn ends up: a freed slave from another faction that walks off, an escaped slave or prisoner, a pawn left on a map that closes, or a prisoner a gravship leaves behind (Odyssey), leaves its caste (a slave with its slave caste remembered), and nothing joins a caste on the way out. A pawn that leaves in a caravan, a transport pod or a shuttle, or is kidnapped, is still yours and keeps its caste.
- ⚠️ **Overlap warnings.** If Better Pawn Control, Better Pawn Control Forked, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active, the settings page names it and what it sets, and one message per save suggests turning those options off. Castes still wins, because it applies a tick later. Detection only; Castes patches none of them. `Source/BlaxCastes/OverlapWarnings.cs`, `Compat.cs` - ⚠️ **Overlap warnings.** If Better Pawn Control, Better Pawn Control Forked, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active, the settings page names it and what it sets, and one message per save suggests turning those options off. Castes still wins, because it applies a tick later. Detection only; Castes patches none of them. `Source/BlaxCastes/OverlapWarnings.cs`, `Compat.cs`
- 💬 **First load.** A new game, or the first load of a save that already has castes, posts one message that points to Assign > Manage castes. While the game runs without the Caste column it waits; a change to the column setting counts after the restart it needs, for this message and the starter castes message. - 💬 **First load.** A new game, or the first load of a save that already has castes, posts one message that points to Assign > Manage castes. While the game runs without the Caste column it waits; a change to the column setting counts after the restart it needs, for this message and the starter castes message.
- ⚙️ **Settings.** `enabled` (off: castes never write a policy, schedule, work priority or loadout; castes and memberships stay in the save), `manageWorkPriorities`, `manageWeaponLoadout` (shown while Weapons Tab Reborn is active), `enableJoinDefaults`, `joinMessages`, `revertOnLeave` ("Reset policies a caste set when a join moves the pawn on"; only governs that revert), `returnToPreviousCaste` and `formerCasteDays` (60), `seedStarterCastes`, `warnOverlaps`, `showAssignColumn` (the Caste column in the Assign, Schedule and Work tabs; needs a restart). All toggles are on by default. While a game is loaded, the settings page also has "Manage castes" and "Join defaults" buttons, the way in while the column is off. `Source/BlaxCastes/BlaxCastesMod.cs` - ⚙️ **Settings.** `enabled` (off: castes never write a policy, schedule, work priority or loadout; castes and memberships stay in the save), `manageWorkPriorities`, `manageWeaponLoadout` (shown while Weapons Tab Reborn is active), `enableJoinDefaults`, `joinMessages`, `revertOnLeave` ("Reset policies a caste set when a join moves the pawn on"; only governs that revert), `returnToPreviousCaste` and `formerCasteDays` (60), `seedStarterCastes`, `warnOverlaps`, `showAssignColumn` (the Caste column in the Assign, Schedule and Work tabs; needs a restart). All toggles are on by default. While a game is loaded, the settings page also has "Manage castes" and "Join defaults" buttons, the way in while the column is off. `Source/BlaxCastes/BlaxCastesMod.cs`
💾 Save safety: all state lives in one game component (`GameComponent_BlaxCastes`), nothing is stored on vanilla objects, and the only vanilla data Castes writes is each pawn's own policies, medical care, timetable and work priorities (and its Weapons Tab Reborn loadout, through that mod's API). Schedules and work priorities are saved as def names and loadouts as ids, never as references. Memberships drop pawns that are discarded or destroyed without being dead, on every save and after loading. A policy that left its database (a mod deleting it without `TryDelete`, or a delete in a vanilla editor opened from the manager) or a loadout Weapons Tab Reborn no longer has becomes unmanaged with one warning per caste; a schedule hour whose activity is gone becomes Anything, and a work type that is gone is dropped, each with one warning. Without Weapons Tab Reborn a caste keeps its loadout id for when the mod comes back. Joins waiting for the next tick are saved with the game. Former-caste records are keyed by the pawn's ID, not by reference; the pawn's own policies in a record are kept like a caste's, and a policy deleted since is dropped before the save, so loading never meets one it cannot find or mistakes a new policy with the same number and name for it. Adding the mod to a running save works. Removing it leaves every pawn on its last policies; the next load logs two red errors for the missing component ("Could not find class BlaxCastes.GameComponent_BlaxCastes" and "Can't load abstract class Verse.GameComponent"). They do no harm and go away once the game is saved again. 💾 Save safety: all state lives in one game component (`GameComponent_BlaxCastes`), nothing is stored on vanilla objects, and the only vanilla data Castes writes is each pawn's own policies, medical care, timetable and work priorities (and its Weapons Tab Reborn loadout, through that mod's API). Schedules and work priorities are saved as def names and loadouts as ids, never as references. Memberships drop pawns that are discarded or destroyed without being dead, on every save and after loading. A policy that left its database (a mod deleting it without `TryDelete`, or a delete in a vanilla editor opened from the manager) or a loadout Weapons Tab Reborn no longer has becomes unmanaged with one warning per caste; a schedule hour whose activity is gone becomes Anything, and a work type that is gone is dropped, each with one warning. Names from an official DLC that is off (Meditate, Childcare, Dark study, Fishing) are kept with no warning and skipped, and work again when the DLC is on again. Without Weapons Tab Reborn a caste keeps its loadout id for when the mod comes back. Joins waiting for the next tick are saved with the game. Former-caste records are keyed by the pawn's ID, not by reference; the pawn's own policies in a record are kept like a caste's, and a policy deleted since is dropped before the save, so loading never meets one it cannot find or mistakes a new policy with the same number and name for it. Adding the mod to a running save works. Removing it leaves every pawn on its last policies; the next load logs two red errors for the missing component ("Could not find class BlaxCastes.GameComponent_BlaxCastes" and "Can't load abstract class Verse.GameComponent"). They do no harm and go away once the game is saved again.
Replaces: Automatic Slave Outfit and PrisonerDefaults, the join, schedule and work defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults, the joiner work priorities of Plug and Play Joiner, and partly Save My Settings (clothing and food presets per pawn). Replaces: Automatic Slave Outfit and PrisonerDefaults, the join, schedule and work defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults, the joiner work priorities of Plug and Play Joiner, and partly Save My Settings (clothing and food presets per pawn).
@ -50,6 +50,36 @@ Compat:
Not supported yet: multiplayer, animal castes. A caste button on selected pawns comes in 1.1. Not supported yet: multiplayer, animal castes. A caste button on selected pawns comes in 1.1.
## DLC support
Blax Castes works with any combination of DLCs, or with the core game alone, so nobody is left out. About.xml lists no DLC. When a DLC is turned off for a save, Castes keeps what it stored from that DLC (Meditate hours, Childcare, Dark study and Fishing priorities) and uses it again once the DLC is back. Removing a DLC from a running save can still make the game itself log errors or drop content. A feature that needs a DLC switches off without it, and everything else keeps working.
| Feature | Needs | Without it |
|---|---|---|
| Castes, caste manager, Caste column, members follow, Apply to all members, Assign by status | Nothing | Same |
| Apparel, food, drug and reading policy, medical care | Nothing | Same |
| Schedule slot | Nothing | Four brushes instead of five |
| Meditate hours | Royalty | No Meditate brush. Saved Meditate hours act as Anything and come back with Royalty; painting them over drops them |
| Work priorities slot, Start from nothing | Nothing | Same |
| Childcare priority | Biotech | Not listed. A saved priority is kept and skipped; "Forget these" drops it |
| Dark study priority | Anomaly | Same as Childcare |
| Fishing priority | Odyssey | Same as Childcare |
| Weapon loadout slot | [1001] Weapons Tab Reborn (a mod, not a DLC) | Row hidden, the saved loadout id is kept |
| Starter Colonist and Prisoner castes and their join rows | Nothing | Same |
| Starter Slave caste, Create Slave outfit, the cold protection note | Ideology | Not created. A save gets the Slave caste, and the Slave outfit if it has none, on its first load with Ideology |
| Join rows: bought as colonist, new colonist, new prisoner | Nothing | Same |
| Join rows: bought as slave, new slave | Ideology | Hidden, or shown with a "Needs Ideology" note while a save made with Ideology still has slaves |
| Status changes: buying, recruiting, arresting, releasing, capturing | Nothing | Same |
| Status changes: enslaving, freeing, imprisoning a slave, returned runaways, a slave sold and bought back | Ideology | Cannot happen |
| The old caste comes back | Nothing | Works for colonists |
| Leaving: sold, released, map exit, closing map; caravans, pods, shuttles and kidnapping keep the caste | Nothing | Same |
| A prisoner a gravship leaves behind leaves its caste | Odyssey | Cannot happen |
| Babies skipped | Biotech | No babies exist |
| Mutants without policies or apparel skipped | Anomaly | No mutants exist. A mutant whose def is gone is left alone |
| Overlap warnings, settings, messages | Nothing | Without Ideology the settings say that slaves need it |
Anomaly and Odyssey are not installed on the test machine, so their parts are checked against the 1.7 game code rather than in a test run.
## Development ## Development
The repo is the mod folder. Link it into the game with a directory junction, run from the repo root (adjust the RimWorld path); `Tests/run-tests.ps1` creates it if it is missing: The repo is the mod folder. Link it into the game with a directory junction, run from the repo root (adjust the RimWorld path); `Tests/run-tests.ps1` creates it if it is missing:
@ -70,7 +100,7 @@ RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Lud
- `Assembly-CSharp.dll` and `UnityStubs.dll` (Rect, Color...) sit in the install root, and target `net10.0`. - `Assembly-CSharp.dll` and `UnityStubs.dll` (Rect, Color...) sit in the install root, and target `net10.0`.
- Harmony for 1.7 is the Harmony mod's `1.7/Assemblies/0Harmony.dll` (Workshop 2009463077). Reference it, don't ship it. Parameterless `PatchAll()` is obsolete in Harmony 3. - Harmony for 1.7 is the Harmony mod's `1.7/Assemblies/0Harmony.dll` (Workshop 2009463077). Reference it, don't ship it. Parameterless `PatchAll()` is obsolete in Harmony 3.
- Patches are applied from a `[StaticConstructorOnStartup]` class, one class at a time, so one broken target can't disable the rest. Check `Player.log` for `[Blax Castes] 5 patches applied` (the join hooks on `Pawn.SetFaction`, `Pawn_GuestTracker.SetGuestStatus` and `Pawn.PreTraded`, and the leaving hooks on `Pawn.ExitMap` and `MapDeiniter.PassPawnsToWorld`). - Patches are applied from a `[StaticConstructorOnStartup]` class, one class at a time, so one broken target can't disable the rest. Check `Player.log` for `[Blax Castes] 6 patches applied` (the join hooks on `Pawn.SetFaction`, `Pawn_GuestTracker.SetGuestStatus` and `Pawn.PreTraded`, and the leaving hooks on `Pawn.ExitMap`, `MapDeiniter.PassPawnsToWorld` and `GravshipUtility.AbandonMap`). Every target is in the core game, so all six apply with any DLC set.
Every change to castes, memberships, join rows and the default caste goes through `CasteManager`, so the sync rules and the `enabled` switch hold whichever window or hook made the change. Every change to castes, memberships, join rows and the default caste goes through `CasteManager`, so the sync rules and the `enabled` switch hold whichever window or hook made the change.
@ -94,16 +124,16 @@ If PowerShell blocks scripts, run it as `powershell -ExecutionPolicy Bypass -Fil
- `-Compat` also loads Blax Slaves and the installed mods Castes is tested next to (Hospitality, Custom Prisoner Interactions, Prisoner Realism, Weapons Tab Reborn), in the load order Castes, then Slaves. Trade as Slave or Colonist stays out, so the buy-mode test drives Blax Slaves' own buy mode. The loadout tests run only here; without Weapons Tab Reborn they skip, and one test checks the slot stays off. - `-Compat` also loads Blax Slaves and the installed mods Castes is tested next to (Hospitality, Custom Prisoner Interactions, Prisoner Realism, Weapons Tab Reborn), in the load order Castes, then Slaves. Trade as Slave or Colonist stays out, so the buy-mode test drives Blax Slaves' own buy mode. The loadout tests run only here; without Weapons Tab Reborn they skip, and one test checks the slot stays off.
- `-Tasoc` adds Trade as Slave or Colonist; Blax Slaves' buy mode stands down for it, and the buy-mode test drives that mod instead. - `-Tasoc` adds Trade as Slave or Colonist; Blax Slaves' buy mode stands down for it, and the buy-mode test drives that mod instead.
- `-NoDlc` runs on the core game alone; `-Dlc Royalty,Biotech` loads only the named installed DLCs. Every installed DLC is still listed as known, so the game does not switch a left-out one on. - `-NoDlc` runs on the core game alone; `-Dlc Royalty,Biotech` loads only the named installed DLCs. Every installed DLC is still listed as known, so the game does not switch a left-out one on. Run the suite without a switch, with `-NoDlc` and with each DLC left out before a release.
- `-NoBuild` skips the build. - `-NoBuild` skips the build.
The mods whose join defaults overlap with Castes (Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit, PrisonerDefaults) and the automatic work managers are not installed on the test machine. Their package ids were read from each mod's About.xml in its public source repository (listed in `Source/BlaxCastes/Compat.cs`), and the overlap and work manager tests inject an id into the detection list. The mods whose join defaults overlap with Castes (Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit, PrisonerDefaults) and the automatic work managers are not installed on the test machine. Their package ids were read from each mod's About.xml in its public source repository (listed in `Source/BlaxCastes/Compat.cs`), and the overlap and work manager tests inject an id into the detection list.
A test fails when Blax Castes logs an error, or when an error's stack passes through the mod or the test code. Errors another mod logs from its own code while a test ticks the game are listed as `LOGERR` lines instead; the harness keeps a short list of them (`KnownForeignErrors` in `Harness.cs`). Today that is Weapons Tab Reborn's "tried to equip loadout" error, which it logs once for the first pawn of another faction that thinks. A test fails when Blax Castes logs an error, or when an error's stack passes through the mod or the test code. It also fails on any `[Blax Castes]` warning it did not declare with `T.ExpectWarning` (must be logged) or `T.AllowWarning` (may be logged), and the startup test fails on any Blax Castes warning, so a missing DLC def or a failed patch shows up in every DLC set. Errors another mod logs from its own code while a test ticks the game are listed as `LOGERR` lines instead; the harness keeps a short list of them (`KnownForeignErrors` in `Harness.cs`). Today that is Weapons Tab Reborn's "tried to equip loadout" error, which it logs once for the first pawn of another faction that thinks.
Only one run at a time: a lock file in the data folder holds the running script's process id, and a lock left by a dead process is taken over. `Mods\BlaxCastes` must be a junction to this repo; the script creates it if missing and stops if a real folder is in the way. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` and `game.err.log` in the data folder). Only one run at a time: a lock file in the data folder holds the running script's process id, and a lock left by a dead process is taken over. `Mods\BlaxCastes` must be a junction to this repo; the script creates it if missing and stops if a real folder is in the way. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` and `game.err.log` in the data folder).
Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for colonists, prisoners, slaves, quest lodgers, babies, castes, policies, ticks and queued joins. Phase 2 runs after the save and reload; carry ids through `T.Carry`, or `T.CarryAtSave` for values later phase-1 tests may still change. Without Ideology the slave tests skip; without Biotech the baby tests skip. The buy-mode compat test needs `-Compat` or `-Tasoc`, the loadout tests `-Compat`. Headless runs have no GUI, so the tests drive the logic behind the windows and the column; drawing is checked by hand. Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for colonists, prisoners, slaves, quest lodgers, babies, castes, policies, ticks and queued joins. Phase 2 runs after the save and reload; carry ids through `T.Carry`, or `T.CarryAtSave` for values later phase-1 tests may still change. A test that needs a DLC skips with "needs Ideology" (slaves) or "needs Biotech" (babies) after its core part; the DLC-off side has its own tests in `DlcTests.cs`. The buy-mode compat test needs `-Compat` or `-Tasoc`, the loadout tests `-Compat`. Headless runs have no GUI, so the tests drive the logic behind the windows and the column; drawing is checked by hand.
Useful 1.7 switches for manual runs: `-quicktest` (straight into a generated colony), `-headless`, `-savedatafolder=<dir>`, `-QuitAfterBoot`, `-NoFileLog`. Useful 1.7 switches for manual runs: `-quicktest` (straight into a generated colony), `-headless`, `-savedatafolder=<dir>`, `-QuitAfterBoot`, `-NoFileLog`.

View File

@ -124,17 +124,24 @@ namespace BlaxCastes
l.CheckboxLabeled("BlaxCastes_SettingWeaponLoadout".Translate(), ref s.manageWeaponLoadout, "BlaxCastes_SettingWeaponLoadoutTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingWeaponLoadout".Translate(), ref s.manageWeaponLoadout, "BlaxCastes_SettingWeaponLoadoutTip".Translate());
l.GapLine(); l.GapLine();
l.CheckboxLabeled("BlaxCastes_SettingJoinDefaults".Translate(), ref s.enableJoinDefaults, "BlaxCastes_SettingJoinDefaultsTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingJoinDefaults".Translate(), ref s.enableJoinDefaults, DlcSupport.IdeologyKey("BlaxCastes_SettingJoinDefaultsTip").Translate());
l.CheckboxLabeled("BlaxCastes_SettingJoinMessages".Translate(), ref s.joinMessages, "BlaxCastes_SettingJoinMessagesTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingJoinMessages".Translate(), ref s.joinMessages, "BlaxCastes_SettingJoinMessagesTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingRevertOnLeave".Translate(), ref s.revertOnLeave, "BlaxCastes_SettingRevertOnLeaveTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingRevertOnLeave".Translate(), ref s.revertOnLeave, "BlaxCastes_SettingRevertOnLeaveTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingReturnToPrevious".Translate(), ref s.returnToPreviousCaste, "BlaxCastes_SettingReturnToPreviousTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingReturnToPrevious".Translate(), ref s.returnToPreviousCaste, DlcSupport.IdeologyKey("BlaxCastes_SettingReturnToPreviousTip").Translate());
if (s.returnToPreviousCaste) if (s.returnToPreviousCaste)
{ {
s.formerCasteDays = Mathf.RoundToInt(l.SliderLabeled("BlaxCastes_SettingFormerCasteDays".Translate(s.formerCasteDays), s.formerCasteDays = Mathf.RoundToInt(l.SliderLabeled("BlaxCastes_SettingFormerCasteDays".Translate(s.formerCasteDays),
s.formerCasteDays, BlaxCastesSettings.MinFormerCasteDays, BlaxCastesSettings.MaxFormerCasteDays, 0.6f, s.formerCasteDays, BlaxCastesSettings.MinFormerCasteDays, BlaxCastesSettings.MaxFormerCasteDays, 0.6f,
"BlaxCastes_SettingFormerCasteDaysTip".Translate())); "BlaxCastes_SettingFormerCasteDaysTip".Translate()));
} }
l.CheckboxLabeled("BlaxCastes_SettingSeedStarter".Translate(), ref s.seedStarterCastes, "BlaxCastes_SettingSeedStarterTip".Translate()); l.CheckboxLabeled(DlcSupport.IdeologyKey("BlaxCastes_SettingSeedStarter").Translate(), ref s.seedStarterCastes,
DlcSupport.IdeologyKey("BlaxCastes_SettingSeedStarterTip").Translate());
string seedNote = SeedStarterNote();
if (seedNote != null)
{
using (new TextBlock(GameFont.Tiny, ColoredText.SubtleGrayColor))
l.Label(seedNote);
}
l.GapLine(); l.GapLine();
l.CheckboxLabeled("BlaxCastes_SettingWarnOverlaps".Translate(), ref s.warnOverlaps, "BlaxCastes_SettingWarnOverlapsTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingWarnOverlaps".Translate(), ref s.warnOverlaps, "BlaxCastes_SettingWarnOverlapsTip".Translate());
@ -157,7 +164,7 @@ namespace BlaxCastes
if (l.ButtonText("BlaxCastes_JoinDefaultsTitle".Translate())) if (l.ButtonText("BlaxCastes_JoinDefaultsTitle".Translate()))
Find.WindowStack.Add(new Dialog_JoinDefaults()); Find.WindowStack.Add(new Dialog_JoinDefaults());
} }
if (!ModsConfig.IdeologyActive) if (ShowsNoIdeologyNote)
{ {
l.GapLine(); l.GapLine();
l.Label("BlaxCastes_SettingNoIdeology".Translate()); l.Label("BlaxCastes_SettingNoIdeology".Translate());
@ -168,6 +175,15 @@ namespace BlaxCastes
s.Reset(); s.Reset();
l.End(); l.End();
} }
/// <summary>
/// Every setting works with any DLC combination, so none is greyed out. Without Ideology the settings
/// page says that slaves need it, and the starter castes setting names the part it leaves out.
/// </summary>
public static bool ShowsNoIdeologyNote => !ModsConfig.IdeologyActive;
/// <summary>The note under the starter castes setting: "Slave caste: needs Ideology" without it, otherwise null.</summary>
public static string SeedStarterNote() => ModsConfig.IdeologyActive ? null : (string)"BlaxCastes_SettingSeedStarterSlaveNote".Translate();
} }
/// <summary> /// <summary>

View File

@ -199,7 +199,8 @@ namespace BlaxCastes
if (schedule != null && schedule.Count != ScheduleSlot.Hours) if (schedule != null && schedule.Count != ScheduleSlot.Hours)
schedule = null; schedule = null;
loadoutId = CasteUtility.ToLoadoutId(loadoutId); loadoutId = CasteUtility.ToLoadoutId(loadoutId);
// Unknown time assignments and work types are fixed, with a warning, by CasteManager.CheckSlots. // Unknown time assignments and work types are fixed, with a warning, by CasteManager.CheckSlots;
// names of an official DLC that is off are kept for when it is back.
} }
} }

View File

@ -429,7 +429,8 @@ namespace BlaxCastes
/// Checks every caste's slots after a load, before a save and while the manager is open: a policy /// 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 /// 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 /// hour with an unknown time assignment becomes Anything, and a work type that no longer exists is
/// dropped. One warning per caste and problem. /// dropped. One warning per caste and problem. Names of an official DLC that is off are kept, with no
/// warning (see FixScheduleAndWork).
/// </summary> /// </summary>
internal static void CheckSlots(GameComponent_BlaxCastes comp) internal static void CheckSlots(GameComponent_BlaxCastes comp)
{ {
@ -475,24 +476,26 @@ namespace BlaxCastes
} }
/// <summary> /// <summary>
/// Schedule hours whose time assignment no longer exists (a removed mod, Meditate without Royalty) /// Schedule hours whose time assignment no longer exists (a removed mod) become Anything, and work
/// become Anything, and work types that no longer exist are dropped, each with one warning. /// types that no longer exist are dropped, each with one warning. Names of an official DLC that is off
/// (Meditate without Royalty, Childcare without Biotech) stay as they are, with no warning: they apply
/// as Anything or are skipped, and work again once the DLC is back.
/// </summary> /// </summary>
internal static void FixScheduleAndWork(Caste caste) internal static void FixScheduleAndWork(Caste caste)
{ {
if (caste == null) if (caste == null)
return; return;
IReadOnlyList<string> schedule = caste.Schedule; IReadOnlyList<string> schedule = caste.Schedule;
if (schedule != null && schedule.Any(n => !ScheduleSlot.IsKnown(n))) if (schedule != null && schedule.Any(n => !ScheduleSlot.IsKept(n)))
{ {
List<string> unknown = schedule.Where(n => !ScheduleSlot.IsKnown(n)).Distinct().ToList(); List<string> unknown = schedule.Where(n => !ScheduleSlot.IsKept(n)).Distinct().ToList();
caste.SetSlotRaw(CasteSlot.Schedule, schedule.ToList()); // Normalize turns unknown names into Anything caste.SetSlotRaw(CasteSlot.Schedule, schedule.ToList()); // Normalize turns unknown names into Anything
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": time assignment " + string.Join(", ", unknown) Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": time assignment " + string.Join(", ", unknown)
+ " no longer in the game. Those schedule hours are now Anything."); + " no longer in the game. Those schedule hours are now Anything.");
} }
if (caste.WorkPriorities.Keys.Any(k => WorkSlot.Resolve(k) == null)) if (caste.WorkPriorities.Keys.Any(k => WorkSlot.Resolve(k) == null && !WorkSlot.IsDlcOff(k)))
{ {
List<string> gone = caste.WorkPriorities.Keys.Where(k => WorkSlot.Resolve(k) == null).ToList(); List<string> gone = caste.WorkPriorities.Keys.Where(k => WorkSlot.Resolve(k) == null && !WorkSlot.IsDlcOff(k)).ToList();
var kept = caste.WorkPriorities.Where(kv => !gone.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value); var kept = caste.WorkPriorities.Where(kv => !gone.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
caste.SetSlotRaw(CasteSlot.Work, kept); caste.SetSlotRaw(CasteSlot.Work, kept);
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": work type " + string.Join(", ", gone) Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": work type " + string.Join(", ", gone)

View File

@ -36,7 +36,21 @@ namespace BlaxCastes
public static bool CanBeMember(Pawn pawn) => public static bool CanBeMember(Pawn pawn) =>
pawn != null && !GameComponent_BlaxCastes.IsGone(pawn) && pawn.RaceProps != null && pawn.RaceProps.Humanlike && IsPlayerSide(pawn); pawn != null && !GameComponent_BlaxCastes.IsGone(pawn) && pawn.RaceProps != null && pawn.RaceProps.Humanlike && IsPlayerSide(pawn);
private static bool PoliciesDisabled(Pawn pawn) => pawn.IsMutant && pawn.mutant.Def.disablePolicies; /// <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> /// <summary>Apparel, drug, reading and schedule: not a quest lodger, not a prisoner, no policy-less mutant.</summary>
private static bool CanTakeOwnPolicies(Pawn pawn) => private static bool CanTakeOwnPolicies(Pawn pawn) =>
@ -63,12 +77,12 @@ namespace BlaxCastes
/// <summary>Whether the slot can be written on this pawn right now.</summary> /// <summary>Whether the slot can be written on this pawn right now.</summary>
public static bool CanUse(Pawn pawn, CasteSlot slot) public static bool CanUse(Pawn pawn, CasteSlot slot)
{ {
if (pawn == null || (pawn.Destroyed && !pawn.Dead)) if (pawn == null || (pawn.Destroyed && !pawn.Dead) || IsMutantWithoutDef(pawn))
return false; return false;
switch (slot) switch (slot)
{ {
case CasteSlot.Apparel: case CasteSlot.Apparel:
return pawn.outfits != null && CanTakeOwnPolicies(pawn) && !(pawn.IsMutant && pawn.mutant.Def.disableApparel); return pawn.outfits != null && CanTakeOwnPolicies(pawn) && MutantDefFor(pawn)?.disableApparel != true;
case CasteSlot.Drug: case CasteSlot.Drug:
return pawn.drugs != null && CanTakeOwnPolicies(pawn); return pawn.drugs != null && CanTakeOwnPolicies(pawn);
case CasteSlot.Reading: case CasteSlot.Reading:
@ -80,7 +94,7 @@ namespace BlaxCastes
return pawn.playerSettings != null && pawn.RaceProps != null && pawn.RaceProps.IsFlesh; return pawn.playerSettings != null && pawn.RaceProps != null && pawn.RaceProps.IsFlesh;
case CasteSlot.Schedule: case CasteSlot.Schedule:
// Like the vanilla Schedule tab: a timetable, and not a subhuman mutant. // Like the vanilla Schedule tab: a timetable, and not a subhuman mutant.
return ScheduleSlot.HasTimetable(pawn) && CanTakeOwnPolicies(pawn) && !pawn.IsSubhuman; return ScheduleSlot.HasTimetable(pawn) && CanTakeOwnPolicies(pawn) && !IsSubhumanMutant(pawn);
case CasteSlot.Work: case CasteSlot.Work:
return WorkSlot.Active && WorkSlot.HasWorkSettings(pawn) && IsColonistOrSlave(pawn); return WorkSlot.Active && WorkSlot.HasWorkSettings(pawn) && IsColonistOrSlave(pawn);
case CasteSlot.Loadout: case CasteSlot.Loadout:

View File

@ -10,7 +10,8 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// The join defaults window, laid out like the vanilla medical defaults: a title, a short text, then /// The join defaults window, laid out like the vanilla medical defaults: a title, a short text, then
/// one row per way of joining with a label on the left and a caste picker on the right. Picks go /// one row per way of joining with a label on the left and a caste picker on the right. Picks go
/// through CasteManager.SetJoinRow. The slave rows are hidden without Ideology. /// through CasteManager.SetJoinRow. Without Ideology the slave rows are hidden, unless a save made with
/// Ideology still has slaves or a slave row picks a caste (ShowsSlaveRows).
/// </summary> /// </summary>
public class Dialog_JoinDefaults : Window public class Dialog_JoinDefaults : Window
{ {
@ -32,19 +33,41 @@ namespace BlaxCastes
public override string CloseButtonText => "OK".Translate(); public override string CloseButtonText => "OK".Translate();
/// <summary>The rows the window shows: all five with Ideology, without the slave rows otherwise.</summary> /// <summary>The rows the window shows: all five while it shows the slave rows (ShowsSlaveRows), the other three otherwise.</summary>
public static List<string> VisibleRows() public static List<string> VisibleRows()
{ {
bool slaves = ShowsSlaveRows();
var rows = new List<string>(); var rows = new List<string>();
foreach (string reason in JoinReason.Rows) foreach (string reason in JoinReason.Rows)
{ {
if (!ModsConfig.IdeologyActive && (reason == JoinReason.BoughtSlave || reason == JoinReason.NewSlave)) if (!slaves && IsSlaveRow(reason))
continue; continue;
rows.Add(reason); rows.Add(reason);
} }
return rows; return rows;
} }
public static bool IsSlaveRow(string reason) => reason == JoinReason.BoughtSlave || reason == JoinReason.NewSlave;
/// <summary>
/// The bought-as-slave and new-slave rows show with Ideology. Without it they show only while they still
/// matter: the colony has slaves (a save made with Ideology) or a slave row picks a caste. They then
/// carry a "Needs Ideology" note (SlaveRowsNote).
/// </summary>
public static bool ShowsSlaveRows()
{
if (ModsConfig.IdeologyActive)
return true;
GameComponent_BlaxCastes comp = GameComponent_BlaxCastes.Instance;
if (comp != null && JoinReason.Rows.Any(r => IsSlaveRow(r) && comp.GetRow(r).mode != JoinRowMode.NoCaste))
return true;
return Current.Game != null && PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction.Any(p => p.IsSlaveOfColony);
}
/// <summary>The note under the slave rows while they show without Ideology, or null.</summary>
public static string SlaveRowsNote() =>
!ModsConfig.IdeologyActive && ShowsSlaveRows() ? (string)"BlaxCastes_JoinSlaveRowsNoIdeology".Translate() : null;
public override void DoWindowContents(Rect inRect) public override void DoWindowContents(Rect inRect)
{ {
GameComponent_BlaxCastes comp = GameComponent_BlaxCastes.Instance; GameComponent_BlaxCastes comp = GameComponent_BlaxCastes.Instance;
@ -73,6 +96,12 @@ namespace BlaxCastes
foreach (string reason in VisibleRows()) foreach (string reason in VisibleRows())
DoRow(inRect, ref y, reason); DoRow(inRect, ref y, reason);
Text.Anchor = TextAnchor.UpperLeft; Text.Anchor = TextAnchor.UpperLeft;
string note = SlaveRowsNote();
if (note != null)
{
using (new TextBlock(GameFont.Tiny, ColoredText.SubtleGrayColor))
Widgets.Label(inRect, ref y, note);
}
} }
private static void DoRow(Rect inRect, ref float y, string reason) private static void DoRow(Rect inRect, ref float y, string reason)
@ -82,7 +111,7 @@ namespace BlaxCastes
var button = new Rect(inRect.xMax - ButtonWidth, y, ButtonWidth, RowHeight); var button = new Rect(inRect.xMax - ButtonWidth, y, ButtonWidth, RowHeight);
if (Mouse.IsOver(row)) if (Mouse.IsOver(row))
Widgets.DrawLightHighlight(row); Widgets.DrawLightHighlight(row);
TooltipHandler.TipRegionByKey(row, "BlaxCastes_RowTip_" + reason); TooltipHandler.TipRegionByKey(row, DlcSupport.IdeologyKey("BlaxCastes_RowTip_" + reason));
Widgets.LabelFit(label, ("BlaxCastes_Row_" + reason).Translate()); Widgets.LabelFit(label, ("BlaxCastes_Row_" + reason).Translate());
if (Widgets.ButtonText(button, RowButtonLabel(reason).Truncate(button.width - 12f))) if (Widgets.ButtonText(button, RowButtonLabel(reason).Truncate(button.width - 12f)))
Find.WindowStack.Add(new FloatMenu(RowMenu(reason))); Find.WindowStack.Add(new FloatMenu(RowMenu(reason)));

View File

@ -119,7 +119,18 @@ namespace BlaxCastes
Messages.Message("BlaxCastes_AssignByStatusDone".Translate(assigned), MessageTypeDefOf.NeutralEvent, historical: false); Messages.Message("BlaxCastes_AssignByStatusDone".Translate(assigned), MessageTypeDefOf.NeutralEvent, historical: false);
}, destructive: true)); }, destructive: true));
} }
TooltipHandler.TipRegion(button, "BlaxCastes_AssignByStatusTip".Translate(count)); TooltipHandler.TipRegion(button, AssignByStatusTipKey().Translate(count));
}
/// <summary>
/// The tooltip key of "Assign by status". Its Ideology-free variant names only the colonist and prisoner
/// rows, so it is used only while the slave rows are hidden (Dialog_JoinDefaults.ShowsSlaveRows): a save
/// made with Ideology that still has slaves puts them into the new-slave row's caste.
/// </summary>
public static string AssignByStatusTipKey()
{
const string key = "BlaxCastes_AssignByStatusTip";
return Dialog_JoinDefaults.ShowsSlaveRows() ? key : DlcSupport.IdeologyKey(key);
} }
/// <summary> /// <summary>
@ -226,7 +237,7 @@ namespace BlaxCastes
var label = new Rect(footer.x, footer.y, button.x - footer.x - Gap, footer.height); var label = new Rect(footer.x, footer.y, button.x - footer.x - Gap, footer.height);
using (new TextBlock(TextAnchor.MiddleLeft)) using (new TextBlock(TextAnchor.MiddleLeft))
Widgets.Label(label, "BlaxCastes_MemberCount".Translate(members.Count)); Widgets.Label(label, "BlaxCastes_MemberCount".Translate(members.Count));
if (members.Count == 0 || !caste.AnyManaged()) if (members.Count == 0 || !AppliesAnything(caste))
return; return;
if (Widgets.ButtonText(button, "BlaxCastes_ApplyToAll".Translate())) if (Widgets.ButtonText(button, "BlaxCastes_ApplyToAll".Translate()))
{ {
@ -243,6 +254,13 @@ namespace BlaxCastes
TooltipHandler.TipRegion(button, "BlaxCastes_ApplyToAllTip".Translate()); TooltipHandler.TipRegion(button, "BlaxCastes_ApplyToAllTip".Translate());
} }
/// <summary>
/// "Apply to all members" shows while the caste manages a slot that writes something. A work slot that
/// lists only work types of a DLC that is off writes nothing, so it does not count.
/// </summary>
public static bool AppliesAnything(Caste caste) =>
caste != null && CasteUtility.AllSlots.Any(slot => caste.IsManaged(slot) && !(slot == CasteSlot.Work && WorkSlot.AllDlcOff(caste.WorkPriorities)));
/// <summary>The confirm text for "Apply to all members", naming the caste and the member count.</summary> /// <summary>The confirm text for "Apply to all members", naming the caste and the member count.</summary>
public static string ApplyToAllConfirmText(Caste caste, int count) => public static string ApplyToAllConfirmText(Caste caste, int count) =>
"BlaxCastes_ApplyToAllConfirm".Translate(caste.label.Named("CASTE"), count.Named("COUNT")); "BlaxCastes_ApplyToAllConfirm".Translate(caste.label.Named("CASTE"), count.Named("COUNT"));
@ -465,7 +483,7 @@ namespace BlaxCastes
if (!Mouse.IsOver(cell)) if (!Mouse.IsOver(cell))
continue; continue;
Widgets.DrawBox(cell, 2); Widgets.DrawBox(cell, 2);
if (paint && brush != null && (def != brush || !managed)) if (paint && PaintsHour(caste, hour, brush))
{ {
PaintHour(caste, hour, brush); PaintHour(caste, hour, brush);
SoundDefOf.Designate_DragStandard_Changed_NoCam.PlayOneShotOnCamera(); SoundDefOf.Designate_DragStandard_Changed_NoCam.PlayOneShotOnCamera();
@ -482,7 +500,31 @@ namespace BlaxCastes
if (Widgets.ButtonText(leave, "BlaxCastes_Unmanaged".Translate(), active: managed) && managed) if (Widgets.ButtonText(leave, "BlaxCastes_Unmanaged".Translate(), active: managed) && managed)
CasteManager.SetSlot(caste, CasteSlot.Schedule, null); CasteManager.SetSlot(caste, CasteSlot.Schedule, null);
TooltipHandler.TipRegion(leave, "BlaxCastes_ScheduleLeaveAloneTip".Translate()); TooltipHandler.TipRegion(leave, "BlaxCastes_ScheduleLeaveAloneTip".Translate());
return y + SmallButtonHeight; y += SmallButtonHeight;
string note = ScheduleDlcNote(caste);
if (note != null)
y = DoNote(width, y + 4f, note, Color.gray);
return y;
}
/// <summary>
/// The note under the schedule grid while the caste has hours of a DLC that is off (Meditate without
/// Royalty): the grid draws them as Anything, and the caste keeps them for when the DLC is back. Null otherwise.
/// </summary>
public static string ScheduleDlcNote(Caste caste)
{
List<string> labels = ScheduleSlot.DlcOffLabels(caste?.Schedule);
return labels.Count == 0 ? null : (string)"BlaxCastes_ScheduleDlcOffNote".Translate(labels.ToCommaList(useAnd: true).Named("LIST"));
}
/// <summary>
/// The note under the work priorities while the caste lists work types of a DLC that is off (Childcare
/// without Biotech): they have no button, and the caste keeps them for when the DLC is back. Null otherwise.
/// </summary>
public static string WorkDlcNote(Caste caste)
{
List<string> labels = WorkSlot.DlcOffLabels(caste?.WorkPriorities);
return labels.Count == 0 ? null : (string)"BlaxCastes_WorkDlcOffNote".Translate(labels.ToCommaList(useAnd: true).Named("LIST"));
} }
/// <summary> /// <summary>
@ -543,6 +585,18 @@ namespace BlaxCastes
return caste == null || names == null ? 0 : CasteManager.SetSlot(caste, CasteSlot.Schedule, names); return caste == null || names == null ? 0 : CasteManager.SetSlot(caste, CasteSlot.Schedule, names);
} }
/// <summary>
/// Painting the hour with the brush changes the caste: it leaves the schedule alone, or the stored hour
/// differs from the brush. The stored name counts, not the cell's color, so the Anything brush replaces a
/// kept Meditate hour that shows as Anything without Royalty.
/// </summary>
public static bool PaintsHour(Caste caste, int hour, TimeAssignmentDef brush)
{
if (caste == null || brush == null || hour < 0 || hour >= ScheduleSlot.Hours)
return false;
return caste.Schedule == null || caste.Schedule[hour] != brush.defName;
}
/// <summary> /// <summary>
/// Paints one hour. A caste that left the schedule alone starts from the game's starting schedule. /// Paints one hour. A caste that left the schedule alone starts from the game's starting schedule.
/// Members follow, hour by hour. Returns how many moved. /// Members follow, hour by hour. Returns how many moved.
@ -611,7 +665,33 @@ namespace BlaxCastes
} }
} }
int rows = (types.Count + WorkColumns - 1) / WorkColumns; int rows = (types.Count + WorkColumns - 1) / WorkColumns;
return y + rows * WorkRowHeight; y += rows * WorkRowHeight;
string dlcNote = WorkDlcNote(caste);
if (dlcNote != null)
{
y = DoNote(width, y + 4f, dlcNote, Color.gray);
var forget = new Rect(ValueX, y, 150f, SmallButtonHeight);
if (Widgets.ButtonText(forget, "BlaxCastes_WorkDlcOffForget".Translate(), active: active) && active)
ForgetDlcOffWork(caste);
TooltipHandler.TipRegion(forget, "BlaxCastes_WorkDlcOffForgetTip".Translate());
y += SmallButtonHeight;
}
return y;
}
/// <summary>
/// "Forget these" under the work DLC note: drops the listed work types of a DLC that is off, for a player
/// who left that DLC for good. Members keep their work as it is. Returns how many types were dropped.
/// </summary>
public static int ForgetDlcOffWork(Caste caste)
{
if (caste == null)
return 0;
var kept = caste.WorkPriorities.Where(kv => !WorkSlot.IsDlcOff(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
int dropped = caste.WorkPriorities.Count - kept.Count;
if (dropped > 0)
CasteManager.SetSlot(caste, CasteSlot.Work, kept);
return dropped;
} }
/// <summary>The line under the work priorities heading, or null: setting off, a work manager, or manual priorities off.</summary> /// <summary>The line under the work priorities heading, or null: setting off, a work manager, or manual priorities off.</summary>

View File

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// Castes works with any combination of DLCs. This class answers two questions for that:
/// - Which official DLC a stored def name belongs to while that DLC is off. Such a def is not in the
/// game, so its DLC is read from the [MayRequire...] attribute of the vanilla DefOf field with its
/// name: TimeAssignmentDefOf.Meditate is Royalty, WorkTypeDefOf.Childcare Biotech, DarkStudy Anomaly
/// and Fishing Odyssey. A caste keeps those names without a warning, and they work again once the
/// DLC is back (a save made with the DLC, loaded without it). Names from a removed mod have no such
/// field and are still dropped with a warning.
/// - Which text to show without Ideology: keys that name slave events or the Slave caste have a
/// "NoIdeology" variant.
/// </summary>
public static class DlcSupport
{
private const string OfficialPrefix = "ludeon.rimworld.";
private static Dictionary<(Type, string), string> owners;
/// <summary>The package id (lower case) of the official DLC a vanilla DefOf field of this name and def type requires, or null.</summary>
public static string OwnerOf(Type defType, string defName)
{
if (defType == null || defName.NullOrEmpty())
return null;
owners ??= ReadOwners();
return owners.TryGetValue((defType, defName), out string id) ? id : null;
}
/// <summary>
/// The name of the official DLC the def needs ("Royalty"), while that DLC is off. Null when the DLC is
/// on, or when the def belongs to no DLC (the core game or a mod).
/// </summary>
public static string InactiveDlcFor(Type defType, string defName)
{
string id = OwnerOf(defType, defName);
return id == null || ModsConfig.IsActive(id) ? null : DlcName(id);
}
/// <summary>"ludeon.rimworld.royalty" to "Royalty".</summary>
public static string DlcName(string packageId)
{
if (packageId.NullOrEmpty())
return packageId;
string id = packageId.ToLowerInvariant();
return (id.StartsWith(OfficialPrefix) ? id.Substring(OfficialPrefix.Length) : id).CapitalizeFirst();
}
/// <summary>
/// The key's "NoIdeology" variant while Ideology is off and the variant exists. Used for texts that name
/// slave events (enslaved, freed) or the Slave caste, which cannot happen without Ideology. CanTranslate
/// asks the active language only, and Castes ships English only, so the default language counts too:
/// a game in another language shows the English variant rather than the text about slaves.
/// </summary>
public static string IdeologyKey(string key)
{
if (ModsConfig.IdeologyActive || key.NullOrEmpty())
return key;
string variant = key + "NoIdeology";
bool exists = variant.CanTranslate() || (LanguageDatabase.defaultLanguage?.HaveTextForKey(variant) ?? false);
return exists ? variant : key;
}
/// <summary>Every Def field of the vanilla DefOf classes that carries a MayRequire attribute for an official DLC.</summary>
private static Dictionary<(Type, string), string> ReadOwners()
{
var result = new Dictionary<(Type, string), string>();
Type[] types;
try
{
types = typeof(DefOf).Assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).ToArray();
}
foreach (Type type in types)
{
if (!type.IsDefined(typeof(DefOf), false))
continue;
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (!typeof(Def).IsAssignableFrom(field.FieldType))
continue;
string id = field.GetCustomAttribute<MayRequireAttribute>(inherit: true)?.modId?.ToLowerInvariant();
if (id != null && id.StartsWith(OfficialPrefix))
result[(field.FieldType, field.Name)] = id;
}
}
return result;
}
}
}

View File

@ -26,6 +26,7 @@ namespace BlaxCastes
private Dictionary<string, FormerCaste> formerCastes = new Dictionary<string, FormerCaste>(); private Dictionary<string, FormerCaste> formerCastes = new Dictionary<string, FormerCaste>();
private bool firstLoadMessageShown; private bool firstLoadMessageShown;
private bool starterCastesSeeded; private bool starterCastesSeeded;
private bool slaveCasteOwed;
private List<string> overlapWarned = new List<string>(); private List<string> overlapWarned = new List<string>();
// Pawns that left the player side, checked on the next tick. Not saved: the 2500-tick sweep ends // Pawns that left the player side, checked on the next tick. Not saved: the 2500-tick sweep ends
@ -104,6 +105,9 @@ namespace BlaxCastes
/// <summary>The starter castes were added to this save (or the save already had castes when it was checked).</summary> /// <summary>The starter castes were added to this save (or the save already had castes when it was checked).</summary>
public bool StarterCastesSeeded => starterCastesSeeded; public bool StarterCastesSeeded => starterCastesSeeded;
/// <summary>The starter castes were added without Ideology, so the Slave caste comes on the first load with it (StarterCastes.AddSlaveCasteIfOwed).</summary>
public bool SlaveCasteOwed => slaveCasteOwed;
// ---- lookups ----------------------------------------------------------------------- // ---- lookups -----------------------------------------------------------------------
public CasteMembership MembershipOf(Pawn pawn) public CasteMembership MembershipOf(Pawn pawn)
@ -230,6 +234,8 @@ namespace BlaxCastes
internal void MarkStarterCastesSeeded() => starterCastesSeeded = true; internal void MarkStarterCastesSeeded() => starterCastesSeeded = true;
internal void SetSlaveCasteOwed(bool owed) => slaveCasteOwed = owed;
internal void MarkFirstLoadMessageShown() => firstLoadMessageShown = true; internal void MarkFirstLoadMessageShown() => firstLoadMessageShown = true;
// ---- upkeep ------------------------------------------------------------------------ // ---- upkeep ------------------------------------------------------------------------
@ -376,14 +382,17 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// A loaded save: the starter castes once, only if the save has no castes, with one message that /// A loaded save: the starter castes once, only if the save has no castes, with one message that
/// replaces the first-load message. Nobody is moved; the manager's "Assign by status" does that. /// replaces the first-load message. A save seeded without Ideology gets the Slave caste on its first
/// load with Ideology, with its own message. Nobody is moved; the manager's "Assign by status" does that.
/// </summary> /// </summary>
public override void LoadedGame() public override void LoadedGame()
{ {
bool seeded = false; bool seeded = false;
Caste slaveAdded = null;
try try
{ {
seeded = StarterCastes.SeedOnLoad(this); seeded = StarterCastes.SeedOnLoad(this);
slaveAdded = StarterCastes.AddSlaveCasteIfOwed(this);
} }
catch (Exception e) catch (Exception e)
{ {
@ -393,6 +402,17 @@ namespace BlaxCastes
ShowSeededMessage(); ShowSeededMessage();
else else
ShowFirstLoadMessageOnce(); ShowFirstLoadMessageOnce();
if (slaveAdded != null)
{
try
{
StarterCastes.ShowSlaveCasteAddedMessage(slaveAdded);
}
catch (Exception e)
{
Log.Error("[Blax Castes] Slave caste message failed: " + e);
}
}
ShowOverlapMessage(); ShowOverlapMessage();
} }
@ -455,6 +475,7 @@ namespace BlaxCastes
Scribe_Collections.Look(ref formerCastes, "formerCastes", LookMode.Value, LookMode.Deep, ref formerKeys, ref formerValues); Scribe_Collections.Look(ref formerCastes, "formerCastes", LookMode.Value, LookMode.Deep, ref formerKeys, ref formerValues);
Scribe_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown"); Scribe_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown");
Scribe_Values.Look(ref starterCastesSeeded, "starterCastesSeeded"); Scribe_Values.Look(ref starterCastesSeeded, "starterCastesSeeded");
Scribe_Values.Look(ref slaveCasteOwed, "slaveCasteOwed");
Scribe_Collections.Look(ref overlapWarned, "overlapWarned", LookMode.Value); Scribe_Collections.Look(ref overlapWarned, "overlapWarned", LookMode.Value);
if (Scribe.mode == LoadSaveMode.LoadingVars) if (Scribe.mode == LoadSaveMode.LoadingVars)

View File

@ -78,11 +78,14 @@ namespace BlaxCastes
return prisonerOfColony ? JoinSide.Prisoner : JoinSide.None; return prisonerOfColony ? JoinSide.Prisoner : JoinSide.None;
} }
/// <summary>Humanlike, not a baby, not a quest lodger, not a mutant without policies. Others never join a caste.</summary> /// <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) => public static bool Eligible(Pawn pawn) =>
pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike
&& !pawn.DevelopmentalStage.Baby() && !pawn.IsQuestLodger() && !pawn.DevelopmentalStage.Baby() && !pawn.IsQuestLodger()
&& !(pawn.IsMutant && pawn.mutant.Def.disablePolicies); && !CasteUtility.IsMutantWithoutDef(pawn) && !CasteUtility.PoliciesDisabled(pawn);
/// <summary>A scope reason or a row id, as opposed to the status fallback.</summary> /// <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; public static bool IsSpecific(string reason) => !reason.NullOrEmpty() && reason != StatusFallback;

View File

@ -45,7 +45,8 @@ namespace BlaxCastes
/// slave that leaves the player side or becomes a prisoner leaves a former-caste record, taken in the /// slave that leaves the player side or becomes a prisoner leaves a former-caste record, taken in the
/// prefix, so it holds the pawn's settings from before the game changed any of them. Inside a /// prefix, so it holds the pawn's settings from before the game changed any of them. Inside a
/// sale nothing is queued; the sale writes the record itself. Leaving the map (Pawn.ExitMap, a closing /// sale nothing is queued; the sale writes the record itself. Leaving the map (Pawn.ExitMap, a closing
/// map) is judged as a whole, from the status before it to the status after it (AfterLeaving). /// map, a map a gravship leaves behind) is judged as a whole, from the status before it to the status
/// after it (AfterLeaving).
/// Nothing is applied here: SetFaction and SetGuestStatus reset medical care, areas, work and slave /// Nothing is applied here: SetFaction and SetGuestStatus reset medical care, areas, work and slave
/// mode right after, so joins wait for the next tick. /// mode right after, so joins wait for the next tick.
/// </summary> /// </summary>
@ -200,14 +201,20 @@ namespace BlaxCastes
} }
/// <summary>A closing map: BeforeLeaving for each of its pawns that matters. Null when none does.</summary> /// <summary>A closing map: BeforeLeaving for each of its pawns that matters. Null when none does.</summary>
public static List<LeaveState> BeforeMapClosed(Map map) public static List<LeaveState> BeforeMapClosed(Map map) => BeforePawnsLeave(map?.mapPawns?.AllPawns);
/// <summary>
/// Pawns left behind together (a closing map, a map a gravship leaves): BeforeLeaving for each that
/// matters. Null when none does.
/// </summary>
public static List<LeaveState> BeforePawnsLeave(IEnumerable<Pawn> pawns)
{ {
List<LeaveState> states = null; List<LeaveState> states = null;
try try
{ {
if (map?.mapPawns == null || Current.Game == null) if (pawns == null || Current.Game == null)
return null; return null;
foreach (Pawn pawn in map.mapPawns.AllPawns.ToList()) foreach (Pawn pawn in pawns.ToList())
{ {
LeaveState state = BeforeLeaving(pawn); LeaveState state = BeforeLeaving(pawn);
if (state.before.valid) if (state.before.valid)
@ -328,6 +335,26 @@ namespace BlaxCastes
} }
} }
/// <summary>
/// A gravship takes off from a map without a grav anchor (Odyssey): GravshipUtility.AbandonMap despawns
/// the pawns left on it and passes them to the world itself, without MapDeiniter.PassPawnsToWorld and
/// without ending a prisoner's status, so it is judged per pawn like a closing map. A prisoner left
/// behind leaves its caste; colonists and slaves left behind stay in the faction and keep theirs. The
/// method is in the 1.7 game with or without Odyssey and returns at once without it, so this patch
/// applies everywhere and does nothing without Odyssey.
/// </summary>
[HarmonyPatch(typeof(GravshipUtility), nameof(GravshipUtility.AbandonMap))]
internal static class Patch_GravshipUtility_AbandonMap
{
public static void Prefix(Map map, out List<LeaveState> __state) => __state = JoinHooks.BeforePawnsLeave(map?.mapPawns?.AllPawnsSpawned);
public static Exception Finalizer(Exception __exception, List<LeaveState> __state)
{
JoinHooks.AfterMapClosed(__state);
return __exception;
}
}
/// <summary> /// <summary>
/// Buying: the pawn's status changes inside Pawn.PreTraded, so a "bought" scope covers it. Blax Slaves /// Buying: the pawn's status changes inside Pawn.PreTraded, so a "bought" scope covers it. Blax Slaves
/// and Trade as Slave or Colonist only set guest.joinStatus before this call, so the final status /// and Trade as Slave or Colonist only set guest.joinStatus before this call, so the final status

View File

@ -106,7 +106,7 @@ namespace BlaxCastes
} }
TooltipHandler.TipRegion(manage, "BlaxCastes_ManageCastesButtonTip".Translate()); TooltipHandler.TipRegion(manage, "BlaxCastes_ManageCastesButtonTip".Translate());
if (!compact) if (!compact)
TooltipHandler.TipRegion(defaults, "BlaxCastes_JoinDefaultsButtonTip".Translate()); TooltipHandler.TipRegion(defaults, DlcSupport.IdeologyKey("BlaxCastes_JoinDefaultsButtonTip").Translate());
} }
/// <summary> /// <summary>

View File

@ -8,9 +8,11 @@ namespace BlaxCastes
{ {
/// <summary> /// <summary>
/// The schedule slot: 24 TimeAssignmentDef defNames, hour 0 first. Names resolve with /// The schedule slot: 24 TimeAssignmentDef defNames, hour 0 first. Names resolve with
/// GetNamedSilentFail; an unknown name, and Meditate without Royalty, becomes Anything. Written with /// GetNamedSilentFail; an unknown name, and Meditate without Royalty, applies as Anything. A caste
/// Pawn_TimetableTracker.SetAssignment, only on pawns that have a timetable (prisoners from other /// keeps a name of an official DLC that is off (Meditate without Royalty, see DlcSupport), so those
/// factions have none). The Follow rule looks at the whole day. /// hours come back with the DLC; a name nothing knows (a removed mod) is stored as Anything. Written
/// with Pawn_TimetableTracker.SetAssignment, only on pawns that have a timetable (prisoners from
/// other factions have none). The Follow rule looks at the whole day.
/// </summary> /// </summary>
public static class ScheduleSlot public static class ScheduleSlot
{ {
@ -29,8 +31,18 @@ namespace BlaxCastes
public static bool IsKnown(string defName) => !defName.NullOrEmpty() && Resolve(defName).defName == defName; public static bool IsKnown(string defName) => !defName.NullOrEmpty() && Resolve(defName).defName == defName;
/// <summary> /// <summary>
/// 24 stored names from a value: a list of names or of TimeAssignmentDefs. Unknown names become /// The name belongs to an official DLC that is off (Meditate without Royalty): the caste keeps it, and
/// Anything. Null for null or anything that is not 24 entries long. /// it applies as Anything until the DLC is on again.
/// </summary>
public static bool IsDlcOff(string defName) =>
!defName.NullOrEmpty() && !IsKnown(defName) && DlcSupport.InactiveDlcFor(typeof(TimeAssignmentDef), defName) != null;
/// <summary>A name a caste keeps as it is: known, or of a DLC that is off.</summary>
public static bool IsKept(string defName) => IsKnown(defName) || IsDlcOff(defName);
/// <summary>
/// 24 stored names from a value: a list of names or of TimeAssignmentDefs. Names of a DLC that is off
/// are kept; other unknown names become Anything. Null for null or anything that is not 24 entries long.
/// </summary> /// </summary>
public static List<string> Normalize(object value) public static List<string> Normalize(object value)
{ {
@ -41,10 +53,24 @@ namespace BlaxCastes
case IEnumerable<TimeAssignmentDef> d: names = d.Select(x => x?.defName); break; case IEnumerable<TimeAssignmentDef> d: names = d.Select(x => x?.defName); break;
default: return null; default: return null;
} }
List<string> result = names.Select(n => Resolve(n).defName).ToList(); List<string> result = names.Select(n => IsKept(n) ? n : TimeAssignmentDefOf.Anything.defName).ToList();
return result.Count == Hours ? result : null; return result.Count == Hours ? result : null;
} }
/// <summary>
/// The stored names of a DLC that is off, each once, with the DLC: "Meditate (needs Royalty)". Empty when
/// there are none. The manager shows them under the grid, which draws those hours as Anything.
/// </summary>
public static List<string> DlcOffLabels(IReadOnlyList<string> names)
{
var result = new List<string>();
if (names == null)
return result;
foreach (string name in names.Where(IsDlcOff).Distinct())
result.Add("BlaxCastes_NeedsDlc".Translate(name.Named("WHAT"), DlcSupport.InactiveDlcFor(typeof(TimeAssignmentDef), name).Named("DLC")));
return result;
}
/// <summary>True for a value Normalize accepts or null.</summary> /// <summary>True for a value Normalize accepts or null.</summary>
public static bool Fits(object value) public static bool Fits(object value)
{ {

View File

@ -11,10 +11,12 @@ namespace BlaxCastes
/// carry the ideo drug rule and any earlier "Make default"). Medical care unmanaged. /// carry the ideo drug rule and any earlier "Make default"). Medical care unmanaged.
/// - Slave (Ideology only): the Slave outfit, Simple food, No drugs. Reading stays unmanaged, because /// - Slave (Ideology only): the Slave outfit, Simple food, No drugs. Reading stays unmanaged, because
/// slave children need books to learn; medical care stays unmanaged, so the game's default care for /// slave children need books to learn; medical care stays unmanaged, so the game's default care for
/// slaves stays in charge. /// slaves stays in charge. Seeded without Ideology, a save gets it on its first load with Ideology.
/// - Prisoner: Simple food. /// - Prisoner: Simple food.
/// Policies are found by their translated starting labels, No drugs by its source def. A miss leaves /// Policies are found by their translated starting labels, No drugs by its source def. A miss leaves
/// the slot unmanaged; Castes never creates vanilla policies itself. /// the slot unmanaged; Castes never creates vanilla policies itself, with one exception: the Slave
/// caste a save gets on its first load with Ideology also gets the Slave outfit when the save has none
/// (AddSlaveCasteIfOwed).
/// Rows: bought as colonist and new colonist use Default caste (Colonist); bought as slave and new /// Rows: bought as colonist and new colonist use Default caste (Colonist); bought as slave and new
/// slave use Slave; new prisoner uses Prisoner. /// slave use Slave; new prisoner uses Prisoner.
/// </summary> /// </summary>
@ -45,8 +47,8 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// The manager's "Create Slave outfit" button: a new apparel policy named like the game's starting /// The manager's "Create Slave outfit" button: a new apparel policy named like the game's starting
/// Slave outfit that allows the apparel the game tags for slaves, the way a new game sets it up. /// Slave outfit that allows the apparel the game tags for slaves, the way a new game sets it up.
/// Only on the player's click; seeding never creates policies. Returns the existing outfit if there /// On the player's click, and for the Slave caste a save is owed (AddSlaveCasteIfOwed); other seeding
/// is one, or null without Ideology. /// never creates policies. Returns the existing outfit if there is one, or null without Ideology.
/// </summary> /// </summary>
public static ApparelPolicy CreateSlaveOutfit() public static ApparelPolicy CreateSlaveOutfit()
{ {
@ -105,14 +107,7 @@ namespace BlaxCastes
SetIfFound(colonist, CasteSlot.Drug, game?.drugPolicyDatabase?.DefaultDrugPolicy()); SetIfFound(colonist, CasteSlot.Drug, game?.drugPolicyDatabase?.DefaultDrugPolicy());
SetIfFound(colonist, CasteSlot.Reading, game?.readingPolicyDatabase?.DefaultReadingPolicy()); SetIfFound(colonist, CasteSlot.Reading, game?.readingPolicyDatabase?.DefaultReadingPolicy());
Caste slave = null; Caste slave = ModsConfig.IdeologyActive ? NewSlaveCaste(comp) : null;
if (ModsConfig.IdeologyActive)
{
slave = NewCaste(comp, SlaveLabel);
SetIfFound(slave, CasteSlot.Apparel, SlaveOutfit());
SetIfFound(slave, CasteSlot.Food, SimpleFood());
SetIfFound(slave, CasteSlot.Drug, NoDrugs());
}
Caste prisoner = NewCaste(comp, PrisonerLabel); Caste prisoner = NewCaste(comp, PrisonerLabel);
SetIfFound(prisoner, CasteSlot.Food, SimpleFood()); SetIfFound(prisoner, CasteSlot.Food, SimpleFood());
@ -127,19 +122,77 @@ namespace BlaxCastes
} }
comp.SetRowRaw(JoinReason.NewPrisoner, JoinRowMode.SpecificCaste, prisoner); comp.SetRowRaw(JoinReason.NewPrisoner, JoinRowMode.SpecificCaste, prisoner);
comp.MarkStarterCastesSeeded(); comp.MarkStarterCastesSeeded();
// Without Ideology the Slave caste is owed: the first load with Ideology adds it (AddSlaveCasteIfOwed).
comp.SetSlaveCasteOwed(slave == null);
List<string> missing = new List<string>(); List<string> missing = new List<string>();
if (slave != null) if (slave != null)
{ missing.AddRange(MissingSlaveSlots(slave));
if (!slave.IsManaged(CasteSlot.Apparel)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Apparel));
if (!slave.IsManaged(CasteSlot.Food)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Food));
if (!slave.IsManaged(CasteSlot.Drug)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Drug));
}
if (!prisoner.IsManaged(CasteSlot.Food)) missing.Add(PrisonerLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Food)); if (!prisoner.IsManaged(CasteSlot.Food)) missing.Add(PrisonerLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Food));
if (missing.Count > 0) if (missing.Count > 0)
Log.Message("[Blax Castes] Starter castes added; policies not found (renamed or removed), left unmanaged: " + string.Join(", ", missing)); Log.Message("[Blax Castes] Starter castes added; policies not found (renamed or removed), left unmanaged: " + string.Join(", ", missing));
} }
/// <summary>The Slave caste: the Slave outfit, Simple food, No drugs, each where the game has it.</summary>
private static Caste NewSlaveCaste(GameComponent_BlaxCastes comp)
{
Caste slave = NewCaste(comp, SlaveLabel);
SetIfFound(slave, CasteSlot.Apparel, SlaveOutfit());
SetIfFound(slave, CasteSlot.Food, SimpleFood());
SetIfFound(slave, CasteSlot.Drug, NoDrugs());
return slave;
}
private static IEnumerable<string> MissingSlaveSlots(Caste slave)
{
foreach (CasteSlot slot in new[] { CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug })
{
if (!slave.IsManaged(slot))
yield return SlaveLabel + ": " + CasteUtility.SlotLabel(slot);
}
}
/// <summary>
/// A save whose starter castes were added without Ideology, loaded with Ideology: adds the Slave caste
/// once, like a new game would have it, and picks it in the bought-as-slave and new-slave rows that are
/// still at No caste. The game makes its Slave outfit only in a new game with Ideology
/// (OutfitDatabase.GenerateStartingOutfits) and loads the saved outfit list over it, so such a save
/// usually has none: the new caste then gets one made like the game's (CreateSlaveOutfit), the one
/// policy Castes creates without a click. A caste already named Slave is used as it is instead of a
/// second one, and when both slave rows already pick a caste nothing is added. Nobody moves. Does
/// nothing while seedStarterCastes is off (the caste stays owed). Returns the caste the rows now pick, or null.
/// </summary>
public static Caste AddSlaveCasteIfOwed(GameComponent_BlaxCastes comp)
{
if (comp == null || !comp.SlaveCasteOwed || !ModsConfig.IdeologyActive || !SettingOn)
return null;
comp.SetSlaveCasteOwed(false);
List<string> openRows = new[] { JoinReason.BoughtSlave, JoinReason.NewSlave }
.Where(r => comp.GetRow(r).mode == JoinRowMode.NoCaste).ToList();
if (openRows.Count == 0)
return null;
Caste slave = comp.Castes.FirstOrDefault(c => c != null && c.label == SlaveLabel);
if (slave == null)
{
if (SlaveOutfit() == null)
CreateSlaveOutfit();
slave = NewSlaveCaste(comp);
List<string> missing = MissingSlaveSlots(slave).ToList();
if (missing.Count > 0)
Log.Message("[Blax Castes] Slave caste added; policies not found (renamed or removed), left unmanaged: " + string.Join(", ", missing));
}
foreach (string row in openRows)
comp.SetRowRaw(row, JoinRowMode.SpecificCaste, slave);
return slave;
}
/// <summary>The one message for a save that just got the Slave caste (AddSlaveCasteIfOwed).</summary>
public static void ShowSlaveCasteAddedMessage(Caste slave)
{
string text = "BlaxCastes_StarterSlaveAddedMessage".Translate(slave.label.Named("CASTE"));
LongEventHandler.ExecuteWhenFinished(() => Messages.Message(text, MessageTypeDefOf.NeutralEvent));
}
private static Caste NewCaste(GameComponent_BlaxCastes comp, string label) private static Caste NewCaste(GameComponent_BlaxCastes comp, string label)
{ {
var caste = new Caste(comp.TakeNextId(), label); var caste = new Caste(comp.TakeNextId(), label);

View File

@ -13,7 +13,8 @@ namespace BlaxCastes
/// stored even while manual priorities are off: the game then reads any nonzero value as on, and the /// stored even while manual priorities are off: the game then reads any nonzero value as on, and the
/// number takes effect once manual priorities are turned on, so members still match the caste after the /// number takes effect once manual priorities are turned on, so members still match the caste after the
/// switch. The Follow rule works per type. The slot is off while the manageWorkPriorities setting is /// switch. The Follow rule works per type. The slot is off while the manageWorkPriorities setting is
/// off or an automatic work manager is active. /// off or an automatic work manager is active. A listed type of an official DLC that is off (Childcare
/// without Biotech) stays listed and is skipped, so it works again once the DLC is back.
/// </summary> /// </summary>
public static class WorkSlot public static class WorkSlot
{ {
@ -73,6 +74,24 @@ namespace BlaxCastes
public static WorkTypeDef Resolve(string defName) => defName.NullOrEmpty() ? null : DefDatabase<WorkTypeDef>.GetNamedSilentFail(defName); public static WorkTypeDef Resolve(string defName) => defName.NullOrEmpty() ? null : DefDatabase<WorkTypeDef>.GetNamedSilentFail(defName);
/// <summary>
/// A listed work type of an official DLC that is off (Childcare without Biotech, Dark study without
/// Anomaly, Fishing without Odyssey): the caste keeps it and skips it until the DLC is on again.
/// </summary>
public static bool IsDlcOff(string defName) =>
!defName.NullOrEmpty() && Resolve(defName) == null && DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName) != null;
/// <summary>Every listed type is of a DLC that is off, so writing the slot changes nothing. False for no entries.</summary>
public static bool AllDlcOff(IReadOnlyDictionary<string, int> values) =>
values != null && values.Count > 0 && values.Keys.All(IsDlcOff);
/// <summary>
/// "Start from nothing" turns the other work off only while at least one listed type is in the game,
/// so a caste that lists only work of a DLC that is off never leaves its members without work.
/// </summary>
public static bool StripsOthers(IReadOnlyDictionary<string, int> values, bool startFromNothing) =>
startFromNothing && values != null && values.Keys.Any(k => Resolve(k) != null);
/// <summary> /// <summary>
/// Work type defName to priority from a value: a dictionary or any list of name and priority pairs. /// Work type defName to priority from a value: a dictionary or any list of name and priority pairs.
/// Entries without a name or outside 0 to 4 are dropped. Null for null, anything else, or no entries. /// Entries without a name or outside 0 to 4 are dropped. Null for null, anything else, or no entries.
@ -164,14 +183,14 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// Writes the listed types. startFromNothing first turns off every other work type except the /// Writes the listed types. startFromNothing first turns off every other work type except the
/// self-care ones (IsSelfCare), which stay as they are, for castes that should do only their listed /// self-care ones (IsSelfCare), which stay as they are, for castes that should do only their listed
/// work. True when anything was written. /// work; not while no listed type is in the game (StripsOthers). True when anything was written.
/// </summary> /// </summary>
public static bool Write(Pawn pawn, IReadOnlyDictionary<string, int> values, bool startFromNothing) public static bool Write(Pawn pawn, IReadOnlyDictionary<string, int> values, bool startFromNothing)
{ {
if (!HasWorkSettings(pawn) || values == null || values.Count == 0) if (!HasWorkSettings(pawn) || values == null || values.Count == 0)
return false; return false;
bool any = false; bool any = false;
if (startFromNothing) if (StripsOthers(values, startFromNothing))
{ {
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading) foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{ {
@ -191,14 +210,15 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// Every work type the caste decides, with its value: the listed ones, and with "Start from nothing" /// Every work type the caste decides, with its value: the listed ones, and with "Start from nothing"
/// every other one except the self-care types, at off. Null while the caste leaves work alone. /// (while it applies, StripsOthers) every other one except the self-care types, at off. Null while the
/// caste leaves work alone.
/// </summary> /// </summary>
public static Dictionary<string, int> Decided(Caste caste) public static Dictionary<string, int> Decided(Caste caste)
{ {
if (caste == null || !caste.IsManaged(CasteSlot.Work)) if (caste == null || !caste.IsManaged(CasteSlot.Work))
return null; return null;
var result = new Dictionary<string, int>(caste.WorkPriorities); var result = new Dictionary<string, int>(caste.WorkPriorities);
if (caste.WorkStartFromNothing) if (StripsOthers(caste.WorkPriorities, caste.WorkStartFromNothing))
{ {
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading) foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{ {
@ -256,7 +276,10 @@ namespace BlaxCastes
public static string TypeLabel(string defName) => Resolve(defName) is WorkTypeDef def ? TypeLabel(def) : defName; public static string TypeLabel(string defName) => Resolve(defName) is WorkTypeDef def ? TypeLabel(def) : defName;
/// <summary>The listed types with their priority, in the Work tab's order: "Firefight 1, Grow 1". Off types say "off".</summary> /// <summary>
/// The listed types with their priority, in the Work tab's order: "Firefight 1, Grow 1". Off types say
/// "off". A type of a DLC that is off comes last with its DLC: "Childcare 1 (needs Biotech)".
/// </summary>
public static string Summary(IReadOnlyDictionary<string, int> values) public static string Summary(IReadOnlyDictionary<string, int> values)
{ {
if (values == null || values.Count == 0) if (values == null || values.Count == 0)
@ -272,10 +295,33 @@ namespace BlaxCastes
} }
foreach (KeyValuePair<string, int> kv in values) foreach (KeyValuePair<string, int> kv in values)
{ {
if (!listed.Contains(kv.Key)) if (listed.Contains(kv.Key))
parts.Add(kv.Key + " " + PriorityLabel(kv.Value)); continue;
parts.Add(IsDlcOff(kv.Key) ? DlcOffLabel(kv.Key, kv.Value) : kv.Key + " " + PriorityLabel(kv.Value));
} }
return string.Join(", ", parts); return string.Join(", ", parts);
} }
/// <summary>The listed types of a DLC that is off, as Summary words them; empty when there are none.</summary>
public static List<string> DlcOffLabels(IReadOnlyDictionary<string, int> values)
{
var result = new List<string>();
if (values == null)
return result;
foreach (KeyValuePair<string, int> kv in values.OrderBy(kv => kv.Key))
{
if (IsDlcOff(kv.Key))
result.Add(DlcOffLabel(kv.Key, kv.Value));
}
return result;
}
/// <summary>"Dark study 1 (needs Anomaly)": the def is not loaded, so its name comes from the defName.</summary>
private static string DlcOffLabel(string defName, int priority)
{
string name = GenText.SplitCamelCase(defName).ToLowerInvariant().CapitalizeFirst();
return "BlaxCastes_NeedsDlc".Translate((name + " " + PriorityLabel(priority)).Named("WHAT"),
DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName).Named("DLC"));
}
} }
} }

View File

@ -6,12 +6,8 @@
<supportedVersions> <supportedVersions>
<li>1.7</li> <li>1.7</li>
</supportedVersions> </supportedVersions>
<modDependencies> <!-- No modDependencies: Blax Castes has no download page yet, and the game drops a dependency without one,
<li> with a warning. run-tests.ps1 loads Blax Castes before this mod. -->
<packageId>blax.castes</packageId>
<displayName>Blax Castes</displayName>
</li>
</modDependencies>
<loadAfter> <loadAfter>
<li>blax.castes</li> <li>blax.castes</li>
<li>blax.slaves</li> <li>blax.slaves</li>

View File

@ -52,6 +52,7 @@ namespace BlaxCastesTests
T.NotNull(comp, "GameComponent_BlaxCastes.Instance"); T.NotNull(comp, "GameComponent_BlaxCastes.Instance");
T.Check(comp.StarterCastesSeeded, "the new game is not marked as seeded"); T.Check(comp.StarterCastesSeeded, "the new game is not marked as seeded");
T.Equal(ModsConfig.IdeologyActive ? 3 : 2, comp.Castes.Count, "castes in a new game (" + string.Join(", ", comp.Castes.Select(c => c.label)) + ")"); T.Equal(ModsConfig.IdeologyActive ? 3 : 2, comp.Castes.Count, "castes in a new game (" + string.Join(", ", comp.Castes.Select(c => c.label)) + ")");
T.Equal(!ModsConfig.IdeologyActive, comp.SlaveCasteOwed, "the Slave caste owed for a load with Ideology");
Caste colonist = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.ColonistLabel); Caste colonist = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.ColonistLabel);
Caste slave = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.SlaveLabel); Caste slave = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.SlaveLabel);
Caste prisoner = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.PrisonerLabel); Caste prisoner = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.PrisonerLabel);
@ -327,6 +328,7 @@ namespace BlaxCastesTests
{ {
ApparelPolicy temp = Current.Game.outfitDatabase.MakeNewOutfit(); ApparelPolicy temp = Current.Game.outfitDatabase.MakeNewOutfit();
temp.label = "BlaxCastes test outfit"; temp.label = "BlaxCastes test outfit";
T.ExpectWarning("Missing policy test");
Caste c = Fixtures.NewCaste("Missing policy test"); Caste c = Fixtures.NewCaste("Missing policy test");
CasteManager.SetSlot(c, CasteSlot.Apparel, temp); CasteManager.SetSlot(c, CasteSlot.Apparel, temp);
CasteManager.SetSlot(c, CasteSlot.Food, Simple()); CasteManager.SetSlot(c, CasteSlot.Food, Simple());

View File

@ -0,0 +1,386 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BlaxCastes;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
/// <summary>
/// Castes works with any combination of DLCs. These run in every DLC set (run-tests.ps1 with no switch,
/// -NoDlc, -Dlc ...) and check the DLC-off side: names of a DLC that is off stay in a caste with no warning
/// (the state a save made with the DLC is in when it loads without it), a mutant whose def is gone throws
/// nothing, and the slave rows and Ideology texts. Which DLC work types are off is read at run time
/// (DlcOffWork), so the tests hold with every DLC set, Anomaly and Odyssey included; a test that needs a
/// DLC, or a DLC that is off, skips with "needs ..." after its core part.
/// </summary>
public static class DlcTests
{
private const string Royalty = "ludeon.rimworld.royalty";
private const string Biotech = "ludeon.rimworld.biotech";
private const string Anomaly = "ludeon.rimworld.anomaly";
private const string Odyssey = "ludeon.rimworld.odyssey";
private static void CheckSlots() => AccessTools.Method(typeof(CasteManager), "CheckSlots").Invoke(null, new object[] { Fixtures.Comp });
private static void SetScheduleRaw(Caste c, List<string> names) => AccessTools.Field(typeof(Caste), "schedule").SetValue(c, names);
private static void SetWorkRaw(Caste c, Dictionary<string, int> work) => AccessTools.Field(typeof(Caste), "workPriorities").SetValue(c, work);
private static WorkTypeDef Growing => Fixtures.NeedDef(DefDatabase<WorkTypeDef>.GetNamedSilentFail("Growing"), "work type Growing");
/// <summary>The work types of a DLC: Childcare (Biotech), Dark study (Anomaly), Fishing (Odyssey).</summary>
private static readonly string[] DlcWork = { "Childcare", "DarkStudy", "Fishing" };
/// <summary>The DLC work types whose DLC is off in this run.</summary>
private static List<string> DlcOffWork() => DlcWork.Where(WorkSlot.IsDlcOff).ToList();
/// <summary>"Dark study 2 (needs Anomaly)" as the summary words a DLC work type that is off.</summary>
private static string NeedsNote(string defName) => "(needs " + DlcSupport.DlcName(DlcSupport.OwnerOf(typeof(WorkTypeDef), defName)) + ")";
/// <summary>Night shift with Meditate at hours 3 and 4.</summary>
private static List<string> MeditateSchedule()
{
var names = new List<string>();
for (int h = 0; h < ScheduleSlot.Hours; h++)
names.Add(h == 3 || h == 4 ? "Meditate" : h < 8 ? TimeAssignmentDefOf.Sleep.defName : TimeAssignmentDefOf.Work.defName);
return names;
}
// ---- which DLC a def belongs to ----------------------------------------------------------
[BlaxTest("dlc: Meditate is Royalty's, Childcare Biotech's, Dark study Anomaly's and Fishing Odyssey's; core and made-up names belong to no DLC")]
public static void DlcOwners()
{
T.Equal(Royalty, DlcSupport.OwnerOf(typeof(TimeAssignmentDef), "Meditate"), "owner of Meditate");
T.Equal(Biotech, DlcSupport.OwnerOf(typeof(WorkTypeDef), "Childcare"), "owner of Childcare");
T.Equal(Anomaly, DlcSupport.OwnerOf(typeof(WorkTypeDef), "DarkStudy"), "owner of DarkStudy");
T.Equal(Odyssey, DlcSupport.OwnerOf(typeof(WorkTypeDef), "Fishing"), "owner of Fishing");
T.Equal(null, DlcSupport.OwnerOf(typeof(TimeAssignmentDef), "Sleep"), "owner of Sleep");
T.Equal(null, DlcSupport.OwnerOf(typeof(WorkTypeDef), "Growing"), "owner of Growing");
T.Equal(null, DlcSupport.OwnerOf(typeof(WorkTypeDef), "BlaxCastesNoSuchWork"), "owner of a made-up work type");
T.Equal(null, DlcSupport.OwnerOf(typeof(WorkTypeDef), "Meditate"), "owner of Meditate as a work type");
T.Equal(ModsConfig.RoyaltyActive ? null : "Royalty", DlcSupport.InactiveDlcFor(typeof(TimeAssignmentDef), "Meditate"), "inactive DLC for Meditate");
T.Equal(ModsConfig.BiotechActive ? null : "Biotech", DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), "Childcare"), "inactive DLC for Childcare");
T.Equal(ModsConfig.AnomalyActive ? null : "Anomaly", DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), "DarkStudy"), "inactive DLC for DarkStudy");
T.Equal(ModsConfig.OdysseyActive ? null : "Odyssey", DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), "Fishing"), "inactive DLC for Fishing");
T.Check(ScheduleSlot.IsKept("Meditate") && !ScheduleSlot.IsKept("BlaxCastesNoSuchAssignment"), "IsKept: Meditate " + ScheduleSlot.IsKept("Meditate"));
T.Check(ScheduleSlot.IsDlcOff("Meditate") == !ModsConfig.RoyaltyActive, "IsDlcOff(Meditate) with Royalty " + ModsConfig.RoyaltyActive);
T.Check(WorkSlot.IsDlcOff("Childcare") == !ModsConfig.BiotechActive, "IsDlcOff(Childcare) with Biotech " + ModsConfig.BiotechActive);
T.Check(!WorkSlot.IsDlcOff("Growing") && !WorkSlot.IsDlcOff("BlaxCastesNoSuchWork"), "a core or made-up work type counts as a DLC's");
T.Check("BlaxCastes_NeedsDlc".CanTranslate() && "BlaxCastes_ScheduleDlcOffNote".CanTranslate() && "BlaxCastes_WorkDlcOffNote".CanTranslate(),
"DLC note strings missing from Keyed");
}
// ---- a caste that holds names of a DLC that is off ---------------------------------------
[BlaxTest("dlc: stored Meditate hours stay in the caste through the load check, painting and Apply with no warning; without Royalty they apply as Anything and the manager notes them")]
public static void MeditateKeptWithoutRoyalty()
{
string anything = TimeAssignmentDefOf.Anything.defName;
Caste c = Fixtures.NewCaste("Meditate kept");
SetScheduleRaw(c, MeditateSchedule()); // as a save made with Royalty loads
CheckSlots();
T.Equal("Meditate", c.Schedule[3], "stored hour 3 after the load check");
Pawn p = Fixtures.Colonist();
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
string expected = ModsConfig.RoyaltyActive ? "Meditate" : anything;
T.Equal(expected, p.timetable.GetAssignment(3).defName, "pawn's hour 3 (Royalty " + ModsConfig.RoyaltyActive + ")");
T.Equal(0, CasteManager.Overrides(p).Count, "overrides right after Assign");
// Painting another hour rewrites the whole day: the Meditate hours must survive it.
Dialog_ManageCastes.PaintHour(c, 12, TimeAssignmentDefOf.Joy);
T.Equal("Meditate", c.Schedule[4], "stored hour 4 after painting hour 12");
T.Equal(TimeAssignmentDefOf.Joy.defName, c.Schedule[12], "stored hour 12 after painting it");
T.Equal(TimeAssignmentDefOf.Joy, p.timetable.GetAssignment(12), "pawn's hour 12 after painting");
CheckSlots();
T.Equal("Meditate", c.Schedule[3], "stored hour 3 after a second load check");
// The Anything brush replaces a stored Meditate hour, also while that hour shows as Anything (no Royalty).
TimeAssignmentDef anythingBrush = TimeAssignmentDefOf.Anything;
T.Check(Dialog_ManageCastes.PaintsHour(c, 3, anythingBrush), "the Anything brush does not paint a stored Meditate hour");
Dialog_ManageCastes.PaintHour(c, 3, anythingBrush);
T.Equal(anything, c.Schedule[3], "stored hour 3 after painting it Anything");
T.Check(!Dialog_ManageCastes.PaintsHour(c, 3, anythingBrush), "the Anything brush paints an hour that is already Anything");
T.Equal("Meditate", c.Schedule[4], "stored hour 4 after painting hour 3");
string note = Dialog_ManageCastes.ScheduleDlcNote(c);
if (ModsConfig.RoyaltyActive)
{
T.Check(note == null, "schedule DLC note with Royalty on: " + note);
return;
}
T.Check(note != null && note.Contains("Meditate") && note.Contains("Royalty"), "schedule DLC note without Royalty: " + note);
T.Check(!ScheduleSlot.Summary(c.Schedule).NullOrEmpty(), "the schedule summary is empty");
}
[BlaxTest("dlc: stored work types of a DLC that is off (Childcare, Dark study, Fishing) stay listed with no warning and are skipped; the summary names their DLC instead of the def name")]
public static void DlcWorkKept()
{
if (WorkSlot.ActiveManager() != null)
T.Skip(WorkSlot.ActiveManager() + " is active, so the work slot is off");
Caste c = Fixtures.NewCaste("DLC work kept");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
var work = new Dictionary<string, int>(c.WorkPriorities) { ["Childcare"] = 1, ["DarkStudy"] = 2, ["Fishing"] = 3 };
SetWorkRaw(c, work); // as a save made with those DLCs loads
CheckSlots();
foreach (string name in new[] { "Childcare", "DarkStudy", "Fishing", "Growing" })
T.Check(c.WorkPriorities.ContainsKey(name), name + " was dropped by the load check: " + WorkSlot.Summary(c.WorkPriorities));
List<string> off = DlcOffWork();
T.Info("DLC work types that are off: " + (off.Count == 0 ? "none" : string.Join(", ", off)));
T.Check(DlcOwnerActive("Childcare") == ModsConfig.BiotechActive && DlcOwnerActive("DarkStudy") == ModsConfig.AnomalyActive
&& DlcOwnerActive("Fishing") == ModsConfig.OdysseyActive, "a DLC work type resolves although its DLC is off, or the other way round");
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
PlaySettings play = Find.PlaySettings;
bool manual = play.useWorkPriorities;
play.useWorkPriorities = true; // so GetPriority shows the caste's number
try
{
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
if (!p.WorkTypeIsDisabled(Growing))
T.Equal(1, p.workSettings.GetPriority(Growing), "pawn's Growing");
foreach (string name in DlcWork)
{
WorkTypeDef def = WorkSlot.Resolve(name);
if (WorkSlot.CanDo(p, def))
T.Equal(work[name], p.workSettings.GetPriority(def), "pawn's " + name + " with its DLC on");
}
T.Equal(0, CasteManager.Overrides(p).Count, "overrides from work types of a DLC that is off");
}
finally
{
play.useWorkPriorities = manual;
}
string summary = WorkSlot.Summary(c.WorkPriorities);
string note = Dialog_ManageCastes.WorkDlcNote(c);
foreach (string name in DlcWork)
{
if (off.Contains(name))
{
string label = GenText.SplitCamelCase(name).ToLowerInvariant().CapitalizeFirst();
T.Check(summary.Contains(label + " " + work[name] + " " + NeedsNote(name)), "summary for " + name + " with its DLC off: " + summary);
T.Check(name == label || !summary.Contains(name), "summary names the def " + name + ": " + summary);
T.Check(note != null && note.Contains(NeedsNote(name)), "work DLC note for " + name + ": " + note);
}
else
{
T.Check(summary.Contains(WorkSlot.TypeLabel(name) + " " + work[name]) && !summary.Contains(NeedsNote(name)), "summary for " + name + " with its DLC on: " + summary);
T.Check(note == null || !note.Contains(NeedsNote(name)), "work DLC note names " + name + " with its DLC on: " + note);
}
}
T.Check((note == null) == (off.Count == 0), "work DLC note with " + off.Count + " types off: " + note);
}
/// <summary>The DLC that owns the work type is active, read from the def being in the game.</summary>
private static bool DlcOwnerActive(string defName) => WorkSlot.Resolve(defName) != null;
[BlaxTest("dlc: Start from nothing with only work types of a DLC that is off turns no work off; with a core type listed it still does")]
public static void StartFromNothingDlcOnly()
{
if (WorkSlot.ActiveManager() != null)
T.Skip(WorkSlot.ActiveManager() + " is active, so the work slot is off");
List<string> off = DlcOffWork();
if (off.Count == 0)
T.Skip("needs a DLC that is off (Childcare, Dark study, Fishing all active)");
Caste c = Fixtures.NewCaste("DLC work only");
SetWorkRaw(c, off.ToDictionary(name => name, name => 1));
CasteManager.SetWorkStartFromNothing(c, true);
T.Check(c.IsManaged(CasteSlot.Work), "setup: the caste does not manage work");
T.Check(!WorkSlot.StripsOthers(c.WorkPriorities, true), "StripsOthers with only work types of a DLC that is off (" + string.Join(", ", off) + ")");
T.Equal(off.Count, WorkSlot.Decided(c).Count, "work types the caste decides (" + string.Join(", ", WorkSlot.Decided(c).Keys) + ")");
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
Dictionary<string, int> before = WorkSlot.Of(p);
int on = before.Count(kv => kv.Value > 0);
T.Check(on > 2, "setup: the colonist has only " + on + " work types on");
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
List<string> changed = WorkSlot.Of(p).Where(kv => before[kv.Key] != kv.Value).Select(kv => kv.Key).ToList();
T.Check(changed.Count == 0, "Start from nothing changed work with no listed type in the game: " + string.Join(", ", changed));
// A core type listed next to them: the other work goes off again.
CasteManager.SetWorkPriority(c, Growing.defName, 1);
T.Check(WorkSlot.StripsOthers(c.WorkPriorities, true), "StripsOthers with Growing listed");
CasteManager.ResetToCaste(p);
int stillOn = WorkSlot.Of(p).Count(kv => kv.Value > 0 && kv.Key != Growing.defName && !WorkSlot.IsSelfCare(WorkSlot.Resolve(kv.Key)));
T.Equal(0, stillOn, "other work types on after Start from nothing with Growing listed");
}
[BlaxTest("dlc: a caste whose only work types are of a DLC that is off shows no Apply to all members; Forget these drops those types, keeps the rest and moves nobody")]
public static void ForgetDlcWork()
{
if (WorkSlot.ActiveManager() != null)
T.Skip(WorkSlot.ActiveManager() + " is active, so the work slot is off");
Caste c = Fixtures.NewCaste("DLC work forget");
T.Check(!Dialog_ManageCastes.AppliesAnything(c), "a new caste shows Apply to all members");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
T.Check(Dialog_ManageCastes.AppliesAnything(c), "a caste with Growing 1 shows no Apply to all members");
T.Equal(0, Dialog_ManageCastes.ForgetDlcOffWork(c), "types Forget these dropped from a caste without DLC work");
T.Equal(1, c.WorkPriorities.Count, "work types after Forget these on a caste without DLC work");
List<string> off = DlcOffWork();
if (off.Count == 0)
T.Skip("needs a DLC that is off (Childcare, Dark study, Fishing all active); the core part passed");
SetWorkRaw(c, off.ToDictionary(name => name, name => 2)); // as a save made with those DLCs loads
T.Check(c.IsManaged(CasteSlot.Work) && WorkSlot.AllDlcOff(c.WorkPriorities), "setup: the caste lists only work of a DLC that is off");
T.Check(!Dialog_ManageCastes.AppliesAnything(c), "Apply to all members shows for a caste whose only work types are of a DLC that is off");
var mixed = off.ToDictionary(name => name, name => 2);
mixed[Growing.defName] = 1;
SetWorkRaw(c, mixed);
T.Check(Dialog_ManageCastes.AppliesAnything(c), "Apply to all members hidden while Growing is listed");
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
Dictionary<string, int> before = WorkSlot.Of(p);
T.Equal(off.Count, Dialog_ManageCastes.ForgetDlcOffWork(c), "types Forget these dropped");
T.Check(c.WorkPriorities.Count == 1 && c.WorkPriorityOf(Growing.defName) == 1, "work after Forget these: " + WorkSlot.Summary(c.WorkPriorities));
T.Check(Dialog_ManageCastes.WorkDlcNote(c) == null, "work DLC note after Forget these: " + Dialog_ManageCastes.WorkDlcNote(c));
List<string> changed = WorkSlot.Of(p).Where(kv => before[kv.Key] != kv.Value).Select(kv => kv.Key).ToList();
T.Check(changed.Count == 0, "Forget these changed a member's work: " + string.Join(", ", changed));
T.Equal(0, CasteManager.Overrides(p).Count, "member's overrides after Forget these");
// Only work of a DLC that is off: forgetting it leaves work alone.
SetWorkRaw(c, off.ToDictionary(name => name, name => 2));
Dialog_ManageCastes.ForgetDlcOffWork(c);
T.Check(!c.IsManaged(CasteSlot.Work), "the caste still manages work after forgetting its only work types");
}
// ---- Anomaly: a mutant whose def is gone -------------------------------------------------
[BlaxTest("dlc: a mutant whose def is gone (a save made with Anomaly loaded without it) is left alone: no slot, no join, and the slot checks and the Caste column throw nothing")]
public static void MutantWithoutDef()
{
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
Caste c = Fixtures.NewCaste("Mutant without def");
CasteManager.SetSlot(c, CasteSlot.Food, Current.Game.foodRestrictionDatabase.DefaultFoodRestriction());
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "setup: Assign failed");
T.Check(!p.IsMutant, "setup: the colonist is already a mutant");
// The game's own policy getters throw for this pawn (they read mutant.Def), so Castes must not call them.
var tracker = (Pawn_MutantTracker)RuntimeHelpers.GetUninitializedObject(typeof(Pawn_MutantTracker));
AccessTools.Field(typeof(Pawn_MutantTracker), "pawn").SetValue(tracker, p);
p.mutant = tracker;
try
{
T.Check(p.IsMutant && p.mutant.Def == null, "setup: not a mutant without a def");
foreach (CasteSlot slot in CasteUtility.AllSlots)
T.Check(!CasteUtility.CanUse(p, slot), "CanUse(" + slot + ") is true for a mutant without a def");
T.Check(!JoinDefaults.Eligible(p), "a mutant without a def is eligible for a caste");
JoinDefaults.Enqueue(p, JoinDefaults.StatusFallback);
T.Check(!JoinDefaults.IsQueued(p), "a mutant without a def was queued");
T.Equal(0, CasteManager.Overrides(p).Count, "overrides of a mutant without a def");
CasteManager.WorkOverrides(p);
T.Equal(0, CasteUtility.Apply(p, c).Count, "slots Apply wrote on a mutant without a def");
T.Check(!JoinDefaults.WillChange(p), "a mutant without a def shows as pending");
T.Check(!PawnColumnWorker_BlaxCaste.CellLabel(p).NullOrEmpty(), "the Caste column has no label for the pawn");
PawnColumnWorker_BlaxCaste.CellTip(p);
PawnColumnWorker_BlaxCaste.MenuEntries(p);
CasteManager.PawnsToAssignByStatus();
}
finally
{
p.mutant = null;
}
}
// ---- Ideology: slave rows and texts ------------------------------------------------------
[BlaxTest("dlc: the join defaults show the slave rows with Ideology; without it only while a slave row picks a caste, with a Needs Ideology note")]
public static void SlaveRowsWithoutIdeology()
{
const string tipKey = "BlaxCastes_AssignByStatusTip";
List<string> rows = Dialog_JoinDefaults.VisibleRows();
if (ModsConfig.IdeologyActive)
{
T.Equal(5, rows.Count, "rows with Ideology");
T.Check(Dialog_JoinDefaults.SlaveRowsNote() == null, "Needs Ideology note with Ideology on");
T.Equal(tipKey, Dialog_ManageCastes.AssignByStatusTipKey(), "Assign by status tooltip with Ideology on");
return;
}
T.Check(!PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction.Any(x => x.IsSlaveOfColony), "setup: a slave exists without Ideology");
T.Equal(3, rows.Count, "rows without Ideology while the slave rows pick nothing (" + string.Join(", ", rows) + ")");
T.Check(Dialog_JoinDefaults.SlaveRowsNote() == null, "Needs Ideology note while the slave rows are hidden");
T.Equal(tipKey + "NoIdeology", Dialog_ManageCastes.AssignByStatusTipKey(), "Assign by status tooltip while the slave rows are hidden");
// A save made with Ideology: its slave row still picks a caste, so the rows show, with the note, and
// Assign by status still names the new-slave row.
Caste c = Fixtures.NewCaste("Slave row without Ideology");
T.Check(CasteManager.SetJoinRow(JoinReason.BoughtSlave, JoinRowMode.SpecificCaste, c), "setup: SetJoinRow failed");
rows = Dialog_JoinDefaults.VisibleRows();
T.Equal(5, rows.Count, "rows without Ideology while a slave row picks a caste");
string note = Dialog_JoinDefaults.SlaveRowsNote();
T.Check(note != null && note.Contains("Ideology"), "Needs Ideology note: " + note);
T.Equal(tipKey, Dialog_ManageCastes.AssignByStatusTipKey(), "Assign by status tooltip while the slave rows show");
}
[BlaxTest("dlc: without Ideology the texts that name slave events or the Slave caste use their Ideology-free variant; with it the original")]
public static void IdeologyTexts()
{
string[] keys =
{
"BlaxCastes_AssignByStatusTip", "BlaxCastes_JoinDefaultsButtonTip", "BlaxCastes_SettingJoinDefaultsTip",
"BlaxCastes_SettingReturnToPreviousTip", "BlaxCastes_SettingSeedStarter", "BlaxCastes_SettingSeedStarterTip",
"BlaxCastes_RowTip_newColonist", "BlaxCastes_RowTip_newPrisoner",
};
foreach (string key in keys)
{
T.Check((key + "NoIdeology").CanTranslate(), key + "NoIdeology is missing from Keyed");
string picked = DlcSupport.IdeologyKey(key);
T.Equal(ModsConfig.IdeologyActive ? key : key + "NoIdeology", picked, "text picked for " + key);
string text = picked.Translate();
if (!ModsConfig.IdeologyActive)
T.Check(!text.Contains("enslave") && !text.Contains("freed") && !text.Contains("imprisoned slave") && !text.Contains("Slave caste,"),
key + " without Ideology names a slave event: " + text);
}
T.Equal("BlaxCastes_CellHint", DlcSupport.IdeologyKey("BlaxCastes_CellHint"), "a key without a variant");
T.Check(BlaxCastesMod.ShowsNoIdeologyNote == !ModsConfig.IdeologyActive, "the settings page's Ideology note");
T.Check((BlaxCastesMod.SeedStarterNote() == null) == ModsConfig.IdeologyActive, "the starter castes note: " + BlaxCastesMod.SeedStarterNote());
T.Check("BlaxCastes_JoinSlaveRowsNoIdeology".CanTranslate() && "BlaxCastes_StarterSlaveAddedMessage".CanTranslate(), "Ideology strings missing from Keyed");
}
// ---- a save made with a DLC, loaded without it ---------------------------------------------
[BlaxTest("dlc: set up a caste with Meditate hours and Childcare, Dark study and Fishing priorities for the reload")]
public static void ReloadSetup()
{
Caste c = Fixtures.KeepCaste(Fixtures.NewCaste("DLC names reload"));
SetScheduleRaw(c, MeditateSchedule());
SetWorkRaw(c, new Dictionary<string, int> { ["Growing"] = 1, ["Childcare"] = 1, ["DarkStudy"] = 2, ["Fishing"] = 3 });
Pawn member = Fixtures.Keep(Fixtures.Colonist());
Fixtures.Unqueue(member);
T.Check(CasteManager.Assign(member, c, false, JoinReason.Manual), "Assign failed");
T.Carry["dlcCaste"] = c.id.ToString();
T.Carry["dlcMember"] = member.ThingID;
}
[BlaxTest("dlc: after the reload the caste still has every DLC name, no Blax Castes warning was logged by the load, and its member applies cleanly", phase: 2)]
public static void ReloadKeepsDlcNames()
{
T.Check(T.Carry.TryGetValue("dlcCaste", out string id), "phase 1 did not set up the caste");
List<string> stray = TestRunner.StrayWarnings();
T.Check(stray.Count == 0, "Blax Castes warnings outside the tests (the save or the load): " + string.Join(" | ", stray.Take(3)));
Caste c = Fixtures.Comp.Castes.FirstOrDefault(x => x.id.ToString() == id);
T.NotNull(c, "caste " + id + " after reload");
T.Check(c.Schedule != null && c.Schedule[3] == "Meditate" && c.Schedule[4] == "Meditate", "Meditate hours after reload: " + (c.Schedule == null ? "none" : string.Join(",", c.Schedule)));
foreach (string name in new[] { "Growing", "Childcare", "DarkStudy", "Fishing" })
T.Check(c.WorkPriorities.ContainsKey(name), name + " lost over the reload: " + WorkSlot.Summary(c.WorkPriorities));
Pawn member = Fixtures.FindPawnById(T.Carry["dlcMember"]);
T.NotNull(member, "member after reload");
T.Check(Fixtures.Comp.CasteOf(member) == c, "member's caste after reload");
CasteManager.ResetToCaste(member);
T.Equal(ModsConfig.RoyaltyActive ? "Meditate" : TimeAssignmentDefOf.Anything.defName, member.timetable.GetAssignment(3).defName, "member's hour 3 after the reload");
T.Equal(0, CasteManager.Overrides(member).Count, "member's overrides after Reset to caste");
}
}
}

View File

@ -20,6 +20,7 @@ namespace BlaxCastesTests
private static readonly List<Caste> madeCastes = new List<Caste>(); private static readonly List<Caste> madeCastes = new List<Caste>();
private static readonly HashSet<Caste> keptCastes = new HashSet<Caste>(); private static readonly HashSet<Caste> keptCastes = new HashSet<Caste>();
private static readonly List<QuestPart_ExtraFaction> lodgerParts = new List<QuestPart_ExtraFaction>(); private static readonly List<QuestPart_ExtraFaction> lodgerParts = new List<QuestPart_ExtraFaction>();
private static readonly HashSet<Thing> removed = new HashSet<Thing>();
private static List<(string reason, JoinRowMode mode, Caste caste)> rowSnapshot; private static List<(string reason, JoinRowMode mode, Caste caste)> rowSnapshot;
private static Caste defaultSnapshot; private static Caste defaultSnapshot;
private static bool keepCasteState; private static bool keepCasteState;
@ -71,7 +72,7 @@ namespace BlaxCastesTests
public static Pawn ColonySlave(Faction origin = null) public static Pawn ColonySlave(Faction origin = null)
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction()); Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction());
Spawn(p); Spawn(p);
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
@ -114,7 +115,7 @@ namespace BlaxCastesTests
public static Pawn Baby() public static Pawn Baby()
{ {
if (!ModsConfig.BiotechActive) if (!ModsConfig.BiotechActive)
T.Skip("babies need Biotech"); T.Skip("needs Biotech (babies)");
Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Baby)); Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Baby));
T.Check(p.DevelopmentalStage.Baby(), "baby fixture is " + p.DevelopmentalStage + ", not a baby"); T.Check(p.DevelopmentalStage.Baby(), "baby fixture is " + p.DevelopmentalStage + ", not a baby");
return p; return p;
@ -293,33 +294,55 @@ namespace BlaxCastesTests
foreach (Pawn p in made) foreach (Pawn p in made)
{ {
if (p == null || kept.Contains(p)) continue; if (p == null || kept.Contains(p)) continue;
DropRitualObligations(p); Remove(p);
if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish);
else if (p.Spawned) p.Destroy(DestroyMode.Vanish);
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
} }
made.Clear(); made.Clear();
} }
/// <summary> /// <summary>
/// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or /// Takes a fixture pawn out of the game: its corpse or the pawn is destroyed, a world pawn is discarded.
/// blinding obligation when it joins or changes status (Ideology). The cleanup destroys the pawn or its /// Then every ritual obligation (Ideology) that points at a pawn removed so far is dropped: a funeral, or a
/// corpse, so drop those obligations too, or the save warns about a reference to a discarded pawn. /// scarification or blinding obligation, which the game gives each colonist on the map. Left behind, it makes
/// the save warn about a reference to a discarded pawn once the world pawn cleanup discards the pawn. The drop
/// comes after the destroy, since the destroy can add one itself (a destroyed corpse adds a funeral without
/// the body), and it covers pawns removed earlier, in case something added one to them since.
/// </summary> /// </summary>
private static void DropRitualObligations(Pawn p) public static void Remove(Pawn p)
{ {
if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) return;
Corpse corpse = p.Corpse; Corpse corpse = p.Corpse;
bool Hits(TargetInfo t) => t.HasThing && (t.Thing == p || (corpse != null && t.Thing == corpse)); if (corpse != null && corpse.Spawned) corpse.Destroy(DestroyMode.Vanish);
else if (p.Spawned) p.Destroy(DestroyMode.Vanish);
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
removed.Add(p);
if (corpse != null) removed.Add(corpse);
foreach (var (ritual, o, _) in RitualObligationsOn(t => removed.Contains(t)).ToList())
ritual.RemoveObligation(o);
}
/// <summary>The active ritual obligations (Ideology) that point at a pawn or its corpse, as ritual def names.</summary>
public static List<string> RitualObligationsOn(Pawn p)
{
Corpse corpse = p.Corpse;
return RitualObligationsOn(t => t == p || (corpse != null && t == corpse)).Select(x => x.ritual.def.defName).ToList();
}
/// <summary>Active ritual obligations that point at a discarded thing, which the save cannot store, as "ritual: thing".</summary>
public static List<string> RitualObligationsOnDiscarded() =>
RitualObligationsOn(t => t.Discarded).Select(x => x.ritual.def.defName + ": " + x.target).ToList();
private static IEnumerable<(Precept_Ritual ritual, RitualObligation obligation, Thing target)> RitualObligationsOn(System.Func<Thing, bool> hits)
{
if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) yield break;
foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading) foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading)
{ {
foreach (Precept precept in ideo.PreceptsListForReading) foreach (Precept precept in ideo.PreceptsListForReading)
{ {
if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue; if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue;
foreach (RitualObligation o in ritual.activeObligations.ToList()) foreach (RitualObligation o in ritual.activeObligations)
{ {
if (o != null && (Hits(o.targetA) || Hits(o.targetB) || Hits(o.targetC))) if (o == null) continue;
ritual.RemoveObligation(o); Thing hit = new[] { o.targetA, o.targetB, o.targetC }.Where(t => t.HasThing).Select(t => t.Thing).FirstOrDefault(hits);
if (hit != null) yield return (ritual, o, hit);
} }
} }
} }

View File

@ -71,6 +71,15 @@ namespace BlaxCastesTests
public static void Skip(string reason) => throw new TestSkipped(reason); public static void Skip(string reason) => throw new TestSkipped(reason);
/// <summary>
/// The current test must log a "[Blax Castes]" warning that contains the fragment. Any other Blax Castes
/// warning fails the test, the way an error does.
/// </summary>
public static void ExpectWarning(string fragment) => TestRunner.ExpectWarning(fragment, required: true);
/// <summary>The current test may log "[Blax Castes]" warnings that contain the fragment (for paths this machine cannot always reach).</summary>
public static void AllowWarning(string fragment) => TestRunner.ExpectWarning(fragment, required: false);
/// <summary>Adds an INFO line under the current test in the results file.</summary> /// <summary>Adds an INFO line under the current test in the results file.</summary>
public static void Info(string message) => TestRunner.Note(message); public static void Info(string message) => TestRunner.Note(message);
@ -92,7 +101,30 @@ namespace BlaxCastesTests
private static string currentTest; private static string currentTest;
private static readonly List<string> modErrors = new List<string>(); private static readonly List<string> modErrors = new List<string>();
private static readonly List<string> otherErrors = new List<string>(); private static readonly List<string> otherErrors = new List<string>();
// "[Blax Castes]" warnings: (where, text). Where is the test name or "(between tests)".
private static readonly List<(string where, string text)> modWarnings = new List<(string, string)>();
private static readonly List<(string fragment, bool required)> expectedWarnings = new List<(string, bool)>();
private static bool hooked; private static bool hooked;
public const string BetweenTests = "(between tests)";
/// <summary>The "[Blax Castes]" warnings in the game log before the first test ran: startup, defs, patches, the new game.</summary>
public static List<string> StartupWarnings { get; private set; } = new List<string>();
/// <summary>The errors in the game log before the first test ran that name Blax Castes or come from its code.</summary>
public static List<string> StartupErrors { get; private set; } = new List<string>();
/// <summary>The "[Blax Castes]" warnings logged outside a test so far (a load, a save), as text.</summary>
public static List<string> StrayWarnings()
{
lock (modErrors) return modWarnings.Where(w => w.where == BetweenTests).Select(w => w.text).ToList();
}
internal static void ExpectWarning(string fragment, bool required)
{
if (!string.IsNullOrEmpty(fragment))
expectedWarnings.Add((fragment, required));
}
private int settleFrames; private int settleFrames;
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxcastestests"); public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxcastestests");
@ -125,6 +157,9 @@ namespace BlaxCastesTests
try { T.Carry[kv.Key] = kv.Value(); } try { T.Carry[kv.Key] = kv.Value(); }
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); } catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
} }
// The save warns about each of these; name them here, so the test that left one is easy to find.
foreach (string left in Fixtures.RitualObligationsOnDiscarded())
Note("ritual obligation on a discarded pawn before the save: " + left);
GameDataSaveLoader.SaveGame(SaveName); GameDataSaveLoader.SaveGame(SaveName);
GameDataSaveLoader.LoadGame(SaveName); GameDataSaveLoader.LoadGame(SaveName);
} }
@ -146,6 +181,11 @@ namespace BlaxCastesTests
private static void Begin() private static void Begin()
{ {
try { File.Delete(ResultPath); } catch { } try { File.Delete(ResultPath); } catch { }
StartupWarnings = Log.Messages.Where(m => m.type == LogMessageType.Warning && m.text != null && m.text.Contains("[Blax Castes]"))
.Select(m => m.text).ToList();
StartupErrors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null
&& (m.text.Contains("Blax Castes") || m.text.Contains("BlaxCastes") || (m.StackTrace != null && m.StackTrace.Contains("at BlaxCastes."))))
.Select(m => OneLine(m.text)).ToList();
HookLog(); HookLog();
Line("BEGIN Blax Castes in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev); Line("BEGIN Blax Castes in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
Fixtures.QuietStoryteller(); Fixtures.QuietStoryteller();
@ -158,8 +198,15 @@ namespace BlaxCastesTests
hooked = true; hooked = true;
Application.logMessageReceivedThreaded += (text, stack, type) => Application.logMessageReceivedThreaded += (text, stack, type) =>
{ {
if (type == LogType.Warning)
{
// Only the mod's own warnings: they all start with "[Blax Castes]".
if (text != null && text.Contains("[Blax Castes]"))
lock (modErrors) modWarnings.Add((currentTest ?? BetweenTests, OneLine(text)));
return;
}
if (type != LogType.Error && type != LogType.Exception) return; if (type != LogType.Error && type != LogType.Exception) return;
string where = currentTest ?? "(between tests)"; string where = currentTest ?? BetweenTests;
string entry = where + ": " + OneLine(text); string entry = where + ": " + OneLine(text);
bool ours = !IsKnownForeignError(text, stack) bool ours = !IsKnownForeignError(text, stack)
&& ((text != null && (text.Contains("BlaxCastes") || text.Contains("Blax Castes"))) || (stack != null && stack.Contains("BlaxCastes"))); && ((text != null && (text.Contains("BlaxCastes") || text.Contains("Blax Castes"))) || (stack != null && stack.Contains("BlaxCastes")));
@ -207,8 +254,9 @@ namespace BlaxCastesTests
private static void RunOne(string name, MethodInfo method) private static void RunOne(string name, MethodInfo method)
{ {
currentTest = name; currentTest = name;
int modErrorsBefore, otherErrorsBefore; expectedWarnings.Clear();
lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; } int modErrorsBefore, otherErrorsBefore, warningsBefore;
lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; warningsBefore = modWarnings.Count; }
var settings = Fixtures.SnapshotSettings(); var settings = Fixtures.SnapshotSettings();
string status = "PASS", detail = ""; string status = "PASS", detail = "";
try try
@ -238,19 +286,38 @@ namespace BlaxCastesTests
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); } try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
} }
List<string> newModErrors, newOtherErrors; List<string> newModErrors, newOtherErrors, newWarnings;
lock (modErrors) lock (modErrors)
{ {
newModErrors = modErrors.Skip(modErrorsBefore).ToList(); newModErrors = modErrors.Skip(modErrorsBefore).ToList();
newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList(); newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList();
newWarnings = modWarnings.Skip(warningsBefore).Select(w => w.text).ToList();
} }
if (status == "PASS" && newModErrors.Count > 0) if (status == "PASS" && newModErrors.Count > 0)
{ {
status = "FAIL"; status = "FAIL";
detail = "Blax Castes logged errors: " + string.Join(" | ", newModErrors.Take(3)); detail = "Blax Castes logged errors: " + string.Join(" | ", newModErrors.Take(3));
} }
if (status == "PASS")
{
// Zero warnings from the mod, except the ones the test declared.
var unexpected = newWarnings.Where(w => !expectedWarnings.Any(e => w.Contains(e.fragment))).ToList();
var missing = expectedWarnings.Where(e => e.required && !newWarnings.Any(w => w.Contains(e.fragment))).Select(e => e.fragment).ToList();
if (unexpected.Count > 0)
{
status = "FAIL";
detail = "Blax Castes logged warnings: " + string.Join(" | ", unexpected.Take(3));
}
else if (missing.Count > 0)
{
status = "FAIL";
detail = "expected Blax Castes warnings were not logged: " + string.Join(" | ", missing);
}
}
Record(status, name, detail); Record(status, name, detail);
foreach (string w in newWarnings.Take(5)) Line(" WARN " + w);
foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e); foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e);
expectedWarnings.Clear();
currentTest = null; currentTest = null;
} }
@ -258,9 +325,11 @@ namespace BlaxCastesTests
{ {
stage = 2; stage = 2;
List<string> stray; List<string> stray;
lock (modErrors) stray = modErrors.Where(e => e.StartsWith("(between tests)")).ToList(); lock (modErrors) stray = modErrors.Where(e => e.StartsWith(BetweenTests)).ToList();
List<string> strayWarnings = StrayWarnings();
foreach (string e in stray.Take(10)) Line(" MODERR " + e); foreach (string e in stray.Take(10)) Line(" MODERR " + e);
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count}"); foreach (string w in strayWarnings.Take(10)) Line(" MODWARN " + w);
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count} strayModWarnings={strayWarnings.Count}");
Line("END"); Line("END");
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}"); Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
Root.Shutdown(); Root.Shutdown();

View File

@ -137,7 +137,7 @@ namespace BlaxCastesTests
public static void BoughtAsSlave() public static void BoughtAsSlave()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Caste bought = RowCaste("Bought slaves join test", SlaveOrSoldier(), Simple()); Caste bought = RowCaste("Bought slaves join test", SlaveOrSoldier(), Simple());
Caste wrong = FoodCaste("Wrong row (bought slave)", Paste()); Caste wrong = FoodCaste("Wrong row (bought slave)", Paste());
Row(JoinReason.BoughtSlave, bought); Row(JoinReason.BoughtSlave, bought);
@ -191,7 +191,7 @@ namespace BlaxCastesTests
public static void EnslavedPrisoner() public static void EnslavedPrisoner()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Caste slaves = RowCaste("New slaves join test", SlaveOrSoldier(), Simple()); Caste slaves = RowCaste("New slaves join test", SlaveOrSoldier(), Simple());
Caste wrong = FoodCaste("Wrong row (enslaved)", Paste()); Caste wrong = FoodCaste("Wrong row (enslaved)", Paste());
Row(JoinReason.NewSlave, slaves); Row(JoinReason.NewSlave, slaves);
@ -244,10 +244,17 @@ namespace BlaxCastesTests
Caste captured = FoodCaste("Captured join test", Simple(), MedicalCareCategory.NoMeds); Caste captured = FoodCaste("Captured join test", Simple(), MedicalCareCategory.NoMeds);
Row(JoinReason.NewPrisoner, captured); Row(JoinReason.NewPrisoner, captured);
Pawn raider = Fixtures.Spawn(Fixtures.Generate(hostile.def.basicMemberKind ?? PawnKindDefOf.Slave, hostile)); // Some generated raiders shrug off DamageUntilDowned (pain-blocking genes or implants), so try a few.
HealthUtility.DamageUntilDowned(raider, allowBleedingWounds: false); Pawn raider = null;
if (raider.Dead) for (int i = 0; i < 5 && raider == null; i++)
T.Skip("the raider died while being downed"); {
Pawn candidate = Fixtures.Spawn(Fixtures.Generate(hostile.def.basicMemberKind ?? PawnKindDefOf.Slave, hostile));
HealthUtility.DamageUntilDowned(candidate, allowBleedingWounds: false);
if (candidate.Downed && !candidate.Dead)
raider = candidate;
}
if (raider == null)
T.Skip("no generated raider could be downed alive in 5 tries");
T.Check(raider.Downed, "setup: the raider is not downed"); T.Check(raider.Downed, "setup: the raider is not downed");
raider.guest.CapturedBy(Faction.OfPlayer, Fixtures.Colonist()); raider.guest.CapturedBy(Faction.OfPlayer, Fixtures.Colonist());
@ -288,7 +295,7 @@ namespace BlaxCastesTests
T.Check(Fixtures.Comp.CasteOf(p) == c, Who(p) + " lost its caste"); T.Check(Fixtures.Comp.CasteOf(p) == c, Who(p) + " lost its caste");
} }
if (slave == null) if (slave == null)
T.Skip("slaves need Ideology; the colonist and prisoner checks passed"); T.Skip("needs Ideology (slaves); the colonist and prisoner checks passed");
} }
[BlaxTest("join: a pawn sold between queue and apply is dropped without errors, and a sold member leaves its caste")] [BlaxTest("join: a pawn sold between queue and apply is dropped without errors, and a sold member leaves its caste")]
@ -436,7 +443,7 @@ namespace BlaxCastesTests
T.Equal(JoinReason.NewPrisoner, JoinDefaults.RowFor(JoinScopes.Bought, prisoner), "bought row of a prisoner falls back to its status"); T.Equal(JoinReason.NewPrisoner, JoinDefaults.RowFor(JoinScopes.Bought, prisoner), "bought row of a prisoner falls back to its status");
Unqueue(prisoner); Unqueue(prisoner);
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology; colonist and prisoner rows passed"); T.Skip("needs Ideology (slaves); colonist and prisoner rows passed");
Pawn slave = Fixtures.ColonySlave(); Pawn slave = Fixtures.ColonySlave();
T.Equal(JoinReason.BoughtSlave, JoinDefaults.RowFor(JoinScopes.Bought, slave), "bought slave row"); T.Equal(JoinReason.BoughtSlave, JoinDefaults.RowFor(JoinScopes.Bought, slave), "bought slave row");
T.Equal(JoinReason.NewSlave, JoinDefaults.RowFor(JoinDefaults.StatusFallback, slave), "status row of a slave"); T.Equal(JoinReason.NewSlave, JoinDefaults.RowFor(JoinDefaults.StatusFallback, slave), "status row of a slave");
@ -450,7 +457,7 @@ namespace BlaxCastesTests
JoinDefaults.Enqueue(lodger, JoinDefaults.StatusFallback); JoinDefaults.Enqueue(lodger, JoinDefaults.StatusFallback);
T.Check(!JoinDefaults.IsQueued(lodger), "a quest lodger was queued"); T.Check(!JoinDefaults.IsQueued(lodger), "a quest lodger was queued");
if (!ModsConfig.BiotechActive) if (!ModsConfig.BiotechActive)
T.Skip("babies need Biotech; the lodger check passed"); T.Skip("needs Biotech (babies); the lodger check passed");
Pawn baby = Fixtures.Baby(); Pawn baby = Fixtures.Baby();
JoinDefaults.Enqueue(baby, JoinDefaults.StatusFallback); JoinDefaults.Enqueue(baby, JoinDefaults.StatusFallback);
T.Check(!JoinDefaults.IsQueued(baby), "a baby was queued"); T.Check(!JoinDefaults.IsQueued(baby), "a baby was queued");
@ -532,7 +539,7 @@ namespace BlaxCastesTests
public static void BuyModeChoice() public static void BuyModeChoice()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
bool tasoc = Compat.IsActive(TaSoC); bool tasoc = Compat.IsActive(TaSoC);
bool slaves = Compat.IsActive(Compat.BlaxSlaves); bool slaves = Compat.IsActive(Compat.BlaxSlaves);
if (!tasoc && !slaves) if (!tasoc && !slaves)

View File

@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Linq; using System.Linq;
using BlaxCastes; using BlaxCastes;
using RimWorld; using RimWorld;
@ -53,6 +54,40 @@ namespace BlaxCastesTests
T.Equal(1, Current.Game.components.Count(x => x is GameComponent_BlaxCastes), "GameComponent_BlaxCastes in the game"); T.Equal(1, Current.Game.components.Count(x => x is GameComponent_BlaxCastes), "GameComponent_BlaxCastes in the game");
} }
[BlaxTest("save: removed fixture pawns keep no ritual obligation, so the save never points at a discarded pawn (Ideology)")]
public static void RemoveDropsRitualObligations()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (ritual obligations)");
Precept_Ritual ritual = Find.IdeoManager.IdeosListForReading.SelectMany(i => i.PreceptsListForReading).OfType<Precept_Ritual>().FirstOrDefault();
if (ritual == null)
T.Skip("no ideoligion in this game has a ritual");
void Oblige(Pawn p) =>
(ritual.activeObligations ?? (ritual.activeObligations = new List<RitualObligation>())).Add(new RitualObligation(ritual, p, expires: false));
// A living colonist with an obligation on it, as a scarification or blinding ritual gives each colonist on the map.
Pawn living = Fixtures.Colonist();
Oblige(living);
// A dead colonist: a funeral when its ideoligion has one, then a funeral without the body once the corpse is destroyed.
Pawn dead = Fixtures.Colonist();
dead.Kill(null);
T.Check(dead.Dead && dead.Corpse != null && dead.Corpse.Spawned, "setup: the dead colonist has no spawned corpse");
Fixtures.Remove(living);
Fixtures.Remove(dead);
T.Check(!living.Spawned && dead.Corpse == null, "the removed pawns are still on the map");
foreach (Pawn p in new[] { living, dead })
{
List<string> left = Fixtures.RitualObligationsOn(p);
T.Check(left.Count == 0, "ritual obligations left on the removed " + p.LabelShort + ": " + string.Join(", ", left));
}
// One that reaches a removed pawn later goes with the next removal.
Oblige(living);
Fixtures.Remove(Fixtures.Colonist());
T.Check(Fixtures.RitualObligationsOn(living).Count == 0, "an obligation added to a removed pawn survived the next removal");
}
// Runs last in this class (source order): the castes, rows and pawns it keeps are checked after the reload. // Runs last in this class (source order): the castes, rows and pawns it keeps are checked after the reload.
[BlaxTest("save: set up castes, rows and memberships for the reload")] [BlaxTest("save: set up castes, rows and memberships for the reload")]
public static void ReloadSetup() public static void ReloadSetup()

View File

@ -34,7 +34,9 @@ namespace BlaxCastesTests
"BlaxCastes_SettingSeedStarter", "BlaxCastes_SettingSeedStarterTip", "BlaxCastes_SettingWarnOverlaps", "BlaxCastes_SettingWarnOverlapsTip", "BlaxCastes_SettingSeedStarter", "BlaxCastes_SettingSeedStarterTip", "BlaxCastes_SettingWarnOverlaps", "BlaxCastes_SettingWarnOverlapsTip",
"BlaxCastes_SettingShowAssignColumn", "BlaxCastes_SettingShowAssignColumnTip", "BlaxCastes_SettingNoIdeology", "BlaxCastes_SettingsReset", "BlaxCastes_SettingShowAssignColumn", "BlaxCastes_SettingShowAssignColumnTip", "BlaxCastes_SettingNoIdeology", "BlaxCastes_SettingsReset",
"BlaxCastes_SettingWorkPriorities", "BlaxCastes_SettingWorkPrioritiesTip", "BlaxCastes_SettingWeaponLoadout", "BlaxCastes_SettingWeaponLoadoutTip", "BlaxCastes_SettingWorkPriorities", "BlaxCastes_SettingWorkPrioritiesTip", "BlaxCastes_SettingWeaponLoadout", "BlaxCastes_SettingWeaponLoadoutTip",
"BlaxCastes_WorkManagerActive", "BlaxCastes_WorkManagerActive", "BlaxCastes_SettingSeedStarterSlaveNote",
"BlaxCastes_SettingJoinDefaultsTipNoIdeology", "BlaxCastes_SettingReturnToPreviousTipNoIdeology",
"BlaxCastes_SettingSeedStarterNoIdeology", "BlaxCastes_SettingSeedStarterTipNoIdeology",
}; };
private static FieldInfo[] Fields => typeof(BlaxCastesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance); private static FieldInfo[] Fields => typeof(BlaxCastesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance);

View File

@ -219,10 +219,11 @@ namespace BlaxCastesTests
T.Equal(TimeAssignmentDefOf.Joy, a.timetable.GetAssignment(16), "A's schedule changed when the caste let go of it"); T.Equal(TimeAssignmentDefOf.Joy, a.timetable.GetAssignment(16), "A's schedule changed when the caste let go of it");
} }
[BlaxTest("schedule: an unknown time assignment becomes Anything (on set, on apply and in the load check); Meditate without Royalty too")] [BlaxTest("schedule: an unknown time assignment becomes Anything (on set, on apply and in the load check, with one warning); Meditate is stored either way and applies as Anything without Royalty")]
public static void ScheduleUnknownName() public static void ScheduleUnknownName()
{ {
const string unknown = "BlaxCastesNoSuchAssignment"; const string unknown = "BlaxCastesNoSuchAssignment";
T.ExpectWarning("Unknown hours");
string anything = TimeAssignmentDefOf.Anything.defName; string anything = TimeAssignmentDefOf.Anything.defName;
List<string> names = NightSchedule(); List<string> names = NightSchedule();
names[2] = unknown; names[2] = unknown;
@ -230,8 +231,8 @@ namespace BlaxCastesTests
Caste c = Fixtures.NewCaste("Unknown hours"); Caste c = Fixtures.NewCaste("Unknown hours");
CasteManager.SetSlot(c, CasteSlot.Schedule, names); CasteManager.SetSlot(c, CasteSlot.Schedule, names);
T.Equal(anything, c.Schedule[2], "stored hour with an unknown assignment"); T.Equal(anything, c.Schedule[2], "stored hour with an unknown assignment");
T.Equal("Meditate", c.Schedule[3], "stored Meditate hour (Royalty " + ModsConfig.RoyaltyActive + ")");
string meditate = ModsConfig.RoyaltyActive ? "Meditate" : anything; string meditate = ModsConfig.RoyaltyActive ? "Meditate" : anything;
T.Equal(meditate, c.Schedule[3], "stored Meditate hour (Royalty " + ModsConfig.RoyaltyActive + ")");
Pawn p = Fixtures.Colonist(); Pawn p = Fixtures.Colonist();
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed"); T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
@ -248,6 +249,22 @@ namespace BlaxCastesTests
T.Equal(0, CasteManager.Overrides(p).Count, "an unknown stored hour counts as an override"); T.Equal(0, CasteManager.Overrides(p).Count, "an unknown stored hour counts as an override");
CheckSlots(); CheckSlots();
T.Equal(anything, c.Schedule[5], "stored hour 5 after the load check"); T.Equal(anything, c.Schedule[5], "stored hour 5 after the load check");
T.Equal("Meditate", c.Schedule[3], "stored Meditate hour after the load check");
}
[BlaxTest("work: a work type nothing knows (a removed mod) is dropped by the load check with one warning; the caste's other types stay")]
public static void WorkUnknownName()
{
const string unknown = "BlaxCastesNoSuchWork";
T.ExpectWarning(unknown);
Caste c = Fixtures.NewCaste("Unknown work");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
var stored = new Dictionary<string, int>(c.WorkPriorities) { [unknown] = 2 };
AccessTools.Field(typeof(Caste), "workPriorities").SetValue(c, stored);
T.Check(WorkSlot.Summary(c.WorkPriorities).Contains(unknown), "setup: the unknown type is not in the summary: " + WorkSlot.Summary(c.WorkPriorities));
CheckSlots();
T.Check(!c.WorkPriorities.ContainsKey(unknown), "the unknown work type is still listed after the load check");
T.Equal(1, c.WorkPriorityOf(Growing.defName) ?? -1, "Growing after the load check");
} }
// ---- work priorities --------------------------------------------------------------------- // ---- work priorities ---------------------------------------------------------------------
@ -566,6 +583,7 @@ namespace BlaxCastesTests
T.Skip("Weapons Tab Reborn is active in this run"); T.Skip("Weapons Tab Reborn is active in this run");
T.Check(!WeaponsTab.Available && !CasteUtility.SlotActive(CasteSlot.Loadout), "the loadout slot is on without Weapons Tab Reborn"); T.Check(!WeaponsTab.Available && !CasteUtility.SlotActive(CasteSlot.Loadout), "the loadout slot is on without Weapons Tab Reborn");
T.Check(!Dialog_ManageCastes.ShowsLoadoutRow, "the manager shows the loadout row without Weapons Tab Reborn"); T.Check(!Dialog_ManageCastes.ShowsLoadoutRow, "the manager shows the loadout row without Weapons Tab Reborn");
T.ExpectWarning("Weapon loadout 1 ");
Caste c = Fixtures.NewCaste("No weapons tab"); Caste c = Fixtures.NewCaste("No weapons tab");
T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Loadout, 1), "members moved by setting a loadout without the mod"); T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Loadout, 1), "members moved by setting a loadout without the mod");
T.Check(!c.IsManaged(CasteSlot.Loadout), "a loadout was stored without the mod"); T.Check(!c.IsManaged(CasteSlot.Loadout), "a loadout was stored without the mod");
@ -639,6 +657,7 @@ namespace BlaxCastesTests
public static void LoadoutDeleted() public static void LoadoutDeleted()
{ {
NeedWeaponsTab(); NeedWeaponsTab();
T.AllowWarning("no longer in the game"); // the deleted loadouts, one warning per caste
int doomed = MakeLoadout("Blax test doomed"); int doomed = MakeLoadout("Blax test doomed");
Caste c = Fixtures.NewCaste("Doomed loadout"); Caste c = Fixtures.NewCaste("Doomed loadout");
CasteManager.SetSlot(c, CasteSlot.Loadout, doomed); CasteManager.SetSlot(c, CasteSlot.Loadout, doomed);
@ -677,6 +696,7 @@ namespace BlaxCastesTests
public static void LoadoutDatabaseMissing() public static void LoadoutDatabaseMissing()
{ {
NeedWeaponsTab(); NeedWeaponsTab();
T.AllowWarning("Weapons Tab Reborn"); // a failed or missing loadout API turns the slot off with a warning
FieldInfo field = LoadoutDatabaseField(); FieldInfo field = LoadoutDatabaseField();
object saved = field.GetValue(null); object saved = field.GetValue(null);
int? first = WeaponsTab.DefaultLoadoutId(); int? first = WeaponsTab.DefaultLoadoutId();
@ -709,6 +729,7 @@ namespace BlaxCastesTests
public static void LoadoutCallFailureIsNotMissing() public static void LoadoutCallFailureIsNotMissing()
{ {
NeedWeaponsTab(); NeedWeaponsTab();
T.AllowWarning("Weapons Tab Reborn"); // a failed or missing loadout API turns the slot off with a warning
FieldInfo field = LoadoutDatabaseField(); FieldInfo field = LoadoutDatabaseField();
FieldInfo ensureField = AccessTools.Field(typeof(WeaponsTab), "ensureDatabase"); FieldInfo ensureField = AccessTools.Field(typeof(WeaponsTab), "ensureDatabase");
T.NotNull(ensureField, "WeaponsTab.ensureDatabase"); T.NotNull(ensureField, "WeaponsTab.ensureDatabase");

View File

@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Linq; using System.Linq;
using BlaxCastes; using BlaxCastes;
using HarmonyLib; using HarmonyLib;
@ -16,7 +17,7 @@ namespace BlaxCastesTests
"BlaxCastes_ManageCastesTitle", "BlaxCastes_JoinDefaultsTitle", "BlaxCastes_ManageCastesTitle", "BlaxCastes_JoinDefaultsTitle",
}; };
[BlaxTest("startup: patcher ran and logged, no errors mentioning Blax Castes")] [BlaxTest("startup: patcher ran and logged, no errors mentioning Blax Castes and no Blax Castes warnings")]
public static void StartupLogged() public static void StartupLogged()
{ {
int ours = Harmony.GetAllPatchedMethods() int ours = Harmony.GetAllPatchedMethods()
@ -25,10 +26,17 @@ namespace BlaxCastesTests
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers)) .SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
.Count(p => p.owner == BlaxCastesStartup.HarmonyId); .Count(p => p.owner == BlaxCastesStartup.HarmonyId);
T.Info("Harmony patches owned by " + BlaxCastesStartup.HarmonyId + ": " + ours); T.Info("Harmony patches owned by " + BlaxCastesStartup.HarmonyId + ": " + ours);
bool logged = Log.Messages.Any(m => m.text != null && m.text.Contains("[Blax Castes]") && m.text.Contains("patches applied")); string line = Log.Messages.FirstOrDefault(m => m.text != null && m.text.Contains("[Blax Castes]") && m.text.Contains("patches applied"))?.text;
T.Check(logged, "startup line '[Blax Castes] N patches applied' not in the log"); T.Check(line != null, "startup line '[Blax Castes] N patches applied' not in the log");
T.Check(!line.Contains("failed"), "a patch failed to apply: " + line);
var errors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Castes") || m.text.Contains("BlaxCastes"))).ToList(); var errors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Castes") || m.text.Contains("BlaxCastes"))).ToList();
T.Check(errors.Count == 0, "errors mentioning Blax Castes at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text))); T.Check(errors.Count == 0, "errors mentioning Blax Castes at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
// Any DLC set: no error from the mod's code while the game started (world generation included), no
// cross-reference or patch warnings, and the Caste column placed by the XML patches.
List<string> startupErrors = TestRunner.StartupErrors;
T.Check(startupErrors.Count == 0, "errors from Blax Castes before the tests: " + string.Join(" | ", startupErrors.Take(3)));
List<string> warnings = TestRunner.StartupWarnings;
T.Check(warnings.Count == 0, "Blax Castes warnings at startup: " + string.Join(" | ", warnings.Take(3)));
} }
[BlaxTest("startup: settings, game component and strings are loaded")] [BlaxTest("startup: settings, game component and strings are loaded")]
@ -49,7 +57,8 @@ namespace BlaxCastesTests
T.Check(Compat.IsActive("blax.castes"), "Compat.IsActive(\"blax.castes\") is false while Blax Castes runs"); T.Check(Compat.IsActive("blax.castes"), "Compat.IsActive(\"blax.castes\") is false while Blax Castes runs");
T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false"); T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false");
T.Check(!Compat.IsActive("blax.castes.does.not.exist"), "Compat.IsActive is true for a made-up id"); T.Check(!Compat.IsActive("blax.castes.does.not.exist"), "Compat.IsActive is true for a made-up id");
T.Info("Blax Slaves active: " + Compat.IsActive(Compat.BlaxSlaves) + ", Ideology: " + ModsConfig.IdeologyActive + ", Biotech: " + ModsConfig.BiotechActive); T.Info("Blax Slaves active: " + Compat.IsActive(Compat.BlaxSlaves) + ", Royalty: " + ModsConfig.RoyaltyActive + ", Ideology: " + ModsConfig.IdeologyActive
+ ", Biotech: " + ModsConfig.BiotechActive + ", Anomaly: " + ModsConfig.AnomalyActive + ", Odyssey: " + ModsConfig.OdysseyActive);
} }
[BlaxTest("windows: the manager and join defaults windows construct, the join queue is callable")] [BlaxTest("windows: the manager and join defaults windows construct, the join queue is callable")]
@ -70,7 +79,7 @@ namespace BlaxCastesTests
Pawn pr = Fixtures.Prisoner(); Pawn pr = Fixtures.Prisoner();
T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology; colonist and prisoner fixtures passed"); T.Skip("needs Ideology (slaves); colonist and prisoner fixtures passed");
Pawn s = Fixtures.ColonySlave(); Pawn s = Fixtures.ColonySlave();
T.Check(s.IsSlaveOfColony, "slave fixture is not a slave of the colony"); T.Check(s.IsSlaveOfColony, "slave fixture is not a slave of the colony");
} }

View File

@ -112,11 +112,21 @@ namespace BlaxCastesTests
T.Check(!off.StarterCastesSeeded, "marked as seeded with the setting off, so turning it on later would do nothing"); T.Check(!off.StarterCastesSeeded, "marked as seeded with the setting off, so turning it on later would do nothing");
} }
[BlaxTest("starter: with the Slave outfit gone before seeding, the Slave caste leaves apparel unmanaged, and Create Slave outfit makes one")] [BlaxTest("starter: with the Slave outfit gone before seeding, the Slave caste leaves apparel unmanaged, and Create Slave outfit makes one; without Ideology there is no button and no Slave outfit")]
public static void MissingSlaveOutfit() public static void MissingSlaveOutfit()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("the Slave caste needs Ideology"); {
// The Ideology-off contract: no Create Slave outfit button, nothing created, no outfit counts as the Slave outfit.
T.Check(!StarterCastes.CanCreateSlaveOutfit, "Create Slave outfit is offered without Ideology");
int before = Current.Game.outfitDatabase.AllOutfits.Count;
T.Check(StarterCastes.CreateSlaveOutfit() == null, "Create Slave outfit made an outfit without Ideology");
T.Equal(before, Current.Game.outfitDatabase.AllOutfits.Count, "outfits after Create Slave outfit without Ideology");
T.Check(StarterCastes.SlaveOutfit() == null, "found a Slave outfit without Ideology");
List<string> slaveLike = Current.Game.outfitDatabase.AllOutfits.Where(o => StarterCastes.IsSlaveOutfit(o)).Select(o => o.label).ToList();
T.Check(slaveLike.Count == 0, "outfits that count as the Slave outfit without Ideology: " + string.Join(", ", slaveLike));
return;
}
ApparelPolicy slaveOutfit = Fixtures.Need(StarterCastes.SlaveOutfit(), "Slave outfit"); ApparelPolicy slaveOutfit = Fixtures.Need(StarterCastes.SlaveOutfit(), "Slave outfit");
T.Check(!StarterCastes.CanCreateSlaveOutfit, "Create Slave outfit is offered while the game has one"); T.Check(!StarterCastes.CanCreateSlaveOutfit, "Create Slave outfit is offered while the game has one");
var outfits = Current.Game.outfitDatabase.AllOutfits; var outfits = Current.Game.outfitDatabase.AllOutfits;
@ -180,10 +190,81 @@ namespace BlaxCastesTests
ApparelPolicy worker = Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker outfit"); ApparelPolicy worker = Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker outfit");
T.Check(!StarterCastes.IsSlaveOutfit(worker), "the Worker outfit counts as the Slave outfit"); T.Check(!StarterCastes.IsSlaveOutfit(worker), "the Worker outfit counts as the Slave outfit");
T.Check(!StarterCastes.IsSlaveOutfit(null), "null counts as the Slave outfit"); T.Check(!StarterCastes.IsSlaveOutfit(null), "null counts as the Slave outfit");
if (!ModsConfig.IdeologyActive)
T.Skip("the Slave outfit needs Ideology; the other checks passed");
T.Check(StarterCastes.IsSlaveOutfit(StarterCastes.SlaveOutfit()), "the Slave outfit does not count as the Slave outfit");
T.Check("BlaxCastes_SlaveOutfitCold".CanTranslate(), "the cold warning is missing from Keyed"); T.Check("BlaxCastes_SlaveOutfitCold".CanTranslate(), "the cold warning is missing from Keyed");
if (!ModsConfig.IdeologyActive)
{
T.Check(Current.Game.outfitDatabase.AllOutfits.All(o => !StarterCastes.IsSlaveOutfit(o)), "an outfit counts as the Slave outfit without Ideology, so the cold warning would show");
return;
}
T.Check(StarterCastes.IsSlaveOutfit(StarterCastes.SlaveOutfit()), "the Slave outfit does not count as the Slave outfit");
}
[BlaxTest("starter: a save seeded without Ideology owes the Slave caste and gets it once on its first load with Ideology, with a Slave outfit when the save has none, picked in the slave rows; nobody moves")]
public static void SlaveCasteLater()
{
Messages.Clear();
GameComponent_BlaxCastes fresh = Fresh();
T.Check(StarterCastes.SeedNewGame(fresh), "did not seed");
// Its loads must not post the first-load message into the game's history (the UI tests count it).
AccessTools.Method(typeof(GameComponent_BlaxCastes), "MarkFirstLoadMessageShown").Invoke(fresh, null);
if (!ModsConfig.IdeologyActive)
{
T.Check(fresh.SlaveCasteOwed, "a save seeded without Ideology does not owe the Slave caste");
fresh.LoadedGame();
T.Equal(2, fresh.Castes.Count, "castes after a load without Ideology (" + string.Join(", ", fresh.Castes.Select(c => c.label)) + ")");
T.Check(fresh.SlaveCasteOwed, "a load without Ideology cleared the owed Slave caste");
T.Check(StarterCastes.AddSlaveCasteIfOwed(fresh) == null, "AddSlaveCasteIfOwed added a caste without Ideology");
return;
}
T.Check(!fresh.SlaveCasteOwed, "a save seeded with Ideology owes the Slave caste");
// Make it look seeded without Ideology: no Slave caste, slave rows at No caste, the caste owed.
Caste seededSlave = ByLabel(fresh, StarterCastes.SlaveLabel);
T.NotNull(seededSlave, "setup: Slave caste");
AccessTools.Method(typeof(GameComponent_BlaxCastes), "RemoveCaste").Invoke(fresh, new object[] { seededSlave });
MethodInfo setRow = AccessTools.Method(typeof(GameComponent_BlaxCastes), "SetRowRaw");
foreach (string row in new[] { JoinReason.BoughtSlave, JoinReason.NewSlave })
setRow.Invoke(fresh, new object[] { row, JoinRowMode.NoCaste, null });
AccessTools.Method(typeof(GameComponent_BlaxCastes), "SetSlaveCasteOwed").Invoke(fresh, new object[] { true });
T.Equal(2, fresh.Castes.Count, "setup: castes without the Slave caste");
// A save started without Ideology has no Slave outfit: the game makes it only in a new game with
// Ideology. The game's own outfit is renamed for the test and named back afterwards.
OutfitDatabase outfits = Current.Game.outfitDatabase;
ApparelPolicy gameOutfit = StarterCastes.SlaveOutfit();
T.NotNull(gameOutfit, "setup: the game's Slave outfit");
string outfitLabel = gameOutfit.label;
int outfitCount = outfits.AllOutfits.Count;
ApparelPolicy created = null;
try
{
gameOutfit.label = outfitLabel + " (Blax Castes test)";
T.Check(StarterCastes.SlaveOutfit() == null, "setup: the game still has a Slave outfit");
fresh.LoadedGame();
Caste slave = ByLabel(fresh, StarterCastes.SlaveLabel);
T.NotNull(slave, "the Slave caste after the first load with Ideology");
T.Equal(3, fresh.Castes.Count, "castes after the first load with Ideology");
T.Check(!fresh.SlaveCasteOwed, "the Slave caste is still owed after it was added");
T.Check(fresh.ResolveRow(JoinReason.BoughtSlave) == slave && fresh.ResolveRow(JoinReason.NewSlave) == slave, "the slave rows do not pick the added Slave caste");
T.Check(slave.FoodPolicy == Simple(), "the added Slave caste's food: " + slave.FoodPolicy?.label);
created = StarterCastes.SlaveOutfit();
T.Check(created != null && created != gameOutfit && outfits.AllOutfits.Count == outfitCount + 1, "the Slave outfit was not created for the added Slave caste");
T.Check(slave.ApparelPolicy == created, "the added Slave caste's apparel: " + (slave.ApparelPolicy?.label ?? "unmanaged"));
T.Equal(0, fresh.Memberships.Count, "memberships after adding the Slave caste (nobody moves)");
string text = ((string)"BlaxCastes_StarterSlaveAddedMessage".Translate(slave.label.Named("CASTE"))).CapitalizeFirst();
T.Equal(1, MessagesWithText(text), "Slave caste messages after the first load with Ideology");
fresh.LoadedGame();
T.Equal(3, fresh.Castes.Count, "castes after a second load");
T.Equal(outfitCount + 1, outfits.AllOutfits.Count, "outfits after a second load");
T.Equal(1, MessagesWithText(text), "Slave caste messages after a second load");
}
finally
{
foreach (ApparelPolicy extra in outfits.AllOutfits.Where(o => o != gameOutfit && o.label == outfitLabel).ToList())
outfits.AllOutfits.Remove(extra);
gameOutfit.label = outfitLabel;
}
} }
[BlaxTest("starter: the save is still seeded after the reload, with one of each starter caste", phase: 2)] [BlaxTest("starter: the save is still seeded after the reload, with one of each starter caste", phase: 2)]

View File

@ -62,7 +62,7 @@ namespace BlaxCastesTests
private static Pawn HomeSlave() private static Pawn HomeSlave()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, Faction.OfPlayer)); Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, Faction.OfPlayer));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony && p.HomeFaction == Faction.OfPlayer, "setup: home slave fixture: slave=" + p.IsSlaveOfColony + ", home=" + p.HomeFaction); T.Check(p.IsSlaveOfColony && p.HomeFaction == Faction.OfPlayer, "setup: home slave fixture: slave=" + p.IsSlaveOfColony + ", home=" + p.HomeFaction);
@ -146,7 +146,7 @@ namespace BlaxCastesTests
public static void ArrestedThenEnslaved() public static void ArrestedThenEnslaved()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Caste miner = Make("Miner (enslave test)", Worker(), Fine()); Caste miner = Make("Miner (enslave test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (enslave test)", null, Paste()); Caste prisoners = Make("Prisoners (enslave test)", null, Paste());
Caste slaves = Make("Slaves (enslave test)", null, Simple()); Caste slaves = Make("Slaves (enslave test)", null, Simple());
@ -172,7 +172,7 @@ namespace BlaxCastesTests
public static void SoldAndBoughtBack() public static void SoldAndBoughtBack()
{ {
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology"); T.Skip("needs Ideology (slaves)");
Caste minerSlaves = Make("Miner slaves (sale test)", Worker(), Simple()); Caste minerSlaves = Make("Miner slaves (sale test)", Worker(), Simple());
Caste wrong = Make("Wrong row (sale test)", Nudist(), Paste()); Caste wrong = Make("Wrong row (sale test)", Nudist(), Paste());
Row(JoinReason.BoughtSlave, wrong); Row(JoinReason.BoughtSlave, wrong);
@ -648,7 +648,7 @@ namespace BlaxCastesTests
T.Info("escaped prisoner still a prisoner of the colony in the world: " + prisoner.IsPrisonerOfColony); T.Info("escaped prisoner still a prisoner of the colony in the world: " + prisoner.IsPrisonerOfColony);
if (!ModsConfig.IdeologyActive) if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology; the escaped prisoner check passed"); T.Skip("needs Ideology (slaves); the escaped prisoner check passed");
Pawn slave = Fixtures.ColonySlave(); Pawn slave = Fixtures.ColonySlave();
Fixtures.Unqueue(slave); Fixtures.Unqueue(slave);
T.Check(CasteManager.Assign(slave, slaves, true, JoinReason.NewSlave), "setup: Assign the slave failed"); T.Check(CasteManager.Assign(slave, slaves, true, JoinReason.NewSlave), "setup: Assign the slave failed");
@ -746,6 +746,107 @@ namespace BlaxCastesTests
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p)); T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p));
} }
/// <summary>Runs a leaving patch's prefix and finalizer around body, the way Harmony does (the patched method itself must not run: it would close the test map).</summary>
private static void AroundLeavingPatch(Type target, string method, string patchClass, Action body)
{
MethodInfo original = AccessTools.Method(target, method);
T.NotNull(original, target.Name + "." + method);
var info = Harmony.GetPatchInfo(original);
T.Check(info != null && info.Prefixes.Any(x => x.owner == BlaxCastesStartup.HarmonyId) && info.Finalizers.Any(x => x.owner == BlaxCastesStartup.HarmonyId),
"Blax Castes did not patch " + target.Name + "." + method);
Type patch = AccessTools.TypeByName("BlaxCastes." + patchClass);
T.NotNull(patch, "the patch class " + patchClass);
object[] prefixArgs = { Fixtures.Map, null };
AccessTools.Method(patch, "Prefix").Invoke(null, prefixArgs);
try
{
body();
}
finally
{
AccessTools.Method(patch, "Finalizer").Invoke(null, new object[] { null, prefixArgs[1] });
}
T.Equal(0, JoinScopes.Depth, "open join scopes after " + method);
}
[BlaxTest("status: a prisoner left on a closing map leaves its caste; nothing joins (no DLC needed)")]
public static void PrisonerLostWithClosingMap()
{
Caste prisoners = Make("Prisoners (closing map test)", null, Paste());
Pawn p = Fixtures.Prisoner();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
MethodInfo cleanUp = AccessTools.Method(typeof(MapDeiniter), "CleanUpAndPassToWorld");
T.NotNull(cleanUp, "MapDeiniter.CleanUpAndPassToWorld");
AroundLeavingPatch(typeof(MapDeiniter), "PassPawnsToWorld", "Patch_MapDeiniter_PassPawnsToWorld", () =>
{
p.DeSpawnOrDeselect();
cleanUp.Invoke(null, new object[] { p });
});
T.Check(!JoinDefaults.IsQueued(p), "the lost prisoner was queued (" + JoinDefaults.QueuedFor(p)?.reason + ")");
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p));
T.Check(!CasteManager.LiveMembers(prisoners).Contains(p), "the lost prisoner still counts as a member");
}
[BlaxTest("status: a gravship that leaves its map (Odyssey) takes the prisoner left behind out of its caste; a colonist left behind keeps its caste")]
public static void GravshipLeavesPawnsBehind()
{
Caste prisoners = Make("Prisoners (gravship test)", null, Paste());
Caste miner = Make("Miner (gravship test)", Worker(), Fine());
Pawn prisoner = Fixtures.Prisoner();
Fixtures.Unqueue(prisoner);
T.Check(CasteManager.Assign(prisoner, prisoners, true, JoinReason.NewPrisoner), "setup: Assign the prisoner failed");
Pawn colonist = Fixtures.Colonist();
Fixtures.Unqueue(colonist);
T.Check(CasteManager.Assign(colonist, miner, false, JoinReason.Manual), "setup: Assign the colonist failed");
// GravshipUtility.AbandonMap's body for these two pawns: despawned and passed to the world, with no status change.
AroundLeavingPatch(typeof(GravshipUtility), nameof(GravshipUtility.AbandonMap), "Patch_GravshipUtility_AbandonMap", () =>
{
foreach (Pawn pawn in new[] { prisoner, colonist })
{
pawn.DeSpawn();
pawn.DestroyOrPassToWorld();
}
});
T.Check(prisoner.IsWorldPawn() && colonist.IsWorldPawn(), "setup: the pawns are not world pawns");
T.Info("prisoner left behind still a prisoner of the colony: " + prisoner.IsPrisonerOfColony);
T.Check(Fixtures.Comp.MembershipOf(prisoner) == null, Who(prisoner) + " kept a membership: " + State(prisoner));
T.Check(!JoinDefaults.IsQueued(prisoner) && !JoinDefaults.IsQueued(colonist), "a pawn left behind was queued");
CheckIn(colonist, miner, JoinReason.Manual, "after being left behind");
if (!ModsConfig.OdysseyActive)
T.Info("Odyssey is off: AbandonMap returns at once in this game, so only the hook's body ran");
}
[BlaxTest("status: a No caste row reverts only the slots still on the caste's value for recruited prisoners; a hand-changed slot stays (no DLC needed)")]
public static void RevertKeepsHandChangesOnRecruit()
{
Caste prisoners = Make("Prisoners (revert test)", null, Paste());
NoCasteRow(JoinReason.NewColonist);
FoodPolicy defaultFood = Current.Game.foodRestrictionDatabase.DefaultFoodRestriction();
T.Check(defaultFood != Paste(), "setup: Paste is the default food");
Pawn follows = Fixtures.Prisoner();
Pawn changed = Fixtures.Prisoner();
foreach (Pawn p in new[] { follows, changed })
{
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
}
changed.foodRestriction.CurrentFoodPolicy = Lavish(); // by hand
foreach (Pawn p in new[] { follows, changed })
{
RecruitUtility.Recruit(p, Faction.OfPlayer, Warden());
T.Check(p.IsColonist, Who(p) + " is not a colonist after Recruit");
}
Fixtures.ApplyJoins(follows, changed);
T.Check(Fixtures.Comp.MembershipOf(follows) == null && Fixtures.Comp.MembershipOf(changed) == null,
"still in a caste after the No caste row: " + State(follows) + " / " + State(changed));
T.Check(follows.foodRestriction.CurrentFoodPolicy == defaultFood, Who(follows) + "'s food did not return to the default: " + follows.foodRestriction.CurrentFoodPolicy.label);
T.Check(changed.foodRestriction.CurrentFoodPolicy == Lavish(), Who(changed) + " lost its hand-set food: " + changed.foodRestriction.CurrentFoodPolicy.label);
}
// ---- save and reload ----------------------------------------------------------------- // ---- save and reload -----------------------------------------------------------------
// The successor policy takes the deleted one's id and label, so both have the same load ID: a // The successor policy takes the deleted one's id and label, so both have the same load ID: a

View File

@ -12,7 +12,7 @@ The headless suite covers the logic but draws nothing. These are the checks only
## Schedule and Work tabs ## Schedule and Work tabs
- [ ] Schedule tab: the Caste column sits right of the timetable. Its "Manage castes" and "Defaults" buttons work, and the Anything, Work, Recreation, Sleep and Meditate brushes at the top left are not covered and pick normally. - [ ] Schedule tab: the Caste column sits right of the timetable. Its "Manage castes" and "Defaults" buttons work, and the Anything, Work, Recreation, Sleep and (with Royalty) Meditate brushes at the top left are not covered and pick normally.
- [ ] Work tab: the header keeps the vanilla height, the work label guide lines reach the cells, and "Manage castes" sits above the "Caste" label without overlapping the sort area. - [ ] Work tab: the header keeps the vanilla height, the work label guide lines reach the cells, and "Manage castes" sits above the "Caste" label without overlapping the sort area.
## Caste manager ## Caste manager
@ -27,6 +27,7 @@ The headless suite covers the logic but draws nothing. These are the checks only
## Join defaults and settings ## Join defaults and settings
- [ ] Join defaults window: castes listed alphabetically; without Ideology the slave rows are hidden. - [ ] Join defaults window: castes listed alphabetically; without Ideology the slave rows are hidden.
- [ ] Without Ideology: the settings read "Starter castes: Colonist and Prisoner" with the grey "Slave caste: needs Ideology" note under it, and the tooltips of Defaults, Join defaults and Assign by status name no slave events.
- [ ] Mod settings: the checkboxes, the day slider (only while "A pawn that comes back gets its old caste" is on), the work manager note and the overlap text fit without covering the Reset button. - [ ] Mod settings: the checkboxes, the day slider (only while "A pawn that comes back gets its old caste" is on), the work manager note and the overlap text fit without covering the Reset button.
## Status changes ## Status changes
@ -41,3 +42,12 @@ The headless suite covers the logic but draws nothing. These are the checks only
- [ ] Load an existing save without castes: one message about the added castes (pointing to the mod settings if the column is off), no first-load message, and nobody's policies change until you click "Assign by status". - [ ] Load an existing save without castes: one message about the added castes (pointing to the mod settings if the column is off), no first-load message, and nobody's policies change until you click "Assign by status".
- [ ] With the column on at startup, untick it in the main menu without restarting, then start a new game: the first-load message still points to Assign > Manage castes. - [ ] With the column on at startup, untick it in the main menu without restarting, then start a new game: the first-load message still points to Assign > Manage castes.
- [ ] With Weapons Tab Reborn added to a save made without it: load paused, open Manage castes, tick the Weapon loadout row and open its dropdown. The row stays active, lists loadouts by name, and the log shows no warning. - [ ] With Weapons Tab Reborn added to a save made without it: load paused, open Manage castes, tick the Weapon loadout row and open its dropdown. The row stays active, lists loadouts by name, and the log shows no warning.
## DLCs added or removed
Use a throwaway save and restart the game between steps, since the DLC list needs one.
- [ ] Make a save with Royalty and Biotech: a caste with two Meditate hours and Childcare 1. Load it without Royalty and Biotech: no Blax Castes warning or red error in the log, the grid shows those hours as Anything with the "Kept for when its DLC is back" note, and the work priorities show the Childcare note. Load it with both again: Meditate and Childcare are back.
- [ ] Make a save with Ideology that has a slave in the Slave caste and a slave without a caste. Load it without Ideology: the join defaults show both slave rows with the "Needs Ideology" note, the slave keeps its caste, and the "Assign by status" tooltip names the new slave row.
- [ ] Start a game without Ideology, save, and load it with Ideology: one message says the Slave caste was set up, the slave rows pick it, and the Slave caste uses a new Slave outfit (Assign > Manage apparel policies lists it once).
- [ ] In the save loaded without Royalty and Biotech: paint the two Anything hours with the Anything brush, and the schedule note goes away. Click "Forget these" under the work note: the note goes away, and a caste whose only work was Childcare no longer shows "Apply to all members".