Crusader_Decomp/docs/standalone-usecode-debugger.md
Maddo ffb1918f35 Add tests for controller fire attempt suppression and usecode interpreter functionality
- Enhanced isometric_controls_tests.cpp to include assertions for controller fire attempt suppression under various conditions.
- Added tests for the Usecode interpreter in usecode_vm_tests.cpp, verifying script execution and stack manipulation.
- Introduced a new PowerShell script, clean-old-build-artifacts.ps1, to facilitate the cleanup of old build artifacts in specified directories.
2026-10-08 09:01:31 +02:00

19 KiB
Raw Blame History

Standalone Crusader USECODE Debugger

Status: Feasibility and architecture proposal
Last evaluated: 2026-10-07
Scope: No Remorse and No Regret USECODE archives and debugger workflows

Executive conclusion

A standalone debugger is feasible, but it should be treated as a new debugger application built from the recovered behavior and data formats, not as a direct extraction of the game's 16-bit debugger code.

The in-game debugger is a front end attached to the game's live interpreter. Its RUN command resumes that interpreter; it does not parse the displayed .unk file or execute it. A standalone tool that can actually run scripts therefore needs its own execution engine or a bridge to a compatible game runtime. Recreating the source pane and menus alone will not provide execution, stepping, or meaningful watches.

There are two useful definitions of “standalone”:

  1. Offline USECODE debugger: opens an archive, decodes bytecode, and runs it in a controlled VM with logged or simulated native calls. This is achievable without the game executable, but scripts that depend on world state or native intrinsics will be limited by the simulation.
  2. Game-faithful debugger: executes scripts against the same process, world state, scheduler, and native services as the game. This requires integrating a compatible runtime such as the ScummVM Ultima 8/Crusader engine, or building a live bridge/instrumentation path. It is a substantially larger project.

The recommended host is the existing Crusader map viewer JavaScript application. Add a debugger workspace to its USECODE tab, reuse its game selection, class/event navigation, and decompiler, and put execution in a separate VM/session layer. Start with an offline VM and an explicit intrinsic-provider boundary. Treat live-game parity as a later integration decision, not a prerequisite for the first useful debugger.

What the in-game debugger actually does

The recovered menu and event paths expose a substantial debugger workflow:

  • Open a unit or text file, view source, search, and navigate to a line.
  • Continue/run, break-next, single-step, run to cursor, step over, and run until return.
  • Set and remove line breakpoints.
  • Inspect values, maintain watches, and change globals.
  • Display the current source line and debugger call stack.
  • Break to TDP; the exact behavior and dependencies of this command remain unresolved.

The source pane reads line-oriented <unit>.unk text. That text is for display and source navigation; it is distinct from the compiled event bodies stored in EUSECODE.FLX. In the recovered Regret event handler, RUN clears debugger break/step latches and resumes through the Gump callback. It does not compile or interpret the visible source text.

The live debugger also relies on state that exists only during real interpreter execution. Its break-state object stores the current unit and line, breakpoints, step flags, and a stack of current-entry records. Those records include runtime pointers used by watch/inspect formatting. Opening the modal UI and loading a .unk file does not create a valid interpreter frame.

This explains the current Regret result: the UI and source file can be made to open, but RUN can still crash when the debugger lacks a genuine current-entry record and valid runtime context. The recovered Regret bootstrap and interpreter hook are stronger than Remorse's dormant path, but the current-entry seeding path is not fully closed. See the Regret debugger investigation and the break-state layout.

What can be reused

The executable work provides a behavioral specification, not a portable source tree. Useful recovered material includes:

  • The debugger command/menu surface, event routing, breakpoint and step-state behavior, and source/watch pane behavior.
  • The break-state layout, breakpoint entries, callstack entries, and expression-formatting evidence.
  • The Crusader archive, class, event, and bytecode layouts in the USECODE format specification.
  • Existing extractors, parser fixtures, per-event source snapshots, and the map-viewer decompiler.
  • ScummVM's Crusader-capable USECODE runtime as a candidate implementation to evaluate for runtime reuse.

