Skip to content
VlcekM edited this page Nov 24, 2026 · 6 revisions

This page catalogs every engine hook available to code mods besides Harmony, organized by feature area. If you haven't set up a mod project yet, start with Writing code mods. For every technical edge case, see the "Registration surface" section of docs/modding.md.

Meitou provides dedicated hooks anywhere a Harmony patch would silently break determinism or save files. For everything else, use Harmony.

You don't need a local Kenshi or Meitou install to compile a mod: reference the Meitou.References NuGet package matching your target game release: <PackageReference Include="Meitou.References" Version="<game version>" />. Adding <MeitouPublicized>true</MeitouPublicized> to your .csproj also unlocks access to non-public engine types and members. Because internal APIs can change without notice between releases, always specify gameVersion in meitou.json when using publicized members. See Reference package for details.

Three kinds of hook

Hook style How you use it When and where it runs
ModContext methods (c.AddX(...)) Call inside Initialize, once per session. Varies by hook (noted in each entry below).
System interfaces (ICrimeObserver, ITradePriceFilter, ...) Implement the interface on a system registered via c.AddSystem. No extra registration needed. Serially during the simulation tick in system order (mods in load order), unless noted otherwise.
World & character APIs (world.PostSound, cold.ModTaskBar, PopulationSystem.SpawnPlatoon, ...) Call directly from your system. From serial tick phases, unless noted otherwise.

Rules that apply to all hooks

  • Keep observers and filters read-only. They can inspect the world and update your system's private state, but never modify world state directly. Queue gameplay changes with Enqueue and apply them in your system's Inputs phase.
  • Exceptions are isolated. If a hook throws, Meitou disables that hook for the current world, logs the error with your mod ID, records the fault in the state hash, and keeps running.
  • UI callbacks run on the host thread while a tick may be running. Never touch the live simulation world there. Read the snapshot provided, queue commands for changes, and copy any lists you want to keep (Meitou reuses them).
  • Visual-only state is not saved or hashed. Task bars, custom meters, bone meshes, sounds, particles, glows, and trails disappear on reload. Store the underlying data in IModSaveData and reapply visuals in IWorldReady.
  • Custom IDs start at 1000. Dialogue codes, record types, and task/job/goal types below 1000 belong to the base game. Claiming a number already used by another mod refuses the second mod. Weather kinds also start at 1000, though they aren't exclusively claimed, so watch for collisions.
  • Zero overhead when unused. If no mod registers for a hook, the engine skips it completely.

Simulation

Data phase

Implement IModDataPhase.EditData(ModDataContext data) on your IMod entry class to modify merged FCS records programmatically. It runs once per session in mods.cfg order, after all .mod files and translations have merged, before anything builds runtime objects from those records, and before any mod's Initialize.

Read from data.Data and apply edits like a .mod file using data.Edit(id), Add(id, type, name), Remove(id), and Apply(record). If your code throws or fails validation, none of your changes are applied and your mod is skipped for the session (already-merged mods stay intact). Records added or renamed here are not translated. Harmony, saved settings, and Dependency<T> are not available yet. Specify the compatible releases in gameVersion. See Data phase for details.

Tick systems

c.AddSystem("rivalry", ctx => new RivalrySystem(ctx.Find<CombatSystem>()), SystemAnchor.AfterPart(StandardParts.Combat));

The factory runs once for every world (new game or loaded save). Position your system in the tick with SystemAnchor.Before(part), AfterPart(part), or End, and implement only the ITickSystem phases you need. If any phase throws, that system is stopped at the next serial step and the player sees a notice. Most simulation hooks below are interfaces you add directly to a tick system.

World ready

Implement IWorldReady.Ready(World world, bool fromSave) on a system. It runs once before the first tick, right after save data has loaded (IModSaveData.Read is finished) or a new game has spawned the player's squad. At this point the world is active, so Enqueue, Tick, and PostSound all target it, and you can modify world state like in a serial phase. This is the ideal place to restore unsaved visual or runtime state.

