Crusader_Decomp/docs/usecode-tool-improvement-plan.md
Maddo 6d4972933f Refactor USECODE tooling documentation and enhance map-viewer decompiler
- Updated the USECODE Tool Improvement Plan to focus on the map-viewer decompiler/editor, emphasizing its role as the primary development target for USECODE editing and recompilation.
- Revised the tooling comparison document to include the newer map-viewer decompiler, clarifying its purpose and distinguishing it from the Python parser.
- Introduced a new ClearAvatarInStasisProcessEntry structure in the entity dispatch entry header, along with related process creation and execution logic in the ProcessKernel.
- Implemented the setItemShape method in LiveFixedMapItems to allow dynamic shape updates for items.
- Enhanced the teleporter process to handle avatar stasis and integrated it into the game main loop, ensuring proper process management and state handling.
- Added tests for the new functionality, including shape setting and teleporter process behavior, to ensure correctness and stability.
2026-10-06 00:01:20 +02:00

10 KiB

USECODE Map-Viewer Decompiler/Editor Plan

Purpose

This note turns the tooling comparison into an implementation plan for the map-viewer USECODE decompiler/editor.

The primary development target is the newer map-viewer implementation at usecode-decompiler.js, with regressions in map_renderer/scripts/test-usecode-structuring.mjs. It should grow into the actual user-facing tool for decompiling, editing, and recompiling USECODE.

The local Python parser/exporter and USECODE/EUSECODE_extracted/ corpus are supporting research infrastructure: use them for byte-level evidence, fixtures, and independent output comparisons. Do not build a competing end-user editor/compiler in those tools.

The intent is not to copy Pentagram or crusader-disasm wholesale. Extract their useful opcode, operand, and metadata evidence and apply it to the map-viewer implementation.

Short version

The most useful next upgrades in the map-viewer implementation are:

  1. keep strengthening opcode/operand and control-flow coverage
  2. preserve a lossless, editable IR alongside readable pseudocode
  3. add a source/IR editing workflow
  4. build an assembler and deterministic class/FLEX archive writer
  5. validate untouched and modified output, including in-game behavior

Current status

Existing work to build on:

  • the map-viewer decompiler already structures a growing set of branches, loops, selectors, list operations, and switch-like dispatches, with focused JavaScript regression tests
  • versioned crusader-usecode-archive-source v1 and per-event crusader-usecode-source v2 JSON snapshots preserve original archive/class/event/body bytes; the per-event overlay validates guarded fixed-width immediate edits and can produce a clearly labeled edited-IR preview, while broader edit support, editor integration, and compilation remain open
  • the workspace Python parser/exporter supplies per-slot byte-backed IR, pseudocode, extracted corpus data, and comparison fixtures
  • both sources provide useful evidence, but neither currently completes the edit → compile → rebuild → in-game validation loop

Still required in the map-viewer product path:

  • improve semantic and structural decompilation based on concrete corpus failures
  • formalize the lossless editable format and connect it to an editor experience
  • implement compilation, relocation/offset updates, and safe archive rebuilding
  • add byte-identical round-trip, edit-regression, and Remorse/Regret runtime tests

Priority 1: Authoritative opcode metadata

What to borrow

From Pentagram and crusader-disasm:

  • stable opcode names
  • operand-shape knowledge
  • special handling for records like SYMBOL_INFO, LINE_NUMBER, PROCESS_EXCLUDE, and END

Why it matters

The map-viewer decompiler already produces readable structured output for a growing subset, but opcode semantics and operand formats still need evidence-backed coverage. Heuristic rendering must remain distinct from the lossless representation used by the future compiler.

Concrete change

Move the map-viewer per-opcode knowledge into a single explicit table describing:

  • mnemonic
  • stack effect where known
  • immediate layout
  • control-flow behavior
  • whether the opcode is normal code, metadata, or trailer-oriented
  • whether the opcode participates in loop selector mini-languages

Expected payoff

  • fewer ad hoc decode branches
  • easier regression testing against the text corpus
  • cleaner IR for later restructuring passes

Priority 2: Real loop/selector decoding

What to borrow

From the older disassembly corpus:

  • the meaning of loopscr tokens such as end, ==, item->shape, item->family, and typed literal selectors
  • the visible repeated patterns in alarm-family and trigger-family bodies

Why it matters

The map-viewer already renders several common selector forms. Remaining selector forms should be added there as evidence and regression cases are established; keep unknown forms visible rather than guessing semantics.

That is the main reason scripts like ALARMHAT still read as partially machine-shaped even though the overall behavior is already understandable.

Concrete change

Extend the map-viewer loop-selector IR so supported forms render as something closer to:

for item in nearby_items(shape=0x04D0, origin=arg_06):

or:

for candidate in nearby_items(family=6, origin=arg_06):

The first target is not full generality. The first target is the set of repeated loop forms already seen in:

  • NPCTRIG
  • ALARMHAT
  • ALARMBOX
  • ALRMTRIG
  • nearby environmental families