Directly lifting the 16-bit routines would retain dependencies on segmented far pointers, the game's Gump/event framework, global memory, allocators, and native services. A portable application should reimplement the recovered semantics behind ordinary interfaces and use the original routines as evidence and comparison points.

The generated pseudocode and .unk files are not original compiler source and are not yet a complete editable/recompilable representation. The current map-viewer source snapshots preserve bytes and support limited immediate-edit previews, but there is not yet a deterministic archive writer or a proven edited-script runtime loop. See the round-trip roadmap.

Target Host: Map Viewer

The map viewer already has a natural home for this feature:

  • ViewportPanel.vue provides the USECODE tab and mounts UsecodeViewer.vue.
  • UsecodeViewer.vue already has a class/event tree, source search, syntax-colored code view, and scene-driven open-target events.
  • usecode-browser.js loads the index and rendered text. In dynamic mode these come from /api/usecode/:game and /api/usecode/:game/raw; static mode reads the corresponding exported cache files.
  • The Node-side usecode-decompiler.js reads original archive files and builds the cache. The current cache contains an index, pseudocode text, and generated .unk files. It does not publish the original archive or the versioned archive-source document as a browser execution input.

The current viewer is therefore a strong navigation and presentation base, but not yet a VM host. Its browser UI receives derived text, while the debugger needs authoritative bytecode, instruction offsets, class/event identities, and variant metadata. Add an explicit archive-source loading path: either serve a read-only archive/source snapshot from the dynamic server and include the equivalent in static exports, or let the user load a local archive. Do not make execution depend on scraping pseudocode text.

The decompiler module is Node-oriented and imports node:crypto, node:fs, node:path, and uses Buffer. It should not be imported directly into the browser bundle. Separate a portable byte-reader/parser/IR core from Node cache and filesystem adapters, or provide the browser with a validated structured snapshot. A Web Worker is the preferred place for VM execution so long-running scripts cannot freeze the map viewer, its canvas, or the debugger controls.

Keep the existing USECODE tab and add a browse/debug mode within it. The class/event tree and map-to-usecode navigation remain shared. A selected event should open a session at its first executable instruction; the right side can show source/decompilation and bytecode, with adjacent runtime panes for current instruction, call stack, locals/globals, watches, breakpoints, and VM output. This integrates the debugger into the existing app without creating a second product shell.

Feature parity and dependencies

In-game capability Standalone equivalent Main dependency or caveat
Open unit/file and browse source Open archive class/event; show decoded listing, pseudocode, or .unk text Must map displayed lines to bytecode offsets. .unk is display data, not executable code.
Search and go to line Search source/listing and navigate to mapped instruction Original debug-line coverage differs by variant. Current extraction finds line markers throughout Remorse, but none in the examined Regret corpus. Synthetic listing lines are possible, but are not original line numbers.
Continue, break-next, single-step Control a VM instruction/event loop Requires a VM with defined stop points and resumable execution state.
Step over, run until return Track call depth and event/process boundaries Must define behavior across class/event calls, spawned processes, and suspension.
Breakpoints Bind breakpoints to class/event plus bytecode offset or mapped source line Class names and source lines alone are not stable identities; retain class ID, event ID, and body digest/offset.
Watch and inspect Evaluate supported expressions against VM frames and values Requires correct local/member/global, string/list/reference, and call-frame semantics. Game-backed values require native runtime state.
Change global Edit VM global state A sandbox can edit its own state. Matching game behavior requires variant-correct global layout and runtime integration.
Break to TDP Reproduce after its contract is recovered Do not claim parity until its host/tool dependency and observable behavior are known.

Proposed architecture

Keep the debugger engine independent of the GUI and of any particular game runtime.