Check world.Start to see how the world started (WorldStartKind.NewGame, Load, or Import) and world.Start.SaveFolder for the save directory path (null on a new game) if you keep sidecar files next to the save.

Save data

Implement IModSaveData (Write(Stream), Read(Stream)) on a system to save data under your system's name inside meitou-mods/<id>.dat in the save folder.

Always key per-character save data using world.LastingIds.GetOrGive(character), never CharacterId (which changes on every reload). Assign lasting IDs during ticks and read CharacterCold.LastingId inside Write.

If you also write your own files next to a save, register c.AddSaveWritten(folder => ...). It runs on the host thread after manual saves, quicksaves, and autosaves finish (don't touch the world from this callback).

State hash

Implement IStateHashed.Hash(ref StateHasher h) to include your system's state in the world hash so meitou-tools mod-check can detect determinism issues in your mod.

Commands

Define custom SimCommand record types, submit them with c.Enqueue (or any callback context's Enqueue), and handle them by type in your system's Inputs phase. Every system sees every command. Note that identical command types compiled into two separate mod DLLs are treated as different .NET types; share command types via a mod dependency.

While the game is paused, commands normally wait for the next tick. To handle a command immediately while paused, mark the command with IPausedCommand and implement IPausedCommandHandler on your system. Its Inputs phase runs between ticks in order alongside built-in UI commands, without advancing simulation time.

Every frame

c.AddFrame(frame => ...) runs once per frame on the host thread right before rendering. The ModFrame parameter gives live, read-only access to the latest world snapshot, tick, selection, active and hovered characters, cursor position, Ctrl/Shift/Alt modifiers, pause and speed state, screen size, UI scale, camera, Project(point) (world-to-screen projection), open screens, player key bindings, and Notify(text, error) for HUD notifications.

Keep it fast, queue commands for state changes, and never store the ModFrame reference beyond the callback. Key actions receive the same view via ModKeyContext.Frame.

Combat

Hook Signature What it does
Hit filter ICombatHitFilter.HitLanding(World, ref PendingHit hit) Modify the DamagePacket (cut, blunt, pierce, stun, bleed, armour penetration) before armour is applied, or set Cancelled = true (turns a melee hit into a miss or lets a bolt pass through). Runs before hit observers. Does not fire for doors or walls.
Hit observer ICombatHitObserver.HitResolved(World, in CombatHit hit) Fires for every landed melee hit, bolt hit, and execution blow, reporting damage dealt, armour absorbed, body part, attacker, and victim.
Hit feed c.AddCombatHitFeed(hits => ...) Visual-only feed (blood, hit markers). Runs once per frame on the render thread with all hits since the previous frame.
Hit reactions IBlowReactionFilter.Reaction(World, in BlowReactionAsk) returns BlowReactionKind Override the stagger caused by a hit or bolt: None, Light, or Heavy (knockback). Runs serially on hit.
Armour IArmourFilter.Piece(World, in ArmourAsk) returns ArmourPiece Override a worn armour piece's stats when a hit checks it (useful for degraded, enchanted, or dynamic gear). Coverage still comes from the FCS record. Runs serially.
Combat speed ICombatSpeedFilter.Rate(World, in CombatSpeedAsk) returns a rate Scale attack speed, block speed (can exceed vanilla caps), crossbow reload rate, or bolt flight speed. Runs concurrently on any thread.
Defences ICombatDefenceObserver.Defended(World, in CombatDefence); ICombatDefenceFilter.Defence(World, in DefenceChoiceAsk) returns a technique Observe every blocked, parried, or dodged melee attack, or pick which block/dodge technique a fighter attempts (-1 for none). The filter runs concurrently on any thread.
Target choice ITargetScoreFilter.Score(World, in TargetScoreAsk) returns a score Adjust how fighters, combat joiners, aggro checks, and assaults score potential targets (highest score wins). Runs concurrently on any thread.
Engagements ICombatEngageFilter.Allows(World, in EngageAsk) Block a fight from starting (EngageKind.Start, serial) or veto a candidate during target selection (Choice, any thread). First veto wins.
Combat moves c.AddCombatMove((world, id, tick) => CombatMove?) Play a CombatTechnique animation, or any ANIMATION clip via CombatMove.Clip(animation, progress) (such as kneeling or crouching), whenever the game isn't playing its own animation. Visual only; deals no damage. Runs in parallel: must be fast, read-only, and deterministic.

Concurrent filters (any thread) must be fast, thread-safe, and strictly read-only against settled tick state. If a filter throws or returns an out-of-range value, the engine keeps its default value, stops calling that filter starting on the next tick, and logs the fault into the state hash.

Custom weapons, weapon classes, and firearms are mostly data-driven; see "Weapon types" and "Ammunition" in docs/modding.md. To make a weapon train a custom skill, register the skill with c.AddSkill and reference it in the WEAPON record's meitou skill field.

Characters

Hook API Notes
Deaths ICharacterDeathObserver.Died(World, in CharacterDeath d) Fires for every death, both on-screen and in off-screen platoon fights, with cause, DeathSite, killer, and killer's faction (none for bleeding, starvation, etc.). If your mod kills a character directly, call Deaths.Report(world, victim, killer, site) so observers get notified.
Experience IExperienceFilter.Gain(World, in ExperienceGain g) returns amount Scale or zero out XP gains by character, stat, or ExperienceSource. The input carries Level and Cap; override Adjust to raise or lower the level cap (even above 101). Runs concurrently on any thread: keep it fast, thread-safe, and read-only.
Need rates INeedRateFilter.Rate(World, in NeedRateAsk) returns rate Change how fast a character's needs drain (NeedKind.Hunger); the HUD updates to match. Runs in parallel: keep it fast, thread-safe, and read-only.
Health changes IHealthChangeObserver.HealthChanged(World, in HealthChange) Reports every change to flesh, stun, bandages, splints, or blood, with before/after values and HealthChangeKind (hit, body, first aid, environment, eaten, rack, other). Fires once per tick after SlowWorld.
Removals IRemovalVeto.Keep(World, in RemovalAsk) Prevent a corpse from decaying or unloading, or stop a platoon from despawning (RemovalKind). Checked again on the next cleanup pass. PlatoonOrphaned can run on any thread.
Refresh CharacterRefresh.Refresh(c.Population, cold, kind) Rebuild a character's combat stats, drawn weapon, gear colours, or appearance after modifying worn gear (Equipment) or visuals (Look). Serial phases only.
Placing CharacterPlacement.Place(world, characters, at) Teleport living characters to a location immediately (for custom starts, scene transitions, or fast travel). Spreads them out like a move order and clears their order queues. Use WalkableNear to just find valid positions. Serial phases and IWorldReady.
Stat modifiers cold.Stats.Modifiers.Set(key, stat, amount) / Remove / RemoveAll Apply temporary +/- stat bonuses. Displayed in the stats window, never trained into base stats, and not saved.
Carry capacity cold.Stats.CarryModifiers.Set(key, CarryTerm.Scale or Kilograms, amount) Adjust carry weight without changing 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 buffs/debuffs 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 Adds a custom skill at the bottom of a stats-window column. Saved with the character. Keep the ID stable (numeric stat indices depend on load order).
Medical meters c.AddMedicalMeter(label), then meter.Set(cold, reading) Adds a progress bar to the medical panel below Hunger. Maximum of four across all mods. Visual only.
Task bars cold.ModTaskBar = new TaskBar(caption, progress) Floating progress bar above a character (like lockpicking). Only clear bars you set. Visual only.
Bone anchors cold.DrawAnchor = new DrawAnchor(carrier, bone, offset, rotation) Attach a character's rendered model to another character's bone (e.g. a rider on a mount). Visual only.
Bone meshes cold.SetBoneMesh(new BoneMesh(key, mesh, bone, offset, rotation)) / RemoveBoneMesh(key) Attach a rigid mesh to a bone (e.g. a saddle). Visual only.
Lasting IDs world.LastingIds.GetOrGive(character), Find(id), KeptIds() Persistent 64-bit character IDs that survive across saves. Shared across all mods.
Hunger level cold.FedTo Override the minimum hunger level for a character (e.g. a captive carried by your squad). Not saved.
Body shapes Data only Races can have any number of body parts, missing or extra limbs, and new part types (like tails) defined via FCS records. See bodies of other shapes.

Items and trade

Hook API Notes
Item use c.AddItemUse(recordId, use => bool) Handles right-clicking an item in the player's inventory. Return true to consume the click (call Inventory.RemoveOne to use up the item) or false to fall back to normal equip/move behavior. Use ItemInstance.ModTag to store a saved custom string on an item.
Items used up IItemUseObserver.ItemUsedUp(World, in ItemUsed u) Fires whenever an item is consumed: food bites, medkit charges, fired bolts, building materials, broken tools, machine inputs, research materials, and read maps/blueprints.
Items created IItemCreatedObserver.Created(World, in ItemCreated) Fires for every newly spawned item (loot, crafted goods, shop stock, starting gear). You can set ModTag here to attach rolled affixes or conditions.
Trade prices ITradePriceFilter.Price(World, in TradeDeal deal, long price) returns price Override prices shown in the trade window and paid by NPC shoppers. deal.Item gives full access to the item (ModTag, quality, maker). Must be read-only because prices are queried multiple times.
Sales ITradeObserver.Traded(World, in TradeSale) Fires after every completed trade (NPC shoppers and player trades), after money and items change hands, with buyer, seller, site, price, and buy-back flag.
Storage use IStorageFilter.Allows(World, who, storage, StorageUse, record) Prevent autonomous AI searches (food, looting, hauling, machine inputs/outputs, building materials) from using specific containers (e.g. private chests or quarantined storage). Never blocks player drags or direct orders. Runs on any thread.
Inventory arrange IInventoryArrangeFilter.Arrange(World, in InventoryArrangeAsk) returns InventoryArrangement? Customize inventory grid sorting whenever the game arranges items (ARRANGE button, making room, shop stock). Call InventoryCommands.Arrange(world, root, owner, reason) to trigger it from a custom button.
Equipment slots c.AddEquipmentSlot(new ModSlot(section, fcsSlot, w, h, x, y)) Adds a custom worn-gear slot. See Writing code mods.
Wear rules c.AddWearRule((item, race, animal) => bool) Block a race from equipping an item, checked after the item's built-in race restrictions. Runs on any thread: must be fast and deterministic.

Crime and factions

Hook API Notes
Crimes ICrimeObserver.CrimeNoted(World, in CrimeEvent e) Fires on every pending crime or bounty transition (CrimeEventKind: Pending, Witnessed, Booked, Lapsed, Expired, Cleared). Inspect CharacterCold.Bounties / Pending for characters you haven't tracked from the start (character IDs reset on load).
Goods taken IGoodsTakenObserver.GoodsTaken(World, in GoodsTaken t) Fires whenever a player character takes items owned by someone else, even when vanilla wouldn't treat it as a crime, letting you enforce custom laws.
Relation changes IRelationChangeObserver.RelationChanged(World, in RelationChange r) Fires on every faction relation change along with its RelationCause (deed, crime, captive sold, dialogue, war, debug). You may modify relations from inside this callback.
Bounties CrimeSystem.AssignBounty(world, character, faction, amount) / ClearBounty(world, character, faction) Add or clear a bounty directly (like dialogue actions do), without triggering a crime event or message. Serial phases and IWorldReady. Still notifies crime observers as Booked / Cleared.
Steal roll CrimeSystem.StealRoll(world, thief, watcher, chance, faction, victim) Run vanilla's theft detection roll for custom stealing mechanics. If caught, triggers watcher reaction, Theft crime, and Thievery XP; returns true when caught. Serial phases only.
World states var state = c.AddWorldState(recordId), then state.Set(world, bool) / Clear(world) Override a WORLD_EVENT_STATE from code; dialogue, spawns, town overrides, and campaigns follow your value. World decisions made under it persist in the save.
Faction list c.ArrangeFactionList(rows => rows) Reorder, rename, hide, or group entries on the Overview screen's Factions tab. Runs on the host thread.

Dialogue

c.AddDialogueCondition(1000, check => check.Matches(IsRaining(check.World)));
c.AddDialogueEffect(1000, act => act.World.Post("Something happened"));

Use your registered code as a DIALOG_ACTION's condition name or action name. Conditions must be read-only (they run for UI previews too), while effects run serially when the line plays. See Writing code mods.

AI and behaviour

All characters (player and NPC) pick what to do through one unified chooser: direct orders first, then jobs and goals by priority tier and score, then a fallback task. See AI goals and orders for a complete tutorial and worked example. Requires API 3; for hooks replaced in API 3, see Moving from API 1 or 2.

Goals, jobs and orders

  • Goals (chosen dynamically by the AI): claim a task ID (1000+) with c.AddGoalType(type, name), add an AI_TASK record with that enum to an AI_PACKAGE or AI Goals list, implement IChooserOwner on your system, and register an IModGoal via chooser.Goal(type, goal). Desire runs concurrently on multiple threads (pure, deterministic read); Start runs serially to launch the character's task with TaskSource.Goal; End fires if the goal loses control. Finish your goal early with ModGoals.Done and check ownership with ModGoals.Holds. Active goals are not saved.
  • Mod jobs: claim an ID (1000+) with c.AddJobType(type, name), register an IJobSource via chooser.Jobs(type, source), and add jobs to CharacterCold.Jobs. Works for any character with a job list. Saved in the character's job list and cleanly dropped on load if the mod is uninstalled.
  • Orders: call world.GiveOrder(actor, row, target, site, point, queued) from a serial phase to issue a direct order to a player character or NPC through the player's order queue (e.g. TaskType.MoveCusOrdered to move to point).
  • Checking goal membership: query AiSystem.WeighsGoal(world, slot, type) or PopulationSystem.GoalDuty(world, squad, role, type) from a serial phase.
  • Desire filters: register an IGoalDesireFilter via chooser.DesireFilter(...) to adjust any character's desire scores for built-in or mod goals, plan steps, queued orders, and jobs (GoalDesireKind). Runs on any thread: keep it fast and read-only.
  • Workplace slots: call AiSystem.WorkSlots(building) from a serial phase to check how many operator slots are held vs. free before assigning a worker.
  • Starting character actions: inside a goal or job, drive characters using TaskStart.Walk, CharacterOrders.Sneak, LockSystem.Picking.Step (with LockSystem.WorkSpot), CrimeSystem.Pickpocket, CarrySystem.BeginPickUp / BeginPutDown, ArrestSystem.TakeOver, AggroSystem.Spotted / Unseen, and ProductionSystem.SitOn.

Shared plumbing

  • Task handlers: implement ITaskOwner and call t.Register(row, handler) inside RegisterTasks(TaskHandlers t) for any task row (1000+) you claimed. Your ITaskHandler receives Start, End(task, TaskEnd), and Done callbacks in serial phases. Call tasks.Of(task) if you want to chain onto the built-in movement handler.
  • Goal claims: implement IGoalSource.Publish(World, SquadGoals goals) to publish (worker, target) pairs so squadmates' AI finders (looting, first aid, errands) don't pick targets your characters are already handling. Claims expire 3 seconds after their last publish. Read-only, fixed order.

Squads, towns and the world

All calls and commands below run in serial phases. Whenever a command accepts Owner: context.Id, pass it: if a player later loads the save without your mod, Meitou automatically returns control of the squad to the player with a notice instead of stranding the save.

Hook What it does
SetSquadAutonomy(squad, on, Independent, Owner) Hands a player squad over to AI control. Pair with ChangeAi, StartContract, EndContract, and SetSquadHome to assign packages and a home base. Set Independent: true for player-faction squads the player shouldn't command directly (staff, caravans). StartContract { AnyRange = true } removes range limits on contract assaults.
SetSquadPackages(squad, packages) Assigns multiple AI packages by slot at once (ChangeAi is the single-package shortcut). Saved, and works on NPC squads too.
SetSquadOptions(squad, options, Owner) Gives a player-faction squad its own SquadAi flags (sit, sleep, share food, heal, etc.) instead of using the global player settings. Pass null to revert.
SetSquadUncounted(squad, on, Owner) Excludes a squad from the faction's max faction size limit.
SetSquadPurse(squad, own, Owner) Gives a squad its own separate cats balance for trading and expenses.
SetSquadShop(squad, on, Template, Owner) Turns a player-faction squad into a shopkeeper that the player can trade with.
SetSquadDormant(squad, on, Owner) Puts a squad to sleep so its zone can unload normally.
PopulationSystem.SpawnPlatoon Spawns an NPC platoon from a SQUAD_TEMPLATE near a point with a starting purse. Setting maxMembers > 0 caps its size (taking the first members from the template, leader first), preserved if the squad respawns.
Platoon.ModTags[c.Id], world.Platoons.FindByTag(c.Id, tag) Attach a saved string tag to a platoon so you can locate it after reloading (numeric platoon IDs change on load). The older Platoon.ModTag is a single string shared across all mods.
PopulationSystem.SpawnIntoPlayerSquad / JoinPlayerSquad Spawns a new character directly into a player squad (use the 5-argument overload to spawn an animal at a specific age), or moves an existing NPC into it.
population.DespawnPlatoon(world, platoon) Permanently removes a platoon (cannot be used on town garrisons or player squads).
PopulationSystem.RequestCampaign Queues a FACTION_CAMPAIGN against a town, just like dialogue actions do.
PopulationSystem.HoldPlatoon / SendPlatoon Off-screen only: freezes a roaming platoon's stand-in and routes it toward a point or character. Once it loads on-screen, steer it with orders, goals, or package changes (see Platoons off screen). Passing your c.Id creates a named hold that saves with the platoon and prevents other mods from interfering; unnamed holds are not saved.
IPlatoonObserver.PlatoonChanged(World, in PlatoonNotice) Fires once per tick when platoons are Added, Removed (with reason: despawned, lost a fight, empty, mod-removed), Loaded, Unloaded, or Arrived at a destination your mod set.
IOffscreenFightRule.Judge(World, first, second) Override off-screen combat between hostile platoons: return Fight, Skip, FirstWins, or SecondWins. Every rule is consulted; any Skip cancels the fight.
PopulationSystem.Data.Roads Read-only road graph used by off-screen travel (NearestRoad, RoadsNear, Route, junctions, roads, points). Safe from any thread.
ConstructionSystem.PlaceSites(world, plans, complete) Places player-faction buildings just like build mode's Confirm (complete: true finishes them immediately). Place interior furniture in a second call with the building as Parent. Returns the created sites and outpost for SetSquadHome.
VisitTown command Sends a wandering trader to visit a player outpost for N hours.
BedSystem.PlayerBedRent Makes NPCs pay rent to sleep in player-owned beds.
Squad.ModTags[c.Id], PlayerTown.ModTags[c.Id] Persistent string tags on player squads and outposts (their numeric IDs change on every load).
ProductionSystem.SitOn(world, slot, seat, row, source) / CanSit Seats a player character or NPC on a chair or throne after validating the seat, character, and doors (CanSit runs the same check without side effects). Built-in AI sitters always take priority. Not saved; re-seat after loading.

Interface and input

All UI and input callbacks run on the host thread. Never modify world state directly; queue commands instead.

Hook API Notes
UI extension c.AddUi(IUiExtension) Register custom styles, controls, actions, overrides for vanilla UI, and HUD slot widgets (UiSlots). Supports mod images (UiNodeKind.Image), single-line text inputs (UiNodeKind.TextBox with Focus and Submit on Enter), and scrolling lists (UiNodeKind.ScrollView with ScrollTo / ScrollOffset).
Node styling & pointer events TextScale, TextColour, Opacity, ImageCrop, inline #RRGGBB colour tags; Pointer (Release, Drag, Wheel, Hover) and Buttons Style individual nodes without creating a style preset. Receive drag deltas (e.g. draggable windows), drop targets (Over), mouse wheel, hover, and extra mouse buttons via UiActionContext.Kind. Set ShowWithHudHidden to keep an overlay visible when F7 hides the HUD.
Fallback fonts registration.AddFallbackFont(path) Register a TTF/OTF font used whenever the active UI font lacks a glyph (such as CJK characters or symbols).
Screen controls registration.AddScreenControls(screen, anchorWidget, placement, ctx => node) Inject custom UI nodes inside or beside widgets on built-in screens and the HUD. Supports UiScreens.ItemCells (per item slot), UiScreens.Portraits (badges on squad portraits), and MapImage on the Overview map.
Screen overrides registration.AddScreenOverrides(screen, widgetPattern, ctx => override) Change a built-in widget's label or text colour, or hide it completely.
Screens & game speed c.Interface (ModInterface) Open the character editor, Overview tabs, or build mode; inspect screen bounds; select a building in build mode; read/set game speed and pause; call HoldPause() to keep the game paused while your window is open.
Right-click menu registration.AddCharacterMenuVerbs(ctx => rows); registration.AddMenuVerbs(ctx => rows) Append custom actions to a character's context menu or any target's menu (containers, doors, buildings, ground items, terrain). Set Unavailable = true to grey out an option (Shift-clicking still selects it). Called every frame while hovering a target, so keep it fast.
World map input registration.AddMapInput(input => taken) Intercept mouse clicks and key presses on the world map, with helpers to convert between map, world, and screen coordinates. Return true to consume the input.
Job offers c.AddJobOffer(new ModJobOffer(type, buildings, caption, takers)) Adds a right-click menu option on matching player buildings that assigns your custom job to the selected characters.
Placement rules c.AddPlacementRule(rule) Override build mode's placement checks: allow something normally blocked (Waive) or add a new restriction (Refuse). Evaluated on every preview ghost; keep it fast and read-only.
Character panel registration.AddCharacterPanelLines(ctx => lines), AddJobPanelButtons(ctx => buttons, layout) Add stat lines (label, value, bar, or button) to the HUD character panel, and add custom buttons beside the jobs list.
Item tooltips registration.AddItemTooltipLines(ctx => lines) Add custom lines to item tooltips. Check ctx.First to detect when a newly created item is first inspected (useful for rolling and tagging).
Line styling Style = new UiLineStyle(Label, Value, Icon) Customize text colours and icons on tooltip, character panel, and town panel lines.
Dialogue replies registration.AddDialogueReplies(ctx => replies) Append custom player response options to the conversation window.
Map markers registration.AddMapMarkers(ctx => markers) Place custom markers on the world map using built-in icons or your own PNG/DDS files (up to 64 files).
Squad AI tab registration.AddSquadAiOptions(ctx => options) Add custom checkboxes to the Squad Overview's AI tab. Your system is responsible for saving their state.
Building panel registration.AddBuildingActions(ctx => buttons) Add buttons to the selected building panel (stick to one or two). Always verify the building still exists when your queued command executes.
Town panel registration.AddTownPanelLines(ctx => lines) Add label/value rows or command buttons to the HUD town panel. Only four mod lines show total across all mods, so keep to one. Return the same set of lines consistently for a given outpost (update only their text), and verify the outpost still exists when commands run.
Key actions c.AddKeyAction(name, label, ctx => ..., defaults) Register a rebindable hotkey on the Controls page (saved in meitou.user.json). Escape, F6, Alt, Ctrl, and Shift cannot be defaults. Check ctx.Ctrl / Shift / Alt for held modifiers, or bind key chords with Binding.Of(Key.P).With(KeyModifiers.Ctrl).
Settings c.AddSettings(object) Expose [Setting] properties on the Settings screen's Mods tab (see Writing code mods). To update a setting from code (such as saving a window's position), call Settings[i].Set(value) or Reset() on the host thread so it persists cleanly.
Debug rows c.AddDebugCommand(label, ctx => status, hasField) Add entries to the F10 debug menu.
Sounds world.PostSound(event, character or point), world.PostInterfaceSound(event) (also on ModContext) Play any one-shot sound event from loaded base-game or mod sound banks (any thread, visual only). On ModContext, passing a .wav filename plays a loose 16-bit PCM file from your mod folder (up to 20 seconds), and PostSound(sound, EffectAnchor, volume) attaches a sound to an anchor (host thread).

Visual effects

Visual-effect methods live on ModContext and must be called on the host thread (for example from a hit feed, UI action, key action, or frame callback), never from a simulation tick system. They are display-only, are not saved or hashed, and clear automatically when a new world loads. Invalid requests return false and log a warning once.

Hook API Notes
Anchors EffectAnchor.At(point), Bone(character, bone), Weapon(character), Building(id), Projectile(id) (plus .Scaled, .Sized, .Pulsing) Defines where an effect, trail, or sound attaches. Follows the target every frame and pauses if the target temporarily disappears.
Particle bursts PlayEffect(effect, anchor, seconds, tint); KeepEffect(...) / StopEffect(effect, anchor); HasEffect(effect) Plays an FCS EFFECT record or Particle Universe system. KeepEffect maintains one persistent effect per mod and anchor (such as an aura or flaming sword), refreshing its timer when called again.
Trails KeepTrail(anchor, TrailStyle, seconds) / StopTrail(anchor) Draws a ribbon trail behind an anchor, or a flat blade slash ribbon when Span is set.
Glow and tint Glow(GlowTarget, colour, seconds, strength); Tint(GlowTarget, colour, seconds, amount, throughWalls); StopGlow(target) Highlights or tints a character, drawn weapon, or worn gear slot. Setting throughWalls: true on Tint reveals the character through obstacles.
Projectile feed AddProjectileFeed(events => ...) Fires once per frame with bolts Fired, Landed, and Gone between rendered snapshots.

Data you define

Hook API
Record types Reserve with c.AddRecordType(5000, "MY_THING"), then read with c.Records(5000).
Weather kinds Set affect type (1000+) on a WEATHER or EFFECT record, pair with ARMOUR weather protection<N> and RACE weather immunity<N>, and handle its gameplay effect in your system.
Weapon skills & classes Set WEAPON meitou skill, and WEAPON / COMBAT_TECHNIQUE meitou class.
Ammunition Set CROSSBOW meitou ammo, and ITEM meitou damage mult, meitou bleed mult, meitou range mult, meitou speed mult, and meitou live ammo.

All meitou ... fields are specific to MeitouClient and safely ignored by the original game. See docs/modding.md for instructions on adding them in FCS.

If you are building a total conversion mod, edit engine-referenced records in place rather than deleting or renaming them. Fixed record ids lists every record Meitou looks up by ID or name and explains what happens if it is missing.