How it works · write-up
Commando architecture reference
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.
The browser game translates the rules and data of Capcom's 1985 Commando (World) into TypeScript. Gameplay preserves source record identities, fixed capacities, update order, partial writes and queued effects. Rendering can use the original sprite output or a semantic object projection for replacement art. The production runtime does not execute Z80 instructions or store a global 64 KiB emulated RAM array.
CommandoGame is the shared runtime's historical name; it also runs later
sections and the Area 2 progression covered by completed session and replay
acceptance.
Separate browser hosts provide play and laboratory controls around that runtime.
Navigate: glossary, hardware, execution, state and limits, scripts, audio, input, rendering, verification, main RAM map and visual address explorer.
Reading the source
Addresses such as $159D identify the original main-CPU address space. Record
offsets such as +$13 are hexadecimal. A range includes both endpoints unless
marked exclusive; KiB means 1,024 bytes. A source address in a TypeScript enum
usually records provenance or a cursor identity, rather than an index into live
RAM. Follow the owning field before assuming storage or aliasing. The audio
chapter names sound-CPU addresses explicitly; its $4000–$47FF RAM belongs to
a separate CPU address space, not the main ROM at the same numeric addresses.
MAIN_RAM_MAP.md inventories the complete $D000–$FFFF
main-CPU RAM range, known globals, record offsets, scene overlays and unresolved
gaps. It includes a visual overview and an interactive explorer.
The original uses fixed-address allocation scans rather than a general heap;
release/reuse and name-entry or sprite-output overlays still retain and alias data.
There are three distinct forms of evidence:
- Source-established: raw ROM data and bounded ASM caller/return analysis define the rule, including selectors, retained fields and ordered effects.
- Native-verified: controlled MAME transactions check specified incoming states, outputs and effects at equivalent caller boundaries. Their seeded inputs and interventions bound the claim.
- Route-verified: recorded inputs exercise composed progression. The accepted browser routes and their selected native caller comparisons do not establish identical physical-frame trajectories or complete pixel equality.
BACKLOG.md states current acceptance and deferred work.
first-section-obligations.json and
rom-coverage.json are authoritative for source review and
coverage; their Markdown reports are generated views. RESEARCH.md
contains detailed evidence. Historical notes in subsystem documents can describe
earlier migration checkpoints; use the current owners and canonical backlog
when interpreting their old pending-work lists.
Glossary
Terms are grouped by context. In particular, bank, native, frame and script have more than one meaning; their entries distinguish those uses. Code identifiers are linked at their subsystem descriptions below.
objects and storage, gameplay and progression, execution and scripting, numbers and data formats, hardware and input, audio playback, graphics and presentation, research and verification.
Objects and storage
| Term | Meaning in this project |
|---|---|
| Actor | A behavior-bearing source record dispatched by a gameplay pass. Often used specifically for the $E500 scripted family; name the family when the distinction matters. An actor need not be visible. |
| Core / core actor / core enemy | Project shorthand for the enemy family occupying eight 32-byte records at $E600–$E6FF, updated by $0F9E. It includes random soldiers, wave-controlled soldiers, enemies emitted by other actors and the converted transport subtype. “Core” identifies this pool and dispatch family, not an object's importance or the game engine's infrastructure. Its subtype IDs use ArcadeEnemyKind. |
| Scripted actor | The separate eight-slot $E500 family, whose kind IDs use ArcadeActorKind. Placements and emitted births feed its native behavior routines. These actors can create core enemies in $E600; core enemies can themselves follow motion scripts, so “scripted” does not mean that only $E500 objects use scripts. |
| Entity or semantic object | A logical gameplay/presentation identity, such as a soldier, gate or vehicle. It can include several source records or sprite pieces. Entity is also an older concrete interface in model.ts; the richer presentation contract is WorldObjectPresentation. |
| Family / namespace | A group whose IDs have their own meanings, such as scripted actors or core enemies. Namespace keeps identical numeric IDs in different families distinct. |
| Kind or subtype | A value selecting behavior within one family. $E500 kinds, $E600 subtypes, scenery kinds and spawn modes have separate namespaces; the same byte does not mean the same object across them. |
| State / controller / state machine | State is the current field values. A controller updates them. A state machine describes the allowed phases and the conditions/effects of moving between them. |
| Scene / world | Scene identifies a session or presentation sequence, such as attract or startup. World refers to active gameplay with player, camera, actors and contacts; scene state also controls world progression. |
| Record | The fields of one source object or controller. A source byte layout is represented by named fields, sometimes distributed between allocation metadata, residue and a subtype owner. |
| Slot | A physical position in a fixed table. Reusing a slot does not continue the former occupant's logical lifetime. |
| Pool | A fixed-capacity allocation domain. Distinguish its slot ownership, complete behavior state and update dispatcher; an allocator array alone need not contain all three. |
| Allocation domain / physical capacity / admission threshold | An allocation domain shares a set of slots. Physical capacity counts those slots; an admission threshold is a caller's additional limit on accepted births. |
| Allocator | A rule that selects a free slot and applies the source initializer's writes. It may inspect only a restricted slot range or reject admission before scanning. |
| Allocation shell / subtype collection | An allocation shell stores slot ownership and residue. A subtype collection stores behavior-specific live records associated with those same slots; it adds no physical capacity. |
| Admission / initializer | Admission decides whether a birth may claim a slot. Its initializer applies the source-defined starting writes, including which old fields survive. |
| Birth or spawn / release | Birth starts an object's lifetime in a claimed record. Release makes that slot reusable; it need not erase all fields or immediately remove its sprite output. |
| Singleton | One dedicated controller record or effect, rather than an independently allocatable collection; for example, the player grenade or shared blast. |
| Owner | The authoritative storage for a field. An actor's ownerId additionally identifies who currently holds its physical slot. |
| Projection or view | A derived representation of owned state. A getter can expose live values; a presentation query returns detached values. Neither creates another gameplay clock or independent pool. |
| Getter / read-only / detached | A getter computes or exposes a value when read. Read-only consumers do not write through their interface. Detached values do not share mutable storage with the gameplay owner. |
| Compound entity | One established whole object with source-identified components, such as a linked center/sides assembly or a vehicle and its gunner. Nearby artwork alone does not establish membership. |
| Structure / layout context | A bounded ROM terrain layout with geometry, provenance and references to independent live actors. WorldStructurePresentation adds no actor, collision body or allocation pool; containment does not establish parentage. |
| Source-owned sprite state | Sprite records that the original logic reads back as authoritative state. The final-exit effect uses 20 such records for positions and column removal; most actor projections instead use separate typed behavior state. |
| Component / relationship | A component is a named part of a whole object's presentation. A relationship records a proved link between objects or parts, such as emission or a shared counter. |
| Linked actor / parent / child / emitter | Linked actors cooperate through established state or counters. An emitter creates another actor; parent/child names that creation link and does not make the child the same lifetime. |
| Lifetime / birth generation | A lifetime runs from one birth to its retirement. A birth generation distinguishes successive occupants of the same slot for stable presentation identities. |
| Conversion | A source transition that changes an existing record's subtype or effect role in place. Its retained fields and presentation identity follow that transition's contract. |
| Occupancy / logical presence / visibility | Occupancy means a slot is held. Logical presence means an object exists in gameplay or its projection. Visibility means it is currently drawn; these conditions can differ. |
| Alias / output alias | Two source roles use the same storage position or output slot. Their writes interact in source order; separate role names do not create separate memory. |
| Retained data or residue | Values the source leaves unchanged across an update, release or slot reuse. These can affect the next occupant; they are intentional state. |
| Partial write | An operation that replaces only specified fields or bytes. Writing a coordinate's whole byte can preserve its fraction; hiding output can preserve image and attributes. |
Gameplay and progression
| Term | Meaning in this project |
|---|---|
| Placement | A ROM record describing when and where to admit an object, usually relative to camera progress. A catalog placement is not a live actor. |
| Scenery | Pool-managed environmental objects such as palms and rocks. Scenery records are distinct from background tiles even when both depict the environment. |
| Terrain / collision category / collision mask | Terrain is the live background collision data. A category selects a shape mask; the mask's bits determine which sampled cells block or contact an object. |
| Contact / hit-pending | Contact is the source test for an interaction between positions or collision shapes. Hit-pending records a detected hit whose later update performs the damage/death transition. |
| Accepted coordinate / movement candidate | Accepted coordinates are the committed position. A candidate is a proposed position awaiting source bounds/contact checks; retained candidates can differ from the last accepted position. |
| Heading / facing / pose heading | Heading selects a movement or aiming direction. Facing is the presented orientation; a separate pose heading can retain the direction used to choose art. |
| Vector / velocity / speed index | A vector gives directional components; velocity gives displacement per update. A speed index selects a ROM table, rather than directly expressing pixels per update. |
| Terrain grace / turn flag | Terrain grace temporarily changes the movement contact checks defined by the actor's source path. A turn flag selects pending steering work and can bypass ordinary script timing. |
| Wave | A scheduled group or sequence of core-enemy births selected through wave records and motion templates. Pending placements and live occupants are tracked separately. |
| Gate / gate latch | A gate is an encounter/progression boundary; a gate door is a particular visible actor. The gate latch is a gameplay flag holding camera progression and changing the control path during gate combat. |
| Drain / forced exit | Drain means finishing pending wave births and clearing the relevant live core records. Forced exit is the source-controlled player approach that follows the encounter's completion. |
| Area / section / loop | This reference uses area for a map-stream group and section for a gate-bounded progression segment. A loop is a new pass through the progression sequence after its final transition. |
| Checkpoint / restart | A checkpoint is the source-selected saved restart position/state. Restart restores that state after a lost life or turn change; it is distinct from restoring an arbitrary test snapshot. |
| Player bank / turn handoff | A player bank saves the per-player values needed across turns, including lives, stock and checkpoint. Turn handoff selects the next player's saved state. |
| Cooldown / warmup / throw delay | Cooldown delays another permitted action. Projectile warmup is an initial launch phase. Throw delay counts down before grenade launch; none is a universal wall-clock delay. |
| Burst / muzzle offset | A burst schedules multiple firing requests. A muzzle offset positions a new projectile relative to its emitter and selected facing. |
| Impact / expiry / blast | Impact is a projectile's contact response; expiry is its timed end-of-flight response. A blast is an explosion effect/controller, which can be shared by several source producers. |
| Stock / credits / bonus threshold | Stock is the remaining grenade count. Credits are paid starts available to the session. A bonus threshold is the score boundary for an extra life under the selected policy. |
| Boot or service / attract / cinematic | Boot/service performs startup checks or service-mode work. Attract is the title/demo flow before play. A cinematic is a controller-driven introduction or transition sequence. |
| RNG | Random-number generator. Here it is the source's deterministic retained-register algorithm; the same incoming state and inputs produce the same sequence. |
| High score / ranking / name entry | A high score is a stored leading score. Ranking determines a final score's place in that table; eligible name entry records the player's identifying letters. |
Execution and scripting
| Term | Meaning in this project |
|---|---|
| Runtime / browser host / entry point | The runtime advances shared game state. A browser host supplies UI, input and display scheduling around it. An entry point is the module/function that starts that host. |
| Module / import graph / build | A module is a source unit with imports/exports. The import graph describes its dependencies. The build emits JavaScript from TypeScript for browser/test execution. |
| TypeScript / typed state / enum | JavaScript is the language executed by the browser. TypeScript adds checks on declared shapes before emitting JavaScript. Typed state uses named fields; enums name defined IDs or values. |
| Interface / contract / API | An interface specifies data or operations exposed to a consumer. A contract adds their required behavior. API means application programming interface, the entry points available to calling code. |
| Callback / setup hook | A callback is a function supplied for another component to invoke. A lab setup hook initializes the shared runtime; it does not provide another gameplay update loop. |
| Dispatcher / dispatch table / selector | A dispatcher chooses a routine using a selector value. A dispatch table maps selector values to handlers; kind, phase and command selectors each belong to their own context. |
| Routine / caller / callee / return boundary | A routine is a bounded piece of source behavior. The caller invokes it, the callee performs it, and the return boundary is where control and returned state reach the caller again. |
| Stack / stack exit | The Z80 stack retains return addresses and saved values. A source stack exit changes which continuation receives control, so translated code must preserve the skipped work and remaining effects. |
| Producer / consumer / ordered effects | A producer creates a request or state change; a consumer processes it. Ordered effects are externally relevant writes/requests in their source sequence, including sound and score requests. |
| Synchronous update | The sole gameplay scheduling policy: perform a modeled update, then drain main commands in order unless a section/restart continuation blocks them. There is no main-CPU cycle counter or simulated raster interruption. |
| Atomic / interleaving / cached read | Atomic work completes without an intervening update. Interleaving suspends it while other work runs. A cached read keeps a previously sampled value across that suspension. |
| Cursor / pointer | A cursor records progress through a stream or unfinished routine. A source pointer is an address selecting data or output; a TypeScript cursor may instead use a typed index. |
| Script | Context-dependent: the compact $159D motion bytecode, a placement stream, or a TypeScript lab initializer. These have different formats and responsibilities. |
| Bytecode / opcode / operand | Bytecode is a compact instruction stream interpreted by a reader. An opcode selects an operation; operands provide its arguments. Motion bytecode and Z80 machine instructions have separate formats. |
| Placement stream / template / lookup table | A placement stream schedules records in order. A template supplies a birth or composite-data pattern. A lookup table maps an index to data, such as direction vectors or pose codes. |
| Timer / counter | A timer usually counts toward a transition; a counter records elapsed updates, events or a sequence position. Each field has its own decrement, wrap and selection rules. |
| Phase | A selector for a controller or actor's current behavior. A phase byte has meaning only within that controller. |
| Tick or update | A modeled gameplay update or a particular source counter. Browser refresh, gameplay update, physical raster frame and an actor's animation tick are separate quantities. |
| Frame / render / accumulator | A raster frame is a board display interval; a browser frame is a display callback. Render draws current output. The host accumulator turns elapsed time into requested gameplay steps. |
| Main command | A two-byte request consumed outside the gameplay IRQ, including video, score and queued shot/core contact work. It is not a motion-script instruction. |
| Sound command | A source sound-request byte queued for transfer to the sound CPU. Modeling that request/ring is separate from generating audible sound. |
| Ring buffer / overrun | A bounded sequence whose read/write positions wrap to its beginning. Overrun occurs when a producer reaches unread entries; these source rings do not gain an implicit overflow queue. |
| Source continuation | A typed cursor retaining work between source boundaries, including cached reads and partial effects. It is not a second actor simulation. |
| Handoff | Transfer from one controller stage or player turn to the next while carrying the required state and retained output; a handoff need not reset gameplay. |
Numbers and data formats
| Term | Meaning in this project |
|---|---|
| Address space / address / offset | An address space is the numbered locations visible to one CPU. An address selects a location; an offset is a displacement from a record, buffer or other base. |
| Bit / nibble / byte / word | A bit is one binary digit; a nibble is four bits; a byte is eight. A word in the documented Z80 layouts is sixteen bits, or two bytes. |
| Hexadecimal / KiB | Hexadecimal is base 16; $FF and 0xFF both mean 255 decimal. KiB is 1,024 bytes; hexadecimal suffixes preserve source values in names. |
| High byte / low byte / endianness | The high byte contains a word's most significant bits; the low byte its least significant bits. Big-endian stores high first; little-endian stores low first. |
| Mask / bit field / flag | A mask selects particular bits. A bit field packs several values into those bits. A flag is a condition represented by a bit or source-defined value. |
| Signed / unsigned / wrap | Signed values can encode negatives; unsigned values cannot. Wrapping arithmetic discards bits outside the source width, so an eight-bit increment from $FF produces $00. |
| Fixed-point coordinate | An integer encoding whole and fractional pixels, commonly 8.8: $1234 means 18 + 52/256 pixels. Velocity words can be signed; coordinate arithmetic preserves source wrapping. |
| Packed BCD | Decimal digits stored one per nibble: $09 is nine, $10 is ten. Score, credits and grenade stock follow their source decimal arithmetic and scaling. |
| Raw ROM / dump / decrypted opcode / disassembly / ASM | Raw ROM is the original stored bytes; a dump is a byte copy of a chip or memory range. Decrypted opcodes form the instruction-fetch view. Disassembly expresses instructions as assembly language (ASM); verify printed data bytes independently. |
| Header / prefix / terminator | A header precedes a record's main data; a prefix is its opening portion. A terminator is a format-specific stop marker; $FF terminates some placement streams but repeats in motion bytecode. |
| Encode / decode / packing | Encoding converts named state into a specified representation; decoding recovers named values. Packing combines fields into source bytes, while retaining their defined width and bit positions. |
| Register / register bank | A CPU register is a small processor-held value. A register bank is a selectable register set. The software RNG's retained register list is an algorithm's state, not CPU hardware registers. |
Hardware and input
| Term | Meaning in this project |
|---|---|
| CPU / Z80A / PCB | CPU means central processing unit, which executes machine instructions. Z80A is the processor type on this board. PCB means printed circuit board. |
| RAM / ROM | RAM is random-access memory used for writable working state. ROM is read-only memory holding persistent program/data; the supplied ROM archive contains chip dumps rather than a live memory snapshot. |
| SRAM / EPROM / PROM / bipolar PROM | SRAM is static RAM, retaining data while powered without dynamic refresh. EPROM is erasable programmable ROM; PROM is programmable ROM. Bipolar PROMs use bipolar-transistor circuitry; the board uses them for fixed color/timing lookups. |
| Clock / Hz / kHz / MHz / cycle / T-state | A clock supplies timing pulses. Hz counts pulses per second; kHz/MHz mean thousands/millions per second. A Z80 T-state is one CPU-clock period; an instruction can take several. |
| DMA / bus arbitration | DMA, direct memory access, transfers data through hardware. Bus arbitration controls who may use shared memory connections and can delay the CPU. |
| Port / latch / buffered output | A port is a hardware input/output interface. A latch retains the last written value. Buffered sprite output is a published copy the video hardware can display while CPU work continues. |
| Bank | A context-specific group: an image bank selects a range of sprite codes, an input bank selects player controls/history, and a saved player bank retains turn state. These are separate uses of the word. |
| Active-low / active-high | An active-low input is asserted by a zero bit; active-high uses a one bit. The runtime complements raw active-low arcade contacts into pressed masks. |
| Input history / qualified press / edge | Input history stores recent sampled button bits. A qualified press passes the source history test; its edge is a released-to-pressed transition, rather than every sample of a held button. |
| DIP switch / cabinet / upright / cocktail | DIP means dual in-line package; the board's small switch banks configure play. Cabinet is the enclosure/control arrangement: upright uses a standing display, cocktail a table with controls on opposing sides. |
| Interrupt / IRQ / NMI | An interrupt transfers CPU control to a handler. IRQ means interrupt request. The board's maskable request path can be disabled by DI; NMI means nonmaskable interrupt, which DI cannot disable. |
| Interrupt vector / handler | The vector selects the interrupt's service entry; the handler is the routine reached there. A requested interrupt can remain pending until execution permits acceptance. |
| RST / RET / DI / EI | Z80 mnemonics: RST calls a fixed restart address; RET returns through the stack. DI disables maskable interrupts; EI enables their acceptance after the following instruction. |
| Raster / scanline / vblank / HSync / VSync | A raster display produces successive pixel lines, called scanlines. Vblank is vertical blanking outside visible lines. HSync and VSync synchronize horizontal lines and vertical frames. |
| FM / PSG / SSG / OPN / DAC | FM is frequency modulation for sound generation; PSG means programmable sound generator. SSG names the YM2203's tone/noise/envelope section used for effects here. OPN is Yamaha's FM Operator Type-N family. DAC means digital-to-analog converter, producing analog output from digital sound values. |
| RGB / bits per pixel | RGB means red, green and blue color components. Bits per pixel describes how many bits encode a source image's palette index, before palette lookup. |
| UI / focus / blur | UI means user interface, including buttons and controls. Focus selects the element receiving keyboard input; browser blur means losing focus, which clears the held-key set here. |
Audio playback
| Term | Meaning in this project |
|---|---|
| Output observer / audio bridge | A host adapter that reads already-published $C800/$C804 writes and forwards newly observed entries to playback. It does not consume the gameplay sound ring again or change its decisions. |
| Sound driver / audio stream | The sound driver's commands, priorities and note/effect bytecode belong to the separate audio program. They are distinct from core motion bytecode and the main-command ring. |
| Synthesizer / ymfm / reSIDfp | A synthesizer generates samples from chip state. ymfm supplies YM2203 synthesis; reSIDfp, through libsidplayfp, supplies C64 SID playback. These libraries do not emulate the main arcade CPU. |
| PCM / sample / sample rate | PCM is pulse-code modulation: numeric amplitude samples. A sample rate counts samples per second. The audio engine renders blocks at the browser's selected sample rate. |
| Stem / mixing / FM music / SSG effects | A stem is a separate sample stream. Music and effects are mixed with independent gains; C64 music can replace the music stem while arcade effects continue. |
| Worker / AudioWorklet / PCM queue | A worker serializes driver and synthesis work outside the UI thread. An AudioWorklet consumes queued PCM on the browser audio rendering thread. These are playback resources, not gameplay pools or part of captureState(). |
| WASM | WebAssembly, the compiled format used by the pinned browser synthesis libraries. It is separate from ROM bytecode and the project's TypeScript gameplay translation. |
| SID / PSID / subtune / MOS6581 / PAL | SID is the C64 sound chip; a PSID file contains tune data/code for a SID player. A subtune selects one song within that file. MOS6581 names the default chip model; PAL selects the default C64 timing standard, subject to tune metadata. |
| User gesture / secure audio context | Browsers require an explicit interaction to enable playback. Remote AudioWorklet use needs a secure HTTPS origin; loopback development can use HTTP. Playback failure does not stop gameplay. |
Graphics and presentation
| Term | Meaning in this project |
|---|---|
| Pixel | One position in a raster image's grid. Source pixel units are distinct from a browser's scaled display size or physical world units. |
| Sprite | One hardware output piece: a 16×16 image, palette, flips and native position. Several sprites can draw one object; a sprite is not an actor. |
| Tile or character | A cell in persistent background or foreground video state. Background tiles are 16×16; foreground characters are 8×8. |
| Piece / sprite group / sprite pair | A piece is one drawn hardware sprite. A sprite group combines pieces for an object or template. A scenery sprite pair is exactly two pieces. |
| Tilemap / macro tile / expansion | A tilemap arranges tile references in a grid. A macro tile describes a block of smaller tiles. Expansion turns the compact macro representation into tile/collision data. |
| Streaming / collision ring | Streaming loads map portions as progression advances. The collision ring reuses bounded storage for the currently needed terrain; its read cursor determines the active portion. |
| Camera / scroll / progress | The camera selects the visible map position. Scroll moves that view; progress is the source forward coordinate used by placement and section rules. Pending scroll and displayed scroll can differ. |
| Background / foreground / HUD | Background is the scrolling tile layer. Foreground is the character layer above sprites. HUD means heads-up display: score, lives, grenade stock and related play information. |
| Image code / attribute / palette | An image code selects graphic data. Attributes supply drawing properties such as bank, flips and palette. A palette maps image color indices to displayed RGB colors. |
| Pen / transparency / crop / flip | A pen is a decoded pixel's palette index. A transparent pen leaves the layer below visible. Crop selects the displayed rectangle; flip mirrors image pixels along an axis. |
| Signed X page | The sprite's attribute selects the X page: combine its low X byte with either a zero or minus-256 offset. This recovers the complete signed native X. |
| Asset / atlas / PNG / JSON | An asset is loaded graphic or rule data. An atlas packs many images into one sheet. PNG (Portable Network Graphics) stores raster images; JSON (JavaScript Object Notation) stores the extracted structured tables. |
| Archetype / variant / damage stage | An archetype selects the object's replacement-art identity. A variant selects an appearance alternative; damage stage records its visible damage progression. These do not replace source family/kind IDs. |
| Action / animation clip / pose / layout | Action names behavior such as walk or die. A clip identifies its animation contract; a pose selects an appearance within it. A composite layout arranges its graphic pieces; a pose band shares a pose across a timer range. |
| Binding / adapter / payload | A binding maps semantic state to an art representation. An adapter converts between interfaces. A model payload is the object/component, transform and animation data delivered to replacement presentation. |
| Visibility mask / exit-effect quarter | A bit mask naming which of a final-exit component's four source subparts remain visible. ExitEffectQuarter bits are source subparts, not model bones or actor lifetimes. |
| Native / world / portrait / local coordinates | Native coordinates follow the unrotated board raster. World coordinates include camera progress. Portrait coordinates describe the final screen; local coordinates are offsets within an object's component structure. |
| Transform / ROT270 / interpolation | A transform maps positions/orientations between coordinate spaces. ROT270 is a 90-degree counterclockwise turn into portrait orientation. Interpolation computes intermediate values, such as facing between initial and target headings. |
| Arc / trajectory / physical height | A trajectory is a path over time; an arc is its curved shape in source screen motion. That motion alone does not establish a physical height for a 3D model. |
| Renderer / Canvas 2D / guide / model marker | The renderer draws current presentation. Canvas 2D is the browser drawing interface. A guide is a diagnostic shape; a model marker stands in for the future replacement artwork. |
| HTTP / local-file URL | HTTP (Hypertext Transfer Protocol) serves pages/assets through the local web server. A URL is a resource address; a local-file URL opens the filesystem directly, with different module/fetch behavior. |
Research and verification
| Term | Meaning in this project |
|---|---|
| MAME / native verification / capture / trace | MAME (Multiple Arcade Machine Emulator) runs the original arcade ROM on emulated hardware here. Native verification compares against that execution. A capture records state/output; a trace records its sequence or execution boundaries. |
| Fixture / seed / replay / snapshot | A fixture supplies test inputs/expectations; seeding sets starting state. Replay applies recorded inputs or displays captures. A snapshot copies owned state at one point for comparison or restoration. |
| Controlled / ordinary / input-only route / intervention | A controlled probe may intervene by setting or holding internal state. An ordinary route follows normal control flow. Input-only means only declared controls drive progression after its stated starting point. |
| Caller-boundary comparison / fidelity | A caller-boundary comparison checks equivalent incoming state and returned effects at a named routine boundary. Fidelity is agreement with the arcade within an explicitly stated behavioral, timing or visual scope. |
| Determinism / restore | Determinism means identical owned state, rules, policy and inputs produce identical subsequent results. Restore reinstates a snapshot's owners, including residue, queues and unfinished work. |
| Codec / independent expectation | A codec encodes/decodes state at a representation boundary. Independent expectations come from separate source/native evidence rather than the implementation being checked. |
| Provenance / metadata | Provenance records where a value or identity came from. Metadata describes that origin or interpretation; a source address can be metadata without being a live storage index. |
| Obligation / coverage ledger / acceptance | An obligation records required source-path/field/effect review. A coverage ledger tracks modeled and verified scope. Acceptance confirms a stated use case; it does not automatically certify the whole ROM. |
| Strict null checking / null safety | Type checking that requires potentially null or undefined values to be handled explicitly. Its remaining test migration concerns fixture assumptions, not another gameplay rule. |
| Generated or ignored artifacts | Generated files are derived outputs such as builds, extracted assets and captures. Ignored files stay local rather than being tracked in Git; their absence from Git does not make them unavailable at runtime. |
| Source exclusion / unowned ROM span | A source exclusion proves an outcome outside a specified caller's reachable scope. An unowned ROM span lacks an established role; it is not thereby proved unused. |
Z80 interrupt and instruction terminology follows the Zilog Z80 CPU User Manual, Interrupt Response and Z80 Instruction Set chapters.
Names preserve original hexadecimal IDs: soldier_26 means $26 (38 decimal).
ArcadeActorKind,
ArcadeEnemyKind and
ArcadeSceneryKind remain separate enums.
Original arcade hardware
The hardware reference is the BSD-licensed
MAME 0.287 Commando driver:
PCB notes, main_map, sound_map, scanline, machine configuration and the
commando ROM definition. This fixes the reference version used by the native
verification tools. ROM file sizes below also agree with the supplied World set.
Processors and memory
| Resource | Type and amount | Role |
|---|---|---|
| Main and sound CPUs | Two Z80A CPUs, nominally 3 MHz each from a 12 MHz oscillator divided by four | Separate gameplay/video and sound programs. Main-CPU bus arbitration and object DMA can halt execution without changing the nominal clock. |
| Main program ROM | 48 KiB: one 27C256 EPROM, 32 KiB, plus one 27C128, 16 KiB | $0000–$BFFF, including executable code and gameplay tables/streams. |
| Sound program ROM | One 27C128, 16 KiB | $0000–$3FFF in the sound CPU. MAME's 64 KiB audio region allocation does not imply 64 KiB of installed sound ROM. |
| Graphics ROM | 16 KiB characters; 96 KiB background tiles; 96 KiB sprites | One, six and six 16 KiB 27C128 EPROMs respectively; not mapped as ordinary main-CPU program bytes. |
| Main work SRAM | HM6264, 8 KiB | $E000–$FFFF, including the CPU-visible 384-byte sprite table. |
| Foreground and background SRAM | M58725/MB8128, 2 KiB foreground; MB8416, 2 KiB background | Each holds 1,024 code bytes and 1,024 attribute bytes. |
| Sound SRAM | M58725/MB8128, 2 KiB | Sound-CPU $4000–$47FF. |
| Video-board SRAM | M5L2114 and P2148, each 1K×4 bits | The driver's PCB drawing shows six 2114 and four 2148 devices: 5 KiB nominal fitted capacity across video circuitry. This is separate from the CPU-visible sprite subrange, not an additional contiguous gameplay pool. |
| Bipolar PROMs | Six TBP24S10 devices; six 256-byte dumps | Three color PROMs, palette selector, interrupt timing and video timing. Dump bytes represent PROM entries; their file size is distinct from a chip's data width. |
| Sound output | Two YM2203 OPN chips at 1.5 MHz, two YM3014 DACs, analog mixing/amplification | FM/PSG audio routed to a mono speaker. |
The graphics data uses 2 bits per pixel for characters, 3 for background tiles and 4 for sprites. Three color PROMs produce a 256-entry RGB palette with four bits per channel. Main opcode fetches use decrypted bytes; operand and table reads use raw ROM data. MAME's decrypted-opcode view is not another installed ROM. The annotated disassembly's printed instruction bytes can therefore mislead a data extraction; compare raw operands separately.
| Main-CPU address | Function |
|---|---|
$0000–$BFFF |
Program ROM and data |
$C000–$C004 reads |
System, P1, P2, DSW1 and DSW2 input ports |
$C800 write |
Eight-bit sound latch; sound CPU reads it at $6000 |
$C804 write |
Coin-counter bits 0/1, sound-CPU reset bit 4, screen flip bit 7 |
$C806 write |
Copy CPU sprite output into the buffered video view |
$C808–$C80B writes |
Two little-endian 16-bit background scroll latches |
$D000–$D3FF, $D400–$D7FF |
Foreground codes and attributes, 1 KiB each |
$D800–$DBFF, $DC00–$DFFF |
Background codes and attributes, 1 KiB each |
$E000–$FFFF |
8 KiB work RAM; $FE00–$FF7F is its 96×4-byte sprite subrange |
The sound CPU writes the YM2203 address/data pairs at $8000/$8001 and
$8002/$8003. The two CPUs have separate address spaces; matching numeric
addresses do not identify shared storage.
Interrupts and devices
The interrupt PROM drives main-CPU restart vectors: RST $08 at scanline 109
and RST $10 at scanline 240, the vblank boundary. The former reaches a RET
at $0008; the latter executes DI and jumps to the frame handler at $02B7.
The same PROM generates four sound-CPU IRQs per raster frame. The sound latch
is a command transfer, not an additional sound-latch NMI in this driver.
MAME configures a 6 MHz pixel clock, 384 clocks per line and 262 lines per
frame: 59.63740458 Hz, with native visible X 0–255 and Y 16–239. The PCB
notes separately report measured sync values of 15.6196 kHz and 59.6170 Hz.
Those observations and the configured clock calculation are different evidence.
The visible 256×224 raster becomes 224×256 after ROT270.
Inputs are digital, active-low contacts: eight-way joystick, fire and grenade
for each control bank; two start and two coin inputs. Cocktail/upright cabinet
configuration affects bank selection and flipping. Two eight-position DIP banks
select starting area, lives, coinage, bonus lives, difficulty, demo sound, flip
and cabinet mode for the World set. Video is a raster display; audio is mono;
coin counters are output devices. Sprite publication at $C806 explains why
CPU work state and the last displayed screen can represent different updates.
Browser runtime and execution order
play-app.ts calls mountPlay() in
play-runtime.ts. lab-app.ts calls
mountLab() in app.ts. Both construct CommandoGame and
load the same ROM-derived rules. The production import graph excludes the lab
catalog, scenario registry and capture setup.
flowchart TD
Input[Keyboard and UI buttons] --> Ports[Active-low input ports]
Ports --> Update[Synchronous update]
Update --> IRQ[IRQ outputs and input histories]
IRQ --> Dispatch[Scene or world dispatcher]
IRQ --> Bus[Published C800 and C804 writes]
Bus --> Audio[Audio observer and serialized worker]
Audio --> Synth[YM2203 synthesis or C64 music]
Synth --> Worklet[PCM queue and AudioWorklet]
Worklet --> Speaker[Browser audio output]
Dispatch --> State[Typed gameplay owners and ordered effects]
State --> Queue[Main command ring]
Queue --> Consumer[Drain complete commands in order]
Consumer --> State
State --> Sprites[96 typed arcade sprite records]
Sprites -->|20 final-exit records read back| Dispatch
State --> Objects[Detached semantic object projection]
Sprites --> Renderer[ArcadeRenderer]
Objects --> Adapter[Guide or model adapter]
Adapter --> Renderer
Renderer --> Canvas[Portrait Canvas display]
Lab[Lab setup callback] --> State
stepWithPorts() supplies fixed ports. stepWithInputProvider() calls its provider
only immediately before an actual input sample; blocked presentation updates do
not consume autopilot decisions, button sequences or randomness. step() can
also supply already-qualified gameplay controls. All three enter stepUpdate()
in play-runtime.ts.
Synchronous scheduling
The browser uses requestAnimationFrame for display and an accumulator with
1000 / 60 milliseconds per requested game step. Elapsed time per callback is
capped at 100 ms; several steps can precede one render. Pause stops stepping;
Step requests one update. This host policy does not establish board timing.
Each update publishes the existing IRQ outputs, samples inputs, and advances the
selected scene/world controller. It then calls drainMainCommands() in
video-commands.ts. Commands finish in
FIFO order, including requests appended by a command. No simulated interrupt
splits a command. Existing section/background and player-restart continuations
retain their presentation pauses and block input sampling and command draining
until they finish. Actor timers, animation counters and source effect order are
unchanged.
The experimental source-timing policy, raster scheduler, instruction-cost graphs
and branch/call accounting were removed in backlog 361. There is no policy
switch to preserve on reset. Queue operations, HUD drawing/awards, sound enqueue
and queued shot contacts now execute ordinary functions and loops. They preserve
byte arithmetic, partial writes, retained pointers and effect order without an
instruction PC or suspended locals. HudScoreDisplay selects the active player
or top score; foreground addresses select output cells, not a simulated CPU.
Background rebuilding uses ordinary semantic operations (368). Difficulty
loading, macro expansion, collision generation and tile drawing run to completion
within each operation; no instruction PC or address-arithmetic cursor is stored.
prepareSceneBackground publishes the first block's settings, expanded tiles and
collision data before the existing presentation pause. completeSceneBackground
draws that block, finishes its counters, performs the remaining four blocks and
restores scenery. Prepared buffers and pointers have one owner: BackgroundState.
The live host saves only PlayerRestartPhase plus a pause count, or
PendingSectionBackground with a destination and pause count. Two intervening
presentations continue to block input sampling and command draining. Completion,
scenery births, sound requests and the next sampled update retain their order.
The later respawn timer remains in SceneState; no second timer was introduced.
New recordings serialize this semantic state directly. Runtime identifier
commando-state-2026-10-24-background-368 rejects incompatible recordings; no
legacy cursor adapter or schema migration is provided. Seeking into a transition
restores its prepared buffers and remaining pause, then uses the same live code.
Historical native mid-instruction captures document the original hardware;
they do not require production suspension APIs or claim matching scanline timing.
stepLogicalUpdate() is the read-only native verification boundary before main
commands drain. It uses the same gameplay and collapses the existing long
background presentation pauses to observe a complete logical update.
This preserves the previously default synchronous behavior, not every physical MAME interleaving. Research 360 measured original IRQs interrupting unfinished main work. That historical evidence and the limits in 152/204 remain; removing the experimental model does not establish physical timing equality. The separate audio driver and synthesizer clocks remain in use.
Active world pass
The source order for $07FC, reflected by the shared runtime, is:
| Order | Source boundary | Work |
|---|---|---|
| 1 | IRQ $0396, $8727, $02FA–$0385, $9E37 |
Publish display/sound/control outputs, sample input histories and process coins before game-state dispatch. |
| 2 | $9FA9, $9F09, $A318, $A399 |
Advance shared clocks and pending camera work; admit and update scenery through the source return chain. The gate latch bypasses that scenery continuation. |
| 3 | $8939 |
Player movement, terrain/scenery contact, throw-delay handling and player output. |
| 4 | $272F, $2747, $2A3E |
Admit a scripted placement, then scan $E500 slots in ascending physical order. These actors can allocate core actors or enemy shots. |
| 5 | $97EF, $94FA, $0F9E |
Select and attempt core births, then scan the eight physical core slots. |
| 6 | $931D, $8E93, $9100 |
Attempt player firing; advance fourteen projectile records; process grenade flight/landing and shared blast effects at their source points. |
| 7 | $AE95 |
Even ticks enqueue player-shot/core contact; odd ticks perform player body/enemy-shot contact. |
| 8 | $0817 and continuations |
Resolve inactive-player restart/game over, section readiness and gate progression after actor/contact effects. |
| 9 | Main consumer $8000/$8007 |
Consume pending commands according to the selected scheduling policy. |
Birth timing follows the consumer's position. A scripted child in a higher
unvisited $E500 slot can update in the same scan; one in a slot already passed
waits. Core births before $0F9E enter that pass. A $0D explosive emitted by a
core actor waits for the next scripted pass, because $E500 has already run.
Projectile birth warmup and later movement likewise follow their producer and
shared updater contracts, not a universal next-frame rule.
Contact order is observable. Queued core contact can read state later than its request was produced; a target hit by an earlier shot is unavailable to a later one in the same transaction. Grenade landing after the core pass marks a core record hit-pending; its death transition starts on the following core pass. Source-ordered sound and score requests must remain attached to those transitions. See ACTIVE_PLAYER.md, NATIVE_SCENERY.md and NATIVE_QUEUED_CONTACT.md for bounded comparisons.
Session lifecycle
Main state $E000 and gameplay/scene phase $E001 are separate selectors.
main-scene.ts coordinates boot/service, attract,
credit/start selection and game startup. Start initializes banks, clears pools,
restores the map and runs the transport/deployment cinematic. The ready handoff
preserves the preceding output until the next active update.
Active play scrolls, admits encounters and enters gate combat. The gate stops
camera progression while leaving joystick control active. Only after placements
and core actors drain does forced exit lead into section modes $05/$06/$07,
background restoration and resumed play. Later section and loop settings use
the same source controllers.
Death continuation saves the current player's bank, chooses restart or turn
handoff, and restores the checkpoint through the shared background/start paths.
Final-life processing selects game-over, score ranking, name entry when eligible,
and return to attract. player-bank.ts,
player-continuation.ts and
post-game.ts own these contracts. Ordinary complete
two-player session acceptance and a longer next-loop combat/restart composition
are complete under backlog 207/208. The continuous shared full-game route in
224 additionally verifies all eight sections, the ending and resumed next-loop
play within its declared caller/rendering boundaries.
State ownership and object capacity
There are five gameplay allocation domains under this counting convention: scripted actors, core actors, player projectiles, enemy projectiles and scenery. The two projectile domains share one fourteen-record TypeScript owner. Player, grenade and shared blast are singleton controllers; sprite output and command rings are separate bounded resources.
Typed state owners
ArcadeCommandContext, available as
game.commands, aggregates state and command/presentation context. Its name
does not imply CPU emulation. The allocation shells and most actor subtype
records are on CommandoGame, rather than all being nested in this aggregate.
| State | Authoritative storage and code |
|---|---|
| Ports, histories, coins and sound ring | commands.irq / FrameIrqState; game.irq references this owner |
| Main/scene mode, placement and wave cursors, RNG registers | commands.scene / SceneState; main CPU mode is separately in IRQ state |
| Player, grenade, lives, stock and blast | commands.playerRuntime / PlayerRuntimeState |
| Scores, thresholds, high scores and saved player banks | commands.hud / HudState |
| Loaded difficulty, map streaming and live collision | commands.background / BackgroundState; expansion corresponds to $F000–$F7FF, collision to $F800–$FBFF |
| Foreground, scenery, linked actors, projectiles and sprites | Dedicated commands fields, with the pool/output owners below |
| Cinematic, name entry and semantic scene controllers | commands.cinematic, .nameEntry, .semanticScene; source-specific records |
| Main command ring | commands.queue; drainMainCommands() completes each typed command body before consuming the next pair |
Getters such as life, camera, scoreBcd and enemyShotCooldown expose these
owners; their names do not imply another stored copy. Shared checkpoint/view
references survive state capture. STATE_OWNERSHIP.md
records the migration and the remaining distinction between source metadata,
gameplay fields and dedicated output buffers.
Two presentation paths sit outside this gameplay allocation inventory.
game.presentationStructures derives terrain layouts and actor references
without another live pool. Browser hosts own GameAudioController; its worker's
2 KiB audio state corresponds to the separate sound CPU, not main RAM.
Capacity and source storage
| Domain | Source storage | Physical capacity | Current owner |
|---|---|---|---|
| Scripted actors | $E500–$E5FF; eight $20-byte records |
8 shared slots across all 48 dispatch kinds | FirstSectionGame.scriptedPool, subtype collections, scriptedPoolFractions residue; linked kinds use commands.linkedActors.records |
| Core enemies | $E600–$E6FF; eight $20-byte records |
8 shared slots across core subtypes $00–$0A |
corePool allocation/residue plus subtype records, dispatched in physical slot order |
| Player projectiles | $E200–$E2BF; six $20-byte records |
6 | commands.projectiles.records[0..5] |
| Enemy projectiles | $E2C0–$E3BF; eight $20-byte records |
8; particular firing gates can permit fewer | commands.projectiles.records[6..13] |
| Scenery | $E800–$E91F; eighteen $10-byte storage positions |
18 stored; $A399 updates the first 9, subject to an 18-sprite-pair output budget |
commands.scenery.slots and placement cursor |
| Player / grenade | $E100 / $E140 source control-record bases |
1 player record and 1 grenade record | commands.playerRuntime.player / .grenade |
| Shared blast | $E080 timer and associated origin/contact fields |
1 current shared effect | commands.playerRuntime.blast |
| Sprite output | $FE00–$FF7F; $04 bytes per source record |
96 output pieces | commands.spriteOutput, an ArcadeSpriteTable of 96 distinct objects |
Pool definitions and record contracts are in
scripted-actor-pool.ts,
core-enemy-pool.ts,
projectile-state.ts,
scenery-slots.ts and
player-state.ts.
CoreEnemyPool itself stores ownership, subtype and retained residue, not every
subtype's full live record. Those records reside in collections such as
firstGateSoldiers, coreSoldiers, randomCoreRecords.soldiers and
allocatedCoreActors. The scripted family likewise uses subtype records.
Linked actors' eight storage records are indexed by the same $E500 slots;
they are not eight additional allocatable actors. A projection such as
playerShots, enemyShots or scriptedSides does not add capacity.
Allocation and exhaustion
| Domain or caller | Scan and admission | When unavailable |
|---|---|---|
Scripted placement $2779 |
First free $E500 slot, ascending 0–7; at most one placement accepted per admission call |
Keeps the unaccepted placement for retry; full-pool return state is itself part of the caller contract. |
Scripted $04 and bridge $06 children |
Only slots 7, 6, 5, descending | No extra child is created; these contend with every other occupant of those slots. |
Core-emitted $0D |
Only $E500 slots 7, 6, 5, 4, 3, descending |
No separate explosive pool is allocated. |
| Core births | Source-specific capacity/cooldown/terrain gates, then a shared free-slot search, generally ascending | A free physical slot alone does not guarantee admission. Rejected initializers can still leave defined partial writes. |
Player fire $936F |
First free player-projectile slot, ascending | Spawn attempt fails; $931D still consumes the scheduled burst request and reloads its interval. |
| Enemy fire | Shared eight-slot domain, constrained by the particular producer and loaded shot settings | No overflow allocation; producer-specific cooldown/write effects follow its own contract. |
Scenery $A35C |
First zero-state record, ascending, before that pass removes old scenery | Source ASM keeps scanning without an explicit end guard. The typed eighteen-record owner throws if exhausted; this is a capacity assertion, not a source retry rule. |
Scenery limits depend on the consumer: ordinary player/shot scenery contact scans the first eight records, grenade contact scans twelve, and the display updater scans nine. Initial clearing covers eighteen, clearing state/attribute without erasing every retained field. These counts must not be substituted for one another. Palms need two sprite pairs, rocks one; the display budget and stored-record count are different limits.
Difficulty settings are loaded state in
BackgroundState, exposed through
loaded-difficulty.ts. Core capacity
E0F4 and enemy-shot capacity E0F0 can be lower than physical capacity.
The $0700 core row, for example, supplies a threshold of six rather than eight;
the birth gate uses its actual comparison against the source count. Settings
remain the loaded row until the real background command replaces them; a camera
boundary alone does not authorize an eager reload.
Record layouts and retained fields
The common 32-byte shape does not give every family identical field meanings. For core-script records, the capture layout is:
| Offset | Core-script meaning |
|---|---|
+$00, +$01, +$02 |
State, heading, pose heading |
+$03..+$06 |
Accepted native Y and X, two 8.8 words |
+$07..+$0A |
Retained candidate Y and X, distinct from accepted coordinates |
+$0B..+$0E |
Y and X velocity words |
+$0F..+$12 |
Speed index, walk counter, turn flag, draw flags |
+$13..+$15 |
Core subtype, motion phase, timer |
+$16..+$17 |
Motion-script pointer |
+$18, +$1E, +$1F |
Terrain grace, composite layout, shot phase |
These words store the high byte first, unlike a normal Z80 little-endian word
load. ROM pointer tables and placement progress words can be little-endian;
decode each source structure independently. The independent
core-script snapshot codec records
this boundary; gameplay uses named fields in
native-core-script.ts.
Projectile +$12 is lifetime and +$13 is flags, rather than the core meanings.
Scripted actors use +$1A for sprite count and +$1B/+$1C for their source
sprite pointer; other fields depend on kind. Scenery uses its own 16-byte layout:
state +$00, Y +$03, X word +$04/+$05, kind +$06, image +$07,
attribute +$08, and contact parameters +$09/+$0A.
Release is not object reconstruction. A player-shot initializer can replace
whole coordinate bytes while preserving low fractions. Releasing a core slot
preserves its named residue for the next claimant. hideArcadeSprite() writes
only nativeY = 0; image, palette, flips and X survive. $00 inactive,
$FF active and $3F hit-pending are common conventions, but each family's
state machine must interpret its own values.
flowchart LR
Placement[Placement or emitted birth request] --> Admission[Caller admission gates]
Admission --> Scan[Scan permitted physical slots]
Scan --> Init[Claim slot and apply partial initializer]
Init --> Active[Dispatch active subtype]
Active --> Active
Active --> Hit[Hit or conversion transition]
Hit --> Active
Hit --> Death[Death or effect phases]
Active --> Release[Release source fields]
Death --> Release
Release --> Retained[Free slot with retained residue]
Retained --> Init
This is a lifecycle vocabulary, not one universal state machine: some kinds release immediately, convert in place, or never draw. Failed admission follows the caller-specific behavior in the table above.
Sprite allocation and aliases
| Source span or start | Usual writer |
|---|---|
$FE04–$FE13 |
Four shared-blast pieces |
$FE14 onward |
Core-emitted $0D pieces, selected by descending scripted slot |
$FE30–$FEBF |
Normal scenery output, up to 36 pieces / 18 pairs |
$FED8–$FF37 |
Eight core slots, three pieces per slot |
$FF38–$FF43 |
Three player pieces |
$FF44–$FF47 |
One grenade piece |
$FF48–$FF7F |
Fourteen projectile pieces, one per record |
$FEAC onward |
Alternate scenery output for later scene phases |
$FED8–$FF27 during final exit |
Twenty records reused as canonical $87F1/$883C effect state, read back for position and column removal |
| Placement-selected pointer | Scripted actor templates and composites |
This is an ownership map by source context, not disjoint global reservations.
Scripted placements, cinematics, alternate scenery and effects can overlap the
same output. For example, alternate scenery from $FEAC overlaps the ordinary
core/player spans; the $FF40 name cursor aliases a player piece. Preserve writer
order and partial output rather than assigning permanent sprite blocks to every
semantic entity. ARCADE_SPRITES.md describes the typed output.
Consequently there is no useful sum of all rows called “maximum live objects.” A compound can consume several actor slots, one actor can emit several pieces, and a released actor can leave visible output. 96 is the output-record limit, not 96 logical actors or a verified per-scanline board throughput limit. Bank, crop, transparency, aliases and hidden Y positions further reduce what is visible.
Placement streams and motion bytecode
The game uses small ROM data languages with fixed consumers, rather than one general-purpose scripting language. Actor kinds dispatch native routines; motion scripts control specific core subtypes; placement streams schedule births; main commands defer work. A TypeScript lab callback only establishes starting state and optional hardware inputs.
Placement and dispatch formats
| Source data | Layout and consumer |
|---|---|
Scripted actors $71AE–$772F |
Six bytes: progress low, progress high, $E500 kind, native Y, sprite pointer low, sprite pointer high. $2747 admits when unsigned progress minus camera is 0–255; stale entries are skipped, future/end entries stop the scan. Progress high $FF terminates a stream. |
Scenery $4000–$412F |
Four bytes: native Y, image code, packed progress-low/kind/mirror, progress high. Progress is (byte3 << 8) + (byte2 & $F0); low three packed bits select the scenery behavior and bit 3 changes the sprite style. High $FF terminates. |
Core waves $AFB1–$B030 |
Four-byte records: placement progress word and template-table pointer word, both little-endian. A selected table has eight little-endian template pointers. |
| Core motion template | Two header bytes followed by motion commands: native Y, then initial X offset/terrain-check flags. The birth caller adds the placement-to-camera offset; the second byte is not universally an absolute X coordinate. |
$E500 dispatch tables |
$27C3 initializer pointers; $2A0E per-kind sprite counts; $2A73 update pointers. All 48 kinds share the same eight slots. |
The extracted catalog indexes 235 scripted actor placements and 76 scenery placements; those are whole-ROM catalog counts, not concurrency limits. Direct placements do not enumerate every runtime kind: emitters and in-place conversions create additional kinds. The extractor and lab catalog preserve numeric kind, source placement and physical output pointer.
Motion reader at $159D
rom-script-interpreter.ts implements
one command read; $142E's parent in
native-core-script.ts controls timing,
movement, contact, drawing and effects. A byte whose low five bits are not $1F
is a heading followed by a duration. Otherwise its upper three bits select the
eight-entry $15DE command dispatch.
In the table, P is the address of the command before the read. Fields not
assigned by that command retain their previous values.
| Stream bytes | Next pointer | Reader result | Parent or caller effect |
|---|---|---|---|
heading, duration |
P+2 |
Heading and pose heading replaced; vector recalculated at current speed; phase $00; timer = duration |
Candidate movement/shared fire follow the normal phase path. |
$1F |
P+1 |
Timer = 1; gate request set | Runtime writes scene gateRequest (E094); the next scripted pass can consume it. |
$3F, speed |
P+2 |
Speed index replaced; current vector, phase and timer retained | At the usual zero-timer reader entry, the parent's decrement wraps timer to $FF; the vector is not immediately recalculated. |
$5F |
P+1 |
Request subtype $01; timer = 0 |
Source stack exit skips the parent's decrement/movement; caller still processes retained candidates and can draw walking output. |
$7F, duration |
P+2 |
Aim from accepted whole coordinates to player; replace heading/pose/vector; phase $03; timer = duration |
Aimed movement uses the shared phase path. |
$9F |
P+1 |
Phase $04; timer $18 |
Hold-pose bands; decremented timer $08 attempts a $0D birth. |
$BF |
P+1 |
Phase $05; timer $40 |
Eight offset-pose bands; draw precedes candidate commit. |
$DF, duration |
P+2 |
Phase $06; timer = duration |
Position-hold path applies source scroll and shared firing. |
$FF |
P |
Recalculate current heading's vector; phase $00; timer $FF |
Repeat from the same byte when timing next reaches the reader; $FF is not a stream terminator. |
Except for $5F, the parent decrements the resulting timer in that update.
Motion phases $00/$01/$02/$03/$07 share movement/fire handling; $04/$05/$06
have the special behavior above. Pending turns can bypass script timing, and
holds can keep earlier movement candidates. These details prevent interpreting
the bytecode as a generic list of independent timed animations. The full contract
and bounded native evidence are in ROM_SCRIPT_INTERPRETER.md.
Raw ROM example
The pointer word at $B031 is 41 B0, selecting template $B041. Its prefix is:
Address Bytes Meaning
B041 F0 Initial native Y = $F0
B042 00 Initial X offset/flags; terrain-check bit clear
B043 80 20 Heading $80 for duration $20; pointer becomes $B045
B045 BF Offset-pose phase $05, timer $40; pointer becomes $B046
B046 5F Convert to core subtype $01; pointer becomes $B047
The birth caller supplies the final native X; the reader starts at $B043.
With an ordinary zero-timer entry and no turn interruption, the first command
sets $20 before the parent decrements it to $1F. At the later $BF read,
$40 similarly becomes $3F. $5F preserves its zero timer through the stack
exit. These are raw operand bytes from the World program ROM, not the listing's
printed decrypted-byte column or an invented demonstration script.
Main and sound command rings
main-command-queue.ts translates the
RST $38 producer and $8007 consumer. Source $ED00–$ED3F is a 64-byte
ring of 32 two-byte entries, command ID then parameter. $ED80/$ED82 are
write/read pointers; $ED85/$ED84 retain the current ID/parameter. Consumed
bytes become $FF. There is no full-ring guard: overrun overwrites unread
entries. TypeScript stores offsets into this dedicated ring, not CPU pointers
into a global allocation.
The fifteen IDs $00–$0E cover print/erase text, scores, credits, score awards,
background columns, high scores, title art, foreground clear, lives, grenade
stock, player-shot/core contact, section badges and bonus policy. In particular,
$06 changes background/collision/settings state and $0C performs collision;
calling this only a video queue would hide gameplay effects. The single dispatch table and FIFO drain live in
video-commands.ts; the runtime supplies the
live background/contact owners. A command finishes before the next pair is read,
including commands it appends. The queue has no instruction cursor.
The sound ring is separate: 32 one-byte entries at $ED40–$ED5F, with
write/read pointers $ED86/$ED88. $8717 queues commands; $8727 takes one for
the IRQ output path and $C800 sound latch. Gameplay sound IDs, queue effects
and ordered hardware writes are modeled. Browser audio now observes those
published outputs without consuming the gameplay queue or altering its rules.
Browser audio playback
GameAudioController sends published
frameOutputWrites to a serialized worker. The
arcade sound driver directly translates the
separate 16 KiB sound program's commands, priority records and streams into
ordered YM2203 writes; it owns bounded 2 KiB audio state corresponding to
sound-CPU $4000–$47FF and does not interpret Z80 instructions. Each 60 Hz host
advance renders 1/60 second of PCM; within that block the sound IRQs follow the
board clock and timing PROM, rather than one IRQ per gameplay update. The
standalone explorer fills its queue from AudioWorklet demand. These audio clocks
use board-clock.ts independently of gameplay;
removing main-CPU cycle accounting does not change their scheduling.
Audio engine and YM2203 synthesis produce separate FM music and SSG effects stems through pinned ymfm WASM for reference/build use. Normal gameplay uses the music stem through a bounded AudioWorklet queue and independent canonical effect samples through native Web Audio nodes. Audio needs a user gesture and, for remote access, a secure HTTPS context; pause/reset follow the browser host. Original C64 music can replace FM through reSIDfp, independently of the arcade/C64 effect-pack selection. C64 tune execution belongs to that existing SID library, independently of the direct Capcom translation.
The observer also sees $C804 sound-reset changes. Play/lab pause suspends
playback; reset discards queued audio, and stale worker replies are separated
by reset/source generations. A long host backlog is bounded and resynchronized.
The free-input playtest can bootstrap theme $21 when audio starts or resets;
boot/attract resets clear that convenience cue. This host cue and sound auditions
do not enqueue gameplay commands. Gameplay snapshots do not include the worker,
chip synthesizers, SID execution or queued PCM, so restoring gameplay does not
promise sample-identical sound continuation.
The standalone sound explorer uses canonical sample buffers for
effects. npm run audio:samples independently encodes 37 MP3 streams, then packs
them with exact byte ranges into assets/audio/effects/effects.bin; the browser
fetches that one file and decodes each isolated range. npm run build verifies
the pack, while music keeps the existing synthesizers. SampleEffectPlayer
creates independent native Web Audio source nodes for each instance, sharing
decoded buffers. The browser mixes them; there
is no custom sample mixer. It supports delayed simultaneous batches, per-instance
stop and global pause/stop, including multiple copies of the same effect. Four
arcade samples have prepared repeating regions. Gameplay and recording replay use
the same canonical library through the positioned graph described below and in
SOUND_PLAN.md.
The explorer covers all 47 reviewed arcade
commands and 19 C64 song/effect slots. Six SSG termination commands, including
gate-entry $16, are controls that produce no new sound. Source data, native
captures and generated ROM assets stay local. See
audio research and limits, the separate
audioCpu ledger sections and backlog 22: service commands $2F..$3F, individual
chip-write instruction timing, independent PCM/analog comparison and wider
browser acceptance remain partial.
Input and gameplay systems
Browser controls to source input
| Browser input | Pressed mask or operation |
|---|---|
| Right / D, Left / A, Down / S, Up / W | $01, $02, $04, $08 direction bits |
| Space / J, Fire button | $10 fire during play; at the title a fresh press requests a free one-player start |
| K, Grenade button | $20 grenade |
| C | Optional manual system coin 1 $80 for diagnostics |
| Enter / 1, Start button | Requests free credits, then sends system start 1 $01 |
| 2, Start 2 button | Requests two free credits, then sends system start 2 $02 |
mountPlay() maintains a held-key set; release removes a key and browser blur
clears the set. Form controls are excluded from gameplay key handling. Buttons
set requests consumed by the next step. playerInputPorts() complements the
pressed masks into active-low ports, supplies P1, leaves raw P2 released, and
passes system controls/DIPs. System-key mapping is shared through
arcade-keyboard.ts.
The playable hosts use free-start.ts at the
sampling boundary, issuing ordinary coin and start inputs when needed. A title
Fire held across the handoff does not become a gameplay shot.
frame-irq.ts samples ports into active-high
source values and shifts six one-byte histories per player bank. A fire or
grenade press qualifies when (history & $07) == $01; holding a button is not
a new press each tick. Active-player, cabinet and flip state select the movement
port and history bank. In upright shared-control play the second bank's history
can follow P1, despite the raw P2 port being released. Low-level
stepWithPorts() can supply both hardware control banks directly.
Movement uses the low direction nibble; fire/grenade bits do not suppress it. The source lookup, heading interpolation and signed 8.8 vectors remain intact, including opposed direction masks. UI code must not normalize these into a different eight-direction rule. Player acceptance tests terrain/scenery and native screen bounds before committing coordinates. The camera follows native forward progress and consumes queued scroll at its source phase.
Combat and progression
- Spawning: placement cursors, random births and core-wave templates feed
shared allocators. The source random generator uses ten retained registers,
the global tick and source player-sprite image input; it is not
Math.random(). - Player fire: a qualified empty-queue press schedules two requests. The first allocation attempt occurs in that update; the next is four updates later. Muzzle offsets, heading vectors, warmup, flight, expiry and impact use extracted rules and the shared six records.
- Enemy fire: source producers share projectile capacity and loaded cooldown/distance/speed settings. Producer identity is preserved for semantic emission relationships without creating another projectile owner.
- Grenade: stock is packed BCD. A qualified accepted use consumes stock and starts the throw delay. Launch initializes the singleton grenade with partial writes; the later grenade pass advances flight, landing contacts and blast. On launch, the source changes the selected control record to the grenade, which affects that update's movement/draw order.
- Score and lives: producers enqueue source score events; the main consumer applies the BCD award and bonus-life policy once. A stored BCD score unit is ten displayed points. HUD values and saved player banks have named owners.
- Progression: camera, gate placement counts, live core occupancy, exit controller and section-ready state govern transitions. A visual absence of sprites is not the gate's occupancy test.
Rendering and semantic objects
Assets and persistent tile state
extract_arcade.py and
extract_video_commands.py read local ROMs
into ignored PNG atlases and JSON tables under assets/arcade/. Runtime asset
loading consumes those results, rather than parsing the annotated disassembly.
ROMs, extracted assets, captures and build output remain outside Git.
BackgroundState owns a streaming work record corresponding to $EF00,
2,048 expansion bytes, a 1,024-byte collision ring, and 1,024 background code
plus 1,024 attribute cells. The background command expands source macro tiles,
updates the live terrain ring and writes video columns. Collision categories
select source masks from $6464; occupancy is sampled in 2-pixel cells. Live
terrain queries use the current collision-reader cursor/scroll phase, not a
substitute whole-level preview map.
Foreground code/color arrays likewise have 1,024 cells each. HUD/text commands change persistent cells and retain those they do not write. Background command execution can also reload difficulty and placement-related state, so moving streaming work to rendering would change gameplay. See NATIVE_BACKGROUND_VIDEO.md.
Arcade output
ArcadeRenderer uses Canvas 2D and draws:
- A 32×32, column-indexed background tilemap of 16×16 tiles, with scroll.
- Typed sprites in slot order 95 down to 0; lower slots draw later.
- A 32×32, row-indexed foreground character map of 8×8 cells.
- The cropped native image rotated into the portrait canvas.
Tile code is video + ((attribute & $C0) << 2); the low nibble selects palette
and bits 4/5 flip the tile. Foreground pen 3 is transparent. Source sprite bytes
are image-low, attribute, Y, X-low: attribute bits 6/7 select image bank, 4/5
palette, 2/3 flips and bit 0 the signed X page. Bit 1 is retained but does not
draw. Sprite pen 15 is transparent and bank 3 is skipped. There are four sprite
palettes, sixteen background palettes and sixteen character palettes.
The live ArcadeSprite has named fields
for full image code, palette, flips, complete signed X, unsigned Y and retained
attribute bit 1. Positions are whole pixels, not gameplay 8.8 coordinates.
Packing the four-byte source layout belongs to
mame-sprite-snapshot.ts and test
codecs. The production renderer reads records directly.
The optional Arcade — complete pieces view uses a separate drawing list. It starts with detached copies of the canonical output and supplements overwritten pieces from current owners using the same pure pose painters. Entries retain their original slot priority; at a shared slot, the canonical final writer stays in front. This list has no 96-entry ceiling and is never written back to gameplay or recordings. Retained complete artwork, hidden contact frames and unsupported phases keep canonical output. The first implementation covers the twelve families affected in audit393; it is an intentional visual enhancement, not new arcade-fidelity evidence or a promise to recover every possible historical partial write.
playlab.html and game.html use the enhanced arcade view by default. The lab and
recording inspector offer it alongside original slots; original replay and video
export remain the defaults. Drawing the enhanced view neither advances gameplay
nor consumes RNG, and a restored recording checkpoint needs no drawing history.
The independent toy/3D whole-object presentation described below is unchanged.
Coordinate conventions are explicit:
Entity.position.x = nativeX Entity.position.y = nativeY
worldForward = cameraPixels + nativeX
worldLateral = nativeY
portraitX = nativeY - 16
portraitY = 255 - nativeX
Native Y is lateral; native X is forward on the portrait playfield. Apply these pixel mappings separately from sprite-art offsets. Source byte wrapping remains part of gameplay; the projection does not infer an unbounded physical trajectory.
Whole objects and replacement presentation
FirstSectionGame.presentationObjects calls
projectWorldObjects(), returning detached
WorldObjectPresentation values. Each keeps
its lifetime ID, archetype, source family/kind/slot, components, relationships,
transforms, animation clip/phase/tick/timer and relevant appearance fields.
Reused core/projectile slots have birth generations; a new occupant is not the
old model merely because its slot number matches.
Arcade sprite output and semantic objects are parallel products of gameplay.
Ordinary actor projections read their typed behavior owners rather than
discovering entities from the 96 sprite records. The final-exit controller is
a source-established exception described below. A five-piece mobile gunner $1F
has gunner and
vehicle components; its emitted enemy shot is a separate projectile. A linked
$01/$02 assembly has source-backed center/side components across shared actor
slots. A gate $14 has two nine-piece panels under one source actor. Emitted
children retain their independent lifetimes and emitter relationships.
compound-entities.ts records established boundaries
and unresolved physical/background parents. semantic-scene.ts
covers scene-controlled components that can mix tiles, body, shadow and effects.
Visual resemblance does not promote background tiles to gameplay actors.
game.presentationStructures, from
world-structures.ts, exposes three
bounded layout contexts: the $05/$22 gun corridor and the Area 1/Area 2 $28
wall openings. They carry ROM tile geometry, terrain-category ownership,
placement references and source-proved suppression/opening links. A placement
trigger is not the live actor anchor; an absent live lifetime has objectId=null.
These references add neither parent ownership nor collision bodies. Grouping
delivery 28/83 is complete; larger physical/artistic parents remain unresolved.
structure-parts.ts gives $22 five
independent cliff-bank patch components, including mirrored/normal poses and
byte-wrapped far-bank offsets. Previous-pass $05 suppression skips native
writes; it does not delete the overlay. $05 separately exposes wall damage/side
and aimed gun state, while $14 retains its two panels.
The final-exit $87F1/$883C controller deliberately reads its twenty sprite
records at $FED8–$FF27 as canonical coordinates and column-removal state.
final-exit-object.ts adapts that
explicit owner into one semantic effect with five components ($8832–$883A).
It adds no second position array. visibilityMask identifies each component's
four source subparts and survives the model adapter; unmatched retained birth
art has pose=null. Replacement renderers receive semantic fields and need
not inspect sprite records. This exception does not turn arbitrary output
aliases into actor parentage.
worldObjectActors() adapts semantic objects for guide/model views. The model binding currently supplies asset and animation payloads displayed as markers; actual replacement art/3D rendering is future work. Source arc tables do not establish physical height: unknown height remains explicit rather than becoming guessed 3D elevation. See SEMANTIC_PRESENTATION.md.
Laboratory and verification boundaries
The active RuntimeLabScenario contract supplies
an optional initializeRuntime(game) callback, label/note and hardware input
masks. resetStage() constructs the production game and invokes that setup.
The legacy flags member is an empty never[]; it does not enable alternative
rules. Initializers can restore measured state or reach a checkpoint through
recorded inputs, but subsequent updates use the same dispatcher as play.
Legacy scenario helper types remaining in the tree do not define the active
page contract.
The catalog/pose inspector and fixed MAME frame replay are inspection paths, not independent gameplay models. Replay decodes captured output and calls the same renderer. New behavior belongs in shared gameplay, with setup-only lab scenarios for useful visual inspection.
captureState() clones the declared owned state; restoreState() requires all
declared fields and restores detached storage. Derived getters and presentation
objects are recalculated. Continuing from a snapshot also requires the same ROM
rules, recording runtime version and subsequent inputs. RNG state, slot residue, queued
commands and in-flight continuations are part of determinism.
The browser audio controller and derived structure/object views are outside
that snapshot; geometry and projections are recomputed, while playback follows
its separate host lifecycle. Recordings retain saved audio and sampled-input
ordinals, and replay/seek uses the same synchronous runtime. The 361 runtime
identifier excludes the deleted timing fields; archives from earlier runtime
versions are rejected by the existing version check rather than migrated.
| Concern | Existing verification boundary |
|---|---|
| Production/lab separation | play-boundary.test.ts and runtime-lab-boundary.test.ts check imports/setup and shared-runtime use. |
| Source field ownership and byte effects | Native transaction tests and independent snapshot helpers compare declared work/video/terrain/sprite regions plus ordered requests. |
| Motion bytecode | rom_script_interpreter.test.ts and native-core-script.test.ts exercise the reader and its parent/caller effects. |
| Input and commands | frame-irq.test.ts and recorder.test.ts cover input history, output order, unsampled restart presentations and recording seek/restore. foreground-cursor.test.ts checks complete native HUD/sound/contact returns and the retained background continuation boundaries. Historical forced instruction interpositions are source evidence, not production suspension APIs. |
| Semantic object continuity | world-presentation.test.ts checks detached projections, components, lineage, reuse and restore. |
| Structures and the final-exit owner | structure-presentation.test.ts checks ROM layouts, independent actor references, component animation/masks and the bounded native-backed $87F1 adapter. |
| Progression | 206–208 cover Area 2, two-player turns and next-loop combat/restart. The shared full-game recording completes all eight sections, the ending and next-loop active play in both engines. |
| Continuous caller/rendering review | Route 224 uses 37,067 hashed inputs and one opening seed: 36,732 complete callers and 17,224 FIFO dispatches match, with 197 fully converged interleaving windows. Of 37,068 entry images, 36,733 equivalent images match exactly; 335 interleaving entry images remain unverified composition, including 30 images with pixel differences. Strict physical replay still fails at update 266. |
| Browser audio | audio-driver.test.ts, audio-playback.test.ts and audio-explorer.test.ts cover bounded driver/native comparisons, output observation, playback and controls. They do not establish analog or instruction-level chip-write timing equality. |
Use the existing obligation/coverage ledgers for exact verified and excluded caller scopes. More tests or graph membership cannot certify omitted source effects. Physical scheduling equality remains unproved (152/204; experimental runtime removed in 361). Remaining audio fidelity (22), actual replacement presentation and unresolved artistic parents (27), test null safety (52), and unowned ROM spans (166) retain separate limits. Completed grouping (28/83) and route acceptance (218–224) do not resolve those other scopes.
For browser verification, serve the repository through python tools/serve.py
and open http://127.0.0.1:8765/commando/ or /commando/playlab.html. Local-file URLs do not reproduce
module, fetch and asset behavior. The README contains build/extraction commands;
non-loopback/public-only listeners intentionally exclude repository documents,
the RAM explorer and captures. Use a project-root loopback listener for those
references. This reference introduces no runtime interface or gameplay changes.
Positioned effects and recording audio (386–388)
Gameplay producers publish read-only sound provenance through sound-observer.ts; GameSoundEvents resolves semantic lifetimes at the completed-update boundary. The game rules and source sound queue are unchanged. SpatialSoundGraph uses native AudioBufferSourceNode/GainNode/PannerNode branches and AudioListener, with64 gameplay pixels per metre and forward mapped to negativeZ. Music remains on its existing worklet/synthesizer branch. Arcade/C64 effects are independently selected samples; unmapped C64 effects explicitly fall back to arcade. Native mixing has no original effect-slot budget. EffectTimeline stores only active voice metadata/offsets for late audio enable and replay reconstruction.
The shared bank loader validates the pack hash and each indexed MP3 range hash, then lets Web Audio resample to the device. The 3D renderer exposes view axes only; sound positions come from authoritative gameplay objects. The audio schema 4 journal saves those lifetimes, positions, view axes and mix settings alongside the existing music pre-roll. A pinned source-PCM hash identifies the canonical bank; portable recording exports embed the exact pack bytes and their hash. Old audio formats are rejected, without compatibility code.
RecordingSpatialAudio reconstructs music and active effect offsets, then renders the same graph with native OfflineAudioContext in bounded two-second stereo blocks. One second of history restores filter tails; leading padding preserves the native 128-sample quantum phase across seeks and recording-part boundaries. Replay primes and prefetches blocks; stereo tempo conversion aligns both channels together. Native DynamicsCompressorNode plus a WaveShaperNode output ceiling handle dense overlap. No software spatializer or effect-channel allocator is used.
The video worker runs gameplay/presentation and H264/AAC encoding. Because native OfflineAudioContext is a window API, it requests stereo audio blocks from the page through a small typed message exchange. It receives transferred PCM, never audio nodes. Cancellation terminates both work paths. Completed MP4 bytes remain in memory for download, while audio buffers stay bounded independently of run duration.