Repository navigation
Code mod hooks
Every place a code mod plugs into the game besides Harmony, grouped by what you want to do. Start with
Writing code mods for the project, manifest and loading; this page is the catalog. The full contract of each hook, with
every edge case, is in docs/modding.md "Registration surface".
Hooks exist only where a Harmony patch would break the game's determinism or saves without an error. Everything else is a Harmony patch.
Build against the Meitou.References package on NuGet, versioned as the release; no game install is needed:
<PackageReference Include="Meitou.References" Version="<game version>" />. Setting <MeitouPublicized>true</MeitouPublicized> in the
project lets the mod reach the game's non-public types and members too; those change between releases without notice, so a mod using them
names its gameVersion. Details: Reference package.
| Kind | How you register | Where it runs |
|---|---|---|
ModContext calls (c.AddX(...)) |
Inside Initialize, once per session. |
Varies; each entry below says. |
System interfaces (ICrimeObserver, ITradePriceFilter...) |
Implement the interface on a system you add with c.AddSystem. Nothing else to register. |
In the tick, serially, in system order (mods in load order), unless the entry says otherwise. |
World and character APIs (world.PostSound, cold.ModTaskBar, PopulationSystem.SpawnPlatoon...) |
Call them from your system. | From your system's serial phases, unless the entry says otherwise. |
Rules shared by every hook:
-
Observers and filters must not change the world. They may read it and change your own system's state; gameplay changes go through
commands you
Enqueueand handle in your system'sInputs. - A throw disables that hook for that world (logged with your mod id) and the fault enters the state hash. The game goes on.
- Interface callbacks run on the host's thread while a tick may be in flight: never touch the world there. Read the snapshot you are given, queue commands, and copy any list you keep (the game reuses them).
-
Display-only state (task bars, meters, bone meshes, sounds) is not saved or hashed: keep your own state in
IModSaveDataand set it again after a load, for example inIWorldReady. - Codes and numbers you claim start at 1000 (dialogue codes, record types, task/job/goal types). A code another mod holds refuses the second mod. Weather kinds also start at 1000, but nothing claims them, so two mods can pick the same one.
- Without any registration for a hook, the game builds nothing for it, so unused hooks cost nothing.
IModDataPhase.EditData(ModDataContext data) on your mod's entry type: once per session while the game data loads, after every data file
and translation is merged and before anything is built from the records, in mods.cfg order and before any mod's Initialize. Read the
merged data.Data; change it as a .mod file would with data.Edit(id), Add(id, type, name), Remove(id) and Apply(record). A throw,
or a change that fails the check, merges none of your changes and leaves the mod out for the session; changes already merged are never
undone. Records added or renamed here are not translated. Harmony, saved settings and Dependency<T> are not offered here. Name the
releases that have it in gameVersion. Details: Data phase.
c.AddSystem("rivalry", ctx => new RivalrySystem(ctx.Find<CombatSystem>()), SystemAnchor.AfterPart(StandardParts.Combat));The factory runs for every world (new game, each load). SystemAnchor.Before(part), AfterPart(part) or End place it in the tick.
Implement only the ITickSystem phases you need. A phase that throws stops that system from the next serial step and shows the player a
notice. Most other hooks on this page are interfaces you add to such a system.
IWorldReady.Ready(World world, bool fromSave): once, before the first tick, after a save loaded (your IModSaveData.Read is done) or a new
game placed the player's characters. The place to re-apply unsaved runtime state. It may change the world like a serial phase.
IModSaveData (Write(Stream), Read(Stream)): saved under your system's name in meitou-mods/<id>.dat in the save folder. Key
per-character data by world.LastingIds.GetOrGive(character), never by CharacterId (new every world). Give ids in the tick, read
CharacterCold.LastingId in Write.
IStateHashed.Hash(ref StateHasher h): put your state in the world's hash so meitou-tools mod-check
can find determinism bugs in it.
Define SimCommand records, queue them with c.Enqueue (or a context's Enqueue), handle them by type in your system's Inputs. Every
system sees every command. Another mod's command type is a different type even from the same DLL copy; share it through a
dependency.
| Hook | Signature | Use it for |
|---|---|---|
| Hit filter | ICombatHitFilter.HitLanding(World, ref PendingHit hit) |
Change the DamagePacket (cut, blunt, pierce, stun, bleed, armour penetration) before armour, or set Cancelled (a melee blow becomes a miss, a bolt flies past). Runs before observers. Doors and walls are not filtered. |
| Hit observer | ICombatHitObserver.HitResolved(World, in CombatHit hit) |
React to every landed melee or bolt contact and execution blow: damage dealt, armour absorbed, body part, attacker, victim. |
| Hit feed | c.AddCombatHitFeed(hits => ...) |
Display only (blood, hit markers). Once a frame on the render thread with the hits since the last frame. |
| Combat moves | c.AddCombatMove((world, id, tick) => CombatMove?) |
Play a CombatTechnique animation when the game plays nothing of its own. Animation only, lands no blow. Runs in parallel: cheap, read-only, deterministic. |
Weapons, weapon classes and firearms of your own are mostly data: see "Weapon types" and "Ammunition" in
docs/modding.md. A weapon training a skill of
your own names it in WEAPON meitou skill after c.AddSkill.
| Hook | API | Notes |
|---|---|---|
| Deaths | ICharacterDeathObserver.Died(World, in CharacterDeath d) |
Every death, loaded or in an off-screen platoon fight: cause, DeathSite, killer and its faction (none for bleeding, hunger and the like). |
| Experience |
IExperienceFilter.Gain(World, in ExperienceGain g) returns the amount |
Scale or cancel (0) any stat gain by character, stat or ExperienceSource. Runs on any thread, concurrently: quick, thread-safe, a pure read. |
| Stat modifiers |
cold.Stats.Modifiers.Set(key, stat, amount) / Remove / RemoveAll
|
Temporary +/- to a stat, shown in the stats window, never trained in or saved. |
| Carry capacity | cold.Stats.CarryModifiers.Set(key, CarryTerm.Scale or Kilograms, amount) |
Change carrying capacity without touching strength. Prefix keys with your mod id. Not saved. |
| Status effects |
c.AddStatusEffect(new StatusEffect(id, name) { ... }), then effect.Apply(world, character, hours, stacks)
|
Named, timed, stackable effects with stat modifiers, shown on the HUD's State line and saved with the character. |
| Skills |
c.AddSkill(new ModSkill(id, label, column)), then skill.Level, Set, Gain
|
A skill at the foot of a stats-window column, saved with the character. Keep the id; the stat number follows the load order. |
| Medical meters |
c.AddMedicalMeter(label), then meter.Set(cold, reading)
|
A bar on the medical panel after Hunger. At most four across all mods. Display only. |
| Task bars | cold.ModTaskBar = new TaskBar(caption, progress) |
The floating progress bar shown while picking a lock. Clear only your own. Display only. |
| Bone anchors | cold.DrawAnchor = new DrawAnchor(carrier, bone, offset, rotation) |
Draw a character on another's bone (a rider on a mount). Display only. |
| Bone meshes |
cold.SetBoneMesh(new BoneMesh(key, mesh, bone, offset, rotation)) / RemoveBoneMesh(key)
|
Hang a rigid mesh on a bone (a saddle). Display only. |
| Lasting ids |
world.LastingIds.GetOrGive(character), Find(id), KeptIds()
|
A 64-bit id that stays with a character for life, across saves. Shared by all mods. |
| Hunger level | cold.FedTo |
A hunger level that comes before the game's rule, for a captive your squad carries. Not saved. |
| Body shapes | Data only | A race's anatomy of any length, extra or missing parts, and new part types such as a tail are plain records. See bodies of other shapes. |
| Hook | API | Notes |
|---|---|---|
| Item use | c.AddItemUse(recordId, use => bool) |
Right-click on the item in the player's own inventory. True uses the click (remove a used-up item with Inventory.RemoveOne); false lets it equip or move. ItemInstance.ModTag is a free, saved string on an item. |
| Items used up | IItemUseObserver.ItemUsedUp(World, in ItemUsed u) |
Food bites, kit charges, bolts shot, building materials, broken tools, machine inputs, research costs, maps and blueprints read. |
| Trade prices |
ITradePriceFilter.Price(World, in TradeDeal deal, long price) returns the price |
Every price the trade window asks and every NPC shopper's purchase. Must be a pure read: the same price is asked more than once. |
| Equipment slots | c.AddEquipmentSlot(new ModSlot(section, fcsSlot, w, h, x, y)) |
A new worn-gear slot; see Writing code mods. |
| Wear rules | c.AddWearRule((item, race, animal) => bool) |
Refuse an item to a race, after its own races lists. Any thread: quick, same answer for the same arguments. |
| Hook | API | Notes |
|---|---|---|
| Crimes | ICrimeObserver.CrimeNoted(World, in CrimeEvent e) |
Every change to a pending crime or bounty, by CrimeEventKind: Pending, Witnessed, Booked, Lapsed, Expired, Cleared. Read CharacterCold.Bounties / Pending for characters you have not followed (ids change at every load). |
| Goods taken | IGoodsTakenObserver.GoodsTaken(World, in GoodsTaken t) |
The player's characters taking goods that are not theirs, including takes the game makes no crime of, so you can judge them by your own law. |
| Relation changes | IRelationChangeObserver.RelationChanged(World, in RelationChange r) |
Every faction relation change with its RelationCause (a deed, a crime, a captive sold, dialogue, war, debug). You may change relations from the callback. |
| World states |
var state = c.AddWorldState(recordId), then state.Set(world, bool) / Clear(world)
|
Take over a WORLD_EVENT_STATE: dialogue, spawns, town overrides and campaigns follow your value. Decisions made under it stay in the save. |
| Faction list | c.ArrangeFactionList(rows => rows) |
Reorder, rename, hide or group the Overview's Faction tab. Host thread. |
c.AddDialogueCondition(1000, check => check.Matches(IsRaining(check.World)));
c.AddDialogueEffect(1000, act => act.World.Post("Something happened"));Use the code as a DIALOG_ACTION's condition name or action name. Conditions only read (they run for previews too); effects run in a
serial step. See Writing code mods.
-
Decision sources: implement
IDecisionOwneron your system; inRegisterSources(DecisionSystem d)calld.Register(source). AnIDecisionSourcehas aStep(1 orders, 2 commitment, 3 urgent jobs, 4 goals, 5 jobs, 6 fallback), aKeywithin the step,CanRunandDesire(pure reads) andStart. To act before a character idles, use step 6 with a key below2000 + TaskType.Idle. Every player character is asked, so check it is one of yours. -
Mod jobs:
c.AddJobType(type, name)claims a job number (1000 up); put jobs inCharacterCold.Jobsand run them from anIJobSource(RegisterJob(type, source)). Saved in the job list; dropped at a load when no mod registers the type.
-
NPC goals (the chooser decides):
c.AddGoalType(type, name), list an AI_TASK with thatenumin your AI_PACKAGE data, implementINpcGoalOwnerandRegister(type, goal).INpcGoal.Desireruns in the parallel think (cheap, pure, deterministic);Startruns serially, setsEngaged = true, starts a task of your own row withTaskSource.Goaland returns true. When done: stop the task, clearEngaged, setcold.Ai.Replan. Nothing is saved: release your characters inIWorldReady. -
Duties (you decide when): find who has your goal with
AiSystem.WeighsGoal(world, slot, type)orPopulationSystem.GoalDuty, take members the AI holds (AiSystem.Holds), walk them withTaskStart.Walk(..., row, TaskSource.Goal). -
Driving characters:
CharacterCold.Engagedkeeps the AI off a character. It is shared and ownerless: engage only one the AI holds now, clear only what you set, and take characters back after a load. Drive them withTaskStart.Walk,CharacterOrders.Sneak,LockSystem.Picking.Step,CrimeSystem.Pickpocket,CarrySystem.BeginPickUp/BeginPutDown,ArrestSystem.TakeOver,AggroSystem.Spotted/Unseen.
-
Task handlers: implement
ITaskOwner; inRegisterTasks(TaskHandlers t)callt.Register(row, handler)for a row you claimed (1000 up). YourITaskHandlergetsStart,End(task, TaskEnd)andDone. Call the task's own handler (tasks.Of(task)) to keep the engine's walk. Serial phases only. -
Goal claims:
IGoalSource.Publish(World, SquadGoals goals)adds (worker, target) pairs so squad mates' finders (looting, medics, errands) skip what yours work on. A claim lasts 3 s after its last publish. Read-only, fixed order.
All are commands or PopulationSystem calls from a serial phase. Pass Owner: context.Id wherever the command takes one: a load without
your mod gives the squad back to the player, with a notice, so removing the mod never strands a save.
| Hook | What it does |
|---|---|
SetSquadAutonomy(squad, on, Independent, Owner) |
The AI runs a player squad; ChangeAi, StartContract, EndContract, SetSquadHome give it packages and a home. Independent: true: a squad the player does not lead (staff, caravans). StartContract { AnyRange = true } lets a contract's assault take its target anywhere, not only within the manoeuvre's reach. |
SetSquadUncounted(squad, on, Owner) |
Keep a squad out of max faction size. |
SetSquadPurse(squad, own, Owner) |
A squad pays and earns from its own money. |
SetSquadShop(squad, on, Template, Owner) |
A shopkeeper of the player's faction the player trades with. |
SetSquadDormant(squad, on, Owner) |
Put a squad to sleep so its place can unload. |
PopulationSystem.SpawnPlatoon |
Add an NPC platoon of a SQUAD_TEMPLATE near a point; find it again after a load by Platoon.ModTag. |
PopulationSystem.SpawnIntoPlayerSquad / JoinPlayerSquad
|
Make a new character in a player squad, or move an NPC into one. |
PopulationSystem.RequestCampaign |
Queue a FACTION_CAMPAIGN against a town, as dialogue does. |
PopulationSystem.HoldPlatoon / SendPlatoon
|
Stop a roaming platoon and send it somewhere. Not saved: hold again after a load. |
VisitTown command |
Send a wandering trader to a player town for N hours. |
BedSystem.PlayerBedRent |
Make NPCs pay to sleep in the player's beds. |
Squad.ModTags[c.Id], PlayerTown.ModTags[c.Id]
|
Your saved tag on a player squad or outpost (their ids change at every load). |
ProductionSystem.SitOn(world, slot, seat, row, source) / CanSit
|
Seat a character, the player's or an NPC, on a chair or throne through the Use order's act-out, after checking the seat, the character and the doors; CanSit gives the same answer and changes nothing. The AI's own sitters always win a seat. Not saved: seat again after a load. |
All run on the host's thread: never touch the world, queue commands instead.
| Hook | API | Notes |
|---|---|---|
| UI extension | c.AddUi(IUiExtension) |
Styles, controls, actions, overrides of vanilla ones, HUD slot contributions (UiSlots). Images from your folder: UiNodeKind.Image. |
| Right-click menu | registration.AddCharacterMenuVerbs(ctx => rows) |
Rows after the game's own in a character's menu. Asked every frame a character is under the cursor: keep it cheap. |
| Map markers | registration.AddMapMarkers(ctx => markers) |
Markers on the world map, with the game's marker images or a PNG/DDS of your own (64 files at most). |
| Squad AI tab | registration.AddSquadAiOptions(ctx => options) |
Tick buttons on the squad overview's AI tab. Your system saves the state. |
| Building panel | registration.AddBuildingActions(ctx => buttons) |
Buttons on a selected building's panel; keep to one or two. Check the building still exists when the command arrives. |
| Town panel | registration.AddTownPanelLines(ctx => lines) |
Lines under the HUD town panel's own: a label with a value, or a button that queues commands. At most four show across all mods, so keep to one. Return the same lines for an outpost every time, changing only their text. Check the outpost still exists when the command arrives. |
| Key actions | c.AddKeyAction(name, label, ctx => ..., defaults) |
A bindable action on the Controls page, saved in meitou.user.json. Escape, F6, Alt, Ctrl and Shift can't be defaults. |
| Settings | c.AddSettings(object) |
[Setting] properties on the Settings screen's Mods page. See Writing code mods. A value your code changes itself (a window's place, an in-game slider) goes through the returned group's Settings[i].Set(value) or Reset(), which keeps it like the page's; call them on the host's thread. |
| Debug rows | c.AddDebugCommand(label, ctx => status, hasField) |
Rows in the F10 menu. |
| Sounds |
world.PostSound(event, character or point), world.PostInterfaceSound(event); the same on ModContext
|
Play any event of the loaded banks, the game's or a mod bank's. Any thread, display only. Post one-shot events. |
| Hook | API |
|---|---|
| Record types |
c.AddRecordType(5000, "MY_THING"), then c.Records(5000). |
| Weather kinds | A WEATHER or EFFECT affect type from 1000 up, with ARMOUR weather protection<N> and RACE weather immunity<N>; your system acts on it. |
| Weapon skills and classes | WEAPON meitou skill; WEAPON and COMBAT_TECHNIQUE meitou class. |
| Ammunition | CROSSBOW meitou ammo; ITEM meitou damage mult, meitou bleed mult, meitou range mult, meitou speed mult, meitou live ammo. |
The meitou ... fields are Meitou only; the original game ignores them. Details and how to enter them in the construction set are in
docs/modding.md.
A data mod that reshapes the whole game (a conversion) edits the records the engine finds by id or by name in place, rather than removing or renaming them: Fixed record ids lists each one, what it is for, and what Meitou does without it.