From 9a654302f973c5cdf0c86d111d937c67e9dc185a Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:18:00 +0000 Subject: [PATCH 01/12] Add: Specify the movement subsystem Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 634 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 634 insertions(+) create mode 100644 specs/movement.md diff --git a/specs/movement.md b/specs/movement.md new file mode 100644 index 0000000..7d383a3 --- /dev/null +++ b/specs/movement.md @@ -0,0 +1,634 @@ +# movement + +## 1. Role + +Movement moves units. Each unit that can move has a motion record (its velocity, speed, turn, flight mode and a +goal), and the goal is what the motion steers to: a short route of waypoints for a ground unit, a point and a +heading for an aircraft. Orders give a goal a target (a point, a unit to follow, a disc, a ring or a footprint +outline), which movement builds for them and frees when they ask. Once a tick, for each unit with a motion, +movement steps the goal towards its target, steers (turning, accelerating, braking, climbing), moves the unit, +places it on the map when it changes cell, and starts the scripts that show it moving. It also takes pathfinding's +routes for its goals and reports an order's progress back to orders. + +## 2. Interface + +### Slots (`interfaces/movement.h`, version 5.0) + +| Slot | When the engine calls it | +| --- | --- | +| `Apply` | for each event of movement's inbox, in the order it was published (`docs/schedule.md`, "Routes") | +| `UpdateMotion` | once a tick for each unit that has a motion, in the unit's update, after its orders | +| `ApplyPathEvent` | in the players phase, for each event pathfinding's `Poll` gives, with the waypoints it copied | +| `HasNetState` | when the network sends unit states (a query) | +| `NewPathOrderAt`, `NewPathOrderToUnit`, `NewPathOrderToUnitAt`, `NewPathOrderToUnitAtAngle`, `NewAirManeuverOrder`, `NewApproachRadius`, `NewRingApproach`, `NewPointMarker` | when an order needs a target; the answer is the new target | +| `TargetType` | when orders asks what kind a target is (a query) | +| `UnitTarget` | when orders asks what a unit's goal steers to (a query) | +| `GetMotionState`, `ReadNetState`, `WriteNetState`, `LoadTarget`, `SaveTarget`, `WriteState` | engine slots (below) | + +The six engine slots are the entry's `engine` slots: the module does not export them, and the host calls the +engine's native slot, which reads and writes the module's records in the block as section 3 lays them out (ABI +section 6, "Engine slots", and section 9.3, "What stays in the engine"). So the module's records must be exactly +the `layout.json` records of section 3, at the offsets it gives, for those slots to read. + +### The manifest entry + +The kit's manifest (`wasm/modules.json`) has the entry `movement`, and the module must match it exactly (ABI 4.2 +and 9.1): + +- `name` and `interface`: `movement`. +- `majors`: `movement` 5, `units` 7, `map` 9, `scripts` 3, `pathfinding` 4, `services` 4. +- `data_base` 622592 (0x98000) and `table_base` 464: the module's window of `window` (32768) bytes and its + `table_slots` (32) table entries (ABI 2.2 and 2.3). +- `blocked`: `true` in the kit's manifest. A blocked entry has no `fuel_budget` and no `size_budget` (ABI 4.2), + and the gate judges a module of it on the recordings route, with `budgets: not_judged` (ABI section 15). +- `exports`, in this order: `Apply`, `UpdateMotion`, `ApplyPathEvent`, `HasNetState`, `NewPathOrderAt`, + `NewPathOrderToUnit`, `NewPathOrderToUnitAt`, `NewPathOrderToUnitAtAngle`, `NewAirManeuverOrder`, + `NewApproachRadius`, `NewRingApproach`, `NewPointMarker`, `TargetType`, `UnitTarget`. +- `engine`: `GetMotionState`, `ReadNetState`, `WriteNetState`, `LoadTarget`, `SaveTarget` and `WriteState`, each + with the entry's reason. +- `data`: `g_game`, `g_simGlobals`, `g_extTdf`, `g_blockBase` (ABI 8.2). The module reads `g_game` (the `Game` + record) and `g_blockBase` (to turn a block offset into an address and back). +- `publishes`: `{"128": 8, "160": 8, "161": 8, "336": 16, "337": 12, "338": 16, "339": 20, "340": 20, "341": 12, + "342": 32, "343": 12, "344": 24, "345": 16, "346": 8, "347": 12}`: los_radar's UPDATE_UNIT (`LosRadarUnit`), map's + ADD_UNIT and REMOVE_UNIT (a `MapEventHeader` alone), and movement's own twelve effects (section 4, "Effects"). + The route table (`data/routes.csv`) carries each from movement's outbox. +- Fuel: the module meters itself by rule version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`. +- Slot kinds: + +| Slot | Kinds | +| --- | --- | +| `Apply` | `[linear, int] -> int` | +| `UpdateMotion` | `[block] -> void` | +| `HasNetState`, `UnitTarget` | `[block] -> int` | +| `ApplyPathEvent` | `[linear, int, linear] -> void` | +| `NewPathOrderAt` | `[int, linear] -> int` | +| `NewPathOrderToUnit` | `[int, block] -> int` | +| `NewPathOrderToUnitAt` | `[int, block, linear] -> int` | +| `NewPathOrderToUnitAtAngle` | `[int, block, int] -> int` | +| `NewAirManeuverOrder`, `NewPointMarker` | `[int, linear, linear] -> int` | +| `NewApproachRadius` | `[int, int, int, int] -> int` | +| `NewRingApproach` | `[int, int, int, int, int] -> int` | +| `TargetType` | `[int] -> int` | + +An order and a target are `int`: block offsets (0 for none) that the module stores and returns. A `short angle` +is the `int` kind, sign-extended from its low 16 bits (ABI 7). + +- Imports, every one listed and nothing else: + +| Import | Kinds | Used for | +| --- | --- | --- | +| `units.UnitRefUnlink` | `[block] -> void` | unlinking a move target's unit reference before the target is freed | +| `units.UnitRefInit` | `[block, block, block] -> void` | building a move target's unit reference | +| `units.UnitRefSetUnit` | `[block, block] -> void` | never called by an exported slot | +| `map.CanPlaceUnitFootprint` | `[block, int, linear, int] -> int` | whether a unit fits at the cell it moves into | +| `map.GetGroundHeight` | `[linear] -> int` | the ground under a move target that takes an altitude | +| `scripts.GetPiecePosition` | `[block, int, linear] -> void` | where a carried unit sits, and where a followed unit is | +| `scripts.GetPieceAngles` | `[block, int, linear] -> void` | the angles of a carried unit | +| `pathfinding.Submit` | `[linear] -> void` | asking for a route for an AI search goal | +| `pathfinding.Cancel` | `[int] -> void` | dropping an AI search goal's request | +| `services.SimAlloc` | `[int] -> linear` | a motion, a goal or a target | +| `services.SimFree` | `[linear] -> void` | freeing them | +| `services.Emit` | `[linear, int] -> void` | every publish of section 4, "Effects" | + +The recordings carry `map.CanPlaceUnitFootprint` as `services.ScheduleMapCanPlaceUnitFootprint` and `Emit` as +`services.SchedPublish 14 ` (ABI 9.3, "Routes in the recordings"; 14 is movement's outbox). +`units.UnitRefSetUnit` is in the entry because the engine slot `LoadTarget` uses it; the module imports it (ABI +9.1: every listed import is imported) and never calls it. + +- Hooks: every slot of `interfaces/movement.h` says "Hooks: none", and the module raises none. + +### Arguments outside the block + +All in the caller's memory (`linear`), little-endian, read in place: + +- **The event of `Apply`**: a `MovementEventHeader` (`kind`, `unit`) and its kind's payload, `size` bytes. The + payloads and their sizes: NEW and DESTROY the header alone (8), LOAD `MovementLoadState` (48), SET_MODE and + SET_FLIGHT_MODE `MovementSetMode` (12), SET_SPEED `MovementSetSpeed` (12), SET_TARGET and DESTROY_TARGET + `MovementTarget` (12), SET_ALTITUDE, SET_APPROACH_RADIUS and SET_HEADING `MovementTargetValue` (16). The recordings + write the fields as `a event.kind`, `a event.unit`, `a event.target`, `a event.mode`, `a event.value`, and the size + as `a size`. +- **The event of `ApplyPathEvent`**: a `PathfindingEventHeader` (20 bytes: `kind`, `unit`, `requester`, `target`, + `tick`) and its payload (`PathfindingStarted`, 24 bytes; `PathfindingFinished`, 28 bytes), `size` bytes, and + `waypoints`, an array of `PathPoint` (4 bytes each, `x` then `y`, signed 16-bit) of at least the finished event's + `count` entries; the module reads at most the first 20. +- **`pos`** of `NewPathOrderAt` and `NewPathOrderToUnitAt`, and **`from`**, **`to`** of `NewAirManeuverOrder`: a + `Vec3` (three signed 32-bit words). **`pos`** and **`size`** of `NewPointMarker`: a `Point16` each (`x`, `y`, + signed 16-bit). +- **What the module passes to imports**, in its own memory: a 56-byte `PathRequest` for `pathfinding.Submit` + (section 4, "Asking for a route"), every byte written; a `Point16` cell for `map.CanPlaceUnitFootprint`; a `Vec3` + that `scripts.GetPiecePosition` writes and a 6-byte `Angles16` (`bank`, `heading`, `pitch`) that + `scripts.GetPieceAngles` writes; every effect payload of `Emit`. `map.GetGroundHeight` is given the address of the + move target's own `pos` in the block, and reads its `x` and `z` (the recordings write only those, `pos=(x,z)`). + +### Events + +None. No slot of this module records a sim event (kinds are listed in `docs/sim-events.md`). What the effects +start in other modules (a script, map's and los_radar's updates) records its own. + +## 3. State + +### Owned + +Movement owns three families of records, all allocated with `services.SimAlloc` (zeroed) of exactly the record's +`layout.json` size and freed with `services.SimFree`. Each `Ref<...>` field is a block offset (0 for none). The +replay names are the recordings' field names. + +**`UnitMotion`** (47 bytes), one per unit that moves, its offset in `Unit.motion`: + +| Field | Bytes | Replay name | Meaning | +| --- | --- | --- | --- | +| `obj` | 0, `Ref` | `obj` | the goal | +| `movementClass` | 4, `Ref` | `movementClass` | the unit type's `UnitDef.movementclass`, set at NEW | +| `velocity` | 8, `Vec3` | `velocityX`, `velocityY`, `velocityZ` | per tick, world units with 16 fractional bits | +| `p2` | 20, `Vec3` | `p2X`, `p2Y`, `p2Z` | the smoothed acceleration that tilts an aircraft | +| `speed` | 32, int | `speed` | | +| `turn` | 36, signed 16-bit | `turn` | the turn of the last tick | +| `pathLockStamp` | 38, int | | map's field: the module never writes it | +| `lastMoveTick` | 42, int | `lastMoveTick` | the last tick the unit moved | +| `flags` | 46, byte | `flags` | bits 0-1 `mode`, the flight mode (0 to 3; 1 grounded, 2 flying); bit 2 `flag`, *blocked*: the unit's last cell change did not fit; bits 3-7 stay 0 | + +**The goals** (base `PathGoal`): word 0 is the goal's class word (see "Class words", below), then `target` (4, +`Ref` to a target) and `owner` (8, `Ref`, the unit). A unit's goal class is fixed at NEW: + +| Goal | Bytes | Fields after the base | +| --- | --- | --- | +| `AiSearchGoal` | 101 | `points` (12, 20 `Point16`, whole world units: 16 per cell, so `x` is a position's `x >> 16`), `count` (92, int), `repathClaimTick` (96, unsigned), `flags` (100, byte: bit 0 `active`, *has a route*; bit 1 `flag_1`, *wants a search*; bit 2 `flag_2`, the blocked bit last sent over the network; bit 3 `flag_3`, *changed since sent*) | +| `PatrolGoal` | 28 | `points` (12, 3 `Point16`), `count` (24, int) | +| `LiteGoal` | 40 | `pos` (12, `Vec3`), `vel` (24, `Vec3`), `heading` (36, signed 16-bit), `field_26` (38, stays 0), `netDirtyFlags` (39, byte: bit 0 `dirty`, bits 1-2 `mode`) | +| `PackedPosGoal` | 39 | `pos`, `vel`, `heading`, `field_26` as `LiteGoal` (the layout's `PackedGoal`) | + +The replay names `points`, `count`, `repathClaimTick`, `flags`, `posX` to `posZ`, `velX` to `velZ`, `heading`, +`netDirtyFlags`; `points` is written as its bytes (`x:...`). + +**The targets** (base `OrderFx`): word 0 is the class word, then `source` (4, `Ref`, the order the target +was built for). The kind is the class: 2 move target, 3 air maneuver target, 4 disc, 5 ring, 6 footprint marker +(the numbers `TargetType` gives; 1, a plain target, is never built by this module). + +| Target | Bytes | Fields after the base | +| --- | --- | --- | +| `PathOrder` (2) | 54 | `flags` (8, unsigned 16-bit), `approachRadius` (10), `altitude` (12), `heading` (14), `piece` (16), each signed 16-bit; `unit` (18, `Ref`, the unit the order moves); `ref` (22, a 16-byte `PathOrderAttach`, units' unit reference: its `owner` at 26 is the followed unit); `pos` (38, `Vec3`); `followOffset` (50, int) | +| `AirManeuverOrder` (3) | 44 | `flags` (8, unsigned 16-bit, bit 0 `headingSet`), `target` (10, `Vec3`), `other` (22, `Vec3`), `saveOnly22` (34), `heading` (36, unsigned 16-bit), `value_26` (38), `self` (40, `Ref`) | +| `ApproachRadius` (4) | 20 | `pos` (8, `Point16`, a cell), `radius` (12, int), `radiusSq` (16, int) | +| `RingApproach` (5) | 28 | `pos` (8, `Point16`), `inner` (12), `outer` (16), `innerSq` (20), `outerSq` (24), ints | +| `PointMarker` (6) | 24 | `x1` (8), `x2` (12), `y1` (16), `y2` (20), ints: the first and last column and row of a rectangle of cells | + +The bits of a move target's `flags`: 0x1 *follows* `ref.owner`; 0x2 *keeps an offset* from it; 0x4 *matches its +heading*; 0x8 *altitude set*; 0x10 *approach radius set* (`radiusFlag`); 0x20 *fixed position*; 0x40 *heading +set* (`headingFlag`); 0x80 *stopped following*. The replay names the reference's owner `ref.owner`, and the +position `posX`, `posY`, `posZ`. + +**`Unit.motion`** is written by movement only (NEW and DESTROY). + +**Class words.** Word 0 of a goal and of a target says its class, and is what the recordings name an object by +(`LiteGoal#1`, `ApproachRadius#2`: `docs/replay-format.md`, "Polymorphic objects") and what the engine slots read +to know the class. The module writes each class's word when it builds the object. The kit does not give the value of +any class word ("Kit gaps", section 7). The embedded `PathOrderAttach` has a class word of its own, which +`units.UnitRefInit` writes. + +### Read + +| Field | Owner | Use | +| --- | --- | --- | +| `Game.ticks`, `Game.seaLevel` (unsigned byte), `Game.gravity`, `Game.overflowBucket` | game | the tick; the water line; the tilt; whether a unit is off the map | +| `Game.units`, `Game.unitsEnd` | units | the unit table, units of 280 bytes, for the limits of section 4 | +| `Unit.pos` (`posX`, `posY`, `posZ`; `xWhole`, `yWhole`, `zWhole` are the high halves), `heading`, `pitch`, `cell`, `footprint` (`Point16`), `flags`, `carrier`, `transportPiece` (byte), `def`, `player`, `list`, `spatialBucket`, `id`, `weapons[0].weapon` | units | as section 4 says; the unit's mode is `Unit.flags` bits 0-1 and its move rate bits 2-3 | +| `UnitDef.maxvelocity`, `brakerate`, `acceleration`, `bankscale`, `pitchscale`, `moverate1`, `moverate2`, `movementclass`, `turnrate` (unsigned 16-bit), `altitude` (signed 16-bit), `draft` (byte), `flags1` | units | bit 11 (`flying`): an aircraft; bit 19 (`b19`): stays at or above the water line when carried; bit 22 (`b22`): a sea unit; bits 12 and 19 (mask 0x81000): no slowdown under water | +| `WeaponDef.range` | weapons | a follow offset | +| `Player.active`, `Player.type` | players | type 1 or 2 is a player whose units check the map; type 3 gets the remote goals | +| `Order.unit`, `Order.flags_42` (bit 0x800000) | orders | the unit an order's target reports to; whether a goal may take a straight route | +| `SpatialBucket.bytes` (byte 1: the bucket's ground height in whole units) | map | the cruise height | +| a carrier's `UnitMotion.speed` and `velocity` | movement | a carried unit takes them | + +### Between ticks + +Nothing outside the block. Every motion, goal and target lives in the block from its allocation to its `SimFree`. +A goal keeps the target offset it was given until it is given another; freeing a target does not clear it. + +## 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. Several effects are delivered before `Emit` returns +(`data/routes.csv`, synchronous): a read listed after such an effect sees what its subscriber wrote. Where it +matters below, a read says "as the block now holds it". + +### Definitions + +The arithmetic is in section 5. For a unit *u*, *d* is `u.def`, and *M* is `u.motion`. + +- **S(a, s), C(a, s)**: the scaled sine and cosine of the kit's runtime (`runtime/vectors/README.md`, "Scaled sine + and cosine"), a 16-bit angle *a* and a scale *s*. **Step(a, s)** = (−S(a, s), 0, −C(a, s)): a step of length *s* + along heading *a*. +- **A(x, z)**: the angle of a vector (README, "Angle of a vector"), kept as its low 16 bits, signed. + **Head(p, q)** = A(p.x − q.x, p.z − q.z): the heading from position *p* towards *q*. +- **Rot(a, x, z)**: rotating a point (README, "Rotating a point"). +- **hyp(x, y)**: the kit's `hypot` of the two values as doubles. **ftol(v)**: the kit's `ftol`. +- **Cell(p, fp)**: the cell of a position for a footprint *fp*: (`(p.x − fp.x × 0x80000 + 0x80000) >> 20`, + `(p.z − fp.y × 0x80000 + 0x80000) >> 20`), each kept to signed 16 bits. **Centre(c, fp)** = (`(c.x × 2 + fp.x) + << 19`, `(c.y × 2 + fp.y) << 19`), the *x* and *z* of the centre of cell *c*. +- **Cruise(u)**: `(d.altitude + Game.seaLevel) << 16` when `d.flags1` has bit 22, else `(d.altitude + b) << 16`, + *b* being byte 1 of `SpatialBucket.bytes` of `u.spatialBucket`. +- **Waypoint *i*** of a goal with `points` and `count`: point *j* = min(*i*, `count` − 1), as the position + (`x << 16`, 0, `y << 16`). +- **Report(t, f)**: when target *t*'s `source` is not 0, publish ORDER_FLAGS with `unit` the `Order.unit` of the + source, `order` the source, and `flags` *f*. A target with no source reports nothing. + +### Targets + +Each target kind answers five questions. Asking can write the target and make imports; the tables say what. + +**Its position, Pos(t)**, which fills *x*, *y* and *z* of an output or fails: + +| Target | Pos(t) | +| --- | --- | +| move target, `flags` has 0x1 and not 0x80, and `ref.owner` is 0 or its `spatialBucket` is `Game.overflowBucket` | fails; nothing written | +| move target, `flags` has 0x1 and not 0x80, otherwise | `scripts.GetPiecePosition(ref.owner, piece)` gives *q*; when `flags` has 0x2, *q* becomes *q* − Step(*a*, `followOffset`), *a* being `ref.owner`'s `Unit.heading`, plus `heading` when `flags` has 0x40 (16-bit sum); then *q.y* += `altitude << 16`; `pos` becomes *q* with *y* at most 0x1ff0000; the answer is `pos` | +| move target, otherwise | when `flags` lacks 0x8, `pos.y` becomes Cruise(`unit`); then `pos.y` is kept to at most 0x1ff0000; the answer is `pos` | +| air maneuver | the answer is `target` as it was; then `target.x` += `other.x` and `target.z` += `other.z`; *h* = Head((0, 0, 0), `other`) as unsigned 16-bit; when `headingSet` and *h* ≠ `heading`: *δ* = `heading` − *h* (signed 16-bit), clamped to ±(`self`'s `turnrate` >> 3), and (`other.x`, `other.z`) becomes Rot(−*δ*, `other.x`, `other.z`), `other.y` 0 | +| disc | *x* and *z* are Centre(`pos`, the source's unit's `footprint`); *y* is not written | +| ring | *x* and *z* start as Centre(`pos`, the source's unit's footprint); *a* = Head(that unit's `pos`, that centre); then *x* += S(*a*, *r*) and *z* += C(*a*, *r*), with *r* = ((`inner` + `outer`) / 2) << 16; *y* is not written | +| footprint marker | *x* = `(fp.x + m × 2) << 19` with *m* = (`x1` + `x2`) / 2 kept to signed 16 bits, *z* = `(fp.y + y2 × 2) << 19` with `y2` kept to signed 16 bits (Q4), *fp* the source's unit's footprint; *y* is not written | + +**Whether it holds a cell, In(t, x, y)**, with no writes: a disc, when (*x* − `pos.x`)² + (*y* − `pos.y`)² ≤ +(`radius` / 16)²; a ring, when that square is at least (`inner` / 16)² and at most (`outer` / 16)²; a footprint +marker, when the cell is on the rectangle's border (*x* is `x1` or `x2` and `y1` ≤ *y* ≤ `y2`, or *y* is `y1` or +`y2` and `x1` ≤ *x* ≤ `x2`); a move or air maneuver target never. + +**Whether a unit has reached it, Reached(t, u)**: for a disc, ring or footprint marker, In(t, `u.cell.x`, +`u.cell.y`). For a move target: Pos(t) (with its writes and import) gives *at*; *r* = hyp(`u.pos.x` − *at.x*, +`u.pos.z` − *at.z*) rounded to a float, times 2⁻¹⁶. Then, in order: with 0x10, the answer is `approachRadius` > *r*; +else *r* > 0.5 gives no; 0x1 with `ref.owner` 0 gives no; 0x4 with `u.heading` ≠ `ref.owner`'s heading (unsigned +16-bit) gives no; 0x8 with |`u.pos.y` − *at.y*| > 0x10000 gives no; otherwise yes. When Pos(t) fails here (a +followed unit that is gone or off the map), the answer is no ("Gaps in the kit"). For an air maneuver: yes when +hyp(`u.pos.x` − `target.x`, `u.pos.z` − `target.z`) rounded to a float, divided by 65536, is below 48; else yes when +`headingSet` and Head((0, 0, 0), `other`) is `heading`; else no. It writes nothing. + +**Whether it stays after it is reached, Keep(t)**: a move target whose `flags` has 0x1 and whose `ref.owner` is +not 0; no other. + +**The heading it wants, Want(t)**, which gives a heading or none, with no writes: a move target whose `flags` has +0x4 or 0x80 and whose `ref.owner` is not 0 gives Head(`unit`'s `pos`, `ref.owner`'s `pos`) when `flags` has 0x2, +else `heading` when it has 0x40, else `ref.owner`'s `heading`; a move target with 0x40 otherwise gives `heading`; an +air maneuver gives Head(`self`'s `pos`, `target`) (unsigned); every other gives none. + +**Its area, Area(t)**, a `PathGoalArea` (`interfaces/pathfinding.h`): a disc gives kind 1 (`PATH_GOAL_CIRCLE`), +`centre` `pos`, `radius[0]` `radius`; a ring kind 2, `centre` `pos`, `radius[0]` `inner`, `radius[1]` `outer`; a +footprint marker kind 3, `left` `x1`, `right` `x2`, `top` `y1`, `bottom` `y2`; every field not named is 0, and a +move or air maneuver target gives all zeros (kind 0). + +### Asking for a route + +**Ask(g)**, for an AI search goal *g* with a target: `pathfinding.Submit` of a `PathRequest` whose `unit` is +*g*'s `owner`, `notBefore` `repathClaimTick` + 60 (unsigned), `goal` Area(target), `requester` *g*'s own block +offset, `target` the target, and `useStart` and `start` 0. The recordings write it as +`(unit,notBefore,kind,(centre),radius0,radius1,left,right,top,bottom,requester,target,useStart,(start))`. + +### Goals + +Each goal class answers two things: what giving it a target does (**Give(g, t)**, *t* a target or 0) and what +its tick does (**Tick(g)**). *o* is the goal's `owner`. + +**Give(g, t)**: + +- **AI search goal.** `pathfinding.Cancel(g)` (its block offset). Then Report(old target, 0x80) when it had one. + `target` becomes *t*, and with *R* standing for *has a route* and *W* for *wants a search*, both start cleared; + when *t* is not 0, *W* is set, and: + 1. when `count` ≥ 3 and In(*t*, last point's `x >> 4`, last point's `y >> 4`) (arithmetic shifts), *R* is set and + *W* cleared; + 2. otherwise, when Pos(*t*) gives *p*: when `count` ≥ 3 and 2 × ftol(hyp(last.x << 16 − *p.x*, last.y << 16 − + *p.z*)) < ftol(hyp(`o.pos.x` − *p.x*, `o.pos.z` − *p.z*)), *R* is set; when *R* is still clear and *o*'s + `Unit.list` is an order whose `flags_42` lacks 0x800000, `count` becomes 2, point 0 (`o.xWhole`, `o.zWhole`), + point 1 (*p.x* >> 16, *p.z* >> 16) kept to signed 16 bits, and *R* is set. The other points are left as they + were. + + Then `repathClaimTick` becomes 0 when it is at most `Game.ticks` − 10 (both unsigned 32-bit, so in the first ten + ticks it always does); `active` is *R*, `flag_1` is *W*, `flag_3` is set; and when *W* is set, Ask(g). Imports in + order: `Cancel`, the report, the imports of Pos(*t*), `Submit`. +- **Lite goal.** Report(old target, 0x80) when it had one; `target` becomes *t*; `dirty` is set. +- **Patrol goal and packed position goal.** Report(old target, 0x80) when it had one; `target` becomes *t*. + +**Tick(g)**: + +- **AI search goal.** First, when it has a target *t* and Reached(*t*, *o*): Report(*t*, 0x20), then, unless + Keep(*t*), Give(*g*, 0). Then, when `count` ≥ 2 and (`o.xWhole` − point 1's `x`)² + (`o.zWhole` − point 1's `y`)² + ≤ 25: the points move down by one (point *i* becomes point *i* + 1 for *i* below `count` − 1; the old last point + stays where it was, Q6), `count` drops by one, `active` is cleared when `count` is now below 2, and `flag_3` is set. + Then, when it has a target (as `target` now is) and either *M*'s blocked bit is set or `count` < 2: `flag_1` is + set and Ask(g). +- **Lite goal.** `dirty` is set when *M*'s `mode` differs from the goal's `mode` bits. Then as a packed position + goal. +- **Packed position goal.** Nothing without a target *t*. Otherwise: *old* = `pos`; Pos(*t*) writes `pos` (when it + fails, `pos` stays *old*); `vel` becomes `pos` − *old*. *dist* = ftol(hyp(`o.pos.x` − `pos.x`, `o.pos.z` − + `pos.z`)). When *dist* > 0xa00000, `pos.y` becomes Cruise(*o*). Then: when *dist* > 0x1400000, `heading` becomes + Head(`o.pos`, `pos`); otherwise, when Want(*t*) gives a heading, `heading` becomes it; otherwise, when *dist* > + 0x100000, `heading` becomes Head(`o.pos`, `pos`). Then, when Reached(*t*, *o*): Report(*t*, 0x20), and unless + Keep(*t*), Give(*g*, 0) (the lite goal's Give for a lite goal). +- **Patrol goal.** Nothing. + +### `Apply(event, size)` + +A size below 8 gives 0. An unknown kind (325 included) gives 0, and so does a size below the kind's payload +(section 2). Then the event's limits, which a malformed event fails, with outcome 0 and no change, without a trap +(ozgb/btm#25): + +- a *unit* is valid when it is not 0, at least `Game.units`, below `Game.unitsEnd`, and a multiple of 280 bytes from + `Game.units`; +- a *target* is valid when it is not 0 and its class word is one of the five target kinds' (section 3); +- for DESTROY_TARGET, SET_ALTITUDE, SET_APPROACH_RADIUS and SET_HEADING, `target` must be valid, and `unit` is not + looked at; for the others, `unit` must be valid and, but for NEW, have a motion; SET_TARGET's `target` must be 0 + or valid; +- a `mode` (SET_MODE, SET_FLIGHT_MODE, and LOAD's `state.mode`) must be 0 to 3, and LOAD's `state.flag` 0 or 1. + +The recordings hold no event outside these limits, and no outcome 0. + +| Kind | What it does | Outcome | +| --- | --- | --- | +| NEW 320 | `SimAlloc(47)` for the motion, then `SimAlloc` of the goal: when `u.player` has `active` not 0 and `type` 3, a packed position goal (39) for an aircraft and a patrol goal (28) otherwise; for every other player a lite goal (40) for an aircraft and an AI search goal (101) otherwise. `u.motion` becomes the motion (a motion it had is not freed). The motion: `obj` the goal, `movementClass` `d.movementclass`, `mode` 1, everything else 0. The goal: its class word, `owner` *u*, `target` 0; an AI search goal `flag_3` set (`flags` 8), the rest 0; a patrol goal all 0; a lite or packed position goal `pos` `u.pos`, `vel` 0, `heading` `u.heading`, and a lite goal `dirty` set (`netDirtyFlags` 1) | 1 | +| DESTROY 321 | when the motion has a goal: an AI search goal first makes `pathfinding.Cancel(goal)`; a packed position goal with a target first frees it as DESTROY_TARGET does and sets its `target` 0; then `SimFree(goal)`. Then `SimFree(motion)`, and `u.motion` becomes 0 | 1 | +| LOAD 322 | `velocity` and `p2` (from `smoothedAcceleration`) take the state's three words each, `speed` its `speed`, `turn` the low 16 bits of `turn`, `mode` and the blocked bit `mode` and `flag` | 1 | +| SET_MODE 323 | `mode` becomes the event's `mode`, nothing else | 1 | +| SET_SPEED 324 | `speed` becomes the event's `speed` | 1 | +| SET_TARGET 326 | Give(*M*'s goal, `target`) | 1 | +| DESTROY_TARGET 327 | a move target first makes `units.UnitRefUnlink` of its `ref`; then `SimFree(target)`. No goal's `target` changes | 1 | +| SET_FLIGHT_MODE 328 | when `mode` differs from the event's *m*: for *m* 1, `speed` and `velocity` become 0, then Tilt(*u*, (0, 0, 0)) (below), then SET_STATE_BITS with `mask` 1 and `set` 0; for any other *m*, SET_STATE_BITS with `mask` 1 and `set` 1; then `mode` becomes *m*. When it is the same, nothing | 1 | +| SET_ALTITUDE 329 | a move target: `flags` gains 0x8, `altitude` becomes the low 16 bits of `value`, and when `flags` has 0x20, `pos.y` becomes (*g* + `value`) << 16, at most 0x1ff0000, where *g* is `map.GetGroundHeight(&pos)` when that is above `Game.seaLevel`, and `Game.seaLevel` otherwise (Q1). An air maneuver target: nothing | 1 for those two kinds; 0 for the other kinds, with no change | +| SET_APPROACH_RADIUS 330 | a move target: `flags` gains 0x10 and `approachRadius` becomes the low 16 bits of `value` | 1; 0 for another kind | +| SET_HEADING 331 | a move target: `flags` gains 0x40 and `heading` becomes the low 16 bits of `value` | 1; 0 for another kind | + +### `UpdateMotion(u)` + +The engine calls it only for a unit with a motion. In this order: + +1. **Tick(*M*'s goal)**. +2. **Steering**: an aircraft (`d.flags1` bit 11) steers as "Flying", every other unit as "Ground". +3. **The move** ("Moving"). +4. **The move rate** ("Move rate"). +5. **SFX_OCCUPY** for *u*. + +**Turning.** To turn towards a wanted change *δ* (signed 16-bit), with *T* = `d.turnrate` (unsigned): when *δ* is +0, `turn` becomes 0 and nothing is published; else `turn` becomes *T* when *δ* ≥ *T*, −*T* when *δ* ≤ −*T*, and *δ* +otherwise (kept to signed 16 bits), and TURN with `delta` `turn` is published. Units adds it to `u.heading` at once. + +**Speed along the heading**, Push(*a*), for a change *a*: `speed` += *a*, and becomes 0 when negative. *i* = +`u.pitch` >> 11 (arithmetic), clamped to −5 to 5, and *F*, a percentage, is by *i*: 25 at −5, 55 at −4, 70 at −3, 85 at −2, 100 at −1 and 0, then 75, 50, 25, 20 +and 15 at 1 to 5. +The cap is *F* × `d.maxvelocity` / 100 (section 5); when `u.yWhole` < `Game.seaLevel` and `d.flags1` has neither +bit 12 nor bit 19, the cap is halved (section 5). `speed` becomes at most the cap, and `velocity` becomes +Step(`u.heading`, `speed`), with the heading as the block now holds it. + +**Ground.** A ground unit has an AI search goal or a patrol goal. When the goal has no route (an AI search goal +without `active`, a patrol goal with `count` below 2), `turn` becomes 0 and Push(−`d.brakerate`). Otherwise, with *p0*, *p1*, *p2* its +waypoints 0, 1, 2 and *P* = `u.pos`: + +- *g* = ftol(hyp(*p1.x* − *P.x*, *p1.z* − *P.z*)). When *g* > 5242880: *e* = *p1* − *p0* (*x* and *z*), *L* = + ftol(hyp(*e.x*, *e.z*)); when *L* ≥ 0x10000, *n* = ((*e.x* << 16) / *L*, (*e.z* << 16) / *L*), *b* = min(*g* − + 5242880, *L*), and *p1* moves back by (*n.x* × *b*) >> 16 and (*n.z* × *b*) >> 16. +- *D1* = hi((*p1.x* − *P.x*)²) + hi((*p1.z* − *P.z*)²) and *D2* the same for *p2*, hi being the high 32 bits of the + 64-bit square. +- *δ* = Head(*P*, *p1*) − `u.heading` (signed 16-bit); turn by *δ*. +- *k* = (|*δ*| × `speed`) / `d.turnrate`; *t* = (`speed`²) >> 16; *q* = (*t* << 16) / (2 × `d.brakerate`); *r* = + hi(*q*²); *lim* = hi(*k*²) × 4 (section 5 for the widths). +- When *D1* > *lim* and *D2* > *r*, Push(`d.acceleration`); else Push(−`d.brakerate`). + +**Flying.** When `mode` is not 2: `velocity`, `speed` and `turn` become 0, and nothing else. Otherwise, with the +goal's `pos` *a*, `vel` *b* and `heading` *h*, and *v0* = `velocity`: + +1. The drag: each word of `velocity` becomes (word × (0x10000 − (`d.acceleration` << 16) / `d.maxvelocity`)) >> 16. +2. The cap: *s* = hyp(`velocity.x`, `velocity.z`) rounded to a float, × 2⁻¹⁶; *m* = `d.brakerate` as a float × + 2⁻¹⁶. When *s* > *m*: *f* = ftol(*m* / *s* × 65536) and `velocity.x` and `.z` become (word × *f*) >> 16; then + *e* = ftol((*s* − *m*) × 65536), and `velocity` += Step(`u.heading`, *e*), with the heading before this tick's + turn. +3. *da* = `u.pos` − *a*, *db* = `velocity` − *b*. +4. The climb: when `u.spatialBucket` is not `Game.overflowBucket`: *l* = 0x10000 when `speed` with its low two bits + cleared is below 0x40000, else `speed` >> 2 (the speed of the last tick); `velocity.y` becomes *l* when *da.y* ≤ + −*l*, −*l* when *da.y* ≥ *l*, and −*da.y* otherwise. +5. Turn by *h* − `u.heading` (signed 16-bit). +6. The correction (section 5, "Flying"): with *A* = `d.acceleration` as a float × 2⁻¹⁶ and *H* = max(8, hyp(*da.x*, + *da.z*) × 2⁻¹⁶), *κ* = −√(2*A* / *H*); *cx* = *da.x* × *κ* × 2⁻¹⁶ − *db.x* × 2⁻¹⁶ and *cz* likewise; when + hyp(*cx*, *cz*) > *A*, both are scaled by *A* / hyp(*cx*, *cz*). `velocity.x` += ftol(*cx* × 65536) and + `velocity.z` += ftol(*cz* × 65536). +7. `speed` becomes ftol(√(*x*² + *y*² + *z*²)) of `velocity`. +8. Tilt(*u*, `velocity` − *v0*). + +**Tilt(*u*, *v*)**: each word of `p2` becomes (word × 0xf333) >> 16, then `p2` += *v*. (*x*, *z*) = Rot(`u.heading` +as the block now holds it, `p2.x`, `p2.z`); *n* = (`Game.gravity` << 16) / 0xccd; TILT is published with `bank` A(( +`d.bankscale` × −*x*) >> 16, *n*) and `pitch` A((`d.pitchscale` × −*x*) >> 16, *n*) (Q5). + +**Moving.** + +- **Carried** (`u.carrier` not 0): with *c* the carrier and *k* = `u.transportPiece` as a signed byte: + `scripts.GetPiecePosition(c, k)` gives *v*; when `d.flags1` has bit 19, *v.y* becomes at least `(s16)(seaLevel − + draft) << 16` (section 5); SET_POSITION with `pos` *v* and `mode` the motion's. `scripts.GetPieceAngles(c, k)` + gives the angles; ANGLES with them (`heading` zero-extended, `bank` and `pitch` sign-extended). `speed` and + `velocity` become *c*'s motion's when *c* has a motion, and 0 otherwise. MOVED with `moved` 0. Nothing more. +- Otherwise *p* = `u.pos` + `velocity`. When *p* is `u.pos` and `mode` is the unit's mode (`u.flags` bits 0-1), + nothing. Otherwise `lastMoveTick` becomes `Game.ticks` and *c* = Cell(*p*, `u.footprint`): + - *c* is `u.cell` and the modes agree: MOVE with `pos` *p*. + - Otherwise, when `u.player` has `active` not 0 and `type` 1 or 2, the blocked bit becomes 1 when + `map.CanPlaceUnitFootprint(d, u.id, &c, mode)` gives 0 and 0 otherwise; for another player it keeps its value + (Q7). Then: + - **blocked**: *p.x* and *p.z* are clamped to within 0x7ffff of Centre(`u.cell`, `u.footprint`); when `speed` + > `d.maxvelocity` / 2, `speed` becomes that half and `velocity` Step(`u.heading`, half); MOVE with `pos` *p*. + - **not blocked**: map's REMOVE_UNIT for *u*, CHANGE_CELL with `pos` *p*, `cell` *c* and `mode`, map's ADD_UNIT + for *u*, MOVED with `moved` 1, los_radar's UPDATE_UNIT for *u*, in that order. + +**Move rate.** The rate is 0 when the blocked bit is set, *u* is carried, or `speed` and `turn` are both 0; else 1 +when `speed` ≤ `d.moverate1`, 3 when `speed` > `d.moverate2`, and 2 otherwise. When it equals `u.flags` bits 2-3, +nothing. Otherwise: START_SCRIPT StopMoving (1) for rate 0, or START_SCRIPT StartMoving (0) when `u.flags` bits 2-3 +are 0; then START_SCRIPT MoveRate1, 2 or 3 (2, 3, 4) for rates 1 to 3; then MOVE_RATE with `rate`. + +### `ApplyPathEvent(event, size, waypoints)` + +A size below 20 does nothing. *g* is the event's `requester`; an event whose requester is not an AI search goal of +this module (by its class word) does nothing (ozgb/btm#25). + +- **STARTED** (size at least 24; otherwise nothing): when the event's `target` is a valid target (section 4, + `Apply`), `repathClaimTick` becomes the event's `tick`, and Report(that target, 0x100 when `start` is + `PATH_START_DIRECT`, 0x200 otherwise). A STARTED with an invalid target does nothing. +- **PROGRESS**: nothing. +- **FINISHED** (size at least 28; otherwise nothing): with *n* = `count`: when *n* is 0 and *g* has a target *t* + that Reached(*t*, owner) says no to, Report(*t*, 0x40); `active` is cleared; `count` and `points` stay. When *n* > + 0: `count` becomes min(*n*, 20), points 0 to `count` − 1 become the first waypoints (the rest stay), and `active` + is set. Either way `flag_1` is cleared and `flag_3` set. + +### Building a target + +Each `New*` slot makes `services.SimAlloc` of its record's size, writes the class word and `source` = `order`, and +returns the new target's block offset. The arguments are the header's, in its order. *U* is the order's `Order.unit` and *fp* its `footprint`. Fields not named +stay 0. + +| Slot | Imports after the alloc | Fields | +| --- | --- | --- | +| `NewPathOrderAt` | `UnitRefInit(&ref, 0, 0)` | `flags` 0x20, `piece` −1, `unit` *U*, `pos` *pos* | +| `NewPathOrderToUnit` | `UnitRefInit(&ref, unit, 0)` | `piece` −1, `unit` *U*, `pos` *U*'s `pos`; when `ref.owner` (now *unit*) is an aircraft, `flags` 7 and `followOffset` *w* << 16 for *w* the `range` of *U*'s `weapons[0].weapon`, 0x640000 when *w* is 0; otherwise `flags` 1 | +| `NewPathOrderToUnitAt` | `UnitRefInit(&ref, unit, 0)` | `flags` 0xa3, `piece` −1, `unit` *U*, `pos` *pos* | +| `NewPathOrderToUnitAtAngle` | `UnitRefInit(&ref, unit, 0)` | `flags` 5, `piece` *angle* (Q3), `unit` *U*, `pos` *U*'s `pos` | +| `NewAirManeuverOrder` | none | `self` *U*, `target` *from*, `other` *to* | +| `NewApproachRadius` | none | `pos` Cell((*x*, 0, *y*), *fp*); `radius`; `radiusSq` (`radius` / 16)² | +| `NewRingApproach` | none | `pos` as a disc's; `inner` the argument *outer*, `outer` the argument *inner* (Q2); `innerSq` (field `inner` / 16)², `outerSq` (field `outer` / 16)² | +| `NewPointMarker` | none | `x1` = *pos.x* − *fp.x*, `y1` = *pos.y* − *fp.y*, `x2` = *size.x* + *pos.x*, `y2` = *size.y* + *pos.y* | + +The record sizes: a move target 54, an air maneuver target 44, a disc 20, a ring 28, a footprint marker 24. The +unit reference is built in place at `ref` (byte 22 of the move target); `UnitRefInit` writes its words and links it +into the list of the unit it is given (the recordings show those writes as `o` lines of the import). The `New*` +slots are only called with an order whose `unit` is a unit, and the `ToUnit` slots with a unit. + +### The queries + +- **`HasNetState(u)`**: 0 when `u.motion` is 0. Otherwise by the goal: an AI search goal gives 1 when `flag_3` is + set or the motion's blocked bit differs from `flag_2`, else 0; a lite goal gives its `dirty` bit; the others 0. + Writes nothing. +- **`TargetType(target)`**: 0 for 0; otherwise the kind of the target (2 to 6, section 3). Writes nothing. +- **`UnitTarget(u)`**: 0 when `u.motion` is 0; otherwise the goal's `target`. Writes nothing. + +### Effects + +Each publish is `services.Emit(&payload, size)`. Every payload starts with `MovementEventHeader` (or map's or +los_radar's header) whose `unit` is the unit's block offset. + +| Kind | Payload, size | Fields | +| --- | --- | --- | +| ORDER_FLAGS 336 | `MovementOrderFlags`, 16 | `unit` the order's `Order.unit`, `order`, `flags` | +| TURN 337 | `MovementTurn`, 12 | `delta`: `turn`, sign-extended | +| TILT 338 | `MovementTilt`, 16 | `bank`, `pitch`, sign-extended from 16 bits | +| ANGLES 339 | `MovementAngles`, 20 | `bank`, `heading`, `pitch` | +| MOVE 340 | `MovementMove`, 20 | `pos` | +| MOVED 341 | `MovementMoved`, 12 | `moved` 0 or 1 | +| CHANGE_CELL 342 | `MovementChangeCell`, 32 | `pos`, `cell` (sign-extended), `mode` | +| MOVE_RATE 343 | `MovementMoveRate`, 12 | `rate` | +| SET_POSITION 344 | `MovementSetPosition`, 24 | `pos`, `mode` | +| SET_STATE_BITS 345 | `MovementSetStateBits`, 16 | `mask`, `set` | +| SFX_OCCUPY 346 | the header alone, 8 | | +| START_SCRIPT 347 | `MovementStartScript`, 12 | `script` (`MovementScript`) | +| map ADD_UNIT 160, REMOVE_UNIT 161 | `MapEventHeader`, 8 | | +| los_radar UPDATE_UNIT 128 | `LosRadarUnit`, 8 | `unit` | + +## 5. Exactness + +- **Draws**: none. Movement draws from no stream. +- **Integers**: 32-bit two's complement; every sum, difference and negation wraps. A product written `(a × b) >> k` + is the exact 64-bit product shifted arithmetically, kept as its low 32 bits; a quotient `(a << 16) / b` is the + 64-bit value divided and truncated toward zero, kept as its low 32 bits; a plain `/` of two ints truncates toward + zero. hi(*x*²) is the high 32 bits of the exact 64-bit square. `>>` of a signed value is arithmetic. A value "kept + to signed 16 bits" is its low 16 bits sign-extended. +- **The speed cap**: ((*F* << 16) × `maxvelocity`) >> 16, then that << 16 divided by 0x640000 (both in 64 bits); + under water, (cap × 0x8000) >> 16. +- **The ground steering widths**: *k* is the 64-bit product of |*δ*| (0 to 32768) and `speed`, divided by + `turnrate` and truncated, kept to 32 bits; `2 × brakerate` wraps at 32 bits; *lim* is hi(*k*²) times 4, wrapping. + The reference never divides by a `turnrate` of 0 here (no moving ground unit has one); a module must not trap on + it, and what it gives is not judged. +- **Comparisons**: `repathClaimTick` against the tick is unsigned. Every other comparison is signed, `turnrate` + and the ANGLES heading being unsigned 16-bit values widened to int. +- **The carried water line**: `(seaLevel − draft)`, its low 16 bits as a signed whole, times 65536. +- **Flying, in floating point.** *s* is the double hyp rounded to a float, then multiplied by the float 2⁻¹⁶ + (exact); *m* is `brakerate` converted to a float, times 2⁻¹⁶. *m* / *s* and *s* − *m* are computed in double from + the floats. *A* is `acceleration` converted to a float, times 2⁻¹⁶. *H* is the double hyp times 2⁻¹⁶, raised to + 8.0 when below it. *κ* = −sqrt((2.0 × *A*) / *H*) in double. *cx* = ((*da.x* × *κ*) × 2⁻¹⁶) − (*db.x* × 2⁻¹⁶) in + double, *cz* likewise; *X* = *cx* rounded to a float, *Z* = *cz* rounded to a float; *μ* = hyp(*cx*, *cz*) of the + doubles. When *μ* > *A*: the *x* step is *X* (as a double) × (*A* / *μ*), a double, and the *z* step is *Z* × (*A* + / *μ*) rounded to a float; otherwise the steps are *X* and *Z*. `velocity.x` += ftol(*x* step × 65536.0) and + `velocity.z` += ftol(*z* step (as a double) × 65536.0) (Q8). The new `speed` is ftol of the double square root of + ((*x*² + *y*²) + *z*²) of the three words as doubles. +- **Reached, in floating point**: the move target's *r* is the double hyp rounded to a float, times 2⁻¹⁶; + `approachRadius` > *r* and *r* > 0.5 compare in double. The air maneuver's distance is the hyp rounded to a float, + divided by 65536 in float, compared with 48. +- **Conversions**: ftol truncates toward zero (the kit's `ftol`: 0 for a NaN or an infinity). A heading kept from + A(...) is its low 16 bits. + +## 6. Quirks + +- **Q1**: SET_ALTITUDE asks `map.GetGroundHeight` twice, with the same position, when the ground is above the + water line, and once when it is not. +- **Q2**: `NewRingApproach` stores its `inner` argument as the ring's `outer` and its `outer` argument as `inner` + (so a caller that passes the outer radius first gets a ring the right way round). +- **Q3**: `NewPathOrderToUnitAtAngle` stores its `angle` as the target's `piece`; the target's `heading` stays 0. +- **Q4**: a footprint marker's position is the middle column of its rectangle but its last row (`y2`), not the + middle row. +- **Q5**: TILT's pitch is computed from the same rotated *x* as the bank, scaled by `pitchscale`, not from *z*. +- **Q6**: a waypoint step leaves the old last point in the array past `count`. +- **Q7**: for a unit whose player is not active or not of type 1 or 2, a cell change does not check the map, and the + blocked bit keeps the value it last had. +- **Q8**: after the flying correction is scaled down, the *x* step is used as a double and the *z* step rounded to a + float. + +## 7. Examples + +From the kit's recordings. Each was recomputed from this spec's definitions. + +- **NEW, an aircraft**: `tests/replay/movement/orders-air-fights.txt`, call at tick 10 of `Apply` (line 134), kind + 320 for `Unit#2` (an aircraft of player 0, type 1): `SimAlloc 47` then `SimAlloc 40`; `Unit#2.motion` becomes + `UnitMotion#3`, whose `obj` is `LiteGoal#1`, `flags` 1, `movementClass` null; the goal's `pos` is the unit's + (39321600, 65536, 19660800), `heading` −32768, `netDirtyFlags` 1. Outcome 1. +- **NEW, a ground unit**: the same file, tick 10 (line 294), `Unit#252` of player 1: `SimAlloc 47`, `SimAlloc 101`, + an `AiSearchGoal#3` with `flags` 8, `count` 0, and the motion's `movementClass` `MovementClass#5`. +- **A disc**: `orders-build-patrol.txt`, tick 150 of `NewApproachRadius`: order `Order#3`, whose unit has footprint + (2,2), x 45878325, y 19689825, radius 16: (45878325 − 1048576 + 524288) >> 20 = 43 and (19689825 − 1048576 + + 524288) >> 20 = 18, so `pos` (43,18), `radiusSq` 1; `SimAlloc 20`, the result `ApproachRadius#1`. +- **A ring** (Q2): the same file, tick 150 of `NewRingApproach`: `inner` 107, `outer` 47 give the fields `inner` 47, + `outer` 107, `innerSq` (47 / 16)² = 4, `outerSq` (107 / 16)² = 36. +- **A footprint marker**: `orders-air-fights.txt`, tick 20 of `NewPointMarker`: `pos` (41,19), `size` (5,5), the + unit's footprint (2,2): `x1` 39, `x2` 46, `y1` 17, `y2` 24. +- **A move target to a unit**: `orders-air.txt`, tick 4095 of `NewPathOrderToUnit`: `Order#2`, unit `Unit#1`, not an + aircraft: `SimAlloc 54`, `UnitRefInit PathOrderAttach#1 Unit#1 null`, then `flags` 1, `piece` −1, + `followOffset` 0, `unit` `Unit#3` (the order's), `pos` that unit's (51887393, 3014656, 25678911). +- **At an angle** (Q3): `orders-air-repair.txt`, tick 670 of `NewPathOrderToUnitAtAngle`, `angle` 1: `flags` 5, + `piece` 1. +- **SET_TARGET on an AI search goal**: `orders-air-fights.txt`, tick 20 of `Apply` (line 651): `Unit#1` at cell + (34,14), position (36700160, ·, 15728640), its goal with no points and `count` 0, its first order's `flags_42` + 1062153 (no 0x800000), target `PointMarker#1` (39, 46, 17, 24, footprint (2,2)). `Cancel AiSearchGoal#1`; no old + target, so no report. Pos gives *x* = (2 + 42 × 2) << 19 = 45088768, *z* = (2 + 24 × 2) << 19 = 26214400, so + `count` 2 and the points (560,240), (688,400); `active`, `flag_1` and `flag_3` set (`flags` 11); then + `Submit (Unit#1,60,3,(0,0),0,0,39,46,17,24,AiSearchGoal#1,PointMarker#1,0,(0,0))`. (The recording carries no + `w` line for `points`; the next call's `r AiSearchGoal#1.points` holds them: "Gaps in the kit".) +- **Ground steering on that route**: the same file, tick 20 of `UpdateMotion` (line 666), `Unit#1` heading 0, + speed 0, `turnrate` 1044, `acceleration` 9830, `maxvelocity` 78643: the unit turns by −1044 (TURN, 12 bytes; + units writes `heading` −1044), accelerates to 9830 (under the cap 78643), and `velocity` becomes Step(−1044, + 9830): S(−1044, 9830) uses entry 504, −803, and (−803 × 9830 + 4096) >> 13 = −964, so `velocityX` 964 and + `velocityZ` −9783. The unit stays in its cell: MOVE (20). The rate becomes 1 from 0: START_SCRIPT StartMoving, + START_SCRIPT MoveRate1, MOVE_RATE (12 bytes each), then SFX_OCCUPY (8). `lastMoveTick` 20. +- **Flying, with a cell change**: `orders-air.txt`, tick 4091 of `UpdateMotion` (line 469), `Unit#5` with + `LiteGoal#3` (`pos` (43530660, 22347776, 65093149), `vel` 0, `heading` 27720), the unit at (66662745, 22347776, + 21084818) heading 27720, `velocity` (−258360, 0, 488660), `speed` 552755, `p2` (−98618, −49661, 98627), + `acceleration` 22937, `maxvelocity` 655360, `brakerate` 393216. The drag scale is 0x10000 − 2293 = 63243; *s* + 8.1392… > *m* 6.0, so the cap applies; the heading wants no turn (no TURN); *κ* −0.03037…, the correction + steps −0.16223… and 0.31012…, so `velocityX` −260514, `velocityZ` 491586, `speed` 556349, then `p2` (−95841, + −47178, 96621) and TILT (16). The new position is in cell (62,20): `CanPlaceUnitFootprint UnitDef#51 5 (62,20) 2 = + 1`, then REMOVE_UNIT (8), CHANGE_CELL (32), ADD_UNIT (8), MOVED (12), UPDATE_UNIT (8); the rate stays 2; SFX_OCCUPY + (8). `lastMoveTick` 4091. +- **Carried**: `units-transport.txt`, `Unit#1` carried by `Unit#3`, `transportPiece` 255: `GetPiecePosition Unit#3 + -1`, SET_POSITION (24), `GetPieceAngles Unit#3 -1 = (19,32865,0)`, ANGLES (20), MOVED (12), SFX_OCCUPY (8). +- **SET_ALTITUDE** (Q1): `orders-air-fights.txt`, tick 30 of `Apply` (line 1048): `PathOrder#1` with `flags` 32 and + `pos` (41943040, 65536, 22282240), value 35: two `GetGroundHeight pos=(41943040,22282240) = 1` (1 is above the + water line 0), `altitude` 35, `flags` 40, `posY` (1 + 35) << 16 = 2359296. +- **SET_APPROACH_RADIUS**: `orders-air.txt`, tick 4095: `PathOrder#4` `flags` 9 becomes 25, `approachRadius` 48. +- **DESTROY_TARGET**: `orders-air-repair.txt`, tick 685: `UnitRefUnlink PathOrder#2.ref`, then `SimFree`. +- **SET_TARGET 0 on a lite goal**: `orders-air-repair.txt`, tick 670: ORDER_FLAGS (16) on the old target, `target` + null. +- **UnitTarget**: `orders-air-fights.txt`, tick 15: `Unit#1`'s goal has no target: null. + +No recording covers: DESTROY, LOAD, SET_SPEED, SET_HEADING, a refused event (outcome 0), SET_ALTITUDE on an air +maneuver target or on a target of another kind, NEW for a player of type 3 (patrol and packed position goals) and +everything those goals do, a move target's follow offset (flags 0x2), an air maneuver target, `ApplyPathEvent`, +`HasNetState`, `TargetType`, `NewPathOrderToUnitAt` and `NewAirManeuverOrder`. + +### Gaps in the kit + +- **Class words.** The kit names the objects of the recordings by their class (`docs/replay-format.md`, + "Polymorphic objects") and the engine slots read the class of a goal or target from its first word, but no file of + the kit gives the value a module writes there for each class. A module built from this spec can't make an object + the replay or an engine slot recognises until the kit gives those values. +- **A blocked entry.** The entry is `blocked`, with no budgets (ABI 4.2); the gate's recordings route judges a module + without them (ABI section 15). +- **Payloads.** The recordings carry each publish as `services.SchedPublish 14 `, without its fields, so the + gate compares an effect by its size and by what its subscribers write (the `o` lines after it), not by its + payload. +- **SET_TARGET's points.** An AI search goal's new two-point route is not written as a `w` line in the `Apply` that + makes it; the following call's `r` line restores it. +- **An unset position.** When Reached asks a followed move target whose unit is gone or off the map, the reference + compares with a position it never set. No recording reaches it; this spec answers no. +- **`Unit.pitch`.** The recordings carry no `pitch` line for the units they move, so the cap's slope index is 0 in + every recorded call. + +## 8. Kit version + +Kit `interfaces-v68` and `reference-traces-v55`, the versions the gate judges against. Interface `movement` 5.0. +The imports are against `units` 7, `map` 9, `scripts` 3, `pathfinding` 4 and `services` 4. From 7238ae48ae6b16be09caed614bd36bceb7674781 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:16:16 +0000 Subject: [PATCH 02/12] Update: Answer the movement spec reviews Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/specs/movement.md b/specs/movement.md index 7d383a3..57a0f09 100644 --- a/specs/movement.md +++ b/specs/movement.md @@ -155,7 +155,7 @@ replay names are the recordings' field names. | `AiSearchGoal` | 101 | `points` (12, 20 `Point16`, whole world units: 16 per cell, so `x` is a position's `x >> 16`), `count` (92, int), `repathClaimTick` (96, unsigned), `flags` (100, byte: bit 0 `active`, *has a route*; bit 1 `flag_1`, *wants a search*; bit 2 `flag_2`, the blocked bit last sent over the network; bit 3 `flag_3`, *changed since sent*) | | `PatrolGoal` | 28 | `points` (12, 3 `Point16`), `count` (24, int) | | `LiteGoal` | 40 | `pos` (12, `Vec3`), `vel` (24, `Vec3`), `heading` (36, signed 16-bit), `field_26` (38, stays 0), `netDirtyFlags` (39, byte: bit 0 `dirty`, bits 1-2 `mode`) | -| `PackedPosGoal` | 39 | `pos`, `vel`, `heading`, `field_26` as `LiteGoal` (the layout's `PackedGoal`) | +| `PackedPosGoal` | 39 | `pos`, `vel`, `heading`, `field_26`, the fields of its base record `PackedGoal` (which `LiteGoal` also starts with) | The replay names `points`, `count`, `repathClaimTick`, `flags`, `posX` to `posZ`, `velX` to `velZ`, `heading`, `netDirtyFlags`; `points` is written as its bytes (`x:...`). @@ -191,14 +191,19 @@ any class word ("Kit gaps", section 7). The embedded `PathOrderAttach` has a cla | --- | --- | --- | | `Game.ticks`, `Game.seaLevel` (unsigned byte), `Game.gravity`, `Game.overflowBucket` | game | the tick; the water line; the tilt; whether a unit is off the map | | `Game.units`, `Game.unitsEnd` | units | the unit table, units of 280 bytes, for the limits of section 4 | -| `Unit.pos` (`posX`, `posY`, `posZ`; `xWhole`, `yWhole`, `zWhole` are the high halves), `heading`, `pitch`, `cell`, `footprint` (`Point16`), `flags`, `carrier`, `transportPiece` (byte), `def`, `player`, `list`, `spatialBucket`, `id`, `weapons[0].weapon` | units | as section 4 says; the unit's mode is `Unit.flags` bits 0-1 and its move rate bits 2-3 | -| `UnitDef.maxvelocity`, `brakerate`, `acceleration`, `bankscale`, `pitchscale`, `moverate1`, `moverate2`, `movementclass`, `turnrate` (unsigned 16-bit), `altitude` (signed 16-bit), `draft` (byte), `flags1` | units | bit 11 (`flying`): an aircraft; bit 19 (`b19`): stays at or above the water line when carried; bit 22 (`b22`): a sea unit; bits 12 and 19 (mask 0x81000): no slowdown under water | -| `WeaponDef.range` | weapons | a follow offset | +| `Unit.pos` (`posX`, `posY`, `posZ`; `xWhole`, `yWhole`, `zWhole` are the high halves), `heading`, `pitch`, `cell`, `footprint` (`Point16`), `flags`, `carrier`, `transportPiece` (byte), `def`, `player`, `list`, `spatialBucket`, `id`, `weapons[0].weapon` (replay `weapon0Def`) | units | as section 4 says; the unit's mode is `Unit.flags` bits 0-1 and its move rate bits 2-3 | +| `UnitDef.maxvelocity`, `brakerate`, `acceleration`, `bankscale`, `pitchscale`, `moverate1`, `moverate2`, `movementclass`, `turnrateUnsigned` (the 16 bits of `turnrate`, read unsigned; this spec writes `turnrate` for it), `altitude` (signed 16-bit), `draft` (byte), `flags1` | units | bit 11 (`flying`): an aircraft; bit 19 (`b19`): stays at or above the water line when carried; bit 22 (`b22`): a sea unit; bits 12 and 19 (mask 0x81000): no slowdown under water | +| `WeaponDef.range` (replay kind `weapondef`) | weapons | a follow offset | | `Player.active`, `Player.type` | players | type 1 or 2 is a player whose units check the map; type 3 gets the remote goals | | `Order.unit`, `Order.flags_42` (bit 0x800000) | orders | the unit an order's target reports to; whether a goal may take a straight route | | `SpatialBucket.bytes` (byte 1: the bucket's ground height in whole units) | map | the cruise height | | a carrier's `UnitMotion.speed` and `velocity` | movement | a carried unit takes them | +A recording's read set also lists fields the module need not read (`Game.width_142a3`, `Game.height_142a7`, and in +some `Apply` calls `Projectile` and `Unit.flags` fields): `r` lines are the call's inputs, and a read is never +compared. The replay schema lists `units.LoadUnit` among movement's imports: only the engine slot `LoadTarget` uses it, +so the entry does not list it. + ### Between ticks Nothing outside the block. Every motion, goal and target lives in the block from its allocation to its `SimFree`. @@ -260,7 +265,8 @@ else *r* > 0.5 gives no; 0x1 with `ref.owner` 0 gives no; 0x4 with `u.heading` 16-bit) gives no; 0x8 with |`u.pos.y` − *at.y*| > 0x10000 gives no; otherwise yes. When Pos(t) fails here (a followed unit that is gone or off the map), the answer is no ("Gaps in the kit"). For an air maneuver: yes when hyp(`u.pos.x` − `target.x`, `u.pos.z` − `target.z`) rounded to a float, divided by 65536, is below 48; else yes when -`headingSet` and Head((0, 0, 0), `other`) is `heading`; else no. It writes nothing. +`headingSet` and A(−`other.x`, −`other.z`), before it is kept to 16 bits (−32768 to 32768), equals `heading` read +unsigned (so a negative angle never matches); else no. It writes nothing. **Whether it stays after it is reached, Keep(t)**: a move target whose `flags` has 0x1 and whose `ref.owner` is not 0; no other. @@ -332,7 +338,8 @@ A size below 8 gives 0. An unknown kind (325 included) gives 0, and so does a si - a *unit* is valid when it is not 0, at least `Game.units`, below `Game.unitsEnd`, and a multiple of 280 bytes from `Game.units`; -- a *target* is valid when it is not 0 and its class word is one of the five target kinds' (section 3); +- a *target* is valid when it is not 0, its record lies inside the block, and its class word is one of the five + target kinds' (section 3); a module reads nothing outside the block to decide it; - for DESTROY_TARGET, SET_ALTITUDE, SET_APPROACH_RADIUS and SET_HEADING, `target` must be valid, and `unit` is not looked at; for the others, `unit` must be valid and, but for NEW, have a motion; SET_TARGET's `target` must be 0 or valid; @@ -350,7 +357,7 @@ The recordings hold no event outside these limits, and no outcome 0. | SET_TARGET 326 | Give(*M*'s goal, `target`) | 1 | | DESTROY_TARGET 327 | a move target first makes `units.UnitRefUnlink` of its `ref`; then `SimFree(target)`. No goal's `target` changes | 1 | | SET_FLIGHT_MODE 328 | when `mode` differs from the event's *m*: for *m* 1, `speed` and `velocity` become 0, then Tilt(*u*, (0, 0, 0)) (below), then SET_STATE_BITS with `mask` 1 and `set` 0; for any other *m*, SET_STATE_BITS with `mask` 1 and `set` 1; then `mode` becomes *m*. When it is the same, nothing | 1 | -| SET_ALTITUDE 329 | a move target: `flags` gains 0x8, `altitude` becomes the low 16 bits of `value`, and when `flags` has 0x20, `pos.y` becomes (*g* + `value`) << 16, at most 0x1ff0000, where *g* is `map.GetGroundHeight(&pos)` when that is above `Game.seaLevel`, and `Game.seaLevel` otherwise (Q1). An air maneuver target: nothing | 1 for those two kinds; 0 for the other kinds, with no change | +| SET_ALTITUDE 329 | a move target: `flags` gains 0x8, `altitude` becomes the low 16 bits of `value`, and when `flags` has 0x20, `pos.y` becomes (*g* + `value`) << 16 with the full 32-bit `value`, at most 0x1ff0000, where *g* is `map.GetGroundHeight(&pos)` when that is above `Game.seaLevel`, and `Game.seaLevel` otherwise (Q1). An air maneuver target: nothing | 1 for those two kinds; 0 for the other kinds, with no change | | SET_APPROACH_RADIUS 330 | a move target: `flags` gains 0x10 and `approachRadius` becomes the low 16 bits of `value` | 1; 0 for another kind | | SET_HEADING 331 | a move target: `flags` gains 0x40 and `heading` becomes the low 16 bits of `value` | 1; 0 for another kind | @@ -438,14 +445,16 @@ are 0; then START_SCRIPT MoveRate1, 2 or 3 (2, 3, 4) for rates 1 to 3; then MOVE ### `ApplyPathEvent(event, size, waypoints)` -A size below 20 does nothing. *g* is the event's `requester`; an event whose requester is not an AI search goal of -this module (by its class word) does nothing (ozgb/btm#25). +A size below 20 does nothing, and so does a kind other than 0 to 2. *g* is the event's `requester`; an event whose +requester is 0, not inside the block, or not an AI search goal of this module (by its class word) does nothing, with +no read outside the block and no trap (ozgb/btm#25). - **STARTED** (size at least 24; otherwise nothing): when the event's `target` is a valid target (section 4, `Apply`), `repathClaimTick` becomes the event's `tick`, and Report(that target, 0x100 when `start` is `PATH_START_DIRECT`, 0x200 otherwise). A STARTED with an invalid target does nothing. - **PROGRESS**: nothing. -- **FINISHED** (size at least 28; otherwise nothing): with *n* = `count`: when *n* is 0 and *g* has a target *t* +- **FINISHED** (size at least 28; otherwise nothing; a negative `count` does nothing, ozgb/btm#25): with *n* = + `count`: when *n* is 0 and *g* has a target *t* that Reached(*t*, owner) says no to, Report(*t*, 0x40); `active` is cleared; `count` and `points` stay. When *n* > 0: `count` becomes min(*n*, 20), points 0 to `count` − 1 become the first waypoints (the rest stay), and `active` is set. Either way `flag_1` is cleared and `flag_3` set. @@ -514,8 +523,8 @@ los_radar's header) whose `unit` is the unit's block offset. under water, (cap × 0x8000) >> 16. - **The ground steering widths**: *k* is the 64-bit product of |*δ*| (0 to 32768) and `speed`, divided by `turnrate` and truncated, kept to 32 bits; `2 × brakerate` wraps at 32 bits; *lim* is hi(*k*²) times 4, wrapping. - The reference never divides by a `turnrate` of 0 here (no moving ground unit has one); a module must not trap on - it, and what it gives is not judged. + A `turnrate` of 0 here, a `brakerate` of 0 in the ground steering and a `maxvelocity` of 0 in the flying + drag are in no recording; a module must not trap on them, and what it gives is not judged. - **Comparisons**: `repathClaimTick` against the tick is unsigned. Every other comparison is signed, `turnrate` and the ANGLES heading being unsigned 16-bit values widened to int. - **The carried water line**: `(seaLevel − draft)`, its low 16 bits as a signed whole, times 65536. @@ -538,8 +547,7 @@ los_radar's header) whose `unit` is the unit's block offset. - **Q1**: SET_ALTITUDE asks `map.GetGroundHeight` twice, with the same position, when the ground is above the water line, and once when it is not. -- **Q2**: `NewRingApproach` stores its `inner` argument as the ring's `outer` and its `outer` argument as `inner` - (so a caller that passes the outer radius first gets a ring the right way round). +- **Q2**: `NewRingApproach` stores its `inner` argument as the ring's `outer` and its `outer` argument as `inner`. - **Q3**: `NewPathOrderToUnitAtAngle` stores its `angle` as the target's `piece`; the target's `heading` stays 0. - **Q4**: a footprint marker's position is the middle column of its rectangle but its last row (`y2`), not the middle row. @@ -624,9 +632,13 @@ everything those goals do, a move target's follow offset (flags 0x2), an air man - **SET_TARGET's points.** An AI search goal's new two-point route is not written as a `w` line in the `Apply` that makes it; the following call's `r` line restores it. - **An unset position.** When Reached asks a followed move target whose unit is gone or off the map, the reference - compares with a position it never set. No recording reaches it; this spec answers no. + compares with a position it never set. No recording reaches it; this spec answers no (ozgb/btm#25). - **`Unit.pitch`.** The recordings carry no `pitch` line for the units they move, so the cap's slope index is 0 in every recorded call. +- **The flying roundings.** No recording separates the float and double steps of section 5 (Q8 included): a module + that rounds them otherwise still replays the six recordings equal. Only scenarios, or a kit vector, would judge them. +- **New objects in the recordings.** Which fields a recording lists as `w` lines for a newly made object follows the + recorder's rules (`docs/replay-format.md`), not this spec: a name reused after a `SimFree` lists fields that are 0. ## 8. Kit version From 649004a91934473fa59a2c03323168976432a1e3 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:35:10 +0000 Subject: [PATCH 03/12] Update: Pin the movement spec to interfaces-v110 Re-pin to interfaces-v110 and reference-traces-v65: payloads of every publish are recorded, class words come from the kit's table, and the new recordings cover DESTROY, LOAD and TargetType. Examples cite the new recordings with their payloads; the kit gaps they close are dropped. Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 139 ++++++++++++++++++++++++++-------------------- 1 file changed, 78 insertions(+), 61 deletions(-) diff --git a/specs/movement.md b/specs/movement.md index 57a0f09..c5bdaeb 100644 --- a/specs/movement.md +++ b/specs/movement.md @@ -90,8 +90,14 @@ is the `int` kind, sign-extended from its low 16 bits (ABI 7). | `services.SimFree` | `[linear] -> void` | freeing them | | `services.Emit` | `[linear, int] -> void` | every publish of section 4, "Effects" | -The recordings carry `map.CanPlaceUnitFootprint` as `services.ScheduleMapCanPlaceUnitFootprint` and `Emit` as -`services.SchedPublish 14 ` (ABI 9.3, "Routes in the recordings"; 14 is movement's outbox). +The recordings carry `map.CanPlaceUnitFootprint` as `services.ScheduleMapCanPlaceUnitFootprint` (ABI 9.3, "Routes +in the recordings"), and each `Emit` as `i services.Emit () `: the payload written as the value of its +kind's payload struct, in field order, from the first `size` bytes (`docs/replay-format.md`, the `effect` row of the +argument kinds' table, and "Event arguments"). The +replay compares the payload byte for byte, so every field of section 4, "Effects", is judged. A block offset in a +payload is written as the object's name (`(336,Unit#1,Order#3,128)`). A named object's `services.SimFree` carries the +size of the record it frees (`services.SimFree AiSearchGoal#1 size 101`); a block allocated in the recording's window +is freed by its `alloc#N` name. `units.UnitRefSetUnit` is in the entry because the engine slot `LoadTarget` uses it; the module imports it (ABI 9.1: every listed import is imported) and never calls it. @@ -181,8 +187,12 @@ position `posX`, `posY`, `posZ`. **Class words.** Word 0 of a goal and of a target says its class, and is what the recordings name an object by (`LiteGoal#1`, `ApproachRadius#2`: `docs/replay-format.md`, "Polymorphic objects") and what the engine slots read -to know the class. The module writes each class's word when it builds the object. The kit does not give the value of -any class word ("Kit gaps", section 7). The embedded `PathOrderAttach` has a class word of its own, which +to know the class. The words are the class word table at the `load_data` base (ABI 7.1, "The class word table starts +the `load_data` region"; `class_words` of `layout.json`): the module copies the table's entry for a class into word 0 +of each object of that class it builds, and learns an object's class by comparing its word 0 with the entries. The +entries movement uses, by `class`: `AiSearchGoal`, `LiteGoal`, `PatrolGoal` and `PackedPosGoal` for the goals; +`PathOrder`, `AirManeuverOrder`, `ApproachRadius`, `RingApproach` and `PointMarker` for the targets (each at `offset` +0). The module never writes the table. The embedded `PathOrderAttach` has a class word of its own, which `units.UnitRefInit` writes. ### Read @@ -492,7 +502,9 @@ slots are only called with an order whose `unit` is a unit, and the `ToUnit` slo ### Effects Each publish is `services.Emit(&payload, size)`. Every payload starts with `MovementEventHeader` (or map's or -los_radar's header) whose `unit` is the unit's block offset. +los_radar's header) whose `unit` is the unit's block offset, and the fields follow in the order the table lists them, +every byte of the `size` written. The recordings write it as the kind, the unit and then the fields, a `Vec3` as its +three words and a cell as its two: `(342,Unit#5,66402231,22347776,21576404,62,20,2)` is a CHANGE_CELL. | Kind | Payload, size | Fields | | --- | --- | --- | @@ -562,85 +574,90 @@ los_radar's header) whose `unit` is the unit's block offset. From the kit's recordings. Each was recomputed from this spec's definitions. -- **NEW, an aircraft**: `tests/replay/movement/orders-air-fights.txt`, call at tick 10 of `Apply` (line 134), kind +- **NEW, an aircraft**: `tests/replay/movement/orders-air-fights.txt`, call at tick 10 of `Apply` (line 118), kind 320 for `Unit#2` (an aircraft of player 0, type 1): `SimAlloc 47` then `SimAlloc 40`; `Unit#2.motion` becomes `UnitMotion#3`, whose `obj` is `LiteGoal#1`, `flags` 1, `movementClass` null; the goal's `pos` is the unit's (39321600, 65536, 19660800), `heading` −32768, `netDirtyFlags` 1. Outcome 1. -- **NEW, a ground unit**: the same file, tick 10 (line 294), `Unit#252` of player 1: `SimAlloc 47`, `SimAlloc 101`, - an `AiSearchGoal#3` with `flags` 8, `count` 0, and the motion's `movementClass` `MovementClass#5`. -- **A disc**: `orders-build-patrol.txt`, tick 150 of `NewApproachRadius`: order `Order#3`, whose unit has footprint - (2,2), x 45878325, y 19689825, radius 16: (45878325 − 1048576 + 524288) >> 20 = 43 and (19689825 − 1048576 + - 524288) >> 20 = 18, so `pos` (43,18), `radiusSq` 1; `SimAlloc 20`, the result `ApproachRadius#1`. -- **A ring** (Q2): the same file, tick 150 of `NewRingApproach`: `inner` 107, `outer` 47 give the fields `inner` 47, - `outer` 107, `innerSq` (47 / 16)² = 4, `outerSq` (107 / 16)² = 36. -- **A footprint marker**: `orders-air-fights.txt`, tick 20 of `NewPointMarker`: `pos` (41,19), `size` (5,5), the - unit's footprint (2,2): `x1` 39, `x2` 46, `y1` 17, `y2` 24. -- **A move target to a unit**: `orders-air.txt`, tick 4095 of `NewPathOrderToUnit`: `Order#2`, unit `Unit#1`, not an - aircraft: `SimAlloc 54`, `UnitRefInit PathOrderAttach#1 Unit#1 null`, then `flags` 1, `piece` −1, +- **NEW, a ground unit**: the same file, tick 10 (line 296), `Unit#252` of player 1: `SimAlloc 47`, `SimAlloc 101`, + an `AiSearchGoal#3` with `flags` 8, `count` 0, `points` all zero, and the motion's `movementClass` + `MovementClass#5`. +- **DESTROY**: `console-ilose.txt`, tick 30 of `Apply` (line 119), `Unit#1` with an AI search goal: `pathfinding.Cancel + AiSearchGoal#1`, `services.SimFree AiSearchGoal#1 size 101`, `services.SimFree UnitMotion#1 size 47`; `Unit#1.motion` + null. Outcome 1. +- **LOAD**: `load-targets.txt`, tick 150 of `Apply` (line 52), kind 322 of size 48 for `Unit#1`, every word of the state 0, + `mode` 1, `flag` 0: the motion keeps the values NEW gave it, so the call writes nothing. Outcome 1. +- **A disc**: `orders-build-patrol.txt`, tick 150 of `NewApproachRadius` (line 153): order `Order#3`, whose unit has + footprint (2,2), x 45878325, y 19689825, radius 16: (45878325 − 1048576 + 524288) >> 20 = 43 and (19689825 − + 1048576 + 524288) >> 20 = 18, so `pos` (43,18), `radiusSq` 1; `SimAlloc 20`, the result `ApproachRadius#1`. +- **A ring** (Q2): the same file, tick 150 of `NewRingApproach` (line 184): `inner` 107, `outer` 47 give the fields + `inner` 47, `outer` 107, `innerSq` (47 / 16)² = 4, `outerSq` (107 / 16)² = 36. +- **A footprint marker**: `orders-air-fights.txt`, tick 20 of `NewPointMarker` (line 640): `pos` (41,19), `size` + (5,5), the unit's footprint (2,2): `x1` 39, `x2` 46, `y1` 17, `y2` 24. +- **TargetType**: `save-midgame.txt`, tick 900 (line 138): `PointMarker#2` gives 6. +- **A move target to a unit**: `orders-air.txt`, tick 4095 of `NewPathOrderToUnit` (line 758): `Order#2`, unit + `Unit#1`, not an aircraft: `SimAlloc 54`, `UnitRefInit PathOrderAttach#1 Unit#1 null`, then `flags` 1, `piece` −1, `followOffset` 0, `unit` `Unit#3` (the order's), `pos` that unit's (51887393, 3014656, 25678911). -- **At an angle** (Q3): `orders-air-repair.txt`, tick 670 of `NewPathOrderToUnitAtAngle`, `angle` 1: `flags` 5, - `piece` 1. -- **SET_TARGET on an AI search goal**: `orders-air-fights.txt`, tick 20 of `Apply` (line 651): `Unit#1` at cell +- **At an angle** (Q3): `orders-air-repair.txt`, tick 670 of `NewPathOrderToUnitAtAngle` (line 255), `angle` 1: + `flags` 5, `piece` 1. +- **SET_TARGET on an AI search goal**: `orders-air-fights.txt`, tick 20 of `Apply` (line 658): `Unit#1` at cell (34,14), position (36700160, ·, 15728640), its goal with no points and `count` 0, its first order's `flags_42` 1062153 (no 0x800000), target `PointMarker#1` (39, 46, 17, 24, footprint (2,2)). `Cancel AiSearchGoal#1`; no old target, so no report. Pos gives *x* = (2 + 42 × 2) << 19 = 45088768, *z* = (2 + 24 × 2) << 19 = 26214400, so - `count` 2 and the points (560,240), (688,400); `active`, `flag_1` and `flag_3` set (`flags` 11); then - `Submit (Unit#1,60,3,(0,0),0,0,39,46,17,24,AiSearchGoal#1,PointMarker#1,0,(0,0))`. (The recording carries no - `w` line for `points`; the next call's `r AiSearchGoal#1.points` holds them: "Gaps in the kit".) -- **Ground steering on that route**: the same file, tick 20 of `UpdateMotion` (line 666), `Unit#1` heading 0, - speed 0, `turnrate` 1044, `acceleration` 9830, `maxvelocity` 78643: the unit turns by −1044 (TURN, 12 bytes; - units writes `heading` −1044), accelerates to 9830 (under the cap 78643), and `velocity` becomes Step(−1044, - 9830): S(−1044, 9830) uses entry 504, −803, and (−803 × 9830 + 4096) >> 13 = −964, so `velocityX` 964 and - `velocityZ` −9783. The unit stays in its cell: MOVE (20). The rate becomes 1 from 0: START_SCRIPT StartMoving, - START_SCRIPT MoveRate1, MOVE_RATE (12 bytes each), then SFX_OCCUPY (8). `lastMoveTick` 20. -- **Flying, with a cell change**: `orders-air.txt`, tick 4091 of `UpdateMotion` (line 469), `Unit#5` with + `count` 2 and the points (560,240), (688,400) (`points` `x:3002f000b0029001` then zeros); `active`, `flag_1` and + `flag_3` set (`flags` 11); then `Submit (Unit#1,60,3,(0,0),0,0,39,46,17,24,AiSearchGoal#1,PointMarker#1,0,(0,0))`. +- **Ground steering on that route**: the same file, tick 20 of `UpdateMotion` (line 674), `Unit#1` heading 0, + speed 0, `pitch` 0, `turnrate` 1044, `acceleration` 9830, `maxvelocity` 78643: the unit turns by −1044 + (`services.Emit (337,Unit#1,-1044) 12`; units' handler writes `heading` −1044), accelerates to 9830 (under the cap + 78643), and `velocity` becomes Step(−1044, 9830): S(−1044, 9830) uses entry 504, −803, and (−803 × 9830 + 4096) >> + 13 = −964, so `velocityX` 964 and `velocityZ` −9783. The unit stays in its cell: `(340,Unit#1,36701124,65536,15718857)`. + The rate becomes 1 from 0: `(347,Unit#1,0)` (StartMoving), `(347,Unit#1,2)` (MoveRate1), `(343,Unit#1,1)`, then + `(346,Unit#1)`. `lastMoveTick` 20. +- **Flying, with a cell change**: `orders-air.txt`, tick 4091 of `UpdateMotion` (line 476), `Unit#5` with `LiteGoal#3` (`pos` (43530660, 22347776, 65093149), `vel` 0, `heading` 27720), the unit at (66662745, 22347776, 21084818) heading 27720, `velocity` (−258360, 0, 488660), `speed` 552755, `p2` (−98618, −49661, 98627), `acceleration` 22937, `maxvelocity` 655360, `brakerate` 393216. The drag scale is 0x10000 − 2293 = 63243; *s* 8.1392… > *m* 6.0, so the cap applies; the heading wants no turn (no TURN); *κ* −0.03037…, the correction steps −0.16223… and 0.31012…, so `velocityX` −260514, `velocityZ` 491586, `speed` 556349, then `p2` (−95841, - −47178, 96621) and TILT (16). The new position is in cell (62,20): `CanPlaceUnitFootprint UnitDef#51 5 (62,20) 2 = - 1`, then REMOVE_UNIT (8), CHANGE_CELL (32), ADD_UNIT (8), MOVED (12), UPDATE_UNIT (8); the rate stays 2; SFX_OCCUPY - (8). `lastMoveTick` 4091. -- **Carried**: `units-transport.txt`, `Unit#1` carried by `Unit#3`, `transportPiece` 255: `GetPiecePosition Unit#3 - -1`, SET_POSITION (24), `GetPieceAngles Unit#3 -1 = (19,32865,0)`, ANGLES (20), MOVED (12), SFX_OCCUPY (8). -- **SET_ALTITUDE** (Q1): `orders-air-fights.txt`, tick 30 of `Apply` (line 1048): `PathOrder#1` with `flags` 32 and - `pos` (41943040, 65536, 22282240), value 35: two `GetGroundHeight pos=(41943040,22282240) = 1` (1 is above the - water line 0), `altitude` 35, `flags` 40, `posY` (1 + 35) << 16 = 2359296. -- **SET_APPROACH_RADIUS**: `orders-air.txt`, tick 4095: `PathOrder#4` `flags` 9 becomes 25, `approachRadius` 48. -- **DESTROY_TARGET**: `orders-air-repair.txt`, tick 685: `UnitRefUnlink PathOrder#2.ref`, then `SimFree`. -- **SET_TARGET 0 on a lite goal**: `orders-air-repair.txt`, tick 670: ORDER_FLAGS (16) on the old target, `target` - null. -- **UnitTarget**: `orders-air-fights.txt`, tick 15: `Unit#1`'s goal has no target: null. - -No recording covers: DESTROY, LOAD, SET_SPEED, SET_HEADING, a refused event (outcome 0), SET_ALTITUDE on an air -maneuver target or on a target of another kind, NEW for a player of type 3 (patrol and packed position goals) and -everything those goals do, a move target's follow offset (flags 0x2), an air maneuver target, `ApplyPathEvent`, -`HasNetState`, `TargetType`, `NewPathOrderToUnitAt` and `NewAirManeuverOrder`. + −47178, 96621) and `(338,Unit#5,-2501,0)`. The new position (66402231, 22347776, 21576404) is in cell (62,20): + `CanPlaceUnitFootprint UnitDef#51 5 (62,20) 2 = 1`, then `(161,Unit#5)`, + `(342,Unit#5,66402231,22347776,21576404,62,20,2)`, `(160,Unit#5)`, `(341,Unit#5,1)`, `(128,Unit#5)`; the rate stays + 2; `(346,Unit#5)`. `lastMoveTick` 4091. +- **Carried**: `units-transport.txt`, tick 4408 (line 3), `Unit#1` carried by `Unit#3`, `transportPiece` 255: + `GetPiecePosition Unit#3 -1 = (41945692,107263,37833406)`, `(344,Unit#1,41945692,107263,37833406,0)`, + `GetPieceAngles Unit#3 -1 = (19,32865,0)`, `(339,Unit#1,19,32865,0)` (the heading zero-extended), `(341,Unit#1,0)`, + `(346,Unit#1)`. +- **SET_FLIGHT_MODE**: `orders-air-fights.txt`, tick 30 of `Apply` (line 1021), `Unit#5` from `mode` 1 to 2: + `(345,Unit#5,1,1)`, then `flags` 2. +- **SET_ALTITUDE** (Q1): the same file, tick 30 of `Apply` (line 1055): `PathOrder#1` with `flags` 32 and `pos` + (41943040, 65536, 22282240), value 35: two `GetGroundHeight pos=(41943040,22282240) = 1` (1 is above the water + line 0), `altitude` 35, `flags` 40, `posY` (1 + 35) << 16 = 2359296. +- **SET_APPROACH_RADIUS**: `orders-air.txt`, tick 4095 (line 822): `PathOrder#4` `flags` 9 becomes 25, + `approachRadius` 48. +- **DESTROY_TARGET**: `orders-air-repair.txt`, tick 670 (line 308): `UnitRefUnlink PathOrder#1.ref`, then + `services.SimFree PathOrder#1 size 54`. +- **SET_TARGET 0 on a lite goal**: the same file, tick 670 (line 300): `(336,Unit#4,Order#2,128)` (ORDER_FLAGS 0x80 + for the old target, whose order's unit is `Unit#4`), `target` null. +- **UnitTarget**: `orders-air-fights.txt`, tick 15 (line 525): `Unit#1`'s goal has no target: null. + +No recording covers: SET_SPEED, SET_HEADING, a refused event (outcome 0), SET_ALTITUDE on an air maneuver target or on +a target of another kind, SET_FLIGHT_MODE to mode 1, NEW for a player of type 3 (patrol and packed position goals) and +everything those goals do, DESTROY of a lite goal, a move target's follow offset (flags 0x2), an air maneuver target, +`ApplyPathEvent`, `HasNetState`, `NewPathOrderToUnitAt` and `NewAirManeuverOrder`. ### Gaps in the kit -- **Class words.** The kit names the objects of the recordings by their class (`docs/replay-format.md`, - "Polymorphic objects") and the engine slots read the class of a goal or target from its first word, but no file of - the kit gives the value a module writes there for each class. A module built from this spec can't make an object - the replay or an engine slot recognises until the kit gives those values. - **A blocked entry.** The entry is `blocked`, with no budgets (ABI 4.2); the gate's recordings route judges a module without them (ABI section 15). -- **Payloads.** The recordings carry each publish as `services.SchedPublish 14 `, without its fields, so the - gate compares an effect by its size and by what its subscribers write (the `o` lines after it), not by its - payload. -- **SET_TARGET's points.** An AI search goal's new two-point route is not written as a `w` line in the `Apply` that - makes it; the following call's `r` line restores it. - **An unset position.** When Reached asks a followed move target whose unit is gone or off the map, the reference compares with a position it never set. No recording reaches it; this spec answers no (ozgb/btm#25). -- **`Unit.pitch`.** The recordings carry no `pitch` line for the units they move, so the cap's slope index is 0 in - every recorded call. +- **`Unit.pitch`.** The recordings carry `pitch` from −3563 to 3356, so the slope index of the cap is −2 to 1 in + every recorded call; the table's entries for −5 to −3 and 2 to 5 are judged by nothing. - **The flying roundings.** No recording separates the float and double steps of section 5 (Q8 included): a module - that rounds them otherwise still replays the six recordings equal. Only scenarios, or a kit vector, would judge them. + that rounds them otherwise still replays the recordings equal. Only scenarios, or a kit vector, would judge them. - **New objects in the recordings.** Which fields a recording lists as `w` lines for a newly made object follows the recorder's rules (`docs/replay-format.md`), not this spec: a name reused after a `SimFree` lists fields that are 0. ## 8. Kit version -Kit `interfaces-v68` and `reference-traces-v55`, the versions the gate judges against. Interface `movement` 5.0. +Kit `interfaces-v110` and `reference-traces-v65`, the versions the gate judges against. Interface `movement` 5.0. The imports are against `units` 7, `map` 9, `scripts` 3, `pathfinding` 4 and `services` 4. From 542cdd79c88ce1acd142986b88720972ba3810a7 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 12:44:41 +0000 Subject: [PATCH 04/12] Add: Implement the movement module Assisted-by: Claude Code:claude-sonnet-5-5 --- movement/.gitignore | 2 + movement/Cargo.lock | 7 + movement/Cargo.toml | 14 + movement/build.sh | 10 + movement/ld-wrap.sh | 9 + movement/mathtest/Cargo.lock | 7 + movement/mathtest/Cargo.toml | 4 + movement/mathtest/src/main.rs | 41 + movement/src/lib.rs | 1580 +++++++++++++++++++++++++++++++++ movement/src/math.rs | 621 +++++++++++++ movement/src/tables.rs | 4 + movement/tools/gen_tables.py | 29 + 12 files changed, 2328 insertions(+) create mode 100644 movement/.gitignore create mode 100644 movement/Cargo.lock create mode 100644 movement/Cargo.toml create mode 100755 movement/build.sh create mode 100755 movement/ld-wrap.sh create mode 100644 movement/mathtest/Cargo.lock create mode 100644 movement/mathtest/Cargo.toml create mode 100644 movement/mathtest/src/main.rs create mode 100644 movement/src/lib.rs create mode 100644 movement/src/math.rs create mode 100644 movement/src/tables.rs create mode 100644 movement/tools/gen_tables.py diff --git a/movement/.gitignore b/movement/.gitignore new file mode 100644 index 0000000..89ff056 --- /dev/null +++ b/movement/.gitignore @@ -0,0 +1,2 @@ +*.wasm +target/ diff --git a/movement/Cargo.lock b/movement/Cargo.lock new file mode 100644 index 0000000..652eef1 --- /dev/null +++ b/movement/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "movement" +version = "0.1.0" diff --git a/movement/Cargo.toml b/movement/Cargo.toml new file mode 100644 index 0000000..78d0494 --- /dev/null +++ b/movement/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "movement" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[profile.release] +panic = "abort" +opt-level = "s" +lto = true +codegen-units = 1 +debug = false diff --git a/movement/build.sh b/movement/build.sh new file mode 100755 index 0000000..b6fefbd --- /dev/null +++ b/movement/build.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Builds module.wasm: link at the manifest's data base 622592 and table base 464, then the kit's fuel pass. +set -e +cd "$(dirname "$0")" +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=622592 -C link-arg=--table-base=464 \ + -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/movement.wasm "$T/raw.wasm" +python3 -I /data/tools/wasm_fuel.py "$T/raw.wasm" -o module.wasm diff --git a/movement/ld-wrap.sh b/movement/ld-wrap.sh new file mode 100755 index 0000000..ada6ff2 --- /dev/null +++ b/movement/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/movement/mathtest/Cargo.lock b/movement/mathtest/Cargo.lock new file mode 100644 index 0000000..a9c723e --- /dev/null +++ b/movement/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/movement/mathtest/Cargo.toml b/movement/mathtest/Cargo.toml new file mode 100644 index 0000000..4ef48d0 --- /dev/null +++ b/movement/mathtest/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "mathtest" +version = "0.1.0" +edition = "2021" diff --git a/movement/mathtest/src/main.rs b/movement/mathtest/src/main.rs new file mode 100644 index 0000000..09382f8 --- /dev/null +++ b/movement/mathtest/src/main.rs @@ -0,0 +1,41 @@ +#[path = "../../src/tables.rs"] +mod tables; +#[path = "../../src/math.rs"] +mod math; +use std::fs; + +fn r32(b: &[u8], o: &mut usize) -> i32 { let v = i32::from_le_bytes(b[*o..*o+4].try_into().unwrap()); *o += 4; v } +fn rf64(b: &[u8], o: &mut usize) -> f64 { let v = f64::from_le_bytes(b[*o..*o+8].try_into().unwrap()); *o += 8; v } + +fn main() { + let d = "/data/runtime/vectors/"; + // fixed-size int records + let mut fails = 0; let mut n = 0; + let b = fs::read(d.to_owned() + "scaled_sine.bin").unwrap(); + let mut o = 0; while o < b.len() { let a = r32(&b,&mut o); let s = r32(&b,&mut o); let r = r32(&b,&mut o); n+=1; if math::scaled_sine(a,s)!=r {fails+=1;} } + println!("scaled_sine {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "scaled_cosine.bin").unwrap(); + let mut o = 0; while o < b.len() { let a = r32(&b,&mut o); let s = r32(&b,&mut o); let r = r32(&b,&mut o); n+=1; if math::scaled_cosine(a,s)!=r {fails+=1;} } + println!("scaled_cosine {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "angle_of_vector.bin").unwrap(); + let mut o = 0; while o < b.len() { let x = r32(&b,&mut o); let z = r32(&b,&mut o); let r = r32(&b,&mut o); n+=1; if math::angle_of_vector(x,z)!=r {fails+=1; if fails<5 {println!("A {} {} -> {} want {}",x,z,math::angle_of_vector(x,z),r);} } } + println!("angle {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "rotate_point.bin").unwrap(); + let mut o = 0; while o < b.len() { let a = r32(&b,&mut o); let x = r32(&b,&mut o); let z = r32(&b,&mut o); let rx = r32(&b,&mut o); let rz = r32(&b,&mut o); n+=1; let (px,pz)=math::rotate_point(a,x,z); if px!=rx||pz!=rz {fails+=1; if fails<5 {println!("R {} {} {} -> {} {} want {} {}",a,x,z,px,pz,rx,rz);} } } + println!("rotate {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "hypot.bin").unwrap(); + let mut o = 0; while o < b.len() { let x = rf64(&b,&mut o); let y = rf64(&b,&mut o); let r = rf64(&b,&mut o); n+=1; let h = math::hypot(x,y); if h.to_bits()!=r.to_bits() {fails+=1; if fails<5 {println!("H {} {} -> {} want {}",x,y,h,r);} } } + println!("hypot {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "sqrt.bin").unwrap(); + let mut o = 0; while o < b.len() { let x = rf64(&b,&mut o); let r = rf64(&b,&mut o); n+=1; if math::sqrt(x).to_bits()!=r.to_bits() {fails+=1;} } + println!("sqrt {} fails {}", n, fails); + let (mut n, mut fails) = (0,0); + let b = fs::read(d.to_owned() + "ftol.bin").unwrap(); + let mut o = 0; while o < b.len() { let x = rf64(&b,&mut o); let r = r32(&b,&mut o); n+=1; if math::ftol(x)!=r {fails+=1;} } + println!("ftol {} fails {}", n, fails); +} diff --git a/movement/src/lib.rs b/movement/src/lib.rs new file mode 100644 index 0000000..f1c77a5 --- /dev/null +++ b/movement/src/lib.rs @@ -0,0 +1,1580 @@ +#![no_std] + +mod math; +mod tables; + +use core::ptr::{addr_of, read_unaligned, read_volatile, write_unaligned}; +use math::*; + +#[link(wasm_import_module = "units")] +extern "C" { + #[link_name = "UnitRefUnlink"] + fn unit_ref_unlink(r: u32); + #[link_name = "UnitRefInit"] + fn unit_ref_init(r: u32, unit: u32, other: u32); + #[link_name = "UnitRefSetUnit"] + fn unit_ref_set_unit(r: u32, unit: u32); +} +#[link(wasm_import_module = "map")] +extern "C" { + #[link_name = "CanPlaceUnitFootprint"] + fn can_place(def: u32, id: i32, cell: *const i32, mode: i32) -> i32; + #[link_name = "GetGroundHeight"] + fn ground_height(pos: u32) -> i32; +} +#[link(wasm_import_module = "scripts")] +extern "C" { + #[link_name = "GetPiecePosition"] + fn piece_position(unit: u32, piece: i32, out: *mut i32); + #[link_name = "GetPieceAngles"] + fn piece_angles(unit: u32, piece: i32, out: *mut i16); +} +#[link(wasm_import_module = "pathfinding")] +extern "C" { + #[link_name = "Submit"] + fn path_submit(req: *const i32); + #[link_name = "Cancel"] + fn path_cancel(requester: u32); +} +#[link(wasm_import_module = "services")] +extern "C" { + #[link_name = "SimAlloc"] + fn sim_alloc(size: i32) -> u32; + #[link_name = "SimFree"] + fn sim_free(p: u32); + #[link_name = "Emit"] + fn emit_raw(p: *const i32, 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: [u8; 8] = [0; 8]; +#[no_mangle] +pub static mut g_blockBase: u32 = 0; + +// Never written: keeps the import `UnitRefSetUnit` and the table import that the ABI lists. +static mut NEVER: u32 = 0; +static KEEP: [extern "C" fn(u32) -> i32; 1] = [UnitTarget]; + +const BLOCK_MAX: u64 = 268435456; +const CLASS_WORDS: u32 = 0x1010_0000; + +// ---- memory ----------------------------------------------------------------------------------- + +#[inline(always)] +fn base() -> u32 { + unsafe { read_volatile(addr_of!(g_blockBase)) } +} +#[inline(always)] +fn game() -> u32 { + unsafe { read_volatile(addr_of!(g_game)) } +} +#[inline(always)] +fn r32(a: u32) -> i32 { + unsafe { read_unaligned(a as *const i32) } +} +#[inline(always)] +fn ru32(a: u32) -> u32 { + unsafe { read_unaligned(a as *const u32) } +} +#[inline(always)] +fn r16(a: u32) -> i32 { + unsafe { read_unaligned(a as *const i16) as i32 } +} +#[inline(always)] +fn ru16(a: u32) -> i32 { + unsafe { read_unaligned(a as *const u16) as i32 } +} +#[inline(always)] +fn r8(a: u32) -> i32 { + unsafe { *(a as *const u8) as i32 } +} +#[inline(always)] +fn w32(a: u32, v: i32) { + unsafe { write_unaligned(a as *mut i32, v) } +} +#[inline(always)] +fn w16(a: u32, v: i32) { + unsafe { write_unaligned(a as *mut i16, v as i16) } +} +#[inline(always)] +fn w8(a: u32, v: i32) { + unsafe { *(a as *mut u8) = v as u8 } +} +/// A block offset stored at `a`, as an address (0 stays 0). +#[inline(always)] +fn rref(a: u32) -> u32 { + let o = ru32(a); + if o == 0 { + 0 + } else { + base().wrapping_add(o) + } +} +#[inline(always)] +fn wref(a: u32, target: u32) { + w32(a, off(target) as i32) +} +#[inline(always)] +fn off(a: u32) -> u32 { + if a == 0 { + 0 + } else { + a.wrapping_sub(base()) + } +} +fn emit(w: &[i32]) { + unsafe { emit_raw(w.as_ptr(), (w.len() * 4) as i32) } +} + +// ---- record offsets ------------------------------------------------------------------------------ + +const G_TICKS: u32 = 232007; +const G_SEA: u32 = 82559; +const G_GRAVITY: u32 = 82531; +const G_OVERFLOW: u32 = 82615; +const G_UNITS: u32 = 82775; +const G_UNITS_END: u32 = 82779; + +const U_MOTION: u32 = 0; +const U_WEAPON: u32 = 16; +const U_LIST: u32 = 92; +const U_HEADING: u32 = 102; +const U_PITCH: u32 = 104; +const U_POS: u32 = 106; +const U_XW: u32 = 108; +const U_YW: u32 = 112; +const U_ZW: u32 = 116; +const U_CELL: u32 = 118; +const U_FP: u32 = 126; +const U_BUCKET: u32 = 130; +const U_CARRIER: u32 = 134; +const U_DEF: u32 = 146; +const U_PLAYER: u32 = 150; +const U_ID: u32 = 168; +const U_TPIECE: u32 = 249; +const U_FLAGS: u32 = 272; +const UNIT_SIZE: u32 = 280; + +const D_MAXV: u32 = 402; +const D_BRAKE: u32 = 410; +const D_ACC: u32 = 414; +const D_BANK: u32 = 418; +const D_PITCH: u32 = 422; +const D_MR1: u32 = 430; +const D_MR2: u32 = 434; +const D_MCLASS: u32 = 438; +const D_TURN: u32 = 442; +const D_ALT: u32 = 540; +const D_DRAFT: u32 = 556; +const D_FLAGS1: u32 = 577; + +const M_OBJ: u32 = 0; +const M_CLASS: u32 = 4; +const M_VEL: u32 = 8; +const M_P2: u32 = 20; +const M_SPEED: u32 = 32; +const M_TURN: u32 = 36; +const M_LAST: u32 = 42; +const M_FLAGS: u32 = 46; + +const GO_TARGET: u32 = 4; +const GO_OWNER: u32 = 8; +const AI_POINTS: u32 = 12; +const AI_COUNT: u32 = 92; +const AI_CLAIM: u32 = 96; +const AI_FLAGS: u32 = 100; +const PA_COUNT: u32 = 24; +const LG_POS: u32 = 12; +const LG_VEL: u32 = 24; +const LG_HEADING: u32 = 36; +const LG_NET: u32 = 39; + +const T_SOURCE: u32 = 4; +const PO_FLAGS: u32 = 8; +const PO_APPROACH: u32 = 10; +const PO_ALT: u32 = 12; +const PO_HEADING: u32 = 14; +const PO_PIECE: u32 = 16; +const PO_UNIT: u32 = 18; +const PO_REF: u32 = 22; +const PO_OWNER: u32 = 26; +const PO_POS: u32 = 38; +const PO_FOLLOW: u32 = 50; +const AM_FLAGS: u32 = 8; +const AM_TARGET: u32 = 10; +const AM_OTHER: u32 = 22; +const AM_HEADING: u32 = 36; +const AM_SELF: u32 = 40; + +// class word table indices +const CW_AI: u32 = 0; +const CW_AIR: u32 = 1; +const CW_DISC: u32 = 2; +const CW_LITE: u32 = 18; +const CW_PACKED: u32 = 20; +const CW_PATHORDER: u32 = 21; +const CW_PATROL: u32 = 23; +const CW_PLAIN: u32 = 24; +const CW_MARKER: u32 = 26; +const CW_RING: u32 = 27; + +fn cw(i: u32) -> u32 { + ru32(CLASS_WORDS + 4 * i) +} + +// goal classes +const GK_NONE: i32 = 0; +const GK_AI: i32 = 1; +const GK_LITE: i32 = 2; +const GK_PACKED: i32 = 3; +const GK_PATROL: i32 = 4; + +fn goal_kind(g: u32) -> i32 { + let w = ru32(g); + if w == cw(CW_AI) { + GK_AI + } else if w == cw(CW_LITE) { + GK_LITE + } else if w == cw(CW_PACKED) { + GK_PACKED + } else if w == cw(CW_PATROL) { + GK_PATROL + } else { + GK_NONE + } +} + +// target kinds are the numbers TargetType gives +fn target_kind(t: u32) -> i32 { + let w = ru32(t); + if w == cw(CW_PATHORDER) { + 2 + } else if w == cw(CW_AIR) { + 3 + } else if w == cw(CW_DISC) { + 4 + } else if w == cw(CW_RING) { + 5 + } else if w == cw(CW_MARKER) { + 6 + } else { + 0 + } +} + +fn target_size(kind: i32) -> u32 { + match kind { + 2 => 54, + 3 => 44, + 4 => 20, + 5 => 28, + 6 => 24, + _ => 0, + } +} + +/// A target offset that is not 0, whose record lies inside the block and whose class word is a target kind's. +fn valid_target(o: u32) -> bool { + if o == 0 || (o as u64) + 4 > BLOCK_MAX { + return false; + } + let k = target_kind(base().wrapping_add(o)); + k != 0 && (o as u64) + target_size(k) as u64 <= BLOCK_MAX +} + +fn valid_unit(o: u32) -> bool { + if o == 0 { + return false; + } + let g = game(); + let first = ru32(g + G_UNITS); + let end = ru32(g + G_UNITS_END); + o >= first && o < end && (o - first) % UNIT_SIZE == 0 +} + +fn seed_target(size: i32, class: u32, order: u32) -> u32 { + let t = unsafe { sim_alloc(size) }; + w32(t, cw(class) as i32); + w32(t + T_SOURCE, order as i32); + t +} + +// ---- small helpers ------------------------------------------------------------------------------- + +fn ticks() -> i32 { + r32(game() + G_TICKS) +} +fn sea_level() -> i32 { + r8(game() + G_SEA) +} +fn uheading(u: u32) -> i32 { + r16(u + U_HEADING) +} +fn upos(u: u32) -> [i32; 3] { + [r32(u + U_POS), r32(u + U_POS + 4), r32(u + U_POS + 8)] +} +fn udef(u: u32) -> u32 { + rref(u + U_DEF) +} +fn head(px: i32, pz: i32, qx: i32, qz: i32) -> i32 { + angle_of_vector(px.wrapping_sub(qx), pz.wrapping_sub(qz)) as i16 as i32 +} +fn s_scaled(a: i32, s: i32) -> i32 { + scaled_sine(a, s) +} +fn c_scaled(a: i32, s: i32) -> i32 { + scaled_cosine(a, s) +} +fn mulsh(a: i32, b: i32, k: u32) -> i32 { + (((a as i64) * (b as i64)) >> k) as i32 +} +fn hi_sq(x: i32) -> i32 { + (((x as i64) * (x as i64)) >> 32) as i32 +} +fn hyp_i(x: i32, z: i32) -> f64 { + hypot(x as f64, z as f64) +} +/// (a << 16) / b in 64 bits, low 32 bits; 0 for a zero divisor. +fn div16(a: i32, b: i64) -> i32 { + if b == 0 { + 0 + } else { + (((a as i64) << 16) / b) as i32 + } +} + +fn cruise(u: u32) -> i32 { + let d = udef(u); + let alt = r16(d + D_ALT); + let flags1 = ru32(d + D_FLAGS1); + if flags1 & (1 << 22) != 0 { + alt.wrapping_add(sea_level()).wrapping_shl(16) + } else { + let bucket = rref(u + U_BUCKET); + alt.wrapping_add(r8(bucket + 1)).wrapping_shl(16) + } +} + + +fn centre(cx: i32, cy: i32, fx: i32, fy: i32) -> (i32, i32) { + ( + cx.wrapping_mul(2).wrapping_add(fx).wrapping_shl(19), + cy.wrapping_mul(2).wrapping_add(fy).wrapping_shl(19), + ) +} + +fn cell_of(px: i32, pz: i32, fx: i32, fy: i32) -> (i32, i32) { + ( + (px.wrapping_sub(fx.wrapping_mul(0x80000)).wrapping_add(0x80000) >> 20) as i16 as i32, + (pz.wrapping_sub(fy.wrapping_mul(0x80000)).wrapping_add(0x80000) >> 20) as i16 as i32, + ) +} + +/// The footprint of the unit of the target's source order. +fn source_unit(t: u32) -> u32 { + let order = rref(t + T_SOURCE); + rref(order + 14) +} + +// ---- reporting ------------------------------------------------------------------------------------- + +fn report(t: u32, flags: i32) { + let src = rref(t + T_SOURCE); + if src == 0 { + return; + } + emit(&[336, r32(src + 14), off(src) as i32, flags]); +} + +// ---- targets --------------------------------------------------------------------------------------- + +/// Pos(t): fills `out` or fails. +fn target_pos(t: u32, out: &mut [i32; 3]) -> bool { + match target_kind(t) { + 2 => { + let f = ru16(t + PO_FLAGS); + let pos = t + PO_POS; + if f & 1 != 0 && f & 0x80 == 0 { + let owner = rref(t + PO_OWNER); + if owner == 0 || ru32(owner + U_BUCKET) == ru32(game() + G_OVERFLOW) { + return false; + } + let mut q = [0i32; 3]; + unsafe { piece_position(owner, r16(t + PO_PIECE), q.as_mut_ptr()) }; + if f & 2 != 0 { + let mut a = uheading(owner); + if f & 0x40 != 0 { + a = a.wrapping_add(r16(t + PO_HEADING)) as i16 as i32; + } + let fo = r32(t + PO_FOLLOW); + q[0] = q[0].wrapping_add(s_scaled(a, fo)); + q[2] = q[2].wrapping_add(c_scaled(a, fo)); + } + q[1] = q[1].wrapping_add(r16(t + PO_ALT).wrapping_shl(16)); + if q[1] > 0x1ff0000 { + q[1] = 0x1ff0000; + } + w32(pos, q[0]); + w32(pos + 4, q[1]); + w32(pos + 8, q[2]); + *out = q; + true + } else { + if f & 8 == 0 { + w32(pos + 4, cruise(rref(t + PO_UNIT))); + } + if r32(pos + 4) > 0x1ff0000 { + w32(pos + 4, 0x1ff0000); + } + *out = [r32(pos), r32(pos + 4), r32(pos + 8)]; + true + } + } + 3 => { + let tg = t + AM_TARGET; + let ot = t + AM_OTHER; + *out = [r32(tg), r32(tg + 4), r32(tg + 8)]; + w32(tg, r32(tg).wrapping_add(r32(ot))); + w32(tg + 8, r32(tg + 8).wrapping_add(r32(ot + 8))); + let h = angle_of_vector(r32(ot).wrapping_neg(), r32(ot + 8).wrapping_neg()) & 0xffff; + let hd = ru16(t + AM_HEADING); + if ru16(t + AM_FLAGS) & 1 != 0 && h != hd { + let delta = (hd.wrapping_sub(h)) as i16 as i32; + let lim = ru16(udef(rref(t + AM_SELF)) + D_TURN) >> 3; + let delta = if delta > lim { + lim + } else if delta < -lim { + -lim + } else { + delta + }; + let (rx, rz) = rotate_point(delta.wrapping_neg(), r32(ot), r32(ot + 8)); + w32(ot, rx); + w32(ot + 4, 0); + w32(ot + 8, rz); + } + true + } + 4 => { + let u = source_unit(t); + let (x, z) = centre(r16(t + 8), r16(t + 10), r16(u + U_FP), r16(u + U_FP + 2)); + out[0] = x; + out[2] = z; + true + } + 5 => { + let u = source_unit(t); + let (cx, cz) = centre(r16(t + 8), r16(t + 10), r16(u + U_FP), r16(u + U_FP + 2)); + let a = head(r32(u + U_POS), r32(u + U_POS + 8), cx, cz); + let r = (r32(t + 12).wrapping_add(r32(t + 16)) / 2).wrapping_shl(16); + out[0] = cx.wrapping_add(s_scaled(a, r)); + out[2] = cz.wrapping_add(c_scaled(a, r)); + true + } + 6 => { + let u = source_unit(t); + let m = (r32(t + 8).wrapping_add(r32(t + 12)) / 2) as i16 as i32; + let y2 = r32(t + 20) as i16 as i32; + out[0] = r16(u + U_FP).wrapping_add(m.wrapping_mul(2)).wrapping_shl(19); + out[2] = r16(u + U_FP + 2).wrapping_add(y2.wrapping_mul(2)).wrapping_shl(19); + true + } + _ => false, + } +} + +fn target_in(t: u32, x: i32, y: i32) -> bool { + match target_kind(t) { + 4 => { + let dx = x.wrapping_sub(r16(t + 8)); + let dy = y.wrapping_sub(r16(t + 10)); + let r = r32(t + 12) / 16; + dx.wrapping_mul(dx).wrapping_add(dy.wrapping_mul(dy)) <= r.wrapping_mul(r) + } + 5 => { + let dx = x.wrapping_sub(r16(t + 8)); + let dy = y.wrapping_sub(r16(t + 10)); + let d = dx.wrapping_mul(dx).wrapping_add(dy.wrapping_mul(dy)); + let i = r32(t + 12) / 16; + let o = r32(t + 16) / 16; + d >= i.wrapping_mul(i) && d <= o.wrapping_mul(o) + } + 6 => { + let (x1, x2, y1, y2) = (r32(t + 8), r32(t + 12), r32(t + 16), r32(t + 20)); + ((x == x1 || x == x2) && y1 <= y && y <= y2) || ((y == y1 || y == y2) && x1 <= x && x <= x2) + } + _ => false, + } +} + +fn reached(t: u32, u: u32) -> bool { + match target_kind(t) { + 4 | 5 | 6 => target_in(t, r16(u + U_CELL), r16(u + U_CELL + 2)), + 2 => { + let mut at = [0i32; 3]; + if !target_pos(t, &mut at) { + return false; + } + let f = ru16(t + PO_FLAGS); + let up = upos(u); + let h = hyp_i(up[0].wrapping_sub(at[0]), up[2].wrapping_sub(at[2])); + let r = (h as f32) * 0.0000152587890625f32; + if f & 0x10 != 0 { + return (r16(t + PO_APPROACH) as f64) > (r as f64); + } + if (r as f64) > 0.5 { + return false; + } + let owner = rref(t + PO_OWNER); + if f & 1 != 0 && owner == 0 { + return false; + } + if f & 4 != 0 && ru16(u + U_HEADING) != ru16(owner + U_HEADING) { + return false; + } + if f & 8 != 0 { + let dy = up[1].wrapping_sub(at[1]); + let ady = if dy < 0 { dy.wrapping_neg() } else { dy }; + if ady > 0x10000 { + return false; + } + } + true + } + 3 => { + let up = upos(u); + let tg = t + AM_TARGET; + let h = hyp_i(up[0].wrapping_sub(r32(tg)), up[2].wrapping_sub(r32(tg + 8))); + let d = (h as f32) / 65536.0f32; + if d < 48.0f32 { + return true; + } + if ru16(t + AM_FLAGS) & 1 != 0 { + let a = angle_of_vector(r32(t + AM_OTHER).wrapping_neg(), r32(t + AM_OTHER + 8).wrapping_neg()); + return a == ru16(t + AM_HEADING); + } + false + } + _ => false, + } +} + +fn keep(t: u32) -> bool { + target_kind(t) == 2 && ru16(t + PO_FLAGS) & 1 != 0 && rref(t + PO_OWNER) != 0 +} + +fn want(t: u32) -> Option { + match target_kind(t) { + 2 => { + let f = ru16(t + PO_FLAGS); + let owner = rref(t + PO_OWNER); + if f & 0x84 != 0 && owner != 0 { + if f & 2 != 0 { + let up = upos(rref(t + PO_UNIT)); + let op = upos(owner); + Some(head(up[0], up[2], op[0], op[2])) + } else if f & 0x40 != 0 { + Some(r16(t + PO_HEADING)) + } else { + Some(uheading(owner)) + } + } else if f & 0x40 != 0 { + Some(r16(t + PO_HEADING)) + } else { + None + } + } + 3 => { + let sp = upos(rref(t + AM_SELF)); + Some(head(sp[0], sp[2], r32(t + AM_TARGET), r32(t + AM_TARGET + 8))) + } + _ => None, + } +} + +/// Fills the goal area of a path request (words 2 to 9). +fn area(t: u32, req: &mut [i32; 14]) { + match target_kind(t) { + 4 => { + req[2] = 1; + req[3] = r32(t + 8); + req[4] = r32(t + 12); + } + 5 => { + req[2] = 2; + req[3] = r32(t + 8); + req[4] = r32(t + 12); + req[5] = r32(t + 16); + } + 6 => { + req[2] = 3; + req[6] = r32(t + 8); + req[7] = r32(t + 12); + req[8] = r32(t + 16); + req[9] = r32(t + 20); + } + _ => {} + } +} + +// ---- goals ----------------------------------------------------------------------------------------- + +fn ask(g: u32) { + let t = rref(g + GO_TARGET); + let mut req = [0i32; 14]; + req[0] = r32(g + GO_OWNER); + req[1] = r32(g + AI_CLAIM).wrapping_add(60); + area(t, &mut req); + req[10] = off(g) as i32; + req[11] = off(t) as i32; + unsafe { path_submit(req.as_ptr()) }; +} + +fn give(g: u32, t: u32) { + let old = rref(g + GO_TARGET); + match goal_kind(g) { + GK_AI => { + let o = rref(g + GO_OWNER); + unsafe { path_cancel(off(g)) }; + if old != 0 { + report(old, 0x80); + } + wref(g + GO_TARGET, t); + let mut r = false; + let mut wnt = false; + if t != 0 { + wnt = true; + let count = r32(g + AI_COUNT); + let last = AI_POINTS + 4 * ((count - 1).clamp(0, 19) as u32); + if count >= 3 && target_in(t, r16(g + last) >> 4, r16(g + last + 2) >> 4) { + r = true; + wnt = false; + } else { + let mut p = [0i32; 3]; + if target_pos(t, &mut p) { + let up = upos(o); + if count >= 3 { + let a = ftol(hyp_i(r16(g + last).wrapping_shl(16).wrapping_sub(p[0]), r16(g + last + 2).wrapping_shl(16).wrapping_sub(p[2]))); + let b = ftol(hyp_i(up[0].wrapping_sub(p[0]), up[2].wrapping_sub(p[2]))); + if a.wrapping_mul(2) < b { + r = true; + } + } + let list = rref(o + U_LIST); + if !r && list != 0 && ru32(list + 66) & 0x800000 == 0 { + w32(g + AI_COUNT, 2); + w16(g + AI_POINTS, r16(o + U_XW)); + w16(g + AI_POINTS + 2, r16(o + U_ZW)); + w16(g + AI_POINTS + 4, p[0] >> 16); + w16(g + AI_POINTS + 6, p[2] >> 16); + r = true; + } + } + } + } + let claim = ru32(g + AI_CLAIM); + if claim <= (ticks() as u32).wrapping_sub(10) { + w32(g + AI_CLAIM, 0); + } + let f = r8(g + AI_FLAGS); + w8(g + AI_FLAGS, (f & !3) | (r as i32) | ((wnt as i32) << 1) | 8); + if wnt { + ask(g); + } + } + GK_LITE => { + if old != 0 { + report(old, 0x80); + } + wref(g + GO_TARGET, t); + w8(g + LG_NET, r8(g + LG_NET) | 1); + } + GK_PACKED | GK_PATROL => { + if old != 0 { + report(old, 0x80); + } + wref(g + GO_TARGET, t); + } + _ => {} + } +} + +fn tick_ai(g: u32, m: u32) { + let o = rref(g + GO_OWNER); + let t = rref(g + GO_TARGET); + if t != 0 && reached(t, o) { + report(t, 0x20); + if !keep(t) { + give(g, 0); + } + } + let count = r32(g + AI_COUNT); + if count >= 2 { + let dx = r16(o + U_XW).wrapping_sub(r16(g + AI_POINTS + 4)); + let dz = r16(o + U_ZW).wrapping_sub(r16(g + AI_POINTS + 6)); + if dx.wrapping_mul(dx).wrapping_add(dz.wrapping_mul(dz)) <= 25 { + let mut i = 0u32; + while (i as i32) < count - 1 && i < 19 { + let s = g + AI_POINTS + 4 * (i + 1); + let d = g + AI_POINTS + 4 * i; + w32(d, r32(s)); + i += 1; + } + w32(g + AI_COUNT, count - 1); + if count - 1 < 2 { + w8(g + AI_FLAGS, r8(g + AI_FLAGS) & !1); + } + w8(g + AI_FLAGS, r8(g + AI_FLAGS) | 8); + } + } + if rref(g + GO_TARGET) != 0 && (r8(m + M_FLAGS) & 4 != 0 || r32(g + AI_COUNT) < 2) { + w8(g + AI_FLAGS, r8(g + AI_FLAGS) | 2); + ask(g); + } +} + +fn tick_packed(g: u32, m: u32, lite: bool) { + let o = rref(g + GO_OWNER); + if lite { + let mode = r8(m + M_FLAGS) & 3; + if mode != (r8(g + LG_NET) >> 1) & 3 { + w8(g + LG_NET, r8(g + LG_NET) | 1); + } + } + let t = rref(g + GO_TARGET); + if t == 0 { + return; + } + let old = [r32(g + LG_POS), r32(g + LG_POS + 4), r32(g + LG_POS + 8)]; + let mut p = old; + if target_pos(t, &mut p) { + w32(g + LG_POS, p[0]); + w32(g + LG_POS + 4, p[1]); + w32(g + LG_POS + 8, p[2]); + } + let pos = [r32(g + LG_POS), r32(g + LG_POS + 4), r32(g + LG_POS + 8)]; + w32(g + LG_VEL, pos[0].wrapping_sub(old[0])); + w32(g + LG_VEL + 4, pos[1].wrapping_sub(old[1])); + w32(g + LG_VEL + 8, pos[2].wrapping_sub(old[2])); + let op = upos(o); + let dist = ftol(hyp_i(op[0].wrapping_sub(pos[0]), op[2].wrapping_sub(pos[2]))); + if dist > 0xa00000 { + w32(g + LG_POS + 4, cruise(o)); + } + if dist > 0x1400000 { + w16(g + LG_HEADING, head(op[0], op[2], pos[0], pos[2])); + } else if let Some(h) = want(t) { + w16(g + LG_HEADING, h); + } else if dist > 0x100000 { + w16(g + LG_HEADING, head(op[0], op[2], pos[0], pos[2])); + } + if reached(t, o) { + report(t, 0x20); + if !keep(t) { + give(g, 0); + } + } +} + +// ---- steering -------------------------------------------------------------------------------------- + +fn turn_by(m: u32, u: u32, delta: i32, t: i32) { + if delta == 0 { + w16(m + M_TURN, 0); + return; + } + let v = if delta >= t { + t + } else if delta <= -t { + -t + } else { + delta + }; + let v = v as i16 as i32; + w16(m + M_TURN, v); + emit(&[337, off(u) as i32, v]); +} + +fn push(m: u32, u: u32, d: u32, a: i32) { + let mut speed = r32(m + M_SPEED).wrapping_add(a); + if speed < 0 { + speed = 0; + } + let i = (r16(u + U_PITCH) >> 11).clamp(-5, 5); + let f: i32 = match i { + -5 => 25, + -4 => 55, + -3 => 70, + -2 => 85, + -1 | 0 => 100, + 1 => 75, + 2 => 50, + 3 => 25, + 4 => 20, + _ => 15, + }; + let c1 = (((f as i64) << 16) * (r32(d + D_MAXV) as i64)) >> 16; + let mut cap = (((c1 as i32 as i64) << 16) / 0x640000) as i32; + if r16(u + U_YW) < sea_level() && ru32(d + D_FLAGS1) & 0x81000 == 0 { + cap = (((cap as i64) * 0x8000) >> 16) as i32; + } + if speed > cap { + speed = cap; + } + w32(m + M_SPEED, speed); + let h = uheading(u); + w32(m + M_VEL, s_scaled(h, speed).wrapping_neg()); + w32(m + M_VEL + 4, 0); + w32(m + M_VEL + 8, c_scaled(h, speed).wrapping_neg()); +} + +fn waypoint(g: u32, kind: i32, i: i32) -> (i32, i32) { + let count = if kind == GK_AI { r32(g + AI_COUNT) } else { r32(g + PA_COUNT) }; + let j = i.min(count - 1).clamp(0, 19) as u32; + let a = g + AI_POINTS + 4 * j; + (r16(a).wrapping_shl(16), r16(a + 2).wrapping_shl(16)) +} + +fn steer_ground(u: u32, m: u32, d: u32) { + let g = rref(m + M_OBJ); + let kind = goal_kind(g); + let route = match kind { + GK_AI => r8(g + AI_FLAGS) & 1 != 0, + GK_PATROL => r32(g + PA_COUNT) >= 2, + _ => return, + }; + let brake = r32(d + D_BRAKE); + if !route { + w16(m + M_TURN, 0); + push(m, u, d, brake.wrapping_neg()); + return; + } + let (p0x, p0z) = waypoint(g, kind, 0); + let (mut p1x, mut p1z) = waypoint(g, kind, 1); + let (p2x, p2z) = waypoint(g, kind, 2); + let pp = upos(u); + let gd = ftol(hyp_i(p1x.wrapping_sub(pp[0]), p1z.wrapping_sub(pp[2]))); + if gd > 5242880 { + let ex = p1x.wrapping_sub(p0x); + let ez = p1z.wrapping_sub(p0z); + let l = ftol(hyp_i(ex, ez)); + if l >= 0x10000 { + let nx = (((ex as i64) << 16) / (l as i64)) as i32; + let nz = (((ez as i64) << 16) / (l as i64)) as i32; + let b = gd.wrapping_sub(5242880).min(l); + p1x = p1x.wrapping_sub(mulsh(nx, b, 16)); + p1z = p1z.wrapping_sub(mulsh(nz, b, 16)); + } + } + let d1 = hi_sq(p1x.wrapping_sub(pp[0])).wrapping_add(hi_sq(p1z.wrapping_sub(pp[2]))); + let d2 = hi_sq(p2x.wrapping_sub(pp[0])).wrapping_add(hi_sq(p2z.wrapping_sub(pp[2]))); + let delta = (head(pp[0], pp[2], p1x, p1z).wrapping_sub(uheading(u))) as i16 as i32; + let t = ru16(d + D_TURN); + turn_by(m, u, delta, t); + let speed = r32(m + M_SPEED); + let ad = (delta as i64).abs(); + let k = if t == 0 { 0 } else { ((ad * (speed as i64)) / (t as i64)) as i32 }; + let tt = (((speed as i64) * (speed as i64)) >> 16) as i32; + let q = div16(tt, (brake.wrapping_mul(2)) as i64); + let r = hi_sq(q); + let lim = hi_sq(k).wrapping_mul(4); + if d1 > lim && d2 > r { + push(m, u, d, r32(d + D_ACC)); + } else { + push(m, u, d, brake.wrapping_neg()); + } +} + +fn tilt(u: u32, m: u32, d: u32, v: [i32; 3]) { + let mut p2 = [r32(m + M_P2), r32(m + M_P2 + 4), r32(m + M_P2 + 8)]; + for i in 0..3 { + p2[i] = mulsh(p2[i], 0xf333, 16).wrapping_add(v[i]); + w32(m + M_P2 + 4 * i as u32, p2[i]); + } + let (x, _z) = rotate_point(uheading(u), p2[0], p2[2]); + let n = (((r32(game() + G_GRAVITY) as i64) << 16) / 0xccd) as i32; + let bank = angle_of_vector(mulsh(r32(d + D_BANK), x.wrapping_neg(), 16), n) as i16 as i32; + let pitch = angle_of_vector(mulsh(r32(d + D_PITCH), x.wrapping_neg(), 16), n) as i16 as i32; + emit(&[338, off(u) as i32, bank, pitch]); +} + +fn steer_air(u: u32, m: u32, d: u32) { + let g = rref(m + M_OBJ); + let kind = goal_kind(g); + if kind != GK_LITE && kind != GK_PACKED { + return; + } + if r8(m + M_FLAGS) & 3 != 2 { + for i in 0..3 { + w32(m + M_VEL + 4 * i, 0); + } + w32(m + M_SPEED, 0); + w16(m + M_TURN, 0); + return; + } + let a = [r32(g + LG_POS), r32(g + LG_POS + 4), r32(g + LG_POS + 8)]; + let b = [r32(g + LG_VEL), r32(g + LG_VEL + 4), r32(g + LG_VEL + 8)]; + let h = r16(g + LG_HEADING); + let mut v = [r32(m + M_VEL), r32(m + M_VEL + 4), r32(m + M_VEL + 8)]; + let v0 = v; + // 1. drag + let scale = 0x10000i32.wrapping_sub(div16(r32(d + D_ACC), r32(d + D_MAXV) as i64)); + for i in 0..3 { + v[i] = mulsh(v[i], scale, 16); + } + // 2. cap + const K: f32 = 0.0000152587890625f32; + let s = (hyp_i(v[0], v[2]) as f32) * K; + let mm = (r32(d + D_BRAKE) as f32) * K; + if s > mm { + let f = ftol(((mm as f64) / (s as f64)) * 65536.0); + v[0] = mulsh(v[0], f, 16); + v[2] = mulsh(v[2], f, 16); + let e = ftol(((s as f64) - (mm as f64)) * 65536.0); + let uh = uheading(u); + v[0] = v[0].wrapping_sub(s_scaled(uh, e)); + v[2] = v[2].wrapping_sub(c_scaled(uh, e)); + } + // 3. + let pp = upos(u); + let da = [pp[0].wrapping_sub(a[0]), pp[1].wrapping_sub(a[1]), pp[2].wrapping_sub(a[2])]; + let db = [v[0].wrapping_sub(b[0]), v[1].wrapping_sub(b[1]), v[2].wrapping_sub(b[2])]; + // 4. climb + if ru32(u + U_BUCKET) != ru32(game() + G_OVERFLOW) { + let sp = r32(m + M_SPEED); + let l = if (sp & !3) < 0x40000 { 0x10000 } else { sp >> 2 }; + v[1] = if da[1] <= -l { + l + } else if da[1] >= l { + -l + } else { + da[1].wrapping_neg() + }; + } + for i in 0..3 { + w32(m + M_VEL + 4 * i as u32, v[i]); + } + // 5. turn + turn_by(m, u, (h.wrapping_sub(uheading(u))) as i16 as i32, ru16(d + D_TURN)); + // 6. correction + let big_a = ((r32(d + D_ACC) as f32) * K) as f64; + let mut hh = hyp_i(da[0], da[2]) * 0.0000152587890625f64; + if hh < 8.0 { + hh = 8.0; + } + let kappa = -sqrt((2.0 * big_a) / hh); + let cx = ((da[0] as f64) * kappa) * 0.0000152587890625f64 - (db[0] as f64) * 0.0000152587890625f64; + let cz = ((da[2] as f64) * kappa) * 0.0000152587890625f64 - (db[2] as f64) * 0.0000152587890625f64; + let xf = cx as f32; + let zf = cz as f32; + let mu = hypot(cx, cz); + let (xs, zs); + if mu > big_a { + xs = (xf as f64) * (big_a / mu); + zs = (((zf as f64) * (big_a / mu)) as f32) as f64; + } else { + xs = xf as f64; + zs = zf as f64; + } + v[0] = v[0].wrapping_add(ftol(xs * 65536.0)); + v[2] = v[2].wrapping_add(ftol(zs * 65536.0)); + // 7. speed + let (fx, fy, fz) = (v[0] as f64, v[1] as f64, v[2] as f64); + w32(m + M_SPEED, ftol(sqrt((fx * fx + fy * fy) + fz * fz))); + for i in 0..3 { + w32(m + M_VEL + 4 * i as u32, v[i]); + } + // 8. + tilt(u, m, d, [v[0].wrapping_sub(v0[0]), v[1].wrapping_sub(v0[1]), v[2].wrapping_sub(v0[2])]); +} + +// ---- moving ---------------------------------------------------------------------------------------- + +fn do_move(u: u32, m: u32, d: u32) { + let carrier = rref(u + U_CARRIER); + let mode = r8(m + M_FLAGS) & 3; + let uo = off(u) as i32; + if carrier != 0 { + let k = r8(u + U_TPIECE) as i8 as i32; + let mut v = [0i32; 3]; + unsafe { piece_position(carrier, k, v.as_mut_ptr()) }; + if ru32(d + D_FLAGS1) & (1 << 19) != 0 { + let floor = ((sea_level().wrapping_sub(r8(d + D_DRAFT))) as i16 as i32).wrapping_shl(16); + if v[1] < floor { + v[1] = floor; + } + } + emit(&[344, uo, v[0], v[1], v[2], mode]); + let mut ang = [0i16; 3]; + unsafe { piece_angles(carrier, k, ang.as_mut_ptr()) }; + emit(&[339, uo, ang[0] as i32, ang[1] as u16 as i32, ang[2] as i32]); + let cm = rref(carrier + U_MOTION); + for i in 0..3 { + w32(m + M_VEL + 4 * i, if cm != 0 { r32(cm + M_VEL + 4 * i) } else { 0 }); + } + w32(m + M_SPEED, if cm != 0 { r32(cm + M_SPEED) } else { 0 }); + emit(&[341, uo, 0]); + return; + } + let up = upos(u); + let vel = [r32(m + M_VEL), r32(m + M_VEL + 4), r32(m + M_VEL + 8)]; + let mut p = [up[0].wrapping_add(vel[0]), up[1].wrapping_add(vel[1]), up[2].wrapping_add(vel[2])]; + let umode = (ru32(u + U_FLAGS) & 3) as i32; + if p == up && mode == umode { + return; + } + w32(m + M_LAST, ticks()); + let (fx, fy) = (r16(u + U_FP), r16(u + U_FP + 2)); + let c = cell_of(p[0], p[2], fx, fy); + let ucell = (r16(u + U_CELL), r16(u + U_CELL + 2)); + if c == ucell && mode == umode { + emit(&[340, uo, p[0], p[1], p[2]]); + return; + } + let player = rref(u + U_PLAYER); + if r32(player) != 0 && (r8(player + 115) == 1 || r8(player + 115) == 2) { + let cc = [c.0 as i16 as u16 as i32 | ((c.1 as i16 as u16 as i32) << 16)]; + let ok = unsafe { can_place(d, ru16(u + U_ID), cc.as_ptr(), mode) }; + let f = r8(m + M_FLAGS); + w8(m + M_FLAGS, if ok == 0 { f | 4 } else { f & !4 }); + } + if r8(m + M_FLAGS) & 4 != 0 { + let (cx, cz) = centre(ucell.0, ucell.1, fx, fy); + p[0] = p[0].clamp(cx.wrapping_sub(0x7ffff), cx.wrapping_add(0x7ffff)); + p[2] = p[2].clamp(cz.wrapping_sub(0x7ffff), cz.wrapping_add(0x7ffff)); + let half = r32(d + D_MAXV) / 2; + if r32(m + M_SPEED) > half { + w32(m + M_SPEED, half); + let h = uheading(u); + w32(m + M_VEL, s_scaled(h, half).wrapping_neg()); + w32(m + M_VEL + 4, 0); + w32(m + M_VEL + 8, c_scaled(h, half).wrapping_neg()); + } + emit(&[340, uo, p[0], p[1], p[2]]); + } else { + emit(&[161, uo]); + emit(&[342, uo, p[0], p[1], p[2], c.0, c.1, mode]); + emit(&[160, uo]); + emit(&[341, uo, 1]); + emit(&[128, uo]); + } +} + +fn move_rate(u: u32, m: u32, d: u32) { + let speed = r32(m + M_SPEED); + let turn = r16(m + M_TURN); + let rate = if r8(m + M_FLAGS) & 4 != 0 || rref(u + U_CARRIER) != 0 || (speed == 0 && turn == 0) { + 0 + } else if speed <= r32(d + D_MR1) { + 1 + } else if speed > r32(d + D_MR2) { + 3 + } else { + 2 + }; + let cur = ((ru32(u + U_FLAGS) >> 2) & 3) as i32; + if rate == cur { + return; + } + let uo = off(u) as i32; + if rate == 0 { + emit(&[347, uo, 1]); + } else if cur == 0 { + emit(&[347, uo, 0]); + } + if rate != 0 { + emit(&[347, uo, rate + 1]); + } + emit(&[343, uo, rate]); +} + +#[no_mangle] +pub extern "C" fn UpdateMotion(u: u32) { + let m = rref(u + U_MOTION); + if m == 0 { + return; + } + let d = udef(u); + let g = rref(m + M_OBJ); + match goal_kind(g) { + GK_AI => tick_ai(g, m), + GK_LITE => tick_packed(g, m, true), + GK_PACKED => tick_packed(g, m, false), + _ => {} + } + if ru32(d + D_FLAGS1) & (1 << 11) != 0 { + steer_air(u, m, d); + } else { + steer_ground(u, m, d); + } + do_move(u, m, d); + move_rate(u, m, d); + emit(&[346, off(u) as i32]); +} + +// ---- Apply ---------------------------------------------------------------------------------------- + +fn destroy_target(t: u32) { + if target_kind(t) == 2 { + unsafe { unit_ref_unlink(t + PO_REF) }; + } + unsafe { sim_free(t) }; +} + +fn set_state_bits(u: u32, mask: i32, set: i32) { + emit(&[345, off(u) as i32, mask, set]); +} + +fn set_mode(m: u32, mode: i32) { + w8(m + M_FLAGS, (r8(m + M_FLAGS) & !3) | (mode & 3)); +} + +#[no_mangle] +pub extern "C" fn Apply(ev: u32, size: u32) -> i32 { + if size < 8 { + return 0; + } + let kind = r32(ev); + let need = match kind { + 320 | 321 => 8, + 322 => 48, + 323 | 324 | 326 | 327 | 328 => 12, + 329 | 330 | 331 => 16, + _ => return 0, + }; + // 328 and 323 carry a MovementSetMode (12), 324 a SetSpeed (12), 326/327 a Target (12) + if size < need { + return 0; + } + let uo = ru32(ev + 4); + let tgt_kind = matches!(kind, 327 | 329 | 330 | 331); + let u = base().wrapping_add(uo); + if tgt_kind { + if !valid_target(ru32(ev + 8)) { + return 0; + } + } else { + if !valid_unit(uo) { + return 0; + } + if kind != 320 && r32(u + U_MOTION) == 0 { + return 0; + } + if kind == 326 { + let t = ru32(ev + 8); + if t != 0 && !valid_target(t) { + return 0; + } + } + if kind == 323 || kind == 328 { + let mode = r32(ev + 8); + if !(0..=3).contains(&mode) { + return 0; + } + } + if kind == 322 { + let mode = r32(ev + 40); + let flag = r32(ev + 44); + if !(0..=3).contains(&mode) || !(0..=1).contains(&flag) { + return 0; + } + } + } + match kind { + 320 => { + let d = udef(u); + let motion = unsafe { sim_alloc(47) }; + let player = rref(u + U_PLAYER); + let air = ru32(d + D_FLAGS1) & (1 << 11) != 0; + let (size, class) = if r32(player) != 0 && r8(player + 115) == 3 { + if air { + (39, CW_PACKED) + } else { + (28, CW_PATROL) + } + } else if air { + (40, CW_LITE) + } else { + (101, CW_AI) + }; + let goal = unsafe { sim_alloc(size) }; + w32(u + U_MOTION, off(motion) as i32); + w32(motion + M_OBJ, off(goal) as i32); + w32(motion + M_CLASS, r32(d + D_MCLASS)); + w8(motion + M_FLAGS, 1); + w32(goal, cw(class) as i32); + w32(goal + GO_OWNER, uo as i32); + if class == CW_AI { + w8(goal + AI_FLAGS, 8); + } else if class == CW_LITE || class == CW_PACKED { + let p = upos(u); + w32(goal + LG_POS, p[0]); + w32(goal + LG_POS + 4, p[1]); + w32(goal + LG_POS + 8, p[2]); + w16(goal + LG_HEADING, uheading(u)); + if class == CW_LITE { + w8(goal + LG_NET, 1); + } + } + 1 + } + 321 => { + let m = rref(u + U_MOTION); + let g = rref(m + M_OBJ); + if g != 0 { + match goal_kind(g) { + GK_AI => unsafe { path_cancel(off(g)) }, + GK_PACKED => { + let t = rref(g + GO_TARGET); + if t != 0 { + destroy_target(t); + w32(g + GO_TARGET, 0); + } + } + _ => {} + } + unsafe { sim_free(g) }; + } + unsafe { sim_free(m) }; + w32(u + U_MOTION, 0); + 1 + } + 322 => { + let m = rref(u + U_MOTION); + for i in 0..3 { + w32(m + M_VEL + 4 * i, r32(ev + 8 + 4 * i)); + w32(m + M_P2 + 4 * i, r32(ev + 20 + 4 * i)); + } + w32(m + M_SPEED, r32(ev + 32)); + w16(m + M_TURN, r32(ev + 36)); + w8(m + M_FLAGS, (r8(m + M_FLAGS) & 0xf8) | (r32(ev + 40) & 3) | ((r32(ev + 44) & 1) << 2)); + 1 + } + 323 => { + set_mode(rref(u + U_MOTION), r32(ev + 8)); + 1 + } + 324 => { + w32(rref(u + U_MOTION) + M_SPEED, r32(ev + 8)); + 1 + } + 326 => { + let m = rref(u + U_MOTION); + give(rref(m + M_OBJ), rref(ev + 8)); + 1 + } + 327 => { + destroy_target(rref(ev + 8)); + 1 + } + 328 => { + let m = rref(u + U_MOTION); + let mode = r32(ev + 8); + if (r8(m + M_FLAGS) & 3) != mode { + if mode == 1 { + w32(m + M_SPEED, 0); + for i in 0..3 { + w32(m + M_VEL + 4 * i, 0); + } + tilt(u, m, udef(u), [0, 0, 0]); + set_state_bits(u, 1, 0); + } else { + set_state_bits(u, 1, 1); + } + set_mode(m, mode); + } + 1 + } + 329 => { + let t = rref(ev + 8); + let value = r32(ev + 12); + match target_kind(t) { + 2 => { + w16(t + PO_FLAGS, ru16(t + PO_FLAGS) | 8); + w16(t + PO_ALT, value); + if ru16(t + PO_FLAGS) & 0x20 != 0 { + let sea = sea_level(); + let mut gh = unsafe { ground_height(t + PO_POS) }; + if gh > sea { + gh = unsafe { ground_height(t + PO_POS) }; + } else { + gh = sea; + } + let y = gh.wrapping_add(value).wrapping_shl(16); + w32(t + PO_POS + 4, if y > 0x1ff0000 { 0x1ff0000 } else { y }); + } + 1 + } + 3 => 1, + _ => 0, + } + } + 330 => { + let t = rref(ev + 8); + if target_kind(t) == 2 { + w16(t + PO_FLAGS, ru16(t + PO_FLAGS) | 0x10); + w16(t + PO_APPROACH, r32(ev + 12)); + 1 + } else { + 0 + } + } + 331 => { + let t = rref(ev + 8); + if target_kind(t) == 2 { + w16(t + PO_FLAGS, ru16(t + PO_FLAGS) | 0x40); + w16(t + PO_HEADING, r32(ev + 12)); + 1 + } else { + 0 + } + } + _ => 0, + } +} + +// ---- path events ------------------------------------------------------------------------------------ + +#[no_mangle] +pub extern "C" fn ApplyPathEvent(ev: u32, size: u32, waypoints: u32) { + if size < 20 { + return; + } + let kind = r32(ev); + if !(0..=2).contains(&kind) { + return; + } + let go = ru32(ev + 8); + if go == 0 || (go as u64) + 101 > BLOCK_MAX { + return; + } + let g = base().wrapping_add(go); + if goal_kind(g) != GK_AI { + return; + } + match kind { + 0 => { + if size < 24 { + return; + } + let to = ru32(ev + 12); + if valid_target(to) { + w32(g + AI_CLAIM, r32(ev + 16)); + report(base().wrapping_add(to), if r32(ev + 20) == 0 { 0x100 } else { 0x200 }); + } + } + 2 => { + if size < 28 { + return; + } + let n = r32(ev + 24); + if n < 0 { + return; + } + if n == 0 { + let t = rref(g + GO_TARGET); + if t != 0 && !reached(t, rref(g + GO_OWNER)) { + report(t, 0x40); + } + w8(g + AI_FLAGS, r8(g + AI_FLAGS) & !1); + } else { + let c = n.min(20); + w32(g + AI_COUNT, c); + for i in 0..c as u32 { + w32(g + AI_POINTS + 4 * i, r32(waypoints + 4 * i)); + } + w8(g + AI_FLAGS, r8(g + AI_FLAGS) | 1); + } + w8(g + AI_FLAGS, (r8(g + AI_FLAGS) & !2) | 8); + } + _ => {} + } +} + +// ---- queries ----------------------------------------------------------------------------------------- + +#[no_mangle] +pub extern "C" fn HasNetState(u: u32) -> i32 { + let m = rref(u + U_MOTION); + if m == 0 { + return 0; + } + let g = rref(m + M_OBJ); + match goal_kind(g) { + GK_AI => { + let f = r8(g + AI_FLAGS); + (f & 8 != 0 || ((r8(m + M_FLAGS) >> 2) & 1) != ((f >> 2) & 1)) as i32 + } + GK_LITE => r8(g + LG_NET) & 1, + _ => 0, + } +} + +#[no_mangle] +pub extern "C" fn TargetType(t: u32) -> i32 { + if unsafe { read_volatile(addr_of!(NEVER)) } != 0 { + unsafe { + unit_ref_set_unit(0, 0); + read_volatile(addr_of!(KEEP[0]))(0); + } + } + if t == 0 { + return 0; + } + let a = base().wrapping_add(t); + let k = target_kind(a); + if k != 0 { + k + } else if ru32(a) == cw(CW_PLAIN) { + 1 + } else { + 0 + } +} + +#[no_mangle] +pub extern "C" fn UnitTarget(u: u32) -> i32 { + let m = rref(u + U_MOTION); + if m == 0 { + return 0; + } + let g = rref(m + M_OBJ); + r32(g + GO_TARGET) +} + +// ---- target builders ----------------------------------------------------------------------------------- + +fn order_unit(order: u32) -> u32 { + rref(base().wrapping_add(order) + 14) +} + +#[no_mangle] +pub extern "C" fn NewPathOrderAt(order: u32, pos: u32) -> u32 { + let t = seed_target(54, CW_PATHORDER, order); + unsafe { unit_ref_init(t + PO_REF, 0, 0) }; + w16(t + PO_FLAGS, 0x20); + w16(t + PO_PIECE, -1); + wref(t + PO_UNIT, order_unit(order)); + for i in 0..3 { + w32(t + PO_POS + 4 * i, r32(pos + 4 * i)); + } + off(t) +} + +#[no_mangle] +pub extern "C" fn NewPathOrderToUnit(order: u32, unit: u32) -> u32 { + let t = seed_target(54, CW_PATHORDER, order); + unsafe { unit_ref_init(t + PO_REF, unit, 0) }; + w16(t + PO_PIECE, -1); + let ou = order_unit(order); + wref(t + PO_UNIT, ou); + for i in 0..3 { + w32(t + PO_POS + 4 * i, r32(ou + U_POS + 4 * i)); + } + let owner = rref(t + PO_OWNER); + if ru32(udef(owner) + D_FLAGS1) & (1 << 11) != 0 { + w16(t + PO_FLAGS, 7); + let wd = rref(ou + U_WEAPON); + let mut w = if wd != 0 { r32(wd + 220) } else { 0 }; + if w == 0 { + w = 0x64; + } + w32(t + PO_FOLLOW, w.wrapping_shl(16)); + } else { + w16(t + PO_FLAGS, 1); + } + off(t) +} + +#[no_mangle] +pub extern "C" fn NewPathOrderToUnitAt(order: u32, unit: u32, pos: u32) -> u32 { + let t = seed_target(54, CW_PATHORDER, order); + unsafe { unit_ref_init(t + PO_REF, unit, 0) }; + w16(t + PO_FLAGS, 0xa3); + w16(t + PO_PIECE, -1); + wref(t + PO_UNIT, order_unit(order)); + for i in 0..3 { + w32(t + PO_POS + 4 * i, r32(pos + 4 * i)); + } + off(t) +} + +#[no_mangle] +pub extern "C" fn NewPathOrderToUnitAtAngle(order: u32, unit: u32, angle: i32) -> u32 { + let t = seed_target(54, CW_PATHORDER, order); + unsafe { unit_ref_init(t + PO_REF, unit, 0) }; + w16(t + PO_FLAGS, 5); + w16(t + PO_PIECE, angle); + let ou = order_unit(order); + wref(t + PO_UNIT, ou); + for i in 0..3 { + w32(t + PO_POS + 4 * i, r32(ou + U_POS + 4 * i)); + } + off(t) +} + +#[no_mangle] +pub extern "C" fn NewAirManeuverOrder(order: u32, from: u32, to: u32) -> u32 { + let t = seed_target(44, CW_AIR, order); + wref(t + AM_SELF, order_unit(order)); + for i in 0..3 { + w32(t + AM_TARGET + 4 * i, r32(from + 4 * i)); + w32(t + AM_OTHER + 4 * i, r32(to + 4 * i)); + } + off(t) +} + +fn disc_cell(order: u32, x: i32, y: i32) -> (i32, i32) { + let u = order_unit(order); + cell_of(x, y, r16(u + U_FP), r16(u + U_FP + 2)) +} + +#[no_mangle] +pub extern "C" fn NewApproachRadius(order: u32, x: i32, y: i32, radius: i32) -> u32 { + let t = seed_target(20, CW_DISC, order); + let c = disc_cell(order, x, y); + w16(t + 8, c.0); + w16(t + 10, c.1); + w32(t + 12, radius); + let r = radius / 16; + w32(t + 16, r.wrapping_mul(r)); + off(t) +} + +#[no_mangle] +pub extern "C" fn NewRingApproach(order: u32, x: i32, y: i32, inner: i32, outer: i32) -> u32 { + let t = seed_target(28, CW_RING, order); + let c = disc_cell(order, x, y); + w16(t + 8, c.0); + w16(t + 10, c.1); + w32(t + 12, outer); + w32(t + 16, inner); + let i = outer / 16; + let o = inner / 16; + w32(t + 20, i.wrapping_mul(i)); + w32(t + 24, o.wrapping_mul(o)); + off(t) +} + +#[no_mangle] +pub extern "C" fn NewPointMarker(order: u32, pos: u32, size: u32) -> u32 { + let t = seed_target(24, CW_MARKER, order); + let u = order_unit(order); + let (px, py) = (r16(pos), r16(pos + 2)); + let (sx, sy) = (r16(size), r16(size + 2)); + w32(t + 8, px.wrapping_sub(r16(u + U_FP))); + w32(t + 16, py.wrapping_sub(r16(u + U_FP + 2))); + w32(t + 12, sx.wrapping_add(px)); + w32(t + 20, sy.wrapping_add(py)); + off(t) +} + +#[cfg(not(test))] +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + loop {} +} diff --git a/movement/src/math.rs b/movement/src/math.rs new file mode 100644 index 0000000..5c6de3c --- /dev/null +++ b/movement/src/math.rs @@ -0,0 +1,621 @@ +// The kit's runtime arithmetic (runtime/vectors/README.md, "Rules"), in integers and doubles. +use crate::tables::*; + +#[derive(Clone, Copy)] +pub struct Ext { + pub m: u64, + pub e: i32, +} + +const TOP: u64 = 1 << 63; +const ZERO: Ext = Ext { m: 0, e: 0 }; + +fn clz(v: u64) -> i32 { + v.leading_zeros() as i32 +} + +pub fn fabs(d: f64) -> f64 { + f64::from_bits(d.to_bits() & 0x7fff_ffff_ffff_ffff) +} + +fn ext_from_u128(v: u128, e: i32, sticky: bool) -> Ext { + if v == 0 { + return ZERO; + } + let lz = v.leading_zeros() as i32; + let v = v << lz; + let hi = (v >> 64) as u64; + let lo = v as u64; + let mut r = Ext { m: hi, e: e - lz + 64 }; + if (lo >> 63) != 0 && (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 +} + +pub fn ext_of_double(d: f64) -> Ext { + let bits = d.to_bits() & 0x7fff_ffff_ffff_ffff; + let mut m = bits & 0xf_ffff_ffff_ffff; + let mut e = (bits >> 52) as i32; + if bits == 0 { + return ZERO; + } + if e == 0 { + e = 1; + } else { + m |= 1 << 52; + } + let sh = clz(m); + Ext { m: m << sh, e: e - 1075 - sh } +} + +pub fn double_of_ext(x: Ext) -> f64 { + if x.m == 0 { + return 0.0; + } + let mut lead = x.e + 63; + let drop = if lead >= -1022 { 11 } else { 11 + (-1022 - lead) }; + if drop > 64 { + return 0.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; + } + let bits; + if lead >= -1022 { + if q == (1u64 << 53) { + q >>= 1; + lead += 1; + } + if lead > 1023 { + return f64::from_bits(0x7ff0_0000_0000_0000); + } + bits = (((lead + 1023) as u64) << 52) | (q & 0xf_ffff_ffff_ffff); + } else { + bits = q; + } + f64::from_bits(bits) +} + +pub fn ext_mul(a: Ext, b: Ext) -> Ext { + if a.m == 0 || b.m == 0 { + return ZERO; + } + ext_from_u128((a.m as u128) * (b.m as u128), a.e + b.e, false) +} + +pub fn ext_add(a: Ext, b: Ext) -> Ext { + if a.m == 0 { + return b; + } + if b.m == 0 { + return a; + } + let (a, b) = if b.e > a.e { (b, a) } else { (a, 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 = a.m.wrapping_add(bh); + let mut e = a.e - 64; + if hi < a.m { + 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) +} + +pub fn ext_div(a: Ext, b: Ext) -> Ext { + let mut ma = a.m >> 11; + let mb = b.m >> 11; + let mut xa = a.e + 11; + let xb = b.e + 11; + if a.m == 0 { + return ZERO; + } + if ma < mb { + ma <<= 1; + xa -= 1; + } + let mut rem = ma; + let mut q = 0u64; + 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 +} + +pub fn ext_sqrt(a: Ext) -> Ext { + if a.m == 0 { + return ZERO; + } + 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: u64 = 0; + 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 +} + +/// Correctly rounded square root of a finite non-negative double. +pub fn sqrt(x: f64) -> f64 { + let bits = x.to_bits(); + if (bits << 1) == 0 { + return x; + } + if (bits >> 63) != 0 { + return f64::from_bits(0xfff8_0000_0000_0000); + } + let e = ((bits >> 52) & 0x7ff) as i32; + if e == 0x7ff { + return x; + } + let mut m = bits & 0xf_ffff_ffff_ffff; + let mut exp2: i32; + if e == 0 { + exp2 = -1074; + while (m & (1 << 52)) == 0 { + m <<= 1; + exp2 -= 1; + } + } else { + m |= 1 << 52; + exp2 = e - 1075; + } + if (exp2 & 1) != 0 { + m <<= 1; + exp2 -= 1; + } + let mut root = 0u64; + let mut rem = 0u64; + for i in 0..56 { + let pair = if i <= 26 { (m >> (52 - 2 * i)) & 3 } else { 0 }; + rem = (rem << 2) | pair; + let c = (root << 2) | 1; + if rem >= c { + rem -= c; + root = (root << 1) | 1; + } else { + root <<= 1; + } + } + let mut m = root >> 3; + let pair = root & 7; + if pair > 4 || (pair == 4 && (rem != 0 || (m & 1) != 0)) { + m += 1; + } + if m == (1 << 53) { + m >>= 1; + exp2 += 2; + } + f64::from_bits((((exp2 / 2 + 1049) as u64) << 52) | (m & 0xf_ffff_ffff_ffff)) +} + +/// Truncation toward zero to 64 bits, low 32 bits; 0 for NaN, infinity, 2^63 and above. +pub fn ftol(x: f64) -> i32 { + let b = x.to_bits(); + let lo = b as u32; + let hi = (b >> 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 +} + +pub fn hypot(x: f64, y: f64) -> f64 { + let ax = fabs(x); + let ay = fabs(y); + if ax == f64::INFINITY || ay == f64::INFINITY { + return f64::INFINITY; + } + if x != x { + return x; + } + if y != y { + return y; + } + if ax == 0.0 && ay == 0.0 { + return 0.0; + } + let big = if ax > 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 = ext_of_double(ra); + let ebb = 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)) +} + +// ---- double-double ------------------------------------------------------------------------- + +#[derive(Clone, Copy)] +struct Dd { + hi: f64, + lo: f64, +} + +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 t = 134217729.0 * a; + let ah = t - (t - a); + let al = a - ah; + let 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_from(a: f64) -> Dd { + Dd { hi: a, lo: 0.0 } +} + +fn dd_product(a: f64, b: f64) -> Dd { + let (hi, lo) = two_prod(a, b); + Dd { hi, lo } +} + +fn dd_const(w: &[u32]) -> Dd { + Dd { + hi: f64::from_bits(((w[0] as u64) << 32) | w[1] as u64), + lo: f64::from_bits(((w[2] as u64) << 32) | w[3] as u64), + } +} + +fn dd_atan_ratio(n: f64, d: f64) -> Dd { + if n == 0.0 { + return dd_from(0.0); + } + let k = (n * 16.0 / d + 0.5) as i32; + let kf = k as f64; + let num = dd_add(dd_from(16.0 * n), dd_neg(dd_product(kf, d))); + let den = dd_add(dd_from(16.0 * d), dd_product(kf, n)); + let u = dd_div(num, den); + let w = dd_mul(u, u); + let mut p = dd_const(&ATAN_SERIES[4 * 11..]); + let mut m = 10; + while m >= 0 { + let c = dd_const(&ATAN_SERIES[4 * m as usize..]); + p = dd_add(dd_mul(p, w), c); + m -= 1; + } + let atan_u = dd_mul(u, p); + let table = dd_const(&ATAN16[4 * k as usize..]); + dd_add(table, 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_from(0.0); + } + let mut a; + if s <= ax { + a = dd_atan_ratio(s, ax); + } else { + let c = dd_const(&PI_HALF[4..]); + a = dd_add(c, dd_neg(dd_atan_ratio(ax, s))); + } + if x < 0.0 { + let c = dd_const(&PI_HALF[0..]); + a = dd_add(c, 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 +} + +/// The double-double rounded to a 64-bit mantissa (positive hi). +fn dd_to_ext(v: Dd) -> Ext { + let hb = v.hi.to_bits(); + let lb = v.lo.to_bits(); + if v.hi == 0.0 { + return ZERO; + } + let eh = ((hb >> 52) & 0x7ff) as i32; + let mh = (hb & 0xf_ffff_ffff_ffff) | (1 << 52); + let n = mh << 11; + if v.lo == 0.0 { + return Ext { m: n, e: eh - 1075 - 11 }; + } + let neg = (lb >> 63) != 0; + let el = ((lb >> 52) & 0x7ff) as i32; + let ml = (lb & 0xf_ffff_ffff_ffff) | (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 Ext { m: n, e: eh - 1075 - 11 }; + } + return Ext { m: 0u64.wrapping_sub(r), e: eh - 1075 - 12 }; + } + let r = round_shift(ml, shift); + Ext { m: if neg { n.wrapping_sub(r) } else { n.wrapping_add(r) }, e: eh - 1075 - 11 } +} + +fn dd_to_x87_double(v: Dd) -> f64 { + double_of_ext(dd_to_ext(v)) +} + +const RAD_TO_ANGLE: f64 = 10430.37835047; +const ANGLE_TO_RAD: f64 = 9.587379924285e-05; + +/// The angle of the vector (x, z): atan2(|x|, z) in 16-bit units, negated for a negative x. The full int. +pub fn angle_of_vector(x: i32, z: i32) -> i32 { + if x == 0 && z == 0 { + return 0; + } + let ax = if x < 0 { -(x as i64) } else { x as i64 } as f64; + let a = dd_to_x87_double(dd_atan2_nonneg(ax, z as f64)); + let r = round_to_int(a * RAD_TO_ANGLE); + if x < 0 { + r.wrapping_neg() + } else { + r + } +} + +// ---- sine table ------------------------------------------------------------------------------ + +pub fn scaled_sine(a: i32, s: i32) -> i32 { + let e = (((a.wrapping_add(32)) >> 7) & 511) as usize; + (((SIN[e] as i64) * (s as i64) + 4096) >> 13) as i32 +} + +pub fn scaled_cosine(a: i32, s: i32) -> i32 { + let e = (((a.wrapping_add(0x4020)) >> 7) & 511) as usize; + (((SIN[e] as i64) * (s as i64) + 4096) >> 13) as i32 +} + +// ---- rotating a point ------------------------------------------------------------------------- + +fn dd_sincos(theta: f64) -> (Dd, Dd) { + // Taylor series, theta the exact double. + let x = dd_from(theta); + let x2 = dd_product(theta, theta); + let mut sin = x; + let mut cos = dd_from(1.0); + let mut ts = x; + let mut tc = dd_from(1.0); + let mut n = 1.0f64; + let mut i = 0; + while i < 30 { + tc = dd_neg(dd_div(dd_mul(tc, x2), dd_from((2.0 * n - 1.0) * (2.0 * n)))); + ts = dd_neg(dd_div(dd_mul(ts, x2), dd_from((2.0 * n) * (2.0 * n + 1.0)))); + cos = dd_add(cos, tc); + sin = dd_add(sin, ts); + n += 1.0; + i += 1; + } + (sin, cos) +} + +/// |x| * m * 2^e rounded to a double (single rounding), sign applied. +fn mul_ext(x: i32, m: u64, e: i32, neg: bool) -> f64 { + if x == 0 || m == 0 { + return 0.0; + } + let ax = if x < 0 { (x as i64).unsigned_abs() } else { x as u64 }; + let p = (ax as u128) * (m as u128); + let l = 128 - p.leading_zeros() as i32; + let (mant, ex): (u64, i32); + if l <= 53 { + mant = p as u64; + ex = e; + } else { + let sh = l - 53; + let q = (p >> sh) as u64; + let rem = p & ((1u128 << sh) - 1); + let half = 1u128 << (sh - 1); + let mut q2 = q; + if rem > half || (rem == half && (q & 1) != 0) { + q2 += 1; + } + mant = q2; + ex = e + sh; + } + let scale = f64::from_bits(((ex + 1023) as u64) << 52); + let v = (mant as f64) * scale; + if neg != (x < 0) { + -v + } else { + v + } +} + +fn dd_signed_ext(v: Dd) -> (Ext, bool) { + if v.hi < 0.0 { + (dd_to_ext(dd_neg(v)), true) + } else { + (dd_to_ext(v), false) + } +} + +pub fn rotate_point(angle: i32, x: i32, z: i32) -> (i32, i32) { + if angle == 0 { + return (x, z); + } + let t = (angle as i16) as i32; + let theta = (t as f64) * ANGLE_TO_RAD; + let (s, c) = dd_sincos(theta); + let (se, sneg) = dd_signed_ext(s); + let (ce, cneg) = dd_signed_ext(c); + let xc = mul_ext(x, ce.m, ce.e, cneg); + let zc = mul_ext(z, ce.m, ce.e, cneg); + let xs = mul_ext(x, se.m, se.e, sneg); + let zs = mul_ext(z, se.m, se.e, sneg); + (round_to_int(xc - zs), round_to_int(zc + xs)) +} diff --git a/movement/src/tables.rs b/movement/src/tables.rs new file mode 100644 index 0000000..f8ab670 --- /dev/null +++ b/movement/src/tables.rs @@ -0,0 +1,4 @@ +pub static SIN: [i16; 640] = [0, 101, 201, 302, 402, 502, 603, 703, 803, 903, 1003, 1102, 1202, 1301, 1401, 1499, 1598, 1697, 1795, 1893, 1990, 2088, 2185, 2282, 2378, 2474, 2570, 2665, 2760, 2854, 2948, 3042, 3135, 3228, 3320, 3411, 3503, 3593, 3683, 3773, 3862, 3950, 4038, 4125, 4212, 4297, 4383, 4467, 4551, 4634, 4717, 4799, 4880, 4960, 5040, 5119, 5197, 5274, 5351, 5427, 5501, 5575, 5649, 5721, 5793, 5863, 5933, 6002, 6070, 6137, 6203, 6268, 6333, 6396, 6458, 6519, 6580, 6639, 6698, 6755, 6811, 6867, 6921, 6974, 7027, 7078, 7128, 7177, 7225, 7272, 7317, 7362, 7405, 7448, 7489, 7529, 7568, 7606, 7643, 7679, 7713, 7746, 7779, 7809, 7839, 7868, 7895, 7921, 7946, 7970, 7993, 8014, 8035, 8054, 8071, 8088, 8103, 8117, 8130, 8142, 8153, 8162, 8170, 8177, 8182, 8186, 8190, 8191, 8192, 8191, 8190, 8186, 8182, 8177, 8170, 8162, 8153, 8142, 8130, 8117, 8103, 8088, 8071, 8054, 8035, 8014, 7993, 7970, 7946, 7921, 7895, 7868, 7839, 7809, 7779, 7746, 7713, 7679, 7643, 7606, 7568, 7529, 7489, 7448, 7405, 7362, 7317, 7272, 7225, 7177, 7128, 7078, 7027, 6974, 6921, 6867, 6811, 6755, 6698, 6639, 6580, 6519, 6458, 6396, 6333, 6268, 6203, 6137, 6070, 6002, 5933, 5863, 5793, 5721, 5649, 5575, 5501, 5427, 5351, 5274, 5197, 5119, 5040, 4960, 4880, 4799, 4717, 4634, 4551, 4467, 4383, 4297, 4212, 4125, 4038, 3950, 3862, 3773, 3683, 3593, 3503, 3411, 3320, 3228, 3135, 3042, 2948, 2854, 2760, 2665, 2570, 2474, 2378, 2282, 2185, 2088, 1990, 1893, 1795, 1697, 1598, 1499, 1401, 1301, 1202, 1102, 1003, 903, 803, 703, 603, 502, 402, 302, 201, 101, 0, -101, -201, -302, -402, -502, -603, -703, -803, -903, -1003, -1102, -1202, -1301, -1401, -1499, -1598, -1697, -1795, -1893, -1990, -2088, -2185, -2282, -2378, -2474, -2570, -2665, -2760, -2854, -2948, -3042, -3135, -3228, -3320, -3411, -3503, -3593, -3683, -3773, -3862, -3950, -4038, -4125, -4212, -4297, -4383, -4467, -4551, -4634, -4717, -4799, -4880, -4960, -5040, -5119, -5197, -5274, -5351, -5427, -5501, -5575, -5649, -5721, -5793, -5863, -5933, -6002, -6070, -6137, -6203, -6268, -6333, -6396, -6458, -6519, -6580, -6639, -6698, -6755, -6811, -6867, -6921, -6974, -7027, -7078, -7128, -7177, -7225, -7272, -7317, -7362, -7405, -7448, -7489, -7529, -7568, -7606, -7643, -7679, -7713, -7746, -7779, -7809, -7839, -7868, -7895, -7921, -7946, -7970, -7993, -8014, -8035, -8054, -8071, -8088, -8103, -8117, -8130, -8142, -8153, -8162, -8170, -8177, -8182, -8186, -8190, -8191, -8192, -8191, -8190, -8186, -8182, -8177, -8170, -8162, -8153, -8142, -8130, -8117, -8103, -8088, -8071, -8054, -8035, -8014, -7993, -7970, -7946, -7921, -7895, -7868, -7839, -7809, -7779, -7746, -7713, -7679, -7643, -7606, -7568, -7529, -7489, -7448, -7405, -7362, -7317, -7272, -7225, -7177, -7128, -7078, -7027, -6974, -6921, -6867, -6811, -6755, -6698, -6639, -6580, -6519, -6458, -6396, -6333, -6268, -6203, -6137, -6070, -6002, -5933, -5863, -5793, -5721, -5649, -5575, -5501, -5427, -5351, -5274, -5197, -5119, -5040, -4960, -4880, -4799, -4717, -4634, -4551, -4467, -4383, -4297, -4212, -4125, -4038, -3950, -3862, -3773, -3683, -3593, -3503, -3411, -3320, -3228, -3135, -3042, -2948, -2854, -2760, -2665, -2570, -2474, -2378, -2282, -2185, -2088, -1990, -1893, -1795, -1697, -1598, -1499, -1401, -1301, -1202, -1102, -1003, -903, -803, -703, -603, -502, -402, -302, -201, -101, 0, 101, 201, 302, 402, 502, 603, 703, 803, 903, 1003, 1102, 1202, 1301, 1401, 1499, 1598, 1697, 1795, 1893, 1990, 2088, 2185, 2282, 2378, 2474, 2570, 2665, 2760, 2854, 2948, 3042, 3135, 3228, 3320, 3411, 3503, 3593, 3683, 3773, 3862, 3950, 4038, 4125, 4212, 4297, 4383, 4467, 4551, 4634, 4717, 4799, 4880, 4960, 5040, 5119, 5197, 5274, 5351, 5427, 5501, 5575, 5649, 5721, 5793, 5863, 5933, 6002, 6070, 6137, 6203, 6268, 6333, 6396, 6458, 6519, 6580, 6639, 6698, 6755, 6811, 6867, 6921, 6974, 7027, 7078, 7128, 7177, 7225, 7272, 7317, 7362, 7405, 7448, 7489, 7529, 7568, 7606, 7643, 7679, 7713, 7746, 7779, 7809, 7839, 7868, 7895, 7921, 7946, 7970, 7993, 8014, 8035, 8054, 8071, 8088, 8103, 8117, 8130, 8142, 8153, 8162, 8170, 8177, 8182, 8186, 8190, 8191]; +pub static ATAN16: [u32; 68] = [0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x3faff55b, 0xb72cfdea, 0xbc3c934d, 0x86d23f1d, 0x3fbfd5ba, 0x9aac2f6e, 0xbc4cd376, 0x86760c17, 0x3fc7b97b, 0x4bce5b02, 0x3c5347b0, 0xb4f881ca, 0x3fcf5b75, 0xf92c80dd, 0x3c68ab6e, 0x3cf7afbd, 0x3fd36277, 0x3707ebcc, 0xbc6963a5, 0x44b672d8, 0x3fd6f619, 0x41e4def1, 0xbc7c63aa, 0xe6f6e918, 0x3fda64ee, 0xc3cc23fd, 0xbc724dec, 0x1b50b7ff, 0x3fddac67, 0x0561bb4f, 0x3c7a2b7f, 0x222f65e2, 0x3fe0657e, 0x94db30d0, 0xbc7d5b49, 0x5f6349e6, 0x3fe1e00b, 0xabdefeb4, 0xbc5928df, 0x287a668f, 0x3fe345f0, 0x1cce37bb, 0x3c810211, 0x37c71102, 0x3fe4978f, 0xa3269ee1, 0x3c72419a, 0x87f2a458, 0x3fe5d589, 0x87169b18, 0x3c60028e, 0x4bc5e7ca, 0x3fe700a7, 0xc5784634, 0xbc78c34d, 0x25aadef6, 0x3fe819d0, 0xb7158a4d, 0xbc7bf762, 0x29d3b917, 0x3fe921fb, 0x54442d18, 0x3c81a626, 0x33145c07]; +pub static ATAN_SERIES: [u32; 48] = [0x3ff00000, 0x00000000, 0x00000000, 0x00000000, 0xbfd55555, 0x55555555, 0xbc755555, 0x55555555, 0x3fc99999, 0x9999999a, 0xbc699999, 0x9999999a, 0xbfc24924, 0x92492492, 0xbc624924, 0x92492492, 0x3fbc71c7, 0x1c71c71c, 0x3c5c71c7, 0x1c71c71c, 0xbfb745d1, 0x745d1746, 0x3c4745d1, 0x745d1746, 0x3fb3b13b, 0x13b13b14, 0xbc53b13b, 0x13b13b14, 0xbfb11111, 0x11111111, 0xbc311111, 0x11111111, 0x3fae1e1e, 0x1e1e1e1e, 0x3c2e1e1e, 0x1e1e1e1e, 0xbfaaf286, 0xbca1af28, 0xbc4af286, 0xbca1af28, 0x3fa86186, 0x18618618, 0x3c486186, 0x18618618, 0xbfa642c8, 0x590b2164, 0xbc3642c8, 0x590b2164]; +pub static PI_HALF: [u32; 8] = [0x400921fb, 0x54442d18, 0x3ca1a626, 0x33145c07, 0x3ff921fb, 0x54442d18, 0x3c91a626, 0x33145c07]; diff --git a/movement/tools/gen_tables.py b/movement/tools/gen_tables.py new file mode 100644 index 0000000..9ce2a54 --- /dev/null +++ b/movement/tools/gen_tables.py @@ -0,0 +1,29 @@ +"""Writes src/tables.rs from the kit's runtime/bitexact_tables.py (the small tables only). +Usage: python3 -I tools/gen_tables.py /data/runtime/bitexact_tables.py src/tables.rs""" +import importlib.util, math, sys +spec = importlib.util.spec_from_file_location("bt", sys.argv[1]) +bt = importlib.util.module_from_spec(spec); spec.loader.exec_module(bt) +out = [] +sin = bt.sin_table() +out.append("pub static SIN: [i16; 640] = [%s];\n" % ", ".join(str(v) for v in sin)) +atans = [] +for k in range(17): + v = bt.atan_scaled(k * bt.ONE // 16) + if k == 16: + pi_dd = bt.double_double(4 * v); half_dd = bt.double_double(2 * v) + atans.append(bt.double_double(v)) +def words(dds): + r = [] + for hi, lo in dds: + r += ["0x%08x" % w for w in (*hi, *lo)] + return r +out.append("pub static ATAN16: [u32; 68] = [%s];\n" % ", ".join(words(atans))) +from fractions import Fraction +ser = [] +for m in range(12): + f = Fraction((-1) ** m, 2 * m + 1) + hi = float(f); lo = float(f - Fraction(hi)) + ser.append((bt.double_bits(hi), bt.double_bits(lo))) +out.append("pub static ATAN_SERIES: [u32; 48] = [%s];\n" % ", ".join(words(ser))) +out.append("pub static PI_HALF: [u32; 8] = [%s];\n" % ", ".join(words([pi_dd, half_dd]))) +open(sys.argv[2], "w").write("".join(out)) From 095645ed69c9099ac69109c3aa683bc7e014478f Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 12:47:52 +0000 Subject: [PATCH 05/12] Fix: Zero a freed target and every new record Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 22 ++++++++++++++++++++++ SPEC-QUESTIONS.md | 17 +++++++++++++++++ movement/src/lib.rs | 14 +++++++++++--- 3 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 SPEC-QUESTIONS.md diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index 5659585..920fcd2 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -37,3 +37,25 @@ - `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. + +# movement implementation notes + +## What was built +`movement/` is a `no_std` Rust cdylib (`src/lib.rs`: the slots, `src/math.rs`: the kit's runtime arithmetic, `src/tables.rs`: generated by `tools/gen_tables.py` from the kit's `bitexact_tables.py`). `build.sh` links at data base 622592 and table base 464 (stack 4096) through `ld-wrap.sh` (as for wind_meteors) and runs the kit's `tools/wasm_fuel.py`. The module is 29665 bytes; the entry is `blocked`, so size and fuel are `not_judged`. +- Records are read and written in place at the `layout.json` offsets (unaligned loads and stores). A `Ref` field holds a block offset; the code turns it into an address with `g_blockBase` and back. +- `math.rs` ports the kit's integer and double-double code (`sqrt`, `ftol`, `hypot` with the 64-bit-mantissa steps, `atan2`) and builds the sine and cosine of the rotate-a-point rule with a double-double Taylor series (the 65536-entry 80-bit table does not fit a 32 KiB window). `mathtest/` replays the kit's `runtime/vectors` (scaled sine and cosine, angle of a vector, rotate point, hypot, sqrt, ftol) against it: every record equal. +- The class words are read from the table at 0x10100000 (index per `layout.json` `class_words`); a target is valid when its class word is one of the five kinds and the record ends within `block_max`. +- `UnitRefSetUnit` and the table import are kept by a never-taken branch behind a never-written static (ABI 9.1 wants every listed import). +- The float steps of the flying correction follow spec section 5 literally (f32 roundings, Q8). + +## Verdicts, in order +1. req1: `differs`; 10 recordings `equal`, `orders-air` (tick 4095, call 35, `PathOrder#5.approachRadius`) and `orders-air-repair` (tick 670, call 10, `PathOrder#3.approachRadius`) differ. +2. req2 (every allocated record zeroed by the module): the same two differences. +3. req3 (the freed target's record zeroed before `SimFree`): `equal`, all 12 recordings. Scenarios, view and budgets are `not_judged`. + +## Unclear points in the spec or kit +- DESTROY_TARGET: the replayer expects a freed target's bytes to read 0 after the call; the spec does not say so (SPEC-QUESTIONS.md, 1). +- `SimAlloc`'s zeroing is promised by the spec, and the module does not rely on it (SPEC-QUESTIONS.md, 2). +- The module-ABI text is clear that blocked entries have no budgets, but the kit has no local checker (`wasm_modules.py` is not in it): the exports, imports, window and element segment were checked by hand with `wasm-tools`. +- The toolchain here is rustc 1.87 and LLD 20, whose `wasm-ld` does not list `--no-stack-first`; the stack falls after the data (top 628624, inside the window 622592..655360). +- No recording reaches the patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, SET_HEADING, air maneuver targets, follow offsets or refused events: those paths follow the spec text only. diff --git a/SPEC-QUESTIONS.md b/SPEC-QUESTIONS.md new file mode 100644 index 0000000..0ff029a --- /dev/null +++ b/SPEC-QUESTIONS.md @@ -0,0 +1,17 @@ +# Spec questions: movement + +None of these blocks the module, which is `equal` (req3). Each was settled by a verdict, not by the spec. + +1. **A freed target's bytes (spec 4, DESTROY_TARGET; 3, "Between ticks").** The spec says only + `UnitRefUnlink`, then `SimFree`. With exactly that (req1, req2) the gate said `differs` in + `orders-air` (tick 4095, call 35, `PathOrder#5.approachRadius`) and `orders-air-repair` (tick 670, call 10, + `PathOrder#3.approachRadius`): the freed block still held the old record, and the replayer expects the bytes + of the freed address to read 0 at the end of the call. Zeroing the target's record before `SimFree` made + all 12 recordings `equal` (req3). Should the spec say that DESTROY_TARGET leaves the freed record zeroed, or is + this an artefact of the replayer that the spec should name? +2. **`SimAlloc` zeroing (spec 3, "Owned").** The spec says `SimAlloc` returns a zeroed record. The module zeroes + each record it allocates itself (req2 onwards) in case a recycled block is not zero. No verdict separates + the two, since req1 (no zeroing) and req2 differed only in the failure of question 1. +3. **Recordings that never reach a path** (patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, + SET_HEADING, an air maneuver target, the follow offset, a refused `Apply`): the module follows the spec text + and nothing judges it. Scenarios and the view are `not_judged` for this blocked entry. diff --git a/movement/src/lib.rs b/movement/src/lib.rs index f1c77a5..314feb4 100644 --- a/movement/src/lib.rs +++ b/movement/src/lib.rs @@ -296,8 +296,15 @@ fn valid_unit(o: u32) -> bool { o >= first && o < end && (o - first) % UNIT_SIZE == 0 } +/// SimAlloc, with the record zeroed (a recycled block may hold the bytes of the record freed before). +fn alloc_zeroed(size: i32) -> u32 { + let p = unsafe { sim_alloc(size) }; + unsafe { core::ptr::write_bytes(p as *mut u8, 0, size as usize) }; + p +} + fn seed_target(size: i32, class: u32, order: u32) -> u32 { - let t = unsafe { sim_alloc(size) }; + let t = alloc_zeroed(size); w32(t, cw(class) as i32); w32(t + T_SOURCE, order as i32); t @@ -1122,6 +1129,7 @@ fn destroy_target(t: u32) { if target_kind(t) == 2 { unsafe { unit_ref_unlink(t + PO_REF) }; } + unsafe { core::ptr::write_bytes(t as *mut u8, 0, target_size(target_kind(t)) as usize) }; unsafe { sim_free(t) }; } @@ -1187,7 +1195,7 @@ pub extern "C" fn Apply(ev: u32, size: u32) -> i32 { match kind { 320 => { let d = udef(u); - let motion = unsafe { sim_alloc(47) }; + let motion = alloc_zeroed(47); let player = rref(u + U_PLAYER); let air = ru32(d + D_FLAGS1) & (1 << 11) != 0; let (size, class) = if r32(player) != 0 && r8(player + 115) == 3 { @@ -1201,7 +1209,7 @@ pub extern "C" fn Apply(ev: u32, size: u32) -> i32 { } else { (101, CW_AI) }; - let goal = unsafe { sim_alloc(size) }; + let goal = alloc_zeroed(size); w32(u + U_MOTION, off(motion) as i32); w32(motion + M_OBJ, off(goal) as i32); w32(motion + M_CLASS, r32(d + D_MCLASS)); From e089b23574a83acff76e94fe18a5010f4a2d18bc Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:09:32 +0000 Subject: [PATCH 06/12] Update: Note the freed target gap in movement Answer the implementer's first spec question: the replay compares a freed target's bytes as zero (ozgb/byte-tactics-moddable#1380). Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/specs/movement.md b/specs/movement.md index c5bdaeb..cd0451e 100644 --- a/specs/movement.md +++ b/specs/movement.md @@ -654,6 +654,12 @@ everything those goals do, DESTROY of a lite goal, a move target's follow offset every recorded call; the table's entries for −5 to −3 and 2 to 5 are judged by nothing. - **The flying roundings.** No recording separates the float and double steps of section 5 (Q8 included): a module that rounds them otherwise still replays the recordings equal. Only scenarios, or a kit vector, would judge them. +- **A freed target's bytes.** The replay compares the bytes of a target that DESTROY_TARGET frees as 0 at the end of + the call (`orders-air` at tick 4095, `orders-air-repair` at tick 670), though those calls carry no `w` line for the + target, and the reference leaves its fields as they were before its `SimFree`. A module that leaves the record as it was differs + there; one that zeroes the record's bytes before `SimFree` replays equal. The goals and motions DESTROY frees are + not compared so. Filed as ozgb/byte-tactics-moddable#1380; until it is settled, zero a target's record before + freeing it. - **New objects in the recordings.** Which fields a recording lists as `w` lines for a newly made object follows the recorder's rules (`docs/replay-format.md`), not this spec: a name reused after a `SimFree` lists fields that are 0. From 7083f53a8e749d96733cd0c1087e2649eaac5255 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 13:45:14 +0000 Subject: [PATCH 07/12] Fix: Answer the movement review's risks and nits Assisted-by: Claude Code:claude-sonnet-5-5 --- movement/src/lib.rs | 14 ++++++++------ movement/src/tables.rs | 2 +- movement/tools/gen_tables.py | 4 ++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/movement/src/lib.rs b/movement/src/lib.rs index 314feb4..9de8868 100644 --- a/movement/src/lib.rs +++ b/movement/src/lib.rs @@ -296,11 +296,9 @@ fn valid_unit(o: u32) -> bool { o >= first && o < end && (o - first) % UNIT_SIZE == 0 } -/// SimAlloc, with the record zeroed (a recycled block may hold the bytes of the record freed before). +/// SimAlloc: the host returns the record zeroed (spec 3, ABI 9.3). fn alloc_zeroed(size: i32) -> u32 { - let p = unsafe { sim_alloc(size) }; - unsafe { core::ptr::write_bytes(p as *mut u8, 0, size as usize) }; - p + unsafe { sim_alloc(size) } } fn seed_target(size: i32, class: u32, order: u32) -> u32 { @@ -1051,8 +1049,9 @@ fn do_move(u: u32, m: u32, d: u32) { } if r8(m + M_FLAGS) & 4 != 0 { let (cx, cz) = centre(ucell.0, ucell.1, fx, fy); - p[0] = p[0].clamp(cx.wrapping_sub(0x7ffff), cx.wrapping_add(0x7ffff)); - p[2] = p[2].clamp(cz.wrapping_sub(0x7ffff), cz.wrapping_add(0x7ffff)); + // not `clamp`: the bounds wrap at 32 bits and may cross, which `clamp` makes a panic + p[0] = p[0].max(cx.wrapping_sub(0x7ffff)).min(cx.wrapping_add(0x7ffff)); + p[2] = p[2].max(cz.wrapping_sub(0x7ffff)).min(cz.wrapping_add(0x7ffff)); let half = r32(d + D_MAXV) / 2; if r32(m + M_SPEED) > half { w32(m + M_SPEED, half); @@ -1451,6 +1450,9 @@ pub extern "C" fn UnitTarget(u: u32) -> i32 { return 0; } let g = rref(m + M_OBJ); + if g == 0 { + return 0; + } r32(g + GO_TARGET) } diff --git a/movement/src/tables.rs b/movement/src/tables.rs index f8ab670..1299755 100644 --- a/movement/src/tables.rs +++ b/movement/src/tables.rs @@ -1,4 +1,4 @@ -pub static SIN: [i16; 640] = [0, 101, 201, 302, 402, 502, 603, 703, 803, 903, 1003, 1102, 1202, 1301, 1401, 1499, 1598, 1697, 1795, 1893, 1990, 2088, 2185, 2282, 2378, 2474, 2570, 2665, 2760, 2854, 2948, 3042, 3135, 3228, 3320, 3411, 3503, 3593, 3683, 3773, 3862, 3950, 4038, 4125, 4212, 4297, 4383, 4467, 4551, 4634, 4717, 4799, 4880, 4960, 5040, 5119, 5197, 5274, 5351, 5427, 5501, 5575, 5649, 5721, 5793, 5863, 5933, 6002, 6070, 6137, 6203, 6268, 6333, 6396, 6458, 6519, 6580, 6639, 6698, 6755, 6811, 6867, 6921, 6974, 7027, 7078, 7128, 7177, 7225, 7272, 7317, 7362, 7405, 7448, 7489, 7529, 7568, 7606, 7643, 7679, 7713, 7746, 7779, 7809, 7839, 7868, 7895, 7921, 7946, 7970, 7993, 8014, 8035, 8054, 8071, 8088, 8103, 8117, 8130, 8142, 8153, 8162, 8170, 8177, 8182, 8186, 8190, 8191, 8192, 8191, 8190, 8186, 8182, 8177, 8170, 8162, 8153, 8142, 8130, 8117, 8103, 8088, 8071, 8054, 8035, 8014, 7993, 7970, 7946, 7921, 7895, 7868, 7839, 7809, 7779, 7746, 7713, 7679, 7643, 7606, 7568, 7529, 7489, 7448, 7405, 7362, 7317, 7272, 7225, 7177, 7128, 7078, 7027, 6974, 6921, 6867, 6811, 6755, 6698, 6639, 6580, 6519, 6458, 6396, 6333, 6268, 6203, 6137, 6070, 6002, 5933, 5863, 5793, 5721, 5649, 5575, 5501, 5427, 5351, 5274, 5197, 5119, 5040, 4960, 4880, 4799, 4717, 4634, 4551, 4467, 4383, 4297, 4212, 4125, 4038, 3950, 3862, 3773, 3683, 3593, 3503, 3411, 3320, 3228, 3135, 3042, 2948, 2854, 2760, 2665, 2570, 2474, 2378, 2282, 2185, 2088, 1990, 1893, 1795, 1697, 1598, 1499, 1401, 1301, 1202, 1102, 1003, 903, 803, 703, 603, 502, 402, 302, 201, 101, 0, -101, -201, -302, -402, -502, -603, -703, -803, -903, -1003, -1102, -1202, -1301, -1401, -1499, -1598, -1697, -1795, -1893, -1990, -2088, -2185, -2282, -2378, -2474, -2570, -2665, -2760, -2854, -2948, -3042, -3135, -3228, -3320, -3411, -3503, -3593, -3683, -3773, -3862, -3950, -4038, -4125, -4212, -4297, -4383, -4467, -4551, -4634, -4717, -4799, -4880, -4960, -5040, -5119, -5197, -5274, -5351, -5427, -5501, -5575, -5649, -5721, -5793, -5863, -5933, -6002, -6070, -6137, -6203, -6268, -6333, -6396, -6458, -6519, -6580, -6639, -6698, -6755, -6811, -6867, -6921, -6974, -7027, -7078, -7128, -7177, -7225, -7272, -7317, -7362, -7405, -7448, -7489, -7529, -7568, -7606, -7643, -7679, -7713, -7746, -7779, -7809, -7839, -7868, -7895, -7921, -7946, -7970, -7993, -8014, -8035, -8054, -8071, -8088, -8103, -8117, -8130, -8142, -8153, -8162, -8170, -8177, -8182, -8186, -8190, -8191, -8192, -8191, -8190, -8186, -8182, -8177, -8170, -8162, -8153, -8142, -8130, -8117, -8103, -8088, -8071, -8054, -8035, -8014, -7993, -7970, -7946, -7921, -7895, -7868, -7839, -7809, -7779, -7746, -7713, -7679, -7643, -7606, -7568, -7529, -7489, -7448, -7405, -7362, -7317, -7272, -7225, -7177, -7128, -7078, -7027, -6974, -6921, -6867, -6811, -6755, -6698, -6639, -6580, -6519, -6458, -6396, -6333, -6268, -6203, -6137, -6070, -6002, -5933, -5863, -5793, -5721, -5649, -5575, -5501, -5427, -5351, -5274, -5197, -5119, -5040, -4960, -4880, -4799, -4717, -4634, -4551, -4467, -4383, -4297, -4212, -4125, -4038, -3950, -3862, -3773, -3683, -3593, -3503, -3411, -3320, -3228, -3135, -3042, -2948, -2854, -2760, -2665, -2570, -2474, -2378, -2282, -2185, -2088, -1990, -1893, -1795, -1697, -1598, -1499, -1401, -1301, -1202, -1102, -1003, -903, -803, -703, -603, -502, -402, -302, -201, -101, 0, 101, 201, 302, 402, 502, 603, 703, 803, 903, 1003, 1102, 1202, 1301, 1401, 1499, 1598, 1697, 1795, 1893, 1990, 2088, 2185, 2282, 2378, 2474, 2570, 2665, 2760, 2854, 2948, 3042, 3135, 3228, 3320, 3411, 3503, 3593, 3683, 3773, 3862, 3950, 4038, 4125, 4212, 4297, 4383, 4467, 4551, 4634, 4717, 4799, 4880, 4960, 5040, 5119, 5197, 5274, 5351, 5427, 5501, 5575, 5649, 5721, 5793, 5863, 5933, 6002, 6070, 6137, 6203, 6268, 6333, 6396, 6458, 6519, 6580, 6639, 6698, 6755, 6811, 6867, 6921, 6974, 7027, 7078, 7128, 7177, 7225, 7272, 7317, 7362, 7405, 7448, 7489, 7529, 7568, 7606, 7643, 7679, 7713, 7746, 7779, 7809, 7839, 7868, 7895, 7921, 7946, 7970, 7993, 8014, 8035, 8054, 8071, 8088, 8103, 8117, 8130, 8142, 8153, 8162, 8170, 8177, 8182, 8186, 8190, 8191]; +pub static SIN: [i16; 512] = [0, 101, 201, 302, 402, 502, 603, 703, 803, 903, 1003, 1102, 1202, 1301, 1401, 1499, 1598, 1697, 1795, 1893, 1990, 2088, 2185, 2282, 2378, 2474, 2570, 2665, 2760, 2854, 2948, 3042, 3135, 3228, 3320, 3411, 3503, 3593, 3683, 3773, 3862, 3950, 4038, 4125, 4212, 4297, 4383, 4467, 4551, 4634, 4717, 4799, 4880, 4960, 5040, 5119, 5197, 5274, 5351, 5427, 5501, 5575, 5649, 5721, 5793, 5863, 5933, 6002, 6070, 6137, 6203, 6268, 6333, 6396, 6458, 6519, 6580, 6639, 6698, 6755, 6811, 6867, 6921, 6974, 7027, 7078, 7128, 7177, 7225, 7272, 7317, 7362, 7405, 7448, 7489, 7529, 7568, 7606, 7643, 7679, 7713, 7746, 7779, 7809, 7839, 7868, 7895, 7921, 7946, 7970, 7993, 8014, 8035, 8054, 8071, 8088, 8103, 8117, 8130, 8142, 8153, 8162, 8170, 8177, 8182, 8186, 8190, 8191, 8192, 8191, 8190, 8186, 8182, 8177, 8170, 8162, 8153, 8142, 8130, 8117, 8103, 8088, 8071, 8054, 8035, 8014, 7993, 7970, 7946, 7921, 7895, 7868, 7839, 7809, 7779, 7746, 7713, 7679, 7643, 7606, 7568, 7529, 7489, 7448, 7405, 7362, 7317, 7272, 7225, 7177, 7128, 7078, 7027, 6974, 6921, 6867, 6811, 6755, 6698, 6639, 6580, 6519, 6458, 6396, 6333, 6268, 6203, 6137, 6070, 6002, 5933, 5863, 5793, 5721, 5649, 5575, 5501, 5427, 5351, 5274, 5197, 5119, 5040, 4960, 4880, 4799, 4717, 4634, 4551, 4467, 4383, 4297, 4212, 4125, 4038, 3950, 3862, 3773, 3683, 3593, 3503, 3411, 3320, 3228, 3135, 3042, 2948, 2854, 2760, 2665, 2570, 2474, 2378, 2282, 2185, 2088, 1990, 1893, 1795, 1697, 1598, 1499, 1401, 1301, 1202, 1102, 1003, 903, 803, 703, 603, 502, 402, 302, 201, 101, 0, -101, -201, -302, -402, -502, -603, -703, -803, -903, -1003, -1102, -1202, -1301, -1401, -1499, -1598, -1697, -1795, -1893, -1990, -2088, -2185, -2282, -2378, -2474, -2570, -2665, -2760, -2854, -2948, -3042, -3135, -3228, -3320, -3411, -3503, -3593, -3683, -3773, -3862, -3950, -4038, -4125, -4212, -4297, -4383, -4467, -4551, -4634, -4717, -4799, -4880, -4960, -5040, -5119, -5197, -5274, -5351, -5427, -5501, -5575, -5649, -5721, -5793, -5863, -5933, -6002, -6070, -6137, -6203, -6268, -6333, -6396, -6458, -6519, -6580, -6639, -6698, -6755, -6811, -6867, -6921, -6974, -7027, -7078, -7128, -7177, -7225, -7272, -7317, -7362, -7405, -7448, -7489, -7529, -7568, -7606, -7643, -7679, -7713, -7746, -7779, -7809, -7839, -7868, -7895, -7921, -7946, -7970, -7993, -8014, -8035, -8054, -8071, -8088, -8103, -8117, -8130, -8142, -8153, -8162, -8170, -8177, -8182, -8186, -8190, -8191, -8192, -8191, -8190, -8186, -8182, -8177, -8170, -8162, -8153, -8142, -8130, -8117, -8103, -8088, -8071, -8054, -8035, -8014, -7993, -7970, -7946, -7921, -7895, -7868, -7839, -7809, -7779, -7746, -7713, -7679, -7643, -7606, -7568, -7529, -7489, -7448, -7405, -7362, -7317, -7272, -7225, -7177, -7128, -7078, -7027, -6974, -6921, -6867, -6811, -6755, -6698, -6639, -6580, -6519, -6458, -6396, -6333, -6268, -6203, -6137, -6070, -6002, -5933, -5863, -5793, -5721, -5649, -5575, -5501, -5427, -5351, -5274, -5197, -5119, -5040, -4960, -4880, -4799, -4717, -4634, -4551, -4467, -4383, -4297, -4212, -4125, -4038, -3950, -3862, -3773, -3683, -3593, -3503, -3411, -3320, -3228, -3135, -3042, -2948, -2854, -2760, -2665, -2570, -2474, -2378, -2282, -2185, -2088, -1990, -1893, -1795, -1697, -1598, -1499, -1401, -1301, -1202, -1102, -1003, -903, -803, -703, -603, -502, -402, -302, -201, -101]; pub static ATAN16: [u32; 68] = [0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x3faff55b, 0xb72cfdea, 0xbc3c934d, 0x86d23f1d, 0x3fbfd5ba, 0x9aac2f6e, 0xbc4cd376, 0x86760c17, 0x3fc7b97b, 0x4bce5b02, 0x3c5347b0, 0xb4f881ca, 0x3fcf5b75, 0xf92c80dd, 0x3c68ab6e, 0x3cf7afbd, 0x3fd36277, 0x3707ebcc, 0xbc6963a5, 0x44b672d8, 0x3fd6f619, 0x41e4def1, 0xbc7c63aa, 0xe6f6e918, 0x3fda64ee, 0xc3cc23fd, 0xbc724dec, 0x1b50b7ff, 0x3fddac67, 0x0561bb4f, 0x3c7a2b7f, 0x222f65e2, 0x3fe0657e, 0x94db30d0, 0xbc7d5b49, 0x5f6349e6, 0x3fe1e00b, 0xabdefeb4, 0xbc5928df, 0x287a668f, 0x3fe345f0, 0x1cce37bb, 0x3c810211, 0x37c71102, 0x3fe4978f, 0xa3269ee1, 0x3c72419a, 0x87f2a458, 0x3fe5d589, 0x87169b18, 0x3c60028e, 0x4bc5e7ca, 0x3fe700a7, 0xc5784634, 0xbc78c34d, 0x25aadef6, 0x3fe819d0, 0xb7158a4d, 0xbc7bf762, 0x29d3b917, 0x3fe921fb, 0x54442d18, 0x3c81a626, 0x33145c07]; pub static ATAN_SERIES: [u32; 48] = [0x3ff00000, 0x00000000, 0x00000000, 0x00000000, 0xbfd55555, 0x55555555, 0xbc755555, 0x55555555, 0x3fc99999, 0x9999999a, 0xbc699999, 0x9999999a, 0xbfc24924, 0x92492492, 0xbc624924, 0x92492492, 0x3fbc71c7, 0x1c71c71c, 0x3c5c71c7, 0x1c71c71c, 0xbfb745d1, 0x745d1746, 0x3c4745d1, 0x745d1746, 0x3fb3b13b, 0x13b13b14, 0xbc53b13b, 0x13b13b14, 0xbfb11111, 0x11111111, 0xbc311111, 0x11111111, 0x3fae1e1e, 0x1e1e1e1e, 0x3c2e1e1e, 0x1e1e1e1e, 0xbfaaf286, 0xbca1af28, 0xbc4af286, 0xbca1af28, 0x3fa86186, 0x18618618, 0x3c486186, 0x18618618, 0xbfa642c8, 0x590b2164, 0xbc3642c8, 0x590b2164]; pub static PI_HALF: [u32; 8] = [0x400921fb, 0x54442d18, 0x3ca1a626, 0x33145c07, 0x3ff921fb, 0x54442d18, 0x3c91a626, 0x33145c07]; diff --git a/movement/tools/gen_tables.py b/movement/tools/gen_tables.py index 9ce2a54..a291b72 100644 --- a/movement/tools/gen_tables.py +++ b/movement/tools/gen_tables.py @@ -4,8 +4,8 @@ spec = importlib.util.spec_from_file_location("bt", sys.argv[1]) bt = importlib.util.module_from_spec(spec); spec.loader.exec_module(bt) out = [] -sin = bt.sin_table() -out.append("pub static SIN: [i16; 640] = [%s];\n" % ", ".join(str(v) for v in sin)) +sin = bt.sin_table()[:512] # scaled sine and cosine index with & 511 only +out.append("pub static SIN: [i16; 512] = [%s];\n" % ", ".join(str(v) for v in sin)) atans = [] for k in range(17): v = bt.atan_scaled(k * bt.ONE // 16) From 4f24005dbdaedf4b67579cb2094830f83143d952 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 13:45:27 +0000 Subject: [PATCH 08/12] Docs: Record the req4 verdict and review answers Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 12 ++++++++++++ SPEC-QUESTIONS.md | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index 920fcd2..648a532 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -53,9 +53,21 @@ 2. req2 (every allocated record zeroed by the module): the same two differences. 3. req3 (the freed target's record zeroed before `SimFree`): `equal`, all 12 recordings. Scenarios, view and budgets are `not_judged`. +4. req4 (after the review fixes and the merge of spec-movement e089b23; 29123 bytes): `equal`, all 12 recordings. Scenarios, digest, view and budgets are `not_judged` (blocked entry). + +## Answers to /srv/inbox/review.md +- 1 (blocked-cell clamp): fixed. `max(lo).min(hi)` replaces `clamp`, so crossed wrapped bounds cannot panic. +- 2 (zeroing a freed target): kept. The spec (section 7, "A freed target's bytes", merged from `spec-movement`) now says to zero a target's record before `SimFree` until ozgb/byte-tactics-moddable#1380 is settled, and req1/req2 vs req3 showed the replayer needs it. The consequence the review names (a goal's stale target offset reads class 0, so no ORDER_FLAGS 0x80) follows from that; no recording is `differs` on it. DESTROY of a packed goal frees its target through the same path. +- 3 (`alloc_zeroed`): the extra zeroing is removed; the module relies on `SimAlloc` returning zeroed records, as the spec and ABI 9.3 say. +- 4 (`UnitTarget` null goal): guarded, gives 0. +- 5 (block bound): left at the manifest's `block_max`. The module cannot learn the block's real end; the spec does not name a bound (see below). +- 6 (null refs): left. A null `Ref` turns into address 0 plus the field offset, which lies in the unused region below the lowest window (ABI 2.1) that the loader leaves zero: the read is deterministic (0) and never traps. +- 7 (sine table): trimmed to 512 entries. + ## Unclear points in the spec or kit - DESTROY_TARGET: the replayer expects a freed target's bytes to read 0 after the call; the spec does not say so (SPEC-QUESTIONS.md, 1). - `SimAlloc`'s zeroing is promised by the spec, and the module does not rely on it (SPEC-QUESTIONS.md, 2). - The module-ABI text is clear that blocked entries have no budgets, but the kit has no local checker (`wasm_modules.py` is not in it): the exports, imports, window and element segment were checked by hand with `wasm-tools`. - The toolchain here is rustc 1.87 and LLD 20, whose `wasm-ld` does not list `--no-stack-first`; the stack falls after the data (top 628624, inside the window 622592..655360). +- The bound of "its record lies inside the block" (Apply targets, ApplyPathEvent requesters) is not given; the module uses `block_max` since it cannot see the block's real size. - No recording reaches the patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, SET_HEADING, air maneuver targets, follow offsets or refused events: those paths follow the spec text only. diff --git a/SPEC-QUESTIONS.md b/SPEC-QUESTIONS.md index 0ff029a..9278155 100644 --- a/SPEC-QUESTIONS.md +++ b/SPEC-QUESTIONS.md @@ -1,6 +1,6 @@ # Spec questions: movement -None of these blocks the module, which is `equal` (req3). Each was settled by a verdict, not by the spec. +None of these blocks the module. Question 1 is now answered by the spec (section 7, "A freed target's bytes"), pending ozgb/byte-tactics-moddable#1380. 1. **A freed target's bytes (spec 4, DESTROY_TARGET; 3, "Between ticks").** The spec says only `UnitRefUnlink`, then `SimFree`. With exactly that (req1, req2) the gate said `differs` in From d22b9bf58a7ead643fb195b9de6d4eff2a983bb9 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:00:52 +0000 Subject: [PATCH 09/12] Update: Give the block bound for movement offsets Answer finding 5 of the code review's first round: an event's offset is inside the block when it fits below block_max of the manifest. Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/specs/movement.md b/specs/movement.md index cd0451e..24815b8 100644 --- a/specs/movement.md +++ b/specs/movement.md @@ -348,7 +348,10 @@ A size below 8 gives 0. An unknown kind (325 included) gives 0, and so does a si - a *unit* is valid when it is not 0, at least `Game.units`, below `Game.unitsEnd`, and a multiple of 280 bytes from `Game.units`; -- a *target* is valid when it is not 0, its record lies inside the block, and its class word is one of the five +- a *target* is valid when it is not 0, its record lies inside the block (the offset, unsigned, plus 4 is at most + `block_max` of the manifest, 268435456, before its class word is read, and plus the record size of the kind that + word names, section 3, after: ABI 2.1 and 16; the same bound holds wherever this spec says inside or outside the + block for an offset an event gives), and its class word is one of the five target kinds' (section 3); a module reads nothing outside the block to decide it; - for DESTROY_TARGET, SET_ALTITUDE, SET_APPROACH_RADIUS and SET_HEADING, `target` must be valid, and `unit` is not looked at; for the others, `unit` must be valid and, but for NEW, have a motion; SET_TARGET's `target` must be 0 From 4b0a957a567b5248bdf4e7e90f5195edd0519e7d Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 14:12:43 +0000 Subject: [PATCH 10/12] Fix: Answer the second movement review Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 9 +++++++++ SPEC-QUESTIONS.md | 3 +-- movement/build.sh | 3 ++- movement/src/lib.rs | 14 +++++--------- movement/src/math.rs | 3 ++- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index 648a532..ad6e41d 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -71,3 +71,12 @@ - The toolchain here is rustc 1.87 and LLD 20, whose `wasm-ld` does not list `--no-stack-first`; the stack falls after the data (top 628624, inside the window 622592..655360). - The bound of "its record lies inside the block" (Apply targets, ApplyPathEvent requesters) is not given; the module uses `block_max` since it cannot see the block's real size. - No recording reaches the patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, SET_HEADING, air maneuver targets, follow offsets or refused events: those paths follow the spec text only. + +## Second review (after the spec's block-bound change, d22b9bf merged) +5. req5 (29375 bytes): `equal`, all 12 recordings; the rest `not_judged`. +- Non-trapping float-to-int: `build.sh` now passes `-nontrapping-fptoint`; the two remaining `trunc_f` casts are range-guarded (`round_to_int`, `dd_atan_ratio`), so none traps. +- Double free: `destroy_target` returns when the record's class word reads 0 (already freed and zeroed), so a packed goal's stale target is not freed twice. +- Block bound: the spec now names it (`block_max` plus the record size); `valid_target` and `ApplyPathEvent` already used it. +- `TargetType` gives 0 for anything but a kind 2 to 6; the plain-target branch is gone. +- The keep-alive branch in `TargetType` stays: it is what keeps the `UnitRefSetUnit` import and the `UnitTarget` element segment past `--gc-sections` (ABI 9.1), and it never runs. +- Stale notes fixed (`SimAlloc` is relied on to zero); `build.sh` removes its temp directory. diff --git a/SPEC-QUESTIONS.md b/SPEC-QUESTIONS.md index 9278155..01f7a5e 100644 --- a/SPEC-QUESTIONS.md +++ b/SPEC-QUESTIONS.md @@ -9,8 +9,7 @@ None of these blocks the module. Question 1 is now answered by the spec (section of the freed address to read 0 at the end of the call. Zeroing the target's record before `SimFree` made all 12 recordings `equal` (req3). Should the spec say that DESTROY_TARGET leaves the freed record zeroed, or is this an artefact of the replayer that the spec should name? -2. **`SimAlloc` zeroing (spec 3, "Owned").** The spec says `SimAlloc` returns a zeroed record. The module zeroes - each record it allocates itself (req2 onwards) in case a recycled block is not zero. No verdict separates +2. **`SimAlloc` zeroing (spec 3, "Owned").** The spec says `SimAlloc` returns a zeroed record. The module relies on that and does not zero records itself. No verdict separates the two, since req1 (no zeroing) and req2 differed only in the failure of question 1. 3. **Recordings that never reach a path** (patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, SET_HEADING, an air maneuver target, the follow offset, a refused `Apply`): the module follows the spec text diff --git a/movement/build.sh b/movement/build.sh index b6fefbd..e118aaf 100755 --- a/movement/build.sh +++ b/movement/build.sh @@ -2,9 +2,10 @@ # Builds module.wasm: link at the manifest's data base 622592 and table base 464, then the kit's fuel pass. set -e cd "$(dirname "$0")" -cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory \ +cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory,-nontrapping-fptoint \ -C link-arg=--import-memory -C link-arg=--import-table -C link-arg=--global-base=622592 -C link-arg=--table-base=464 \ -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/movement.wasm "$T/raw.wasm" python3 -I /data/tools/wasm_fuel.py "$T/raw.wasm" -o module.wasm +rm -rf "$T" diff --git a/movement/src/lib.rs b/movement/src/lib.rs index 9de8868..cfa5e49 100644 --- a/movement/src/lib.rs +++ b/movement/src/lib.rs @@ -218,7 +218,6 @@ const CW_LITE: u32 = 18; const CW_PACKED: u32 = 20; const CW_PATHORDER: u32 = 21; const CW_PATROL: u32 = 23; -const CW_PLAIN: u32 = 24; const CW_MARKER: u32 = 26; const CW_RING: u32 = 27; @@ -1125,6 +1124,10 @@ pub extern "C" fn UpdateMotion(u: u32) { // ---- Apply ---------------------------------------------------------------------------------------- fn destroy_target(t: u32) { + if target_kind(t) == 0 { + // already freed (and zeroed): a goal's stale target offset + return; + } if target_kind(t) == 2 { unsafe { unit_ref_unlink(t + PO_REF) }; } @@ -1433,14 +1436,7 @@ pub extern "C" fn TargetType(t: u32) -> i32 { return 0; } let a = base().wrapping_add(t); - let k = target_kind(a); - if k != 0 { - k - } else if ru32(a) == cw(CW_PLAIN) { - 1 - } else { - 0 - } + target_kind(a) } #[no_mangle] diff --git a/movement/src/math.rs b/movement/src/math.rs index 5c6de3c..3f3b1eb 100644 --- a/movement/src/math.rs +++ b/movement/src/math.rs @@ -418,7 +418,8 @@ fn dd_atan_ratio(n: f64, d: f64) -> Dd { if n == 0.0 { return dd_from(0.0); } - let k = (n * 16.0 / d + 0.5) as i32; + let kv = n * 16.0 / d + 0.5; + let k = if kv > -1e9 && kv < 1e9 { kv as i32 } else { 0 }; let kf = k as f64; let num = dd_add(dd_from(16.0 * n), dd_neg(dd_product(kf, d))); let den = dd_add(dd_from(16.0 * d), dd_product(kf, n)); From 03e6adad05b6494d8df812da32786a7ef0d5fbb2 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:29:36 +0000 Subject: [PATCH 11/12] Update: Compare movement event sizes unsigned Answer finding 1 of the code review's third round: the size of Apply and ApplyPathEvent is the header's unsigned int. Assisted-by: Claude:claude-opus-5-5 --- specs/movement.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/specs/movement.md b/specs/movement.md index 24815b8..5c0a421 100644 --- a/specs/movement.md +++ b/specs/movement.md @@ -71,7 +71,9 @@ and 9.1): | `TargetType` | `[int] -> int` | An order and a target are `int`: block offsets (0 for none) that the module stores and returns. A `short angle` -is the `int` kind, sign-extended from its low 16 bits (ABI 7). +is the `int` kind, sign-extended from its low 16 bits (ABI 7). The `size` of `Apply` and `ApplyPathEvent` is the header's +`unsigned int`: every comparison of that size in section 4 is unsigned 32-bit, so a size of −1 is 4294967295 and is not +below any payload's size. - Imports, every one listed and nothing else: @@ -540,7 +542,7 @@ three words and a cell as its two: `(342,Unit#5,66402231,22347776,21576404,62,20 `turnrate` and truncated, kept to 32 bits; `2 × brakerate` wraps at 32 bits; *lim* is hi(*k*²) times 4, wrapping. A `turnrate` of 0 here, a `brakerate` of 0 in the ground steering and a `maxvelocity` of 0 in the flying drag are in no recording; a module must not trap on them, and what it gives is not judged. -- **Comparisons**: `repathClaimTick` against the tick is unsigned. Every other comparison is signed, `turnrate` +- **Comparisons**: `repathClaimTick` against the tick and an event's `size` (section 2) are unsigned. Every other comparison is signed, `turnrate` and the ANGLES heading being unsigned 16-bit values widened to int. - **The carried water line**: `(seaLevel − draft)`, its low 16 bits as a signed whole, times 65536. - **Flying, in floating point.** *s* is the double hyp rounded to a float, then multiplied by the float 2⁻¹⁶ From a69e1c76cdcb03c1ab1dcad8bcf1116bad51735e Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 14:31:31 +0000 Subject: [PATCH 12/12] Fix: Answer the third movement review Assisted-by: Claude Code:claude-sonnet-5-5 --- IMPLEMENTATION-NOTES.md | 54 ++++++++++++++++++++--------------------- movement/build.sh | 4 +-- movement/ld-wrap.sh | 10 ++------ movement/src/lib.rs | 54 ++++++++++++++++------------------------- movement/src/math.rs | 4 +++ 5 files changed, 55 insertions(+), 71 deletions(-) diff --git a/IMPLEMENTATION-NOTES.md b/IMPLEMENTATION-NOTES.md index ad6e41d..55aed09 100644 --- a/IMPLEMENTATION-NOTES.md +++ b/IMPLEMENTATION-NOTES.md @@ -41,42 +41,40 @@ # movement implementation notes ## What was built -`movement/` is a `no_std` Rust cdylib (`src/lib.rs`: the slots, `src/math.rs`: the kit's runtime arithmetic, `src/tables.rs`: generated by `tools/gen_tables.py` from the kit's `bitexact_tables.py`). `build.sh` links at data base 622592 and table base 464 (stack 4096) through `ld-wrap.sh` (as for wind_meteors) and runs the kit's `tools/wasm_fuel.py`. The module is 29665 bytes; the entry is `blocked`, so size and fuel are `not_judged`. +`movement/` is a `no_std` Rust cdylib (`src/lib.rs`: the slots, `src/math.rs`: the kit's runtime arithmetic, `src/tables.rs`: generated by `tools/gen_tables.py` from the kit's `bitexact_tables.py`). `build.sh` links at data base 622592 and table base 464 (stack 4096) through `ld-wrap.sh` (which forwards to wind_meteors's one wrapper) and runs the kit's `tools/wasm_fuel.py`. The entry is `blocked`, so size and fuel are `not_judged`. Current module: see the last verdict below. - Records are read and written in place at the `layout.json` offsets (unaligned loads and stores). A `Ref` field holds a block offset; the code turns it into an address with `g_blockBase` and back. -- `math.rs` ports the kit's integer and double-double code (`sqrt`, `ftol`, `hypot` with the 64-bit-mantissa steps, `atan2`) and builds the sine and cosine of the rotate-a-point rule with a double-double Taylor series (the 65536-entry 80-bit table does not fit a 32 KiB window). `mathtest/` replays the kit's `runtime/vectors` (scaled sine and cosine, angle of a vector, rotate point, hypot, sqrt, ftol) against it: every record equal. -- The class words are read from the table at 0x10100000 (index per `layout.json` `class_words`); a target is valid when its class word is one of the five kinds and the record ends within `block_max`. -- `UnitRefSetUnit` and the table import are kept by a never-taken branch behind a never-written static (ABI 9.1 wants every listed import). +- `math.rs` ports the kit's integer and double-double code (`sqrt`, `ftol`, `hypot`, `atan2`) and builds the sine and cosine of the rotate-a-point rule with a double-double Taylor series (it stops once the terms are below 1e-45; the 65536-entry table does not fit the window). `mathtest/` replays the kit's `runtime/vectors` against it: every record equal. +- Class words are read from the table at 0x10100000; a target is valid when its class word is one of the five kinds and the record ends within `block_max`. +- `UnitRefSetUnit` and the table import are kept by a `#[used]` function-pointer table (`KEEP`, holding `UnitTarget` and a never-called wrapper of `UnitRefSetUnit`); the link uses `--no-gc-sections`, so no slot runs extra instructions for it. - The float steps of the flying correction follow spec section 5 literally (f32 roundings, Q8). +- `size` of `Apply` and `ApplyPathEvent` is compared unsigned (spec section 2, merged from spec-movement 03e6ada). +- DESTROY_TARGET zeroes the record before `SimFree` (spec section 7, "A freed target's bytes"). ## Verdicts, in order 1. req1: `differs`; 10 recordings `equal`, `orders-air` (tick 4095, call 35, `PathOrder#5.approachRadius`) and `orders-air-repair` (tick 670, call 10, `PathOrder#3.approachRadius`) differ. 2. req2 (every allocated record zeroed by the module): the same two differences. -3. req3 (the freed target's record zeroed before `SimFree`): `equal`, all 12 recordings. Scenarios, view and budgets are `not_judged`. +3. req3 (the freed target's record zeroed before `SimFree`): `equal`, all 12 recordings. +4. req4 (after the first review fixes, 29123 bytes): `equal`, all 12 recordings. +5. req5 (second review, 29375 bytes): `equal`, all 12 recordings. +6. req6 (third review, 29489 bytes): `equal`, all 12 recordings. +Scenarios, digest, view and budgets are `not_judged` throughout (blocked entry). -4. req4 (after the review fixes and the merge of spec-movement e089b23; 29123 bytes): `equal`, all 12 recordings. Scenarios, digest, view and budgets are `not_judged` (blocked entry). +## Answers to the reviews +First and second review: blocked-cell clamp uses `max().min()`; no extra zeroing of allocated records (`SimAlloc` zeroes); `UnitTarget` guards a null goal; `TargetType` gives 0 outside kinds 2 to 6; non-trapping float-to-int is on and the two remaining casts are range-guarded; the sine table is 512 entries; `build.sh` cleans its temp directory. -## Answers to /srv/inbox/review.md -- 1 (blocked-cell clamp): fixed. `max(lo).min(hi)` replaces `clamp`, so crossed wrapped bounds cannot panic. -- 2 (zeroing a freed target): kept. The spec (section 7, "A freed target's bytes", merged from `spec-movement`) now says to zero a target's record before `SimFree` until ozgb/byte-tactics-moddable#1380 is settled, and req1/req2 vs req3 showed the replayer needs it. The consequence the review names (a goal's stale target offset reads class 0, so no ORDER_FLAGS 0x80) follows from that; no recording is `differs` on it. DESTROY of a packed goal frees its target through the same path. -- 3 (`alloc_zeroed`): the extra zeroing is removed; the module relies on `SimAlloc` returning zeroed records, as the spec and ABI 9.3 say. -- 4 (`UnitTarget` null goal): guarded, gives 0. -- 5 (block bound): left at the manifest's `block_max`. The module cannot learn the block's real end; the spec does not name a bound (see below). -- 6 (null refs): left. A null `Ref` turns into address 0 plus the field offset, which lies in the unused region below the lowest window (ABI 2.1) that the loader leaves zero: the read is deterministic (0) and never traps. -- 7 (sine table): trimmed to 512 entries. +Third review: +- 1 (`size` signedness): the spec now says unsigned (merged 03e6ada); the module already compared unsigned (-1 is 4294967295, not below any size). +- 2 (stale target offset after reuse): kept. The spec says a goal keeps the offset it was given until given another and that a target is valid by its class word; the module cannot tell a reused block from the old one, and no recording reuses one. Destroying a target twice is guarded by the zeroed class word. +- 3 (`rotate_point` cost): the series stops once both terms are below 1e-45, far under double-double precision; the kit's rotate vectors are still all equal. +- 4 (keep-alive in `TargetType`): removed; see the `KEEP` table above. +- 5 (`alloc_zeroed`, `s_scaled`, `c_scaled`): removed, the callers use `sim_alloc` and the math functions directly. +- 6 (`build.sh` temp directory): `trap ... EXIT`. +- 7 (duplicate `ld-wrap.sh`): movement's forwards to wind_meteors's. +- 8 (notes): reorganised, one section each. ## Unclear points in the spec or kit -- DESTROY_TARGET: the replayer expects a freed target's bytes to read 0 after the call; the spec does not say so (SPEC-QUESTIONS.md, 1). -- `SimAlloc`'s zeroing is promised by the spec, and the module does not rely on it (SPEC-QUESTIONS.md, 2). -- The module-ABI text is clear that blocked entries have no budgets, but the kit has no local checker (`wasm_modules.py` is not in it): the exports, imports, window and element segment were checked by hand with `wasm-tools`. -- The toolchain here is rustc 1.87 and LLD 20, whose `wasm-ld` does not list `--no-stack-first`; the stack falls after the data (top 628624, inside the window 622592..655360). -- The bound of "its record lies inside the block" (Apply targets, ApplyPathEvent requesters) is not given; the module uses `block_max` since it cannot see the block's real size. +- DESTROY_TARGET: the replayer expects a freed target's bytes to read 0; the spec now says so, pending ozgb/byte-tactics-moddable#1380. +- The kit has no local checker (`wasm_modules.py` is not in it): exports, imports, window and element segment were checked by hand with `wasm-tools`. +- The toolchain (rustc 1.87, LLD 20) has no `--no-stack-first`; the stack falls after the data (inside the window). +- The block's real end is not visible to a module; the bound is `block_max` plus the record size, as the spec says. - No recording reaches the patrol and packed goals, `ApplyPathEvent`, `HasNetState`, SET_SPEED, SET_HEADING, air maneuver targets, follow offsets or refused events: those paths follow the spec text only. - -## Second review (after the spec's block-bound change, d22b9bf merged) -5. req5 (29375 bytes): `equal`, all 12 recordings; the rest `not_judged`. -- Non-trapping float-to-int: `build.sh` now passes `-nontrapping-fptoint`; the two remaining `trunc_f` casts are range-guarded (`round_to_int`, `dd_atan_ratio`), so none traps. -- Double free: `destroy_target` returns when the record's class word reads 0 (already freed and zeroed), so a packed goal's stale target is not freed twice. -- Block bound: the spec now names it (`block_max` plus the record size); `valid_target` and `ApplyPathEvent` already used it. -- `TargetType` gives 0 for anything but a kind 2 to 6; the plain-target branch is gone. -- The keep-alive branch in `TargetType` stays: it is what keeps the `UnitRefSetUnit` import and the `UnitTarget` element segment past `--gc-sections` (ABI 9.1), and it never runs. -- Stale notes fixed (`SimAlloc` is relied on to zero); `build.sh` removes its temp directory. diff --git a/movement/build.sh b/movement/build.sh index e118aaf..96146e0 100755 --- a/movement/build.sh +++ b/movement/build.sh @@ -4,8 +4,8 @@ set -e cd "$(dirname "$0")" cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory,-nontrapping-fptoint \ -C link-arg=--import-memory -C link-arg=--import-table -C link-arg=--global-base=622592 -C link-arg=--table-base=464 \ - -C link-arg=--no-entry -C link-arg=-zstack-size=4096 -C link-arg=--gc-sections + -C link-arg=--no-entry -C link-arg=-zstack-size=4096 -C link-arg=--no-gc-sections T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT cp target/wasm32-unknown-unknown/release/movement.wasm "$T/raw.wasm" python3 -I /data/tools/wasm_fuel.py "$T/raw.wasm" -o module.wasm -rm -rf "$T" diff --git a/movement/ld-wrap.sh b/movement/ld-wrap.sh index ada6ff2..e138f3b 100755 --- a/movement/ld-wrap.sh +++ b/movement/ld-wrap.sh @@ -1,9 +1,3 @@ #!/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 "$@" +# Same linker wrapper as wind_meteors's (one copy, so fixes do not drift). +exec "$(dirname "$0")/../wind_meteors/ld-wrap.sh" "$@" diff --git a/movement/src/lib.rs b/movement/src/lib.rs index cfa5e49..ad6de02 100644 --- a/movement/src/lib.rs +++ b/movement/src/lib.rs @@ -55,9 +55,14 @@ pub static mut g_extTdf: [u8; 8] = [0; 8]; #[no_mangle] pub static mut g_blockBase: u32 = 0; -// Never written: keeps the import `UnitRefSetUnit` and the table import that the ABI lists. -static mut NEVER: u32 = 0; -static KEEP: [extern "C" fn(u32) -> i32; 1] = [UnitTarget]; +/// Never called by a slot: it only keeps the import `UnitRefSetUnit` the ABI lists, and (through the +/// function-pointer table below, which `#[used]` retains) the table import and element segment. +extern "C" fn keep_unit_ref_set_unit(a: u32) -> i32 { + unsafe { unit_ref_set_unit(a, a) }; + 0 +} +#[used] +static KEEP: [extern "C" fn(u32) -> i32; 2] = [UnitTarget, keep_unit_ref_set_unit]; const BLOCK_MAX: u64 = 268435456; const CLASS_WORDS: u32 = 0x1010_0000; @@ -295,13 +300,8 @@ fn valid_unit(o: u32) -> bool { o >= first && o < end && (o - first) % UNIT_SIZE == 0 } -/// SimAlloc: the host returns the record zeroed (spec 3, ABI 9.3). -fn alloc_zeroed(size: i32) -> u32 { - unsafe { sim_alloc(size) } -} - fn seed_target(size: i32, class: u32, order: u32) -> u32 { - let t = alloc_zeroed(size); + let t = unsafe { sim_alloc(size) }; w32(t, cw(class) as i32); w32(t + T_SOURCE, order as i32); t @@ -327,12 +327,6 @@ fn udef(u: u32) -> u32 { fn head(px: i32, pz: i32, qx: i32, qz: i32) -> i32 { angle_of_vector(px.wrapping_sub(qx), pz.wrapping_sub(qz)) as i16 as i32 } -fn s_scaled(a: i32, s: i32) -> i32 { - scaled_sine(a, s) -} -fn c_scaled(a: i32, s: i32) -> i32 { - scaled_cosine(a, s) -} fn mulsh(a: i32, b: i32, k: u32) -> i32 { (((a as i64) * (b as i64)) >> k) as i32 } @@ -415,8 +409,8 @@ fn target_pos(t: u32, out: &mut [i32; 3]) -> bool { a = a.wrapping_add(r16(t + PO_HEADING)) as i16 as i32; } let fo = r32(t + PO_FOLLOW); - q[0] = q[0].wrapping_add(s_scaled(a, fo)); - q[2] = q[2].wrapping_add(c_scaled(a, fo)); + q[0] = q[0].wrapping_add(scaled_sine(a, fo)); + q[2] = q[2].wrapping_add(scaled_cosine(a, fo)); } q[1] = q[1].wrapping_add(r16(t + PO_ALT).wrapping_shl(16)); if q[1] > 0x1ff0000 { @@ -475,8 +469,8 @@ fn target_pos(t: u32, out: &mut [i32; 3]) -> bool { let (cx, cz) = centre(r16(t + 8), r16(t + 10), r16(u + U_FP), r16(u + U_FP + 2)); let a = head(r32(u + U_POS), r32(u + U_POS + 8), cx, cz); let r = (r32(t + 12).wrapping_add(r32(t + 16)) / 2).wrapping_shl(16); - out[0] = cx.wrapping_add(s_scaled(a, r)); - out[2] = cz.wrapping_add(c_scaled(a, r)); + out[0] = cx.wrapping_add(scaled_sine(a, r)); + out[2] = cz.wrapping_add(scaled_cosine(a, r)); true } 6 => { @@ -831,9 +825,9 @@ fn push(m: u32, u: u32, d: u32, a: i32) { } w32(m + M_SPEED, speed); let h = uheading(u); - w32(m + M_VEL, s_scaled(h, speed).wrapping_neg()); + w32(m + M_VEL, scaled_sine(h, speed).wrapping_neg()); w32(m + M_VEL + 4, 0); - w32(m + M_VEL + 8, c_scaled(h, speed).wrapping_neg()); + w32(m + M_VEL + 8, scaled_cosine(h, speed).wrapping_neg()); } fn waypoint(g: u32, kind: i32, i: i32) -> (i32, i32) { @@ -940,8 +934,8 @@ fn steer_air(u: u32, m: u32, d: u32) { v[2] = mulsh(v[2], f, 16); let e = ftol(((s as f64) - (mm as f64)) * 65536.0); let uh = uheading(u); - v[0] = v[0].wrapping_sub(s_scaled(uh, e)); - v[2] = v[2].wrapping_sub(c_scaled(uh, e)); + v[0] = v[0].wrapping_sub(scaled_sine(uh, e)); + v[2] = v[2].wrapping_sub(scaled_cosine(uh, e)); } // 3. let pp = upos(u); @@ -1055,9 +1049,9 @@ fn do_move(u: u32, m: u32, d: u32) { if r32(m + M_SPEED) > half { w32(m + M_SPEED, half); let h = uheading(u); - w32(m + M_VEL, s_scaled(h, half).wrapping_neg()); + w32(m + M_VEL, scaled_sine(h, half).wrapping_neg()); w32(m + M_VEL + 4, 0); - w32(m + M_VEL + 8, c_scaled(h, half).wrapping_neg()); + w32(m + M_VEL + 8, scaled_cosine(h, half).wrapping_neg()); } emit(&[340, uo, p[0], p[1], p[2]]); } else { @@ -1197,7 +1191,7 @@ pub extern "C" fn Apply(ev: u32, size: u32) -> i32 { match kind { 320 => { let d = udef(u); - let motion = alloc_zeroed(47); + let motion = unsafe { sim_alloc(47) }; let player = rref(u + U_PLAYER); let air = ru32(d + D_FLAGS1) & (1 << 11) != 0; let (size, class) = if r32(player) != 0 && r8(player + 115) == 3 { @@ -1211,7 +1205,7 @@ pub extern "C" fn Apply(ev: u32, size: u32) -> i32 { } else { (101, CW_AI) }; - let goal = alloc_zeroed(size); + let goal = unsafe { sim_alloc(size) }; w32(u + U_MOTION, off(motion) as i32); w32(motion + M_OBJ, off(goal) as i32); w32(motion + M_CLASS, r32(d + D_MCLASS)); @@ -1426,12 +1420,6 @@ pub extern "C" fn HasNetState(u: u32) -> i32 { #[no_mangle] pub extern "C" fn TargetType(t: u32) -> i32 { - if unsafe { read_volatile(addr_of!(NEVER)) } != 0 { - unsafe { - unit_ref_set_unit(0, 0); - read_volatile(addr_of!(KEEP[0]))(0); - } - } if t == 0 { return 0; } diff --git a/movement/src/math.rs b/movement/src/math.rs index 3f3b1eb..b3f8c51 100644 --- a/movement/src/math.rs +++ b/movement/src/math.rs @@ -560,6 +560,10 @@ fn dd_sincos(theta: f64) -> (Dd, Dd) { sin = dd_add(sin, ts); n += 1.0; i += 1; + // the rest are below double-double precision + if tc.hi.abs() < 1e-45 && ts.hi.abs() < 1e-45 { + break; + } } (sin, cos) }