+
+ 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.
+
+<color=#19C63C>Lawbook</color>
+- 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.
+
+<color=#19C63C>Punishments</color>
+- 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.
+
+<color=#19C63C>Safe to add and remove</color>
+- 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.
+
+<color=#19C63C>Made by Blax</color>
+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
+
diff --git a/About/ModIcon.png b/About/ModIcon.png
new file mode 100644
index 0000000..b4a8fa8
Binary files /dev/null and b/About/ModIcon.png differ
diff --git a/About/Preview.png b/About/Preview.png
new file mode 100644
index 0000000..1a25c48
Binary files /dev/null and b/About/Preview.png differ
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..dfdaa7c
--- /dev/null
+++ b/CHANGELOG.md
@@ -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.
diff --git a/Defs/BlaxLaws_Acts.xml b/Defs/BlaxLaws_Acts.xml
new file mode 100644
index 0000000..e7718ae
--- /dev/null
+++ b/Defs/BlaxLaws_Acts.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+ SetFire
+
+ The pawn set something on fire.
+
+
+
+ DisplayedCorpse
+
+ The pawn hauled a corpse to a public place during a corpse obsession.
+
+
+
+ StartedSocialFight
+
+ The pawn answered an interaction with a social fight. The offender is the pawn who swings first.
+
+
+
diff --git a/Defs/BlaxLaws_BreakLinks.xml b/Defs/BlaxLaws_BreakLinks.xml
new file mode 100644
index 0000000..4fea795
--- /dev/null
+++ b/Defs/BlaxLaws_BreakLinks.xml
@@ -0,0 +1,53 @@
+
+
+
+
+
+ BlaxLaws_Link_BingingDrug
+
+ MentalState_BingingDrug
+ Ate/@anyDrug
+ true
+
+
+
+ BlaxLaws_Link_BingingFood
+
+ MentalState_Binging
+ Ate/@any
+
+
+
+ BlaxLaws_Link_FireStartingSpree
+
+ MentalState_FireStartingSpree
+ Special/SetFire
+
+
+
+ BlaxLaws_Link_CorpseObsession
+
+ MentalState_CorpseObsession
+ Special/DisplayedCorpse
+
+
+
+ BlaxLaws_Link_InsultingSpree
+
+ MentalState_InsultingSpree
+ Interaction/@insultOrSlight
+
+
+
+ BlaxLaws_Link_Jailbreaker
+
+ MentalState_Jailbreaker
+ Interaction/SparkJailbreak
+
+
+
diff --git a/Defs/BlaxLaws_Categories.xml b/Defs/BlaxLaws_Categories.xml
new file mode 100644
index 0000000..911433e
--- /dev/null
+++ b/Defs/BlaxLaws_Categories.xml
@@ -0,0 +1,83 @@
+
+
+
+
+
+ Break
+
+ Every mental break a colonist can have. Planning: the break has started. Did it: the act linked to the break happened during it.
+ BlaxLaws.ActCategoryWorker_Break
+ 10
+
+
MentalState_Berserk
+
MentalState_BerserkWarcall
+
+
+
Berserk
+
+
+
+
+ Ate
+
+ Everything that can be eaten or drunk: food, meals, raw food, corpses and drugs. Counts only when the pawn eats on its own.
+ BlaxLaws.ActCategoryWorker_Ate
+ 20
+
+
+
+ Used
+
+ Everything that can be used: psytrainers, neurotrainers, mech serums and modded usables.
+ BlaxLaws.ActCategoryWorker_Used
+ 30
+
+
+
+ Interaction
+
+ Every social interaction. The offender is the pawn who starts it.
+ BlaxLaws.ActCategoryWorker_Interaction
+ 40
+
+
+
+ RecordedAct
+
+ Every act the game records with the pawn as the doer. Most recorded acts need Ideology.
+ BlaxLaws.ActCategoryWorker_RecordedAct
+ 50
+
+
+
+ Record
+
+ Every record the game counts for a pawn, such as kills, bodies stripped or things hauled. A case opens when the record goes up.
+ BlaxLaws.ActCategoryWorker_Record
+ 60
+
+
+
+ Bill
+
+ Every bill. A case opens when the pawn finishes one iteration.
+ BlaxLaws.ActCategoryWorker_Bill
+ 70
+
+
+
+ Special
+
+ Acts the game records nowhere else: setting a fire, displaying a corpse and starting a social fight.
+ BlaxLaws.ActCategoryWorker_Special
+ 80
+
+
+
diff --git a/Defs/BlaxLaws_Jobs.xml b/Defs/BlaxLaws_Jobs.xml
new file mode 100644
index 0000000..57f830c
--- /dev/null
+++ b/Defs/BlaxLaws_Jobs.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+ BlaxLaws_Subdue
+ BlaxLaws.JobDriver_Subdue
+ subduing TargetA.
+ false
+ false
+ false
+
+
+
diff --git a/Defs/BlaxLaws_MainButtons.xml b/Defs/BlaxLaws_MainButtons.xml
new file mode 100644
index 0000000..2c95671
--- /dev/null
+++ b/Defs/BlaxLaws_MainButtons.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+ BlaxLaws_Laws
+
+ Your colony's lawbook and its cases.
+ BlaxLaws.MainTabWindow_Laws
+ 105
+ true
+
+
+
diff --git a/Defs/BlaxLaws_Punishments.xml b/Defs/BlaxLaws_Punishments.xml
new file mode 100644
index 0000000..0701fca
--- /dev/null
+++ b/Defs/BlaxLaws_Punishments.xml
@@ -0,0 +1,83 @@
+
+
+
+
+
+ Warn
+
+ Files the case and posts a message, nothing more.
+ BlaxLaws.PunishmentWorker_Warn
+ 10
+ true
+
+
BreakPlanning
+
BreakDidIt
+
HostileBreakPlanning
+
HostileBreakDidIt
+
Act
+
+
+
+
+ Guilty
+
+ 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.
+ BlaxLaws.PunishmentWorker_Guilty
+ 20
+ true
+ true
+
+
BreakDidIt
+
HostileBreakPlanning
+
HostileBreakDidIt
+
Act
+
+
+
+
+ Subdue
+
+ 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.
+ BlaxLaws.PunishmentWorker_Subdue
+ 30
+
+
BreakPlanning
+
BreakDidIt
+
+
+
+
+ Jail
+
+ A warden arrests the pawn. It sits out the days in a prisoner bed on "Maintain only" and walks back to work.
+ BlaxLaws.PunishmentWorker_Jail
+ 40
+ true
+
+
BreakPlanning
+
BreakDidIt
+
HostileBreakPlanning
+
HostileBreakDidIt
+
Act
+
+
+
+
+ SubdueThenJail
+
+ A warden beats the pawn down and carries it to a prisoner bed. After the break it jails without the beating.
+ BlaxLaws.PunishmentWorker_SubdueThenJail
+ 50
+ true
+
+
BreakDidIt
+
+
+
+
diff --git a/Languages/English/Keyed/BlaxLaws.xml b/Languages/English/Keyed/BlaxLaws.xml
new file mode 100644
index 0000000..6bab1af
--- /dev/null
+++ b/Languages/English/Keyed/BlaxLaws.xml
@@ -0,0 +1,64 @@
+
+
+
+
+
+
+ Needs {0}
+ Missing: {0}
+
+
+ Planning
+ Did it
+ Minor
+ Moderate
+ Serious
+ Grave
+ Open
+ Enforcing
+ Jailed
+ Closed
+ Law repealed
+ Break ended
+ Not enforced
+ Offender gone
+ Warned
+ Guilty
+ Subdued
+ Sentence served
+ Released early
+
+
+ Any drug
+ Hard drugs
+ Social drugs
+
+
+ No laws yet. Add one or press Starter lawbook.
+ {0} broke a law: {1} ({2}). Punishment: {3}.
+
+
+ Enforce laws
+ Wardens carry out the punishments of your lawbook. Off: cases are still filed and listed, and nothing is carried out.
+ Show Laws tab
+ Shows the Laws button in the bottom bar. Off hides it; your laws stay and are still enforced.
+ Messages for cases
+ Posts a message whenever a case is filed or moves on.
+ Letters for jailings
+ 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".
+ Enforcers
+ Wardens first, then anyone able
+ The nearest colonist with Warden work goes first; when none can, the nearest colonist able to do the job.
+ Wardens only
+ Only colonists with Warden work enforce laws. When none can, the case waits.
+ Subdued pawns lose their catharsis
+ 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.
+ Player orders are exempt
+ An act done while drafted or on a job you ordered opens no case.
+ Days between cases for acts outside a break: {0}
+ 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.
+ Keep closed cases: {0} days
+ Closed cases older than this are removed from the case list when the game is saved.
+ Reset to defaults
+
+
diff --git a/Languages/English/Keyed/BlaxLaws_Catalogue.xml b/Languages/English/Keyed/BlaxLaws_Catalogue.xml
new file mode 100644
index 0000000..d7d354a
--- /dev/null
+++ b/Languages/English/Keyed/BlaxLaws_Catalogue.xml
@@ -0,0 +1,30 @@
+
+
+
+
+ Any mental break
+ Any drug binge
+ Any tantrum
+ Any insulting spree
+ Any aggressive break
+
+ Anything eaten
+ Any drug
+ Hard drugs
+ Social drugs
+ Medical drugs
+ Any meat, meals with meat included
+ Raw meat or corpses
+ Human meat, as an ingredient too
+ Insect meat, as an ingredient too
+ Raw food
+ Any meal
+
+ Insult or slight
+
+ Any surgery
+
+
+ {0} ({1})
+
+
diff --git a/Languages/English/Keyed/BlaxLaws_Enforcement.xml b/Languages/English/Keyed/BlaxLaws_Enforcement.xml
new file mode 100644
index 0000000..716fb1a
--- /dev/null
+++ b/Languages/English/Keyed/BlaxLaws_Enforcement.xml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+ waiting until the danger is over
+ nobody can enforce it
+ waiting for a free enforcer
+ waiting for a free prisoner bed
+ waiting while someone else handles the pawn
+ waiting until the break ends or the pawn is down
+ waiting for Arrest now
+ waiting until the pawn is back on a map
+
+
+ Not subdued
+ Escaped
+ Died in jail
+ Already a prisoner
+
+
+ {1} subdued {0}.
+ {1} stopped subduing {0}: the hits cause no pain.
+ {0} is a child and is warned instead of subdued.
+ {0}'s break is over, so {0} is warned instead of subdued.
+ {0} fights back in this break, so {0} is warned instead of subdued.
+ Slaves aren't jailed yet, so {0} is warned.
+ {0} is already a prisoner. Laws leaves {0} to you and closes the case.
+ {0} died while serving a sentence.
+ {0} escaped from jail.
+ {0} has served the sentence and is free again.
+ {0} is out of jail before the sentence ended. The case is closed.
+ {0} has served the sentence. A warden will release {0}.
+ No warden released {0} within a day of the sentence's end, so {0} is released where {0} is.
+ The law {0} was jailed under was repealed. A warden will release {0}.
+
+
+ Jailed: {0}
+ {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.
+ No prisoner bed: {0}
+ {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.
+ Nobody to enforce: {0}
+ 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.
+ Arrest waits: {0}
+ {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.
+ an arrest takes away {0}'s ideoligion role
+ an arrest shuts down the mechs {0} controls
+
+
diff --git a/Languages/English/Keyed/BlaxLaws_UI.xml b/Languages/English/Keyed/BlaxLaws_UI.xml
new file mode 100644
index 0000000..fb89bbc
--- /dev/null
+++ b/Languages/English/Keyed/BlaxLaws_UI.xml
@@ -0,0 +1,70 @@
+
+
+
+
+ Lawbook
+ Cases
+ Add law
+ Pick an act from the catalogue of everything the game records and add a law for it. Then set its stage, severity and punishment.
+ Starter lawbook
+ Adds seven suggested laws: drug binges, fire-starting sprees, corpse obsession, starting a social fight and insults. Laws already in the book are skipped.
+ Laws added: {0}.
+ Every starter law is already in the book.
+ "Enforce laws" is off in the mod settings: cases are listed, nothing is carried out.
+
+
+ Action
+ Drug
+ Drug binges only: which drug counts as "did it".
+ Stage
+ Planning: a mental break has started and nothing is done yet. Did it: the act happened. Only mental breaks have Planning.
+ Severity
+ Sets the default days (Minor 1, Moderate 3, Serious 5, Grave 10) and orders the case log.
+ Punishment
+ Days
+ Days of guilt or of jail, 1 to 50.
+ On
+ Off: the law stays in the book and catches nothing.
+ -
+
+
+ {0}: {1}
+ Click to pick another act.
+ From: {0}
+ The book already has a law for {0} at stage {1}.
+ Delete this law
+ Delete the law "{0}"? Its open cases ({1}) close as "law repealed".
+ {0} of them sit in jail. They are set to "Release", and a warden lets them go.
+ This law can catch the same act as a law of another category, so one act may open a case under each:\n{0}
+
+
+ Pick an act
+ {0} ({1})
+ Stages: {0}
+ A break hostile to the colony: the pawn fights back, so it can't be subdued.
+ Already in the lawbook. Adding it again adds a law for a stage that has none, or shows the existing law.
+ No act matches the search.
+ The act catalogue is empty.
+
+
+ Show closed cases
+ No cases yet.
+ Who
+ What
+ When
+ Status
+ {0} against {1}
+ {0} times
+ on a table
+ dug up from a grave
+ just now
+ {0} ago
+ {0} days
+ Jailed, release in {0}
+ Jailed, release due
+ Show
+ Select {0} and move the view there.
+ Arrest now
+ Laws doesn't make this arrest on its own: {0}. Press to arrest now.
+
+
diff --git a/README.md b/README.md
index 89ed0a9..6a060a1 100644
--- a/README.md
+++ b/README.md
@@ -1,93 +1,157 @@
+
+
# Blax Laws
[](https://rimworldgame.com)
[](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077)
[](#dlc-support)
-[](docs/design.md)
+[](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.
-
-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`.
+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.
## Features
### 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`
-- ๐ **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`
-- ๐ **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`
-- ๐ฏ **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".
-- ๐๏ธ **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.
-- ๐ **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.
+- ๐ **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.** "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 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, 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; 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.
+- โ๏ธ **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 " or "Missing: ", isn't enforced and works again when the content comes back.
### 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`
-- ๐ฅ **Fire-starting spree.** Planning when a pyromaniac's spree starts, did it with every fire set.
-- โฐ๏ธ **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.
-- ๐ **Started a social fight.** The pawn who reacts and swings first, usually the insulted one.
-- ๐ฏ๏ธ **Insult.** Every insult by the one who insults; slights are their own entry. Planning for insulting sprees.
-- ๐ **Ate.** Any food or drug by name, or a group: any meat (meals included), raw meat and corpses, human meat, insect meat, hard drugs.
-- ๐งพ **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.
-- ๐ข **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.
-- ๐งฎ **No flood.** Acts outside a break open at most one case per colonist and law a day; more acts only raise its count.
+- ๐ง **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.
+- ๐ **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.
+- ๐ **Used.** Psytrainers, neurotrainers, mech serums and modded usables, when the pawn uses one on its own.
+- ๐ฏ๏ธ **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.
+- ๐งพ **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.
+- ๐ **Records.** Every counted record, such as kills, animals slaughtered, bodies stripped or things hauled. A case opens when the record goes up.
+- ๐งช **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.
+- ๐ฅ **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.
+- ๐ **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
-- โ **Warn.** A record and a message.
-- โ๏ธ **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`
-- ๐ **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`
-- ๐ **Subdue, then jail.** Beaten down and carried straight to a cell before a doctor takes it to bed.
+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`
+
+- โ **Warn.** The case is filed and a message posted, nothing more.
+- โ๏ธ **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.** 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
-- โณ **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.
-- โธ๏ธ **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.
+- โณ **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`
+- ๐๏ธ **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-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`
-- โ๏ธ **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".
+- ๐พ **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" (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
-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.
-- ๐๏ธ **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.
-- ๐๏ธ **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.
-- ๐ณ๏ธ **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.
-- ๐ **Repeat offenders.** A criminal record per colonist, harsher punishments for a repeat offence, and early release on probation.
-- ๐งโโ๏ธ **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.
-- ๐ **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).
+- ๐ช **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.
+- ๐ **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 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; later a jury and pardon petitions.
+- ๐ค **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, 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.
## 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.
-- **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.
-- **Ideology** also records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires.
+- **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 would shut down in jail, so their case waits for "Arrest now".
- **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 "; a case whose offender was a slave keeps its name.
## 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.
-- โ๏ธ RimCourt: it judges civil disputes as the lord, Laws tries those who break your laws; both run side by side.
-- โป๏ธ Replaces Rimworld Law and Order, which has no 1.7 build, needs Ideology and adds its own crime events.
+- โ๏ธ Hospitality: guests are never offenders.
+- โ๏ธ 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.
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
diff --git a/Source/Art/README.md b/Source/Art/README.md
new file mode 100644
index 0000000..e29965d
--- /dev/null
+++ b/Source/Art/README.md
@@ -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/.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.
diff --git a/Source/Art/blax-monogram.svg b/Source/Art/blax-monogram.svg
new file mode 100644
index 0000000..a628153
--- /dev/null
+++ b/Source/Art/blax-monogram.svg
@@ -0,0 +1,16 @@
+
diff --git a/Source/Art/fonts/geist.woff2 b/Source/Art/fonts/geist.woff2
new file mode 100644
index 0000000..8f01e76
Binary files /dev/null and b/Source/Art/fonts/geist.woff2 differ
diff --git a/Source/Art/fonts/inter.woff2 b/Source/Art/fonts/inter.woff2
new file mode 100644
index 0000000..41f6888
Binary files /dev/null and b/Source/Art/fonts/inter.woff2 differ
diff --git a/Source/Art/fonts/rajdhani-700.woff2 b/Source/Art/fonts/rajdhani-700.woff2
new file mode 100644
index 0000000..59012d4
Binary files /dev/null and b/Source/Art/fonts/rajdhani-700.woff2 differ
diff --git a/Source/Art/header.html b/Source/Art/header.html
new file mode 100644
index 0000000..13c6af3
--- /dev/null
+++ b/Source/Art/header.html
@@ -0,0 +1,46 @@
+
+
+
+
+
+
+
+
+
+
Write your colony's laws. Wardens stop and jail whoever breaks them.
+
+
+
+
+
+
+
Write your own lawbook
Empty until you add a law.
+
+
+
+
Any act can be a crime
Every break, drug, meal and bill.
+
+
+
+
Subdue or jail
A binge stopped before the first dose.
+
+
+
+
Court and votes planned
Trials, judges and laws put to a vote.
+
+
+
+
diff --git a/Source/BlaxLaws/BlaxLaws.csproj b/Source/BlaxLaws/BlaxLaws.csproj
new file mode 100644
index 0000000..d42b7a8
--- /dev/null
+++ b/Source/BlaxLaws/BlaxLaws.csproj
@@ -0,0 +1,46 @@
+
+
+
+
+ net10.0
+ BlaxLaws
+ BlaxLaws
+ latest
+ disable
+ disable
+ ..\..\1.7\Assemblies\
+ false
+ false
+ false
+ false
+ portable
+ true
+
+ false
+
+ $(MSBuildProjectDirectory)=Source/BlaxLaws
+
+
+
+
+ E:\SteamLibrary\steamapps\common\RimWorld
+ E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies
+
+
+
+
+ $(RimWorldDir)\Assembly-CSharp.dll
+ false
+
+
+ $(RimWorldDir)\UnityStubs.dll
+ false
+
+
+ $(HarmonyDir)\0Harmony.dll
+ false
+
+
+
+
diff --git a/Source/BlaxLaws/BlaxLawsDefOf.cs b/Source/BlaxLaws/BlaxLawsDefOf.cs
new file mode 100644
index 0000000..dedcfd7
--- /dev/null
+++ b/Source/BlaxLaws/BlaxLawsDefOf.cs
@@ -0,0 +1,25 @@
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ /// Defs Laws ships. Act categories and special acts are read through ActCatalogue, not here.
+ [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));
+ }
+ }
+}
diff --git a/Source/BlaxLaws/BlaxLawsMod.cs b/Source/BlaxLaws/BlaxLawsMod.cs
new file mode 100644
index 0000000..3fcf287
--- /dev/null
+++ b/Source/BlaxLaws/BlaxLawsMod.cs
@@ -0,0 +1,211 @@
+using System;
+using System.Collections.Generic;
+using HarmonyLib;
+using RimWorld;
+using UnityEngine;
+using Verse;
+
+namespace BlaxLaws
+{
+ /// Who enforces laws (setting "Enforcers").
+ public enum EnforcerMode
+ {
+ /// Wardens (Warden work active) first, then anyone able.
+ WardensFirst,
+ /// Only wardens; without one the case waits.
+ WardensOnly,
+ }
+
+ ///
+ /// Global settings (design: "Lawbook tab", settings page). The lawbook itself is per save and lives in
+ /// GameComponent_BlaxLaws, never here.
+ ///
+ public class BlaxLawsSettings : ModSettings
+ {
+ /// Wardens carry out punishments. Off: cases open and close, nothing is carried out.
+ public bool enforceLaws = true;
+ /// The Laws button shows in the bottom bar. Written live into MainButtonDef.buttonVisible.
+ public bool showLawsTab = true;
+ /// A message for every case (CaseMessages).
+ public bool caseMessages = true;
+ /// Letters when a colonist is jailed or the player has to act.
+ public bool jailLetters = true;
+ /// Who enforces.
+ public EnforcerMode enforcers = EnforcerMode.WardensFirst;
+ /// A subdued pawn loses the catharsis that ending its break gives.
+ public bool subdueRemovesCatharsis = true;
+ /// An act done while drafted or on a player-forced job opens no case.
+ public bool playerOrdersExempt = true;
+ /// Days between cases of one offender under one law for acts outside a break (0 to 7).
+ public int cooldownDays = DefaultCooldownDays;
+ /// Closed cases older than this are pruned on save (7 to 360).
+ 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);
+
+ /// The cooldown window in ticks; 0 files every act.
+ 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;
+
+ /// The settings, or defaults before the mod class exists, so nothing reads null while loading.
+ public static BlaxLawsSettings S => Settings ?? (fallback ??= new BlaxLawsSettings());
+ private static BlaxLawsSettings fallback;
+
+ public BlaxLawsMod(ModContentPack content) : base(content)
+ {
+ Settings = GetSettings();
+ }
+
+ public override string SettingsCategory() => "Blax Laws";
+
+ ///
+ /// 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.
+ ///
+ public static void ApplyTabVisibility()
+ {
+ try
+ {
+ MainButtonDef def = BlaxLawsDefOf.BlaxLaws_Laws ?? DefDatabase.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();
+ }
+ }
+
+ ///
+ /// 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].
+ ///
+ [StaticConstructorOnStartup]
+ public static class BlaxLawsStartup
+ {
+ public const string HarmonyId = "blax.laws";
+ public static readonly Harmony Harmony = new Harmony(HarmonyId);
+
+ /// Patch classes that failed to apply, by type name. Read by the smoke test.
+ public static readonly List FailedPatches = new List();
+
+ /// Patch classes applied at startup.
+ 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();
+ }
+ }
+}
diff --git a/Source/BlaxLaws/CaseFiler.cs b/Source/BlaxLaws/CaseFiler.cs
new file mode 100644
index 0000000..343b877
--- /dev/null
+++ b/Source/BlaxLaws/CaseFiler.cs
@@ -0,0 +1,199 @@
+using System;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class CaseFiler
+ {
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// The tick the pawn's break started, to within 30 ticks: now minus MentalState.Age.
+ public static int BreakStartTick(MentalState state) => state == null ? Now : Now - state.Age;
+
+ /// Whether the case's break is still running on its offender.
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/ActCatalogue.cs b/Source/BlaxLaws/Catalogue/ActCatalogue.cs
new file mode 100644
index 0000000..bb2ee31
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/ActCatalogue.cs
@@ -0,0 +1,266 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class ActCategoryWorker
+ {
+ public ActCategoryDef def;
+
+ /// Every entry of the category, def and group entries both. Default: none.
+ public virtual IEnumerable MakeEntries()
+ {
+ yield break;
+ }
+
+ /// The category's tooltip in the picker. Default: the def's description.
+ public virtual string Tooltip => def?.description;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static class ActCatalogue
+ {
+ private static bool built;
+ private static bool building;
+ private static readonly List all = new List();
+ private static readonly Dictionary byKey = new Dictionary();
+ private static readonly Dictionary> byCategory = new Dictionary>();
+ private static readonly List categories = new List();
+ private static readonly List chemicalOptions = new List();
+ private static readonly List Empty = new List();
+
+ /// Bumped on every build, for caches keyed on the catalogue.
+ public static int Version { get; private set; }
+
+ public static bool Built => built;
+
+ /// Every entry, category by category in picker order.
+ public static IReadOnlyList All
+ {
+ get
+ {
+ EnsureBuilt();
+ return all;
+ }
+ }
+
+ /// The categories in picker order.
+ public static IReadOnlyList Categories
+ {
+ get
+ {
+ EnsureBuilt();
+ return categories;
+ }
+ }
+
+ /// A category's entries: groups first, in the worker's order, then every def A to Z.
+ public static IReadOnlyList EntriesOf(string categoryId)
+ {
+ EnsureBuilt();
+ return categoryId != null && byCategory.TryGetValue(categoryId, out List list) ? list : Empty;
+ }
+
+ /// The entry for a key, or null when it is missing (a DLC or mod that isn't loaded, a typo).
+ 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;
+ }
+
+ /// The single-def entry of a def in a category, or null.
+ public static ActEntry EntryFor(string categoryId, Def def) => def == null ? null : Get(ActKey.Of(categoryId, def.defName));
+
+ /// The group behind a group key, or null.
+ public static ActGroup GroupOf(string key) => Get(key)?.group;
+
+ ///
+ /// 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.
+ ///
+ public static IReadOnlyList ChemicalOptions
+ {
+ get
+ {
+ EnsureBuilt();
+ return chemicalOptions;
+ }
+ }
+
+ public static void EnsureBuilt()
+ {
+ if (!built && !building)
+ Build();
+ }
+
+ /// Builds the catalogue from the loaded defs. A worker that throws logs once and leaves its category empty.
+ public static void Build()
+ {
+ building = true;
+ try
+ {
+ all.Clear();
+ byKey.Clear();
+ byCategory.Clear();
+ categories.Clear();
+ chemicalOptions.Clear();
+ BreakLinks.ClearCache();
+
+ categories.AddRange(DefDatabase.AllDefsListForReading.OrderBy(c => c.order).ThenBy(c => c.defName));
+ foreach (ActCategoryDef cat in categories)
+ {
+ var list = new List();
+ try
+ {
+ foreach (ActEntry e in cat.Worker.MakeEntries() ?? Enumerable.Empty())
+ {
+ 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;
+ }
+ }
+
+ /// Drops the catalogue; the next read builds it again. Tests only.
+ public static void Reset()
+ {
+ built = false;
+ all.Clear();
+ byKey.Clear();
+ byCategory.Clear();
+ categories.Clear();
+ chemicalOptions.Clear();
+ }
+
+ /// Group sizes, the stage and break fields, and the picker order: groups first, defs A to Z.
+ private static void Finish(ActCategoryDef cat, List list)
+ {
+ List 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 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();
+ foreach (ThingDef t in DefDatabase.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));
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/ActEntry.cs b/Source/BlaxLaws/Catalogue/ActEntry.cs
new file mode 100644
index 0000000..80cbd64
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/ActEntry.cs
@@ -0,0 +1,119 @@
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class ActEntry
+ {
+ /// "Ate/WakeUp" or "Ate/@hardDrugs".
+ public string key;
+
+ public string categoryId;
+
+ /// The def's defName, or the group id with its "@".
+ public string name;
+
+ /// The def of a single entry; null for a group.
+ public Def def;
+
+ /// The group of a group entry; null for a single def.
+ public ActGroup group;
+
+ /// What the picker and the row show.
+ public string label;
+
+ /// "Core", the DLC's name or the mod's name.
+ public string sourceMod;
+
+ /// The source's package id, lower case.
+ public string sourcePackageId;
+
+ /// Break entries: a planning stage (always, for a break).
+ public bool hasPlanning;
+
+ /// A did-it stage: every entry outside the breaks, and a break with a link.
+ public bool hasDidIt = true;
+
+ /// A break hostile to the colony (berserk): no Subdue. For a group: every member is hostile.
+ public bool hostileBreak;
+
+ /// A drug binge entry: rows keep a drug option.
+ public bool hasDrugOption;
+
+ /// Break entries: the links of the entry's breaks (one for a def, the distinct links of its members for a group).
+ public List links = new List();
+
+ public bool IsGroup => group != null;
+
+ public bool IsBreak => categoryId == ActCategories.Break;
+
+ /// Rank for "the most specific row wins": a single def 3, a group 2, the category's "any" 1.
+ public int Rank => def != null ? 3 : group != null && !group.IsAny ? 2 : 1;
+
+ /// The stages the entry offers, planning first.
+ public IEnumerable Stages
+ {
+ get
+ {
+ if (hasPlanning)
+ yield return LawStage.Planning;
+ if (hasDidIt)
+ yield return LawStage.DidIt;
+ }
+ }
+
+ public bool HasStage(LawStage stage) => stage == LawStage.Planning ? hasPlanning : hasDidIt;
+
+ /// The stage a new row gets.
+ public LawStage FirstStage => hasPlanning ? LawStage.Planning : LawStage.DidIt;
+
+ /// Whether the act is this entry's: the same def, or a member of the group.
+ 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 -------------------------------------------------
+
+ /// A single-def entry with the def's label and source mod.
+ 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),
+ };
+ }
+
+ /// A group entry. Groups are Laws' own, so their source is Core.
+ 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 + ")";
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/ActGroup.cs b/Source/BlaxLaws/Catalogue/ActGroup.cs
new file mode 100644
index 0000000..bd19626
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/ActGroup.cs
@@ -0,0 +1,79 @@
+using System;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public abstract class ActGroup
+ {
+ /// The category id.
+ public string categoryId;
+
+ /// The group id with its "@" (ActGroups), unique within the category.
+ public string id;
+
+ /// The Keyed key of the label ("BlaxLaws_Group_hardDrugs").
+ public string labelKey;
+
+ ///
+ /// Def entries of the category this group covers, set by ActCatalogue.Build. "The smaller group wins"
+ /// when two groups match one act.
+ ///
+ public int size;
+
+ public string Key => ActKey.OfGroup(categoryId, id);
+
+ /// The category's "any": every entry. The least specific row.
+ public bool IsAny => id == ActGroups.Any;
+
+ /// The check needs the thing itself (ActEvent.facts or thing), not only the def.
+ public virtual bool DependsOnThing => false;
+
+ public virtual string Label => labelKey.NullOrEmpty() ? id : labelKey.Translate().ToString();
+
+ ///
+ /// 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.
+ ///
+ public abstract bool MatchesDef(Def def);
+
+ /// Whether the act belongs to the group. Default: its def does.
+ public virtual bool Matches(ActEvent act) => IsAny || (act?.def != null && MatchesDef(act.def));
+ }
+
+ /// A group from two predicates, for the catalogue package's group lists.
+ public sealed class PredicateGroup : ActGroup
+ {
+ private readonly Func defPredicate;
+ private readonly Func actPredicate;
+
+ /// Null for a def-level group; set for a group that reads the thing.
+ public PredicateGroup(string categoryId, string id, string labelKey, Func defPredicate, Func 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs b/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs
new file mode 100644
index 0000000..1c6efed
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs
@@ -0,0 +1,18 @@
+using RimWorld;
+
+namespace BlaxLaws
+{
+ /// The special acts of the first release (Defs/BlaxLaws_Acts.xml), for the hooks that file them.
+ [DefOf]
+ public static class BlaxLawsActDefOf
+ {
+ public static ActDef SetFire;
+ public static ActDef DisplayedCorpse;
+ public static ActDef StartedSocialFight;
+
+ static BlaxLawsActDefOf()
+ {
+ DefOfHelper.EnsureInitializedInCtor(typeof(BlaxLawsActDefOf));
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/CatalogueDefs.cs b/Source/BlaxLaws/Catalogue/CatalogueDefs.cs
new file mode 100644
index 0000000..1e79cc2
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/CatalogueDefs.cs
@@ -0,0 +1,230 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class ActCategoryDef : Def
+ {
+ public Type workerClass = typeof(ActCategoryWorker);
+
+ /// Picker order; lower first.
+ public int order;
+
+ /// Def names the worker adds beyond its rule (Berserk for the breaks).
+ public List include = new List();
+
+ /// Def names the worker leaves out (animal and baby states, faction-level events).
+ public List exclude = new List();
+
+ ///
+ /// 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.
+ ///
+ public List hostileStateClasses = new List();
+
+ [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 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";
+ }
+ }
+
+ ///
+ /// 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/<defName>", so it never changes. Its
+ /// hook files it with an ActEvent whose def is this ActDef.
+ ///
+ public class ActDef : Def
+ {
+ public Type workerClass = typeof(ActWorker);
+
+ /// Picker order inside "Special acts"; lower first, then A to Z.
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ public class ActWorker
+ {
+ public ActDef def;
+
+ /// The tooltip the lawbook row shows, saying who counts as the offender. Default: the def's description.
+ public virtual string RowTooltip => def?.description;
+ }
+
+ ///
+ /// 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.
+ ///
+ public class BreakLinkDef : Def
+ {
+ /// The mental state class, subclasses included.
+ public Type stateClass;
+
+ /// The linked act's key in another category: a single def ("Special/SetFire") or a group ("Ate/@anyDrug").
+ public string act;
+
+ /// The row's drug option filters the act (drug binges).
+ public bool usesDrugOption;
+
+ public override IEnumerable 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";
+ }
+ }
+
+ /// Resolves the link of a mental state: the most derived linked class wins.
+ public static class BreakLinks
+ {
+ private static readonly Dictionary byClass = new Dictionary();
+ private static readonly Dictionary hostileByClass = new Dictionary();
+
+ /// The link for a break, or null when its class has none (Planning only).
+ 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.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;
+ }
+
+ ///
+ /// 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).
+ ///
+ 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);
+ }
+
+ /// A state hostile to the colony by its class (berserk), from the Break category's hostileStateClasses.
+ 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.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;
+ }
+
+ /// Drops the caches (tests that add a link at runtime).
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/CatalogueGroups.cs b/Source/BlaxLaws/Catalogue/CatalogueGroups.cs
new file mode 100644
index 0000000..29c8e57
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/CatalogueGroups.cs
@@ -0,0 +1,125 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// The group entries of each category, in picker order (design: "Act catalogue and detection", the Groups
+ /// column). Labels are Keyed "BlaxLaws_Group_<id without @>"; the "any" group of a category is
+ /// "BlaxLaws_Group_any<Category>", 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".
+ ///
+ 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;
+
+ /// Any break, any drug binge, any tantrum, any insulting spree, any aggressive break.
+ public static IEnumerable 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ public static IEnumerable 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));
+ }
+
+ /// Insult or slight: the two vanilla defs and any interaction whose worker is theirs or derives from it.
+ public static IEnumerable Interaction(string cat)
+ {
+ yield return DefGroup(cat, ActGroups.InsultOrSlight, IsInsultOrSlight);
+ }
+
+ /// Any surgery (RecipeDef.IsSurgery, Verse/RecipeDef.cs:362).
+ public static IEnumerable 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 pred) => new PredicateGroup(cat, id, LabelKey(id), pred);
+
+ private static ActGroup ThingGroup(string cat, string id, ActFacts fact, Func could) =>
+ new PredicateGroup(cat, id, LabelKey(id), could, act => (FoodFacts.Of(act) & fact) != 0);
+ }
+
+ ///
+ /// 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.
+ ///
+ public sealed class CatalogueAnyGroup : ActGroup
+ {
+ private HashSet 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();
+ 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);
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/CatalogueRules.cs b/Source/BlaxLaws/Catalogue/CatalogueRules.cs
new file mode 100644
index 0000000..5b18f5c
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/CatalogueRules.cs
@@ -0,0 +1,210 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class CatalogueRules
+ {
+ ///
+ /// 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.
+ ///
+ public static readonly string[] BreakInclude =
+ {
+ "Berserk", "BerserkPermanent", "BerserkWarcall", "BerserkTrance", "WanderConfused", "Wander_Psychotic_Short",
+ "CubeSculpting", "Terror",
+ };
+
+ ///
+ /// 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.
+ ///
+ public static readonly string[] BreakExclude =
+ {
+ "Manhunter", "ManhunterPermanent", "ManhunterBloodRain", "Roaming", "CocoonDisturbed", "BerserkMechanoid",
+ "Crying", "Giggling", "SocialFighting", "PanicFlee",
+ };
+
+ ///
+ /// 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).
+ ///
+ 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 breakExclude = new HashSet(BreakExclude);
+ private static readonly HashSet recordedActExclude = new HashSet(RecordedActExclude);
+
+ /// A def name the built-in list or the category's XML list leaves out.
+ 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 ---------------------------------------------------------
+
+ ///
+ /// Ate: anything with an ingestible a colonist can eat or drink. Plants (grazing) and the corpses of
+ /// races without flesh (mechanoids) are left out.
+ ///
+ 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;
+ }
+
+ /// Used: a ThingDef whose comps hold a CompProperties_Usable (subclasses included).
+ 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;
+ }
+
+ /// Records: Int and Float records count acts; Time records count time.
+ public static bool CountsActs(RecordDef def) => def != null && (def.type == RecordType.Int || def.type == RecordType.Float);
+
+ // ---- building entries ----------------------------------------------------------------
+
+ ///
+ /// 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).
+ ///
+ public static List EntriesFor(ActCategoryDef cat, IEnumerable byRule, IEnumerable builtInInclude = null) where T : Def
+ {
+ var defs = new List();
+ var seen = new HashSet();
+ 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.GetNamedSilentFail(name));
+ }
+ if (cat?.include != null)
+ {
+ foreach (string name in cat.include)
+ Take(DefDatabase.GetNamedSilentFail(name));
+ }
+
+ var entries = new List(defs.Count);
+ foreach (T d in defs)
+ entries.Add(ActEntry.ForDef(cat.defName, d));
+ Disambiguate(entries);
+ return entries;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static void Disambiguate(List entries)
+ {
+ var byLabel = new Dictionary>(StringComparer.OrdinalIgnoreCase);
+ foreach (ActEntry e in entries)
+ {
+ if (e?.def == null || e.label == null)
+ continue;
+ if (!byLabel.TryGetValue(e.label, out List same))
+ byLabel[e.label] = same = new List();
+ same.Add(e);
+ }
+ foreach (List 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);
+ }
+ }
+ }
+
+ /// "Binging_DrugExtreme" to "Binging Drug Extreme".
+ 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();
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/FoodFacts.cs b/Source/BlaxLaws/Catalogue/FoodFacts.cs
new file mode 100644
index 0000000..195d30d
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/FoodFacts.cs
@@ -0,0 +1,178 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class FoodFacts
+ {
+ /// The facts of a real thing. Falls back to the def when the thing can't be read.
+ 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;
+ }
+
+ /// The facts a def alone gives: no ingredients, a corpse's race from its def.
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+
+ /// The food can hold ingredients (meals, pemmican), so a thing of it may hold meat.
+ public static bool HasIngredients(ThingDef def) => def?.GetCompProperties() != null;
+
+ /// Human meat or a humanlike corpse, by the def.
+ 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;
+ }
+
+ /// Insect meat or an insect corpse, by the def.
+ 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;
+ }
+ }
+
+ /// Drugs as the drug binge and its option see them.
+ public static class DrugInfo
+ {
+ private static Dictionary chemicalCategory;
+
+ /// The chemical a drug def's CompProperties_Drug names, or null.
+ public static ChemicalDef ChemicalOf(ThingDef def) => def?.GetCompProperties()?.chemical;
+
+ /// The drug category of a def; None for anything that isn't a drug.
+ public static DrugCategory CategoryOf(ThingDef def) => def?.ingestible?.drugCategory ?? DrugCategory.None;
+
+ ///
+ /// The strongest category among the drugs carrying the chemical (wake-up: Hard; alcohol: Social), or
+ /// None when no loaded drug carries it.
+ ///
+ public static DrugCategory CategoryOfChemical(ChemicalDef chemical)
+ {
+ if (chemical == null)
+ return DrugCategory.None;
+ if (chemicalCategory == null)
+ {
+ var map = new Dictionary();
+ foreach (ThingDef t in DefDatabase.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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs b/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs
new file mode 100644
index 0000000..92a00b4
--- /dev/null
+++ b/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs
@@ -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.
+
+ ///
+ /// 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.
+ ///
+ public class ActCategoryWorker_Break : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries()
+ {
+ var list = CatalogueGroups.Break(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
+ IEnumerable fromBreaks = DefDatabase.AllDefsListForReading.Select(b => b.mentalState).Where(s => s != null);
+ list.AddRange(CatalogueRules.EntriesFor(def, fromBreaks, CatalogueRules.BreakInclude));
+ return list;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ public class ActCategoryWorker_Ate : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries()
+ {
+ var list = CatalogueGroups.Ate(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
+ list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.IsEdible)));
+ return list;
+ }
+ }
+
+ /// Used: every ThingDef with a CompProperties_Usable (psytrainers, neurotrainers, mech serums, modded usables). No groups.
+ public class ActCategoryWorker_Used : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries() =>
+ CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.IsUsable));
+ }
+
+ /// Social interactions: every InteractionDef. Group: insult or slight.
+ public class ActCategoryWorker_Interaction : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries()
+ {
+ var list = CatalogueGroups.Interaction(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
+ list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading));
+ return list;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ public class ActCategoryWorker_RecordedAct : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries() =>
+ CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading);
+ }
+
+ /// Records: every RecordDef with type Int or Float; Time records count time, not acts. No groups.
+ public class ActCategoryWorker_Record : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries() =>
+ CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.CountsActs));
+ }
+
+ /// Bills: every RecipeDef. Group: any surgery.
+ public class ActCategoryWorker_Bill : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries()
+ {
+ var list = CatalogueGroups.Bill(def.defName).Select(g => ActEntry.ForGroup(g)).ToList();
+ list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading));
+ return list;
+ }
+ }
+
+ /// Special acts: every ActDef (Defs/BlaxLaws_Acts.xml), by order then A to Z. No groups.
+ public class ActCategoryWorker_Special : ActCategoryWorker
+ {
+ public override IEnumerable MakeEntries() =>
+ CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.OrderBy(a => a.order).ThenBy(a => a.label ?? a.defName));
+ }
+}
diff --git a/Source/BlaxLaws/Compat.cs b/Source/BlaxLaws/Compat.cs
new file mode 100644
index 0000000..f84d0d2
--- /dev/null
+++ b/Source/BlaxLaws/Compat.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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).
+ ///
+ 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";
+
+ ///
+ /// Package ids tests treat as active. Only tests write it; the runner clears it after every test.
+ ///
+ public static readonly HashSet SimulatedActive = new HashSet(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+}
diff --git a/Source/BlaxLaws/Detection/DetectionHooks.cs b/Source/BlaxLaws/Detection/DetectionHooks.cs
new file mode 100644
index 0000000..946166e
--- /dev/null
+++ b/Source/BlaxLaws/Detection/DetectionHooks.cs
@@ -0,0 +1,72 @@
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class DetectionHooks
+ {
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// A building whose def is a table (Verse/ThingDef.cs:1008) stands on the thing's cell.
+ public static bool OnTable(Thing thing)
+ {
+ if (thing == null || !thing.Spawned || thing.Map == null)
+ return false;
+ List 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;
+ }
+
+ /// The corpse lies in a grave or sarcophagus (Verse.AI/CorpseObsessionMentalStateUtility.cs:46).
+ public static bool InGrave(Corpse corpse) => corpse?.ParentHolder is Building_Grave;
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_A_MentalState.cs b/Source/BlaxLaws/Detection/Hook_A_MentalState.cs
new file mode 100644
index 0000000..549cb36
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_A_MentalState.cs
@@ -0,0 +1,99 @@
+using System;
+using System.Runtime.CompilerServices;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch(typeof(MentalStateHandler), nameof(MentalStateHandler.TryStartMentalState))]
+ public static class Patch_MentalStateHandler_TryStartMentalState
+ {
+ public const string Where = "hook A, MentalStateHandler.TryStartMentalState";
+
+ ///
+ /// 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).
+ ///
+ 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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_C_Ingested.cs b/Source/BlaxLaws/Detection/Hook_C_Ingested.cs
new file mode 100644
index 0000000..8013356
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_C_Ingested.cs
@@ -0,0 +1,86 @@
+using System;
+using System.Runtime.CompilerServices;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch(typeof(Thing), nameof(Thing.Ingested))]
+ public static class Patch_Thing_Ingested
+ {
+ public const string Where = "hook C, Thing.Ingested";
+
+ /// What the prefix hands to the postfix. A struct: an empty book allocates nothing.
+ 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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs b/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs
new file mode 100644
index 0000000..0bffab1
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs
@@ -0,0 +1,84 @@
+using System;
+using System.Runtime.CompilerServices;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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).
+ ///
+ [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);
+ }
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs b/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs
new file mode 100644
index 0000000..5f89370
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs
@@ -0,0 +1,171 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [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);
+ }
+ }
+ }
+
+ ///
+ /// 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).
+ ///
+ [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);
+ }
+ }
+ }
+
+ ///
+ /// 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).
+ ///
+ [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);
+ }
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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 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 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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs b/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs
new file mode 100644
index 0000000..378877a
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs
@@ -0,0 +1,123 @@
+using System;
+using System.Runtime.CompilerServices;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [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);
+ }
+ }
+ }
+
+ ///
+ /// 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).
+ ///
+ [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 seen = new ConditionalWeakTable();
+
+ 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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs b/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs
new file mode 100644
index 0000000..3baa790
--- /dev/null
+++ b/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs
@@ -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
+{
+ ///
+ /// 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.
+ ///
+ [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 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);
+ }
+ }
+
+ /// Balances the depth count even when UsedBy throws. Returns void, so other mods' stack traces stay whole.
+ public static void Finalizer(int __state)
+ {
+ if (__state != 0 && depth > 0)
+ depth--;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/DlcSupport.cs b/Source/BlaxLaws/DlcSupport.cs
new file mode 100644
index 0000000..ca9ec24
--- /dev/null
+++ b/Source/BlaxLaws/DlcSupport.cs
@@ -0,0 +1,117 @@
+using System;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.<DLC>Active. ModLister.Check<DLC> is an install check, not an
+ /// active check, and is never used.
+ ///
+ public static class DlcSupport
+ {
+ public const string CoreName = "Core";
+ public const string CorePackageId = "ludeon.rimworld";
+ private const string OfficialPrefix = "ludeon.rimworld.";
+
+ /// The official DLCs by name, in release order.
+ public static readonly string[] DlcNames = { "Royalty", "Ideology", "Biotech", "Anomaly", "Odyssey" };
+
+ // ---- where a def comes from ---------------------------------------------------------
+
+ /// "Core", the DLC's name ("Ideology") or the mod's name, as the catalogue shows it.
+ 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;
+ }
+
+ /// The package id a catalogue entry saves with a row, lower case. Core for a def without a mod.
+ public static string SourcePackageId(ModContentPack mod) => mod?.PackageId ?? CorePackageId;
+
+ /// True for "ludeon.rimworld.royalty" and the other official DLCs, false for Core and mods.
+ public static bool IsDlcPackageId(string packageId) =>
+ !packageId.NullOrEmpty() && packageId.ToLowerInvariant().StartsWith(OfficialPrefix);
+
+ /// "ludeon.rimworld.royalty" to "Royalty".
+ 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();
+ }
+
+ ///
+ /// The official DLC a saved row's source names, by package id or by name ("Ideology"), or null for
+ /// Core and mods.
+ ///
+ 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;
+ }
+
+ /// Whether the official DLC of this name is active. False for an unknown name.
+ 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;
+ }
+ }
+
+ /// "Needs Ideology".
+ public static string NeedsText(string dlcName) => "BlaxLaws_NeedsDlc".Translate(dlcName);
+
+ ///
+ /// What a row whose entry is missing shows: "Needs <DLC>" for a DLC source, else
+ /// "Missing: <mod>" (design: "A missing entry from a DLC shows Needs <DLC>").
+ ///
+ 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 ------------------------------
+
+ /// A slave (Ideology).
+ public static bool IsSlave(Pawn p) => ModsConfig.IdeologyActive && p != null && p.IsSlave;
+
+ /// A child, never beaten (Biotech).
+ public static bool IsChild(Pawn p) => ModsConfig.BiotechActive && p != null && p.DevelopmentalStage.Child();
+
+ /// Holds an ideoligion role, which an arrest takes (Ideology; Precept_Role.cs:582-585).
+ public static bool HoldsRole(Pawn p) => ModsConfig.IdeologyActive && p?.Ideo != null && p.Ideo.GetRole(p) != null;
+
+ /// A mechanitor that controls mechs, which an arrest shuts down (Biotech; Pawn_GuestTracker.cs:536-539).
+ public static bool IsMechanitorWithMechs(Pawn p) =>
+ ModsConfig.BiotechActive && p?.mechanitor != null && MechanitorUtility.IsMechanitor(p) && p.mechanitor.ControlledPawns.Count > 0;
+
+ ///
+ /// 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).
+ ///
+ public static bool HeldForArrestNow(Pawn p) => HoldsRole(p) || IsMechanitorWithMechs(p);
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/CaseLetters.cs b/Source/BlaxLaws/Enforcement/CaseLetters.cs
new file mode 100644
index 0000000..05ec48a
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/CaseLetters.cs
@@ -0,0 +1,81 @@
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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").
+ ///
+ 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> sent = new ConditionalWeakTable>();
+
+ /// True the first time per case and kind in this session: one letter per wait, even when a case flips between waits.
+ public static bool Once(LawCase c, string kind)
+ {
+ if (c == null || kind == null)
+ return false;
+ return sent.GetOrCreateValue(c).Add(kind);
+ }
+
+ /// Sends the letter when "Letters for jailings" is on. The keys take the args as {0}, {1}, ...
+ 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);
+ }
+
+ /// A letter when letters are on, else a case message (Messages for cases).
+ 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));
+ }
+
+ ///
+ /// "Jailed: Bob" at the capture: the act, the sentence and the release day. A case message instead
+ /// while "Letters for jailings" is off.
+ ///
+ 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));
+ }
+
+ /// The letter that the case waits because nobody can ever enforce it.
+ public static void NoEnforcer(LawCase c) =>
+ Send(c, "BlaxLaws_LetterNoEnforcerLabel", "BlaxLaws_LetterNoEnforcerText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label);
+ }
+
+ /// Vanilla guilt (Pawn_GuiltTracker.cs:46-61), saved and counted down by the game.
+ public static class Guilt
+ {
+ /// Guilty for at least these ticks. A longer guilt already on the pawn is never shortened.
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/CaseMessages.cs b/Source/BlaxLaws/Enforcement/CaseMessages.cs
new file mode 100644
index 0000000..93148a9
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/CaseMessages.cs
@@ -0,0 +1,31 @@
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class CaseMessages
+ {
+ /// One message when a stage's punishment is dispatched: "Bob broke a law: Wake-up (Did it). Punishment: jail."
+ 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);
+ }
+
+ /// A message about the case, pointing at the offender while it is spawned. Does nothing with messages off.
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/Enforcement.cs b/Source/BlaxLaws/Enforcement/Enforcement.cs
new file mode 100644
index 0000000..d5f637f
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/Enforcement.cs
@@ -0,0 +1,269 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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).
+ ///
+ public static class Enforcement
+ {
+ public const int SweepInterval = 250;
+ public const int SentenceInterval = 2500;
+
+ /// Ticks after the capture the "Maintain only" write lands (design: "Jail for N days").
+ public const int MaintainOnlyDelay = 2;
+
+ private struct Entry
+ {
+ public int caseId;
+ public CaseTask task;
+ public LawStage stage;
+ public int dueTick;
+ }
+
+ private static readonly List queue = new List();
+ private static readonly List due = new List();
+
+ /// Entries waiting. The component's tick returns at once while this is 0 and no case exists.
+ public static int Pending => queue.Count;
+
+ /// Queues the stage's punishment for the next tick.
+ public static void Enqueue(LawCase c, LawStage stage) => Schedule(c, CaseTask.Punish, stage, 1);
+
+ /// Queues a task for the case, delayTicks from now (at least 1).
+ 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) });
+ }
+
+ /// Whether a task for the case is waiting.
+ 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;
+ }
+
+ /// Drops every entry: a new game or a load. Then Refill.
+ public static void Reset() => queue.Clear();
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+ }
+
+ /// One game tick: due entries, then the sweeps.
+ 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);
+ }
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ internal static bool DispatchNow(LawCase c, Func filter)
+ {
+ GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
+ if (c == null || comp == null || queue.Count == 0)
+ return false;
+ List 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())).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;
+ }
+
+ /// Starts the stage's punishment: once per stage, with a message, handing over from an unfinished earlier one.
+ 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);
+ }
+
+ /// The case's running punishment, or null.
+ public static PunishmentDef ActiveOf(LawCase c) =>
+ c == null || c.activePunishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(c.activePunishment);
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+ }
+ }
+
+ /// Every 2500 ticks: the sentence check of each jailed case.
+ 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);
+ }
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/EnforcerJobs.cs b/Source/BlaxLaws/Enforcement/EnforcerJobs.cs
new file mode 100644
index 0000000..d8c0951
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/EnforcerJobs.cs
@@ -0,0 +1,96 @@
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class EnforcerJobs
+ {
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// A subdue, arrest or capture job on this offender.
+ 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;
+ }
+
+ /// The pawn's current job is this def on this target.
+ 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;
+ }
+
+ /// A job of this def on this target waits in the pawn's queue.
+ 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;
+ }
+
+ /// The pawn runs or has queued an Arrest or Capture of the target.
+ 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));
+
+ ///
+ /// 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).
+ ///
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/Enforcers.cs b/Source/BlaxLaws/Enforcement/Enforcers.cs
new file mode 100644
index 0000000..cc10cf2
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/Enforcers.cs
@@ -0,0 +1,208 @@
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+using Verse.AI;
+using Verse.AI.Group;
+
+namespace BlaxLaws
+{
+ /// What the enforcer must be able to do.
+ public enum EnforcerNeed
+ {
+ /// Violence (subdue).
+ Subdue,
+ /// Manipulation (arrest, capture).
+ Arrest,
+ /// Both: "Subdue then jail" beats the pawn down and carries it to the prisoner bed.
+ SubdueAndArrest,
+ }
+
+ ///
+ /// 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.
+ ///
+ public static class Enforcers
+ {
+ private struct Candidate
+ {
+ public Pawn pawn;
+ public bool warden;
+ public float distSq;
+ }
+
+ private static readonly List tmp = new List();
+
+ /// The enforcer for the case, or null when nobody can go now (the case waits for the sweep).
+ public static Pawn Pick(LawCase c, EnforcerNeed need) => Pick(c, need, out _);
+
+ /// The enforcer, or null with WaitReasons.NoEnforcer (nobody able at all) or Busy (nobody free now).
+ 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);
+ }
+
+ /// The pick over the given candidates (the map's free colonists in the game; a fixed list in tests).
+ public static Pawn PickFrom(LawCase c, EnforcerNeed need, IEnumerable 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;
+ }
+
+ ///
+ /// 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".
+ ///
+ 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;
+ }
+
+ /// Free to be sent now (see the class summary). A job of this case's own enforcement counts as free.
+ 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);
+ }
+
+ ///
+ /// A job Laws never pulls a pawn off: player-forced, not casually interruptible, fleeing, or surgery.
+ ///
+ 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;
+ }
+
+ /// Warden work is active for the pawn (and not disabled).
+ public static bool IsWarden(Pawn p) =>
+ p?.workSettings != null && p.workSettings.EverWork && !p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) &&
+ p.workSettings.WorkIsActive(WorkTypeDefOf.Warden);
+
+ ///
+ /// 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).
+ ///
+ public static bool DangerBlocks(Pawn offender)
+ {
+ if (offender == null || !offender.Spawned || offender.Map == null)
+ return false;
+ return GenHostility.AnyHostileActiveThreatToPlayer(offender.Map) || PawnUtility.EnemiesAreNearby(offender);
+ }
+
+ ///
+ /// 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).
+ ///
+ public static bool FightsBack(Pawn p) => p?.MentalState != null && p.MentalState.ForceHostileTo(Faction.OfPlayer);
+
+ ///
+ /// 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).
+ ///
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs b/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs
new file mode 100644
index 0000000..7e94625
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs
@@ -0,0 +1,168 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class JobDriver_Subdue : JobDriver
+ {
+ public const int HitIntervalTicks = 90;
+ public const int MaxHits = 40;
+ public const int PainlessHitsToStop = 3;
+
+ /// A hit is painful when PainTotal rises by at least this share of the injury's own pain.
+ public const float PainShare = 0.25f;
+
+ private int lastHitTick = -1000000;
+ private int hits;
+ private int painlessHits;
+ private LawCase lawCase;
+
+ private static readonly List memoriesBefore = new List();
+ private static readonly List agesBefore = new List();
+
+ public Pawn Target => job?.GetTarget(TargetIndex.A).Thing as Pawn;
+
+ /// Hits dealt so far.
+ public int Hits => hits;
+
+ /// The job reserves nothing, so no reservation list ever refers to it.
+ public override bool TryMakePreToilReservations(bool errorOnFailed) => true;
+
+ public override void Notify_Starting()
+ {
+ base.Notify_Starting();
+ lawCase = SubdueFlow.CaseFor(pawn, Target);
+ }
+
+ protected override IEnumerable 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);
+ }
+ }
+ }
+
+ /// The memories of the recovery thought the target has before the hit, with their ages.
+ private static void RememberMemories(Pawn target, ThoughtDef def)
+ {
+ memoriesBefore.Clear();
+ agesBefore.Clear();
+ List 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);
+ }
+ }
+ }
+
+ /// Removes the recovery memory the downing gave, and puts back the age of one it only renewed.
+ private static void DropNewMemories(Pawn target, ThoughtDef def)
+ {
+ MemoryThoughtHandler handler = target.needs?.mood?.thoughts?.memories;
+ if (handler == null)
+ return;
+ List 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();
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/PunishmentDef.cs b/Source/BlaxLaws/Enforcement/PunishmentDef.cs
new file mode 100644
index 0000000..1997b2f
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/PunishmentDef.cs
@@ -0,0 +1,108 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class PunishmentDef : Def
+ {
+ public Type workerClass = typeof(PunishmentWorker);
+
+ /// Dropdown order; lower first.
+ public int order;
+
+ /// The row's Days field applies (Guilty, Jail, Subdue then jail).
+ public bool usesDays;
+
+ ///
+ /// Never replaces or stops what a case already runs, and never becomes the case's active punishment
+ /// (Warn, Guilty: "Warn and Guilty run alongside").
+ ///
+ public bool runsAlongside;
+
+ public List fits = new List();
+
+ [Unsaved]
+ private PunishmentWorker workerInt;
+
+ public PunishmentWorker Worker
+ {
+ get
+ {
+ if (workerInt == null)
+ {
+ workerInt = (PunishmentWorker)Activator.CreateInstance(workerClass ?? typeof(PunishmentWorker));
+ workerInt.def = this;
+ }
+ return workerInt;
+ }
+ }
+
+ /// The entry kind and stage a row has, as fits names them.
+ 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 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";
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ public class PunishmentWorker
+ {
+ public PunishmentDef def;
+
+ ///
+ /// 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.
+ ///
+ public virtual void Start(LawCase c, Law law, LawStage stage)
+ {
+ }
+
+ ///
+ /// 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.
+ ///
+ public virtual void Sweep(LawCase c)
+ {
+ }
+
+ /// Every 2500 ticks while the case is Jailed under this punishment: the sentence check.
+ public virtual void SentenceSweep(LawCase c)
+ {
+ }
+
+ /// Ends this punishment's running job, because a later stage takes over or the law was deleted. Keeps LawCase.enforcer.
+ public virtual void Stop(LawCase c)
+ {
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs
new file mode 100644
index 0000000..4e1edb2
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs
@@ -0,0 +1,24 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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".
+ ///
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs
new file mode 100644
index 0000000..67c48ca
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs
@@ -0,0 +1,102 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs
new file mode 100644
index 0000000..af19247
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs
@@ -0,0 +1,93 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Down already, the break over, a live break that fights back, or a child: jail without a beating.
+ private static bool JailsWithoutBeating(LawCase c)
+ {
+ Pawn o = c.offender;
+ return o.Downed || DlcSupport.IsChild(o) || Enforcers.FightsBack(o) || !SubdueFlow.InBreak(c);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs
new file mode 100644
index 0000000..64eae3b
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs
@@ -0,0 +1,20 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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".
+ ///
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/SubdueFlow.cs b/Source/BlaxLaws/Enforcement/SubdueFlow.cs
new file mode 100644
index 0000000..77d31aa
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/SubdueFlow.cs
@@ -0,0 +1,491 @@
+using System.Collections.Generic;
+using RimWorld;
+using UnityEngine;
+using Verse;
+using Verse.AI;
+using Verse.Sound;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class SubdueFlow
+ {
+ ///
+ /// 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).
+ ///
+ 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;
+ }
+
+ /// The case's enforcer runs the subdue job on the offender right now.
+ public static bool Runs(LawCase c) =>
+ c?.enforcer != null && c.offender != null && EnforcerJobs.Runs(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender);
+
+ /// The open case whose subdue this enforcer carries out on this target, or null.
+ public static LawCase CaseFor(Pawn enforcer, Pawn target)
+ {
+ GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
+ if (comp == null || enforcer == null || target == null)
+ return null;
+ IReadOnlyList 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;
+ }
+
+ /// "Subdue" or "Subdue then jail".
+ public static bool IsSubduePunishment(string defName) =>
+ defName != null && (defName == BlaxLawsDefOf.Subdue?.defName || defName == BlaxLawsDefOf.SubdueThenJail?.defName);
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Ends the running subdue job of the case, if any. Keeps the enforcer for a hand-over.
+ public static void End(LawCase c)
+ {
+ if (c?.enforcer != null && c.offender != null)
+ EnforcerJobs.End(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender);
+ }
+
+ ///
+ /// 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.
+ ///
+ public static bool CallOffInDanger(LawCase c)
+ {
+ if (!Runs(c) || !Enforcers.DangerBlocks(c.offender))
+ return false;
+ End(c);
+ WaitReasons.Set(c, WaitReasons.Danger);
+ return true;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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));
+ }
+
+ /// Closes the case as Warned with a message saying why it wasn't a subdue.
+ 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);
+ }
+
+ ///
+ /// 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").
+ ///
+ 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");
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+ }
+
+ ///
+ /// 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).
+ ///
+ public static class SubdueHits
+ {
+ public const float MinDamage = 4f;
+ public const float MaxDamage = 8f;
+
+ /// A part keeps at least this share of its HP.
+ public const float KeepHealthShare = 0.5f;
+
+ /// The pawn's injuries stay at or below this share of the injury sum that kills it.
+ public const float LethalShare = 0.9f;
+
+ public const float MeleeXpPerHit = 40f;
+
+ private static readonly List parts = new List();
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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).
+ ///
+ public static float DamageFactor(Pawn target, DamageInfo dinfo)
+ {
+ float factor = 1f;
+ List 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;
+ }
+
+ ///
+ /// 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).
+ ///
+ 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 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
+ }
+ }
+
+ /// A part of the torso or the limbs the subdue may ever hit (see the class 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);
+ }
+
+ /// The part sits in the head: in the FullHead or UpperHead group, or in the brain's branch below the core part (the neck).
+ 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;
+ }
+
+ /// HP the part may still lose and keep its share: current HP minus half the maximum.
+ public static float Headroom(Pawn target, BodyPartRecord part) => PartHealth(target, part) - Floor(target, part);
+
+ ///
+ /// 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).
+ ///
+ public static float RoomToLive(Pawn target)
+ {
+ float sum = 0f;
+ List 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;
+ }
+
+ /// The HP the part always keeps: half its maximum (BodyPartDef.cs:138-141, scaled by the pawn's health scale).
+ public static float Floor(Pawn target, BodyPartRecord part) => part.def.GetMaxHealth(target) * KeepHealthShare;
+
+ ///
+ /// 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.
+ ///
+ public static float PartHealth(Pawn target, BodyPartRecord part)
+ {
+ float hp = part.def.GetMaxHealth(target);
+ List 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);
+ }
+
+ /// The part's ancestor right below the core part (the core part itself for the core).
+ private static BodyPartRecord TopBranch(BodyPartRecord part)
+ {
+ BodyPartRecord p = part;
+ while (p.parent != null && p.parent.parent != null)
+ p = p.parent;
+ return p;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs b/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs
new file mode 100644
index 0000000..034576f
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs
@@ -0,0 +1,104 @@
+using System;
+using HarmonyLib;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Enforcement/WaitReasons.cs b/Source/BlaxLaws/Enforcement/WaitReasons.cs
new file mode 100644
index 0000000..9f2ba20
--- /dev/null
+++ b/Source/BlaxLaws/Enforcement/WaitReasons.cs
@@ -0,0 +1,77 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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").
+ ///
+ public static class WaitReasons
+ {
+ /// Hostiles threaten the offender's map (a raid, a berserk colonist): nobody is sent.
+ public const string Danger = "BlaxLaws_Wait_Danger";
+
+ /// Nobody on the map can ever enforce it (no warden in "Wardens only", nobody able): the player has to act.
+ public const string NoEnforcer = "BlaxLaws_Wait_NoEnforcer";
+
+ /// Enforcers exist but none is free now (asleep, on a rescue, in a ritual, out of reach).
+ public const string Busy = "BlaxLaws_Wait_Busy";
+
+ /// No prisoner bed the enforcer can take the offender to.
+ public const string NoBed = "BlaxLaws_Wait_NoBed";
+
+ /// Someone else holds the offender or the bed (a doctor's rescue): the arrest waits, no reservation error.
+ public const string Reserved = "BlaxLaws_Wait_Reserved";
+
+ /// The offender's break is hostile to the colony (berserk): the arrest waits until it ends or the pawn is down.
+ public const string HostileBreak = "BlaxLaws_Wait_HostileBreak";
+
+ /// A role holder or a mechanitor with mechs: Laws doesn't arrest it on its own; "Arrest now" does.
+ public const string Hold = "BlaxLaws_Wait_Hold";
+
+ /// The offender isn't on a map (carried, in a caravan).
+ public const string Away = "BlaxLaws_Wait_Away";
+
+ /// The reason's text, or "" for none.
+ public static string Label(string reason)
+ {
+ if (reason.NullOrEmpty())
+ return "";
+ return reason.CanTranslate() ? reason.Translate().ToString() : reason;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+ }
+
+ ///
+ /// Outcome keys of this package beside CaseOutcomes. Saved as strings; the label is
+ /// "BlaxLaws_Outcome_" + key (CaseOutcomes.Label), from BlaxLaws_Enforcement.xml.
+ ///
+ public static class EnforcementOutcomes
+ {
+ /// The subdue gave up: three hits in a row caused no pain (go-juice, painkillers, every part at its cap).
+ public const string NotSubdued = "NotSubdued";
+
+ /// A jailed pawn left the map before its sentence was served.
+ public const string Escaped = "Escaped";
+
+ /// A jailed pawn died.
+ public const string Died = "Died";
+
+ /// The offender became a prisoner some other way (arrested by hand, another mod): Laws never touches it.
+ public const string AlreadyPrisoner = "AlreadyPrisoner";
+ }
+}
diff --git a/Source/BlaxLaws/GameComponent_BlaxLaws.cs b/Source/BlaxLaws/GameComponent_BlaxLaws.cs
new file mode 100644
index 0000000..636f9d3
--- /dev/null
+++ b/Source/BlaxLaws/GameComponent_BlaxLaws.cs
@@ -0,0 +1,359 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class GameComponent_BlaxLaws : GameComponent
+ {
+ private List laws = new List();
+ private int nextLawId = 1;
+ private List cases = new List();
+ private int nextCaseId = 1;
+
+ /// A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick.
+ private int saveToken;
+
+ // Not saved: cases by offender, rebuilt on load and kept on every add and prune.
+ private readonly Dictionary> byOffender = new Dictionary>();
+
+ // Weak, so the main menu never keeps the last game and its pawns alive.
+ private static readonly System.WeakReference cached = new System.WeakReference(null);
+ private static readonly System.WeakReference cachedGame = new System.WeakReference(null);
+
+ private static readonly List EmptyCases = new List();
+
+ public GameComponent_BlaxLaws()
+ {
+ }
+
+ /// Called by the game for a new game and for a loaded one, before anything of the save is read.
+ 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);
+ }
+
+ /// The component of the running game, or null when no game is loaded.
+ 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();
+ 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 ---------------------------------------------------------------------------
+
+ /// The lawbook rows in display order. Do not change the list; use Lawbook.
+ public IReadOnlyList Laws => laws;
+
+ /// Every case, oldest first. Do not change the list.
+ public IReadOnlyList 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;
+ }
+
+ /// The cases filed against this pawn, oldest first. Empty for null or a pawn without cases.
+ public IReadOnlyList CasesOf(Pawn pawn)
+ {
+ if (pawn != null && byOffender.TryGetValue(pawn, out List list))
+ return list;
+ return EmptyCases;
+ }
+
+ /// True while any case isn't closed. The tick's fast path reads it.
+ public bool AnyOpenCase
+ {
+ get
+ {
+ for (int i = cases.Count - 1; i >= 0; i--)
+ {
+ if (!cases[i].IsClosed)
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /// The cases that aren't closed, as a new list (safe to change cases while walking it).
+ public List OpenCases()
+ {
+ var result = new List();
+ foreach (LawCase c in cases)
+ {
+ if (!c.IsClosed)
+ result.Add(c);
+ }
+ return result;
+ }
+
+ /// Open cases a row runs for, for "deleting a law with open cases asks first and names the count".
+ 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;
+ }
+
+ ///
+ /// The pawn's newest case outside a break whose did-it row is this one, open or closed, or null. The
+ /// cooldown reads it.
+ ///
+ public LawCase LatestActCaseOf(Pawn pawn, int lawId)
+ {
+ IReadOnlyList 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;
+ }
+
+ /// Ticks two break start ticks may differ by and still name the same break (MentalState.age moves in steps of 30).
+ public const int BreakStartTolerance = 120;
+
+ /// The pawn's case for this break (same state def, started at the same tick), open or closed, or null.
+ public LawCase BreakCaseOf(Pawn pawn, string stateDefName, int breakStartTick)
+ {
+ if (stateDefName.NullOrEmpty())
+ return null;
+ IReadOnlyList 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);
+ }
+
+ /// Closes the case with a CaseOutcomes key. A closed case is pruned after "Keep closed cases".
+ 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;
+ }
+
+ ///
+ /// Removes closed cases that closed more than the given ticks ago. Returns the number removed.
+ /// Runs on every save with "Keep closed cases".
+ ///
+ 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 list))
+ byOffender[c.offender] = list = new List();
+ 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();
+ }
+
+ /// Missing lists, null entries and ids that would repeat.
+ private void EnsureState()
+ {
+ laws ??= new List();
+ laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty());
+ cases ??= new List();
+ 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();
+ }
+ }
+}
diff --git a/Source/BlaxLaws/HookGuard.cs b/Source/BlaxLaws/HookGuard.cs
new file mode 100644
index 0000000..81d0ba5
--- /dev/null
+++ b/Source/BlaxLaws/HookGuard.cs
@@ -0,0 +1,50 @@
+using System;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class HookGuard
+ {
+ /// Logs the failure once per game under this key and swallows it.
+ public static void Fail(string where, Exception e) => LawsLog.Once(where, e);
+
+ /// Runs the body; a throw is logged once and swallowed.
+ public static void Run(string where, Action body)
+ {
+ try
+ {
+ body();
+ }
+ catch (Exception e)
+ {
+ Fail(where, e);
+ }
+ }
+
+ /// Runs the body and returns its value; a throw is logged once and gives the fallback.
+ public static T Run(string where, Func body, T fallback)
+ {
+ try
+ {
+ return body();
+ }
+ catch (Exception e)
+ {
+ Fail(where, e);
+ return fallback;
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Lawbook.cs b/Source/BlaxLaws/Lawbook.cs
new file mode 100644
index 0000000..e24c8d6
--- /dev/null
+++ b/Source/BlaxLaws/Lawbook.cs
@@ -0,0 +1,399 @@
+using System.Collections.Generic;
+using System.Linq;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class Lawbook
+ {
+ public const int MinDays = 1;
+ public const int MaxDays = 50;
+
+ private static readonly List NoLaws = new List();
+
+ /// The running game's rows, or an empty list without a game.
+ public static IReadOnlyList Laws => GameComponent_BlaxLaws.Instance?.Laws ?? NoLaws;
+
+ /// The default days of a severity: Minor 1, Moderate 3, Serious 5, Grave 10.
+ 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;
+
+ /// Null, "" and "@any" read as the same option (no option for a non-binge row, any drug for a binge row).
+ public static string NormalizeOption(string option) => option.NullOrEmpty() || option == DrugOptions.Any ? null : option;
+
+ // ---- lookups -------------------------------------------------------------------------
+
+ /// The row with this key, or null.
+ 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;
+ }
+
+ /// The stages an entry offers (planning only for breaks; did it for linked breaks and every other entry).
+ public static IEnumerable StagesOf(ActEntry entry) => entry?.Stages ?? Enumerable.Empty();
+
+ /// Whether the punishment fits the entry and stage (PunishmentDef.fits).
+ public static bool Fits(PunishmentDef punishment, ActEntry entry, LawStage stage) =>
+ punishment != null && entry != null && punishment.Fits(entry, stage);
+
+ /// The punishments a row of this entry and stage offers, in order.
+ public static IEnumerable PunishmentsFor(ActEntry entry, LawStage stage) =>
+ DefDatabase.AllDefsListForReading.Where(p => Fits(p, entry, stage)).OrderBy(p => p.order);
+
+ /// "Needs Ideology" or "Missing: Core" for a row whose entry is missing, else null.
+ public static string MissingText(Law law) => law?.MissingText;
+
+ // ---- writes --------------------------------------------------------------------------
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Adds NewRow(actKey). Returns the new row, or null when a row with that key exists (Find gives it).
+ public static Law Add(string actKey)
+ {
+ Law law = NewRow(actKey);
+ return TryAdd(law, out _) ? law : null;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Changes a drug binge row's option. Refused when the key exists.
+ 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;
+ }
+
+ /// Changes the row's stage; a punishment that no longer fits resets to Warn. Refused when the key exists.
+ 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;
+ }
+
+ /// Changes the severity. Days move to the new default only while they still equal the old default.
+ 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();
+ }
+
+ /// Changes the punishment. Refused (false) when it doesn't fit the row's entry and stage.
+ 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();
+ }
+
+ /// Moves the row to a new place in the list.
+ 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();
+ }
+
+ /// The open cases a delete would close; the UI names the count and asks first.
+ public static int OpenCaseCount(Law law) => GameComponent_BlaxLaws.Instance?.OpenCaseCount(law) ?? 0;
+
+ /// Deletes the row. Its open cases close as "law repealed". Returns how many closed.
+ 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.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 -----------------------------------------------------------------
+
+ /// One suggested row.
+ 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;
+ }
+ }
+
+ ///
+ /// The seven suggested rows (design: "Defaults I picked"), Core entries only. "Ate: any meat" is left
+ /// out, since most colonies eat meat.
+ ///
+ 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),
+ };
+
+ /// Adds the starter rows that are missing. Returns how many were added (0 when pressed again).
+ 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 ------------------------------------------------------------------------
+
+ ///
+ /// 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.
+ ///
+ public static Law BestRow(ActEvent act, LawStage stage)
+ {
+ if (act == null || act.categoryId == null)
+ return null;
+ IReadOnlyList 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;
+ }
+
+ /// Whether row a (entry ea) is more specific than row b (entry eb).
+ 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;
+ }
+
+ /// Stores the entry's label and source on the row, so a missing entry still shows them.
+ 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";
+ }
+
+ /// After every write: the hot-path cache follows the book.
+ private static void Changed() => Watch.Rebuild();
+ }
+}
diff --git a/Source/BlaxLaws/LawsLog.cs b/Source/BlaxLaws/LawsLog.cs
new file mode 100644
index 0000000..81d8ed0
--- /dev/null
+++ b/Source/BlaxLaws/LawsLog.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Collections.Generic;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class LawsLog
+ {
+ private static readonly HashSet logged = new HashSet();
+
+ /// Logs "[Blax Laws] where failed" with the exception, once per key until the next reset.
+ 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.
+ }
+ }
+
+ /// A one-time message (stand-downs, hints), not an error.
+ public static void MessageOnce(string key, string text)
+ {
+ try
+ {
+ lock (logged)
+ {
+ if (!logged.Add("msg:" + key))
+ return;
+ }
+ Log.Message("[Blax Laws] " + text);
+ }
+ catch
+ {
+ }
+ }
+
+ /// 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).
+ 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();
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ public static class LawsTestHooks
+ {
+ /// CaseFiler.Report throws, to test that a hook's HookGuard keeps vanilla running.
+ public static bool ReportThrows;
+
+ public static void Reset()
+ {
+ ReportThrows = false;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Model/ActEvent.cs b/Source/BlaxLaws/Model/ActEvent.cs
new file mode 100644
index 0000000..97cb499
--- /dev/null
+++ b/Source/BlaxLaws/Model/ActEvent.cs
@@ -0,0 +1,61 @@
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public sealed class ActEvent
+ {
+ /// The category id (ActCategories).
+ public string categoryId;
+
+ /// The def the act is about; see the class summary.
+ public Def def;
+
+ /// Who did it. Filtered by Offenders.IsCovered inside Report.
+ public Pawn offender;
+
+ /// Who it was done to, when there is someone (the insulted pawn, the provoker of a fight).
+ public Pawn victim;
+
+ /// The thing involved (the eaten stack, the used item, the corpse), when there is one. May be destroyed by now.
+ public Thing thing;
+
+ /// The drug's chemical (a dose), or the binge's chosen chemical (hook A on a drug binge).
+ public ChemicalDef chemical;
+
+ /// The drug's category (a dose), or the binge's (MentalState_BingingDrug.drugCategory).
+ public DrugCategory drugCategory;
+
+ /// What the hook read from the thing for thing-level groups (hook C's prefix).
+ public ActFacts facts;
+
+ /// Notes the case takes over (on a table, dug up).
+ public CaseNotes notes;
+
+ /// The live mental state: the new one for a Break report, else null (Report reads the offender's).
+ 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 : "");
+ }
+}
diff --git a/Source/BlaxLaws/Model/ActKey.cs b/Source/BlaxLaws/Model/ActKey.cs
new file mode 100644
index 0000000..4ddfc4d
--- /dev/null
+++ b/Source/BlaxLaws/Model/ActKey.cs
@@ -0,0 +1,164 @@
+using System;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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);
+
+ /// A group key; the id may come with or without its "@".
+ public static string OfGroup(string categoryId, string groupId) =>
+ Of(categoryId, groupId.StartsWith(GroupPrefix) ? groupId : GroupPrefix + groupId);
+
+ /// "Ate" for "Ate/WakeUp", null for a key without a separator.
+ public static string CategoryOf(string key)
+ {
+ if (key.NullOrEmpty())
+ return null;
+ int i = key.IndexOf(Separator);
+ return i <= 0 ? null : key.Substring(0, i);
+ }
+
+ /// "WakeUp" for "Ate/WakeUp", "@humanMeat" for "Ate/@humanMeat", null for a key without a separator.
+ 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;
+ }
+ }
+
+ /// The categories' ids: the defNames of the ActCategoryDefs in Defs/BlaxLaws_Categories.xml.
+ 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 };
+ }
+
+ /// The special acts' ids: the defNames of the ActDefs in Defs/BlaxLaws_Acts.xml.
+ public static class SpecialActs
+ {
+ public const string SetFire = "SetFire";
+ public const string DisplayedCorpse = "DisplayedCorpse";
+ public const string StartedSocialFight = "StartedSocialFight";
+ }
+
+ ///
+ /// 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).
+ ///
+ public static class ActGroups
+ {
+ /// The category's "any": every entry of it. The least specific row.
+ 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";
+ }
+
+ ///
+ /// 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.
+ ///
+ public static class DrugOptions
+ {
+ public const string Any = "@any";
+ public const string Hard = "@hard";
+ public const string Social = "@social";
+
+ /// Null and "" read as Any.
+ public static string Normalize(string option) => option.NullOrEmpty() ? Any : option;
+
+ ///
+ /// The option's rank for "the most specific row wins": one chemical 3, hard or social 2, any 1.
+ ///
+ public static int Rank(string option)
+ {
+ string o = Normalize(option);
+ if (o == Any)
+ return 1;
+ return o == Hard || o == Social ? 2 : 3;
+ }
+
+ /// Whether the dose (or the binge's chosen chemical) in the act counts under the option.
+ 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;
+ }
+
+ /// The option's label: "Any drug", "Hard drugs", "Social drugs" or the chemical's label.
+ 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.GetNamedSilentFail(o);
+ return chem != null ? chem.LabelCap.ToString() : o;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Model/Enums.cs b/Source/BlaxLaws/Model/Enums.cs
new file mode 100644
index 0000000..7dcf5c1
--- /dev/null
+++ b/Source/BlaxLaws/Model/Enums.cs
@@ -0,0 +1,139 @@
+using System;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public enum LawStage
+ {
+ Planning,
+ DidIt,
+ }
+
+ /// A law's severity. Sets the default days (1, 3, 5, 10) and orders the case log. Saved by name.
+ public enum LawSeverity
+ {
+ Minor,
+ Moderate,
+ Serious,
+ Grave,
+ }
+
+ /// Where a case stands. Saved by name.
+ public enum CaseStatus
+ {
+ /// Filed; nothing runs yet, or it waits (no bed, no enforcer, danger, a hold).
+ Open,
+ /// An enforcer is on it (a subdue, an arrest or a capture job).
+ Enforcing,
+ /// The offender serves a sentence in Laws' custody.
+ Jailed,
+ /// Done; LawCase.outcome says how.
+ Closed,
+ }
+
+ /// Notes a case keeps about the act ("on a table", "dug up from a grave"). Saved by name.
+ [Flags]
+ public enum CaseNotes
+ {
+ None = 0,
+ OnTable = 1,
+ DugUp = 2,
+ }
+
+ ///
+ /// 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.
+ ///
+ [Flags]
+ public enum ActFacts
+ {
+ None = 0,
+ /// Any meat, meals with meat included (FoodUtility.GetFoodKind).
+ Meat = 1,
+ /// Raw meat or a corpse, unprocessed.
+ RawMeatOrCorpse = 2,
+ /// Human meat, a humanlike corpse or an ingredient of either.
+ HumanMeat = 4,
+ /// Insect meat.
+ InsectMeat = 8,
+ /// Raw food (ingestible preferability).
+ RawFood = 16,
+ /// A meal (processed food).
+ Meal = 32,
+ }
+
+ /// Which stages of a case have had their punishment dispatched. Saved by name.
+ [Flags]
+ public enum StageMask
+ {
+ None = 0,
+ Planning = 1,
+ DidIt = 2,
+ }
+
+ ///
+ /// The entry kind and stage a punishment fits (design: "Lawbook tab", punishments per entry and stage).
+ /// Read from PunishmentDef.fits in XML.
+ ///
+ public enum PunishmentFit
+ {
+ /// A break that isn't hostile to the colony, at planning.
+ BreakPlanning,
+ /// A break that isn't hostile to the colony, at did it.
+ BreakDidIt,
+ /// A break hostile to the colony (berserk), at planning.
+ HostileBreakPlanning,
+ /// A break hostile to the colony (berserk), at did it.
+ HostileBreakDidIt,
+ /// Every entry outside the breaks: ate, used, interactions, recorded acts, records, bills, special acts.
+ Act,
+ }
+
+ /// What an Enforcement queue entry does when it comes due.
+ public enum CaseTask
+ {
+ /// Start the punishment of the case's law for the entry's stage (PunishmentWorker.Start).
+ Punish,
+ /// Write "Maintain only" on a pawn Laws just jailed (Sentences.WriteMaintainOnly).
+ MaintainOnly,
+ }
+
+ /// Outcome keys of closed cases. The label is "BlaxLaws_Outcome_" + key. Saved as strings.
+ 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";
+
+ /// The outcome's label, or the key itself when no string exists (an outcome a later release added).
+ public static string Label(string key)
+ {
+ if (key.NullOrEmpty())
+ return "";
+ string k = "BlaxLaws_Outcome_" + key;
+ return k.CanTranslate() ? k.Translate().ToString() : key;
+ }
+ }
+
+ /// Labels for the enums, from Keyed.
+ 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;
+ }
+}
diff --git a/Source/BlaxLaws/Model/Law.cs b/Source/BlaxLaws/Model/Law.cs
new file mode 100644
index 0000000..b3c4496
--- /dev/null
+++ b/Source/BlaxLaws/Model/Law.cs
@@ -0,0 +1,89 @@
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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 <DLC>" or "Missing: <mod>"
+ /// 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.
+ ///
+ public class Law : IExposable
+ {
+ /// Unique in the save, never reused. 0 until Lawbook adds the row.
+ public int id;
+
+ /// The catalogue entry: "Ate/WakeUp", "Break/@anyDrugBinge" (ActKey).
+ public string actKey;
+
+ /// The entry's label when the row was written, shown while the entry is missing.
+ public string savedLabel;
+
+ /// The entry's source when the row was written: "Core", "Ideology" or a mod's name.
+ public string savedMod;
+
+ /// The entry's source package id when the row was written ("ludeon.rimworld.ideology").
+ public string savedPackageId;
+
+ /// Drug binge rows only: DrugOptions ("@any", "@hard", "@social" or a ChemicalDef defName). Null otherwise.
+ public string option;
+
+ public LawStage stage = LawStage.DidIt;
+
+ public LawSeverity severity = LawSeverity.Moderate;
+
+ /// The PunishmentDef's defName ("Warn", "Jail").
+ public string punishment = "Warn";
+
+ /// 1 to 50; used by punishments with usesDays.
+ public int days = 3;
+
+ public bool enabled = true;
+
+ /// The category id, the first part of the act key.
+ public string CategoryId => ActKey.CategoryOf(actKey);
+
+ /// The catalogue entry, or null while it is missing.
+ public ActEntry Entry => ActCatalogue.Get(actKey);
+
+ public bool Resolves => Entry != null;
+
+ /// The punishment's def, or null when a later release's punishment was saved and is gone.
+ public PunishmentDef PunishmentDef => punishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(punishment);
+
+ /// The label the lawbook shows: the entry's, the saved one while missing, else the key.
+ public string Label => Entry?.label ?? (savedLabel.NullOrEmpty() ? actKey : savedLabel);
+
+ /// "Needs Ideology" or "Missing: Core" while the entry is missing, else null.
+ public string MissingText => Resolves ? null : DlcSupport.MissingText(savedMod, savedPackageId);
+
+ /// The sentence or guilt length in ticks.
+ public int DaysTicks => days * GenDate.TicksPerDay;
+
+ /// Whether this row has the given key (option compared as DrugOptions only for rows that keep one).
+ 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)");
+ }
+}
diff --git a/Source/BlaxLaws/Model/LawCase.cs b/Source/BlaxLaws/Model/LawCase.cs
new file mode 100644
index 0000000..5576b14
--- /dev/null
+++ b/Source/BlaxLaws/Model/LawCase.cs
@@ -0,0 +1,237 @@
+using RimWorld;
+using RimWorld.Planet;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public class LawCase : IExposable
+ {
+ public int id;
+
+ // ---- who ------------------------------------------------------------------------------
+
+ public Pawn offender;
+ /// The offender's short name when the case was filed, kept after the pawn is gone.
+ public string offenderName;
+ public string offenderId;
+
+ public Pawn victim;
+ public string victimName;
+ public string victimId;
+
+ // ---- what -----------------------------------------------------------------------------
+
+ /// The act key of the row that opened the case.
+ public string actKey;
+
+ /// The defName that matched (which drug, which recipe, which break). Updated by a later act of the case.
+ public string matchedDef;
+
+ /// Break cases: the MentalStateDef's defName. Null for acts outside a break.
+ public string breakState;
+
+ /// Break cases: the tick the break started (TicksGame minus MentalState.Age, to within 30 ticks).
+ public int breakStartTick = -1;
+
+ /// The row whose punishment the planning stage runs, or -1.
+ public int planningLawId = -1;
+
+ /// The row whose punishment the did-it stage runs, or -1. Set once per case.
+ public int didItLawId = -1;
+
+ /// The highest severity of the case's rows, kept for the log after a row is deleted.
+ public LawSeverity severity;
+
+ /// The stage reached.
+ public LawStage stage;
+
+ /// Did-it acts in this case: doses during a binge, repeats inside the cooldown. 0 at planning.
+ 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;
+
+ /// CaseOutcomes key once closed, else null.
+ public string outcome;
+
+ /// Which stages' punishments were dispatched (each row fires once per case).
+ public StageMask punishedStages;
+
+ /// The PunishmentDef defName running for this case (Enforcement calls its Sweep), or null.
+ public string activePunishment;
+
+ /// The stage activePunishment runs for.
+ public LawStage activeStage;
+
+ /// The pawn carrying it out, one enforcement at a time.
+ public Pawn enforcer;
+
+ /// Why enforcement waits, as a Keyed key the Cases tab shows, or null. Set by the punishment workers.
+ public string waitReason;
+
+ // ---- jail -----------------------------------------------------------------------------
+
+ /// The tick the offender became Laws' prisoner (hook K), or -1.
+ public int captureTick = -1;
+
+ /// "Maintain only" was written two ticks after the capture.
+ public bool maintainOnlyDone;
+
+ /// Capture tick plus the sentence, or -1.
+ public int releaseTick = -1;
+
+ /// The bed the offender owned right before the arrest job took it, given back when the arrest fails.
+ public Building_Bed oldBed;
+
+ /// "Arrest now" lifted the hold for this case: from here on it arrests a role holder or mechanitor like anyone.
+ public bool holdLifted;
+
+ // ---- reads ----------------------------------------------------------------------------
+
+ public bool IsClosed => status == CaseStatus.Closed;
+
+ public bool IsBreakCase => !breakState.NullOrEmpty();
+
+ public MentalStateDef BreakStateDef => breakState.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(breakState);
+
+ public int LawIdFor(LawStage s) => s == LawStage.Planning ? planningLawId : didItLawId;
+
+ /// The row the stage runs, or null (none, or deleted).
+ public Law LawFor(LawStage s) => GameComponent_BlaxLaws.Instance?.LawById(LawIdFor(s));
+
+ /// The row the case shows: did it, else planning, else null.
+ 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);
+
+ /// The offender's name, live while the pawn exists.
+ public string OffenderLabel => offender != null ? offender.LabelShort : offenderName ?? "?";
+
+ public string VictimLabel => victim != null ? victim.LabelShort : victimName;
+
+ /// What the case is about: the current row's label, else the act key.
+ 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;
+ }
+
+ /// Sets the row a stage runs and raises the case's severity to it.
+ 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;
+ }
+
+ /// Nulls references to pawns and things that are gone, so the save holds no reference it can't load. Names stay.
+ 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;
+ }
+
+ ///
+ /// 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).
+ ///
+ 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 + ")" : "");
+ }
+}
diff --git a/Source/BlaxLaws/Offenders.cs b/Source/BlaxLaws/Offenders.cs
new file mode 100644
index 0000000..c11c2d9
--- /dev/null
+++ b/Source/BlaxLaws/Offenders.cs
@@ -0,0 +1,47 @@
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class Offenders
+ {
+ /// The pawn can be an offender.
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static bool OnPlayerOrder(Pawn p) => p != null && (p.Drafted || (p.CurJob?.playerForced ?? false));
+
+ /// IsCovered and, while the setting is on, not on a player order.
+ public static bool CountsAsOffender(Pawn p) =>
+ IsCovered(p) && !(BlaxLawsMod.S.playerOrdersExempt && OnPlayerOrder(p));
+ }
+}
diff --git a/Source/BlaxLaws/Sentences/CaptureHook.cs b/Source/BlaxLaws/Sentences/CaptureHook.cs
new file mode 100644
index 0000000..efe3f38
--- /dev/null
+++ b/Source/BlaxLaws/Sentences/CaptureHook.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Collections.Generic;
+using HarmonyLib;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ [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 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);
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Sentences/JailFlow.cs b/Source/BlaxLaws/Sentences/JailFlow.cs
new file mode 100644
index 0000000..6f1bb0e
--- /dev/null
+++ b/Source/BlaxLaws/Sentences/JailFlow.cs
@@ -0,0 +1,285 @@
+using RimWorld;
+using Verse;
+using Verse.AI;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class JailFlow
+ {
+ /// The sentence: the days of the row the case runs, in ticks.
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static int RenewalTicks(LawCase c) => SentenceTicks(c) + Sentences.FallbackTicks;
+
+ ///
+ /// The case now runs as Jail (from "Subdue then jail", or a fallback). Clears the wait reason the subdue
+ /// left.
+ ///
+ 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;
+ }
+
+ /// The case's enforcer runs or has queued an Arrest or Capture of the offender.
+ public static bool ArrestRuns(LawCase c) => c?.enforcer != null && EnforcerJobs.TakesToJail(c.enforcer, c.offender);
+
+ /// Ends the case's Arrest or Capture job, current or queued, and gives the old bed back.
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Whether "Arrest now" lifted the hold for this case. Saved on the case.
+ public static bool HoldLifted(LawCase c) => c != null && c.holdLifted;
+
+ /// "Arrest now": from here on the case arrests a role holder or mechanitor like anyone.
+ public static void LiftHold(LawCase c)
+ {
+ if (c == null)
+ return;
+ c.holdLifted = true;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ ///
+ /// "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.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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).
+ ///
+ public static void NoteOldBed(LawCase c, Pawn o)
+ {
+ Building_Bed owned = o?.ownership?.OwnedBed;
+ if (owned != null && !owned.ForPrisoners && !owned.Medical)
+ c.oldBed = owned;
+ }
+
+ ///
+ /// 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).
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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");
+ }
+
+ /// The offender became a prisoner without Laws (by hand, another mod): Laws never touches it and closes the case.
+ 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);
+ }
+
+ /// 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.
+ 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);
+ }
+}
diff --git a/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs b/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs
new file mode 100644
index 0000000..5aebe13
--- /dev/null
+++ b/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs
@@ -0,0 +1,94 @@
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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);
+
+ ///
+ /// 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".
+ ///
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/Sentences/Sentences.cs b/Source/BlaxLaws/Sentences/Sentences.cs
new file mode 100644
index 0000000..a9ee2db
--- /dev/null
+++ b/Source/BlaxLaws/Sentences/Sentences.cs
@@ -0,0 +1,173 @@
+using System;
+using RimWorld;
+using UnityEngine;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class Sentences
+ {
+ /// A day after the release tick without a release, Laws releases the pawn in place.
+ public const int FallbackTicks = GenDate.TicksPerDay;
+
+ private static int Now => Find.TickManager?.TicksGame ?? 0;
+
+ ///
+ /// 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).
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+ }
+
+ /// The Cases tab's "Arrest now" applies: a jail case held for a role holder or mechanitor.
+ public static bool CanArrestNow(LawCase c) =>
+ c?.offender != null && !c.IsClosed && c.status == CaseStatus.Open && c.waitReason == WaitReasons.Hold;
+
+ /// "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).
+ public static void ArrestNow(LawCase c)
+ {
+ if (!CanArrestNow(c))
+ return;
+ JailFlow.LiftHold(c);
+ JailFlow.Become(c);
+ JailFlow.TryArrest(c, ignoreHold: true);
+ }
+
+ /// Ticks of the sentence left for a jailed case, or -1. The Cases tab counts down with it.
+ public static int TicksLeft(LawCase c) =>
+ c != null && c.status == CaseStatus.Jailed && c.releaseTick >= 0 ? Math.Max(0, c.releaseTick - Now) : -1;
+
+ /// This capture is the one Laws sent: the case's own enforcer took the offender for a jail case.
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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));
+ }
+
+ /// The release day as a date at the offender's map.
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/ActIcons.cs b/Source/BlaxLaws/UI/ActIcons.cs
new file mode 100644
index 0000000..43de3ff
--- /dev/null
+++ b/Source/BlaxLaws/UI/ActIcons.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using HarmonyLib;
+using RimWorld;
+using UnityEngine;
+using Verse;
+
+namespace BlaxLaws
+{
+ /// Textures the Laws tab uses, all vanilla.
+ [StaticConstructorOnStartup]
+ internal static class LawsTex
+ {
+ /// The overlap icon: vanilla's warning sign, or the info button when a texture pack lacks it.
+ public static readonly Texture2D Overlap = ContentFinder.Get("UI/Widgets/Warning", false) ?? TexButton.Info;
+
+ public static readonly Texture2D InBook = Widgets.CheckboxOnTex;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static class ActIcons
+ {
+ private static readonly Dictionary symbols = new Dictionary();
+
+ // 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");
+
+ /// Whether the entry draws an icon.
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/ActOverlaps.cs b/Source/BlaxLaws/UI/ActOverlaps.cs
new file mode 100644
index 0000000..ebcee61
--- /dev/null
+++ b/Source/BlaxLaws/UI/ActOverlaps.cs
@@ -0,0 +1,279 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class ActOverlaps
+ {
+ private static readonly List None = new List();
+ private static readonly Dictionary> byLaw = new Dictionary>();
+ private static readonly Dictionary pairCache = new Dictionary();
+ 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;
+
+ /// The rows of other categories that can catch the same act as this row. Empty when none.
+ public static IReadOnlyList Of(Law law)
+ {
+ if (law == null)
+ return None;
+ Refresh();
+ return byLaw.TryGetValue(law, out List list) ? list : None;
+ }
+
+ /// Whether the row takes part in overlaps at all: on, resolving, did it, outside the breaks.
+ 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);
+ }
+
+ /// Whether one game act can be caught by both entries (different categories only).
+ 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;
+ }
+
+ /// Drops the cache. The next read builds it again.
+ public static void Reset()
+ {
+ byLaw.Clear();
+ pairCache.Clear();
+ cachedWatch = -1;
+ }
+
+ private static void Refresh()
+ {
+ IReadOnlyList 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 list))
+ byLaw[of] = list = new List();
+ 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;
+ }
+
+ /// True when some member def of a and some member def of b make the pair.
+ private static bool Any(ActEntry a, ActEntry b, Func pair)
+ {
+ List 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;
+ }
+
+ /// The defs an entry covers: its def, or every def entry of its category the group matches.
+ public static List Members(ActEntry e)
+ {
+ var result = new List();
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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() != 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;
+ }
+
+ /// Whether finishing one iteration of the recipe raises the record for the doer.
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/ActPickerTree.cs b/Source/BlaxLaws/UI/ActPickerTree.cs
new file mode 100644
index 0000000..39e9001
--- /dev/null
+++ b/Source/BlaxLaws/UI/ActPickerTree.cs
@@ -0,0 +1,154 @@
+using System.Collections.Generic;
+using RimWorld;
+using Verse;
+
+namespace BlaxLaws
+{
+ /// One visible line of the act picker: a category header or an entry.
+ public sealed class ActPickerRow
+ {
+ public ActCategoryDef category;
+
+ /// Null for a category header.
+ public ActEntry entry;
+
+ /// Header: the category is open.
+ public bool open;
+
+ /// Header: entries that pass the search (all of them without a search).
+ public int count;
+
+ /// Entry: the lawbook has a row for this act key (the tick).
+ public bool inBook;
+
+ public bool IsHeader => entry == null;
+
+ public override string ToString() => IsHeader ? "[" + category?.defName + " " + count + (open ? " open" : "") + "]" : entry.key + (inBook ? " (in book)" : "");
+ }
+
+ ///
+ /// 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.
+ ///
+ public sealed class ActPickerTree
+ {
+ public readonly QuickSearchFilter filter = new QuickSearchFilter();
+
+ private readonly HashSet open = new HashSet();
+ private readonly List rows = new List();
+ private readonly HashSet inBook = new HashSet();
+ private string builtText;
+ private int builtCatalogue = -1;
+ private int builtWatch = -1;
+ private int builtLaws = -1;
+ private bool dirty = true;
+
+ /// The lines to draw, top to bottom.
+ public IReadOnlyList Rows
+ {
+ get
+ {
+ Refresh();
+ return rows;
+ }
+ }
+
+ /// Entries the search leaves, over every category.
+ public int Hits { get; private set; }
+
+ public string SearchText
+ {
+ get => filter.Text;
+ set
+ {
+ if (filter.Text == value)
+ return;
+ filter.Text = value ?? "";
+ dirty = true;
+ }
+ }
+
+ /// Whether the category's entries show. While searching, a category with hits is always open.
+ public bool IsOpen(string categoryId) => filter.Active || open.Contains(categoryId);
+
+ /// Opens or closes a category (no effect while searching, when hits decide).
+ 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;
+ }
+
+ /// Whether the entry passes the search: its label or its defName (a group's id) contains the text.
+ 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));
+ }
+
+ /// The entry rows of a category that pass the search, in picker order.
+ public List EntriesShown(string categoryId)
+ {
+ var list = new List();
+ 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 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) });
+ }
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/CaseLog.cs b/Source/BlaxLaws/UI/CaseLog.cs
new file mode 100644
index 0000000..36a2596
--- /dev/null
+++ b/Source/BlaxLaws/UI/CaseLog.cs
@@ -0,0 +1,201 @@
+using System.Collections.Generic;
+using RimWorld;
+using RimWorld.Planet;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ public static class CaseLog
+ {
+ /// Cases newest first, as a new list (see FillRows). Closed ones only when asked.
+ public static List Rows(bool includeClosed)
+ {
+ var rows = new List();
+ FillRows(rows, includeClosed);
+ return rows;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static void FillRows(List into, bool includeClosed)
+ {
+ if (into == null)
+ return;
+ into.Clear();
+ GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
+ if (comp == null)
+ return;
+ IReadOnlyList 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;
+ }
+
+ /// The offender's name, with the victim when the case has one.
+ 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();
+ }
+
+ /// The row's action, the def that matched when it differs, the count and the notes.
+ 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;
+ }
+
+ /// The label of the def that matched (which drug, which recipe, which break), or null.
+ 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);
+
+ /// "3 days ago", from the last act of the case.
+ 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));
+ }
+
+ /// The punishment the case runs or ran, with its days.
+ 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;
+ }
+
+ /// The status, with the outcome of a closed case, the countdown of a jailed one or why it waits.
+ 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;
+ }
+
+ ///
+ /// "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).
+ ///
+ public static bool CanArrestNow(LawCase c) =>
+ c != null && c.offender != null && !LawCase.IsGone(c.offender) && Sentences.CanArrestNow(c);
+
+ /// Why the case is held, for the button's tooltip.
+ public static string HoldReason(Pawn p) => JailFlow.HoldReason(p);
+
+ /// The "Arrest now" button: renews guilt and starts the arrest (Sentences.ArrestNow).
+ public static void ArrestNow(LawCase c)
+ {
+ if (!CanArrestNow(c))
+ return;
+ HookGuard.Run("Arrest now", () => Sentences.ArrestNow(c));
+ }
+
+ /// Whether the jump button can show the offender: alive or dead, on a map, carried, in a caravan.
+ public static bool CanJump(LawCase c)
+ {
+ Pawn p = c?.offender;
+ if (p == null || LawCase.IsGone(p))
+ return false;
+ return CameraJumper.CanJump(Target(p));
+ }
+
+ /// The jump button: selects the offender (its corpse when dead) the vanilla way.
+ 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;
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/Dialog_PickAct.cs b/Source/BlaxLaws/UI/Dialog_PickAct.cs
new file mode 100644
index 0000000..bbbc549
--- /dev/null
+++ b/Source/BlaxLaws/UI/Dialog_PickAct.cs
@@ -0,0 +1,194 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RimWorld;
+using UnityEngine;
+using Verse;
+using Verse.Sound;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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 onPick;
+ private readonly QuickSearchWidget search = new QuickSearchWidget();
+ private readonly ActPickerTree tree = new ActPickerTree();
+ private Vector2 scroll;
+ private bool focusSearch = true;
+
+ /// The tree the window draws, for tests and callers that preset the search.
+ public ActPickerTree Tree => tree;
+
+ /// Called with the picked act key.
+ public Dialog_PickAct(Action onPick)
+ {
+ this.onPick = onPick;
+ doCloseX = true;
+ closeOnClickedOutside = true;
+ absorbInputAroundWindow = true;
+ forcePause = false;
+ onlyOneOfTypeAllowed = true;
+ }
+
+ /// "Add law": a pick adds a row (LawbookUi.AddFromPicker), or shows the existing one.
+ public static Dialog_PickAct ForNewRow() => new Dialog_PickAct(key => LawbookUi.AddFromPicker(key, out _));
+
+ /// A click on a row's Action: a pick changes the row's action (LawbookUi.ChangeAction).
+ 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 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();
+ }
+ }
+
+ /// True when the click picked the entry and the window closed.
+ 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;
+ }
+
+ /// The entry's tooltip: label, source, stages, what the act is and whether the book has it.
+ public static string EntryTooltip(ActEntry e, bool inBook)
+ {
+ if (e == null)
+ return null;
+ var parts = new List { 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);
+ }
+
+ /// Returns the key to the caller and closes.
+ protected void Pick(string actKey)
+ {
+ Close();
+ HookGuard.Run("Picking an act", () => onPick?.Invoke(actKey));
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/LawbookUi.cs b/Source/BlaxLaws/UI/LawbookUi.cs
new file mode 100644
index 0000000..7ab6d8d
--- /dev/null
+++ b/Source/BlaxLaws/UI/LawbookUi.cs
@@ -0,0 +1,361 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RimWorld;
+using UnityEngine;
+using Verse;
+
+namespace BlaxLaws
+{
+ /// One entry of a lawbook column's dropdown. A null action is a disabled entry; reason says why.
+ public sealed class RowChoice
+ {
+ public string label;
+
+ /// The value the entry sets: a drug option, a LawStage, a LawSeverity or a PunishmentDef.
+ public object payload;
+
+ /// Writes the choice through Lawbook. Null for a disabled entry.
+ public Action action;
+
+ /// Why the entry is disabled ("Needs Ideology"), or null.
+ public string reason;
+
+ /// The row has this value now.
+ public bool selected;
+
+ public override string ToString() => label + (selected ? " (selected)" : "") + (action == null ? " (disabled: " + reason + ")" : "");
+ }
+
+ ///
+ /// 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).
+ ///
+ public static class LawbookUi
+ {
+ /// Seconds the tab highlights a row it jumped to.
+ public const float FocusSeconds = 2.5f;
+
+ /// The row the tab scrolls to and highlights, or 0.
+ public static int FocusLawId { get; private set; }
+
+ /// Real time until which the focused row is highlighted.
+ public static float FocusUntil { get; private set; }
+
+ /// Set when Focus asks the tab to scroll; the tab clears it once it scrolled.
+ public static bool ScrollPending { get; set; }
+
+ /// Shows the row: the Lawbook tab scrolls to it and highlights it.
+ 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 ------------------------------------------------------------------------
+
+ /// "Ate: Wake-up". A row whose entry is missing shows its saved label.
+ public static string ActionLabel(Law law)
+ {
+ if (law == null)
+ return "";
+ return "BlaxLaws_ActionLabel".Translate(CategoryLabel(law.CategoryId), law.Label);
+ }
+
+ /// The category's label ("Ate"), or its id while the category is unknown.
+ public static string CategoryLabel(string categoryId)
+ {
+ if (categoryId.NullOrEmpty())
+ return "?";
+ ActCategoryDef cat = DefDatabase.GetNamedSilentFail(categoryId);
+ return cat != null && !cat.label.NullOrEmpty() ? cat.LabelCap.ToString() : categoryId;
+ }
+
+ /// The Action cell's tooltip: source mod, what counts, a missing entry's reason.
+ public static string ActionTooltip(Law law)
+ {
+ if (law == null)
+ return null;
+ var parts = new List();
+ 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);
+ }
+
+ /// What the entry's act is, for tooltips: a special act's row tooltip, else the category's tooltip.
+ 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.GetNamedSilentFail(e.categoryId);
+ return cat?.Worker.Tooltip;
+ }, null);
+ }
+
+ /// The Days cell: the number when the punishment uses days, else "-".
+ 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 ----------------------------------------------------------------
+
+ /// Whether the row has an Option column value: drug binges only.
+ public static bool HasOption(Law law) => law?.Entry?.hasDrugOption ?? (law?.option != null);
+
+ /// Any drug, hard drugs, social drugs, then every drug's chemical A to Z.
+ public static List OptionChoices(Law law)
+ {
+ var list = new List();
+ if (law == null || !HasOption(law))
+ return list;
+ var options = new List { 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;
+ }
+
+ /// The stages the entry offers; a missing entry keeps the row's stage only.
+ public static List StageChoices(Law law)
+ {
+ var list = new List();
+ if (law == null)
+ return list;
+ ActEntry e = law.Entry;
+ IEnumerable 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 SeverityChoices(Law law)
+ {
+ var list = new List();
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ public static List PunishmentChoices(Law law)
+ {
+ var list = new List();
+ 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 ----------------------------------------------------
+
+ /// Sets the option; a refusal shows the row that has the key.
+ public static bool ChangeOption(Law law, string option)
+ {
+ if (Lawbook.SetOption(law, option, out Law existing))
+ return true;
+ Refused(existing);
+ return false;
+ }
+
+ /// Sets the stage; a punishment that no longer fits resets to Warn. A refusal shows the existing row.
+ public static bool ChangeStage(Law law, LawStage stage)
+ {
+ if (Lawbook.SetStage(law, stage, out Law existing))
+ return true;
+ Refused(existing);
+ return false;
+ }
+
+ /// The act picker's pick for an existing row: SetAction, or the existing row with that key.
+ public static bool ChangeAction(Law law, string actKey)
+ {
+ if (Lawbook.SetAction(law, actKey, out Law existing))
+ {
+ Focus(law);
+ return true;
+ }
+ Refused(existing);
+ return false;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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 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;
+ }
+
+ /// Rows already in the book for this act key, any option and stage.
+ public static List RowsOf(string actKey) => Lawbook.Laws.Where(l => l.actKey == actKey).ToList();
+
+ /// "Starter lawbook": adds the missing starter rows and says how many.
+ 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;
+ }
+
+ /// The confirmation a delete asks first, naming the open cases it closes; null when it has none.
+ 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;
+ }
+
+ /// Open cases of the row whose offender serves its sentence: a repeal sets them to Release (PunishmentWorker_Jail.Stop).
+ 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;
+ }
+
+ /// Deletes the row, asking first when it has open cases (design: "Bulk changes ask first and name the count").
+ 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);
+ }
+ }
+}
diff --git a/Source/BlaxLaws/UI/MainTabWindow_Laws.cs b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs
new file mode 100644
index 0000000..29dbefa
--- /dev/null
+++ b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs
@@ -0,0 +1,470 @@
+using System;
+using System.Collections.Generic;
+using RimWorld;
+using UnityEngine;
+using Verse;
+
+namespace BlaxLaws
+{
+ ///
+ /// 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.
+ ///
+ 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 caseRows = new List();
+ private struct DaysBuffer
+ {
+ public int value;
+ public string text;
+ }
+
+ private readonly Dictionary dayBuffers = new Dictionary();
+ private readonly List tabs = new List();
+
+ 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 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 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 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 overlaps)
+ {
+ var lines = new List();
+ 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> 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> Elements(List 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