1. Archive and source model

  • Load the correct Remorse or Regret archive and preserve all original bytes.
  • Index classes, event slots, bodies, and raw offsets using the locally validated format rules.
  • Decode instructions to an addressable listing while retaining unknown instructions and trailer bytes.
  • Maintain source maps from displayed rows and any available LINE_NUMBER metadata to class/event/body offsets.
  • Identify every debug position by variant, archive identity, class ID, event ID, and instruction/body offset; treat names as labels.

2. Debuggable VM core

  • Represent VM values, evaluation stack, locals, members, globals, event frames, and process state explicitly.
  • Execute supported bytecode with a program counter that can pause and resume at instruction boundaries.
  • Implement class/event dispatch, process spawn, suspend/resume, return, and the control-flow forms needed by real scripts.
  • Emit trace events for instruction entry/exit, calls, returns, intrinsic calls, state changes, and errors.
  • Store breakpoints and step plans in debugger-session state rather than in GUI widgets.

Unknown opcodes or value semantics must stop with an actionable diagnostic or remain opaque in static views. The VM must not silently guess instruction lengths or side effects.

3. Intrinsic providers

Define a variant-specific interface for native calls. Start with a sandbox provider that records arguments and returns configured values or explicit “unsupported” results. Add deterministic implementations for low-risk services, then a game-backed provider if runtime parity is required.

Remorse and Regret must use separate ordinal/signature metadata. A matching ordinal number is not evidence of matching behavior. Intrinsics that mutate world state should be visibly marked and disabled or simulated by default in offline sessions.

4. Debugger session and UI

Build the front end around the VM session API inside the existing map viewer's USECODE tab. Reuse its game/version selection, class/event tree, open-usecode-target event, decompiler view, and existing generated-source paths. Add an explicit debug-session state that is separate from selected-map state and viewer history.

A first useful UI needs a disassembly/source view, current instruction, call stack, locals/globals, breakpoint list, watch list, and VM output/error log. Add run, pause, step-into, step-over, and run-to-return controls only as their semantics become implemented. Preserve recovered commands where their semantics are known; label unsupported or unresolved operations instead of presenting them as working controls.

The UI need not imitate the game's Gump rendering. Reproducing the debugger's capabilities and state transitions is the goal; a desktop UI can provide a clearer view of bytecode addresses, raw bytes, and unsupported operations than the original screen allowed.

5. Browser/runtime boundary

  • Give the VM a browser-safe input contract based on Uint8Array or a validated archive-source document; keep Node filesystem access in cache/build adapters.
  • Reuse the existing decompiler IR for labels and explanatory views, but execute decoded instructions from preserved bytecode and retain each instruction's exact body offset and raw bytes.
  • Put VM stepping in a Web Worker with messages for start, pause, step, breakpoint hit, trace, result, and error. Keep UI controls responsive and make runaway scripts interruptible.
  • Keep static deployment viable by exporting the same read-only archive input used by the dynamic server. The current static export copies the generated usecode cache, which is not sufficient until that cache contains execution input.
  • Keep archive selection, VM session, breakpoint/watch state, and map selection as separate state domains. A map click may select an event, but must not silently start or mutate a running session.

.unk Format Investigation

The canonical evidence inventory, open questions, and step-by-step investigation plan now live in usecode-unk-format.md. The key boundary for the standalone debugger remains that .unk is display/source-mapping data; execution and breakpoints must be anchored to compiled event bytecode and valid VM state. Keep authentic, generated, and synthetic .unk files explicitly distinguished.

