How it works · write-up
Runtime state ownership correction
Working notes, rendered as they are: they were written while building the game, so expect ROM addresses, register names and references to source files that are not published.
Status: complete for backlog109. 2026-10-14.
Follow-up111 replaces its dedicated sprite byte buffer with typed records; see the final section and ARCADE_SPRITES.md.
Finding at the start of109
This finding and the intermediate checkpoints below describe the migration history. The final section records the completed replacement.
VideoCommandMachine allocates a 65,536-byte array in video-commands.ts.
Foreground, background, sprite output, globals and actor records occupy slices
of this same allocation. commandForeground() and commandBackground() return
views into it, not separate allocations.
Gameplay is currently hybrid. FirstSectionGame still owns typed player,
life, camera, scenery, projectile and actor models. prepareCommands(),
storeShotModels(), storeLinkedActorModel() and storeLiveScenery() copy
fields into the address space. Corresponding readers copy results back. Some
retained fields exist only in the array. Thus neither representation is merely
a disposable diagnostic snapshot. There are overlapping state owners.
The array first appeared with the command handlers in b9bce1a. Later native translations expanded its role into gameplay. This is architectural drift, not a requirement imposed by the source ASM or by MAME comparisons. No Z80 instruction execution makes this an emulated CPU; the TypeScript handlers themselves read and write the array.
Required ownership
Follow-up114: BackgroundState.work owns the24-bit EF00 camera coordinate.
FirstSectionGame.camera is a typed accessor view of that owner; its bounds
metadata, queued E057 and pulse have one CameraControlState. Snapshots contain
the work record and control state, without a second coordinate. E05B/C/D and
EDA2/3 are distinct source shadow/checkpoint fields, copied only at the source
write points. Native tests deliberately seed them differently to verify that
retention. The active-player phase clears E057 at8963/897D; camera9F09 retains it.
| State | Owner and interface |
|---|---|
| Player, life, input and camera | Named typed domain records; one owner per field. |
| Scripted/core/scenery/projectile pools | Typed slot records with named phase, fixed-point coordinates, counters, flags and retained fields. Preserve physical iteration and reuse rules. |
| Placement streams | Typed cursors into decoded ROM data. Keep original addresses as evidence/metadata. |
| Score, credits, lives and inventory | Their domain owners; command handlers receive explicit access to these owners. |
| Main command ring | A typed command queue with the source capacity and overwrite behavior. It routes both gameplay and presentation commands. |
| Background expansion/collision | Explicit background stream state, tile data and terrain grid. A streaming work record has named fields, not offsets into a global array. |
| Arcade tile/sprite output | A separate arcade presentation state. Structured sprite entries and dedicated tile buffers may retain output between updates. |
| ROM/MAME byte snapshots | Verification codecs outside production gameplay; decode fixtures into domain records and encode results for byte comparison. |
Byte arrays remain appropriate for ROM input, dense tile/terrain data, assets
and captures. They must not become an addressable store for unrelated gameplay
globals or pool entries. Wrapping the same array in getters, or renaming ram
to state, does not implement this correction.
Concrete examples
acceptNativeScenery() should receive scenery stream state, the scenery pool,
camera progress and placement rules. It updates a named placement cursor and
one typed slot. It does not find those through E05B/E05E/E800 addresses.
The existing scrollScriptedActorWord() already takes a coordinate and a pulse.
Its caller should update the actor's named coordinate/state and request hiding
its presentation components. applyNativeScriptedScroll() must lose its
general RAM argument and record/sprite addresses.
Retained source fields are still required where subsequent behavior reads them. Define those fields explicitly on the owning record, including byte wrapping and reset/reuse semantics. Do not replace them with collection queries or discard them when an actor becomes inactive.
Some actors write overlapping arcade sprite slots. Preserve that ordering in the arcade presentation adapter. It does not require overlapping gameplay records or a global CPU address space.
Replacement art boundary
Gameplay exposes entity identity, position, facing, action/phase, animation progress and compound component relationships. Arcade, high-resolution and 3D presentation adapters consume that semantic state. Sprite codes, tile indices and hardware slot addresses belong to the arcade adapter and evidence mapping. The existing model binding is a starting point, not proof that all native paths already support interchangeable rendering.
Migration order and completion gates
- Inventory each affected field and select its single typed owner. Include retained fields and every current store/read bridge. Record the mapping to source addresses for verification.
- Convert scenery allocation/update and scripted scrolling end to end, including initialization, contacts, runtime callers and setup-only lab scenarios. Move byte encoding/decoding into verification helpers. No new per-frame model-to-RAM-to-model bridge is acceptable.
- Apply the same ownership correction to player, projectiles, grenade/blast and linked actors. Preserve the established call order, slot reuse, retained output and ordered effects. Keep existing complete native comparisons.
- Convert background work, score/HUD, attract/start, name entry and transition
handlers. Give command consumers explicit typed dependencies. Remove the
global array from
VideoCommandMachine, then rename/decompose that type to describe its actual command-processing responsibilities. - Remove obsolete bridges and production address arithmetic. Verify all affected ROM fixtures through codecs, run domain/runtime tests, and inspect the shared-runtime HTTP scenarios in arcade and model presentation modes.
Each migrated subsystem must have one authoritative state, no production 64 KB scratch snapshot, and no invocation of the old RAM implementation hidden behind an adapter. Keep the coverage ledger's verified behavior evidence; change implementation links as modules move. This architecture correction does not itself close any remaining ROM behavior obligation.
The user requested a verified checkpoint of the background cursor work before the migration. Its HTTP scenario and native comparisons are recorded in NATIVE_BACKGROUND_VIDEO.md. This checkpoint retains the current storage; the subsequent migration must preserve the findings with typed owners.
Implemented migration checkpoint (historical)
Scenery's eighteen storage slots, nine-record display pass and placement cursor
now have named fields in scenery-slots.ts. Linked01/02 has named records and
a side counter in linked-actor-state.ts. FirstSectionGame exposes semantic
projections for existing consumers; those projections are not stored in a
second pool or snapshot. Scene/start/cinematic paths use the same owners.
scenery-state.ts and linked-actor-models.ts initialize/project typed records;
they no longer read or write a byte array.
scripted-actor-scroll.ts accepts a named scroll record and returns removal /
hide count. Linked actor updates use it directly. The queued core contact
consumer also uses typed shot/enemy records; its previous64KB temporary array
is removed. ROM snapshot codecs are under tests/helpers, never production.
Complete existing MAME comparisons still pass:256 scenery updates,512 linked updates,256 births,32 linked/shot combined updates, all1109 queued contacts and controlled suspensions, plus startup and scroll fixtures. A runtime ownership test poisons the old E800/E500/E0BC locations and proves they are neither read nor rewritten. Snapshot/restore retains one typed owner. HTTP scenery breakup and linked collapse still show the retained pose and3000-point result.
The player/projectile, grenade/blast, background work, HUD/score and scene consumers still require migration. The dedicated sprite-output view temporarily shares the old allocation with unmigrated writers to preserve alias ordering; it contains presentation bytes only. The global allocation is not yet removed.
Background storage migrated
BackgroundState owns the streaming work record, loaded stage parameters,
terrain metadata, expansion and collision data, and tile/color output.
background-commands.ts and native-background-video.ts no longer accept a
RAM address space. Named word fields preserve split reads/writes across the
source cursor. Projectile terrain reads receive the collision window directly.
The old D800/EF00/F000 storage is poisoned in a runtime test and remains
untouched; the shared HTTP scenario still ends atD87E. All413 tests pass,
including all10 native transactions, four IRQs and10 controlled suspensions.
The global command array still exists for player/projectile, grenade/blast, HUD/score and remaining scene state. Removing it completely remains109.
Projectile storage migrated
All fourteen projectile slots now live in ProjectileState. Named records own phase/counts, flags, heading/velocity, coordinates, retained fractions and semantic identity metadata. Player/enemy shot arrays and fraction lists are read-only semantic projections; explicit spawn/contact writers update the records. Neither projection clocks behavior or stores another authoritative pool. The two per-frame storeShotModels RAM copies are removed. Native flight, player allocation and terrain contact take typed records/context directly.
Enemy birth warmup remains at its source producer phase; setup snapshots keep their captured timer. Phase02's terminal state01 is distinguished from a queued contact using its phase and retained impact metadata. The existing native full-buffer matrices and long ordinary-route tests all pass. The ownership regression now poisons E200-E3BF as well, and snapshot data contains no duplicate playerShots/enemyShots arrays. HTTP expiry/impact output is verified.
Player/control and grenade/blast, HUD/score and remaining scene state still use the global array and remain109. Dedicated sprite output remains a shared presentation view during migration of its remaining writers.
Player/control and grenade/blast migrated
PlayerRuntimeState owns the player and grenade control records, lives, stock, throw delay, pending scroll and blast/latch state. Player, life and grenade DTOs are projections; setup and effect writers explicitly update their owner. The active-player, grenade flight and blast rules take typed state and dedicated sprite output directly. Their per-frame RAM copies are removed. Native comparisons (896 player,256 grenade and384 blast updates) and long ordinary routes pass. HTTP launch and landing/next blast-pose output is verified. Snapshots contain no duplicate player/life/grenade DTOs; poisoned E100/E140, E080 and E09C-E09E stay untouched during gameplay.
The source A5FE clears36 eight-byte positions:18 scenery records' state and attribute, not12 records. A nonzero last-slot regression now verifies this without clearing its retained sprite/coordinate fields. HUD/score and scene consumers still use the transitional global allocation; the cinematic pulse still uses a narrowly scoped old-template caller until its record is migrated. Item109 remains open until that allocation and its remaining bridges are gone.
Global allocation removed
HUD scores/thresholds/high-score rows/saved player banks now have named records
in hud-state.ts. IRQ fields have one FrameIrqState owner: the runtime's irq
property references it directly. Commands update lives/stock on PlayerRuntimeState,
with no prepare/finish copy. Score producers queue an award; the command consumer
applies it once. Player score and next-threshold views reference the HUD owner.
Pending scroll is returned to the camera owner, not retained in a second control
record.
Attract/start context lives in session-state.ts; cinematic vehicle/pulse and
name-entry movers/shots/letter effects have their own typed records. E10B's name
cursor Y/copied player Y is represented by one cursor field. Vehicle X uses one
24-bit fixed coordinate, preserving its overlapping source word operations.
Name-entry's retained command targets map explicitly to typed owners or sprite
output; unknown writable targets fail explicitly and remain part of wider92
scheduling work. Source pointer numbers remain provenance/cursor metadata.
VideoCommandMachine.ram, the65,536-byte allocation, per-frame preparation and
all production address-array adapters are removed. Its replacement, ArcadeCommandContext, is an aggregate
of typed owners and command/presentation context; it does not emulate a CPU. CommandSourceAddress values are source provenance, not storage offsets.
Foreground code/color and384-byte sprite output are separate allocations.
Background expansion/collision/tile data and command/sound rings remain dedicated
buffers. tests/helpers/machine-snapshot.ts and session-snapshot.ts alone
assemble an address space for the unchanged independent native expectations.
All416 TypeScript tests and37 Python tests pass, including native HUD/score, name-entry, attract/start, player/projectile/linked/scenery/background matrices and long routes. The production import-boundary test rejects address-array access/allocation, verifies no lab imports, and snapshot tests reject duplicate player/shot/score/IRQ projections. HTTP background wrap, grenade launch/blast, name entry, title setup, gate rendering and corrected throw inspection pass. The standalone gate preview now also matches384 native compound outputs. This completes109's storage correction; behavioral coverage and wider scheduler, actor/output aliases and legacy lab migration obligations retain their own IDs.
Source0734-0759 pool clears are delivered through StartGameEffects.clearActorPools to the canonical core/scripted owners at restore, before the cinematic. This shares clearActorPools with the runtime reset; it does not defer the effect to world handoff or introduce scenario-specific stepping. A populated-pool runtime regression verifies the source phase and removal of actor identities/residue.
Sprite output is now96 typed records (111)
ArcadeCommandContext.spriteOutput is an ArcadeSpriteTable of96 independent
objects. Image/bank, palette, flips, complete signed X, complete Y and retained
attribute bit1 have named fields. Every writer, template, semantic-piece adapter
and renderer consumes these records directly. There is no backing byte buffer,
per-frame packing bridge or second sprite-output owner. Source addresses remain
placement/provenance metadata and convert to physical slot indices on entry.
Byte packing lives in mame-sprite-snapshot.ts and test snapshot helpers.
Production play cannot import that codec. Existing native full-region matrices
still compare original bytes; all422 TS/37 Python tests pass. The actual renderer
matches frame1600's57,344 pixels and runtime throw/blast/gate images were inspected
using local Canvas. Browser HTTP interaction was blocked by controller policy.
This completes111 without changing the wider gameplay/scheduling coverage claims.
Loaded settings and clocks (116)
BackgroundState.difficulty owns all F0-FA fields, including live F3/F6/F8/FA. FirstSectionGame.enemyShotCooldown and randomCore.clock are unstored typed views that follow settings replacement and restore. randomCoreRecords holds the random registers, soldiers and count metadata only. Snapshot storage excludes both views. Settings readers use the loaded record, retaining the old row until the real queued background command runs. No camera-boundary substitute reload remains.
Section presentation and cursor projections (127)
SceneState owns E062; cameraControl.scrollPulse is an unstored view. Captures store cameraPlacement's max/pending controls and the source scene once. E096 remains a physical AFB1 record address. Wave metadata is resolved by recordAddress across ordinary and gate records, never a filtered-array index. Section modes05/06/07 call source handlers; sectionBackground stores only the in-flight typed continuation. It does not contain a second gameplay timer.
ArcadeCommandContext.semanticScene contains presentation snapshots with stable object/sequence/component identities, variant, action, phase, source remaining timer and native transforms. The section vignette combines0999 tiles,0B36 body, optional0B65 sprite and0B86 effect. The transport combinesAB27 body,ABCE shadow andAD63 effect. Components refer to replacement assets independently of96 native sprite slots; a later3D renderer can replace the whole object while retaining source behavior. These projections never drive collision, movement or timing.