Expected payoff

  • much better readability for object-searching scripts
  • better gameplay interpretation of trigger/controller classes
  • a cleaner path to naming common search idioms

Priority 3: Better intrinsic naming and signatures

What to borrow

From Pentagram and crusader-disasm:

  • historical intrinsic names
  • text-mined call arities and stack cleanup behavior
  • rough prototype guesses from the older corpus tools

Why it matters

Readable pseudocode is bottlenecked less by control flow now and more by anonymous calls like Intrinsic0007() or generic placeholders like class_0A18_slot_20(...).

The older tool lines already contain partial information that can improve this materially, as long as it is treated as hint-quality evidence rather than rename authority.

Concrete change

Build a local intrinsic metadata table with confidence levels:

  • verified
  • strong hint
  • weak hint

Populate it from:

  • Pentagram tables
  • usecode_opcodes.txt
  • mined calli/add sp patterns from crusader_disasm.txt
  • current repo notes where compiled-side names are already justified

Expected payoff

  • more readable pseudocode
  • safer future promotion of intrinsic names
  • less confusion between Remorse-only, Regret-only, and cross-game vocabulary

Priority 4: Explicit code-versus-trailer boundaries

What to borrow

From Pentagram's symbol-info/debug-symbol handling:

  • the idea that 0x5C points into structured trailer data
  • the practical distinction between executable body and debug/local trailer rows

Why it matters

The JELYHACK pass already showed how important this is. Tiny scripts are easy to misread if post-ret metadata gets rendered as live code.

The current renderers avoid some of these misclassifications, but the map-viewer IR/compiler path must make code and trailer boundaries first-class so edits cannot accidentally treat metadata as executable bytes.

Concrete change

Make trailer parsing explicit in the IR:

  • code extent
  • trailer extent
  • debug symbol rows
  • line-number records
  • terminal END

Expected payoff

  • safer whole-corpus export
  • better local naming and source-like output
  • fewer false positives when mining repeated code bodies

Priority 5: Corpus-level pattern clustering

What to borrow

From the crusader-disasm corpus mindset:

  • treat the full body set as a searchable evidence base, not only as isolated scripts

Why it matters

The JELYHACK result was only obvious after repeated-body comparison showed it was a small shared stub. The same strategy can keep the decompiler honest elsewhere.

Concrete change

Add corpus analysis helpers that cluster or index:

  • exact repeated bodies
  • normalized repeated bodies
  • repeated loop-selector templates
  • repeated spawn/call templates by class and slot

Those results should feed back into readable annotations like:

  • shared interaction stub
  • alarm-family controller template
  • common trigger setup pattern

Expected payoff

  • faster triage of interesting scripts
  • better distinction between generic templates and unique gameplay logic
  • fewer overinterpretations of tiny bodies

Priority 6: Stronger runtime bridge and import path

What to borrow

From the local repo workflow rather than directly from Pentagram:

  • the current runtime anchors already recorded in runtime_vm_ir.tsv
  • the Ghidra-side annotation path planned in the USECODE notes

Why it matters

The map-viewer decompiler is strongest when its readable output can be tied back to the compiled loader and sequencer. Keep those runtime anchors attached as evidence, without letting them replace the lossless byte representation needed for compilation.

Concrete change

Expand the export and annotation path so pseudocode/index output can carry verified runtime anchors where known, especially around:

  • 000d:51fd
  • 000d:5572
  • 000d:46ec
  • 000d:21ed
  • 000d:22bc
  • 000d:ebe3

Expected payoff

  • easier Ghidra-side correlation
  • safer promotion of slot/event names
  • better compiled-to-script navigation

Suggested implementation order

  1. Continue improving the map-viewer decoder, operand model, control-flow structuring, and trailer handling against extracted fixtures.
  2. Keep each semantic or rendering improvement covered by focused and real-corpus regressions in the map-viewer test suite.
  3. Define the map-viewer's versioned, lossless editable IR and source/editor experience; retain raw bytes and provenance for unsupported instructions.
  4. Implement a bounded assembler, label/branch resolution, and deterministic class/FLEX archive rebuild in the same product path.
  5. Prove byte-identical output for unchanged inputs, then test supported edits and reject unsafe edits clearly.
  6. Run controlled Remorse and Regret game tests before declaring a supported round-trip workflow.

What not to do yet

  • Do not treat readable pseudocode as compilable source or let the Python proof of concept become a second editor/compiler.
  • Do not stop at readability: the intended outcome is an editor/decompiler/recompiler that produces working in-game USECODE.
  • Do not mass-promote intrinsic or event names from Pentagram or the old disasm corpus without current-binary support.
  • Do not try to solve every loop/selector form before landing the small repeated set that already appears across the alarm and trigger families.

Current best next step

The most leverage is in loop-selector decoding.

That is the place where the older tools still give us directly reusable structure and where the current readable output most obviously needs another step forward.