Implementation stages

  1. Create the browser input contract. Deliver original archive bytes or a validated archive-source snapshot to both dynamic and static map-viewer builds. Keep the API read-only and variant-specific.
  2. Separate portable decode from Node I/O. Extract the archive reader and instruction/IR model into browser-safe code; keep filesystem, cache generation, and Node hashing behind adapters. Add exact byte-offset navigation from the existing pseudocode view.
  3. Build a read-only debugger workspace. Extend the existing USECODE tab with bytecode view, raw bytes, class/event metadata, and source/bytecode navigation. Do not imply execution yet.
  4. Investigate and validate .unk. Recover the text-loader contract and authentic source mapping; retain explicit provenance for authentic versus generated .unk files.
  5. Add a worker-hosted bounded VM. Begin with a small, testable opcode subset and sandboxed intrinsics. Add breakpoints, continue, instruction stepping, call-stack display, trace output, and explicit unsupported-op reporting.
  6. Expand runtime semantics. Add class/event calls, spawned processes, suspend/resume, managed values, and the variant-specific intrinsic contracts needed by selected corpus scripts.
  7. Add watch/inspect and source mapping. Support a documented expression subset and map any authentic .unk rows and generated listing rows to bytecode offsets. Never label synthetic Regret rows as original source lines.
  8. Evaluate game-backed parity. Compare the custom VM against ScummVM's Crusader runtime or another compatible host before implementing a second complete world/intrinsic layer. Keep this evaluation in the map-viewer app; a separate emulator/process bridge is an optional later project, not the initial product.
  9. Prove behavior incrementally. Use known scripts and traces, verify pause/resume and breakpoints around calls and yields, compare Remorse and Regret independently, and record unsupported commands and intrinsics.

Effort Estimate

These are rough engineering estimates for one engineer familiar with the map viewer, the current decoder, and the recovered debugger notes. They assume a sandboxed offline VM for the first release and do not include implementing all game intrinsics or reproducing game-world behavior.

Workstream Estimate Main uncertainty
Browser archive input, portable decoder boundary, and basic Vue session integration 1-2 weeks Whether the static exporter should package raw FLEX bytes or a validated snapshot; expected archive transfer/storage size.
First .unk investigation and validator fixtures 1-2 weeks Availability of authentic .unk files and a repeatable game-side test path.
VM core for a useful, bounded opcode subset 4-8 weeks Value ownership, stack semantics, branches, and how much real corpus behavior must execute in the first cut.
Worker controls, breakpoints, stepping, trace, and basic call-stack integration 2-4 weeks Correct process/call behavior for spawn, suspend, and nested event dispatch.
Watch/inspect, source mapping, variant regression, and hardening 3-6 weeks Expression semantics, missing Regret line markers, and intrinsic requirements of target scripts.

Some work can overlap. A read-only bytecode debugger inside the current tab is a much smaller first milestone, roughly 2-4 weeks. A useful sandboxed debugger that actually runs a documented subset is approximately 10-18 engineer-weeks. A claim of broad game-faithful parity is a multi-month effort with no defensible upper bound until a ScummVM/runtime-reuse spike establishes how much world and intrinsic behavior can be reused. The parity spike itself should be time-boxed to 1-2 weeks and end with a written integration decision.

The highest-risk work is not the Vue layout. It is defining and testing a correct runtime state/value model, supplying original bytecode to the browser, and deciding whether intrinsic behavior is simulated or borrowed from a game runtime.

Acceptance criteria

Call the first release a standalone USECODE debugger when it can load both supported archive variants, navigate bytecode, run the documented supported subset, pause/resume/step deterministically, maintain breakpoints and call stacks, inspect supported VM values, and report every unsupported opcode/intrinsic without corrupting state.

Claim in-game debugger parity only when the supported menu actions have equivalent behavior and scripts can execute against compatible native/world services. A VM with stub intrinsics is useful, but it is not equivalent to the game's live debugger for gameplay-dependent scripts.

For modified archives, require byte-identical no-op round trips, independent parse validation, and disposable-copy in-game tests. The existing editor roadmap's M2–M7 gates remain prerequisites for a reliable authoring-and-rebuild workflow; they are related to, but separate from, implementing a standalone execution debugger.