# perception
What an observer can see and how fast it notices. Pure maths, no engine.
```
An observer stands at (x, y, z) facing (fx, fz) on the ground plane and is of a kind the config describes
(range by light, half-angle, a near range that works whatever way it faces, and optionally how far up and
down it looks). The host supplies the one thing geometry cannot: whether the line between the two is blocked
(`hasLine`, from a physics ray or anything else).
local Perception = require("~.modules.perception")
local seen, distance = Perception.inView(kindCfg, light, ox, oz, fx, fz, tx, tz) -- flat ground
local seen, distance = Perception.inView3(kindCfg, light, { x, y, z, fx, fz }, { x, y, z })
-- with heights: distance is the straight line; kindCfg.vertical = { up, down } (degrees) limits how steeply
-- it looks (someone on a roof is not seen by a guard with up = 35 standing at the wall's foot)
local rate = Perception.fillRate(cfg, "guard", {
distance = distance, inView = seen, hasLine = true, light = 1,
act = "wanted", concealment = { "crowd" }, described = 0.5, strikes = 0, known = false,
}) -- awareness per second (0 when it cannot see or there is nothing to see)
-- described: false / true, or 0..1 = how much of a held description the suspect matches
-- known: this observer knows the suspect's face (cfg.known.fillFactor applies, and it notices even an idle one)
local yaw = Perception.sweep(baseYaw, arcDegrees, period, t) -- a camera panning to and fro
Light is 0 (dark) .. 1 (full day). Angles are degrees. Distances are metres.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# arrest
Being caught, as a staged sequence with hooks, and its bill as an itemised list.
```
The stages are data (cfg.arrest.stages), each with a name, a duration and what the suspect may do in it:
breakable + breakHold the suspect can get free by holding the break input that long, if it has a charge
skippableAfter the stage can be ended early by the skip input after that many seconds
control a name for the host's input layer ("break", "skip", "none")
The sequence moves nobody and draws nothing. It calls hooks at every boundary so animation, camera and UI stay
in step with it:
local Arrest = require("~.modules.arrest")
local seq = Arrest.new(cfg.arrest, {
onStage = function(stage, ctx) end, -- a stage begins: play the animation, cut the camera, show UI
onStageEnd = function(stage, ctx) end,
onBreak = function(ctx) end, -- the suspect got free
onDone = function(ctx) end, -- the last stage ended
})
seq:begin({ charges = 1, by = "w3", level = 2, bill = bill }) -- ctx is passed to every hook
local status = seq:tick(dt, { breakHeld = false, skip = false }) -- "running" | "broke" | "done" | "idle"
seq:view() -- { stage, index, count, time, duration, progress, breakable, breakProgress, canSkip, charges }
The bill is computed by a pure function from rules the game supplies, so the UI shows exactly what is taken:
local bill = Arrest.bill({
fine = { base = 40, perLevel = 35, walletShare = 0.5 }, -- min(wallet * share, base + perLevel * level)
confiscate = { carried = true, vehicle = true, vehicleWithin = 30 },
strikes = 1, maxStrikes = 3, hours = 2,
}, { wallet = 180, level = 2, carried = 9, vehicleStock = 40, vehicleDistance = 12, vehicleProtected = false,
strikes = 0, work = "fish-market wall" })
-- { lines = { { key = "fine", amount = 90 }, { key = "carried", amount = 9 }, { key = "vehicle", amount = 40 },
-- { key = "work", name = "fish-market wall" }, { key = "strike", amount = 1, total = 1 },
-- { key = "hours", amount = 2 } },
-- fine = 90, carried = 9, vehicle = 40, strikes = 1, hours = 2, work = "fish-market wall" }
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# grab
The moment of capture, made readable: a telegraphed reach on foot, a closing box
```
round a vehicle. Neither is a distance check that fires at once.
On foot each pursuer has a Reach: in range with a clear line it winds up (the animation and sound hook); when
the windup ends the grab lands only if the suspect is still inside the escape distance with a clear line,
otherwise it misses and the pursuer recovers before trying again.
local Grab = require("~.modules.grab")
local reach = Grab.reach(cfg.grab)
local phase, event = reach:tick(dt, distance, hasLine, factor?)
-- factor (default 1) scales the reach and the escape distance: a suspect who cannot run is easier to take
-- phase: "idle" | "windup" | "recover"; event: nil | "windup" | "hit" | "miss" | "ready"
reach:progress() -- 0..1 through the windup (drives the HUD flash and the arm's blend)
reach:cancel() -- the pursuer was stunned or blinded
In a vehicle the suspect is boxed when it is nearly stopped with a pursuer close for long enough:
local box = Grab.box(cfg.grab.vehicle)
local progress, done = box:tick(dt, speed, nearestPursuerDistance) -- 0..1, true when it completes
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# hub
A small event hub: named events, plain payload tables, no engine.
```
Every pursuitKit system reports what happened through a hub the host passes in, so animation, camera, sound and
UI subscribe to moments instead of polling state.
local Hub = require("~.modules.hub")
local hub = Hub.new()
local off = hub:on("state", function(e) print(e.from, e.to) end)
hub:emit("state", { from = "clear", to = "noticed" })
off() -- disconnect
hub:onAny(function(name, e) ... end) -- every event (a log, a recorder, a test)
A handler that errors does not stop the others; its message is kept in hub.lastError.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# incident
The pursuit as a state machine with named, timed, observable states.
```
clear ──(someone is noticing)──> noticed ──(a report lands)──> reported ──(responders arrive / timeout)──┐
^ │ └────────(a pursuer is certain)────────┐ │ v
│ └─(nobody is)─> clear v └──(a pursuer is certain)──> pursuit <──(seen)── search
│ pursuit ──(unseen for loseSight)────────────────────> search
└──────────── escaped <──(the search timer runs out)──────────────────────────────────────────────────────┘
pursuit ──(a grab completes)──> arrest ──(the arrest sequence ends)──> released ──> clear
It owns the last known position (where the pursuers believe the suspect is) and the search area (centre,
radius growing with time, time left). It does not move anyone: pursuers read it.
local Incident = require("~.modules.incident")
local inc = Incident.new(cfg, heat, hub?) -- cfg: kit config; heat: a heat.module meter
inc:tick(dt, {
awareness = 0.4, -- highest observer meter
seen = false, -- a pursuer is certain AND has eyes on the suspect now
x = 0, z = 0, -- where the suspect is
hidden = false, -- the suspect is in a hiding place
reports = { { x, z, offence } }, -- reports that landed this tick
responderAt = false, -- a responder has reached the last known position
})
inc.state inc.time (seconds in this state) inc.lkp = { x, z }
inc.search = { x, z, radius, left, duration } while searching (else nil)
inc:arrest() -- a grab completed: state "arrest" (the arrest module runs the sequence)
inc:broke() -- the suspect broke free: back to pursuit
inc:release() -- the sequence ended: "released" for one tick, then clear; heat reset by the host's rules
inc:view() -- { state, time, level, levelName, heat, lkp, search, timer = { left, duration } } for a HUD
Events on the hub: "state" { from, to, level }, "lkp" { x, z }, "searchStarted" { x, z, radius, duration },
"escaped" { level, name, heatBefore }, "arrested" { level }, "released" {}.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# awareness
One meter per observer, 0 (unaware) to 1 (certain), with two thresholds.
```
Each tick the host says how fast each observer that can currently see the suspect is filling (from
perception.fillRate); everyone else drains. Crossing a threshold is a moment, returned as an event:
local Awareness = require("~.modules.awareness")
local aw = Awareness.new(cfg) -- the kit config (reads cfg.observers[kind])
local events = aw:tick(dt, { { id = "w1", kind = "guard", rate = 0.6 }, ... })
-- events: { type = "suspicious" | "alert" | "calm", id, kind, onAlert? }
aw:value("w1") aw:stage("w1") -- 0..1 and "unaware" | "suspicious" | "alert"
aw:max() -- highest value, and whose (the HUD's meter)
aw:forget("w1") -- the observer left the world
aw:set("w1", "guard", 1) -- a host-forced value (a radio call that tells a guard for certain)
aw:snapshot() -- { { id, kind, value, stage } } sorted by value, for UI
An observer stays "alert" until it has drained below its suspicious threshold again ("calm"), so a pursuer that
loses sight for a moment does not forget whom it was chasing.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# description
What the pursuers know the suspect looks like, and losing it.
```
A description is a set of tags with values ("jacket" = "ochre", "vehicle.kind" = "van", "vehicle.colour" =
"blue", "vehicle.plate" = "VR 1123"), noted when the suspect
is identified. While the suspect's current appearance matches any noted tag, observers treat it as worth
looking at (perception's `described`). Changing the thing a tag describes, out of sight, sheds that tag.
local Description = require("~.modules.description")
local d = Description.new()
d:note({ jacket = "ochre", vehicle = "blue van" })
d:matches({ jacket = "ochre" }) -- true, { "jacket" }
d:matches({ jacket = "grey", vehicle = nil }) -- false, {} (on foot, jacket turned)
d:strength({ jacket = "ochre" }) -- 0..1: the share of what they know that the appearance matches
d:shed("jacket") -- they no longer know the jacket (returns true if they did)
d:known() -- { jacket = "ochre", ... } a copy, for UI
d:clear()
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# heat
How wanted the suspect is: one number, cut into named levels by data.
```
Heat only rises through named offences (cfg.heat.offences) and, while a pursuit lasts, by a slow tick. It only
falls while nobody is looking, after a grace period. Level changes are moments (returned and emitted).
local Heat = require("~.modules.heat")
local heat = Heat.new(cfg.heat, hub?) -- hub (pursuitKit.modules.hub) is optional
heat:add("seen") -- points for a named offence; returns points added
heat:addPoints(5, "scripted") -- raw points
heat:tick(dt, "pursuit" | "clear" | other) -- pursuit ticks up, clear decays after the grace, others hold
heat:escaped() -- applies cfg.heat.escape.factor
heat.value heat:level() heat:levelName() heat:fraction() -- 0-based level; share of the way to the next
heat:setDecayFactor(1.5) -- a host rule (friendly ground cools faster)
Events on the hub: "heat" { value, level, name, delta, offence }, "heatLevel" { from, to, name }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# reports
Reports on their way: a witness walking to a call box, a camera holding its view.
```
An observer whose kind answers an alert with a report does not raise heat at once. It opens a pending report
that lands after a delay, and can be cancelled before it does (the relay was jammed, the witness lost interest,
the camera was blinded). That delay is the player's window, so it is explicit and observable:
local Reports = require("~.modules.reports")
local rp = Reports.new()
rp:open("cit7", { delay = 4, via = "relay", offence = "reported", x = 10, z = -4, relay = "box3" })
rp:hold("cit7", true) -- pause it (the witness has not reached the relay yet); hold(id, false) resumes
rp:cancel("cit7") -- returns true if there was one
rp:cancelRelay("box3") -- every report going through that relay; returns how many
local landed = rp:tick(dt) -- { { id, offence, x, z, via, relay } } that arrived this tick
rp:pending() -- { { id, left, delay, via, relay, held } } soonest first, for the HUD
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# pursuitKit
Being noticed, being hunted, getting away, getting caught: as data-configured, engine-free logic any game can
drive. Nothing in it names a game, a city, a guard or a crime. The host says where observers and the suspect are
and whether the line between them is clear; the kit answers with states, timers and events, and with intents for
pursuers on foot and in vehicles.
**Status:** every module's logic is covered by case modules that run in the engine's Luau VM in edit mode
(`tests/cases/{core,response,standing}`, 92 cases; see "Tests"). The kit has NOT been run against a scene: the
raycast adapter and everything a host stages (animation, vehicles, sound) are untested here.
## What is in it
| Module (`require("pursuitKit.modules.<name>")`) | What it does |
|-|-|
| `config` | `DEFAULTS`, `merge(base, over)` (`Config.NONE` drops a default), `validate(cfg)`: the whole kit's behaviour as one table |
| `hub` | named events: `on`, `onAny`, `emit` |
| `perception` | view cone in 2D or 3D (`inView3`, `vertical`), range by light, fill rate, panning (`sweep`) |
| `awareness` | one 0..1 meter per observer with suspicious/alert thresholds and events |
| `reports` | pending reports with delays, holds, relays that can be jammed |
| `heat` | offences → points → named levels; pursuit tick; decay after a grace; escape factor |
| `incident` | the state machine: clear, noticed, reported, pursuit, search, escaped, arrest, released; last known position; search area |
| `grab` | the telegraphed reach on foot (`reach`) and the vehicle box-in (`box`) |
| `arrest` | the staged arrest with hooks, break-free and skip; several `sequences` (arrest, detain-and-eject, hand-over); `Arrest.bill(rules, facts)` |
| `dispatch` | who is sent where for a heat level: `plan`, `sweepPoints`, `cordon`, `entry` |
| `pursuer` | one pursuer's intent by profile (`cfg.pursuer[name]`: speeds, leash, home, look-round on arrival); writers for the character bus and the vehicle bus |
| `description` | what the pursuers know the suspect looks like (`strength` 0..1), shedding it |
| `firefight` | pursuers who shoot back: who is armed at a level, the aim telegraph, bursts, led and spread shots. Holds no projectile |
| `roadblocks` | blocks and bridge checkpoints on a road GRAPH the host supplies: ordered, standing, lifted; `plan` forecasts |
| `vehiclePursuit` | pursuit cars that work together: shadow, chase, box, ram, block, dismount where a car cannot go |
| `theft` | taking a vehicle: the offence by its state, the owner's delayed report, the hot list, lawful kinds |
| `roster` | pursuers as named people: beats, shifts, bribes and leverage, arrangements found out, faces remembered |
| `record` | strikes that fade; confiscated things in an impound with a growing fee and a sale date |
| `party` | several suspects in one world: heat is each one's own, shared with accomplices standing close |
| `director` | perception, awareness, reports, heat, incident, grab, arrest and description assembled behind `setObserver` / `setSuspect` / `tick` |
| `engineAdapters` | `lineOfSight` on `Physics.raycast`; `lightAt` / `lightByHour` (the only module that calls the engine) |
Every module's header comment is its reference: the calls, the shapes they return, and its section of the config.
## Using it
```lua
local Config = require("pursuitKit.modules.config")
local Director = require("pursuitKit.modules.director")
local Adapters = require("pursuitKit.modules.engineAdapters")
local Arrest = require("pursuitKit.modules.arrest")
local cfg = Config.merge(Config.DEFAULTS, myGameConfig) -- see the schema in modules/config
assert(Config.validate(cfg))
local dir = Director.new(cfg, {
hasLine = Adapters.lineOfSight({ pass = isGlassOrCrowd }),
light = Adapters.lightByHour(function() return clock.hour end),
bill = function(level, ctx) return Arrest.bill(myBillRules, factsFor(level)) end,
})
dir.hub:on("state", function(e) hud.setPursuit(e.to) end)
dir.hub:on("arrestStage", function(e) cast.play(e.stage); camera.cut(e.stage); hud.arrest(e) end)
-- every frame
dir:setObserver(id, { kind = "guard", x = x, y = y, z = z, fx = fx, fz = fz })
dir:setSuspect({ x = px, y = py, z = pz, act = currentAct, concealment = tags, hidden = inHide,
appearance = { jacket = jacket }, inVehicle = driving, speed = speed, charges = slips })
dir:input({ breakHeld = interactHeld, skip = confirmPressed })
local view = dir:tick(dt) -- everything a HUD draws
dir:offence("fired_arm") -- something the game saw her do
dir:report({ offence = "stolen_vehicle", x = x, z = z, delay = 8, appearance = tags }) -- a report from outside
dir:noise({ x = x, z = z, radius = 30 }) -- observers in earshot grow suspicious
```
Pursuers (the host owns their entities):
```lua
local Dispatch = require("pursuitKit.modules.dispatch")
local Pursuer = require("pursuitKit.modules.pursuer")
local orders = Dispatch.plan(cfg, view.level, view, units) -- units: { { id, kind, x, z, available } }
for _, u in units do
local senses = dir:senses(u.id) -- sees, sx, sz, stunned, grabbing
senses.x, senses.z, senses.order, senses.path = u.x, u.z, orders[u.id], route(u, orders[u.id])
local intent = u.brain:decide(dt, senses) -- u.brain = Pursuer.new(cfg, "foot")
if u.kind == "foot" then
u.controller.inputX, u.controller.inputZ = Pursuer.characterBus(intent, u.x, u.z)
else
u.vehicle.inputThrottle, u.vehicle.inputSteer, u.vehicle.inputBrake, u.vehicle.inputHandbrake =
Pursuer.vehicleBus(intent, u.x, u.z, u.fx, u.fz, u.forwardSpeed, cfg.frame.right)
end
end
```
The response beyond the chase (each is independent; use what the game needs):
```lua
local ff = Firefight.new(cfg.firefight, rng) -- rng() -> [0, 1): the kit ships no generator
for _, e in ff:tick(dt, { level = view.level, suspect = s, shooters = shooters }) do
-- "aim" (stage the telegraph), "shot" { from, at, wash, speed, gravity, ... } (fly it), "lower"
end
local rb = Roadblocks.new(cfg.roadblocks, graph) -- graph = { nodes = { [id] = { x, z } }, edges = { { id, a, b, class, bridge } } }
for _, e in rb:update(dt, { level = view.level, state = view.state, x = lkp.x, z = lkp.z, radius = r }) do end
Roadblocks.plan(cfg.roadblocks, graph, { level = view.level + 1, x = x, z = z, radius = r }) -- forecast for a map
local vp = VehiclePursuit.new(cfg.vehiclePursuit, cfg.frame.right)
local intents = vp:tick(dt, { level = view.level, target = car, units = cars }) -- shadow | chase | box | ram | block | dismount
local theft = Theft.new(cfg.theft)
local r = theft:take(vehicle, { witnessed = seen, x = x, z = z }) -- the offence now, the owner's report later
for _, landed in theft:tick(dt) do dir:report(landed) end
local roster = Roster.new(cfg.roster, people, rng) -- named pursuers: onDuty, cover, arrange, use, sawFace
local record = Record.new(cfg.record) -- strike, confiscate, impounded, fee, release, dayPassed
local party = Party.new(cfg.party) -- join, place, together, charge, reported
```
## Interfaces the host provides
- **Line of sight** `hasLine(observer, suspect) -> boolean`. `engineAdapters.lineOfSight` is one implementation.
- **Light** `light(x, z) -> 0..1` (optional).
- **The bill** `bill(level, ctx) -> table` (optional; `Arrest.bill` builds one from rules).
- **A generator** `rng() -> [0, 1)` for firefight spread and roster rolls. Seed it: the kit is deterministic for a
given sequence of inputs and rolls.
- **A road graph** for road blocks, and a `path = { { x, z }, ... }` per pursuer per order (roads for cars, a nav
path on foot). The kit does not pathfind.
- **Movers**: a character with `inputX`, `inputZ`, `inputJump` and a vehicle with `inputThrottle`, `inputSteer`,
`inputBrake`, `inputHandbrake`, or any AI driver that accepts the intent (`mode`, a point, a speed).
- **Projectiles**: whatever flies a `shot` event from `from` towards `at` and reports what it hit.
- **Staging**: animation, camera and UI for `grabWindup`, `grabMissed`, firefight `aim`, and each `arrestStage`;
the kit gives the moments and durations and waits for nobody.
## Frame
Positions are `(x, y, z)` with y up; where only the ground matters `(x, z)`. `cfg.frame.right` is the sign of x
on the right of someone facing +z: `-1` in the Zero engine's frame (+x east, +z south), `1` in a z-north frame.
It decides flank sides and steering.
## Events (on `dir.hub`)
| Event | Payload | When |
|-|-|-|
| `state` | `from, to, level` | the incident changes state |
| `heat` / `heatLevel` | `value, level, name, delta, offence` / `from, to, name` | heat changes / crosses a level |
| `observer` | `type = suspicious, alert or calm; id; kind` | an observer crosses a threshold |
| `cheer` | `id` | an observer whose kind answers alert with "cheer" becomes certain |
| `reportOpened` / `reportLanded` | `id, delay, via, relay` / `id, offence, x, z` | a report starts its delay / arrives |
| `lkp` | `x, z` | the last known position moves by more than a metre outside a pursuit |
| `searchStarted` | `x, z, radius, duration` | a search begins |
| `escaped` | `level, name, heatBefore` | a search ran out |
| `grabWindup` / `grabMissed` | `by` | a pursuer starts / fails a reach |
| `arrested` | `level` | a grab landed |
| `arrestStage` | `stage, control, duration, ctx` | each stage of the sequence begins |
| `arrestBroke` / `arrestDone` | `{}` / `bill, level, sequence, outcome` | the suspect broke free / the sequence ended |
| `released` | `{}` | the incident is over after an arrest |
`firefight`, `roadblocks`, `vehiclePursuit`, `theft` and `record` return their events from `tick` / `update` /
`dayPassed` instead of emitting: the host decides which hub they go on.
## Rules the config must keep
`acts.wanted` (what a certain observer takes the suspect to be doing), `heat.offences.seen`, the offence named by
`arrest.breakOffence`, one `response` entry per heat level, `heat.levels[1].at == 0`, a `firefight.levels`,
`roadblocks.levels` and `vehiclePursuit.levels` entry per heat level when those sections are used.
`Config.validate` checks the structural ones and names what is wrong.
## Tests
The cases are modules (`tests/cases/*.module`, each returns `function(Test)`), registered by
`tests/pursuitKit.testSuite` for the engine's runner. The engine's runner closes and reloads the open scene, so
while a scene is being worked on run them in-process instead with `caseBench` (see its README): same cases, no
scene touched.