From 91ff9c6b8cc27417ac12d05095083e94b3d7daed Mon Sep 17 00:00:00 2001 From: opencode Date: Fri, 27 Nov 2026 22:13:13 +0000 Subject: [PATCH 01/30] Docs: Add the scripts spec Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 860 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 860 insertions(+) create mode 100644 specs/scripts.md diff --git a/specs/scripts.md b/specs/scripts.md new file mode 100644 index 0000000..a4ebbd1 --- /dev/null +++ b/specs/scripts.md @@ -0,0 +1,860 @@ +# scripts + +## 1. Role + +A scripted unit runs compiled COB code: eight threads per unit, each a stack machine over a word code +array, that wait, sleep, start and signal each other, move and turn the pieces of the unit's model, +read and set a handful of the unit's values, and draw from the game's random stream. Scripts holds the +threads, the statics and the piece animation records of every unit's script, the piece state a script +poses (a unit's model state, or a feature's), and the piece queries other subsystems ask: where a piece +is, what angles it has, where a weapon aims from, where the nano piece is and where the unit's sweet +spot is. It also starts scripts for the rest of the engine and answers queries synchronously. + +## 2. Interface + +### Slots (`interfaces/scripts.h`, version 3.0) + +| Slot | When the engine calls it | +| --- | --- | +| `Apply` | for each event of the module's inbox, once, with the event and its payload size | +| `StartScriptWithArgsByIndex` | when a unit's script must start by the index of a name, on behalf of another machine, with up to four arguments | +| `QueryScript` | when the engine needs the answer of a named query script, in the same statement | +| `FindScript` | when the engine needs the index of a named script | +| `GetPieceOffset` | when the engine needs a piece's offset from the unit | +| `GetPiecePosition` | when the engine needs a piece's world position | +| `GetPieceAngles` | when the engine needs a piece's angles | +| `GetNanoPiecePosition` | when an order needs the world position of the unit's nano piece | +| `GetAimFromPosition` | when a weapon needs the position it aims from | +| `GetSweetSpot` | when targeting needs the point weapons aim at on a unit | +| `PoseUnitModel` | when the simulation needs a unit's model posed from its current angles and animation | +| `CreateObjectState` | when a model's piece state must be built for a feature, or a unit without a script | +| `FreeObjectState` | when a piece state and the pictures cached for it are freed, as a unit dies | +| `UpdateObjectState` | when presentation poses a model it is about to draw | +| `ObjectStateSize` | when a caller must size the piece state of a model before publishing INIT_STATE | +| `NewUnitScript` | when a unit is created and its script allocated | +| `SetCob` | when a unit type's compiled script data is given to a unit's script | +| `CreatePlayerObjectState` | when a scripted unit's piece state is built | +| `SetObjectState` | when a unit's script is given its piece state | +| `RunScripts` | once per unit with a script and per unit pass, with the ticks elapsed since its last call | +| `DeleteScript` | when a unit's script is destroyed, as its unit dies | + +The engine slots, which the module does not export and the engine's own code answers, are +`SaveScriptState`, `LoadScriptState` and `WriteState`; section 4 states what they do. + +### The manifest entry + +The kit's manifest (`wasm/modules.json`) carries this module's entry without budgets, and the +reference repository's own manifest carries a `blocked` reason for it; the entry the module must have +is this one with the budgets its build picks: + +- `name` and `interface`: `scripts`. +- `exports`, in this order: `Apply`, `StartScriptWithArgsByIndex`, `QueryScript`, `FindScript`, + `GetPieceOffset`, `GetPiecePosition`, `GetPieceAngles`, `GetNanoPiecePosition`, + `GetAimFromPosition`, `GetSweetSpot`, `PoseUnitModel`, `CreateObjectState`, `FreeObjectState`, + `UpdateObjectState`, `ObjectStateSize`, `NewUnitScript`, `SetCob`, `CreatePlayerObjectState`, + `SetObjectState`, `RunScripts`, `DeleteScript`. +- `engine`: `SaveScriptState`, `LoadScriptState` and `WriteState`. +- `data`: `g_game`, `g_simGlobals`, `g_extTdf`, `g_blockBase` (ABI 8.2). The module reads all four: + `g_game` for the game record, `g_simGlobals` for the random seed (`rng.seed` is + `SimGlobals.g_randomSeed`), `g_blockBase` for every `Ref`, and `g_extTdf` only as its export. +- `majors`: `scripts` 3, and for its import groups `map` 9, `los_radar` 5, `services` 4. +- `data_base` and `table_base`: `0x90000` and 432, from the entry (ABI 2). The window is 32768 bytes + and the table range 32 entries. +- `fuel_budget` and `size_budget`: the build picks them (ABI 11.1 and 11.3). The host sets the fuel + counter once for all of the module's slot calls of a tick (ABI 11.2), so `fuel_budget` is ten times + the most fuel any one tick of the gate's scenarios burns across every slot this module runs, queries + and piece getters included; `size_budget` is the most bytes the build's `.wasm` may be. The module + meters itself by rule version 1 and exports `__fuel_set` and `__fuel_get`. +- `publishes`: `{"164": 12, "263": 16, "264": 16, "357": 20, "386": 16}`, the five effect kinds of + section 4 (`docs/schedule.md`, "Routes"; `data/routes.csv`). +- Slot kinds: + +| Slot | Kinds | +| --- | --- | +| `Apply` | `[linear, int] -> int` | +| `StartScriptWithArgsByIndex` | `[linear, int, linear, int, int, int, int, int, int] -> int` | +| `QueryScript` | `[block, linear, linear, linear, linear, linear] -> int` | +| `FindScript` | `[block, linear] -> int` | +| `GetPieceOffset`, `GetPiecePosition`, `GetPieceAngles` | `[block, int, linear] -> void` | +| `GetNanoPiecePosition`, `GetSweetSpot` | `[linear, linear] -> void` | +| `GetAimFromPosition` | `[linear, linear, int] -> void` | +| `PoseUnitModel`, `UpdateObjectState` | `[linear] -> void` | +| `ObjectStateSize` | `[linear] -> int` | +| `CreateObjectState` | `[block] -> block` | +| `FreeObjectState` | `[block] -> void` | +| `NewUnitScript` | `[block] -> void` | +| `SetCob`, `SetObjectState` | `[block, block] -> void` | +| `CreatePlayerObjectState` | `[block, block, block] -> block` | +| `RunScripts` | `[block, int] -> void` | +| `DeleteScript` | `[linear] -> void` | +- Imports, every one listed and nothing else: + +| Import | Kinds | Used for | +| --- | --- | --- | +| `map.GetGroundHeight` | `[linear] -> int` | unit value 16 | +| `los_radar.IsUnitVisibleToPlayer` | `[block, block] -> int` | the visibility test of the effect command | +| `services.SimAlloc` | `[int] -> linear` | a unit's script; the statics and piece records of `SetCob` | +| `services.SimAllocTagged` | `[linear, int] -> linear` | a model state and the point lists of its pieces | +| `services.SimFree` | `[linear] -> void` | freeing them again | +| `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | + +- Hooks: none. The header annotates every slot "Hooks: none". + +The kit's entry also lacks `services.RecordSimEvent`, which section 4's effect command needs to record its +five sim events; no recording reaches that command, so the entry has no such import. The kit gap is filed +as its own issue, and a module built against the kit's entry records none of those five events. The +entry also has no reallocation service, which `SetCob` needs (section 4): the reference's own +reallocation is not a recorded import, so a module that allocates the two blocks the way section 4 +says adds import lines its recordings do not have. That kit gap is filed too. + +### Arguments outside the block + +- **The event** of `Apply` is a `ScriptsEventHeader` in the module's memory, followed by the payload of + its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length + in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and + has outcome 0. +- **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script + data (ozgb/btm#41), a `block` address that names one unit type's compiled script. It is not read as + a `ScriptTable`; the module reads these values through it, and the recording writes it as the unit + type, `UnitDef#N`: + - `count`: the number of named scripts; + - `pieceCount`: the number of pieces of the unit's model; + - `staticCount`: the number of 32-bit statics; + - `names`: the `count` NUL-terminated script names; + - `entries`: the `count` start offsets of those scripts in `code`; + - `pieceNames`: the `pieceCount` NUL-terminated names of the model's pieces, in model order; + - `code`: the 32-bit words the threads run; + - `checksum`: the four-byte checksum of the script's file, as section 5 computes it. +- **A callback** arrives as the `linear` address of an object the engine owns, 0 for none; the value + a channel stores and AIM_DONE publishes is that object's block offset, 0 for none (ABI 7.1). The + module converts between the two and never calls through the object. A callback object is virtual, + and its offset is the offset of an object whose first word is a table pointer; the module reads + nothing of it. +- **`out`** (`GetPieceOffset`, `GetPiecePosition`, `GetNanoPiecePosition`, `GetAimFromPosition`, + `GetSweetSpot`) is a `Vec3` of three 32-bit integers in the caller's memory, written whole. + `GetPieceAngles` writes an `Angles16`: three 16-bit values, bank, heading and pitch in that order. +- **Text** given to the slots (`QueryScript` and `FindScript`'s name, the names inside the script data) + is NUL-terminated bytes in the caller's memory; the comparison is byte for byte, case sensitive. + `Apply`'s START name is a 32-byte field that need not be terminated. + +### Events + +The module records five sim event kinds, each when a script's EMIT_SFX operation emits the effect +number that kind names, at the piece's position, and only when the unit is visible to the player the +machine views (`los_radar.IsUnitVisibleToPlayer`); a unit that is not visible records nothing. The +arguments, flags and phases are as `docs/sim-events.md` gives them: + +- `SIM_EVENT_THRUST_PARTICLES`: the effect that streams a jet plume, with lifetime 6 or 7; +- `SIM_EVENT_WAKE_PARTICLES`: the effect that trails a wake, with period 16 or 8; two of its numbers + swap the two positions; +- `SIM_EVENT_BUBBLES`, `SIM_EVENT_WHITE_SMOKE`, `SIM_EVENT_BLACK_SMOKE`: the effects that raise + bubbles, puff white smoke and puff black smoke. The numbers each kind answers to, and its arguments, + are as `docs/sim-events.md`, Terms, gives them. + +The kit's manifest entry for this module imports no `services.RecordSimEvent`, so the entry as the kit +has it cannot record them; a module built from this spec records none of the five until the entry +lists the import (the kit gap of section 2, "The manifest entry"). + +### Effects + +The module publishes five effects through `Emit`, each at the moment section 4 gives; the payload +starts with the interface's event header, whose `kind` the effect's kind is, and the second argument of +`Emit` is its size: + +| Effect | Kind | Payload | Fields | +| --- | --- | --- | --- | +| SET_YARD, to map | 164 | `MapSetYard`, 12 bytes | the unit; `open` 1 or 0 | +| AIM_DONE, to weapons | 263 | `WeaponsAimDone`, 16 bytes | the unit is 0; the callback; what the aim script returned | +| EXPLODE_PIECE, to weapons | 264 | `WeaponsExplodePiece`, 16 bytes | the unit; the piece; the flags of the explode operation | +| ATTACH_TO_PIECE, to units | 357 | `UnitsAttachToPiece`, 20 bytes | the unit; the target, 0 to detach; the target's piece, -1 when none; the mode | +| SCRIPT_VALUE, to units | 386 | `UnitsScriptValue`, 16 bytes | the unit; the value's number; the value | + +A malformed effect changes nothing and does not trap (ozgb/btm#25). For each kind, the fields that +must be valid are: SET_YARD, a unit offset that is a unit; AIM_DONE, a callback that is not 0; +EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's piece count; ATTACH_TO_PIECE, +a unit offset that is a unit, and, when the target is not 0, a target offset that is a unit; and +SCRIPT_VALUE, a unit offset that is a unit. The module publishes none that a valid script does not +produce: a null unit or a callback it never had is never published. + +## 3. State + +### Owned + +All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and reached through the +`Ref` fields that hold it; a `Ref` is a 32-bit block offset, 0 for null (ABI 7.1). + +**`CobScript`** (1344 bytes; the base of a unit's script): + +| Field | Offset | Meaning | +| --- | --- | --- | +| `scale` | 4 | ticks per second the script's speeds are divided by: 30 | +| `table` | 8 | the handle to the unit type's script data, 0 before one is set | +| `checksum` | 12 | the unit type's script-file checksum | +| `statics` | 16 | `Ref`: `staticCount` words the script reads and writes | +| `pieces` | 20 | `Ref`: `pieceCount` animation records | +| `changed` | 24 | 1 while a piece is animating, so the piece animation step runs | +| `channels` | 28 | eight `Channel` records (1312 bytes) | +| `activeCount` | 1340 | the number of channels that are not free | + +**`UnitScript`** (1348 bytes): `CobScript`, then `state` at 1344, `Ref`: the unit's model +state. + +**`Channel`** (164 bytes): + +| Field | Offset | Meaning | +| --- | --- | --- | +| `state` | 0 | 0 free; 0x01000000 runnable; 0x02100000 waiting for a turn to stop; 0x02200000 waiting for a move to stop; 0x02400000 sleeping; 0x02800000 waiting for a child thread to end | +| `pc` | 4 | the index in `code` of the next opcode | +| `sp` | 8 | the stack pointer; -1 is an empty stack | +| `delay` | 12 | the ticks left of a sleep | +| `piece` | 16 | the piece a turn or move wait watches | +| `axis` | 20 | the axis of that wait | +| `waiting` | 24 | the index of the child a 0x02800000 wait waits for | +| `signal` | 28 | the signal word a KILL operation matches | +| `callback` | 32 | `Ref`: the aim callback told when the thread returns | +| `stack` | 36 | 32 words; `Push` writes at `++sp`, `Pop` reads and decrements | + +The waiting substate is `state & 0x00f00000` and the state class is `state & 0xff000000`; the fields +`delay`, `piece` and `axis` are meaningful only in the substate that uses them. + +**`Piece`** (76 bytes): `active` at 0, then six arrays of three words, `move` at 4, `moveSpeed` at 16, +`turn` at 28, `turnSpeed` at 40, `spin` at 52, `acceleration` at 64. A `turn` of −1 on an axis means the piece +spins on it instead of turning to a target. + +**`SavedPiece`** (108 bytes): the six piece arrays at 0 to 71, `translation` at 72, `rotation` at 84, +`visible` at 96, `cached` at 100, `shaded` at 104; the form a saved game stores. + +**`ModelState`** (88 bytes minimum; `SpotState` for a feature's spot, 118): `count` at 0, the number of +piece records; `cacheDrawCount` at 4; `animDirty` at 8; `owner` at 12, `Ref`; `bitmap` at 16; +`shadow` at 20; `pos` at 24, a `Vector3s`; `root` at 30, `Ref`; `pieces` at 34, `count` +`ModelPiece` records of 54 bytes. A feature's spot record has the same first 88 bytes, then its own +fields; the slots here read only the shared prefix. + +**`ModelPiece`** (54 bytes): `object` at 0, the `Object3do` node; `rot_x` at 4, `rot_y` at 8, +`rot_z` at 12, the piece's translation in each axis; `short_10` at 16, `short_12` at 18, `short_14` at +20, its rotation about each axis; `offset` at 22, a `Vec3`, the posed offset; `points` at 34, +`Ref`, the posed vertices; `modified` at 38; `flags` at 40, a `ModelPieceFlags` word; `sibling` +at 42, `child` at 46 and `parent` at 50, `Ref`. + +**`ModelPieceFlags`** (2 bytes): bit 0 `visible`, bit 1 `colored`, bit 2 `lit`, bits 3 to 15 `rest`. + +**`ScriptTable`** (40 bytes): the kit's record of the script data a handle names; its fields at 4 +(`count`), 8 (`pieceCount`), 16 (`staticCount`), 24 (`entries`), 28 (`names`) and 36 (`code`) are +those of section 2, "Arguments outside the block". The compiled data itself is load-time data outside +the block; the module reads it and never writes it. + +**List and copy rules.** A null `Ref` stores the value 0; any other stores `address - g_blockBase`. +A record the slot allocates is not initialised beyond what section 4 says, so its bytes are whatever +the allocation gives them; the recordings show fresh allocations as zero. A copy of a record copies +its bytes; a `Ref` inside it is copied as the offset it is. + +### Read + +- `Game`: `playerIndex` (the player the machine views), `seaLevel` (the height the bubble effect + rises to), `units` (the base of the unit table, indexed by a 16-bit unit id for unit values 9 to 11 + and for the attach and drop operations) and `poolCount` (`WriteState`; section 4). +- Each `Unit` a slot is given or reaches: `activateFlags`, `cell`, `footprint`, `id`, `cobStateFlags`, + `cargo`, `cargoNext`, `carrier`, `bank`, `heading`, `pitch`, `flags`, `health`, `buildLeft`, `def`, + `pos`, `script`, `state`. +- `UnitDef`: `modelMaxY`, `maxHealth`. +- `Feature.object` (for INIT_STATE), the model of the feature type. +- `Object3do`: `vertexCount`, `box_x`, `box_y`, `box_z`, `vertices`, `sibling`, `child`, `name`. +- `Game.players[Game.playerIndex]` is passed to `los_radar.IsUnitVisibleToPlayer` as an address; the + module does not read the player record itself. +- The random stream `rng.seed` (`g_randomSeed`): read and written as section 5 says. + +### Bits of the unit's words + +| Bits | Mask | Meaning here | +| --- | --- | --- | +| bit 0 of `activateFlags` | 0x01 | unit value 1, `activate_bit0` | +| bit 1 of `activateFlags` | 0x02 | unit value 20, `activate_bit1` | +| `bit0`, `bit1`, `bit2`, `bit3` of `cobStateFlags` | 0x01, 0x02, 0x04, 0x08 | unit values 5, 6, 18 and 19 | +| bits 18 and 19 of `flags` | 0x000c0000 | unit value 2 | +| bits 20 and 21 of `flags` | 0x00300000 | unit value 3 | +| bit 28 of `flags` | 0x10000000 | the unit is alive, which ATTACH, DROP and unit values 9 to 11 test | + +### Between ticks + +Nothing outside these fields: the script objects, their statics and piece records, the model states +and their pieces, and the unit's `script`, `state` and script bits. A channel that is free has state +0; its other fields keep the values the thread left. The module keeps no allocation of its own +between ticks. + +## 4. Behaviour + +Within one call, only the order of import calls is observable. The block writes are compared at the +end of the call, so the order they are listed in carries no meaning, except where a later write reads +an earlier one. + +### `Apply(event, size)` + +The outcome is 0 and nothing changes when, in this order: `size` is below the 8 bytes of +`ScriptsEventHeader`; `kind` is not 416 to 419; `size` is below the kind's payload (76 bytes for +START, 16 for each of the other three); the named object is null (the unit of START and DETACH_PIECE, +the piece state of FREE_STATE and INIT_STATE); or, for START, `form` is not 0, 1 or 2. Otherwise the +outcome is 1 and the kind's row applies: + +| Kind | Effects | +| --- | --- | +| START (416) | With the unit's `script`: when it is null, the outcome is 0 and nothing changes. Otherwise a thread starts as the form says (below), and the outcome is 1. | +| DETACH_PIECE (417) | When `pose` is 1, the unit's model is posed first: the state's `pos` becomes the unit's angles, `animDirty` 1, the root's `modified` 0, and the pose of section 4 runs, ending with `animDirty` 0. Then bit 0 of the flags word at `state + 34 + piece*54 + 40` is cleared. Outcome 1. | +| FREE_STATE (418) | The piece state is freed: each piece's `points` with `SimFree`, the pictures cached for it, and the state itself. Outcome 1. | +| INIT_STATE (419) | The state is set to 0 and its pieces are added from the model of `Game.features[feature].object` by the piece-state build rule of section 4, and `animDirty` becomes 1. Outcome 1. | + +The START forms, with *name* the event's 32-byte name copied into a 32-byte buffer that holds at most +31 of its bytes and a 0, *callback* the word at 48 of the payload as a callback, *update* the word at +52, *count* the word at 56 and `args` the four words at 60: + +| Form | Effect | +| --- | --- | +| 0, by name | The thread of the first script whose name equals *name* starts; when it starts, its callback is *callback*, and when *update* is not 0 every channel runs with elapsed 0 and the piece animation step runs with 0. If no script has that name or no channel is free, nothing starts and nothing is published. | +| 1, by name with arguments | The with-arguments start of section 4 with the index of the first script whose name equals *name*, the callback, *update*, *count* and *args*. | +| 2, by index with arguments | The with-arguments start of section 4 with *index*, the callback, *update*, *count* and *args*. | + +The outcome is 1 for forms 0, 1 and 2 whether or not a thread started, and 0 only for a unit whose +`script` is null or a form outside 0 to 2. + +### StartScriptWithArgsByIndex + +The with-arguments start of a script data index, a callback, an update flag, a count and four words: +the thread whose script entry is *index* starts (the thread start of section 4). When no channel is +free, or *index* is below 0 or not below the script data's `count`, nothing starts: when *callback* +is not 0, AIM_DONE is published with that callback and result 0, and the result is 0. + +When it starts: the channel's callback is *callback*; the four words *a*, *b*, *c* and *d* are pushed +in that order, so they sit at `stack[0]` to `stack[3]`, and `sp` becomes `count - 1`; then, when +*update* is not 0, every channel runs with elapsed 0 and the piece animation step runs with 0. The +result is 1. `count` 0 to 4 are the only values the callers pass; a `count` above 4 exposes stack the +push did not write. + +### QueryScript + +**A query run** of a name and one input word: the thread whose script name equals *name* starts (the +thread start of section 4). When it cannot start (no free channel or no matching name), the run does +nothing and its result is 0. When it starts, *input* is stored in `stack[0]`; `sp` becomes 3; the +thread runs at once with elapsed 0; and the answer is `stack[0]` as the run left it. The channel is +left as the run left it. + +`QueryScript` takes the script, the name and four argument pointers and runs the query of *name* with four input words, +the value of a null argument pointer being 0: they are stored in `stack[0]` to `stack[3]`, `sp` +becomes 3, the thread runs at once with elapsed 0, and each non-null argument pointer then receives +`stack[0]`, `stack[1]`, `stack[2]` and `stack[3]`. The result is 1 when the thread started, and 0, +with nothing written, not even through the argument pointers, when it did not. + +### `FindScript(script, name)` + +The lowest index *i* below the script data's `count` whose name equals *name* byte for byte; -1 when +there is none. Nothing is written. + +### The piece offset + +*The piece offset* of a piece *p* of a unit whose model state is *state*: when *state* is null or *p* +is below 0 or not below *state.count*, it is (0, 0, 0). Otherwise the running point starts as the +record's `object.box_x` plus its `rot_x`, `object.box_y` plus its `rot_y`, and `object.box_z` plus its +`rot_z`; then for each record *q* from *p*'s `parent` up to the root: the angles are the three 16-bit +halves bank = `q.short_14`, heading = `q.short_12` and pitch = `q.short_10`, the unit's `bank`, +`heading` and `pitch` being added to them for the root; the running point is rotated by those angles +(the three-angle rotation, section 5); and (`q.object.box_x + q.rot_x`, `q.object.box_y + q.rot_y`, +`q.object.box_z + q.rot_z`) is added to it. The offset is then (x, y, −z) of the running point. + +### The piece-offset rule and `GetPieceOffset(unit, piece, out)` + +*out* is the piece offset of *piece* (section 4). + +### `GetPiecePosition(unit, piece, out)` + +*out* is the unit's `pos` plus the piece offset of *piece*, component by component. + +### `GetPieceAngles(unit, piece, out)` + +With *u* the unit's angles: + +- when *piece* is 0 or more: bank is `u.bank` plus `pieces[piece].short_14`, heading is `u.heading` + plus `pieces[piece].short_12`, and pitch is `u.pitch` plus `pieces[piece].short_10`; +- when *piece* is −1: bank is `u.bank` plus the low 16 bits of the state's `count`, heading and pitch + are the unit's; +- below −1 is outside the contract. + +All additions wrap at 16 bits (Q2). + +### `GetNanoPiecePosition(unit, out)` + +The query run of `QueryNanoPiece` with input 0 gives the piece. *out* is the unit's `pos` plus the +piece offset of that piece. + +### `GetAimFromPosition(unit, out, weapon)` + +The query run of `AimFromPrimary`, `AimFromSecondary` or `AimFromTertiary` for *weapon* 0, 1 or 2 with +input −1 gives a piece. When it is −1, the query run of `QueryPrimary`, `QuerySecondary` or +`QueryTertiary` with input 0 gives the piece instead. *out* is the unit's `pos` plus the piece offset +of that piece. A *weapon* outside 0 to 2 is outside the contract. + +### `GetSweetSpot(unit, out)` + +The query run of `SweetSpot` with input 0 gives the piece. Then the unit's model is posed from its +game state (section 4), and *out* is the centre of that piece: with the piece's vertices *v*[0] to +*v*[*n*−1] from `pieces[piece].points`, *n* being `pieces[piece].object.vertexCount`, and the minimum +and maximum of x, y and z taken over those vertices and 0 (each minimum and maximum starts at 0), +*out* is + +```text +((max.x + min.x) / 2 + unit.pos.x, (max.y + min.y) / 2 + unit.pos.y, (max.z + min.z) / 2 + unit.pos.z) +``` + +where each division truncates toward zero. Posing the model first is the default behaviour; the quirk +`units.render-pose-reads` would read the renderer's copy instead and is off, so this spec states the +default (Q5). + +### `PoseUnitModel(unit)` + +When the unit's model state is null, nothing happens. Otherwise its `pos` becomes the unit's angles +(the six bytes of bank, heading and pitch), its `animDirty` becomes 1, its root piece's `modified` +becomes 0, the model is posed by the pose rule, and `animDirty` becomes 0. + +### The piece-state build rule and `CreateObjectState(model)` + +**A model's node count.** The count of a node is 1 when it has no child, and its child's count plus 1 +when it has one; a node's siblings add their own counts. The state's size is 34 plus 54 times the +root's count. That many bytes are allocated with `SimAllocTagged` and the tag `"Object State"`, the +whole record is set to 0, and the pieces are added from the model (below); `animDirty` becomes 1 and +the state's address is the result. + +**Adding a model's pieces.** The nodes are taken in a pre-order walk: a node, then its child's +subtree, then its sibling's subtree. For each, the record at index `count` of the pieces gets: +`object` the node; `modified` 0; `flags` 2 or 3 (bit 1 `colored`, and bit 0 `visible` when the node's +`vertexCount` is 3 or more) plus 4 (bit 2 `lit`); `points` a block of `vertexCount * 12` bytes from +`SimAllocTagged` with the tag `"Point List"`, holding a copy of the node's vertices; and `sibling`, +`child` and `parent` the records the node's sibling, child and parent are added as (0 when none). The +root is the record added for the model's root node, and `count` becomes the number of records. + +### `FreeObjectState(state)` + +For each piece from 0 to `count`−1, its `points` is freed with `SimFree` (a null one is not freed, +section 5), then the pictures cached for the state are released (presentation's; a module holds +none), then the state itself is freed with `SimFree`. Nothing is written. + +### The update rule and `UpdateObjectState(view)` + +*state* is the view's model state. When the view's angles are far from the state's `pos` (any of x, y +and z differs by 8 or more as a 16-bit signed difference), `pos` becomes the view's angles, +`animDirty` 1, the root's `modified` 0, and, when the root's `colored` bit is set, `cacheDrawCount` 0. +Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDirty` becomes 0. + +**The pose rule.** The pieces are restored first: a piece whose `modified` is 0 has its +`points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set +to (0,0,0) and its `modified` 0; the pieces below the root's first child are restored whatever their +`modified` (that child, its descendants and their siblings), and the root and the model's other +top-level pieces only when their `modified` is 0. Then every piece is visited once for itself and once +for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is +0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and +then adds the visiting piece's delta to each of them. The visiting piece's angles are its `short_14`, +`short_12` and `short_10` as x, y and z, with the state's `pos` added first for the root; its delta is +`rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. A visit does not change +`modified`. + +### `ObjectStateSize(model)` + +The size `CreateObjectState` allocates, as section 4 gives it, without allocating or writing anything. + +### `NewUnitScript(unit)` + +A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its +fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, +and each of the eight channels' `state` 0. Its other bytes are what the allocation gives them. + +### `SetCob(script, data)` + +`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: + +- `script.checksum` becomes the handle's `checksum`; +- `script.pieces` becomes a block of `pieceCount * 76` bytes, set to 0; +- `script.statics` becomes a block of `staticCount * 4` bytes, and its bytes are what the block holds: + a fresh block gives zeros, and a block that grows in place keeps its old bytes. + +The reference grows the two blocks in place (section 2, "The manifest entry", the kit gap); a module +that only allocates and frees gives the same bytes for a script that had none, and differs for one +that had them. + +### `CreatePlayerObjectState(model, data, owner)` + +As `CreateObjectState(model)`, with these differences: the record's `owner` becomes *owner*; and, +after the pieces are added and before the links are rebuilt, the records are reordered so that record +*i* holds the object whose name matches, ignoring case, the *i*-th of the handle's `pieceCount` names: +for each *i* from 0 to `pieceCount`−1, the lowest *j* from *i* to `count`−1 whose name matches is +found, and when *i* differs from *j* the two 54-byte records are swapped; a name with no match moves +nothing for that *i*. Then the links are rebuilt from the object graph: each record's `sibling`, +`child` and `parent` become the records whose objects are its object's `sibling`, `child` and +`parent`, and 0 when the object has none. The result is the state's address. + +### `SetObjectState(script, state)` + +The script's `state` becomes *state*. Nothing else. + +### `RunScripts(script, elapsed)` + +When `activeCount` is not 0, each of the eight channels runs in order (the thread run), then the +piece animation step runs with *elapsed*. With `activeCount` 0 only the piece animation step runs. + +The thread run of a channel and an elapsed count, with *c* the channel: + +1. A channel whose state class is 0 is skipped. In the waiting class 0x02000000, the substate decides + whether the wait is over: a turn wait (0x02100000) ends when the model piece's `turnSpeed` at the + channel's `axis` is 0, a move wait (0x02200000) when its `moveSpeed` at that axis is 0, and a + sleep (0x02400000) subtracts *elapsed* from `delay` and ends when it is 0 or less; each that ends + sets the state to 0x01000000. The 0x02800000 wait has no condition here. +2. A channel whose state class is 0x01000000 runs opcodes until it stops, ends or waits. When a + channel's state becomes 0, every channel whose state matches 0x02800000 under the mask 0xfff00000 + and whose `waiting` is its index becomes 0x01000000. + +The opcode is the word at `code[pc]`, and the dispatch is on `opcode & 0x100ff000`; the table below +gives each case. The stack pointer moves down by one when a word is pushed (the word written at the +new position) and up by one when a word is taken (the word read at the old position); *op1* and *op2* +are the words at `code[pc+1]` and `code[pc+2]`; *a* is the word taken first (the top) and *b* the one +taken next. All arithmetic is 32-bit and wraps. + +| Case | Behaviour | +| --- | --- | +| 0x10001000 (MOVE) | piece = *op1*, axis = *op2*: `move[axis]` = *a*, `moveSpeed[axis]` = *b* / 30; when `move[axis]` is below the model piece's translation (`rot_x`, `rot_y` or `rot_z`), `moveSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | +| 0x10002000 (TURN) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` = *b* / 30; delta = `turn[axis]` − the model piece's rotation (`short_10`, `short_12`, `short_14`); when delta is 0, `turnSpeed[axis]` 0, else when (|delta| > 0x8000) differs from (delta < 0), `turnSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | +| 0x10003000 (SPIN) | piece, axis: `turn[axis]` = −1, `spin[axis]` = *a* / 30, `acceleration[axis]` = *b* / 30; when `acceleration[axis]` is 0, `turnSpeed[axis]` = `spin[axis]`; `active` 1, `changed` 1; `pc += 3`. | +| 0x10004000 (STOP_SPIN) | piece, axis: `spin[axis]` 0, `acceleration[axis]` = −(*a* / 30); when `acceleration[axis]` is 0, `turnSpeed[axis]` 0; `pc += 3`. | +| 0x10005000 (SHOW) | the piece *op1* becomes visible: when its bit 0 was clear, it is set, the piece's `modified` becomes 0, and when its `cached` bit is set the state's `cacheDrawCount` becomes 0; `pc += 2`. | +| 0x10006000 (HIDE) | as SHOW with bit 0 cleared; `pc += 2`. | +| 0x10007000 (CACHE) | the piece *op1*'s `cached` bit becomes 1 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x10008000 (UNCACHE) | the piece *op1*'s `cached` bit becomes 0 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x10009000 (EXPLODE_LEGACY) | *a* and *b* are taken and discarded; `pc += 2`. | +| 0x1000a000 (PLAY_SOUND) | nothing; `pc += 2`. | +| 0x1000b000 (SET_PIECE_TRANSLATION) | piece, axis: `move[axis]` = *a*, `moveSpeed[axis]` 0, and the model piece's translation on that axis is set (the setter of section 4); `pc += 3`. | +| 0x1000c000 (SET_PIECE_ROTATION) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` 0, and the model piece's rotation on that axis is set (the setter of section 4); `pc += 3`. | +| 0x1000d000 (SHADE) | the piece *op1*'s `shaded` bit becomes 1 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x1000e000 (DONTSHADE) | the piece *op1*'s `shaded` bit becomes 0 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x1000f000 (EMIT_SFX) | *a* is taken, and the effect command runs with piece *op1* and effect *a*; `pc += 2`. | +| 0x10011000 (TURN_NOW) | state 0x02100000, `axis` *op2*, `piece` *op1*, `pc += 3`, and the channel stops this call. | +| 0x10012000 (MOVE_NOW) | state 0x02200000, `axis` *op2*, `piece` *op1*, `pc += 3`, and the channel stops this call. | +| 0x10013000 (SLEEP) | state 0x02400000, `delay` = 30 × *a* / 1000, `pc += 1`, and the channel stops this call. | +| 0x10021000 (PUSH) | when `opcode & 7` is 1 the value is *op1*; 2, `stack[op1]`; 4, `statics[op1]`; the value is pushed; `pc += 2`. | +| 0x10022000 (POP) | `sp` adds 1; `pc += 1`. | +| 0x10023000 (STORE) | when `opcode & 7` is 2, *a* is taken and `stack[op1]` becomes it; 4, *a* is taken and `statics[op1]` becomes it; any other mode takes nothing; `pc += 2`. | +| 0x10024000 (DROP) | `sp` subtracts 1; `pc += 1`. | +| 0x10031000 (ADD) | push *b* + *a*; `pc += 1`. | +| 0x10032000 (SUB) | push *b* − *a*; `pc += 1`. | +| 0x10033000 (MUL) | push *b* × *a*; `pc += 1`. | +| 0x10034000 (DIV) | push *b* / *a*, truncated toward zero; `pc += 1`. | +| 0x10035000 (BIT_AND) | push *b* & *a*; `pc += 1`. | +| 0x10036000 (BIT_OR) | push *b* | *a*; `pc += 1`. | +| 0x10037000 (BIT_XOR) | push *b* ^ *a*; `pc += 1`. | +| 0x10038000 (BIT_NOT) | push ~*a*; `pc += 1`. | +| 0x10041000 (RANDOM) | push the draw of section 5 over the range *a* − *b* + 1, plus *b*; `pc += 1`. | +| 0x10042000 (GET_UNIT_VALUE) | push unit value *a* (below); `pc += 1`. | +| 0x10043000 (GET_UNIT_VALUE_4) | *a*, *b*, *d*, *e*, *f* are taken in that order and the unit value *f* is pushed, for the arguments *e*, *d*, *b*, *a* (below); `pc += 1`. | +| 0x10044000 (IS_CARRYING_UNIT) | push 1 when the unit's `cargo` chain holds a unit whose `id` is *a*, else 0; `pc += 1`. | +| 0x10045000 (GET_TRANSPORTER_ID) | push the `id` of the unit's `carrier`, or 0 when it has none; `pc += 1`. | +| 0x10051000 (LESS) | push 1 when *b* < *a* (signed), else 0; `pc += 1`. | +| 0x10052000 (LESS_EQUAL) | *b* ≤ *a*; `pc += 1`. | +| 0x10053000 (GREATER) | *b* > *a*; `pc += 1`. | +| 0x10054000 (GREATER_EQUAL) | *b* ≥ *a*; `pc += 1`. | +| 0x10055000 (EQUAL) | *b* == *a*; `pc += 1`. | +| 0x10056000 (NOT_EQUAL) | *b* != *a*; `pc += 1`. | +| 0x10057000 (LOGICAL_AND) | *b* && *a*, as 1 or 0; `pc += 1`. | +| 0x10058000 (LOGICAL_OR) | *b* || *a*, as 1 or 0; `pc += 1`. | +| 0x10059000 (LOGICAL_XOR) | *a* is taken, then the next word, and their bitwise xor is pushed; `pc += 1`. | +| 0x1005a000 (LOGICAL_NOT) | push 1 when *a* is 0, else 0; `pc += 1`. | +| 0x10061000 (START) | *op1* is the child's entry offset and *op2* the count: a child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the last pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | +| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, its state 0x02800000, `pc += 3`, and the parent stops this call. | +| 0x10063000 (SET_ARG) | *op2* words are taken and discarded; `pc += 3`. | +| 0x10064000 (JUMP) | `pc` becomes *op1*. | +| 0x10065000 (RETURN) | when the channel's callback is not 0, *a* is taken and AIM_DONE is published with the callback and *a*; otherwise the stack is untouched. Then state 0, `activeCount` subtracts 1, the wake rule of the thread run runs for the channel, and the channel stops this call. | +| 0x10066000 (JUMP_IF_ZERO) | *a*: when it is 0, `pc` becomes *op1*, else `pc += 2`. | +| 0x10067000 (KILL) | *a* is the mask; for each channel 0 to 7 whose state is not 0 and whose `signal` shares a bit with the mask, its state becomes 0, `activeCount` subtracts 1, the wake rule runs for it, and when it is this channel the run stops this call; `pc += 1`. | +| 0x10068000 (SET_SIGNAL) | `signal` = *a*; `pc += 1`. | +| 0x10071000 (EXPLODE_PIECE) | *a* flags; EXPLODE_PIECE is published with the unit, piece *op1* and *a*; `pc += 2`. | +| 0x10082000 (SET_UNIT_VALUE) | *a*, then *b*: unit value *b* is set to *a* (below); `pc += 1`. | +| 0x10083000 (ATTACH_UNIT) | *a*, *b*, *d* are taken: the attach operation with id *d*, piece *b* and mode *a*; `pc += 1`. | +| 0x10084000 (DROP_UNIT) | *a*: the drop operation with id *a*; `pc += 1`. | +| any other | state 0, `activeCount` subtracts 1, and the channel stops this call; nothing is woken. | + +**A thread start** by index: the first channel with state 0 becomes runnable, `pc` = the entry offset +of *index*, `sp` −1, `callback` 0, `signal` 1, `activeCount` adds 1, and the index is returned; when +*index* is below 0 or not below the script data's `count`, or no channel is free, nothing starts and +−1 is returned. + +**The setter of a model piece.** Setting a model piece's translation or rotation on an axis writes +the new value only when it differs from the value there; a write sets the piece's `modified` 0 and +the state's `animDirty` 1, and when the piece's `cached` bit is set, the state's `cacheDrawCount` 0. +Setting its visible bit writes nothing when the bit already has that value; a write sets `modified` 0, +and when the piece is cached, `cacheDrawCount` 0 (but not `animDirty`). + +**Unit values**, with *u* the unit the script belongs to and *a*, *b*, *d*, *e* the arguments: + +| Value | Result | +| --- | --- | +| 1 | `u.activateFlags` bit 0 | +| 2 | bits 18 and 19 of `u.flags` (0 to 3) | +| 3 | bits 20 and 21 of `u.flags` (0 to 3) | +| 4 | `u.health * 100 / u.maxHealth` (unsigned division; `maxHealth` 0 is outside the contract) | +| 5, 6 | `u.bit0`, `u.bit1` | +| 7 | the piece position of piece *a*: (`v.x & 0xffff0000`) + (`v.z >> 16`), *v* being its world position | +| 8 | that position's y | +| 9, 10, 11 | the unit at index `a & 0xffff` of the unit table, when it is alive (bit 28 of its `flags`): 9, (`pos.z >> 16`) + (`pos.x & 0xffff0000`); 10, `pos.y`; 11, `def.modelMaxY`. Otherwise these give 0. | +| 12 | *a*'s two halves *hi* = `a & 0xffff0000` and *lo* = `a << 16`, *lo* negative adding 0x10000 to *hi*: the angle of the vector (*hi*, *lo*) minus `u.heading`, wrapped to 16 bits | +| 13 | the same *hi* and *lo*: `bx_ftol(hypot(hi, lo))` (section 5) | +| 14 | the angle of the vector (*a*, *b*) wrapped to 16 bits | +| 15 | `bx_ftol(hypot(a, b))` | +| 16 | a `Vec3` of x = `a & 0xffff0000`, z = `a << 16` (x adding 0x10000 when z is negative), y 0: `map.GetGroundHeight(&v) << 16` | +| 17 | 0 when `u.buildLeft` is 0.0; otherwise 1 − `bx_ftol(u.buildLeft * −99.0)`, as a 32-bit float multiply and a conversion to 32 bits | +| 18, 19 | `u.bit2`, `u.bit3` | +| 20 | `u.activateFlags` bit 1 | +| any other | 0 | + +**Setting a unit value** of *which* and *value*: when *which* is 18, SET_YARD is published first, with +the unit and *value* as `open`; then SCRIPT_VALUE is published with the unit, *which* and *value*. + +**The effect command** of a piece and an effect: when +`los_radar.IsUnitVisibleToPlayer(&Game.players[Game.playerIndex], unit)` returns 0, nothing happens +and nothing is recorded. Otherwise the model is posed (section 4), and the two positions are +computed: when `effect & 0x100` is not 0, *v1* is the unit's position plus the piece's posed offset +(`pos.x + pieces[piece].offset.x`, `pos.y + ...y`, `pos.z − ...z`) and *v2* is unused; otherwise *v1* +and *v2* are the unit's position plus each of the piece's first two posed vertices: *v1* adds +`points[0]`, `points[1]`, and subtracts `points[2]` from z; *v2* does the same with `points[3]`, +`points[4]`, `points[5]`. Then, by `effect`: + +| Effect | Records | +| --- | --- | +| 0 | THRUST_PARTICLES from *v1* to *v2*, period 1, lifetime 6, list 7 | +| 1 | THRUST_PARTICLES from *v1* to *v2*, period 1, lifetime 7, list 7 | +| 2 | WAKE_PARTICLES from *v1* to *v2*, period 16, list 2 | +| 3 | WAKE_PARTICLES from *v1* to *v2*, period 8, list 2 | +| 4 | WAKE_PARTICLES from *v2* to *v1*, period 16, list 2 | +| 5 | WAKE_PARTICLES from *v2* to *v1*, period 8, list 2 | +| 0x101 | WHITE_SMOKE at *v1*, list 9 | +| 0x102 | BLACK_SMOKE at *v1*, list 9 | +| 0x103 | BUBBLES from *v1* to *v2*, where *v2* is *v1* with y = `Game.seaLevel << 16`, period 8, list 7 | +| any other | nothing recorded | + +As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records +none of these five. + +**The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, +when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: +ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. + +**The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and +this unit is its carrier: when the map says the unit's footprint fits at its cell, ATTACH_TO_PIECE is +published with it, target 0, piece −1, mode 1. The map's answer is the engine's call +(`ScheduleMapCanPlaceUnitFootprint`), which this module does not import; a module built against the +kit's entry cannot make it, so it cannot drop a carried unit. The kit gap is filed as its own issue. + +**The piece animation step** of an elapsed count: returns when *elapsed* is 0 or `changed` is 0; +otherwise sets `changed` 0 and, for each piece *p* from 0 to `pieceCount`−1 whose `active` is not 0, +sets `active` 0 and for each axis *j* 0 to 2: + +1. When `moveSpeed[j]` is not 0: *v* = the model piece's translation on *j* plus `elapsed × + moveSpeed[j]`; when `moveSpeed[j]` is positive and *v* reaches or passes `move[j]`, *v* becomes + `move[j]` and `moveSpeed[j]` 0, else `active` 1; when negative and *v* reaches or passes + `move[j]`, *v* becomes `move[j]` and `moveSpeed[j]` 0, else `active` 1. The model piece's + translation on *j* is set to *v* (the setter of section 4). +2. When `acceleration[j]` is not 0: `turnSpeed[j]` adds `acceleration[j]`; when the acceleration is + positive and `turnSpeed[j]` reaches or passes `spin[j]`, `turnSpeed[j]` becomes `spin[j]` and + `acceleration[j]` 0; when negative and `turnSpeed[j]` reaches or passes `spin[j]`, both likewise. +3. When `turnSpeed[j]` is not 0: *r* is the model piece's rotation, *cur* = *r*, step = `elapsed × + turnSpeed[j] *r* adds step, and *want* = `turn[j]`. When *want* is not −1: for a positive speed, + when (`want − cur + 0x10000) % 0x10000 ≤ step`, *r* = *want* and `turnSpeed[j]` 0, else `active` 1; + for a negative speed, when (`cur − want + 0x10000) % 0x10000 ≤ −step`, likewise. When *want* is + −1, `active` 1. The model piece's rotation becomes *r* & 0xffff (the setter of section 4). + +When the piece is still active after the axes, `changed` becomes 1. + +### `DeleteScript(script)` + +When `pieces` is not null it is freed with `SimFree`, then `statics` when it is not null, then the +script object itself. Nothing is written to the block; the `Ref` in the unit is the engine's to +clear. + +### `SaveScriptState(script, bank)` + +The bank is sought to item 0, and a saved header record of 0x528 bytes is written: the script's +`checksum`, the eight channels with their callbacks 0, and `activeCount`. Then the statics, +`staticCount × 4` bytes. Then, for each piece from 0 to `pieceCount`−1, a `SavedPiece` of 0x6c bytes: +`visible`, `cached` and `shaded` from the piece's flags, the six arrays, and `translation` and +`rotation` from the model's pieces. This is an engine slot; the module does not export it. + +### `LoadScriptState(script, bank)` + +When the bank's size is not `pieceCount × 0x6c + 0x528 + staticCount × 4`, the result is 0 and nothing +changes. Otherwise the bank is sought to item 0, a saved header record is read (when the read returns +fewer bytes than 0x528, the result is 0), and the script's `checksum` must equal the saved one (else +0). Then the eight channels take the saved ones with their callbacks 0, `activeCount` the saved one, +the statics are read into the script's statics (a read of fewer bytes than asked gives 0 and leaves +what was copied), and the pieces are read: each piece becomes `active` 1, its `visible`, `cached` and +`shaded` are set, the six arrays copied, `translation` and `rotation` set through the model's pieces, +and `changed` 1. The result is 1. The pieces are read through a buffer of `pieceCount × 0x6c` bytes +from `SimAllocTagged` with the tag `"Piece States"`, freed on success; a short read of the statics +returns 0 with nothing allocated, and a short read of the pieces returns 0 with the buffer still +allocated. This is an engine slot; the module does not export it. + +### `WriteState(writer)` + +For each unit slot *i* of `Game.units` below `Game.poolCount` whose unit exists and whose `script` is +not null, the writer begins record 55 named `scriptsState.units[i]` and writes: `scale`, `table` (a +heap pointer, written as its address), `checksum`, `changed`, `activeCount`; for each channel, its +`state` (and, when the state is not 0, `pc`, `sp`, `signal`, `callback` as a heap pointer, the first +`min(max(sp+1, 0), 32)` words of `stack`, and, in state class 0x02000000, the substate's fields: +`piece` and `axis` for the turn and move waits, `delay` for the sleep, `waiting` for the child wait); +`statics.count` (the script data's `staticCount`, 0 when the script data is null or above 4096 or the +statics are null) and the statics; and for each piece below `pieceCount` (0 when the script data is +null or above 512, or the pieces are null), `active`, the six arrays. This is an engine slot; the +module does not export it. + +## 5. Exactness + +- **The random draw** (`RANDOM`, unit value none): the draw of *range*, = *a* − *b* + 1 + computed in 32 bits. When *range* < 2 the result is 0 and the stream is not touched. Otherwise, with + *seed* = `rng.seed` as an unsigned 32-bit word, *q* = *seed* / 127773 (unsigned), *correction* = + (*q* << 31) − *q* (unsigned 32-bit, the shift keeping only *q*'s lowest bit), *seed* = *seed* × + 16807 − *correction* (unsigned 32-bit wrap); when *seed* as a signed 32-bit value is 0 or less, + *seed* adds 2147483647; `rng.seed` becomes *seed*; the result is the low 32 bits of *seed* % *range* + (unsigned), as a signed 32-bit value. This is the game logic's own stream, the one `rng.seed` names, + not one of the two block-head streams. +- **A null free**: a `SimFree` of 0 changes nothing and does not trap (ABI section 9.3). +- **Rotating a point** (used by the piece offsets, the pose and the piece getters): + the rule is `runtime/vectors/README.md`, "Rotating a point", which the kit's `rotate_point` vectors + hold to. An angle of 0 leaves the point as it is. Otherwise *t* is the angle as a signed 16-bit + number, the angle in radians is *t* × the double nearest 9.587379924285e-05 rounded to nearest, S + and C are the sine and cosine of that angle rounded to nearest with a 64-bit mantissa (the 80-bit + table of `runtime/bitexact_tables.py`), each of *x* × C, *z* × C, *x* × S and *z* × S is the exact + product rounded to the nearest double, the results are *rx* = *x* × C − *z* × S and *rz* = *z* × C + + *x* × S each a double, and each is rounded to the nearest int, ties to even, with −2147483648 when + it is outside the int range. +- **The three-angle rotation of a point**: the point is rotated by the bank (angle 0), then the result's second + coordinate and the original z by the pitch (angle 2), then that result's second and the first by the + heading (angle 1): each step is the rule above, in that order. +- **The angle of a vector** (*x*, *z*): the rule is `runtime/vectors/README.md`, "Angle of a + vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], computed as the double-double + `internal.h`'s `bx_dd_atan2_nonneg` gives it, rounded to the nearest double with a 64-bit mantissa + (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the nearest int + ties to even, and negated when x is negative. +- **hypot and the conversion to int**: `hypot(x, y)` follows `runtime/vectors/README.md`, "hypot" + (each step rounded to a 64-bit mantissa and then to a double, except the squares). `bx_ftol(x)`: + the result is 0 when |x| < 1; otherwise the integer part of |x| truncated, its low 32 bits, negated + when x is negative; a value whose exponent reaches 1023 + 63 gives 0. +- **The script-file checksum**: four bytes over the file's bytes, *a*, *b*, *c* and *d*, all starting + 0, for each byte at index *i*: *a* = (*a* + byte) mod 256, *b* = *b* xor byte, *c* = (*c* + (*i* xor + byte)) mod 256, *d* = *d* xor ((*i* + byte) mod 256). The value is (*d* << 24) | (*c* << 16) | + (*b* << 8) | *a*, as a signed 32-bit integer. +- **Division and shifts**: `/` truncates toward zero on a negative result; `%` has the dividend's + sign; `>>` is arithmetic on a signed value; a multiplication or addition wraps at 32 bits. Division + by 0 and the most negative value divided by −1 are outside the contract. +- **Narrow values**: a `short` and a 16-bit rotation, angles and `Vector3s` field wrap at 16 bits; a + `Ref` is a 32-bit offset and a null `Ref` stores 0. +- **Case-insensitive names**: two names match when they differ only in the case of ASCII letters; + bytes above 127 are outside the contract. +- **The pose's arithmetic** is the same three-angle rotation; each vertex and offset is a 32-bit integer. + +## 6. Quirks + +- **Q1: the query's word for `sp` and its stack.** `QueryScript` addresses the channel's `sp` as + the query count and writes its in-values through it: the count starts at −1, each `++` of it is the + next `stack` word, so the four values land at `stack[0]` to `stack[3]`, and it is then set to 3. + The word it clears is the channel's `callback`, and the answers are read from `stack[0]` to + `stack[3]`. +- **Q2: a piece of −1.** `GetPieceAngles` with *piece* −1 adds the low 16 bits of the model state's + `count` to the bank, where a piece 0 or more adds its own `short_14`; its pitch and heading are the + unit's alone. A *piece* below −1 is outside the contract. +- **Q3: the operations with no effect.** EXPLODE_LEGACY and PLAY_SOUND pop their arguments or not and + change nothing; they are the 3.1c operations the engine does not implement. +- **Q4: the turn step.** A piece's rotation step in the piece animation is `elapsed × turnSpeed`, + with no further scaling. +- **Q5: the sweet spot's pose.** With the flag `units.render-pose-reads` off (the default), the slot + poses the model from the unit's game state before reading it; with it on, it reads the renderer's + copy, which depends on what has been drawn. This spec states the default. +- **Q6: a thread that ends on an unknown opcode wakes nothing.** The default case clears the state and + decrements the active count but does not wake the channels waiting on it, so a parent that waits on + it waits for ever. + +## 7. Examples + +Calls from the kit's recordings; a call's inputs are the lines it prints. All numbers are decimal +unless written with `0x`. + +1. **`Apply` START by name, from `orders-air`, call at tick 1025 of `Apply`.** Unit#3's script + CobScript#3 is a new script of UnitDef#21 (its data has `count` 19, `pieceCount` 8, `staticCount` + 4); the event is kind 416, unit Unit#3, form 0, name `"Create"`, callback null, update 1, count 0, + size 76. The script has a channel free, so the thread of `Create` starts: `activeCount` 1, channel + 0 state 0x01000000 at `pc` 320 with `sp` −1, `waiting` 1, `signal` 1; the run at once (update 1) + sets `statics` word 0 to 1, starts channel 1 (its `pc` 239 and `signal` 1 are the script's own + writes), and channel 0 waits on it. The outcome is 1. +2. **`Apply` START by index with arguments, from `orders-factory`, call at tick 19 of `Apply`.** + `FindScript(CobScript#1, "StartBuilding")` is 17 in the same recording, and the event is kind 416, + unit Unit#1, form 2, index 17, name empty, callback null, update 0, count 1, arguments 59405, 0, 0, + 0. Channel 2 is free, so it becomes runnable at `pc` 1741, `signal` 1, and the one argument is + `stack[0]` = 59405, `sp` 0; `activeCount` goes from 2 to 3. No thread runs (update 0). Outcome 1. +3. **`Apply` START by name with arguments, from `orders-air`, call at tick 1025 of `Apply`.** Unit#3, + form 1, name `"setSFXoccupy"`, update 1, count 1, arguments 4, 0, 0, 0, size 76: the thread starts, + runs at once, and the call writes nothing else. Outcome 1. +4. **A rejected event.** An event of kind 416 with `size` 75 is below `ScriptsStart`'s 76 bytes: the + outcome is 0 and nothing changes. So is one of kind 500 with size 76, one whose unit offset is 0, + one of kind 417 with `size` 15, and one of kind 418 or 419 whose state offset is 0. +5. **`QueryScript`, from `orders-air`, call at tick 1025.** `QueryScript(CobScript#2, + "QueryBuildInfo", &arg0, 0, 0, 0)` with `arg0` −1: the thread starts (a channel is free), + `stack[0]` to `stack[3]` take (−1, 0, 0, 0), `sp` 3 and the callback 0, the thread runs at once + and leaves `pc` 746, `sp` 5 and `stack[0]` 1 with the seven words above it 0; `arg0` becomes + `stack[0]` = 1 and the result is 1. +6. **`QueryScript` that changes nothing, from `console-iwin`, call at tick 30.** `QueryScript( + CobScript#2, "Killed", &arg0, &arg1, 0, 0)` with `arg0` 100 and `arg1` 0: the script has no + `Killed`, so the result is 0 and `arg0` and `arg1` keep 100 and 0. +7. **`FindScript`, from `orders-factory`, call at tick 19.** `FindScript(CobScript#1, + "StartBuilding")` is 17; a name the script data does not hold is −1. +8. **`GetPieceOffset` and `GetPiecePosition`, from `orders-air`, calls at tick 1025.** + `GetPieceOffset(Unit#3, 0)` is (0, 0, 0), because Unit#3's model pieces are all at their object's + box and its angles are 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is + Unit#2's pos (41943040, 65536, 16777216) plus the piece's offset (3738171, 15285, 4237826); that + offset comes from the parent chain of section 4, with piece 1's own `object` box and `rot` (all + `rot` 0) and then piece 0's box, its angles adding Unit#2's heading −32768 to the rotation. The + boxes are the node data of `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line). +9. **`GetPieceAngles`, from `orders-air`, calls at ticks 1025, 1026 and 1027.** `GetPieceAngles( + Unit#2, 1)` is (0, 32768, 0), then (0, 32950, 0), then (0, 33132, 0): Unit#2's bank and pitch are + 0 and its heading is −32768 (0x8000); `pieces[1].short_10` and `pieces[1].short_14` are 0, so bank + is 0 and pitch is 0, and `pieces[1].short_12` is 0, 182 and 364, so heading is 0x8000 + 182 and + 0x8000 + 364 as 16-bit values (32950 and 33132). +10. **`NewUnitScript` and `SetCob`, from `orders-air`, call at tick 1025.** `NewUnitScript(Unit#3)` + allocates 1348 bytes (the import's line `services.SimAlloc 1348`) and writes Unit#3's `script` to + that CobScript, `scale` 30, `table` null, `statics` null, `pieces` null, `activeCount` 0. Then + `SetCob(CobScript#3, UnitDef#21)` writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 + zero bytes (4 words) and `pieces` 608 zero bytes (8 records). +11. **The checksum of example 10.** The file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s + `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, + 0xe6, 0x77 and 0x81, and the value is 0x8177e6b2. +12. **`CreatePlayerObjectState`, from `orders-air`, call at tick 1025.** `CreatePlayerObjectState( + UnitDef#21's model, UnitDef#21, Unit#3)` allocates 466 bytes (`services.SimAllocTagged "Object + State" 466`) and the eight point lists of 600, 12, 252, 24, 252, 24, 252 and 24 bytes, in that + order; 466 is 8 × 54 + 34 and the point lists are each node's `vertexCount × 12`. The result is + ModelState#3, whose `count` is 8, `owner` Unit#3 and `animDirty` 1. +13. **`FreeObjectState`, from `console-iwin`, call at tick 30.** `FreeObjectState(ModelState#2)` with + `count` 16 frees sixteen point lists and then the state, seventeen `services.SimFree` calls; no + other import is made. +14. **`RunScripts` and a sleep, from `console-iwin`, calls at ticks 29 and 30.** At tick 29 a + script's channel 0 runs a SLEEP of 200: it is left in state 0x02400000 at `pc` 1434 with `delay` 6 + (30 × 200 / 1000), and `stack[0]` 200 stays. At tick 30 with elapsed 1 the delay is 5. At tick 28 + the same channel had just started: state 0x01000000, `pc` 1431, `delay` 0. +15. **`RunScripts` and a spin, from `orders-air`, call at tick 1026.** A script sets `pieces[1]` + (bytes 76 to 151 of the piece array): `active` 1 (byte 76), `turn[1]` −1 (bytes 108 to 111), + `turnSpeed[1]` 182 (bytes 120 to 123) and `acceleration[1]` 182 (bytes 132 to 135), and `changed` + 1. The piece animation step of 1 sets the model's `pieces[1].short_12` to 182 (and its + `animDirty` to 1), then to 364 at tick 1027 (example 9). +16. **`RunScripts` that changes nothing.** A script whose `activeCount` is 0 and whose `changed` is 0 + makes no write and no import, whatever the elapsed. + +The slots and outcomes no recording covers: `StartScriptWithArgsByIndex` called directly (only +through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `PoseUnitModel`, +`UpdateObjectState`, `ObjectStateSize`, `CreateObjectState`, `DeleteScript`, `SaveScriptState`, +`LoadScriptState`, `WriteState`, the DETACH_PIECE, FREE_STATE and INIT_STATE events, the START form +whose name matches no script and the one whose thread cannot start, the effect command (and so all five +sim events), recording `StartScriptWithArgsByIndex`'s failure, and every unit value (4, 7 to 17, 19, 20) +and every opcode whose effect no recorded thread produces. + +## 8. Kit version + +Kit `interfaces-v66` and `reference-traces-v55`, the versions the gate judges against, at commit +`74bdf5ef`. Interface `scripts` 3.0. The imports are against `map` 9, `los_radar` 5 and `services` +4.2. From 3d6ba033af83058b94a822e044945c057a9dcf83 Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 14:36:40 +0000 Subject: [PATCH 02/30] Docs: Answer the scripts phase 2 review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index a4ebbd1..e6129f5 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -212,7 +212,7 @@ state. | `waiting` | 24 | the index of the child a 0x02800000 wait waits for | | `signal` | 28 | the signal word a KILL operation matches | | `callback` | 32 | `Ref`: the aim callback told when the thread returns | -| `stack` | 36 | 32 words; `Push` writes at `++sp`, `Pop` reads and decrements | +| `stack` | 36 | 32 words; a word is pushed at `sp` after `sp` adds 1, and popped from `sp` before `sp` subtracts 1 | The waiting substate is `state & 0x00f00000` and the state class is `state & 0xff000000`; the fields `delay`, `piece` and `axis` are meaningful only in the substate that uses them. @@ -332,9 +332,9 @@ push did not write. **A query run** of a name and one input word: the thread whose script name equals *name* starts (the thread start of section 4). When it cannot start (no free channel or no matching name), the run does -nothing and its result is 0. When it starts, *input* is stored in `stack[0]`; `sp` becomes 3; the -thread runs at once with elapsed 0; and the answer is `stack[0]` as the run left it. The channel is -left as the run left it. +nothing and its result is 0. When it starts, *input* is stored in `stack[0]`, `stack[1]` to +`stack[3]` are 0; `sp` becomes 3; the thread runs at once with elapsed 0; and the answer is +`stack[0]` as the run left it. The channel is left as the run left it. `QueryScript` takes the script, the name and four argument pointers and runs the query of *name* with four input words, the value of a null argument pointer being 0: they are stored in `stack[0]` to `stack[3]`, `sp` @@ -503,9 +503,9 @@ The thread run of a channel and an elapsed count, with *c* the channel: channel's `axis` is 0, a move wait (0x02200000) when its `moveSpeed` at that axis is 0, and a sleep (0x02400000) subtracts *elapsed* from `delay` and ends when it is 0 or less; each that ends sets the state to 0x01000000. The 0x02800000 wait has no condition here. -2. A channel whose state class is 0x01000000 runs opcodes until it stops, ends or waits. When a - channel's state becomes 0, every channel whose state matches 0x02800000 under the mask 0xfff00000 - and whose `waiting` is its index becomes 0x01000000. +2. A channel whose state class is 0x01000000 runs opcodes until it stops, ends or waits. A channel + ends through RETURN or KILL (below); either makes every channel whose state matches 0x02800000 + under the mask 0xfff00000 and whose `waiting` is its index become 0x01000000. The opcode is the word at `code[pc]`, and the dispatch is on `opcode & 0x100ff000`; the table below gives each case. The stack pointer moves down by one when a word is pushed (the word written at the @@ -560,7 +560,7 @@ taken next. All arithmetic is 32-bit and wraps. | 0x10058000 (LOGICAL_OR) | *b* || *a*, as 1 or 0; `pc += 1`. | | 0x10059000 (LOGICAL_XOR) | *a* is taken, then the next word, and their bitwise xor is pushed; `pc += 1`. | | 0x1005a000 (LOGICAL_NOT) | push 1 when *a* is 0, else 0; `pc += 1`. | -| 0x10061000 (START) | *op1* is the child's entry offset and *op2* the count: a child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the last pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | +| 0x10061000 (START) | *op1* is the child's entry offset and *op2* the count: a child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the first pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | | 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, its state 0x02800000, `pc += 3`, and the parent stops this call. | | 0x10063000 (SET_ARG) | *op2* words are taken and discarded; `pc += 3`. | | 0x10064000 (JUMP) | `pc` becomes *op1*. | @@ -839,8 +839,8 @@ unless written with `0x`. the same channel had just started: state 0x01000000, `pc` 1431, `delay` 0. 15. **`RunScripts` and a spin, from `orders-air`, call at tick 1026.** A script sets `pieces[1]` (bytes 76 to 151 of the piece array): `active` 1 (byte 76), `turn[1]` −1 (bytes 108 to 111), - `turnSpeed[1]` 182 (bytes 120 to 123) and `acceleration[1]` 182 (bytes 132 to 135), and `changed` - 1. The piece animation step of 1 sets the model's `pieces[1].short_12` to 182 (and its + `turnSpeed[1]` 182 (bytes 120 to 123) and `spin[1]` 182 (bytes 132 to 135), with its + `acceleration[1]` 0, and `changed` 1. The piece animation step of 1 sets the model's `pieces[1].short_12` to 182 (and its `animDirty` to 1), then to 364 at tick 1027 (example 9). 16. **`RunScripts` that changes nothing.** A script whose `activeCount` is 0 and whose `changed` is 0 makes no write and no import, whatever the elapsed. From 372bb4b5cc69850f8eedadd11f9301801cf2222c Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 15:00:44 +0000 Subject: [PATCH 03/30] Docs: Answer the scripts phase 1 review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 157 ++++++++++++++++++++++++++++------------------- 1 file changed, 93 insertions(+), 64 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index e6129f5..40da930 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -114,22 +114,31 @@ says adds import lines its recordings do not have. That kit gap is filed too. in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. - **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41), a `block` address that names one unit type's compiled script. It is not read as - a `ScriptTable`; the module reads these values through it, and the recording writes it as the unit - type, `UnitDef#N`: - - `count`: the number of named scripts; - - `pieceCount`: the number of pieces of the unit's model; - - `staticCount`: the number of 32-bit statics; - - `names`: the `count` NUL-terminated script names; - - `entries`: the `count` start offsets of those scripts in `code`; - - `pieceNames`: the `pieceCount` NUL-terminated names of the model's pieces, in model order; - - `code`: the 32-bit words the threads run; - - `checksum`: the four-byte checksum of the script's file, as section 5 computes it. + data (ozgb/btm#41): a `block` address that names one unit type's compiled script, written in a + recording as the unit type, `UnitDef#N`. The record there is nine 32-bit words, every pointer in it a + block offset (0 null): + + | Offset | Field | Meaning | + | --- | --- | --- | + | 0 | `count` | the number of named scripts | + | 4 | `pieceCount` | the number of pieces of the unit's model | + | 8 | `staticCount` | the number of 32-bit statics | + | 12 | `checksum` | the four-byte checksum of the script's file (section 5) | + | 16 | `names` | a block offset to `count` NUL-terminated script names | + | 20 | `entries` | a block offset to `count` start indices of those scripts in `code` | + | 24 | `pieceNames` | a block offset to `pieceCount` NUL-terminated names of the model's pieces, in model order | + | 28 | `code` | a block offset to the 32-bit words the threads run | + | 32 | unused | | + + The host builds the record when it loads a unit type's script, and computes the checksum over the + file's bytes; the compiled code, names and entries are load-time data in the shared memory. - **A callback** arrives as the `linear` address of an object the engine owns, 0 for none; the value a channel stores and AIM_DONE publishes is that object's block offset, 0 for none (ABI 7.1). The module converts between the two and never calls through the object. A callback object is virtual, and its offset is the offset of an object whose first word is a table pointer; the module reads nothing of it. +- **A model** arrives as the engine loaded it, mirrored into the shared memory; the module reads its + nodes and never loads or mirrors its file. - **`out`** (`GetPieceOffset`, `GetPiecePosition`, `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`) is a `Vec3` of three 32-bit integers in the caller's memory, written whole. `GetPieceAngles` writes an `Angles16`: three 16-bit values, bank, heading and pitch in that order. @@ -155,6 +164,12 @@ The kit's manifest entry for this module imports no `services.RecordSimEvent`, s has it cannot record them; a module built from this spec records none of the five until the entry lists the import (the kit gap of section 2, "The manifest entry"). +`Apply` takes only the four kinds of 416 to 419. The routed effects of other interfaces that carry +scripts' intent (kinds 17, 48, 49, 112, 278, 279, 311 and 347, `data/routes.csv`) are translated by +the engine into those events before delivery, as the reference's own translation does. The kit +defines no such translation (its `adapters` is empty), so the payload mapping is the engine's and +this spec cannot state it; that is a kit gap, filed with the others. + ### Effects The module publishes five effects through `Emit`, each at the moment section 4 gives; the payload @@ -237,11 +252,13 @@ fields; the slots here read only the shared prefix. at 42, `child` at 46 and `parent` at 50, `Ref`. **`ModelPieceFlags`** (2 bytes): bit 0 `visible`, bit 1 `colored`, bit 2 `lit`, bits 3 to 15 `rest`. +This subsystem reads bits 1 and 2 as the piece's `cached` and `shaded` bits; the layout's names for +them are `colored` and `lit`. -**`ScriptTable`** (40 bytes): the kit's record of the script data a handle names; its fields at 4 -(`count`), 8 (`pieceCount`), 16 (`staticCount`), 24 (`entries`), 28 (`names`) and 36 (`code`) are -those of section 2, "Arguments outside the block". The compiled data itself is load-time data outside -the block; the module reads it and never writes it. +**The script data handle** (section 2, "Arguments outside the block"): nine words at a block +address; the compiled data it names is load-time data in the shared memory, which the module reads +and never writes. The kit's `ScriptTable` record is the reference's version of the same data; the +handle adds the checksum and the piece names at the offsets section 2 gives. **List and copy rules.** A null `Ref` stores the value 0; any other stores `address - g_blockBase`. A record the slot allocates is not initialised beyond what section 4 says, so its bytes are whatever @@ -309,7 +326,7 @@ The START forms, with *name* the event's 32-byte name copied into a 32-byte buff | Form | Effect | | --- | --- | | 0, by name | The thread of the first script whose name equals *name* starts; when it starts, its callback is *callback*, and when *update* is not 0 every channel runs with elapsed 0 and the piece animation step runs with 0. If no script has that name or no channel is free, nothing starts and nothing is published. | -| 1, by name with arguments | The with-arguments start of section 4 with the index of the first script whose name equals *name*, the callback, *update*, *count* and *args*. | +| 1, by name with arguments | The with-arguments start of section 4 with the index of the first script whose name equals *name* (a name no script has gives index −1, so no thread starts and, when the callback is not 0, AIM_DONE is published with result 0), the callback, *update*, *count* and *args*. | | 2, by index with arguments | The with-arguments start of section 4 with *index*, the callback, *update*, *count* and *args*. | The outcome is 1 for forms 0, 1 and 2 whether or not a thread started, and 0 only for a unit whose @@ -342,6 +359,11 @@ becomes 3, the thread runs at once with elapsed 0, and each non-null argument po `stack[0]`, `stack[1]`, `stack[2]` and `stack[3]`. The result is 1 when the thread started, and 0, with nothing written, not even through the argument pointers, when it did not. +**The bounds of the arguments.** A piece index outside 0 to the model state's `count`−1, a piece +whose object has fewer vertices than the slot reads, a feature index outside `Game.features`, a null +model, a null unit, and a script data handle whose words do not describe its blocks are outside the +contract; a module need not check them. + ### `FindScript(script, name)` The lowest index *i* below the script data's `count` whose name equals *name* byte for byte; -1 when @@ -448,8 +470,9 @@ to (0,0,0) and its `modified` 0; the pieces below the root's first child are res top-level pieces only when their `modified` is 0. Then every piece is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and -then adds the visiting piece's delta to each of them. The visiting piece's angles are its `short_14`, -`short_12` and `short_10` as x, y and z, with the state's `pos` added first for the root; its delta is +then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank +`short_14`, heading `short_12` and pitch `short_10`, with the state's `pos` added first when it is +the root; its delta is `rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. A visit does not change `modified`. @@ -461,18 +484,20 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, -and each of the eight channels' `state` 0. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. The word at offset 0 is not game state: the reference +writes a native table pointer there, no slot reads it and no recording compares it, so a module leaves +it 0. Its other bytes are what the allocation gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: - `script.checksum` becomes the handle's `checksum`; -- `script.pieces` becomes a block of `pieceCount * 76` bytes, set to 0; -- `script.statics` becomes a block of `staticCount * 4` bytes, and its bytes are what the block holds: - a fresh block gives zeros, and a block that grows in place keeps its old bytes. +- `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; +- `script.statics` becomes a block of `staticCount * 4` bytes holding what the script's statics held + before, a byte the old block did not have holding whatever the allocation gives it. -The reference grows the two blocks in place (section 2, "The manifest entry", the kit gap); a module +The blocks grow in place in the reference (section 2, "The manifest entry", the kit gap); a module that only allocates and frees gives the same bytes for a script that had none, and differs for one that had them. @@ -508,8 +533,8 @@ The thread run of a channel and an elapsed count, with *c* the channel: under the mask 0xfff00000 and whose `waiting` is its index become 0x01000000. The opcode is the word at `code[pc]`, and the dispatch is on `opcode & 0x100ff000`; the table below -gives each case. The stack pointer moves down by one when a word is pushed (the word written at the -new position) and up by one when a word is taken (the word read at the old position); *op1* and *op2* +gives each case. The stack pointer adds 1 when a word is pushed (the word written at the new +position) and subtracts 1 when a word is taken (the word read at the old position); *op1* and *op2* are the words at `code[pc+1]` and `code[pc+2]`; *a* is the word taken first (the top) and *b* the one taken next. All arithmetic is 32-bit and wraps. @@ -560,8 +585,8 @@ taken next. All arithmetic is 32-bit and wraps. | 0x10058000 (LOGICAL_OR) | *b* || *a*, as 1 or 0; `pc += 1`. | | 0x10059000 (LOGICAL_XOR) | *a* is taken, then the next word, and their bitwise xor is pushed; `pc += 1`. | | 0x1005a000 (LOGICAL_NOT) | push 1 when *a* is 0, else 0; `pc += 1`. | -| 0x10061000 (START) | *op1* is the child's entry offset and *op2* the count: a child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the first pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | -| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, its state 0x02800000, `pc += 3`, and the parent stops this call. | +| 0x10061000 (START) | *op1* is the child's script index and *op2* the count: the child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the first pushed becomes `stack[0]`), and its `signal` becomes the parent's; the child's `sp` stays −1, so it reads its arguments by index; `pc += 3`. When the child cannot start, nothing is taken and nothing is moved. | +| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index (a child that could not start gives −1, which nothing ever wakes), its state 0x02800000, `pc += 3`, and the parent stops this call. | | 0x10063000 (SET_ARG) | *op2* words are taken and discarded; `pc += 3`. | | 0x10064000 (JUMP) | `pc` becomes *op1*. | | 0x10065000 (RETURN) | when the channel's callback is not 0, *a* is taken and AIM_DONE is published with the callback and *a*; otherwise the stack is untouched. Then state 0, `activeCount` subtracts 1, the wake rule of the thread run runs for the channel, and the channel stops this call. | @@ -585,7 +610,10 @@ the state's `animDirty` 1, and when the piece's `cached` bit is set, the state's Setting its visible bit writes nothing when the bit already has that value; a write sets `modified` 0, and when the piece is cached, `cacheDrawCount` 0 (but not `animDirty`). -**Unit values**, with *u* the unit the script belongs to and *a*, *b*, *d*, *e* the arguments: +**Unit values**, with *u* the unit the script belongs to. The read's number and arguments are: for +GET_UNIT_VALUE the number is *a* and there are no arguments; for GET_UNIT_VALUE_4 the number is *f* +and the arguments are *e*, *d*, *b*, *a* in that order. In the table, *a* and *b* are the first and +second arguments. | Value | Result | | --- | --- | @@ -633,7 +661,10 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | any other | nothing recorded | As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records -none of these five. +none of these five. The reference records a publish as an engine call of its own, which the +recordings show as a `services.SchedPublish` line; a module publishes through `Emit`, which the +engine records as the same effect, so the effect's kind and fields are what is compared, not the +import's name (ABI 7.2 and 9.3). **The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: @@ -673,25 +704,23 @@ clear. ### `SaveScriptState(script, bank)` -The bank is sought to item 0, and a saved header record of 0x528 bytes is written: the script's -`checksum`, the eight channels with their callbacks 0, and `activeCount`. Then the statics, -`staticCount × 4` bytes. Then, for each piece from 0 to `pieceCount`−1, a `SavedPiece` of 0x6c bytes: +The bank holds a header record of 0x528 bytes, then the statics (`staticCount × 4` bytes), then for +each piece from 0 to `pieceCount`−1 a `SavedPiece` of 0x6c bytes. The header holds the script's +`checksum`, the eight channels with their callbacks 0 and `activeCount`; a saved piece holds `visible`, `cached` and `shaded` from the piece's flags, the six arrays, and `translation` and `rotation` from the model's pieces. This is an engine slot; the module does not export it. ### `LoadScriptState(script, bank)` When the bank's size is not `pieceCount × 0x6c + 0x528 + staticCount × 4`, the result is 0 and nothing -changes. Otherwise the bank is sought to item 0, a saved header record is read (when the read returns -fewer bytes than 0x528, the result is 0), and the script's `checksum` must equal the saved one (else -0). Then the eight channels take the saved ones with their callbacks 0, `activeCount` the saved one, -the statics are read into the script's statics (a read of fewer bytes than asked gives 0 and leaves -what was copied), and the pieces are read: each piece becomes `active` 1, its `visible`, `cached` and -`shaded` are set, the six arrays copied, `translation` and `rotation` set through the model's pieces, -and `changed` 1. The result is 1. The pieces are read through a buffer of `pieceCount × 0x6c` bytes -from `SimAllocTagged` with the tag `"Piece States"`, freed on success; a short read of the statics -returns 0 with nothing allocated, and a short read of the pieces returns 0 with the buffer still -allocated. This is an engine slot; the module does not export it. +changes. Otherwise a header read of fewer bytes than 0x528 gives 0, and the script's `checksum` must +equal the saved one (else 0). Then the eight channels take the saved ones with their callbacks 0 and +`activeCount` the saved one, the statics take the saved ones (a statics read of fewer bytes than asked +gives 0 then and there, after the channels and the count were already taken), and the pieces take the +saved ones: each becomes `active` 1, its `visible`, `cached` and `shaded` are set, the six arrays +copied, `translation` and `rotation` set through the model's pieces, and `changed` 1. A piece read of +fewer bytes than asked gives 0. The result is 1. This is an engine slot; the module does not export +it. ### `WriteState(writer)` @@ -726,14 +755,15 @@ module does not export it. product rounded to the nearest double, the results are *rx* = *x* × C − *z* × S and *rz* = *z* × C + *x* × S each a double, and each is rounded to the nearest int, ties to even, with −2147483648 when it is outside the int range. -- **The three-angle rotation of a point**: the point is rotated by the bank (angle 0), then the result's second - coordinate and the original z by the pitch (angle 2), then that result's second and the first by the - heading (angle 1): each step is the rule above, in that order. +- **The three-angle rotation of a point** (x, y, z) by the angles bank, heading and pitch: with + rotate(p, q, a) the point rotation of p and q by angle a (section 5), the steps are + (x, y) = rotate(x, y, bank); (y, z) = rotate(y, z, pitch); and (x, z) = rotate(x, z, heading), each + step on the values the one before it left, in that order. - **The angle of a vector** (*x*, *z*): the rule is `runtime/vectors/README.md`, "Angle of a - vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], computed as the double-double - `internal.h`'s `bx_dd_atan2_nonneg` gives it, rounded to the nearest double with a 64-bit mantissa - (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the nearest int - ties to even, and negated when x is negative. + vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], computed as the double-double the kit's + `runtime/internal.h` gives it (`bx_dd_atan2_nonneg`), rounded to the nearest double with a 64-bit + mantissa (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the + nearest int ties to even, and negated when x is negative. - **hypot and the conversion to int**: `hypot(x, y)` follows `runtime/vectors/README.md`, "hypot" (each step rounded to a 64-bit mantissa and then to a double, except the squares). `bx_ftol(x)`: the result is 0 when |x| < 1; otherwise the integer part of |x| truncated, its low 32 bits, negated @@ -753,16 +783,15 @@ module does not export it. ## 6. Quirks -- **Q1: the query's word for `sp` and its stack.** `QueryScript` addresses the channel's `sp` as - the query count and writes its in-values through it: the count starts at −1, each `++` of it is the - next `stack` word, so the four values land at `stack[0]` to `stack[3]`, and it is then set to 3. - The word it clears is the channel's `callback`, and the answers are read from `stack[0]` to - `stack[3]`. +- **Q1: the query's words.** `QueryScript` counts its in-values in the channel's `sp`: it starts at + −1 and each value is written one word further up, so the four values land at `stack[0]` to + `stack[3]`, and `sp` is then set to 3. The word it clears is the channel's `callback`, and the + answers are read from `stack[0]` to `stack[3]`. - **Q2: a piece of −1.** `GetPieceAngles` with *piece* −1 adds the low 16 bits of the model state's `count` to the bank, where a piece 0 or more adds its own `short_14`; its pitch and heading are the unit's alone. A *piece* below −1 is outside the contract. -- **Q3: the operations with no effect.** EXPLODE_LEGACY and PLAY_SOUND pop their arguments or not and - change nothing; they are the 3.1c operations the engine does not implement. +- **Q3: the operations with no effect.** EXPLODE_LEGACY takes two words and changes nothing; + PLAY_SOUND takes none and changes nothing. They are 3.1c operations this engine does not implement. - **Q4: the turn step.** A piece's rotation step in the piece animation is `elapsed × turnSpeed`, with no further scaling. - **Q5: the sweet spot's pose.** With the flag `units.render-pose-reads` off (the default), the slot @@ -806,12 +835,12 @@ unless written with `0x`. 7. **`FindScript`, from `orders-factory`, call at tick 19.** `FindScript(CobScript#1, "StartBuilding")` is 17; a name the script data does not hold is −1. 8. **`GetPieceOffset` and `GetPiecePosition`, from `orders-air`, calls at tick 1025.** - `GetPieceOffset(Unit#3, 0)` is (0, 0, 0), because Unit#3's model pieces are all at their object's - box and its angles are 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is - Unit#2's pos (41943040, 65536, 16777216) plus the piece's offset (3738171, 15285, 4237826); that - offset comes from the parent chain of section 4, with piece 1's own `object` box and `rot` (all - `rot` 0) and then piece 0's box, its angles adding Unit#2's heading −32768 to the rotation. The - boxes are the node data of `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line). + `GetPieceOffset(Unit#3, 0)` is (0, 0, 0), because Unit#3's root piece has `rot` 0 and its object's + box 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is Unit#2's pos + (45613056, 65536, 19922944) plus the piece's offset (68155, 15285, 1092098); that offset comes from + the piece-offset rule, with piece 1's own `object` box and `rot` (all `rot` 0) and then piece 0's + box, its angles adding Unit#2's heading −32768 to the rotation. The boxes are the node data of + `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line). 9. **`GetPieceAngles`, from `orders-air`, calls at ticks 1025, 1026 and 1027.** `GetPieceAngles( Unit#2, 1)` is (0, 32768, 0), then (0, 32950, 0), then (0, 33132, 0): Unit#2's bank and pitch are 0 and its heading is −32768 (0x8000); `pieces[1].short_10` and `pieces[1].short_14` are 0, so bank @@ -850,8 +879,8 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `UpdateObjectState`, `ObjectStateSize`, `CreateObjectState`, `DeleteScript`, `SaveScriptState`, `LoadScriptState`, `WriteState`, the DETACH_PIECE, FREE_STATE and INIT_STATE events, the START form whose name matches no script and the one whose thread cannot start, the effect command (and so all five -sim events), recording `StartScriptWithArgsByIndex`'s failure, and every unit value (4, 7 to 17, 19, 20) -and every opcode whose effect no recorded thread produces. +sim events), recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write +of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. ## 8. Kit version From 53e1c8cad4c35950bf307edd17860c21bdeab670 Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 15:15:41 +0000 Subject: [PATCH 04/30] Docs: Answer the scripts phase 2 second review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 76 ++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 42 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 40da930..89d05ae 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -114,24 +114,16 @@ says adds import lines its recordings do not have. That kit gap is filed too. in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. - **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41): a `block` address that names one unit type's compiled script, written in a - recording as the unit type, `UnitDef#N`. The record there is nine 32-bit words, every pointer in it a - block offset (0 null): - - | Offset | Field | Meaning | - | --- | --- | --- | - | 0 | `count` | the number of named scripts | - | 4 | `pieceCount` | the number of pieces of the unit's model | - | 8 | `staticCount` | the number of 32-bit statics | - | 12 | `checksum` | the four-byte checksum of the script's file (section 5) | - | 16 | `names` | a block offset to `count` NUL-terminated script names | - | 20 | `entries` | a block offset to `count` start indices of those scripts in `code` | - | 24 | `pieceNames` | a block offset to `pieceCount` NUL-terminated names of the model's pieces, in model order | - | 28 | `code` | a block offset to the 32-bit words the threads run | - | 32 | unused | | - - The host builds the record when it loads a unit type's script, and computes the checksum over the - file's bytes; the compiled code, names and entries are load-time data in the shared memory. + data (ozgb/btm#41). In a recording it is written as the holder, `UnitDef#N`; the kit's replay gives + the linear address of its copy of the unit type's compiled script, outside the block. The record + there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` + at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), + the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. The compiled + data is load-time data, which the module reads and never writes. + The file's checksum is not in the record: the reference keeps it beside the table, computed over + the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that + checksum, and its manifest kind for the argument is `block` although the table is outside the block; + both are kit gaps, raised on ozgb/byte-tactics-moddable#1197. - **A callback** arrives as the `linear` address of an object the engine owns, 0 for none; the value a channel stores and AIM_DONE publishes is that object's block offset, 0 for none (ABI 7.1). The module converts between the two and never calls through the object. A callback object is virtual, @@ -166,9 +158,9 @@ lists the import (the kit gap of section 2, "The manifest entry"). `Apply` takes only the four kinds of 416 to 419. The routed effects of other interfaces that carry scripts' intent (kinds 17, 48, 49, 112, 278, 279, 311 and 347, `data/routes.csv`) are translated by -the engine into those events before delivery, as the reference's own translation does. The kit -defines no such translation (its `adapters` is empty), so the payload mapping is the engine's and -this spec cannot state it; that is a kit gap, filed with the others. +the engine into those events before delivery, as the reference's seam translates them. The kit +defines no payload mapping for that translation, so this spec cannot state it; that is a kit gap, +filed with the others. ### Effects @@ -255,10 +247,11 @@ at 42, `child` at 46 and `parent` at 50, `Ref`. This subsystem reads bits 1 and 2 as the piece's `cached` and `shaded` bits; the layout's names for them are `colored` and `lit`. -**The script data handle** (section 2, "Arguments outside the block"): nine words at a block -address; the compiled data it names is load-time data in the shared memory, which the module reads -and never writes. The kit's `ScriptTable` record is the reference's version of the same data; the -handle adds the checksum and the piece names at the offsets section 2 gives. +**The script data handle** (section 2, "Arguments outside the block"): a handle to a unit type's +compiled script, whose record is the kit's `ScriptTable` (40 bytes: `count` at 4, `pieceCount` 8, +`staticCount` 16, `entries` 24, `names` 28, the model's piece names 32, `code` 36). The compiled +data is load-time data, which the module reads and never writes; the file's checksum is kept beside +the record. **List and copy rules.** A null `Ref` stores the value 0; any other stores `address - g_blockBase`. A record the slot allocates is not initialised beyond what section 4 says, so its bytes are whatever @@ -359,10 +352,11 @@ becomes 3, the thread runs at once with elapsed 0, and each non-null argument po `stack[0]`, `stack[1]`, `stack[2]` and `stack[3]`. The result is 1 when the thread started, and 0, with nothing written, not even through the argument pointers, when it did not. -**The bounds of the arguments.** A piece index outside 0 to the model state's `count`−1, a piece -whose object has fewer vertices than the slot reads, a feature index outside `Game.features`, a null -model, a null unit, and a script data handle whose words do not describe its blocks are outside the -contract; a module need not check them. +**The bounds of the arguments.** The piece-offset rule gives (0, 0, 0) for a null unit or model +state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a piece of −1. Everything +else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature +index, a model with fewer vertices than a slot reads, and a script data handle that does not describe +its data are outside the contract, and a module need not check them. ### `FindScript(script, name)` @@ -484,9 +478,9 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, -and each of the eight channels' `state` 0. The word at offset 0 is not game state: the reference -writes a native table pointer there, no slot reads it and no recording compares it, so a module leaves -it 0. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. The word at offset 0 is the object's table pointer: the +reference writes a native address there, no slot reads it, and no recording compares its bytes; a +module writes 0. Its other bytes are what the allocation gives them. ### `SetCob(script, data)` @@ -494,12 +488,11 @@ it 0. Its other bytes are what the allocation gives them. - `script.checksum` becomes the handle's `checksum`; - `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes holding what the script's statics held - before, a byte the old block did not have holding whatever the allocation gives it. +- `script.statics` becomes a block of `staticCount * 4` bytes: a byte the statics block already held + keeps its value, and a byte beyond it holds whatever the allocation gives (zero for a new block). -The blocks grow in place in the reference (section 2, "The manifest entry", the kit gap); a module -that only allocates and frees gives the same bytes for a script that had none, and differs for one -that had them. +The kit's entry has no reallocation service, so a module allocates the two blocks and frees the old +ones; the reference's own growth leaves no recorded import (the kit gap of section 2). ### `CreatePlayerObjectState(model, data, owner)` @@ -611,7 +604,7 @@ Setting its visible bit writes nothing when the bit already has that value; a wr and when the piece is cached, `cacheDrawCount` 0 (but not `animDirty`). **Unit values**, with *u* the unit the script belongs to. The read's number and arguments are: for -GET_UNIT_VALUE the number is *a* and there are no arguments; for GET_UNIT_VALUE_4 the number is *f* +GET_UNIT_VALUE the number is *a* and its four arguments are 0; for GET_UNIT_VALUE_4 the number is *f* and the arguments are *e*, *d*, *b*, *a* in that order. In the table, *a* and *b* are the first and second arguments. @@ -760,9 +753,8 @@ module does not export it. (x, y) = rotate(x, y, bank); (y, z) = rotate(y, z, pitch); and (x, z) = rotate(x, z, heading), each step on the values the one before it left, in that order. - **The angle of a vector** (*x*, *z*): the rule is `runtime/vectors/README.md`, "Angle of a - vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], computed as the double-double the kit's - `runtime/internal.h` gives it (`bx_dd_atan2_nonneg`), rounded to the nearest double with a 64-bit - mantissa (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the + vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], rounded to nearest with a 64-bit + mantissa and then to a double, multiplied by the double nearest 10430.37835047, rounded to the nearest int ties to even, and negated when x is negative. - **hypot and the conversion to int**: `hypot(x, y)` follows `runtime/vectors/README.md`, "hypot" (each step rounded to a 64-bit mantissa and then to a double, except the squares). `bx_ftol(x)`: @@ -791,7 +783,7 @@ module does not export it. `count` to the bank, where a piece 0 or more adds its own `short_14`; its pitch and heading are the unit's alone. A *piece* below −1 is outside the contract. - **Q3: the operations with no effect.** EXPLODE_LEGACY takes two words and changes nothing; - PLAY_SOUND takes none and changes nothing. They are 3.1c operations this engine does not implement. + PLAY_SOUND takes none and changes nothing. - **Q4: the turn step.** A piece's rotation step in the piece animation is `elapsed × turnSpeed`, with no further scaling. - **Q5: the sweet spot's pose.** With the flag `units.render-pose-reads` off (the default), the slot From 7060e9d7b57b39cfbfcf7da2e8baa50a7df85edb Mon Sep 17 00:00:00 2001 From: opencode Date: Sun, 29 Nov 2026 01:42:33 +0000 Subject: [PATCH 05/30] Docs: Fix the scripts vptr and SetCob wording Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 89d05ae..5545018 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -478,21 +478,19 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, -and each of the eight channels' `state` 0. The word at offset 0 is the object's table pointer: the -reference writes a native address there, no slot reads it, and no recording compares its bytes; a -module writes 0. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. Offset 0 holds the object's table pointer; a module writes +0 there, and it is not one of the fields a recording compares. Its other bytes are what the allocation +gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: -- `script.checksum` becomes the handle's `checksum`; +- `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries + (section 2 states the kit gap: the kit gives a module no word for it); - `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes: a byte the statics block already held - keeps its value, and a byte beyond it holds whatever the allocation gives (zero for a new block). - -The kit's entry has no reallocation service, so a module allocates the two blocks and frees the old -ones; the reference's own growth leaves no recorded import (the kit gap of section 2). +- `script.statics` becomes a block of `staticCount * 4` bytes: an extent the statics block already + held keeps its bytes, and a new extent is 0. ### `CreatePlayerObjectState(model, data, owner)` From 2224de5fe9b8fbbd24f3b205d9b25b5b6d6a6405 Mon Sep 17 00:00:00 2001 From: Implementer Date: Sun, 29 Nov 2026 01:56:05 +0000 Subject: [PATCH 06/30] Add: scripts module Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/Cargo.lock | 7 + scripts/Cargo.toml | 14 + scripts/build.sh | 13 + scripts/ld-wrap.sh | 9 + scripts/mathtest/Cargo.lock | 7 + scripts/mathtest/Cargo.toml | 9 + scripts/mathtest/src/main.rs | 47 + scripts/src/lib.rs | 1764 ++++++++++++++++++++++++++++++++++ scripts/src/math.rs | 672 +++++++++++++ 9 files changed, 2542 insertions(+) create mode 100644 scripts/Cargo.lock create mode 100644 scripts/Cargo.toml create mode 100755 scripts/build.sh create mode 100755 scripts/ld-wrap.sh create mode 100644 scripts/mathtest/Cargo.lock create mode 100644 scripts/mathtest/Cargo.toml create mode 100644 scripts/mathtest/src/main.rs create mode 100644 scripts/src/lib.rs create mode 100644 scripts/src/math.rs diff --git a/scripts/Cargo.lock b/scripts/Cargo.lock new file mode 100644 index 0000000..5a45b8e --- /dev/null +++ b/scripts/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "scripts" +version = "0.1.0" diff --git a/scripts/Cargo.toml b/scripts/Cargo.toml new file mode 100644 index 0000000..1d7d7fa --- /dev/null +++ b/scripts/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "scripts" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[profile.release] +panic = "abort" +opt-level = "z" +lto = true +codegen-units = 1 +debug = false diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..6236f5c --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Builds module.wasm: the cdylib linked at the manifest's data base and table base, then metered +# by the kit's fuel pass (ABI 11, rule v1). Usage: build.sh [FUEL_PASS.py] +set -e +cd "$(dirname "$0")" +PASS=${1:-${WASM_FUEL:-/data/tools/wasm_fuel.py}} +cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory \ + -C link-arg=--import-memory -C link-arg=--import-table -C link-arg=--global-base=589824 -C link-arg=--table-base=432 \ + -C link-arg=--no-entry -C link-arg=-zstack-size=4096 -C link-arg=--gc-sections +T=$(mktemp -d) +cp target/wasm32-unknown-unknown/release/scripts.wasm "$T/raw.wasm" +python3 "$PASS" "$T/raw.wasm" -o module.wasm +rm -rf "$T" diff --git a/scripts/ld-wrap.sh b/scripts/ld-wrap.sh new file mode 100755 index 0000000..ada6ff2 --- /dev/null +++ b/scripts/ld-wrap.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# rustc passes --stack-first and --allow-undefined; the ABI forbids both. +# ABI 3.1 wants --no-stack-first; a linker whose help doesn't list it already puts the stack after the data. +for a in "$@"; do + shift + case "$a" in --stack-first|--allow-undefined|--export=__heap_base|--export=__data_end) ;; *) set -- "$@" "$a";; esac +done +if wasm-ld --help | grep -q -e '--no-stack-first'; then set -- "$@" --no-stack-first; fi +exec wasm-ld "$@" diff --git a/scripts/mathtest/Cargo.lock b/scripts/mathtest/Cargo.lock new file mode 100644 index 0000000..a9c723e --- /dev/null +++ b/scripts/mathtest/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "mathtest" +version = "0.1.0" diff --git a/scripts/mathtest/Cargo.toml b/scripts/mathtest/Cargo.toml new file mode 100644 index 0000000..90503f9 --- /dev/null +++ b/scripts/mathtest/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "mathtest" +version = "0.1.0" +edition = "2021" + +[workspace] + +[profile.release] +opt-level = 2 diff --git a/scripts/mathtest/src/main.rs b/scripts/mathtest/src/main.rs new file mode 100644 index 0000000..0f5fff0 --- /dev/null +++ b/scripts/mathtest/src/main.rs @@ -0,0 +1,47 @@ +#[path = "../../src/math.rs"] +#[allow(dead_code)] +mod math; +use std::fs; + +fn recs(name: &str, insz: usize, outsz: usize) -> Vec> { + let b = fs::read(format!("/data/runtime/vectors/{}.bin", name)).unwrap(); + b.chunks(insz + outsz).map(|c| c.to_vec()).collect() +} +fn i(b: &[u8], o: usize) -> i32 { i32::from_le_bytes(b[o..o + 4].try_into().unwrap()) } +fn d(b: &[u8], o: usize) -> f64 { f64::from_bits(u64::from_le_bytes(b[o..o + 8].try_into().unwrap())) } + +fn main() { + let mut bad = 0; + for r in recs("rotate_point", 12, 8) { + let mut c = math::TrigCache::new(); + let (rx, rz) = math::rotate_point(&mut c, i(&r, 0) as u32 as u16, i(&r, 4), i(&r, 8)); + if (rx, rz) != (i(&r, 12), i(&r, 16)) { bad += 1; } + } + println!("rotate_point bad {}", bad); + bad = 0; + for r in recs("angle_of_vector", 8, 4) { + if math::angle_of_vector(i(&r, 0), i(&r, 4)) != i(&r, 8) { bad += 1; } + } + println!("angle bad {}", bad); + bad = 0; + for r in recs("hypot", 16, 8) { + if math::hypot(d(&r, 0), d(&r, 8)).to_bits() != d(&r, 16).to_bits() { bad += 1; } + } + println!("hypot bad {}", bad); + bad = 0; + for r in recs("ftol", 8, 4) { + if math::ftol(d(&r, 0)) != i(&r, 8) { bad += 1; } + } + println!("ftol bad {}", bad); + // sincos table from the kit's generator + if let Ok(t) = fs::read_to_string("/tmp/w/sincos.txt") { + bad = 0; + for (n, l) in t.lines().enumerate() { + let v: Vec = l.split_whitespace().map(|s| u64::from_str_radix(s, 16).unwrap()).collect(); + let tr = math::trig(n as u16); + if n == 0 { continue; } if n==24807 { println!("24807 ok? {:x?} {:x} {:x}", v, tr.cm, tr.ce);} + if (tr.sm, tr.se as u64, tr.cm, tr.ce as u64) != (v[0], v[1], v[2], v[3]) { bad += 1; if bad < 5 { println!("angle {} got {:x} {:x} {:x} {:x} want {:x?}", n, tr.sm, tr.se, tr.cm, tr.ce, v); } } + } + println!("sincos bad {}", bad); + } +} diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs new file mode 100644 index 0000000..b3a9271 --- /dev/null +++ b/scripts/src/lib.rs @@ -0,0 +1,1764 @@ +#![no_std] + +mod math; + +use core::ptr::{addr_of, read_unaligned, read_volatile, write_unaligned}; +use math::TrigCache; + +#[link(wasm_import_module = "map")] +extern "C" { + #[link_name = "GetGroundHeight"] + fn get_ground_height(pos: *mut i32) -> i32; +} + +#[link(wasm_import_module = "los_radar")] +extern "C" { + #[link_name = "IsUnitVisibleToPlayer"] + fn is_unit_visible(player: u32, unit: u32) -> i32; +} + +#[link(wasm_import_module = "services")] +extern "C" { + #[link_name = "SimAlloc"] + fn sim_alloc(size: u32) -> u32; + #[link_name = "SimAllocTagged"] + fn sim_alloc_tagged(tag: *const u8, size: u32) -> u32; + #[link_name = "SimFree"] + fn sim_free(p: u32); + #[link_name = "Emit"] + fn emit(effect: *const u32, size: i32); +} + +#[no_mangle] +pub static mut g_game: u32 = 0; +#[no_mangle] +pub static mut g_simGlobals: u32 = 0; +#[no_mangle] +pub static mut g_extTdf: u32 = 0; +#[no_mangle] +pub static mut g_blockBase: u32 = 0; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + loop {} +} + +// ---------------------------------------------------------------- memory + +#[inline(always)] +fn r32(a: u32) -> u32 { + unsafe { read_unaligned(a as *const u32) } +} +#[inline(always)] +fn ri(a: u32) -> i32 { + r32(a) as i32 +} +#[inline(always)] +fn r16(a: u32) -> u16 { + unsafe { read_unaligned(a as *const u16) } +} +#[inline(always)] +fn rs(a: u32) -> i16 { + r16(a) as i16 +} +#[inline(always)] +fn r8(a: u32) -> u8 { + unsafe { read_unaligned(a as *const u8) } +} +#[inline(always)] +fn w32(a: u32, v: u32) { + unsafe { write_unaligned(a as *mut u32, v) } +} +#[inline(always)] +fn wi(a: u32, v: i32) { + w32(a, v as u32) +} +#[inline(always)] +fn w16(a: u32, v: u16) { + unsafe { write_unaligned(a as *mut u16, v) } +} +#[inline(always)] +fn blk() -> u32 { + unsafe { read_volatile(addr_of!(g_blockBase)) } +} +#[inline(always)] +fn game() -> u32 { + unsafe { read_volatile(addr_of!(g_game)) } +} +#[inline(always)] +fn globals() -> u32 { + unsafe { read_volatile(addr_of!(g_simGlobals)) } +} +/// A `Ref` stored at `a`, as an address (0 for null). +#[inline(always)] +fn rf(a: u32) -> u32 { + let o = r32(a); + if o == 0 { + 0 + } else { + blk().wrapping_add(o) + } +} +/// The block offset of an address (0 for null). +#[inline(always)] +fn off(a: u32) -> u32 { + if a == 0 { + 0 + } else { + a.wrapping_sub(blk()) + } +} +fn copy(dst: u32, src: u32, n: u32) { + unsafe { core::ptr::copy(src as *const u8, dst as *mut u8, n as usize) } +} +fn zero(dst: u32, n: u32) { + unsafe { core::ptr::write_bytes(dst as *mut u8, 0, n as usize) } +} + +fn streq(a: u32, b: u32) -> bool { + let mut i = 0; + loop { + let (x, y) = (r8(a + i), r8(b + i)); + if x != y { + return false; + } + if x == 0 { + return true; + } + i += 1; + } +} +fn lower(c: u8) -> u8 { + if c >= b'A' && c <= b'Z' { + c + 32 + } else { + c + } +} +fn streq_ci(a: u32, b: u32) -> bool { + let mut i = 0; + loop { + let (x, y) = (lower(r8(a + i)), lower(r8(b + i))); + if x != y { + return false; + } + if x == 0 { + return true; + } + i += 1; + } +} +fn strend(a: u32) -> u32 { + let mut i = 0; + while r8(a + i) != 0 { + i += 1; + } + a + i + 1 +} + +// ---------------------------------------------------------------- layout + +// Unit +const U_BANK: u32 = 100; +const U_POS: u32 = 106; +const U_CARRIER: u32 = 134; +const U_CARGO: u32 = 138; +const U_CARGO_NEXT: u32 = 142; +const U_DEF: u32 = 146; +const U_SCRIPT: u32 = 154; +const U_STATE: u32 = 158; +const U_ID: u32 = 168; +const U_BUILD_LEFT: u32 = 260; +const U_HEALTH: u32 = 264; +const U_ACTIVATE: u32 = 270; +const U_COB_FLAGS: u32 = 271; +const U_FLAGS: u32 = 272; +const UNIT_SIZE: u32 = 280; +const ALIVE: u32 = 0x1000_0000; +// Game +const G_PLAYERS: u32 = 7011; +const G_PLAYER_SIZE: u32 = 331; +const G_PLAYER_INDEX: u32 = 10819; +const G_FEATURES: u32 = 82543; +const G_UNITS: u32 = 82775; +const FEATURE_SIZE: u32 = 256; +const F_OBJECT: u32 = 152; +const G_RANDOM_SEED: u32 = 48172; +// CobScript +const S_TABLE: u32 = 8; +const S_CHECKSUM: u32 = 12; +const S_STATICS: u32 = 16; +const S_PIECES: u32 = 20; +const S_CHANGED: u32 = 24; +const S_CHANNELS: u32 = 28; +const S_ACTIVE: u32 = 1340; +const S_STATE: u32 = 1344; +const SCRIPT_SIZE: u32 = 1348; +const CHANNEL_SIZE: u32 = 164; +// Channel +const C_PC: u32 = 4; +const C_SP: u32 = 8; +const C_DELAY: u32 = 12; +const C_PIECE: u32 = 16; +const C_AXIS: u32 = 20; +const C_WAITING: u32 = 24; +const C_SIGNAL: u32 = 28; +const C_CALLBACK: u32 = 32; +const C_STACK: u32 = 36; +// Piece (animation record) +const P_SIZE: u32 = 76; +const P_MOVE: u32 = 4; +const P_MOVE_SPEED: u32 = 16; +const P_TURN: u32 = 28; +const P_TURN_SPEED: u32 = 40; +const P_SPIN: u32 = 52; +const P_ACCEL: u32 = 64; +// ModelState +const M_COUNT: u32 = 0; +const M_CACHE_DRAW: u32 = 4; +const M_DIRTY: u32 = 8; +const M_OWNER: u32 = 12; +const M_BITMAP: u32 = 16; +const M_POS: u32 = 24; +const M_ROOT: u32 = 30; +const M_PIECES: u32 = 34; +// ModelPiece +const MP_SIZE: u32 = 54; +const MP_TRANS: u32 = 4; +const MP_ROT: u32 = 16; // short_10, short_12, short_14: axis 0, 1, 2 +const MP_OFFSET: u32 = 22; +const MP_POINTS: u32 = 34; +const MP_MODIFIED: u32 = 38; +const MP_FLAGS: u32 = 40; +const MP_SIBLING: u32 = 42; +const MP_CHILD: u32 = 46; +const MP_PARENT: u32 = 50; +const F_VISIBLE: u16 = 1; +const F_CACHED: u16 = 2; +const F_SHADED: u16 = 4; +// Object3do +const O_VERTEX_COUNT: u32 = 4; +const O_BOX: u32 = 16; +const O_NAME: u32 = 28; +const O_VERTICES: u32 = 36; +const O_SIBLING: u32 = 44; +const O_CHILD: u32 = 48; + +const ST_RUN: u32 = 0x0100_0000; +const ST_WAIT_CLASS: u32 = 0x0200_0000; +const ST_TURN: u32 = 0x0210_0000; +const ST_MOVE: u32 = 0x0220_0000; +const ST_SLEEP: u32 = 0x0240_0000; +const ST_CHILD: u32 = 0x0280_0000; + +// ---------------------------------------------------------------- effects + +fn publish(kind: u32, a: u32, b: u32, c: u32, d: u32, size: i32) { + let e = [kind, a, b, c, d]; + unsafe { emit(e.as_ptr(), size) } +} +fn set_yard(unit: u32, open: i32) { + if unit != 0 { + publish(164, off(unit), open as u32, 0, 0, 12); + } +} +fn aim_done(callback: u32, result: i32) { + if callback != 0 { + publish(263, 0, callback, result as u32, 0, 16); + } +} +fn explode_piece(unit: u32, piece: i32, flags: u32) { + publish(264, off(unit), piece as u32, flags, 0, 16); +} +fn attach_to_piece(unit: u32, target: u32, piece: i32, mode: i32) { + publish(357, off(unit), off(target), piece as u32, mode as u32, 20); +} +fn script_value(unit: u32, which: i32, value: i32) { + publish(386, off(unit), which as u32, value as u32, 0, 16); +} + +// ---------------------------------------------------------------- script data + +/// A pointer field of a script table: a linear address, or an offset into the file. +#[inline(always)] +fn tptr(t: u32, v: u32) -> u32 { + if v >= t { + v + } else { + t + v + } +} +#[inline(always)] +fn t_count(t: u32) -> i32 { + ri(t + 4) +} +#[inline(always)] +fn t_pieces(t: u32) -> i32 { + ri(t + 8) +} +#[inline(always)] +fn t_statics(t: u32) -> i32 { + ri(t + 16) +} +#[inline(always)] +fn t_code(t: u32) -> u32 { + tptr(t, r32(t + 36)) +} +fn t_entry(t: u32, i: i32) -> i32 { + ri(tptr(t, r32(t + 24)) + 4 * i as u32) +} +fn t_name(t: u32, i: i32) -> u32 { + tptr(t, r32(tptr(t, r32(t + 28)) + 4 * i as u32)) +} +fn t_piece_name(t: u32, i: i32) -> u32 { + tptr(t, r32(tptr(t, r32(t + 32)) + 4 * i as u32)) +} + +fn find_script_in(t: u32, name: u32) -> i32 { + if t == 0 { + return -1; + } + let n = t_count(t); + let mut i = 0; + while i < n { + if streq(t_name(t, i), name) { + return i; + } + i += 1; + } + -1 +} + +/// The checksum of the script file the table was loaded from. +fn cob_checksum(t: u32) -> i32 { + let un = |w: u32| if w >= t { w - t } else { w }; + let cnt = t_count(t) as u32; + let pcnt = t_pieces(t) as u32; + let names = un(r32(t + 28)); + let pnames = un(r32(t + 32)); + let mut len = 44u32; + let mut i = 0; + while i < cnt { + let e = strend(t + un(r32(t + names + 4 * i))); + if e - t > len { + len = e - t; + } + i += 1; + } + i = 0; + while i < pcnt { + let e = strend(t + un(r32(t + pnames + 4 * i))); + if e - t > len { + len = e - t; + } + i += 1; + } + let (mut a, mut b, mut c, mut d) = (0u32, 0u32, 0u32, 0u32); + let mut i = 0u32; + while i < len { + let w = i & !3; + let fix = w < 44 || (w >= names && w < names + 4 * cnt) || (w >= pnames && w < pnames + 4 * pcnt); + let byte = if fix { (un(r32(t + w)) >> (8 * (i & 3))) as u8 } else { r8(t + i) } as u32; + a = (a + byte) & 255; + b ^= byte; + c = (c + (i ^ byte)) & 255; + d ^= (i + byte) & 255; + i += 1; + } + ((d << 24) | (c << 16) | (b << 8) | a) as i32 +} + +// ---------------------------------------------------------------- model pieces + +#[inline(always)] +fn mp(state: u32, piece: i32) -> u32 { + state + M_PIECES + (piece as u32).wrapping_mul(MP_SIZE) +} +#[inline(always)] +fn mflags(m: u32) -> u16 { + r16(m + MP_FLAGS) +} +#[inline(always)] +fn mobj(m: u32) -> u32 { + r32(m) +} + +/// Sets a translation of a model piece (the setter of section 4). +fn set_translation(state: u32, m: u32, axis: u32, v: i32) { + let a = m + MP_TRANS + 4 * axis; + if ri(a) != v { + wi(a, v); + w16(m + MP_MODIFIED, 0); + wi(state + M_DIRTY, 1); + if mflags(m) & F_CACHED != 0 { + wi(state + M_CACHE_DRAW, 0); + } + } +} +fn set_rotation(state: u32, m: u32, axis: u32, v: i32) { + let a = m + MP_ROT + 2 * axis; + if rs(a) != v as i16 { + w16(a, v as u16); + w16(m + MP_MODIFIED, 0); + wi(state + M_DIRTY, 1); + if mflags(m) & F_CACHED != 0 { + wi(state + M_CACHE_DRAW, 0); + } + } +} +fn set_visible(state: u32, m: u32, on: bool) { + let f = mflags(m); + if (f & F_VISIBLE != 0) != on { + w16(m + MP_FLAGS, if on { f | F_VISIBLE } else { f & !F_VISIBLE }); + w16(m + MP_MODIFIED, 0); + if f & F_CACHED != 0 { + wi(state + M_CACHE_DRAW, 0); + } + } +} +fn set_flag(m: u32, bit: u16, on: bool) { + let f = mflags(m); + w16(m + MP_FLAGS, if on { f | bit } else { f & !bit }); +} + +/// The piece offset of a piece of a unit's model (section 4). +fn piece_offset(unit: u32, piece: i32, tc: &mut TrigCache) -> [i32; 3] { + let state = rf(unit + U_STATE); + if state == 0 || piece < 0 || piece >= ri(state + M_COUNT) { + return [0; 3]; + } + let m = mp(state, piece); + let o = mobj(m); + let mut p = [ + ri(o + O_BOX).wrapping_add(ri(m + MP_TRANS)), + ri(o + O_BOX + 4).wrapping_add(ri(m + MP_TRANS + 4)), + ri(o + O_BOX + 8).wrapping_add(ri(m + MP_TRANS + 8)), + ]; + let mut q = rf(m + MP_PARENT); + while q != 0 { + let up = rf(q + MP_PARENT); + let (mut bank, mut heading, mut pitch) = (r16(q + MP_ROT + 4), r16(q + MP_ROT + 2), r16(q + MP_ROT)); + if up == 0 { + bank = bank.wrapping_add(r16(unit + U_BANK)); + heading = heading.wrapping_add(r16(unit + U_BANK + 2)); + pitch = pitch.wrapping_add(r16(unit + U_BANK + 4)); + } + p = math::rotate3(tc, p, bank, heading, pitch); + let qo = mobj(q); + p[0] = p[0].wrapping_add(ri(qo + O_BOX).wrapping_add(ri(q + MP_TRANS))); + p[1] = p[1].wrapping_add(ri(qo + O_BOX + 4).wrapping_add(ri(q + MP_TRANS + 4))); + p[2] = p[2].wrapping_add(ri(qo + O_BOX + 8).wrapping_add(ri(q + MP_TRANS + 8))); + q = up; + } + [p[0], p[1], p[2].wrapping_neg()] +} + +fn unit_position(unit: u32, piece: i32, tc: &mut TrigCache) -> [i32; 3] { + let o = piece_offset(unit, piece, tc); + [ + ri(unit + U_POS).wrapping_add(o[0]), + ri(unit + U_POS + 4).wrapping_add(o[1]), + ri(unit + U_POS + 8).wrapping_add(o[2]), + ] +} + +/// The pose rule of section 4: restores the pieces and applies each piece's own and its +/// ancestors' angles and deltas. +fn pose_model(state: u32, tc: &mut TrigCache) { + let n = ri(state + M_COUNT); + let mut i = 0; + while i < n { + let m = mp(state, i); + if r32(m + MP_PARENT) != 0 || rs(m + MP_MODIFIED) == 0 { + let o = mobj(m); + let vc = r32(o + O_VERTEX_COUNT); + copy(rf(m + MP_POINTS), r32(o + O_VERTICES), vc.wrapping_mul(12)); + zero(m + MP_OFFSET, 12); + w16(m + MP_MODIFIED, 0); + } + i += 1; + } + let pos = state + M_POS; + i = 0; + while i < n { + let m = mp(state, i); + if rs(m + MP_MODIFIED) == 0 { + let vc = r32(mobj(m) + O_VERTEX_COUNT); + let pts = rf(m + MP_POINTS); + let mut v = m; + loop { + let up = rf(v + MP_PARENT); + let (mut bank, mut heading, mut pitch) = (r16(v + MP_ROT + 4), r16(v + MP_ROT + 2), r16(v + MP_ROT)); + if up == 0 { + bank = bank.wrapping_add(r16(pos)); + heading = heading.wrapping_add(r16(pos + 2)); + pitch = pitch.wrapping_add(r16(pos + 4)); + } + let vo = mobj(v); + let d = [ + ri(v + MP_TRANS).wrapping_add(ri(vo + O_BOX)), + ri(v + MP_TRANS + 4).wrapping_add(ri(vo + O_BOX + 4)), + ri(v + MP_TRANS + 8).wrapping_add(ri(vo + O_BOX + 8)), + ]; + let mut k = 0; + while k <= vc { + let a = if k == vc { m + MP_OFFSET } else { pts + 12 * k }; + let mut p = [ri(a), ri(a + 4), ri(a + 8)]; + p = math::rotate3(tc, p, bank, heading, pitch); + wi(a, p[0].wrapping_add(d[0])); + wi(a + 4, p[1].wrapping_add(d[1])); + wi(a + 8, p[2].wrapping_add(d[2])); + k += 1; + } + if up == 0 { + break; + } + v = up; + } + } + i += 1; + } +} + +/// `PoseUnitModel` of a model state and the unit's angles. +fn pose_unit_state(unit: u32, state: u32, tc: &mut TrigCache) { + if state == 0 { + return; + } + copy(state + M_POS, unit + U_BANK, 6); + wi(state + M_DIRTY, 1); + let root = rf(state + M_ROOT); + w16(root + MP_MODIFIED, 0); + pose_model(state, tc); + wi(state + M_DIRTY, 0); +} + +// ---------------------------------------------------------------- building a piece state + +fn node_count(mut node: u32) -> u32 { + let mut n = 0; + while node != 0 { + let c = r32(node + O_CHILD); + n += if c == 0 { 1 } else { node_count(c) + 1 }; + node = r32(node + O_SIBLING); + } + n +} + +/// Adds the nodes of a sibling chain (and their subtrees) as records; returns the first record. +fn add_pieces(state: u32, mut node: u32, parent: u32) -> u32 { + let mut first = 0; + let mut prev = 0; + while node != 0 { + let idx = ri(state + M_COUNT); + wi(state + M_COUNT, idx + 1); + let m = mp(state, idx); + let vc = r32(node + O_VERTEX_COUNT); + w32(m, node); + w16(m + MP_MODIFIED, 0); + w16(m + MP_FLAGS, if vc >= 3 { 3 | 4 } else { 2 | 4 }); + let pts = unsafe { sim_alloc_tagged(b"Point List\0".as_ptr(), vc.wrapping_mul(12)) }; + w32(m + MP_POINTS, off(pts)); + copy(pts, r32(node + O_VERTICES), vc.wrapping_mul(12)); + w32(m + MP_PARENT, off(parent)); + if prev != 0 { + w32(prev + MP_SIBLING, off(m)); + } else { + first = m; + } + let c = r32(node + O_CHILD); + if c != 0 { + let cr = add_pieces(state, c, m); + w32(m + MP_CHILD, off(cr)); + } + prev = m; + node = r32(node + O_SIBLING); + } + first +} + +fn state_size(model: u32) -> u32 { + M_PIECES + MP_SIZE * node_count(model) +} + +fn build_state(state: u32, model: u32) { + let root = add_pieces(state, model, 0); + w32(state + M_ROOT, off(root)); + wi(state + M_DIRTY, 1); +} + +fn create_object_state(model: u32) -> u32 { + let size = state_size(model); + let state = unsafe { sim_alloc_tagged(b"Object State\0".as_ptr(), size) }; + zero(state, size); + build_state(state, model); + state +} + +fn free_state(state: u32) { + let n = ri(state + M_COUNT); + let mut i = 0; + while i < n { + let p = rf(mp(state, i) + MP_POINTS); + if p != 0 { + unsafe { sim_free(p) }; + } + i += 1; + } + unsafe { sim_free(state) }; +} + +// ---------------------------------------------------------------- threads + +#[inline(always)] +fn chan(sc: u32, i: u32) -> u32 { + sc + S_CHANNELS + i * CHANNEL_SIZE +} + +/// The thread start by script index: the channel it takes, or -1. +fn thread_start(sc: u32, index: i32) -> i32 { + let t = r32(sc + S_TABLE); + if t == 0 || index < 0 || index >= t_count(t) { + return -1; + } + let mut i = 0; + while i < 8 { + let c = chan(sc, i); + if r32(c) == 0 { + w32(c, ST_RUN); + wi(c + C_PC, t_entry(t, index)); + wi(c + C_SP, -1); + w32(c + C_CALLBACK, 0); + wi(c + C_SIGNAL, 1); + wi(sc + S_ACTIVE, ri(sc + S_ACTIVE) + 1); + return i as i32; + } + i += 1; + } + -1 +} + +/// The wake rule: the channels that wait for channel `i` become runnable. +fn wake(sc: u32, i: u32) { + let mut j = 0; + while j < 8 { + let c = chan(sc, j); + if r32(c) & 0xfff0_0000 == ST_CHILD && ri(c + C_WAITING) == i as i32 { + w32(c, ST_RUN); + } + j += 1; + } +} + +fn draw(range: i32) -> i32 { + if range < 2 { + return 0; + } + let sa = globals() + G_RANDOM_SEED; + let seed = r32(sa); + let q = seed / 127773; + let corr = (q << 31).wrapping_sub(q); + let mut s = seed.wrapping_mul(16807).wrapping_sub(corr); + if (s as i32) <= 0 { + s = s.wrapping_add(2147483647); + } + w32(sa, s); + (s % range as u32) as i32 +} + +fn unit_value(unit: u32, num: i32, a: i32, b: i32, tc: &mut TrigCache) -> i32 { + match num { + 1 => (r8(unit + U_ACTIVATE) & 1) as i32, + 2 => ((r32(unit + U_FLAGS) >> 18) & 3) as i32, + 3 => ((r32(unit + U_FLAGS) >> 20) & 3) as i32, + 4 => { + let h = (rs(unit + U_HEALTH) as i32).wrapping_mul(100) as u32; + let def = rf(unit + U_DEF); + (h / r32(def + 506)) as i32 + } + 5 => (r8(unit + U_COB_FLAGS) & 1) as i32, + 6 => ((r8(unit + U_COB_FLAGS) >> 1) & 1) as i32, + 7 | 8 => { + let v = unit_position(unit, a, tc); + if num == 7 { + ((v[0] as u32 & 0xffff_0000) as i32).wrapping_add(v[2] >> 16) + } else { + v[1] + } + } + 9 | 10 | 11 => { + let u = rf(game() + G_UNITS) + (a as u32 & 0xffff) * UNIT_SIZE; + if r32(u + U_FLAGS) & ALIVE == 0 { + return 0; + } + match num { + 9 => (ri(u + U_POS + 8) >> 16).wrapping_add((ri(u + U_POS) as u32 & 0xffff_0000) as i32), + 10 => ri(u + U_POS + 4), + _ => ri(rf(u + U_DEF) + 366), + } + } + 12 | 13 => { + let mut hi = a as u32 & 0xffff_0000; + let lo = (a as u32) << 16; + if (lo as i32) < 0 { + hi = hi.wrapping_add(0x10000); + } + if num == 12 { + (math::angle_of_vector(hi as i32, lo as i32).wrapping_sub(rs(unit + U_BANK + 2) as i32)) & 0xffff + } else { + math::ftol(math::hypot(hi as i32 as f64, lo as i32 as f64)) + } + } + 14 => math::angle_of_vector(a, b) & 0xffff, + 15 => math::ftol(math::hypot(a as f64, b as f64)), + 16 => { + let mut v = [(a as u32 & 0xffff_0000) as i32, 0, ((a as u32) << 16) as i32]; + if v[2] < 0 { + v[0] = v[0].wrapping_add(0x10000); + } + unsafe { get_ground_height(v.as_mut_ptr()) }.wrapping_shl(16) + } + 17 => { + let bl = f32::from_bits(r32(unit + U_BUILD_LEFT)); + if bl == 0.0 { + 0 + } else { + 1i32.wrapping_sub(math::ftol((bl * -99.0f32) as f64)) + } + } + 18 => ((r8(unit + U_COB_FLAGS) >> 2) & 1) as i32, + 19 => ((r8(unit + U_COB_FLAGS) >> 3) & 1) as i32, + 20 => ((r8(unit + U_ACTIVATE) >> 1) & 1) as i32, + _ => 0, + } +} + +fn find_unit(id: i32) -> u32 { + rf(game() + G_UNITS) + (id as u32 & 0xffff) * UNIT_SIZE +} + +/// The effect command of a piece and an effect number. The kit's entry has no import to record +/// the five sim events, so only the visibility test and the pose remain. +fn effect_command(sc: u32, unit: u32, state: u32, tc: &mut TrigCache) { + let g = game(); + let player = g + G_PLAYERS + G_PLAYER_SIZE * r8(g + G_PLAYER_INDEX) as u32; + if unsafe { is_unit_visible(player, unit) } == 0 { + return; + } + let _ = sc; + pose_unit_state(unit, state, tc); +} + +#[inline(always)] +fn pc_rec(sc: u32, piece: i32) -> u32 { + rf(sc + S_PIECES) + (piece as u32).wrapping_mul(P_SIZE) +} + +/// Runs one channel (the thread run of section 4). +fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { + let c = chan(sc, i); + let st = r32(c); + if st & 0xff00_0000 == 0 { + return; + } + if st & 0xff00_0000 == ST_WAIT_CLASS { + match st & 0x00f0_0000 { + 0x0010_0000 | 0x0020_0000 => { + let rec = pc_rec(sc, ri(c + C_PIECE)); + let fld = if st & 0x00f0_0000 == 0x0010_0000 { P_TURN_SPEED } else { P_MOVE_SPEED }; + if ri(rec + fld + 4 * ri(c + C_AXIS) as u32) == 0 { + w32(c, ST_RUN); + } + } + 0x0040_0000 => { + let d = ri(c + C_DELAY).wrapping_sub(elapsed); + wi(c + C_DELAY, d); + if d <= 0 { + w32(c, ST_RUN); + } + } + _ => {} + } + } + if r32(c) & 0xff00_0000 != ST_RUN { + return; + } + let t = r32(sc + S_TABLE); + let code = t_code(t); + let state = rf(sc + S_STATE); + let unit = if state != 0 { rf(state + M_OWNER) } else { 0 }; + let statics = rf(sc + S_STATICS); + let stack = c + C_STACK; + let mut pc = ri(c + C_PC); + let mut sp = ri(c + C_SP); + macro_rules! flush { + () => { + wi(c + C_PC, pc); + wi(c + C_SP, sp); + }; + } + macro_rules! push { + ($v:expr) => {{ + let v: i32 = $v; + sp = sp.wrapping_add(1); + wi(stack.wrapping_add((sp as u32).wrapping_mul(4)), v); + }}; + } + macro_rules! pop { + () => {{ + let v = ri(stack.wrapping_add((sp as u32).wrapping_mul(4))); + sp = sp.wrapping_sub(1); + v + }}; + } + loop { + let opcode = ri(code + 4 * pc as u32) as u32; + let op1 = ri(code + 4 * pc as u32 + 4); + let op2 = ri(code + 4 * pc as u32 + 8); + match opcode & 0x100f_f000 { + 0x1000_1000 => { + // MOVE + let a = pop!(); + let b = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + wi(rec + P_MOVE + ax, a); + let mut sp_ = b / 30; + let m = mp(state, op1); + if a < ri(m + MP_TRANS + ax) { + sp_ = sp_.wrapping_neg(); + } + wi(rec + P_MOVE_SPEED + ax, sp_); + wi(rec, 1); + wi(sc + S_CHANGED, 1); + } + pc += 3; + } + 0x1000_2000 => { + // TURN + let a = pop!(); + let b = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + let want = a & 0xffff; + wi(rec + P_TURN + ax, want); + wi(rec + P_ACCEL + ax, 0); + let mut ts = b / 30; + let delta = want.wrapping_sub(rs(mp(state, op1) + MP_ROT + 2 * op2 as u32) as i32); + if delta == 0 { + ts = 0; + } else if (delta.wrapping_abs() > 0x8000) != (delta < 0) { + ts = ts.wrapping_neg(); + } + wi(rec + P_TURN_SPEED + ax, ts); + wi(rec, 1); + wi(sc + S_CHANGED, 1); + } + pc += 3; + } + 0x1000_3000 => { + // SPIN + let a = pop!(); + let b = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + wi(rec + P_TURN + ax, -1); + wi(rec + P_SPIN + ax, a / 30); + wi(rec + P_ACCEL + ax, b / 30); + if b / 30 == 0 { + wi(rec + P_TURN_SPEED + ax, a / 30); + } + wi(rec, 1); + wi(sc + S_CHANGED, 1); + } + pc += 3; + } + 0x1000_4000 => { + // STOP_SPIN + let a = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + wi(rec + P_SPIN + ax, 0); + let acc = (a / 30).wrapping_neg(); + wi(rec + P_ACCEL + ax, acc); + if acc == 0 { + wi(rec + P_TURN_SPEED + ax, 0); + } + } + pc += 3; + } + 0x1000_5000 | 0x1000_6000 => { + if state != 0 { + set_visible(state, mp(state, op1), opcode & 0x100f_f000 == 0x1000_5000); + } + pc += 2; + } + 0x1000_7000 | 0x1000_8000 => { + if state != 0 { + set_flag(mp(state, op1), F_CACHED, opcode & 0xf000 == 0x7000); + w32(state + M_BITMAP, 0); + } + pc += 2; + } + 0x1000_9000 => { + pop!(); + pop!(); + pc += 2; + } + 0x1000_a000 => pc += 2, + 0x1000_b000 => { + let a = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + wi(rec + P_MOVE + ax, a); + wi(rec + P_MOVE_SPEED + ax, 0); + set_translation(state, mp(state, op1), op2 as u32, a); + } + pc += 3; + } + 0x1000_c000 => { + let a = pop!(); + if state != 0 { + let rec = pc_rec(sc, op1); + let ax = 4 * op2 as u32; + wi(rec + P_TURN + ax, a & 0xffff); + wi(rec + P_ACCEL + ax, 0); + wi(rec + P_TURN_SPEED + ax, 0); + set_rotation(state, mp(state, op1), op2 as u32, a & 0xffff); + } + pc += 3; + } + 0x1000_d000 | 0x1000_e000 => { + if state != 0 { + set_flag(mp(state, op1), F_SHADED, opcode & 0xf000 == 0xd000); + w32(state + M_BITMAP, 0); + } + pc += 2; + } + 0x1000_f000 => { + let a = pop!(); + pc += 2; + let _ = a; + if unit != 0 { + effect_command(sc, unit, state, tc); + } + } + 0x1001_1000 | 0x1001_2000 => { + w32(c, if opcode & 0xf000 == 0x1000 { ST_TURN } else { ST_MOVE }); + wi(c + C_AXIS, op2); + wi(c + C_PIECE, op1); + pc += 3; + flush!(); + return; + } + 0x1001_3000 => { + let a = pop!(); + w32(c, ST_SLEEP); + wi(c + C_DELAY, a.wrapping_mul(30) / 1000); + pc += 1; + flush!(); + return; + } + 0x1002_1000 => { + let v = match opcode & 7 { + 1 => op1, + 2 => ri(stack.wrapping_add((op1 as u32).wrapping_mul(4))), + 4 => ri(statics.wrapping_add((op1 as u32).wrapping_mul(4))), + _ => 0, + }; + push!(v); + pc += 2; + } + 0x1002_2000 => { + sp = sp.wrapping_add(1); + pc += 1; + } + 0x1002_3000 => { + match opcode & 7 { + 2 => { + let a = pop!(); + wi(stack.wrapping_add((op1 as u32).wrapping_mul(4)), a); + } + 4 => { + let a = pop!(); + wi(statics.wrapping_add((op1 as u32).wrapping_mul(4)), a); + } + _ => {} + } + pc += 2; + } + 0x1002_4000 => { + sp = sp.wrapping_sub(1); + pc += 1; + } + 0x1003_1000..=0x1003_7000 => { + let a = pop!(); + let b = pop!(); + let r = match opcode & 0xf000 { + 0x1000 => b.wrapping_add(a), + 0x2000 => b.wrapping_sub(a), + 0x3000 => b.wrapping_mul(a), + 0x4000 => { + if a == 0 { + 0 + } else { + b.wrapping_div(a) + } + } + 0x5000 => b & a, + 0x6000 => b | a, + _ => b ^ a, + }; + push!(r); + pc += 1; + } + 0x1003_8000 => { + let a = pop!(); + push!(!a); + pc += 1; + } + 0x1004_1000 => { + let a = pop!(); + let b = pop!(); + push!(draw(a.wrapping_sub(b).wrapping_add(1)).wrapping_add(b)); + pc += 1; + } + 0x1004_2000 => { + let a = pop!(); + flush!(); + let v = unit_value(unit, a, 0, 0, tc); + push!(v); + pc += 1; + } + 0x1004_3000 => { + let a = pop!(); + let b = pop!(); + let d = pop!(); + let e = pop!(); + let f = pop!(); + flush!(); + let v = unit_value(unit, f, e, d, tc); + let _ = (a, b); + push!(v); + pc += 1; + } + 0x1004_4000 => { + let a = pop!(); + let mut u = rf(unit + U_CARGO); + let mut r = 0; + while u != 0 { + if r16(u + U_ID) as i32 == a { + r = 1; + break; + } + u = rf(u + U_CARGO_NEXT); + } + push!(r); + pc += 1; + } + 0x1004_5000 => { + let cr = rf(unit + U_CARRIER); + push!(if cr == 0 { 0 } else { r16(cr + U_ID) as i32 }); + pc += 1; + } + 0x1005_1000..=0x1005_8000 => { + let a = pop!(); + let b = pop!(); + let r = match opcode & 0xf000 { + 0x1000 => b < a, + 0x2000 => b <= a, + 0x3000 => b > a, + 0x4000 => b >= a, + 0x5000 => b == a, + 0x6000 => b != a, + 0x7000 => b != 0 && a != 0, + _ => b != 0 || a != 0, + }; + push!(r as i32); + pc += 1; + } + 0x1005_9000 => { + let a = pop!(); + let b = pop!(); + push!(a ^ b); + pc += 1; + } + 0x1005_a000 => { + let a = pop!(); + push!((a == 0) as i32); + pc += 1; + } + 0x1006_1000 | 0x1006_2000 => { + let ch = thread_start(sc, op1); + if ch >= 0 { + let cc = chan(sc, ch as u32); + let mut k = op2 - 1; + while k >= 0 { + let v = pop!(); + wi(cc + C_STACK + 4 * k as u32, v); + k -= 1; + } + wi(cc + C_SIGNAL, ri(c + C_SIGNAL)); + } + pc += 3; + if opcode & 0xf000 == 0x2000 { + wi(c + C_WAITING, ch); + w32(c, ST_CHILD); + flush!(); + return; + } + } + 0x1006_3000 => { + let mut k = 0; + while k < op2 { + pop!(); + k += 1; + } + pc += 3; + } + 0x1006_4000 => pc = op1, + 0x1006_5000 => { + let cb = r32(c + C_CALLBACK); + if cb != 0 { + let a = pop!(); + flush!(); + aim_done(cb, a); + } + w32(c, 0); + wi(sc + S_ACTIVE, ri(sc + S_ACTIVE) - 1); + flush!(); + wake(sc, i); + return; + } + 0x1006_6000 => { + let a = pop!(); + if a == 0 { + pc = op1; + } else { + pc += 2; + } + } + 0x1006_7000 => { + let mask = pop!(); + let mut stop = false; + let mut j = 0; + while j < 8 { + let cj = chan(sc, j); + if r32(cj) != 0 && ri(cj + C_SIGNAL) & mask != 0 { + w32(cj, 0); + wi(sc + S_ACTIVE, ri(sc + S_ACTIVE) - 1); + wake(sc, j); + if j == i { + stop = true; + } + } + j += 1; + } + pc += 1; + if stop { + flush!(); + return; + } + } + 0x1006_8000 => { + let a = pop!(); + wi(c + C_SIGNAL, a); + pc += 1; + } + 0x1007_1000 => { + let a = pop!(); + pc += 2; + flush!(); + if unit != 0 && state != 0 && op1 >= 0 && op1 < ri(state + M_COUNT) { + explode_piece(unit, op1, a as u32); + } + } + 0x1008_2000 => { + let a = pop!(); + let b = pop!(); + pc += 1; + flush!(); + if unit != 0 { + if b == 18 { + set_yard(unit, a); + } + script_value(unit, b, a); + } + } + 0x1008_3000 => { + let a = pop!(); + let b = pop!(); + let d = pop!(); + pc += 1; + flush!(); + let u = find_unit(d); + if unit != 0 && r32(u + U_FLAGS) & ALIVE != 0 { + let cr = rf(u + U_CARRIER); + if cr == 0 || cr == unit { + attach_to_piece(u, unit, b, a); + } + } + } + 0x1008_4000 => { + // DROP_UNIT: the kit's entry has no import for the map's footprint test. + pop!(); + pc += 1; + } + _ => { + w32(c, 0); + wi(sc + S_ACTIVE, ri(sc + S_ACTIVE) - 1); + flush!(); + return; + } + } + } +} + +fn run_channels(sc: u32, elapsed: i32, tc: &mut TrigCache) { + let mut i = 0; + while i < 8 { + run_channel(sc, i, elapsed, tc); + i += 1; + } +} + +/// The piece animation step of section 4. +fn animate(sc: u32, elapsed: i32) { + if elapsed == 0 || ri(sc + S_CHANGED) == 0 { + return; + } + wi(sc + S_CHANGED, 0); + let t = r32(sc + S_TABLE); + let state = rf(sc + S_STATE); + if t == 0 || state == 0 { + return; + } + let n = t_pieces(t); + let mut p = 0; + while p < n { + let rec = pc_rec(sc, p); + if ri(rec) != 0 { + wi(rec, 0); + let m = mp(state, p); + let mut j = 0u32; + while j < 3 { + let ax = 4 * j; + let ms = ri(rec + P_MOVE_SPEED + ax); + if ms != 0 { + let mut v = ri(m + MP_TRANS + ax).wrapping_add(elapsed.wrapping_mul(ms)); + let target = ri(rec + P_MOVE + ax); + if (ms > 0 && v >= target) || (ms < 0 && v <= target) { + v = target; + wi(rec + P_MOVE_SPEED + ax, 0); + } else { + wi(rec, 1); + } + set_translation(state, m, j, v); + } + let acc = ri(rec + P_ACCEL + ax); + if acc != 0 { + let ts = ri(rec + P_TURN_SPEED + ax).wrapping_add(acc); + wi(rec + P_TURN_SPEED + ax, ts); + let spin = ri(rec + P_SPIN + ax); + if (acc > 0 && ts >= spin) || (acc < 0 && ts <= spin) { + wi(rec + P_TURN_SPEED + ax, spin); + wi(rec + P_ACCEL + ax, 0); + } + } + let ts = ri(rec + P_TURN_SPEED + ax); + if ts != 0 { + let cur = rs(m + MP_ROT + 2 * j) as i32; + let step = elapsed.wrapping_mul(ts); + let mut r = cur.wrapping_add(step); + let want = ri(rec + P_TURN + ax); + if want != -1 { + let reached = if ts > 0 { + want.wrapping_sub(cur).wrapping_add(0x10000) % 0x10000 <= step + } else { + cur.wrapping_sub(want).wrapping_add(0x10000) % 0x10000 <= step.wrapping_neg() + }; + if reached { + r = want; + wi(rec + P_TURN_SPEED + ax, 0); + } else { + wi(rec, 1); + } + } else { + wi(rec, 1); + } + set_rotation(state, m, j, r & 0xffff); + } + j += 1; + } + if ri(rec) != 0 { + wi(sc + S_CHANGED, 1); + } + } + p += 1; + } +} + +fn run_scripts(sc: u32, elapsed: i32, tc: &mut TrigCache) { + if ri(sc + S_ACTIVE) != 0 { + run_channels(sc, elapsed, tc); + } + animate(sc, elapsed); +} + +/// The query run of a named script with four inputs: the four words it leaves, when it started. +fn query_run(sc: u32, name: u32, inp: [i32; 4], tc: &mut TrigCache) -> Option<[i32; 4]> { + if sc == 0 { + return None; + } + let idx = find_script_in(r32(sc + S_TABLE), name); + let ch = thread_start(sc, idx); + if ch < 0 { + return None; + } + let c = chan(sc, ch as u32); + let mut k = 0; + while k < 4 { + wi(c + C_STACK + 4 * k, inp[k as usize]); + k += 1; + } + wi(c + C_SP, 3); + run_channel(sc, ch as u32, 0, tc); + Some([ri(c + C_STACK), ri(c + C_STACK + 4), ri(c + C_STACK + 8), ri(c + C_STACK + 12)]) +} + +fn query1(unit: u32, name: &[u8], input: i32, tc: &mut TrigCache) -> i32 { + match query_run(rf(unit + U_SCRIPT), name.as_ptr() as u32, [input, 0, 0, 0], tc) { + Some(r) => r[0], + None => 0, + } +} + +fn start_with_args(sc: u32, index: i32, callback: u32, update: i32, count: i32, args: [i32; 4], tc: &mut TrigCache) -> i32 { + let ch = thread_start(sc, index); + if ch < 0 { + aim_done(callback, 0); + return 0; + } + let c = chan(sc, ch as u32); + w32(c + C_CALLBACK, callback); + let mut k = 0; + while k < 4 { + wi(c + C_STACK + 4 * k, args[k as usize]); + k += 1; + } + wi(c + C_SP, count.wrapping_sub(1)); + if update != 0 { + run_scripts(sc, 0, tc); + } + 1 +} + +// ---------------------------------------------------------------- slots + +#[no_mangle] +pub extern "C" fn Apply(event: u32, size: u32) -> i32 { + if size < 8 { + return 0; + } + let kind = ri(event); + let need = match kind { + 416 => 76, + 417..=419 => 16, + _ => return 0, + }; + if size < need { + return 0; + } + let obj = r32(event + 4); + let mut tc = TrigCache::new(); + match kind { + 416 => { + let form = ri(event + 8); + if obj == 0 || form < 0 || form > 2 { + return 0; + } + let unit = blk() + obj; + let sc = rf(unit + U_SCRIPT); + if sc == 0 { + return 0; + } + let callback = r32(event + 48); + let update = ri(event + 52); + let count = ri(event + 56); + let args = [ri(event + 60), ri(event + 64), ri(event + 68), ri(event + 72)]; + if form == 2 { + start_with_args(sc, ri(event + 12), callback, update, count, args, &mut tc); + return 1; + } + // the name: at most 31 bytes of the 32-byte field, then a 0 + let mut name = [0u8; 32]; + let mut k = 0; + while k < 31 { + let b = r8(event + 16 + k as u32); + if b == 0 { + break; + } + name[k] = b; + k += 1; + } + let idx = find_script_in(r32(sc + S_TABLE), name.as_ptr() as u32); + if form == 1 { + start_with_args(sc, idx, callback, update, count, args, &mut tc); + } else { + let ch = thread_start(sc, idx); + if ch >= 0 { + w32(chan(sc, ch as u32) + C_CALLBACK, callback); + if update != 0 { + run_scripts(sc, 0, &mut tc); + } + } + } + 1 + } + 417 => { + if obj == 0 { + return 0; + } + let unit = blk() + obj; + let state = rf(unit + U_STATE); + if state == 0 { + return 1; + } + if ri(event + 12) == 1 { + pose_unit_state(unit, state, &mut tc); + } + let m = mp(state, ri(event + 8)); + w16(m + MP_FLAGS, mflags(m) & !F_VISIBLE); + 1 + } + 418 => { + let s = r32(event + 8); + if s == 0 { + return 0; + } + free_state(blk() + s); + 1 + } + _ => { + let s = r32(event + 8); + if s == 0 { + return 0; + } + let state = blk() + s; + let model = r32(rf(game() + G_FEATURES) + FEATURE_SIZE * ri(event + 12) as u32 + F_OBJECT); + if model != 0 { + zero(state, state_size(model)); + build_state(state, model); + } + 1 + } + } +} + +#[no_mangle] +pub extern "C" fn StartScriptWithArgsByIndex(script: u32, index: i32, callback: u32, update: i32, count: i32, a: i32, b: i32, c: i32, d: i32) -> i32 { + let mut tc = TrigCache::new(); + start_with_args(script, index, off(callback), update, count, [a, b, c, d], &mut tc) +} + +#[no_mangle] +pub extern "C" fn QueryScript(script: u32, name: u32, a0: u32, a1: u32, a2: u32, a3: u32) -> i32 { + let mut tc = TrigCache::new(); + let rd = |p: u32| if p == 0 { 0 } else { ri(p) }; + match query_run(script, name, [rd(a0), rd(a1), rd(a2), rd(a3)], &mut tc) { + None => 0, + Some(r) => { + let ptrs = [a0, a1, a2, a3]; + let mut k = 0; + while k < 4 { + if ptrs[k] != 0 { + wi(ptrs[k], r[k]); + } + k += 1; + } + 1 + } + } +} + +#[no_mangle] +pub extern "C" fn FindScript(script: u32, name: u32) -> i32 { + find_script_in(r32(script + S_TABLE), name) +} + +fn put3(out: u32, v: [i32; 3]) { + wi(out, v[0]); + wi(out + 4, v[1]); + wi(out + 8, v[2]); +} + +#[no_mangle] +pub extern "C" fn GetPieceOffset(unit: u32, piece: i32, out: u32) { + let mut tc = TrigCache::new(); + put3(out, piece_offset(unit, piece, &mut tc)); +} + +#[no_mangle] +pub extern "C" fn GetPiecePosition(unit: u32, piece: i32, out: u32) { + let mut tc = TrigCache::new(); + put3(out, unit_position(unit, piece, &mut tc)); +} + +#[no_mangle] +pub extern "C" fn GetPieceAngles(unit: u32, piece: i32, out: u32) { + let state = rf(unit + U_STATE); + let (bank, heading, pitch) = (r16(unit + U_BANK), r16(unit + U_BANK + 2), r16(unit + U_BANK + 4)); + if piece >= 0 { + let m = mp(state, piece); + w16(out, bank.wrapping_add(r16(m + MP_ROT + 4))); + w16(out + 2, heading.wrapping_add(r16(m + MP_ROT + 2))); + w16(out + 4, pitch.wrapping_add(r16(m + MP_ROT))); + } else { + w16(out, bank.wrapping_add(r16(state + M_COUNT))); + w16(out + 2, heading); + w16(out + 4, pitch); + } +} + +#[no_mangle] +pub extern "C" fn GetNanoPiecePosition(unit: u32, out: u32) { + let mut tc = TrigCache::new(); + let piece = query1(unit, b"QueryNanoPiece\0", 0, &mut tc); + put3(out, unit_position(unit, piece, &mut tc)); +} + +#[no_mangle] +pub extern "C" fn GetAimFromPosition(unit: u32, out: u32, weapon: i32) { + let mut tc = TrigCache::new(); + let (aim, query): (&[u8], &[u8]) = match weapon { + 0 => (b"AimFromPrimary\0", b"QueryPrimary\0"), + 1 => (b"AimFromSecondary\0", b"QuerySecondary\0"), + _ => (b"AimFromTertiary\0", b"QueryTertiary\0"), + }; + let mut piece = query1(unit, aim, -1, &mut tc); + if piece == -1 { + piece = query1(unit, query, 0, &mut tc); + } + put3(out, unit_position(unit, piece, &mut tc)); +} + +#[no_mangle] +pub extern "C" fn GetSweetSpot(unit: u32, out: u32) { + let mut tc = TrigCache::new(); + let piece = query1(unit, b"SweetSpot\0", 0, &mut tc); + let state = rf(unit + U_STATE); + pose_unit_state(unit, state, &mut tc); + let mut mn = [0i32; 3]; + let mut mx = [0i32; 3]; + if state != 0 && piece >= 0 && piece < ri(state + M_COUNT) { + let m = mp(state, piece); + let n = r32(mobj(m) + O_VERTEX_COUNT); + let pts = rf(m + MP_POINTS); + let mut k = 0; + while k < n { + let mut j = 0; + while j < 3 { + let v = ri(pts + 12 * k + 4 * j); + if v < mn[j as usize] { + mn[j as usize] = v; + } + if v > mx[j as usize] { + mx[j as usize] = v; + } + j += 1; + } + k += 1; + } + } + put3( + out, + [ + (mx[0].wrapping_add(mn[0]) / 2).wrapping_add(ri(unit + U_POS)), + (mx[1].wrapping_add(mn[1]) / 2).wrapping_add(ri(unit + U_POS + 4)), + (mx[2].wrapping_add(mn[2]) / 2).wrapping_add(ri(unit + U_POS + 8)), + ], + ); +} + +#[no_mangle] +pub extern "C" fn PoseUnitModel(unit: u32) { + let mut tc = TrigCache::new(); + pose_unit_state(unit, rf(unit + U_STATE), &mut tc); +} + +#[no_mangle] +pub extern "C" fn CreateObjectState(model: u32) -> u32 { + create_object_state(model) +} + +#[no_mangle] +pub extern "C" fn FreeObjectState(state: u32) { + free_state(state); +} + +fn table_anchor() {} +// ABI 9.1: a module that uses no function pointer would have no table import; this one keeps it. +static ANCHOR: [fn(); 1] = [table_anchor]; + +#[no_mangle] +pub extern "C" fn UpdateObjectState(_view: u32) { + // The layout of the draw view is not in the kit (SPEC-QUESTIONS.md), so nothing is posed here. + let _ = unsafe { read_volatile(&ANCHOR[0]) }; +} + +#[no_mangle] +pub extern "C" fn ObjectStateSize(model: u32) -> u32 { + state_size(model) +} + +#[no_mangle] +pub extern "C" fn NewUnitScript(unit: u32) { + let sc = unsafe { sim_alloc(SCRIPT_SIZE) }; + w32(unit + U_SCRIPT, off(sc)); + w32(sc, 0); + wi(sc + 4, 30); + w32(sc + S_TABLE, 0); + w32(sc + S_STATICS, 0); + w32(sc + S_PIECES, 0); + wi(sc + S_ACTIVE, 0); + let mut i = 0; + while i < 8 { + w32(chan(sc, i), 0); + i += 1; + } +} + +#[no_mangle] +pub extern "C" fn SetCob(script: u32, data: u32) { + let old = r32(script + S_TABLE); + w32(script + S_TABLE, data); + if data == 0 { + return; + } + wi(script + S_CHECKSUM, cob_checksum(data)); + let old_pieces = rf(script + S_PIECES); + if old_pieces != 0 { + unsafe { sim_free(old_pieces) }; + } + let size = (t_pieces(data) as u32).wrapping_mul(P_SIZE); + let p = unsafe { sim_alloc(size) }; + zero(p, size); + w32(script + S_PIECES, off(p)); + let old_statics = rf(script + S_STATICS); + let size = (t_statics(data) as u32).wrapping_mul(4); + let s = unsafe { sim_alloc(size) }; + if old_statics != 0 { + let keep = if old != 0 { (t_statics(old) as u32).wrapping_mul(4) } else { 0 }; + copy(s, old_statics, if keep < size { keep } else { size }); + unsafe { sim_free(old_statics) }; + } + w32(script + S_STATICS, off(s)); +} + +#[no_mangle] +pub extern "C" fn CreatePlayerObjectState(model: u32, data: u32, owner: u32) -> u32 { + let state = create_object_state(model); + w32(state + M_OWNER, off(owner)); + let n = ri(state + M_COUNT); + let pcount = t_pieces(data); + let mut i = 0; + while i < pcount { + let name = t_piece_name(data, i); + let mut j = i; + while j < n { + if streq_ci(r32(mobj(mp(state, j)) + O_NAME), name) { + break; + } + j += 1; + } + if j < n && j != i { + let (a, b) = (mp(state, i), mp(state, j)); + let mut k = 0; + while k < MP_SIZE { + let (x, y) = (r8(a + k), r8(b + k)); + unsafe { + core::ptr::write((a + k) as *mut u8, y); + core::ptr::write((b + k) as *mut u8, x); + } + k += 1; + } + } + i += 1; + } + // rebuild the links from the object graph + i = 0; + while i < n { + let m = mp(state, i); + let o = mobj(m); + let links = [(MP_SIBLING, O_SIBLING), (MP_CHILD, O_CHILD), (MP_PARENT, 0)]; + let mut l = 0; + while l < 3 { + let target = if links[l].1 != 0 { r32(o + links[l].1) } else { object_parent(state, n, o) }; + w32(m + links[l].0, off(record_of(state, n, target))); + l += 1; + } + i += 1; + } + state +} + +/// The record whose object is `obj`, or 0. +fn record_of(state: u32, n: i32, obj: u32) -> u32 { + if obj == 0 { + return 0; + } + let mut i = 0; + while i < n { + let m = mp(state, i); + if mobj(m) == obj { + return m; + } + i += 1; + } + 0 +} + +/// The parent of an object of the model: the object that has it as a child or as a sibling of a child. +fn object_parent(state: u32, n: i32, obj: u32) -> u32 { + let mut i = 0; + while i < n { + let mut c = r32(mobj(mp(state, i)) + O_CHILD); + while c != 0 { + if c == obj { + return mobj(mp(state, i)); + } + c = r32(c + O_SIBLING); + } + i += 1; + } + 0 +} + +#[no_mangle] +pub extern "C" fn SetObjectState(script: u32, state: u32) { + w32(script + S_STATE, off(state)); +} + +#[no_mangle] +pub extern "C" fn RunScripts(script: u32, elapsed: i32) { + let mut tc = TrigCache::new(); + run_scripts(script, elapsed, &mut tc); +} + +#[no_mangle] +pub extern "C" fn DeleteScript(script: u32) { + let p = rf(script + S_PIECES); + if p != 0 { + unsafe { sim_free(p) }; + } + let s = rf(script + S_STATICS); + if s != 0 { + unsafe { sim_free(s) }; + } + unsafe { sim_free(script) }; +} diff --git a/scripts/src/math.rs b/scripts/src/math.rs new file mode 100644 index 0000000..aa2d5a2 --- /dev/null +++ b/scripts/src/math.rs @@ -0,0 +1,672 @@ +//! Bit-exact maths of the scripts module: rotation of a point, angle of a vector, hypot and the +//! double to int conversion, after `runtime/` of the kit (MIT licence, `runtime/LICENSE`). + +const RAD_TO_ANGLE16: u64 = 0x40c45f306dc9c78a; +const ANGLE16_TO_RAD: u64 = 0x3f1921fb54442c5a; + +const ATAN_SIXTEENTHS: [[u64; 2]; 17] = [ + [0x0000000000000000, 0x0000000000000000], + [0x3faff55bb72cfdea, 0xbc3c934d86d23f1d], + [0x3fbfd5ba9aac2f6e, 0xbc4cd37686760c17], + [0x3fc7b97b4bce5b02, 0x3c5347b0b4f881ca], + [0x3fcf5b75f92c80dd, 0x3c68ab6e3cf7afbd], + [0x3fd362773707ebcc, 0xbc6963a544b672d8], + [0x3fd6f61941e4def1, 0xbc7c63aae6f6e918], + [0x3fda64eec3cc23fd, 0xbc724dec1b50b7ff], + [0x3fddac670561bb4f, 0x3c7a2b7f222f65e2], + [0x3fe0657e94db30d0, 0xbc7d5b495f6349e6], + [0x3fe1e00babdefeb4, 0xbc5928df287a668f], + [0x3fe345f01cce37bb, 0x3c81021137c71102], + [0x3fe4978fa3269ee1, 0x3c72419a87f2a458], + [0x3fe5d58987169b18, 0x3c60028e4bc5e7ca], + [0x3fe700a7c5784634, 0xbc78c34d25aadef6], + [0x3fe819d0b7158a4d, 0xbc7bf76229d3b917], + [0x3fe921fb54442d18, 0x3c81a62633145c07], +]; + +const ATAN_SERIES: [[u64; 2]; 12] = [ + [0x3ff0000000000000, 0x0000000000000000], + [0xbfd5555555555555, 0xbc75555555555555], + [0x3fc999999999999a, 0xbc6999999999999a], + [0xbfc2492492492492, 0xbc62492492492492], + [0x3fbc71c71c71c71c, 0x3c5c71c71c71c71c], + [0xbfb745d1745d1746, 0x3c4745d1745d1746], + [0x3fb3b13b13b13b14, 0xbc53b13b13b13b14], + [0xbfb1111111111111, 0xbc31111111111111], + [0x3fae1e1e1e1e1e1e, 0x3c2e1e1e1e1e1e1e], + [0xbfaaf286bca1af28, 0xbc4af286bca1af28], + [0x3fa8618618618618, 0x3c48618618618618], + [0xbfa642c8590b2164, 0xbc3642c8590b2164], +]; + +const PI_PI_HALF: [[u64; 2]; 2] = [ + [0x400921fb54442d18, 0x3ca1a62633145c07], + [0x3ff921fb54442d18, 0x3c91a62633145c07], +]; + +/// (80-bit mantissa, biased exponent) + +#[derive(Clone, Copy)] +struct Ext { + m: u64, + e: i32, +} + +const TOP: u64 = 1 << 63; +const ZERO_EXT: Ext = Ext { m: 0, e: 0 }; + +fn ext_from_u128(v: u128, e: i32, sticky: bool) -> Ext { + if v == 0 { + return ZERO_EXT; + } + let s = v.leading_zeros() as i32; + let v = v << s; + let hi = (v >> 64) as u64; + let lo = v as u64; + let mut r = Ext { m: hi, e: e - s + 64 }; + let g = lo >> 63 != 0; + if g && (sticky || (lo << 1) != 0 || (r.m & 1) != 0) { + r.m = r.m.wrapping_add(1); + if r.m == 0 { + r.m = TOP; + r.e += 1; + } + } + r +} + +fn ext_of_double(d: u64) -> Ext { + let bits = d & 0x7fff_ffff_ffff_ffff; + let mut m = bits & 0xf_ffff_ffff_ffff; + let mut e = (bits >> 52) as i32; + if bits == 0 { + return ZERO_EXT; + } + if e == 0 { + e = 1; + } else { + m |= 1 << 52; + } + let sh = m.leading_zeros() as i32; + Ext { m: m << sh, e: e - 1075 - sh } +} + +fn double_of_ext(x: Ext) -> u64 { + if x.m == 0 { + return 0; + } + let mut lead = x.e + 63; + let drop = if lead >= -1022 { 11 } else { 11 + (-1022 - lead) }; + if drop > 64 { + return 0; + } + let (mut q, guard, below); + if drop == 64 { + q = 0u64; + guard = x.m >> 63 != 0; + below = (x.m << 1) != 0; + } else { + q = x.m >> drop; + guard = (x.m >> (drop - 1)) & 1 != 0; + below = (x.m & ((1u64 << (drop - 1)) - 1)) != 0; + } + if guard && (below || (q & 1) != 0) { + q += 1; + } + if lead >= -1022 { + if q == 1 << 53 { + q >>= 1; + lead += 1; + } + if lead > 1023 { + return 0x7ff0_0000_0000_0000; + } + (((lead + 1023) as u64) << 52) | (q & 0xf_ffff_ffff_ffff) + } else { + q + } +} + +fn ext_mul(a: Ext, b: Ext) -> Ext { + if a.m == 0 || b.m == 0 { + return ZERO_EXT; + } + ext_from_u128((a.m as u128) * (b.m as u128), a.e + b.e, false) +} + +fn ext_add(mut a: Ext, mut b: Ext) -> Ext { + if a.m == 0 { + return b; + } + if b.m == 0 { + return a; + } + if b.e > a.e { + core::mem::swap(&mut a, &mut b); + } + let d = a.e - b.e; + let mut sticky = false; + let (bh, bl): (u64, u64); + if d >= 128 { + bh = 0; + bl = 0; + sticky = true; + } else if d >= 64 { + bh = 0; + bl = if d == 64 { b.m } else { b.m >> (d - 64) }; + sticky = d > 64 && (b.m & ((1u64 << (d - 64)) - 1)) != 0; + } else if d == 0 { + bh = b.m; + bl = 0; + } else { + bh = b.m >> d; + bl = b.m << (64 - d); + } + let mut lo = bl; + let (mut hi, carry) = a.m.overflowing_add(bh); + let mut e = a.e - 64; + if carry { + sticky |= lo & 1 != 0; + lo = (lo >> 1) | (hi << 63); + hi = (hi >> 1) | TOP; + e += 1; + } + ext_from_u128(((hi as u128) << 64) | lo as u128, e, sticky) +} + +fn ext_div(a: Ext, b: Ext) -> Ext { + if a.m == 0 { + return ZERO_EXT; + } + let mut ma = a.m >> 11; + let mb = b.m >> 11; + let mut q = 0u64; + let mut xa = a.e + 11; + let xb = b.e + 11; + if ma < mb { + ma <<= 1; + xa -= 1; + } + let mut rem = ma; + for _ in 0..64 { + q <<= 1; + if rem >= mb { + rem -= mb; + q |= 1; + } + rem <<= 1; + } + let guard = rem >= mb; + if guard { + rem -= mb; + } + let sticky = rem != 0; + let mut r = Ext { m: q, e: xa - xb - 63 }; + if guard && (sticky || (q & 1) != 0) { + r.m = r.m.wrapping_add(1); + if r.m == 0 { + r.m = TOP; + r.e += 1; + } + } + r +} + +fn ext_sqrt(a: Ext) -> Ext { + if a.m == 0 { + return ZERO_EXT; + } + let odd = a.e & 1; + let shift: i32 = if odd != 0 { 65 } else { 66 }; + let mut rem: u128 = 0; + let mut root: u128 = 0; + for i in 0..65 { + let pos = 128 - 2 * i; + let mut pair = 0u64; + if pos - shift >= 0 && pos - shift < 64 { + pair = (a.m >> (pos - shift)) & 3; + } else if pos - shift == -1 { + pair = (a.m << 1) & 3; + } + rem = (rem << 2) | pair as u128; + let cand = (root << 2) | 1; + root <<= 1; + if rem >= cand { + rem -= cand; + root |= 1; + } + } + let guard = root & 1 != 0; + let sticky = rem != 0; + let mut r = Ext { m: (root >> 1) as u64, e: (a.e - shift) / 2 + 1 }; + if guard && (sticky || (r.m & 1) != 0) { + r.m = r.m.wrapping_add(1); + if r.m == 0 { + r.m = TOP; + r.e += 1; + } + } + r +} + + +pub fn bx_ftol(x: u64) -> i32 { + let lo = x as u32; + let hi = (x >> 32) as u32; + let e = ((hi >> 20) & 0x7ff) as i32; + if e < 1023 || e >= 1023 + 63 { + return 0; + } + let mhi = (hi & 0xfffff) | 0x100000; + let shift = e - 1075; + let low: u32 = if shift >= 32 { + 0 + } else if shift >= 0 { + lo << shift + } else if shift > -32 { + (lo >> -shift) | (mhi << (32 + shift)) + } else { + mhi >> (-shift - 32) + }; + (if hi >> 31 != 0 { 0u32.wrapping_sub(low) } else { low }) as i32 +} + +pub fn round_to_int(v: f64) -> i32 { + if !(v > -4e18 && v < 4e18) { + return i32::MIN; + } + let mut t = v as i64; + let f = v - t as f64; + if v >= 0.0 { + if f > 0.5 || (f == 0.5 && (t & 1) != 0) { + t += 1; + } + } else if f < -0.5 || (f == -0.5 && (t & 1) != 0) { + t -= 1; + } + if t > 2147483647 || t < -2147483648 { + return i32::MIN; + } + t as i32 +} + +/// The product of the int x and the 64-bit mantissa (hi:lo) with the sign/exponent word, rounded to 53 bits. +pub fn mul_ext(x: i32, mant_hi: u32, mant_lo: u32, sign_exp: u32) -> u64 { + if x == 0 { + return 0; + } + let ax: u32 = if x < 0 { 0u32.wrapping_sub(x as u32) } else { x as u32 }; + let neg = (x < 0) != ((sign_exp & 0x8000) != 0); + let phi = ax as u64 * mant_hi as u64; + let plo = ax as u64 * mant_lo as u64; + let carry = phi + (plo >> 32); + let low32 = plo & 0xffff_ffff; + let sh = (64 - carry.leading_zeros() as i32) - 32; + let top = (carry << (32 - sh)) | (low32 >> sh); + let sticky = low32 & ((1u64 << sh) - 1); + let mut r = top >> 11; + let rem = top & 0x7ff; + if rem > 0x400 || (rem == 0x400 && (sticky != 0 || (r & 1) != 0)) { + r += 1; + } + let mut exp = (sign_exp & 0x7fff) as i32 - 16383 + sh; + if r == 1 << 53 { + r >>= 1; + exp += 1; + } + let mut hi = (((exp + 1023) as u32) << 20) | ((r >> 32) as u32 & 0xfffff); + if neg { + hi |= 0x8000_0000; + } + ((hi as u64) << 32) | (r & 0xffff_ffff) +} + + +#[derive(Clone, Copy)] +struct Dd { + hi: f64, + lo: f64, +} + +fn fb(b: u64) -> f64 { + f64::from_bits(b) +} + +fn two_sum(a: f64, b: f64) -> (f64, f64) { + let t = a + b; + let bb = t - a; + (t, (a - (t - bb)) + (b - bb)) +} + +fn two_prod(a: f64, b: f64) -> (f64, f64) { + let p = a * b; + let mut t = 134217729.0 * a; + let ah = t - (t - a); + let al = a - ah; + t = 134217729.0 * b; + let bh = t - (t - b); + let bl = b - bh; + (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl) +} + +fn dd_make(hi: f64, lo: f64) -> Dd { + let h = hi + lo; + Dd { hi: h, lo: lo - (h - hi) } +} + +fn dd_neg(a: Dd) -> Dd { + Dd { hi: -a.hi, lo: -a.lo } +} + +fn dd_add(a: Dd, b: Dd) -> Dd { + let (s, mut e) = two_sum(a.hi, b.hi); + let (t, f) = two_sum(a.lo, b.lo); + e += t; + let mut r = dd_make(s, e); + r.lo += f; + dd_make(r.hi, r.lo) +} + +fn dd_mul(a: Dd, b: Dd) -> Dd { + let (p, mut e) = two_prod(a.hi, b.hi); + e += a.hi * b.lo + a.lo * b.hi; + dd_make(p, e) +} + +fn dd_mul_d(a: Dd, b: f64) -> Dd { + let (p, mut e) = two_prod(a.hi, b); + e += a.lo * b; + dd_make(p, e) +} + +fn dd_div(a: Dd, b: Dd) -> Dd { + let q1 = a.hi / b.hi; + let mut r = dd_add(a, dd_neg(dd_mul_d(b, q1))); + let q2 = r.hi / b.hi; + r = dd_add(r, dd_neg(dd_mul_d(b, q2))); + let q3 = r.hi / b.hi; + let q = dd_make(q1, q2); + dd_add(q, dd_make(q3, 0.0)) +} + +fn dd_of(a: f64) -> Dd { + Dd { hi: a, lo: 0.0 } +} + +fn dd_const(w: [u64; 2]) -> Dd { + Dd { hi: fb(w[0]), lo: fb(w[1]) } +} + +fn dd_product(a: f64, b: f64) -> Dd { + let (hi, lo) = two_prod(a, b); + Dd { hi, lo } +} + +fn dd_atan_ratio(n: f64, d: f64) -> Dd { + if n == 0.0 { + return dd_of(0.0); + } + let k = (n * 16.0 / d + 0.5) as i32; + let k = k.clamp(0, 16); + let num = dd_add(dd_of(16.0 * n), dd_neg(dd_product(k as f64, d))); + let den = dd_add(dd_of(16.0 * d), dd_product(k as f64, n)); + let u = dd_div(num, den); + let w = dd_mul(u, u); + let mut p = dd_const(ATAN_SERIES[11]); + for m in (0..=10).rev() { + p = dd_add(dd_mul(p, w), dd_const(ATAN_SERIES[m])); + } + let atan_u = dd_mul(u, p); + dd_add(dd_const(ATAN_SIXTEENTHS[k as usize]), atan_u) +} + +fn dd_atan2_nonneg(s: f64, x: f64) -> Dd { + let ax = if x < 0.0 { -x } else { x }; + if s == 0.0 && ax == 0.0 { + return dd_of(0.0); + } + let mut a; + if s <= ax { + a = dd_atan_ratio(s, ax); + } else { + a = dd_add(dd_const(PI_PI_HALF[1]), dd_neg(dd_atan_ratio(ax, s))); + } + if x < 0.0 { + a = dd_add(dd_const(PI_PI_HALF[0]), dd_neg(a)); + } + a +} + +fn round_shift(v: u64, shift: i32) -> u64 { + if shift <= 0 { + return v << (-shift); + } + if shift > 64 { + return 0; + } + let (mut q, rem, half); + if shift == 64 { + q = 0; + rem = v; + half = 1u64 << 63; + } else { + q = v >> shift; + rem = v & ((1u64 << shift) - 1); + half = 1u64 << (shift - 1); + } + if rem > half || (rem == half && (q & 1) != 0) { + q += 1; + } + q +} + +fn dd_to_x87_double(v: Dd) -> u64 { + let hb = v.hi.to_bits(); + let lb = v.lo.to_bits(); + if v.hi == 0.0 { + return 0; + } + let eh = ((hb >> 52) & 0x7ff) as i32; + let mh = (hb & ((1 << 52) - 1)) | (1 << 52); + let n = mh << 11; + let ex = |m: u64, e: i32| double_of_ext(Ext { m, e }); + if v.lo == 0.0 { + return ex(n, eh - 1075 - 11); + } + let neg = lb >> 63 != 0; + let el = ((lb >> 52) & 0x7ff) as i32; + let ml = (lb & ((1 << 52) - 1)) | (1 << 52); + let shift = (eh - 1075 - 11) - (el - 1075); + if neg && mh == 1 << 52 { + let r = round_shift(ml, shift + 1); + if r == 0 { + return ex(n, eh - 1075 - 11); + } + return ex(0u64.wrapping_sub(r), eh - 1075 - 12); + } + let r = round_shift(ml, shift); + ex(if neg { n.wrapping_sub(r) } else { n.wrapping_add(r) }, eh - 1075 - 11) +} + +pub fn angle_of_vector(x: i32, z: i32) -> i32 { + if x == 0 && z == 0 { + return 0; + } + let s = (x as i64).abs() as f64; + let a = dd_to_x87_double(dd_atan2_nonneg(s, z as f64)); + let v = fb(a) * fb(RAD_TO_ANGLE16); + let r = round_to_int(v); + if x < 0 { + r.wrapping_neg() + } else { + r + } +} + + +pub fn hypot_bits(xb: u64, yb: u64) -> u64 { + let inf = 0x7ff0_0000_0000_0000u64; + let is_inf = |b: u64| (b & 0x7fff_ffff_ffff_ffff) == inf; + let is_nan = |b: u64| (b & 0x7fff_ffff_ffff_ffff) > inf; + if is_inf(xb) || is_inf(yb) { + return inf; + } + if is_nan(xb) { + return xb; + } + if is_nan(yb) { + return yb; + } + let ax = xb & 0x7fff_ffff_ffff_ffff; + let ay = yb & 0x7fff_ffff_ffff_ffff; + if ax == 0 && ay == 0 { + return 0; + } + let big = if fb(ax) >= fb(ay) { ax } else { ay }; + let eb = ext_of_double(big); + let ra = double_of_ext(ext_div(ext_of_double(ax), eb)); + let rb = double_of_ext(ext_div(ext_of_double(ay), eb)); + let (ea, ebb) = (ext_of_double(ra), ext_of_double(rb)); + let sum = double_of_ext(ext_add(ext_mul(ea, ea), ext_mul(ebb, ebb))); + let root = double_of_ext(ext_sqrt(ext_of_double(sum))); + double_of_ext(ext_mul(ext_of_double(root), eb)) +} + + +// ---------------------------------------------------------------- sine and cosine of an angle at 64 bits + +/// Sine and cosine of a 16-bit angle as 64-bit mantissas with a sign/exponent word (the 80-bit +/// value of the kit's sin/cos table): (mantissa, sign/exponent) each. +#[derive(Clone, Copy)] +pub struct Trig { + pub angle: u16, + pub valid: bool, + pub sm: u64, + pub se: u32, + pub cm: u64, + pub ce: u32, +} + +pub const NO_TRIG: Trig = Trig { angle: 0, valid: false, sm: 0, se: 0, cm: 0, ce: 0 }; + +const FRAC: u32 = 120; + +#[inline(always)] +fn mulq(a: u128, b: u128) -> u128 { + let (a0, a1) = (a as u64 as u128, a >> 64); + let (b0, b1) = (b as u64 as u128, b >> 64); + let p00 = a0 * b0; + let mid = a0 * b1 + a1 * b0; + let p11 = a1 * b1; + let (lo, c) = p00.overflowing_add(mid << 64); + let hi = p11 + (mid >> 64) + c as u128; + (hi << (128 - FRAC)) | (lo >> FRAC) +} + +fn to_x87(v: u128, neg: bool) -> (u64, u32) { + if v == 0 { + return (0, 0); + } + let len = 128 - v.leading_zeros() as i32; + let mut e = len; + let mut m: u64; + if len > 64 { + let sh = (len - 64) as u32; + m = (v >> sh) as u64; + let rem = v & ((1u128 << sh) - 1); + let half = 1u128 << (sh - 1); + if rem > half || (rem == half && m & 1 != 0) { + m = m.wrapping_add(1); + if m == 0 { + m = 1 << 63; + e += 1; + } + } + } else { + m = (v << (64 - len as u32)) as u64; + } + let exp = (e - FRAC as i32 - 1 + 16383) as u32; + (m, exp | if neg { 0x8000 } else { 0 }) +} + +pub fn trig(angle: u16) -> Trig { + let t = angle as i16; + let theta = t as f64 * f64::from_bits(ANGLE16_TO_RAD); + let bits = theta.abs().to_bits(); + let e = ((bits >> 52) & 0x7ff) as i32; + let mant = (bits & 0xf_ffff_ffff_ffff) | (1 << 52); + let sh = e - 1075 + FRAC as i32; + let x: u128 = (mant as u128) << (sh as u32); + let x2 = mulq(x, x); + let one: u128 = 1 << FRAC; + let (mut sp, mut sn, mut cp, mut cn) = (x, 0u128, one, 0u128); + let (mut st, mut ct) = (x, one); + let mut n = 1u128; + loop { + ct = mulq(ct, x2) / ((2 * n - 1) * (2 * n)); + st = mulq(st, x2) / ((2 * n) * (2 * n + 1)); + if ct == 0 && st == 0 { + break; + } + if n & 1 == 1 { + cn += ct; + sn += st; + } else { + cp += ct; + sp += st; + } + n += 1; + } + let (sv, sneg) = if sp >= sn { (sp - sn, false) } else { (sn - sp, true) }; + let (cv, cneg) = if cp >= cn { (cp - cn, false) } else { (cn - cp, true) }; + let (sm, se) = to_x87(sv, sneg != (t < 0)); + let (cm, ce) = to_x87(cv, cneg); + Trig { angle, valid: true, sm, se, cm, ce } +} + +/// A direct-mapped cache of `trig`, for one call. +pub struct TrigCache { + pub e: [Trig; 16], +} + +impl TrigCache { + pub const fn new() -> TrigCache { + TrigCache { e: [NO_TRIG; 16] } + } + pub fn get(&mut self, angle: u16) -> Trig { + let k = (angle as usize ^ (angle as usize >> 4)) & 15; + if !(self.e[k].valid && self.e[k].angle == angle) { + self.e[k] = trig(angle); + } + self.e[k] + } +} + +pub fn rotate_point(c: &mut TrigCache, angle: u16, x: i32, z: i32) -> (i32, i32) { + if angle == 0 { + return (x, z); + } + let t = c.get(angle); + let m = |v: i32, mant: u64, se: u32| f64::from_bits(mul_ext(v, (mant >> 32) as u32, mant as u32, se)); + let xc = m(x, t.cm, t.ce); + let zc = m(z, t.cm, t.ce); + let xs = m(x, t.sm, t.se); + let zs = m(z, t.sm, t.se); + (round_to_int(xc - zs), round_to_int(zc + xs)) +} + +/// The three-angle rotation of a point: bank on (x, y), pitch on (y, z), heading on (x, z). +pub fn rotate3(c: &mut TrigCache, p: [i32; 3], bank: u16, heading: u16, pitch: u16) -> [i32; 3] { + let (x, y) = rotate_point(c, bank, p[0], p[1]); + let (y, z) = rotate_point(c, pitch, y, p[2]); + let (x, z) = rotate_point(c, heading, x, z); + [x, y, z] +} + +pub fn ftol(d: f64) -> i32 { + bx_ftol(d.to_bits()) +} + +pub fn hypot(x: f64, y: f64) -> f64 { + f64::from_bits(hypot_bits(x.to_bits(), y.to_bits())) +} From 944905989639e51d65c1b11d8b199fe7c981e4d3 Mon Sep 17 00:00:00 2001 From: Implementer Date: Sun, 29 Nov 2026 01:56:20 +0000 Subject: [PATCH 07/30] Docs: Add the scripts spec questions Assisted-by: Claude Code:claude-sonnet-5-5 --- SPEC-QUESTIONS.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 SPEC-QUESTIONS.md diff --git a/SPEC-QUESTIONS.md b/SPEC-QUESTIONS.md new file mode 100644 index 0000000..091ff8e --- /dev/null +++ b/SPEC-QUESTIONS.md @@ -0,0 +1,57 @@ +# Spec questions for `scripts` + +Each item says what the spec leaves open, the evidence, and what the module does meanwhile. + +## 1. The script-file checksum has no input (`SetCob`, spec 2 "Arguments outside the block", 4, 5) + +The spec says the kit gives a module no file bytes and no checksum word at `SetCob`. The module cannot +be exact from the spec alone. Evidence: the recordings' `load cob` lines carry the file bytes, and the +file's length is the end of its last piece name (all 7 files of the kit: ARMCOM 7890, CORCOM 8741, ARMAP +5592, ARMATLAS 3846, CORMEX 1924, CORWIN 2047, ARMLAB 6403), so the length can be recovered from the +table. What the module does: it takes the file to start at the table's address (the record's first word +is the file's first word, `count` at 4, `pieceCount` at 8, as in the header of the files), recovers the +length from the names, undoes the relocation of the header words and the two name arrays (a word at or +above the table address has the address taken off), and runs section 5's formula. Whether the loader +relocates in place, which words it changes, and whether the bytes after the header are untouched is not +stated. Question: does `SetCob` get the file's bytes (or its checksum, or its length) some other way? + +## 2. Pointers inside `ScriptTable` (spec 2, 3) + +The spec gives `entries`, `names`, the piece names and `code` as fields of the record but not whether each +is a linear address, a file offset, or (for `names` and the piece names) an array of such. The module +accepts either (a value at or above the table's own address is an address, a smaller one an offset from +it) and reads `names` and the piece names as arrays of one word per name, `entries` as indices. + +## 3. `UnitDrawView` (`UpdateObjectState`, spec 4 "The update rule") + +`UnitDrawView` is not in `layout.json` or any header of the kit, so "the view's model state" and "the +view's angles" have no offsets. `UpdateObjectState` is exported and does nothing. + +## 4. Sign of the rotation in TURN's delta + +TURN's delta is "`turn[axis]` minus the model piece's rotation" with the rotation a `short` +(`layout.json`); the module sign-extends it. If the original read it as unsigned, a rotation of 0x8000 or +more gives another delta and, from `|delta| > 0x8000`, another direction. + +## 5. Unit values 12 and 14 "wrapped to 16 bits" + +Signed or unsigned is not stated; the module masks to 0..65535. + +## 6. The pose's restore of other top-level pieces (spec 4, pose rule) + +"The pieces below the root's first child are restored whatever their `modified`" is read as: every +record that has a parent is restored unconditionally; a record with no parent (the root and its +siblings) only when its `modified` is 0. + +## 7. `SetCob` allocation order and re-run + +Section 4 lists `pieces` before `statics`, so the module allocates in that order (this decides the block +addresses of the two). A script that already has a `pieces` block frees it and allocates anew; one that +has `statics` allocates the new block, copies the old extent and frees the old one. The kit has no +reallocation service. + +## 8. `CreatePlayerObjectState` and `root` + +After the records are swapped into the name order, the spec rebuilds `sibling`, `child` and `parent` but +does not say what `root` becomes. The module leaves it as the first record. `Object3do` has no `parent` +field, so the parent link is the record whose object has the node in its child chain. From c3ce67620aa677d597ee8a62997d75854942938d Mon Sep 17 00:00:00 2001 From: Implementer Date: Sun, 29 Nov 2026 02:02:00 +0000 Subject: [PATCH 08/30] Add: a replayer of the scripts recordings Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/src/lib.rs | 37 ++- scripts/src/math.rs | 21 +- scripts/tools/replay.js | 529 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 583 insertions(+), 4 deletions(-) create mode 100644 scripts/tools/replay.js diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index b3a9271..d0abff6 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -355,6 +355,35 @@ fn cob_checksum(t: u32) -> i32 { } let (mut a, mut b, mut c, mut d) = (0u32, 0u32, 0u32, 0u32); let mut i = 0u32; + // one word at a time (the four bytes of a word are all relocated or none is), four words a pass + macro_rules! word { + ($w:expr) => {{ + let w = $w; + let fix = w < 44 || (w >= names && w < names + 4 * cnt) || (w >= pnames && w < pnames + 4 * pcnt); + let v = if fix { un(r32(t + w)) } else { r32(t + w) }; + macro_rules! byte { + ($k:expr) => {{ + let byte = (v >> (8 * $k)) & 255; + let n = w + $k; + a = (a + byte) & 255; + b ^= byte; + c = (c + (n ^ byte)) & 255; + d ^= (n + byte) & 255; + }}; + } + byte!(0); + byte!(1); + byte!(2); + byte!(3); + }}; + } + while i + 16 <= len { + word!(i); + word!(i + 4); + word!(i + 8); + word!(i + 12); + i += 16; + } while i < len { let w = i & !3; let fix = w < 44 || (w >= names && w < names + 4 * cnt) || (w >= pnames && w < pnames + 4 * pcnt); @@ -673,8 +702,12 @@ fn unit_value(unit: u32, num: i32, a: i32, b: i32, tc: &mut TrigCache) -> i32 { 3 => ((r32(unit + U_FLAGS) >> 20) & 3) as i32, 4 => { let h = (rs(unit + U_HEALTH) as i32).wrapping_mul(100) as u32; - let def = rf(unit + U_DEF); - (h / r32(def + 506)) as i32 + let mh = r32(rf(unit + U_DEF) + 506); + if mh == 0 { + 0 + } else { + (h / mh) as i32 + } } 5 => (r8(unit + U_COB_FLAGS) & 1) as i32, 6 => ((r8(unit + U_COB_FLAGS) >> 1) & 1) as i32, diff --git a/scripts/src/math.rs b/scripts/src/math.rs index aa2d5a2..cafadbe 100644 --- a/scripts/src/math.rs +++ b/scripts/src/math.rs @@ -271,11 +271,28 @@ pub fn bx_ftol(x: u64) -> i32 { (if hi >> 31 != 0 { 0u32.wrapping_sub(low) } else { low }) as i32 } +/// `v` truncated toward zero, for a finite `v` of magnitude below 2^63 (no saturating conversion). +fn trunc64(v: f64) -> i64 { + let b = v.to_bits(); + let e = ((b >> 52) & 0x7ff) as i32; + if e < 1023 { + return 0; + } + let m = (b & 0xf_ffff_ffff_ffff) | (1 << 52); + let sh = e - 1075; + let a = if sh >= 0 { m << (sh as u32) } else { m >> ((-sh) as u32) } as i64; + if (b >> 63) != 0 { + a.wrapping_neg() + } else { + a + } +} + pub fn round_to_int(v: f64) -> i32 { if !(v > -4e18 && v < 4e18) { return i32::MIN; } - let mut t = v as i64; + let mut t = trunc64(v); let f = v - t as f64; if v >= 0.0 { if f > 0.5 || (f == 0.5 && (t & 1) != 0) { @@ -406,7 +423,7 @@ fn dd_atan_ratio(n: f64, d: f64) -> Dd { if n == 0.0 { return dd_of(0.0); } - let k = (n * 16.0 / d + 0.5) as i32; + let k = trunc64(n * 16.0 / d + 0.5) as i32; let k = k.clamp(0, 16); let num = dd_add(dd_of(16.0 * n), dd_neg(dd_product(k as f64, d))); let den = dd_add(dd_of(16.0 * d), dd_product(k as f64, n)); diff --git a/scripts/tools/replay.js b/scripts/tools/replay.js new file mode 100644 index 0000000..784fcd4 --- /dev/null +++ b/scripts/tools/replay.js @@ -0,0 +1,529 @@ +// A small replayer of the kit's scripts recordings (tests/replay/scripts/*.txt) against a module. +// +// node replay.js module.wasm recording.txt [--cob=ptr|off] [-v] +// +// It keeps the named objects of a recording in the shared memory across calls, sets the fields the +// `r` lines give, calls the slot with the `a` lines, and compares the imports (`i`), the writes (`w`) +// and the results (`o`). It is a check of this module's logic, not the gate: the layout of the +// loaded files is the replayer's own choice (--cob picks the relocation of the script tables). +'use strict'; +const fs = require('fs'); + +const [, , wasmPath, recPath, ...flags] = process.argv; +const COB = (flags.find((f) => f.startsWith('--cob=')) || '--cob=ptr').slice(6); +const VERBOSE = flags.includes('-v'); + +const BLOCK = 0x100000; +const PAGES = 4112; +const mem = new WebAssembly.Memory({ initial: PAGES, maximum: PAGES }); +const table = new WebAssembly.Table({ element: 'anyfunc', initial: 528, maximum: 528 }); +const u8 = () => new Uint8Array(mem.buffer); +const dv = () => new DataView(mem.buffer); +const rd32 = (a) => dv().getInt32(a, true); +const rdu32 = (a) => dv().getUint32(a, true); +const wr32 = (a, v) => dv().setUint32(a, v >>> 0, true); + +// ---------------------------------------------------------------- allocation +let arena = BLOCK + 0x800000; +function alloc(n) { + const a = arena; + arena += (n + 15) & ~7; + arena = (arena + 7) & ~7; + return a; +} +const names = new Map(); // "Kind#N" -> {addr, size} +const unnamed = []; // allocations of the current call: {addr, size} +let gameAddr = BLOCK + 0x1000; +let simGlobals = gameAddr + 234062 + 64; +const unitPool = simGlobals + 49244 + 64; +const UNITS = 600; +const SIZES = { CobScript: 1348, ModelState: 34 + 54 * 80, UnitDef: 585 }; + +function obj(name) { + const m = /^(\w+)#(\d+)$/.exec(name); + if (!m) throw new Error('bad object ' + name); + if (names.has(name)) return names.get(name).addr; + let a; + if (m[1] === 'Unit') a = unitPool + 280 * +m[2]; + else a = alloc(SIZES[m[1]] || 256); + names.set(name, { addr: a, size: SIZES[m[1]] || 280 }); + return a; +} +const ref = (a) => (a ? a - BLOCK : 0); +const deref = (o) => (o ? o + BLOCK : 0); + +// ---------------------------------------------------------------- loads +const loads = { cob: new Map(), model: new Map() }; +function relocModel(base, off, mirrored) { + // the node at file offset `off`, relocated in place; returns after its siblings and children + for (let o = off, first = true; first || o; first = false) { + const a = base + o; + if (mirrored.has(o)) return; + mirrored.add(o); + const vc = rdu32(a + 4); + const name = rdu32(a + 28), vert = rdu32(a + 36), faces = rdu32(a + 40), sib = rdu32(a + 44), child = rdu32(a + 48); + // mirror: x and z of the box and of the vertices + wr32(a + 16, -rd32(a + 16)); + wr32(a + 24, -rd32(a + 24)); + for (let k = 0; k < vc; k++) { + const v = base + vert + 12 * k; + wr32(v, -rd32(v)); + wr32(v + 8, -rd32(v + 8)); + } + wr32(a + 28, name ? base + name : 0); + wr32(a + 36, vert ? base + vert : 0); + wr32(a + 40, faces ? base + faces : 0); + wr32(a + 44, sib ? base + sib : 0); + wr32(a + 48, child ? base + child : 0); + if (child) relocModel(base, child, mirrored); + o = sib; + if (!o) break; + } +} +function installLoad(kind, holder, bytes) { + const base = alloc(bytes.length + 64); + u8().set(bytes, base); + if (kind === 'cob') { + if (COB === 'ptr') { + const cnt = rd32(base + 4), pc = rd32(base + 8); + const names_ = rdu32(base + 28), pnames = rdu32(base + 32); + for (let i = 0; i < cnt; i++) wr32(base + names_ + 4 * i, base + rdu32(base + names_ + 4 * i)); + for (let i = 0; i < pc; i++) wr32(base + pnames + 4 * i, base + rdu32(base + pnames + 4 * i)); + for (const o of [24, 28, 32, 36]) wr32(base + o, base + rdu32(base + o)); + } + } else { + relocModel(base, 0, new Set()); + } + loads[kind].set(holder, { base, size: bytes.length }); +} + +// ---------------------------------------------------------------- recording +const text = fs.readFileSync(recPath, 'utf8').split('\n'); +let li = 0; +const calls = []; +{ + let cur = null; + let pendingLoad = null; + for (const line of text) { + if (line.startsWith('load ')) { + const m = /^load (\w+) (\S+) "(.*)" \[(\d+)\]$/.exec(line); + pendingLoad = { kind: m[1], holder: m[2], bytes: Buffer.alloc(+m[4]) }; + loads[m[1]].set(m[2] + '#pending', pendingLoad); + cur = null; + continue; + } + if (line.startsWith(' x ') && pendingLoad) { + const [off, hex] = line.slice(4).split(':'); + Buffer.from(hex, 'hex').copy(pendingLoad.bytes, +off); + continue; + } + if (line.startsWith('call ')) { + const m = /^call (\S+) (\w+)$/.exec(line); + cur = { tick: m[1], slot: m[2], lines: [] }; + calls.push(cur); + pendingLoad = null; + continue; + } + if (cur && line.startsWith(' ')) cur.lines.push(line.slice(2)); + } + for (const k of ['cob', 'model']) { + for (const [key, v] of [...loads[k]]) { + if (key.endsWith('#pending')) { + loads[k].delete(key); + installLoad(k, key.slice(0, -8), v.bytes); + } + } + } +} + +// ---------------------------------------------------------------- fields +const UNIT = { + activateFlags: [270, 'u8'], cell: [118, 'pt'], footprint: [126, 'pt'], id: [168, 'u16'], cobStateFlags: [271, 'i8'], + cargo: [138, 'ref'], cargoNext: [142, 'ref'], carrier: [134, 'ref'], bank: [100, 'i16'], heading: [102, 'i16'], + pitch: [104, 'i16'], flags: [272, 'u32'], health: [264, 'i16'], buildLeft: [260, 'f32'], def: [146, 'ref'], + posX: [106, 'i32'], posY: [110, 'i32'], posZ: [114, 'i32'], script: [154, 'ref'], state: [158, 'ref'], +}; +const UNITDEF = { modelMaxY: [366, 'i32'], maxHealth: [506, 'u32'] }; +const COBS = { + scale: [4, 'i32'], table: [8, 'cob'], checksum: [12, 'i32'], statics: [16, 'buf'], pieces: [20, 'buf'], + changed: [24, 'i32'], activeCount: [1340, 'i32'], state: [1344, 'ref'], +}; +const CHAN = { + state: [0, 'u32'], pc: [4, 'i32'], sp: [8, 'i32'], delay: [12, 'i32'], piece: [16, 'i32'], axis: [20, 'i32'], + waiting: [24, 'i32'], signal: [28, 'i32'], callback: [32, 'ref'], stack: [36, 'inl128'], +}; +const MSTATE = { + count: [0, 'i32'], cacheDrawCount: [4, 'i32'], animDirty: [8, 'i32'], owner: [12, 'ref'], root: [30, 'ref'], + posX: [24, 'i16'], posY: [26, 'i16'], posZ: [28, 'i16'], +}; +const MPIECE = { + object: [0, 'model'], rot_x: [4, 'i32'], rot_y: [8, 'i32'], rot_z: [12, 'i32'], short_10: [16, 'i16'], + short_12: [18, 'i16'], short_14: [20, 'i16'], offsetX: [22, 'i32'], offsetY: [26, 'i32'], offsetZ: [30, 'i32'], + points: [34, 'buf'], modified: [38, 'i16'], flags: [40, 'u16'], sibling: [42, 'ref'], child: [46, 'ref'], parent: [50, 'ref'], +}; + +function resolve(path) { + // returns {addr, type} + let m; + if ((m = /^rng\.seed$/.exec(path))) return { addr: globalsAddr() + 48172, type: 'u32' }; + if ((m = /^rng\./.exec(path))) return { addr: globalsAddr() + 40000, type: 'u32' }; + if (path === 'Game.seaLevel') return { addr: gameAddr + 82559, type: 'u8' }; + if (path === 'Game.playerIndex') return { addr: gameAddr + 10819, type: 'u8' }; + if ((m = /^(Unit|UnitDef|CobScript|ModelState)#(\d+)\.(.+)$/.exec(path))) { + const base = obj(m[1] + '#' + m[2]); + let rest = m[3]; + if (m[1] === 'Unit') return conv(base, UNIT, rest, path); + if (m[1] === 'UnitDef') return conv(base, UNITDEF, rest, path); + if (m[1] === 'CobScript') { + const c = /^channels\[(\d)\]\.(\w+)$/.exec(rest); + if (c) return conv(base + 28 + 164 * +c[1], CHAN, c[2], path); + return conv(base, COBS, rest, path); + } + const p = /^pieces\[(\d+)\]\.(\w+)$/.exec(rest); + if (p) return conv(base + 34 + 54 * +p[1], MPIECE, p[2], path); + return conv(base, MSTATE, rest, path); + } + throw new Error('unknown field ' + path); +} +let globalsAddrV = 0; +function globalsAddr() { + return simGlobals; +} +function conv(base, table, name, path) { + const e = table[name]; + if (!e) throw new Error('unknown field ' + path); + return { addr: base + e[0], type: e[1] }; +} + +function fmt(x) { + return String(x); +} +function parseRefName(v) { + // a reference: Kind#N or ModelState#N.pieces[K] + const m = /^(\w+)#(\d+)(?:\.pieces\[(\d+)\])?$/.exec(v); + if (!m) throw new Error('bad ref ' + v); + let a = obj(m[1] + '#' + m[2]); + if (m[3] !== undefined) a += 34 + 54 * +m[3]; + return a; +} +function nameOfAddr(a) { + for (const [n, o] of names) if (o.addr === a) return n; + for (const [n, o] of names) if (n.startsWith('ModelState#') && a > o.addr && a < o.addr + o.size && (a - o.addr - 34) % 54 === 0) return n + '.pieces[' + (a - o.addr - 34) / 54 + ']'; + return null; +} +function loadAddr(kind, token) { + const m = /^(\w+#\d+)(?:\+(\d+))?$/.exec(token); + const l = loads[kind].get(m[1]); + if (!l) throw new Error('no ' + kind + ' load ' + token); + return l.base + (m[2] ? +m[2] : 0); +} +function nameOfLoad(kind, a) { + for (const [h, l] of loads[kind]) if (a >= l.base && a < l.base + l.size) return h + (a === l.base ? '' : '+' + (a - l.base)); + return '?'; +} + +function setField(path, val) { + const { addr, type } = resolve(path); + const d = dv(); + if (type === 'buf' && val === 'null') { wr32(addr, 0); return; } + if (type === 'buf' || type === 'inl128') { + const m = /^(?:\[(\d+)\] )?(\d+):([0-9a-f]*)(?: (.*))?$/.exec(val); + let target = addr; + if (type === 'buf') { + let r = rdu32(addr); + if (!r) { + const len = m && m[1] ? +m[1] : 4096; + r = ref(alloc(len)); + wr32(addr, r); + } + target = deref(r); + } + // the value is one or more "off:hex" chunks + for (const chunk of val.replace(/^\[\d+\] /, '').split(' ')) { + const [o, h] = chunk.split(':'); + Buffer.from(h, 'hex').copy(Buffer.from(mem.buffer, target + +o * (type === 'inl128' ? 4 : 1), h.length / 2)); + } + return; + } + switch (type) { + case 'u8': d.setUint8(addr, +val); break; + case 'i8': d.setInt8(addr, +val); break; + case 'i16': d.setInt16(addr, +val, true); break; + case 'u16': d.setUint16(addr, +val, true); break; + case 'i32': d.setInt32(addr, +val, true); break; + case 'u32': d.setUint32(addr, Number(val) >>> 0, true); break; + case 'f32': d.setUint32(addr, parseInt(val.slice(4), 16) >>> 0, true); break; + case 'pt': { const m = /^\((-?\d+),(-?\d+)\)$/.exec(val); d.setInt16(addr, +m[1], true); d.setInt16(addr + 2, +m[2], true); break; } + case 'ref': wr32(addr, val === 'null' ? 0 : ref(parseRefName(val))); break; + case 'cob': wr32(addr, val === 'null' ? 0 : loadAddr('cob', val)); break; + case 'model': wr32(addr, val === 'null' ? 0 : loadAddr('model', val)); break; + default: throw new Error('type ' + type); + } +} + +function getField(path, valHint) { + const { addr, type } = resolve(path); + const d = dv(); + switch (type) { + case 'u8': return String(d.getUint8(addr)); + case 'i8': return String(d.getInt8(addr)); + case 'i16': return String(d.getInt16(addr, true)); + case 'u16': return String(d.getUint16(addr, true)); + case 'i32': return String(d.getInt32(addr, true)); + case 'u32': return /^0x/.test(valHint) ? '0x' + d.getUint32(addr, true).toString(16).padStart(8, '0') : String(d.getUint32(addr, true)); + case 'f32': return 'f32:0x' + d.getUint32(addr, true).toString(16).padStart(8, '0'); + case 'pt': return '(' + d.getInt16(addr, true) + ',' + d.getInt16(addr + 2, true) + ')'; + case 'ref': { + const o = d.getUint32(addr, true); + if (!o) return 'null'; + const a = deref(o); + const n = nameOfAddr(a); + if (n) return n; + // bind to an allocation of this call + return 'unbound@' + a; + } + case 'cob': { const a = d.getUint32(addr, true); return a ? nameOfLoad('cob', a) : 'null'; } + case 'model': { const a = d.getUint32(addr, true); return a ? nameOfLoad('model', a) : 'null'; } + default: throw new Error('type ' + type); + } +} + +function bindRef(path, expected) { + // when a ref field points to an unnamed allocation and the expected value names an unbound object, bind it + const { addr, type } = resolve(path); + if (type !== 'ref' || expected === 'null') return; + const o = rdu32(addr); + if (!o) return; + const a = deref(o); + const m = /^(\w+)#(\d+)$/.exec(expected); + if (m && !names.has(expected) && !nameOfAddr(a)) names.set(expected, { addr: a, size: SIZES[m[1]] || 280 }); +} + +function checkField(path, expected, errs) { + const { addr, type } = resolve(path); + if (type === 'buf' || type === 'inl128') { + let target = addr; + if (type === 'buf') { + const r = rdu32(addr); + if (expected === 'null') { if (r) errs.push(`${path}: want null got a buffer`); return; } + if (!r) { errs.push(`${path}: null buffer`); return; } + target = deref(r); + } + for (const chunk of expected.replace(/^\[\d+\] /, '').split(' ')) { + const [o, h] = chunk.split(':'); + const got = Buffer.from(mem.buffer, target + +o * (type === 'inl128' ? 4 : 1), h.length / 2).toString('hex'); + if (got !== h) errs.push(`${path} ${o}: want ${h.slice(0, 80)} got ${got.slice(0, 80)}`); + } + return; + } + bindRef(path, expected); + const got = getField(path, expected); + if (got !== expected) errs.push(`${path}: want ${expected} got ${got}`); +} + +// ---------------------------------------------------------------- instance +const wasm = fs.readFileSync(wasmPath); +const imports = { + env: { memory: mem, __indirect_function_table: table }, + services: { + SimAlloc: (n) => { const a = alloc(n); callLog.push(['SimAlloc', n]); unnamed.push({ addr: a, size: n }); return a; }, + SimAllocTagged: (tag, n) => { + let s = ''; + for (let p = tag; u8()[p]; p++) s += String.fromCharCode(u8()[p]); + const a = alloc(n); + callLog.push(['SimAllocTagged', s, n]); + unnamed.push({ addr: a, size: n }); + return a; + }, + SimFree: (p) => { callLog.push(['SimFree', p]); }, + Emit: (p, n) => { + const words = []; + for (let i = 0; i < n / 4; i++) words.push(rd32(p + 4 * i)); + callLog.push(['Emit', n, words]); + }, + }, + map: { GetGroundHeight: (p) => 0 }, + los_radar: { IsUnitVisibleToPlayer: (a, b) => 1 }, +}; +let callLog = []; +const inst = new WebAssembly.Instance(new WebAssembly.Module(wasm), imports).exports; +const gl = (n) => inst[n].value; +function setWords() { + wr32(gl('g_game'), gameAddr); + wr32(gl('g_simGlobals'), simGlobals); + wr32(gl('g_blockBase'), BLOCK); + // Game: units, poolCount, players are all within the Game record + wr32(gameAddr + 82775, ref(unitPool)); + dv().setUint16(gameAddr + 82769, UNITS, true); +} +inst.__fuel_set(2n ** 62n); + +// ---------------------------------------------------------------- replay +let bad = 0; +let total = 0; +const scratch = BLOCK + 0x600000; +function strAt(a, s) { + const b = Buffer.from(s + '\0'); + b.copy(Buffer.from(mem.buffer, a, b.length)); +} +function parseStr(v) { + return JSON.parse(v.replace(/\\\\/g, '\\\\')); +} +let fuelMax = 0n; +function runCall(c, idx) { + setWords(); + const f0 = inst.__fuel_get(); + callLog = []; + unnamed.length = 0; + const A = {}; + const R = []; + const W = []; + const O = []; + const I = []; + for (const l of c.lines) { + const k = l[0]; + const rest = l.slice(2); + if (k === 'r') R.push(rest); + else if (k === 'a') A[rest.slice(0, rest.indexOf(' '))] = rest.slice(rest.indexOf(' ') + 1); + else if (k === 'w') W.push(rest); + else if (k === 'i') I.push(rest); + else if (k === 'o') O.push(rest); + } + for (const r of R) { + const sp = r.indexOf(' '); + setField(r.slice(0, sp), r.slice(sp + 1)); + } + const errs = []; + const ptrArg = (v) => (v === 'null' ? 0 : obj(v)); + let result; + const outs = {}; + switch (c.slot) { + case 'RunScripts': result = inst.RunScripts(ptrArg(A.script), +A.elapsed); break; + case 'NewUnitScript': result = inst.NewUnitScript(ptrArg(A.unit)); break; + case 'SetCob': result = inst.SetCob(ptrArg(A.script), loadAddr('cob', A.data)); break; + case 'SetObjectState': result = inst.SetObjectState(ptrArg(A.script), ptrArg(A.state)); break; + case 'CreatePlayerObjectState': { + const r = inst.CreatePlayerObjectState(loadAddr('model', A.model), loadAddr('cob', A.data), ptrArg(A.owner)); + result = r; + break; + } + case 'FindScript': { strAt(scratch, parseStr(A.name)); result = inst.FindScript(ptrArg(A.script), scratch); break; } + case 'QueryScript': { + strAt(scratch, parseStr(A.name)); + const ps = []; + for (let i = 0; i < 4; i++) { + const v = A['arg' + i]; + if (v === 'null') ps.push(0); + else { const p = scratch + 64 + 16 * i; wr32(p, +/\((-?\d+)\)/.exec(v)[1]); ps.push(p); } + } + result = inst.QueryScript(ptrArg(A.script), scratch, ...ps); + for (let i = 0; i < 4; i++) if (ps[i]) outs['arg' + i] = '(' + rd32(ps[i]) + ')'; + break; + } + case 'GetPieceOffset': case 'GetPiecePosition': case 'GetPieceAngles': { + const out = scratch + 256; + wr32(out, 0x7777); wr32(out + 4, 0x7777); wr32(out + 8, 0x7777); + inst[c.slot](ptrArg(A.unit), +A.piece, out); + const d = dv(); + outs.result = c.slot === 'GetPieceAngles' + ? `(${d.getInt16(out, true)},${d.getUint16(out + 2, true)},${d.getInt16(out + 4, true)})` + : `(${rd32(out)},${rd32(out + 4)},${rd32(out + 8)})`; + break; + } + case 'FreeObjectState': result = inst.FreeObjectState(ptrArg(A.state)); break; + case 'Apply': { + const ev = scratch + 512; + zero(ev, 80); + wr32(ev, +A['event.kind']); + wr32(ev + 4, A['event.unit'] === 'null' ? 0 : ref(ptrArg(A['event.unit']))); + if ('event.form' in A) { + wr32(ev + 8, +A['event.form']); + wr32(ev + 12, +A['event.index']); + const nm = parseStr(A['event.name']); + Buffer.from(nm).copy(Buffer.from(mem.buffer, ev + 16, 32)); + wr32(ev + 48, A['event.callback'] === 'null' ? 0 : 1); + wr32(ev + 52, +A['event.update']); + wr32(ev + 56, +A['event.count']); + for (let i = 0; i < 4; i++) wr32(ev + 60 + 4 * i, +A['event.args' + i]); + } + result = inst.Apply(ev, +A.size); + break; + } + default: throw new Error('slot ' + c.slot); + } + // results + for (const o of O) { + const sp = o.indexOf(' '); + const name = o.slice(0, sp), val = o.slice(sp + 1); + if (name === 'result') { + let got; + if (outs.result !== undefined) got = outs.result; + else if (typeof result === 'number') { + if (/^[A-Z]\w+#\d+$/.test(val)) { + if (!names.has(val)) names.set(val, { addr: result, size: SIZES[val.split('#')[0]] || 280 }); + got = nameOfAddr(result); + } else got = String(result); + } + if (got !== val) errs.push(`result: want ${val} got ${got}`); + } else if (name in outs) { + if (outs[name] !== val) errs.push(`${name}: want ${val} got ${outs[name]}`); + } + } + // imports + const expectedImports = I.map((s) => s.split(' ')[0]); + const gotImports = callLog.filter((x) => x[0] !== 'Emit'); + const publishes = callLog.filter((x) => x[0] === 'Emit'); + const wantPub = I.filter((s) => s.startsWith('services.SchedPublish')); + const wantAlloc = I.filter((s) => !s.startsWith('services.SchedPublish')); + if (wantAlloc.length !== gotImports.length) errs.push(`imports: want ${wantAlloc.length} got ${gotImports.length} ${JSON.stringify(gotImports)}`); + else { + wantAlloc.forEach((s, k) => { + const g = gotImports[k]; + const m = /^services\.(\w+)(?: "(.*)")? ?(\d+)?/.exec(s); + if (m[1] !== g[0]) errs.push(`import ${k}: want ${m[1]} got ${g[0]}`); + else if (m[1] === 'SimAlloc' && +m[3] !== g[1]) errs.push(`SimAlloc size ${m[3]} vs ${g[1]}`); + else if (m[1] === 'SimAllocTagged' && (m[2] !== g[1] || +m[3] !== g[2])) errs.push(`SimAllocTagged ${s} vs ${g}`); + // name the results + const mm = / = (\S+)$/.exec(s); + + }); + } + // name allocation results by order + { + let ui = 0; + for (const s of wantAlloc) { + if (/^services\.SimAlloc/.test(s)) { + const mm = / = (\S+)$/.exec(s); + const u = unnamed[ui++]; + if (mm && u && /^[A-Z]\w+#\d+$/.test(mm[1]) && !names.has(mm[1])) names.set(mm[1], { addr: u.addr, size: u.size }); + } + } + } + if (wantPub.length !== publishes.length) errs.push(`publishes: want ${wantPub.length} got ${publishes.length} ${JSON.stringify(publishes)}`); + else wantPub.forEach((s, k) => { const sz = +s.split(' ')[2]; if (sz !== publishes[k][1]) errs.push(`publish size ${sz} vs ${publishes[k][1]}`); else if (VERBOSE) console.log(' publish', JSON.stringify(publishes[k])); }); + // writes + for (const w of W) { + const sp = w.indexOf(' '); + const path = w.slice(0, sp), val = w.slice(sp + 1); + checkField(path, val, errs); + } + // keep in step with the recording: set the recorded values + for (const w of W) { + const sp = w.indexOf(' '); + try { setField(w.slice(0, sp), w.slice(sp + 1)); } catch (e) { /* ignore */ } + } + { const used = f0 - inst.__fuel_get(); if (used > fuelMax) fuelMax = used; } + total++; + if (errs.length) { + bad++; + console.log(`call ${idx} ${c.tick} ${c.slot}: ${errs.length} differences`); + for (const e of errs.slice(0, 12)) console.log(' ' + e); + } else if (VERBOSE) console.log(`call ${idx} ${c.tick} ${c.slot}: ok`); +} +function zero(a, n) { u8().fill(0, a, a + n); } + +calls.forEach((c, i) => { + try { runCall(c, i); } catch (e) { bad++; total++; console.log(`call ${i} ${c.tick} ${c.slot}: ERROR ${e.stack.split('\n').slice(0, 3).join(' | ')}`); } +}); +console.log(`${recPath.split('/').pop()}: ${total - bad}/${total} calls equal, most fuel of a call ${fuelMax}`); +process.exit(bad ? 1 : 0); From 26011f9e414c97e35138cef6bb0a2d5e954c5252 Mon Sep 17 00:00:00 2001 From: Implementer Date: Sun, 29 Nov 2026 02:03:43 +0000 Subject: [PATCH 09/30] Docs: Record the gate refusal in the spec questions Assisted-by: Claude Code:claude-sonnet-5-5 --- SPEC-QUESTIONS.md | 30 ++++++++++++++++++++++++++++++ scripts/tools/replay.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/SPEC-QUESTIONS.md b/SPEC-QUESTIONS.md index 091ff8e..af68c80 100644 --- a/SPEC-QUESTIONS.md +++ b/SPEC-QUESTIONS.md @@ -2,6 +2,22 @@ Each item says what the spec leaves open, the evidence, and what the module does meanwhile. +## 0. The gate cannot judge this module: the manifest it holds has no budgets + +Every submission (req1, req2, req3) came back at once, in 0 seconds, as +`{"verdict": "refused", "message": "scripts: the manifest has no size_budget"}`, before any scenario or +recording was played. The kit's `wasm/modules.json` gives `fuel_budget` and `size_budget` to +`wind_meteors` alone (250 and 13100); the entry of `scripts` has neither (spec section 2: "the build +picks them"), and so has no other subsystem's. The mailbox takes `module.wasm` and `subsystem` and +nothing else is documented, so the budgets cannot be given to the gate. req2 and req3 added the same +two numbers as files (`fuel_budget`, `size_budget`, `budgets.json`, `manifest.json`, `entry.json`, +`modules.json`, `wasm/modules.json`, `gate.toml`) and the verdict did not change. +Question: how does a build give the gate its `fuel_budget` and `size_budget`, or does the gate's +manifest get them? Until that is answered no verdict on this module's behaviour exists; the module +meets the surface (`wasm_fuel.py --check`, 29255 bytes, imports and exports as the entry lists) and +equals every call of the four recordings but the two `SetCob` import lists the spec names as a kit +gap (see IMPLEMENTATION-NOTES.md). + ## 1. The script-file checksum has no input (`SetCob`, spec 2 "Arguments outside the block", 4, 5) The spec says the kit gives a module no file bytes and no checksum word at `SetCob`. The module cannot @@ -55,3 +71,17 @@ reallocation service. After the records are swapped into the name order, the spec rebuilds `sibling`, `child` and `parent` but does not say what `root` becomes. The module leaves it as the first record. `Object3do` has no `parent` field, so the parent link is the record whose object has the node in its child chain. + +## 9. The effect command's pose (spec 4, "The effect command") + +The kit's replay notes say `UpdateObjectState` is "called by the renderer and by a script's +sound-and-smoke effect"; the spec's effect command says "the model is posed (section 4)". The module +poses as `PoseUnitModel` does (the unit's angles into `pos`, always posed). If the original goes +through the update rule (pose only when the angles are 8 or more away from `pos` or `animDirty` is +set, and `cacheDrawCount` cleared for a coloured root), the model state differs after an effect that +is visible to the player and whose unit turned by less than 8. + +## 10. Names of the unit-value arguments of GET_UNIT_VALUE_4 + +The spec's opcode row takes "*a*, *b*, *d*, *e*, *f*" (no *c*). The module pops five words in that +order and uses the fifth as the number, the fourth and third as the first and second argument. diff --git a/scripts/tools/replay.js b/scripts/tools/replay.js index 784fcd4..c8a9408 100644 --- a/scripts/tools/replay.js +++ b/scripts/tools/replay.js @@ -525,5 +525,41 @@ function zero(a, n) { u8().fill(0, a, a + n); } calls.forEach((c, i) => { try { runCall(c, i); } catch (e) { bad++; total++; console.log(`call ${i} ${c.tick} ${c.slot}: ERROR ${e.stack.split('\n').slice(0, 3).join(' | ')}`); } }); +if (flags.includes('--smoke')) smoke(); console.log(`${recPath.split('/').pop()}: ${total - bad}/${total} calls equal, most fuel of a call ${fuelMax}`); +function smoke() { + const STACK_TOP = 594608; + const lo = STACK_TOP - 4096; + const mark = () => u8().fill(0xaa, lo, STACK_TOP); + const depth = () => { let a = lo; while (a < STACK_TOP && u8()[a] === 0xaa) a++; return STACK_TOP - a; }; + let worst = 0; + setWords(); + const out = scratch + 1024; + for (const [n, o] of names) { + if (!n.startsWith('Unit#')) continue; + const st = rdu32(o.addr + 158); + if (!st) continue; + const t = (what, f) => { mark(); callLog = []; f(); worst = Math.max(worst, depth()); console.log(`smoke ${n} ${what}: stack ${depth()}`); }; + t('PoseUnitModel', () => inst.PoseUnitModel(o.addr)); + t('GetSweetSpot', () => { inst.GetSweetSpot(o.addr, out); console.log(' ', rd32(out), rd32(out + 4), rd32(out + 8)); }); + t('GetNano', () => { inst.GetNanoPiecePosition(o.addr, out); console.log(' ', rd32(out), rd32(out + 4), rd32(out + 8)); }); + t('GetAim', () => { inst.GetAimFromPosition(o.addr, out, 0); }); + const cnt = rd32(deref(st)); + inst.PoseUnitModel(o.addr); + let badp = 0; + for (let p = 0; p < cnt; p++) { + inst.GetPieceOffset(o.addr, p, out); + const m = deref(st) + 34 + 54 * p; + const off3 = [rd32(m + 22), rd32(m + 26), -rd32(m + 30) | 0]; + const got = [rd32(out), rd32(out + 4), rd32(out + 8)]; + if (off3.some((v, k) => v !== got[k])) { badp++; console.log(' piece', p, 'posed', off3, 'offset rule', got); } + } + console.log(`smoke ${n}: ${cnt} pieces, ${badp} differ between the pose and the offset rule`); + t('Apply DETACH', () => { + const ev = scratch + 512; zero(ev, 80); wr32(ev, 417); wr32(ev + 4, ref(o.addr)); wr32(ev + 8, 1); wr32(ev + 12, 1); + console.log(' outcome', inst.Apply(ev, 16)); + }); + } + console.log('smoke stack worst', worst); +} process.exit(bad ? 1 : 0); From 154bc73b26f74444ea069b2408e20e4b47db23d4 Mon Sep 17 00:00:00 2001 From: Implementer Date: Sun, 29 Nov 2026 02:04:20 +0000 Subject: [PATCH 10/30] Docs: Write the scripts implementation notes Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 62 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index 5659585..f28d48a 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -1,4 +1,64 @@ -# wind_meteors implementation notes +# scripts implementation notes + +## What was built +`scripts/` is a `no_std` Rust cdylib (`src/lib.rs`, with the bit-exact maths in `src/math.rs`), built by +`scripts/build.sh`: +- `ld-wrap.sh` is the linker wrapper of the wind_meteors module (drops `--stack-first`, `--allow-undefined` + and the `__heap_base`/`__data_end` exports; adds `--no-stack-first` when the linker lists it). +- Link options: data base 589824, table base 432, stack 4096, `--import-memory --import-table`. +- The fuel pass is the kit's `tools/wasm_fuel.py` (rule v1); `--check` accepts the module (29255 bytes). +- `target-cpu=mvp` plus sign-ext and bulk-memory. No saturating float conversion is left in the module + (`trunc64` in `math.rs` truncates a double by its bits). +- All 21 slots of the entry are exported. `UpdateObjectState` keeps the table import alive and does + nothing (`UnitDrawView` has no layout in the kit). The three engine slots are not exported. +- Imports: `map.GetGroundHeight`, `los_radar.IsUnitVisibleToPlayer`, `services.SimAlloc`, `SimAllocTagged`, + `SimFree` and `Emit`, nothing else. `Emit` publishes SET_YARD, AIM_DONE, EXPLODE_PIECE, ATTACH_TO_PIECE and + SCRIPT_VALUE with the sizes of the entry's `publishes` (12, 16, 16, 20, 16). +- No statics but the four data words and constants (the strings, the table anchor, the maths tables). +- Rotation of a point, the angle of a vector, hypot and `bx_ftol` are the kit's runtime ported to Rust + (`runtime/*.c`; the double-double arctangent tables are in `math.rs`). The sine and cosine of a 16-bit + angle at 64 bits are computed (a 120-bit fixed-point Taylor series, rounded to nearest even) rather than + read from the 65536-entry table, which would not fit the 32 KB window. `mathtest/` (a std crate that + includes `math.rs`) checks them against `runtime/vectors` (`rotate_point`, `angle_of_vector`, `hypot`, + `ftol`: no difference) and against the kit's generator for all 65536 angles (no difference). +- A direct-mapped cache of 16 `Trig` entries lives on the stack of one slot call (no static). +- `tools/replay.js` replays the four recordings of `tests/replay/scripts/` against the module with node + (`node tools/replay.js module.wasm RECORDING [--cob=ptr|off] [--smoke]`). It names objects as the format + does, sets the `r` lines, calls the slot, compares imports, `w` and `o` lines. `--smoke` also poses every + unit's model and checks that the posed `offset` of each piece equals the piece-offset rule, and prints + the stack depth reached (about 1.1 KB of the 4 KB). + +## Verdicts, in order +1. req1: `refused`, `scripts: the manifest has no size_budget` (no scenario played). +2. req2: `refused`, the same, with budgets given as extra files in the request directory. +3. req3: `refused`, the same, with more file names tried. +4. req4 (the final 29255-byte module, nothing but `module.wasm` and `subsystem`): `refused`, the same. + +The gate never reached the module, so there is no gate verdict on its behaviour. The local replay of the +four recordings (78 calls, `--cob=ptr` and `--cob=off`) is equal except for the two `SetCob` calls of +`orders-air` and `orders-factory`, whose recorded import lists are empty while the spec (2, "The manifest +entry") says a module that allocates the two blocks adds `SimAlloc` lines; the module makes them. +The most fuel any one call of those recordings burns is 1885. + +## Unclear points in the spec or kit +All are in `SPEC-QUESTIONS.md`; in short: +0. no way to give the gate the budgets (above); +1. the file checksum of `SetCob` has no input; the module rebuilds it from the table's memory (the file is + taken to start at the table's address, its length is the end of the last name, relocated words are + un-relocated by subtracting the table address); +2. whether the `ScriptTable` pointers are addresses or offsets (the module accepts either); +3. `UnitDrawView` has no layout, so `UpdateObjectState` does nothing; +4. TURN's delta uses the rotation as a signed `short`; +5. unit values 12 and 14 are masked to 16 bits unsigned; +6. the pose's restore of the other top-level pieces; +7. the order and re-run behaviour of the two allocations of `SetCob`; +8. `root` after the player state's reordering; +9. the effect command's pose (PoseUnitModel's or the update rule's); +10. the arguments of GET_UNIT_VALUE_4. +The kit has no `RecordSimEvent` import for scripts, so no sim event is recorded, and no `map` import for +the drop of a carried unit, so DROP_UNIT takes its word and does nothing (spec 2 and 4). + +# wind_meteors implementation notes (an earlier task) ## What was built `wind_meteors/` is a `no_std` Rust cdylib (`src/lib.rs`) built by `wind_meteors/build.sh`: From 9279e114e0d51b3856d0e9efbb34e624a2b7f1c2 Mon Sep 17 00:00:00 2001 From: opencode Date: Sun, 29 Nov 2026 02:07:50 +0000 Subject: [PATCH 11/30] Docs: Answer the scripts implementer questions Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 5545018..3cd8015 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -118,8 +118,10 @@ says adds import lines its recordings do not have. That kit gap is filed too. the linear address of its copy of the unit type's compiled script, outside the block. The record there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), - the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. The compiled - data is load-time data, which the module reads and never writes. + the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. `names` and + the piece names are linear addresses of arrays of linear addresses of the names; `entries` is an + array of `count` indices into `code`; `code` is a linear address. The compiled data is load-time + data, which the module reads and never writes. The file's checksum is not in the record: the reference keeps it beside the table, computed over the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that checksum, and its manifest kind for the argument is `block` although the table is outside the block; @@ -452,6 +454,9 @@ none), then the state itself is freed with `SimFree`. Nothing is written. ### The update rule and `UpdateObjectState(view)` +The view is the unit record itself: its model state is the `Ref` at 158 and its angles are +the six bytes at 100 (bank, heading, pitch). + *state* is the view's model state. When the view's angles are far from the state's `pos` (any of x, y and z differs by 8 or more as a 16-bit signed difference), `pos` becomes the view's angles, `animDirty` 1, the root's `modified` 0, and, when the root's `colored` bit is set, `cacheDrawCount` 0. @@ -460,8 +465,8 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi **The pose rule.** The pieces are restored first: a piece whose `modified` is 0 has its `points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set to (0,0,0) and its `modified` 0; the pieces below the root's first child are restored whatever their -`modified` (that child, its descendants and their siblings), and the root and the model's other -top-level pieces only when their `modified` is 0. Then every piece is visited once for itself and once +`modified` (that child, its descendants and their siblings), and a piece with no parent (the root +and the model's other top-level pieces) only when its `modified` is 0. Then every piece is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank @@ -484,7 +489,7 @@ gives them. ### `SetCob(script, data)` -`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: +`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise, in this order: - `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries (section 2 states the kit gap: the kit gives a module no word for it); @@ -501,7 +506,8 @@ for each *i* from 0 to `pieceCount`−1, the lowest *j* from *i* to `count`−1 found, and when *i* differs from *j* the two 54-byte records are swapped; a name with no match moves nothing for that *i*. Then the links are rebuilt from the object graph: each record's `sibling`, `child` and `parent` become the records whose objects are its object's `sibling`, `child` and -`parent`, and 0 when the object has none. The result is the state's address. +`parent`, and 0 when the object has none; the root becomes the record whose object is the model's +root. The result is the state's address. ### `SetObjectState(script, state)` @@ -532,7 +538,8 @@ taken next. All arithmetic is 32-bit and wraps. | Case | Behaviour | | --- | --- | | 0x10001000 (MOVE) | piece = *op1*, axis = *op2*: `move[axis]` = *a*, `moveSpeed[axis]` = *b* / 30; when `move[axis]` is below the model piece's translation (`rot_x`, `rot_y` or `rot_z`), `moveSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | -| 0x10002000 (TURN) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` = *b* / 30; delta = `turn[axis]` − the model piece's rotation (`short_10`, `short_12`, `short_14`); when delta is 0, `turnSpeed[axis]` 0, else when (|delta| > 0x8000) differs from (delta < 0), `turnSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | +| 0x10002000 (TURN) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` = *b* / 30; delta = `turn[axis]` − the model piece's rotation on that axis as an unsigned 16-bit +value (`short_10`, `short_12`, `short_14`); when delta is 0, `turnSpeed[axis]` 0, else when (|delta| > 0x8000) differs from (delta < 0), `turnSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | | 0x10003000 (SPIN) | piece, axis: `turn[axis]` = −1, `spin[axis]` = *a* / 30, `acceleration[axis]` = *b* / 30; when `acceleration[axis]` is 0, `turnSpeed[axis]` = `spin[axis]`; `active` 1, `changed` 1; `pc += 3`. | | 0x10004000 (STOP_SPIN) | piece, axis: `spin[axis]` 0, `acceleration[axis]` = −(*a* / 30); when `acceleration[axis]` is 0, `turnSpeed[axis]` 0; `pc += 3`. | | 0x10005000 (SHOW) | the piece *op1* becomes visible: when its bit 0 was clear, it is set, the piece's `modified` becomes 0, and when its `cached` bit is set the state's `cacheDrawCount` becomes 0; `pc += 2`. | @@ -616,9 +623,9 @@ second arguments. | 7 | the piece position of piece *a*: (`v.x & 0xffff0000`) + (`v.z >> 16`), *v* being its world position | | 8 | that position's y | | 9, 10, 11 | the unit at index `a & 0xffff` of the unit table, when it is alive (bit 28 of its `flags`): 9, (`pos.z >> 16`) + (`pos.x & 0xffff0000`); 10, `pos.y`; 11, `def.modelMaxY`. Otherwise these give 0. | -| 12 | *a*'s two halves *hi* = `a & 0xffff0000` and *lo* = `a << 16`, *lo* negative adding 0x10000 to *hi*: the angle of the vector (*hi*, *lo*) minus `u.heading`, wrapped to 16 bits | +| 12 | *a*'s two halves *hi* = `a & 0xffff0000` and *lo* = `a << 16`, *lo* negative adding 0x10000 to *hi*: the angle of the vector (*hi*, *lo*) minus `u.heading`, as an unsigned 16-bit value | | 13 | the same *hi* and *lo*: `bx_ftol(hypot(hi, lo))` (section 5) | -| 14 | the angle of the vector (*a*, *b*) wrapped to 16 bits | +| 14 | the angle of the vector (*a*, *b*), as an unsigned 16-bit value | | 15 | `bx_ftol(hypot(a, b))` | | 16 | a `Vec3` of x = `a & 0xffff0000`, z = `a << 16` (x adding 0x10000 when z is negative), y 0: `map.GetGroundHeight(&v) << 16` | | 17 | 0 when `u.buildLeft` is 0.0; otherwise 1 − `bx_ftol(u.buildLeft * −99.0)`, as a 32-bit float multiply and a conversion to 32 bits | @@ -631,7 +638,7 @@ the unit and *value* as `open`; then SCRIPT_VALUE is published with the unit, *w **The effect command** of a piece and an effect: when `los_radar.IsUnitVisibleToPlayer(&Game.players[Game.playerIndex], unit)` returns 0, nothing happens -and nothing is recorded. Otherwise the model is posed (section 4), and the two positions are +and nothing is recorded. Otherwise the model is updated by the update rule, and the two positions are computed: when `effect & 0x100` is not 0, *v1* is the unit's position plus the piece's posed offset (`pos.x + pieces[piece].offset.x`, `pos.y + ...y`, `pos.z − ...z`) and *v2* is unused; otherwise *v1* and *v2* are the unit's position plus each of the piece's first two posed vertices: *v1* adds From a12614db6e767385db0e39a9c54b4ebd0c6d000a Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:58:15 +0000 Subject: [PATCH 12/30] Update: Pin the scripts spec to interfaces-v89 Move the kit to interfaces-v89 and reference-traces-v59. List the imports the entry now has (SimRealloc, RecordSimEvent and CanPlaceUnitFootprint), say SetCob reallocates through SimRealloc, let the drop operation call the map, and drop the gaps they closed. The entry is blocked, so the gate judges recordings only. Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 71 ++++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 32 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 3cd8015..32e3733 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -43,9 +43,10 @@ The engine slots, which the module does not export and the engine's own code ans ### The manifest entry -The kit's manifest (`wasm/modules.json`) carries this module's entry without budgets, and the -reference repository's own manifest carries a `blocked` reason for it; the entry the module must have -is this one with the budgets its build picks: +The kit's manifest (`wasm/modules.json`) carries this module's entry with a `blocked` reason, so the entry +has neither `fuel_budget` nor `size_budget` and the host runs the native default for every slot of it. The gate +judges a module of the entry on its recordings alone, with no scenario, fuel budget or size budget +(`docs/module-abi.md`, sections 4.2 and 15). The module is still built to the entry as this section gives it: - `name` and `interface`: `scripts`. - `exports`, in this order: `Apply`, `StartScriptWithArgsByIndex`, `QueryScript`, `FindScript`, @@ -60,11 +61,8 @@ is this one with the budgets its build picks: - `majors`: `scripts` 3, and for its import groups `map` 9, `los_radar` 5, `services` 4. - `data_base` and `table_base`: `0x90000` and 432, from the entry (ABI 2). The window is 32768 bytes and the table range 32 entries. -- `fuel_budget` and `size_budget`: the build picks them (ABI 11.1 and 11.3). The host sets the fuel - counter once for all of the module's slot calls of a tick (ABI 11.2), so `fuel_budget` is ten times - the most fuel any one tick of the gate's scenarios burns across every slot this module runs, queries - and piece getters included; `size_budget` is the most bytes the build's `.wasm` may be. The module - meters itself by rule version 1 and exports `__fuel_set` and `__fuel_get`. +- `fuel_budget` and `size_budget`: none, as the entry is `blocked`. The module still meters itself by rule + version 1 and exports `__fuel_set` and `__fuel_get` (ABI 11). - `publishes`: `{"164": 12, "263": 16, "264": 16, "357": 20, "386": 16}`, the five effect kinds of section 4 (`docs/schedule.md`, "Routes"; `data/routes.csv`). - Slot kinds: @@ -92,20 +90,19 @@ is this one with the budgets its build picks: | Import | Kinds | Used for | | --- | --- | --- | | `map.GetGroundHeight` | `[linear] -> int` | unit value 16 | +| `map.CanPlaceUnitFootprint` | `[block, int, linear, int] -> int` | the drop operation of section 4 | | `los_radar.IsUnitVisibleToPlayer` | `[block, block] -> int` | the visibility test of the effect command | -| `services.SimAlloc` | `[int] -> linear` | a unit's script; the statics and piece records of `SetCob` | +| `services.SimAlloc` | `[int] -> linear` | a unit's script | | `services.SimAllocTagged` | `[linear, int] -> linear` | a model state and the point lists of its pieces | | `services.SimFree` | `[linear] -> void` | freeing them again | +| `services.SimRealloc` | `[linear, int] -> linear` | the statics and piece records of `SetCob` | +| `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the five sim events of the effect command | | `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | - Hooks: none. The header annotates every slot "Hooks: none". -The kit's entry also lacks `services.RecordSimEvent`, which section 4's effect command needs to record its -five sim events; no recording reaches that command, so the entry has no such import. The kit gap is filed -as its own issue, and a module built against the kit's entry records none of those five events. The -entry also has no reallocation service, which `SetCob` needs (section 4): the reference's own -reallocation is not a recorded import, so a module that allocates the two blocks the way section 4 -says adds import lines its recordings do not have. That kit gap is filed too. +A recording carries the scheduler's own name for one of these calls: `services.ScheduleMapCanPlaceUnitFootprint` is +`map.CanPlaceUnitFootprint` (`docs/module-abi.md`, "Routes in the recordings"). ### Arguments outside the block @@ -154,9 +151,9 @@ arguments, flags and phases are as `docs/sim-events.md` gives them: bubbles, puff white smoke and puff black smoke. The numbers each kind answers to, and its arguments, are as `docs/sim-events.md`, Terms, gives them. -The kit's manifest entry for this module imports no `services.RecordSimEvent`, so the entry as the kit -has it cannot record them; a module built from this spec records none of the five until the entry -lists the import (the kit gap of section 2, "The manifest entry"). +The module records each through `services.RecordSimEvent` with flags 0, the arguments in the order +`docs/sim-events.md` gives them, and their count: nine for THRUST_PARTICLES, eight for WAKE_PARTICLES and +BUBBLES, and four for WHITE_SMOKE and BLACK_SMOKE. `Apply` takes only the four kinds of 416 to 419. The routed effects of other interfaces that carry scripts' intent (kinds 17, 48, 49, 112, 278, 279, 311 and 347, `data/routes.csv`) are translated by @@ -493,9 +490,11 @@ gives them. - `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries (section 2 states the kit gap: the kit gives a module no word for it); -- `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes: an extent the statics block already - held keeps its bytes, and a new extent is 0. +- `script.pieces` becomes the result of `services.SimRealloc(script.pieces, pieceCount * 76)` (a null + `pieces` allocates; a size of 0 frees the block and gives null); +- `script.statics` becomes the result of `services.SimRealloc(script.statics, staticCount * 4)`: an extent + the statics block already held keeps its bytes, and a new extent is 0; +- the whole extent of the `pieces` block, `pieceCount * 76` bytes, is set to 0 (when `pieces` is not null). ### `CreatePlayerObjectState(model, data, owner)` @@ -658,8 +657,7 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | 0x103 | BUBBLES from *v1* to *v2*, where *v2* is *v1* with y = `Game.seaLevel << 16`, period 8, list 7 | | any other | nothing recorded | -As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records -none of these five. The reference records a publish as an engine call of its own, which the +The module records each row through `services.RecordSimEvent` (section 2, "Events"). The reference records a publish as an engine call of its own, which the recordings show as a `services.SchedPublish` line; a module publishes through `Emit`, which the engine records as the same effect, so the effect's kind and fields are what is compared, not the import's name (ABI 7.2 and 9.3). @@ -669,10 +667,10 @@ when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. **The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and -this unit is its carrier: when the map says the unit's footprint fits at its cell, ATTACH_TO_PIECE is -published with it, target 0, piece −1, mode 1. The map's answer is the engine's call -(`ScheduleMapCanPlaceUnitFootprint`), which this module does not import; a module built against the -kit's entry cannot make it, so it cannot drop a carried unit. The kit gap is filed as its own issue. +this unit is its carrier: when `map.CanPlaceUnitFootprint` with the unit's `def` (as a block offset), the +unit's `id` as a 16-bit value, the address of a copy of the unit's `cell` (a `Point16`, two 16-bit values) in +the module's own memory and the flags 1 returns a value that is not 0, ATTACH_TO_PIECE is published with it, +target 0, piece −1, mode 1. No recording reaches this operation. **The piece animation step** of an elapsed count: returns when *elapsed* is 0 or `changed` is 0; otherwise sets `changed` 0 and, for each piece *p* from 0 to `pieceCount`−1 whose `active` is not 0, @@ -846,7 +844,8 @@ unless written with `0x`. 10. **`NewUnitScript` and `SetCob`, from `orders-air`, call at tick 1025.** `NewUnitScript(Unit#3)` allocates 1348 bytes (the import's line `services.SimAlloc 1348`) and writes Unit#3's `script` to that CobScript, `scale` 30, `table` null, `statics` null, `pieces` null, `activeCount` 0. Then - `SetCob(CobScript#3, UnitDef#21)` writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 + `SetCob(CobScript#3, UnitDef#21)` makes the import lines `services.SimRealloc null 608` (the pieces) + and `services.SimRealloc null 16` (the statics), and writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 zero bytes (4 words) and `pieces` 608 zero bytes (8 records). 11. **The checksum of example 10.** The file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, @@ -876,11 +875,19 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `UpdateObjectState`, `ObjectStateSize`, `CreateObjectState`, `DeleteScript`, `SaveScriptState`, `LoadScriptState`, `WriteState`, the DETACH_PIECE, FREE_STATE and INIT_STATE events, the START form whose name matches no script and the one whose thread cannot start, the effect command (and so all five -sim events), recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write +sim events), the drop operation, recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. ## 8. Kit version -Kit `interfaces-v66` and `reference-traces-v55`, the versions the gate judges against, at commit -`74bdf5ef`. Interface `scripts` 3.0. The imports are against `map` 9, `los_radar` 5 and `services` -4.2. +Kit `interfaces-v89` and `reference-traces-v59`, the versions the gate judges against. Interface `scripts` 3.0. +The imports are against `map` 9, `los_radar` 5 and `services` 4.5. + +The kit's manifest entry is `blocked`, so it has no `fuel_budget` and no `size_budget`, and the host runs the +native default for every slot of it. The gate judges a module of the entry on its recordings, with no fuel or +size budget (`docs/module-abi.md`, sections 4.2 and 15). The gaps left in the kit, which the spec works around +(section 2): + +- the file checksum of a script, which a module has no word for; +- the manifest kind of the script data handle, `block`, although the table is outside the block; +- the translation of the routed effects of other interfaces into the four events `Apply` takes. From aefb925f23b9b8d0b758024214c83aa71fcba446 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:00:27 +0000 Subject: [PATCH 13/30] Fix: List RandomInt in the scripts imports The kit entry lists services.RandomInt; say that no recording calls it and the module draws from rng.seed itself. Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/scripts.md b/specs/scripts.md index 32e3733..aa6dd32 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -97,6 +97,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `services.SimFree` | `[linear] -> void` | freeing them again | | `services.SimRealloc` | `[linear, int] -> linear` | the statics and piece records of `SetCob` | | `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the five sim events of the effect command | +| `services.RandomInt` | `[int] -> int` | listed by the entry; no recording calls it, and the module makes the draw of section 5 from `rng.seed` itself | | `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | - Hooks: none. The header annotates every slot "Hooks: none". From e3a0b9738521a82a709a65157b5f47824be025d9 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:02:24 +0000 Subject: [PATCH 14/30] Update: Merge main, move scripts notes into scripts/ Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 62 +----------- scripts/IMPLEMENTATION-NOTES.md | 99 +++++++++++++++++++ .../SPEC-QUESTIONS.md | 0 3 files changed, 100 insertions(+), 61 deletions(-) create mode 100644 scripts/IMPLEMENTATION-NOTES.md rename SPEC-QUESTIONS.md => scripts/SPEC-QUESTIONS.md (100%) diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index f28d48a..5659585 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -1,64 +1,4 @@ -# scripts implementation notes - -## What was built -`scripts/` is a `no_std` Rust cdylib (`src/lib.rs`, with the bit-exact maths in `src/math.rs`), built by -`scripts/build.sh`: -- `ld-wrap.sh` is the linker wrapper of the wind_meteors module (drops `--stack-first`, `--allow-undefined` - and the `__heap_base`/`__data_end` exports; adds `--no-stack-first` when the linker lists it). -- Link options: data base 589824, table base 432, stack 4096, `--import-memory --import-table`. -- The fuel pass is the kit's `tools/wasm_fuel.py` (rule v1); `--check` accepts the module (29255 bytes). -- `target-cpu=mvp` plus sign-ext and bulk-memory. No saturating float conversion is left in the module - (`trunc64` in `math.rs` truncates a double by its bits). -- All 21 slots of the entry are exported. `UpdateObjectState` keeps the table import alive and does - nothing (`UnitDrawView` has no layout in the kit). The three engine slots are not exported. -- Imports: `map.GetGroundHeight`, `los_radar.IsUnitVisibleToPlayer`, `services.SimAlloc`, `SimAllocTagged`, - `SimFree` and `Emit`, nothing else. `Emit` publishes SET_YARD, AIM_DONE, EXPLODE_PIECE, ATTACH_TO_PIECE and - SCRIPT_VALUE with the sizes of the entry's `publishes` (12, 16, 16, 20, 16). -- No statics but the four data words and constants (the strings, the table anchor, the maths tables). -- Rotation of a point, the angle of a vector, hypot and `bx_ftol` are the kit's runtime ported to Rust - (`runtime/*.c`; the double-double arctangent tables are in `math.rs`). The sine and cosine of a 16-bit - angle at 64 bits are computed (a 120-bit fixed-point Taylor series, rounded to nearest even) rather than - read from the 65536-entry table, which would not fit the 32 KB window. `mathtest/` (a std crate that - includes `math.rs`) checks them against `runtime/vectors` (`rotate_point`, `angle_of_vector`, `hypot`, - `ftol`: no difference) and against the kit's generator for all 65536 angles (no difference). -- A direct-mapped cache of 16 `Trig` entries lives on the stack of one slot call (no static). -- `tools/replay.js` replays the four recordings of `tests/replay/scripts/` against the module with node - (`node tools/replay.js module.wasm RECORDING [--cob=ptr|off] [--smoke]`). It names objects as the format - does, sets the `r` lines, calls the slot, compares imports, `w` and `o` lines. `--smoke` also poses every - unit's model and checks that the posed `offset` of each piece equals the piece-offset rule, and prints - the stack depth reached (about 1.1 KB of the 4 KB). - -## Verdicts, in order -1. req1: `refused`, `scripts: the manifest has no size_budget` (no scenario played). -2. req2: `refused`, the same, with budgets given as extra files in the request directory. -3. req3: `refused`, the same, with more file names tried. -4. req4 (the final 29255-byte module, nothing but `module.wasm` and `subsystem`): `refused`, the same. - -The gate never reached the module, so there is no gate verdict on its behaviour. The local replay of the -four recordings (78 calls, `--cob=ptr` and `--cob=off`) is equal except for the two `SetCob` calls of -`orders-air` and `orders-factory`, whose recorded import lists are empty while the spec (2, "The manifest -entry") says a module that allocates the two blocks adds `SimAlloc` lines; the module makes them. -The most fuel any one call of those recordings burns is 1885. - -## Unclear points in the spec or kit -All are in `SPEC-QUESTIONS.md`; in short: -0. no way to give the gate the budgets (above); -1. the file checksum of `SetCob` has no input; the module rebuilds it from the table's memory (the file is - taken to start at the table's address, its length is the end of the last name, relocated words are - un-relocated by subtracting the table address); -2. whether the `ScriptTable` pointers are addresses or offsets (the module accepts either); -3. `UnitDrawView` has no layout, so `UpdateObjectState` does nothing; -4. TURN's delta uses the rotation as a signed `short`; -5. unit values 12 and 14 are masked to 16 bits unsigned; -6. the pose's restore of the other top-level pieces; -7. the order and re-run behaviour of the two allocations of `SetCob`; -8. `root` after the player state's reordering; -9. the effect command's pose (PoseUnitModel's or the update rule's); -10. the arguments of GET_UNIT_VALUE_4. -The kit has no `RecordSimEvent` import for scripts, so no sim event is recorded, and no `map` import for -the drop of a carried unit, so DROP_UNIT takes its word and does nothing (spec 2 and 4). - -# wind_meteors implementation notes (an earlier task) +# wind_meteors implementation notes ## What was built `wind_meteors/` is a `no_std` Rust cdylib (`src/lib.rs`) built by `wind_meteors/build.sh`: diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md new file mode 100644 index 0000000..f28d48a --- /dev/null +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -0,0 +1,99 @@ +# scripts implementation notes + +## What was built +`scripts/` is a `no_std` Rust cdylib (`src/lib.rs`, with the bit-exact maths in `src/math.rs`), built by +`scripts/build.sh`: +- `ld-wrap.sh` is the linker wrapper of the wind_meteors module (drops `--stack-first`, `--allow-undefined` + and the `__heap_base`/`__data_end` exports; adds `--no-stack-first` when the linker lists it). +- Link options: data base 589824, table base 432, stack 4096, `--import-memory --import-table`. +- The fuel pass is the kit's `tools/wasm_fuel.py` (rule v1); `--check` accepts the module (29255 bytes). +- `target-cpu=mvp` plus sign-ext and bulk-memory. No saturating float conversion is left in the module + (`trunc64` in `math.rs` truncates a double by its bits). +- All 21 slots of the entry are exported. `UpdateObjectState` keeps the table import alive and does + nothing (`UnitDrawView` has no layout in the kit). The three engine slots are not exported. +- Imports: `map.GetGroundHeight`, `los_radar.IsUnitVisibleToPlayer`, `services.SimAlloc`, `SimAllocTagged`, + `SimFree` and `Emit`, nothing else. `Emit` publishes SET_YARD, AIM_DONE, EXPLODE_PIECE, ATTACH_TO_PIECE and + SCRIPT_VALUE with the sizes of the entry's `publishes` (12, 16, 16, 20, 16). +- No statics but the four data words and constants (the strings, the table anchor, the maths tables). +- Rotation of a point, the angle of a vector, hypot and `bx_ftol` are the kit's runtime ported to Rust + (`runtime/*.c`; the double-double arctangent tables are in `math.rs`). The sine and cosine of a 16-bit + angle at 64 bits are computed (a 120-bit fixed-point Taylor series, rounded to nearest even) rather than + read from the 65536-entry table, which would not fit the 32 KB window. `mathtest/` (a std crate that + includes `math.rs`) checks them against `runtime/vectors` (`rotate_point`, `angle_of_vector`, `hypot`, + `ftol`: no difference) and against the kit's generator for all 65536 angles (no difference). +- A direct-mapped cache of 16 `Trig` entries lives on the stack of one slot call (no static). +- `tools/replay.js` replays the four recordings of `tests/replay/scripts/` against the module with node + (`node tools/replay.js module.wasm RECORDING [--cob=ptr|off] [--smoke]`). It names objects as the format + does, sets the `r` lines, calls the slot, compares imports, `w` and `o` lines. `--smoke` also poses every + unit's model and checks that the posed `offset` of each piece equals the piece-offset rule, and prints + the stack depth reached (about 1.1 KB of the 4 KB). + +## Verdicts, in order +1. req1: `refused`, `scripts: the manifest has no size_budget` (no scenario played). +2. req2: `refused`, the same, with budgets given as extra files in the request directory. +3. req3: `refused`, the same, with more file names tried. +4. req4 (the final 29255-byte module, nothing but `module.wasm` and `subsystem`): `refused`, the same. + +The gate never reached the module, so there is no gate verdict on its behaviour. The local replay of the +four recordings (78 calls, `--cob=ptr` and `--cob=off`) is equal except for the two `SetCob` calls of +`orders-air` and `orders-factory`, whose recorded import lists are empty while the spec (2, "The manifest +entry") says a module that allocates the two blocks adds `SimAlloc` lines; the module makes them. +The most fuel any one call of those recordings burns is 1885. + +## Unclear points in the spec or kit +All are in `SPEC-QUESTIONS.md`; in short: +0. no way to give the gate the budgets (above); +1. the file checksum of `SetCob` has no input; the module rebuilds it from the table's memory (the file is + taken to start at the table's address, its length is the end of the last name, relocated words are + un-relocated by subtracting the table address); +2. whether the `ScriptTable` pointers are addresses or offsets (the module accepts either); +3. `UnitDrawView` has no layout, so `UpdateObjectState` does nothing; +4. TURN's delta uses the rotation as a signed `short`; +5. unit values 12 and 14 are masked to 16 bits unsigned; +6. the pose's restore of the other top-level pieces; +7. the order and re-run behaviour of the two allocations of `SetCob`; +8. `root` after the player state's reordering; +9. the effect command's pose (PoseUnitModel's or the update rule's); +10. the arguments of GET_UNIT_VALUE_4. +The kit has no `RecordSimEvent` import for scripts, so no sim event is recorded, and no `map` import for +the drop of a carried unit, so DROP_UNIT takes its word and does nothing (spec 2 and 4). + +# wind_meteors implementation notes (an earlier task) + +## What was built +`wind_meteors/` is a `no_std` Rust cdylib (`src/lib.rs`) built by `wind_meteors/build.sh`: +- `ld-wrap.sh` is the linker wrapper. rustc passes `--stack-first` and `--allow-undefined`, which the ABI forbids, so the wrapper removes them. The `__heap_base` and `__data_end` exports are removed the same way. +- `fuel.py` is the fuel pass (ABI 11, rule v1). It works on the `wasm-tools print` text: it inserts the decrement at every function entry and loop top, then adds the counter global, `__fuel_set` and `__fuel_get`. +- Link options: data base 196608, table base 48, stack 4096. +- Flags: `target-cpu=mvp` plus sign-ext and bulk-memory, so no non-trapping float conversions. `d2i` does the guarded double-to-int conversion by hand. +- Every helper is `#[inline(always)]`, to keep the fuel use of a tick small against the 250 budget. +- Block fields are packed (unaligned), so all accesses are unaligned loads and stores at the offsets in `layout.json`. +- The sine table is a 512-entry `static` generated from the spec formula. +- `EmptyShutdownPreCleanup` volatile-reads a static function-pointer table. That keeps the `env.__indirect_function_table` import, which ABI 9.1 requires, and it is the element segment at table base 48. +- The module is 6850 bytes against a 13100 budget. + +## Update to spec v59 / kit interfaces-v59 (wind_meteors 3.1) +- `UpdateWind(stream)` is one slot now; `Apply(event, size)` replaces the Enable/Disable/SetMeteorParams/CmdMeteor entry points (kinds 64-69, size checks per the spec). +- A meteor is published with `services.Emit` (a 36-byte SPAWN effect, weapon as a slot in `Game.weapons`, -1 for none) instead of `weapons.SpawnProjectile`. The `CommandArgs_GetIntArg` import is gone. +- `SimGlobals` meteor offsets moved down by 4 bytes (checked in `layout.json`); `Game` offsets are unchanged. +- `d2i` now follows the spec: truncate to 64 bits and keep the low 32; NaN, infinity or 2^63 and above gives 0 (the old one gave 0x80000000 on overflow). + +## Verdicts, in order +1. req1: `equal` (3 recordings, every scenario, digest and view). + +2. req2, req3: no verdict. The gate answered at once with `the gate wrote no usable result (exit 2): No such file or directory: .../gate/reqN/out/result.json`. The module submitted is byte-identical to req1's (6850 bytes), so this is a gate fault, not a difference. +3. req4 (after the review answers, same 6850-byte module): `equal` (3 recordings, every scenario). + +## Answers to /srv/inbox/review.md +- 1 (`--no-stack-first`): `ld-wrap.sh` now appends `--no-stack-first` when the linker's help lists it. The local LLD 20.1.8 doesn't, and rejects it, so it's left off there and the stack falls after the data (top 202176, in the window). Not verifiable against 22.1.8 here. +- 2 (`EmptyShutdownPreCleanup`): kept. The volatile read keeps the table import and element segment ABI 9.1 requires; commented in the source. Unobservable. +- 3 (unterminated name): the spec calls it undefined; the copy is bounded at 32 bytes. Kept. +- 4 (weapon slot range): the spec says it never happens in a match. No guard. +- 5-8: nits, left. The dead `return` and spare NUL in `BAD` are harmless; `d2i` guards follow spec 5; the size-guarded arms are correct. +- 9: `fuel.py` and `build.sh` now use temporary directories and the unused `ng` is gone. + +## Unclear points in the spec or kit +- ABI 3.1 says `--no-stack-first`; this toolchain's linker default already puts the stack after the data, so the option is not passed. rustc's `--stack-first` is removed by the linker wrapper. The stack top (202176) lies inside the window. +- `fuel.py` is my own pass (the kit now has `tools/wasm_fuel.py`; its `--check` accepts the module). +- `SaveMeteors`, `LoadMeteors`, `FatalError` and the Q3 outcomes follow the spec text only; no recording has them. +- The header's DISABLE comment ("drops no meteor") reads differently from spec Q4 (a due shower starts and is then made inactive); the module follows the spec and was equal. diff --git a/SPEC-QUESTIONS.md b/scripts/SPEC-QUESTIONS.md similarity index 100% rename from SPEC-QUESTIONS.md rename to scripts/SPEC-QUESTIONS.md From e3d3451d3e150ba411e01c84c87874159885c470 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:03:47 +0000 Subject: [PATCH 15/30] Update: Follow the v89 scripts spec Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/src/lib.rs | 149 +++++++++++++++++++++++++++++++++------- scripts/tools/replay.js | 24 ++++++- 2 files changed, 145 insertions(+), 28 deletions(-) diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index d0abff6..1469516 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -9,6 +9,8 @@ use math::TrigCache; extern "C" { #[link_name = "GetGroundHeight"] fn get_ground_height(pos: *mut i32) -> i32; + #[link_name = "CanPlaceUnitFootprint"] + fn can_place_footprint(def: u32, other: u32, cell: *const u16, flags: i32) -> i32; } #[link(wasm_import_module = "los_radar")] @@ -25,6 +27,12 @@ extern "C" { fn sim_alloc_tagged(tag: *const u8, size: u32) -> u32; #[link_name = "SimFree"] fn sim_free(p: u32); + #[link_name = "SimRealloc"] + fn sim_realloc(p: u32, size: u32) -> u32; + #[link_name = "RecordSimEvent"] + fn record_sim_event(kind: u32, flags: u32, args: *const u32, count: u32); + #[link_name = "RandomInt"] + fn random_int(n: i32) -> i32; #[link_name = "Emit"] fn emit(effect: *const u32, size: i32); } @@ -161,6 +169,7 @@ fn strend(a: u32) -> u32 { // Unit const U_BANK: u32 = 100; const U_POS: u32 = 106; +const U_CELL: u32 = 118; const U_CARRIER: u32 = 134; const U_CARGO: u32 = 138; const U_CARGO_NEXT: u32 = 142; @@ -183,6 +192,7 @@ const G_FEATURES: u32 = 82543; const G_UNITS: u32 = 82775; const FEATURE_SIZE: u32 = 256; const F_OBJECT: u32 = 152; +const G_SEA_LEVEL: u32 = 82559; const G_RANDOM_SEED: u32 = 48172; // CobScript const S_TABLE: u32 = 8; @@ -234,6 +244,7 @@ const MP_SIBLING: u32 = 42; const MP_CHILD: u32 = 46; const MP_PARENT: u32 = 50; const F_VISIBLE: u16 = 1; +const F_COLORED: u16 = 2; const F_CACHED: u16 = 2; const F_SHADED: u16 = 4; // Object3do @@ -680,6 +691,10 @@ fn wake(sc: u32, i: u32) { } fn draw(range: i32) -> i32 { + if range == i32::MIN { + // The entry lists `services.RandomInt`, so the import stays; no recorded range is this one. + return unsafe { random_int(range) }; + } if range < 2 { return 0; } @@ -770,16 +785,88 @@ fn find_unit(id: i32) -> u32 { rf(game() + G_UNITS) + (id as u32 & 0xffff) * UNIT_SIZE } -/// The effect command of a piece and an effect number. The kit's entry has no import to record -/// the five sim events, so only the visibility test and the pose remain. -fn effect_command(sc: u32, unit: u32, state: u32, tc: &mut TrigCache) { +/// The update rule of section 4 for the unit record acting as the view. +fn update_state(unit: u32, tc: &mut TrigCache) { + let state = rf(unit + U_STATE); + if state == 0 { + return; + } + let mut k = 0; + let mut far = false; + while k < 6 { + let d = (r16(unit + U_BANK + k) as i16).wrapping_sub(r16(state + M_POS + k) as i16) as i32; + if d >= 8 || d <= -8 { + far = true; + } + k += 2; + } + if far { + copy(state + M_POS, unit + U_BANK, 6); + wi(state + M_DIRTY, 1); + let root = rf(state + M_ROOT); + w16(root + MP_MODIFIED, 0); + if r16(root + MP_FLAGS) & F_COLORED != 0 { + wi(state + M_CACHE_DRAW, 0); + } + } + if ri(state + M_DIRTY) != 0 { + pose_model(state, tc); + wi(state + M_DIRTY, 0); + } +} + +fn sim_event(kind: u32, args: &[u32]) { + unsafe { record_sim_event(kind, 0, args.as_ptr(), args.len() as u32) } +} + +/// The effect command of a piece and an effect number. +fn effect_command(unit: u32, piece: i32, effect: i32, tc: &mut TrigCache) { let g = game(); let player = g + G_PLAYERS + G_PLAYER_SIZE * r8(g + G_PLAYER_INDEX) as u32; if unsafe { is_unit_visible(player, unit) } == 0 { return; } - let _ = sc; - pose_unit_state(unit, state, tc); + update_state(unit, tc); + let state = rf(unit + U_STATE); + if state == 0 || piece < 0 || piece >= ri(state + M_COUNT) { + return; + } + let m = mp(state, piece); + let up = [ri(unit + U_POS), ri(unit + U_POS + 4), ri(unit + U_POS + 8)]; + let (v1, v2); + if effect & 0x100 != 0 { + v1 = [ + up[0].wrapping_add(ri(m + MP_OFFSET)), + up[1].wrapping_add(ri(m + MP_OFFSET + 4)), + up[2].wrapping_sub(ri(m + MP_OFFSET + 8)), + ]; + v2 = v1; + } else { + let pts = rf(m + MP_POINTS); + v1 = [ + up[0].wrapping_add(ri(pts)), + up[1].wrapping_add(ri(pts + 4)), + up[2].wrapping_sub(ri(pts + 8)), + ]; + v2 = [ + up[0].wrapping_add(ri(pts + 12)), + up[1].wrapping_add(ri(pts + 16)), + up[2].wrapping_sub(ri(pts + 20)), + ]; + } + let (a, b) = (v1.map(|x| x as u32), v2.map(|x| x as u32)); + match effect { + 0 | 1 => sim_event(6, &[a[0], a[1], a[2], b[0], b[1], b[2], 1, if effect == 0 { 6 } else { 7 }, 7]), + 2 | 3 => sim_event(7, &[a[0], a[1], a[2], b[0], b[1], b[2], if effect == 2 { 16 } else { 8 }, 2]), + 4 | 5 => sim_event(7, &[b[0], b[1], b[2], a[0], a[1], a[2], if effect == 4 { 16 } else { 8 }, 2]), + 0x101 => sim_event(28, &[a[0], a[1], a[2], 9]), + 0x102 => sim_event(29, &[a[0], a[1], a[2], 9]), + 0x103 => { + let sea = (r8(g + G_SEA_LEVEL) as u32) << 16; + sim_event(8, &[a[0], a[1], a[2], a[0], sea, a[2], 8, 7]); + } + _ => {} + } } #[inline(always)] @@ -879,7 +966,7 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { wi(rec + P_TURN + ax, want); wi(rec + P_ACCEL + ax, 0); let mut ts = b / 30; - let delta = want.wrapping_sub(rs(mp(state, op1) + MP_ROT + 2 * op2 as u32) as i32); + let delta = want.wrapping_sub(r16(mp(state, op1) + MP_ROT + 2 * op2 as u32) as i32); if delta == 0 { ts = 0; } else if (delta.wrapping_abs() > 0x8000) != (delta < 0) { @@ -976,9 +1063,8 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { 0x1000_f000 => { let a = pop!(); pc += 2; - let _ = a; if unit != 0 { - effect_command(sc, unit, state, tc); + effect_command(unit, op1, a, tc); } } 0x1001_1000 | 0x1001_2000 => { @@ -1238,9 +1324,17 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { } } 0x1008_4000 => { - // DROP_UNIT: the kit's entry has no import for the map's footprint test. - pop!(); + let a = pop!(); pc += 1; + flush!(); + let u = find_unit(a); + if unit != 0 && r32(u + U_FLAGS) & ALIVE != 0 && rf(u + U_CARRIER) == unit { + let cell = [r16(u + U_CELL), r16(u + U_CELL + 2)]; + let fits = unsafe { can_place_footprint(r32(u + U_DEF), r16(u + U_ID) as u32, cell.as_ptr(), 1) }; + if fits != 0 { + attach_to_piece(u, 0, -1, 1); + } + } } _ => { w32(c, 0); @@ -1639,9 +1733,11 @@ fn table_anchor() {} static ANCHOR: [fn(); 1] = [table_anchor]; #[no_mangle] -pub extern "C" fn UpdateObjectState(_view: u32) { - // The layout of the draw view is not in the kit (SPEC-QUESTIONS.md), so nothing is posed here. +pub extern "C" fn UpdateObjectState(view: u32) { + // ABI 9.1: a module that uses no function pointer would have no table import; this one keeps it. let _ = unsafe { read_volatile(&ANCHOR[0]) }; + let mut tc = TrigCache::new(); + update_state(view, &mut tc); } #[no_mangle] @@ -1674,23 +1770,22 @@ pub extern "C" fn SetCob(script: u32, data: u32) { return; } wi(script + S_CHECKSUM, cob_checksum(data)); - let old_pieces = rf(script + S_PIECES); - if old_pieces != 0 { - unsafe { sim_free(old_pieces) }; - } - let size = (t_pieces(data) as u32).wrapping_mul(P_SIZE); - let p = unsafe { sim_alloc(size) }; - zero(p, size); + let psize = (t_pieces(data) as u32).wrapping_mul(P_SIZE); + let p = unsafe { sim_realloc(rf(script + S_PIECES), psize) }; w32(script + S_PIECES, off(p)); let old_statics = rf(script + S_STATICS); let size = (t_statics(data) as u32).wrapping_mul(4); - let s = unsafe { sim_alloc(size) }; - if old_statics != 0 { - let keep = if old != 0 { (t_statics(old) as u32).wrapping_mul(4) } else { 0 }; - copy(s, old_statics, if keep < size { keep } else { size }); - unsafe { sim_free(old_statics) }; - } + let s = unsafe { sim_realloc(old_statics, size) }; w32(script + S_STATICS, off(s)); + if s != 0 { + let keep = if old_statics != 0 && old != 0 { (t_statics(old) as u32).wrapping_mul(4) } else { 0 }; + if keep < size { + zero(s + keep, size - keep); + } + } + if p != 0 { + zero(p, psize); + } } #[no_mangle] @@ -1698,6 +1793,7 @@ pub extern "C" fn CreatePlayerObjectState(model: u32, data: u32, owner: u32) -> let state = create_object_state(model); w32(state + M_OWNER, off(owner)); let n = ri(state + M_COUNT); + let root_obj = if n > 0 { mobj(rf(state + M_ROOT)) } else { 0 }; let pcount = t_pieces(data); let mut i = 0; while i < pcount { @@ -1737,6 +1833,9 @@ pub extern "C" fn CreatePlayerObjectState(model: u32, data: u32, owner: u32) -> } i += 1; } + if n > 0 { + w32(state + M_ROOT, off(record_of(state, n, root_obj))); + } state } diff --git a/scripts/tools/replay.js b/scripts/tools/replay.js index c8a9408..8c059a8 100644 --- a/scripts/tools/replay.js +++ b/scripts/tools/replay.js @@ -335,6 +335,19 @@ const imports = { unnamed.push({ addr: a, size: n }); return a; }, + SimRealloc: (p, n) => { + const a = alloc(n); + if (p) u8().copyWithin(a, p, p + n); + callLog.push(['SimRealloc', p, n]); + unnamed.push({ addr: a, size: n }); + return a; + }, + RecordSimEvent: (kind, flags, p, n) => { + const words = []; + for (let i = 0; i < n; i++) words.push(rd32(p + 4 * i)); + callLog.push(['RecordSimEvent', kind, words]); + }, + RandomInt: (n) => 0, SimFree: (p) => { callLog.push(['SimFree', p]); }, Emit: (p, n) => { const words = []; @@ -342,7 +355,7 @@ const imports = { callLog.push(['Emit', n, words]); }, }, - map: { GetGroundHeight: (p) => 0 }, + map: { GetGroundHeight: (p) => 0, CanPlaceUnitFootprint: () => 1 }, los_radar: { IsUnitVisibleToPlayer: (a, b) => 1 }, }; let callLog = []; @@ -471,7 +484,7 @@ function runCall(c, idx) { } // imports const expectedImports = I.map((s) => s.split(' ')[0]); - const gotImports = callLog.filter((x) => x[0] !== 'Emit'); + const gotImports = callLog.filter((x) => x[0] !== 'Emit' && x[0] !== 'RecordSimEvent'); const publishes = callLog.filter((x) => x[0] === 'Emit'); const wantPub = I.filter((s) => s.startsWith('services.SchedPublish')); const wantAlloc = I.filter((s) => !s.startsWith('services.SchedPublish')); @@ -481,6 +494,11 @@ function runCall(c, idx) { const g = gotImports[k]; const m = /^services\.(\w+)(?: "(.*)")? ?(\d+)?/.exec(s); if (m[1] !== g[0]) errs.push(`import ${k}: want ${m[1]} got ${g[0]}`); + else if (m[1] === 'SimRealloc') { + const mr = /^services\.SimRealloc (\S+) (\d+)/.exec(s); + if (+mr[2] !== g[2]) errs.push(`SimRealloc size ${mr[2]} vs ${g[2]}`); + if ((mr[1] === 'null') !== (g[1] === 0)) errs.push(`SimRealloc old ${mr[1]} vs ${g[1]}`); + } else if (m[1] === 'SimAlloc' && +m[3] !== g[1]) errs.push(`SimAlloc size ${m[3]} vs ${g[1]}`); else if (m[1] === 'SimAllocTagged' && (m[2] !== g[1] || +m[3] !== g[2])) errs.push(`SimAllocTagged ${s} vs ${g}`); // name the results @@ -492,7 +510,7 @@ function runCall(c, idx) { { let ui = 0; for (const s of wantAlloc) { - if (/^services\.SimAlloc/.test(s)) { + if (/^services\.Sim(Alloc|Realloc)/.test(s)) { const mm = / = (\S+)$/.exec(s); const u = unnamed[ui++]; if (mm && u && /^[A-Z]\w+#\d+$/.test(mm[1]) && !names.has(mm[1])) names.set(mm[1], { addr: u.addr, size: u.size }); From 270c45d4f66284ccdff95753c8e5b4caafec2f71 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:13:45 +0000 Subject: [PATCH 16/30] Update: Write the CobScript class word, record gate answers Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 29 ++++++++++++++++ scripts/SPEC-QUESTIONS.md | 59 +++++++++++++++++++++++++++++++++ scripts/src/lib.rs | 15 ++++----- scripts/tools/replay.js | 2 +- 4 files changed, 96 insertions(+), 9 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index f28d48a..5b43158 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -97,3 +97,32 @@ the drop of a carried unit, so DROP_UNIT takes its word and does nothing (spec 2 - `fuel.py` is my own pass (the kit now has `tools/wasm_fuel.py`; its `--check` accepts the module). - `SaveMeteors`, `LoadMeteors`, `FatalError` and the Q3 outcomes follow the spec text only; no recording has them. - The header's DISABLE comment ("drops no meteor") reads differently from spec Q4 (a due shower starts and is then made inactive); the module follows the spec and was equal. + +## Second session (kit interfaces-v89, v90 from req27) + +Changes: the merge of `main` and `spec-scripts`; imports now `map.CanPlaceUnitFootprint`, `services.SimRealloc`, +`RecordSimEvent`, `RandomInt` (kept alive by a branch on `i32::MIN`, a range no recording draws) beside the old +ones, as the entry lists; `SetCob` uses `SimRealloc` (pieces, then statics, new statics extent zeroed, pieces +zeroed); the effect command updates the model by the update rule and records THRUST/WAKE/BUBBLES/WHITE_SMOKE/ +BLACK_SMOKE through `RecordSimEvent`; DROP_UNIT calls `CanPlaceUnitFootprint` (flags 1, a copy of the cell); +`UpdateObjectState(view)` runs the update rule on the unit record (model state at 158, angles at 100); TURN's +rotation is unsigned; `CreatePlayerObjectState` sets `root`; `NewUnitScript` copies the `CobScript` class word +(`class_words[5]`, load data base + 20) into offset 0; table pointers are plain linear addresses. +`tools/replay.js` knows the new imports and a memory big enough for the class table; my replayer is equal on all +40+8+20+10 calls of the four recordings. + +Verdicts, in order (all `differs`, a gate that plays the recordings): +1. req1 (first build): console-iwin call 1 `CobScript#2.activeCount`, orders-air call 0 `CobScript#1.activeCount`, + orders-factory call 1 `Unit#2.script` (`CobScript#?`), orders-move-attack call 1 `CobScript#1.statics`. +2. req2 (table pointers as plain addresses): the same four. +3. req3 to req26, req28 to req31: probe builds (a number written into `activeCount`, `Unit.script` variants, a + no-op `SetCob`). They showed that the script table is not in the memory (SPEC-QUESTIONS 11), that the class + word is needed (13) and that `SetCob` is refused by the glue (12). req13 and req29 were my own mistakes (a + scan past the memory end: `failed`; a build without the `SimRealloc` import: `refused`). +4. req27 (class word written, kit v90): orders-factory now fails at `SetCob` as a glue `failed`; the others as before. +5. req32 (the final module): the same as req27. + +The module is therefore blocked on the questions 11 and 12 of SPEC-QUESTIONS.md: the gate does not give the module +the script data, so no recording that runs a thread, starts a script or reads a script table can be equal. +Unclear in the spec or kit besides: the spec's "writes 0 at offset 0" of `NewUnitScript` (13), the kit moving to +v90 during the session (14), and the file checksum of `SetCob` (1 above), which could not be tested. diff --git a/scripts/SPEC-QUESTIONS.md b/scripts/SPEC-QUESTIONS.md index af68c80..14fbf8f 100644 --- a/scripts/SPEC-QUESTIONS.md +++ b/scripts/SPEC-QUESTIONS.md @@ -85,3 +85,62 @@ is visible to the player and whose unit turned by less than 8. The spec's opcode row takes "*a*, *b*, *d*, *e*, *f*" (no *c*). The module pops five words in that order and uses the fifth as the number, the fourth and third as the first and second argument. + +# Second session (kit interfaces-v89, then v90 from req27; the gate now plays the recordings) + +Item 0 above is answered: the gate no longer refuses; it plays the four recordings. Nothing below is a guess: +each fact comes from a verdict (req1 to req31; req3 to req26 and req28 to req31 are probe builds, see +IMPLEMENTATION-NOTES.md for how they read the memory: a probe writes a number into `CobScript.activeCount` +and the verdict prints it as `value`). + +## 11. The compiled script data (`ScriptTable`) is not in the module's memory (blocks every call that runs code) + +Spec section 2 ("Arguments outside the block") says the handle is the linear address of the kit's copy of the +unit type's compiled script. In a `RunScripts` call the field `CobScript.table` holds 1919240 (0x1d4b88) in +all four recordings (the same unit type, `ARMCOM`, so the same value). The memory there is zero: `count` +(offset 4), `names` (28) and `code` (36) read 0, and a scan of the 64 words around it finds no non-zero word. +Scans for the header of `ARMCOM.COB` (`count` 20 at 4, `pieceCount` 14 at 8, `staticCount` 4 at 16, word 4 at 0) +over 0x0..0x100000, the whole block (0x100000..0x10100000) and the whole load data region +(0x10100000..0x14100000) find nothing. The load data holds only the class word table and the models +(its last non-zero word is at word 48 in `console-iwin`, 4490 in `orders-air`). `UnitDef#34.data` is 0. +So 1919240 looks like a native address of the replayer's own heap, not a copy in the shared memory. The +effect: every thread run reads `code` and finds 0, so a thread ends at its first step (`activeCount` +falls where the recording keeps it), `Apply`'s START finds no script name, and `SetCob` and +`CreatePlayerObjectState` have no names or counts to read. The verdicts show it: `console-iwin` call 1, +`orders-air` call 0 and `orders-move-attack` call 1 differ only because of code that cannot be read. +Question: is the cob load mapped into the load data (as models are) in the gate? Which field or argument +holds its address? + +## 12. `SetCob` ends in a glue failure before the module's code runs + +With the class word of item 13 written, `orders-factory` passes `NewUnitScript` (call 1) and then fails +at `SetCob` (call 2) as `{"class": "glue", "reason": "module-trap", "status": "failed"}`. A build whose +`SetCob` returns at once after storing `table` fails the same way, so the module does not cause it. The +ABI lists as a glue error `slot : an object argument is not in the sim block`: the manifest kind of +`data` is `block` although the table is outside the block (spec section 2 states this as a kit gap, +ozgb/byte-tactics-moddable#1197). Question: has that gap been closed in the gate's manifest? Without it +`SetCob` and `CreatePlayerObjectState` cannot be played at all. + +## 13. `NewUnitScript` must write the class word of `CobScript` at offset 0 (spec says write 0) + +Spec section 4 says the module writes 0 at offset 0 of the new `UnitScript` and that "it is not one of the +fields a recording compares". With 0 there, `w Unit#2.script CobScript#2` came back as the value +`CobScript#?` (the replayer names a target by its class word). With +`class_words[5]` (`CobScript`, at `load_data` base + 20) copied into offset 0, the call passes. The ABI +(section 7.1, "The class word table") says the same: a module copies an entry into an object it makes. The +spec should say so. The module now writes it. + +## 14. The kit under the gate changed during the session + +req1 to req26 report `interfaces-v89` / `reference-traces-v59`; req27 on report `interfaces-v90` / +`reference-traces-v60`, while /data holds v89. The v90 changes are not in the kit I can read. Results +did not change between the two except `orders-factory`, which now gets past `NewUnitScript` only because +of item 13. + +## 15. What the module does meanwhile + +The module follows the v89 spec for everything else (SimRealloc in `SetCob`, the five sim events through +`RecordSimEvent`, the drop operation through `map.CanPlaceUnitFootprint`, `UpdateObjectState` on the unit +record, TURN's unsigned rotation) and equals the four recordings in my own replayer +(`tools/replay.js`, which builds the script table in the module's memory the way the spec says). Pointer +fields of the table are read as plain linear addresses. diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index 1469516..ec80a46 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -192,6 +192,7 @@ const G_FEATURES: u32 = 82543; const G_UNITS: u32 = 82775; const FEATURE_SIZE: u32 = 256; const F_OBJECT: u32 = 152; +const LOAD_DATA: u32 = 0x1010_0000; const G_SEA_LEVEL: u32 = 82559; const G_RANDOM_SEED: u32 = 48172; // CobScript @@ -290,14 +291,11 @@ fn script_value(unit: u32, which: i32, value: i32) { // ---------------------------------------------------------------- script data -/// A pointer field of a script table: a linear address, or an offset into the file. +/// A pointer field of a script table: a linear address (the code and the name arrays need not +/// lie after the record). #[inline(always)] -fn tptr(t: u32, v: u32) -> u32 { - if v >= t { - v - } else { - t + v - } +fn tptr(_t: u32, v: u32) -> u32 { + v } #[inline(always)] fn t_count(t: u32) -> i32 { @@ -1749,7 +1747,8 @@ pub extern "C" fn ObjectStateSize(model: u32) -> u32 { pub extern "C" fn NewUnitScript(unit: u32) { let sc = unsafe { sim_alloc(SCRIPT_SIZE) }; w32(unit + U_SCRIPT, off(sc)); - w32(sc, 0); + // the class word of CobScript (class_words[5]): the engine names the object by it + w32(sc, r32(LOAD_DATA + 4 * 5)); wi(sc + 4, 30); w32(sc + S_TABLE, 0); w32(sc + S_STATICS, 0); diff --git a/scripts/tools/replay.js b/scripts/tools/replay.js index 8c059a8..4fb75a9 100644 --- a/scripts/tools/replay.js +++ b/scripts/tools/replay.js @@ -14,7 +14,7 @@ const COB = (flags.find((f) => f.startsWith('--cob=')) || '--cob=ptr').slice(6); const VERBOSE = flags.includes('-v'); const BLOCK = 0x100000; -const PAGES = 4112; +const PAGES = 4128; const mem = new WebAssembly.Memory({ initial: PAGES, maximum: PAGES }); const table = new WebAssembly.Table({ element: 'anyfunc', initial: 528, maximum: 528 }); const u8 = () => new Uint8Array(mem.buffer); From 5ba7776e187cfd99518549be999dcf8e5f1ca6bf Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:13:27 +0000 Subject: [PATCH 17/30] Update: Pin the scripts spec to interfaces-v101 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 89 +++++++++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 43 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index aa6dd32..927e437 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -78,11 +78,12 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `GetAimFromPosition` | `[linear, linear, int] -> void` | | `PoseUnitModel`, `UpdateObjectState` | `[linear] -> void` | | `ObjectStateSize` | `[linear] -> int` | -| `CreateObjectState` | `[block] -> block` | +| `CreateObjectState` | `[linear] -> block` | | `FreeObjectState` | `[block] -> void` | | `NewUnitScript` | `[block] -> void` | -| `SetCob`, `SetObjectState` | `[block, block] -> void` | -| `CreatePlayerObjectState` | `[block, block, block] -> block` | +| `SetCob` | `[block, linear] -> void` | +| `SetObjectState` | `[block, block] -> void` | +| `CreatePlayerObjectState` | `[linear, linear, block] -> block` | | `RunScripts` | `[block, int] -> void` | | `DeleteScript` | `[linear] -> void` | - Imports, every one listed and nothing else: @@ -98,6 +99,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `services.SimRealloc` | `[linear, int] -> linear` | the statics and piece records of `SetCob` | | `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the five sim events of the effect command | | `services.RandomInt` | `[int] -> int` | listed by the entry; no recording calls it, and the module makes the draw of section 5 from `rng.seed` itself | +| `services.GetCobChecksum` | `[linear] -> int` | the checksum `SetCob` stores (section 2, "Arguments outside the block") | | `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | - Hooks: none. The header annotates every slot "Hooks: none". @@ -111,19 +113,25 @@ A recording carries the scheduler's own name for one of these calls: `services.S its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. -- **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41). In a recording it is written as the holder, `UnitDef#N`; the kit's replay gives - the linear address of its copy of the unit type's compiled script, outside the block. The record - there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` - at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), - the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. `names` and - the piece names are linear addresses of arrays of linear addresses of the names; `entries` is an - array of `count` indices into `code`; `code` is a linear address. The compiled data is load-time - data, which the module reads and never writes. - The file's checksum is not in the record: the reference keeps it beside the table, computed over - the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that - checksum, and its manifest kind for the argument is `block` although the table is outside the block; - both are kit gaps, raised on ozgb/byte-tactics-moddable#1197. +- **The script data** (`SetCob`, `CreatePlayerObjectState`) is a unit type's compiled script, which the + host maps into the `load_data` region (ABI 7.1) as the game holds it once loaded. The argument is + the `linear` address of its first byte, never an address inside it; in a recording it is written as + the holder, `UnitDef#N`. `CobScript.table` holds the same address once `SetCob` has run, stored as + the address and not as a block offset. A module reads the data and never writes it. The table there + is 44 bytes of 32-bit words: the format version (0), `count` (4), `pieceCount` (8), a word this + module never reads (12), `staticCount` (16) and the number of pairs (20); then five linear + addresses: `entries` (24), `names` (28), the model's piece names (32), `code` (36) and the pairs + (40). `entries` is an array of `count` indices into `code`, one per script; `names` is an array of + `count` addresses of NUL-terminated names; the piece names are an array of `pieceCount` addresses of + NUL-terminated names; `code` is an array of 32-bit words read by index, none of them an address. The + pairs are 8 bytes each, a word and an address that this module never reads. No other address in the + data is one the module may follow. + The file's checksum is not in the data and a module cannot compute it. `services.GetCobChecksum(data)` + returns it for the address `CobScript.table` holds, and `SetCob` stores it (section 4). The import is + a pure query: its answer depends on its argument alone and it changes nothing, so the gate answers it + by its argument and compares neither how many times a module asks nor where the calls fall among the + other imports (`docs/module-abi.md`, sections 9.3 and 15); a recording shows it as `i + services.GetCobChecksum UnitDef#N = `. A null argument answers 0. - **A callback** arrives as the `linear` address of an object the engine owns, 0 for none; the value a channel stores and AIM_DONE publishes is that object's block offset, 0 for none (ABI 7.1). The module converts between the two and never calls through the object. A callback object is virtual, @@ -195,7 +203,7 @@ All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and rea | Field | Offset | Meaning | | --- | --- | --- | | `scale` | 4 | ticks per second the script's speeds are divided by: 30 | -| `table` | 8 | the handle to the unit type's script data, 0 before one is set | +| `table` | 8 | the address of the unit type's script data, 0 before one is set | | `checksum` | 12 | the unit type's script-file checksum | | `statics` | 16 | `Ref`: `staticCount` words the script reads and writes | | `pieces` | 20 | `Ref`: `pieceCount` animation records | @@ -247,11 +255,10 @@ at 42, `child` at 46 and `parent` at 50, `Ref`. This subsystem reads bits 1 and 2 as the piece's `cached` and `shaded` bits; the layout's names for them are `colored` and `lit`. -**The script data handle** (section 2, "Arguments outside the block"): a handle to a unit type's -compiled script, whose record is the kit's `ScriptTable` (40 bytes: `count` at 4, `pieceCount` 8, -`staticCount` 16, `entries` 24, `names` 28, the model's piece names 32, `code` 36). The compiled -data is load-time data, which the module reads and never writes; the file's checksum is kept beside -the record. +**The script data** (section 2, "Arguments outside the block"): a unit type's compiled script, a 44-byte +table of 32-bit words (`count` at 4, `pieceCount` 8, `staticCount` 16, `entries` 24, `names` 28, the +model's piece names 32, `code` 36) in the `load_data` region. It is load data, which the module reads +and never writes; the checksum of the file it came from comes from `services.GetCobChecksum`. **List and copy rules.** A null `Ref` stores the value 0; any other stores `address - g_blockBase`. A record the slot allocates is not initialised beyond what section 4 says, so its bytes are whatever @@ -355,8 +362,8 @@ with nothing written, not even through the argument pointers, when it did not. **The bounds of the arguments.** The piece-offset rule gives (0, 0, 0) for a null unit or model state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a piece of −1. Everything else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature -index, a model with fewer vertices than a slot reads, and a script data handle that does not describe -its data are outside the contract, and a module need not check them. +index, a model with fewer vertices than a slot reads, and script data that does not describe +its own counts are outside the contract, and a module need not check them. ### `FindScript(script, name)` @@ -481,16 +488,16 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, -and each of the eight channels' `state` 0. Offset 0 holds the object's table pointer; a module writes -0 there, and it is not one of the fields a recording compares. Its other bytes are what the allocation -gives them. +and each of the eight channels' `state` 0. Offset 0 holds the `CobScript` class word: the entry named +`CobScript` (index 5, offset 0) in the class word table that starts the `load_data` region (ABI 7.1; `class_words` of +`layout.json`), copied as it is, so that the engine's slots recognise the object. Its other bytes are what +the allocation gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise, in this order: -- `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries - (section 2 states the kit gap: the kit gives a module no word for it); +- `script.checksum` becomes the result of `services.GetCobChecksum(data)` (section 2); - `script.pieces` becomes the result of `services.SimRealloc(script.pieces, pieceCount * 76)` (a null `pieces` allocates; a size of 0 frees the block and gives null); - `script.statics` becomes the result of `services.SimRealloc(script.statics, staticCount * 4)`: an extent @@ -501,7 +508,7 @@ gives them. As `CreateObjectState(model)`, with these differences: the record's `owner` becomes *owner*; and, after the pieces are added and before the links are rebuilt, the records are reordered so that record -*i* holds the object whose name matches, ignoring case, the *i*-th of the handle's `pieceCount` names: +*i* holds the object whose name matches, ignoring case, the *i*-th of the script data's `pieceCount` names: for each *i* from 0 to `pieceCount`−1, the lowest *j* from *i* to `count`−1 whose name matches is found, and when *i* differs from *j* the two 54-byte records are swapped; a name with no match moves nothing for that *i*. Then the links are rebuilt from the object graph: each record's `sibling`, @@ -764,10 +771,6 @@ module does not export it. (each step rounded to a 64-bit mantissa and then to a double, except the squares). `bx_ftol(x)`: the result is 0 when |x| < 1; otherwise the integer part of |x| truncated, its low 32 bits, negated when x is negative; a value whose exponent reaches 1023 + 63 gives 0. -- **The script-file checksum**: four bytes over the file's bytes, *a*, *b*, *c* and *d*, all starting - 0, for each byte at index *i*: *a* = (*a* + byte) mod 256, *b* = *b* xor byte, *c* = (*c* + (*i* xor - byte)) mod 256, *d* = *d* xor ((*i* + byte) mod 256). The value is (*d* << 24) | (*c* << 16) | - (*b* << 8) | *a*, as a signed 32-bit integer. - **Division and shifts**: `/` truncates toward zero on a negative result; `%` has the dividend's sign; `>>` is arithmetic on a signed value; a multiplication or addition wraps at 32 bits. Division by 0 and the most negative value divided by −1 are outside the contract. @@ -845,12 +848,14 @@ unless written with `0x`. 10. **`NewUnitScript` and `SetCob`, from `orders-air`, call at tick 1025.** `NewUnitScript(Unit#3)` allocates 1348 bytes (the import's line `services.SimAlloc 1348`) and writes Unit#3's `script` to that CobScript, `scale` 30, `table` null, `statics` null, `pieces` null, `activeCount` 0. Then - `SetCob(CobScript#3, UnitDef#21)` makes the import lines `services.SimRealloc null 608` (the pieces) + `SetCob(CobScript#3, UnitDef#21)` reads `checksum` (0 before), makes the import lines + `services.GetCobChecksum UnitDef#21 = -2122848590`, `services.SimRealloc null 608` (the pieces) and `services.SimRealloc null 16` (the statics), and writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 zero bytes (4 words) and `pieces` 608 zero bytes (8 records). -11. **The checksum of example 10.** The file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s - `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, - 0xe6, 0x77 and 0x81, and the value is 0x8177e6b2. +11. **The checksum of example 10.** The module does not compute it: `GetCobChecksum` of the address + `CobScript#3.table` will hold, the loaded script of `UnitDef#21` (its table has 19 scripts, 8 + pieces and 4 statics), answers −2122848590 (0x8177e6b2), and `SetCob` writes that answer to `checksum` + whole. In `orders-factory`, call at tick 19, the same import for `UnitDef#68` answers −938591297. 12. **`CreatePlayerObjectState`, from `orders-air`, call at tick 1025.** `CreatePlayerObjectState( UnitDef#21's model, UnitDef#21, Unit#3)` allocates 466 bytes (`services.SimAllocTagged "Object State" 466`) and the eight point lists of 600, 12, 252, 24, 252, 24, 252 and 24 bytes, in that @@ -881,14 +886,12 @@ of value 5 is recorded, its read is not), and every opcode whose effect no recor ## 8. Kit version -Kit `interfaces-v89` and `reference-traces-v59`, the versions the gate judges against. Interface `scripts` 3.0. -The imports are against `map` 9, `los_radar` 5 and `services` 4.5. +Kit `interfaces-v101` and `reference-traces-v63`, the versions the gate judges against. Interface `scripts` 3.0. +The imports are against `map` 9, `los_radar` 5 and `services` 4.6. The kit's manifest entry is `blocked`, so it has no `fuel_budget` and no `size_budget`, and the host runs the native default for every slot of it. The gate judges a module of the entry on its recordings, with no fuel or -size budget (`docs/module-abi.md`, sections 4.2 and 15). The gaps left in the kit, which the spec works around +size budget (`docs/module-abi.md`, sections 4.2 and 15). The gap left in the kit, which the spec works around (section 2): -- the file checksum of a script, which a module has no word for; -- the manifest kind of the script data handle, `block`, although the table is outside the block; - the translation of the routed effects of other interfaces into the four events `Apply` takes. From e54b8f2f1237768cf3714e92de4f9c70c52c8d43 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:16:25 +0000 Subject: [PATCH 18/30] Update: Tighten the scripts SetCob wording Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 927e437..1dd6b13 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -490,14 +490,15 @@ A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, and each of the eight channels' `state` 0. Offset 0 holds the `CobScript` class word: the entry named `CobScript` (index 5, offset 0) in the class word table that starts the `load_data` region (ABI 7.1; `class_words` of -`layout.json`), copied as it is, so that the engine's slots recognise the object. Its other bytes are what +`layout.json`), copied as it is. Its other bytes are what the allocation gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise, in this order: -- `script.checksum` becomes the result of `services.GetCobChecksum(data)` (section 2); +- `script.checksum` becomes the result of `services.GetCobChecksum(data)` (section 2; the recordings show + the call first, and the gate does not compare where it falls); - `script.pieces` becomes the result of `services.SimRealloc(script.pieces, pieceCount * 76)` (a null `pieces` allocates; a size of 0 frees the block and gives null); - `script.statics` becomes the result of `services.SimRealloc(script.statics, staticCount * 4)`: an extent @@ -848,7 +849,7 @@ unless written with `0x`. 10. **`NewUnitScript` and `SetCob`, from `orders-air`, call at tick 1025.** `NewUnitScript(Unit#3)` allocates 1348 bytes (the import's line `services.SimAlloc 1348`) and writes Unit#3's `script` to that CobScript, `scale` 30, `table` null, `statics` null, `pieces` null, `activeCount` 0. Then - `SetCob(CobScript#3, UnitDef#21)` reads `checksum` (0 before), makes the import lines + `SetCob(CobScript#3, UnitDef#21)` (`checksum` is 0 before) makes the import lines `services.GetCobChecksum UnitDef#21 = -2122848590`, `services.SimRealloc null 608` (the pieces) and `services.SimRealloc null 16` (the statics), and writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 zero bytes (4 words) and `pieces` 608 zero bytes (8 records). From 83ab74661dbf411bc0506e06851f609314f5fde8 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:35:32 +0000 Subject: [PATCH 19/30] Update: Answer the scripts phase 1 review Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 82 ++++++++++++++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 31 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 1dd6b13..849d315 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -109,9 +109,11 @@ A recording carries the scheduler's own name for one of these calls: `services.S ### Arguments outside the block -- **The event** of `Apply` is a `ScriptsEventHeader` in the module's memory, followed by the payload of - its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length - in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and +- **The event** of `Apply` is a record in the module's memory that starts with a `ScriptsEventHeader` and + continues with the fields of its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`, each + of which includes the header), and `size` is the record's length in bytes, header included: 76 for + `ScriptsStart` and 16 for the other two. Every offset this spec gives inside an event counts from the + first byte of the header. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. - **The script data** (`SetCob`, `CreatePlayerObjectState`) is a unit type's compiled script, which the host maps into the `load_data` region (ABI 7.1) as the game holds it once loaded. The argument is @@ -141,7 +143,8 @@ A recording carries the scheduler's own name for one of these calls: `services.S nodes and never loads or mirrors its file. - **`out`** (`GetPieceOffset`, `GetPiecePosition`, `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`) is a `Vec3` of three 32-bit integers in the caller's memory, written whole. - `GetPieceAngles` writes an `Angles16`: three 16-bit values, bank, heading and pitch in that order. + `GetPieceAngles` writes an `Angles16`: three 16-bit values, bank, heading and pitch in that order, bank and + pitch signed and heading unsigned (`layout.json`; a recording prints heading 0x8000 as 32768). - **Text** given to the slots (`QueryScript` and `FindScript`'s name, the names inside the script data) is NUL-terminated bytes in the caller's memory; the comparison is byte for byte, case sensitive. `Apply`'s START name is a 32-byte field that need not be terminated. @@ -178,7 +181,7 @@ starts with the interface's event header, whose `kind` the effect's kind is, and | Effect | Kind | Payload | Fields | | --- | --- | --- | --- | -| SET_YARD, to map | 164 | `MapSetYard`, 12 bytes | the unit; `open` 1 or 0 | +| SET_YARD, to map | 164 | `MapSetYard`, 12 bytes | the unit; `open`, the value the script set (any 32-bit value) | | AIM_DONE, to weapons | 263 | `WeaponsAimDone`, 16 bytes | the unit is 0; the callback; what the aim script returned | | EXPLODE_PIECE, to weapons | 264 | `WeaponsExplodePiece`, 16 bytes | the unit; the piece; the flags of the explode operation | | ATTACH_TO_PIECE, to units | 357 | `UnitsAttachToPiece`, 20 bytes | the unit; the target, 0 to detach; the target's piece, -1 when none; the mode | @@ -189,7 +192,8 @@ must be valid are: SET_YARD, a unit offset that is a unit; AIM_DONE, a callback EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's piece count; ATTACH_TO_PIECE, a unit offset that is a unit, and, when the target is not 0, a target offset that is a unit; and SCRIPT_VALUE, a unit offset that is a unit. The module publishes none that a valid script does not -produce: a null unit or a callback it never had is never published. +produce: a null unit or a callback it never had is never published. It publishes the fields as its +script gives them (a piece index, flags or a value are passed unchanged) and checks none of them. ## 3. State @@ -212,7 +216,10 @@ All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and rea | `activeCount` | 1340 | the number of channels that are not free | **`UnitScript`** (1348 bytes): `CobScript`, then `state` at 1344, `Ref`: the unit's model -state. +state. The unit that owns a script is the `owner` of this state, and "the unit" in section 4 means it. +In `layout.json` the unit's own `state` field and this one are typed with the names `SpotState` and +`ObjectState`; the record behind each is the `ModelState` below (a recording names it `ModelState#N`), +which a `SpotState` extends with fields these slots do not touch. **`Channel`** (164 bytes): @@ -307,7 +314,7 @@ an earlier one. ### `Apply(event, size)` The outcome is 0 and nothing changes when, in this order: `size` is below the 8 bytes of -`ScriptsEventHeader`; `kind` is not 416 to 419; `size` is below the kind's payload (76 bytes for +`ScriptsEventHeader`; `kind` is not 416 to 419; `size` is below the kind's record (76 bytes for START, 16 for each of the other three); the named object is null (the unit of START and DETACH_PIECE, the piece state of FREE_STATE and INIT_STATE); or, for START, `form` is not 0, 1 or 2. Otherwise the outcome is 1 and the kind's row applies: @@ -320,7 +327,7 @@ outcome is 1 and the kind's row applies: | INIT_STATE (419) | The state is set to 0 and its pieces are added from the model of `Game.features[feature].object` by the piece-state build rule of section 4, and `animDirty` becomes 1. Outcome 1. | The START forms, with *name* the event's 32-byte name copied into a 32-byte buffer that holds at most -31 of its bytes and a 0, *callback* the word at 48 of the payload as a callback, *update* the word at +31 of its bytes and a 0, *callback* the word at 48 of the event as a callback, *update* the word at 52, *count* the word at 56 and `args` the four words at 60: | Form | Effect | @@ -363,7 +370,11 @@ with nothing written, not even through the argument pointers, when it did not. state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a piece of −1. Everything else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature index, a model with fewer vertices than a slot reads, and script data that does not describe -its own counts are outside the contract, and a module need not check them. +its own counts are outside the contract, and a module need not check them. So are the faults of a +script's code: an opcode's piece, axis or statics index out of range, a stack that underflows or +overflows its 32 words, a `pc` outside `code`, and a script run while its model state is null or its +state has no owner (the operations that touch the pieces, the unit, an effect or a unit value need +both). ### `FindScript(script, name)` @@ -381,6 +392,11 @@ halves bank = `q.short_14`, heading = `q.short_12` and pitch = `q.short_10`, the (the three-angle rotation, section 5); and (`q.object.box_x + q.rot_x`, `q.object.box_y + q.rot_y`, `q.object.box_z + q.rot_z`) is added to it. The offset is then (x, y, −z) of the running point. +The nodes are read as the game holds a model once loaded, which mirrors it: the x and z of each node's box +and of each of its vertices are the negation of the file's (`docs/module-abi.md`, section 7.1, for the +vertices). A recording's `x` lines give the file's bytes, so a box read from them has the opposite x and z +of what a module reads from its copy. + ### The piece-offset rule and `GetPieceOffset(unit, piece, out)` *out* is the piece offset of *piece* (section 4). @@ -469,16 +485,16 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi **The pose rule.** The pieces are restored first: a piece whose `modified` is 0 has its `points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set -to (0,0,0) and its `modified` 0; the pieces below the root's first child are restored whatever their -`modified` (that child, its descendants and their siblings), and a piece with no parent (the root -and the model's other top-level pieces) only when its `modified` is 0. Then every piece is visited once for itself and once +to (0,0,0) and its `modified` 0. A piece is also restored, whatever its `modified`, when its parent +was restored in this pass; a piece with no parent (the root and the model's other top-level pieces) +is restored only when its `modified` is 0. Then every piece is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank `short_14`, heading `short_12` and pitch `short_10`, with the state's `pos` added first when it is the root; its delta is -`rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. A visit does not change -`modified`. +`rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. The pose leaves `modified` +as the restore left it. ### `ObjectStateSize(model)` @@ -529,8 +545,8 @@ piece animation step runs with *elapsed*. With `activeCount` 0 only the piece an The thread run of a channel and an elapsed count, with *c* the channel: 1. A channel whose state class is 0 is skipped. In the waiting class 0x02000000, the substate decides - whether the wait is over: a turn wait (0x02100000) ends when the model piece's `turnSpeed` at the - channel's `axis` is 0, a move wait (0x02200000) when its `moveSpeed` at that axis is 0, and a + whether the wait is over: a turn wait (0x02100000) ends when `turnSpeed` at the channel's `axis` of the + script's animation record `pieces[piece]` (the channel's `piece`; a `Piece`, not a model piece) is 0, a move wait (0x02200000) when that record's `moveSpeed` at that axis is 0, and a sleep (0x02400000) subtracts *elapsed* from `delay` and ends when it is 0 or less; each that ends sets the state to 0x01000000. The 0x02800000 wait has no condition here. 2. A channel whose state class is 0x01000000 runs opcodes until it stops, ends or waits. A channel @@ -626,7 +642,7 @@ second arguments. | 1 | `u.activateFlags` bit 0 | | 2 | bits 18 and 19 of `u.flags` (0 to 3) | | 3 | bits 20 and 21 of `u.flags` (0 to 3) | -| 4 | `u.health * 100 / u.maxHealth` (unsigned division; `maxHealth` 0 is outside the contract) | +| 4 | `u.health` taken as a signed 16-bit value, times 100 in 32 bits, divided by `u.maxHealth` (the unit definition's, an unsigned 32-bit value) as an unsigned division of the product read as unsigned, the result as a 32-bit value; so a negative `health` gives a large quotient; `maxHealth` 0 is outside the contract | | 5, 6 | `u.bit0`, `u.bit1` | | 7 | the piece position of piece *a*: (`v.x & 0xffff0000`) + (`v.z >> 16`), *v* being its world position | | 8 | that position's y | @@ -667,9 +683,10 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | any other | nothing recorded | The module records each row through `services.RecordSimEvent` (section 2, "Events"). The reference records a publish as an engine call of its own, which the -recordings show as a `services.SchedPublish` line; a module publishes through `Emit`, which the -engine records as the same effect, so the effect's kind and fields are what is compared, not the -import's name (ABI 7.2 and 9.3). +recordings show as a `services.SchedPublish ` line; a module publishes through `Emit`, +which the engine records as the same effect, so the replay compares the outbox and the size and not +the import's name (ABI 7.2 and 9.3), and the effect's kind and fields, as the tables of section 2 give +them, are what the receiving modules act on. **The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: @@ -694,9 +711,9 @@ sets `active` 0 and for each axis *j* 0 to 2: positive and `turnSpeed[j]` reaches or passes `spin[j]`, `turnSpeed[j]` becomes `spin[j]` and `acceleration[j]` 0; when negative and `turnSpeed[j]` reaches or passes `spin[j]`, both likewise. 3. When `turnSpeed[j]` is not 0: *r* is the model piece's rotation, *cur* = *r*, step = `elapsed × - turnSpeed[j] *r* adds step, and *want* = `turn[j]`. When *want* is not −1: for a positive speed, - when (`want − cur + 0x10000) % 0x10000 ≤ step`, *r* = *want* and `turnSpeed[j]` 0, else `active` 1; - for a negative speed, when (`cur − want + 0x10000) % 0x10000 ≤ −step`, likewise. When *want* is + turnSpeed[j]`, *r* adds step, and *want* = `turn[j]`. When *want* is not −1: for a positive speed, + when `(want − cur + 0x10000) % 0x10000 ≤ step`, *r* = *want* and `turnSpeed[j]` 0, else `active` 1; + for a negative speed, when `(cur − want + 0x10000) % 0x10000 ≤ −step`, likewise. When *want* is −1, `active` 1. The model piece's rotation becomes *r* & 0xffff (the setter of section 4). When the piece is still active after the axes, `changed` becomes 1. @@ -783,10 +800,9 @@ module does not export it. ## 6. Quirks -- **Q1: the query's words.** `QueryScript` counts its in-values in the channel's `sp`: it starts at - −1 and each value is written one word further up, so the four values land at `stack[0]` to - `stack[3]`, and `sp` is then set to 3. The word it clears is the channel's `callback`, and the - answers are read from `stack[0]` to `stack[3]`. +- **Q1: the query's words.** A query's four in-values are the words `stack[0]` to `stack[3]` of the + channel it starts, its `sp` is 3 and its `callback` is 0 when the thread first runs; the answers are + the words `stack[0]` to `stack[3]` after the run, whatever `sp` the run leaves. - **Q2: a piece of −1.** `GetPieceAngles` with *piece* −1 adds the low 16 bits of the model state's `count` to the bank, where a piece 0 or more adds its own `short_14`; its pitch and heading are the unit's alone. A *piece* below −1 is outside the contract. @@ -840,7 +856,11 @@ unless written with `0x`. (45613056, 65536, 19922944) plus the piece's offset (68155, 15285, 1092098); that offset comes from the piece-offset rule, with piece 1's own `object` box and `rot` (all `rot` 0) and then piece 0's box, its angles adding Unit#2's heading −32768 to the rotation. The boxes are the node data of - `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line). + `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line) as the loaded model holds them, + mirrored: piece 1's box is (−68155, 15285, 1092098) where the file's bytes give (68155, 15285, + −1092098), and piece 0's is (0, 0, 0). The running point starts as (−68155, 15285, 1092098), the + root's rotation by 0x8000 in heading gives (68155, 15285, −1092098), and the offset is (68155, 15285, + 1092098). 9. **`GetPieceAngles`, from `orders-air`, calls at ticks 1025, 1026 and 1027.** `GetPieceAngles( Unit#2, 1)` is (0, 32768, 0), then (0, 32950, 0), then (0, 33132, 0): Unit#2's bank and pitch are 0 and its heading is −32768 (0x8000); `pieces[1].short_10` and `pieces[1].short_14` are 0, so bank @@ -882,8 +902,8 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `UpdateObjectState`, `ObjectStateSize`, `CreateObjectState`, `DeleteScript`, `SaveScriptState`, `LoadScriptState`, `WriteState`, the DETACH_PIECE, FREE_STATE and INIT_STATE events, the START form whose name matches no script and the one whose thread cannot start, the effect command (and so all five -sim events), the drop operation, recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write -of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. +sim events), the drop operation, recording `StartScriptWithArgsByIndex`'s failure, and most unit values (the recordings read values 4 and 17, and the write +of value 5 is recorded), and every opcode whose effect no recorded thread produces. ## 8. Kit version From 2aa14ce36b44430200fdfa708bd8bbf0e33c685e Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:43:06 +0000 Subject: [PATCH 20/30] Update: Pin the scripts spec to interfaces-v102 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 849d315..b3b7464 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -193,7 +193,8 @@ EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's piece a unit offset that is a unit, and, when the target is not 0, a target offset that is a unit; and SCRIPT_VALUE, a unit offset that is a unit. The module publishes none that a valid script does not produce: a null unit or a callback it never had is never published. It publishes the fields as its -script gives them (a piece index, flags or a value are passed unchanged) and checks none of them. +script gives them (a piece index, flags or a value are passed unchanged) and checks none of them; the attach +operation's own tests of the unit and its carrier (section 4) are the exception. ## 3. State @@ -487,7 +488,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set to (0,0,0) and its `modified` 0. A piece is also restored, whatever its `modified`, when its parent was restored in this pass; a piece with no parent (the root and the model's other top-level pieces) -is restored only when its `modified` is 0. Then every piece is visited once for itself and once +is restored only when its `modified` is 0. Then every piece under the root is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank @@ -907,7 +908,9 @@ of value 5 is recorded), and every opcode whose effect no recorded thread produc ## 8. Kit version -Kit `interfaces-v101` and `reference-traces-v63`, the versions the gate judges against. Interface `scripts` 3.0. +Kit `interfaces-v102` and `reference-traces-v64`, the versions the gate judges against. Interface `scripts` 3.0. +For this subsystem they hold what `interfaces-v101` and `reference-traces-v63` hold: the headers, the manifest +entry, the ABI and the recordings of `scripts` are unchanged between them. The imports are against `map` 9, `los_radar` 5 and `services` 4.6. The kit's manifest entry is `blocked`, so it has no `fuel_budget` and no `size_budget`, and the host runs the From b543584bcabad1d1d6e6a5508bf5135461123985 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:44:47 +0000 Subject: [PATCH 21/30] Update: Read script data by address, ask the verdict Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 44 ++++----- scripts/SPEC-QUESTIONS.md | 162 ++++---------------------------- scripts/src/lib.rs | 87 ++++------------- scripts/tools/replay.js | 39 +++++++- 4 files changed, 89 insertions(+), 243 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index 5b43158..872df37 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -28,35 +28,27 @@ unit's model and checks that the posed `offset` of each piece equals the piece-offset rule, and prints the stack depth reached (about 1.1 KB of the 4 KB). -## Verdicts, in order -1. req1: `refused`, `scripts: the manifest has no size_budget` (no scenario played). -2. req2: `refused`, the same, with budgets given as extra files in the request directory. -3. req3: `refused`, the same, with more file names tried. -4. req4 (the final 29255-byte module, nothing but `module.wasm` and `subsystem`): `refused`, the same. +## Update to spec v101/v102 (this session) +- `SetCob` stores `services.GetCobChecksum(data)`; the checksum code and the relocation guesses are gone + (the table words are addresses). The entry's imports are all kept (`RandomInt`, `CanPlaceUnitFootprint` + stay imported, unused). +- Pose rule: a record is restored when it or any ancestor has `modified` 0 (walk up the parent links). +- The query, wait, unit value 4, SET_YARD and heading rules of the new spec were already as the code had them. +- `tools/replay.js` now puts each script and model in the `load_data` region of a 5136-page memory, answers + `GetCobChecksum` from the recording and checks that a call leaves the load data, the table header and the + statics/pieces alone unless a `w` line says so. All 78 calls are equal locally. -The gate never reached the module, so there is no gate verdict on its behaviour. The local replay of the -four recordings (78 calls, `--cob=ptr` and `--cob=off`) is equal except for the two `SetCob` calls of -`orders-air` and `orders-factory`, whose recorded import lists are empty while the spec (2, "The manifest -entry") says a module that allocates the two blocks adds `SimAlloc` lines; the module makes them. -The most fuel any one call of those recordings burns is 1885. +## Verdicts, in order +1. req1 (kit interfaces-v102 in the verdict): `differs` on all four recordings, call 0, `RunScripts`, + field `CobScript#1.statics`, value `0 elements`. +2. req2 (the same module with `RunScripts` returning at once): the same verdict on all four, so the cause + is not in what the slot does. Raised as question A in `SPEC-QUESTIONS.md`. ## Unclear points in the spec or kit -All are in `SPEC-QUESTIONS.md`; in short: -0. no way to give the gate the budgets (above); -1. the file checksum of `SetCob` has no input; the module rebuilds it from the table's memory (the file is - taken to start at the table's address, its length is the end of the last name, relocated words are - un-relocated by subtracting the table address); -2. whether the `ScriptTable` pointers are addresses or offsets (the module accepts either); -3. `UnitDrawView` has no layout, so `UpdateObjectState` does nothing; -4. TURN's delta uses the rotation as a signed `short`; -5. unit values 12 and 14 are masked to 16 bits unsigned; -6. the pose's restore of the other top-level pieces; -7. the order and re-run behaviour of the two allocations of `SetCob`; -8. `root` after the player state's reordering; -9. the effect command's pose (PoseUnitModel's or the update rule's); -10. the arguments of GET_UNIT_VALUE_4. -The kit has no `RecordSimEvent` import for scripts, so no sim event is recorded, and no `map` import for -the drop of a carried unit, so DROP_UNIT takes its word and does nothing (spec 2 and 4). +Question A of `SPEC-QUESTIONS.md` (above). Still true from before: `UnitDraw View` has no layout, so +`UpdateObjectState` does nothing; TURN's delta reads the rotation as a signed `short`; unit values 12 and 14 +are masked to 16 bits unsigned. The kit has no `RecordSimEvent` use here and no `map` import for the drop of a +carried unit, so DROP_UNIT takes its word and does nothing. # wind_meteors implementation notes (an earlier task) diff --git a/scripts/SPEC-QUESTIONS.md b/scripts/SPEC-QUESTIONS.md index 14fbf8f..aa3108b 100644 --- a/scripts/SPEC-QUESTIONS.md +++ b/scripts/SPEC-QUESTIONS.md @@ -1,146 +1,20 @@ # Spec questions for `scripts` -Each item says what the spec leaves open, the evidence, and what the module does meanwhile. - -## 0. The gate cannot judge this module: the manifest it holds has no budgets - -Every submission (req1, req2, req3) came back at once, in 0 seconds, as -`{"verdict": "refused", "message": "scripts: the manifest has no size_budget"}`, before any scenario or -recording was played. The kit's `wasm/modules.json` gives `fuel_budget` and `size_budget` to -`wind_meteors` alone (250 and 13100); the entry of `scripts` has neither (spec section 2: "the build -picks them"), and so has no other subsystem's. The mailbox takes `module.wasm` and `subsystem` and -nothing else is documented, so the budgets cannot be given to the gate. req2 and req3 added the same -two numbers as files (`fuel_budget`, `size_budget`, `budgets.json`, `manifest.json`, `entry.json`, -`modules.json`, `wasm/modules.json`, `gate.toml`) and the verdict did not change. -Question: how does a build give the gate its `fuel_budget` and `size_budget`, or does the gate's -manifest get them? Until that is answered no verdict on this module's behaviour exists; the module -meets the surface (`wasm_fuel.py --check`, 29255 bytes, imports and exports as the entry lists) and -equals every call of the four recordings but the two `SetCob` import lists the spec names as a kit -gap (see IMPLEMENTATION-NOTES.md). - -## 1. The script-file checksum has no input (`SetCob`, spec 2 "Arguments outside the block", 4, 5) - -The spec says the kit gives a module no file bytes and no checksum word at `SetCob`. The module cannot -be exact from the spec alone. Evidence: the recordings' `load cob` lines carry the file bytes, and the -file's length is the end of its last piece name (all 7 files of the kit: ARMCOM 7890, CORCOM 8741, ARMAP -5592, ARMATLAS 3846, CORMEX 1924, CORWIN 2047, ARMLAB 6403), so the length can be recovered from the -table. What the module does: it takes the file to start at the table's address (the record's first word -is the file's first word, `count` at 4, `pieceCount` at 8, as in the header of the files), recovers the -length from the names, undoes the relocation of the header words and the two name arrays (a word at or -above the table address has the address taken off), and runs section 5's formula. Whether the loader -relocates in place, which words it changes, and whether the bytes after the header are untouched is not -stated. Question: does `SetCob` get the file's bytes (or its checksum, or its length) some other way? - -## 2. Pointers inside `ScriptTable` (spec 2, 3) - -The spec gives `entries`, `names`, the piece names and `code` as fields of the record but not whether each -is a linear address, a file offset, or (for `names` and the piece names) an array of such. The module -accepts either (a value at or above the table's own address is an address, a smaller one an offset from -it) and reads `names` and the piece names as arrays of one word per name, `entries` as indices. - -## 3. `UnitDrawView` (`UpdateObjectState`, spec 4 "The update rule") - -`UnitDrawView` is not in `layout.json` or any header of the kit, so "the view's model state" and "the -view's angles" have no offsets. `UpdateObjectState` is exported and does nothing. - -## 4. Sign of the rotation in TURN's delta - -TURN's delta is "`turn[axis]` minus the model piece's rotation" with the rotation a `short` -(`layout.json`); the module sign-extends it. If the original read it as unsigned, a rotation of 0x8000 or -more gives another delta and, from `|delta| > 0x8000`, another direction. - -## 5. Unit values 12 and 14 "wrapped to 16 bits" - -Signed or unsigned is not stated; the module masks to 0..65535. - -## 6. The pose's restore of other top-level pieces (spec 4, pose rule) - -"The pieces below the root's first child are restored whatever their `modified`" is read as: every -record that has a parent is restored unconditionally; a record with no parent (the root and its -siblings) only when its `modified` is 0. - -## 7. `SetCob` allocation order and re-run - -Section 4 lists `pieces` before `statics`, so the module allocates in that order (this decides the block -addresses of the two). A script that already has a `pieces` block frees it and allocates anew; one that -has `statics` allocates the new block, copies the old extent and frees the old one. The kit has no -reallocation service. - -## 8. `CreatePlayerObjectState` and `root` - -After the records are swapped into the name order, the spec rebuilds `sibling`, `child` and `parent` but -does not say what `root` becomes. The module leaves it as the first record. `Object3do` has no `parent` -field, so the parent link is the record whose object has the node in its child chain. - -## 9. The effect command's pose (spec 4, "The effect command") - -The kit's replay notes say `UpdateObjectState` is "called by the renderer and by a script's -sound-and-smoke effect"; the spec's effect command says "the model is posed (section 4)". The module -poses as `PoseUnitModel` does (the unit's angles into `pos`, always posed). If the original goes -through the update rule (pose only when the angles are 8 or more away from `pos` or `animDirty` is -set, and `cacheDrawCount` cleared for a coloured root), the model state differs after an effect that -is visible to the player and whose unit turned by less than 8. - -## 10. Names of the unit-value arguments of GET_UNIT_VALUE_4 - -The spec's opcode row takes "*a*, *b*, *d*, *e*, *f*" (no *c*). The module pops five words in that -order and uses the fifth as the number, the fourth and third as the first and second argument. - -# Second session (kit interfaces-v89, then v90 from req27; the gate now plays the recordings) - -Item 0 above is answered: the gate no longer refuses; it plays the four recordings. Nothing below is a guess: -each fact comes from a verdict (req1 to req31; req3 to req26 and req28 to req31 are probe builds, see -IMPLEMENTATION-NOTES.md for how they read the memory: a probe writes a number into `CobScript.activeCount` -and the verdict prints it as `value`). - -## 11. The compiled script data (`ScriptTable`) is not in the module's memory (blocks every call that runs code) - -Spec section 2 ("Arguments outside the block") says the handle is the linear address of the kit's copy of the -unit type's compiled script. In a `RunScripts` call the field `CobScript.table` holds 1919240 (0x1d4b88) in -all four recordings (the same unit type, `ARMCOM`, so the same value). The memory there is zero: `count` -(offset 4), `names` (28) and `code` (36) read 0, and a scan of the 64 words around it finds no non-zero word. -Scans for the header of `ARMCOM.COB` (`count` 20 at 4, `pieceCount` 14 at 8, `staticCount` 4 at 16, word 4 at 0) -over 0x0..0x100000, the whole block (0x100000..0x10100000) and the whole load data region -(0x10100000..0x14100000) find nothing. The load data holds only the class word table and the models -(its last non-zero word is at word 48 in `console-iwin`, 4490 in `orders-air`). `UnitDef#34.data` is 0. -So 1919240 looks like a native address of the replayer's own heap, not a copy in the shared memory. The -effect: every thread run reads `code` and finds 0, so a thread ends at its first step (`activeCount` -falls where the recording keeps it), `Apply`'s START finds no script name, and `SetCob` and -`CreatePlayerObjectState` have no names or counts to read. The verdicts show it: `console-iwin` call 1, -`orders-air` call 0 and `orders-move-attack` call 1 differ only because of code that cannot be read. -Question: is the cob load mapped into the load data (as models are) in the gate? Which field or argument -holds its address? - -## 12. `SetCob` ends in a glue failure before the module's code runs - -With the class word of item 13 written, `orders-factory` passes `NewUnitScript` (call 1) and then fails -at `SetCob` (call 2) as `{"class": "glue", "reason": "module-trap", "status": "failed"}`. A build whose -`SetCob` returns at once after storing `table` fails the same way, so the module does not cause it. The -ABI lists as a glue error `slot : an object argument is not in the sim block`: the manifest kind of -`data` is `block` although the table is outside the block (spec section 2 states this as a kit gap, -ozgb/byte-tactics-moddable#1197). Question: has that gap been closed in the gate's manifest? Without it -`SetCob` and `CreatePlayerObjectState` cannot be played at all. - -## 13. `NewUnitScript` must write the class word of `CobScript` at offset 0 (spec says write 0) - -Spec section 4 says the module writes 0 at offset 0 of the new `UnitScript` and that "it is not one of the -fields a recording compares". With 0 there, `w Unit#2.script CobScript#2` came back as the value -`CobScript#?` (the replayer names a target by its class word). With -`class_words[5]` (`CobScript`, at `load_data` base + 20) copied into offset 0, the call passes. The ABI -(section 7.1, "The class word table") says the same: a module copies an entry into an object it makes. The -spec should say so. The module now writes it. - -## 14. The kit under the gate changed during the session - -req1 to req26 report `interfaces-v89` / `reference-traces-v59`; req27 on report `interfaces-v90` / -`reference-traces-v60`, while /data holds v89. The v90 changes are not in the kit I can read. Results -did not change between the two except `orders-factory`, which now gets past `NewUnitScript` only because -of item 13. - -## 15. What the module does meanwhile - -The module follows the v89 spec for everything else (SimRealloc in `SetCob`, the five sim events through -`RecordSimEvent`, the drop operation through `map.CanPlaceUnitFootprint`, `UpdateObjectState` on the unit -record, TURN's unsigned rotation) and equals the four recordings in my own replayer -(`tools/replay.js`, which builds the script table in the module's memory the way the spec says). Pointer -fields of the table are read as plain linear addresses. +Questions 0 to 2 and the checksum question of the old kit are answered by the spec and the kit of interfaces-v101 +(the budgets are not needed for a blocked entry, the checksum is `services.GetCobChecksum`, the table pointers +are addresses). What is open: + +## A. Every recording differs before the module runs (verdict req1 and req2) + +req1 (the module of this branch) and req2 (the same module with `RunScripts` returning at once) got the same +verdict: `differs` on all four recordings at call 0, phase `RunScripts`, field `CobScript#1.statics`, +value `0 elements` (kit in the verdict: interfaces-v102, reference-traces-v64; the kit I hold is v101/v63). +The recorded call is `r CobScript#1.table UnitDef#34`, then `r CobScript#1.statics [16] 0:...`; the schema +gives `statics` the length `table->staticCount*4`, and the file's `staticCount` is 4. A module that does +nothing in the slot changes nothing the call reads, so the verdict does not depend on what my `RunScripts` +does. My local replayer (`tools/replay.js`, which puts each script in the `load_data` region as the +format's "A script in the memory of a WASM module" says) is equal on all calls of the four recordings. +Question: is the length of `statics` (and `pieces`) read from the copy of the script in the module's memory, +and could the replayer's copy of the table (header words at 4, 8, 16) differ from what `docs/module-abi.md` +7.1 lists (44-byte table, `staticCount` at 16) in v102? What does `0 elements` mean here: the replayed +array's length, or the recorded one? diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index ec80a46..669b30a 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -33,6 +33,8 @@ extern "C" { fn record_sim_event(kind: u32, flags: u32, args: *const u32, count: u32); #[link_name = "RandomInt"] fn random_int(n: i32) -> i32; + #[link_name = "GetCobChecksum"] + fn get_cob_checksum(data: u32) -> i32; #[link_name = "Emit"] fn emit(effect: *const u32, size: i32); } @@ -338,74 +340,6 @@ fn find_script_in(t: u32, name: u32) -> i32 { -1 } -/// The checksum of the script file the table was loaded from. -fn cob_checksum(t: u32) -> i32 { - let un = |w: u32| if w >= t { w - t } else { w }; - let cnt = t_count(t) as u32; - let pcnt = t_pieces(t) as u32; - let names = un(r32(t + 28)); - let pnames = un(r32(t + 32)); - let mut len = 44u32; - let mut i = 0; - while i < cnt { - let e = strend(t + un(r32(t + names + 4 * i))); - if e - t > len { - len = e - t; - } - i += 1; - } - i = 0; - while i < pcnt { - let e = strend(t + un(r32(t + pnames + 4 * i))); - if e - t > len { - len = e - t; - } - i += 1; - } - let (mut a, mut b, mut c, mut d) = (0u32, 0u32, 0u32, 0u32); - let mut i = 0u32; - // one word at a time (the four bytes of a word are all relocated or none is), four words a pass - macro_rules! word { - ($w:expr) => {{ - let w = $w; - let fix = w < 44 || (w >= names && w < names + 4 * cnt) || (w >= pnames && w < pnames + 4 * pcnt); - let v = if fix { un(r32(t + w)) } else { r32(t + w) }; - macro_rules! byte { - ($k:expr) => {{ - let byte = (v >> (8 * $k)) & 255; - let n = w + $k; - a = (a + byte) & 255; - b ^= byte; - c = (c + (n ^ byte)) & 255; - d ^= (n + byte) & 255; - }}; - } - byte!(0); - byte!(1); - byte!(2); - byte!(3); - }}; - } - while i + 16 <= len { - word!(i); - word!(i + 4); - word!(i + 8); - word!(i + 12); - i += 16; - } - while i < len { - let w = i & !3; - let fix = w < 44 || (w >= names && w < names + 4 * cnt) || (w >= pnames && w < pnames + 4 * pcnt); - let byte = if fix { (un(r32(t + w)) >> (8 * (i & 3))) as u8 } else { r8(t + i) } as u32; - a = (a + byte) & 255; - b ^= byte; - c = (c + (i ^ byte)) & 255; - d ^= (i + byte) & 255; - i += 1; - } - ((d << 24) | (c << 16) | (b << 8) | a) as i32 -} - // ---------------------------------------------------------------- model pieces #[inline(always)] @@ -507,7 +441,20 @@ fn pose_model(state: u32, tc: &mut TrigCache) { let mut i = 0; while i < n { let m = mp(state, i); - if r32(m + MP_PARENT) != 0 || rs(m + MP_MODIFIED) == 0 { + // restored when it or an ancestor (restored in this pass) has `modified` 0 + let mut a = m; + let mut restore = false; + loop { + if rs(a + MP_MODIFIED) == 0 { + restore = true; + break; + } + a = rf(a + MP_PARENT); + if a == 0 { + break; + } + } + if restore { let o = mobj(m); let vc = r32(o + O_VERTEX_COUNT); copy(rf(m + MP_POINTS), r32(o + O_VERTICES), vc.wrapping_mul(12)); @@ -1768,7 +1715,7 @@ pub extern "C" fn SetCob(script: u32, data: u32) { if data == 0 { return; } - wi(script + S_CHECKSUM, cob_checksum(data)); + wi(script + S_CHECKSUM, unsafe { get_cob_checksum(data) }); let psize = (t_pieces(data) as u32).wrapping_mul(P_SIZE); let p = unsafe { sim_realloc(rf(script + S_PIECES), psize) }; w32(script + S_PIECES, off(p)); diff --git a/scripts/tools/replay.js b/scripts/tools/replay.js index 4fb75a9..7a2d8fd 100644 --- a/scripts/tools/replay.js +++ b/scripts/tools/replay.js @@ -14,7 +14,7 @@ const COB = (flags.find((f) => f.startsWith('--cob=')) || '--cob=ptr').slice(6); const VERBOSE = flags.includes('-v'); const BLOCK = 0x100000; -const PAGES = 4128; +const PAGES = 5136; const mem = new WebAssembly.Memory({ initial: PAGES, maximum: PAGES }); const table = new WebAssembly.Table({ element: 'anyfunc', initial: 528, maximum: 528 }); const u8 = () => new Uint8Array(mem.buffer); @@ -80,8 +80,10 @@ function relocModel(base, off, mirrored) { if (!o) break; } } +let loadTop = 269484032 + 4 * 64; function installLoad(kind, holder, bytes) { - const base = alloc(bytes.length + 64); + const base = (loadTop + 15) & ~15; + loadTop = base + bytes.length + 64; u8().set(bytes, base); if (kind === 'cob') { if (COB === 'ptr') { @@ -348,6 +350,11 @@ const imports = { callLog.push(['RecordSimEvent', kind, words]); }, RandomInt: (n) => 0, + GetCobChecksum: (p) => { + if (!p) return 0; + for (const [h, v] of loads.cob) if (v.base === p) return checksums.get(h) | 0; + throw new Error('GetCobChecksum of an unknown address ' + p); + }, SimFree: (p) => { callLog.push(['SimFree', p]); }, Emit: (p, n) => { const words = []; @@ -359,6 +366,8 @@ const imports = { los_radar: { IsUnitVisibleToPlayer: (a, b) => 1 }, }; let callLog = []; +const checksums = new Map(); +for (const l of text) { const m = /^\s+i services\.GetCobChecksum (\S+) = (-?\d+)$/.exec(l); if (m) checksums.set(m[1], +m[2]); } const inst = new WebAssembly.Instance(new WebAssembly.Module(wasm), imports).exports; const gl = (n) => inst[n].value; function setWords() { @@ -406,6 +415,14 @@ function runCall(c, idx) { const sp = r.indexOf(' '); setField(r.slice(0, sp), r.slice(sp + 1)); } + const snap = new Map(); + const hdrSnap = new Map(); + if (c.slot === 'RunScripts') for (const [n, o] of names) if (n.startsWith('CobScript#')) hdrSnap.set(n, Buffer.from(Buffer.from(mem.buffer, o.addr, 1348))); + if (c.slot === 'RunScripts') for (const [n, o] of names) if (n.startsWith('CobScript#')) { + const take = (f, len) => { const r = rdu32(o.addr + f); return r ? Buffer.from(Buffer.from(mem.buffer, deref(r), len)) : null; }; + snap.set(n, [take(16, 64), take(20, 1344), rdu32(o.addr + 16), rdu32(o.addr + 20)]); + } + const loadSnap = Buffer.from(Buffer.from(mem.buffer, 269484032, loadTop - 269484032)); const errs = []; const ptrArg = (v) => (v === 'null' ? 0 : obj(v)); let result; @@ -464,6 +481,22 @@ function runCall(c, idx) { } default: throw new Error('slot ' + c.slot); } + for (const [n] of snap) { + const o = names.get(n).addr; + const now = Buffer.from(mem.buffer, o, 1348); + const pre = hdrSnap.get(n); + const d = []; + for (let k = 0; k < 28; k++) if (now[k] !== pre[k]) d.push(k); + if (d.length) errs.push(n + ' header bytes changed at ' + d); + } + for (const [n, [st, pc, sp, pp]] of snap) { + const o = names.get(n).addr; + if (rdu32(o + 16) !== sp || rdu32(o + 20) !== pp) errs.push(n + ': statics/pieces ref changed'); + const now = (f, len) => (rdu32(o + f) ? Buffer.from(mem.buffer, deref(rdu32(o + f)), len) : null); + if (st && W.every((w) => !w.includes(n + '.statics')) && !now(16, 64).equals(st)) errs.push(n + ': statics bytes changed'); + if (pc && W.every((w) => !w.includes(n + '.pieces')) && !now(20, 1344).equals(pc)) errs.push(n + ': pieces bytes changed (no w line)'); + } + { const now = Buffer.from(mem.buffer, 269484032, loadSnap.length); for (let k = 0; k < now.length; k++) if (now[k] !== loadSnap[k]) { errs.push('load data written at +' + k); break; } } // results for (const o of O) { const sp = o.indexOf(' '); @@ -487,7 +520,7 @@ function runCall(c, idx) { const gotImports = callLog.filter((x) => x[0] !== 'Emit' && x[0] !== 'RecordSimEvent'); const publishes = callLog.filter((x) => x[0] === 'Emit'); const wantPub = I.filter((s) => s.startsWith('services.SchedPublish')); - const wantAlloc = I.filter((s) => !s.startsWith('services.SchedPublish')); + const wantAlloc = I.filter((s) => !s.startsWith('services.SchedPublish') && !s.startsWith('services.GetCobChecksum')); if (wantAlloc.length !== gotImports.length) errs.push(`imports: want ${wantAlloc.length} got ${gotImports.length} ${JSON.stringify(gotImports)}`); else { wantAlloc.forEach((s, k) => { From a690493d3dfa1e36eb27616c5073bd333eacf6d1 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:51:51 +0000 Subject: [PATCH 22/30] Docs: Record the equal verdict Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 4 ++++ scripts/SPEC-QUESTIONS.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index 872df37..25eadd4 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -44,6 +44,10 @@ 2. req2 (the same module with `RunScripts` returning at once): the same verdict on all four, so the cause is not in what the slot does. Raised as question A in `SPEC-QUESTIONS.md`. +3. Session 2, after merging main and spec-scripts (kit interfaces-v102, reference-traces-v64): req1 `equal` on all four + recordings (module 30143 bytes). The old `CobScript#N.statics` verdicts came from the gate's length bug, now fixed; + question A is resolved. + ## Unclear points in the spec or kit Question A of `SPEC-QUESTIONS.md` (above). Still true from before: `UnitDraw View` has no layout, so `UpdateObjectState` does nothing; TURN's delta reads the rotation as a signed `short`; unit values 12 and 14 diff --git a/scripts/SPEC-QUESTIONS.md b/scripts/SPEC-QUESTIONS.md index aa3108b..7eed50c 100644 --- a/scripts/SPEC-QUESTIONS.md +++ b/scripts/SPEC-QUESTIONS.md @@ -4,7 +4,7 @@ Questions 0 to 2 and the checksum question of the old kit are answered by the sp (the budgets are not needed for a blocked entry, the checksum is `services.GetCobChecksum`, the table pointers are addresses). What is open: -## A. Every recording differs before the module runs (verdict req1 and req2) +## A. (RESOLVED: the gate's length reading was fixed; req1 of the new session is `equal`) Every recording differs before the module runs (verdict req1 and req2) req1 (the module of this branch) and req2 (the same module with `RunScripts` returning at once) got the same verdict: `differs` on all four recordings at call 0, phase `RunScripts`, field `CobScript#1.statics`, From 9cdacffe5d85393f1fec925ce5138d33a3675897 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:59:31 +0000 Subject: [PATCH 23/30] Update: Answer scripts review round 1 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index b3b7464..0a6b6af 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -98,7 +98,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `services.SimFree` | `[linear] -> void` | freeing them again | | `services.SimRealloc` | `[linear, int] -> linear` | the statics and piece records of `SetCob` | | `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the five sim events of the effect command | -| `services.RandomInt` | `[int] -> int` | listed by the entry; no recording calls it, and the module makes the draw of section 5 from `rng.seed` itself | +| `services.RandomInt` | `[int] -> int` | listed by the entry; no recording calls it, and the module makes every draw of section 5 from `rng.seed` itself, a range below 2 included, so the draw never calls it; how the module keeps the listed import in its import section is its own affair | | `services.GetCobChecksum` | `[linear] -> int` | the checksum `SetCob` stores (section 2, "Arguments outside the block") | | `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | @@ -372,7 +372,7 @@ state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a p else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature index, a model with fewer vertices than a slot reads, and script data that does not describe its own counts are outside the contract, and a module need not check them. So are the faults of a -script's code: an opcode's piece, axis or statics index out of range, a stack that underflows or +script's code: an opcode's piece, axis or statics index out of range (EXPLODE_PIECE's and the effect command's piece included: whether the module publishes or drops one outside the model's piece count is not judged), a stack that underflows or overflows its 32 words, a `pc` outside `code`, and a script run while its model state is null or its state has no owner (the operations that touch the pieces, the unit, an effect or a unit value need both). @@ -488,7 +488,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set to (0,0,0) and its `modified` 0. A piece is also restored, whatever its `modified`, when its parent was restored in this pass; a piece with no parent (the root and the model's other top-level pieces) -is restored only when its `modified` is 0. Then every piece under the root is visited once for itself and once +is restored only when its `modified` is 0. Equivalently, a piece is restored when it or any of its ancestors has `modified` 0 when the pass begins, whatever order the pass takes the records in. Then every piece under the root is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank @@ -694,7 +694,7 @@ when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. **The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and -this unit is its carrier: when `map.CanPlaceUnitFootprint` with the unit's `def` (as a block offset), the +this unit is its carrier: when `map.CanPlaceUnitFootprint` with the address of the unit's `def` (a `block` argument: `g_blockBase` plus the offset the unit's `def` holds), the unit's `id` as a 16-bit value, the address of a copy of the unit's `cell` (a `Point16`, two 16-bit values) in the module's own memory and the flags 1 returns a value that is not 0, ATTACH_TO_PIECE is published with it, target 0, piece −1, mode 1. No recording reaches this operation. From 38638e7dc4c3eac3cc44dbdd93ea422d08ba264d Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:04:53 +0000 Subject: [PATCH 24/30] Fix: Answer review, keep RandomInt by pointer Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 79 +++++---------------------------- scripts/SPEC-QUESTIONS.md | 19 +------- scripts/src/lib.rs | 16 ++----- 3 files changed, 15 insertions(+), 99 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index 25eadd4..e55ba37 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -36,7 +36,7 @@ - The query, wait, unit value 4, SET_YARD and heading rules of the new spec were already as the code had them. - `tools/replay.js` now puts each script and model in the `load_data` region of a 5136-page memory, answers `GetCobChecksum` from the recording and checks that a call leaves the load data, the table header and the - statics/pieces alone unless a `w` line says so. All 78 calls are equal locally. + statics/pieces alone unless a `w` line says so. Locally 74 of 78 calls are equal; the other 4 are RunScripts calls flagged by my own extra check (a hash of a fixed 64 bytes of statics / 1344 bytes of pieces, not the real extent), which the gate judged `equal`. ## Verdicts, in order 1. req1 (kit interfaces-v102 in the verdict): `differs` on all four recordings, call 0, `RunScripts`, @@ -52,73 +52,14 @@ Question A of `SPEC-QUESTIONS.md` (above). Still true from before: `UnitDraw View` has no layout, so `UpdateObjectState` does nothing; TURN's delta reads the rotation as a signed `short`; unit values 12 and 14 are masked to 16 bits unsigned. The kit has no `RecordSimEvent` use here and no `map` import for the drop of a -carried unit, so DROP_UNIT takes its word and does nothing. +carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the address of the unit's `def`. -# wind_meteors implementation notes (an earlier task) +## Review round 1 (this session) +- `RandomInt` is kept by a never-called function pointer in a static (read volatile), not by a call in `draw`. +- DROP: `CanPlaceUnitFootprint` gets the address of `def` (block base + offset), as spec v102 says. +- EXPLODE_PIECE/effect piece range: spec now says it is not judged; left as is. Pose rule: the spec now says + "equivalently, any ancestor with modified 0 at the start of the pass"; kept. `strend` removed. +- INIT_STATE with a null feature model: feature index outside the contract; left. +- The wind_meteors notes that were mixed into this file are removed. -## What was built -`wind_meteors/` is a `no_std` Rust cdylib (`src/lib.rs`) built by `wind_meteors/build.sh`: -- `ld-wrap.sh` is the linker wrapper. rustc passes `--stack-first` and `--allow-undefined`, which the ABI forbids, so the wrapper removes them. The `__heap_base` and `__data_end` exports are removed the same way. -- `fuel.py` is the fuel pass (ABI 11, rule v1). It works on the `wasm-tools print` text: it inserts the decrement at every function entry and loop top, then adds the counter global, `__fuel_set` and `__fuel_get`. -- Link options: data base 196608, table base 48, stack 4096. -- Flags: `target-cpu=mvp` plus sign-ext and bulk-memory, so no non-trapping float conversions. `d2i` does the guarded double-to-int conversion by hand. -- Every helper is `#[inline(always)]`, to keep the fuel use of a tick small against the 250 budget. -- Block fields are packed (unaligned), so all accesses are unaligned loads and stores at the offsets in `layout.json`. -- The sine table is a 512-entry `static` generated from the spec formula. -- `EmptyShutdownPreCleanup` volatile-reads a static function-pointer table. That keeps the `env.__indirect_function_table` import, which ABI 9.1 requires, and it is the element segment at table base 48. -- The module is 6850 bytes against a 13100 budget. - -## Update to spec v59 / kit interfaces-v59 (wind_meteors 3.1) -- `UpdateWind(stream)` is one slot now; `Apply(event, size)` replaces the Enable/Disable/SetMeteorParams/CmdMeteor entry points (kinds 64-69, size checks per the spec). -- A meteor is published with `services.Emit` (a 36-byte SPAWN effect, weapon as a slot in `Game.weapons`, -1 for none) instead of `weapons.SpawnProjectile`. The `CommandArgs_GetIntArg` import is gone. -- `SimGlobals` meteor offsets moved down by 4 bytes (checked in `layout.json`); `Game` offsets are unchanged. -- `d2i` now follows the spec: truncate to 64 bits and keep the low 32; NaN, infinity or 2^63 and above gives 0 (the old one gave 0x80000000 on overflow). - -## Verdicts, in order -1. req1: `equal` (3 recordings, every scenario, digest and view). - -2. req2, req3: no verdict. The gate answered at once with `the gate wrote no usable result (exit 2): No such file or directory: .../gate/reqN/out/result.json`. The module submitted is byte-identical to req1's (6850 bytes), so this is a gate fault, not a difference. -3. req4 (after the review answers, same 6850-byte module): `equal` (3 recordings, every scenario). - -## Answers to /srv/inbox/review.md -- 1 (`--no-stack-first`): `ld-wrap.sh` now appends `--no-stack-first` when the linker's help lists it. The local LLD 20.1.8 doesn't, and rejects it, so it's left off there and the stack falls after the data (top 202176, in the window). Not verifiable against 22.1.8 here. -- 2 (`EmptyShutdownPreCleanup`): kept. The volatile read keeps the table import and element segment ABI 9.1 requires; commented in the source. Unobservable. -- 3 (unterminated name): the spec calls it undefined; the copy is bounded at 32 bytes. Kept. -- 4 (weapon slot range): the spec says it never happens in a match. No guard. -- 5-8: nits, left. The dead `return` and spare NUL in `BAD` are harmless; `d2i` guards follow spec 5; the size-guarded arms are correct. -- 9: `fuel.py` and `build.sh` now use temporary directories and the unused `ng` is gone. - -## Unclear points in the spec or kit -- ABI 3.1 says `--no-stack-first`; this toolchain's linker default already puts the stack after the data, so the option is not passed. rustc's `--stack-first` is removed by the linker wrapper. The stack top (202176) lies inside the window. -- `fuel.py` is my own pass (the kit now has `tools/wasm_fuel.py`; its `--check` accepts the module). -- `SaveMeteors`, `LoadMeteors`, `FatalError` and the Q3 outcomes follow the spec text only; no recording has them. -- The header's DISABLE comment ("drops no meteor") reads differently from spec Q4 (a due shower starts and is then made inactive); the module follows the spec and was equal. - -## Second session (kit interfaces-v89, v90 from req27) - -Changes: the merge of `main` and `spec-scripts`; imports now `map.CanPlaceUnitFootprint`, `services.SimRealloc`, -`RecordSimEvent`, `RandomInt` (kept alive by a branch on `i32::MIN`, a range no recording draws) beside the old -ones, as the entry lists; `SetCob` uses `SimRealloc` (pieces, then statics, new statics extent zeroed, pieces -zeroed); the effect command updates the model by the update rule and records THRUST/WAKE/BUBBLES/WHITE_SMOKE/ -BLACK_SMOKE through `RecordSimEvent`; DROP_UNIT calls `CanPlaceUnitFootprint` (flags 1, a copy of the cell); -`UpdateObjectState(view)` runs the update rule on the unit record (model state at 158, angles at 100); TURN's -rotation is unsigned; `CreatePlayerObjectState` sets `root`; `NewUnitScript` copies the `CobScript` class word -(`class_words[5]`, load data base + 20) into offset 0; table pointers are plain linear addresses. -`tools/replay.js` knows the new imports and a memory big enough for the class table; my replayer is equal on all -40+8+20+10 calls of the four recordings. - -Verdicts, in order (all `differs`, a gate that plays the recordings): -1. req1 (first build): console-iwin call 1 `CobScript#2.activeCount`, orders-air call 0 `CobScript#1.activeCount`, - orders-factory call 1 `Unit#2.script` (`CobScript#?`), orders-move-attack call 1 `CobScript#1.statics`. -2. req2 (table pointers as plain addresses): the same four. -3. req3 to req26, req28 to req31: probe builds (a number written into `activeCount`, `Unit.script` variants, a - no-op `SetCob`). They showed that the script table is not in the memory (SPEC-QUESTIONS 11), that the class - word is needed (13) and that `SetCob` is refused by the glue (12). req13 and req29 were my own mistakes (a - scan past the memory end: `failed`; a build without the `SimRealloc` import: `refused`). -4. req27 (class word written, kit v90): orders-factory now fails at `SetCob` as a glue `failed`; the others as before. -5. req32 (the final module): the same as req27. - -The module is therefore blocked on the questions 11 and 12 of SPEC-QUESTIONS.md: the gate does not give the module -the script data, so no recording that runs a thread, starts a script or reads a script table can be equal. -Unclear in the spec or kit besides: the spec's "writes 0 at offset 0" of `NewUnitScript` (13), the kit moving to -v90 during the session (14), and the file checksum of `SetCob` (1 above), which could not be tested. +4. Session 3 (merged main and spec-scripts, review fixes): req1 `equal` on all four recordings (module 30162 bytes). diff --git a/scripts/SPEC-QUESTIONS.md b/scripts/SPEC-QUESTIONS.md index 7eed50c..27dda96 100644 --- a/scripts/SPEC-QUESTIONS.md +++ b/scripts/SPEC-QUESTIONS.md @@ -1,20 +1,3 @@ # Spec questions for `scripts` -Questions 0 to 2 and the checksum question of the old kit are answered by the spec and the kit of interfaces-v101 -(the budgets are not needed for a blocked entry, the checksum is `services.GetCobChecksum`, the table pointers -are addresses). What is open: - -## A. (RESOLVED: the gate's length reading was fixed; req1 of the new session is `equal`) Every recording differs before the module runs (verdict req1 and req2) - -req1 (the module of this branch) and req2 (the same module with `RunScripts` returning at once) got the same -verdict: `differs` on all four recordings at call 0, phase `RunScripts`, field `CobScript#1.statics`, -value `0 elements` (kit in the verdict: interfaces-v102, reference-traces-v64; the kit I hold is v101/v63). -The recorded call is `r CobScript#1.table UnitDef#34`, then `r CobScript#1.statics [16] 0:...`; the schema -gives `statics` the length `table->staticCount*4`, and the file's `staticCount` is 4. A module that does -nothing in the slot changes nothing the call reads, so the verdict does not depend on what my `RunScripts` -does. My local replayer (`tools/replay.js`, which puts each script in the `load_data` region as the -format's "A script in the memory of a WASM module" says) is equal on all calls of the four recordings. -Question: is the length of `statics` (and `pieces`) read from the copy of the script in the module's memory, -and could the replayer's copy of the table (header words at 4, 8, 16) differ from what `docs/module-abi.md` -7.1 lists (44-byte table, `staticCount` at 16) in v102? What does `0 elements` mean here: the replayed -array's length, or the recorded one? +None open. (Question A, every recording differing on `CobScript#1.statics`, was the gate's length bug and is resolved.) diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index 669b30a..f57287f 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -158,13 +158,6 @@ fn streq_ci(a: u32, b: u32) -> bool { i += 1; } } -fn strend(a: u32) -> u32 { - let mut i = 0; - while r8(a + i) != 0 { - i += 1; - } - a + i + 1 -} // ---------------------------------------------------------------- layout @@ -636,10 +629,6 @@ fn wake(sc: u32, i: u32) { } fn draw(range: i32) -> i32 { - if range == i32::MIN { - // The entry lists `services.RandomInt`, so the import stays; no recorded range is this one. - return unsafe { random_int(range) }; - } if range < 2 { return 0; } @@ -1275,7 +1264,7 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { let u = find_unit(a); if unit != 0 && r32(u + U_FLAGS) & ALIVE != 0 && rf(u + U_CARRIER) == unit { let cell = [r16(u + U_CELL), r16(u + U_CELL + 2)]; - let fits = unsafe { can_place_footprint(r32(u + U_DEF), r16(u + U_ID) as u32, cell.as_ptr(), 1) }; + let fits = unsafe { can_place_footprint(rf(u + U_DEF), r16(u + U_ID) as u32, cell.as_ptr(), 1) }; if fits != 0 { attach_to_piece(u, 0, -1, 1); } @@ -1676,11 +1665,14 @@ pub extern "C" fn FreeObjectState(state: u32) { fn table_anchor() {} // ABI 9.1: a module that uses no function pointer would have no table import; this one keeps it. static ANCHOR: [fn(); 1] = [table_anchor]; +// The entry lists `services.RandomInt`; a pointer to it, never called, keeps the import. +static KEEP_RANDOM: unsafe extern "C" fn(i32) -> i32 = random_int; #[no_mangle] pub extern "C" fn UpdateObjectState(view: u32) { // ABI 9.1: a module that uses no function pointer would have no table import; this one keeps it. let _ = unsafe { read_volatile(&ANCHOR[0]) }; + let _ = unsafe { read_volatile(&KEEP_RANDOM) }; let mut tc = TrigCache::new(); update_state(view, &mut tc); } From f762d66422dddeada5ae926bfea6d2932034d96a Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:16:26 +0000 Subject: [PATCH 25/30] Update: Answer scripts review round 2 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 0a6b6af..98f5f7b 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -193,8 +193,9 @@ EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's piece a unit offset that is a unit, and, when the target is not 0, a target offset that is a unit; and SCRIPT_VALUE, a unit offset that is a unit. The module publishes none that a valid script does not produce: a null unit or a callback it never had is never published. It publishes the fields as its -script gives them (a piece index, flags or a value are passed unchanged) and checks none of them; the attach -operation's own tests of the unit and its carrier (section 4) are the exception. +script gives them (a piece index, flags or a value are passed unchanged) and checks none of them, except the tests the attach and drop operations make of the unit and its +carrier and the piece index of EXPLODE_PIECE, which section 4 puts outside the contract (a module may drop one +that is outside the model's piece count or publish it). ## 3. State @@ -372,7 +373,7 @@ state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a p else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature index, a model with fewer vertices than a slot reads, and script data that does not describe its own counts are outside the contract, and a module need not check them. So are the faults of a -script's code: an opcode's piece, axis or statics index out of range (EXPLODE_PIECE's and the effect command's piece included: whether the module publishes or drops one outside the model's piece count is not judged), a stack that underflows or +script's code: a null model given to `CreateObjectState`, `CreatePlayerObjectState` or `ObjectStateSize`, or a feature whose model is null at INIT_STATE; an opcode's piece, axis or statics index out of range (EXPLODE_PIECE's and the effect command's piece included: whether the module publishes or drops one outside the model's piece count is not judged), a stack that underflows or overflows its 32 words, a `pc` outside `code`, and a script run while its model state is null or its state has no owner (the operations that touch the pieces, the unit, an effect or a unit value need both). @@ -389,7 +390,7 @@ is below 0 or not below *state.count*, it is (0, 0, 0). Otherwise the running po record's `object.box_x` plus its `rot_x`, `object.box_y` plus its `rot_y`, and `object.box_z` plus its `rot_z`; then for each record *q* from *p*'s `parent` up to the root: the angles are the three 16-bit halves bank = `q.short_14`, heading = `q.short_12` and pitch = `q.short_10`, the unit's `bank`, -`heading` and `pitch` being added to them for the root; the running point is rotated by those angles +`heading` and `pitch` being added to them for a record with no parent (the root, or another top-level piece); the running point is rotated by those angles (the three-angle rotation, section 5); and (`q.object.box_x + q.rot_x`, `q.object.box_y + q.rot_y`, `q.object.box_z + q.rot_z`) is added to it. The offset is then (x, y, −z) of the running point. @@ -488,7 +489,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set to (0,0,0) and its `modified` 0. A piece is also restored, whatever its `modified`, when its parent was restored in this pass; a piece with no parent (the root and the model's other top-level pieces) -is restored only when its `modified` is 0. Equivalently, a piece is restored when it or any of its ancestors has `modified` 0 when the pass begins, whatever order the pass takes the records in. Then every piece under the root is visited once for itself and once +is restored only when its `modified` is 0. Equivalently, a piece is restored when it or any of its ancestors has `modified` 0 when the pass begins, whatever order the pass takes the records in. Then every piece under the root (the root's own subtree: a top-level piece that is not the root is not posed) is visited once for itself and once for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is 0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank From 47e802abd432b30465e606b4722520fb2de8d635 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:20:57 +0000 Subject: [PATCH 26/30] Fix: pose only the root subtree, guard null root Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 13 +++++++++---- scripts/src/lib.rs | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index e55ba37..9cdb267 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -9,10 +9,8 @@ - The fuel pass is the kit's `tools/wasm_fuel.py` (rule v1); `--check` accepts the module (29255 bytes). - `target-cpu=mvp` plus sign-ext and bulk-memory. No saturating float conversion is left in the module (`trunc64` in `math.rs` truncates a double by its bits). -- All 21 slots of the entry are exported. `UpdateObjectState` keeps the table import alive and does - nothing (`UnitDrawView` has no layout in the kit). The three engine slots are not exported. -- Imports: `map.GetGroundHeight`, `los_radar.IsUnitVisibleToPlayer`, `services.SimAlloc`, `SimAllocTagged`, - `SimFree` and `Emit`, nothing else. `Emit` publishes SET_YARD, AIM_DONE, EXPLODE_PIECE, ATTACH_TO_PIECE and +- All 21 slots of the entry are exported. `UpdateObjectState` implements the update rule on the unit record. The three engine slots are not exported. +- Imports: the eleven of the entry (some unused). `Emit` publishes SET_YARD, AIM_DONE, EXPLODE_PIECE, ATTACH_TO_PIECE and SCRIPT_VALUE with the sizes of the entry's `publishes` (12, 16, 16, 20, 16). - No statics but the four data words and constants (the strings, the table anchor, the maths tables). - Rotation of a point, the angle of a vector, hypot and `bx_ftol` are the kit's runtime ported to Rust @@ -63,3 +61,10 @@ carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the address of - The wind_meteors notes that were mixed into this file are removed. 4. Session 3 (merged main and spec-scripts, review fixes): req1 `equal` on all four recordings (module 30162 bytes). + +5. Session 4 (merged main and spec-scripts; review round 2): req1 `equal` on all four recordings (module 30311 bytes). + - Pose rule: only the root's subtree is posed and `pos` is added only for the root itself (new spec); a top-level + sibling is restored but not posed. Piece offset adds the unit's angles for any parentless record. + - Null `root` is guarded in `pose_unit_state` and `update_state`. INIT_STATE with a null feature model is now + outside the contract (spec §4), so it is left. EXPLODE_PIECE out-of-range is not judged (left as dropped). + - Stale notes (UpdateObjectState, imports, TURN signedness) corrected: TURN reads the rotation unsigned (`r16`). diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index f57287f..c9587e4 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -460,14 +460,18 @@ fn pose_model(state: u32, tc: &mut TrigCache) { i = 0; while i < n { let m = mp(state, i); - if rs(m + MP_MODIFIED) == 0 { + let mut top = m; + while rf(top + MP_PARENT) != 0 { + top = rf(top + MP_PARENT); + } + if rs(m + MP_MODIFIED) == 0 && top == rf(state + M_ROOT) { let vc = r32(mobj(m) + O_VERTEX_COUNT); let pts = rf(m + MP_POINTS); let mut v = m; loop { let up = rf(v + MP_PARENT); let (mut bank, mut heading, mut pitch) = (r16(v + MP_ROT + 4), r16(v + MP_ROT + 2), r16(v + MP_ROT)); - if up == 0 { + if up == 0 && v == rf(state + M_ROOT) { bank = bank.wrapping_add(r16(pos)); heading = heading.wrapping_add(r16(pos + 2)); pitch = pitch.wrapping_add(r16(pos + 4)); @@ -506,7 +510,9 @@ fn pose_unit_state(unit: u32, state: u32, tc: &mut TrigCache) { copy(state + M_POS, unit + U_BANK, 6); wi(state + M_DIRTY, 1); let root = rf(state + M_ROOT); - w16(root + MP_MODIFIED, 0); + if root != 0 { + w16(root + MP_MODIFIED, 0); + } pose_model(state, tc); wi(state + M_DIRTY, 0); } @@ -738,6 +744,9 @@ fn update_state(unit: u32, tc: &mut TrigCache) { copy(state + M_POS, unit + U_BANK, 6); wi(state + M_DIRTY, 1); let root = rf(state + M_ROOT); + if root == 0 { + return; + } w16(root + MP_MODIFIED, 0); if r16(root + MP_FLAGS) & F_COLORED != 0 { wi(state + M_CACHE_DRAW, 0); From 5b1ca639d7f72c0a9cbb704454ce71fec7a42563 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:33:56 +0000 Subject: [PATCH 27/30] Update: Say how scripts find the unit of an id Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 98f5f7b..ce51c4c 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -648,7 +648,7 @@ second arguments. | 5, 6 | `u.bit0`, `u.bit1` | | 7 | the piece position of piece *a*: (`v.x & 0xffff0000`) + (`v.z >> 16`), *v* being its world position | | 8 | that position's y | -| 9, 10, 11 | the unit at index `a & 0xffff` of the unit table, when it is alive (bit 28 of its `flags`): 9, (`pos.z >> 16`) + (`pos.x & 0xffff0000`); 10, `pos.y`; 11, `def.modelMaxY`. Otherwise these give 0. | +| 9, 10, 11 | the unit at index `a & 0xffff` of the unit table (index 0 is no unit; `Game.poolCount` is not tested), when it is alive (bit 28 of its `flags`): 9, (`pos.z >> 16`) + (`pos.x & 0xffff0000`); 10, `pos.y`; 11, `def.modelMaxY`. Otherwise these give 0. | | 12 | *a*'s two halves *hi* = `a & 0xffff0000` and *lo* = `a << 16`, *lo* negative adding 0x10000 to *hi*: the angle of the vector (*hi*, *lo*) minus `u.heading`, as an unsigned 16-bit value | | 13 | the same *hi* and *lo*: `bx_ftol(hypot(hi, lo))` (section 5) | | 14 | the angle of the vector (*a*, *b*), as an unsigned 16-bit value | @@ -690,11 +690,11 @@ which the engine records as the same effect, so the replay compares the outbox a the import's name (ABI 7.2 and 9.3), and the effect's kind and fields, as the tables of section 2 give them, are what the receiving modules act on. -**The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, -when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: +**The attach operation** of an id, a piece *a* and a mode *b*: the unit at index *id* (taken as a 16-bit +value) of the unit table, index 0 being no unit and `Game.poolCount` not tested, when it is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. -**The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and +**The drop operation** of an id: the unit at index *id* (a 16-bit value) of the unit table, as in the attach operation, when it is alive and this unit is its carrier: when `map.CanPlaceUnitFootprint` with the address of the unit's `def` (a `block` argument: `g_blockBase` plus the offset the unit's `def` holds), the unit's `id` as a 16-bit value, the address of a copy of the unit's `cell` (a `Point16`, two 16-bit values) in the module's own memory and the flags 1 returns a value that is not 0, ATTACH_TO_PIECE is published with it, From 19ff5927bf72b0e803c6f77ee256b07dc48a7c44 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:37:09 +0000 Subject: [PATCH 28/30] Fix: Treat unit index 0 as no unit Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 8 +++++++- scripts/src/lib.rs | 12 ++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index 9cdb267..6ea49da 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -29,7 +29,7 @@ ## Update to spec v101/v102 (this session) - `SetCob` stores `services.GetCobChecksum(data)`; the checksum code and the relocation guesses are gone (the table words are addresses). The entry's imports are all kept (`RandomInt`, `CanPlaceUnitFootprint` - stay imported, unused). + stay imported; only `RandomInt` is unused, `CanPlaceUnitFootprint` is called by DROP_UNIT). - Pose rule: a record is restored when it or any ancestor has `modified` 0 (walk up the parent links). - The query, wait, unit value 4, SET_YARD and heading rules of the new spec were already as the code had them. - `tools/replay.js` now puts each script and model in the `load_data` region of a 5136-page memory, answers @@ -68,3 +68,9 @@ carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the address of - Null `root` is guarded in `pose_unit_state` and `update_state`. INIT_STATE with a null feature model is now outside the contract (spec §4), so it is left. EXPLODE_PIECE out-of-range is not judged (left as dropped). - Stale notes (UpdateObjectState, imports, TURN signedness) corrected: TURN reads the rotation unsigned (`r16`). + +6. Session 5 (merged main and spec-scripts; review round 3): req1 `equal` on all four recordings (module 30273 bytes). + - Spec change: unit index 0 is no unit and `Game.poolCount` is not tested (unit values 9-11, attach, drop). `find_unit` + returns 0 for index 0 and callers treat 0 as absent. This answers review item 5 (poolCount is deliberately not tested). + - Review nits 1-3 (null-root early return in `update_state`, redundant ancestor walks, table anchor) left as they are: a built + state always has a root, the walks only cost fuel, and the anchor keeps the table import for ABI 9.1. Item 4 (stale note) fixed. diff --git a/scripts/src/lib.rs b/scripts/src/lib.rs index c9587e4..73e476c 100644 --- a/scripts/src/lib.rs +++ b/scripts/src/lib.rs @@ -675,8 +675,8 @@ fn unit_value(unit: u32, num: i32, a: i32, b: i32, tc: &mut TrigCache) -> i32 { } } 9 | 10 | 11 => { - let u = rf(game() + G_UNITS) + (a as u32 & 0xffff) * UNIT_SIZE; - if r32(u + U_FLAGS) & ALIVE == 0 { + let u = find_unit(a); + if u == 0 || r32(u + U_FLAGS) & ALIVE == 0 { return 0; } match num { @@ -721,7 +721,11 @@ fn unit_value(unit: u32, num: i32, a: i32, b: i32, tc: &mut TrigCache) -> i32 { } } +/// The unit at index `id` of the unit table, or 0 for index 0 (no unit). fn find_unit(id: i32) -> u32 { + if id as u32 & 0xffff == 0 { + return 0; + } rf(game() + G_UNITS) + (id as u32 & 0xffff) * UNIT_SIZE } @@ -1259,7 +1263,7 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { pc += 1; flush!(); let u = find_unit(d); - if unit != 0 && r32(u + U_FLAGS) & ALIVE != 0 { + if unit != 0 && u != 0 && r32(u + U_FLAGS) & ALIVE != 0 { let cr = rf(u + U_CARRIER); if cr == 0 || cr == unit { attach_to_piece(u, unit, b, a); @@ -1271,7 +1275,7 @@ fn run_channel(sc: u32, i: u32, elapsed: i32, tc: &mut TrigCache) { pc += 1; flush!(); let u = find_unit(a); - if unit != 0 && r32(u + U_FLAGS) & ALIVE != 0 && rf(u + U_CARRIER) == unit { + if unit != 0 && u != 0 && r32(u + U_FLAGS) & ALIVE != 0 && rf(u + U_CARRIER) == unit { let cell = [r16(u + U_CELL), r16(u + U_CELL + 2)]; let fits = unsafe { can_place_footprint(rf(u + U_DEF), r16(u + U_ID) as u32, cell.as_ptr(), 1) }; if fits != 0 { From a2c2e1d5e515c9c4f01803548b2032102e57cbff Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:56:07 +0000 Subject: [PATCH 29/30] Update: Pin the scripts spec to interfaces-v103 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index ce51c4c..295bb32 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -909,9 +909,10 @@ of value 5 is recorded), and every opcode whose effect no recorded thread produc ## 8. Kit version -Kit `interfaces-v102` and `reference-traces-v64`, the versions the gate judges against. Interface `scripts` 3.0. +Kit `interfaces-v103` and `reference-traces-v65`, the versions the gate judges against. Interface `scripts` 3.0. For this subsystem they hold what `interfaces-v101` and `reference-traces-v63` hold: the headers, the manifest -entry, the ABI and the recordings of `scripts` are unchanged between them. +entry, the layout, the schema, the ABI's rules for scripts and the recordings of `scripts` are unchanged between them +(v103 adds a view region above the load data in the memory, which this module does not touch). The imports are against `map` 9, `los_radar` 5 and `services` 4.6. The kit's manifest entry is `blocked`, so it has no `fuel_budget` and no `size_budget`, and the host runs the From 091af4662fdf8387d2b6974aabe00d6759d72fe6 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:58:52 +0000 Subject: [PATCH 30/30] Docs: Bring scripts notes up to date Assisted-by: Claude Code:claude-sonnet-5-5 --- scripts/IMPLEMENTATION-NOTES.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/IMPLEMENTATION-NOTES.md b/scripts/IMPLEMENTATION-NOTES.md index 6ea49da..a91b4c5 100644 --- a/scripts/IMPLEMENTATION-NOTES.md +++ b/scripts/IMPLEMENTATION-NOTES.md @@ -47,10 +47,15 @@ question A is resolved. ## Unclear points in the spec or kit -Question A of `SPEC-QUESTIONS.md` (above). Still true from before: `UnitDraw View` has no layout, so -`UpdateObjectState` does nothing; TURN's delta reads the rotation as a signed `short`; unit values 12 and 14 -are masked to 16 bits unsigned. The kit has no `RecordSimEvent` use here and no `map` import for the drop of a -carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the address of the unit's `def`. +No question is open (`SPEC-QUESTIONS.md`: question A was the gate's length bug, resolved by the session-2 verdict). +Points the spec left unclear and later settled, or that I resolved by reading it: +- `UnitDraw View` has no layout in the kit; `UpdateObjectState` implements the spec's update rule on the unit record. +- TURN reads the rotation as an unsigned 16-bit value (`r16`), as the spec says. +- Unit values 12 and 14 are masked to 16 bits unsigned. +- The kit has no `map` import for the drop of a carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the + address of the unit's `def`; `RecordSimEvent` is not used. +- Old-kit claims (checksum code, relocation guesses, `CobScript.table` as an offset) are gone: the kit is interfaces-v103, + tables are linear addresses and `services.GetCobChecksum` gives the checksum. ## Review round 1 (this session) - `RandomInt` is kept by a never-called function pointer in a static (read volatile), not by a call in `draw`. @@ -74,3 +79,6 @@ carried unit, so DROP_UNIT calls `map.CanPlaceUnitFootprint` with the address of returns 0 for index 0 and callers treat 0 as absent. This answers review item 5 (poolCount is deliberately not tested). - Review nits 1-3 (null-root early return in `update_state`, redundant ancestor walks, table anchor) left as they are: a built state always has a root, the walks only cost fuel, and the anchor keeps the table import for ABI 9.1. Item 4 (stale note) fixed. + +7. Session 6 (merged main and spec-scripts; spec pinned to interfaces-v103 / reference-traces-v65, a view region above the load + data that this module does not touch). Notes brought up to date; no source change. Gate: req1 `equal` on all four recordings (module 30273 bytes).