Blax Laws 1.0.0: lawbook, act catalogue, enforcement and jail

- Laws tab with the lawbook and the case log; the book starts empty and
  the mod watches nothing until a law exists.
- Act catalogue built from the game's defs (breaks, food, drugs, usables,
  interactions, recorded acts, records, bills) plus special acts, with
  groups, break links and a starter lawbook.
- Enforcement: warn, guilty, subdue, jail for N days and subdue then jail,
  one case per incident, danger waits, role holders and mechanitors held
  for Arrest now.
- Headless test suite green in every DLC combination, core only and with
  the compat mods.
This commit is contained in:
Fabian @ Blax Software 2026-12-02 21:07:17 +01:00
parent b673e44f76
commit 756af6c14e
115 changed files with 16820 additions and 66 deletions

BIN
1.7/Assemblies/BlaxLaws.dll Normal file

Binary file not shown.

BIN
1.7/Assemblies/BlaxLaws.pdb Normal file

Binary file not shown.

46
About/About.xml Normal file
View File

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Blax Laws</name>
<author>Blax Gaming</author>
<packageId>blax.laws</packageId>
<modVersion>1.0.0</modVersion>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
<modDependencies>
<li>
<packageId>brrainz.harmony</packageId>
<displayName>Harmony</displayName>
<steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl>
<downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl>
</li>
</modDependencies>
<loadAfter>
<li>brrainz.harmony</li>
<li>blax.castes</li>
<li>blax.zones</li>
<li>blax.slaves</li>
<li>blax.defaults</li>
</loadAfter>
<description>Write a lawbook and the colony enforces it. Add "Drug binge, planning: subdue" and a warden goes for a binging colonist at once and beats it down; if it reaches a drug first, that dose counts as "did it". Add "Drug binge, did it: jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Works with any DLC combination, core only included.
&lt;color=#19C63C&gt;Lawbook&lt;/color&gt;
- A Laws tab in the bottom bar. The book starts empty, and until you add a law Blax Laws does nothing.
- A law's action comes from a searchable list built from the game's own defs: every mental break, everything that can be eaten or used, every social interaction, every act the game records and every bill, plus setting a fire, displaying a corpse and starting a social fight. DLC and modded content show up with their mod's name.
- "Starter lawbook" adds seven suggested laws in one click.
- The Cases tab lists who did what and when, the punishment and its status.
&lt;color=#19C63C&gt;Punishments&lt;/color&gt;
- Warn, guilty for N days, subdue (a short fistfight that ends a break: bruises on torso and limbs, never the head), jail for N days, and subdue then jail.
- A warden goes at once, but nobody is pulled off a rescue, a tending, a fire or a surgery, and nobody is sent while hostiles threaten the map.
- Jailed colonists sit out their sentence on "Maintain only", so no prison mod recruits or enslaves them, and walk back to work when it is served. Role holders and mechanitors wait for your "Arrest now".
- Laws only watches what the game already does: no new crime events, no new mental breaks.
&lt;color=#19C63C&gt;Safe to add and remove&lt;/color&gt;
- Add it to a running save. The lawbook and the cases live in Blax Laws' own save data, so after you unsubscribe the save still loads: jailed colonists stay prisoners you can release by hand, and the log shows two errors.
Enforcement, the Laws tab, messages and letters can be switched off in the mod settings; with enforcement off, cases are still filed and listed. Multiplayer: not supported.
&lt;color=#19C63C&gt;Made by Blax&lt;/color&gt;
Blax Gaming is a project of Blax Software, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. www.blax.at</description>
</ModMetaData>

BIN
About/ModIcon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
About/Preview.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

21
CHANGELOG.md Normal file
View File

@ -0,0 +1,21 @@
# Changelog
## 1.0.0
- First release. "Laws" in the bottom bar opens the lawbook and the case log. The book starts empty, and until you add a law Blax Laws watches nothing.
- Laws: each row is Action, Stage, Severity, Punishment and Days, plus an On switch, and each dropdown offers only what fits the action and stage. A second row with the same action, drug and stage is refused, and the list jumps to the existing one. Severity sets the default days (1, 3, 5 or 10); days go from 1 to 50.
- Pick any act: "Add law" opens a searchable tree like a tailoring bill's filter, built from the game's own defs, so DLC and modded mental breaks, food, drugs, usables, social interactions, recorded acts, records and recipes show up with no patch, each labelled with its mod. Groups such as any drug binge, hard drugs, any meat, human meat, insult or slight and any surgery come first in each category. Special acts: set a fire, displayed a corpse ("on a table", "dug up from a grave") and started a social fight.
- Starter lawbook: one click adds seven laws. Drug binges, fire-starting sprees and corpse obsessions are subdued as they start, a binge whose drug was already taken is jailed for 5 days and a fire already set for 10, and starting a social fight or an insult gets a warning. Pressing it again adds only the missing ones.
- Planning and did it: planning is the moment a mental break starts; did it is the act the break is about, such as a dose during a binge, a fire, the displayed corpse or an insult. A break another pawn's psycast forces on a colonist is not the colonist's doing and opens no case, and a Berserk trance you order counts as a player order. A modded break built on one of these gets the same link. When two laws match, the most specific wins: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat".
- One case per incident: a binge is one case from start to end and counts the doses. Acts outside a break open at most one case per colonist and law a day (0 to 7 days in the settings), so a colony of meat eaters doesn't flood the log.
- Warn files the case with a message. Guilty for N days uses vanilla guilt: the arrest is always accepted, and executing or banishing the colonist costs the colony only the mildest thoughts.
- Subdue: a warden beats the offender down with fists to end its break. Bruises on torso and limbs only, never the head or a bionic part, no bleeding. Every part keeps at least half its health, and the bruises never add up to a deadly amount. The offender doesn't fight back and gets no catharsis from the break, and the warden isn't marked guilty. Children are never beaten.
- Jail for N days: the offender is arrested into a prisoner bed and set to "Maintain only", so no prison mod recruits or enslaves it. When the time is served a warden walks it out, and it goes back to work with its work priorities. "Subdue then jail" beats it down and carries it straight to the cell.
- If the binger reaches its drug before the warden reaches the binger, that dose counts as did it: the same warden arrests it instead of beating it.
- Enforcement: wardens first, then anyone able ("Wardens only" in the settings), nearest first. Nobody is pulled off a rescue, a patient, a fire or a surgery, and nobody is sent while hostiles threaten the map; a warden already on a case is called back when a raid arrives. A berserk colonist fights back, so its jail waits until the break ends or you down it.
- Role holders (Ideology) and mechanitors (Biotech) are never arrested on their own, since jail would take the role or shut the mechs down. Their case waits for "Arrest now" in the case log, and a letter says why. Once pressed, "Arrest now" stays in effect for that case, also after a save. Colony slaves are subdued during a break and warned otherwise.
- Cases: who, what, stage, when, punishment and status, newest first, with a jump to the pawn. Letters only when a colonist is jailed or you have to act: no prisoner bed, nobody to enforce, an arrest waiting for you.
- An arrest that fails gives the colonist its old bed back if it is still free. A jailed colonist that is recruited, released by you or another mod, escapes or dies closes its sentence; if no warden releases a colonist within a day of its release date, Laws releases it where it is.
- Settings: Enforce laws (off keeps the case log and carries out nothing), Show Laws tab, messages for cases, letters for jailings, wardens first or wardens only, subdued pawns lose their catharsis, player orders are exempt, days between cases and how long closed cases stay.
- Save-safe: the lawbook and the cases live in Blax Laws' own save data. Blax Laws can be added to a running save. After you remove it, a save loads with two errors in the log, and colonists it jailed stay prisoners you release by hand.
- Works with any DLC combination, core only included.

27
Defs/BlaxLaws_Acts.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Special acts: acts with their own hook (design: "Act catalogue and detection"). The defName is the second part
of the act key ("Special/SetFire"), so it never changes. Another mod adds a special act with an ActDef and
its own hook that files it through CaseFiler.Report.
-->
<Defs>
<BlaxLaws.ActDef>
<defName>SetFire</defName>
<label>set a fire</label>
<description>The pawn set something on fire.</description>
</BlaxLaws.ActDef>
<BlaxLaws.ActDef>
<defName>DisplayedCorpse</defName>
<label>displayed a corpse</label>
<description>The pawn hauled a corpse to a public place during a corpse obsession.</description>
</BlaxLaws.ActDef>
<BlaxLaws.ActDef>
<defName>StartedSocialFight</defName>
<label>started a social fight</label>
<description>The pawn answered an interaction with a social fight. The offender is the pawn who swings first.</description>
</BlaxLaws.ActDef>
</Defs>

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Break links (design: "Link table"): the act that counts as a break's "Did it". Links go by mental state class,
subclasses included; the most derived class wins, so the drug binge link beats the food binge link.
act is an act key in another category, a single def or a group. usesDrugOption: the row's drug option
filters the act. Another mod links its own break class with a BreakLinkDef and no code.
-->
<Defs>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_BingingDrug</defName>
<label>took the drug</label>
<stateClass>MentalState_BingingDrug</stateClass>
<act>Ate/@anyDrug</act>
<usesDrugOption>true</usesDrugOption>
</BlaxLaws.BreakLinkDef>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_BingingFood</defName>
<label>ate</label>
<stateClass>MentalState_Binging</stateClass>
<act>Ate/@any</act>
</BlaxLaws.BreakLinkDef>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_FireStartingSpree</defName>
<label>set a fire</label>
<stateClass>MentalState_FireStartingSpree</stateClass>
<act>Special/SetFire</act>
</BlaxLaws.BreakLinkDef>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_CorpseObsession</defName>
<label>displayed a corpse</label>
<stateClass>MentalState_CorpseObsession</stateClass>
<act>Special/DisplayedCorpse</act>
</BlaxLaws.BreakLinkDef>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_InsultingSpree</defName>
<label>insulted someone</label>
<stateClass>MentalState_InsultingSpree</stateClass>
<act>Interaction/@insultOrSlight</act>
</BlaxLaws.BreakLinkDef>
<BlaxLaws.BreakLinkDef>
<defName>BlaxLaws_Link_Jailbreaker</defName>
<label>sparked a jailbreak</label>
<stateClass>MentalState_Jailbreaker</stateClass>
<act>Interaction/SparkJailbreak</act>
</BlaxLaws.BreakLinkDef>
</Defs>

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The act catalogue's categories (design: "The act catalogue is built from the game's defs, saved as names").
A category's defName is the first part of every act key ("Ate/WakeUp"), so it never changes.
Each worker reads the loaded defs once and returns the category's entries; the include and exclude lists
are def names the worker adds beyond its rule or leaves out. The vanilla lists (animal, baby and mechanoid
states, the berserk states no mental break names, faction-level history events) are built into
CatalogueRules; the lists here add to them, so another mod can patch in its own states or events.
-->
<Defs>
<BlaxLaws.ActCategoryDef>
<defName>Break</defName>
<label>mental breaks</label>
<description>Every mental break a colonist can have. Planning: the break has started. Did it: the act linked to the break happened during it.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Break</workerClass>
<order>10</order>
<hostileStateClasses>
<li>MentalState_Berserk</li>
<li>MentalState_BerserkWarcall</li>
</hostileStateClasses>
<include>
<li>Berserk</li>
</include>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Ate</defName>
<label>ate</label>
<description>Everything that can be eaten or drunk: food, meals, raw food, corpses and drugs. Counts only when the pawn eats on its own.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Ate</workerClass>
<order>20</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Used</defName>
<label>used</label>
<description>Everything that can be used: psytrainers, neurotrainers, mech serums and modded usables.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Used</workerClass>
<order>30</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Interaction</defName>
<label>social interactions</label>
<description>Every social interaction. The offender is the pawn who starts it.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Interaction</workerClass>
<order>40</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>RecordedAct</defName>
<label>recorded acts</label>
<description>Every act the game records with the pawn as the doer. Most recorded acts need Ideology.</description>
<workerClass>BlaxLaws.ActCategoryWorker_RecordedAct</workerClass>
<order>50</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Record</defName>
<label>records</label>
<description>Every record the game counts for a pawn, such as kills, bodies stripped or things hauled. A case opens when the record goes up.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Record</workerClass>
<order>60</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Bill</defName>
<label>bills</label>
<description>Every bill. A case opens when the pawn finishes one iteration.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Bill</workerClass>
<order>70</order>
</BlaxLaws.ActCategoryDef>
<BlaxLaws.ActCategoryDef>
<defName>Special</defName>
<label>special acts</label>
<description>Acts the game records nowhere else: setting a fire, displaying a corpse and starting a social fight.</description>
<workerClass>BlaxLaws.ActCategoryWorker_Special</workerClass>
<order>80</order>
</BlaxLaws.ActCategoryDef>
</Defs>

18
Defs/BlaxLaws_Jobs.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The subdue job (design: "The subdue job never enters a save"). Not suspendable and never opportunistic, so a
vanilla interrupt ends it instead of putting it into the saved job queue; the save prefix on
Pawn_JobTracker.ExposeData hides it from the file.
-->
<Defs>
<JobDef>
<defName>BlaxLaws_Subdue</defName>
<driverClass>BlaxLaws.JobDriver_Subdue</driverClass>
<reportString>subduing TargetA.</reportString>
<suspendable>false</suspendable>
<allowOpportunisticPrefix>false</allowOpportunisticPrefix>
<casualInterruptible>false</casualInterruptible>
</JobDef>
</Defs>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The Laws tab, after Ideoligions (order 100, Ideology/Defs/MainButtonDefs/MainButtons.xml:9) and before Menu
(500, Core/Defs/Misc/MainButtonDefs/MainButtons.xml:131). Never saved. Laws are colony policy across every map
and caravan, so the tab also opens without a map. "Show Laws tab" writes buttonVisible live.
-->
<Defs>
<MainButtonDef>
<defName>BlaxLaws_Laws</defName>
<label>laws</label>
<description>Your colony's lawbook and its cases.</description>
<tabWindowClass>BlaxLaws.MainTabWindow_Laws</tabWindowClass>
<order>105</order>
<validWithoutMap>true</validWithoutMap>
</MainButtonDef>
</Defs>

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Punishments of the first release (design: "Lawbook tab", punishments per entry and stage). The defName is what
a law row saves, so it never changes. fits names the entry kinds and stages that offer the punishment:
BreakPlanning, BreakDidIt (a break that isn't hostile to the colony), HostileBreakPlanning, HostileBreakDidIt
(berserk) and Act (every entry outside the breaks). runsAlongside: the punishment never replaces or stops the
one a case already runs.
-->
<Defs>
<BlaxLaws.PunishmentDef>
<defName>Warn</defName>
<label>warn</label>
<description>Files the case and posts a message, nothing more.</description>
<workerClass>BlaxLaws.PunishmentWorker_Warn</workerClass>
<order>10</order>
<runsAlongside>true</runsAlongside>
<fits>
<li>BreakPlanning</li>
<li>BreakDidIt</li>
<li>HostileBreakPlanning</li>
<li>HostileBreakDidIt</li>
<li>Act</li>
</fits>
</BlaxLaws.PunishmentDef>
<BlaxLaws.PunishmentDef>
<defName>Guilty</defName>
<label>guilty</label>
<description>Marks the pawn guilty the vanilla way for the days: its arrest is always accepted, and executing or banishing it costs the colony the mildest thoughts.</description>
<workerClass>BlaxLaws.PunishmentWorker_Guilty</workerClass>
<order>20</order>
<usesDays>true</usesDays>
<runsAlongside>true</runsAlongside>
<fits>
<li>BreakDidIt</li>
<li>HostileBreakPlanning</li>
<li>HostileBreakDidIt</li>
<li>Act</li>
</fits>
</BlaxLaws.PunishmentDef>
<BlaxLaws.PunishmentDef>
<defName>Subdue</defName>
<label>subdue</label>
<description>A warden beats the pawn down with fists to end its break: bruises on torso and limbs, never the head or a bionic part. After the break it warns instead.</description>
<workerClass>BlaxLaws.PunishmentWorker_Subdue</workerClass>
<order>30</order>
<fits>
<li>BreakPlanning</li>
<li>BreakDidIt</li>
</fits>
</BlaxLaws.PunishmentDef>
<BlaxLaws.PunishmentDef>
<defName>Jail</defName>
<label>jail</label>
<description>A warden arrests the pawn. It sits out the days in a prisoner bed on "Maintain only" and walks back to work.</description>
<workerClass>BlaxLaws.PunishmentWorker_Jail</workerClass>
<order>40</order>
<usesDays>true</usesDays>
<fits>
<li>BreakPlanning</li>
<li>BreakDidIt</li>
<li>HostileBreakPlanning</li>
<li>HostileBreakDidIt</li>
<li>Act</li>
</fits>
</BlaxLaws.PunishmentDef>
<BlaxLaws.PunishmentDef>
<defName>SubdueThenJail</defName>
<label>subdue then jail</label>
<description>A warden beats the pawn down and carries it to a prisoner bed. After the break it jails without the beating.</description>
<workerClass>BlaxLaws.PunishmentWorker_SubdueThenJail</workerClass>
<order>50</order>
<usesDays>true</usesDays>
<fits>
<li>BreakDidIt</li>
</fits>
</BlaxLaws.PunishmentDef>
</Defs>

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Shared keys (integrator). Each work package keeps its own keys in BlaxLaws_<package>.xml. -->
<!-- Missing entries -->
<BlaxLaws_NeedsDlc>Needs {0}</BlaxLaws_NeedsDlc>
<BlaxLaws_MissingMod>Missing: {0}</BlaxLaws_MissingMod>
<!-- Stages, severities, case status and outcomes -->
<BlaxLaws_Stage_Planning>Planning</BlaxLaws_Stage_Planning>
<BlaxLaws_Stage_DidIt>Did it</BlaxLaws_Stage_DidIt>
<BlaxLaws_Severity_Minor>Minor</BlaxLaws_Severity_Minor>
<BlaxLaws_Severity_Moderate>Moderate</BlaxLaws_Severity_Moderate>
<BlaxLaws_Severity_Serious>Serious</BlaxLaws_Severity_Serious>
<BlaxLaws_Severity_Grave>Grave</BlaxLaws_Severity_Grave>
<BlaxLaws_Status_Open>Open</BlaxLaws_Status_Open>
<BlaxLaws_Status_Enforcing>Enforcing</BlaxLaws_Status_Enforcing>
<BlaxLaws_Status_Jailed>Jailed</BlaxLaws_Status_Jailed>
<BlaxLaws_Status_Closed>Closed</BlaxLaws_Status_Closed>
<BlaxLaws_Outcome_Repealed>Law repealed</BlaxLaws_Outcome_Repealed>
<BlaxLaws_Outcome_BreakEnded>Break ended</BlaxLaws_Outcome_BreakEnded>
<BlaxLaws_Outcome_NotEnforced>Not enforced</BlaxLaws_Outcome_NotEnforced>
<BlaxLaws_Outcome_OffenderGone>Offender gone</BlaxLaws_Outcome_OffenderGone>
<BlaxLaws_Outcome_Warned>Warned</BlaxLaws_Outcome_Warned>
<BlaxLaws_Outcome_Guilty>Guilty</BlaxLaws_Outcome_Guilty>
<BlaxLaws_Outcome_Subdued>Subdued</BlaxLaws_Outcome_Subdued>
<BlaxLaws_Outcome_Served>Sentence served</BlaxLaws_Outcome_Served>
<BlaxLaws_Outcome_ReleasedEarly>Released early</BlaxLaws_Outcome_ReleasedEarly>
<!-- Drug options of binge rows -->
<BlaxLaws_DrugOption_Any>Any drug</BlaxLaws_DrugOption_Any>
<BlaxLaws_DrugOption_Hard>Hard drugs</BlaxLaws_DrugOption_Hard>
<BlaxLaws_DrugOption_Social>Social drugs</BlaxLaws_DrugOption_Social>
<!-- Lawbook and cases -->
<BlaxLaws_EmptyBook>No laws yet. Add one or press Starter lawbook.</BlaxLaws_EmptyBook>
<BlaxLaws_CaseFiled>{0} broke a law: {1} ({2}). Punishment: {3}.</BlaxLaws_CaseFiled>
<!-- Settings -->
<BlaxLaws_SettingEnforceLaws>Enforce laws</BlaxLaws_SettingEnforceLaws>
<BlaxLaws_SettingEnforceLawsTip>Wardens carry out the punishments of your lawbook. Off: cases are still filed and listed, and nothing is carried out.</BlaxLaws_SettingEnforceLawsTip>
<BlaxLaws_SettingShowTab>Show Laws tab</BlaxLaws_SettingShowTab>
<BlaxLaws_SettingShowTabTip>Shows the Laws button in the bottom bar. Off hides it; your laws stay and are still enforced.</BlaxLaws_SettingShowTabTip>
<BlaxLaws_SettingCaseMessages>Messages for cases</BlaxLaws_SettingCaseMessages>
<BlaxLaws_SettingCaseMessagesTip>Posts a message whenever a case is filed or moves on.</BlaxLaws_SettingCaseMessagesTip>
<BlaxLaws_SettingJailLetters>Letters for jailings</BlaxLaws_SettingJailLetters>
<BlaxLaws_SettingJailLettersTip>Sends a letter when a colonist is jailed, and when you have to act: no prisoner bed, no enforcer, or a role holder waiting for "Arrest now".</BlaxLaws_SettingJailLettersTip>
<BlaxLaws_SettingEnforcers>Enforcers</BlaxLaws_SettingEnforcers>
<BlaxLaws_EnforcersWardensFirst>Wardens first, then anyone able</BlaxLaws_EnforcersWardensFirst>
<BlaxLaws_EnforcersWardensFirstTip>The nearest colonist with Warden work goes first; when none can, the nearest colonist able to do the job.</BlaxLaws_EnforcersWardensFirstTip>
<BlaxLaws_EnforcersWardensOnly>Wardens only</BlaxLaws_EnforcersWardensOnly>
<BlaxLaws_EnforcersWardensOnlyTip>Only colonists with Warden work enforce laws. When none can, the case waits.</BlaxLaws_EnforcersWardensOnlyTip>
<BlaxLaws_SettingSubdueCatharsis>Subdued pawns lose their catharsis</BlaxLaws_SettingSubdueCatharsis>
<BlaxLaws_SettingSubdueCatharsisTip>A colonist whose break ends because it was subdued doesn't get the catharsis that ending a break gives, so the beating doesn't reward the crime.</BlaxLaws_SettingSubdueCatharsisTip>
<BlaxLaws_SettingPlayerOrdersExempt>Player orders are exempt</BlaxLaws_SettingPlayerOrdersExempt>
<BlaxLaws_SettingPlayerOrdersExemptTip>An act done while drafted or on a job you ordered opens no case.</BlaxLaws_SettingPlayerOrdersExemptTip>
<BlaxLaws_SettingCooldownDays>Days between cases for acts outside a break: {0}</BlaxLaws_SettingCooldownDays>
<BlaxLaws_SettingCooldownDaysTip>A pawn who does the same act again while its last case under the same law is open, or within these days of that case, gets no new case; the count on that case goes up. 0 files every act.</BlaxLaws_SettingCooldownDaysTip>
<BlaxLaws_SettingKeepClosedDays>Keep closed cases: {0} days</BlaxLaws_SettingKeepClosedDays>
<BlaxLaws_SettingKeepClosedDaysTip>Closed cases older than this are removed from the case list when the game is saved.</BlaxLaws_SettingKeepClosedDaysTip>
<BlaxLaws_SettingsReset>Reset to defaults</BlaxLaws_SettingsReset>
</LanguageData>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Act catalogue: group entries. The "any" group of a category is BlaxLaws_Group_any<Category>. -->
<BlaxLaws_Group_anyBreak>Any mental break</BlaxLaws_Group_anyBreak>
<BlaxLaws_Group_anyDrugBinge>Any drug binge</BlaxLaws_Group_anyDrugBinge>
<BlaxLaws_Group_anyTantrum>Any tantrum</BlaxLaws_Group_anyTantrum>
<BlaxLaws_Group_anyInsultingSpree>Any insulting spree</BlaxLaws_Group_anyInsultingSpree>
<BlaxLaws_Group_anyAggressive>Any aggressive break</BlaxLaws_Group_anyAggressive>
<BlaxLaws_Group_anyAte>Anything eaten</BlaxLaws_Group_anyAte>
<BlaxLaws_Group_anyDrug>Any drug</BlaxLaws_Group_anyDrug>
<BlaxLaws_Group_hardDrugs>Hard drugs</BlaxLaws_Group_hardDrugs>
<BlaxLaws_Group_socialDrugs>Social drugs</BlaxLaws_Group_socialDrugs>
<BlaxLaws_Group_medicalDrugs>Medical drugs</BlaxLaws_Group_medicalDrugs>
<BlaxLaws_Group_anyMeat>Any meat, meals with meat included</BlaxLaws_Group_anyMeat>
<BlaxLaws_Group_rawMeatOrCorpse>Raw meat or corpses</BlaxLaws_Group_rawMeatOrCorpse>
<BlaxLaws_Group_humanMeat>Human meat, as an ingredient too</BlaxLaws_Group_humanMeat>
<BlaxLaws_Group_insectMeat>Insect meat, as an ingredient too</BlaxLaws_Group_insectMeat>
<BlaxLaws_Group_rawFood>Raw food</BlaxLaws_Group_rawFood>
<BlaxLaws_Group_anyMeal>Any meal</BlaxLaws_Group_anyMeal>
<BlaxLaws_Group_insultOrSlight>Insult or slight</BlaxLaws_Group_insultOrSlight>
<BlaxLaws_Group_anySurgery>Any surgery</BlaxLaws_Group_anySurgery>
<!-- Two entries of one category with the same label: the label and the def's name. -->
<BlaxLaws_CatalogueLabelWithName>{0} ({1})</BlaxLaws_CatalogueLabelWithName>
</LanguageData>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Enforcement, subdue and jail. -->
<!-- Why a case waits (LawCase.waitReason, shown in the Cases tab) -->
<BlaxLaws_Wait_Danger>waiting until the danger is over</BlaxLaws_Wait_Danger>
<BlaxLaws_Wait_NoEnforcer>nobody can enforce it</BlaxLaws_Wait_NoEnforcer>
<BlaxLaws_Wait_Busy>waiting for a free enforcer</BlaxLaws_Wait_Busy>
<BlaxLaws_Wait_NoBed>waiting for a free prisoner bed</BlaxLaws_Wait_NoBed>
<BlaxLaws_Wait_Reserved>waiting while someone else handles the pawn</BlaxLaws_Wait_Reserved>
<BlaxLaws_Wait_HostileBreak>waiting until the break ends or the pawn is down</BlaxLaws_Wait_HostileBreak>
<BlaxLaws_Wait_Hold>waiting for Arrest now</BlaxLaws_Wait_Hold>
<BlaxLaws_Wait_Away>waiting until the pawn is back on a map</BlaxLaws_Wait_Away>
<!-- Outcomes of closed cases, beside the shared ones -->
<BlaxLaws_Outcome_NotSubdued>Not subdued</BlaxLaws_Outcome_NotSubdued>
<BlaxLaws_Outcome_Escaped>Escaped</BlaxLaws_Outcome_Escaped>
<BlaxLaws_Outcome_Died>Died in jail</BlaxLaws_Outcome_Died>
<BlaxLaws_Outcome_AlreadyPrisoner>Already a prisoner</BlaxLaws_Outcome_AlreadyPrisoner>
<!-- Messages ({0} is the offender, {1} the enforcer) -->
<BlaxLaws_MsgSubdued>{1} subdued {0}.</BlaxLaws_MsgSubdued>
<BlaxLaws_MsgSubdueGaveUp>{1} stopped subduing {0}: the hits cause no pain.</BlaxLaws_MsgSubdueGaveUp>
<BlaxLaws_MsgWarnedChild>{0} is a child and is warned instead of subdued.</BlaxLaws_MsgWarnedChild>
<BlaxLaws_MsgWarnedAfterBreak>{0}'s break is over, so {0} is warned instead of subdued.</BlaxLaws_MsgWarnedAfterBreak>
<BlaxLaws_MsgWarnedFightsBack>{0} fights back in this break, so {0} is warned instead of subdued.</BlaxLaws_MsgWarnedFightsBack>
<BlaxLaws_MsgWarnedSlave>Slaves aren't jailed yet, so {0} is warned.</BlaxLaws_MsgWarnedSlave>
<BlaxLaws_MsgAlreadyPrisoner>{0} is already a prisoner. Laws leaves {0} to you and closes the case.</BlaxLaws_MsgAlreadyPrisoner>
<BlaxLaws_MsgDiedInJail>{0} died while serving a sentence.</BlaxLaws_MsgDiedInJail>
<BlaxLaws_MsgEscaped>{0} escaped from jail.</BlaxLaws_MsgEscaped>
<BlaxLaws_MsgBackAtWork>{0} has served the sentence and is free again.</BlaxLaws_MsgBackAtWork>
<BlaxLaws_MsgReleasedEarly>{0} is out of jail before the sentence ended. The case is closed.</BlaxLaws_MsgReleasedEarly>
<BlaxLaws_MsgSentenceServed>{0} has served the sentence. A warden will release {0}.</BlaxLaws_MsgSentenceServed>
<BlaxLaws_MsgReleasedInPlace>No warden released {0} within a day of the sentence's end, so {0} is released where {0} is.</BlaxLaws_MsgReleasedInPlace>
<BlaxLaws_MsgRepealedRelease>The law {0} was jailed under was repealed. A warden will release {0}.</BlaxLaws_MsgRepealedRelease>
<!-- Letters ({0} is the offender, {1} the law) -->
<BlaxLaws_LetterJailedLabel>Jailed: {0}</BlaxLaws_LetterJailedLabel>
<BlaxLaws_LetterJailedText>{0} was arrested for {2} and serves a sentence of {1} in a prisoner bed, on "Maintain only".\n\nThe sentence ends on {3}. Then a warden releases {0}, and {0} goes back to work with the same work priorities.</BlaxLaws_LetterJailedText>
<BlaxLaws_LetterNoBedLabel>No prisoner bed: {0}</BlaxLaws_LetterNoBedLabel>
<BlaxLaws_LetterNoBedText>{0} is to be jailed for {1}, but there is no prisoner bed a warden can take {0} to.\n\nBuild a bed and set it for prisoners. The arrest follows within a few hours.</BlaxLaws_LetterNoBedText>
<BlaxLaws_LetterNoEnforcerLabel>Nobody to enforce: {0}</BlaxLaws_LetterNoEnforcerLabel>
<BlaxLaws_LetterNoEnforcerText>Nobody can carry out the punishment of {0} for {1}.\n\nAn enforcer is an adult free colonist who can walk, and who can do violence for a subdue or carry people for an arrest. With "Wardens only" it also needs Warden work. The case waits until someone can.</BlaxLaws_LetterNoEnforcerText>
<BlaxLaws_LetterHoldLabel>Arrest waits: {0}</BlaxLaws_LetterHoldLabel>
<BlaxLaws_LetterHoldText>{0} is to be jailed for {1}. Laws doesn't arrest {0} on its own: {2}.\n\nPress "Arrest now" on the case in the Laws tab to jail {0} anyway.</BlaxLaws_LetterHoldText>
<BlaxLaws_HoldRole>an arrest takes away {0}'s ideoligion role</BlaxLaws_HoldRole>
<BlaxLaws_HoldMechs>an arrest shuts down the mechs {0} controls</BlaxLaws_HoldMechs>
</LanguageData>

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Laws tab -->
<BlaxLaws_TabLawbook>Lawbook</BlaxLaws_TabLawbook>
<BlaxLaws_TabCases>Cases</BlaxLaws_TabCases>
<BlaxLaws_AddLaw>Add law</BlaxLaws_AddLaw>
<BlaxLaws_AddLawTip>Pick an act from the catalogue of everything the game records and add a law for it. Then set its stage, severity and punishment.</BlaxLaws_AddLawTip>
<BlaxLaws_StarterLawbook>Starter lawbook</BlaxLaws_StarterLawbook>
<BlaxLaws_StarterLawbookTip>Adds seven suggested laws: drug binges, fire-starting sprees, corpse obsession, starting a social fight and insults. Laws already in the book are skipped.</BlaxLaws_StarterLawbookTip>
<BlaxLaws_StarterAdded>Laws added: {0}.</BlaxLaws_StarterAdded>
<BlaxLaws_StarterNone>Every starter law is already in the book.</BlaxLaws_StarterNone>
<BlaxLaws_EnforceOff>"Enforce laws" is off in the mod settings: cases are listed, nothing is carried out.</BlaxLaws_EnforceOff>
<!-- Lawbook columns -->
<BlaxLaws_ColAction>Action</BlaxLaws_ColAction>
<BlaxLaws_ColOption>Drug</BlaxLaws_ColOption>
<BlaxLaws_ColOptionTip>Drug binges only: which drug counts as "did it".</BlaxLaws_ColOptionTip>
<BlaxLaws_ColStage>Stage</BlaxLaws_ColStage>
<BlaxLaws_ColStageTip>Planning: a mental break has started and nothing is done yet. Did it: the act happened. Only mental breaks have Planning.</BlaxLaws_ColStageTip>
<BlaxLaws_ColSeverity>Severity</BlaxLaws_ColSeverity>
<BlaxLaws_ColSeverityTip>Sets the default days (Minor 1, Moderate 3, Serious 5, Grave 10) and orders the case log.</BlaxLaws_ColSeverityTip>
<BlaxLaws_ColPunishment>Punishment</BlaxLaws_ColPunishment>
<BlaxLaws_ColDays>Days</BlaxLaws_ColDays>
<BlaxLaws_ColDaysTip>Days of guilt or of jail, 1 to 50.</BlaxLaws_ColDaysTip>
<BlaxLaws_ColOn>On</BlaxLaws_ColOn>
<BlaxLaws_ColOnTip>Off: the law stays in the book and catches nothing.</BlaxLaws_ColOnTip>
<BlaxLaws_NoDays>-</BlaxLaws_NoDays>
<!-- Lawbook rows -->
<BlaxLaws_ActionLabel>{0}: {1}</BlaxLaws_ActionLabel>
<BlaxLaws_ActionTip>Click to pick another act.</BlaxLaws_ActionTip>
<BlaxLaws_SourceMod>From: {0}</BlaxLaws_SourceMod>
<BlaxLaws_RowExists>The book already has a law for {0} at stage {1}.</BlaxLaws_RowExists>
<BlaxLaws_DeleteLaw>Delete this law</BlaxLaws_DeleteLaw>
<BlaxLaws_DeleteConfirm>Delete the law "{0}"? Its open cases ({1}) close as "law repealed".</BlaxLaws_DeleteConfirm>
<BlaxLaws_DeleteConfirmJailed>{0} of them sit in jail. They are set to "Release", and a warden lets them go.</BlaxLaws_DeleteConfirmJailed>
<BlaxLaws_OverlapTip>This law can catch the same act as a law of another category, so one act may open a case under each:\n{0}</BlaxLaws_OverlapTip>
<!-- Act picker -->
<BlaxLaws_PickerTitle>Pick an act</BlaxLaws_PickerTitle>
<BlaxLaws_PickerCategory>{0} ({1})</BlaxLaws_PickerCategory>
<BlaxLaws_PickerStages>Stages: {0}</BlaxLaws_PickerStages>
<BlaxLaws_PickerHostile>A break hostile to the colony: the pawn fights back, so it can't be subdued.</BlaxLaws_PickerHostile>
<BlaxLaws_PickerInBook>Already in the lawbook. Adding it again adds a law for a stage that has none, or shows the existing law.</BlaxLaws_PickerInBook>
<BlaxLaws_PickerNoMatch>No act matches the search.</BlaxLaws_PickerNoMatch>
<BlaxLaws_PickerEmpty>The act catalogue is empty.</BlaxLaws_PickerEmpty>
<!-- Cases -->
<BlaxLaws_ShowClosed>Show closed cases</BlaxLaws_ShowClosed>
<BlaxLaws_NoCases>No cases yet.</BlaxLaws_NoCases>
<BlaxLaws_ColWho>Who</BlaxLaws_ColWho>
<BlaxLaws_ColWhat>What</BlaxLaws_ColWhat>
<BlaxLaws_ColWhen>When</BlaxLaws_ColWhen>
<BlaxLaws_ColStatus>Status</BlaxLaws_ColStatus>
<BlaxLaws_CaseWhoVictim>{0} against {1}</BlaxLaws_CaseWhoVictim>
<BlaxLaws_CaseCount>{0} times</BlaxLaws_CaseCount>
<BlaxLaws_Note_OnTable>on a table</BlaxLaws_Note_OnTable>
<BlaxLaws_Note_DugUp>dug up from a grave</BlaxLaws_Note_DugUp>
<BlaxLaws_JustNow>just now</BlaxLaws_JustNow>
<BlaxLaws_Ago>{0} ago</BlaxLaws_Ago>
<BlaxLaws_DaysCount>{0} days</BlaxLaws_DaysCount>
<BlaxLaws_ReleaseIn>Jailed, release in {0}</BlaxLaws_ReleaseIn>
<BlaxLaws_ReleaseDue>Jailed, release due</BlaxLaws_ReleaseDue>
<BlaxLaws_JumpTo>Show</BlaxLaws_JumpTo>
<BlaxLaws_JumpToTip>Select {0} and move the view there.</BlaxLaws_JumpToTip>
<BlaxLaws_ArrestNow>Arrest now</BlaxLaws_ArrestNow>
<BlaxLaws_ArrestNowTip>Laws doesn't make this arrest on its own: {0}. Press to arrest now.</BlaxLaws_ArrestNowTip>
</LanguageData>

162
README.md
View File

@ -1,93 +1,157 @@
![Blax Laws](About/Preview.png)
# Blax Laws # Blax Laws
[![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)
[![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support) [![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support)
[![Status: design](https://img.shields.io/badge/status-design-CDCDCD)](docs/design.md) [![Status: 1.0](https://img.shields.io/badge/status-1.0-CDCDCD)](CHANGELOG.md)
RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your colony's laws, and colonists who break them get stopped, jailed and, later, tried in court. Add "Drug binge, wake-up, planning, subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it" and the did-it law applies. Add "Drug binge, did it, jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Needs Harmony. Works with any DLC combination, core only included. RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your colony's laws from every act the game knows, picked the way you pick what to tailor, and your wardens enforce them. Add "Drug binge, planning: subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it". Add "Drug binge, did it: jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Needs Harmony. Works with any DLC combination, core only included.
Status: design. Nothing is built yet; below is what the first release, the quick first version, will do. What the whole mod covers and in which order: `docs/features.md`. The specs: `docs/design.md`.
## Features ## Features
### The lawbook ### The lawbook
- 📖 **An empty lawbook.** A "Laws" tab in the bottom bar. Add a law as Action, Stage, Severity, Punishment and Days, each a dropdown that only offers what fits. Nothing is watched or punished until the first row exists. `Source/BlaxLaws/MainTabWindow_Laws.cs` - 📖 **An empty lawbook.** A "Laws" button in the bottom bar with two tabs, Lawbook and Cases. A law is a row of Action, Stage, Severity, Punishment and Days, plus an On switch; each dropdown offers only what fits the action and stage. Nothing is watched or punished until the first row exists. `Source/BlaxLaws/UI/MainTabWindow_Laws.cs`
- 🔎 **Pick any act.** The Action comes from a searchable list, like choosing what to tailor: every mental break, everything that can be eaten or used, every social interaction, every act the game records, every record and every bill. It's built from the game's own data when the game starts, so DLC and modded breaks, drugs and recipes show up with no patch, each labelled with its mod. `Source/BlaxLaws/Dialog_PickAct.cs` - 🔎 **Pick any act.** "Add law" opens a searchable tree like a tailoring bill's filter: every mental break, everything that can be eaten or used, every social interaction, every act the game records, every record and every bill, plus the special acts. It's built from the loaded defs when the game starts, so DLC and modded breaks, drugs and recipes show up with no patch, each labelled with its mod. Typing filters every category at once; an entry already in the book shows a tick and jumps to its row. `Source/BlaxLaws/UI/Dialog_PickAct.cs`, `Source/BlaxLaws/Catalogue/ActCatalogue.cs`
- 📝 **Starter lawbook.** One click adds seven suggested laws: subdue drug binges, fire-starting sprees and corpse obsession before they start, jail for binges and fires already done, a warning for fights and insults. `Source/BlaxLaws/Lawbook.cs` - 📝 **Starter lawbook.** One click adds seven laws: any drug binge, planning: subdue (Moderate); any drug binge, did it: jail 5 days (Serious); fire-starting spree, planning: subdue (Serious); fire-starting spree, did it: jail 10 days (Grave); corpse obsession, planning: subdue (Moderate); started a social fight: warn (Minor); insult: warn (Minor). Pressing it again adds only the missing ones. Every starter law uses core content. `Source/BlaxLaws/Lawbook.cs`
- 🎯 **One law per act.** Each action, option and stage appears once in the book, and when two laws fit an act the more specific one wins: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat". - 🎯 **One law per act, the most specific wins.** Action, Option and Stage are a row's key; a second row with the same three is refused and the list jumps to the existing one. A drug binge row names which drug counts: any drug, hard drugs, social drugs or one drug. When two rows of a category match an act, a single def beats a group, a smaller group beats a larger one, and one drug beats hard or social drugs beats any drug: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat".
- 🎚️ **Stages that mean something.** "Planning" is the moment a mental break starts and nothing is done yet; "Did it" is the act the break is about, such as the first dose of a binge. An entry only offers the stages the game can really tell apart. - 🎚️ **Stages that mean something.** "Planning" is the moment a mental break starts and nothing is done yet; the game picks the break type only then, so only breaks have it. "Did it" is the act the break is about, such as the first dose of a binge. An entry offers only the stages the game can tell apart.
- 📋 **Case log.** Who, what, when, which punishment and how it ended, newest first, with a jump to the pawn and "Arrest now" for cases that wait. - ⚖️ **Severity and days.** Minor, Moderate, Serious or Grave set the default days (1, 3, 5, 10) and order the case log. Days go from 1 to 50. Changing the severity moves the days along only while you haven't typed your own.
- 📋 **Case log.** Who, what, stage, when, punishment and status, newest first, with a jump to the pawn and "Arrest now" for cases that wait. Deleting a law with open cases asks first, names the count and closes them as "law repealed".
- 🧩 **Missing entries wait.** A row whose DLC or mod is gone stays in the book with its saved name, shows "Needs <DLC>" or "Missing: <mod>", isn't enforced and works again when the content comes back.
### Crimes ### Crimes
The catalogue holds hundreds of acts; these are the ones the starter lawbook and the examples use. Laws adds no crime events and no mental breaks. It only watches what the game does anyway. `Source/BlaxLaws/Detection/`, `Source/BlaxLaws/CaseFiler.cs`
- 💊 **Drug binge.** Any drug, hard or social drugs, or one chemical such as wake-up. Planning when the binge starts, did it with every dose. `Source/BlaxLaws/Detection/BreakHooks.cs` - 🧠 **Mental breaks.** Every break a colonist can have, berserk included; animal and baby states are left out. Groups: any drug binge, any tantrum, any insulting spree, any aggressive break, any break.
- 🔥 **Fire-starting spree.** Planning when a pyromaniac's spree starts, did it with every fire set. - 🍖 **Ate.** Every food, meal, raw food, corpse and drug, modded and DLC ones included. Groups: any drug, hard, social or medical drugs, any meat (meals with meat included), raw meat or corpses, human meat, insect meat, raw food, any meal. It counts only when the pawn eats on its own: a doctor's dose, a warden feeding a patient or a baby being fed doesn't. A drink at a gathering spot counts.
- ⚰️ **Corpse obsession.** Planning when the obsession starts, did it when the corpse is on display; the case notes "on a table" and whether the corpse was dug up from a grave, which it usually is. - 💉 **Used.** Psytrainers, neurotrainers, mech serums and modded usables, when the pawn uses one on its own.
- 👊 **Started a social fight.** The pawn who reacts and swings first, usually the insulted one. - 🗯️ **Social interactions.** Every interaction: insults, slights, chitchat, romance attempts, breakups, jailbreak talk, modded ones. The pawn who starts it is the offender. Group: insult or slight.
- 🗯️ **Insult.** Every insult by the one who insults; slights are their own entry. Planning for insulting sprees. - 🧾 **Recorded acts.** Every act the game records with the pawn as its doer, such as cut a tree, butchered a human, harvested an organ or executed a prisoner. Most of them are recorded only with Ideology, and the category's tooltip says so.
- 🍖 **Ate.** Any food or drug by name, or a group: any meat (meals included), raw meat and corpses, human meat, insect meat, hard drugs. - 📊 **Records.** Every counted record, such as kills, animals slaughtered, bodies stripped or things hauled. A case opens when the record goes up.
- 🧾 **Recorded acts, records and bills.** Cut a tree, butchered a human, harvested an organ (most need Ideology); kills, bodies stripped; made a human leather duster, any surgery. - 🧪 **Bills.** Every recipe, such as made a human leather duster, cooked a fine meal or installed a bionic arm, when the pawn finishes one iteration. Group: any surgery.
- 💢 **Tantrums and rages.** Planning when the break starts; a warden can subdue a tantrum or a murderous rage, since those pawns don't turn on it. A berserk colonist fights back, so its case takes a warning, guilt or jail, and the jail waits until the break is over or you down it. - 🔥 **Special acts.** Set a fire (the pawn who ignites it, never a raider); displayed a corpse, where the case notes "on a table" and "dug up from a grave", which it nearly always is; started a social fight, filed on the pawn who swings first, usually the insulted one.
- 🧮 **No flood.** Acts outside a break open at most one case per colonist and law a day; more acts only raise its count. - 🔗 **Breaks lead to their act.** A drug binge's "did it" is a dose of the drug the row names, a food binge's a meal, a fire-starting spree's a fire, a corpse obsession's the displayed corpse, an insulting spree's an insult or slight, a jailbreaker's jailbreak talk. Links go by mental state class, so a modded break built on one of these gets its link too, and another mod can add its own with a `BreakLinkDef` and no code. Every other break is Planning only for now. `Defs/BlaxLaws_BreakLinks.xml`
- 📁 **One case per incident.** A binge is one case from start to end; it moves from planning to did it, each row fires once per case, and the case counts the doses. An act that is the did-it of an open break case belongs to that case; when it also matches a row of its own, the row with the higher severity decides.
- 🧮 **No flood.** Acts outside a break open at most one case per offender and law a day (0 to 7 days in the settings). A further act in that window raises the count on that case and posts no message, so a meat-eating colony of 60 doesn't flood the log or the save.
- 👥 **Who is covered.** Free colonists, children included, and colony slaves. Never guests, Hospitality visitors, quest lodgers, prisoners or babies. Acts while drafted or on a job you ordered open no case (setting).
### Punishments ### Punishments
- ✋ **Warn.** A record and a message. Which punishments a row offers depends on its entry and stage: a planning row offers warn, subdue and jail; a break's did-it row also guilty and subdue then jail; every other act warn, guilty and jail. `Defs/BlaxLaws_Punishments.xml`
- ⚖️ **Guilty for N days.** Vanilla guilt: the arrest of a free colonist is always accepted, executing it costs the colony only the small "justified execution" mood hit plus its family's grief, and banishing it costs no colony-wide mood.
- 🛑 **Subdue.** A warden beats the offender down with fists to stop the break: bruises on torso and limbs, never the head or a bionic part, no lost parts, no scars, and the beating doesn't hand out the break's catharsis. No warden is pulled off a rescue, a patient or a fire, and nobody is sent while raiders are on the map. `Source/BlaxLaws/JobDriver_Subdue.cs` - ✋ **Warn.** The case is filed and a message posted, nothing more.
- 🔒 **Jail for N days.** Arrested into a prisoner bed, kept on "Maintain only" so no prison mod recruits or enslaves your colonist, released by a warden when the time is served, back to work with its priorities intact. `Source/BlaxLaws/Enforcement.cs` - ⚖️ **Guilty for N days.** Vanilla guilt: the guilty icon shows, the arrest of a free colonist is always accepted, executing it costs the colony only the -2 "justified execution of colonist" thought plus its family's grief, and banishing it costs no colony-wide thought. A longer guilt already on the pawn is never shortened. `Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs`
- 🔗 **Subdue, then jail.** Beaten down and carried straight to a cell before a doctor takes it to bed. - 🛑 **Subdue.** A warden beats the offender down with fists to end its break: capped blunt hits on torso, shoulders, arms and legs, never the head, never a bionic part, no lost parts, no scars, no bleeding. Every part keeps at least half its health, and the bruises never add up to a deadly amount. The offender doesn't fight back, and the enforcer isn't marked guilty. The beating stops at downed, or once three hits in a row add no pain (go-juice, painkillers). The subdued pawn loses the catharsis that ending its break would give (setting), so the beating doesn't reward the crime. Tantrums, murderous and sadistic rage can be subdued too; the warden is never the rage's named victim. After the break a subdue row warns instead. `Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs`
- 🔒 **Jail for N days.** A warden arrests the offender into a prisoner bed; guilt for the sentence is renewed right before the arrest, so it is always accepted. Two ticks after the capture the prisoner is set to "Maintain only", after any default a prison mod or Blax Castes writes, so nothing recruits, enslaves or executes your colonist. `Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs`
- ⛓️ **Subdue, then jail.** Beaten down, and in the same tick the warden's next job is the vanilla capture to a prisoner bed, ahead of a doctor's rescue. After the break it jails without the beating.
- 👶 **Children are never beaten** (Biotech): a subdue on a child becomes jail when the row has days, a warning otherwise.
- 😡 **Berserk breaks fight back.** Their rows offer warn, guilty and jail, never subdue. The jail waits until the break ends or you down the pawn, then arrests or captures it.
### Enforcement
- 🚑 **One enforcer per case, safely.** The nearest awake colonist with Warden work goes, then anyone able (setting: wardens only). Never a slave, a child, the offender, a pawn in a break, on a player order or in a party or ritual, and never one rescuing, carrying or tending someone, fighting a fire, manning a turret, doing surgery or fleeing. `Source/BlaxLaws/Enforcement/Enforcers.cs`
- ⚠️ **Nobody is sent into danger.** While hostiles threaten the map, a berserk colonist included, cases wait and are enforced after the fight. A warden already on a case when a raid arrives is called back.
- 🔁 **Cases move on by themselves.** A planning case closes when the break ends with nothing done, a lost subdue starts again, and an arrest that waited for a bed, an enforcer, a doctor's reservation or the end of a fight happens as soon as it can. A did-it jail that arrives while the planning subdue still runs takes over from it. `Source/BlaxLaws/Enforcement/Enforcement.cs`
- 📨 **Messages and letters.** A message for every case. A letter only when a colonist is jailed or you have to act: no prisoner bed, no enforcer, a role holder on hold. No second letter for a break, since the vanilla one already arrives.
### Sentences ### Sentences
- ⏳ **Served and released.** The colonist sits out its days on "Maintain only", a warden lets it out when the time is served, and another mod's early release closes the sentence instead of fighting it. - ⏳ **Served and released.** The colonist sits out its days on "Maintain only", keeping its work priorities, since prisoners have no disabled work types. When the time is served Laws sets "Release" and a warden walks it out; if nobody has after a day, Laws releases it in place. The release counts from the capture, not from the filing. `Source/BlaxLaws/Sentences/Sentences.cs`
- ⏸️ **Role holders and mechanitors wait.** An arrest would take an ideoligion role and shut a mechanitor's mechs down, so their case waits with "Arrest now" and a letter says why. - 🛏️ **The old bed.** The arrest job claims the prisoner bed before the arrest happens; if the arrest then fails, Laws gives the colonist its old bed back when it is still free.
- 🚪 **Another mod's early release wins.** A jailed colonist that is recruited, released by you or another mod, escapes or dies closes its sentence with that outcome and a message.
- ⏸️ **Role holders and mechanitors wait.** An arrest would take an ideoligion role (Ideology) and shut a mechanitor's mechs down (Biotech), so their case waits with "Arrest now" and a letter says why. Guilt is set anyway and renewed when you press it.
- 🔗 **Slaves aren't jailed yet.** Releasing an imprisoned slave would send it back to its old faction, so a slave's jail row subdues it while it is in its break and warns otherwise, until "Jail for slaves" ships.
### Save and settings ### Save and settings
- 💾 **Save-safe.** One piece of game data holds the lawbook and the cases. Unsubscribing leaves a save that loads with two errors in the log; jailed colonists stay prisoners you can release by hand. `Source/BlaxLaws/GameComponent_BlaxLaws.cs` - 💾 **Save-safe.** One game component holds the lawbook and the cases, as names and numbers; nothing of Laws enters a vanilla save list, and the subdue job is hidden from the save. Blax Laws can be added to a running save. Unsubscribing leaves a save that loads with two errors in the log: jailed colonists stay vanilla prisoners you release by hand in the prisoner tab, and their guilt runs out on its own. `Source/BlaxLaws/GameComponent_BlaxLaws.cs`
- ⚙️ **Mod settings.** "Enforce laws", "Show Laws tab", messages and letters, who enforces, catharsis after subdue, player orders exempt, days between cases for acts outside a break, how long closed cases stay, "Reset to defaults". - ⚙️ **Mod settings.** "Enforce laws" (off keeps the case log and carries out nothing), "Show Laws tab", "Messages for cases", "Letters for jailings", "Enforcers" (wardens first or wardens only), "Subdued pawns lose their catharsis", "Player orders are exempt", "Days between cases for acts outside a break", "Keep closed cases" (60 days), "Reset to defaults". `Source/BlaxLaws/BlaxLawsMod.cs`
## Planned ## Planned
The whole plan, by area, with the order and the reasons: `docs/features.md`. Coming after the first release: In build order. What each area covers and its steps are in `docs/features.md`, the specs in `docs/design.md`.
- 🔪 **Violence, next.** Assault, harming prisoners or slaves, manslaughter and murder, plus "did it" for tantrums, berserk, rages and the slaughterer break; drugs the pawn's drug policy doesn't allow. - 🔪 **Violence, drugs and the rest of the punishments.** Assault, harming prisoners or slaves, manslaughter and murder, with "did it" for tantrums, berserk and the rages; the slaughterer break; drugs the pawn's drug policy doesn't allow. Reprimand, and banish or execute after you confirm. Release gives back the bed, grave, throne, deathrest casket, ideoligion role, mech work modes and the dropped weapon, so role holders and mechanitors no longer wait. Pardon, early release and more days.
- 🛏️ **Back to its own bed.** When the sentence is served the colonist gets back its bed, grave, throne, deathrest casket, ideoligion role, its mechs' work modes and the weapon the arrest made it drop, so role holders and mechanitors no longer wait. With it: pardon, early release and more days, a reprimand, and banish or execute after you confirm. - 📈 **Repeat offenders.** A criminal record per colonist, then harsher punishments for a repeat offence and early release on probation.
- 🏛️ **Court.** "Trial" as a punishment through Ideology's trial, then court sessions without any DLC: a judge, a prosecutor and spectators at a place you pick, a verdict that weighs evidence against Social skill, the sentence from your lawbook, "jail, then trial" for an offender you want locked up until the verdict, and if you want a court that sits on its own at a set hour. Then attorneys, witnesses and a guilty plea, trials over up to three days, courtrooms and appeals. - 🏛️ **Court.** "Trial" as a punishment through Ideology's trial, then court sessions on the core game: a judge, a prosecutor and spectators at a place you pick, a verdict that weighs evidence against Social skill, the sentence from your lawbook, "jail, then trial", and a court that sits on its own if you want. Then attorneys, witnesses and a guilty plea, trials over several days, courtrooms and appeals.
- 🗳️ **Colony votes.** Colonists propose and repeal laws and vote by traits, beliefs, opinion and mood, and you back or veto the result; the colony elects its judge, with terms, by-elections and recalls; later a jury and pardon petitions. - 🗳️ **Colony votes.** Colonists propose and repeal laws and vote by traits, beliefs, opinion and mood, and you back or veto the result; the colony elects its judge; later a jury and pardon petitions.
- 📈 **Repeat offenders.** A criminal record per colonist, harsher punishments for a repeat offence, and early release on probation. - 🤝 **With the other Blax mods.** Blax Castes keeps a convict's caste through any sentence, Blax Slaves' wardens calm slaves before Laws steps in, a jailed slave becomes a slave again, and confinement as a sentence through a Blax Castes caste.
- 🧑‍⚖️ **Your call.** Decide a case yourself instead of a fixed punishment, talk a colonist down instead of beating it, and laws for one group only: slaves, children, a caste, or a colonist above the law. - 💬 **Your call.** Decide a case yourself, talk a colonist down instead of beating it, laws for one group only (slaves, children, a caste, or a colonist above the law), lawbook templates for the next colony, your own convicts breaking out and slave rebellions as crimes, crimes against the faith (Ideology), and a fighter you pick to subdue a berserk colonist.
- 📚 **Lawbook templates.** Take your lawbook to the next colony.
- 🚨 **Uprisings.** Your own convicts breaking out, and slave rebellions, as crimes.
- 🙏 **Crimes against the faith.** One law for anything the colony's ideoligion forbids, and one for leaving it (Ideology).
- 🥊 **Subdue a pawn that fights back.** For a berserk colonist, you pick the fighter and Laws sends it.
- 🤝 **With the other Blax mods.** Blax Castes keeps a convict's caste through any sentence, Blax Slaves' wardens calm slaves before Laws steps in, jailed slaves become slaves again, and a confinement sentence through a Blax Castes caste (the last two still Fabian's call).
## DLC support ## DLC support
Blax Laws works with any combination of DLCs, core only included, and lists none as a dependency. Every category and punishment of the first release runs on the core game; later, the throne, deathrest casket, role and mech parts of the release give-back switch off without their DLC. The act list shows what your game has: a DLC's breaks, drugs and recipes appear when it's active. Blax Laws works with any combination of DLCs, core only included, and lists none as a dependency. Every category and punishment of this release runs on the core game. The act list shows what your game has: a DLC's breaks, drugs, interactions, usables and recipes appear when it is active and are absent without it.
- **Ideology** adds slaves, who can be warned, marked guilty and subdued. An arrest takes a role holder's role, so its case waits for "Arrest now" until the give-back returns the role at the release. - **Ideology** adds slaves, who get warn, guilty and subdue, and records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires. An arrest would take a role holder's role, so its case waits for "Arrest now".
- **Biotech** adds children, who are never beaten, and mechanitors, whose mechs shut down in jail; their case waits for "Arrest now" until the give-back returns the mechs to their work modes. - **Biotech** adds children, who are never beaten, and mechanitors, whose mechs would shut down in jail, so their case waits for "Arrest now".
- **Ideology** also records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires.
- **Royalty**, **Anomaly** and **Odyssey**: their acts appear in the list when active; Laws needs none of them. - **Royalty**, **Anomaly** and **Odyssey**: their acts appear in the list when active; Laws needs none of them.
- **A save made with a DLC** loads without it. - **A save made with a DLC** loads without it. A law naming a DLC entry stays and shows "Needs <DLC>"; a case whose offender was a slave keeps its name.
## Compatibility ## Compatibility
- ✔️ Prison Labor, Prisoner Realism, Custom Prisoner Interactions and Hospitality: a jailed colonist is a vanilla prisoner, so their features apply; Laws only keeps its own prisoners on "Maintain only" and lets them go when the time is served. - ✔️ Prison Labor, Prisoner Realism and Custom Prisoner Interactions: a jailed colonist is a vanilla prisoner, so their features apply. Laws only keeps its own convicts on "Maintain only" and lets them go when the time is served; Prison Labor's work toggle stays as that mod sets it. While that toggle is on, Prison Labor turns off the work types it bars prisoners from, and they stay off after the release; turn the toggle off on a jailed colonist to keep its work priorities.
- ✔️ Prisoner Sentencing and Prison Expanded: if one of them releases a colonist Laws jailed, Laws closes its sentence instead of fighting it. - ✔️ Prisoner Sentencing and Prison Expanded: if one of them releases a colonist Laws jailed, Laws closes its sentence instead of fighting it.
- ✔️ RimCourt: it judges civil disputes as the lord, Laws tries those who break your laws; both run side by side. - ✔️ Hospitality: guests are never offenders.
- ♻️ Replaces Rimworld Law and Order, which has no 1.7 build, needs Ideology and adds its own crime events. - ✔️ Blax Zones: arrests use any prisoner bed, zone beds included. Blax Castes: a jailed colonist moves to its new-prisoner row and back to its old caste after the release; Laws writes only "Maintain only" and "Release" on colonists it jailed.
- ✔️ `Tests/run-tests.ps1 -Compat` runs the suite next to Prison Labor, Prisoner Realism, Custom Prisoner Interactions, Hospitality, Vanilla Social Interactions Expanded, Blax Castes, Blax Zones, Blax Slaves and Blax Defaults, and Humanoid Alien Races once it is installed.
- ❌ Multiplayer: not supported. - ❌ Multiplayer: not supported.
Load order: Harmony, Blax Castes, Blax Zones, Blax Slaves, Blax Laws. No Blax mod needs another. Load order: Harmony, Blax Castes, Blax Zones, Blax Slaves, Blax Laws. No Blax mod needs another.
## 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):
```powershell
New-Item -ItemType Junction -Path "E:\SteamLibrary\steamapps\common\RimWorld\Mods\BlaxLaws" -Target (Get-Location).Path
```
Build (needs the .NET 10 SDK; output goes to `1.7/Assemblies/BlaxLaws.dll`). `RimWorldDir` and `HarmonyDir` in the csproj point at the Steam install and the Harmony mod; override them with `-p:RimWorldDir=...` elsewhere.
```powershell
dotnet build Source\BlaxLaws\BlaxLaws.csproj -c Release
```
`Tests/run-tests.ps1` builds the mod and the test mod in `Tests/BlaxLawsTests`, starts RimWorld headless with its own save data folder in `%TEMP%\BlaxLawsTest`, runs the suite, saves and reloads, then loads the save with the mod's game component removed. Your mod list, saves and settings stay untouched. It needs Steam running. The script's header lists every switch.
```powershell
.\Tests\run-tests.ps1 # every installed DLC
.\Tests\run-tests.ps1 -NoDlc # core only
.\Tests\run-tests.ps1 -Dlc Ideology # only the DLCs named
.\Tests\run-tests.ps1 -Compat # next to the mods listed under Compatibility
```
Design and roadmap: `docs/design.md` and `docs/features.md`.
### Workshop upload
`Tools/workshop-upload.ps1` creates and updates the Workshop item from the command line. A small tool (`Tools/WorkshopUpload`) uses the Steamworks.NET build and `steam_api64.dll` that ship with RimWorld and attaches to the running, logged-in Steam client as RimWorld, so it needs no password, no game window and no dev mode.
```powershell
.\Tools\workshop-upload.ps1 # dry run: build, stage, check the Steam login and the item
.\Tools\workshop-upload.ps1 -Check # release check: every -Publish gate, then the list of problems
.\Tools\workshop-upload.ps1 -Publish -DescriptionFile docs\workshop-description.txt # upload and replace the description
```
The dry run and `-Check` upload nothing. The script stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), the title from About.xml and the preview from `About/Preview.png`. The change note is every CHANGELOG.md entry newer than the version in `Tools/workshop-published.txt`.
Blax Laws has no Workshop item yet. Without `About/PublishedFileId.txt` the first `-Publish` creates it, Public unless you pass `-Visibility private` (Steam's own default for a new item is Private), and writes its id to `About/PublishedFileId.txt` before the content upload, so a failed upload is retried as an update and never makes a second item. After a successful upload it writes `Tools/workshop-published.txt`. Commit both files.
`-Publish` refuses unless:
- the shipped files are committed and pushed, and the top CHANGELOG.md entry matches `modVersion` in About.xml;
- two `Tests/run-tests.ps1` runs passed after the last build, one with every installed DLC and one with `-NoDlc` (`BlaxLawsTestResults.all.txt` and `BlaxLawsTestResults.nodlc.txt` in `%TEMP%\BlaxLawsTest`);
- `About/Preview.png` is under 1 MB;
- the description fits Steam's 8000-byte limit, every forgejo.blax.at link in it opens without a login, and every `[img]` host sends an `Access-Control-Allow-Origin` header. Steam loads description images cross-origin and shows a broken image otherwise. Forgejo's raw URLs send no such header, so the images are served from `cdn.blax.at/blax-gaming/laws/`, which does.
The Workshop page is `docs/workshop-description.txt` (Steam BBCode). Its art is rendered from `Source/Art` (see `Source/Art/README.md`), and `docs/workshop-media.md` lists the in-game clips worth recording. `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note.
The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Laws > Advanced... > Upload to Steam Workshop (dev mode), then `Tools/workshop-stage.ps1 -Done` copies `About/PublishedFileId.txt` back into the repo and restores the junction.
--- ---
## Made by Blax ## Made by Blax

56
Source/Art/README.md Normal file
View File

@ -0,0 +1,56 @@
# Preview art
`preview.html` renders `About/Preview.png` (1280x720) and `icon.html` renders `About/ModIcon.png` (256x256) from `icon.svg`. Both follow the Blax CI from https://www.blax.at/ui-ci and match the art of the other Blax Gaming mods, so the mods read as one label: Blax black `#050805`, Blax green `#19C63C`, logo gray `#CDCDCD`, Geist for headings, Inter for body text, Rajdhani only for the "Blax Gaming" wordmark. Fonts are the woff2 files blax.at self-hosts (all SIL Open Font License); icons are lucide (ISC license).
The preview has Slaves' layout: wordmark top left, "Blax Laws" with a green subtitle on the left, four feature rows on the right (write your own lawbook, any act can be a crime, subdue or jail, court and votes planned). "Laws" is short, so the feature column starts at 700 px instead of Zones' 760 and the longer row titles stay on one line. The icon is the Blax monogram with a green "scale" badge, so it stands apart from Slaves' plain monogram, Castes' "layers", Zones' "package" and Defaults' "sliders-horizontal" badges in the mod list.
| File | Renders |
|---|---|
| `preview.html` | `About/Preview.png`, 1280x720 |
| `icon.html` + `icon.svg` | `About/ModIcon.png`, 256x256, transparent |
| `header.html` | the Workshop section headers in `docs/art/steam/`, 1270x150 |
| `oss-banner.html` | `docs/art/blax-oss-banner.png`, 1600x254, from `docs/art/blax-oss-banner.svg` |
| `blax-monogram.svg`, `monogram-centered.svg` | the Blax monogram, used by the pages above |
| `fonts/` | Geist, Inter, Rajdhani 700 |
Render with Edge headless from this folder. The separate profile folder keeps the headless run away from an open Edge window, and `| Out-Null` waits for each screenshot.
```powershell
$edge = 'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
$here = (Get-Location).Path -replace '\\','/'
$edgeData = "$env:TEMP\blax-art-edge-laws"
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1280,720 --screenshot="$PWD\..\..\About\Preview.png" "file:///$here/preview.html" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=2000 --window-size=256,256 --default-background-color=00000000 --screenshot="$PWD\..\..\About\ModIcon.png" "file:///$here/icon.html" | Out-Null
```
`About/Preview.png` must stay under 1 MB for the Workshop; it is about 90 KB.
## Workshop page art
The Steam description (`docs/workshop-description.txt`) shows a section header from `docs/art/steam/` above each part and Blax Software's Open Source Initiative banner at the end. Steam shows no SVG, so the banner (`docs/art/blax-oss-banner.svg`, the same file as in the other Blax Gaming mods) is also rendered as a PNG; it is the same PNG as Zones' `docs/art/blax-oss-banner.png`. `header.html` takes the title (`t`), subtitle (`s`) and lucide icon name (`i`) as query parameters; the icon must be in its `icons` map.
| File | t | s | i |
|---|---|---|---|
| `lawbook.png` | Lawbook | Write what is forbidden and see every case | book-open-text |
| `crimes.png` | Crimes | Any act can be one, DLC and modded content included | fingerprint |
| `punishments.png` | Punishments | Warn, guilty, subdue and jail | lock-keyhole |
| `planned.png` | Planned | Coming in later releases | milestone |
| `compatibility.png` | Compatibility | Other mods and where they overlap | puzzle |
```powershell
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1600,254 --screenshot="$PWD\..\..\docs\art\blax-oss-banner.png" "file:///$here/oss-banner.html" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\lawbook.png" "file:///$here/header.html?t=Lawbook&s=Write%20what%20is%20forbidden%20and%20see%20every%20case&i=book-open-text" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\crimes.png" "file:///$here/header.html?t=Crimes&s=Any%20act%20can%20be%20one%2C%20DLC%20and%20modded%20content%20included&i=fingerprint" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\punishments.png" "file:///$here/header.html?t=Punishments&s=Warn%2C%20guilty%2C%20subdue%20and%20jail&i=lock-keyhole" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\planned.png" "file:///$here/header.html?t=Planned&s=Coming%20in%20later%20releases&i=milestone" | Out-Null
& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\compatibility.png" "file:///$here/header.html?t=Compatibility&s=Other%20mods%20and%20where%20they%20overlap&i=puzzle" | Out-Null
```
Check each result for its size before using it:
```powershell
Add-Type -AssemblyName System.Drawing
Get-ChildItem ..\..\About\*.png, ..\..\docs\art\steam\*.png, ..\..\docs\art\*.png | ForEach-Object { $i = [System.Drawing.Image]::FromFile($_.FullName); '{0}: {1}x{2}, {3} bytes' -f $_.Name, $i.Width, $i.Height, $_.Length; $i.Dispose() }
```
The Steam page loads these images from the Blax CDN (`https://cdn.blax.at/blax-gaming/`), not from Forgejo: Steam requests description images cross-origin, and only the CDN answers with `Access-Control-Allow-Origin`. After re-rendering, copy the PNGs to `blax-gaming/laws/` on the CDN (`blax-gaming/laws/<name>.png`; the banner is shared at `blax-gaming/blax-oss-banner.png` and is already there). The upload steps are in Blax's internal infrastructure docs.

View File

@ -0,0 +1,16 @@
<svg width="980" height="980" viewBox="0 0 980 980" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_477_24)">
<circle cx="474.5" cy="474.5" r="474.5" fill="#CDCDCD"/>
<circle cx="475" cy="474" r="352" stroke="black" stroke-width="96"/>
<path d="M475 226L405 651.616L474.5 778L545 651.616L475 226Z" fill="black"/>
<path d="M385 226L475 306L565 226H385Z" fill="black"/>
<path d="M875 226H99L131.5 179.542L169.5 139.031L253.5 84.0246L475 45L715 98.1478L875 226Z" fill="#CDCDCD"/>
<rect x="287" y="226" width="13" height="13" fill="#CDCDCD"/>
<rect x="650" y="226" width="13" height="13" fill="#CDCDCD"/>
</g>
<defs>
<clipPath id="clip0_477_24">
<rect width="980" height="980" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 740 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

46
Source/Art/header.html Normal file
View File

@ -0,0 +1,46 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Section header for the Workshop page, 1270x150 (shown at half size). Parameters: ?t=Title&s=Subtitle&i=icon -->
<style>
@font-face { font-family: Geist; src: url(fonts/geist.woff2) format("woff2"); font-weight: 100 900; }
@font-face { font-family: Inter; src: url(fonts/inter.woff2) format("woff2"); font-weight: 100 900; }
:root {
--background: #050805;
--accent: #19C63C;
--heading: oklch(98% .008 145);
--muted-foreground: oklch(75% .015 145);
--border: oklch(30% .016 145);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 1270px; height: 150px; background: var(--background); overflow: hidden; }
body { font-family: Inter, sans-serif; display: flex; align-items: center; gap: 32px; padding: 0 56px; border-bottom: 4px solid var(--accent); }
svg.icon { width: 64px; height: 64px; flex: none; color: var(--accent); }
h1 { font-family: Geist, sans-serif; font-weight: 600; font-size: 54px; line-height: 1; letter-spacing: -0.035em; color: var(--heading); }
p { margin-top: 10px; font-size: 25px; line-height: 1.2; color: var(--muted-foreground); }
.mark { margin-left: auto; width: 52px; height: 52px; opacity: .35; }
</style>
</head>
<body>
<svg class="icon" viewBox="0 0 24 24" id="icon"></svg>
<div><h1 id="t"></h1><p id="s"></p></div>
<img class="mark" src="blax-monogram.svg" alt="">
<script>
// lucide icons (ISC license), from api.iconify.design/lucide
const icons = {
'book-open-text': '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v16m4-8h2m-2-4h2m2.001 10A2 2 0 0 0 22 17V5a2 2 0 0 0-1.999-2L16 3.002A5 5 0 0 0 12 5a5 5 0 0 0-4-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 1.999 2H8a5 5 0 0 1 4 2a5 5 0 0 1 4-2zM6 13h2M6 9h2"/>',
fingerprint: '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4M14 13.12c0 2.38 0 6.38-1 8.88m4.29-.98c.12-.6.43-2.3.5-3.02M2 12a10 10 0 0 1 18-6M2 16h.01m19.79 0c.2-2 .131-5.354 0-6"/><path d="M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2m2.31 12c.21-.66.45-1.32.57-2M9 6.8a6 6 0 0 1 9 5.2v2"/></g>',
'lock-keyhole': '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><circle cx="12" cy="16" r="1"/><rect width="18" height="12" x="3" y="10" rx="2"/><path d="M7 10V7a5 5 0 0 1 10 0v3"/></g>',
scale: '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M12 3v18m7-13l3 8a5 5 0 0 1-6 0zV7"/><path d="M3 7h1a17 17 0 0 0 8-2a17 17 0 0 0 8 2h1M5 8l3 8a5 5 0 0 1-6 0zV7m2 14h10"/></g>',
gavel: '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m14 13l-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381M16 16l6-6m-.5.5l-8-8M8 8l6-6M8.5 7.5l8 8"/>',
puzzle: '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.39 4.39a1 1 0 0 0 1.68-.474a2.5 2.5 0 1 1 3.014 3.015a1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474a2.5 2.5 0 1 0-3.014 3.015a1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474a2.5 2.5 0 1 1-3.014-3.015a1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474a2.5 2.5 0 1 0 3.014-3.015a1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>',
milestone: '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 13v8m0-18v3m6.172 0a2 2 0 0 1 1.414.586l2.06 2.06a1.207 1.207 0 0 1 0 1.708l-2.06 2.06a2 2 0 0 1-1.414.586H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1z"/>'
};
const q = new URLSearchParams(location.search);
document.getElementById('t').textContent = q.get('t') || 'Title';
document.getElementById('s').textContent = q.get('s') || '';
document.getElementById('icon').innerHTML = icons[q.get('i')] || '';
</script>
</body>
</html>

6
Source/Art/icon.html Normal file
View File

@ -0,0 +1,6 @@
<!doctype html>
<html><head><meta charset="utf-8"><style>
html, body { margin: 0; width: 256px; height: 256px; background: transparent; overflow: hidden; }
img { display: block; width: 256px; height: 256px; }
</style></head>
<body><img src="icon.svg" alt=""></body></html>

27
Source/Art/icon.svg Normal file
View File

@ -0,0 +1,27 @@
<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<!-- transparent gap between the monogram and the badge, so it works on any background -->
<mask id="gap">
<rect width="256" height="256" fill="white"/>
<circle cx="204" cy="204" r="59" fill="black"/>
</mask>
</defs>
<!-- Blax monogram, 200 px wide, top left -->
<g mask="url(#gap)">
<g transform="scale(0.210748)">
<circle cx="474.5" cy="474.5" r="474.5" fill="#CDCDCD"/>
<circle cx="475" cy="474" r="352" stroke="black" stroke-width="96"/>
<path d="M475 226L405 651.616L474.5 778L545 651.616L475 226Z" fill="black"/>
<path d="M385 226L475 306L565 226H385Z" fill="black"/>
<path d="M875 226H99L131.5 179.542L169.5 139.031L253.5 84.0246L475 45L715 98.1478L875 226Z" fill="#CDCDCD"/>
<rect x="287" y="226" width="13" height="13" fill="#CDCDCD"/>
<rect x="650" y="226" width="13" height="13" fill="#CDCDCD"/>
</g>
</g>
<!-- Laws badge: lucide "scale" (ISC license) on Blax green -->
<circle cx="204" cy="204" r="52" fill="#19C63C"/>
<g transform="translate(204 204) scale(3) translate(-12 -12)" stroke="#050805" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3v18m7-13l3 8a5 5 0 0 1-6 0zV7"/>
<path d="M3 7h1a17 17 0 0 0 8-2a17 17 0 0 0 8 2h1M5 8l3 8a5 5 0 0 1-6 0zV7m2 14h10"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,16 @@
<svg width="256" height="256" viewBox="0 0 949 949" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_477_24)">
<circle cx="474.5" cy="474.5" r="474.5" fill="#CDCDCD"/>
<circle cx="475" cy="474" r="352" stroke="black" stroke-width="96"/>
<path d="M475 226L405 651.616L474.5 778L545 651.616L475 226Z" fill="black"/>
<path d="M385 226L475 306L565 226H385Z" fill="black"/>
<path d="M875 226H99L131.5 179.542L169.5 139.031L253.5 84.0246L475 45L715 98.1478L875 226Z" fill="#CDCDCD"/>
<rect x="287" y="226" width="13" height="13" fill="#CDCDCD"/>
<rect x="650" y="226" width="13" height="13" fill="#CDCDCD"/>
</g>
<defs>
<clipPath id="clip0_477_24">
<rect width="980" height="980" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 740 B

View File

@ -0,0 +1,13 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Renders docs/art/blax-oss-banner.svg (Blax Software's Open Source Initiative banner) as a PNG for the Steam page, which shows no SVG. -->
<style>
* { margin: 0; padding: 0; }
html, body { width: 1600px; height: 254px; background: #fff; overflow: hidden; }
img { display: block; width: 1600px; height: 254px; object-fit: cover; }
</style>
</head>
<body><img src="../../docs/art/blax-oss-banner.svg" alt=""></body>
</html>

76
Source/Art/preview.html Normal file
View File

@ -0,0 +1,76 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@font-face { font-family: Geist; src: url(fonts/geist.woff2) format("woff2"); font-weight: 100 900; }
@font-face { font-family: Inter; src: url(fonts/inter.woff2) format("woff2"); font-weight: 100 900; }
@font-face { font-family: Rajdhani; src: url(fonts/rajdhani-700.woff2) format("woff2"); font-weight: 700; }
:root {
--background: #050805; /* Blax black */
--accent: #19C63C; /* Blax green */
--logo-gray: #CDCDCD;
--heading: oklch(98% .008 145);
--foreground: oklch(97% .01 145);
--muted-foreground: oklch(75% .015 145);
--border: oklch(30% .016 145);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 1280px; height: 720px; background: var(--background); overflow: hidden; }
body { font-family: Inter, sans-serif; color: var(--foreground); position: relative; }
.top { position: absolute; left: 72px; right: 72px; top: 52px; display: flex; align-items: center; justify-content: space-between; }
.brand { display: flex; align-items: center; gap: 16px; }
.brand img { width: 56px; height: 56px; }
.wordmark { font-family: Rajdhani, sans-serif; font-weight: 700; font-size: 40px; line-height: 1; letter-spacing: -0.01em; color: var(--heading); }
.wordmark span { color: var(--accent); }
.hero { position: absolute; left: 72px; top: 158px; width: 600px; }
h1 { font-family: Geist, sans-serif; font-weight: 600; font-size: 178px; line-height: .9; letter-spacing: -0.045em; color: var(--heading); }
.sub { margin-top: 26px; font-family: Geist, sans-serif; font-weight: 600; font-size: 46px; line-height: 1; letter-spacing: -0.03em; color: var(--accent); }
.lede { margin-top: 18px; font-size: 23px; line-height: 1.4; color: var(--muted-foreground); max-width: 560px; }
/* "Laws" is short, so the feature column starts 60 px further left than Zones' and its longer row titles fit on one line. */
.features { position: absolute; left: 700px; right: 72px; top: 150px; bottom: 56px; display: flex; flex-direction: column; border-left: 1px solid var(--border); }
.feature { flex: 1; display: flex; align-items: center; gap: 24px; padding-left: 40px; border-top: 1px solid var(--border); }
.feature:first-child { border-top: 0; }
.feature svg { width: 40px; height: 40px; flex: none; color: var(--accent); }
.feature h2 { font-family: Geist, sans-serif; font-weight: 600; font-size: 31px; line-height: 1.05; letter-spacing: -0.03em; color: var(--heading); }
.feature p { margin-top: 6px; font-size: 19px; line-height: 1.35; color: var(--muted-foreground); }
</style>
</head>
<body>
<div class="top">
<div class="brand">
<img src="blax-monogram.svg" alt="">
<div class="wordmark">Blax <span>Gaming</span></div>
</div>
</div>
<div class="hero">
<h1>Blax<br>Laws</h1>
<div class="sub">for RimWorld 1.7</div>
<p class="lede">Write your colony's laws.<br>Wardens stop and jail whoever breaks them.</p>
</div>
<!-- lucide icons (ISC license): book-open-text, fingerprint, lock-keyhole, gavel -->
<div class="features">
<div class="feature">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v16m4-8h2m-2-4h2m2.001 10A2 2 0 0 0 22 17V5a2 2 0 0 0-1.999-2L16 3.002A5 5 0 0 0 12 5a5 5 0 0 0-4-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 1.999 2H8a5 5 0 0 1 4 2a5 5 0 0 1 4-2zM6 13h2M6 9h2"/></svg>
<div><h2>Write your own lawbook</h2><p>Empty until you add a law.</p></div>
</div>
<div class="feature">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4M14 13.12c0 2.38 0 6.38-1 8.88m4.29-.98c.12-.6.43-2.3.5-3.02M2 12a10 10 0 0 1 18-6M2 16h.01m19.79 0c.2-2 .131-5.354 0-6"/><path d="M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2m2.31 12c.21-.66.45-1.32.57-2M9 6.8a6 6 0 0 1 9 5.2v2"/></svg>
<div><h2>Any act can be a crime</h2><p>Every break, drug, meal and bill.</p></div>
</div>
<div class="feature">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="16" r="1"/><rect width="18" height="12" x="3" y="10" rx="2"/><path d="M7 10V7a5 5 0 0 1 10 0v3"/></svg>
<div><h2>Subdue or jail</h2><p>A binge stopped before the first dose.</p></div>
</div>
<div class="feature">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m14 13l-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381M16 16l6-6m-.5.5l-8-8M8 8l6-6M8.5 7.5l8 8"/></svg>
<div><h2>Court and votes planned</h2><p>Trials, judges and laws put to a vote.</p></div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- RimWorld 1.7 runs on .NET 10 (CoreCLR). Build: dotnet build -c Release -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>BlaxLaws</AssemblyName>
<RootNamespace>BlaxLaws</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<OutputPath>..\..\1.7\Assemblies\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<GenerateDependencyFile>false</GenerateDependencyFile>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType>
<Deterministic>true</Deterministic>
<!-- The SDK appends the git commit to the informational version, so every commit would change the
next build and the committed DLL could never match HEAD. Same source, same bytes. -->
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<!-- Keep local paths out of the shipped DLL/PDB. -->
<PathMap>$(MSBuildProjectDirectory)=Source/BlaxLaws</PathMap>
</PropertyGroup>
<!-- Override on the command line if the game or the Harmony mod live elsewhere. -->
<PropertyGroup>
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="UnityStubs">
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="0Harmony">
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,25 @@
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>Defs Laws ships. Act categories and special acts are read through ActCatalogue, not here.</summary>
[DefOf]
public static class BlaxLawsDefOf
{
public static PunishmentDef Warn;
public static PunishmentDef Guilty;
public static PunishmentDef Subdue;
public static PunishmentDef Jail;
public static PunishmentDef SubdueThenJail;
public static JobDef BlaxLaws_Subdue;
public static MainButtonDef BlaxLaws_Laws;
static BlaxLawsDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(BlaxLawsDefOf));
}
}
}

View File

@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>Who enforces laws (setting "Enforcers").</summary>
public enum EnforcerMode
{
/// <summary>Wardens (Warden work active) first, then anyone able.</summary>
WardensFirst,
/// <summary>Only wardens; without one the case waits.</summary>
WardensOnly,
}
/// <summary>
/// Global settings (design: "Lawbook tab", settings page). The lawbook itself is per save and lives in
/// GameComponent_BlaxLaws, never here.
/// </summary>
public class BlaxLawsSettings : ModSettings
{
/// <summary>Wardens carry out punishments. Off: cases open and close, nothing is carried out.</summary>
public bool enforceLaws = true;
/// <summary>The Laws button shows in the bottom bar. Written live into MainButtonDef.buttonVisible.</summary>
public bool showLawsTab = true;
/// <summary>A message for every case (CaseMessages).</summary>
public bool caseMessages = true;
/// <summary>Letters when a colonist is jailed or the player has to act.</summary>
public bool jailLetters = true;
/// <summary>Who enforces.</summary>
public EnforcerMode enforcers = EnforcerMode.WardensFirst;
/// <summary>A subdued pawn loses the catharsis that ending its break gives.</summary>
public bool subdueRemovesCatharsis = true;
/// <summary>An act done while drafted or on a player-forced job opens no case.</summary>
public bool playerOrdersExempt = true;
/// <summary>Days between cases of one offender under one law for acts outside a break (0 to 7).</summary>
public int cooldownDays = DefaultCooldownDays;
/// <summary>Closed cases older than this are pruned on save (7 to 360).</summary>
public int keepClosedDays = DefaultKeepClosedDays;
public const int DefaultCooldownDays = 1;
public const int MinCooldownDays = 0;
public const int MaxCooldownDays = 7;
public const int DefaultKeepClosedDays = 60;
public const int MinKeepClosedDays = 7;
public const int MaxKeepClosedDays = 360;
public int CooldownDaysClamped => Mathf.Clamp(cooldownDays, MinCooldownDays, MaxCooldownDays);
public int KeepClosedDaysClamped => Mathf.Clamp(keepClosedDays, MinKeepClosedDays, MaxKeepClosedDays);
/// <summary>The cooldown window in ticks; 0 files every act.</summary>
public int CooldownTicks => CooldownDaysClamped * GenDate.TicksPerDay;
public int KeepClosedTicks => KeepClosedDaysClamped * GenDate.TicksPerDay;
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref enforceLaws, "enforceLaws", true);
Scribe_Values.Look(ref showLawsTab, "showLawsTab", true);
Scribe_Values.Look(ref caseMessages, "caseMessages", true);
Scribe_Values.Look(ref jailLetters, "jailLetters", true);
Scribe_Values.Look(ref enforcers, "enforcers", EnforcerMode.WardensFirst);
Scribe_Values.Look(ref subdueRemovesCatharsis, "subdueRemovesCatharsis", true);
Scribe_Values.Look(ref playerOrdersExempt, "playerOrdersExempt", true);
Scribe_Values.Look(ref cooldownDays, "cooldownDays", DefaultCooldownDays);
Scribe_Values.Look(ref keepClosedDays, "keepClosedDays", DefaultKeepClosedDays);
if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.PostLoadInit)
{
cooldownDays = CooldownDaysClamped;
keepClosedDays = KeepClosedDaysClamped;
}
}
public void Reset()
{
var d = new BlaxLawsSettings();
enforceLaws = d.enforceLaws;
showLawsTab = d.showLawsTab;
caseMessages = d.caseMessages;
jailLetters = d.jailLetters;
enforcers = d.enforcers;
subdueRemovesCatharsis = d.subdueRemovesCatharsis;
playerOrdersExempt = d.playerOrdersExempt;
cooldownDays = d.cooldownDays;
keepClosedDays = d.keepClosedDays;
}
}
public class BlaxLawsMod : Mod
{
public static BlaxLawsSettings Settings;
/// <summary>The settings, or defaults before the mod class exists, so nothing reads null while loading.</summary>
public static BlaxLawsSettings S => Settings ?? (fallback ??= new BlaxLawsSettings());
private static BlaxLawsSettings fallback;
public BlaxLawsMod(ModContentPack content) : base(content)
{
Settings = GetSettings<BlaxLawsSettings>();
}
public override string SettingsCategory() => "Blax Laws";
/// <summary>
/// Writes "Show Laws tab" into the button def. The bottom bar counts buttonVisible for its width
/// (MainButtonsRoot.cs:15-27), so the change shows at once. Never throws.
/// </summary>
public static void ApplyTabVisibility()
{
try
{
MainButtonDef def = BlaxLawsDefOf.BlaxLaws_Laws ?? DefDatabase<MainButtonDef>.GetNamedSilentFail("BlaxLaws_Laws");
if (def != null)
def.buttonVisible = S.showLawsTab;
}
catch (Exception e)
{
LawsLog.Once("Show Laws tab", e);
}
}
public override void DoSettingsWindowContents(Rect inRect)
{
BlaxLawsSettings s = Settings;
var l = new Listing_Standard();
l.maxOneColumn = true;
l.Begin(inRect);
l.CheckboxLabeled("BlaxLaws_SettingEnforceLaws".Translate(), ref s.enforceLaws, "BlaxLaws_SettingEnforceLawsTip".Translate());
bool tab = s.showLawsTab;
l.CheckboxLabeled("BlaxLaws_SettingShowTab".Translate(), ref s.showLawsTab, "BlaxLaws_SettingShowTabTip".Translate());
if (tab != s.showLawsTab)
ApplyTabVisibility();
l.CheckboxLabeled("BlaxLaws_SettingCaseMessages".Translate(), ref s.caseMessages, "BlaxLaws_SettingCaseMessagesTip".Translate());
l.CheckboxLabeled("BlaxLaws_SettingJailLetters".Translate(), ref s.jailLetters, "BlaxLaws_SettingJailLettersTip".Translate());
l.GapLine();
l.Label("BlaxLaws_SettingEnforcers".Translate());
if (l.RadioButton("BlaxLaws_EnforcersWardensFirst".Translate(), s.enforcers == EnforcerMode.WardensFirst, 12f, "BlaxLaws_EnforcersWardensFirstTip".Translate()))
s.enforcers = EnforcerMode.WardensFirst;
if (l.RadioButton("BlaxLaws_EnforcersWardensOnly".Translate(), s.enforcers == EnforcerMode.WardensOnly, 12f, "BlaxLaws_EnforcersWardensOnlyTip".Translate()))
s.enforcers = EnforcerMode.WardensOnly;
l.CheckboxLabeled("BlaxLaws_SettingSubdueCatharsis".Translate(), ref s.subdueRemovesCatharsis, "BlaxLaws_SettingSubdueCatharsisTip".Translate());
l.CheckboxLabeled("BlaxLaws_SettingPlayerOrdersExempt".Translate(), ref s.playerOrdersExempt, "BlaxLaws_SettingPlayerOrdersExemptTip".Translate());
l.GapLine();
s.cooldownDays = Mathf.RoundToInt(l.SliderLabeled("BlaxLaws_SettingCooldownDays".Translate(s.CooldownDaysClamped),
s.CooldownDaysClamped, BlaxLawsSettings.MinCooldownDays, BlaxLawsSettings.MaxCooldownDays, 0.6f,
"BlaxLaws_SettingCooldownDaysTip".Translate()));
s.cooldownDays = s.CooldownDaysClamped;
s.keepClosedDays = Mathf.RoundToInt(l.SliderLabeled("BlaxLaws_SettingKeepClosedDays".Translate(s.KeepClosedDaysClamped),
s.KeepClosedDaysClamped, BlaxLawsSettings.MinKeepClosedDays, BlaxLawsSettings.MaxKeepClosedDays, 0.6f,
"BlaxLaws_SettingKeepClosedDaysTip".Translate()));
s.keepClosedDays = s.KeepClosedDaysClamped;
l.Gap();
if (l.ButtonText("BlaxLaws_SettingsReset".Translate()))
{
s.Reset();
ApplyTabVisibility();
}
l.End();
}
}
/// <summary>
/// Applies the Harmony patches after every Mod class exists (so the Harmony mod has set up its 1.7
/// backend), one class at a time so a single broken target can't take the rest down, and logs
/// "[Blax Laws] N patches applied". A patch class is any class in this assembly with [HarmonyPatch].
/// </summary>
[StaticConstructorOnStartup]
public static class BlaxLawsStartup
{
public const string HarmonyId = "blax.laws";
public static readonly Harmony Harmony = new Harmony(HarmonyId);
/// <summary>Patch classes that failed to apply, by type name. Read by the smoke test.</summary>
public static readonly List<string> FailedPatches = new List<string>();
/// <summary>Patch classes applied at startup.</summary>
public static int Applied { get; private set; }
static BlaxLawsStartup()
{
int ok = 0;
foreach (Type type in typeof(BlaxLawsStartup).Assembly.GetTypes())
{
if (!type.IsDefined(typeof(HarmonyPatch), false))
continue;
try
{
Harmony.CreateClassProcessor(type).Patch();
ok++;
}
catch (Exception e)
{
FailedPatches.Add(type.Name);
Log.Error("[Blax Laws] Patch " + type.Name + " failed: " + e);
}
}
Applied = ok;
Log.Message("[Blax Laws] " + ok + " patches applied" + (FailedPatches.Count > 0 ? ", " + FailedPatches.Count + " failed" : ""));
BlaxLawsMod.ApplyTabVisibility();
}
}
}

View File

@ -0,0 +1,199 @@
using System;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// Turns an act into a case (design: "Act catalogue and detection", How, and "Defaults I picked"). The one
/// entry point every detection hook calls; it never punishes, it queues: Enforcement starts the
/// punishment a tick later.
///
/// - A break's start (category Break) opens a planning case when a planning row matches.
/// - An act that is the linked did-it of the offender's current break belongs to that break's case and
/// opens no other case. When the act also matches a row of its own category, the row with the higher
/// severity decides, the break's row on a tie. Each stage's punishment fires once per case; later acts
/// raise the count.
/// - Any other act: the most specific enabled row of its category decides. Within the cooldown
/// ("Days between cases") a further act of the same offender under the same row raises the count on
/// that case, open or closed, and files nothing new.
/// </summary>
public static class CaseFiler
{
/// <summary>
/// Files the act. Returns the case that took it (new or existing), or null when no row covers it, the
/// offender isn't covered, or the act is a player order. Safe to call from any hook; the hook still
/// wraps the call in its own try/catch.
/// </summary>
public static LawCase Report(ActEvent act)
{
if (LawsTestHooks.ReportThrows)
throw new InvalidOperationException("test: CaseFiler.Report throws");
if (act?.offender == null || act.categoryId == null || !Watch.Any)
return null;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || !Offenders.CountsAsOffender(act.offender))
return null;
if (act.categoryId == ActCategories.Break)
return ReportBreakStart(comp, act);
Law own = Lawbook.BestRow(act, LawStage.DidIt);
LawCase linked = ReportLinkedAct(comp, act, own);
if (linked != null)
return linked;
return own == null ? null : ReportAct(comp, act, own);
}
/// <summary>
/// Opens a case for a row, at a stage, without matching: for hooks that already know the row (a later
/// stage of a special flow) and for tests. Sets the stage's row, count, notes and ticks; queues nothing.
/// </summary>
public static LawCase Open(Law law, ActEvent act, LawStage stage)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null || act?.offender == null)
return null;
int now = Now;
var c = new LawCase
{
id = comp.TakeCaseId(),
actKey = law.actKey,
matchedDef = act.def?.defName,
stage = stage,
count = stage == LawStage.DidIt ? 1 : 0,
notes = act.notes,
openTick = now,
lastActTick = now,
status = CaseStatus.Open,
};
c.SetOffender(act.offender);
c.SetVictim(act.victim);
c.SetLaw(stage, law);
comp.AddCase(c);
return c;
}
/// <summary>The tick the pawn's break started, to within 30 ticks: now minus MentalState.Age.</summary>
public static int BreakStartTick(MentalState state) => state == null ? Now : Now - state.Age;
/// <summary>Whether the case's break is still running on its offender.</summary>
public static bool StillInBreak(LawCase c)
{
if (c == null || !c.IsBreakCase || c.offender == null || c.offender.Dead)
return false;
MentalState state = c.offender.MentalState;
return state?.def != null && state.def.defName == c.breakState &&
Math.Abs(BreakStartTick(state) - c.breakStartTick) <= GameComponent_BlaxLaws.BreakStartTolerance;
}
private static int Now => Find.TickManager?.TicksGame ?? 0;
// ---- the three paths -----------------------------------------------------------------
private static LawCase ReportBreakStart(GameComponent_BlaxLaws comp, ActEvent act)
{
if (!(act.def is MentalStateDef state))
return null;
Law row = Lawbook.BestRow(act, LawStage.Planning);
if (row == null)
return null;
MentalState live = act.mentalState ?? act.offender.MentalState;
int start = BreakStartTick(live);
LawCase c = comp.BreakCaseOf(act.offender, state.defName, start);
if (c != null)
return c;
c = Open(row, act, LawStage.Planning);
c.breakState = state.defName;
c.breakStartTick = start;
Enforcement.Enqueue(c, LawStage.Planning);
return c;
}
private static LawCase ReportLinkedAct(GameComponent_BlaxLaws comp, ActEvent act, Law own)
{
MentalState state = act.offender.MentalState;
if (state?.def == null)
return null;
BreakLinkDef link = BreakLinks.For(state.def);
if (link == null || !BreakLinks.Matches(link, act))
return null;
var breakAct = new ActEvent(ActCategories.Break, state.def, act.offender)
{
victim = act.victim,
thing = act.thing,
chemical = act.chemical,
drugCategory = act.drugCategory,
facts = act.facts,
notes = act.notes,
mentalState = state,
};
Law breakRow = Lawbook.BestRow(breakAct, LawStage.DidIt);
int start = BreakStartTick(state);
LawCase c = comp.BreakCaseOf(act.offender, state.def.defName, start);
if (c == null && breakRow == null)
return null; // No law on this break: the act files as any other act.
int now = Now;
if (c == null)
{
c = Open(breakRow, breakAct, LawStage.DidIt);
c.breakState = state.def.defName;
c.breakStartTick = start;
c.count = 0;
}
c.count++;
c.lastActTick = now;
c.notes |= act.notes;
c.matchedDef = act.def?.defName;
if (c.stage == LawStage.Planning)
c.stage = LawStage.DidIt;
if (c.victim == null && act.victim != null)
c.SetVictim(act.victim);
if (c.didItLawId < 0 && !c.HasPunished(LawStage.DidIt))
{
Law decider = breakRow;
if (own != null && (decider == null || own.severity > decider.severity))
decider = own;
if (decider != null)
{
c.SetLaw(LawStage.DidIt, decider);
if (c.IsClosed)
{
// A planning case already closed (warned) while the break goes on: the did-it reopens it.
c.status = CaseStatus.Open;
c.outcome = null;
c.closeTick = -1;
}
Enforcement.Enqueue(c, LawStage.DidIt);
}
}
return c;
}
private static LawCase ReportAct(GameComponent_BlaxLaws comp, ActEvent act, Law own)
{
int now = Now;
int window = BlaxLawsMod.S.CooldownTicks;
if (window > 0)
{
LawCase recent = comp.LatestActCaseOf(act.offender, own.id);
// An unresolved case takes every repeat, whatever its age (a held or waiting jail case gets no
// second case and no second letter). After it closes the window counts from its open tick, so
// frequent repeats can't push it out forever.
if (recent != null && (!recent.IsClosed || now - recent.openTick < window))
{
recent.count++;
recent.lastActTick = now;
recent.notes |= act.notes;
return recent;
}
}
LawCase c = Open(own, act, LawStage.DidIt);
Enforcement.Enqueue(c, LawStage.DidIt);
return c;
}
}
}

View File

@ -0,0 +1,266 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Base class of the category workers (ActCategoryDef.workerClass). A worker walks its DefDatabase once
/// and returns the category's entries: one ActEntry.ForDef per def and one ActEntry.ForGroup per group,
/// groups in the order the picker shows them. It never reads the lawbook and keeps no state of a game.
/// </summary>
public class ActCategoryWorker
{
public ActCategoryDef def;
/// <summary>Every entry of the category, def and group entries both. Default: none.</summary>
public virtual IEnumerable<ActEntry> MakeEntries()
{
yield break;
}
/// <summary>The category's tooltip in the picker. Default: the def's description.</summary>
public virtual string Tooltip => def?.description;
}
/// <summary>
/// The act catalogue: every entry the loaded game has, by category (design: "The act catalogue is built
/// from the game's defs, saved as names"). Built once, on first use or at the first game start, from the
/// ActCategoryDefs' workers; never saved. The picker searches it; nothing else walks it. Lookups by key
/// are a dictionary read.
/// </summary>
public static class ActCatalogue
{
private static bool built;
private static bool building;
private static readonly List<ActEntry> all = new List<ActEntry>();
private static readonly Dictionary<string, ActEntry> byKey = new Dictionary<string, ActEntry>();
private static readonly Dictionary<string, List<ActEntry>> byCategory = new Dictionary<string, List<ActEntry>>();
private static readonly List<ActCategoryDef> categories = new List<ActCategoryDef>();
private static readonly List<string> chemicalOptions = new List<string>();
private static readonly List<ActEntry> Empty = new List<ActEntry>();
/// <summary>Bumped on every build, for caches keyed on the catalogue.</summary>
public static int Version { get; private set; }
public static bool Built => built;
/// <summary>Every entry, category by category in picker order.</summary>
public static IReadOnlyList<ActEntry> All
{
get
{
EnsureBuilt();
return all;
}
}
/// <summary>The categories in picker order.</summary>
public static IReadOnlyList<ActCategoryDef> Categories
{
get
{
EnsureBuilt();
return categories;
}
}
/// <summary>A category's entries: groups first, in the worker's order, then every def A to Z.</summary>
public static IReadOnlyList<ActEntry> EntriesOf(string categoryId)
{
EnsureBuilt();
return categoryId != null && byCategory.TryGetValue(categoryId, out List<ActEntry> list) ? list : Empty;
}
/// <summary>The entry for a key, or null when it is missing (a DLC or mod that isn't loaded, a typo).</summary>
public static ActEntry Get(string key)
{
if (key == null)
return null;
EnsureBuilt();
byKey.TryGetValue(key, out ActEntry e);
return e;
}
public static bool TryGet(string key, out ActEntry entry)
{
entry = Get(key);
return entry != null;
}
/// <summary>The single-def entry of a def in a category, or null.</summary>
public static ActEntry EntryFor(string categoryId, Def def) => def == null ? null : Get(ActKey.Of(categoryId, def.defName));
/// <summary>The group behind a group key, or null.</summary>
public static ActGroup GroupOf(string key) => Get(key)?.group;
/// <summary>
/// Drug options after Any, Hard and Social: the defName of every ChemicalDef a drug's
/// CompProperties_Drug names, A to Z by label. No other chemical is listed.
/// </summary>
public static IReadOnlyList<string> ChemicalOptions
{
get
{
EnsureBuilt();
return chemicalOptions;
}
}
public static void EnsureBuilt()
{
if (!built && !building)
Build();
}
/// <summary>Builds the catalogue from the loaded defs. A worker that throws logs once and leaves its category empty.</summary>
public static void Build()
{
building = true;
try
{
all.Clear();
byKey.Clear();
byCategory.Clear();
categories.Clear();
chemicalOptions.Clear();
BreakLinks.ClearCache();
categories.AddRange(DefDatabase<ActCategoryDef>.AllDefsListForReading.OrderBy(c => c.order).ThenBy(c => c.defName));
foreach (ActCategoryDef cat in categories)
{
var list = new List<ActEntry>();
try
{
foreach (ActEntry e in cat.Worker.MakeEntries() ?? Enumerable.Empty<ActEntry>())
{
if (e == null || e.key.NullOrEmpty())
continue;
if (e.categoryId != cat.defName)
{
LawsLog.WarningOnce("catalogue-category:" + e.key, "Catalogue entry " + e.key + " came from category " + cat.defName + "; skipped.");
continue;
}
if (byKey.ContainsKey(e.key))
continue;
byKey[e.key] = e;
list.Add(e);
}
}
catch (Exception ex)
{
LawsLog.Once("Catalogue category " + cat.defName, ex);
}
Finish(cat, list);
byCategory[cat.defName] = list;
all.AddRange(list);
}
BuildChemicalOptions();
Version++;
built = true;
}
finally
{
building = false;
}
}
/// <summary>Drops the catalogue; the next read builds it again. Tests only.</summary>
public static void Reset()
{
built = false;
all.Clear();
byKey.Clear();
byCategory.Clear();
categories.Clear();
chemicalOptions.Clear();
}
/// <summary>Group sizes, the stage and break fields, and the picker order: groups first, defs A to Z.</summary>
private static void Finish(ActCategoryDef cat, List<ActEntry> list)
{
List<ActEntry> defs = list.Where(e => e.def != null).ToList();
foreach (ActEntry g in list)
{
if (g.group == null)
continue;
g.group.size = g.group.IsAny ? defs.Count : defs.Count(d => SafeMatches(g.group, d.def));
}
bool breaks = cat.defName == ActCategories.Break;
foreach (ActEntry e in list)
{
if (!breaks)
{
e.hasPlanning = false;
e.hasDidIt = true;
continue;
}
e.hasPlanning = true;
e.links.Clear();
if (e.def is MentalStateDef state)
{
BreakLinkDef link = BreakLinks.For(state);
if (link != null)
e.links.Add(link);
e.hostileBreak = BreakLinks.IsHostile(state);
}
else if (e.group != null)
{
bool anyMember = false, allHostile = true;
foreach (ActEntry d in defs)
{
if (!(d.def is MentalStateDef s) || !(e.group.IsAny || SafeMatches(e.group, s)))
continue;
anyMember = true;
if (!BreakLinks.IsHostile(s))
allHostile = false;
BreakLinkDef link = BreakLinks.For(s);
if (link != null && !e.links.Contains(link))
e.links.Add(link);
}
e.hostileBreak = anyMember && allHostile;
}
e.hasDidIt = e.links.Count > 0;
e.hasDrugOption = e.links.Any(l => l.usesDrugOption);
}
List<ActEntry> ordered = list.Where(e => e.group != null)
.Concat(list.Where(e => e.group == null).OrderBy(e => e.label, StringComparer.CurrentCultureIgnoreCase).ThenBy(e => e.key))
.ToList();
list.Clear();
list.AddRange(ordered);
}
private static bool SafeMatches(ActGroup g, Def def)
{
try
{
return g.MatchesDef(def);
}
catch (Exception ex)
{
LawsLog.Once("Catalogue group " + g.Key, ex);
return false;
}
}
private static void BuildChemicalOptions()
{
var chems = new HashSet<ChemicalDef>();
foreach (ThingDef t in DefDatabase<ThingDef>.AllDefsListForReading)
{
if (t.comps == null)
continue;
foreach (CompProperties c in t.comps)
{
if (c is CompProperties_Drug drug && drug.chemical != null)
chems.Add(drug.chemical);
}
}
chemicalOptions.AddRange(chems.OrderBy(c => c.label ?? c.defName, StringComparer.CurrentCultureIgnoreCase).Select(c => c.defName));
}
}
}

View File

@ -0,0 +1,119 @@
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// One entry of the act catalogue: a single def or a group. Built once per game start by ActCatalogue
/// from the category workers; never saved (rows save the key). The worker fills key, category, def or
/// group, label and source; ActCatalogue.Build fills the stage and break fields from the link table.
/// </summary>
public class ActEntry
{
/// <summary>"Ate/WakeUp" or "Ate/@hardDrugs".</summary>
public string key;
public string categoryId;
/// <summary>The def's defName, or the group id with its "@".</summary>
public string name;
/// <summary>The def of a single entry; null for a group.</summary>
public Def def;
/// <summary>The group of a group entry; null for a single def.</summary>
public ActGroup group;
/// <summary>What the picker and the row show.</summary>
public string label;
/// <summary>"Core", the DLC's name or the mod's name.</summary>
public string sourceMod;
/// <summary>The source's package id, lower case.</summary>
public string sourcePackageId;
/// <summary>Break entries: a planning stage (always, for a break).</summary>
public bool hasPlanning;
/// <summary>A did-it stage: every entry outside the breaks, and a break with a link.</summary>
public bool hasDidIt = true;
/// <summary>A break hostile to the colony (berserk): no Subdue. For a group: every member is hostile.</summary>
public bool hostileBreak;
/// <summary>A drug binge entry: rows keep a drug option.</summary>
public bool hasDrugOption;
/// <summary>Break entries: the links of the entry's breaks (one for a def, the distinct links of its members for a group).</summary>
public List<BreakLinkDef> links = new List<BreakLinkDef>();
public bool IsGroup => group != null;
public bool IsBreak => categoryId == ActCategories.Break;
/// <summary>Rank for "the most specific row wins": a single def 3, a group 2, the category's "any" 1.</summary>
public int Rank => def != null ? 3 : group != null && !group.IsAny ? 2 : 1;
/// <summary>The stages the entry offers, planning first.</summary>
public IEnumerable<LawStage> Stages
{
get
{
if (hasPlanning)
yield return LawStage.Planning;
if (hasDidIt)
yield return LawStage.DidIt;
}
}
public bool HasStage(LawStage stage) => stage == LawStage.Planning ? hasPlanning : hasDidIt;
/// <summary>The stage a new row gets.</summary>
public LawStage FirstStage => hasPlanning ? LawStage.Planning : LawStage.DidIt;
/// <summary>Whether the act is this entry's: the same def, or a member of the group.</summary>
public bool Matches(ActEvent act)
{
if (act == null || act.categoryId != categoryId)
return false;
if (group != null)
return group.Matches(act);
return act.def != null && (act.def == def || act.def.defName == name);
}
// ---- builders for the category workers -------------------------------------------------
/// <summary>A single-def entry with the def's label and source mod.</summary>
public static ActEntry ForDef(string categoryId, Def def, string label = null)
{
return new ActEntry
{
key = ActKey.Of(categoryId, def.defName),
categoryId = categoryId,
name = def.defName,
def = def,
label = !label.NullOrEmpty() ? label : !def.label.NullOrEmpty() ? def.LabelCap.ToString() : def.defName,
sourceMod = DlcSupport.SourceName(def.modContentPack),
sourcePackageId = DlcSupport.SourcePackageId(def.modContentPack),
};
}
/// <summary>A group entry. Groups are Laws' own, so their source is Core.</summary>
public static ActEntry ForGroup(ActGroup group, string label = null)
{
return new ActEntry
{
key = group.Key,
categoryId = group.categoryId,
name = group.id,
group = group,
label = label.NullOrEmpty() ? group.Label : label,
sourceMod = DlcSupport.CoreName,
sourcePackageId = DlcSupport.CorePackageId,
};
}
public override string ToString() => key + " (" + label + ", " + sourceMod + ")";
}
}

View File

@ -0,0 +1,79 @@
using System;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// A group entry of a category ("Any drug binge", "Hard drugs", "Human meat", "Any surgery"). Groups are
/// predicates over defs, written once in code by the catalogue package; Watch expands a def-level group
/// into the set of defs it covers when the lawbook changes. A group that depends on the thing rather
/// than its def (a meal with human meat in it) sets DependsOnThing and overrides Matches(ActEvent); its
/// check then runs on every act of the category while the category is watched.
/// </summary>
public abstract class ActGroup
{
/// <summary>The category id.</summary>
public string categoryId;
/// <summary>The group id with its "@" (ActGroups), unique within the category.</summary>
public string id;
/// <summary>The Keyed key of the label ("BlaxLaws_Group_hardDrugs").</summary>
public string labelKey;
/// <summary>
/// Def entries of the category this group covers, set by ActCatalogue.Build. "The smaller group wins"
/// when two groups match one act.
/// </summary>
public int size;
public string Key => ActKey.OfGroup(categoryId, id);
/// <summary>The category's "any": every entry. The least specific row.</summary>
public bool IsAny => id == ActGroups.Any;
/// <summary>The check needs the thing itself (ActEvent.facts or thing), not only the def.</summary>
public virtual bool DependsOnThing => false;
public virtual string Label => labelKey.NullOrEmpty() ? id : labelKey.Translate().ToString();
/// <summary>
/// Whether a def of the category belongs to the group. For a DependsOnThing group: whether a thing of
/// this def could (a meal could hold meat); the act check decides.
/// </summary>
public abstract bool MatchesDef(Def def);
/// <summary>Whether the act belongs to the group. Default: its def does.</summary>
public virtual bool Matches(ActEvent act) => IsAny || (act?.def != null && MatchesDef(act.def));
}
/// <summary>A group from two predicates, for the catalogue package's group lists.</summary>
public sealed class PredicateGroup : ActGroup
{
private readonly Func<Def, bool> defPredicate;
private readonly Func<ActEvent, bool> actPredicate;
/// <param name="actPredicate">Null for a def-level group; set for a group that reads the thing.</param>
public PredicateGroup(string categoryId, string id, string labelKey, Func<Def, bool> defPredicate, Func<ActEvent, bool> actPredicate = null)
{
this.categoryId = categoryId;
this.id = id.StartsWith(ActKey.GroupPrefix) ? id : ActKey.GroupPrefix + id;
this.labelKey = labelKey;
this.defPredicate = defPredicate ?? (_ => true);
this.actPredicate = actPredicate;
}
public override bool DependsOnThing => actPredicate != null;
public override bool MatchesDef(Def def) => def != null && defPredicate(def);
public override bool Matches(ActEvent act)
{
if (IsAny)
return true;
if (act == null)
return false;
return actPredicate != null ? actPredicate(act) : act.def != null && defPredicate(act.def);
}
}
}

View File

@ -0,0 +1,18 @@
using RimWorld;
namespace BlaxLaws
{
/// <summary>The special acts of the first release (Defs/BlaxLaws_Acts.xml), for the hooks that file them.</summary>
[DefOf]
public static class BlaxLawsActDefOf
{
public static ActDef SetFire;
public static ActDef DisplayedCorpse;
public static ActDef StartedSocialFight;
static BlaxLawsActDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(BlaxLawsActDefOf));
}
}
}

View File

@ -0,0 +1,230 @@
using System;
using System.Collections.Generic;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// A category of the act catalogue (Defs/BlaxLaws_Categories.xml). The defName is the category id, the
/// first part of every act key, so it never changes. The worker reads the loaded defs once and returns
/// the category's entries.
/// </summary>
public class ActCategoryDef : Def
{
public Type workerClass = typeof(ActCategoryWorker);
/// <summary>Picker order; lower first.</summary>
public int order;
/// <summary>Def names the worker adds beyond its rule (Berserk for the breaks).</summary>
public List<string> include = new List<string>();
/// <summary>Def names the worker leaves out (animal and baby states, faction-level events).</summary>
public List<string> exclude = new List<string>();
/// <summary>
/// Break category only: mental state classes hostile to the colony, subclasses included (berserk). Their
/// entries never offer Subdue. Enforcement re-checks ForceHostileTo(Faction.OfPlayer) on the live
/// state, which wins over this list.
/// </summary>
public List<Type> hostileStateClasses = new List<Type>();
[Unsaved]
private ActCategoryWorker workerInt;
public ActCategoryWorker Worker
{
get
{
if (workerInt == null)
{
workerInt = (ActCategoryWorker)Activator.CreateInstance(workerClass ?? typeof(ActCategoryWorker));
workerInt.def = this;
}
return workerInt;
}
}
public bool Includes(string defName) => include != null && include.Contains(defName);
public bool Excludes(string defName) => exclude != null && exclude.Contains(defName);
public override IEnumerable<string> ConfigErrors()
{
foreach (string e in base.ConfigErrors())
yield return e;
if (workerClass == null || !typeof(ActCategoryWorker).IsAssignableFrom(workerClass))
yield return "workerClass must be an ActCategoryWorker";
if (defName.IndexOf(ActKey.Separator) >= 0)
yield return "defName must not contain '" + ActKey.Separator + "': it is the first part of an act key";
}
}
/// <summary>
/// A special act with its own hook (Defs/BlaxLaws_Acts.xml): SetFire, DisplayedCorpse, StartedSocialFight in
/// the first release. The defName is the act's id in "Special/&lt;defName&gt;", so it never changes. Its
/// hook files it with an ActEvent whose def is this ActDef.
/// </summary>
public class ActDef : Def
{
public Type workerClass = typeof(ActWorker);
/// <summary>Picker order inside "Special acts"; lower first, then A to Z.</summary>
public int order;
[Unsaved]
private ActWorker workerInt;
public ActWorker Worker
{
get
{
if (workerInt == null)
{
workerInt = (ActWorker)Activator.CreateInstance(workerClass ?? typeof(ActWorker));
workerInt.def = this;
}
return workerInt;
}
}
public string Key => ActKey.Of(ActCategories.Special, defName);
}
/// <summary>
/// Behaviour of one special act beyond its hook. The first release needs none; the hook files the act.
/// Later acts (the violent ones, the uprisings) override what they need.
/// </summary>
public class ActWorker
{
public ActDef def;
/// <summary>The tooltip the lawbook row shows, saying who counts as the offender. Default: the def's description.</summary>
public virtual string RowTooltip => def?.description;
}
/// <summary>
/// A break's "Did it" (Defs/BlaxLaws_BreakLinks.xml): the act that counts, for a mental state class and its
/// subclasses. Another mod links its own break class with one of these and no code.
/// </summary>
public class BreakLinkDef : Def
{
/// <summary>The mental state class, subclasses included.</summary>
public Type stateClass;
/// <summary>The linked act's key in another category: a single def ("Special/SetFire") or a group ("Ate/@anyDrug").</summary>
public string act;
/// <summary>The row's drug option filters the act (drug binges).</summary>
public bool usesDrugOption;
public override IEnumerable<string> ConfigErrors()
{
foreach (string e in base.ConfigErrors())
yield return e;
if (stateClass == null || !typeof(MentalState).IsAssignableFrom(stateClass))
yield return "stateClass must be a MentalState class";
if (ActKey.CategoryOf(act) == null || ActKey.NameOf(act) == null)
yield return "act must be an act key such as Special/SetFire";
if (ActKey.CategoryOf(act) == ActCategories.Break)
yield return "act must name an act outside the breaks";
}
}
/// <summary>Resolves the link of a mental state: the most derived linked class wins.</summary>
public static class BreakLinks
{
private static readonly Dictionary<Type, BreakLinkDef> byClass = new Dictionary<Type, BreakLinkDef>();
private static readonly Dictionary<Type, bool> hostileByClass = new Dictionary<Type, bool>();
/// <summary>The link for a break, or null when its class has none (Planning only).</summary>
public static BreakLinkDef For(MentalStateDef state) => For(state?.stateClass);
public static BreakLinkDef For(Type stateClass)
{
if (stateClass == null)
return null;
lock (byClass)
{
if (byClass.TryGetValue(stateClass, out BreakLinkDef cachedLink))
return cachedLink;
}
BreakLinkDef best = null;
int bestDepth = -1;
foreach (BreakLinkDef link in DefDatabase<BreakLinkDef>.AllDefsListForReading)
{
if (link.stateClass == null || !link.stateClass.IsAssignableFrom(stateClass))
continue;
int depth = Depth(link.stateClass);
if (depth > bestDepth)
{
best = link;
bestDepth = depth;
}
}
lock (byClass) byClass[stateClass] = best;
return best;
}
/// <summary>
/// Whether the act is the link's act: same category and the link's def, or a member of the link's
/// group. The drug option is not checked here (Lawbook.BestRow checks it on the break row).
/// </summary>
public static bool Matches(BreakLinkDef link, ActEvent act)
{
if (link == null || act == null || act.def == null)
return false;
if (ActKey.CategoryOf(link.act) != act.categoryId)
return false;
string name = ActKey.NameOf(link.act);
if (!ActKey.IsGroup(link.act))
return name == act.def.defName;
ActGroup group = ActCatalogue.GroupOf(link.act);
return group != null && group.Matches(act);
}
/// <summary>A state hostile to the colony by its class (berserk), from the Break category's hostileStateClasses.</summary>
public static bool IsHostile(MentalStateDef state)
{
Type cls = state?.stateClass;
if (cls == null)
return false;
lock (hostileByClass)
{
if (hostileByClass.TryGetValue(cls, out bool h))
return h;
}
bool hostile = false;
ActCategoryDef breaks = DefDatabase<ActCategoryDef>.GetNamedSilentFail(ActCategories.Break);
if (breaks?.hostileStateClasses != null)
{
foreach (Type t in breaks.hostileStateClasses)
{
if (t != null && t.IsAssignableFrom(cls))
{
hostile = true;
break;
}
}
}
lock (hostileByClass) hostileByClass[cls] = hostile;
return hostile;
}
/// <summary>Drops the caches (tests that add a link at runtime).</summary>
public static void ClearCache()
{
lock (byClass) byClass.Clear();
lock (hostileByClass) hostileByClass.Clear();
}
private static int Depth(Type t)
{
int d = 0;
for (Type x = t; x != null; x = x.BaseType)
d++;
return d;
}
}
}

View File

@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The group entries of each category, in picker order (design: "Act catalogue and detection", the Groups
/// column). Labels are Keyed "BlaxLaws_Group_&lt;id without @&gt;"; the "any" group of a category is
/// "BlaxLaws_Group_any&lt;Category&gt;", since one id serves several categories.
///
/// Def-level groups are expanded into Watch's set of watched defs. The meat groups that look into a meal's
/// ingredients read the thing (ActEvent.facts from hook C); their def check says which defs could match
/// (a meal could hold meat), which sets their size for "the smaller group wins".
/// </summary>
public static class CatalogueGroups
{
public static string LabelKey(string groupId) => "BlaxLaws_Group_" + (groupId.StartsWith(ActKey.GroupPrefix) ? groupId.Substring(1) : groupId);
public static string AnyLabelKey(string categoryId) => "BlaxLaws_Group_any" + categoryId;
/// <summary>Any break, any drug binge, any tantrum, any insulting spree, any aggressive break.</summary>
public static IEnumerable<ActGroup> Break(string cat)
{
yield return new CatalogueAnyGroup(cat, AnyLabelKey(cat));
yield return DefGroup(cat, ActGroups.AnyDrugBinge, d => StateIs(d, typeof(MentalState_BingingDrug)));
yield return DefGroup(cat, ActGroups.AnyTantrum, d => StateIs(d, typeof(MentalState_Tantrum)));
yield return DefGroup(cat, ActGroups.AnyInsultingSpree, d => StateIs(d, typeof(MentalState_InsultingSpree)));
yield return DefGroup(cat, ActGroups.AnyAggressive, d => d is MentalStateDef s && s.IsAggro);
}
/// <summary>
/// Anything eaten (the food binge's link), the drug groups by ingestible.drugCategory, the meat groups,
/// raw food by preferability and any meal by the Meal food type.
/// </summary>
public static IEnumerable<ActGroup> Ate(string cat)
{
yield return new CatalogueAnyGroup(cat, AnyLabelKey(cat));
yield return DefGroup(cat, ActGroups.AnyDrug, d => d is ThingDef t && t.IsDrug);
yield return DefGroup(cat, ActGroups.HardDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Hard);
yield return DefGroup(cat, ActGroups.SocialDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Social);
yield return DefGroup(cat, ActGroups.MedicalDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Medical);
yield return ThingGroup(cat, ActGroups.AnyMeat, ActFacts.Meat,
d => d is ThingDef t && (FoodUtility.GetFoodKind(t) == FoodKind.Meat || FoodFacts.HasIngredients(t)));
yield return DefGroup(cat, ActGroups.RawMeatOrCorpse, d => FoodFacts.IsRawMeatOrCorpse(d as ThingDef));
yield return ThingGroup(cat, ActGroups.HumanMeat, ActFacts.HumanMeat,
d => d is ThingDef t && (FoodFacts.SourceIsHumanlike(t) || FoodFacts.HasIngredients(t)));
yield return ThingGroup(cat, ActGroups.InsectMeat, ActFacts.InsectMeat,
d => d is ThingDef t && (FoodFacts.SourceIsInsect(t) || FoodFacts.HasIngredients(t)));
yield return DefGroup(cat, ActGroups.RawFood, d => FoodFacts.IsRawFood(d as ThingDef));
yield return DefGroup(cat, ActGroups.AnyMeal, d => FoodFacts.IsMeal(d as ThingDef));
}
/// <summary>Insult or slight: the two vanilla defs and any interaction whose worker is theirs or derives from it.</summary>
public static IEnumerable<ActGroup> Interaction(string cat)
{
yield return DefGroup(cat, ActGroups.InsultOrSlight, IsInsultOrSlight);
}
/// <summary>Any surgery (RecipeDef.IsSurgery, Verse/RecipeDef.cs:362).</summary>
public static IEnumerable<ActGroup> Bill(string cat)
{
yield return DefGroup(cat, ActGroups.AnySurgery, d => d is RecipeDef r && r.IsSurgery);
}
public static bool IsInsultOrSlight(Def d)
{
if (!(d is InteractionDef i))
return false;
if (i == InteractionDefOf.Insult || i.defName == "Slight")
return true;
// workerClass is private; the worker is made once per def anyway (RimWorld/InteractionDef.cs:45-55).
InteractionWorker w = i.Worker;
return w is InteractionWorker_Insult || w is InteractionWorker_Slight;
}
private static bool StateIs(Def d, Type stateClass) =>
d is MentalStateDef s && s.stateClass != null && stateClass.IsAssignableFrom(s.stateClass);
private static ActGroup DefGroup(string cat, string id, Func<Def, bool> pred) => new PredicateGroup(cat, id, LabelKey(id), pred);
private static ActGroup ThingGroup(string cat, string id, ActFacts fact, Func<Def, bool> could) =>
new PredicateGroup(cat, id, LabelKey(id), could, act => (FoodFacts.Of(act) & fact) != 0);
}
/// <summary>
/// A category's "any": every def entry of the category, and nothing the catalogue left out (an "any
/// break" row never catches a social fight or a manhunter state). Rank 1, the least specific row.
/// Membership is a set of the category's defs, rebuilt when the catalogue is.
/// </summary>
public sealed class CatalogueAnyGroup : ActGroup
{
private HashSet<Def> members;
private int membersVersion = -1;
public CatalogueAnyGroup(string categoryId, string labelKey)
{
this.categoryId = categoryId;
id = ActGroups.Any;
this.labelKey = labelKey;
}
public override bool MatchesDef(Def def)
{
if (def == null)
return false;
if (members == null || membersVersion != ActCatalogue.Version)
{
var set = new HashSet<Def>();
foreach (ActEntry e in ActCatalogue.EntriesOf(categoryId))
{
if (e.def != null)
set.Add(e.def);
}
members = set;
membersVersion = ActCatalogue.Version;
}
return members.Contains(def);
}
public override bool Matches(ActEvent act) => act?.def != null && (act.categoryId == null || act.categoryId == categoryId) && MatchesDef(act.def);
}
}

View File

@ -0,0 +1,210 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The rules the category workers apply to the loaded defs (design: "Act catalogue and detection", How),
/// and the built-in include and exclude lists. The lists of an ActCategoryDef in XML add to the built-in
/// ones, so another mod can name its own states or events with no code.
///
/// Checked against the 1.7 defs and decompiled code:
/// - Every MentalBreakDef names a colonist state (Core, Royalty, Ideology and Biotech
/// Defs/MentalStateDefs); animal, baby and mechanoid states come only from code (MentalStateDefOf.Manhunter,
/// Roaming, CocoonDisturbed, BerserkMechanoid; Biotech's baby fits). The exclude list guards against a
/// modded break naming one of them. Catatonic and RunWild name no state (MentalStates_Mood.xml), so no
/// hook ever sees them and they stay out.
/// - Time records never pass Increment or AddTo: they are added straight to the record map every 80 ticks
/// (RimWorld/Pawn_RecordsTracker.cs:60-70).
/// - Corpse defs carry an ingestible even for mechanoids (RimWorld/ThingDefGenerator_Corpses.cs:165-169), and
/// plants carry one for grazing animals; neither is anything a colonist eats.
/// </summary>
public static class CatalogueRules
{
/// <summary>
/// Break states colonists reach without a MentalBreakDef: berserk (pulsers, scaria, a refused arrest), the
/// trance berserk a pawn casts on itself, the warcall berserk, and states from hediffs. Hook A skips a state
/// another pawn's ability forced on the pawn (a psycast, Neuroquake), so those never file. A name that
/// isn't loaded (its DLC is off) is skipped.
/// </summary>
public static readonly string[] BreakInclude =
{
"Berserk", "BerserkPermanent", "BerserkWarcall", "BerserkTrance", "WanderConfused", "Wander_Psychotic_Short",
"CubeSculpting", "Terror",
};
/// <summary>
/// Animal, baby and mechanoid states, the panic flight of enemies (Verse.AI/MentalStateHandler.cs:207-214,
/// only for pawns outside the colony) and the social fight, which is the special act StartedSocialFight.
/// </summary>
public static readonly string[] BreakExclude =
{
"Manhunter", "ManhunterPermanent", "ManhunterBloodRain", "Roaming", "CocoonDisturbed", "BerserkMechanoid",
"Crying", "Giggling", "SocialFighting", "PanicFlee",
};
/// <summary>
/// Faction-level history events: goodwill, trade, quests, raids, charity and pollution reach a faction,
/// not a colonist (Core Defs/Goodwill, Ideology Precepts_Charity, Precepts_Raiders, Precepts_Relics,
/// Biotech HistoryEventDefs.xml).
/// </summary>
public static readonly string[] RecordedActExclude =
{
// Core Defs/Goodwill/GoodwillEvents_Diplomatic.xml
"GaveGift", "PeaceTalksBackfire", "PeaceTalksDisaster", "PeaceTalksSuccess", "PeaceTalksTriumph", "RequestedMilitaryAid",
"RequestedOrbitalTrader", "RequestedTrader", "Traded",
// GoodwillEvents_Misc.xml
"AttackedBuilding", "DebugGoodwill", "LaborersMissedShuttle", "ReachNaturalGoodwill", "RitualDone", "ShuttleDestroyed",
"UsedForbiddenThing", "UsedHarmfulAbility",
// GoodwillEvents_Pawns.xml
"AttackedMember", "FriendlyExitedMapTended", "GuiltyPrisonerDied", "InnocentPrisonerDied", "MemberCaptured", "MemberCrushed",
"MemberExitedMapHealthy", "MemberKilled", "MemberNeutrallyDied", "MemberSold", "MemberStripped", "PerformedHarmfulSurgery",
"PrisonerDied", "UsedHarmfulItem", "XenogermAbsorbed",
// GoodwillEvents_Quests.xml
"AcceptedDeserter", "FailedToKeepLodgersHappy", "MemberMissedShuttle", "MonumentConstructionExpired",
"MonumentConstructionMapRemoved", "MonumentDestroyed", "QuestGoodwillReward", "QuestPawnArrested", "QuestPawnLost",
"QuestPrisonerEnslaved", "QuestPrisonerRecruited", "ShuttleCommanderMissedShuttle", "ShuttleGuardsMissedShuttle",
// GoodwillEvents_World.xml
"AttackedCaravan", "AttackedSettlement", "DestroyedEnemyBase", "SettlementProximity",
// Core HistoryEventDefs.xml and Ideology Precepts_Charity.xml
"CharityRefused_ThreatReward_Joiner", "CharityFulfilled_Beggars", "CharityFulfilled_HospitalityRefugees",
"CharityFulfilled_IntroWimp", "CharityFulfilled_RefugeePodCrash", "CharityFulfilled_ShuttleCrashRescue",
"CharityFulfilled_ThreatReward_Joiner", "CharityFulfilled_WandererJoins", "CharityRefused_Beggars", "CharityRefused_Beggars_Betrayed",
"CharityRefused_HospitalityRefugees", "CharityRefused_IntroWimp", "CharityRefused_Pilgrims", "CharityRefused_Pilgrims_Betrayed",
"CharityRefused_RefugeePodCrash", "CharityRefused_ShuttleCrashRescue", "CharityRefused_WandererJoins",
// Ideology Precepts_Raiders.xml, Precepts_Proselytizing.xml, Precepts_Ranching.xml, Precepts_Relics.xml
"PlayerRaidedSomeone", "Raided", "Raided_BanditCamp", "Raided_WorkSite", "RelicHuntSuccess", "ReliquaryPilgrimsSuccess",
"HospitalitySuccess_Animals", "RelicDestroyed", "RelicLost",
// Biotech HistoryEventDefs.xml
"PollutedNearbySite", "PollutedBase", "ToxicWasteDumping",
};
private static readonly HashSet<string> breakExclude = new HashSet<string>(BreakExclude);
private static readonly HashSet<string> recordedActExclude = new HashSet<string>(RecordedActExclude);
/// <summary>A def name the built-in list or the category's XML list leaves out.</summary>
public static bool Excluded(ActCategoryDef cat, string defName)
{
if (defName == null)
return true;
if (cat != null && cat.Excludes(defName))
return true;
switch (cat?.defName)
{
case ActCategories.Break: return breakExclude.Contains(defName);
case ActCategories.RecordedAct: return recordedActExclude.Contains(defName);
default: return false;
}
}
// ---- what each category holds ---------------------------------------------------------
/// <summary>
/// Ate: anything with an ingestible a colonist can eat or drink. Plants (grazing) and the corpses of
/// races without flesh (mechanoids) are left out.
/// </summary>
public static bool IsEdible(ThingDef def)
{
if (def?.ingestible == null)
return false;
if (def.category == ThingCategory.Plant)
return false;
if (def.IsCorpse && def.ingestible.sourceDef?.race != null && !def.ingestible.sourceDef.race.IsFlesh)
return false;
return true;
}
/// <summary>Used: a ThingDef whose comps hold a CompProperties_Usable (subclasses included).</summary>
public static bool IsUsable(ThingDef def)
{
if (def?.comps == null)
return false;
for (int i = 0; i < def.comps.Count; i++)
{
if (def.comps[i] is CompProperties_Usable)
return true;
}
return false;
}
/// <summary>Records: Int and Float records count acts; Time records count time.</summary>
public static bool CountsActs(RecordDef def) => def != null && (def.type == RecordType.Int || def.type == RecordType.Float);
// ---- building entries ----------------------------------------------------------------
/// <summary>
/// Single-def entries for the defs the rule found plus the include names, minus the exclude names,
/// each def once, with labels told apart (see Disambiguate).
/// </summary>
public static List<ActEntry> EntriesFor<T>(ActCategoryDef cat, IEnumerable<T> byRule, IEnumerable<string> builtInInclude = null) where T : Def
{
var defs = new List<T>();
var seen = new HashSet<T>();
void Take(T d)
{
if (d != null && !Excluded(cat, d.defName) && seen.Add(d))
defs.Add(d);
}
if (byRule != null)
{
foreach (T d in byRule)
Take(d);
}
if (builtInInclude != null)
{
foreach (string name in builtInInclude)
Take(DefDatabase<T>.GetNamedSilentFail(name));
}
if (cat?.include != null)
{
foreach (string name in cat.include)
Take(DefDatabase<T>.GetNamedSilentFail(name));
}
var entries = new List<ActEntry>(defs.Count);
foreach (T d in defs)
entries.Add(ActEntry.ForDef(cat.defName, d));
Disambiguate(entries);
return entries;
}
/// <summary>
/// Entries of one category that share a label (three states read "tantrum", two "binging on drug")
/// get the def's name in brackets, "Tantrum (Targeted Tantrum)". An entry whose def name reads as its
/// label keeps the plain label. The picker searches labels and def names, so both stay findable.
/// </summary>
public static void Disambiguate(List<ActEntry> entries)
{
var byLabel = new Dictionary<string, List<ActEntry>>(StringComparer.OrdinalIgnoreCase);
foreach (ActEntry e in entries)
{
if (e?.def == null || e.label == null)
continue;
if (!byLabel.TryGetValue(e.label, out List<ActEntry> same))
byLabel[e.label] = same = new List<ActEntry>();
same.Add(e);
}
foreach (List<ActEntry> same in byLabel.Values)
{
if (same.Count < 2)
continue;
foreach (ActEntry e in same)
{
string readable = Readable(e.def.defName);
if (Squash(readable) == Squash(e.label))
continue;
e.label = "BlaxLaws_CatalogueLabelWithName".Translate(e.label, readable);
}
}
}
/// <summary>"Binging_DrugExtreme" to "Binging Drug Extreme".</summary>
public static string Readable(string defName) =>
defName.NullOrEmpty() ? defName : GenText.SplitCamelCase(defName.Replace('_', ' ')).Replace(" ", " ").Trim();
private static string Squash(string s) => s == null ? "" : s.Replace(" ", "").Replace("-", "").ToLowerInvariant();
}
}

View File

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// What a piece of food is, for the Ate groups that read the thing rather than its def (a meal with meat
/// in it, human meat as an ingredient). Hook C reads it in its prefix, before the stack can be destroyed,
/// and puts it into ActEvent.facts. Built on the game's own checks:
/// - meat: FoodUtility.GetFoodKind(Thing), which reads a meal's ingredients (RimWorld/FoodUtility.cs:1454-1486);
/// - human meat: FoodUtility.IsHumanlikeCorpseOrHumanlikeMeatOrIngredient (:1114-1129), as Thing.Ingested
/// uses it (Verse/Thing.cs:2033);
/// - insect meat: the meat's source race has insectoid flesh (FoodUtility.GetMeatSourceCategory, :1178-1197),
/// read for corpses and ingredients by FoodUtility.IsInsectCorpseOrInsectMeatIngredient (:1140-1159).
/// Meals carry the Meal food type (Core Defs/ThingDefs_Items/Items_Food.xml:36); the Processed food type
/// marks drugs and chocolate (Core Defs/Drugs), so "any meal" reads FoodTypeFlags.Meal, not IsProcessedFood.
/// </summary>
public static class FoodFacts
{
/// <summary>The facts of a real thing. Falls back to the def when the thing can't be read.</summary>
public static ActFacts Of(Thing food)
{
if (food?.def?.ingestible == null)
return ActFacts.None;
ThingDef def = food.def;
ActFacts f = OfDefOnly(def) & ~(ActFacts.Meat | ActFacts.HumanMeat | ActFacts.InsectMeat);
if (FoodUtility.GetFoodKind(food) == FoodKind.Meat)
f |= ActFacts.Meat;
if (FoodUtility.IsHumanlikeCorpseOrHumanlikeMeatOrIngredient(food))
f |= ActFacts.HumanMeat;
if (FoodUtility.IsInsectCorpseOrInsectMeatIngredient(food))
f |= ActFacts.InsectMeat;
return f;
}
/// <summary>The facts a def alone gives: no ingredients, a corpse's race from its def.</summary>
public static ActFacts OfDefOnly(ThingDef def)
{
if (def?.ingestible == null)
return ActFacts.None;
ActFacts f = ActFacts.None;
if (FoodUtility.GetFoodKind(def) == FoodKind.Meat)
f |= ActFacts.Meat;
if (IsRawMeatOrCorpse(def))
f |= ActFacts.RawMeatOrCorpse;
if (SourceIsHumanlike(def))
f |= ActFacts.HumanMeat;
if (SourceIsInsect(def))
f |= ActFacts.InsectMeat;
if (IsRawFood(def))
f |= ActFacts.RawFood;
if (IsMeal(def))
f |= ActFacts.Meal;
return f;
}
/// <summary>
/// The facts of an act: the hook's, or read now from the thing (an act reported by other code), or
/// from the def. A thing that throws while read (a corpse already emptied) gives the def's facts.
/// </summary>
public static ActFacts Of(ActEvent act)
{
if (act == null)
return ActFacts.None;
if (act.facts != ActFacts.None)
return act.facts;
if (act.thing != null)
{
try
{
return Of(act.thing);
}
catch (Exception)
{
// A destroyed corpse has no inner pawn any more; the def still answers.
}
}
return OfDefOnly(act.def as ThingDef);
}
public static bool IsRawMeatOrCorpse(ThingDef def) => def?.ingestible != null && !def.IsProcessedFood && (def.IsMeat || def.IsCorpse);
public static bool IsRawFood(ThingDef def) =>
def?.ingestible != null && (def.ingestible.preferability == FoodPreferability.RawBad || def.ingestible.preferability == FoodPreferability.RawTasty);
public static bool IsMeal(ThingDef def) => def?.ingestible != null && (def.ingestible.foodType & FoodTypeFlags.Meal) != 0;
/// <summary>The food can hold ingredients (meals, pemmican), so a thing of it may hold meat.</summary>
public static bool HasIngredients(ThingDef def) => def?.GetCompProperties<CompProperties_Ingredients>() != null;
/// <summary>Human meat or a humanlike corpse, by the def.</summary>
public static bool SourceIsHumanlike(ThingDef def)
{
if (def?.ingestible == null)
return false;
if (def.IsCorpse)
return def.ingestible.sourceDef?.race?.Humanlike ?? false;
return FoodUtility.GetMeatSourceCategory(def) == MeatSourceCategory.Humanlike;
}
/// <summary>Insect meat or an insect corpse, by the def.</summary>
public static bool SourceIsInsect(ThingDef def)
{
if (def?.ingestible == null)
return false;
if (def.IsCorpse)
return def.ingestible.sourceDef?.race?.FleshType == FleshTypeDefOf.Insectoid;
return FoodUtility.GetMeatSourceCategory(def) == MeatSourceCategory.Insect;
}
}
/// <summary>Drugs as the drug binge and its option see them.</summary>
public static class DrugInfo
{
private static Dictionary<ChemicalDef, DrugCategory> chemicalCategory;
/// <summary>The chemical a drug def's CompProperties_Drug names, or null.</summary>
public static ChemicalDef ChemicalOf(ThingDef def) => def?.GetCompProperties<CompProperties_Drug>()?.chemical;
/// <summary>The drug category of a def; None for anything that isn't a drug.</summary>
public static DrugCategory CategoryOf(ThingDef def) => def?.ingestible?.drugCategory ?? DrugCategory.None;
/// <summary>
/// The strongest category among the drugs carrying the chemical (wake-up: Hard; alcohol: Social), or
/// None when no loaded drug carries it.
/// </summary>
public static DrugCategory CategoryOfChemical(ChemicalDef chemical)
{
if (chemical == null)
return DrugCategory.None;
if (chemicalCategory == null)
{
var map = new Dictionary<ChemicalDef, DrugCategory>();
foreach (ThingDef t in DefDatabase<ThingDef>.AllDefsListForReading)
{
ChemicalDef c = ChemicalOf(t);
if (c == null)
continue;
DrugCategory cat = CategoryOf(t);
if (cat == DrugCategory.Any)
cat = DrugCategory.None;
if (!map.TryGetValue(c, out DrugCategory had) || Strength(cat) > Strength(had))
map[c] = cat;
}
chemicalCategory = map;
}
return chemicalCategory.TryGetValue(chemical, out DrugCategory found) ? found : DrugCategory.None;
}
/// <summary>
/// The category a binge's planning case counts under for the "hard" and "social" options. The state's
/// own category, unless vanilla set it to Any: an addict's binge, or one that found no drug of its
/// break's category (Verse.AI/MentalState_BingingDrug.cs:60-80). Then the chosen chemical decides.
/// </summary>
public static DrugCategory BingeCategory(MentalState_BingingDrug binge)
{
if (binge == null)
return DrugCategory.None;
if (binge.drugCategory == DrugCategory.Hard || binge.drugCategory == DrugCategory.Social || binge.drugCategory == DrugCategory.Medical)
return binge.drugCategory;
return CategoryOfChemical(binge.chemical);
}
private static int Strength(DrugCategory c)
{
switch (c)
{
case DrugCategory.Hard: return 3;
case DrugCategory.Social: return 2;
case DrugCategory.Medical: return 1;
default: return 0;
}
}
}
}

View File

@ -0,0 +1,97 @@
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxLaws
{
// The eight category workers (design: "Act catalogue and detection", How). Each walks its DefDatabase once
// per catalogue build and returns its group entries first, then one ActEntry.ForDef per def. ActCatalogue
// fills group sizes, stages, links and hostility, and sorts the defs A to Z. What each rule admits is in
// CatalogueRules, the groups in CatalogueGroups.
/// <summary>
/// Mental breaks: every MentalStateDef a MentalBreakDef starts (mentalState), plus the built-in and XML
/// include lists (berserk and other states colonists reach without a break def), minus the exclude lists
/// (animal, baby and mechanoid states, the social fight). Groups: any break, any drug binge, any tantrum,
/// any insulting spree, any aggressive break.
/// </summary>
public class ActCategoryWorker_Break : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries()
{
var list = CatalogueGroups.Break(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
IEnumerable<MentalStateDef> fromBreaks = DefDatabase<MentalBreakDef>.AllDefsListForReading.Select(b => b.mentalState).Where(s => s != null);
list.AddRange(CatalogueRules.EntriesFor(def, fromBreaks, CatalogueRules.BreakInclude));
return list;
}
}
/// <summary>
/// Ate: every ThingDef with an ingestible a colonist can eat (CatalogueRules.IsEdible): food, meals, raw
/// food, corpses, drugs, modded and DLC ones. Groups: anything eaten, the drug groups, the meat groups,
/// raw food, any meal.
/// </summary>
public class ActCategoryWorker_Ate : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries()
{
var list = CatalogueGroups.Ate(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase<ThingDef>.AllDefsListForReading.Where(CatalogueRules.IsEdible)));
return list;
}
}
/// <summary>Used: every ThingDef with a CompProperties_Usable (psytrainers, neurotrainers, mech serums, modded usables). No groups.</summary>
public class ActCategoryWorker_Used : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries() =>
CatalogueRules.EntriesFor(def, DefDatabase<ThingDef>.AllDefsListForReading.Where(CatalogueRules.IsUsable));
}
/// <summary>Social interactions: every InteractionDef. Group: insult or slight.</summary>
public class ActCategoryWorker_Interaction : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries()
{
var list = CatalogueGroups.Interaction(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase<InteractionDef>.AllDefsListForReading));
return list;
}
}
/// <summary>
/// Recorded acts: every HistoryEventDef minus the faction-level ones (CatalogueRules.RecordedActExclude and
/// the XML list). No groups. Many are recorded only with Ideology active; the category tooltip says so.
/// </summary>
public class ActCategoryWorker_RecordedAct : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries() =>
CatalogueRules.EntriesFor(def, DefDatabase<HistoryEventDef>.AllDefsListForReading);
}
/// <summary>Records: every RecordDef with type Int or Float; Time records count time, not acts. No groups.</summary>
public class ActCategoryWorker_Record : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries() =>
CatalogueRules.EntriesFor(def, DefDatabase<RecordDef>.AllDefsListForReading.Where(CatalogueRules.CountsActs));
}
/// <summary>Bills: every RecipeDef. Group: any surgery.</summary>
public class ActCategoryWorker_Bill : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries()
{
var list = CatalogueGroups.Bill(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase<RecipeDef>.AllDefsListForReading));
return list;
}
}
/// <summary>Special acts: every ActDef (Defs/BlaxLaws_Acts.xml), by order then A to Z. No groups.</summary>
public class ActCategoryWorker_Special : ActCategoryWorker
{
public override IEnumerable<ActEntry> MakeEntries() =>
CatalogueRules.EntriesFor(def, DefDatabase<ActDef>.AllDefsListForReading.OrderBy(a => a.order).ThenBy(a => a.label ?? a.defName));
}
}

39
Source/BlaxLaws/Compat.cs Normal file
View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Shared mod detection. Laws has no hard dependency on any other mod. Sibling APIs (CastesApi,
/// SlavesApi) are bound by reflection into cached delegates at startup by the feature that needs them;
/// a missing sibling or member is a silent no-op. Package ids of mods a single feature reacts to live
/// in that feature's partial file of this class (Compat.PrisonLabor.cs and so on), each with the source
/// it was read from.
///
/// Package ids of the Blax mods, from their own About/About.xml (2026-12-01).
/// </summary>
public static partial class Compat
{
public const string BlaxCastes = "blax.castes";
public const string BlaxSlaves = "blax.slaves";
public const string BlaxZones = "blax.zones";
public const string BlaxDefaults = "blax.defaults";
/// <summary>
/// Package ids tests treat as active. Only tests write it; the runner clears it after every test.
/// </summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Active by packageId, local or Steam copy, or simulated by a test. ModsConfig.IsActive misses a mod
/// that is installed both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Laws uses it.
/// </summary>
public static bool IsActive(string packageId) =>
SimulatedActive.Contains(packageId) || ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null;
public static bool CastesActive => IsActive(BlaxCastes);
public static bool SlavesActive => IsActive(BlaxSlaves);
}
}

View File

@ -0,0 +1,72 @@
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The first release's detection hooks (design: "Detection: one postfix per act, quiet while the book is
/// empty"), one [HarmonyPatch] class per hook in this folder; BlaxLawsStartup applies them. Every hook reads
/// its Watch flag first, so an empty book costs one static field read per call; then Watch.MayMatch (one
/// set lookup); then it builds an ActEvent and calls CaseFiler.Report, all inside its own try/catch with
/// HookGuard.Fail. Hooks only record: CaseFiler queues, Enforcement punishes a tick later.
///
/// | Hook | Target (decompiled 1.7) | Files |
/// |---|---|---|
/// | A | MentalStateHandler.TryStartMentalState, prefix and postfix (Verse.AI/MentalStateHandler.cs:91; undraft :141-144, PostStart :162, StopAll :165-172, return true :202) | Break, planning; skips states another pawn's ability caused |
/// | C | Thing.Ingested, prefix and postfix (Verse/Thing.cs:2005) | Ate, and a binge's dose |
/// | E | Pawn_InteractionsTracker.TryInteractWith, postfix (RimWorld/Pawn_InteractionsTracker.cs:176, true at :268) | Interaction |
/// | F | Pawn_InteractionsTracker.StartSocialFight, postfix (:373) | Special/StartedSocialFight |
/// | I | Verb_Ignite.TryCastShot, postfix (RimWorld/Verb_Ignite.cs:12) | Special/SetFire |
/// | J | MentalState_CorpseObsession.MentalStateTick, postfix (Verse.AI/MentalState_CorpseObsession.cs:18) | Special/DisplayedCorpse |
/// | U | CompUsable.UsedBy and every override, prefix, postfix and finalizer (RimWorld/CompUsable.cs:161) | Used |
/// | H | HistoryEventsManager.RecordEvent, postfix (RimWorld/HistoryEventsManager.cs:55) | RecordedAct |
/// | R | Pawn_RecordsTracker.Increment and AddTo, postfixes (RimWorld/Pawn_RecordsTracker.cs:72, 84) | Record |
/// | B | RecordsUtility.Notify_BillDone, postfix (RimWorld/RecordsUtility.cs:52) | Bill |
///
/// None of the targets is a method of a few lines: A, C, E, H, U and B have loops, try blocks or dozens of
/// calls; F builds a message and starts two states; I and J are virtual overrides reached through a
/// virtual call; Increment and AddTo each build an error string on their failure path (about 80 bytes of
/// IL with five calls), above what the JIT inlines into a caller.
/// </summary>
public static class DetectionHooks
{
/// <summary>
/// The pawn acts on its own: one of the targets A, B or C of its current job is the thing. Vanilla
/// moves a job's target to the stack it carries (RimWorld/Toils_Ingest.cs:34; Verse.AI/Toils_Haul.cs:104)
/// and eats or uses the target (RimWorld/Toils_Ingest.cs:402, 428; RimWorld/JobDriver_UseItem.cs:95-96),
/// and a drink at a gathering spot is target C of the social relax job (RimWorld/JobDriver_SocialRelax.cs:75).
/// A doctor's dose, a warden or parent feeding someone and a doctor's serum run on the feeder's job
/// (RimWorld/Recipe_AdministerIngestible.cs:11, RimWorld/JobDriver_FoodFeedPatient.cs:78,
/// RimWorld/JobDriver_Feed.cs:47, RimWorld/Recipe_AdministerUsableItem.cs:15), so the eater's own job never
/// targets the thing.
/// </summary>
public static bool OnOwnJob(Pawn pawn, Thing thing)
{
if (thing == null)
return false;
Job job = pawn?.CurJob;
if (job == null)
return false;
return job.targetA.Thing == thing || job.targetB.Thing == thing || job.targetC.Thing == thing;
}
/// <summary>A building whose def is a table (Verse/ThingDef.cs:1008) stands on the thing's cell.</summary>
public static bool OnTable(Thing thing)
{
if (thing == null || !thing.Spawned || thing.Map == null)
return false;
List<Thing> here = thing.Position.GetThingList(thing.Map);
for (int i = 0; i < here.Count; i++)
{
if (here[i] != thing && here[i].def != null && here[i].def.IsTable)
return true;
}
return false;
}
/// <summary>The corpse lies in a grave or sarcophagus (Verse.AI/CorpseObsessionMentalStateUtility.cs:46).</summary>
public static bool InGrave(Corpse corpse) => corpse?.ParentHolder is Building_Grave;
}
}

View File

@ -0,0 +1,99 @@
using System;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// Hook A: a break starts (category Break, planning). Postfix on MentalStateHandler.TryStartMentalState
/// (Verse.AI/MentalStateHandler.cs:91), about 110 lines. The new state's PostStart has run at :162 before
/// `return true` at :202, so a drug binge has chosen its chemical (Verse.AI/MentalState_BingingDrug.cs:24-27)
/// and a corpse obsession its corpse (Verse.AI/MentalState_CorpseObsession.cs:41-45). The method undrafts
/// the pawn (:141-144) and, for most states, stops its job (:165-172) before the postfix runs. A state
/// another pawn's ability forced on the pawn files nothing, and a self-cast state is checked for the player
/// order in the prefix, before vanilla undrafts the pawn and stops its job.
/// </summary>
[HarmonyPatch(typeof(MentalStateHandler), nameof(MentalStateHandler.TryStartMentalState))]
public static class Patch_MentalStateHandler_TryStartMentalState
{
public const string Where = "hook A, MentalStateHandler.TryStartMentalState";
/// <summary>
/// A state the pawn starts on itself (a self-cast ability such as the Berserk trance: otherPawn is the pawn,
/// RimWorld/CompAbilityEffect_GiveMentalState.cs:59) is a player order when the pawn is drafted or on a
/// player-forced job. That has to be read here, before vanilla undrafts the pawn (Verse.AI/MentalStateHandler.cs:141-144)
/// and StopAll ends the cast job (:165-172).
/// </summary>
public static void Prefix(Pawn ___pawn, Pawn otherPawn, out bool __state)
{
__state = false;
if (!Watch.Break || otherPawn == null || otherPawn != ___pawn)
return;
__state = OrderedAtStart(___pawn);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool OrderedAtStart(Pawn pawn)
{
try
{
return Offenders.OnPlayerOrder(pawn);
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
return false;
}
}
public static void Postfix(MentalStateHandler __instance, Pawn ___pawn, MentalStateDef stateDef, Pawn otherPawn, bool __result, bool __state)
{
if (!Watch.Break || !__result)
return;
File(__instance, ___pawn, stateDef, otherPawn, __state);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(MentalStateHandler __instance, Pawn ___pawn, MentalStateDef stateDef, Pawn otherPawn, bool orderedAtStart)
{
try
{
MentalState state = __instance.CurState;
// A state that ended inside its own start (no corpse to obsess over) files nothing.
if (state?.def == null || state.def != stateDef || !Watch.MayMatch(ActCategories.Break, state.def))
return;
// Another pawn's ability forced the state on this one (a psycast, Neuroquake, a modded caster): the
// pawn did nothing. Only abilities and the social fight pass otherPawn, and the social fight is its own
// special act (hook F).
if (otherPawn != null && otherPawn != ___pawn)
return;
// A self-cast state on a player order (Berserk trance cast by the player) is exempt like any other order.
if (orderedAtStart && BlaxLawsMod.S.playerOrdersExempt)
return;
var act = new ActEvent(ActCategories.Break, state.def, ___pawn) { mentalState = state };
if (state is MentalState_BingingDrug binge)
{
act.chemical = binge.chemical;
act.drugCategory = DrugInfo.BingeCategory(binge);
}
else if (state is MentalState_CorpseObsession obsession && DetectionHooks.InGrave(obsession.corpse))
{
// Vanilla obsesses over buried corpses (Verse.AI/CorpseObsessionMentalStateUtility.cs:17-21), so
// the corpse is nearly always dug up; hook J keeps the note for the did-it.
act.notes |= CaseNotes.DugUp;
act.thing = obsession.corpse;
}
CaseFiler.Report(act);
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}

View File

@ -0,0 +1,86 @@
using System;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook C: a pawn eats or drinks (category Ate) and every dose of a drug binge, which reaches
/// CompDrug.PostIngested through this method (Verse/Thing.cs:2180; Verse/ThingWithComps.cs:767-774). Prefix
/// and postfix on Thing.Ingested (Verse/Thing.cs:2005). Toils_Ingest calls it once per meal with the job's
/// target as the eaten thing (RimWorld/Toils_Ingest.cs:402, 428). The prefix reads the facts while the
/// stack still exists (it may be destroyed at :2176-2179) and checks that the eater acts on its own job;
/// the postfix files, so an ingestion vanilla refuses (destroyed, not ingestible now, :2007-2016) files
/// nothing.
/// </summary>
[HarmonyPatch(typeof(Thing), nameof(Thing.Ingested))]
public static class Patch_Thing_Ingested
{
public const string Where = "hook C, Thing.Ingested";
/// <summary>What the prefix hands to the postfix. A struct: an empty book allocates nothing.</summary>
public struct State
{
public bool file;
public ActFacts facts;
public ChemicalDef chemical;
public DrugCategory drugCategory;
}
public static void Prefix(Thing __instance, Pawn ingester, out State __state)
{
__state = default;
if (!Watch.Ate)
return;
__state = Read(__instance, ingester);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static State Read(Thing __instance, Pawn ingester)
{
State __state = default;
try
{
ThingDef def = __instance?.def;
if (def == null || ingester == null || __instance.Destroyed || !Watch.MayMatch(ActCategories.Ate, def))
return default;
if (!Offenders.IsCovered(ingester) || !DetectionHooks.OnOwnJob(ingester, __instance))
return default;
__state.facts = FoodFacts.Of(__instance);
__state.chemical = DrugInfo.ChemicalOf(def);
__state.drugCategory = DrugInfo.CategoryOf(def);
__state.file = true;
}
catch (Exception e)
{
__state = default;
HookGuard.Fail(Where, e);
}
return __state;
}
public static void Postfix(Thing __instance, Pawn ingester, State __state)
{
if (!__state.file)
return;
try
{
CaseFiler.Report(new ActEvent(ActCategories.Ate, __instance.def, ingester)
{
thing = __instance,
facts = __state.facts,
chemical = __state.chemical,
drugCategory = __state.drugCategory,
});
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}

View File

@ -0,0 +1,84 @@
using System;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook E: a social interaction happens (category Interaction). Postfix on
/// Pawn_InteractionsTracker.TryInteractWith (RimWorld/Pawn_InteractionsTracker.cs:176), about 90 lines,
/// which returns true at :268 once the interaction took place. The offender is the initiator (the
/// tracker's pawn), the victim the recipient. Insults in a spree come through here (RimWorld/JobDriver_Insult.cs:34),
/// and so does the jailbreaker's talk: JobGiver_InducePrisonerToEscape gives a SparkJailbreak job
/// (RimWorld/JobGiver_InducePrisonerToEscape.cs:15-16) whose driver, JobDriver_SingleInteraction (Core
/// Defs/JobDefs/Jobs_Misc.xml:558-559), calls Toils_Interpersonal.Interact (RimWorld/Toils_Interpersonal.cs:292-301).
/// </summary>
[HarmonyPatch(typeof(Pawn_InteractionsTracker), nameof(Pawn_InteractionsTracker.TryInteractWith))]
public static class Patch_Pawn_InteractionsTracker_TryInteractWith
{
public const string Where = "hook E, Pawn_InteractionsTracker.TryInteractWith";
public static void Postfix(Pawn ___pawn, Pawn recipient, InteractionDef intDef, bool __result)
{
if (!Watch.Interaction || !__result)
return;
File(___pawn, recipient, intDef, __result);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Pawn ___pawn, Pawn recipient, InteractionDef intDef, bool __result)
{
try
{
if (intDef == null || !Watch.MayMatch(ActCategories.Interaction, intDef))
return;
CaseFiler.Report(new ActEvent(ActCategories.Interaction, intDef, ___pawn) { victim = recipient });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
/// <summary>
/// Hook F: a social fight starts (Special/StartedSocialFight). Postfix on
/// Pawn_InteractionsTracker.StartSocialFight (RimWorld/Pawn_InteractionsTracker.cs:373): a message, two
/// TryStartMentalState calls and a tale. CheckSocialFightStart calls it on the recipient of an
/// interaction (:217, :355-371), so the offender is the tracker's pawn, the one who swings first, and the
/// provoker (otherPawn) is the victim. It files only when the fight really started for the offender.
/// </summary>
[HarmonyPatch(typeof(Pawn_InteractionsTracker), nameof(Pawn_InteractionsTracker.StartSocialFight))]
public static class Patch_Pawn_InteractionsTracker_StartSocialFight
{
public const string Where = "hook F, Pawn_InteractionsTracker.StartSocialFight";
public static void Postfix(Pawn ___pawn, Pawn otherPawn)
{
if (!Watch.StartedSocialFight)
return;
File(___pawn, otherPawn);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Pawn ___pawn, Pawn otherPawn)
{
try
{
if (___pawn == null || ___pawn.MentalStateDef != MentalStateDefOf.SocialFighting || BlaxLawsActDefOf.StartedSocialFight == null)
return;
CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.StartedSocialFight, ___pawn) { victim = otherPawn });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}

View File

@ -0,0 +1,171 @@
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook H: the game records an act with a doer (category RecordedAct). Postfix on
/// HistoryEventsManager.RecordEvent (RimWorld/HistoryEventsManager.cs:55-...), with a try block and two
/// record maps. The offender is the event's Doer argument; an event without a doer pawn files nothing.
/// Core records some events whatever DLC is on (ExecutedPrisoner, RimWorld/ThoughtUtility.cs:56;
/// IngestedDrug, RimWorld/CompDrug.cs:105; CutTree, RimWorld/Plant.cs:627; AteHumanMeat, Verse/Thing.cs:2041),
/// most others only behind ModsConfig.IdeologyActive. RecordEvent also runs for acts the player orders (an
/// execution); the player-order exemption reads the doer's job like every other hook.
/// </summary>
[HarmonyPatch(typeof(HistoryEventsManager), nameof(HistoryEventsManager.RecordEvent))]
public static class Patch_HistoryEventsManager_RecordEvent
{
public const string Where = "hook H, HistoryEventsManager.RecordEvent";
public static void Postfix(HistoryEvent historyEvent)
{
if (!Watch.RecordedAct)
return;
File(historyEvent);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(HistoryEvent historyEvent)
{
try
{
HistoryEventDef def = historyEvent.def;
if (def == null || !Watch.MayMatch(ActCategories.RecordedAct, def))
return;
if (!historyEvent.args.TryGetArg(HistoryEventArgsNames.Doer, out Pawn doer) || doer == null)
return;
historyEvent.args.TryGetArg(HistoryEventArgsNames.Victim, out Pawn victim);
CaseFiler.Report(new ActEvent(ActCategories.RecordedAct, def, doer) { victim = victim });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
/// <summary>
/// Hook R, first half: an Int record goes up by one (category Record). Postfix on
/// Pawn_RecordsTracker.Increment (RimWorld/Pawn_RecordsTracker.cs:72-82). The offender is the tracker's
/// pawn. Time records never come here: they are added to the record map directly (:60-70).
/// </summary>
[HarmonyPatch(typeof(Pawn_RecordsTracker), nameof(Pawn_RecordsTracker.Increment))]
public static class Patch_Pawn_RecordsTracker_Increment
{
public const string Where = "hook R, Pawn_RecordsTracker.Increment";
public static void Postfix(Pawn_RecordsTracker __instance, RecordDef def)
{
if (!Watch.Record)
return;
File(__instance, def);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Pawn_RecordsTracker __instance, RecordDef def)
{
try
{
// Increment changes only Int records (:74-81).
if (def == null || def.type != RecordType.Int || !Watch.MayMatch(ActCategories.Record, def))
return;
CaseFiler.Report(new ActEvent(ActCategories.Record, def, __instance.pawn));
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
/// <summary>
/// Hook R, second half: an Int or Float record goes up by a value (category Record). Postfix on
/// Pawn_RecordsTracker.AddTo (RimWorld/Pawn_RecordsTracker.cs:84-97). Files only when the record went up:
/// an Int record adds the rounded value (:88).
/// </summary>
[HarmonyPatch(typeof(Pawn_RecordsTracker), nameof(Pawn_RecordsTracker.AddTo))]
public static class Patch_Pawn_RecordsTracker_AddTo
{
public const string Where = "hook R, Pawn_RecordsTracker.AddTo";
public static void Postfix(Pawn_RecordsTracker __instance, RecordDef def, float value)
{
if (!Watch.Record)
return;
File(__instance, def, value);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Pawn_RecordsTracker __instance, RecordDef def, float value)
{
try
{
if (def == null || !Watch.MayMatch(ActCategories.Record, def))
return;
bool up = def.type == RecordType.Int ? UnityEngine.Mathf.Round(value) >= 1f : def.type == RecordType.Float && value > 0f;
if (!up)
return;
CaseFiler.Report(new ActEvent(ActCategories.Record, def, __instance.pawn));
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
/// <summary>
/// Hook B: a pawn finishes one iteration of a bill (category Bill). Postfix on RecordsUtility.Notify_BillDone
/// (RimWorld/RecordsUtility.cs:52-67), static, two nested loops. Toils_Recipe.FinishRecipeAndStartStoringProduct
/// calls it right after bill.Notify_IterationCompleted for every bill type, surgery and Biotech's mech
/// gestators included, always with the pawn that finished the bill (Verse.AI/Toils_Recipe.cs:197-200), and
/// nothing else calls it. The recipe is the doer's current job's (Verse.AI/Job.cs:197); a null files
/// nothing. A surgery names its patient as the victim.
/// </summary>
[HarmonyPatch(typeof(RecordsUtility), nameof(RecordsUtility.Notify_BillDone))]
public static class Patch_RecordsUtility_Notify_BillDone
{
public const string Where = "hook B, RecordsUtility.Notify_BillDone";
public static void Postfix(Pawn billDoer, List<Thing> products)
{
if (!Watch.Bill)
return;
File(billDoer, products);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Pawn billDoer, List<Thing> products)
{
try
{
RecipeDef recipe = billDoer?.CurJob?.RecipeDef;
if (recipe == null || !Watch.MayMatch(ActCategories.Bill, recipe))
return;
var act = new ActEvent(ActCategories.Bill, recipe, billDoer);
// Bill_Medical.GiverPawn throws for a bill outside a pawn's bill stack (RimWorld/Bill_Medical.cs:72-85).
if (billDoer.CurJob.bill is Bill_Medical medical && medical.billStack?.billGiver is Pawn patient)
act.victim = patient;
if (products != null && products.Count > 0)
act.thing = products[0];
CaseFiler.Report(act);
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}

View File

@ -0,0 +1,123 @@
using System;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// Hook I: a pawn sets a fire (Special/SetFire). Postfix on Verb_Ignite.TryCastShot (RimWorld/Verb_Ignite.cs:12-22),
/// a protected override reached only through the virtual verb call (Verse/Verb.cs:462). The offender is
/// the caster, which FireUtility.TryStartFireIn gets as instigator (:16). Raiders ignite too
/// (RimWorld/TrashUtility.cs:97, 117); the offender filter in CaseFiler drops them.
/// </summary>
[HarmonyPatch(typeof(Verb_Ignite), "TryCastShot")]
public static class Patch_Verb_Ignite_TryCastShot
{
public const string Where = "hook I, Verb_Ignite.TryCastShot";
public static void Postfix(Verb_Ignite __instance, bool __result)
{
if (!Watch.SetFire || !__result)
return;
File(__instance, __result);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(Verb_Ignite __instance, bool __result)
{
try
{
Pawn caster = __instance.CasterPawn;
if (caster == null || BlaxLawsActDefOf.SetFire == null)
return;
CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.SetFire, caster) { thing = __instance.CurrentTarget.Thing });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
/// <summary>
/// Hook J: a corpse obsession displays its corpse (Special/DisplayedCorpse). Postfix on
/// MentalState_CorpseObsession.MentalStateTick (Verse.AI/MentalState_CorpseObsession.cs:18-39), a virtual
/// override that runs only for obsessed pawns. The haul job's last, instant toil sets alreadyHauledCorpse
/// (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:82-95, the call at :90), so the hook sees the flag on
/// the obsession's next tick, after the haul job and its grave target are gone.
///
/// The hook files when it saw the flag false and now sees it true. Vanilla saves the flag
/// (MentalState_CorpseObsession.cs:15), so after a load an obsession that already displayed its corpse is
/// never seen false and never files again; the "seen false" mark is unsaved and kept per live state.
/// While the flag is false it re-reads "dug up" for the current corpse on each tick, since vanilla may pick
/// another corpse (:26-28); a corpse carried out of its grave keeps the note. "On a table" is read from
/// the corpse's cell: 80% of drops go on a table (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:64,
/// TryFindTableCell :97-123).
/// </summary>
[HarmonyPatch(typeof(MentalState_CorpseObsession), nameof(MentalState_CorpseObsession.MentalStateTick))]
public static class Patch_MentalState_CorpseObsession_MentalStateTick
{
public const string Where = "hook J, MentalState_CorpseObsession.MentalStateTick";
private sealed class Seen
{
public bool unhauled;
public Corpse corpse;
public CaseNotes notes;
}
private static readonly ConditionalWeakTable<MentalState_CorpseObsession, Seen> seen = new ConditionalWeakTable<MentalState_CorpseObsession, Seen>();
public static void Postfix(MentalState_CorpseObsession __instance)
{
if (!Watch.DisplayedCorpse)
return;
File(__instance);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void File(MentalState_CorpseObsession __instance)
{
try
{
Pawn pawn = __instance.pawn;
// Recovered inside this tick: the state is gone from its pawn.
if (pawn == null || pawn.MentalState != __instance)
return;
Seen s = seen.GetValue(__instance, _ => new Seen());
if (!__instance.alreadyHauledCorpse)
{
Corpse corpse = __instance.corpse;
if (corpse != s.corpse)
{
s.corpse = corpse;
s.notes = CaseNotes.None;
}
if (DetectionHooks.InGrave(corpse))
s.notes |= CaseNotes.DugUp;
s.unhauled = true;
return;
}
if (!s.unhauled || BlaxLawsActDefOf.DisplayedCorpse == null)
return;
s.unhauled = false;
CaseNotes notes = s.notes;
Corpse shown = __instance.corpse;
if (DetectionHooks.OnTable(shown))
notes |= CaseNotes.OnTable;
CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.DisplayedCorpse, pawn) { thing = shown, notes = notes });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}

View File

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook U: a pawn uses an item (category Used). Prefix, postfix and finalizer on CompUsable.UsedBy
/// (RimWorld/CompUsable.cs:161) and on every subclass that overrides it, found by reflection at startup
/// (in the game code only CompUseableDatacore, which calls base, RimWorld/CompUseableDatacore.cs:28-32). A
/// depth count makes an override that calls base file once. UsedBy returns with no effect when
/// CanBeUsedBy(p, false, true) refuses (:163-166), so the prefix asks the same question and files only
/// when it was accepted and the item is a target of the pawn's own job: JobDriver_UseItem uses its target
/// A (RimWorld/JobDriver_UseItem.cs:95-96) and IngestionOutcomeDoer_UseThing the ingested thing
/// (RimWorld/IngestionOutcomeDoer_UseThing.cs:10). A patient a doctor gives a healer mech serum
/// (RimWorld/Recipe_AdministerUsableItem.cs:15) lies in bed on its own job and files nothing.
/// </summary>
[HarmonyPatch]
public static class Patch_CompUsable_UsedBy
{
public const string Where = "hook U, CompUsable.UsedBy";
// __state: 0 the call isn't counted, 1 counted, 2 counted and files.
[ThreadStatic]
private static int depth;
public static IEnumerable<MethodBase> TargetMethods()
{
MethodInfo baseMethod = AccessTools.DeclaredMethod(typeof(CompUsable), nameof(CompUsable.UsedBy), new[] { typeof(Pawn) });
if (baseMethod != null)
yield return baseMethod;
foreach (Type t in typeof(CompUsable).AllSubclasses())
{
if (t.ContainsGenericParameters)
continue;
MethodInfo m = AccessTools.DeclaredMethod(t, nameof(CompUsable.UsedBy), new[] { typeof(Pawn) });
if (m != null && !m.IsAbstract && m.GetMethodBody() != null)
yield return m;
}
}
// The user is bound by position (__0): a modded override may name its parameter otherwise.
public static void Prefix(CompUsable __instance, Pawn __0, out int __state)
{
__state = 0;
if (!Watch.Used)
return;
depth++;
__state = 1;
if (depth == 1 && Files(__instance, __0))
__state = 2;
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Files(CompUsable __instance, Pawn p)
{
try
{
ThingWithComps item = __instance?.parent;
if (p == null || item?.def == null || !Watch.MayMatch(ActCategories.Used, item.def))
return false;
if (!Offenders.IsCovered(p) || !DetectionHooks.OnOwnJob(p, item))
return false;
return __instance.CanBeUsedBy(p, forced: false, ignoreReserveAndReachable: true).Accepted;
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
return false;
}
}
public static void Postfix(CompUsable __instance, Pawn __0, int __state)
{
if (__state != 2)
return;
try
{
ThingWithComps item = __instance.parent;
CaseFiler.Report(new ActEvent(ActCategories.Used, item.def, __0) { thing = item });
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
/// <summary>Balances the depth count even when UsedBy throws. Returns void, so other mods' stack traces stay whole.</summary>
public static void Finalizer(int __state)
{
if (__state != 0 && depth > 0)
depth--;
}
}
}

View File

@ -0,0 +1,117 @@
using System;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Laws works with any DLC combination, core only included (design: "DLC support"). This class names
/// where a def comes from, says what a missing catalogue entry needs, and guards every read of DLC-only
/// pawn state behind ModsConfig.&lt;DLC&gt;Active. ModLister.Check&lt;DLC&gt; is an install check, not an
/// active check, and is never used.
/// </summary>
public static class DlcSupport
{
public const string CoreName = "Core";
public const string CorePackageId = "ludeon.rimworld";
private const string OfficialPrefix = "ludeon.rimworld.";
/// <summary>The official DLCs by name, in release order.</summary>
public static readonly string[] DlcNames = { "Royalty", "Ideology", "Biotech", "Anomaly", "Odyssey" };
// ---- where a def comes from ---------------------------------------------------------
/// <summary>"Core", the DLC's name ("Ideology") or the mod's name, as the catalogue shows it.</summary>
public static string SourceName(ModContentPack mod)
{
if (mod == null || mod.IsCoreMod)
return CoreName;
if (IsDlcPackageId(mod.PackageId))
return DlcName(mod.PackageId);
return mod.Name.NullOrEmpty() ? mod.PackageIdPlayerFacing : mod.Name;
}
/// <summary>The package id a catalogue entry saves with a row, lower case. Core for a def without a mod.</summary>
public static string SourcePackageId(ModContentPack mod) => mod?.PackageId ?? CorePackageId;
/// <summary>True for "ludeon.rimworld.royalty" and the other official DLCs, false for Core and mods.</summary>
public static bool IsDlcPackageId(string packageId) =>
!packageId.NullOrEmpty() && packageId.ToLowerInvariant().StartsWith(OfficialPrefix);
/// <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 official DLC a saved row's source names, by package id or by name ("Ideology"), or null for
/// Core and mods.
/// </summary>
public static string DlcOf(string savedMod, string savedPackageId)
{
if (IsDlcPackageId(savedPackageId))
return DlcName(savedPackageId);
foreach (string dlc in DlcNames)
{
if (string.Equals(dlc, savedMod, StringComparison.OrdinalIgnoreCase))
return dlc;
}
return null;
}
/// <summary>Whether the official DLC of this name is active. False for an unknown name.</summary>
public static bool IsDlcActive(string dlcName)
{
switch (dlcName?.ToLowerInvariant())
{
case "royalty": return ModsConfig.RoyaltyActive;
case "ideology": return ModsConfig.IdeologyActive;
case "biotech": return ModsConfig.BiotechActive;
case "anomaly": return ModsConfig.AnomalyActive;
case "odyssey": return ModsConfig.OdysseyActive;
default: return false;
}
}
/// <summary>"Needs Ideology".</summary>
public static string NeedsText(string dlcName) => "BlaxLaws_NeedsDlc".Translate(dlcName);
/// <summary>
/// What a row whose entry is missing shows: "Needs &lt;DLC&gt;" for a DLC source, else
/// "Missing: &lt;mod&gt;" (design: "A missing entry from a DLC shows Needs &lt;DLC&gt;").
/// </summary>
public static string MissingText(string savedMod, string savedPackageId)
{
string dlc = DlcOf(savedMod, savedPackageId);
if (dlc != null)
return NeedsText(dlc);
string mod = !savedMod.NullOrEmpty() ? savedMod : !savedPackageId.NullOrEmpty() ? savedPackageId : CoreName;
return "BlaxLaws_MissingMod".Translate(mod);
}
// ---- DLC-only pawn state, always behind the active check ------------------------------
/// <summary>A slave (Ideology).</summary>
public static bool IsSlave(Pawn p) => ModsConfig.IdeologyActive && p != null && p.IsSlave;
/// <summary>A child, never beaten (Biotech).</summary>
public static bool IsChild(Pawn p) => ModsConfig.BiotechActive && p != null && p.DevelopmentalStage.Child();
/// <summary>Holds an ideoligion role, which an arrest takes (Ideology; Precept_Role.cs:582-585).</summary>
public static bool HoldsRole(Pawn p) => ModsConfig.IdeologyActive && p?.Ideo != null && p.Ideo.GetRole(p) != null;
/// <summary>A mechanitor that controls mechs, which an arrest shuts down (Biotech; Pawn_GuestTracker.cs:536-539).</summary>
public static bool IsMechanitorWithMechs(Pawn p) =>
ModsConfig.BiotechActive && p?.mechanitor != null && MechanitorUtility.IsMechanitor(p) && p.mechanitor.ControlledPawns.Count > 0;
/// <summary>
/// Laws doesn't jail this pawn on its own while "Release gives back what jail took" isn't built or is
/// off: the case waits with "Arrest now" (design: "Jail for N days", hold).
/// </summary>
public static bool HeldForArrestNow(Pawn p) => HoldsRole(p) || IsMechanitorWithMechs(p);
}
}

View File

@ -0,0 +1,81 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Letters, only when a colonist is jailed or the player has to act: no prisoner bed, nobody to enforce,
/// a role holder or mechanitor waiting for "Arrest now" (setting "Letters for jailings"). Vanilla letter
/// defs only: Laws adds no Letter class and no LetterDef, so nothing of Laws enters the letter archive's
/// save (design: "Data model").
/// </summary>
public static class CaseLetters
{
public const string KindNoEnforcer = "NoEnforcer";
public const string KindNoBed = "NoBed";
public const string KindHold = "Hold";
// Letters of each kind already sent per case in this session. Callers also send only when the
// case's saved wait reason changes, so a reload doesn't repeat a letter for the same wait.
private static readonly ConditionalWeakTable<LawCase, HashSet<string>> sent = new ConditionalWeakTable<LawCase, HashSet<string>>();
/// <summary>True the first time per case and kind in this session: one letter per wait, even when a case flips between waits.</summary>
public static bool Once(LawCase c, string kind)
{
if (c == null || kind == null)
return false;
return sent.GetOrCreateValue(c).Add(kind);
}
/// <summary>Sends the letter when "Letters for jailings" is on. The keys take the args as {0}, {1}, ...</summary>
public static void Send(LawCase c, string labelKey, string textKey, LetterDef def, params NamedArgument[] args)
{
if (!BlaxLawsMod.S.jailLetters || Find.LetterStack == null)
return;
LookTargets targets = c?.offender != null && c.offender.Spawned ? new LookTargets(c.offender) : LookTargets.Invalid;
Find.LetterStack.ReceiveLetter(labelKey.Translate(args), textKey.Translate(args), def ?? LetterDefOf.NeutralEvent, targets);
}
/// <summary>A letter when letters are on, else a case message (Messages for cases).</summary>
public static void SendOrPost(LawCase c, string labelKey, string textKey, LetterDef def, params NamedArgument[] args)
{
if (BlaxLawsMod.S.jailLetters)
Send(c, labelKey, textKey, def, args);
else
CaseMessages.Post(c, textKey.Translate(args));
}
/// <summary>
/// "Jailed: Bob" at the capture: the act, the sentence and the release day. A case message instead
/// while "Letters for jailings" is off.
/// </summary>
public static void Jailed(LawCase c)
{
if (c == null)
return;
int now = Find.TickManager?.TicksGame ?? 0;
int left = c.releaseTick >= 0 ? c.releaseTick - now : JailFlow.SentenceTicks(c);
SendOrPost(c, "BlaxLaws_LetterJailedLabel", "BlaxLaws_LetterJailedText", LetterDefOf.NeutralEvent,
c.OffenderLabel, left.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false), c.Label, Sentences.ReleaseDate(c));
}
/// <summary>The letter that the case waits because nobody can ever enforce it.</summary>
public static void NoEnforcer(LawCase c) =>
Send(c, "BlaxLaws_LetterNoEnforcerLabel", "BlaxLaws_LetterNoEnforcerText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label);
}
/// <summary>Vanilla guilt (Pawn_GuiltTracker.cs:46-61), saved and counted down by the game.</summary>
public static class Guilt
{
/// <summary>Guilty for at least these ticks. A longer guilt already on the pawn is never shortened.</summary>
public static void AtLeast(Pawn p, int ticks)
{
if (p?.guilt == null || ticks <= 0)
return;
if (p.guilt.TicksUntilInnocent < ticks)
p.guilt.Notify_Guilty(ticks);
}
}
}

View File

@ -0,0 +1,31 @@
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Messages for cases (setting "Messages for cases"). Letters are the punishment workers' own, only when
/// a colonist is jailed or the player has to act (setting "Letters for jailings"); Laws never sends a
/// second letter for a break, since the vanilla break letter already arrives.
/// </summary>
public static class CaseMessages
{
/// <summary>One message when a stage's punishment is dispatched: "Bob broke a law: Wake-up (Did it). Punishment: jail."</summary>
public static void Filed(LawCase c, Law law, LawStage stage, PunishmentDef punishment)
{
if (c == null || law == null || !BlaxLawsMod.S.caseMessages)
return;
string text = "BlaxLaws_CaseFiled".Translate(c.OffenderLabel, law.Label, LawLabels.Stage(stage), punishment?.label ?? law.punishment);
Post(c, text);
}
/// <summary>A message about the case, pointing at the offender while it is spawned. Does nothing with messages off.</summary>
public static void Post(LawCase c, string text, MessageTypeDef type = null)
{
if (!BlaxLawsMod.S.caseMessages || text.NullOrEmpty())
return;
LookTargets target = c?.offender != null && c.offender.Spawned ? new LookTargets(c.offender) : LookTargets.Invalid;
Messages.Message(text, target, type ?? MessageTypeDefOf.NeutralEvent, historical: true);
}
}
}

View File

@ -0,0 +1,269 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The enforcement queue (design: "Enforcement runs a tick later"). CaseFiler queues (case, stage)
/// entries from inside hooks; GameComponent_BlaxLaws.GameComponentTick drains them on a later tick, so
/// nothing acts inside a status change, an ingestion or an interaction. Every 250 ticks a sweep walks
/// the open cases only; every 2500 ticks the jailed ones. Nothing scans all pawns.
///
/// Not saved: entries refer to cases by id, and Refill rebuilds the queue from the cases after a load
/// (a stage with a row whose punishment never ran, a "Maintain only" write still owed).
/// </summary>
public static class Enforcement
{
public const int SweepInterval = 250;
public const int SentenceInterval = 2500;
/// <summary>Ticks after the capture the "Maintain only" write lands (design: "Jail for N days").</summary>
public const int MaintainOnlyDelay = 2;
private struct Entry
{
public int caseId;
public CaseTask task;
public LawStage stage;
public int dueTick;
}
private static readonly List<Entry> queue = new List<Entry>();
private static readonly List<Entry> due = new List<Entry>();
/// <summary>Entries waiting. The component's tick returns at once while this is 0 and no case exists.</summary>
public static int Pending => queue.Count;
/// <summary>Queues the stage's punishment for the next tick.</summary>
public static void Enqueue(LawCase c, LawStage stage) => Schedule(c, CaseTask.Punish, stage, 1);
/// <summary>Queues a task for the case, delayTicks from now (at least 1).</summary>
public static void Schedule(LawCase c, CaseTask task, LawStage stage, int delayTicks)
{
if (c == null)
return;
int now = Find.TickManager?.TicksGame ?? 0;
queue.Add(new Entry { caseId = c.id, task = task, stage = stage, dueTick = now + Math.Max(1, delayTicks) });
}
/// <summary>Whether a task for the case is waiting.</summary>
public static bool IsQueued(LawCase c, CaseTask task)
{
if (c == null)
return false;
foreach (Entry e in queue)
{
if (e.caseId == c.id && e.task == task)
return true;
}
return false;
}
/// <summary>Drops every entry: a new game or a load. Then Refill.</summary>
public static void Reset() => queue.Clear();
/// <summary>
/// After a load: queues each stage that has a row and never ran, and each "Maintain only" still owed
/// after a capture. Cases in Enforcing need nothing here; the 250-tick sweep re-issues their jobs.
/// </summary>
public static void Refill(GameComponent_BlaxLaws comp)
{
if (comp == null)
return;
foreach (LawCase c in comp.Cases)
{
if (c.IsClosed)
continue;
foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt })
{
if (c.LawIdFor(s) > 0 && !c.HasPunished(s))
Enqueue(c, s);
}
if (c.status == CaseStatus.Jailed && c.captureTick >= 0 && !c.maintainOnlyDone)
Schedule(c, CaseTask.MaintainOnly, c.activeStage, 1);
}
}
/// <summary>One game tick: due entries, then the sweeps.</summary>
internal static void Tick(GameComponent_BlaxLaws comp)
{
int now = Find.TickManager.TicksGame;
if (queue.Count > 0)
Drain(comp, now);
if (now % SweepInterval == 0)
Sweep(comp);
if (now % SentenceInterval == 0)
SentenceSweep(comp);
}
private static void Drain(GameComponent_BlaxLaws comp, int now)
{
due.Clear();
for (int i = 0; i < queue.Count; i++)
{
if (queue[i].dueTick <= now)
due.Add(queue[i]);
}
if (due.Count == 0)
return;
queue.RemoveAll(e => e.dueTick <= now);
foreach (Entry e in due)
{
LawCase c = comp.CaseById(e.caseId);
if (c == null)
continue;
try
{
switch (e.task)
{
case CaseTask.Punish:
Dispatch(comp, c, e.stage);
break;
case CaseTask.MaintainOnly:
Sentences.WriteMaintainOnly(c);
break;
}
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement " + e.task, ex);
}
}
}
/// <summary>
/// Dispatches the case's queued punish entries whose punishment passes the filter now instead of next
/// tick, so a case about to close still carries out a stage filed in the same tick (a did-it Guilty,
/// Warn or Subdue filed during the subdue). Returns whether one ran.
/// </summary>
internal static bool DispatchNow(LawCase c, Func<PunishmentDef, bool> filter)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (c == null || comp == null || queue.Count == 0)
return false;
List<Entry> now = null;
for (int i = 0; i < queue.Count; i++)
{
Entry e = queue[i];
if (e.caseId != c.id || e.task != CaseTask.Punish || c.HasPunished(e.stage))
continue;
PunishmentDef p = c.LawFor(e.stage)?.PunishmentDef;
if (p != null && filter(p))
(now ?? (now = new List<Entry>())).Add(e);
}
if (now == null)
return false;
queue.RemoveAll(e => now.Contains(e));
foreach (Entry e in now)
{
try
{
Dispatch(comp, c, e.stage);
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement " + e.task, ex);
}
}
return true;
}
/// <summary>Starts the stage's punishment: once per stage, with a message, handing over from an unfinished earlier one.</summary>
private static void Dispatch(GameComponent_BlaxLaws comp, LawCase c, LawStage stage)
{
if (c.IsClosed || c.HasPunished(stage))
return;
Law law = c.LawFor(stage);
if (law == null)
return;
c.MarkPunished(stage);
PunishmentDef p = law.PunishmentDef;
CaseMessages.Filed(c, law, stage, p);
if (!BlaxLawsMod.S.enforceLaws)
{
// "Enforce laws" off: the case log runs, nothing is carried out.
if (c.activePunishment == null)
comp.CloseCase(c, CaseOutcomes.NotEnforced);
return;
}
if (p == null)
{
LawsLog.WarningOnce("punishment:" + law.punishment, "Law " + law.id + " names the punishment " + law.punishment + ", which isn't loaded; its cases are only listed.");
return;
}
if (!p.runsAlongside)
{
PunishmentDef active = ActiveOf(c);
if (active != null && active != p && !c.IsClosed)
active.Worker.Stop(c);
c.activePunishment = p.defName;
c.activeStage = stage;
}
p.Worker.Start(c, law, stage);
}
/// <summary>The case's running punishment, or null.</summary>
public static PunishmentDef ActiveOf(LawCase c) =>
c == null || c.activePunishment.NullOrEmpty() ? null : DefDatabase<PunishmentDef>.GetNamedSilentFail(c.activePunishment);
/// <summary>
/// Every 250 ticks: closes planning cases whose break ended with nothing done, closes cases whose
/// offender is gone, and lets each active punishment retry and re-issue.
/// </summary>
private static void Sweep(GameComponent_BlaxLaws comp)
{
if (!comp.AnyOpenCase)
return;
foreach (LawCase c in comp.OpenCases())
{
try
{
if (c.offender == null || LawCase.IsGone(c.offender))
{
if (c.status != CaseStatus.Jailed)
comp.CloseCase(c, CaseOutcomes.OffenderGone);
continue;
}
PunishmentDef active = ActiveOf(c);
if (active == null && c.status == CaseStatus.Open && c.IsBreakCase && c.stage == LawStage.Planning &&
!IsQueued(c, CaseTask.Punish) && !CaseFiler.StillInBreak(c))
{
comp.CloseCase(c, CaseOutcomes.BreakEnded);
continue;
}
if (active != null && c.status != CaseStatus.Jailed)
active.Worker.Sweep(c);
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement sweep", ex);
}
}
}
/// <summary>Every 2500 ticks: the sentence check of each jailed case.</summary>
private static void SentenceSweep(GameComponent_BlaxLaws comp)
{
if (!comp.AnyOpenCase)
return;
foreach (LawCase c in comp.OpenCases())
{
if (c.status != CaseStatus.Jailed)
continue;
try
{
PunishmentDef active = ActiveOf(c);
if (active != null)
active.Worker.SentenceSweep(c);
else
Sentences.Check(c);
}
catch (Exception ex)
{
HookGuard.Fail("Sentence sweep", ex);
}
}
}
}
}

View File

@ -0,0 +1,96 @@
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// Starting, finding and ending the enforcer's jobs. Laws starts its jobs at once, interrupting what the
/// enforcer does, with playerForced set (design: "Enforcement runs a tick later"), and never queues a
/// job of its own; the one job it queues is the vanilla Capture after a subdue.
/// </summary>
public static class EnforcerJobs
{
/// <summary>
/// Starts the job now: StartJob with InterruptForced and preToilReservationsCanFail, so a reservation
/// that fails ends the job quietly instead of logging (Pawn_JobTracker.cs:252, 373-375). Returns
/// whether the job runs.
/// </summary>
public static bool Start(Pawn enforcer, Job job)
{
if (enforcer?.jobs == null || job == null)
return false;
job.playerForced = true;
enforcer.jobs.StartJob(job, JobCondition.InterruptForced, null, resumeCurJobAfterwards: false, cancelBusyStances: true,
null, JobTag.Misc, fromQueue: false, canReturnCurJobToPool: false, keepCarryingThingOverride: null, continueSleeping: false,
addToJobsThisTick: true, preToilReservationsCanFail: true);
return enforcer.CurJob == job;
}
/// <summary>A subdue, arrest or capture job on this offender.</summary>
public static bool IsEnforcementJob(Job job, Pawn offender)
{
if (job?.def == null || offender == null || job.targetA.Thing != offender)
return false;
return job.def == BlaxLawsDefOf.BlaxLaws_Subdue || job.def == JobDefOf.Arrest || job.def == JobDefOf.Capture;
}
/// <summary>The pawn's current job is this def on this target.</summary>
public static bool Runs(Pawn pawn, JobDef def, Pawn target)
{
Job job = pawn?.CurJob;
return job != null && job.def == def && target != null && job.targetA.Thing == target;
}
/// <summary>A job of this def on this target waits in the pawn's queue.</summary>
public static bool Queued(Pawn pawn, JobDef def, Pawn target)
{
JobQueue queue = pawn?.jobs?.jobQueue;
if (queue == null || target == null)
return false;
for (int i = 0; i < queue.Count; i++)
{
Job job = queue[i]?.job;
if (job != null && job.def == def && job.targetA.Thing == target)
return true;
}
return false;
}
/// <summary>The pawn runs or has queued an Arrest or Capture of the target.</summary>
public static bool TakesToJail(Pawn pawn, Pawn target) =>
pawn != null && target != null && !pawn.Dead &&
(Runs(pawn, JobDefOf.Arrest, target) || Runs(pawn, JobDefOf.Capture, target) ||
Queued(pawn, JobDefOf.Capture, target) || Queued(pawn, JobDefOf.Arrest, target));
/// <summary>
/// Ends the pawn's job of this def on this target, current or queued. Returns whether one ended. The pawn
/// starts no new job here: a hand-over (Enforcement.Dispatch stops the earlier punishment, then starts the
/// next) must find its enforcer free, and the think tree would hand it any job at once, Ingest, Reading
/// or ClearSnow among them, which aren't casually interruptible, so the pick would pass it over. A pawn
/// left without a job gets one from the think tree on its next job tick (Pawn_JobTracker.cs:195-202).
/// </summary>
public static bool End(Pawn pawn, JobDef def, Pawn target)
{
if (pawn?.jobs == null || def == null || target == null)
return false;
bool ended = false;
JobQueue queue = pawn.jobs.jobQueue;
for (int i = queue.Count - 1; i >= 0; i--)
{
Job job = queue[i]?.job;
if (job != null && job.def == def && job.targetA.Thing == target)
{
pawn.jobs.EndCurrentOrQueuedJob(job, JobCondition.InterruptForced);
ended = true;
}
}
if (Runs(pawn, def, target))
{
pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, startNewJob: false);
ended = true;
}
return ended;
}
}
}

View File

@ -0,0 +1,208 @@
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
using Verse.AI.Group;
namespace BlaxLaws
{
/// <summary>What the enforcer must be able to do.</summary>
public enum EnforcerNeed
{
/// <summary>Violence (subdue).</summary>
Subdue,
/// <summary>Manipulation (arrest, capture).</summary>
Arrest,
/// <summary>Both: "Subdue then jail" beats the pawn down and carries it to the prisoner bed.</summary>
SubdueAndArrest,
}
/// <summary>
/// Who enforces and when nobody may be sent (design: "Enforcement runs a tick later", enforcer pick and
/// danger). Runs only when a case is dispatched or swept, never per tick, and walks only the free
/// colonists of the offender's map.
///
/// The pick: free non-slave adult colonists on the offender's map, awake, not downed, not in a mental
/// state, not drafted, no player-forced job, no lord (parties, rituals, caravans forming), not the
/// offender and not the victim a murderous rage names. Never pulled off a job that must not be dropped:
/// a job that isn't casually interruptible (in Core: Rescue, Capture, Arrest, TendPatient, BeatFire,
/// ExtinguishSelf, ManTurret, DeliverToBed, LayDown), carrying a pawn (PawnUtility.cs:115), fleeing
/// (Flee, FleeAndCower) or surgery (a DoBill whose recipe IsSurgery, RecipeDef.cs:362). Wardens first
/// (Warden work active), then anyone able unless the setting is "Wardens only"; nearest by straight
/// distance among those that can reach the offender. The case's own enforcer goes first when it is still
/// free, so a later stage hands over to the same pawn.
/// </summary>
public static class Enforcers
{
private struct Candidate
{
public Pawn pawn;
public bool warden;
public float distSq;
}
private static readonly List<Candidate> tmp = new List<Candidate>();
/// <summary>The enforcer for the case, or null when nobody can go now (the case waits for the sweep).</summary>
public static Pawn Pick(LawCase c, EnforcerNeed need) => Pick(c, need, out _);
/// <summary>The enforcer, or null with WaitReasons.NoEnforcer (nobody able at all) or Busy (nobody free now).</summary>
public static Pawn Pick(LawCase c, EnforcerNeed need, out string waitReason)
{
Pawn offender = c?.offender;
if (offender == null || !offender.Spawned || offender.Map == null)
{
waitReason = WaitReasons.Away;
return null;
}
return PickFrom(c, need, offender.Map.mapPawns.FreeColonistsSpawned, out waitReason);
}
/// <summary>The pick over the given candidates (the map's free colonists in the game; a fixed list in tests).</summary>
public static Pawn PickFrom(LawCase c, EnforcerNeed need, IEnumerable<Pawn> candidates, out string waitReason)
{
waitReason = null;
Pawn offender = c?.offender;
if (offender == null || !offender.Spawned)
{
waitReason = WaitReasons.Away;
return null;
}
bool wardensOnly = BlaxLawsMod.S.enforcers == EnforcerMode.WardensOnly;
// Hand-over: a later stage keeps the pawn that already acts for the case.
Pawn own = c.enforcer;
if (own != null && own.Spawned && own.Map == offender.Map && IsAble(own, offender, need, wardensOnly) &&
IsFree(own, c) && own.CanReach(offender, PathEndMode.Touch, Danger.Deadly))
return own;
int able = 0;
tmp.Clear();
try
{
foreach (Pawn p in candidates)
{
if (p == null || p.Map != offender.Map || !IsAble(p, offender, need, wardensOnly))
continue;
able++;
if (!IsFree(p, c))
continue;
tmp.Add(new Candidate { pawn = p, warden = IsWarden(p), distSq = (p.Position - offender.Position).LengthHorizontalSquared });
}
tmp.Sort((a, b) =>
{
if (a.warden != b.warden)
return a.warden ? -1 : 1;
return a.distSq.CompareTo(b.distSq);
});
foreach (Candidate cand in tmp)
{
if (cand.pawn.CanReach(offender, PathEndMode.Touch, Danger.Deadly))
return cand.pawn;
}
}
finally
{
tmp.Clear();
}
waitReason = able == 0 ? WaitReasons.NoEnforcer : WaitReasons.Busy;
return null;
}
/// <summary>
/// Could ever enforce this case, whatever it does right now: a free non-slave adult colonist other
/// than the offender, able to move and to do what the punishment needs; a warden in "Wardens only".
/// </summary>
public static bool IsAble(Pawn p, Pawn offender, EnforcerNeed need, bool wardensOnly)
{
if (p == null || p == offender || p.Dead || !p.RaceProps.Humanlike)
return false;
if (!p.IsFreeNonSlaveColonist || DlcSupport.IsSlave(p) || p.IsQuestLodger())
return false;
// Children (Biotech) and babies never enforce; DevelopmentalStage reads Adult without Biotech.
if (!p.DevelopmentalStage.Adult())
return false;
if (p.health?.capacities == null || !p.health.capacities.CapableOf(PawnCapacityDefOf.Moving))
return false;
if ((need == EnforcerNeed.Subdue || need == EnforcerNeed.SubdueAndArrest) && p.WorkTagIsDisabled(WorkTags.Violent))
return false;
if ((need == EnforcerNeed.Arrest || need == EnforcerNeed.SubdueAndArrest) && !p.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
return false;
if (wardensOnly && !IsWarden(p))
return false;
return true;
}
/// <summary>Free to be sent now (see the class summary). A job of this case's own enforcement counts as free.</summary>
public static bool IsFree(Pawn p, LawCase c)
{
if (p == null || !p.Spawned || p.Downed || p.Dead || !p.Awake() || p.InMentalState || p.Drafted)
return false;
if (p.GetLord() != null)
return false;
if (p.IsCarryingPawn())
return false;
Pawn offender = c?.offender;
if (offender?.MentalState is MentalState_MurderousRage rage && rage.target == p)
return false;
Job job = p.CurJob;
if (job == null)
return true;
if (offender != null && EnforcerJobs.IsEnforcementJob(job, offender))
return c.enforcer == p;
return !MustNotDrop(job);
}
/// <summary>
/// A job Laws never pulls a pawn off: player-forced, not casually interruptible, fleeing, or surgery.
/// </summary>
public static bool MustNotDrop(Job job)
{
if (job?.def == null)
return false;
if (job.playerForced || !job.def.casualInterruptible)
return true;
if (job.def == JobDefOf.Flee || job.def == JobDefOf.FleeAndCower || job.def == JobDefOf.FleeAndCowerShort)
return true;
if (job.def == JobDefOf.DoBill && job.RecipeDef != null && job.RecipeDef.IsSurgery)
return true;
return false;
}
/// <summary>Warden work is active for the pawn (and not disabled).</summary>
public static bool IsWarden(Pawn p) =>
p?.workSettings != null && p.workSettings.EverWork && !p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) &&
p.workSettings.WorkIsActive(WorkTypeDefOf.Warden);
/// <summary>
/// True while hostiles threaten the offender's map (GenHostility.cs:227) or are near the offender
/// (PawnUtility.cs:161): nobody is sent, the case waits. A berserk colonist counts: its state is
/// hostile to the player faction (MentalState_Berserk.cs:12-15, GenHostility.cs:128-133).
/// </summary>
public static bool DangerBlocks(Pawn offender)
{
if (offender == null || !offender.Spawned || offender.Map == null)
return false;
return GenHostility.AnyHostileActiveThreatToPlayer(offender.Map) || PawnUtility.EnemiesAreNearby(offender);
}
/// <summary>
/// The offender's live break is hostile to the colony (berserk in vanilla). Wins over the catalogue's
/// hostileBreak (design: "Lawbook tab"): such a pawn fights back and vanilla refuses its arrest
/// (GenAI.cs:83).
/// </summary>
public static bool FightsBack(Pawn p) => p?.MentalState != null && p.MentalState.ForceHostileTo(Faction.OfPlayer);
/// <summary>
/// The enforcer can take the offender to the bed now: neither is reserved by someone else. Checked
/// right before an Arrest or Capture starts, so StartJob never logs a reservation error
/// (ReservationUtility.cs:63; Pawn_JobTracker.cs:336, 373-380).
/// </summary>
public static bool CanTakeToBed(Pawn enforcer, Pawn offender, Building_Bed bed)
{
if (enforcer == null || offender == null || bed == null)
return false;
return enforcer.CanReserve(offender) && enforcer.CanReserve(bed, bed.SleepingSlotsCount, 0);
}
}
}

View File

@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The subdue job's driver (JobDef BlaxLaws_Subdue, design: "Subdue"). One toil,
/// Toils_Combat.FollowAndMeleeAttack (Toils_Combat.cs:115-178): it follows the target, calls Hit while
/// adjacent and ends when the target is downed (:165-167) or unreachable (:132-134). The toil runs as a
/// tickIntervalAction, which Thing.DoTick calls every 1 to 15 ticks depending on the camera
/// (Thing.cs:726-735; GenTicks.cs:130-142), so hits are timed by game ticks, never by calls: one every 90
/// ticks, also off screen.
///
/// The job ends with a message once three hits in a row add no pain (a hit counts as painless when
/// PainTotal rises by less than a quarter of the new injury's own pain: go-juice's pain factor of 0.1,
/// painkillers, every allowed part at its cap, the pawn's injuries at the total cap of SubdueHits) or after
/// 40 hits. The beaten pawn loses the break's
/// recovery thought (Catharsis) that the downing gives through RecoverFromState (Pawn_HealthTracker.cs:
/// 850-853; MentalState.cs:92-95) while "Subdued pawns lose their catharsis" is on.
///
/// Never saved: the JobDef isn't suspendable (an interrupt ends it instead of queueing it), the job
/// reserves nothing, and Patch_Pawn_JobTracker_ExposeData hides it from the save. So none of its fields
/// needs saving; after a load the sweep issues a new subdue.
/// </summary>
public class JobDriver_Subdue : JobDriver
{
public const int HitIntervalTicks = 90;
public const int MaxHits = 40;
public const int PainlessHitsToStop = 3;
/// <summary>A hit is painful when PainTotal rises by at least this share of the injury's own pain.</summary>
public const float PainShare = 0.25f;
private int lastHitTick = -1000000;
private int hits;
private int painlessHits;
private LawCase lawCase;
private static readonly List<Thought_Memory> memoriesBefore = new List<Thought_Memory>();
private static readonly List<int> agesBefore = new List<int>();
public Pawn Target => job?.GetTarget(TargetIndex.A).Thing as Pawn;
/// <summary>Hits dealt so far.</summary>
public int Hits => hits;
/// <summary>The job reserves nothing, so no reservation list ever refers to it.</summary>
public override bool TryMakePreToilReservations(bool errorOnFailed) => true;
public override void Notify_Starting()
{
base.Notify_Starting();
lawCase = SubdueFlow.CaseFor(pawn, Target);
}
protected override IEnumerable<Toil> MakeNewToils()
{
this.FailOnDespawnedOrNull(TargetIndex.A);
this.FailOn(() => Target == null || Target.Dead || lawCase == null || lawCase.IsClosed || lawCase.enforcer != pawn);
// No longer in the break the case recorded (it ended, or was cured some other way).
this.FailOn(() => Target != null && !Target.Downed && !SubdueFlow.InBreak(lawCase));
yield return Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, Hit);
}
private void Hit()
{
try
{
Pawn target = Target;
if (target == null || lawCase == null || target.Dead)
return;
int now = Find.TickManager.TicksGame;
if (now - lastHitTick < HitIntervalTicks)
return;
lastHitTick = now;
hits++;
pawn.rotationTracker?.FaceTarget(target);
ThoughtDef recovery = target.MentalStateDef?.moodRecoveryThought;
bool dropRecovery = recovery != null && BlaxLawsMod.S.subdueRemovesCatharsis;
if (dropRecovery)
RememberMemories(target, recovery);
float painBefore = target.health.hediffSet.PainTotal;
float injuryPain = SubdueHits.Hit(pawn, target);
if (target.Dead)
{
EndJobWith(JobCondition.Incompletable);
return;
}
if (target.Downed)
{
if (dropRecovery)
DropNewMemories(target, recovery);
SubdueFlow.OnDowned(lawCase, pawn);
ReadyForNextToil();
return;
}
float gain = target.health.hediffSet.PainTotal - painBefore;
if (injuryPain <= 0f || gain < injuryPain * PainShare)
painlessHits++;
else
painlessHits = 0;
if (painlessHits >= PainlessHitsToStop || hits >= MaxHits)
{
SubdueFlow.OnGaveUp(lawCase, pawn);
EndJobWith(JobCondition.Incompletable);
}
}
catch (Exception e)
{
HookGuard.Fail("Subdue hit", e);
try
{
EndJobWith(JobCondition.Incompletable);
}
catch (Exception e2)
{
HookGuard.Fail("Subdue end after a failed hit", e2);
}
}
}
/// <summary>The memories of the recovery thought the target has before the hit, with their ages.</summary>
private static void RememberMemories(Pawn target, ThoughtDef def)
{
memoriesBefore.Clear();
agesBefore.Clear();
List<Thought_Memory> list = target.needs?.mood?.thoughts?.memories?.Memories;
if (list == null)
return;
foreach (Thought_Memory m in list)
{
if (m.def == def)
{
memoriesBefore.Add(m);
agesBefore.Add(m.age);
}
}
}
/// <summary>Removes the recovery memory the downing gave, and puts back the age of one it only renewed.</summary>
private static void DropNewMemories(Pawn target, ThoughtDef def)
{
MemoryThoughtHandler handler = target.needs?.mood?.thoughts?.memories;
if (handler == null)
return;
List<Thought_Memory> now = handler.Memories;
for (int i = now.Count - 1; i >= 0; i--)
{
Thought_Memory m = now[i];
if (m.def != def)
continue;
int idx = memoriesBefore.IndexOf(m);
if (idx < 0)
handler.RemoveMemory(m);
else if (m.age < agesBefore[idx])
m.age = agesBefore[idx];
}
memoriesBefore.Clear();
agesBefore.Clear();
}
}
}

View File

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// A punishment (Defs/BlaxLaws_Punishments.xml). The defName is what a row saves, so it never changes.
/// fits says which entry kinds and stages offer it; the worker carries it out.
/// </summary>
public class PunishmentDef : Def
{
public Type workerClass = typeof(PunishmentWorker);
/// <summary>Dropdown order; lower first.</summary>
public int order;
/// <summary>The row's Days field applies (Guilty, Jail, Subdue then jail).</summary>
public bool usesDays;
/// <summary>
/// Never replaces or stops what a case already runs, and never becomes the case's active punishment
/// (Warn, Guilty: "Warn and Guilty run alongside").
/// </summary>
public bool runsAlongside;
public List<PunishmentFit> fits = new List<PunishmentFit>();
[Unsaved]
private PunishmentWorker workerInt;
public PunishmentWorker Worker
{
get
{
if (workerInt == null)
{
workerInt = (PunishmentWorker)Activator.CreateInstance(workerClass ?? typeof(PunishmentWorker));
workerInt.def = this;
}
return workerInt;
}
}
/// <summary>The entry kind and stage a row has, as fits names them.</summary>
public static PunishmentFit FitOf(ActEntry entry, LawStage stage)
{
if (entry == null || !entry.IsBreak)
return PunishmentFit.Act;
if (entry.hostileBreak)
return stage == LawStage.Planning ? PunishmentFit.HostileBreakPlanning : PunishmentFit.HostileBreakDidIt;
return stage == LawStage.Planning ? PunishmentFit.BreakPlanning : PunishmentFit.BreakDidIt;
}
public bool Fits(ActEntry entry, LawStage stage) =>
entry != null && entry.HasStage(stage) && fits != null && fits.Contains(FitOf(entry, stage));
public override IEnumerable<string> ConfigErrors()
{
foreach (string e in base.ConfigErrors())
yield return e;
if (workerClass == null || !typeof(PunishmentWorker).IsAssignableFrom(workerClass))
yield return "workerClass must be a PunishmentWorker";
if (fits == null || fits.Count == 0)
yield return "fits names no entry kind";
}
}
/// <summary>
/// Carries out a punishment. Enforcement calls Start from the queue a tick after the act was filed,
/// never inside a hook, and never while "Enforce laws" is off. Every call is wrapped by Enforcement in
/// a HookGuard, so a throw logs once and the game goes on.
///
/// One enforcement per case: when a case's active punishment is a different, unfinished one and the new
/// one doesn't run alongside, Enforcement calls the old worker's Stop first (it ends its job and keeps
/// LawCase.enforcer), then the new worker's Start, which takes over with the same enforcer.
/// </summary>
public class PunishmentWorker
{
public PunishmentDef def;
/// <summary>
/// Starts the punishment for the stage. Set the case's status (Enforcing, Jailed, or close it with
/// GameComponent_BlaxLaws.CloseCase), its enforcer and waitReason as needed. Default: nothing.
/// </summary>
public virtual void Start(LawCase c, Law law, LawStage stage)
{
}
/// <summary>
/// Every 250 ticks while this is the case's active punishment and the case isn't closed: retry a wait
/// (no bed, no enforcer, danger), re-issue a lost job, hand over to a capture, give an old bed back.
/// </summary>
public virtual void Sweep(LawCase c)
{
}
/// <summary>Every 2500 ticks while the case is Jailed under this punishment: the sentence check.</summary>
public virtual void SentenceSweep(LawCase c)
{
}
/// <summary>Ends this punishment's running job, because a later stage takes over or the law was deleted. Keeps LawCase.enforcer.</summary>
public virtual void Stop(LawCase c)
{
}
}
}

View File

@ -0,0 +1,24 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Guilty for N days: pawn.guilt.Notify_Guilty(days * 60000) (Pawn_GuiltTracker.cs:46-49), which vanilla
/// saves (:40-44) and counts down (:51-61); a longer guilt already on the pawn is never shortened. The
/// guilty icon shows, the arrest of a free colonist is always accepted (Pawn.cs:4087), and executing or
/// banishing it costs the colony the mildest thoughts (ThoughtUtility.cs:27-31;
/// PawnDiedOrDownedThoughtsUtility.cs:214-232). Runs alongside; closes the case as Guilty when nothing
/// else runs for it. Design: "Warn and guilty".
/// </summary>
public class PunishmentWorker_Guilty : PunishmentWorker
{
public override void Start(LawCase c, Law law, LawStage stage)
{
if (c?.offender == null || law == null)
return;
Guilt.AtLeast(c.offender, law.DaysTicks);
if (!c.IsClosed && c.activePunishment.NullOrEmpty())
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Guilty);
}
}
}

View File

@ -0,0 +1,102 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Subdue (design: "Subdue"): the BlaxLaws_Subdue job while the offender is still in its break. After the
/// break a did-it Subdue row warns and a planning one closes as "break ended". A child (Biotech) is never
/// beaten: it is warned (a Subdue row has no days). A break hostile to the colony (berserk, checked on
/// the live state) never gets it: the pawn fights back, so it is warned. A slave is subdued like a
/// colonist. A subdue that meets danger is called off; the sweep starts it again after the fight.
/// </summary>
public class PunishmentWorker_Subdue : PunishmentWorker
{
public override void Start(LawCase c, Law law, LawStage stage)
{
Pawn o = c?.offender;
if (o == null || c.IsClosed || o.Dead || SubdueFlow.Runs(c))
return;
if (DlcSupport.IsChild(o))
{
SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedChild");
return;
}
if (o.Downed && c.status == CaseStatus.Enforcing)
{
// The earlier stage's subdue downed it: this stage's subdue is done too.
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Subdued);
return;
}
if (o.Downed || !SubdueFlow.InBreak(c))
{
SubdueFlow.BreakOver(c);
return;
}
if (Enforcers.FightsBack(o))
{
SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedFightsBack");
return;
}
SubdueFlow.TryIssue(c, EnforcerNeed.Subdue);
}
public override void Sweep(LawCase c)
{
if (c == null || c.IsClosed)
return;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (!BlaxLawsMod.S.enforceLaws)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.NotEnforced);
return;
}
Pawn o = c.offender;
if (o == null || o.Dead)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.OffenderGone);
return;
}
if (SubdueFlow.Runs(c))
{
// A raid or a berserk colonist since the start: the warden is called off and the case waits.
SubdueFlow.CallOffInDanger(c);
return;
}
// A did-it Warn, Guilty or Subdue queued for next tick runs now, before anything below closes the case.
SubdueFlow.RunQueuedAlongside(c, sameToo: true);
if (c.IsClosed || SubdueFlow.Runs(c))
return;
// A later stage with another punishment dispatches next tick and takes over (as Enforcement.Sweep's
// break-ended close waits for it).
if (SubdueFlow.HandOverDue(c))
return;
if (o.Downed && c.status == CaseStatus.Enforcing)
{
// Downed while the enforcer was on it, by a hit or anything else: the break is over.
comp?.CloseCase(c, CaseOutcomes.Subdued);
return;
}
if (o.Downed || !SubdueFlow.InBreak(c))
{
SubdueFlow.BreakOver(c);
return;
}
if (Enforcers.FightsBack(o))
{
SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedFightsBack");
return;
}
// A lost subdue (the enforcer got hungry, drafted, downed, or the game was loaded) starts again.
SubdueFlow.TryIssue(c, EnforcerNeed.Subdue);
}
public override void Stop(LawCase c)
{
SubdueFlow.End(c);
if (c != null && !c.IsClosed)
c.status = CaseStatus.Open;
}
}
}

View File

@ -0,0 +1,93 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Subdue then jail (design: "Subdue"): the subdue job, and in the tick the hit downs the target, a
/// vanilla Capture to a prisoner bed at the front of the enforcer's queue (JailFlow.CaptureAfterSubdue).
/// From then on the case runs as Jail: activePunishment becomes "Jail" and PunishmentWorker_Jail sweeps
/// it. It jails without the beating when the break is over, when the pawn is already down, when its live
/// break fights back (the jail then waits), for a child (Biotech), and when the beating gives up. A slave
/// is never jailed in this release: subdued while in a break, else warned.
/// </summary>
public class PunishmentWorker_SubdueThenJail : PunishmentWorker
{
public override void Start(LawCase c, Law law, LawStage stage)
{
Pawn o = c?.offender;
if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed)
return;
if (SubdueFlow.Runs(c) || JailFlow.ArrestRuns(c))
return;
if (DlcSupport.IsSlave(o))
{
JailFlow.SlaveFallback(c);
return;
}
// Conviction: guilt for the sentence when the case is filed; renewed right before the capture.
Guilt.AtLeast(o, JailFlow.SentenceTicks(c));
if (JailsWithoutBeating(c))
{
JailFlow.Become(c);
JailFlow.TryArrest(c, ignoreHold: false);
return;
}
SubdueFlow.TryIssue(c, EnforcerNeed.SubdueAndArrest);
}
public override void Sweep(LawCase c)
{
if (c == null || c.IsClosed)
return;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (!BlaxLawsMod.S.enforceLaws)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.NotEnforced);
return;
}
Pawn o = c.offender;
if (o == null || o.Dead)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.OffenderGone);
return;
}
if (SubdueFlow.Runs(c))
{
// A raid or a berserk colonist since the start: the warden is called off and the case waits.
SubdueFlow.CallOffInDanger(c);
return;
}
if (DlcSupport.IsSlave(o))
{
JailFlow.SlaveFallback(c);
return;
}
if (JailsWithoutBeating(c))
{
JailFlow.Become(c);
JailFlow.TryArrest(c, ignoreHold: false);
return;
}
SubdueFlow.TryIssue(c, EnforcerNeed.SubdueAndArrest);
}
public override void SentenceSweep(LawCase c) => Sentences.Check(c);
public override void Stop(LawCase c)
{
SubdueFlow.End(c);
JailFlow.EndArrest(c);
if (c != null && !c.IsClosed && c.status != CaseStatus.Jailed)
c.status = CaseStatus.Open;
}
/// <summary>Down already, the break over, a live break that fights back, or a child: jail without a beating.</summary>
private static bool JailsWithoutBeating(LawCase c)
{
Pawn o = c.offender;
return o.Downed || DlcSupport.IsChild(o) || Enforcers.FightsBack(o) || !SubdueFlow.InBreak(c);
}
}
}

View File

@ -0,0 +1,20 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Warn: the case's message is the record (CaseMessages.Filed, posted by Enforcement at dispatch). Closes
/// the case as Warned once its stage is done, unless an earlier stage's punishment still runs beside it
/// ("Warn and Guilty run alongside"). A later did-it act reopens a closed break case (CaseFiler).
/// Design: "Warn and guilty".
/// </summary>
public class PunishmentWorker_Warn : PunishmentWorker
{
public override void Start(LawCase c, Law law, LawStage stage)
{
if (c == null || c.IsClosed || !c.activePunishment.NullOrEmpty())
return;
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Warned);
}
}
}

View File

@ -0,0 +1,491 @@
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.Sound;
namespace BlaxLaws
{
/// <summary>
/// The subdue part of a case (design: "Subdue"): who is sent, what happens when the pawn goes down or the
/// beating gives up, and what a Subdue row does when the break is already over. The Subdue and "Subdue
/// then jail" workers and JobDriver_Subdue call in here.
/// </summary>
public static class SubdueFlow
{
/// <summary>
/// The offender is still in the break the case is about: the recorded break for a break case, any
/// break for a case outside one (a slave's jail row falls back to subdue only while it is in a break).
/// </summary>
public static bool InBreak(LawCase c)
{
Pawn o = c?.offender;
if (o == null || o.Dead)
return false;
return c.IsBreakCase ? CaseFiler.StillInBreak(c) : o.InMentalState;
}
/// <summary>The case's enforcer runs the subdue job on the offender right now.</summary>
public static bool Runs(LawCase c) =>
c?.enforcer != null && c.offender != null && EnforcerJobs.Runs(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender);
/// <summary>The open case whose subdue this enforcer carries out on this target, or null.</summary>
public static LawCase CaseFor(Pawn enforcer, Pawn target)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || enforcer == null || target == null)
return null;
IReadOnlyList<LawCase> list = comp.CasesOf(target);
for (int i = list.Count - 1; i >= 0; i--)
{
LawCase c = list[i];
if (!c.IsClosed && c.enforcer == enforcer && IsSubduePunishment(c.activePunishment))
return c;
}
return null;
}
/// <summary>"Subdue" or "Subdue then jail".</summary>
public static bool IsSubduePunishment(string defName) =>
defName != null && (defName == BlaxLawsDefOf.Subdue?.defName || defName == BlaxLawsDefOf.SubdueThenJail?.defName);
/// <summary>
/// Sends an enforcer on the subdue job, or leaves the case waiting with its reason (danger, nobody
/// free, nobody able: a letter once). Returns whether the job runs.
/// </summary>
public static bool TryIssue(LawCase c, EnforcerNeed need)
{
Pawn o = c?.offender;
if (o == null || !o.Spawned)
{
WaitReasons.Set(c, WaitReasons.Away);
return false;
}
if (Enforcers.DangerBlocks(o))
{
WaitReasons.Set(c, WaitReasons.Danger);
return false;
}
Pawn e = Enforcers.Pick(c, need, out string reason);
if (e == null)
{
if (WaitReasons.Set(c, reason) && reason == WaitReasons.NoEnforcer && CaseLetters.Once(c, CaseLetters.KindNoEnforcer))
CaseLetters.NoEnforcer(c);
return false;
}
return TryStartWith(c, e);
}
/// <summary>
/// Starts the subdue job with this enforcer, no pick and no danger check: the hook point for a subdue
/// the player starts ("Subdue a pawn that fights back", Enforcement step 3). Returns whether it runs.
/// Step 3 must also leave its offender out of CallOffInDanger.
/// </summary>
public static bool TryStartWith(LawCase c, Pawn enforcer)
{
if (c?.offender == null || enforcer == null || BlaxLawsDefOf.BlaxLaws_Subdue == null)
return false;
Job job = JobMaker.MakeJob(BlaxLawsDefOf.BlaxLaws_Subdue, c.offender);
c.enforcer = enforcer;
c.status = CaseStatus.Enforcing;
c.waitReason = null;
if (EnforcerJobs.Start(enforcer, job))
return true;
WaitReasons.Set(c, WaitReasons.Busy);
return false;
}
/// <summary>Ends the running subdue job of the case, if any. Keeps the enforcer for a hand-over.</summary>
public static void End(LawCase c)
{
if (c?.enforcer != null && c.offender != null)
EnforcerJobs.End(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender);
}
/// <summary>
/// A running subdue meets danger (a raid lands, a colonist goes berserk): the job ends and the case waits
/// for Danger, so the sweep sends someone again after the fight. The job is player-forced, so vanilla
/// never pulls the enforcer off it when it is hit (Pawn_JobTracker.cs:982) and the hostility response
/// skips it (PawnUtility.cs:377-385). Returns whether it was called off.
/// </summary>
public static bool CallOffInDanger(LawCase c)
{
if (!Runs(c) || !Enforcers.DangerBlocks(c.offender))
return false;
End(c);
WaitReasons.Set(c, WaitReasons.Danger);
return true;
}
/// <summary>
/// A later stage of the case is queued and dispatches within a tick (a did-it act filed during the
/// subdue), and its punishment replaces the subdue (a Jail). The subdue then leaves the case open, so
/// Enforcement hands over to that stage's punishment (design: "One enforcement per case") instead of the
/// stage being dropped on a closed case. A queued Warn, Guilty or same subdue is no hand-over:
/// RunQueuedAlongside carries it out before the case closes.
/// </summary>
public static bool HandOverDue(LawCase c)
{
if (c == null || !BlaxLawsMod.S.enforceLaws || !Enforcement.IsQueued(c, CaseTask.Punish))
return false;
foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt })
{
if (c.HasPunished(s))
continue;
PunishmentDef p = c.LawFor(s)?.PunishmentDef;
if (p != null && !p.runsAlongside && p.defName != c.activePunishment)
return true;
}
return false;
}
/// <summary>
/// Before the subdue closes its case: a queued stage that runs alongside (Warn, Guilty) runs now, and with
/// sameToo one with this same subdue punishment too, so it is carried out and logged instead of dropped
/// on the closed case. While the subdue job runs, a same-punishment stage starts nothing; from the sweep
/// its Start closes the downed offender's case as Subdued. A stage with another punishment (a Jail)
/// stays queued and HandOverDue keeps the case open for it.
/// </summary>
internal static void RunQueuedAlongside(LawCase c, bool sameToo)
{
if (c == null || c.IsClosed || !BlaxLawsMod.S.enforceLaws)
return;
string active = c.activePunishment;
Enforcement.DispatchNow(c, p => p.runsAlongside || (sameToo && p.defName == active));
}
/// <summary>Closes the case as Warned with a message saying why it wasn't a subdue.</summary>
public static void WarnInstead(LawCase c, string messageKey)
{
if (c == null || c.IsClosed)
return;
CaseMessages.Post(c, messageKey.Translate(c.OffenderLabel));
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Warned);
}
/// <summary>
/// The break is over before a subdue could act: a planning case closes as "break ended" (nothing was
/// done), a did-it Subdue row warns (design: "Defaults I picked").
/// </summary>
public static void BreakOver(LawCase c)
{
if (c == null || c.IsClosed)
return;
if (c.activeStage == LawStage.Planning)
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.BreakEnded);
else
WarnInstead(c, "BlaxLaws_MsgWarnedAfterBreak");
}
/// <summary>
/// The hit downed the offender. Subdue closes the case; "Subdue then jail" queues the vanilla Capture
/// at the front of the enforcer's queue (JailFlow.CaptureAfterSubdue). Called by the driver inside
/// its toil, so nothing here starts a job. A later stage already queued (HandOverDue) keeps the case open
/// for its hand-over.
/// </summary>
internal static void OnDowned(LawCase c, Pawn enforcer)
{
if (c == null || c.IsClosed)
return;
if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName)
{
JailFlow.CaptureAfterSubdue(c, enforcer);
return;
}
CaseMessages.Post(c, "BlaxLaws_MsgSubdued".Translate(c.OffenderLabel, enforcer.LabelShort));
RunQueuedAlongside(c, sameToo: Runs(c));
if (c.IsClosed)
return;
if (HandOverDue(c))
return; // The queued stage takes over next tick: a Jail captures the downed offender.
GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Subdued);
}
/// <summary>
/// Three hits in a row caused no pain, or the ceiling was reached: one message. Subdue closes the case
/// as not subdued; "Subdue then jail" arrests instead, from the next sweep (the driver is still inside
/// its toil, so no job starts here). A later stage already queued (HandOverDue) keeps the case open for
/// its hand-over.
/// </summary>
internal static void OnGaveUp(LawCase c, Pawn enforcer)
{
if (c == null || c.IsClosed)
return;
CaseMessages.Post(c, "BlaxLaws_MsgSubdueGaveUp".Translate(c.OffenderLabel, enforcer.LabelShort));
if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName)
{
JailFlow.Become(c);
return;
}
// A queued same-punishment stage is no hand-over: it is done here while the job still runs (or dropped
// with the closed case), so it never starts a second beating of a pawn the subdue just gave up on.
RunQueuedAlongside(c, sameToo: Runs(c));
if (c.IsClosed)
return;
if (HandOverDue(c))
return; // The queued stage takes over next tick.
GameComponent_BlaxLaws.Instance?.CloseCase(c, EnforcementOutcomes.NotSubdued);
}
}
/// <summary>
/// One hit of the subdue (design: "Subdue", the hit). Blunt damage on a random part of the torso or the
/// limbs: not missing, depth Outside, skin covered, not solid, not in the head or neck branch, not
/// carrying or below an added part (HediffSet.cs:1225; an injury there gives no pain, Hediff_Injury.cs:
/// 132-135). The injury is 4 to 8 points, capped so the part keeps at least half its HP and the pawn's
/// injuries, old scars included, stay at nine tenths of the sum that kills it: vanilla kills a pawn whose
/// injury severities add up to 150 times its health scale (Pawn_HealthTracker.cs:73, 705-719), and the
/// part caps alone add up to more (a human's torso and limbs to about 235). A normal adult goes down at
/// about 64 points of bruises, one with halved pain (Biotech's reduced pain gene) at about 128; one that isn't
/// down at the total cap gets the "no pain" ending.
///
/// The caps hold whatever vanilla multiplies in on the way from the DamageInfo to the injury: the race's
/// damage multiplier, rounded to a whole number (Thing.cs:1487-1497), the genes' and hediffs' damage
/// factors (Pawn.cs:1919-1927), and IncomingDamageFactor, which applies even with armour ignored
/// (DamageWorker_AddInjury.cs:164-167; Tough is 0.5). The amount is divided by all of them; with
/// propagation off the injury's severity is exactly what is left (:181-183, 199-221). The part's HP is
/// counted unrounded: HediffSet.GetPartHealth rounds to a whole point (HediffSet.cs:581-605), which
/// would let a hit take a part with an odd maximum (a foot has 25) half a point below its share. A
/// rounding or another mod's damage factor that still takes the hit past a cap is healed back on the
/// hit's own bruise (Hediff_Injury.Heal, Hediff_Injury.cs:201-212).
///
/// SetAllowDamagePropagation(false) makes AddInjury skip ApplySpecialEffectsToPart, so there is no inner
/// bone crack and no stun (DamageWorker_Blunt.cs:18-78): Blunt on a skin-covered, non-solid part is a
/// Bruise (HealthUtility.cs:519-531). instigatorGuilty false skips the guilt for harming a player pawn
/// (Pawn_HealthTracker.cs:323-329); TakeDamage sets no meleeThreat, so the target never turns on the
/// enforcer, and gives the target HarmedMe toward it (:379-382).
/// </summary>
public static class SubdueHits
{
public const float MinDamage = 4f;
public const float MaxDamage = 8f;
/// <summary>A part keeps at least this share of its HP.</summary>
public const float KeepHealthShare = 0.5f;
/// <summary>The pawn's injuries stay at or below this share of the injury sum that kills it.</summary>
public const float LethalShare = 0.9f;
public const float MeleeXpPerHit = 40f;
private static readonly List<BodyPartRecord> parts = new List<BodyPartRecord>();
/// <summary>
/// Hits once. Returns the pain the new injury carries before pain factors (its PainOffset), or 0 when
/// nothing could be hit: every allowed part at its cap, the pawn at the total cap, or a damage factor of 0.
/// </summary>
public static float Hit(Pawn enforcer, Pawn target)
{
if (enforcer == null || target == null || target.Dead || !target.Spawned)
return 0f;
BodyPartRecord part = PickPart(target, out float headroom);
if (part == null)
return 0f;
var dinfo = new DamageInfo(DamageDefOf.Blunt, 1f, armorPenetration: 0f, angle: -1f, instigator: enforcer,
hitPart: part, weapon: enforcer.def, category: DamageInfo.SourceCategory.ThingOrUnknown, intendedTarget: target,
instigatorGuilty: false);
dinfo.SetAllowDamagePropagation(false);
dinfo.SetIgnoreArmor(true);
float factor = DamageFactor(target, dinfo);
if (factor <= 0.001f)
return 0f;
float injury = Mathf.Min(Rand.Range(MinDamage, MaxDamage), headroom);
if (injury < 0.5f)
return 0f;
dinfo.SetAmount(injury / factor);
DamageWorker.DamageResult result = target.TakeDamage(dinfo);
KeepShare(target, part, result);
if (enforcer.Spawned)
enforcer.Drawer.Notify_MeleeAttackOn(target);
if (target.Spawned)
SoundDefOf.Pawn_Melee_Punch_HitPawn.PlayOneShot(new TargetInfo(target.Position, target.Map));
enforcer.skills?.Learn(SkillDefOf.Melee, MeleeXpPerHit);
float pain = 0f;
if (result?.hediffs != null)
{
foreach (Hediff h in result.hediffs)
pain += h.PainOffset;
}
return pain;
}
/// <summary>
/// What vanilla multiplies a damage amount by before it becomes the injury's severity, armour ignored:
/// the race's multiplier for the damage (Thing.cs:1487-1497, which also rounds the amount), the genes'
/// factor with Biotech and the hediffs' factor (Pawn.cs:1919-1927), and IncomingDamageFactor for
/// external violence (DamageWorker_AddInjury.cs:164-167).
/// </summary>
public static float DamageFactor(Pawn target, DamageInfo dinfo)
{
float factor = 1f;
List<DamageMultiplier> multipliers = target.def.damageMultipliers;
if (multipliers != null)
{
for (int i = 0; i < multipliers.Count; i++)
{
if (multipliers[i].damageDef == dinfo.Def)
factor *= multipliers[i].multiplier;
}
}
if (ModsConfig.BiotechActive && target.genes != null)
factor *= target.genes.FactorForDamage(dinfo);
factor *= target.health.FactorForDamage(dinfo);
if (dinfo.Def.ExternalViolenceFor(target))
factor *= target.GetStatValue(StatDefOf.IncomingDamageFactor);
return factor;
}
/// <summary>
/// After the hit: when the part ended below its share or the pawn past the total cap anyway (the race
/// multiplier's rounding, or a damage factor another mod adds), the hit's bruise there heals back the
/// difference. The bruise is the new injury, or the one it merged into (HediffSet.cs:325-331;
/// Hediff_Injury.cs:214-221).
/// </summary>
private static void KeepShare(Pawn target, BodyPartRecord part, DamageWorker.DamageResult result)
{
if (target.Dead)
return;
float deficit = Mathf.Max(Floor(target, part) - PartHealth(target, part), -RoomToLive(target));
if (deficit <= 0f)
return;
List<Hediff> set = target.health.hediffSet.hediffs;
Hediff_Injury bruise = null;
HediffDef def = null;
if (result?.hediffs != null)
{
foreach (Hediff h in result.hediffs)
{
if (h is Hediff_Injury injury && injury.Part == part)
{
def = injury.def;
if (set.Contains(injury))
bruise = injury;
}
}
}
for (int i = set.Count - 1; bruise == null && def != null && i >= 0; i--)
{
if (set[i] is Hediff_Injury merged && merged.Part == part && merged.def == def && !merged.IsPermanent() && !merged.IsTended())
bruise = merged;
}
bruise?.Heal(Mathf.Min(deficit, bruise.Severity));
}
/// <summary>
/// A part the subdue may hit, weighted by coverage, and how much injury it can still take: its own
/// headroom, at most what the pawn has left below the total cap. Null when no part or no total is left.
/// </summary>
public static BodyPartRecord PickPart(Pawn target, out float headroom)
{
headroom = 0f;
HediffSet hs = target?.health?.hediffSet;
if (hs == null)
return null;
float room = RoomToLive(target);
if (room < 1f)
return null;
parts.Clear();
try
{
foreach (BodyPartRecord part in hs.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Outside))
{
if (Allowed(target, part) && Headroom(target, part) >= 1f)
parts.Add(part);
}
if (!parts.TryRandomElementByWeight(p => p.coverageAbs, out BodyPartRecord chosen))
return null;
headroom = Mathf.Min(Headroom(target, chosen), room);
return chosen;
}
finally
{
parts.Clear();
}
}
/// <summary>A part of the torso or the limbs the subdue may ever hit (see the class summary).</summary>
public static bool Allowed(Pawn target, BodyPartRecord part)
{
HediffSet hs = target.health.hediffSet;
if (part == null || part.depth != BodyPartDepth.Outside || part.coverageAbs <= 0f)
return false;
if (hs.PartIsMissing(part) || part.def.IsSolid(part, hs.hediffs) || !part.def.IsSkinCovered(part, hs))
return false;
if (hs.PartOrAnyAncestorHasDirectlyAddedParts(part))
return false;
return !InHeadOrNeck(target, part);
}
/// <summary>The part sits in the head: in the FullHead or UpperHead group, or in the brain's branch below the core part (the neck).</summary>
public static bool InHeadOrNeck(Pawn target, BodyPartRecord part)
{
for (BodyPartRecord p = part; p != null; p = p.parent)
{
if (p.IsInGroup(BodyPartGroupDefOf.FullHead) || p.IsInGroup(BodyPartGroupDefOf.UpperHead))
return true;
}
BodyPartRecord branch = TopBranch(part);
if (branch.parent == null)
return false;
foreach (BodyPartRecord brain in target.RaceProps.body.GetPartsWithTag(BodyPartTagDefOf.ConsciousnessSource))
{
if (TopBranch(brain) == branch)
return true;
}
return false;
}
/// <summary>HP the part may still lose and keep its share: current HP minus half the maximum.</summary>
public static float Headroom(Pawn target, BodyPartRecord part) => PartHealth(target, part) - Floor(target, part);
/// <summary>
/// Injury the pawn can still take before its injuries, old scars included, reach the total cap: the
/// share of the sum vanilla kills at (LethalDamageThreshold, Pawn_HealthTracker.cs:73, 705-719).
/// </summary>
public static float RoomToLive(Pawn target)
{
float sum = 0f;
List<Hediff> list = target.health.hediffSet.hediffs;
for (int i = 0; i < list.Count; i++)
{
if (list[i] is Hediff_Injury injury)
sum += injury.Severity;
}
return target.health.LethalDamageThreshold * LethalShare - sum;
}
/// <summary>The HP the part always keeps: half its maximum (BodyPartDef.cs:138-141, scaled by the pawn's health scale).</summary>
public static float Floor(Pawn target, BodyPartRecord part) => part.def.GetMaxHealth(target) * KeepHealthShare;
/// <summary>
/// The part's HP as HediffSet.GetPartHealth counts it, its maximum minus the injuries on it, 0 when it
/// is missing (HediffSet.cs:581-605), but not rounded to a whole point.
/// </summary>
public static float PartHealth(Pawn target, BodyPartRecord part)
{
float hp = part.def.GetMaxHealth(target);
List<Hediff> list = target.health.hediffSet.hediffs;
for (int i = 0; i < list.Count; i++)
{
Hediff h = list[i];
if (h.Part != part)
continue;
if (h is Hediff_MissingPart)
return 0f;
if (h is Hediff_Injury injury)
hp = injury.destroysBodyParts ? hp - injury.Severity : Mathf.Max(hp - injury.Severity, 1f);
}
return Mathf.Max(hp, 0f);
}
/// <summary>The part's ancestor right below the core part (the core part itself for the core).</summary>
private static BodyPartRecord TopBranch(BodyPartRecord part)
{
BodyPartRecord p = part;
while (p.parent != null && p.parent.parent != null)
p = p.parent;
return p;
}
}
}

View File

@ -0,0 +1,104 @@
using System;
using HarmonyLib;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The subdue job never enters a save (design: "The subdue job never enters a save"). A saved job with a
/// missing JobDef would break the enforcer after removal: Job.ExposeData saves the def (Job.cs:505), and
/// Pawn_JobTracker.ExposeData (Pawn_JobTracker.cs:90-109, virtual, deep-saves curJob, curDriver and the
/// queue) would then end a job whose def is null.
///
/// Prefix, only while Scribe.mode is Saving and only when the tracker holds a BlaxLaws_Subdue job: hides
/// curJob and curDriver from the scribe and swaps the queue for a copy without subdue entries (a
/// backstop: the JobDef isn't suspendable, so vanilla never queues it). The finalizer puts everything
/// back, also when saving throws. It returns void, so Harmony rethrows with the full stack trace.
/// </summary>
[HarmonyPatch(typeof(Pawn_JobTracker), nameof(Pawn_JobTracker.ExposeData))]
public static class Patch_Pawn_JobTracker_ExposeData
{
public sealed class Hidden
{
public bool hidCurrent;
public Job curJob;
public JobDriver curDriver;
public JobQueue queue;
}
public static void Prefix(Pawn_JobTracker __instance, out Hidden __state)
{
__state = null;
try
{
if (Scribe.mode != LoadSaveMode.Saving || __instance == null)
return;
JobDef ours = BlaxLawsDefOf.BlaxLaws_Subdue;
if (ours == null)
return;
bool current = __instance.curJob?.def == ours;
bool queued = AnyQueued(__instance.jobQueue, ours);
if (!current && !queued)
return;
var hidden = new Hidden();
if (current)
{
hidden.hidCurrent = true;
hidden.curJob = __instance.curJob;
hidden.curDriver = __instance.curDriver;
__instance.curJob = null;
__instance.curDriver = null;
}
if (queued)
{
hidden.queue = __instance.jobQueue;
var filtered = new JobQueue();
foreach (QueuedJob q in hidden.queue)
{
if (q?.job != null && q.job.def != ours)
filtered.EnqueueLast(q.job, q.tag);
}
__instance.jobQueue = filtered;
}
__state = hidden;
}
catch (Exception e)
{
HookGuard.Fail("Hiding the subdue job from the save", e);
}
}
public static void Finalizer(Pawn_JobTracker __instance, Hidden __state)
{
if (__state == null || __instance == null)
return;
try
{
if (__state.hidCurrent)
{
__instance.curJob = __state.curJob;
__instance.curDriver = __state.curDriver;
}
if (__state.queue != null)
__instance.jobQueue = __state.queue;
}
catch (Exception e)
{
HookGuard.Fail("Restoring the subdue job after the save", e);
}
}
private static bool AnyQueued(JobQueue queue, JobDef def)
{
if (queue == null)
return false;
for (int i = 0; i < queue.Count; i++)
{
if (queue[i]?.job?.def == def)
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,77 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Why enforcement waits: the Keyed keys LawCase.waitReason holds and the Cases tab shows
/// (WaitReasons.Label). A case that waits is Open; the 250-tick sweep retries it, a case waiting for a
/// prisoner bed only every 2500 ticks (design: "Enforcement runs a tick later").
/// </summary>
public static class WaitReasons
{
/// <summary>Hostiles threaten the offender's map (a raid, a berserk colonist): nobody is sent.</summary>
public const string Danger = "BlaxLaws_Wait_Danger";
/// <summary>Nobody on the map can ever enforce it (no warden in "Wardens only", nobody able): the player has to act.</summary>
public const string NoEnforcer = "BlaxLaws_Wait_NoEnforcer";
/// <summary>Enforcers exist but none is free now (asleep, on a rescue, in a ritual, out of reach).</summary>
public const string Busy = "BlaxLaws_Wait_Busy";
/// <summary>No prisoner bed the enforcer can take the offender to.</summary>
public const string NoBed = "BlaxLaws_Wait_NoBed";
/// <summary>Someone else holds the offender or the bed (a doctor's rescue): the arrest waits, no reservation error.</summary>
public const string Reserved = "BlaxLaws_Wait_Reserved";
/// <summary>The offender's break is hostile to the colony (berserk): the arrest waits until it ends or the pawn is down.</summary>
public const string HostileBreak = "BlaxLaws_Wait_HostileBreak";
/// <summary>A role holder or a mechanitor with mechs: Laws doesn't arrest it on its own; "Arrest now" does.</summary>
public const string Hold = "BlaxLaws_Wait_Hold";
/// <summary>The offender isn't on a map (carried, in a caravan).</summary>
public const string Away = "BlaxLaws_Wait_Away";
/// <summary>The reason's text, or "" for none.</summary>
public static string Label(string reason)
{
if (reason.NullOrEmpty())
return "";
return reason.CanTranslate() ? reason.Translate().ToString() : reason;
}
/// <summary>
/// Puts the case back to Open with the reason. Returns true when the reason changed, so a letter goes
/// out once per wait and not on every sweep.
/// </summary>
public static bool Set(LawCase c, string reason)
{
if (c == null)
return false;
bool changed = c.waitReason != reason;
c.status = CaseStatus.Open;
c.waitReason = reason;
return changed;
}
}
/// <summary>
/// Outcome keys of this package beside CaseOutcomes. Saved as strings; the label is
/// "BlaxLaws_Outcome_" + key (CaseOutcomes.Label), from BlaxLaws_Enforcement.xml.
/// </summary>
public static class EnforcementOutcomes
{
/// <summary>The subdue gave up: three hits in a row caused no pain (go-juice, painkillers, every part at its cap).</summary>
public const string NotSubdued = "NotSubdued";
/// <summary>A jailed pawn left the map before its sentence was served.</summary>
public const string Escaped = "Escaped";
/// <summary>A jailed pawn died.</summary>
public const string Died = "Died";
/// <summary>The offender became a prisoner some other way (arrested by hand, another mod): Laws never touches it.</summary>
public const string AlreadyPrisoner = "AlreadyPrisoner";
}
}

View File

@ -0,0 +1,359 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// All Blax Laws state of one game: the lawbook rows and the cases (design: "Lawbook and cases in one
/// GameComponent"). Laws are colony policy across every map, caravan and world pawn, so this is a
/// GameComponent. Game.FillComponents adds it to a new game and after loading (Verse/Game.cs:345,
/// 443-446, 472-489), so a save made without Laws loads with an empty book. After a plain unsubscribe
/// the node loads as null with exactly 2 errors and FillComponents drops it (Verse/Game.cs:474).
///
/// Read through the properties and lookups. Rows change only through Lawbook, cases only through
/// CaseFiler, Enforcement and the punishment workers (CloseCase). Nothing of Laws is stored on vanilla
/// objects, and no Laws def enters a vanilla save list.
/// </summary>
public class GameComponent_BlaxLaws : GameComponent
{
private List<Law> laws = new List<Law>();
private int nextLawId = 1;
private List<LawCase> cases = new List<LawCase>();
private int nextCaseId = 1;
/// <summary>A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick.</summary>
private int saveToken;
// Not saved: cases by offender, rebuilt on load and kept on every add and prune.
private readonly Dictionary<Pawn, List<LawCase>> byOffender = new Dictionary<Pawn, List<LawCase>>();
// Weak, so the main menu never keeps the last game and its pawns alive.
private static readonly System.WeakReference<GameComponent_BlaxLaws> cached = new System.WeakReference<GameComponent_BlaxLaws>(null);
private static readonly System.WeakReference<Game> cachedGame = new System.WeakReference<Game>(null);
private static readonly List<LawCase> EmptyCases = new List<LawCase>();
public GameComponent_BlaxLaws()
{
}
/// <summary>Called by the game for a new game and for a loaded one, before anything of the save is read.</summary>
public GameComponent_BlaxLaws(Game game) : this()
{
// The hot-path flags and the queue belong to the last game: clear them before this one's hooks run.
Watch.Clear();
Enforcement.Reset();
saveToken = NewToken();
if (game != null)
Remember(this, game);
}
/// <summary>The component of the running game, or null when no game is loaded.</summary>
public static GameComponent_BlaxLaws Instance
{
get
{
Game game = Current.Game;
if (game == null)
return null;
if (cachedGame.TryGetTarget(out Game g) && g == game && cached.TryGetTarget(out GameComponent_BlaxLaws c) && c != null)
return c;
GameComponent_BlaxLaws found = game.GetComponent<GameComponent_BlaxLaws>();
if (found != null)
Remember(found, game);
return found;
}
}
private static void Remember(GameComponent_BlaxLaws comp, Game game)
{
cached.SetTarget(comp);
cachedGame.SetTarget(game);
}
private static int NewToken() => new Random(Environment.TickCount ^ Guid.NewGuid().GetHashCode()).Next(1, int.MaxValue);
// ---- reads ---------------------------------------------------------------------------
/// <summary>The lawbook rows in display order. Do not change the list; use Lawbook.</summary>
public IReadOnlyList<Law> Laws => laws;
/// <summary>Every case, oldest first. Do not change the list.</summary>
public IReadOnlyList<LawCase> Cases => cases;
public int NextLawId => nextLawId;
public int NextCaseId => nextCaseId;
public int SaveToken => saveToken;
public Law LawById(int id)
{
if (id <= 0)
return null;
for (int i = 0; i < laws.Count; i++)
{
if (laws[i].id == id)
return laws[i];
}
return null;
}
public LawCase CaseById(int id)
{
if (id <= 0)
return null;
for (int i = cases.Count - 1; i >= 0; i--)
{
if (cases[i].id == id)
return cases[i];
}
return null;
}
/// <summary>The cases filed against this pawn, oldest first. Empty for null or a pawn without cases.</summary>
public IReadOnlyList<LawCase> CasesOf(Pawn pawn)
{
if (pawn != null && byOffender.TryGetValue(pawn, out List<LawCase> list))
return list;
return EmptyCases;
}
/// <summary>True while any case isn't closed. The tick's fast path reads it.</summary>
public bool AnyOpenCase
{
get
{
for (int i = cases.Count - 1; i >= 0; i--)
{
if (!cases[i].IsClosed)
return true;
}
return false;
}
}
/// <summary>The cases that aren't closed, as a new list (safe to change cases while walking it).</summary>
public List<LawCase> OpenCases()
{
var result = new List<LawCase>();
foreach (LawCase c in cases)
{
if (!c.IsClosed)
result.Add(c);
}
return result;
}
/// <summary>Open cases a row runs for, for "deleting a law with open cases asks first and names the count".</summary>
public int OpenCaseCount(Law law)
{
if (law == null)
return 0;
int n = 0;
foreach (LawCase c in cases)
{
if (!c.IsClosed && (c.planningLawId == law.id || c.didItLawId == law.id))
n++;
}
return n;
}
/// <summary>
/// The pawn's newest case outside a break whose did-it row is this one, open or closed, or null. The
/// cooldown reads it.
/// </summary>
public LawCase LatestActCaseOf(Pawn pawn, int lawId)
{
IReadOnlyList<LawCase> list = CasesOf(pawn);
for (int i = list.Count - 1; i >= 0; i--)
{
LawCase c = list[i];
if (!c.IsBreakCase && c.didItLawId == lawId)
return c;
}
return null;
}
/// <summary>Ticks two break start ticks may differ by and still name the same break (MentalState.age moves in steps of 30).</summary>
public const int BreakStartTolerance = 120;
/// <summary>The pawn's case for this break (same state def, started at the same tick), open or closed, or null.</summary>
public LawCase BreakCaseOf(Pawn pawn, string stateDefName, int breakStartTick)
{
if (stateDefName.NullOrEmpty())
return null;
IReadOnlyList<LawCase> list = CasesOf(pawn);
for (int i = list.Count - 1; i >= 0; i--)
{
LawCase c = list[i];
if (c.breakState == stateDefName && Math.Abs(c.breakStartTick - breakStartTick) <= BreakStartTolerance)
return c;
}
return null;
}
// ---- writes, for Lawbook, CaseFiler and Enforcement ----------------------------------------
internal int TakeLawId()
{
foreach (Law l in laws)
{
if (l.id >= nextLawId)
nextLawId = l.id + 1;
}
return nextLawId++;
}
internal int TakeCaseId()
{
if (cases.Count > 0 && cases[cases.Count - 1].id >= nextCaseId)
nextCaseId = cases[cases.Count - 1].id + 1;
return nextCaseId++;
}
internal void AddLaw(Law law) => laws.Add(law);
internal bool RemoveLaw(Law law) => laws.Remove(law);
internal void MoveLaw(Law law, int index)
{
if (!laws.Remove(law))
return;
laws.Insert(Math.Max(0, Math.Min(index, laws.Count)), law);
}
internal void AddCase(LawCase c)
{
cases.Add(c);
Index(c);
}
/// <summary>Closes the case with a CaseOutcomes key. A closed case is pruned after "Keep closed cases".</summary>
public void CloseCase(LawCase c, string outcome)
{
if (c == null)
return;
c.status = CaseStatus.Closed;
c.outcome = outcome;
c.closeTick = Find.TickManager?.TicksGame ?? 0;
c.activePunishment = null;
c.waitReason = null;
}
/// <summary>
/// Removes closed cases that closed more than the given ticks ago. Returns the number removed.
/// Runs on every save with "Keep closed cases".
/// </summary>
public int PruneClosedCases(int olderThanTicks)
{
int now = Find.TickManager?.TicksGame ?? 0;
int removed = cases.RemoveAll(c => c == null || (c.IsClosed && c.closeTick >= 0 && now - c.closeTick > olderThanTicks));
if (removed > 0)
RebuildIndex();
return removed;
}
private void Index(LawCase c)
{
if (c?.offender == null)
return;
if (!byOffender.TryGetValue(c.offender, out List<LawCase> list))
byOffender[c.offender] = list = new List<LawCase>();
list.Add(c);
}
private void RebuildIndex()
{
byOffender.Clear();
foreach (LawCase c in cases)
Index(c);
}
// ---- game hooks ----------------------------------------------------------------------
public override void GameComponentTick()
{
// The empty book costs one count and one field read per tick.
if (cases.Count == 0 && Enforcement.Pending == 0)
return;
try
{
Enforcement.Tick(this);
}
catch (Exception e)
{
HookGuard.Fail("Enforcement tick", e);
}
}
public override void FinalizeInit()
{
Remember(this, Current.Game);
// Log-once flags count per game, so a failure in a later game is not silent.
LawsLog.ResetOnce();
try
{
ActCatalogue.EnsureBuilt();
Watch.Rebuild();
Enforcement.Reset();
Enforcement.Refill(this);
}
catch (Exception e)
{
HookGuard.Fail("Game start", e);
}
}
// ---- save ----------------------------------------------------------------------------
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
try
{
PruneClosedCases(BlaxLawsMod.S.KeepClosedTicks);
}
catch (Exception e)
{
HookGuard.Fail("Pruning closed cases", e);
}
}
Scribe_Values.Look(ref saveToken, "saveToken");
Scribe_Values.Look(ref nextLawId, "nextLawId", 1);
Scribe_Collections.Look(ref laws, "laws", LookMode.Deep);
Scribe_Values.Look(ref nextCaseId, "nextCaseId", 1);
Scribe_Collections.Look(ref cases, "cases", LookMode.Deep);
if (Scribe.mode == LoadSaveMode.LoadingVars)
Remember(this, Current.Game);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
EnsureState();
}
/// <summary>Missing lists, null entries and ids that would repeat.</summary>
private void EnsureState()
{
laws ??= new List<Law>();
laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty());
cases ??= new List<LawCase>();
cases.RemoveAll(c => c == null);
if (saveToken == 0)
saveToken = NewToken();
foreach (Law l in laws)
{
if (l.id >= nextLawId)
nextLawId = l.id + 1;
}
foreach (LawCase c in cases)
{
if (c.id >= nextCaseId)
nextCaseId = c.id + 1;
}
RebuildIndex();
}
}
}

View File

@ -0,0 +1,50 @@
using System;
namespace BlaxLaws
{
/// <summary>
/// Every Harmony hook catches its own exceptions, so the vanilla method and every other mod's patch
/// always run (design: "Rules every feature follows"). The pattern, in every prefix, postfix and
/// finalizer body:
///
/// try { ... }
/// catch (Exception e) { HookGuard.Fail("hook C, Thing.Ingested", e); }
///
/// Hot hooks write the try/catch themselves; Run allocates a closure per call and is for cold paths
/// only (startup, UI, a sweep). A finalizer always returns void: one that returns an Exception makes
/// Harmony "throw ex" and cuts every other mod's stack trace. A prefix that must not skip vanilla
/// returns void too; a bool prefix returns true from its catch.
/// </summary>
public static class HookGuard
{
/// <summary>Logs the failure once per game under this key and swallows it.</summary>
public static void Fail(string where, Exception e) => LawsLog.Once(where, e);
/// <summary>Runs the body; a throw is logged once and swallowed.</summary>
public static void Run(string where, Action body)
{
try
{
body();
}
catch (Exception e)
{
Fail(where, e);
}
}
/// <summary>Runs the body and returns its value; a throw is logged once and gives the fallback.</summary>
public static T Run<T>(string where, Func<T> body, T fallback)
{
try
{
return body();
}
catch (Exception e)
{
Fail(where, e);
return fallback;
}
}
}
}

399
Source/BlaxLaws/Lawbook.cs Normal file
View File

@ -0,0 +1,399 @@
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Every write to the lawbook goes through here (design: "Lawbook tab", How), and so does the "most
/// specific row wins" match. Each write rebuilds Watch. Action, Option and Stage are a row's key: a write
/// that would make a second row with the same key is refused and names the existing row.
/// </summary>
public static class Lawbook
{
public const int MinDays = 1;
public const int MaxDays = 50;
private static readonly List<Law> NoLaws = new List<Law>();
/// <summary>The running game's rows, or an empty list without a game.</summary>
public static IReadOnlyList<Law> Laws => GameComponent_BlaxLaws.Instance?.Laws ?? NoLaws;
/// <summary>The default days of a severity: Minor 1, Moderate 3, Serious 5, Grave 10.</summary>
public static int DefaultDays(LawSeverity severity)
{
switch (severity)
{
case LawSeverity.Minor: return 1;
case LawSeverity.Moderate: return 3;
case LawSeverity.Serious: return 5;
default: return 10;
}
}
public static int ClampDays(int days) => days < MinDays ? MinDays : days > MaxDays ? MaxDays : days;
/// <summary>Null, "" and "@any" read as the same option (no option for a non-binge row, any drug for a binge row).</summary>
public static string NormalizeOption(string option) => option.NullOrEmpty() || option == DrugOptions.Any ? null : option;
// ---- lookups -------------------------------------------------------------------------
/// <summary>The row with this key, or null.</summary>
public static Law Find(string actKey, string option, LawStage stage)
{
foreach (Law l in Laws)
{
if (l.HasKey(actKey, option, stage))
return l;
}
return null;
}
/// <summary>The stages an entry offers (planning only for breaks; did it for linked breaks and every other entry).</summary>
public static IEnumerable<LawStage> StagesOf(ActEntry entry) => entry?.Stages ?? Enumerable.Empty<LawStage>();
/// <summary>Whether the punishment fits the entry and stage (PunishmentDef.fits).</summary>
public static bool Fits(PunishmentDef punishment, ActEntry entry, LawStage stage) =>
punishment != null && entry != null && punishment.Fits(entry, stage);
/// <summary>The punishments a row of this entry and stage offers, in order.</summary>
public static IEnumerable<PunishmentDef> PunishmentsFor(ActEntry entry, LawStage stage) =>
DefDatabase<PunishmentDef>.AllDefsListForReading.Where(p => Fits(p, entry, stage)).OrderBy(p => p.order);
/// <summary>"Needs Ideology" or "Missing: Core" for a row whose entry is missing, else null.</summary>
public static string MissingText(Law law) => law?.MissingText;
// ---- writes --------------------------------------------------------------------------
/// <summary>
/// A new row for the entry, not added yet: the entry's first stage, Moderate, Warn, 3 days and On; a
/// drug binge row gets the Any option. A missing entry gives a did-it row.
/// </summary>
public static Law NewRow(string actKey)
{
ActEntry entry = ActCatalogue.Get(actKey);
var law = new Law
{
actKey = actKey,
stage = entry?.FirstStage ?? LawStage.DidIt,
severity = LawSeverity.Moderate,
punishment = BlaxLawsDefOf.Warn?.defName ?? "Warn",
days = DefaultDays(LawSeverity.Moderate),
enabled = true,
option = entry != null && entry.hasDrugOption ? DrugOptions.Any : null,
};
Remember(law, entry);
return law;
}
/// <summary>
/// Adds a prepared row (from NewRow, the starter list or a test). Gives it an id and, when its entry
/// resolves, the entry's label and source. Refuses a row whose key exists: then existing is that row.
/// </summary>
public static bool TryAdd(Law law, out Law existing)
{
existing = null;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null || law.actKey.NullOrEmpty())
return false;
existing = Find(law.actKey, law.option, law.stage);
if (existing != null)
return false;
if (law.id <= 0 || comp.LawById(law.id) != null)
law.id = comp.TakeLawId();
law.days = ClampDays(law.days);
Remember(law, ActCatalogue.Get(law.actKey));
comp.AddLaw(law);
Changed();
return true;
}
/// <summary>Adds NewRow(actKey). Returns the new row, or null when a row with that key exists (Find gives it).</summary>
public static Law Add(string actKey)
{
Law law = NewRow(actKey);
return TryAdd(law, out _) ? law : null;
}
/// <summary>
/// Changes the row's action. The stage moves to the entry's first stage if the entry lacks it, a
/// punishment that no longer fits resets to Warn, and the option follows the entry. Refused when the
/// new key exists: then existing is that row.
/// </summary>
public static bool SetAction(Law law, string actKey, out Law existing)
{
existing = null;
if (law == null || actKey.NullOrEmpty())
return false;
ActEntry entry = ActCatalogue.Get(actKey);
LawStage stage = entry == null || entry.HasStage(law.stage) ? law.stage : entry.FirstStage;
string option = entry != null && entry.hasDrugOption ? law.option ?? DrugOptions.Any : null;
existing = FindOther(law, actKey, option, stage);
if (existing != null)
return false;
law.actKey = actKey;
law.stage = stage;
law.option = option;
Remember(law, entry);
ResetPunishmentIfUnfit(law, entry);
Changed();
return true;
}
/// <summary>Changes a drug binge row's option. Refused when the key exists.</summary>
public static bool SetOption(Law law, string option, out Law existing)
{
existing = null;
if (law == null)
return false;
existing = FindOther(law, law.actKey, option, law.stage);
if (existing != null)
return false;
law.option = option;
Changed();
return true;
}
/// <summary>Changes the row's stage; a punishment that no longer fits resets to Warn. Refused when the key exists.</summary>
public static bool SetStage(Law law, LawStage stage, out Law existing)
{
existing = null;
if (law == null)
return false;
ActEntry entry = law.Entry;
if (entry != null && !entry.HasStage(stage))
return false;
existing = FindOther(law, law.actKey, law.option, stage);
if (existing != null)
return false;
law.stage = stage;
ResetPunishmentIfUnfit(law, entry);
Changed();
return true;
}
/// <summary>Changes the severity. Days move to the new default only while they still equal the old default.</summary>
public static void SetSeverity(Law law, LawSeverity severity)
{
if (law == null || law.severity == severity)
return;
if (law.days == DefaultDays(law.severity))
law.days = DefaultDays(severity);
law.severity = severity;
Changed();
}
/// <summary>Changes the punishment. Refused (false) when it doesn't fit the row's entry and stage.</summary>
public static bool SetPunishment(Law law, PunishmentDef punishment)
{
if (law == null || punishment == null)
return false;
ActEntry entry = law.Entry;
if (entry != null && !punishment.Fits(entry, law.stage))
return false;
law.punishment = punishment.defName;
Changed();
return true;
}
public static void SetDays(Law law, int days)
{
if (law == null)
return;
law.days = ClampDays(days);
Changed();
}
public static void SetEnabled(Law law, bool enabled)
{
if (law == null || law.enabled == enabled)
return;
law.enabled = enabled;
Changed();
}
/// <summary>Moves the row to a new place in the list.</summary>
public static void Move(Law law, int index)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null)
return;
comp.MoveLaw(law, index);
Changed();
}
/// <summary>The open cases a delete would close; the UI names the count and asks first.</summary>
public static int OpenCaseCount(Law law) => GameComponent_BlaxLaws.Instance?.OpenCaseCount(law) ?? 0;
/// <summary>Deletes the row. Its open cases close as "law repealed". Returns how many closed.</summary>
public static int Delete(Law law)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null || !comp.RemoveLaw(law))
return 0;
int closed = 0;
foreach (LawCase c in comp.OpenCases())
{
if (c.planningLawId != law.id && c.didItLawId != law.id)
continue;
PunishmentDef active = c.activePunishment.NullOrEmpty() ? null : DefDatabase<PunishmentDef>.GetNamedSilentFail(c.activePunishment);
if (active != null)
HookGuard.Run("Stopping " + active.defName, () => active.Worker.Stop(c));
comp.CloseCase(c, CaseOutcomes.Repealed);
closed++;
}
Changed();
return closed;
}
// ---- starter lawbook -----------------------------------------------------------------
/// <summary>One suggested row.</summary>
public readonly struct StarterRow
{
public readonly string actKey;
public readonly string option;
public readonly LawStage stage;
public readonly LawSeverity severity;
public readonly string punishment;
public readonly int days;
public StarterRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days)
{
this.actKey = actKey;
this.option = option;
this.stage = stage;
this.severity = severity;
this.punishment = punishment;
this.days = days;
}
}
/// <summary>
/// The seven suggested rows (design: "Defaults I picked"), Core entries only. "Ate: any meat" is left
/// out, since most colonies eat meat.
/// </summary>
public static readonly StarterRow[] StarterRows =
{
new StarterRow(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.Planning, LawSeverity.Moderate, "Subdue", 3),
new StarterRow(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.DidIt, LawSeverity.Serious, "Jail", 5),
new StarterRow(ActKey.Of(ActCategories.Break, "FireStartingSpree"), null, LawStage.Planning, LawSeverity.Serious, "Subdue", 5),
new StarterRow(ActKey.Of(ActCategories.Break, "FireStartingSpree"), null, LawStage.DidIt, LawSeverity.Grave, "Jail", 10),
new StarterRow(ActKey.Of(ActCategories.Break, "CorpseObsession"), null, LawStage.Planning, LawSeverity.Moderate, "Subdue", 3),
new StarterRow(ActKey.Of(ActCategories.Special, SpecialActs.StartedSocialFight), null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1),
new StarterRow(ActKey.Of(ActCategories.Interaction, "Insult"), null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1),
};
/// <summary>Adds the starter rows that are missing. Returns how many were added (0 when pressed again).</summary>
public static int AddStarter()
{
int added = 0;
foreach (StarterRow s in StarterRows)
{
if (Find(s.actKey, s.option, s.stage) != null)
continue;
var law = new Law
{
actKey = s.actKey,
option = s.option,
stage = s.stage,
severity = s.severity,
punishment = s.punishment,
days = s.days,
enabled = true,
// Every starter entry is Core's; this is what a missing entry shows until the catalogue knows it.
savedLabel = ActKey.NameOf(s.actKey),
savedMod = DlcSupport.CoreName,
savedPackageId = DlcSupport.CorePackageId,
};
if (TryAdd(law, out _))
added++;
}
return added;
}
// ---- matching ------------------------------------------------------------------------
/// <summary>
/// The most specific enabled row of the act's category for the stage whose entry matches the act, or
/// null. Specificity: a single def over a group (the smaller group first) over the category's "any";
/// then, for drug binge rows, one chemical over hard or social over any drug; then the older row.
/// Rows whose entry is missing never match.
/// </summary>
public static Law BestRow(ActEvent act, LawStage stage)
{
if (act == null || act.categoryId == null)
return null;
IReadOnlyList<Law> rows = Watch.LawsOf(act.categoryId);
Law best = null;
ActEntry bestEntry = null;
for (int i = 0; i < rows.Count; i++)
{
Law law = rows[i];
if (!law.enabled || law.stage != stage)
continue;
ActEntry entry = ActCatalogue.Get(law.actKey);
if (entry == null || !entry.Matches(act))
continue;
if (entry.hasDrugOption && !DrugOptions.Matches(law.option, act))
continue;
if (best == null || MoreSpecific(entry, law, bestEntry, best))
{
best = law;
bestEntry = entry;
}
}
return best;
}
/// <summary>Whether row a (entry ea) is more specific than row b (entry eb).</summary>
public static bool MoreSpecific(ActEntry ea, Law a, ActEntry eb, Law b)
{
if (ea.Rank != eb.Rank)
return ea.Rank > eb.Rank;
if (ea.Rank == 2)
{
int sa = ea.group?.size ?? int.MaxValue, sb = eb.group?.size ?? int.MaxValue;
if (sa != sb)
return sa < sb;
}
int oa = ea.hasDrugOption ? DrugOptions.Rank(a.option) : 0;
int ob = eb.hasDrugOption ? DrugOptions.Rank(b.option) : 0;
if (oa != ob)
return oa > ob;
return a.id < b.id;
}
// ---- helpers -------------------------------------------------------------------------
private static Law FindOther(Law self, string actKey, string option, LawStage stage)
{
foreach (Law l in Laws)
{
if (l != self && l.HasKey(actKey, option, stage))
return l;
}
return null;
}
/// <summary>Stores the entry's label and source on the row, so a missing entry still shows them.</summary>
private static void Remember(Law law, ActEntry entry)
{
if (entry == null)
return;
law.savedLabel = entry.label;
law.savedMod = entry.sourceMod;
law.savedPackageId = entry.sourcePackageId;
}
private static void ResetPunishmentIfUnfit(Law law, ActEntry entry)
{
PunishmentDef p = law.PunishmentDef;
if (entry != null && (p == null || !p.Fits(entry, law.stage)))
law.punishment = BlaxLawsDefOf.Warn?.defName ?? "Warn";
}
/// <summary>After every write: the hot-path cache follows the book.</summary>
private static void Changed() => Watch.Rebuild();
}
}

View File

@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// One-time logging. Every hook sits in try/catch and logs through HookGuard, which logs here, so a
/// broken hook logs once per game instead of every call. The flags reset in
/// GameComponent_BlaxLaws.FinalizeInit, so a failure in a later game logs again.
/// </summary>
public static class LawsLog
{
private static readonly HashSet<string> logged = new HashSet<string>();
/// <summary>Logs "[Blax Laws] where failed" with the exception, once per key until the next reset.</summary>
public static void Once(string where, Exception e)
{
try
{
lock (logged)
{
if (!logged.Add(where))
return;
}
Log.Error("[Blax Laws] " + where + " failed (logged once per game): " + e);
}
catch
{
// Logging must never throw into a hook.
}
}
/// <summary>A one-time message (stand-downs, hints), not an error.</summary>
public static void MessageOnce(string key, string text)
{
try
{
lock (logged)
{
if (!logged.Add("msg:" + key))
return;
}
Log.Message("[Blax Laws] " + text);
}
catch
{
}
}
/// <summary>A one-time warning, for data the game hands over that Laws can't use (a broken def, a saved name it can't read).</summary>
public static void WarningOnce(string key, string text)
{
try
{
lock (logged)
{
if (!logged.Add("warn:" + key))
return;
}
Log.Warning("[Blax Laws] " + text);
}
catch
{
}
}
public static void ResetOnce()
{
lock (logged) logged.Clear();
}
}
/// <summary>
/// Switches the test mod flips to force failure paths. Not game state: nothing here is saved and the
/// test runner resets every field after each test.
/// </summary>
public static class LawsTestHooks
{
/// <summary>CaseFiler.Report throws, to test that a hook's HookGuard keeps vanilla running.</summary>
public static bool ReportThrows;
public static void Reset()
{
ReportThrows = false;
}
}
}

View File

@ -0,0 +1,61 @@
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// One act as a hook saw it, handed to CaseFiler.Report. Hooks build it only after their Watch flag and
/// Watch.MayMatch passed, so an empty lawbook allocates nothing. Never saved.
///
/// What each category puts in def: Break the MentalStateDef, Ate the eaten ThingDef, Used the used
/// ThingDef, Interaction the InteractionDef, RecordedAct the HistoryEventDef, Record the RecordDef, Bill
/// the RecipeDef, Special the ActDef.
/// </summary>
public sealed class ActEvent
{
/// <summary>The category id (ActCategories).</summary>
public string categoryId;
/// <summary>The def the act is about; see the class summary.</summary>
public Def def;
/// <summary>Who did it. Filtered by Offenders.IsCovered inside Report.</summary>
public Pawn offender;
/// <summary>Who it was done to, when there is someone (the insulted pawn, the provoker of a fight).</summary>
public Pawn victim;
/// <summary>The thing involved (the eaten stack, the used item, the corpse), when there is one. May be destroyed by now.</summary>
public Thing thing;
/// <summary>The drug's chemical (a dose), or the binge's chosen chemical (hook A on a drug binge).</summary>
public ChemicalDef chemical;
/// <summary>The drug's category (a dose), or the binge's (MentalState_BingingDrug.drugCategory).</summary>
public DrugCategory drugCategory;
/// <summary>What the hook read from the thing for thing-level groups (hook C's prefix).</summary>
public ActFacts facts;
/// <summary>Notes the case takes over (on a table, dug up).</summary>
public CaseNotes notes;
/// <summary>The live mental state: the new one for a Break report, else null (Report reads the offender's).</summary>
public MentalState mentalState;
public ActEvent()
{
}
public ActEvent(string categoryId, Def def, Pawn offender)
{
this.categoryId = categoryId;
this.def = def;
this.offender = offender;
}
public override string ToString() =>
categoryId + "/" + (def?.defName ?? "null") + " by " + (offender?.LabelShort ?? "nobody") + (victim != null ? " on " + victim.LabelShort : "");
}
}

View File

@ -0,0 +1,164 @@
using System;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Act keys: how the save names a catalogue entry. "Category/defName" for a single def
/// ("Ate/WakeUp", "Break/FireStartingSpree", "Special/SetFire"), "Category/@group" for a group
/// ("Ate/@humanMeat", "Break/@anyDrugBinge"). The category is an ActCategoryDef's defName, the group
/// id an ActGroup's id. Keys are only ever added, never renamed: a saved row names its entry by key.
/// </summary>
public static class ActKey
{
public const char Separator = '/';
public const string GroupPrefix = "@";
public static string Of(string categoryId, string name) => categoryId + Separator + name;
public static string Of(string categoryId, Def def) => Of(categoryId, def.defName);
/// <summary>A group key; the id may come with or without its "@".</summary>
public static string OfGroup(string categoryId, string groupId) =>
Of(categoryId, groupId.StartsWith(GroupPrefix) ? groupId : GroupPrefix + groupId);
/// <summary>"Ate" for "Ate/WakeUp", null for a key without a separator.</summary>
public static string CategoryOf(string key)
{
if (key.NullOrEmpty())
return null;
int i = key.IndexOf(Separator);
return i <= 0 ? null : key.Substring(0, i);
}
/// <summary>"WakeUp" for "Ate/WakeUp", "@humanMeat" for "Ate/@humanMeat", null for a key without a separator.</summary>
public static string NameOf(string key)
{
if (key.NullOrEmpty())
return null;
int i = key.IndexOf(Separator);
return i < 0 || i == key.Length - 1 ? null : key.Substring(i + 1);
}
public static bool IsGroup(string key) => NameOf(key)?.StartsWith(GroupPrefix) ?? false;
public static bool TryParse(string key, out string categoryId, out string name)
{
categoryId = CategoryOf(key);
name = NameOf(key);
return categoryId != null && name != null;
}
}
/// <summary>The categories' ids: the defNames of the ActCategoryDefs in Defs/BlaxLaws_Categories.xml.</summary>
public static class ActCategories
{
public const string Break = "Break";
public const string Ate = "Ate";
public const string Used = "Used";
public const string Interaction = "Interaction";
public const string RecordedAct = "RecordedAct";
public const string Record = "Record";
public const string Bill = "Bill";
public const string Special = "Special";
public static readonly string[] All = { Break, Ate, Used, Interaction, RecordedAct, Record, Bill, Special };
}
/// <summary>The special acts' ids: the defNames of the ActDefs in Defs/BlaxLaws_Acts.xml.</summary>
public static class SpecialActs
{
public const string SetFire = "SetFire";
public const string DisplayedCorpse = "DisplayedCorpse";
public const string StartedSocialFight = "StartedSocialFight";
}
/// <summary>
/// Group ids the catalogue package registers (design: "Act catalogue and detection", the Groups column).
/// Each is unique within its category; the key is ActKey.OfGroup(category, id).
/// </summary>
public static class ActGroups
{
/// <summary>The category's "any": every entry of it. The least specific row.</summary>
public const string Any = "@any";
// Mental breaks
public const string AnyDrugBinge = "@anyDrugBinge";
public const string AnyTantrum = "@anyTantrum";
public const string AnyInsultingSpree = "@anyInsultingSpree";
public const string AnyAggressive = "@anyAggressive";
// Ate
public const string AnyDrug = "@anyDrug";
public const string HardDrugs = "@hardDrugs";
public const string SocialDrugs = "@socialDrugs";
public const string MedicalDrugs = "@medicalDrugs";
public const string AnyMeat = "@anyMeat";
public const string RawMeatOrCorpse = "@rawMeatOrCorpse";
public const string HumanMeat = "@humanMeat";
public const string InsectMeat = "@insectMeat";
public const string RawFood = "@rawFood";
public const string AnyMeal = "@anyMeal";
// Social interactions
public const string InsultOrSlight = "@insultOrSlight";
// Bills
public const string AnySurgery = "@anySurgery";
}
/// <summary>
/// The option of a drug binge row: which drug counts. "@any", "@hard", "@social", or a ChemicalDef's
/// defName. Rows of other entries keep a null option.
/// </summary>
public static class DrugOptions
{
public const string Any = "@any";
public const string Hard = "@hard";
public const string Social = "@social";
/// <summary>Null and "" read as Any.</summary>
public static string Normalize(string option) => option.NullOrEmpty() ? Any : option;
/// <summary>
/// The option's rank for "the most specific row wins": one chemical 3, hard or social 2, any 1.
/// </summary>
public static int Rank(string option)
{
string o = Normalize(option);
if (o == Any)
return 1;
return o == Hard || o == Social ? 2 : 3;
}
/// <summary>Whether the dose (or the binge's chosen chemical) in the act counts under the option.</summary>
public static bool Matches(string option, ActEvent act)
{
string o = Normalize(option);
if (o == Any)
return true;
if (act == null)
return false;
if (o == Hard)
return act.drugCategory == DrugCategory.Hard;
if (o == Social)
return act.drugCategory == DrugCategory.Social;
return act.chemical != null && act.chemical.defName == o;
}
/// <summary>The option's label: "Any drug", "Hard drugs", "Social drugs" or the chemical's label.</summary>
public static string Label(string option)
{
string o = Normalize(option);
if (o == Any)
return "BlaxLaws_DrugOption_Any".Translate();
if (o == Hard)
return "BlaxLaws_DrugOption_Hard".Translate();
if (o == Social)
return "BlaxLaws_DrugOption_Social".Translate();
ChemicalDef chem = DefDatabase<ChemicalDef>.GetNamedSilentFail(o);
return chem != null ? chem.LabelCap.ToString() : o;
}
}
}

View File

@ -0,0 +1,139 @@
using System;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// A law's stage. Planning: a break has started and nothing is done yet (break entries only). Did it:
/// the act happened. Saved by name, so the names never change.
/// </summary>
public enum LawStage
{
Planning,
DidIt,
}
/// <summary>A law's severity. Sets the default days (1, 3, 5, 10) and orders the case log. Saved by name.</summary>
public enum LawSeverity
{
Minor,
Moderate,
Serious,
Grave,
}
/// <summary>Where a case stands. Saved by name.</summary>
public enum CaseStatus
{
/// <summary>Filed; nothing runs yet, or it waits (no bed, no enforcer, danger, a hold).</summary>
Open,
/// <summary>An enforcer is on it (a subdue, an arrest or a capture job).</summary>
Enforcing,
/// <summary>The offender serves a sentence in Laws' custody.</summary>
Jailed,
/// <summary>Done; LawCase.outcome says how.</summary>
Closed,
}
/// <summary>Notes a case keeps about the act ("on a table", "dug up from a grave"). Saved by name.</summary>
[Flags]
public enum CaseNotes
{
None = 0,
OnTable = 1,
DugUp = 2,
}
/// <summary>
/// What a hook read from the thing itself, before it could be destroyed (hook C's prefix), for groups
/// that depend on the thing rather than its def: a meal with meat in it, human meat. Not saved.
/// </summary>
[Flags]
public enum ActFacts
{
None = 0,
/// <summary>Any meat, meals with meat included (FoodUtility.GetFoodKind).</summary>
Meat = 1,
/// <summary>Raw meat or a corpse, unprocessed.</summary>
RawMeatOrCorpse = 2,
/// <summary>Human meat, a humanlike corpse or an ingredient of either.</summary>
HumanMeat = 4,
/// <summary>Insect meat.</summary>
InsectMeat = 8,
/// <summary>Raw food (ingestible preferability).</summary>
RawFood = 16,
/// <summary>A meal (processed food).</summary>
Meal = 32,
}
/// <summary>Which stages of a case have had their punishment dispatched. Saved by name.</summary>
[Flags]
public enum StageMask
{
None = 0,
Planning = 1,
DidIt = 2,
}
/// <summary>
/// The entry kind and stage a punishment fits (design: "Lawbook tab", punishments per entry and stage).
/// Read from PunishmentDef.fits in XML.
/// </summary>
public enum PunishmentFit
{
/// <summary>A break that isn't hostile to the colony, at planning.</summary>
BreakPlanning,
/// <summary>A break that isn't hostile to the colony, at did it.</summary>
BreakDidIt,
/// <summary>A break hostile to the colony (berserk), at planning.</summary>
HostileBreakPlanning,
/// <summary>A break hostile to the colony (berserk), at did it.</summary>
HostileBreakDidIt,
/// <summary>Every entry outside the breaks: ate, used, interactions, recorded acts, records, bills, special acts.</summary>
Act,
}
/// <summary>What an Enforcement queue entry does when it comes due.</summary>
public enum CaseTask
{
/// <summary>Start the punishment of the case's law for the entry's stage (PunishmentWorker.Start).</summary>
Punish,
/// <summary>Write "Maintain only" on a pawn Laws just jailed (Sentences.WriteMaintainOnly).</summary>
MaintainOnly,
}
/// <summary>Outcome keys of closed cases. The label is "BlaxLaws_Outcome_" + key. Saved as strings.</summary>
public static class CaseOutcomes
{
public const string Repealed = "Repealed";
public const string BreakEnded = "BreakEnded";
public const string NotEnforced = "NotEnforced";
public const string OffenderGone = "OffenderGone";
public const string Warned = "Warned";
public const string Guilty = "Guilty";
public const string Subdued = "Subdued";
public const string Served = "Served";
public const string ReleasedEarly = "ReleasedEarly";
/// <summary>The outcome's label, or the key itself when no string exists (an outcome a later release added).</summary>
public static string Label(string key)
{
if (key.NullOrEmpty())
return "";
string k = "BlaxLaws_Outcome_" + key;
return k.CanTranslate() ? k.Translate().ToString() : key;
}
}
/// <summary>Labels for the enums, from Keyed.</summary>
public static class LawLabels
{
public static string Stage(LawStage stage) => ("BlaxLaws_Stage_" + stage).Translate();
public static string Severity(LawSeverity severity) => ("BlaxLaws_Severity_" + severity).Translate();
public static string Status(CaseStatus status) => ("BlaxLaws_Status_" + status).Translate();
public static StageMask Mask(LawStage stage) => stage == LawStage.Planning ? StageMask.Planning : StageMask.DidIt;
}
}

View File

@ -0,0 +1,89 @@
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// One row of the lawbook. Holds only names and numbers, so a row whose entry is gone (a DLC drug
/// without its DLC, a removed mod's interaction) stays, shows "Needs &lt;DLC&gt;" or "Missing: &lt;mod&gt;"
/// and works again when the mod comes back (design: "Lawbook and cases in one GameComponent").
///
/// Read the fields freely; change a row only through Lawbook, which keeps the key unique and rebuilds
/// the Watch cache. Action (actKey), Option and Stage are the row's key.
/// </summary>
public class Law : IExposable
{
/// <summary>Unique in the save, never reused. 0 until Lawbook adds the row.</summary>
public int id;
/// <summary>The catalogue entry: "Ate/WakeUp", "Break/@anyDrugBinge" (ActKey).</summary>
public string actKey;
/// <summary>The entry's label when the row was written, shown while the entry is missing.</summary>
public string savedLabel;
/// <summary>The entry's source when the row was written: "Core", "Ideology" or a mod's name.</summary>
public string savedMod;
/// <summary>The entry's source package id when the row was written ("ludeon.rimworld.ideology").</summary>
public string savedPackageId;
/// <summary>Drug binge rows only: DrugOptions ("@any", "@hard", "@social" or a ChemicalDef defName). Null otherwise.</summary>
public string option;
public LawStage stage = LawStage.DidIt;
public LawSeverity severity = LawSeverity.Moderate;
/// <summary>The PunishmentDef's defName ("Warn", "Jail").</summary>
public string punishment = "Warn";
/// <summary>1 to 50; used by punishments with usesDays.</summary>
public int days = 3;
public bool enabled = true;
/// <summary>The category id, the first part of the act key.</summary>
public string CategoryId => ActKey.CategoryOf(actKey);
/// <summary>The catalogue entry, or null while it is missing.</summary>
public ActEntry Entry => ActCatalogue.Get(actKey);
public bool Resolves => Entry != null;
/// <summary>The punishment's def, or null when a later release's punishment was saved and is gone.</summary>
public PunishmentDef PunishmentDef => punishment.NullOrEmpty() ? null : DefDatabase<PunishmentDef>.GetNamedSilentFail(punishment);
/// <summary>The label the lawbook shows: the entry's, the saved one while missing, else the key.</summary>
public string Label => Entry?.label ?? (savedLabel.NullOrEmpty() ? actKey : savedLabel);
/// <summary>"Needs Ideology" or "Missing: Core" while the entry is missing, else null.</summary>
public string MissingText => Resolves ? null : DlcSupport.MissingText(savedMod, savedPackageId);
/// <summary>The sentence or guilt length in ticks.</summary>
public int DaysTicks => days * GenDate.TicksPerDay;
/// <summary>Whether this row has the given key (option compared as DrugOptions only for rows that keep one).</summary>
public bool HasKey(string key, string opt, LawStage stg) =>
actKey == key && stage == stg && Lawbook.NormalizeOption(option) == Lawbook.NormalizeOption(opt);
public void ExposeData()
{
Scribe_Values.Look(ref id, "id");
Scribe_Values.Look(ref actKey, "actKey");
Scribe_Values.Look(ref savedLabel, "savedLabel");
Scribe_Values.Look(ref savedMod, "savedMod");
Scribe_Values.Look(ref savedPackageId, "savedPackageId");
Scribe_Values.Look(ref option, "option");
Scribe_Values.Look(ref stage, "stage", LawStage.DidIt);
Scribe_Values.Look(ref severity, "severity", LawSeverity.Moderate);
Scribe_Values.Look(ref punishment, "punishment", "Warn");
Scribe_Values.Look(ref days, "days", 3);
Scribe_Values.Look(ref enabled, "enabled", true);
}
public override string ToString() =>
"Law " + id + " " + actKey + (option != null ? " [" + option + "]" : "") + " " + stage + " " + severity + " " + punishment +
(enabled ? "" : " (off)");
}
}

View File

@ -0,0 +1,237 @@
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// One incident: a break from its start to its end, or one act outside a break (plus the repeats the
/// cooldown folds into it). Saved deep in GameComponent_BlaxLaws as names, numbers and pawn references;
/// a reference to a pawn that is gone becomes null on save and after load, and the case keeps the name
/// (design: "Lawbook and cases in one GameComponent").
///
/// CaseFiler opens cases; Enforcement and the punishment workers move them on. Write the fields from
/// those places only; close a case with GameComponent_BlaxLaws.CloseCase.
/// </summary>
public class LawCase : IExposable
{
public int id;
// ---- who ------------------------------------------------------------------------------
public Pawn offender;
/// <summary>The offender's short name when the case was filed, kept after the pawn is gone.</summary>
public string offenderName;
public string offenderId;
public Pawn victim;
public string victimName;
public string victimId;
// ---- what -----------------------------------------------------------------------------
/// <summary>The act key of the row that opened the case.</summary>
public string actKey;
/// <summary>The defName that matched (which drug, which recipe, which break). Updated by a later act of the case.</summary>
public string matchedDef;
/// <summary>Break cases: the MentalStateDef's defName. Null for acts outside a break.</summary>
public string breakState;
/// <summary>Break cases: the tick the break started (TicksGame minus MentalState.Age, to within 30 ticks).</summary>
public int breakStartTick = -1;
/// <summary>The row whose punishment the planning stage runs, or -1.</summary>
public int planningLawId = -1;
/// <summary>The row whose punishment the did-it stage runs, or -1. Set once per case.</summary>
public int didItLawId = -1;
/// <summary>The highest severity of the case's rows, kept for the log after a row is deleted.</summary>
public LawSeverity severity;
/// <summary>The stage reached.</summary>
public LawStage stage;
/// <summary>Did-it acts in this case: doses during a binge, repeats inside the cooldown. 0 at planning.</summary>
public int count;
public CaseNotes notes;
// ---- when and how far -----------------------------------------------------------------
public int openTick;
public int lastActTick;
public int closeTick = -1;
public CaseStatus status = CaseStatus.Open;
/// <summary>CaseOutcomes key once closed, else null.</summary>
public string outcome;
/// <summary>Which stages' punishments were dispatched (each row fires once per case).</summary>
public StageMask punishedStages;
/// <summary>The PunishmentDef defName running for this case (Enforcement calls its Sweep), or null.</summary>
public string activePunishment;
/// <summary>The stage activePunishment runs for.</summary>
public LawStage activeStage;
/// <summary>The pawn carrying it out, one enforcement at a time.</summary>
public Pawn enforcer;
/// <summary>Why enforcement waits, as a Keyed key the Cases tab shows, or null. Set by the punishment workers.</summary>
public string waitReason;
// ---- jail -----------------------------------------------------------------------------
/// <summary>The tick the offender became Laws' prisoner (hook K), or -1.</summary>
public int captureTick = -1;
/// <summary>"Maintain only" was written two ticks after the capture.</summary>
public bool maintainOnlyDone;
/// <summary>Capture tick plus the sentence, or -1.</summary>
public int releaseTick = -1;
/// <summary>The bed the offender owned right before the arrest job took it, given back when the arrest fails.</summary>
public Building_Bed oldBed;
/// <summary>"Arrest now" lifted the hold for this case: from here on it arrests a role holder or mechanitor like anyone.</summary>
public bool holdLifted;
// ---- reads ----------------------------------------------------------------------------
public bool IsClosed => status == CaseStatus.Closed;
public bool IsBreakCase => !breakState.NullOrEmpty();
public MentalStateDef BreakStateDef => breakState.NullOrEmpty() ? null : DefDatabase<MentalStateDef>.GetNamedSilentFail(breakState);
public int LawIdFor(LawStage s) => s == LawStage.Planning ? planningLawId : didItLawId;
/// <summary>The row the stage runs, or null (none, or deleted).</summary>
public Law LawFor(LawStage s) => GameComponent_BlaxLaws.Instance?.LawById(LawIdFor(s));
/// <summary>The row the case shows: did it, else planning, else null.</summary>
public Law CurrentLaw => LawFor(LawStage.DidIt) ?? LawFor(LawStage.Planning);
public bool HasPunished(LawStage s) => (punishedStages & LawLabels.Mask(s)) != 0;
public void MarkPunished(LawStage s) => punishedStages |= LawLabels.Mask(s);
/// <summary>The offender's name, live while the pawn exists.</summary>
public string OffenderLabel => offender != null ? offender.LabelShort : offenderName ?? "?";
public string VictimLabel => victim != null ? victim.LabelShort : victimName;
/// <summary>What the case is about: the current row's label, else the act key.</summary>
public string Label => CurrentLaw?.Label ?? actKey;
// ---- writes for CaseFiler, Enforcement and the punishment workers -----------------------
public void SetOffender(Pawn p)
{
offender = p;
offenderName = p?.LabelShort;
offenderId = p?.ThingID;
}
public void SetVictim(Pawn p)
{
victim = p;
victimName = p?.LabelShort;
victimId = p?.ThingID;
}
/// <summary>Sets the row a stage runs and raises the case's severity to it.</summary>
public void SetLaw(LawStage s, Law law)
{
if (law == null)
return;
if (s == LawStage.Planning)
planningLawId = law.id;
else
didItLawId = law.id;
if (law.severity > severity)
severity = law.severity;
}
/// <summary>Nulls references to pawns and things that are gone, so the save holds no reference it can't load. Names stay.</summary>
public void DropGoneReferences()
{
if (IsGone(offender))
offender = null;
if (IsGone(victim))
victim = null;
if (IsGone(enforcer))
enforcer = null;
if (oldBed != null && (oldBed.Destroyed || oldBed.Discarded))
oldBed = null;
}
/// <summary>
/// Null, discarded, or destroyed without being dead. A dead pawn stays while its corpse or the world
/// still holds it, so its reference resolves on load (the Castes rule).
/// </summary>
public static bool IsGone(Pawn pawn)
{
if (pawn == null || pawn.Discarded)
return true;
if (!pawn.Destroyed)
return false;
if (!pawn.Dead)
return true;
return pawn.Corpse == null && !pawn.IsWorldPawn();
}
public void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
DropGoneReferences();
Scribe_Values.Look(ref id, "id");
Scribe_References.Look(ref offender, "offender", saveDestroyedThings: true);
Scribe_Values.Look(ref offenderName, "offenderName");
Scribe_Values.Look(ref offenderId, "offenderId");
Scribe_References.Look(ref victim, "victim", saveDestroyedThings: true);
Scribe_Values.Look(ref victimName, "victimName");
Scribe_Values.Look(ref victimId, "victimId");
Scribe_Values.Look(ref actKey, "actKey");
Scribe_Values.Look(ref matchedDef, "matchedDef");
Scribe_Values.Look(ref breakState, "breakState");
Scribe_Values.Look(ref breakStartTick, "breakStartTick", -1);
Scribe_Values.Look(ref planningLawId, "planningLawId", -1);
Scribe_Values.Look(ref didItLawId, "didItLawId", -1);
Scribe_Values.Look(ref severity, "severity", LawSeverity.Minor);
Scribe_Values.Look(ref stage, "stage", LawStage.Planning);
Scribe_Values.Look(ref count, "count");
Scribe_Values.Look(ref notes, "notes", CaseNotes.None);
Scribe_Values.Look(ref openTick, "openTick");
Scribe_Values.Look(ref lastActTick, "lastActTick");
Scribe_Values.Look(ref closeTick, "closeTick", -1);
Scribe_Values.Look(ref status, "status", CaseStatus.Open);
Scribe_Values.Look(ref outcome, "outcome");
Scribe_Values.Look(ref punishedStages, "punishedStages", StageMask.None);
Scribe_Values.Look(ref activePunishment, "activePunishment");
Scribe_Values.Look(ref activeStage, "activeStage", LawStage.Planning);
Scribe_References.Look(ref enforcer, "enforcer", saveDestroyedThings: true);
Scribe_Values.Look(ref waitReason, "waitReason");
Scribe_Values.Look(ref captureTick, "captureTick", -1);
Scribe_Values.Look(ref maintainOnlyDone, "maintainOnlyDone");
Scribe_Values.Look(ref releaseTick, "releaseTick", -1);
Scribe_References.Look(ref oldBed, "oldBed");
Scribe_Values.Look(ref holdLifted, "holdLifted");
if (Scribe.mode == LoadSaveMode.PostLoadInit)
DropGoneReferences();
}
public override string ToString() =>
"Case " + id + " " + OffenderLabel + " " + actKey + " " + stage + " x" + count + " " + status + (outcome != null ? " (" + outcome + ")" : "");
}
}

View File

@ -0,0 +1,47 @@
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Who the laws cover (design: "Detection", offender filter, shared by every hook): free colonists,
/// children included, and colony slaves, spawned on a map. Never guests, Hospitality visitors, quest
/// lodgers, prisoners, babies or subhumans. Caravan acts are skipped.
/// </summary>
public static class Offenders
{
/// <summary>The pawn can be an offender.</summary>
public static bool IsCovered(Pawn p)
{
if (p == null || !p.Spawned || p.Map == null || p.Dead)
return false;
if (p.RaceProps == null || !p.RaceProps.Humanlike)
return false;
if (p.Faction == null || !p.Faction.IsPlayer)
return false;
// A slave in a break isn't IsColonist (Pawn.cs:518-527), so slaves are checked on their own.
if (!p.IsFreeColonist && !p.IsSlaveOfColony)
return false;
if (p.IsPrisoner)
return false;
if (p.IsQuestLodger())
return false;
if (p.DevelopmentalStage.Baby())
return false;
// Mutants exist only with Anomaly; without it IsSubhuman reads a null field and is false.
if (p.IsSubhuman)
return false;
return true;
}
/// <summary>
/// The act is a player order: the pawn is drafted or its current job is player-forced (Job.cs:37).
/// Exempt while "Player orders are exempt" is on.
/// </summary>
public static bool OnPlayerOrder(Pawn p) => p != null && (p.Drafted || (p.CurJob?.playerForced ?? false));
/// <summary>IsCovered and, while the setting is on, not on a player order.</summary>
public static bool CountsAsOffender(Pawn p) =>
IsCovered(p) && !(BlaxLawsMod.S.playerOrdersExempt && OnPlayerOrder(p));
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook K (design: "Enforcement runs a tick later"): a postfix on Pawn_GuestTracker.CapturedBy
/// (RimWorld/Pawn_GuestTracker.cs:561-576, 16 lines with calls, not inlinable), which the arrest and
/// capture jobs call when the enforcer picks the pawn up (JobDriver_TakeToBed.cs:164-178). It returns at
/// once unless the pawn has a case in Enforcing whose own enforcer made the capture for a jail
/// punishment; then the sentence starts (Sentences.OnCaptured). Nothing else of the capture changes.
///
/// Hook point for later steps: "Release gives back what jail took" adds a prefix here that notes the
/// weapon the pawn holds before SetGuestStatus drops it (:564; :461), and "Castes keeps the caste" sends
/// Castes the blax.laws.jailed hint from that prefix.
/// </summary>
[HarmonyPatch(typeof(Pawn_GuestTracker), nameof(Pawn_GuestTracker.CapturedBy))]
public static class Patch_Pawn_GuestTracker_CapturedBy
{
public static void Postfix(Pawn ___pawn, Faction by, Pawn byPawn)
{
try
{
if (byPawn == null || ___pawn == null || by == null || !by.IsPlayer)
return;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null)
return;
IReadOnlyList<LawCase> list = comp.CasesOf(___pawn);
if (list.Count == 0 || !___pawn.IsPrisonerOfColony)
return;
for (int i = list.Count - 1; i >= 0; i--)
{
LawCase c = list[i];
if (Sentences.IsOurCapture(c, byPawn))
{
Sentences.OnCaptured(c);
return;
}
}
}
catch (Exception e)
{
HookGuard.Fail("hook K, Pawn_GuestTracker.CapturedBy", e);
}
}
}
}

View File

@ -0,0 +1,285 @@
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLaws
{
/// <summary>
/// The arrest of a jail case (design: "Jail for N days"): the hold for role holders and mechanitors, the
/// waits (hostile break, danger, no enforcer, no prisoner bed, a reservation someone else holds), guilt
/// renewed right before the job, the old bed noted before the job's first toil takes it and given back
/// when the arrest fails, and the Arrest or Capture job itself. PunishmentWorker_Jail, "Subdue then
/// jail" and "Arrest now" call in here; the sentence itself is Sentences.
/// </summary>
public static class JailFlow
{
/// <summary>The sentence: the days of the row the case runs, in ticks.</summary>
public static int SentenceTicks(LawCase c)
{
Law law = c?.LawFor(c.activeStage) ?? c?.CurrentLaw;
if (law != null)
return Lawbook.ClampDays(law.days) * GenDate.TicksPerDay;
return Lawbook.DefaultDays(c?.severity ?? LawSeverity.Moderate) * GenDate.TicksPerDay;
}
/// <summary>
/// Guilt right before an Arrest or Capture: the sentence plus one day for the release fallback, so the
/// arrest of a free colonist is accepted (Pawn.cs:4087) and a downed one can be captured
/// (GenAI.cs:39-67) however late the arrest comes.
/// </summary>
public static int RenewalTicks(LawCase c) => SentenceTicks(c) + Sentences.FallbackTicks;
/// <summary>
/// The case now runs as Jail (from "Subdue then jail", or a fallback). Clears the wait reason the subdue
/// left.
/// </summary>
public static void Become(LawCase c)
{
if (c == null || c.IsClosed)
return;
c.activePunishment = BlaxLawsDefOf.Jail?.defName ?? "Jail";
if (c.status != CaseStatus.Jailed)
c.status = CaseStatus.Open;
c.waitReason = null;
}
/// <summary>The case's enforcer runs or has queued an Arrest or Capture of the offender.</summary>
public static bool ArrestRuns(LawCase c) => c?.enforcer != null && EnforcerJobs.TakesToJail(c.enforcer, c.offender);
/// <summary>Ends the case's Arrest or Capture job, current or queued, and gives the old bed back.</summary>
public static void EndArrest(LawCase c)
{
if (c?.enforcer == null || c.offender == null)
return;
bool ended = EnforcerJobs.End(c.enforcer, JobDefOf.Arrest, c.offender);
ended |= EnforcerJobs.End(c.enforcer, JobDefOf.Capture, c.offender);
if (ended)
GiveOldBedBack(c);
}
/// <summary>
/// A running or queued Arrest or Capture meets danger: the job ends, the old bed goes back and the case
/// waits for Danger; the sweep arrests after the fight. An enforcer already carrying the offender
/// finishes, since the carry makes it a prisoner (JobDriver_TakeToBed.cs:121-129). Returns whether it
/// was called off.
/// </summary>
public static bool CallOffInDanger(LawCase c)
{
Pawn o = c?.offender;
if (o == null || c.enforcer == null || c.enforcer.IsCarryingPawn(o) || !Enforcers.DangerBlocks(o))
return false;
EndArrest(c);
WaitReasons.Set(c, WaitReasons.Danger);
return true;
}
/// <summary>Whether "Arrest now" lifted the hold for this case. Saved on the case.</summary>
public static bool HoldLifted(LawCase c) => c != null && c.holdLifted;
/// <summary>"Arrest now": from here on the case arrests a role holder or mechanitor like anyone.</summary>
public static void LiftHold(LawCase c)
{
if (c == null)
return;
c.holdLifted = true;
}
/// <summary>
/// Starts the Arrest (or the Capture of a downed offender) now, or leaves the case waiting with its
/// reason; a letter goes out once when the player has to act (hold, no bed, nobody to enforce).
/// Returns whether the job runs.
/// </summary>
public static bool TryArrest(LawCase c, bool ignoreHold)
{
Pawn o = c?.offender;
if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed)
return false;
if (o.IsPrisonerOfColony)
{
AlreadyPrisoner(c);
return false;
}
// First: a role holder or mechanitor waits for "Arrest now" whatever else its case waited for before.
if (!ignoreHold && DlcSupport.HeldForArrestNow(o) && !HoldLifted(c))
{
if (WaitReasons.Set(c, WaitReasons.Hold) && CaseLetters.Once(c, CaseLetters.KindHold))
HoldLetter(c);
return false;
}
if (!o.Spawned)
{
WaitReasons.Set(c, WaitReasons.Away);
return false;
}
// Vanilla refuses the arrest of a pawn whose break is hostile to the arrester (GenAI.cs:83): wait
// until it ends or the pawn is down, then arrest or capture it.
if (!o.Downed && Enforcers.FightsBack(o))
{
WaitReasons.Set(c, WaitReasons.HostileBreak);
return false;
}
if (Enforcers.DangerBlocks(o))
{
WaitReasons.Set(c, WaitReasons.Danger);
return false;
}
Pawn e = Enforcers.Pick(c, EnforcerNeed.Arrest, out string reason);
if (e == null)
{
if (WaitReasons.Set(c, reason) && reason == WaitReasons.NoEnforcer && CaseLetters.Once(c, CaseLetters.KindNoEnforcer))
CaseLetters.NoEnforcer(c);
return false;
}
Building_Bed bed = FindPrisonerBed(o, e);
if (bed == null)
{
if (WaitReasons.Set(c, WaitReasons.NoBed) && CaseLetters.Once(c, CaseLetters.KindNoBed))
NoBedLetter(c);
return false;
}
if (!Enforcers.CanTakeToBed(e, o, bed))
{
WaitReasons.Set(c, WaitReasons.Reserved);
return false;
}
Guilt.AtLeast(o, RenewalTicks(c));
NoteOldBed(c, o);
// The float menu offers Arrest only to drafted pawns (FloatMenuOptionProvider_Arrest.cs:27-30), so
// Laws builds the job as it does (:52-54).
Job job = JobMaker.MakeJob(o.Downed ? JobDefOf.Capture : JobDefOf.Arrest, o, bed);
job.count = 1;
c.enforcer = e;
c.status = CaseStatus.Enforcing;
c.waitReason = null;
if (EnforcerJobs.Start(e, job))
return true;
WaitReasons.Set(c, WaitReasons.Reserved);
return false;
}
/// <summary>
/// "Subdue then jail", in the tick the hit downed the offender: renews guilt and puts a vanilla Capture
/// to a prisoner bed at the front of the enforcer's queue (JobQueue.cs:40), so it is the enforcer's
/// next job, ahead of a doctor's rescue. A queued job fails its reservations silently
/// (Pawn_JobTracker.cs:336, 373-375), and a queued vanilla Capture is safe in a save. The case runs as
/// Jail from here; no bed or a hold leaves it waiting.
/// </summary>
public static void CaptureAfterSubdue(LawCase c, Pawn enforcer)
{
Become(c);
Pawn o = c?.offender;
if (o == null || enforcer?.jobs == null || c.IsClosed)
return;
if (DlcSupport.HeldForArrestNow(o) && !HoldLifted(c))
{
if (WaitReasons.Set(c, WaitReasons.Hold) && CaseLetters.Once(c, CaseLetters.KindHold))
HoldLetter(c);
return;
}
Building_Bed bed = FindPrisonerBed(o, enforcer);
if (bed == null)
{
if (WaitReasons.Set(c, WaitReasons.NoBed) && CaseLetters.Once(c, CaseLetters.KindNoBed))
NoBedLetter(c);
return;
}
Guilt.AtLeast(o, RenewalTicks(c));
NoteOldBed(c, o);
Job job = JobMaker.MakeJob(JobDefOf.Capture, o, bed);
job.count = 1;
job.playerForced = true;
enforcer.jobs.jobQueue.EnqueueFirst(job, JobTag.Misc);
c.enforcer = enforcer;
c.status = CaseStatus.Enforcing;
c.waitReason = null;
}
/// <summary>
/// A prisoner bed the enforcer can take the offender to, as the arrest float menu searches
/// (FloatMenuOptionProvider_Arrest.cs:41-49): first respecting other reservations, then ignoring
/// them. The caller checks the reservations before it starts a job.
/// </summary>
public static Building_Bed FindPrisonerBed(Pawn offender, Pawn enforcer)
{
if (offender == null || enforcer == null)
return null;
return RestUtility.FindBedFor(offender, enforcer, checkSocialProperness: false, ignoreOtherReservations: false, GuestStatus.Prisoner)
?? RestUtility.FindBedFor(offender, enforcer, checkSocialProperness: false, ignoreOtherReservations: true, GuestStatus.Prisoner);
}
/// <summary>
/// The bed the offender owns, right before the job: the arrest's first toil claims the prisoner bed,
/// which unclaims the colonist's own (JobDriver_TakeToBed.cs:73; Pawn_Ownership.cs:125-138), and a
/// failed job gives up only the prisoner bed (JobDriver_TakeToBed.cs:74-80).
/// </summary>
public static void NoteOldBed(LawCase c, Pawn o)
{
Building_Bed owned = o?.ownership?.OwnedBed;
if (owned != null && !owned.ForPrisoners && !owned.Medical)
c.oldBed = owned;
}
/// <summary>
/// After an Arrest or Capture that ended without a prisoner: reclaims the old bed if it is still free.
/// A bed someone else claimed meanwhile stays theirs (ClaimBedIfNonMedical would evict them).
/// </summary>
public static void GiveOldBedBack(LawCase c)
{
Pawn o = c?.offender;
Building_Bed bed = c?.oldBed;
if (o?.ownership == null || bed == null || o.Dead || o.IsPrisonerOfColony)
return;
if (!bed.Spawned || bed.Destroyed || bed.ForPrisoners || bed.Medical)
return;
Building_Bed owned = o.ownership.OwnedBed;
if (owned == bed || (owned != null && !owned.ForPrisoners))
return;
if (!bed.AnyUnownedSleepingSlot)
return;
o.ownership.ClaimBedIfNonMedical(bed);
}
/// <summary>
/// A slave's jail row in this release (no "Jail for slaves" yet: releasing an imprisoned slave sends it
/// back to its old faction, GenGuest.cs:14-19): subdue while it is in a break, else warn.
/// </summary>
public static void SlaveFallback(LawCase c)
{
Pawn o = c?.offender;
if (o == null || c.IsClosed)
return;
if (!o.Downed && SubdueFlow.InBreak(c) && !Enforcers.FightsBack(o) && !DlcSupport.IsChild(o))
{
c.activePunishment = BlaxLawsDefOf.Subdue?.defName ?? "Subdue";
c.waitReason = null;
SubdueFlow.TryIssue(c, EnforcerNeed.Subdue);
return;
}
SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedSlave");
}
/// <summary>The offender became a prisoner without Laws (by hand, another mod): Laws never touches it and closes the case.</summary>
public static void AlreadyPrisoner(LawCase c)
{
if (c == null || c.IsClosed || c.status == CaseStatus.Jailed)
return;
CaseMessages.Post(c, "BlaxLaws_MsgAlreadyPrisoner".Translate(c.OffenderLabel));
GameComponent_BlaxLaws.Instance?.CloseCase(c, EnforcementOutcomes.AlreadyPrisoner);
}
/// <summary>Why Laws holds the arrest of this pawn: its ideoligion role or the mechs it controls. For the hold letter and the "Arrest now" tooltip.</summary>
public static string HoldReason(Pawn p)
{
string name = p?.LabelShort ?? "?";
return DlcSupport.HoldsRole(p)
? "BlaxLaws_HoldRole".Translate(name).Resolve()
: "BlaxLaws_HoldMechs".Translate(name).Resolve();
}
private static void HoldLetter(LawCase c) =>
CaseLetters.Send(c, "BlaxLaws_LetterHoldLabel", "BlaxLaws_LetterHoldText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label, HoldReason(c.offender));
private static void NoBedLetter(LawCase c) =>
CaseLetters.Send(c, "BlaxLaws_LetterNoBedLabel", "BlaxLaws_LetterNoBedText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label);
}
}

View File

@ -0,0 +1,94 @@
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Jail for N days (design: "Jail for N days"). Start convicts (guilt for the sentence) and arrests
/// through JailFlow: guilt renewed right before the job, a prisoner bed, the old bed noted, Arrest or
/// Capture with reservation checks. A break hostile to the colony waits until it ends or the pawn is
/// down; a role holder or mechanitor waits for "Arrest now"; a slave falls back to subdue in a break,
/// else warn. The sweep retries waits (a missing bed every 2500 ticks) and gives the old bed back when an
/// arrest ended without a prisoner; Sentences takes over at the capture. An arrest or capture not yet
/// carrying the offender is called off when danger comes.
/// </summary>
public class PunishmentWorker_Jail : PunishmentWorker
{
public override void Start(LawCase c, Law law, LawStage stage)
{
Pawn o = c?.offender;
if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed || JailFlow.ArrestRuns(c))
return;
if (DlcSupport.IsSlave(o))
{
JailFlow.SlaveFallback(c);
return;
}
// Conviction: guilt for the sentence when the case is filed. The arrest may come days later; it
// renews the guilt right before the job, and the sentence counts from the capture.
Guilt.AtLeast(o, JailFlow.SentenceTicks(c));
JailFlow.Become(c);
JailFlow.TryArrest(c, ignoreHold: false);
}
public override void Sweep(LawCase c)
{
if (c == null || c.IsClosed || c.status == CaseStatus.Jailed)
return;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (!BlaxLawsMod.S.enforceLaws)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.NotEnforced);
return;
}
Pawn o = c.offender;
if (o == null || o.Dead)
{
Stop(c);
comp?.CloseCase(c, CaseOutcomes.OffenderGone);
return;
}
if (c.status == CaseStatus.Enforcing)
{
if (JailFlow.ArrestRuns(c))
{
// Danger since the start: the arrest or the queued capture is called off and the case waits.
JailFlow.CallOffInDanger(c);
return;
}
if (o.IsPrisonerOfColony)
{
JailFlow.AlreadyPrisoner(c);
return;
}
// The Arrest or Capture ended without a prisoner (interrupted, refused, reservations lost).
JailFlow.GiveOldBedBack(c);
c.status = CaseStatus.Open;
c.waitReason = null;
}
if (c.waitReason == WaitReasons.NoBed && (Find.TickManager.TicksGame % Enforcement.SentenceInterval) != 0)
return;
JailFlow.TryArrest(c, ignoreHold: false);
}
public override void SentenceSweep(LawCase c) => Sentences.Check(c);
/// <summary>
/// Ends an unfinished arrest and gives the old bed back (a later stage takes over). A jailed case is
/// stopped only when its law is repealed: the pawn Laws jailed gets "Release".
/// </summary>
public override void Stop(LawCase c)
{
if (c == null)
return;
if (c.status == CaseStatus.Jailed)
{
Sentences.ReleaseOnRepeal(c);
return;
}
JailFlow.EndArrest(c);
if (!c.IsClosed)
c.status = CaseStatus.Open;
}
}
}

View File

@ -0,0 +1,173 @@
using System;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Serving the sentence (design: "Jail for N days"). Hook K (Patch_Pawn_GuestTracker_CapturedBy) moves a
/// case to Jailed at the capture and starts the sentence there, not at filing; "Maintain only" lands two
/// ticks later, after any next-tick default from Blax Castes or a prison mod. Every 2500 ticks Check sets
/// "Release" once the sentence is served, releases in place a day later if no warden did, and closes the
/// case when the pawn is out (served, released early, escaped, dead). Laws writes the prisoner
/// interaction mode only on pawns it jailed itself.
/// </summary>
public static class Sentences
{
/// <summary>A day after the release tick without a release, Laws releases the pawn in place.</summary>
public const int FallbackTicks = GenDate.TicksPerDay;
private static int Now => Find.TickManager?.TicksGame ?? 0;
/// <summary>
/// Writes "Maintain only" on a pawn Laws jailed, two ticks after the capture
/// (Pawn_GuestTracker.cs:304), and sets maintainOnlyDone. Two ticks win over Castes' next-tick default
/// and Prison Labor's default in any component order (GameComponentUtility.cs:24-31; Game.cs:472-489).
/// </summary>
public static void WriteMaintainOnly(LawCase c)
{
if (c == null || c.IsClosed || c.status != CaseStatus.Jailed || c.maintainOnlyDone)
return;
Pawn p = c.offender;
if (p?.guest == null || !p.IsPrisonerOfColony)
return;
p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.MaintainOnly);
c.maintainOnlyDone = true;
}
/// <summary>
/// Every 2500 ticks for a jailed case: the early end, the "Maintain only" backstop, "Release" at the
/// release tick (wardens take it through WorkGiver_Warden_ReleasePrisoner, which calls
/// GenGuest.PrisonerRelease: WasImprisoned, unclaim, free again, GenGuest.cs:8-21), and the fallback.
/// </summary>
public static void Check(LawCase c)
{
if (c == null || c.IsClosed || c.status != CaseStatus.Jailed)
return;
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null)
return;
Pawn p = c.offender;
int now = Now;
if (p == null || LawCase.IsGone(p))
{
comp.CloseCase(c, CaseOutcomes.OffenderGone);
return;
}
if (p.Dead)
{
CaseMessages.Post(c, "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel));
comp.CloseCase(c, EnforcementOutcomes.Died);
return;
}
if (c.releaseTick < 0)
c.releaseTick = (c.captureTick >= 0 ? c.captureTick : now) + JailFlow.SentenceTicks(c);
bool served = now >= c.releaseTick;
if (!p.IsPrisonerOfColony)
{
// Out of Laws' custody: released by a warden after the sentence, or early (recruited,
// released by hand or by another mod), or escaped off the map.
if (!p.Spawned && !served)
{
CaseMessages.Post(c, "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel));
comp.CloseCase(c, EnforcementOutcomes.Escaped);
}
else if (served)
{
CaseMessages.Post(c, "BlaxLaws_MsgBackAtWork".Translate(c.OffenderLabel));
comp.CloseCase(c, CaseOutcomes.Served);
}
else
{
CaseMessages.Post(c, "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel));
comp.CloseCase(c, CaseOutcomes.ReleasedEarly);
}
return;
}
if (!c.maintainOnlyDone && !Enforcement.IsQueued(c, CaseTask.MaintainOnly))
WriteMaintainOnly(c);
if (!served)
return;
if (p.guest.ExclusiveInteractionMode != PrisonerInteractionModeDefOf.Release)
{
p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.Release);
CaseMessages.Post(c, "BlaxLaws_MsgSentenceServed".Translate(c.OffenderLabel));
}
if (now >= c.releaseTick + FallbackTicks && p.Spawned)
{
// Nobody released it (no warden, unreachable, a break): Laws releases it where it is.
GenGuest.PrisonerRelease(p);
CaseMessages.Post(c, "BlaxLaws_MsgReleasedInPlace".Translate(c.OffenderLabel));
comp.CloseCase(c, CaseOutcomes.Served);
}
}
/// <summary>The Cases tab's "Arrest now" applies: a jail case held for a role holder or mechanitor.</summary>
public static bool CanArrestNow(LawCase c) =>
c?.offender != null && !c.IsClosed && c.status == CaseStatus.Open && c.waitReason == WaitReasons.Hold;
/// <summary>"Arrest now" on a held case: lifts the hold, renews guilt and starts the arrest (or leaves it waiting for a bed or an enforcer).</summary>
public static void ArrestNow(LawCase c)
{
if (!CanArrestNow(c))
return;
JailFlow.LiftHold(c);
JailFlow.Become(c);
JailFlow.TryArrest(c, ignoreHold: true);
}
/// <summary>Ticks of the sentence left for a jailed case, or -1. The Cases tab counts down with it.</summary>
public static int TicksLeft(LawCase c) =>
c != null && c.status == CaseStatus.Jailed && c.releaseTick >= 0 ? Math.Max(0, c.releaseTick - Now) : -1;
/// <summary>This capture is the one Laws sent: the case's own enforcer took the offender for a jail case.</summary>
public static bool IsOurCapture(LawCase c, Pawn byPawn)
{
if (c == null || c.IsClosed || c.status != CaseStatus.Enforcing || byPawn == null || c.enforcer != byPawn)
return false;
string p = c.activePunishment;
return p != null && (p == BlaxLawsDefOf.Jail?.defName || p == BlaxLawsDefOf.SubdueThenJail?.defName);
}
/// <summary>
/// Hook K's postfix: the sentence starts at the capture. Records the capture and release ticks, queues
/// "Maintain only" two ticks on, and sends the jail letter.
/// </summary>
internal static void OnCaptured(LawCase c)
{
int now = Now;
c.activePunishment = BlaxLawsDefOf.Jail?.defName ?? "Jail";
c.status = CaseStatus.Jailed;
c.waitReason = null;
c.captureTick = now;
c.releaseTick = now + JailFlow.SentenceTicks(c);
c.maintainOnlyDone = false;
Enforcement.Schedule(c, CaseTask.MaintainOnly, c.activeStage, Enforcement.MaintainOnlyDelay);
CaseLetters.Jailed(c);
}
/// <summary>
/// The law of a jailed case was repealed (Lawbook.Delete stops the case): Laws sets "Release" on the
/// pawn it jailed, so a warden lets it go.
/// </summary>
internal static void ReleaseOnRepeal(LawCase c)
{
Pawn p = c?.offender;
if (p?.guest == null || !p.IsPrisonerOfColony)
return;
p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.Release);
CaseMessages.Post(c, "BlaxLaws_MsgRepealedRelease".Translate(c.OffenderLabel));
}
/// <summary>The release day as a date at the offender's map.</summary>
public static string ReleaseDate(LawCase c)
{
if (c == null || c.releaseTick < 0)
return "";
Map map = c.offender?.MapHeld;
Vector2 at = map != null ? Find.WorldGrid.LongLatOf(map.Tile) : Vector2.zero;
return GenDate.DateFullStringAt(GenDate.TickGameToAbs(c.releaseTick), at);
}
}
}

View File

@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>Textures the Laws tab uses, all vanilla.</summary>
[StaticConstructorOnStartup]
internal static class LawsTex
{
/// <summary>The overlap icon: vanilla's warning sign, or the info button when a texture pack lacks it.</summary>
public static readonly Texture2D Overlap = ContentFinder<Texture2D>.Get("UI/Widgets/Warning", false) ?? TexButton.Info;
public static readonly Texture2D InBook = Widgets.CheckboxOnTex;
}
/// <summary>
/// The icon of a catalogue entry (design: "Act picker"): the thing's icon for ate, used and bills, the
/// interaction symbol for interactions, nothing otherwise (the label carries it). Never throws into the
/// GUI: a broken modded icon logs once and draws nothing.
/// </summary>
public static class ActIcons
{
private static readonly Dictionary<InteractionDef, Texture2D> symbols = new Dictionary<InteractionDef, Texture2D>();
// InteractionDef.symbol is private; reading the path first keeps ContentFinder from logging an error
// for a modded interaction without one.
private static readonly FieldInfo SymbolPath = AccessTools.Field(typeof(InteractionDef), "symbol");
/// <summary>Whether the entry draws an icon.</summary>
public static bool HasIcon(ActEntry e)
{
switch (e?.def)
{
case ThingDef _:
return true;
case RecipeDef r:
return r.UIIconThing != null || r.UIIcon != null;
case InteractionDef i:
return Symbol(i) != null;
default:
return false;
}
}
public static void Draw(Rect rect, ActEntry e)
{
if (e?.def == null)
return;
try
{
switch (e.def)
{
case ThingDef t:
Widgets.DefIcon(rect, t);
break;
case RecipeDef r when r.UIIconThing != null || r.UIIcon != null:
Widgets.DefIcon(rect, r);
break;
case InteractionDef i:
Texture2D tex = Symbol(i);
if (tex != null)
GUI.DrawTexture(rect, tex);
break;
}
}
catch (Exception ex)
{
LawsLog.Once("Icon of " + e.key, ex);
}
}
private static Texture2D Symbol(InteractionDef def)
{
if (symbols.TryGetValue(def, out Texture2D tex))
return tex;
tex = null;
try
{
// Ideoligion and faction symbols depend on the initiator; the picker shows the def's own symbol only.
string path = SymbolPath?.GetValue(def) as string;
if (!path.NullOrEmpty() && def.symbolSource == InteractionSymbolSource.Def)
tex = def.GetSymbol();
}
catch (Exception ex)
{
LawsLog.Once("Symbol of " + def.defName, ex);
}
symbols[def] = tex;
return tex;
}
}
}

View File

@ -0,0 +1,279 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The overlap icon of the lawbook (design: "Lawbook tab", row spec, and "One act, one case"): a row
/// that can catch the same act as a row of another category. Outside a break each category files its
/// own case, so a dose can open an "Ate" case and a "Recorded acts" case at once; the icon says so.
///
/// Only did-it rows outside the breaks take part: inside a break the break case owns the act. Rows that
/// are off or whose entry is missing catch nothing and are left out. The pairs come from what one game
/// act records in each category, read from the game code:
///
/// - Ate and Recorded acts: Thing.Ingested records the eating events (Verse/Thing.cs:2031-2129) and
/// CompDrug.PostIngested the drug events (RimWorld/CompDrug.cs:105-113) for the eater as doer.
/// - Ate and Records: the ingest toil adds the nutrition eaten (RimWorld/Toils_Ingest.cs:432).
/// - Bills and Records: a finished bill counts meals cooked or things crafted
/// (RimWorld/RecordsUtility.cs:52-75), a surgery the operations performed (RimWorld/Bill_Medical.cs:138).
///
/// Cached per lawbook write (Watch.Version) and catalogue build; the tab reads it every frame.
/// </summary>
public static class ActOverlaps
{
private static readonly List<Law> None = new List<Law>();
private static readonly Dictionary<Law, List<Law>> byLaw = new Dictionary<Law, List<Law>>();
private static readonly Dictionary<string, bool> pairCache = new Dictionary<string, bool>();
private static int cachedWatch = -1;
private static int cachedCatalogue = -1;
private static int cachedCount = -1;
// The game the cache belongs to, by identity hash, so the cache never keeps a finished game alive.
private static int cachedComp;
/// <summary>The rows of other categories that can catch the same act as this row. Empty when none.</summary>
public static IReadOnlyList<Law> Of(Law law)
{
if (law == null)
return None;
Refresh();
return byLaw.TryGetValue(law, out List<Law> list) ? list : None;
}
/// <summary>Whether the row takes part in overlaps at all: on, resolving, did it, outside the breaks.</summary>
public static bool Counts(Law law)
{
if (law == null || !law.enabled || law.stage != LawStage.DidIt)
return false;
ActEntry e = law.Entry;
return e != null && !e.IsBreak && e.HasStage(LawStage.DidIt);
}
/// <summary>Whether one game act can be caught by both entries (different categories only).</summary>
public static bool Overlap(ActEntry a, ActEntry b)
{
if (a == null || b == null || a.categoryId == b.categoryId)
return false;
string key = string.CompareOrdinal(a.key, b.key) < 0 ? a.key + "|" + b.key : b.key + "|" + a.key;
if (pairCache.TryGetValue(key, out bool known))
return known;
bool result = HookGuard.Run("Overlap " + key, () => Compute(a, b), false);
pairCache[key] = result;
return result;
}
/// <summary>Drops the cache. The next read builds it again.</summary>
public static void Reset()
{
byLaw.Clear();
pairCache.Clear();
cachedWatch = -1;
}
private static void Refresh()
{
IReadOnlyList<Law> laws = Lawbook.Laws;
GameComponent_BlaxLaws instance = GameComponent_BlaxLaws.Instance;
int comp = instance == null ? 0 : System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(instance);
if (cachedWatch == Watch.Version && cachedCatalogue == ActCatalogue.Version && cachedCount == laws.Count && cachedComp == comp)
return;
cachedWatch = Watch.Version;
cachedCount = laws.Count;
cachedComp = comp;
if (cachedCatalogue != ActCatalogue.Version)
{
pairCache.Clear();
cachedCatalogue = ActCatalogue.Version;
}
byLaw.Clear();
for (int i = 0; i < laws.Count; i++)
{
Law a = laws[i];
if (!Counts(a))
continue;
for (int j = i + 1; j < laws.Count; j++)
{
Law b = laws[j];
if (!Counts(b) || !Overlap(a.Entry, b.Entry))
continue;
Add(a, b);
Add(b, a);
}
}
}
private static void Add(Law of, Law other)
{
if (!byLaw.TryGetValue(of, out List<Law> list))
byLaw[of] = list = new List<Law>();
list.Add(other);
}
private static bool Compute(ActEntry a, ActEntry b)
{
if (Is(a, b, ActCategories.Ate, ActCategories.RecordedAct, out ActEntry ate, out ActEntry rec))
return Any(ate, rec, (t, e) => t is ThingDef td && e is HistoryEventDef ev && IngestionRecords(td, ev));
if (Is(a, b, ActCategories.Ate, ActCategories.Record, out ate, out rec))
return Any(ate, rec, (t, r) => t is ThingDef td && r is RecordDef rd && rd == RecordDefOf.NutritionEaten && td.IsNutritionGivingIngestible);
if (Is(a, b, ActCategories.Bill, ActCategories.Record, out ActEntry bill, out rec))
return Any(bill, rec, (x, r) => x is RecipeDef recipe && r is RecordDef rd && BillCounts(recipe, rd));
return false;
}
private static bool Is(ActEntry a, ActEntry b, string catA, string catB, out ActEntry first, out ActEntry second)
{
if (a.categoryId == catA && b.categoryId == catB)
{
first = a;
second = b;
return true;
}
if (b.categoryId == catA && a.categoryId == catB)
{
first = b;
second = a;
return true;
}
first = second = null;
return false;
}
/// <summary>True when some member def of a and some member def of b make the pair.</summary>
private static bool Any(ActEntry a, ActEntry b, Func<Def, Def, bool> pair)
{
List<Def> mb = Members(b);
if (mb.Count == 0)
return false;
foreach (Def da in Members(a))
{
for (int i = 0; i < mb.Count; i++)
{
if (pair(da, mb[i]))
return true;
}
}
return false;
}
/// <summary>The defs an entry covers: its def, or every def entry of its category the group matches.</summary>
public static List<Def> Members(ActEntry e)
{
var result = new List<Def>();
if (e == null)
return result;
if (e.def != null)
{
result.Add(e.def);
return result;
}
ActGroup g = e.group;
if (g == null)
return result;
foreach (ActEntry d in ActCatalogue.EntriesOf(e.categoryId))
{
if (d.def == null)
continue;
bool member;
try
{
member = g.IsAny || g.MatchesDef(d.def);
}
catch (Exception ex)
{
HookGuard.Fail("Overlap group " + g.Key, ex);
member = false;
}
if (member)
result.Add(d.def);
}
return result;
}
/// <summary>
/// Whether eating a thing of this def can record the event with the eater as doer. Def-level, so it
/// says "can": a meal records human meat only when one of its ingredients is.
/// </summary>
public static bool IngestionRecords(ThingDef t, HistoryEventDef ev)
{
if (t?.ingestible == null || ev == null)
return false;
if (t.ingestible.ateEvent == ev)
return true;
bool drug = t.GetCompProperties<CompProperties_Drug>() != null;
bool ingredients = t.HasComp(typeof(CompIngredients));
bool humanMeat = HumanlikeMeatOrCorpse(t);
bool rawPlant = t.thingCategories != null && t.thingCategories.Contains(ThingCategoryDefOf.PlantFoodRaw);
bool meat = t.IsMeat || t.IsCorpse;
switch (ev.defName)
{
// RimWorld/CompDrug.cs:105-113
case "IngestedDrug":
return drug;
case "IngestedHardDrug":
return drug && t.ingestible.drugCategory == DrugCategory.Hard;
case "IngestedRecreationalDrug":
return drug && t.IsNonMedicalDrug;
// Verse/Thing.cs:2031-2045, 2089-2104
case "AteHumanMeat":
return humanMeat || ingredients;
case "AteHumanMeatDirect":
return humanMeat;
case "AteHumanMeatAsIngredient":
case "AteInsectMeatAsIngredient":
case "AteFungusAsIngredient":
case "AteNonFungusMealWithPlants":
return ingredients;
// Verse/Thing.cs:2046-2049
case "AteNonCannibalFood":
return t.IsNutritionGivingIngestible && !humanMeat;
// Verse/Thing.cs:2055-2071
case "AteMeat":
return meat && !t.IsProcessedFood && !humanMeat;
case "AteNonMeat":
return !meat && !t.IsProcessedFood && !t.IsDrug && t.IsNutritionGivingIngestible;
// Verse/Thing.cs:2072-2086
case "AteVeneratedAnimalMeat":
return meat || ingredients;
case "AteFungus":
case "AteNonFungusPlant":
return rawPlant;
default:
return false;
}
}
private static bool HumanlikeMeatOrCorpse(ThingDef t)
{
if (t.IsCorpse)
return t.ingestible?.sourceDef?.race?.Humanlike ?? false;
return FoodUtility.GetMeatSourceCategory(t) == MeatSourceCategory.Humanlike;
}
/// <summary>Whether finishing one iteration of the recipe raises the record for the doer.</summary>
public static bool BillCounts(RecipeDef recipe, RecordDef record)
{
if (recipe == null || record == null)
return false;
if (record == RecordDefOf.OperationsPerformed)
return recipe.IsSurgery;
if (recipe.products == null)
return false;
foreach (ThingDefCountClass p in recipe.products)
{
ThingDef d = p?.thingDef;
if (d == null)
continue;
// RimWorld/RecordsUtility.cs:58-65 and ShouldIncrementThingsCrafted :69-75
bool meal = d.IsNutritionGivingIngestible && (int)d.ingestible.preferability >= 7;
if (meal && record == RecordDefOf.MealsCooked)
return true;
if (!meal && record == RecordDefOf.ThingsCrafted &&
(d.IsApparel || d.IsWeapon || d.HasComp(typeof(CompArt)) || d.HasComp(typeof(CompQuality))))
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,154 @@
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>One visible line of the act picker: a category header or an entry.</summary>
public sealed class ActPickerRow
{
public ActCategoryDef category;
/// <summary>Null for a category header.</summary>
public ActEntry entry;
/// <summary>Header: the category is open.</summary>
public bool open;
/// <summary>Header: entries that pass the search (all of them without a search).</summary>
public int count;
/// <summary>Entry: the lawbook has a row for this act key (the tick).</summary>
public bool inBook;
public bool IsHeader => entry == null;
public override string ToString() => IsHeader ? "[" + category?.defName + " " + count + (open ? " open" : "") + "]" : entry.key + (inBook ? " (in book)" : "");
}
/// <summary>
/// The act picker's tree (design: "Act picker"): the catalogue's categories as collapsible headers, each
/// with its groups first and then every entry A to Z (ActCatalogue's order). The search matches each
/// entry's label and defName; typing filters every category at once, opens those with hits and hides
/// those without. The visible lines are rebuilt only when the search, an open state, the catalogue or the
/// lawbook changes, so the window draws only the lines in view, even with hundreds of bills.
/// </summary>
public sealed class ActPickerTree
{
public readonly QuickSearchFilter filter = new QuickSearchFilter();
private readonly HashSet<string> open = new HashSet<string>();
private readonly List<ActPickerRow> rows = new List<ActPickerRow>();
private readonly HashSet<string> inBook = new HashSet<string>();
private string builtText;
private int builtCatalogue = -1;
private int builtWatch = -1;
private int builtLaws = -1;
private bool dirty = true;
/// <summary>The lines to draw, top to bottom.</summary>
public IReadOnlyList<ActPickerRow> Rows
{
get
{
Refresh();
return rows;
}
}
/// <summary>Entries the search leaves, over every category.</summary>
public int Hits { get; private set; }
public string SearchText
{
get => filter.Text;
set
{
if (filter.Text == value)
return;
filter.Text = value ?? "";
dirty = true;
}
}
/// <summary>Whether the category's entries show. While searching, a category with hits is always open.</summary>
public bool IsOpen(string categoryId) => filter.Active || open.Contains(categoryId);
/// <summary>Opens or closes a category (no effect while searching, when hits decide).</summary>
public void Toggle(string categoryId)
{
if (filter.Active || categoryId == null)
return;
if (!open.Remove(categoryId))
open.Add(categoryId);
dirty = true;
}
public void SetOpen(string categoryId, bool isOpen)
{
if (categoryId == null)
return;
if (isOpen ? open.Add(categoryId) : open.Remove(categoryId))
dirty = true;
}
/// <summary>Whether the entry passes the search: its label or its defName (a group's id) contains the text.</summary>
public bool Matches(ActEntry e)
{
if (e == null)
return false;
if (!filter.Active)
return true;
return filter.Matches(e.label) || filter.Matches(e.name) || (e.def != null && filter.Matches(e.def.defName));
}
/// <summary>The entry rows of a category that pass the search, in picker order.</summary>
public List<ActEntry> EntriesShown(string categoryId)
{
var list = new List<ActEntry>();
foreach (ActEntry e in ActCatalogue.EntriesOf(categoryId))
{
if (Matches(e))
list.Add(e);
}
return list;
}
public void MarkDirty() => dirty = true;
private void Refresh()
{
int laws = Lawbook.Laws.Count;
if (!dirty && builtText == filter.Text && builtCatalogue == ActCatalogue.Version && builtWatch == Watch.Version && builtLaws == laws)
return;
dirty = false;
builtText = filter.Text;
builtCatalogue = ActCatalogue.Version;
builtWatch = Watch.Version;
builtLaws = laws;
inBook.Clear();
foreach (Law l in Lawbook.Laws)
{
if (!l.actKey.NullOrEmpty())
inBook.Add(l.actKey);
}
rows.Clear();
Hits = 0;
foreach (ActCategoryDef cat in ActCatalogue.Categories)
{
List<ActEntry> shown = EntriesShown(cat.defName);
Hits += shown.Count;
if (filter.Active && shown.Count == 0)
continue;
bool isOpen = IsOpen(cat.defName);
rows.Add(new ActPickerRow { category = cat, open = isOpen, count = shown.Count });
if (!isOpen)
continue;
foreach (ActEntry e in shown)
rows.Add(new ActPickerRow { category = cat, entry = e, inBook = inBook.Contains(e.key) });
}
}
}
}

View File

@ -0,0 +1,201 @@
using System.Collections.Generic;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The logic behind the Cases tab (design: "Lawbook tab", Cases): cases newest first with who, what,
/// stage, when, punishment and status, the jump to the pawn, and "Arrest now" for a held case. Reads
/// the component only; "Arrest now" goes through Sentences.
/// </summary>
public static class CaseLog
{
/// <summary>Cases newest first, as a new list (see FillRows). Closed ones only when asked.</summary>
public static List<LawCase> Rows(bool includeClosed)
{
var rows = new List<LawCase>();
FillRows(rows, includeClosed);
return rows;
}
/// <summary>
/// Fills the list with the cases newest first; among cases of one tick the higher severity first, then the
/// higher id. Closed ones only when asked. The Cases tab calls it on every GUI event with a list it keeps,
/// so it allocates nothing and sorts nothing it doesn't have to: cases are added in the order they open, so
/// walking them backwards is already in order, and the insertion sort only moves cases of one tick.
/// </summary>
public static void FillRows(List<LawCase> into, bool includeClosed)
{
if (into == null)
return;
into.Clear();
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null)
return;
IReadOnlyList<LawCase> all = comp.Cases;
for (int i = all.Count - 1; i >= 0; i--)
{
LawCase c = all[i];
if (c == null || (!includeClosed && c.IsClosed))
continue;
int j = into.Count - 1;
into.Add(c);
while (j >= 0 && ShowsBefore(c, into[j]))
{
into[j + 1] = into[j];
j--;
}
into[j + 1] = c;
}
}
private static bool ShowsBefore(LawCase a, LawCase b)
{
if (a.openTick != b.openTick)
return a.openTick > b.openTick;
if (a.severity != b.severity)
return a.severity > b.severity;
return a.id > b.id;
}
/// <summary>The offender's name, with the victim when the case has one.</summary>
public static string Who(LawCase c)
{
if (c == null)
return "";
string victim = c.VictimLabel;
return victim.NullOrEmpty() ? c.OffenderLabel : "BlaxLaws_CaseWhoVictim".Translate(c.OffenderLabel, victim).ToString();
}
/// <summary>The row's action, the def that matched when it differs, the count and the notes.</summary>
public static string What(LawCase c)
{
if (c == null)
return "";
Law law = c.CurrentLaw;
string text = law != null ? LawbookUi.ActionLabel(law) : LawbookUi.CategoryLabel(ActKey.CategoryOf(c.actKey)) + ": " + (ActKey.NameOf(c.actKey) ?? c.actKey);
string matched = MatchedLabel(c);
if (!matched.NullOrEmpty() && (law == null || !string.Equals(matched, law.Label, System.StringComparison.OrdinalIgnoreCase)))
text += " (" + matched + ")";
if (c.count > 1)
text += ", " + "BlaxLaws_CaseCount".Translate(c.count);
if ((c.notes & CaseNotes.OnTable) != 0)
text += ", " + "BlaxLaws_Note_OnTable".Translate();
if ((c.notes & CaseNotes.DugUp) != 0)
text += ", " + "BlaxLaws_Note_DugUp".Translate();
return text;
}
/// <summary>The label of the def that matched (which drug, which recipe, which break), or null.</summary>
public static string MatchedLabel(LawCase c)
{
string name = c?.matchedDef ?? c?.breakState;
if (name.NullOrEmpty())
return null;
string category = ActKey.CategoryOf(c.actKey);
ActEntry e = ActCatalogue.Get(ActKey.Of(category ?? "", name));
if (e != null)
return e.label;
// A dose during a binge matched an Ate def, not a Break def.
foreach (ActCategoryDef cat in ActCatalogue.Categories)
{
e = ActCatalogue.Get(ActKey.Of(cat.defName, name));
if (e != null)
return e.label;
}
return name;
}
public static string Stage(LawCase c) => c == null ? "" : LawLabels.Stage(c.stage);
/// <summary>"3 days ago", from the last act of the case.</summary>
public static string When(LawCase c)
{
if (c == null || Find.TickManager == null)
return "";
int ago = Find.TickManager.TicksGame - c.lastActTick;
if (ago < GenDate.TicksPerHour)
return "BlaxLaws_JustNow".Translate();
return "BlaxLaws_Ago".Translate(ago.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false));
}
/// <summary>The punishment the case runs or ran, with its days.</summary>
public static string Punishment(LawCase c)
{
if (c == null)
return "";
PunishmentDef active = Enforcement.ActiveOf(c);
Law law = c.LawFor(c.activeStage) ?? c.CurrentLaw;
PunishmentDef p = active ?? law?.PunishmentDef;
if (p == null)
return law?.punishment ?? "";
string text = p.LabelCap;
if (p.usesDays && law != null)
text += ", " + "BlaxLaws_DaysCount".Translate(law.days);
return text;
}
/// <summary>The status, with the outcome of a closed case, the countdown of a jailed one or why it waits.</summary>
public static string Status(LawCase c)
{
if (c == null)
return "";
string status = LawLabels.Status(c.status);
if (c.IsClosed)
return c.outcome.NullOrEmpty() ? status : CaseOutcomes.Label(c.outcome);
if (c.status == CaseStatus.Jailed && c.releaseTick >= 0 && Find.TickManager != null)
{
int left = c.releaseTick - Find.TickManager.TicksGame;
return left > 0
? "BlaxLaws_ReleaseIn".Translate(left.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false)).ToString()
: "BlaxLaws_ReleaseDue".Translate().ToString();
}
string wait = WaitReasons.Label(c.waitReason);
return wait.NullOrEmpty() ? status : status + ": " + wait;
}
/// <summary>
/// "Arrest now" shows for a case that waits on the hold: the jail of a role holder or a mechanitor with
/// mechs, which Laws doesn't arrest on its own (design: "Jail for N days", hold).
/// </summary>
public static bool CanArrestNow(LawCase c) =>
c != null && c.offender != null && !LawCase.IsGone(c.offender) && Sentences.CanArrestNow(c);
/// <summary>Why the case is held, for the button's tooltip.</summary>
public static string HoldReason(Pawn p) => JailFlow.HoldReason(p);
/// <summary>The "Arrest now" button: renews guilt and starts the arrest (Sentences.ArrestNow).</summary>
public static void ArrestNow(LawCase c)
{
if (!CanArrestNow(c))
return;
HookGuard.Run("Arrest now", () => Sentences.ArrestNow(c));
}
/// <summary>Whether the jump button can show the offender: alive or dead, on a map, carried, in a caravan.</summary>
public static bool CanJump(LawCase c)
{
Pawn p = c?.offender;
if (p == null || LawCase.IsGone(p))
return false;
return CameraJumper.CanJump(Target(p));
}
/// <summary>The jump button: selects the offender (its corpse when dead) the vanilla way.</summary>
public static void JumpTo(LawCase c)
{
if (!CanJump(c))
return;
HookGuard.Run("Jump to offender", () => CameraJumper.TryJumpAndSelect(Target(c.offender)));
}
private static GlobalTargetInfo Target(Pawn p)
{
if (p.Dead && p.Corpse != null)
return p.Corpse;
return p;
}
}
}

View File

@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace BlaxLaws
{
/// <summary>
/// The act picker (design: "Lawbook tab", Act picker), a window like the ingredient filter of a tailoring
/// bill: the vanilla QuickSearchWidget on top, below it the catalogue's categories as a collapsible tree
/// (ActPickerTree), groups first, then every entry A to Z with its icon and its source mod in grey. An
/// entry already in the book shows a tick. One click picks an entry and closes the window. Only the lines
/// in view are drawn.
/// </summary>
public class Dialog_PickAct : Window
{
private const float RowHeight = 26f;
private const float IconSize = 24f;
private const float Indent = 22f;
private const float TitleHeight = 36f;
private const float Gap = 6f;
private readonly Action<string> onPick;
private readonly QuickSearchWidget search = new QuickSearchWidget();
private readonly ActPickerTree tree = new ActPickerTree();
private Vector2 scroll;
private bool focusSearch = true;
/// <summary>The tree the window draws, for tests and callers that preset the search.</summary>
public ActPickerTree Tree => tree;
/// <param name="onPick">Called with the picked act key.</param>
public Dialog_PickAct(Action<string> onPick)
{
this.onPick = onPick;
doCloseX = true;
closeOnClickedOutside = true;
absorbInputAroundWindow = true;
forcePause = false;
onlyOneOfTypeAllowed = true;
}
/// <summary>"Add law": a pick adds a row (LawbookUi.AddFromPicker), or shows the existing one.</summary>
public static Dialog_PickAct ForNewRow() => new Dialog_PickAct(key => LawbookUi.AddFromPicker(key, out _));
/// <summary>A click on a row's Action: a pick changes the row's action (LawbookUi.ChangeAction).</summary>
public static Dialog_PickAct ForRow(Law law)
{
var d = new Dialog_PickAct(key => LawbookUi.ChangeAction(law, key));
string cat = law?.CategoryId;
if (cat != null)
d.tree.SetOpen(cat, true);
return d;
}
public override Vector2 InitialSize => new Vector2(560f, 680f);
public override void DoWindowContents(Rect inRect)
{
Rect title = new Rect(inRect.x, inRect.y, inRect.width, TitleHeight);
using (new TextBlock(GameFont.Medium))
Widgets.Label(title, "BlaxLaws_PickerTitle".Translate());
Rect searchRect = new Rect(inRect.x, title.yMax, inRect.width, QuickSearchWidget.WidgetHeight);
search.noResultsMatched = tree.filter.Active && tree.Hits == 0;
search.OnGUI(searchRect, () => tree.SearchText = search.filter.Text);
if (focusSearch)
{
search.Focus();
focusSearch = false;
}
if (tree.SearchText != search.filter.Text)
tree.SearchText = search.filter.Text;
Rect outRect = new Rect(inRect.x, searchRect.yMax + Gap, inRect.width, inRect.yMax - searchRect.yMax - Gap);
IReadOnlyList<ActPickerRow> rows = tree.Rows;
if (rows.Count == 0)
{
using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor))
Widgets.Label(outRect, tree.filter.Active ? "BlaxLaws_PickerNoMatch".Translate() : "BlaxLaws_PickerEmpty".Translate());
return;
}
Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, rows.Count * RowHeight);
Widgets.BeginScrollView(outRect, ref scroll, viewRect);
try
{
int first = Mathf.Max(0, Mathf.FloorToInt(scroll.y / RowHeight));
int last = Mathf.Min(rows.Count - 1, Mathf.CeilToInt((scroll.y + outRect.height) / RowHeight));
for (int i = first; i <= last; i++)
{
Rect r = new Rect(0f, i * RowHeight, viewRect.width, RowHeight);
try
{
if (rows[i].IsHeader)
DrawHeader(r, rows[i]);
else if (DrawEntry(r, rows[i], i))
break;
}
catch (Exception e)
{
LawsLog.Once("Act picker row", e);
}
}
}
finally
{
Widgets.EndScrollView();
}
}
private void DrawHeader(Rect r, ActPickerRow row)
{
Widgets.DrawHighlightIfMouseover(r);
Rect icon = new Rect(r.x, r.y + (r.height - 18f) / 2f, 18f, 18f);
GUI.DrawTexture(icon, row.open ? TexButton.Collapse : TexButton.Reveal);
Rect label = new Rect(icon.xMax + 6f, r.y, r.width - icon.width - 6f, r.height);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft))
Widgets.Label(label, "BlaxLaws_PickerCategory".Translate(row.category.LabelCap, row.count));
string tip = HookGuard.Run("Category tooltip", () => row.category.Worker.Tooltip, null);
if (!tip.NullOrEmpty())
TooltipHandler.TipRegion(r, tip);
if (Widgets.ButtonInvisible(r))
{
tree.Toggle(row.category.defName);
(row.open ? SoundDefOf.TabClose : SoundDefOf.TabOpen).PlayOneShotOnCamera();
}
}
/// <returns>True when the click picked the entry and the window closed.</returns>
private bool DrawEntry(Rect r, ActPickerRow row, int index)
{
ActEntry e = row.entry;
if (index % 2 == 1)
Widgets.DrawLightHighlight(r);
Widgets.DrawHighlightIfMouseover(r);
float x = r.x + Indent;
if (ActIcons.HasIcon(e))
{
ActIcons.Draw(new Rect(x, r.y + (r.height - IconSize) / 2f, IconSize, IconSize), e);
x += IconSize + 4f;
}
Rect tick = new Rect(r.xMax - 22f, r.y + (r.height - 18f) / 2f, 18f, 18f);
float sourceWidth = Mathf.Min(150f, r.width * 0.3f);
Rect source = new Rect(tick.x - sourceWidth - 4f, r.y, sourceWidth, r.height);
Rect label = new Rect(x, r.y, source.x - x - 4f, r.height);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft))
{
Widgets.Label(label, e.label.Truncate(label.width));
GUI.color = ColoredText.SubtleGrayColor;
Text.Anchor = TextAnchor.MiddleRight;
Widgets.Label(source, (e.sourceMod ?? "").Truncate(source.width));
GUI.color = Color.white;
}
if (row.inBook)
GUI.DrawTexture(tick, LawsTex.InBook);
TooltipHandler.TipRegion(r, () => EntryTooltip(e, row.inBook), e.key.GetHashCode());
if (!Widgets.ButtonInvisible(r))
return false;
SoundDefOf.Click.PlayOneShotOnCamera();
Pick(e.key);
return true;
}
/// <summary>The entry's tooltip: label, source, stages, what the act is and whether the book has it.</summary>
public static string EntryTooltip(ActEntry e, bool inBook)
{
if (e == null)
return null;
var parts = new List<string> { e.label, "BlaxLaws_SourceMod".Translate(e.sourceMod ?? DlcSupport.CoreName) };
string stages = string.Join(", ", Lawbook.StagesOf(e).Select(LawLabels.Stage));
if (!stages.NullOrEmpty())
parts.Add("BlaxLaws_PickerStages".Translate(stages));
if (e.IsBreak && e.hostileBreak)
parts.Add("BlaxLaws_PickerHostile".Translate());
string what = LawbookUi.EntryDescription(e);
if (!what.NullOrEmpty())
parts.Add(what);
if (inBook)
parts.Add("BlaxLaws_PickerInBook".Translate());
return string.Join("\n\n", parts);
}
/// <summary>Returns the key to the caller and closes.</summary>
protected void Pick(string actKey)
{
Close();
HookGuard.Run("Picking an act", () => onPick?.Invoke(actKey));
}
}
}

View File

@ -0,0 +1,361 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>One entry of a lawbook column's dropdown. A null action is a disabled entry; reason says why.</summary>
public sealed class RowChoice
{
public string label;
/// <summary>The value the entry sets: a drug option, a LawStage, a LawSeverity or a PunishmentDef.</summary>
public object payload;
/// <summary>Writes the choice through Lawbook. Null for a disabled entry.</summary>
public Action action;
/// <summary>Why the entry is disabled ("Needs Ideology"), or null.</summary>
public string reason;
/// <summary>The row has this value now.</summary>
public bool selected;
public override string ToString() => label + (selected ? " (selected)" : "") + (action == null ? " (disabled: " + reason + ")" : "");
}
/// <summary>
/// The logic behind the Lawbook tab (design: "Lawbook tab"), kept apart from the drawing so the
/// headless tests drive it: what each column offers, what a pick from the act picker does, the starter
/// button and the delete confirmation. Every write goes through Lawbook. A write Lawbook refuses because
/// the key exists shows the existing row instead (Focus).
/// </summary>
public static class LawbookUi
{
/// <summary>Seconds the tab highlights a row it jumped to.</summary>
public const float FocusSeconds = 2.5f;
/// <summary>The row the tab scrolls to and highlights, or 0.</summary>
public static int FocusLawId { get; private set; }
/// <summary>Real time until which the focused row is highlighted.</summary>
public static float FocusUntil { get; private set; }
/// <summary>Set when Focus asks the tab to scroll; the tab clears it once it scrolled.</summary>
public static bool ScrollPending { get; set; }
/// <summary>Shows the row: the Lawbook tab scrolls to it and highlights it.</summary>
public static void Focus(Law law)
{
if (law == null)
return;
FocusLawId = law.id;
FocusUntil = Time.realtimeSinceStartup + FocusSeconds;
ScrollPending = true;
}
public static void ClearFocus()
{
FocusLawId = 0;
ScrollPending = false;
}
// ---- labels ------------------------------------------------------------------------
/// <summary>"Ate: Wake-up". A row whose entry is missing shows its saved label.</summary>
public static string ActionLabel(Law law)
{
if (law == null)
return "";
return "BlaxLaws_ActionLabel".Translate(CategoryLabel(law.CategoryId), law.Label);
}
/// <summary>The category's label ("Ate"), or its id while the category is unknown.</summary>
public static string CategoryLabel(string categoryId)
{
if (categoryId.NullOrEmpty())
return "?";
ActCategoryDef cat = DefDatabase<ActCategoryDef>.GetNamedSilentFail(categoryId);
return cat != null && !cat.label.NullOrEmpty() ? cat.LabelCap.ToString() : categoryId;
}
/// <summary>The Action cell's tooltip: source mod, what counts, a missing entry's reason.</summary>
public static string ActionTooltip(Law law)
{
if (law == null)
return null;
var parts = new List<string>();
ActEntry e = law.Entry;
parts.Add(ActionLabel(law));
string missing = law.MissingText;
if (missing != null)
parts.Add(missing);
string source = e?.sourceMod ?? law.savedMod;
if (!source.NullOrEmpty())
parts.Add("BlaxLaws_SourceMod".Translate(source));
string what = EntryDescription(e);
if (!what.NullOrEmpty())
parts.Add(what);
parts.Add("BlaxLaws_ActionTip".Translate());
return string.Join("\n\n", parts);
}
/// <summary>What the entry's act is, for tooltips: a special act's row tooltip, else the category's tooltip.</summary>
public static string EntryDescription(ActEntry e)
{
if (e == null)
return null;
return HookGuard.Run("Entry tooltip " + e.key, () =>
{
if (e.def is ActDef act)
return act.Worker.RowTooltip;
ActCategoryDef cat = DefDatabase<ActCategoryDef>.GetNamedSilentFail(e.categoryId);
return cat?.Worker.Tooltip;
}, null);
}
/// <summary>The Days cell: the number when the punishment uses days, else "-".</summary>
public static bool UsesDays(Law law) => law?.PunishmentDef?.usesDays ?? false;
public static string PunishmentLabel(Law law)
{
if (law == null)
return "";
PunishmentDef p = law.PunishmentDef;
return p != null ? p.LabelCap.ToString() : law.punishment ?? "";
}
// ---- column choices ----------------------------------------------------------------
/// <summary>Whether the row has an Option column value: drug binges only.</summary>
public static bool HasOption(Law law) => law?.Entry?.hasDrugOption ?? (law?.option != null);
/// <summary>Any drug, hard drugs, social drugs, then every drug's chemical A to Z.</summary>
public static List<RowChoice> OptionChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null || !HasOption(law))
return list;
var options = new List<string> { DrugOptions.Any, DrugOptions.Hard, DrugOptions.Social };
options.AddRange(ActCatalogue.ChemicalOptions);
string current = DrugOptions.Normalize(law.option);
foreach (string o in options)
{
string option = o;
list.Add(new RowChoice
{
label = DrugOptions.Label(option),
payload = option,
selected = option == current,
action = () => ChangeOption(law, option),
});
}
return list;
}
/// <summary>The stages the entry offers; a missing entry keeps the row's stage only.</summary>
public static List<RowChoice> StageChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
ActEntry e = law.Entry;
IEnumerable<LawStage> stages = e != null ? Lawbook.StagesOf(e) : new[] { law.stage };
foreach (LawStage s in stages)
{
LawStage stage = s;
list.Add(new RowChoice
{
label = LawLabels.Stage(stage),
payload = stage,
selected = stage == law.stage,
action = e == null ? (Action)null : () => ChangeStage(law, stage),
reason = e == null ? law.MissingText : null,
});
}
return list;
}
public static List<RowChoice> SeverityChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
foreach (LawSeverity s in Enum.GetValues(typeof(LawSeverity)))
{
LawSeverity severity = s;
list.Add(new RowChoice
{
label = LawLabels.Severity(severity),
payload = severity,
selected = severity == law.severity,
action = () => Lawbook.SetSeverity(law, severity),
});
}
return list;
}
/// <summary>
/// The punishments that fit the row's entry and stage, in order (Lawbook.PunishmentsFor). A row whose
/// entry is missing keeps its punishment and offers nothing else.
/// </summary>
public static List<RowChoice> PunishmentChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
ActEntry e = law.Entry;
if (e == null)
{
PunishmentDef p = law.PunishmentDef;
list.Add(new RowChoice { label = PunishmentLabel(law), payload = p, selected = true, reason = law.MissingText });
return list;
}
foreach (PunishmentDef p in Lawbook.PunishmentsFor(e, law.stage))
{
PunishmentDef punishment = p;
list.Add(new RowChoice
{
label = punishment.LabelCap,
payload = punishment,
selected = punishment.defName == law.punishment,
action = () => Lawbook.SetPunishment(law, punishment),
});
}
return list;
}
// ---- writes that may be refused ----------------------------------------------------
/// <summary>Sets the option; a refusal shows the row that has the key.</summary>
public static bool ChangeOption(Law law, string option)
{
if (Lawbook.SetOption(law, option, out Law existing))
return true;
Refused(existing);
return false;
}
/// <summary>Sets the stage; a punishment that no longer fits resets to Warn. A refusal shows the existing row.</summary>
public static bool ChangeStage(Law law, LawStage stage)
{
if (Lawbook.SetStage(law, stage, out Law existing))
return true;
Refused(existing);
return false;
}
/// <summary>The act picker's pick for an existing row: SetAction, or the existing row with that key.</summary>
public static bool ChangeAction(Law law, string actKey)
{
if (Lawbook.SetAction(law, actKey, out Law existing))
{
Focus(law);
return true;
}
Refused(existing);
return false;
}
/// <summary>
/// The act picker's pick for "Add law". Adds a row for the entry's first stage that has no row yet
/// (a drug binge with the Any option), so an entry with planning and did it can get both. When every
/// stage has a row, nothing is added and existing is the first stage's row, which the tab shows.
/// Returns the new row, or null.
/// </summary>
public static Law AddFromPicker(string actKey, out Law existing)
{
existing = null;
if (actKey.NullOrEmpty())
return null;
Law row = Lawbook.NewRow(actKey);
ActEntry entry = ActCatalogue.Get(actKey);
IEnumerable<LawStage> stages = entry != null ? Lawbook.StagesOf(entry) : new[] { row.stage };
foreach (LawStage s in stages)
{
Law found = Lawbook.Find(actKey, row.option, s);
if (found != null)
{
existing ??= found;
continue;
}
row.stage = s;
if (!Lawbook.TryAdd(row, out Law refused))
{
existing = refused;
break;
}
existing = null;
Focus(row);
return row;
}
Refused(existing);
return null;
}
/// <summary>Rows already in the book for this act key, any option and stage.</summary>
public static List<Law> RowsOf(string actKey) => Lawbook.Laws.Where(l => l.actKey == actKey).ToList();
/// <summary>"Starter lawbook": adds the missing starter rows and says how many.</summary>
public static int PressStarter()
{
int added = Lawbook.AddStarter();
string text = added > 0 ? "BlaxLaws_StarterAdded".Translate(added) : "BlaxLaws_StarterNone".Translate();
Messages.Message(text, MessageTypeDefOf.SilentInput, historical: false);
return added;
}
/// <summary>The confirmation a delete asks first, naming the open cases it closes; null when it has none.</summary>
public static string DeleteConfirmText(Law law)
{
int open = Lawbook.OpenCaseCount(law);
if (open <= 0)
return null;
string text = "BlaxLaws_DeleteConfirm".Translate(ActionLabel(law), open);
int jailed = JailedCount(law);
if (jailed > 0)
text += "\n\n" + "BlaxLaws_DeleteConfirmJailed".Translate(jailed);
return text;
}
/// <summary>Open cases of the row whose offender serves its sentence: a repeal sets them to Release (PunishmentWorker_Jail.Stop).</summary>
public static int JailedCount(Law law)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null)
return 0;
int n = 0;
foreach (LawCase c in comp.Cases)
{
if (!c.IsClosed && c.status == CaseStatus.Jailed && (c.planningLawId == law.id || c.didItLawId == law.id))
n++;
}
return n;
}
/// <summary>Deletes the row, asking first when it has open cases (design: "Bulk changes ask first and name the count").</summary>
public static void RequestDelete(Law law)
{
if (law == null)
return;
string confirm = DeleteConfirmText(law);
if (confirm == null)
{
Lawbook.Delete(law);
return;
}
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(confirm, () => Lawbook.Delete(law), destructive: true));
}
private static void Refused(Law existing)
{
if (existing == null)
return;
Focus(existing);
Messages.Message("BlaxLaws_RowExists".Translate(ActionLabel(existing), LawLabels.Stage(existing.stage)), MessageTypeDefOf.RejectInput, historical: false);
}
}
}

View File

@ -0,0 +1,470 @@
using System;
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The Laws tab (MainButtonDef BlaxLaws_Laws; design: "Lawbook tab"). Two tabs:
/// - Lawbook: one line per row with Action (icon, category and label; a click opens the act picker),
/// Option (drug binges only), Stage, Severity, Punishment, Days, On, the overlap icon and delete.
/// Each dropdown offers only what fits the row's action and stage. "Add law" opens the act picker,
/// "Starter lawbook" adds the suggested rows. An empty book shows one line.
/// - Cases: newest first, who, what, stage, when, punishment and status, a button to jump to the pawn
/// and, for a held case, "Arrest now".
/// The logic lives in LawbookUi and CaseLog; every write goes through Lawbook. Only the lines in view
/// are drawn.
/// </summary>
public class MainTabWindow_Laws : MainTabWindow
{
private enum Page
{
Lawbook,
Cases,
}
private const float RowHeight = 30f;
private const float HeaderHeight = 26f;
private const float ButtonHeight = 32f;
private const float Gap = 6f;
private const float IconSize = 24f;
private const float ScrollBar = 16f;
// Lawbook columns; Action takes what is left.
private const float OptionWidth = 130f;
private const float StageWidth = 90f;
private const float SeverityWidth = 100f;
private const float PunishmentWidth = 150f;
private const float DaysWidth = 56f;
private const float OnWidth = 36f;
private const float SmallIcon = 24f;
// Cases columns; What takes what is left.
private const float WhoWidth = 150f;
private const float CaseStageWidth = 80f;
private const float WhenWidth = 110f;
private const float CasePunishmentWidth = 140f;
private const float StatusWidth = 190f;
private const float CaseButtonsWidth = 180f;
private static Page page = Page.Lawbook;
private static bool showClosed = true;
private static readonly Color SeriousColor = new Color(1f, 0.82f, 0.45f);
private Vector2 lawScroll;
private Vector2 caseScroll;
// The Cases tab's rows, refilled in place on every GUI event (CaseLog.FillRows).
private readonly List<LawCase> caseRows = new List<LawCase>();
private struct DaysBuffer
{
public int value;
public string text;
}
private readonly Dictionary<int, DaysBuffer> dayBuffers = new Dictionary<int, DaysBuffer>();
private readonly List<TabRecord> tabs = new List<TabRecord>();
public override Vector2 RequestedTabSize => new Vector2(1010f, 640f);
public override void PreOpen()
{
base.PreOpen();
dayBuffers.Clear();
}
public override void DoWindowContents(Rect inRect)
{
Rect body = inRect;
body.yMin += TabDrawer.TabHeight;
tabs.Clear();
tabs.Add(new TabRecord("BlaxLaws_TabLawbook".Translate(), () => page = Page.Lawbook, page == Page.Lawbook));
tabs.Add(new TabRecord("BlaxLaws_TabCases".Translate(), () => page = Page.Cases, page == Page.Cases));
Widgets.DrawMenuSection(body);
TabDrawer.DrawTabs(body, tabs);
body = body.ContractedBy(10f);
try
{
if (page == Page.Lawbook)
DoLawbook(body);
else
DoCases(body);
}
catch (Exception e)
{
LawsLog.Once("Laws tab", e);
}
finally
{
Text.Anchor = TextAnchor.UpperLeft;
Text.Font = GameFont.Small;
GUI.color = Color.white;
}
}
// ---- Lawbook ---------------------------------------------------------------------------
private void DoLawbook(Rect rect)
{
Rect buttons = new Rect(rect.x, rect.y, rect.width, ButtonHeight);
Rect add = new Rect(buttons.x, buttons.y, 160f, ButtonHeight);
if (Widgets.ButtonText(add, "BlaxLaws_AddLaw".Translate()))
Find.WindowStack.Add(Dialog_PickAct.ForNewRow());
TooltipHandler.TipRegion(add, "BlaxLaws_AddLawTip".Translate());
Rect starter = new Rect(add.xMax + Gap, buttons.y, 180f, ButtonHeight);
if (Widgets.ButtonText(starter, "BlaxLaws_StarterLawbook".Translate()))
LawbookUi.PressStarter();
TooltipHandler.TipRegion(starter, "BlaxLaws_StarterLawbookTip".Translate());
if (!BlaxLawsMod.S.enforceLaws)
{
Rect off = new Rect(starter.xMax + Gap * 2, buttons.y, buttons.xMax - starter.xMax - Gap * 2, ButtonHeight);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleRight, ColorLibrary.RedReadable))
Widgets.Label(off, "BlaxLaws_EnforceOff".Translate());
}
IReadOnlyList<Law> laws = Lawbook.Laws;
Rect list = new Rect(rect.x, buttons.yMax + Gap, rect.width, rect.yMax - buttons.yMax - Gap);
if (laws.Count == 0)
{
using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor))
Widgets.Label(list, "BlaxLaws_EmptyBook".Translate());
return;
}
Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight);
DrawLawHeader(header);
Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax);
Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, laws.Count * RowHeight);
ScrollToFocus(laws, outRect.height);
Widgets.BeginScrollView(outRect, ref lawScroll, viewRect);
try
{
int first = Mathf.Max(0, Mathf.FloorToInt(lawScroll.y / RowHeight));
int last = Mathf.Min(laws.Count - 1, Mathf.CeilToInt((lawScroll.y + outRect.height) / RowHeight));
for (int i = first; i <= last && i < laws.Count; i++)
{
Rect r = new Rect(0f, i * RowHeight, viewRect.width, RowHeight);
try
{
DrawLaw(r, laws[i], i);
}
catch (Exception e)
{
LawsLog.Once("Lawbook row", e);
}
}
}
finally
{
Widgets.EndScrollView();
}
}
private void ScrollToFocus(IReadOnlyList<Law> laws, float height)
{
if (!LawbookUi.ScrollPending)
return;
LawbookUi.ScrollPending = false;
page = Page.Lawbook;
for (int i = 0; i < laws.Count; i++)
{
if (laws[i].id != LawbookUi.FocusLawId)
continue;
float top = i * RowHeight;
if (top < lawScroll.y || top + RowHeight > lawScroll.y + height)
lawScroll.y = Mathf.Max(0f, top - height / 2f);
return;
}
}
private static void Columns(Rect r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment,
out Rect days, out Rect on, out Rect overlap, out Rect delete)
{
float x = r.xMax;
delete = new Rect(x - SmallIcon, r.y, SmallIcon, r.height);
x = delete.x - Gap;
overlap = new Rect(x - SmallIcon, r.y, SmallIcon, r.height);
x = overlap.x - Gap;
on = new Rect(x - OnWidth, r.y, OnWidth, r.height);
x = on.x - Gap;
days = new Rect(x - DaysWidth, r.y, DaysWidth, r.height);
x = days.x - Gap;
punishment = new Rect(x - PunishmentWidth, r.y, PunishmentWidth, r.height);
x = punishment.x - Gap;
severity = new Rect(x - SeverityWidth, r.y, SeverityWidth, r.height);
x = severity.x - Gap;
stage = new Rect(x - StageWidth, r.y, StageWidth, r.height);
x = stage.x - Gap;
option = new Rect(x - OptionWidth, r.y, OptionWidth, r.height);
x = option.x - Gap;
action = new Rect(r.x, r.y, x - r.x, r.height);
}
private static void DrawLawHeader(Rect r)
{
Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on, out _, out _);
using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor))
{
HeaderLabel(action, "BlaxLaws_ColAction", null);
HeaderLabel(option, "BlaxLaws_ColOption", "BlaxLaws_ColOptionTip");
HeaderLabel(stage, "BlaxLaws_ColStage", "BlaxLaws_ColStageTip");
HeaderLabel(severity, "BlaxLaws_ColSeverity", "BlaxLaws_ColSeverityTip");
HeaderLabel(punishment, "BlaxLaws_ColPunishment", null);
HeaderLabel(days, "BlaxLaws_ColDays", "BlaxLaws_ColDaysTip");
HeaderLabel(on, "BlaxLaws_ColOn", "BlaxLaws_ColOnTip");
}
Widgets.DrawLineHorizontal(r.x, r.yMax - 1f, r.width);
}
private static void HeaderLabel(Rect r, string key, string tipKey)
{
Widgets.Label(r, key.Translate());
if (tipKey != null)
TooltipHandler.TipRegion(r, tipKey.Translate());
}
private void DrawLaw(Rect r, Law law, int index)
{
if (index % 2 == 1)
Widgets.DrawLightHighlight(r);
if (law.id == LawbookUi.FocusLawId && Time.realtimeSinceStartup < LawbookUi.FocusUntil)
Widgets.DrawHighlightSelected(r);
Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on,
out Rect overlap, out Rect delete);
ActEntry entry = law.Entry;
Color rowColor = law.enabled ? Color.white : Color.gray;
// Action: icon, category and label; a click opens the picker.
Widgets.DrawHighlightIfMouseover(action);
float x = action.x + 2f;
if (entry != null && ActIcons.HasIcon(entry))
{
ActIcons.Draw(new Rect(x, action.y + (action.height - IconSize) / 2f, IconSize, IconSize), entry);
x += IconSize + 4f;
}
Rect label = new Rect(x, action.y, action.xMax - x, action.height);
string text = LawbookUi.ActionLabel(law);
string missing = law.MissingText;
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, missing != null ? ColoredText.SubtleGrayColor : rowColor))
Widgets.Label(label, (missing != null ? text + " (" + missing + ")" : text).Truncate(label.width));
TooltipHandler.TipRegion(action, () => LawbookUi.ActionTooltip(law), law.id * 31 + 1);
if (Widgets.ButtonInvisible(action))
Find.WindowStack.Add(Dialog_PickAct.ForRow(law));
// Option, drug binges only.
if (LawbookUi.HasOption(law))
Dropdown(option, law, LawbookUi.OptionChoices, DrugOptions.Label(law.option));
Dropdown(stage, law, LawbookUi.StageChoices, LawLabels.Stage(law.stage));
Dropdown(severity, law, LawbookUi.SeverityChoices, LawLabels.Severity(law.severity));
Dropdown(punishment, law, LawbookUi.PunishmentChoices, LawbookUi.PunishmentLabel(law));
// Days: a 1 to 50 field for punishments with days, "-" otherwise.
if (LawbookUi.UsesDays(law))
{
// The buffer belongs to the value it was typed for; a change from elsewhere (Severity moving
// untouched days) starts a fresh one, so stale text never writes the old number back.
string buffer = null;
if (dayBuffers.TryGetValue(law.id, out DaysBuffer kept) && kept.value == law.days)
buffer = kept.text;
int value = law.days;
Rect field = days.ContractedBy(0f, 3f);
Widgets.TextFieldNumeric(field, ref value, ref buffer, Lawbook.MinDays, Lawbook.MaxDays);
if (value != law.days && value >= Lawbook.MinDays && value <= Lawbook.MaxDays)
Lawbook.SetDays(law, value);
dayBuffers[law.id] = new DaysBuffer { value = law.days, text = buffer };
}
else
{
using (new TextBlock(GameFont.Small, TextAnchor.MiddleCenter, ColoredText.SubtleGrayColor))
Widgets.Label(days, "BlaxLaws_NoDays".Translate());
}
// On.
bool enabled = law.enabled;
Widgets.Checkbox(new Vector2(on.x + (on.width - 24f) / 2f, on.y + (on.height - 24f) / 2f), ref enabled);
if (enabled != law.enabled)
Lawbook.SetEnabled(law, enabled);
TooltipHandler.TipRegion(on, "BlaxLaws_ColOnTip".Translate());
// Overlap icon.
IReadOnlyList<Law> overlaps = ActOverlaps.Of(law);
if (overlaps.Count > 0)
{
Rect icon = new Rect(overlap.x, overlap.y + (overlap.height - SmallIcon) / 2f, SmallIcon, SmallIcon);
GUI.DrawTexture(icon, LawsTex.Overlap);
TooltipHandler.TipRegion(icon, () => OverlapTip(overlaps), law.id * 31 + 2);
}
// Delete, asking first when the row has open cases.
Rect del = new Rect(delete.x, delete.y + (delete.height - SmallIcon) / 2f, SmallIcon, SmallIcon);
if (Widgets.ButtonImage(del, TexButton.Delete, Color.white, GenUI.SubtleMouseoverColor, true, "BlaxLaws_DeleteLaw".Translate()))
LawbookUi.RequestDelete(law);
}
private static string OverlapTip(IReadOnlyList<Law> overlaps)
{
var lines = new List<string>();
foreach (Law o in overlaps)
lines.Add(" - " + LawbookUi.ActionLabel(o) + " (" + LawLabels.Stage(o.stage) + ")");
return "BlaxLaws_OverlapTip".Translate(string.Join("\n", lines));
}
private static void Dropdown(Rect rect, Law law, Func<Law, List<RowChoice>> choices, string label)
{
Rect button = rect.ContractedBy(0f, 2f);
Widgets.Dropdown(button, law, l => (object)null, l => Elements(choices(l)), label.Truncate(button.width - 16f));
}
private static IEnumerable<Widgets.DropdownMenuElement<object>> Elements(List<RowChoice> choices)
{
foreach (RowChoice c in choices)
{
string label = c.action == null && !c.reason.NullOrEmpty() ? c.label + " (" + c.reason + ")" : c.label;
yield return new Widgets.DropdownMenuElement<object>
{
option = new FloatMenuOption(label, c.action),
payload = c.payload,
};
}
}
// ---- Cases -----------------------------------------------------------------------------
private void DoCases(Rect rect)
{
Rect top = new Rect(rect.x, rect.y, rect.width, ButtonHeight);
Rect closed = new Rect(top.x, top.y + 4f, 240f, 24f);
Widgets.CheckboxLabeled(closed, "BlaxLaws_ShowClosed".Translate(), ref showClosed);
CaseLog.FillRows(caseRows, showClosed);
List<LawCase> cases = caseRows;
Rect list = new Rect(rect.x, top.yMax + Gap, rect.width, rect.yMax - top.yMax - Gap);
if (cases.Count == 0)
{
using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor))
Widgets.Label(list, "BlaxLaws_NoCases".Translate());
return;
}
Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight);
CaseColumns(header, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out _);
using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor))
{
Widgets.Label(who, "BlaxLaws_ColWho".Translate());
Widgets.Label(what, "BlaxLaws_ColWhat".Translate());
Widgets.Label(stage, "BlaxLaws_ColStage".Translate());
Widgets.Label(when, "BlaxLaws_ColWhen".Translate());
Widgets.Label(punishment, "BlaxLaws_ColPunishment".Translate());
Widgets.Label(status, "BlaxLaws_ColStatus".Translate());
}
Widgets.DrawLineHorizontal(header.x, header.yMax - 1f, header.width);
Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax);
Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, cases.Count * RowHeight);
Widgets.BeginScrollView(outRect, ref caseScroll, viewRect);
try
{
int first = Mathf.Max(0, Mathf.FloorToInt(caseScroll.y / RowHeight));
int last = Mathf.Min(cases.Count - 1, Mathf.CeilToInt((caseScroll.y + outRect.height) / RowHeight));
for (int i = first; i <= last; i++)
{
try
{
DrawCase(new Rect(0f, i * RowHeight, viewRect.width, RowHeight), cases[i], i);
}
catch (Exception e)
{
LawsLog.Once("Cases row", e);
}
}
}
finally
{
Widgets.EndScrollView();
}
}
private static void CaseColumns(Rect r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons)
{
float x = r.xMax;
buttons = new Rect(x - CaseButtonsWidth, r.y, CaseButtonsWidth, r.height);
x = buttons.x - Gap;
status = new Rect(x - StatusWidth, r.y, StatusWidth, r.height);
x = status.x - Gap;
punishment = new Rect(x - CasePunishmentWidth, r.y, CasePunishmentWidth, r.height);
x = punishment.x - Gap;
when = new Rect(x - WhenWidth, r.y, WhenWidth, r.height);
x = when.x - Gap;
stage = new Rect(x - CaseStageWidth, r.y, CaseStageWidth, r.height);
x = stage.x - Gap;
who = new Rect(r.x, r.y, WhoWidth, r.height);
what = new Rect(who.xMax + Gap, r.y, x - who.xMax - Gap, r.height);
}
private static void DrawCase(Rect r, LawCase c, int index)
{
if (index % 2 == 1)
Widgets.DrawLightHighlight(r);
Widgets.DrawHighlightIfMouseover(r);
CaseColumns(r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons);
Color color = c.IsClosed ? ColoredText.SubtleGrayColor : SeverityColor(c.severity);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, color))
{
Cell(who, CaseLog.Who(c));
Cell(what, CaseLog.What(c));
Cell(stage, CaseLog.Stage(c));
Cell(when, CaseLog.When(c));
Cell(punishment, CaseLog.Punishment(c));
Cell(status, CaseLog.Status(c));
}
TooltipHandler.TipRegion(new Rect(r.x, r.y, buttons.x - r.x, r.height), () => CaseTip(c), c.id * 31 + 3);
float bx = buttons.xMax;
if (CaseLog.CanJump(c))
{
Rect jump = new Rect(bx - 70f, r.y + 3f, 70f, r.height - 6f);
if (Widgets.ButtonText(jump, "BlaxLaws_JumpTo".Translate()))
CaseLog.JumpTo(c);
TooltipHandler.TipRegion(jump, "BlaxLaws_JumpToTip".Translate(c.OffenderLabel));
bx = jump.x - Gap;
}
if (CaseLog.CanArrestNow(c))
{
Rect arrest = new Rect(bx - 100f, r.y + 3f, 100f, r.height - 6f);
if (Widgets.ButtonText(arrest, "BlaxLaws_ArrestNow".Translate()))
CaseLog.ArrestNow(c);
TooltipHandler.TipRegion(arrest, () => "BlaxLaws_ArrestNowTip".Translate(CaseLog.HoldReason(c.offender)), c.id * 31 + 4);
}
}
private static void Cell(Rect r, string text)
{
Widgets.Label(r, (text ?? "").Truncate(r.width));
}
private static string CaseTip(LawCase c)
{
var lines = new List<string>
{
CaseLog.Who(c),
CaseLog.What(c),
LawLabels.Severity(c.severity) + ", " + CaseLog.Stage(c),
CaseLog.Punishment(c),
CaseLog.Status(c),
};
return string.Join("\n", lines);
}
private static Color SeverityColor(LawSeverity s)
{
switch (s)
{
case LawSeverity.Grave: return ColorLibrary.RedReadable;
case LawSeverity.Serious: return SeriousColor;
default: return Color.white;
}
}
}
}

210
Source/BlaxLaws/Watch.cs Normal file
View File

@ -0,0 +1,210 @@
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The hot-path cache of the current game's lawbook (design: "Detection: one postfix per act, quiet while
/// the book is empty"). One static flag per category and per special act, plus per category the set of
/// watched defs (groups expanded) and the enabled rows whose entry resolves. Rebuilt on every lawbook
/// write and in GameComponent_BlaxLaws.FinalizeInit, cleared when a game starts or loads. Not game state:
/// nothing here is saved.
///
/// Every hook reads its flag first, so while the book is empty a hook costs one static field read:
///
/// if (!Watch.Ate) return; // empty book: done
/// if (!Watch.MayMatch(ActCategories.Ate, def)) return; // one set lookup
/// CaseFiler.Report(new ActEvent(ActCategories.Ate, def, pawn) { ... });
///
/// A break row with a linked did-it also watches the linked act (a drug binge row watches every drug,
/// a fire-starting spree row the SetFire special act), so a dose during a binge reaches CaseFiler.
/// </summary>
public static class Watch
{
/// <summary>Any category or special act is watched. False for an empty book.</summary>
public static bool Any;
// One flag per category: some enabled row (or a break row's link) uses it.
public static bool Break;
public static bool Ate;
public static bool Used;
public static bool Interaction;
public static bool RecordedAct;
public static bool Record;
public static bool Bill;
public static bool Special;
// One flag per special act of the first release.
public static bool SetFire;
public static bool DisplayedCorpse;
public static bool StartedSocialFight;
/// <summary>Bumped on every rebuild.</summary>
public static int Version { get; private set; }
private sealed class CategoryWatch
{
public readonly HashSet<Def> defs = new HashSet<Def>();
/// <summary>A row or link on the category's "any".</summary>
public bool all;
/// <summary>A watched group reads the thing, so every act of the category must be checked.</summary>
public bool thingGroups;
/// <summary>Enabled rows of this category whose entry resolves, in lawbook order.</summary>
public readonly List<Law> laws = new List<Law>();
}
private static readonly Dictionary<string, CategoryWatch> byCategory = new Dictionary<string, CategoryWatch>();
private static readonly HashSet<string> specials = new HashSet<string>();
private static readonly List<Law> NoLaws = new List<Law>();
/// <summary>Whether any enabled row (or break link) uses the category.</summary>
public static bool Category(string categoryId) => categoryId != null && byCategory.ContainsKey(categoryId);
/// <summary>Whether a row (or break link) watches this special act ("SetFire").</summary>
public static bool SpecialAct(string actId) => actId != null && specials.Contains(actId);
/// <summary>The def is in the category's watched set, or the category watches everything.</summary>
public static bool IsWatched(string categoryId, Def def)
{
if (categoryId == null || !byCategory.TryGetValue(categoryId, out CategoryWatch w))
return false;
return w.all || (def != null && w.defs.Contains(def));
}
/// <summary>A watched group of the category reads the thing, so a hook must report every act of it.</summary>
public static bool ThingGroups(string categoryId) =>
categoryId != null && byCategory.TryGetValue(categoryId, out CategoryWatch w) && w.thingGroups;
/// <summary>
/// The act may match a row or a link: the def is watched, or a thing-level group needs the act. A
/// hook builds its ActEvent and calls CaseFiler.Report only when this is true.
/// </summary>
public static bool MayMatch(string categoryId, Def def)
{
if (categoryId == null || !byCategory.TryGetValue(categoryId, out CategoryWatch w))
return false;
return w.all || w.thingGroups || (def != null && w.defs.Contains(def));
}
/// <summary>Enabled rows of the category whose entry resolves. Empty when none. Do not change the list.</summary>
public static IReadOnlyList<Law> LawsOf(string categoryId)
{
if (categoryId != null && byCategory.TryGetValue(categoryId, out CategoryWatch w))
return w.laws;
return NoLaws;
}
/// <summary>Everything off: an empty book.</summary>
public static void Clear()
{
byCategory.Clear();
specials.Clear();
SetFlags();
Version++;
}
/// <summary>
/// Rebuilds from the running game's lawbook. Disabled rows and rows whose entry is missing watch
/// nothing. Never throws.
/// </summary>
public static void Rebuild()
{
try
{
byCategory.Clear();
specials.Clear();
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp != null)
{
foreach (Law law in comp.Laws)
{
if (law == null || !law.enabled)
continue;
ActEntry entry = ActCatalogue.Get(law.actKey);
if (entry == null || !entry.HasStage(law.stage))
continue;
Of(entry.categoryId).laws.Add(law);
AddEntry(entry);
if (entry.IsBreak)
{
foreach (BreakLinkDef link in entry.links)
{
ActEntry linked = ActCatalogue.Get(link.act);
if (linked != null)
AddEntry(linked);
}
}
}
}
}
catch (System.Exception e)
{
HookGuard.Fail("Rebuilding the watched acts", e);
}
SetFlags();
Version++;
}
private static CategoryWatch Of(string categoryId)
{
if (!byCategory.TryGetValue(categoryId, out CategoryWatch w))
byCategory[categoryId] = w = new CategoryWatch();
return w;
}
private static void AddEntry(ActEntry entry)
{
CategoryWatch w = Of(entry.categoryId);
if (entry.categoryId == ActCategories.Special)
specials.Add(entry.name);
if (entry.def != null)
{
w.defs.Add(entry.def);
return;
}
ActGroup g = entry.group;
if (g == null)
return;
if (g.IsAny)
{
w.all = true;
if (entry.categoryId == ActCategories.Special)
{
foreach (ActEntry e in ActCatalogue.EntriesOf(ActCategories.Special))
{
if (e.def != null)
specials.Add(e.name);
}
}
return;
}
if (g.DependsOnThing)
w.thingGroups = true;
foreach (ActEntry e in ActCatalogue.EntriesOf(entry.categoryId))
{
if (e.def != null && g.MatchesDef(e.def))
{
w.defs.Add(e.def);
if (entry.categoryId == ActCategories.Special)
specials.Add(e.name);
}
}
}
private static void SetFlags()
{
Break = Category(ActCategories.Break);
Ate = Category(ActCategories.Ate);
Used = Category(ActCategories.Used);
Interaction = Category(ActCategories.Interaction);
RecordedAct = Category(ActCategories.RecordedAct);
Record = Category(ActCategories.Record);
Bill = Category(ActCategories.Bill);
Special = Category(ActCategories.Special);
SetFire = SpecialAct(SpecialActs.SetFire);
DisplayedCorpse = SpecialAct(SpecialActs.DisplayedCorpse);
StartedSocialFight = SpecialAct(SpecialActs.StartedSocialFight);
Any = byCategory.Count > 0;
}
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Blax Laws Tests</name>
<author>Blax Gaming</author>
<packageId>blax.laws.tests</packageId>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
<!-- No modDependencies: Blax Laws has no download page yet, and the game drops a dependency without one,
with a warning. run-tests.ps1 loads Blax Laws before this mod. -->
<loadAfter>
<li>blax.castes</li>
<li>blax.zones</li>
<li>blax.slaves</li>
<li>blax.defaults</li>
<li>blax.laws</li>
</loadAfter>
<description>In-game test suite for Blax Laws. Does nothing unless the game is started with -blaxlawstests (see Tests/run-tests.ps1). Not for players.</description>
</ModMetaData>

View File

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Test-only defs for CatalogueTests.TestModDefs: the act catalogue lists modded defs with their mod as source,
and a modded break that reuses a vanilla state class gets that class's "Did it" link. Loaded only with the test
mod. The break never starts on its own (base commonality 0), the interaction is never picked at random (the base
InteractionWorker weighs 0), the recipe has no bench and the drug no trader or loot tag.
-->
<Defs>
<ThingDef ParentName="DrugPillBase">
<defName>BlaxLawsTest_Drug</defName>
<label>test drug</label>
<description>A drug that exists only in the Blax Laws test suite.</description>
<graphicData>
<texPath>Things/Item/Drug/WakeUp</texPath>
<graphicClass>Graphic_StackCount</graphicClass>
</graphicData>
<rotatable>false</rotatable>
<tradeability>None</tradeability>
<statBases>
<MarketValue>1</MarketValue>
<Mass>0.005</Mass>
</statBases>
<ingestible>
<drugCategory>Social</drugCategory>
</ingestible>
<comps>
<li Class="CompProperties_Drug">
<listOrder>9999</listOrder>
</li>
</comps>
</ThingDef>
<InteractionDef>
<defName>BlaxLawsTest_Interaction</defName>
<label>test interaction</label>
<workerClass>InteractionWorker</workerClass>
<logRulesInitiator>
<rulesStrings>
<li>r_logentry->[INITIATOR_nameDef] tested [RECIPIENT_nameDef].</li>
</rulesStrings>
</logRulesInitiator>
</InteractionDef>
<RecipeDef>
<defName>BlaxLawsTest_Recipe</defName>
<label>make test thing</label>
<description>A recipe that exists only in the Blax Laws test suite.</description>
<jobString>Making a test thing.</jobString>
<workAmount>100</workAmount>
</RecipeDef>
<MentalBreakDef>
<defName>BlaxLawsTest_FireBreak</defName>
<mentalState>BlaxLawsTest_FireSpree</mentalState>
<baseCommonality>0</baseCommonality>
<intensity>Minor</intensity>
</MentalBreakDef>
<MentalStateDef ParentName="BaseMentalState">
<defName>BlaxLawsTest_FireSpree</defName>
<stateClass>MentalState_FireStartingSpree</stateClass>
<label>test fire spree</label>
<category>Malicious</category>
<colonistsOnly>true</colonistsOnly>
<prisonersCanDo>false</prisonersCanDo>
<minTicksBeforeRecovery>6000</minTicksBeforeRecovery>
<maxTicksBeforeRecovery>10000</maxTicksBeforeRecovery>
<recoveryMtbDays>0.033</recoveryMtbDays>
<baseInspectLine>Mental state: Test fire spree</baseInspectLine>
</MentalStateDef>
</Defs>

View File

@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- In-game test suite. Built and run by Tests/run-tests.ps1; the DLL is not committed. -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>BlaxLawsTests</AssemblyName>
<RootNamespace>BlaxLawsTests</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<OutputPath>..\1.7\Assemblies\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<GenerateDependencyFile>false</GenerateDependencyFile>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType>
<PathMap>$(MSBuildProjectDirectory)=Tests/BlaxLawsTests/Source</PathMap>
</PropertyGroup>
<PropertyGroup>
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
<BlaxLawsDir Condition="'$(BlaxLawsDir)' == ''">$(MSBuildProjectDirectory)\..\..\..\1.7\Assemblies</BlaxLawsDir>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="UnityStubs">
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="0Harmony">
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="BlaxLaws">
<HintPath>$(BlaxLawsDir)\BlaxLaws.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,390 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BlaxLaws;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLawsTests
{
/// <summary>
/// The act catalogue (design: "Act catalogue and detection", Tests, Catalogue; "Lawbook tab", Tests, the
/// parts the catalogue answers): every def of the loaded game has its entry, the groups cover what their
/// rules say, breaks carry their stages and links, labels can be found and told apart, DLC entries appear
/// only with their DLC, and the watched sets follow the lawbook.
/// </summary>
public static class CatalogueTests
{
private const string TestModPackageId = "blax.laws.tests";
private static ActEntry Entry(string key)
{
ActEntry e = ActCatalogue.Get(key);
T.NotNull(e, "catalogue entry " + key);
return e;
}
private static string Key(string category, Def def) => ActKey.Of(category, def.defName);
[BlaxTest("catalogue: every break state, edible thing, usable, interaction, recorded act, counting record, recipe and special act has an entry; no Time record, plant or excluded state has one")]
public static void EveryDefHasAnEntry()
{
var sw = Stopwatch.StartNew();
ActCatalogue.Build();
sw.Stop();
Watch.Rebuild();
T.Info("catalogue built in " + sw.ElapsedMilliseconds + " ms: " + string.Join(", ",
ActCatalogue.Categories.Select(c => c.defName + " " + ActCatalogue.EntriesOf(c.defName).Count)) + ", " + ActCatalogue.All.Count + " in all");
var missing = new List<string>();
void Need(string category, Def def)
{
if (def != null && ActCatalogue.Get(Key(category, def)) == null)
missing.Add(Key(category, def));
}
ActCategoryDef breaks = DefDatabase<ActCategoryDef>.GetNamed(ActCategories.Break);
foreach (MentalBreakDef b in DefDatabase<MentalBreakDef>.AllDefsListForReading)
{
if (b.mentalState != null && !CatalogueRules.Excluded(breaks, b.mentalState.defName))
Need(ActCategories.Break, b.mentalState);
}
foreach (string name in CatalogueRules.BreakInclude)
Need(ActCategories.Break, DefDatabase<MentalStateDef>.GetNamedSilentFail(name));
foreach (ThingDef t in DefDatabase<ThingDef>.AllDefsListForReading)
{
if (CatalogueRules.IsEdible(t))
Need(ActCategories.Ate, t);
if (CatalogueRules.IsUsable(t))
Need(ActCategories.Used, t);
}
foreach (InteractionDef i in DefDatabase<InteractionDef>.AllDefsListForReading)
Need(ActCategories.Interaction, i);
ActCategoryDef recorded = DefDatabase<ActCategoryDef>.GetNamed(ActCategories.RecordedAct);
foreach (HistoryEventDef h in DefDatabase<HistoryEventDef>.AllDefsListForReading)
{
if (!CatalogueRules.Excluded(recorded, h.defName))
Need(ActCategories.RecordedAct, h);
}
foreach (RecordDef r in DefDatabase<RecordDef>.AllDefsListForReading)
{
if (r.type != RecordType.Time)
Need(ActCategories.Record, r);
}
foreach (RecipeDef r in DefDatabase<RecipeDef>.AllDefsListForReading)
Need(ActCategories.Bill, r);
foreach (ActDef a in DefDatabase<ActDef>.AllDefsListForReading)
Need(ActCategories.Special, a);
T.Check(missing.Count == 0, missing.Count + " def(s) without an entry, first: " + string.Join(", ", missing.Take(8)));
var wrong = new List<string>();
foreach (RecordDef r in DefDatabase<RecordDef>.AllDefsListForReading.Where(r => r.type == RecordType.Time))
{
if (ActCatalogue.Get(Key(ActCategories.Record, r)) != null)
wrong.Add("Time record " + r.defName);
}
foreach (string name in CatalogueRules.BreakExclude)
{
if (ActCatalogue.Get(ActKey.Of(ActCategories.Break, name)) != null)
wrong.Add("excluded state " + name);
}
foreach (ThingDef plant in DefDatabase<ThingDef>.AllDefsListForReading.Where(t => t.category == ThingCategory.Plant && t.ingestible != null).Take(20))
{
if (ActCatalogue.Get(Key(ActCategories.Ate, plant)) != null)
wrong.Add("plant " + plant.defName);
}
if (ActCatalogue.Get(ActKey.Of(ActCategories.RecordedAct, "Traded")) != null)
wrong.Add("faction-level event Traded");
T.Check(wrong.Count == 0, "entries that must not exist: " + string.Join(", ", wrong.Take(8)));
// The examples of the design, all Core.
Entry("Break/Binging_DrugExtreme");
Entry("Break/FireStartingSpree");
Entry("Break/CorpseObsession");
Entry("Break/Berserk");
Entry("Ate/WakeUp");
Entry("Used/MechSerumHealer");
Entry("Interaction/Insult");
Entry("Interaction/SparkJailbreak");
Entry("RecordedAct/ExecutedPrisoner");
Entry("Record/BodiesStripped");
Entry("Bill/" + RecipeDefOf.RemoveBodyPart.defName);
Entry("Special/SetFire");
Entry("Special/DisplayedCorpse");
Entry("Special/StartedSocialFight");
}
[BlaxTest("catalogue: every group of the design exists with its label, comes before the defs and covers what its rule says")]
public static void Groups()
{
var groups = new (string category, string id)[]
{
(ActCategories.Break, ActGroups.Any), (ActCategories.Break, ActGroups.AnyDrugBinge), (ActCategories.Break, ActGroups.AnyTantrum),
(ActCategories.Break, ActGroups.AnyInsultingSpree), (ActCategories.Break, ActGroups.AnyAggressive),
(ActCategories.Ate, ActGroups.Any), (ActCategories.Ate, ActGroups.AnyDrug), (ActCategories.Ate, ActGroups.HardDrugs),
(ActCategories.Ate, ActGroups.SocialDrugs), (ActCategories.Ate, ActGroups.MedicalDrugs), (ActCategories.Ate, ActGroups.AnyMeat),
(ActCategories.Ate, ActGroups.RawMeatOrCorpse), (ActCategories.Ate, ActGroups.HumanMeat), (ActCategories.Ate, ActGroups.InsectMeat),
(ActCategories.Ate, ActGroups.RawFood), (ActCategories.Ate, ActGroups.AnyMeal),
(ActCategories.Interaction, ActGroups.InsultOrSlight), (ActCategories.Bill, ActGroups.AnySurgery),
};
foreach (var (category, id) in groups)
{
ActEntry e = Entry(ActKey.OfGroup(category, id));
T.Check(e.IsGroup && e.def == null, e.key + " is not a group entry");
T.Check(e.group.labelKey.CanTranslate(), e.key + ": label " + e.group.labelKey + " missing from Keyed");
T.Check(e.label == e.group.labelKey.Translate().ToString(), e.key + " reads '" + e.label + "', not its Keyed label");
T.Equal(DlcSupport.CoreName, e.sourceMod, e.key + " source");
T.Check(e.group.size > 0, e.key + " covers no def of the loaded game");
}
foreach (ActCategoryDef cat in ActCatalogue.Categories)
{
IReadOnlyList<ActEntry> list = ActCatalogue.EntriesOf(cat.defName);
int firstDef = list.Count;
for (int i = 0; i < list.Count; i++)
{
if (list[i].def != null)
{
firstDef = i;
break;
}
}
T.Check(list.Skip(firstDef).All(e => e.def != null), cat.defName + ": a group comes after a def entry");
}
ActGroup G(string key) => Entry(key).group;
void In(string key, Def def, bool expected)
{
T.NotNull(def, "def for " + key);
T.Check(G(key).MatchesDef(def) == expected, key + (expected ? " misses " : " takes in ") + def.defName);
}
MentalStateDef State(string name) => DefDatabase<MentalStateDef>.GetNamed(name);
In("Break/@anyDrugBinge", State("Binging_DrugExtreme"), true);
In("Break/@anyDrugBinge", State("Binging_DrugMajor"), true);
In("Break/@anyDrugBinge", State("Binging_Food"), false);
In("Break/@anyTantrum", State("Tantrum"), true);
In("Break/@anyTantrum", State("TargetedTantrum"), true);
In("Break/@anyTantrum", State("BedroomTantrum"), true);
In("Break/@anyTantrum", State("MurderousRage"), false);
In("Break/@anyInsultingSpree", State("InsultingSpree"), true);
In("Break/@anyInsultingSpree", State("TargetedInsultingSpree"), true);
In("Break/@anyAggressive", State("Berserk"), true);
In("Break/@anyAggressive", State("Wander_Sad"), false);
In("Break/@any", State("Wander_Sad"), true);
In("Break/@any", MentalStateDefOf.SocialFighting, false);
In("Break/@any", MentalStateDefOf.Manhunter, false);
ThingDef cowMeat = ThingDefOf.Cow.race.meatDef;
ThingDef insect = DefDatabase<ThingDef>.GetNamed("Megaspider");
In("Ate/@any", ThingDefOf.MealSimple, true);
In("Ate/@anyDrug", ThingDefOf.Beer, true);
In("Ate/@anyDrug", ThingDefOf.MealSimple, false);
In("Ate/@hardDrugs", ThingDefOf.WakeUp, true);
In("Ate/@hardDrugs", ThingDefOf.Yayo, true);
In("Ate/@hardDrugs", ThingDefOf.Beer, false);
In("Ate/@socialDrugs", ThingDefOf.Beer, true);
In("Ate/@socialDrugs", ThingDefOf.SmokeleafJoint, true);
In("Ate/@medicalDrugs", ThingDefOf.Penoxycyline, true);
In("Ate/@rawMeatOrCorpse", cowMeat, true);
In("Ate/@rawMeatOrCorpse", ThingDefOf.Human.race.corpseDef, true);
In("Ate/@rawMeatOrCorpse", ThingDefOf.MealSimple, false);
In("Ate/@humanMeat", ThingDefOf.Meat_Human, true);
In("Ate/@humanMeat", ThingDefOf.Human.race.corpseDef, true);
In("Ate/@humanMeat", cowMeat, false);
In("Ate/@insectMeat", insect.race.meatDef, true);
In("Ate/@insectMeat", insect.race.corpseDef, true);
In("Ate/@insectMeat", cowMeat, false);
In("Ate/@anyMeat", cowMeat, true);
In("Ate/@rawFood", ThingDefOf.RawPotatoes, true);
In("Ate/@rawFood", ThingDefOf.MealSimple, false);
In("Ate/@anyMeal", ThingDefOf.MealSimple, true);
In("Ate/@anyMeal", ThingDefOf.MealSurvivalPack, true);
In("Ate/@anyMeal", ThingDefOf.Beer, false);
In("Ate/@anyMeal", ThingDefOf.Chocolate, false);
In("Interaction/@insultOrSlight", InteractionDefOf.Insult, true);
In("Interaction/@insultOrSlight", DefDatabase<InteractionDef>.GetNamed("Slight"), true);
In("Interaction/@insultOrSlight", InteractionDefOf.Chitchat, false);
In("Bill/@anySurgery", RecipeDefOf.RemoveBodyPart, true);
In("Bill/@anySurgery", DefDatabase<RecipeDef>.GetNamed("CookMealSimple"), false);
// The thing decides for meals: a simple meal is human meat only with human meat in it.
Thing mealHuman = ThingMaker.MakeThing(ThingDefOf.MealSimple);
mealHuman.TryGetComp<CompIngredients>().RegisterIngredient(ThingDefOf.Meat_Human);
Thing mealVeg = ThingMaker.MakeThing(ThingDefOf.MealSimple);
mealVeg.TryGetComp<CompIngredients>().RegisterIngredient(ThingDefOf.RawPotatoes);
ActEvent Ate(Thing food) => new ActEvent(ActCategories.Ate, food.def, null) { thing = food, facts = FoodFacts.Of(food) };
T.Check(G("Ate/@humanMeat").Matches(Ate(mealHuman)), "a simple meal with human meat isn't human meat");
T.Check(G("Ate/@anyMeat").Matches(Ate(mealHuman)), "a simple meal with human meat isn't meat");
T.Check(!G("Ate/@humanMeat").Matches(Ate(mealVeg)), "a simple meal of potatoes is human meat");
T.Check(!G("Ate/@anyMeat").Matches(Ate(mealVeg)), "a simple meal of potatoes is meat");
T.Check(!G("Ate/@rawMeatOrCorpse").Matches(Ate(mealHuman)), "a simple meal is raw meat");
// The smaller group wins: sizes must order the nested groups.
T.Check(G("Ate/@hardDrugs").size < G("Ate/@anyDrug").size, "hard drugs aren't smaller than any drug");
T.Check(G("Ate/@humanMeat").size < G("Ate/@anyMeat").size, "human meat isn't smaller than any meat");
T.Check(G("Break/@anyDrugBinge").size < G("Break/@any").size, "any drug binge isn't smaller than any break");
}
[BlaxTest("catalogue: breaks get Planning, a Did it through their link, hostility and the drug option; other entries are Did it only")]
public static void BreakStagesAndLinks()
{
ActEntry fire = Entry("Break/FireStartingSpree");
T.Check(fire.hasPlanning && fire.hasDidIt, "fire-starting spree stages: planning " + fire.hasPlanning + ", did it " + fire.hasDidIt);
T.Check(fire.links.Any(l => l.act == "Special/SetFire"), "fire-starting spree isn't linked to Special/SetFire");
ActEntry sad = Entry("Break/Wander_Sad");
T.Check(sad.hasPlanning && !sad.hasDidIt, "sad wandering offers Did it without a link");
T.Check(Entry("Break/CorpseObsession").links.Any(l => l.act == "Special/DisplayedCorpse"), "corpse obsession isn't linked to DisplayedCorpse");
T.Check(Entry("Break/Jailbreaker").links.Any(l => l.act == "Interaction/SparkJailbreak"), "jailbreaker isn't linked to SparkJailbreak");
T.Check(Entry("Break/TargetedInsultingSpree").links.Any(l => l.act == "Interaction/@insultOrSlight"), "targeted insulting spree isn't linked to insult or slight");
ActEntry extreme = Entry("Break/Binging_DrugExtreme");
T.Check(extreme.links.Count == 1 && extreme.links[0].act == "Ate/@anyDrug" && extreme.hasDrugOption,
"a drug binge takes the drug link (most derived class) with the option, has: " + string.Join(", ", extreme.links.Select(l => l.act)));
ActEntry food = Entry("Break/Binging_Food");
T.Check(food.links.Count == 1 && food.links[0].act == "Ate/@any" && !food.hasDrugOption, "food binge link: " + string.Join(", ", food.links.Select(l => l.act)));
ActEntry anyBinge = Entry("Break/@anyDrugBinge");
T.Check(anyBinge.hasPlanning && anyBinge.hasDidIt && anyBinge.hasDrugOption, "any drug binge: planning, did it and the drug option expected");
T.Check(Entry("Break/Berserk").hostileBreak, "berserk isn't hostile to the colony");
T.Check(!Entry("Break/Tantrum").hostileBreak && !Entry("Break/MurderousRage").hostileBreak, "a tantrum or murderous rage is marked hostile");
T.Check(!Entry("Break/@anyAggressive").hostileBreak, "any aggressive break is marked hostile, but holds tantrums");
foreach (BreakLinkDef link in DefDatabase<BreakLinkDef>.AllDefsListForReading)
T.NotNull(ActCatalogue.Get(link.act), "the act of " + link.defName + " (" + link.act + ")");
foreach (ActEntry e in ActCatalogue.All.Where(x => !x.IsBreak))
T.Check(!e.hasPlanning && e.hasDidIt, e.key + " should be Did it only");
}
[BlaxTest("catalogue: a Berserk row offers Warn, Guilty and Jail, never Subdue; a Tantrum or MurderousRage row also offers Subdue; a Planning row never offers Guilty")]
public static void PunishmentsByEntry()
{
string Names(string key, LawStage stage) => string.Join(",", Lawbook.PunishmentsFor(Entry(key), stage).Select(p => p.defName));
T.Equal("Warn,Guilty,Jail", Names("Break/Berserk", LawStage.Planning), "Berserk planning");
T.Equal("Warn,Subdue,Jail", Names("Break/Tantrum", LawStage.Planning), "Tantrum planning");
T.Equal("Warn,Subdue,Jail", Names("Break/MurderousRage", LawStage.Planning), "MurderousRage planning");
T.Check(Names("Break/FireStartingSpree", LawStage.DidIt).Contains("Subdue"), "a linked break's did-it lacks Subdue");
T.Check(!Names("Interaction/Insult", LawStage.DidIt).Contains("Subdue"), "an interaction offers Subdue");
}
[BlaxTest("catalogue: the drug option list holds WakeUp, every option is a drug's chemical, and no other chemical")]
public static void ChemicalOptions()
{
IReadOnlyList<string> options = ActCatalogue.ChemicalOptions;
T.Check(options.Contains("WakeUp"), "WakeUp missing from the drug options: " + string.Join(", ", options));
var drugChemicals = new HashSet<string>(DefDatabase<ThingDef>.AllDefsListForReading.Select(DrugInfo.ChemicalOf).Where(c => c != null).Select(c => c.defName));
T.Check(options.All(drugChemicals.Contains), "a drug option no drug carries: " + string.Join(", ", options.Where(o => !drugChemicals.Contains(o))));
T.Equal(DrugCategory.Hard, DrugInfo.CategoryOfChemical(DefDatabase<ChemicalDef>.GetNamed("WakeUp")), "category of the wake-up chemical");
T.Equal(DrugCategory.Social, DrugInfo.CategoryOfChemical(DefDatabase<ChemicalDef>.GetNamed("Alcohol")), "category of the alcohol chemical");
}
[BlaxTest("catalogue: searching 'wake' finds Wake-up under Ate and the make wake-up bill; 'insult' finds Insult and the insulting sprees; equal labels are told apart")]
public static void LabelsAndSearch()
{
// The picker matches the label and the def name (design: "Act picker").
List<ActEntry> Search(string text) => ActCatalogue.All.Where(e =>
(e.label ?? "").IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0 ||
(e.def?.defName ?? "").IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
List<ActEntry> wake = Search("wake");
T.Check(wake.Any(e => e.categoryId == ActCategories.Ate && e.def == ThingDefOf.WakeUp), "'wake' doesn't find Ate: wake-up");
ActEntry makeWake = wake.FirstOrDefault(e => e.categoryId == ActCategories.Bill && (e.def as RecipeDef)?.ProducedThingDef == ThingDefOf.WakeUp);
T.NotNull(makeWake, "'wake' finding the bill that makes wake-up");
T.Check(makeWake.label.IndexOf("wake-up", StringComparison.OrdinalIgnoreCase) >= 0, "the wake-up bill reads '" + makeWake.label + "'");
List<ActEntry> insult = Search("insult");
T.Check(insult.Any(e => e.key == "Interaction/Insult"), "'insult' doesn't find Interaction: insult");
T.Check(insult.Any(e => e.key == "Break/InsultingSpree") && insult.Any(e => e.key == "Break/TargetedInsultingSpree"),
"'insult' doesn't find both insulting sprees under breaks");
string extreme = Entry("Break/Binging_DrugExtreme").label, major = Entry("Break/Binging_DrugMajor").label;
T.Check(extreme != major, "both drug binges read '" + extreme + "'");
T.Equal("Tantrum", Entry("Break/Tantrum").label, "the plain tantrum's label");
T.Check(Entry("Break/TargetedTantrum").label != "Tantrum", "the targeted tantrum reads like the plain one");
// Strict for the official content; a mod list may hold two defs whose names read alike, noted only.
foreach (ActCategoryDef cat in ActCatalogue.Categories)
{
var shared = ActCatalogue.EntriesOf(cat.defName).Where(e => e.def != null)
.GroupBy(e => e.label, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1).ToList();
var official = shared.Where(g => g.All(e => e.sourcePackageId == DlcSupport.CorePackageId || DlcSupport.IsDlcPackageId(e.sourcePackageId)))
.Select(g => g.Key).ToList();
T.Check(official.Count == 0, cat.defName + ": labels still shared: " + string.Join(", ", official.Take(5)));
if (shared.Count > official.Count)
T.Info(cat.defName + ": " + (shared.Count - official.Count) + " label(s) shared by modded entries, first: " + shared.First(g => !official.Contains(g.Key)).Key);
}
T.Equal(DlcSupport.CoreName, Entry("Ate/WakeUp").sourceMod, "source of Ate: wake-up");
}
[BlaxTest("catalogue: the test mod's drug, interaction, recipe and break appear with the test mod as source; the test break offers Did it through its class's link")]
public static void TestModDefs()
{
string[] keys = { "Ate/BlaxLawsTest_Drug", "Interaction/BlaxLawsTest_Interaction", "Bill/BlaxLawsTest_Recipe", "Break/BlaxLawsTest_FireSpree" };
if (DefDatabase<MentalStateDef>.GetNamedSilentFail("BlaxLawsTest_FireSpree") == null)
T.Fail("the test mod's catalogue defs aren't loaded: Tests/BlaxLawsTests/Defs/BlaxLawsTests_Catalogue.xml is missing");
foreach (string key in keys)
{
ActEntry e = Entry(key);
T.Equal(TestModPackageId, e.sourcePackageId, key + " source package");
T.Check(e.sourceMod != DlcSupport.CoreName && !e.sourceMod.NullOrEmpty(), key + " source reads '" + e.sourceMod + "'");
}
ActEntry spree = Entry("Break/BlaxLawsTest_FireSpree");
T.Check(spree.hasPlanning && spree.hasDidIt && spree.links.Any(l => l.act == "Special/SetFire"),
"the test break reusing MentalState_FireStartingSpree lacks the SetFire link");
T.Check(Entry("Ate/@anyDrug").group.MatchesDef(DefDatabase<ThingDef>.GetNamed("BlaxLawsTest_Drug")), "the test drug isn't in any drug");
}
[BlaxTest("catalogue: no entry of an inactive DLC appears, each active DLC's entries name it, and every starter row resolves")]
public static void DlcEntries()
{
var bySource = ActCatalogue.All.GroupBy(e => e.sourceMod).Select(g => g.Key + " " + g.Count());
T.Info("entries by source: " + string.Join(", ", bySource));
var stray = ActCatalogue.All.Where(e => DlcSupport.IsDlcPackageId(e.sourcePackageId) && !DlcSupport.IsDlcActive(DlcSupport.DlcName(e.sourcePackageId))).ToList();
T.Check(stray.Count == 0, "entries of an inactive DLC: " + string.Join(", ", stray.Take(5)));
if (ModsConfig.IdeologyActive)
T.Equal("Ideology", Entry("Break/IdeoChange").sourceMod, "source of the Ideology break IdeoChange");
else
T.Check(ActCatalogue.Get("Break/IdeoChange") == null, "Ideology's IdeoChange break is listed without Ideology");
if (ModsConfig.BiotechActive)
T.Equal("Biotech", Entry("Break/PanicFleeFire").sourceMod, "source of the Biotech break PanicFleeFire");
foreach (Lawbook.StarterRow s in Lawbook.StarterRows)
{
ActEntry e = Entry(s.actKey);
T.Check(e.HasStage(s.stage), "starter row " + s.actKey + " has no " + s.stage + " stage");
T.Check(!DlcSupport.IsDlcPackageId(e.sourcePackageId), "starter row " + s.actKey + " comes from " + e.sourceMod);
}
}
[BlaxTest("watch: an any-drug-binge row watches both binge states and every drug through its link; deleting it clears them; a meal group watches every meal")]
public static void WatchFollowsRows()
{
MentalStateDef extreme = DefDatabase<MentalStateDef>.GetNamed("Binging_DrugExtreme");
MentalStateDef major = DefDatabase<MentalStateDef>.GetNamed("Binging_DrugMajor");
MentalStateDef sad = DefDatabase<MentalStateDef>.GetNamed("Wander_Sad");
T.Check(!Watch.Break && !Watch.Ate, "the book isn't empty at the start");
Law binge = Fixtures.LawRow("Break/@anyDrugBinge", DrugOptions.Any, LawStage.Planning, LawSeverity.Moderate, "Warn", 3);
T.Check(Watch.Any && Watch.Break, "the Break flag is off with a binge row");
T.Check(Watch.IsWatched(ActCategories.Break, extreme) && Watch.IsWatched(ActCategories.Break, major), "a binge state isn't watched");
T.Check(!Watch.IsWatched(ActCategories.Break, sad), "sad wandering is watched by a binge row");
T.Check(Watch.Ate && Watch.IsWatched(ActCategories.Ate, ThingDefOf.WakeUp) && Watch.IsWatched(ActCategories.Ate, ThingDefOf.Beer),
"the binge's link doesn't watch the drugs");
T.Check(!Watch.MayMatch(ActCategories.Ate, ThingDefOf.MealSimple), "a binge row watches simple meals");
T.Check(!Watch.Interaction && !Watch.Special, "a binge row turned an unrelated flag on");
Lawbook.Delete(binge);
T.Check(!Watch.Any && !Watch.Break && !Watch.Ate, "deleting the binge row left a flag on");
T.Check(!Watch.IsWatched(ActCategories.Break, extreme), "deleting the binge row left the state watched");
Law fire = Fixtures.LawRow("Break/FireStartingSpree", null, LawStage.Planning, LawSeverity.Moderate, "Warn", 3);
T.Check(Watch.SetFire && Watch.Special && !Watch.DisplayedCorpse, "a fire spree row must watch SetFire only among the special acts");
Lawbook.SetEnabled(fire, false);
T.Check(!Watch.Any, "a disabled row still watches");
Lawbook.SetEnabled(fire, true);
Fixtures.LawRow("Ate/@anyMeal", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(Watch.IsWatched(ActCategories.Ate, ThingDefOf.MealSimple) && Watch.IsWatched(ActCategories.Ate, ThingDefOf.MealFine), "any meal doesn't watch the meals");
T.Check(!Watch.IsWatched(ActCategories.Ate, ThingDefOf.RawPotatoes), "any meal watches raw potatoes");
Fixtures.LawRow("Ate/@humanMeat", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(Watch.ThingGroups(ActCategories.Ate) && Watch.MayMatch(ActCategories.Ate, ThingDefOf.RawPotatoes),
"a group that reads the thing must let every act of the category through");
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,372 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxLaws;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI;
namespace BlaxLawsTests
{
/// <summary>
/// Shared helpers for tests. Pawns and things made here are removed after each test unless passed to
/// Keep(). Mod settings are restored after each test, and lawbook rows a test added are deleted unless
/// passed to KeepLaw(), so tests may change both freely.
/// </summary>
public static partial class Fixtures
{
private static readonly List<Pawn> made = new List<Pawn>();
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
private static readonly List<Thing> madeThings = new List<Thing>();
private static readonly HashSet<Thing> keptThings = new HashSet<Thing>();
private static readonly HashSet<int> keptLaws = new HashSet<int>();
private static readonly List<Action> cleanups = new List<Action>();
public static Map Map => Find.CurrentMap;
public static BlaxLawsSettings Settings => BlaxLawsMod.Settings;
public static GameComponent_BlaxLaws Comp => GameComponent_BlaxLaws.Instance;
// ---- factions --------------------------------------------------------------------
/// <summary>A visible, non-player, humanlike faction that is not hostile to the player.</summary>
public static Faction FriendlyFaction() =>
Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer))
.OrderBy(f => f.loadID).FirstOrDefault();
/// <summary>A visible, non-player, humanlike faction hostile to the player.</summary>
public static Faction HostileFaction() =>
Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && f.HostileTo(Faction.OfPlayer))
.OrderBy(f => f.loadID).FirstOrDefault();
// ---- pawns -----------------------------------------------------------------------
/// <summary>A fresh pawn, not spawned. Relations off so no accidental family ties.</summary>
public static Pawn Generate(PawnKindDef kind, Faction faction, DevelopmentalStage stage = DevelopmentalStage.Adult)
{
var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer,
forceGenerateNewPawn: true, allowDowned: stage.Baby(), canGeneratePawnRelations: false,
colonistRelationChanceFactor: 0f, developmentalStages: stage);
Pawn p = PawnGenerator.GeneratePawn(req);
made.Add(p);
return p;
}
/// <summary>
/// A standable, unfogged cell near the map center that belongs to a district, so pawns spawned there
/// path, find beds and count as in a room like any colonist. The district reaches the map edge: never
/// the inside of a room a fixture built, such as a prison cell, where no other pawn fits beside it.
/// </summary>
public static IntVec3 PawnCell()
{
Map map = Map;
if (CellFinder.TryFindRandomCellNear(map.Center, map, 20,
c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) is District d && d.TouchesMapEdge && c.GetFirstPawn(map) == null, out IntVec3 cell))
return cell;
if (CellFinder.TryFindRandomCellNear(map.Center, map, 60, c => c.Standable(map) && c.GetDistrict(map) != null, out cell))
return cell;
T.Fail("no standable cell with a district near the map center");
return IntVec3.Invalid;
}
/// <summary>Spawns the pawn at the cell, or on PawnCell() when none is given.</summary>
public static Pawn Spawn(Pawn p, IntVec3? at = null)
{
IntVec3 cell = at ?? PawnCell();
T.Check(cell.GetDistrict(Map) != null, "spawn cell " + cell + " has no district");
GenSpawn.Spawn(p, cell, Map);
return p;
}
/// <summary>A spawned free adult colonist.</summary>
public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer));
/// <summary>A spawned slave of the colony. Skips the test without Ideology.</summary>
public static Pawn ColonySlave(Faction origin = null)
{
T.NeedsDlc("Ideology", ModsConfig.IdeologyActive);
Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction());
Spawn(p);
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony, "slave fixture is not a slave of the colony");
return p;
}
/// <summary>A spawned prisoner of the colony, from a hostile faction when there is one.</summary>
public static Pawn Prisoner()
{
Faction from = HostileFaction() ?? FriendlyFaction();
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
return p;
}
/// <summary>A spawned child of the colony. Skips the test without Biotech.</summary>
public static Pawn Child()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Child));
T.Check(p.DevelopmentalStage.Child(), "child fixture is " + p.DevelopmentalStage + ", not a child");
return p;
}
/// <summary>Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
public static Pawn Keep(Pawn p)
{
kept.Add(p);
return p;
}
public static Pawn FindPawnById(string thingId)
{
if (thingId == null) return null;
foreach (Map m in Find.Maps)
foreach (Pawn p in m.mapPawns.AllPawns)
if (p.ThingID == thingId) return p;
foreach (Pawn p in Find.WorldPawns.AllPawnsAliveOrDead)
if (p.ThingID == thingId) return p;
return null;
}
// ---- things ----------------------------------------------------------------------
/// <summary>Destroy this thing after the test unless kept.</summary>
public static TT Track<TT>(TT thing) where TT : Thing
{
madeThings.Add(thing);
return thing;
}
public static TT Keep<TT>(TT thing) where TT : Thing
{
keptThings.Add(thing);
return thing;
}
/// <summary>A thing a test made or kept, so a fixture never clears it away.</summary>
public static bool IsFixtureThing(Thing t) => madeThings.Contains(t) || keptThings.Contains(t);
/// <summary>
/// Ground a fixture building may go on once cleared, as a player clears a building site: walkable terrain
/// that is not water, unfogged, in the district, with no building and no pawn, and nothing on it but plants,
/// filth and items no test made. A wild map (a dense jungle) has few cells free of trees and starting items.
/// </summary>
public static bool Buildable(IntVec3 c, Map map, District district)
{
if (!c.InBounds(map) || c.Fogged(map) || c.GetDistrict(map) != district)
return false;
TerrainDef terrain = c.GetTerrain(map);
if (terrain.IsWater || terrain.passability != Traversability.Standable)
return false;
List<Thing> things = c.GetThingList(map);
for (int i = 0; i < things.Count; i++)
{
Thing t = things[i];
if (t is Plant || t.def.category == ThingCategory.Filth || t.def.category == ThingCategory.Mote)
continue;
if (t.def.category == ThingCategory.Item && !IsFixtureThing(t))
continue;
return false;
}
return true;
}
/// <summary>Removes the plants and items on the cells, so a building fits (see Buildable).</summary>
public static void ClearGround(IEnumerable<IntVec3> cells, Map map)
{
foreach (IntVec3 c in cells)
{
if (!c.InBounds(map))
continue;
foreach (Thing t in c.GetThingList(map).ToList())
{
if ((t is Plant || t.def.category == ThingCategory.Item) && !IsFixtureThing(t) && !t.Destroyed)
t.Destroy(DestroyMode.Vanish);
}
}
}
// ---- lawbook ---------------------------------------------------------------------
/// <summary>
/// Adds a row through Lawbook.TryAdd and returns it; fails the test when a row with the key exists.
/// Deleted after the test unless passed to KeepLaw.
/// </summary>
public static Law LawRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days,
string savedMod = null, string savedPackageId = null)
{
var law = new Law
{
actKey = actKey,
option = option,
stage = stage,
severity = severity,
punishment = punishment,
days = days,
enabled = true,
savedLabel = ActKey.NameOf(actKey),
savedMod = savedMod,
savedPackageId = savedPackageId,
};
T.Check(Lawbook.TryAdd(law, out Law existing), "LawRow " + actKey + ": refused, existing " + existing);
return law;
}
public static Law KeepLaw(Law law)
{
keptLaws.Add(law.id);
return law;
}
/// <summary>The ids of the rows before a test (used by the runner).</summary>
public static HashSet<int> SnapshotLawbook() => new HashSet<int>(Lawbook.Laws.Select(l => l.id));
/// <summary>Deletes every row a test added that it didn't keep (used by the runner).</summary>
public static void RestoreLawbook(HashSet<int> before)
{
foreach (Law l in Lawbook.Laws.ToList())
{
if (!before.Contains(l.id) && !keptLaws.Contains(l.id))
Lawbook.Delete(l);
}
}
/// <summary>Runs after the test, before things are removed (undo a test-only patch, for example).</summary>
public static void OnCleanup(Action action) => cleanups.Add(action);
// ---- time ------------------------------------------------------------------------
public static void Tick(int ticks)
{
for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick();
}
/// <summary>
/// No incidents, and no mental break a test didn't start: the quick test's own colonists sleep on the
/// ground, eat what they find and hear of every fixture colonist that dies, so over the suite's
/// simulated days their mood sinks and they would break (MentalBreaker checks
/// DebugSettings.enableRandomMentalStates first). Tests start breaks with forced: true, which ignores it.
/// </summary>
public static void QuietStoryteller()
{
Find.Storyteller.incidentQueue.Clear();
Find.Storyteller.storytellerComps.Clear();
DebugSettings.enableRandomMentalStates = false;
}
/// <summary>
/// Before each phase-1 test: the pawns no test made stay out of the next test's way. The quick test's
/// colonists are fed and taken out of any break, and an animal in a manhunter state calms down. A
/// starving or breaking colonist wanders off and can turn an animal manhunter, and a manhunter is an
/// active threat that keeps every later enforcement waiting for the danger to pass
/// (Enforcers.DangerBlocks; RimWorld/GenHostility.cs:227). Each such fix is noted in the results.
/// </summary>
public static void CalmBystanders()
{
Map map = Map;
if (map == null)
return;
foreach (Pawn p in map.mapPawns.AllPawnsSpawned.ToList())
{
if (p == null || p.Dead || kept.Contains(p) || made.Contains(p))
continue;
if (p.IsFreeColonist)
{
if (p.needs?.food != null)
p.needs.food.CurLevel = p.needs.food.MaxLevel;
if (p.needs?.joy != null)
p.needs.joy.CurLevel = 1f;
}
if ((p.IsFreeColonist || p.RaceProps.Animal) && p.InMentalState)
{
TestRunner.Note("calmed " + p.LabelShort + " out of " + p.MentalStateDef.defName + " before the test");
p.MentalState.RecoverFromState();
}
}
}
// ---- settings and cleanup (used by the runner) -----------------------------------
public static Dictionary<FieldInfo, object> SnapshotSettings()
{
var d = new Dictionary<FieldInfo, object>();
if (Settings == null) return d;
foreach (FieldInfo f in typeof(BlaxLawsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
d[f] = f.GetValue(Settings);
return d;
}
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
{
if (Settings == null) return;
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
BlaxLawsMod.ApplyTabVisibility();
}
public static void Cleanup()
{
List<Action> actions = cleanups.ToList();
cleanups.Clear();
foreach (Action a in actions)
{
try { a(); }
catch (Exception e) { TestRunner.Note("cleanup action threw: " + e.Message); }
}
Find.Selector?.ClearSelection();
foreach (Thing t in madeThings)
{
if (t == null || keptThings.Contains(t) || t.Destroyed) continue;
if (t.Spawned || t.holdingOwner != null) t.Destroy(DestroyMode.Vanish);
}
madeThings.Clear();
// Two passes: a pawn another fixture pawn carries (an arrest or capture cut off by the test's end) is
// held, not spawned, and destroying the carrier drops it onto the map, where it would stay as a
// prisoner that claims the next test's prisoner bed.
for (int pass = 0; pass < 2; pass++)
{
foreach (Pawn p in made)
{
if (p == null || kept.Contains(p) || p.Destroyed) continue;
if (pass == 0) DropRitualObligations(p);
if (p.Corpse != null && (p.Corpse.Spawned || p.Corpse.holdingOwner != null)) p.Corpse.Destroy(DestroyMode.Vanish);
else if (p.Spawned || p.holdingOwner != null) p.Destroy(DestroyMode.Vanish);
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
}
}
made.Clear();
}
/// <summary>
/// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or
/// blinding obligation when it joins or changes status (Ideology). The cleanup destroys the pawn or its
/// corpse, so drop those obligations too, or the save warns about a reference to a discarded pawn.
/// </summary>
private static void DropRitualObligations(Pawn p)
{
if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) return;
Corpse corpse = p.Corpse;
bool Hits(TargetInfo t) => t.HasThing && (t.Thing == p || (corpse != null && t.Thing == corpse));
foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading)
{
foreach (Precept precept in ideo.PreceptsListForReading)
{
if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue;
foreach (RitualObligation o in ritual.activeObligations.ToList())
{
if (o != null && (Hits(o.targetA) || Hits(o.targetB) || Hits(o.targetC)))
ritual.RemoveObligation(o);
}
}
}
}
}
}

View File

@ -0,0 +1,656 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using BlaxLaws;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
namespace BlaxLawsTests
{
/// <summary>
/// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh quick-test
/// colony. Phase 2 runs after the runner saved that game and loaded it again. Phase 3 runs after the
/// runner saved again, replaced the GameComponent_BlaxLaws class in the save with one that doesn't exist
/// and loaded that: the vanilla side of a save whose mod was removed.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class BlaxTestAttribute : Attribute
{
public readonly string Name;
public readonly int Phase;
public BlaxTestAttribute(string name, int phase = 1)
{
Name = name;
Phase = phase;
}
}
public class TestFailure : Exception
{
public TestFailure(string message) : base(message) { }
}
public class TestSkipped : Exception
{
public TestSkipped(string message) : base(message) { }
}
/// <summary>Assertions and notes for test bodies.</summary>
public static class T
{
/// <summary>Values carried from phase 1 into phases 2 and 3. Store ThingIDs, ids or def names, never objects.</summary>
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
/// <summary>Carry values read right before the first save, after every phase-1 test ran.</summary>
internal static readonly Dictionary<string, Func<string>> CarryAtSaveTime = new Dictionary<string, Func<string>>();
/// <summary>Carries a value read right before the save instead of now, for state later phase-1 tests may still change.</summary>
public static void CarryAtSave(string key, Func<string> read) => CarryAtSaveTime[key] = read;
public static void Check(bool condition, string message)
{
if (!condition) throw new TestFailure(message);
}
public static void Equal<TV>(TV expected, TV actual, string what)
{
if (!EqualityComparer<TV>.Default.Equals(expected, actual))
throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}");
}
public static void NotNull(object value, string what)
{
if (value == null) throw new TestFailure(what + " is null");
}
public static void Fail(string message) => throw new TestFailure(message);
public static void Skip(string reason) => throw new TestSkipped(reason);
/// <summary>Skips the test unless the DLC is active, with "needs &lt;DLC&gt;" as the reason.</summary>
public static void NeedsDlc(string dlc, bool active)
{
if (!active) throw new TestSkipped("needs " + dlc);
}
/// <summary>Adds an INFO line under the current test in the results file.</summary>
public static void Info(string message) => TestRunner.Note(message);
/// <summary>
/// Expects exactly <paramref name="count"/> errors whose text contains <paramref name="fragment"/>,
/// logged during this test or, in phase 3, during the phase-3 load. Checked when the test ends, so call
/// it before or after the action. Matching errors are excused: they never count as Blax Laws errors,
/// here or as stray errors. Several tests may expect the same errors.
/// </summary>
public static void ExpectErrors(string fragment, int count) => TestRunner.Expect(fragment, count);
/// <summary>Error texts (one line each) logged while the phase-3 save loaded. Empty before phase 3.</summary>
public static List<string> Phase3LoadErrors => TestRunner.LoadErrors();
/// <summary>"Could not resolve reference" warnings logged while the phase-3 save loaded.</summary>
public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings;
/// <summary>"Could not resolve reference" warnings (one line each) logged while the phase-1 save loaded for phase 2.</summary>
public static List<string> Phase2ResolveWarnings => TestRunner.Phase2Warnings();
/// <summary>
/// The warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made for a book or tale and never
/// saved (a vanilla leak, see TestRunner.vanillaTalePawns), not anything Blax Laws saved.
/// </summary>
public static bool NamesVanillaTalePawn(string warning) => TestRunner.NamesVanillaTalePawn(warning);
/// <summary>
/// The warning names a pawn a relation already pointed at, with no save holding it, when the suite
/// began (left by the world's generation, see TestRunner.unsavedAtStart), not anything Blax Laws saved.
/// </summary>
public static bool NamesPawnUnsavedAtStart(string warning) => TestRunner.NamesPawnUnsavedAtStart(warning);
private static string Show(object o) => o == null ? "null" : o.ToString();
}
/// <summary>
/// Drives the suite when the game runs with -quicktest -blaxlawstests: phase 1, save, load, phase 2, save,
/// strip the component class, load, phase 3, then writes BlaxLawsTestResults.txt into the save data
/// folder and quits.
/// </summary>
public class TestRunner : GameComponent
{
public const string SaveName = "BlaxLawsTest";
public const string Phase3SaveName = "BlaxLawsTest3";
public const string ResultFile = "BlaxLawsTestResults.txt";
/// <summary>The class attribute phase 3 replaces in the save.</summary>
public const string ComponentClassAttr = "Class=\"BlaxLaws.GameComponent_BlaxLaws\"";
/// <summary>A class that doesn't exist; the phase-3 save names it instead of GameComponent_BlaxLaws.</summary>
public const string RemovedComponentClass = "BlaxLawsRemoved.GameComponent_BlaxLaws";
/// <summary>Where errors logged during the phase-3 load are filed.</summary>
public const string Phase3LoadTag = "(phase 3 load)";
/// <summary>Where errors logged while the phase-1 save loads for phase 2 are filed.</summary>
public const string Phase2LoadTag = "(phase 2 load)";
private class LogEntry
{
public string where;
public string text;
public bool ours;
public bool excused;
public bool warning;
}
private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 phase 2 done + phase-3 load queued, 3 finished
private static int loadsSeen;
private static int pass, fail, skip;
private static string currentTest;
private static readonly List<LogEntry> errors = new List<LogEntry>();
private static readonly List<(string fragment, int count)> expectations = new List<(string, int)>();
private static int resolveWarnings;
private static readonly List<string> phase2Warnings = new List<string>();
private static readonly HashSet<string> danglingSeen = new HashSet<string>();
private static bool hooked;
private int settleFrames;
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxlawstests");
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
/// <summary>Component nodes phase 3 replaced in the save. Set before the phase-3 load.</summary>
public static int Phase3ReplacedCount { get; private set; }
public static int ResolveWarnings => resolveWarnings;
public TestRunner(Game game) { }
public override void LoadedGame()
{
if (Enabled && (stage == 1 || stage == 2)) loadsSeen++;
}
public override void GameComponentUpdate()
{
if (!Enabled || stage == 3) return;
if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return;
if (++settleFrames < 30) return;
if (stage == 0)
{
stage = 1;
Begin();
RunPhase(1);
Line("STAGE save+reload");
try
{
foreach (var kv in T.CarryAtSaveTime)
{
try { T.Carry[kv.Key] = kv.Value(); }
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
}
NoteDanglingRelations();
GameDataSaveLoader.SaveGame(SaveName);
lock (errors) phase2Warnings.Clear();
currentTest = Phase2LoadTag;
GameDataSaveLoader.LoadGame(SaveName);
}
catch (Exception e)
{
currentTest = null;
Record("FAIL", "save and reload", e.ToString());
Finish();
}
}
else if (stage == 1 && loadsSeen >= 1)
{
stage = 2;
currentTest = null;
Line("STAGE phase 2 (after reload)");
Note("phase 2 load: " + Phase2Warnings().Count + " 'Could not resolve reference' warning(s)");
RunPhase(2);
Line("STAGE phase 3 (component class removed from the save)");
try
{
StartPhase3Load();
}
catch (Exception e)
{
currentTest = null;
Record("FAIL", "phase 3 save and load", e.ToString());
Finish();
}
}
else if (stage == 2 && loadsSeen >= 2)
{
currentTest = null;
Note("phase 3 load: " + Phase3ReplacedCount + " component node(s) replaced, " + LoadErrors().Count + " error(s), " +
resolveWarnings + " 'Could not resolve reference' warning(s)");
RunPhase(3);
Finish();
}
}
/// <summary>
/// Saves as BlaxLawsTest3 (saves are plain XML in 1.7, ScribeSaver.cs:45-49), replaces the component's
/// class with one that doesn't exist and loads it. Laws' assembly stays loaded, so Game.FillComponents
/// adds a fresh, empty component after the load.
/// </summary>
private static void StartPhase3Load()
{
GameDataSaveLoader.SaveGame(Phase3SaveName);
string path = GenFilePaths.FilePathForSavedGame(Phase3SaveName);
string xml = File.ReadAllText(path);
int count = 0;
for (int i = xml.IndexOf(ComponentClassAttr, StringComparison.Ordinal); i >= 0; i = xml.IndexOf(ComponentClassAttr, i + 1, StringComparison.Ordinal))
count++;
if (count == 0)
throw new Exception("the phase-3 save holds no " + ComponentClassAttr);
Phase3ReplacedCount = count;
File.WriteAllText(path, xml.Replace(ComponentClassAttr, "Class=\"" + RemovedComponentClass + "\""));
lock (errors) resolveWarnings = 0;
currentTest = Phase3LoadTag;
GameDataSaveLoader.LoadGame(Phase3SaveName);
}
/// <summary>The game log as it stood when the suite began, before any test ran (the startup test reads it).</summary>
public static List<LogMessage> StartupLog { get; private set; } = new List<LogMessage>();
/// <summary>
/// The new game as it stood when the suite began, before any test ran: rows, cases, the watch flags and
/// the enforcement queue. Test classes run in name order, so the empty-book test reads this instead of
/// the state other tests left behind.
/// </summary>
public static NewGameState AtStart { get; private set; }
public sealed class NewGameState
{
public int laws, cases, pending;
public bool watchAny, categoryFlag, specialFlag;
}
private static void Begin()
{
try { File.Delete(ResultPath); } catch { }
StartupLog = Log.Messages.ToList();
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
AtStart = new NewGameState
{
laws = comp?.Laws.Count ?? -1,
cases = comp?.Cases.Count ?? -1,
pending = Enforcement.Pending,
watchAny = Watch.Any,
categoryFlag = Watch.Break || Watch.Ate || Watch.Used || Watch.Interaction || Watch.RecordedAct || Watch.Record || Watch.Bill || Watch.Special,
specialFlag = Watch.SetFire || Watch.DisplayedCorpse || Watch.StartedSocialFight,
};
HookLog();
HookPawnWatchers();
Line("BEGIN Blax Laws in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
Line("DLCs: Royalty " + ModsConfig.RoyaltyActive + ", Ideology " + ModsConfig.IdeologyActive + ", Biotech " + ModsConfig.BiotechActive +
", Anomaly " + ModsConfig.AnomalyActive + ", Odyssey " + ModsConfig.OdysseyActive);
Fixtures.QuietStoryteller();
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
NoteUnsavedAtStart();
}
private static void HookLog()
{
if (hooked) return;
hooked = true;
Application.logMessageReceivedThreaded += (text, stack, type) =>
{
if (type == LogType.Warning)
{
if (text != null && text.Contains("Could not resolve reference"))
{
if (currentTest == Phase3LoadTag)
lock (errors) resolveWarnings++;
else if (currentTest == Phase2LoadTag)
lock (errors) phase2Warnings.Add(OneLine(text));
}
// Blax Laws' own warnings ("[Blax Laws] ...") between tests count as stray mod warnings.
if (text != null && text.Contains("[Blax Laws]"))
lock (errors) errors.Add(new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = true, warning = true });
return;
}
if (type != LogType.Error && type != LogType.Exception) return;
bool ours = !IsKnownForeignError(text, stack)
&& ((text != null && (text.Contains("BlaxLaws") || text.Contains("Blax Laws"))) || (stack != null && stack.Contains("BlaxLaws")));
var entry = new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = ours };
lock (errors) errors.Add(entry);
};
}
/// <summary>
/// Errors another mod logs from its own code while a test ticks the game. The test's frames are in the
/// stack, so the check above would blame Blax Laws; these show as LOGERR lines instead. Each entry is a
/// text fragment and the frame that logs it. Add one per mod, with the reason, as Zones does:
/// - Prison Labor (-Compat): its postfix on Pawn_GuestTracker.SetGuestStatus passes its own
/// PrisonLabor_workOption, a non-exclusive mode in 1.7, to SetExclusiveInteraction, so the game logs
/// "Attempted to set guest exclusive interaction to a non-exclusive interaction type" once for the
/// first pawn made a prisoner (the prisoner fixture).
/// - Prisoner Realism (-Compat): HediffComp_Solitary ticks on a prisoner the release job carries
/// (JobDriver_ReleasePrisoner.cs:27), and SolitaryUtility.IsInSolitary passes pawn.Map, null while it is
/// carried, to GetDoor (its Source/Features/Solitary/SolitaryUtility.cs:56-59): an NRE the game logs as
/// "Exception ticking hediff (PR_Solitary ...)" whenever a warden releases a prisoner from a cell.
/// </summary>
private static readonly (string text, string frame)[] KnownForeignErrors =
{
("non-exclusive interaction type: PrisonLabor_", "Patch_DefaultInteractionMode"),
("PrisonerRealism.SolitaryUtility.IsInSolitary", "Pawn_HealthTracker.HealthTick"),
};
private static bool IsKnownForeignError(string text, string stack)
{
if (text == null || stack == null)
return false;
foreach (var (fragment, frame) in KnownForeignErrors)
{
if (text.Contains(fragment) && stack.Contains(frame))
return true;
}
return false;
}
internal static void Expect(string fragment, int count)
{
if (fragment.NullOrEmpty()) throw new TestFailure("ExpectErrors needs a text fragment");
expectations.Add((fragment, count));
}
internal static List<string> LoadErrors()
{
lock (errors) return errors.Where(e => e.where == Phase3LoadTag && !e.warning).Select(e => e.text).ToList();
}
internal static List<string> Phase2Warnings()
{
lock (errors) return phase2Warnings.ToList();
}
/// <summary>
/// Notes every pawn relation, new since the last check, whose other pawn no save holds (discarded, or
/// on no map, in no container and not a world pawn). Each one becomes a "Could not resolve reference"
/// warning when the save loads. Runs after every test and once more right before the phase-1 save.
/// Pawns vanilla made for books and tales are left out here (see vanillaTalePawns); the reload test
/// counts them.
/// </summary>
private static void NoteDanglingRelations()
{
try
{
foreach (var (p, r, o) in DanglingRelations())
{
if (!danglingSeen.Add(p.ThingID + ">" + (o?.ThingID ?? "null")))
continue;
if (o != null && (IsVanillaTalePawn(o.ThingID) || IsUnsavedAtStart(o.ThingID)))
continue;
Note("dangling relation: " + p.ThingID + " (" + p.LabelShort + ", " + (p.Faction?.GetUniqueLoadID() ?? "no faction") + ") " +
r.def.defName + " -> " + Describe(o));
}
}
catch (Exception e)
{
Note("relation check threw: " + OneLine(e.Message));
}
}
/// <summary>Every pawn relation whose other pawn no save holds (discarded, or on no map, in no container and not a world pawn).</summary>
private static List<(Pawn p, DirectPawnRelation r, Pawn o)> DanglingRelations()
{
var found = new List<(Pawn, DirectPawnRelation, Pawn)>();
var all = new HashSet<Pawn>(PawnsFinder.All_AliveOrDead);
foreach (Pawn p in all.ToList())
{
if (p?.relations == null)
continue;
foreach (DirectPawnRelation r in p.relations.DirectRelations)
{
Pawn o = r.otherPawn;
if (o != null && !o.Discarded && all.Contains(o))
continue;
found.Add((p, r, o));
}
}
return found;
}
/// <summary>
/// Pawns that relations already pointed at, with no save holding them, when the suite began: the new
/// world's generation left them so (seen with an AncientSoldier ex-lover of a faction pawn), before any
/// test ran and with an empty lawbook. The reload test excuses them like the tale pawns.
/// </summary>
private static readonly HashSet<string> unsavedAtStart = new HashSet<string>();
private static bool IsUnsavedAtStart(string thingId) => thingId != null && unsavedAtStart.Contains(thingId);
/// <summary>The "Could not resolve reference" warning names a pawn no save held when the suite began.</summary>
internal static bool NamesPawnUnsavedAtStart(string warning)
{
Match m = warning == null ? null : ResolveWarningId.Match(warning);
return m != null && m.Success && IsUnsavedAtStart(m.Groups[1].Value);
}
private static void NoteUnsavedAtStart()
{
try
{
foreach (var (p, r, o) in DanglingRelations())
{
if (o == null || !unsavedAtStart.Add(o.ThingID))
continue;
Note("unsaved at the start (world generation): " + p.ThingID + " (" + p.LabelShort + ") " + r.def.defName + " -> " + Describe(o));
}
}
catch (Exception e)
{
Note("start relation check threw: " + OneLine(e.Message));
}
}
private static string Describe(Pawn o)
{
if (o == null)
return "null";
string removed;
lock (worldRemovals) worldRemovals.TryGetValue(o.ThingID, out removed);
return o.ThingID + " (" + o.LabelShort + ", kind " + o.kindDef?.defName + ", " + (o.Faction?.GetUniqueLoadID() ?? "no faction") +
", destroyed " + o.Destroyed + ", discarded " + o.Discarded + ", dead " + o.Dead + ", spawned " + o.Spawned +
", world pawn " + o.IsWorldPawn() + ", held by " + (o.ParentHolder?.ToString() ?? "nothing") + ")" +
(IsVanillaTalePawn(o.ThingID) ? "; vanilla: made by TaleData_Pawn.GenerateRandom and never saved" : "") +
(removed != null ? "; left the world pawns from: " + removed : "");
}
/// <summary>Who took each pawn out of WorldPawns this run (ThingID to the calling frames), for the dangling-relation notes.</summary>
private static readonly Dictionary<string, string> worldRemovals = new Dictionary<string, string>();
private static bool pawnWatchersHooked;
/// <summary>
/// Pawns vanilla's TaleData_Pawn.GenerateRandom made this run (ThingIDs). It generates a pawn for a
/// book's text (Book.GenerateBook, Book.cs:235), a unique weapon's name or a tale, keeps only its
/// TaleData and never saves or discards the pawn (TaleData_Pawn.cs:110-115). Relations to such a pawn
/// point at a pawn no save holds.
/// </summary>
private static readonly HashSet<string> vanillaTalePawns = new HashSet<string>();
private static readonly Regex ResolveWarningId = new Regex(@"loadID Thing_(\S+) of type Verse\.Pawn");
private static bool IsVanillaTalePawn(string thingId)
{
lock (vanillaTalePawns) return thingId != null && vanillaTalePawns.Contains(thingId);
}
/// <summary>The "Could not resolve reference" warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made and never saved.</summary>
internal static bool NamesVanillaTalePawn(string warning)
{
Match m = warning == null ? null : ResolveWarningId.Match(warning);
return m != null && m.Success && IsVanillaTalePawn(m.Groups[1].Value);
}
/// <summary>Installs the WorldPawns.RemovePawn and TaleData_Pawn.GenerateRandom watchers once, at startup (QuickTestMap), before the world exists.</summary>
internal static void HookPawnWatchers()
{
if (pawnWatchersHooked)
return;
pawnWatchersHooked = true;
try
{
var harmony = new HarmonyLib.Harmony("blax.laws.tests.harness");
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(WorldPawns), nameof(WorldPawns.RemovePawn)),
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnWorldPawnRemoved))));
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(TaleData_Pawn), nameof(TaleData_Pawn.GenerateRandom)),
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnTalePawnGenerated))));
}
catch (Exception e)
{
Note("could not watch WorldPawns.RemovePawn or TaleData_Pawn.GenerateRandom: " + OneLine(e.Message));
}
}
private static void OnTalePawnGenerated(TaleData_Pawn __result)
{
string id = __result?.pawn?.ThingID;
if (id != null)
lock (vanillaTalePawns) vanillaTalePawns.Add(id);
}
private static void OnWorldPawnRemoved(Pawn p)
{
if (p == null)
return;
var frames = new System.Diagnostics.StackTrace(2, false).GetFrames() ?? new System.Diagnostics.StackFrame[0];
string where = string.Join(" < ", frames.Take(8).Select(f => f.GetMethod()).Where(m => m != null)
.Select(m => m.DeclaringType?.Name + "." + m.Name));
lock (worldRemovals) worldRemovals[p.ThingID] = where;
}
private static void RunPhase(int phase)
{
var tests = typeof(TestRunner).Assembly.GetTypes()
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
.Select(m => (method: m, attr: m.GetCustomAttribute<BlaxTestAttribute>()))
.Where(x => x.attr != null && x.attr.Phase == phase)
.OrderBy(x => x.method.DeclaringType.FullName)
.ThenBy(x => x.method.MetadataToken)
.ToList();
foreach (var (method, attr) in tests) RunOne(attr.Name, method, phase);
}
private static void RunOne(string name, MethodInfo method, int phase)
{
currentTest = name;
expectations.Clear();
int before;
lock (errors) before = errors.Count;
var settings = Fixtures.SnapshotSettings();
var lawbook = Fixtures.SnapshotLawbook();
string status = "PASS", detail = "";
try
{
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
if (phase == 1)
Fixtures.CalmBystanders();
method.Invoke(null, null);
}
catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s)
{
status = "SKIP"; detail = s.Message;
}
catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f)
{
status = "FAIL"; detail = f.Message;
}
catch (TargetInvocationException tie)
{
status = "FAIL"; detail = "exception: " + tie.InnerException;
}
catch (Exception e)
{
status = "FAIL"; detail = "runner exception: " + e;
}
finally
{
Fixtures.RestoreSettings(settings);
try { Fixtures.RestoreLawbook(lawbook); } catch (Exception e) { Note("lawbook restore threw: " + OneLine(e.Message)); }
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
LawsTestHooks.Reset();
Compat.SimulatedActive.Clear();
NoteDanglingRelations();
}
List<LogEntry> newErrors;
lock (errors)
{
newErrors = errors.Skip(before).Where(e => !e.warning).ToList();
var window = phase == 3 ? newErrors.Concat(errors.Take(before).Where(e => e.where == Phase3LoadTag && !e.warning)).ToList() : newErrors;
foreach (var (fragment, count) in expectations)
{
var matches = window.Where(e => e.text.Contains(fragment)).ToList();
foreach (LogEntry m in matches) m.excused = true;
if (matches.Count != count && status == "PASS")
{
status = "FAIL";
detail = $"expected {count} error(s) containing '{fragment}', got {matches.Count}";
}
}
}
expectations.Clear();
var newModErrors = newErrors.Where(e => e.ours && !e.excused).ToList();
var newOtherErrors = newErrors.Where(e => !e.ours && !e.excused).ToList();
if (status == "PASS" && newModErrors.Count > 0)
{
status = "FAIL";
detail = "Blax Laws logged errors: " + string.Join(" | ", newModErrors.Take(3).Select(e => e.text));
}
Record(status, name, detail);
foreach (LogEntry e in newOtherErrors.Take(5)) Line(" LOGERR " + e.where + ": " + e.text);
currentTest = null;
}
private static void Finish()
{
stage = 3;
currentTest = null;
List<LogEntry> stray, strayWarnings;
lock (errors)
{
stray = errors.Where(e => e.where.StartsWith("(") && e.ours && !e.excused && !e.warning).ToList();
strayWarnings = errors.Where(e => e.where.StartsWith("(") && e.warning).ToList();
}
foreach (LogEntry e in stray.Take(10)) Line(" MODERR " + e.where + ": " + e.text);
foreach (LogEntry e in strayWarnings.Take(10)) Line(" MODWARN " + e.where + ": " + e.text);
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count} strayModWarnings={strayWarnings.Count}");
Line("END");
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
Root.Shutdown();
}
internal static void Note(string message) => Line(" INFO " + OneLine(message));
private static void Record(string status, string name, string detail)
{
if (status == "PASS") pass++;
else if (status == "FAIL") fail++;
else skip++;
Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}");
}
private static void Line(string text)
{
Log.Message("[BlaxTest] " + text);
try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { }
}
private static string OneLine(string s)
{
if (s == null) return "";
s = s.Replace("\r", " ").Replace("\n", " | ");
return s.Length > 1500 ? s.Substring(0, 1500) + "..." : s;
}
}
}

View File

@ -0,0 +1,655 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxLaws;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLawsTests
{
/// <summary>
/// "Jail for N days": the arrest, hook K, "Maintain only" two ticks after the capture, the release, the
/// old bed, a late arrest, no prisoner bed, the holds and fallbacks, the early end, and a jailed colonist
/// through the save and the removal.
/// </summary>
public static class JailTests
{
private const string PrisonLaborId = "avius.prisonlabor"; // Prison Labor's About.xml (Workshop 1899474310), read 2026-12-01
private const string CastesId = "blax.castes";
private static int Now => Find.TickManager.TicksGame;
// ---- the sentence -----------------------------------------------------------------
[BlaxTest("jail: a did-it binge case with jail 3 days: a prisoner within 2500 ticks, the break over without catharsis, guilt for the sentence plus a day, Maintain only two ticks after the capture; at the release tick Release, a warden releases it with WasImprisoned and the same work priorities")]
public static void JailThreeDays()
{
EnforceFixtures.PrisonCell();
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
Dictionary<WorkTypeDef, int> priorities = EnforceFixtures.Priorities(o);
EnforceFixtures.ForceBreak(o, EnforceFixtures.DrugBinge, causedByMood: true);
LawCase c = EnforceFixtures.BreakCase(o, "Jail", LawStage.DidIt, 3);
Enforcement.Enqueue(c, LawStage.DidIt);
int arrestStart = -1;
bool jailed = EnforceFixtures.RunUntil(() =>
{
if (arrestStart < 0 && c.status == CaseStatus.Enforcing)
arrestStart = Now;
return o.IsPrisonerOfColony;
}, EnforceFixtures.SubdueTicks);
T.Check(jailed, "not a prisoner within 2500 ticks; case " + c + ", wait " + c.waitReason);
T.Equal(CaseStatus.Jailed, c.status, "the case's status at the capture");
T.Equal(Now, c.captureTick, "the capture tick");
T.Equal(c.captureTick + 3 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
T.Check(o.MentalState == null, "the break goes on in jail: " + o.MentalStateDef?.defName);
T.Check(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis) == null, "the jailed pawn has Catharsis");
int minGuilt = 4 * GenDate.TicksPerDay - (Now - arrestStart) - 30;
T.Check(o.guilt.TicksUntilInnocent >= minGuilt, "guilt " + o.guilt.TicksUntilInnocent + ", expected at least " + minGuilt);
Fixtures.Tick(2);
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode two ticks after the capture");
bool labor = LaborOn(o);
T.Check(c.maintainOnlyDone, "maintainOnlyDone after the write");
c.releaseTick = Now;
EnforceFixtures.TickPastSentenceSweep();
T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the mode at the release tick");
bool released = EnforceFixtures.RunUntil(() => !o.IsPrisonerOfColony, 4000);
T.Check(released, "no warden released the pawn");
T.Check(o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the release");
T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the release");
string diff = PriorityDiff(priorities, o, labor);
T.Check(diff == null, "work priorities changed: " + diff);
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the release: " + c);
}
[BlaxTest("jail: a mode written at capture plus 1 (Enslave with Ideology, else Reduce resistance) reads Maintain only at capture plus 2, with Laws' component first")]
public static void MaintainOnlyLandsLast()
{
MoveLawsComponentFirst();
EnforceFixtures.PrisonCell();
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
Enforcement.Enqueue(c, LawStage.DidIt);
T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason);
T.Equal(Now, c.captureTick, "the capture tick");
Fixtures.Tick(1);
PrisonerInteractionModeDef other = ModsConfig.IdeologyActive && PrisonerInteractionModeDefOf.Enslave != null
? PrisonerInteractionModeDefOf.Enslave
: PrisonerInteractionModeDefOf.ReduceResistance;
o.guest.SetExclusiveInteraction(other);
T.Equal(other, o.guest.ExclusiveInteractionMode, "the mode written at capture plus 1");
Fixtures.Tick(1);
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode at capture plus 2");
}
/// <summary>Puts Laws' component before Castes' in Game.components for the test (Castes writes its default a tick after the capture).</summary>
private static void MoveLawsComponentFirst()
{
List<GameComponent> list = Current.Game.components;
GameComponent_BlaxLaws laws = Fixtures.Comp;
int at = list.FindIndex(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes");
int mine = list.IndexOf(laws);
if (at < 0 || mine < 0 || mine < at)
return;
List<GameComponent> before = list.ToList();
list.Remove(laws);
list.Insert(at, laws);
Fixtures.OnCleanup(() =>
{
list.Clear();
list.AddRange(before);
});
}
[BlaxTest("jail: with Prison Labor's work option off the released pawn has the work priorities it had before the arrest; with it on only the work types Prison Labor bars prisoners from are off (needs Prison Labor)")]
public static void PrisonLaborKeepsPriorities()
{
if (!Compat.IsActive(PrisonLaborId))
T.Skip("needs Prison Labor");
PrisonerInteractionModeDef work = DefDatabase<PrisonerInteractionModeDef>.GetNamedSilentFail("PrisonLabor_workOption");
T.NotNull(work, "Prison Labor's PrisonLabor_workOption mode");
foreach (bool on in new[] { false, true })
{
Pawn o = EnforceFixtures.Offender();
Dictionary<WorkTypeDef, int> priorities = EnforceFixtures.Priorities(o);
LawCase c = JailAndRelease(o, () => o.guest.ToggleNonExclusiveInteraction(work, on));
string diff = PriorityDiff(priorities, o, on);
T.Check(diff == null, "work priorities changed with the work option " + (on ? "on" : "off") + ": " + diff);
T.Check(c.IsClosed, "the case after the release: " + c);
}
}
/// <summary>Prison Labor's work option is on for the prisoner (PrisonLaborUtility.LaborEnabled in its 1.7 PrisonLabor.dll).</summary>
private static bool LaborOn(Pawn o)
{
PrisonerInteractionModeDef work = DefDatabase<PrisonerInteractionModeDef>.GetNamedSilentFail("PrisonLabor_workOption");
return work != null && o.guest != null && o.guest.IsInteractionEnabled(work);
}
/// <summary>
/// The changed work priorities, or null. While Prison Labor's work option is on, its JobGiver_Labor runs
/// WorkSettings.InitWorkSettings, which disables every work type its settings bar prisoners from
/// (WorkSettings.WorkDisabled, Pawn_WorkSettings.Disable), and those stay at 0 after the release: Prison
/// Labor's call, not Laws' (design: "Jail for N days", Overlaps). Only those may read 0 afterwards.
/// </summary>
private static string PriorityDiff(Dictionary<WorkTypeDef, int> before, Pawn o, bool labor)
{
Func<WorkTypeDef, bool> barred = _ => false;
if (labor)
{
MethodInfo m = GenTypes.GetTypeInAnyAssembly("PrisonLabor.Core.LaborWorkSettings.WorkSettings")?
.GetMethod("WorkDisabled", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(WorkTypeDef) }, null);
T.NotNull(m, "Prison Labor's WorkSettings.WorkDisabled(WorkTypeDef)");
barred = wt => (bool)m.Invoke(null, new object[] { wt });
}
var diff = before.Where(kv => o.workSettings.GetPriority(kv.Key) != kv.Value && !(o.workSettings.GetPriority(kv.Key) == 0 && barred(kv.Key)))
.Select(kv => kv.Key.defName + " " + kv.Value + " to " + o.workSettings.GetPriority(kv.Key)).ToList();
return diff.Count == 0 ? null : string.Join(", ", diff);
}
[BlaxTest("jail: with Blax Castes the released pawn is back in its old caste (needs Blax Castes)")]
public static void CastesKeepsCaste()
{
if (!Compat.IsActive(CastesId))
T.Skip("needs Blax Castes");
GameComponent castes = Current.Game.components.FirstOrDefault(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes");
T.NotNull(castes, "Castes' game component");
MethodInfo casteOf = castes.GetType().GetMethod("CasteOf", new[] { typeof(Pawn) });
T.NotNull(casteOf, "GameComponent_BlaxCastes.CasteOf(Pawn)");
// A generated colonist joins no caste (Castes' join hooks see no SetFaction or SetGuestStatus), so the
// offender is put into a caste of its own, which no join row names: only "back to its old caste"
// brings it back there after the release.
Type manager = GenTypes.GetTypeInAnyAssembly("BlaxCastes.CasteManager");
MethodInfo create = manager?.GetMethod("CreateCaste", BindingFlags.Public | BindingFlags.Static);
MethodInfo assign = manager?.GetMethod("Assign", BindingFlags.Public | BindingFlags.Static);
MethodInfo delete = manager?.GetMethod("DeleteCaste", BindingFlags.Public | BindingFlags.Static);
T.Check(create != null && assign != null && delete != null, "CasteManager.CreateCaste, Assign and DeleteCaste");
object caste = create.Invoke(null, new object[] { "BlaxLawsTest caste" });
T.NotNull(caste, "the test caste");
Fixtures.OnCleanup(() => delete.Invoke(null, new[] { caste }));
Pawn o = EnforceFixtures.Offender();
T.Check((bool)assign.Invoke(null, new object[] { o, caste, false, null }), "fixture: the offender can't join the test caste");
Fixtures.Tick(2);
object before = casteOf.Invoke(castes, new object[] { o });
T.Check(Equals(before, caste), "fixture: the offender isn't in the test caste: " + before);
JailAndRelease(o, null);
Fixtures.Tick(5);
object after = casteOf.Invoke(castes, new object[] { o });
T.Check(Equals(before, after), "the caste after the release isn't the old one: " + before + " to " + after);
}
/// <summary>Jails the pawn through a 1-day row and releases it through the fallback. atJail runs while it is jailed.</summary>
private static LawCase JailAndRelease(Pawn o, Action atJail)
{
// The fallback below backdates the release tick by a day. Before day 2 that tick would be negative,
// which Sentences.Check reads as "not set yet" and recomputes from the capture, so the game clock
// is moved past a day first, before anything of this test is scheduled.
if (Now < 2 * Sentences.FallbackTicks)
Find.TickManager.DebugSetTicksGame(2 * Sentences.FallbackTicks);
EnforceFixtures.PrisonCell();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
LawCase c = EnforceFixtures.ActCase(o, "Jail", 1);
Enforcement.Enqueue(c, LawStage.DidIt);
// An arrested colonist turns prisoner when the warden picks it up (JobDriver_TakeToBed.cs:124-129) and
// stays held, not spawned, until it is tucked in; the fallback releases only a spawned pawn. atJail runs
// at the pick-up, before the prisoner thinks once (Prison Labor's default work option is set there).
T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason);
atJail?.Invoke();
T.Check(EnforceFixtures.RunUntil(() => o.Spawned && o.InBed(), EnforceFixtures.SubdueTicks),
"the prisoner isn't in its bed; case " + c + ", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned);
Fixtures.Tick(5);
c.releaseTick = Now - Sentences.FallbackTicks - 1;
Sentences.Check(c);
T.Check(!o.IsPrisonerOfColony, "the fallback didn't release the pawn; case " + c + ", spawned " + o.Spawned + ", in bed " + o.InBed());
return c;
}
// ---- the arrest -------------------------------------------------------------------
[BlaxTest("jail: an arrest interrupted after its first toil leaves the colonist its old bed by the next sweep; a bed someone else claimed meanwhile stays theirs")]
public static void OldBedBack()
{
PrisonRoom room = EnforceFixtures.PrisonCell();
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
Building_Bed own = EnforceFixtures.ColonistBed(o.Position);
T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed");
// Bystanders without a bed would take the freed bed when they go to sleep before the sweep: the case
// of a bed someone else claimed, which the second half tests on purpose.
EnforceFixtures.BedsForBystanders(o);
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Check(JailFlow.ArrestRuns(c), "no arrest started; wait " + c.waitReason);
T.Equal(own, c.oldBed, "the old bed noted in the case");
T.Check(o.ownership.OwnedBed == room.bed, "the arrest's first toil didn't claim the prisoner bed: " + o.ownership.OwnedBed);
Pawn raider = EnforceFixtures.Raider(); // keeps the retry waiting, so the sweep's give-back shows
c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced);
Fixtures.Tick(Enforcement.SweepInterval + 1);
T.Check(o.ownership.OwnedBed == own, "the colonist doesn't own its old bed after the sweep: it owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed") +
", the old bed's owners " + Owners(own) + "; case " + c + ", wait " + c.waitReason + ", arrest runs " + JailFlow.ArrestRuns(c));
T.Equal(WaitReasons.Danger, c.waitReason, "the case's wait while the raider is on the map");
raider.Destroy(DestroyMode.Vanish);
T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c), Enforcement.SweepInterval + 5), "no second arrest; wait " + c.waitReason);
T.Check(o.ownership.OwnedBed == room.bed, "the second arrest didn't claim the prisoner bed");
Pawn other = EnforceFixtures.Offender(EnforceFixtures.CellNear(o.Position, 6f, 12f));
T.Check(other.ownership.ClaimBedIfNonMedical(own), "fixture: another colonist can't claim the free old bed");
EnforceFixtures.Raider();
c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced);
Fixtures.Tick(Enforcement.SweepInterval + 1);
T.Check(own.OwnersForReading.Contains(other), "the other colonist lost the bed it claimed");
T.Check(!own.OwnersForReading.Contains(o), "the offender took back a bed someone else claimed");
}
[BlaxTest("jail: a raid that lands while the arrest walks to the colonist calls it off, gives the old bed back and waits for the danger; after the raid the sweep arrests")]
public static void RaidCallsOffArrest()
{
PrisonRoom room = EnforceFixtures.PrisonCell();
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
Building_Bed own = EnforceFixtures.ColonistBed(o.Position);
T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed");
EnforceFixtures.BedsForBystanders(o);
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason);
T.Check(!c.enforcer.IsCarryingPawn(o), "fixture: the warden already carries the colonist");
Pawn raider = EnforceFixtures.Raider();
// The worker's sweep directly, so the arrest can't finish between the raid and the check.
BlaxLawsDefOf.Jail.Worker.Sweep(c);
T.Check(!JailFlow.ArrestRuns(c), "the arrest still runs during the raid");
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an enforcement job on the colonist during the raid");
T.Equal(CaseStatus.Open, c.status, "status during the raid");
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
T.Check(!o.IsPrisonerOfColony, "a prisoner during the raid");
T.Check(o.ownership.OwnedBed == own, "the old bed wasn't given back: owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed"));
raider.Destroy(DestroyMode.Vanish);
T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SweepInterval + 5), "no arrest after the raid; wait " + c.waitReason);
T.Check(o.ownership.OwnedBed == room.bed || o.IsPrisonerOfColony, "the second arrest didn't claim the prisoner bed");
}
[BlaxTest("jail: a raid that lands while the warden already carries the arrested colonist doesn't call the arrest off: the carry finishes and the case is jailed")]
public static void RaidLetsCarryFinish()
{
PrisonRoom room = EnforceFixtures.PrisonCell();
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
EnforceFixtures.BedsForBystanders(o);
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason);
Pawn enforcer = c.enforcer;
T.Check(EnforceFixtures.RunUntil(() => enforcer.IsCarryingPawn(o), EnforceFixtures.SubdueTicks),
"fixture: the warden never carried the colonist; case " + c + ", warden on " + (enforcer.CurJobDef?.defName ?? "no job"));
EnforceFixtures.Raider();
// A carried pawn is despawned, so the raider counts through the enforcer's map (Raider() checks the threat).
T.Check(GenHostility.AnyHostileActiveThreatToPlayer(enforcer.Map), "fixture: the raider is no threat on the warden's map");
// The worker's sweep directly, while the warden carries the colonist.
BlaxLawsDefOf.Jail.Worker.Sweep(c);
T.Check(JailFlow.ArrestRuns(c), "the arrest was called off mid-carry");
T.Check(enforcer.IsCarryingPawn(o), "the warden dropped the colonist");
T.Check(c.waitReason != WaitReasons.Danger, "the case waits for the danger while the carry goes on");
T.Check(EnforceFixtures.RunUntil(() => c.status == CaseStatus.Jailed, EnforceFixtures.SubdueTicks),
"the carry didn't end in a jailing with the raider on the map; case " + c + ", wait " + c.waitReason);
T.Check(o.IsPrisonerOfColony && o.ownership.OwnedBed == room.bed, "the colonist isn't a prisoner owning the cell's bed: " + (o.ownership.OwnedBed?.ToString() ?? "no bed"));
}
private static string Owners(Building_Bed bed)
{
List<Pawn> owners = bed.OwnersForReading;
if (owners.Count == 0)
return "none";
return string.Join(", ", owners.Select(p => p.LabelShort + (p.Awake() ? " (awake)" : " (asleep)")));
}
[BlaxTest("jail: a 5-day row whose guilt ran out while no prisoner bed existed: once a bed is built the arrest is accepted against Social 0 and the release comes 5 days after the capture")]
public static void LateArrest()
{
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
SocialZeroForAll();
LawCase c = EnforceFixtures.ActCase(o, "Jail", 5);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed");
T.Check(o.guilt.TicksUntilInnocent >= 5 * GenDate.TicksPerDay - 30, "no guilt for the sentence at filing: " + o.guilt.TicksUntilInnocent);
o.guilt.Notify_Guilty(0); // the six days without a bed: the guilt from filing has run out
T.Check(!o.guilt.IsGuilty, "fixture: the guilt didn't run out");
EnforceFixtures.PrisonCell();
int guiltAtArrest = -1;
bool jailed = EnforceFixtures.RunUntil(() =>
{
if (guiltAtArrest < 0 && JailFlow.ArrestRuns(c))
guiltAtArrest = o.guilt.TicksUntilInnocent;
return o.IsPrisonerOfColony || o.InMentalState;
}, Enforcement.SentenceInterval + EnforceFixtures.SubdueTicks);
T.Check(guiltAtArrest >= 6 * GenDate.TicksPerDay - 30, "guilt when the arrest started: " + guiltAtArrest);
T.Check(!o.InMentalState, "the arrest was refused: " + o.MentalStateDef?.defName);
T.Check(jailed, "no arrest after the bed was built; case " + c + ", wait " + c.waitReason);
T.Equal(c.captureTick + 5 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
}
/// <summary>Every free colonist's Social at 0 for the test, restored after.</summary>
private static void SocialZeroForAll()
{
var old = new List<(SkillRecord skill, int level)>();
foreach (Pawn p in EnforceFixtures.Map.mapPawns.FreeColonistsSpawned)
{
SkillRecord s = p.skills?.GetSkill(SkillDefOf.Social);
if (s == null)
continue;
old.Add((s, s.Level));
s.Level = 0;
}
Fixtures.OnCleanup(() =>
{
foreach (var (skill, level) in old)
skill.Level = level;
});
}
[BlaxTest("jail: no prisoner bed gives one letter and no arrest; building one leads to the arrest at the next sweep")]
public static void NoPrisonerBed()
{
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
string label = "BlaxLaws_LetterNoBedLabel".Translate(c.OffenderLabel);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed");
EnforceFixtures.TickPastSentenceSweep();
EnforceFixtures.TickPastSentenceSweep();
T.Equal(1, EnforceFixtures.LettersLabeled(label), "no-bed letters");
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an arrest started without a bed");
EnforceFixtures.PrisonCell();
bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SentenceInterval + 5);
T.Check(arrest, "no arrest after the bed was built; wait " + c.waitReason);
}
// ---- holds and fallbacks ----------------------------------------------------------
[BlaxTest("jail: a role holder gets no arrest and one letter; Arrest now arrests (needs Ideology)")]
public static void HoldRoleHolder()
{
T.NeedsDlc("Ideology", ModsConfig.IdeologyActive);
Pawn o = null;
for (int i = 0; i < 10 && o == null; i++)
{
Pawn candidate = EnforceFixtures.Offender();
if (GiveRole(candidate))
o = candidate;
}
if (o == null)
T.Skip("ten generated colonists met the requirements of no role of their ideoligion");
Fixtures.Tick(1);
T.Check(DlcSupport.HoldsRole(o), "fixture: the colonist holds no role after a tick");
CheckHoldAndArrestNow(o);
}
[BlaxTest("jail: a mechanitor with a mech gets no arrest and one letter; Arrest now arrests (needs Biotech)")]
public static void HoldMechanitor()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
Pawn o = EnforceFixtures.Offender();
MakeMechanitor(o, keep: false);
CheckHoldAndArrestNow(o);
}
[BlaxTest("jail: a pawn that becomes a mechanitor with a mech while its case waits for a bed is held, not arrested (needs Biotech)")]
public static void HoldAfterOtherWait()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
Pawn o = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Equal(WaitReasons.NoBed, c.waitReason, "fixture: the wait without a prisoner bed");
MakeMechanitor(o, keep: false);
EnforceFixtures.PrisonCell();
JailFlow.TryArrest(c, ignoreHold: false);
T.Equal(WaitReasons.Hold, c.waitReason, "the wait after the pawn got a mech");
T.Check(!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony, "Laws arrested a mechanitor on its own after a bed wait");
T.Check(!c.holdLifted, "the hold counts as lifted without Arrest now");
}
/// <summary>
/// Gives the colonist a mechlink and a lifter it oversees (needs Biotech). With keep the mech stays for
/// phase 2 and the relation is left in place; otherwise the cleanup removes the relation.
/// </summary>
private static void MakeMechanitor(Pawn o, bool keep)
{
o.health.AddHediff(HediffDefOf.MechlinkImplant, o.health.hediffSet.GetBrain());
T.Check(MechanitorUtility.IsMechanitor(o), "fixture: the mechlink made no mechanitor");
PawnKindDef kind = DefDatabase<PawnKindDef>.GetNamedSilentFail("Mech_Lifter");
T.NotNull(kind, "PawnKindDef Mech_Lifter");
Pawn mech = Fixtures.Spawn(Fixtures.Generate(kind, Faction.OfPlayer), EnforceFixtures.CellNear(o.Position, 2f, 5f));
o.relations.AddDirectRelation(PawnRelationDefOf.Overseer, mech);
o.mechanitor.Notify_BandwidthChanged(); // rebuilds ControlledPawns from the control groups (Pawn_MechanitorTracker.cs:268-290)
if (keep)
Fixtures.Keep(mech);
else
Fixtures.OnCleanup(() =>
{
if (o.relations.DirectRelationExists(PawnRelationDefOf.Overseer, mech))
o.relations.RemoveDirectRelation(PawnRelationDefOf.Overseer, mech);
});
T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor controls no mech");
}
private static void CheckHoldAndArrestNow(Pawn o)
{
EnforceFixtures.PrisonCell();
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
string label = "BlaxLaws_LetterHoldLabel".Translate(c.OffenderLabel);
EnforceFixtures.Dispatch(c, LawStage.DidIt);
T.Equal(WaitReasons.Hold, c.waitReason, "the wait of a held pawn");
Fixtures.Tick(Enforcement.SweepInterval + 1);
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "a held pawn was arrested");
T.Equal(1, EnforceFixtures.LettersLabeled(label), "hold letters");
T.Check(Sentences.CanArrestNow(c), "Arrest now isn't offered");
o.guilt.Notify_Guilty(0);
Sentences.ArrestNow(c);
T.Check(JailFlow.ArrestRuns(c), "Arrest now started no arrest; wait " + c.waitReason);
T.Check(o.guilt.TicksUntilInnocent >= 4 * GenDate.TicksPerDay - 30, "Arrest now didn't renew the guilt: " + o.guilt.TicksUntilInnocent);
Fixtures.Tick(Enforcement.SweepInterval + 1);
T.Check(JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, "the sweep put the hold back; wait " + c.waitReason);
}
/// <summary>
/// Gives the colonist a role of its ideoligion whose requirements it meets, a multi role when there is
/// one, among the active roles; undone before the cleanup. Returns false when no role fits. A role whose requirements the pawn
/// misses (a skill, not a child) is taken away again on the next role tick (Precept_RoleSingle.cs:66-70;
/// Precept_Role.cs:508-520, 582-597).
/// </summary>
private static bool GiveRole(Pawn o)
{
Ideo ideo = o.Ideo;
if (ideo == null)
return false;
Precept_Role role = ideo.PreceptsListForReading.OfType<Precept_RoleMulti>().FirstOrDefault(r => r.Active && r.RequirementsMet(o))
?? (Precept_Role)ideo.PreceptsListForReading.OfType<Precept_RoleSingle>().FirstOrDefault(r => r.Active && r.RequirementsMet(o));
if (role == null)
return false;
Pawn previous = (role as Precept_RoleSingle)?.ChosenPawnValue;
role.Assign(o, addThoughts: false);
Fixtures.OnCleanup(() =>
{
if (role.IsAssigned(o))
role.Unassign(o, generateThoughts: false);
if (previous != null && !previous.Destroyed && role is Precept_RoleSingle single && single.ChosenPawnValue == null)
single.Assign(previous, addThoughts: false);
});
return true;
}
[BlaxTest("jail: a slave in a binge with a jail row is subdued; the same row outside a break warns (needs Ideology)")]
public static void SlaveFallsBack()
{
Pawn slave = EnforceFixtures.Ready(Fixtures.ColonySlave());
EnforceFixtures.Warden(EnforceFixtures.CellNear(slave.Position, 2f, 5f));
LawCase quiet = EnforceFixtures.ActCase(slave, "Jail", 3);
EnforceFixtures.Dispatch(quiet, LawStage.DidIt);
T.Check(quiet.IsClosed && quiet.outcome == CaseOutcomes.Warned, "the slave's case outside a break: " + quiet);
T.Check(!slave.IsPrisoner && !EnforceFixtures.AnyEnforcementJobOn(slave), "the slave was arrested outside a break");
EnforceFixtures.ForceBreak(slave, EnforceFixtures.DrugBinge);
LawCase binge = EnforceFixtures.BreakCase(slave, "Jail", LawStage.DidIt, 3);
EnforceFixtures.Dispatch(binge, LawStage.DidIt);
T.Equal("Subdue", binge.activePunishment, "the binging slave's punishment");
T.Check(SubdueFlow.Runs(binge), "no subdue for the binging slave; wait " + binge.waitReason);
T.Check(!slave.IsPrisoner, "the slave was jailed");
}
// ---- the early end and the fallback -----------------------------------------------
[BlaxTest("jail: recruiting the jailed pawn closes the sentence as released early")]
public static void RecruitEndsEarly()
{
Pawn o = EnforceFixtures.Offender();
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
RecruitUtility.Recruit(o, Faction.OfPlayer, warden);
T.Check(!o.IsPrisonerOfColony, "fixture: the recruited pawn is still a prisoner");
Sentences.Check(c);
T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the case after the recruitment: " + c);
}
[BlaxTest("jail: a day after the sentence without a release, Laws releases the pawn in place")]
public static void FallbackRelease()
{
// A release tick a day and a tick in the past must be a real tick (-1 means "not set yet").
if (Now < Sentences.FallbackTicks + 1)
Fixtures.Tick(Sentences.FallbackTicks + 1 - Now);
Pawn o = EnforceFixtures.Offender();
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
c.releaseTick = Now - Sentences.FallbackTicks - 1;
Sentences.Check(c);
T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist, o.LabelShort + " isn't free after the fallback");
T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the fallback");
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the fallback: " + c);
}
[BlaxTest("jail: repealing the law of a jailed pawn sets Release on it")]
public static void RepealReleases()
{
Pawn o = EnforceFixtures.Offender();
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
Sentences.WriteMaintainOnly(c);
string confirm = LawbookUi.DeleteConfirmText(c.LawFor(LawStage.DidIt)) ?? "";
T.Check(confirm.Contains("Release"), "the delete confirmation doesn't say the jailed pawn is set to Release: " + confirm);
T.Equal(1, Lawbook.Delete(c.LawFor(LawStage.DidIt)), "cases the repeal closed");
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the repeal: " + c);
T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the jailed pawn's mode after the repeal");
}
// ---- save and removal ---------------------------------------------------------------
private const string JailSaveKey = "jail.savedPrisoner";
[BlaxTest("jail save: a colonist jailed for 50 days at the first save (setup)")]
public static void JailSaveSetup()
{
T.CarryAtSave(JailSaveKey, JailForSave);
}
private static string JailForSave()
{
PrisonRoom room = EnforceFixtures.PrisonCell(keep: true);
Pawn o = Fixtures.Keep(EnforceFixtures.Offender(room.inside));
Pawn warden = Fixtures.Keep(EnforceFixtures.Warden());
LawCase c = EnforceFixtures.JailDirect(o, warden, 50);
Fixtures.KeepLaw(c.LawFor(LawStage.DidIt));
Sentences.WriteMaintainOnly(c);
return c.id + "|" + o.ThingID + "|" + c.captureTick;
}
[BlaxTest("jail save: the jailed colonist is still Laws' prisoner on Maintain only after the reload", phase: 2)]
public static void JailSaveRoundTrip()
{
T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run");
string[] parts = carry.Split('|');
LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0]));
Pawn o = Fixtures.FindPawnById(parts[1]);
T.NotNull(c, "the jail case after the reload");
T.NotNull(o, "the jailed colonist after the reload");
T.Check(c.offender == o, "the case's offender didn't resolve");
T.Equal(CaseStatus.Jailed, c.status, "the case's status");
T.Equal(int.Parse(parts[2]), c.captureTick, "the capture tick");
T.Equal(c.captureTick + 50 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
T.Check(c.maintainOnlyDone, "maintainOnlyDone after the reload");
T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner after the reload");
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode after the reload");
}
private const string HoldSaveKey = "jail.holdLifted";
[BlaxTest("jail save: a mechanitor's case with Arrest now pressed at the first save (setup, needs Biotech)")]
public static void HoldLiftSaveSetup()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
T.CarryAtSave(HoldSaveKey, HoldLiftForSave);
}
private static string HoldLiftForSave()
{
Pawn o = Fixtures.Keep(EnforceFixtures.Offender());
Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)));
MakeMechanitor(o, keep: true);
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
Fixtures.KeepLaw(c.LawFor(LawStage.DidIt));
EnforceFixtures.Dispatch(c, LawStage.DidIt);
if (c.waitReason != WaitReasons.Hold)
throw new InvalidOperationException("the mechanitor's case waits for " + (c.waitReason ?? "nothing") + ", not the hold");
Sentences.ArrestNow(c);
// The state a failed arrest leaves (PunishmentWorker_Jail.Sweep): no job, Open, no wait.
JailFlow.EndArrest(c);
c.status = CaseStatus.Open;
c.waitReason = null;
return c.id + "|" + o.ThingID;
}
[BlaxTest("jail save: Arrest now still holds after the reload; a failed arrest retries without a second hold", phase: 2)]
public static void HoldLiftRoundTrip()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
T.Check(T.Carry.TryGetValue(HoldSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 hold setup did not run");
string[] parts = carry.Split('|');
T.Check(parts.Length == 2, "carry: " + carry);
LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0]));
Pawn o = Fixtures.FindPawnById(parts[1]);
T.NotNull(c, "the held case after the reload");
T.NotNull(o, "the mechanitor after the reload");
T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor lost its mech in the reload");
T.Check(c.holdLifted, "holdLifted after the reload");
T.Check(c.waitReason != WaitReasons.Hold, "a sweep after the reload put the hold back");
if (!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony)
{
c.status = CaseStatus.Open;
c.waitReason = null;
JailFlow.TryArrest(c, ignoreHold: false);
T.Check(c.waitReason != WaitReasons.Hold && !Sentences.CanArrestNow(c), "the retry after the reload went back to the hold; wait " + c.waitReason);
}
}
[BlaxTest("removal: the colonist Laws jailed is still a prisoner of the colony", phase: 3)]
public static void JailedAfterRemoval()
{
T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run");
Pawn o = Fixtures.FindPawnById(carry.Split('|')[1]);
T.NotNull(o, "the jailed colonist after the removal");
T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner of the colony after the removal");
T.Equal(0, Fixtures.Comp.Cases.Count, "cases in the fresh component");
}
}
}

View File

@ -0,0 +1,53 @@
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxLawsTests
{
/// <summary>
/// The vanilla quick test picks a random tile at 250x250 (Root_Play.cs:94-96), and a hilly or mountainous
/// tile can leave too little open ground for the fixtures. While -blaxlawstests is on, the quick-test map
/// is 325x325 on a flat or small-hills tile, as in Blax Zones' suite. The tile and every position on it
/// still vary per run.
/// </summary>
[StaticConstructorOnStartup]
public static class QuickTestMap
{
public const int MapSize = 325;
private const int TileAttempts = 200;
static QuickTestMap()
{
if (!TestRunner.Enabled)
return;
new Harmony("blax.laws.tests.quicktestmap").Patch(
AccessTools.Method(typeof(Root_Play), nameof(Root_Play.SetupForQuickTestPlay)),
postfix: new HarmonyMethod(typeof(QuickTestMap), nameof(Postfix)));
// Jail tests tick whole days, so the autosaver fires. Its "Autosaving" long event is synchronous with
// text, so it waits to be drawn (LongEventHandler.cs:52-58, 410-413), which never happens headless, and
// every later long event, the suite's own save+reload included, queues behind it forever.
new Harmony("blax.laws.tests.noautosave").Patch(
AccessTools.Method(typeof(Autosaver), nameof(Autosaver.AutosaverTick)),
prefix: new HarmonyMethod(typeof(QuickTestMap), nameof(SkipAutosave)));
// Before the world and map are made, so every pawn vanilla makes for a book or tale is known.
TestRunner.HookPawnWatchers();
}
public static bool SkipAutosave() => false;
public static void Postfix()
{
GameInitData init = Find.GameInitData;
init.mapSize = MapSize;
for (int i = 0; i < TileAttempts && !Open(init.startingTile); i++)
init.startingTile = TileFinder.RandomStartingTile();
}
private static bool Open(PlanetTile tile)
{
Hilliness h = Find.WorldGrid[tile].hilliness;
return h == Hilliness.Flat || h == Hilliness.SmallHills;
}
}
}

View File

@ -0,0 +1,220 @@
using System.Collections.Generic;
using System.Linq;
using BlaxLaws;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLawsTests
{
/// <summary>The skeleton and the harness work: patches, settings, defs, the component, the empty book, all three phases.</summary>
public static class SmokeTests
{
private static readonly string[] SharedKeys =
{
"BlaxLaws_NeedsDlc", "BlaxLaws_MissingMod", "BlaxLaws_Stage_Planning", "BlaxLaws_Stage_DidIt",
"BlaxLaws_Severity_Minor", "BlaxLaws_Severity_Moderate", "BlaxLaws_Severity_Serious", "BlaxLaws_Severity_Grave",
"BlaxLaws_Status_Open", "BlaxLaws_Status_Enforcing", "BlaxLaws_Status_Jailed", "BlaxLaws_Status_Closed",
"BlaxLaws_Outcome_Repealed", "BlaxLaws_Outcome_BreakEnded", "BlaxLaws_Outcome_NotEnforced",
"BlaxLaws_DrugOption_Any", "BlaxLaws_DrugOption_Hard", "BlaxLaws_DrugOption_Social",
"BlaxLaws_EmptyBook", "BlaxLaws_CaseFiled",
"BlaxLaws_SettingEnforceLaws", "BlaxLaws_SettingShowTab", "BlaxLaws_SettingCaseMessages", "BlaxLaws_SettingJailLetters",
"BlaxLaws_SettingEnforcers", "BlaxLaws_EnforcersWardensFirst", "BlaxLaws_EnforcersWardensOnly",
"BlaxLaws_SettingSubdueCatharsis", "BlaxLaws_SettingPlayerOrdersExempt", "BlaxLaws_SettingCooldownDays",
"BlaxLaws_SettingKeepClosedDays", "BlaxLaws_SettingsReset",
};
[BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Laws")]
public static void StartupLogged()
{
int ours = Harmony.GetAllPatchedMethods()
.Select(Harmony.GetPatchInfo)
.Where(info => info != null)
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
.Count(p => p.owner == BlaxLawsStartup.HarmonyId);
T.Info("patch classes applied: " + BlaxLawsStartup.Applied + ", Harmony patches owned by " + BlaxLawsStartup.HarmonyId + ": " + ours);
T.Check(BlaxLawsStartup.FailedPatches.Count == 0, "patch classes failed: " + string.Join(", ", BlaxLawsStartup.FailedPatches));
// Only what was logged before the first test: later tests log expected errors on purpose.
var startup = TestRunner.StartupLog;
string line = startup.FirstOrDefault(m => m.text != null && m.text.Contains("[Blax Laws]") && m.text.Contains("patches applied"))?.text;
T.Check(line != null, "startup line '[Blax Laws] N patches applied' not in the log");
T.Check(line.Contains("[Blax Laws] " + BlaxLawsStartup.Applied + " patches applied"), "startup line names another count: " + line);
var errors = startup.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList();
T.Check(errors.Count == 0, "errors mentioning Blax Laws at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
var warnings = startup.Where(m => m.type == LogMessageType.Warning && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList();
T.Check(warnings.Count == 0, "warnings mentioning Blax Laws at startup: " + string.Join(" | ", warnings.Take(3).Select(e => e.text)));
}
[BlaxTest("startup: every Blax Laws finalizer returns void, so Harmony rethrows exceptions with their stack trace")]
public static void FinalizersReturnVoid()
{
// One finalizer returning Exception on a method makes Harmony "throw ex" instead of "rethrow"
// (0Harmony EmitFinalizers), which cuts the inner frames off every exception passing through it.
var finalizers = Harmony.GetAllPatchedMethods()
.Select(Harmony.GetPatchInfo)
.Where(info => info != null)
.SelectMany(info => info.Finalizers)
.Where(p => p.owner == BlaxLawsStartup.HarmonyId)
.ToList();
T.Info("Blax Laws finalizers: " + finalizers.Count);
var bad = finalizers.Where(p => p.PatchMethod.ReturnType != typeof(void)).Select(p => p.PatchMethod.DeclaringType?.Name).ToList();
T.Check(bad.Count == 0, "finalizers that return a value: " + string.Join(", ", bad));
}
[BlaxTest("startup: settings, shared strings, defs and exactly one game component")]
public static void Loaded()
{
T.NotNull(BlaxLawsMod.Settings, "BlaxLawsMod.Settings");
var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
T.NotNull(BlaxLawsDefOf.Warn, "PunishmentDef Warn");
T.NotNull(BlaxLawsDefOf.Guilty, "PunishmentDef Guilty");
T.NotNull(BlaxLawsDefOf.Subdue, "PunishmentDef Subdue");
T.NotNull(BlaxLawsDefOf.Jail, "PunishmentDef Jail");
T.NotNull(BlaxLawsDefOf.SubdueThenJail, "PunishmentDef SubdueThenJail");
T.NotNull(BlaxLawsDefOf.BlaxLaws_Subdue, "JobDef BlaxLaws_Subdue");
T.Check(!BlaxLawsDefOf.BlaxLaws_Subdue.suspendable, "BlaxLaws_Subdue is suspendable, so an interrupt would queue it into the save");
T.NotNull(BlaxLawsDefOf.BlaxLaws_Laws, "MainButtonDef BlaxLaws_Laws");
foreach (string cat in ActCategories.All)
T.NotNull(DefDatabase<ActCategoryDef>.GetNamedSilentFail(cat), "ActCategoryDef " + cat);
foreach (string act in new[] { SpecialActs.SetFire, SpecialActs.DisplayedCorpse, SpecialActs.StartedSocialFight })
T.NotNull(DefDatabase<ActDef>.GetNamedSilentFail(act), "ActDef " + act);
T.Equal(6, DefDatabase<BreakLinkDef>.DefCount, "BreakLinkDefs");
int comps = Current.Game.components.Count(c => c is GameComponent_BlaxLaws);
T.Equal(1, comps, "GameComponent_BlaxLaws in the game");
T.NotNull(GameComponent_BlaxLaws.Instance, "GameComponent_BlaxLaws.Instance");
T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent<GameComponent_BlaxLaws>(), "Instance is not the game's component");
T.Check(GameComponent_BlaxLaws.Instance.SaveToken != 0, "the save token is 0");
}
[BlaxTest("new game: an empty book, no cases, every watch flag off, nothing queued")]
public static void EmptyBook()
{
// The new game as the suite found it, before any test ran (tests of other classes run first).
TestRunner.NewGameState start = TestRunner.AtStart;
T.NotNull(start, "the state at the start of the suite");
T.Equal(0, start.laws, "rows in a new game");
T.Equal(0, start.cases, "cases in a new game");
T.Check(!start.watchAny, "Watch.Any is on for an empty book");
T.Check(!start.categoryFlag, "a category flag is on for an empty book");
T.Check(!start.specialFlag, "a special act flag is on for an empty book");
T.Equal(0, start.pending, "queued enforcement entries");
// The book is empty again between tests: the flags are off and an act files nothing.
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
T.Equal(0, comp.Laws.Count, "rows left by earlier tests");
T.Check(!Watch.Any, "Watch.Any is on for an empty book");
int cases = comp.Cases.Count;
Pawn p = Fixtures.Colonist();
T.Check(CaseFiler.Report(new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p)) == null, "an act against an empty book filed a case");
Fixtures.Tick(Enforcement.SweepInterval + 1);
T.Equal(cases, comp.Cases.Count, "cases after ticking an empty book");
}
[BlaxTest("settings: cooldown clamps to 0..7 days, kept cases to 7..360, defaults")]
public static void SettingClamps()
{
BlaxLawsSettings s = Fixtures.Settings;
var d = new BlaxLawsSettings();
T.Equal(1, d.cooldownDays, "default cooldown days");
T.Equal(60, d.keepClosedDays, "default kept days");
T.Check(d.enforceLaws && d.showLawsTab && d.caseMessages && d.jailLetters && d.subdueRemovesCatharsis && d.playerOrdersExempt,
"a default toggle is off");
T.Equal(EnforcerMode.WardensFirst, d.enforcers, "default enforcers");
s.cooldownDays = -3;
T.Equal(0, s.CooldownDaysClamped, "cooldown -3 clamped");
s.cooldownDays = 99;
T.Equal(7, s.CooldownDaysClamped, "cooldown 99 clamped");
T.Equal(7 * GenDate.TicksPerDay, s.CooldownTicks, "cooldown ticks at 7 days");
s.keepClosedDays = 1;
T.Equal(7, s.KeepClosedDaysClamped, "kept days 1 clamped");
s.keepClosedDays = 999;
T.Equal(360, s.KeepClosedDaysClamped, "kept days 999 clamped");
}
[BlaxTest("settings: Show Laws tab off hides the button at once, on shows it")]
public static void ShowTabLive()
{
MainButtonDef button = BlaxLawsDefOf.BlaxLaws_Laws;
Fixtures.Settings.showLawsTab = false;
BlaxLawsMod.ApplyTabVisibility();
T.Check(!button.buttonVisible, "buttonVisible stays true with the setting off");
Fixtures.Settings.showLawsTab = true;
BlaxLawsMod.ApplyTabVisibility();
T.Check(button.buttonVisible, "buttonVisible stays false with the setting on");
}
[BlaxTest("harness: colonist, prisoner, colony slave and child fixtures stand in a district")]
public static void PawnFixtures()
{
Pawn c = Fixtures.Colonist();
T.Check(c.Spawned && c.IsFreeColonist, "colonist fixture is not a spawned free colonist");
T.Check(c.GetDistrict() != null, "colonist fixture stands in no district");
T.Check(Offenders.IsCovered(c), "a free colonist isn't covered by the laws");
Pawn pr = Fixtures.Prisoner();
T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
T.Check(!Offenders.IsCovered(pr), "a prisoner is covered by the laws");
if (ModsConfig.IdeologyActive)
{
Pawn s = Fixtures.ColonySlave();
T.Check(Offenders.IsCovered(s), "a colony slave isn't covered by the laws");
}
if (ModsConfig.BiotechActive)
{
Pawn ch = Fixtures.Child();
T.Check(Offenders.IsCovered(ch), "a colony child isn't covered by the laws");
T.Check(DlcSupport.IsChild(ch), "DlcSupport.IsChild is false for the child fixture");
}
if (!ModsConfig.IdeologyActive || !ModsConfig.BiotechActive)
T.Info("slave fixture needs Ideology, child fixture needs Biotech; skipped what is off");
}
[BlaxTest("harness: exactly one component after the reload", phase: 2)]
public static void ComponentAfterReload()
{
T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "GameComponent_BlaxLaws after the reload");
T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent<GameComponent_BlaxLaws>(), "Instance is not the reloaded game's component");
}
[BlaxTest("harness: the reload logs no 'Could not resolve reference' warning except for vanilla's unsaved tale pawns, pawns the new world left unsaved and Hospitality's stale lords", phase: 2)]
public static void ReloadResolvesEveryReference()
{
// A reference Blax Laws saves but can't load would show here. Three leaks of other code are excused
// by name:
// - vanilla: a pawn TaleData_Pawn.GenerateRandom made for a book or tale and never saved;
// - vanilla: a pawn a relation already named, with no save holding it, when the suite began (world
// generation, before any test and with an empty lawbook);
// - Hospitality (-Compat): CompGuest.PostSpawnSetup stores Pawn.GetLord() on every humanlike pawn and
// saves it with Scribe_References, and nothing clears it when the pawn leaves the map
// (Hospitality Source/CompGuest.cs, lord). Blax Laws saves no Lord reference.
List<string> all = T.Phase2ResolveWarnings;
List<string> vanilla = all.Where(T.NamesVanillaTalePawn).ToList();
List<string> atStart = all.Where(w => !vanilla.Contains(w) && T.NamesPawnUnsavedAtStart(w)).ToList();
bool hospitality = Compat.IsActive("Orion.Hospitality");
List<string> staleLords = hospitality ? all.Where(w => w.Contains("of type Verse.AI.Group.Lord.")).ToList() : new List<string>();
List<string> rest = all.Where(w => !vanilla.Contains(w) && !atStart.Contains(w) && !staleLords.Contains(w)).ToList();
T.Info(all.Count + " warning(s) on the reload: " + vanilla.Count + " for pawns vanilla made for books or tales and never saved, " +
atStart.Count + " for pawns the new world left unsaved, " +
staleLords.Count + " for lords Hospitality's CompGuest still names");
T.Equal(0, rest.Count, "other 'Could not resolve reference' warnings while the phase-1 save loaded (first: " +
string.Join(" | ", rest.Take(3)) + ")");
}
[BlaxTest("harness: phase 3 loads with exactly the two removal errors and a fresh, empty component", phase: 3)]
public static void Phase3Removal()
{
T.Equal(1, TestRunner.Phase3ReplacedCount, "component nodes replaced in the phase-3 save");
T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, 1);
T.ExpectErrors("Can't load abstract class Verse.GameComponent", 1);
T.Info("load errors: " + T.Phase3LoadErrors.Count + ", resolve warnings: " + T.Phase3ResolveWarnings);
T.Equal(2, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save");
T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "fresh GameComponent_BlaxLaws");
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
T.Equal(0, comp.Laws.Count, "rows in the fresh component");
T.Equal(0, comp.Cases.Count, "cases in the fresh component");
T.Check(!Watch.Any, "Watch.Any is on after the removal load");
}
}
}

View File

@ -0,0 +1,161 @@
using System.Linq;
using BlaxLaws;
using RimWorld;
using Verse;
namespace BlaxLawsTests
{
/// <summary>
/// The lawbook and case store: rows keyed on Action, Option and Stage, rows whose entry is missing, the
/// starter lawbook, and rows and cases through the save as names and numbers.
/// </summary>
public static class StoreTests
{
private const string MissingCoreKey = "Ate/BlaxLawsTest_NoSuchFood";
private const string MissingIdeologyKey = "RecordedAct/BlaxLawsTest_NoSuchEvent";
[BlaxTest("lawbook: a row whose entry is missing stays, reads Missing: Core or Needs Ideology, watches nothing and files nothing")]
public static void MissingEntryRows()
{
Law core = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3, "Core", "ludeon.rimworld");
Law ideo = Fixtures.LawRow(MissingIdeologyKey, null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3, "Ideology", "ludeon.rimworld.ideology");
T.Check(Lawbook.Laws.Contains(core) && Lawbook.Laws.Contains(ideo), "a row with a missing entry left the book");
T.Check(!core.Resolves && !ideo.Resolves, "a made-up act key resolves");
T.Equal("Missing: Core", core.MissingText, "missing text of a Core row");
T.Equal("Needs Ideology", ideo.MissingText, "missing text of an Ideology row");
T.Equal("Needs Ideology", DlcSupport.MissingText("Ideology", null), "missing text from the DLC name alone");
T.Equal("Missing: Some Mod", DlcSupport.MissingText("Some Mod", "someone.somemod"), "missing text of a mod row");
T.Check(!Watch.Any, "a row whose entry is missing turned a watch flag on");
Pawn p = Fixtures.Colonist();
T.Check(CaseFiler.Report(new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p)) == null, "a row whose entry is missing filed a case");
}
[BlaxTest("lawbook: a second row with the same action, option and stage is refused and names the first")]
public static void DuplicateRefused()
{
Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
var dup = new Law { actKey = MissingCoreKey, stage = LawStage.DidIt, punishment = "Jail", days = 5 };
T.Check(!Lawbook.TryAdd(dup, out Law existing), "the duplicate row was added");
T.Check(existing == a, "the refusal names " + existing + ", not the first row");
var otherStage = new Law { actKey = MissingCoreKey, stage = LawStage.Planning, punishment = "Warn", days = 1 };
T.Check(Lawbook.TryAdd(otherStage, out _), "a row with another stage was refused");
var binge = new Law { actKey = "Break/@anyDrugBinge", option = DrugOptions.Any, stage = LawStage.DidIt, punishment = "Warn", days = 3 };
T.Check(Lawbook.TryAdd(binge, out _), "a binge row was refused");
var bingeNull = new Law { actKey = "Break/@anyDrugBinge", option = null, stage = LawStage.DidIt, punishment = "Warn", days = 3 };
T.Check(!Lawbook.TryAdd(bingeNull, out Law e2) && e2 == binge, "a binge row with no option counts as Any and must be refused");
var bingeWake = new Law { actKey = "Break/@anyDrugBinge", option = "WakeUpChemical", stage = LawStage.DidIt, punishment = "Warn", days = 3 };
T.Check(Lawbook.TryAdd(bingeWake, out _), "a binge row with another option was refused");
T.Check(a.id > 0 && otherStage.id > a.id, "row ids are not handed out in order: " + a.id + ", " + otherStage.id);
}
[BlaxTest("lawbook: Moderate to Serious moves untouched days from 3 to 5 and leaves typed days alone; days clamp to 1..50")]
public static void SeverityMovesDefaultDays()
{
Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Moderate, "Jail", 3);
Lawbook.SetSeverity(a, LawSeverity.Serious);
T.Equal(5, a.days, "untouched days after Moderate to Serious");
Lawbook.SetDays(a, 7);
Lawbook.SetSeverity(a, LawSeverity.Grave);
T.Equal(7, a.days, "typed days after Serious to Grave");
Lawbook.SetDays(a, 0);
T.Equal(1, a.days, "days 0 clamped");
Lawbook.SetDays(a, 80);
T.Equal(50, a.days, "days 80 clamped");
T.Equal(1, Lawbook.DefaultDays(LawSeverity.Minor), "Minor days");
T.Equal(10, Lawbook.DefaultDays(LawSeverity.Grave), "Grave days");
}
[BlaxTest("lawbook: Starter lawbook adds 7 rows, pressing it again adds none")]
public static void StarterLawbook()
{
int before = Lawbook.Laws.Count;
T.Equal(7, Lawbook.AddStarter(), "rows the starter lawbook added");
T.Equal(before + 7, Lawbook.Laws.Count, "rows in the book after the starter lawbook");
T.Equal(0, Lawbook.AddStarter(), "rows a second press added");
Law jail = Lawbook.Find("Break/@anyDrugBinge", DrugOptions.Any, LawStage.DidIt);
T.NotNull(jail, "starter row 'any drug binge, did it'");
T.Equal("Jail", jail.punishment, "punishment of 'any drug binge, did it'");
T.Equal(5, jail.days, "days of 'any drug binge, did it'");
T.Equal(LawSeverity.Serious, jail.severity, "severity of 'any drug binge, did it'");
Law fire = Lawbook.Find("Break/FireStartingSpree", null, LawStage.DidIt);
T.Check(fire != null && fire.punishment == "Jail" && fire.days == 10 && fire.severity == LawSeverity.Grave, "starter fire-starting spree did-it row: " + fire);
T.NotNull(Lawbook.Find("Interaction/Insult", null, LawStage.DidIt), "starter row 'Insult, did it'");
T.NotNull(Lawbook.Find("Special/StartedSocialFight", null, LawStage.DidIt), "starter row 'started a social fight'");
T.Check(Lawbook.Laws.All(l => l.savedMod == "Core" || l.Resolves), "a starter row saved another mod than Core");
}
[BlaxTest("cases: a filed case closes with its outcome, and deleting its row closes the open ones as repealed")]
public static void CaseLifecycle()
{
GameComponent_BlaxLaws comp = Fixtures.Comp;
Pawn p = Fixtures.Colonist();
Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Serious, "Warn", 5);
LawCase c = CaseFiler.Open(a, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p), LawStage.DidIt);
T.NotNull(c, "CaseFiler.Open");
T.Check(comp.Cases.Contains(c) && comp.CasesOf(p).Contains(c), "the case is not in the store or its offender index");
T.Equal(a.id, c.didItLawId, "the case's did-it row");
T.Equal(LawSeverity.Serious, c.severity, "the case's severity");
T.Equal(1, c.count, "the count of a new did-it case");
T.Equal(p.LabelShort, c.offenderName, "the offender's saved name");
T.Equal(1, Lawbook.OpenCaseCount(a), "open cases of the row");
T.Equal(1, Lawbook.Delete(a), "cases the delete closed");
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the delete: " + c);
T.Equal("Law repealed", CaseOutcomes.Label(c.outcome), "the repealed label");
}
[BlaxTest("save: a row and a case go into the save as names and numbers (setup)")]
public static void SaveSetup()
{
Pawn p = Fixtures.Keep(Fixtures.Colonist());
Law a = Fixtures.KeepLaw(Fixtures.LawRow(MissingIdeologyKey, null, LawStage.DidIt, LawSeverity.Grave, "Jail", 12, "Ideology", "ludeon.rimworld.ideology"));
Lawbook.SetEnabled(a, false);
LawCase c = CaseFiler.Open(a, new ActEvent(ActCategories.RecordedAct, null, p) { notes = CaseNotes.OnTable | CaseNotes.DugUp }, LawStage.DidIt);
c.count = 4;
c.breakState = "Binging_DrugExtreme";
c.breakStartTick = 1234;
c.MarkPunished(LawStage.DidIt);
c.status = CaseStatus.Jailed;
c.captureTick = 2000;
c.releaseTick = 2000 + 12 * GenDate.TicksPerDay;
T.Carry["save.law"] = a.id.ToString();
T.Carry["save.case"] = c.id.ToString();
T.Carry["save.pawn"] = p.ThingID;
}
[BlaxTest("save: the row and the case keep every field through the reload", phase: 2)]
public static void SaveRoundTrip()
{
T.Check(T.Carry.ContainsKey("save.law"), "phase-1 setup did not run");
GameComponent_BlaxLaws comp = Fixtures.Comp;
Law a = comp.LawById(int.Parse(T.Carry["save.law"]));
T.NotNull(a, "the kept row after the reload");
T.Equal(MissingIdeologyKey, a.actKey, "act key");
T.Equal(LawStage.DidIt, a.stage, "stage");
T.Equal(LawSeverity.Grave, a.severity, "severity");
T.Equal("Jail", a.punishment, "punishment");
T.Equal(12, a.days, "days");
T.Check(!a.enabled, "the row's On flag came back on");
T.Equal("Ideology", a.savedMod, "saved mod");
T.Equal("Needs Ideology", a.MissingText, "missing text after the reload");
T.Check(comp.NextLawId > a.id, "next row id " + comp.NextLawId + " would repeat " + a.id);
LawCase c = comp.CaseById(int.Parse(T.Carry["save.case"]));
T.NotNull(c, "the kept case after the reload");
Pawn p = Fixtures.FindPawnById(T.Carry["save.pawn"]);
T.NotNull(p, "the kept colonist after the reload");
T.Check(c.offender == p, "the case's offender reference didn't resolve to the colonist");
T.Check(comp.CasesOf(p).Contains(c), "the offender index lacks the case after the reload");
T.Equal(a.id, c.didItLawId, "did-it row");
T.Equal(4, c.count, "count");
T.Equal(CaseNotes.OnTable | CaseNotes.DugUp, c.notes, "notes");
T.Equal("Binging_DrugExtreme", c.breakState, "break state");
T.Equal(1234, c.breakStartTick, "break start tick");
T.Check(c.HasPunished(LawStage.DidIt) && !c.HasPunished(LawStage.Planning), "punished stages: " + c.punishedStages);
T.Equal(CaseStatus.Jailed, c.status, "status");
T.Equal(2000, c.captureTick, "capture tick");
T.Equal(2000 + 12 * GenDate.TicksPerDay, c.releaseTick, "release tick");
T.Equal(LawSeverity.Grave, c.severity, "severity");
T.Check(comp.NextCaseId > c.id, "next case id " + comp.NextCaseId + " would repeat " + c.id);
}
}
}

View File

@ -0,0 +1,558 @@
using System.Collections.Generic;
using System.Linq;
using BlaxLaws;
using RimWorld;
using Verse;
namespace BlaxLawsTests
{
/// <summary>
/// The Laws tab, the act picker, the case log and the letters (design: "Lawbook tab", Tests). Headless
/// runs have no GUI, so these drive the logic behind the widgets: what each column's dropdown offers and
/// what picking it writes, what a pick from the act picker adds, the picker's tree and search, the
/// overlap icon, the delete confirmation, the case log's lines and "Arrest now", and the letters.
/// Drawing is checked by hand.
/// </summary>
public static class UiTests
{
private const string Binge = "Break/@anyDrugBinge";
private const string Insult = "Interaction/Insult";
private const string MissingKey = "Ate/BlaxLawsTest_UiNoSuchFood";
// ---- helpers -----------------------------------------------------------------------------
private static ActEntry Entry(string key)
{
ActEntry e = ActCatalogue.Get(key);
T.NotNull(e, "catalogue entry " + key);
return e;
}
/// <summary>A fresh row through the picker's "Add law" path; fails when the book had one.</summary>
private static Law Add(string key)
{
Entry(key);
Law row = LawbookUi.AddFromPicker(key, out Law existing);
T.Check(row != null, "Add law for " + key + " added nothing, existing " + existing);
return row;
}
private static List<string> Names(List<RowChoice> choices) =>
choices.Select(c => c.payload is Def d ? d.defName : c.payload?.ToString()).ToList();
private static string Show(List<RowChoice> choices) => string.Join(" | ", choices.Select(c => c.ToString()));
private static RowChoice Choice(List<RowChoice> choices, string name)
{
RowChoice c = choices.FirstOrDefault(x => (x.payload is Def d ? d.defName : x.payload?.ToString()) == name);
T.NotNull(c, "menu entry " + name + " in " + Show(choices));
return c;
}
/// <summary>Turns the other rows of a category off for this test, so its watch flag reads only this test's rows.</summary>
private static void SilenceOtherRows(string categoryId)
{
foreach (Law l in Lawbook.Laws.Where(l => l.enabled && l.CategoryId == categoryId).ToList())
{
Lawbook.SetEnabled(l, false);
Law kept = l;
Fixtures.OnCleanup(() => Lawbook.SetEnabled(kept, true));
}
}
/// <summary>Removes the letters a test sent from the stack and the archive, so the save never holds their targets.</summary>
private static void RemoveNewLettersAfterTest()
{
var before = new HashSet<Letter>(Find.LetterStack.LettersListForReading);
Fixtures.OnCleanup(() =>
{
foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l)).ToList())
{
Find.LetterStack.RemoveLetter(l);
Find.Archive.Remove(l);
}
});
}
private static List<Letter> LettersSince(HashSet<Letter> before) =>
Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l)).ToList();
private static LawCase OpenCase(Law law, Pawn p) =>
CaseFiler.Open(law, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p), law.stage);
// ---- the tab -----------------------------------------------------------------------------
[BlaxTest("ui: the Laws button opens MainTabWindow_Laws after Ideoligions, also without a map; Show Laws tab writes buttonVisible")]
public static void MainButton()
{
MainButtonDef def = BlaxLawsDefOf.BlaxLaws_Laws;
T.NotNull(def, "MainButtonDef BlaxLaws_Laws");
T.Equal(typeof(MainTabWindow_Laws), def.tabWindowClass, "tab window class");
T.Equal(105, def.order, "button order");
T.Check(def.validWithoutMap, "the Laws tab is not valid without a map");
T.Check(def.TabWindow is MainTabWindow_Laws, "TabWindow is " + def.TabWindow?.GetType().Name);
Fixtures.Settings.showLawsTab = false;
BlaxLawsMod.ApplyTabVisibility();
T.Check(!def.buttonVisible, "Show Laws tab off left the button visible");
Fixtures.Settings.showLawsTab = true;
BlaxLawsMod.ApplyTabVisibility();
T.Check(def.buttonVisible, "Show Laws tab on left the button hidden");
}
[BlaxTest("ui: Add law gives a row at the entry's first stage, Moderate, Warn, 3 days and On; a binge row gets Any drug")]
public static void AddLawDefaults()
{
Law binge = Add(Binge);
T.Equal(LawStage.Planning, binge.stage, "stage of a new binge row");
T.Equal(LawSeverity.Moderate, binge.severity, "severity of a new row");
T.Equal("Warn", binge.punishment, "punishment of a new row");
T.Equal(3, binge.days, "days of a new row");
T.Check(binge.enabled, "a new row is off");
T.Equal(DrugOptions.Any, DrugOptions.Normalize(binge.option), "option of a new binge row");
T.Check(LawbookUi.HasOption(binge), "a binge row has no Drug column");
T.Equal(binge.id, LawbookUi.FocusLawId, "the tab doesn't show the new row");
Law insult = Add(Insult);
T.Equal(LawStage.DidIt, insult.stage, "stage of a new Insult row (no planning outside the breaks)");
T.Check(insult.option == null && !LawbookUi.HasOption(insult), "an Insult row has a drug option: " + insult.option);
T.Equal(0, LawbookUi.OptionChoices(insult).Count, "drug options of an Insult row");
T.Check(insult.savedLabel == Entry(Insult).label && insult.savedMod == "Core", "the row didn't save the entry's label and mod: " + insult.savedLabel + ", " + insult.savedMod);
}
[BlaxTest("ui: Add law on an entry whose stages all have rows adds nothing and shows the existing row")]
public static void AddLawDuplicateShowsRow()
{
Law planning = Add(Binge);
ActEntry e = Entry(Binge);
T.Check(e.HasStage(LawStage.DidIt), "the any drug binge entry has no Did it stage (break link missing)");
Law didIt = Add(Binge);
T.Equal(LawStage.DidIt, didIt.stage, "stage of the second binge row");
int count = Lawbook.Laws.Count;
LawbookUi.ClearFocus();
Law third = LawbookUi.AddFromPicker(Binge, out Law existing);
T.Check(third == null, "a third binge row was added: " + third);
T.Equal(count, Lawbook.Laws.Count, "rows after the refused pick");
T.Check(existing == planning, "the refusal names " + existing + ", not the planning row");
T.Equal(planning.id, LawbookUi.FocusLawId, "the tab doesn't jump to the existing row");
T.Check(LawbookUi.ScrollPending, "the tab isn't asked to scroll to the existing row");
Law insult = Add(Insult);
T.Check(!LawbookUi.ChangeAction(didIt, Insult), "changing an action to a key in the book was allowed");
T.Equal(Binge, didIt.actKey, "the refused action change still changed the row");
T.Equal(insult.id, LawbookUi.FocusLawId, "the refused action change doesn't show the existing row");
}
[BlaxTest("ui: an any drug binge row turns the Break flag on and watches both binge breaks; deleting it turns them off")]
public static void BingeRowWatches()
{
SilenceOtherRows(ActCategories.Break);
MentalStateDef extreme = DefDatabase<MentalStateDef>.GetNamed("Binging_DrugExtreme");
MentalStateDef major = DefDatabase<MentalStateDef>.GetNamed("Binging_DrugMajor");
T.Check(!Watch.Break, "the Break flag is on before the row");
Law row = Add(Binge);
T.Check(Watch.Break && Watch.Any, "the Break flag is off after adding the row");
T.Check(Watch.IsWatched(ActCategories.Break, extreme), "Binging_DrugExtreme is not watched");
T.Check(Watch.IsWatched(ActCategories.Break, major), "Binging_DrugMajor is not watched");
T.Check(!Watch.IsWatched(ActCategories.Break, DefDatabase<MentalStateDef>.GetNamed("FireStartingSpree")), "a binge row watches the fire-starting spree");
Lawbook.SetEnabled(row, false);
T.Check(!Watch.Break, "the Break flag is on with the row off");
Lawbook.SetEnabled(row, true);
Lawbook.Delete(row);
T.Check(!Watch.Break, "the Break flag is on after deleting the row");
T.Check(!Watch.IsWatched(ActCategories.Break, extreme) && !Watch.IsWatched(ActCategories.Break, major), "a binge break is still watched after the delete");
}
// ---- column dropdowns ------------------------------------------------------------------
[BlaxTest("ui: a Planning row never offers Reprimand, Banish or Execute; a Berserk row never offers Subdue; a Tantrum row does")]
public static void PunishmentMenus()
{
Law planning = Add(Binge);
List<string> p = Names(LawbookUi.PunishmentChoices(planning));
T.Check(p.Contains("Warn") && p.Contains("Subdue") && p.Contains("Jail"), "a binge planning row lacks Warn, Subdue or Jail: " + string.Join(", ", p));
foreach (string never in new[] { "Reprimand", "Banish", "Execute", "Guilty", "SubdueThenJail" })
T.Check(!p.Contains(never), "a binge planning row offers " + never);
Law didIt = Add(Binge);
List<string> d = Names(LawbookUi.PunishmentChoices(didIt));
foreach (string must in new[] { "Warn", "Guilty", "Subdue", "Jail", "SubdueThenJail" })
T.Check(d.Contains(must), "a binge did-it row lacks " + must + ": " + string.Join(", ", d));
Law berserk = Add("Break/Berserk");
List<string> b = Names(LawbookUi.PunishmentChoices(berserk));
T.Check(Entry("Break/Berserk").hostileBreak, "the Berserk entry isn't marked hostile");
T.Check(!b.Contains("Subdue") && !b.Contains("SubdueThenJail"), "a Berserk row offers a subdue: " + string.Join(", ", b));
T.Check(b.Contains("Warn") && b.Contains("Guilty") && b.Contains("Jail"), "a Berserk row lacks Warn, Guilty or Jail: " + string.Join(", ", b));
Law tantrum = Add("Break/Tantrum");
T.Check(Names(LawbookUi.PunishmentChoices(tantrum)).Contains("Subdue"), "a Tantrum row doesn't offer Subdue");
Law insult = Add(Insult);
List<string> a = Names(LawbookUi.PunishmentChoices(insult));
T.Check(a.Contains("Warn") && a.Contains("Guilty") && a.Contains("Jail") && !a.Contains("Subdue") && !a.Contains("SubdueThenJail"),
"an Insult row offers " + string.Join(", ", a) + " (expected Warn, Guilty, Jail, no subdue)");
Choice(LawbookUi.PunishmentChoices(insult), "Jail").action();
T.Equal("Jail", insult.punishment, "picking Jail in the menu");
T.Check(LawbookUi.UsesDays(insult), "a Jail row shows no Days field");
Choice(LawbookUi.PunishmentChoices(insult), "Warn").action();
T.Check(!LawbookUi.UsesDays(insult), "a Warn row shows a Days field");
}
[BlaxTest("ui: switching a Subdue row's action to Ate: any meat resets it to Warn and Did it; Severity moves untouched days")]
public static void ActionAndSeverityResets()
{
Law row = Add(Binge);
Choice(LawbookUi.PunishmentChoices(row), "Subdue").action();
T.Equal("Subdue", row.punishment, "picking Subdue in the menu");
T.Check(LawbookUi.ChangeAction(row, "Ate/@anyMeat"), "changing the action to Ate: any meat was refused");
T.Equal("Ate/@anyMeat", row.actKey, "act key after the change");
T.Equal("Warn", row.punishment, "punishment after switching a Subdue row to Ate: any meat");
T.Equal(LawStage.DidIt, row.stage, "stage after switching to an entry without Planning");
T.Check(row.option == null, "the option stayed after switching away from a binge: " + row.option);
T.Check(row.savedLabel == Entry("Ate/@anyMeat").label, "the row didn't save the new entry's label: " + row.savedLabel);
Choice(LawbookUi.SeverityChoices(row), nameof(LawSeverity.Serious)).action();
T.Equal(5, row.days, "untouched days after Moderate to Serious in the menu");
Lawbook.SetDays(row, 8);
Choice(LawbookUi.SeverityChoices(row), nameof(LawSeverity.Grave)).action();
T.Equal(8, row.days, "typed days after Serious to Grave in the menu");
T.Check(LawbookUi.SeverityChoices(row).Single(c => c.selected).payload.Equals(LawSeverity.Grave), "the severity menu marks another value as selected");
// The first binge row became Ate: any meat, so the binge's planning key is free again.
Law planning = Add(Binge);
T.Equal(LawStage.Planning, planning.stage, "stage of the next binge row");
Law didIt = Add(Binge);
T.Equal(LawStage.DidIt, didIt.stage, "stage of the binge row after that");
Choice(LawbookUi.PunishmentChoices(didIt), "SubdueThenJail").action();
T.Equal("SubdueThenJail", didIt.punishment, "picking Subdue then jail in the menu");
T.Check(!LawbookUi.ChangeStage(didIt, LawStage.Planning), "the stage menu made a second binge planning row");
T.Equal(planning.id, LawbookUi.FocusLawId, "the refused stage change doesn't show the existing row");
Lawbook.Delete(planning);
Choice(LawbookUi.StageChoices(didIt), nameof(LawStage.Planning)).action();
T.Equal(LawStage.Planning, didIt.stage, "stage after picking Planning");
T.Equal("Warn", didIt.punishment, "Subdue then jail, which planning doesn't offer, didn't reset to Warn on the stage change");
Choice(LawbookUi.PunishmentChoices(didIt), "Jail").action();
Choice(LawbookUi.StageChoices(didIt), nameof(LawStage.DidIt)).action();
T.Equal("Jail", didIt.punishment, "a Jail row that still fits lost its punishment on the stage change");
}
[BlaxTest("ui: the drug option list holds WakeUp and no non-drug chemical; picking an option keeps the key unique")]
public static void DrugOptionMenu()
{
Law row = Add(Binge);
List<RowChoice> choices = LawbookUi.OptionChoices(row);
List<string> names = Names(choices);
T.Check(names.Count > 3 && names[0] == DrugOptions.Any && names[1] == DrugOptions.Hard && names[2] == DrugOptions.Social,
"the option menu doesn't start with Any, Hard, Social: " + string.Join(", ", names.Take(4)));
T.Check(names.Contains("WakeUp"), "the option menu lacks the wake-up chemical: " + string.Join(", ", names));
var drugChemicals = new HashSet<string>();
foreach (ThingDef t in DefDatabase<ThingDef>.AllDefsListForReading)
{
CompProperties_Drug drug = t.GetCompProperties<CompProperties_Drug>();
if (drug?.chemical != null)
drugChemicals.Add(drug.chemical.defName);
}
foreach (string n in names.Skip(3))
T.Check(drugChemicals.Contains(n), "the option menu lists " + n + ", a chemical no drug names");
T.Equal(names.Count, names.Distinct().Count(), "options listed twice");
List<string> others = DefDatabase<ChemicalDef>.AllDefsListForReading.Select(c => c.defName).Where(n => !drugChemicals.Contains(n)).ToList();
T.Info("chemicals no drug names (left out): " + (others.Count == 0 ? "none" : string.Join(", ", others)));
Choice(choices, "WakeUp").action();
T.Equal("WakeUp", row.option, "option after picking wake-up");
T.Equal(DrugOptions.Label("WakeUp"), DefDatabase<ChemicalDef>.GetNamed("WakeUp").LabelCap.ToString(), "the wake-up option's label");
// The planning key with Any drug is free again, so the next pick adds a planning row with Any drug.
Law second = Add(Binge);
T.Equal(LawStage.Planning, second.stage, "stage of the second binge row");
T.Equal(DrugOptions.Any, DrugOptions.Normalize(second.option), "option of the second binge row");
T.Check(!LawbookUi.ChangeOption(second, "WakeUp"), "a second planning row with the wake-up option was allowed");
T.Equal(row.id, LawbookUi.FocusLawId, "the refused option doesn't show the existing row");
T.Check(LawbookUi.ChangeOption(second, DrugOptions.Hard), "the hard drugs option was refused");
T.Equal(DrugOptions.Hard, second.option, "option after picking hard drugs");
}
[BlaxTest("ui: a row whose entry is missing shows its saved label and why, keeps its stage and punishment and offers nothing else")]
public static void MissingEntryRow()
{
Law row = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Moderate, "Jail", 4, "Ideology", "ludeon.rimworld.ideology");
T.Check(LawbookUi.ActionLabel(row).Contains(ActKey.NameOf(MissingKey)), "the action label lacks the saved label: " + LawbookUi.ActionLabel(row));
T.Check(LawbookUi.ActionTooltip(row).Contains("Needs Ideology"), "the action tooltip doesn't say Needs Ideology: " + LawbookUi.ActionTooltip(row));
List<RowChoice> stages = LawbookUi.StageChoices(row);
T.Check(stages.Count == 1 && stages[0].action == null && stages[0].selected && stages[0].reason == "Needs Ideology", "stage menu of a missing row: " + Show(stages));
List<RowChoice> punishments = LawbookUi.PunishmentChoices(row);
T.Check(punishments.Count == 1 && punishments[0].action == null && Equals(punishments[0].payload, BlaxLawsDefOf.Jail), "punishment menu of a missing row: " + Show(punishments));
T.Check(LawbookUi.UsesDays(row), "a missing Jail row lost its Days field");
T.Equal(0, ActOverlaps.Of(row).Count, "overlaps of a missing row");
}
// ---- act picker --------------------------------------------------------------------------
[BlaxTest("ui: the picker's search for 'wake' lists Wake-up under Ate and make wake-up under Bills; 'insult' lists Insult and the insulting sprees")]
public static void PickerSearch()
{
var tree = new ActPickerTree { SearchText = "wake" };
List<ActPickerRow> rows = tree.Rows.ToList();
List<ActPickerRow> entries = rows.Where(r => !r.IsHeader).ToList();
T.Check(entries.Any(r => r.category.defName == ActCategories.Ate && r.entry.def?.defName == "WakeUp"), "'wake' doesn't list Wake-up under Ate");
T.Check(entries.Any(r => r.category.defName == ActCategories.Bill && r.entry.def is RecipeDef rd && rd.ProducedThingDef?.defName == "WakeUp"),
"'wake' doesn't list make wake-up under Bills");
T.Check(entries.All(r => tree.Matches(r.entry)), "a listed entry doesn't match 'wake'");
T.Check(!entries.Any(r => r.entry.def?.defName == "Beer"), "'wake' lists Beer");
foreach (ActPickerRow h in rows.Where(r => r.IsHeader))
{
T.Check(h.open && h.count > 0, "searching shows the category " + h.category.defName + " closed or empty");
T.Equal(h.count, entries.Count(r => r.category == h.category), "entries listed under " + h.category.defName);
}
T.Equal(entries.Count, tree.Hits, "hits of 'wake'");
tree.SearchText = "insult";
entries = tree.Rows.Where(r => !r.IsHeader).ToList();
T.Check(entries.Any(r => r.category.defName == ActCategories.Interaction && r.entry.def?.defName == "Insult"), "'insult' doesn't list Insult under interactions");
T.Check(entries.Any(r => r.category.defName == ActCategories.Break && r.entry.def?.defName == "InsultingSpree"), "'insult' doesn't list the insulting spree under breaks");
T.Check(entries.Any(r => r.category.defName == ActCategories.Break && r.entry.def?.defName == "TargetedInsultingSpree"), "'insult' doesn't list the targeted insulting spree under breaks");
tree.SearchText = "blaxlawstest no act is called this";
T.Equal(0, tree.Rows.Count, "lines for a search without hits");
T.Equal(0, tree.Hits, "hits for a search without hits");
}
[BlaxTest("ui: the picker opens with every category closed, opens one on a click, groups first; entries in the book show a tick")]
public static void PickerTree()
{
var tree = new ActPickerTree();
IReadOnlyList<ActCategoryDef> cats = ActCatalogue.Categories;
T.Equal(cats.Count, tree.Rows.Count, "lines with every category closed");
T.Check(tree.Rows.All(r => r.IsHeader && !r.open), "a closed tree shows an entry");
T.Check(cats.Select(c => c.defName).SequenceEqual(ActCategories.All.Where(id => cats.Any(c => c.defName == id))), "categories not in picker order: " + string.Join(", ", cats.Select(c => c.defName)));
tree.Toggle(ActCategories.Break);
List<ActPickerRow> rows = tree.Rows.ToList();
List<ActPickerRow> breaks = rows.Where(r => !r.IsHeader).ToList();
T.Equal(ActCatalogue.EntriesOf(ActCategories.Break).Count, breaks.Count, "entries under an opened Mental breaks");
T.Check(breaks.Count > 0 && breaks.All(r => r.category.defName == ActCategories.Break), "an opened category lists another category's entries");
int firstDef = breaks.FindIndex(r => !r.entry.IsGroup);
T.Check(firstDef > 0 && breaks.Skip(firstDef).All(r => !r.entry.IsGroup), "groups don't come first under Mental breaks");
T.Equal(1, rows.Count(r => r.IsHeader && r.open), "open categories after one click");
Law insult = Add(Insult);
tree.SearchText = "insult";
ActPickerRow insultLine = tree.Rows.First(r => !r.IsHeader && r.entry.key == Insult);
T.Check(insultLine.inBook, "Insult has a row but shows no tick");
T.Check(tree.Rows.Where(r => !r.IsHeader && r.entry.key != Insult).All(r => !r.inBook), "an entry without a row shows a tick");
T.Check(Dialog_PickAct.EntryTooltip(insultLine.entry, true).Contains("Core"), "the entry tooltip lacks its source mod");
Dialog_PickAct forRow = Dialog_PickAct.ForRow(insult);
T.Check(forRow.Tree.IsOpen(ActCategories.Interaction), "the picker for a row doesn't open the row's category");
tree.SearchText = "";
tree.Toggle(ActCategories.Break);
T.Equal(cats.Count, tree.Rows.Count, "lines after closing Mental breaks again");
}
// ---- overlap icon ------------------------------------------------------------------------
[BlaxTest("ui: Ate: wake-up next to Recorded acts: ingested a drug shows the overlap icon on both; a cook's bill overlaps meals cooked")]
public static void OverlapIcon()
{
Law ate = Fixtures.LawRow("Ate/WakeUp", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3);
Law recorded = Fixtures.LawRow("RecordedAct/IngestedDrug", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3);
Law insult = Fixtures.LawRow(Insult, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(ate.Resolves && recorded.Resolves && insult.Resolves, "an overlap row doesn't resolve: " + ate.MissingText + ", " + recorded.MissingText + ", " + insult.MissingText);
T.Check(ActOverlaps.Of(ate).Contains(recorded), "Ate: wake-up shows no overlap with Recorded acts: ingested a drug");
T.Check(ActOverlaps.Of(recorded).Contains(ate), "Recorded acts: ingested a drug shows no overlap with Ate: wake-up");
T.Equal(0, ActOverlaps.Of(insult).Count, "overlaps of an Insult row");
T.Check(!ActOverlaps.Of(ate).Contains(insult), "Ate: wake-up overlaps Insult");
Lawbook.SetEnabled(recorded, false);
T.Equal(0, ActOverlaps.Of(ate).Count, "overlaps of Ate: wake-up with the recorded-act row off");
Lawbook.SetEnabled(recorded, true);
T.Check(ActOverlaps.Of(ate).Contains(recorded), "the overlap didn't come back with the row on again");
Law meal = Fixtures.LawRow("Ate/MealSimple", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(!ActOverlaps.Of(meal).Contains(recorded), "a simple meal overlaps ingested a drug");
Law cook = Fixtures.LawRow("Bill/CookMealSimple", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Law cooked = Fixtures.LawRow("Record/MealsCooked", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(cook.Resolves && cooked.Resolves, "the bill or record row doesn't resolve: " + cook.MissingText + ", " + cooked.MissingText);
T.Check(ActOverlaps.Of(cook).Contains(cooked) && ActOverlaps.Of(cooked).Contains(cook), "cooking a simple meal shows no overlap with meals cooked");
T.Check(!ActOverlaps.Of(cooked).Contains(ate), "meals cooked overlaps eating wake-up");
}
// ---- delete and starter ------------------------------------------------------------------
[BlaxTest("ui: deleting a law with open cases asks first and names the count; without open cases it deletes at once")]
public static void DeleteAsksFirst()
{
Law quiet = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
T.Check(LawbookUi.DeleteConfirmText(quiet) == null, "a row without cases asks before the delete");
LawbookUi.RequestDelete(quiet);
T.Check(!Lawbook.Laws.Contains(quiet), "a row without cases wasn't deleted at once");
Law busy = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Pawn p = Fixtures.Colonist();
LawCase c1 = OpenCase(busy, p);
LawCase c2 = OpenCase(busy, Fixtures.Colonist());
string text = LawbookUi.DeleteConfirmText(busy);
T.Check(text != null && text.Contains("(2)"), "the confirmation doesn't name 2 open cases: " + text);
int windows = Find.WindowStack.Count;
LawbookUi.RequestDelete(busy);
Dialog_MessageBox box = Find.WindowStack.WindowOfType<Dialog_MessageBox>();
T.Check(box != null && Find.WindowStack.Count == windows + 1, "no confirmation opened");
T.Check(Lawbook.Laws.Contains(busy) && !c1.IsClosed, "the row was deleted before the confirmation");
Find.WindowStack.TryRemove(box, doCloseSound: false);
T.Check(Lawbook.Laws.Contains(busy), "closing the confirmation deleted the row");
T.Equal(2, Lawbook.Delete(busy), "cases the confirmed delete closed");
T.Check(c1.outcome == CaseOutcomes.Repealed && c2.outcome == CaseOutcomes.Repealed, "the cases didn't close as repealed: " + c1 + "; " + c2);
}
[BlaxTest("ui: the Starter lawbook button adds 7 rows; pressing it again adds none")]
public static void StarterButton()
{
foreach (Lawbook.StarterRow s in Lawbook.StarterRows)
T.Check(Lawbook.Find(s.actKey, s.option, s.stage) == null, "setup: starter row " + s.actKey + " is already in the book");
T.Equal(7, LawbookUi.PressStarter(), "rows the button added");
T.Equal(0, LawbookUi.PressStarter(), "rows a second press added");
foreach (Lawbook.StarterRow s in Lawbook.StarterRows)
{
Law l = Lawbook.Find(s.actKey, s.option, s.stage);
T.Check(l != null && l.Resolves, "starter row " + s.actKey + " " + s.stage + " is missing or doesn't resolve: " + l?.MissingText);
}
}
// ---- case log ----------------------------------------------------------------------------
[BlaxTest("ui: the case log lists newest first with who, what, stage, when, punishment and status; closed cases only when asked")]
public static void CaseLogLines()
{
GameComponent_BlaxLaws comp = Fixtures.Comp;
int now = Find.TickManager.TicksGame;
Law warn = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Law jail = Fixtures.LawRow("Ate/BlaxLawsTest_UiNoSuchDrug", null, LawStage.DidIt, LawSeverity.Grave, "Jail", 5);
Pawn a = Fixtures.Colonist();
Pawn b = Fixtures.Colonist();
LawCase older = OpenCase(warn, a);
older.openTick = older.lastActTick = now - 3 * GenDate.TicksPerDay;
LawCase newer = OpenCase(jail, b);
newer.count = 3;
newer.notes = CaseNotes.OnTable;
List<LawCase> rows = CaseLog.Rows(true).Where(c => c == older || c == newer).ToList();
T.Check(rows.Count == 2 && rows[0] == newer && rows[1] == older, "the log isn't newest first: " + string.Join("; ", rows));
T.Equal(a.LabelShort, CaseLog.Who(older), "who");
T.Check(CaseLog.What(newer).Contains("3 times") && CaseLog.What(newer).Contains("on a table"), "what lacks the count or the note: " + CaseLog.What(newer));
T.Check(CaseLog.What(older).Contains(ActKey.NameOf(MissingKey)), "what lacks the row's label: " + CaseLog.What(older));
T.Equal("Did it", CaseLog.Stage(older), "stage");
T.Check(CaseLog.When(older).Contains("3 days") && CaseLog.When(older).Contains("ago"), "when: " + CaseLog.When(older));
T.Check(CaseLog.Punishment(newer).Contains("5"), "punishment lacks the days: " + CaseLog.Punishment(newer));
T.Equal("Open", CaseLog.Status(older), "status of an open case");
newer.status = CaseStatus.Jailed;
newer.releaseTick = now + 2 * GenDate.TicksPerDay;
T.Check(CaseLog.Status(newer).Contains("2 days"), "a jailed case doesn't count down: " + CaseLog.Status(newer));
newer.status = CaseStatus.Open;
newer.waitReason = WaitReasons.Danger;
T.Check(CaseLog.Status(newer).Contains("danger"), "a waiting case doesn't say why: " + CaseLog.Status(newer));
comp.CloseCase(older, CaseOutcomes.Warned);
T.Equal("Warned", CaseLog.Status(older), "status of a closed case");
T.Check(!CaseLog.Rows(false).Contains(older), "a closed case shows with closed cases hidden");
T.Check(CaseLog.Rows(false).Contains(newer), "an open case is hidden");
T.Check(CaseLog.CanJump(newer), "no jump button for a spawned offender");
}
[BlaxTest("ui: the Cases tab refills one list in place, newest first, then severity, then id within a tick, and follows closing and severity changes")]
public static void CaseRowsFillInPlace()
{
GameComponent_BlaxLaws comp = Fixtures.Comp;
int now = Find.TickManager.TicksGame;
Law minor = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderMinor", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Law moderate = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderModerate", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 1);
Law grave = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderGrave", null, LawStage.DidIt, LawSeverity.Grave, "Warn", 1);
LawCase older = OpenCase(grave, Fixtures.Colonist());
older.openTick = older.lastActTick = now - GenDate.TicksPerDay;
LawCase m = OpenCase(moderate, Fixtures.Colonist());
LawCase b = OpenCase(minor, Fixtures.Colonist());
LawCase g = OpenCase(grave, Fixtures.Colonist());
LawCase b2 = OpenCase(minor, Fixtures.Colonist());
var mine = new HashSet<LawCase> { older, m, b, g, b2 };
string Order(List<LawCase> l) => string.Join("; ", l.Where(mine.Contains).Select(x => x.id + "/" + x.severity));
var rows = new List<LawCase>();
CaseLog.FillRows(rows, true);
List<LawCase> got = rows.Where(mine.Contains).ToList();
T.Check(got.SequenceEqual(new[] { g, m, b2, b, older }), "not newest first, then severity, then id: " + Order(rows));
T.Check(CaseLog.Rows(true).SequenceEqual(rows), "Rows and FillRows disagree");
int capacity = rows.Capacity;
CaseLog.FillRows(rows, true);
T.Equal(capacity, rows.Capacity, "a second fill of the same cases grew the list");
b.SetLaw(LawStage.Planning, grave); // raises b to Grave; same tick as g, lower id
CaseLog.FillRows(rows, true);
T.Check(rows.Where(mine.Contains).SequenceEqual(new[] { g, b, m, b2, older }), "a raised severity didn't reorder the rows: " + Order(rows));
comp.CloseCase(m, CaseOutcomes.Warned);
CaseLog.FillRows(rows, false);
T.Check(!rows.Contains(m) && rows.Contains(g) && rows.Contains(older), "closing a case didn't hide only it: " + Order(rows));
CaseLog.FillRows(rows, true);
T.Check(rows.Contains(m), "a closed case is missing with closed cases shown");
m.status = CaseStatus.Open;
m.outcome = null;
m.closeTick = -1;
CaseLog.FillRows(rows, false);
T.Check(rows.Contains(m), "a reopened case stays hidden");
foreach (LawCase c in mine)
comp.CloseCase(c, CaseOutcomes.Warned);
}
[BlaxTest("ui: Arrest now shows only for a held case and the Cases tab says it waits for it; not for another wait or a closed case")]
public static void ArrestNowShowsForHold()
{
Law jail = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Serious, "Jail", 5);
Pawn p = Fixtures.Colonist();
LawCase c = OpenCase(jail, p);
try
{
c.activePunishment = "Jail";
c.activeStage = LawStage.DidIt;
T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a case that doesn't wait");
WaitReasons.Set(c, WaitReasons.Danger);
T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a case that waits for the danger to pass");
T.Check(CaseLog.Status(c).Contains("danger"), "the status of a danger wait doesn't say why: " + CaseLog.Status(c));
// The hold JailFlow sets for a role holder or a mechanitor (JailTests drive the real hold and its letter).
WaitReasons.Set(c, WaitReasons.Hold);
T.Check(CaseLog.CanArrestNow(c), "Arrest now doesn't show for a held case");
T.Check(CaseLog.Status(c).Contains("Arrest now"), "the status of a held case doesn't say it waits for Arrest now: " + CaseLog.Status(c));
T.Check(!CaseLog.HoldReason(p).NullOrEmpty(), "no hold reason for the tooltip");
Fixtures.Comp.CloseCase(c, CaseOutcomes.NotEnforced);
T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a closed case");
}
finally
{
c.activePunishment = null;
}
}
[BlaxTest("ui: the jail letter names the offender, the law, the days and the release day; none with letters off")]
public static void JailLetter()
{
RemoveNewLettersAfterTest();
var before = new HashSet<Letter>(Find.LetterStack.LettersListForReading);
Law jail = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Serious, "Jail", 5);
Pawn p = Fixtures.Colonist();
LawCase c = OpenCase(jail, p);
c.activeStage = LawStage.DidIt;
c.captureTick = Find.TickManager.TicksGame;
c.releaseTick = c.captureTick + 5 * GenDate.TicksPerDay;
CaseLetters.Jailed(c);
List<Letter> sent = LettersSince(before);
T.Equal(1, sent.Count, "jail letters");
string text = (sent[0] as ChoiceLetter)?.Text.ToString() ?? "";
T.Check(text.Contains(p.LabelShort) && text.Contains("5 days") && text.Contains(ActKey.NameOf(MissingKey)), "the jail letter: " + text);
T.Check(text.Contains(Sentences.ReleaseDate(c)) && !Sentences.ReleaseDate(c).NullOrEmpty(), "the jail letter lacks the release day: " + text);
Fixtures.Settings.jailLetters = false;
CaseLetters.Jailed(c);
T.Equal(1, LettersSince(before).Count, "jail letters with letters off");
}
}
}

248
Tests/run-tests.ps1 Normal file
View File

@ -0,0 +1,248 @@
<#
Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its
own save data folder, so your mod list, saves and settings stay untouched. Needs Steam running and
the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures or Blax Laws errors outside
the tests, 2 the run didn't finish.
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Laws
.\Tests\run-tests.ps1 -Compat also Blax Castes, Blax Zones, Blax Slaves, Blax Defaults and the installed
mods Laws is tested next to: Prison Labor, Prisoner Realism, Custom Prisoner
Interactions, Hospitality, Vanilla Social Interactions Expanded and Humanoid
Alien Races once it is installed
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (tests that need a DLC skip with "needs <DLC>")
.\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
.\Tests\run-tests.ps1 -DataDir <folder> another save data folder, for runs in parallel (one folder each)
.\Tests\run-tests.ps1 -Worktree run from a copy of the repo (a work package built in parallel): Mods\BlaxLaws
points at this copy for the run and back at its old target afterwards
.\Tests\run-tests.ps1 -WaitSeconds 1800 wait up to this long for another run's lock instead of failing at once
Call it with literal switches or hashtable splatting (@{ NoDlc = $true }), never array splatting: an array
passes a switch as a positional value.
Mods\BlaxLaws must be a directory junction to this repo; it is created if missing and left in place. With -Worktree
it may point at another copy: it is retargeted for the run and restored afterwards, under the lock.
While the suite runs, the test mod is linked into the game's Mods folder as Mods\BlaxLawsTests; that link is
removed afterwards (cmd /c rmdir, never a recursive delete). A link another run left that already points at this
test mod is used as it is and left in place, so parallel runs can share one link made before and removed after.
Only one run per data folder: a lock file in the data folder holds the running script's process id.
Every run starts from default mod settings: the Blax Laws, Blax Castes, Blax Zones, Blax Slaves and Blax Defaults
settings files in the data folder are deleted.
The results go to BlaxLawsTestResults.txt in the data folder, and a copy per DLC set next to it:
BlaxLawsTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-<names>.txt. Runs with -Compat write
.<set>-compat.txt instead (.all-compat.txt, .nodlc-compat.txt, ...). Each copy starts with a "REPO <path>" line
naming the copy of the repo that was tested, so a -Worktree run never counts for the main checkout. The Workshop
upload checks the "all" and "nodlc" copies.
#>
param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[string]$DataDir = (Join-Path $env:TEMP 'BlaxLawsTest'),
[switch]$Compat,
[switch]$NoDlc,
[string[]]$Dlc,
[switch]$NoBuild,
[switch]$AllowWhileRunning,
[switch]$Worktree,
[int]$WaitSeconds = 0,
[int]$TimeoutSeconds = 900
)
$ErrorActionPreference = 'Stop'
# A wrong path (for example a switch passed as a positional value) would put the Mods junction somewhere odd.
if (-not (Test-Path -LiteralPath (Join-Path $RimWorldDir 'Assembly-CSharp.dll'))) { throw "No RimWorld 1.7 install at '$RimWorldDir'." }
$repo = Split-Path -Parent $PSScriptRoot
$testMod = Join-Path $PSScriptRoot 'BlaxLawsTests'
$modLink = Join-Path $RimWorldDir 'Mods\BlaxLaws'
$link = Join-Path $RimWorldDir 'Mods\BlaxLawsTests'
$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100'
$lockFile = Join-Path $DataDir 'run.lock'
if ((Get-Process -Name RimWorld -ErrorAction SilentlyContinue) -and -not $AllowWhileRunning) {
throw 'RimWorld is running. Close it first, or pass -AllowWhileRunning.'
}
function Get-FullPath([string]$path) { [IO.Path]::GetFullPath($path).TrimEnd('\') }
# One run per data folder. A lock whose process is gone is stale and taken over; a live one is waited for up to -WaitSeconds.
New-Item -ItemType Directory -Force $DataDir | Out-Null
function Enter-Lock {
$deadline = [DateTime]::UtcNow.AddSeconds([Math]::Max(0, $WaitSeconds))
$stale = 0
$waiting = $false
while ($true) {
try {
$stream = [IO.File]::Open($lockFile, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
$bytes = [Text.Encoding]::ASCII.GetBytes([string]$PID)
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
return
}
catch [IO.IOException] {
$owner = (Get-Content -LiteralPath $lockFile -Raw -ErrorAction SilentlyContinue)
$ownerPid = 0
if ($owner -and [int]::TryParse($owner.Trim(), [ref]$ownerPid) -and $ownerPid -ne $PID -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) {
if ([DateTime]::UtcNow -ge $deadline) { throw "Another test run (process $ownerPid) is in progress. Lock: $lockFile" }
if (-not $waiting) { Write-Host "Waiting for test run $ownerPid to finish..."; $waiting = $true }
Start-Sleep -Seconds 5
continue
}
if (++$stale -gt 3) { throw "Could not take the lock $lockFile" }
Write-Warning "removing stale lock from process $owner"
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
}
}
Enter-Lock
$restoreTarget = $null
try {
# Mods\BlaxLaws: a junction to this repo. Created if missing; replaced only with -Worktree, and put back afterwards.
if (Test-Path -LiteralPath $modLink) {
$item = Get-Item -LiteralPath $modLink -Force
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "$modLink is a real folder, not a junction to $repo. Move it away and run again."
}
$target = @($item.Target)[0]
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $repo)) {
if (-not $Worktree) { throw "$modLink points to '$target', not to $repo. Pass -Worktree to run from this copy." }
cmd /c rmdir "$modLink" | Out-Null
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
$restoreTarget = $target
Write-Host "Mods\BlaxLaws points at $repo for this run (was $target)"
}
}
else {
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
Write-Host "Created junction $modLink -> $repo"
}
if (-not $NoBuild) {
foreach ($proj in (Join-Path $repo 'Source\BlaxLaws\BlaxLaws.csproj'), (Join-Path $testMod 'Source\BlaxLawsTests.csproj')) {
& dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" }
}
}
# packageId (lower case) -> About.xml, for every installed local and Workshop mod
$installed = @{}
foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) +
@(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) {
$x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8)
if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x }
}
function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) {
$id = $id.ToLower()
if ($list -contains $id -or $id -like 'ludeon.*') { return }
$x = $installed[$id]
if (-not $x) { Write-Warning "not installed, skipped: $id"; return }
foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } }
[void]$list.Add($id)
}
# Load order: Harmony, core, DLCs, the mods Laws is tested next to, Blax Castes, Blax Zones, Blax Slaves,
# Blax Defaults, Blax Laws, the tests (Laws lists the other Blax mods in loadAfter; Zones lists Castes,
# Slaves lists Zones).
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
if ($NoDlc) { $loadDlcs = @() }
elseif ($Dlc) {
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
}
else { $loadDlcs = @($installedDlcs) }
$mods = New-Object System.Collections.ArrayList
$expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
[void]$mods.Add('brrainz.harmony')
[void]$mods.Add('ludeon.rimworld')
foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
# Name of this DLC set for the per-set copy of the results.
$dlcSet = if ($loadDlcs.Count -eq 0) { 'nodlc' } elseif ($loadDlcs.Count -eq $installedDlcs.Count) { 'all' } else { 'dlc-' + ($loadDlcs -join '-').ToLower() }
# Other mods change what runs and what skips, so their runs never stand in for the plain ones.
if ($Compat) { $dlcSet += '-compat' }
$setResults = Join-Path $DataDir "BlaxLawsTestResults.$dlcSet.txt"
if ($Compat) {
# Package ids read from the installed copies' About/About.xml (2026-12-01). Humanoid Alien Races
# (erdelf.humanoidalienraces) is skipped with a warning while it is not installed.
foreach ($id in 'avius.prisonlabor', 'legator.prisonerrealism', 'mlie.customprisonerinteractions', 'orion.hospitality',
'vanillaexpanded.vanillasocialinteractionsexpanded', 'erdelf.humanoidalienraces') {
Add-WithDependencies $id $mods
}
foreach ($id in 'blax.castes', 'blax.zones', 'blax.slaves', 'blax.defaults') { Add-WithDependencies $id $mods }
}
[void]$mods.Add('blax.laws')
[void]$mods.Add('blax.laws.tests')
# fresh test data folder: mod list only, no old saves, results or mod settings (files are named Mod_<folder>_<class>.xml)
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxLawsTest.rws'), (Join-Path $DataDir 'Saves\BlaxLawsTest3.rws'),
(Join-Path $DataDir 'BlaxLawsTestResults.txt'), $setResults
Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like 'Mod_BlaxLaws_*' -or $_.Name -like 'Mod_blax.laws_*' -or
$_.Name -like 'Mod_BlaxCastes_*' -or $_.Name -like 'Mod_blax.castes_*' -or
$_.Name -like 'Mod_BlaxZones_*' -or $_.Name -like 'Mod_blax.zones_*' -or
$_.Name -like 'Mod_BlaxSlaves_*' -or $_.Name -like 'Mod_blax.slaves_*' -or
$_.Name -like 'Mod_BlaxDefaults_*' -or $_.Name -like 'Mod_blax.defaults_*' } |
Remove-Item -Force -ErrorAction SilentlyContinue
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
[IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig)
Write-Host ("Mods: " + ($mods -join ', '))
$createdLink = $false
try {
# A test-mod link that points elsewhere (a run from another copy that died) is replaced; one that points
# at this test mod is used as it is and left for whoever made it.
if (Test-Path -LiteralPath $link) {
$item = Get-Item -LiteralPath $link -Force
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "$link is a real folder, not a junction. Move it away and run again." }
$target = @($item.Target)[0]
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $testMod)) {
Write-Warning "replacing stale test-mod link $link -> $target"
cmd /c rmdir "$link" | Out-Null
}
}
if (-not (Test-Path -LiteralPath $link)) {
New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null
$createdLink = $true
}
$gameArgs = "-headless -quicktest -blaxlawstests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`""
$sw = [Diagnostics.Stopwatch]::StartNew()
$p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs `
-RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') `
-WindowStyle Hidden -PassThru
if ($AllowWhileRunning) {
try { $p.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { Write-Warning "could not lower the test game's priority: $_" }
}
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
$p.Kill()
Write-Warning "timed out after $TimeoutSeconds s, test game (process $($p.Id)) killed"
}
Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log'))
}
finally {
if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null }
}
}
finally {
if ($restoreTarget) {
cmd /c rmdir "$modLink" | Out-Null
New-Item -ItemType Junction -Path $modLink -Target $restoreTarget | Out-Null
Write-Host "Mods\BlaxLaws points at $restoreTarget again"
}
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
$results = Join-Path $DataDir 'BlaxLawsTestResults.txt'
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
# The per-set copy names the tested copy of the repo, so the Workshop upload never takes another copy's run.
[IO.File]::WriteAllLines($setResults, [string[]](@("REPO $repo") + @(Get-Content -LiteralPath $results -Encoding UTF8)), (New-Object Text.UTF8Encoding $false))
$lines = Get-Content -LiteralPath $results -Encoding UTF8
$lines | ForEach-Object { Write-Host $_ }
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }
if ($lines -match '^FAIL ') { exit 1 }
# Errors Blax Laws logged outside the tests (while a save loads, between tests) fail the run too.
$summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1
if ($summary -match '\bstrayModErrors=[1-9]') { Write-Host 'Blax Laws logged errors outside the tests (MODERR lines).'; exit 1 }
exit 0

Some files were not shown because too many files have changed in this diff Show More