From dfebd1d628bb9ce105abcec050b70b6ffadc9566 Mon Sep 17 00:00:00 2001 From: SomeeName <168603991+SomeeName@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:28:43 +0100 Subject: [PATCH] Add 26 tone slots (A to Z) for native charts --- docs/ARCHITECTURE.md | 6 + docs/NATIVE-FORMAT.md | 4 + docs/agents/tones-notes.md | 445 +++++++++++++++++++++ docs/release/CHANGELOG.md | 8 + docs/release/NATIVE-FORMAT.md | 40 ++ mkdocs.yml | 1 + sites.json | 20 +- src/features/native/hooks.cpp | 11 +- src/features/tones/game.cpp | 193 +++++++++ src/features/tones/game.h | 14 + src/features/tones/hooks.cpp | 95 +++++ src/features/tones/hooks_toneplan.cpp | 63 +++ src/features/tones/native_registration.cpp | 78 ++++ src/features/tones/native_registration.h | 24 ++ src/features/tones/registration.cpp | 54 +++ src/features/tones/selection.h | 21 + src/features/tones/state.cpp | 381 ++++++++++++++++++ src/features/tones/state.h | 31 ++ src/features/tones/toneplan.cpp | 118 ++++++ src/features/tones/toneplan.h | 12 + src/features/tones/tones.h | 8 + src/hook_rules.cpp | 5 + src/model/gates.h | 1 + src/model/groups.cpp | 3 +- src/model/groups.h | 1 + src/model/nativemanifest.cpp | 27 +- src/model/nativemanifest.h | 4 +- src/registry.cpp | 3 +- tests/model/test_nativemanifest.cpp | 50 +++ tests/test_hook_rules.cpp | 5 +- tests/test_registry.cpp | 9 +- tests/tones/json_fixture.h | 73 ++++ tests/tones/manifest_fixture.h | 117 ++++++ tests/tones/test_apply.cpp | 53 +++ tests/tones/test_native_registration.cpp | 174 ++++++++ tests/tones/test_registration.cpp | 34 ++ tests/tones/test_selection.cpp | 23 ++ tests/tones/test_state.cpp | 361 +++++++++++++++++ tests/tones/test_toneplan.cpp | 132 ++++++ tools/check_exports.py | 22 + tools/native_chart.py | 47 ++- tools/tests/emu_harness.py | 74 +--- tools/tests/emu_refs.py | 63 +++ tools/tests/test_emu_tones.py | 105 +++++ tools/tests/test_midhook_wrap_table.py | 20 +- tools/tests/test_tone_slots.py | 230 +++++++++++ tools/tone_demo.py | 157 ++++++++ 47 files changed, 3351 insertions(+), 69 deletions(-) create mode 100644 docs/agents/tones-notes.md create mode 100644 src/features/tones/game.cpp create mode 100644 src/features/tones/game.h create mode 100644 src/features/tones/hooks.cpp create mode 100644 src/features/tones/hooks_toneplan.cpp create mode 100644 src/features/tones/native_registration.cpp create mode 100644 src/features/tones/native_registration.h create mode 100644 src/features/tones/registration.cpp create mode 100644 src/features/tones/selection.h create mode 100644 src/features/tones/state.cpp create mode 100644 src/features/tones/state.h create mode 100644 src/features/tones/toneplan.cpp create mode 100644 src/features/tones/toneplan.h create mode 100644 src/features/tones/tones.h create mode 100644 tests/tones/json_fixture.h create mode 100644 tests/tones/manifest_fixture.h create mode 100644 tests/tones/test_apply.cpp create mode 100644 tests/tones/test_native_registration.cpp create mode 100644 tests/tones/test_registration.cpp create mode 100644 tests/tones/test_selection.cpp create mode 100644 tests/tones/test_state.cpp create mode 100644 tests/tones/test_toneplan.cpp create mode 100644 tools/tests/emu_refs.py create mode 100644 tools/tests/test_emu_tones.py create mode 100644 tools/tests/test_tone_slots.py create mode 100644 tools/tone_demo.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bb304af..081068a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -24,6 +24,12 @@ before the repository went public. They remain only in the maintainer's private hashes elsewhere in these docs also point into that history, for example those of the frozen stub fixtures in chapter 14. The fixture files themselves are in the tree. +Native tone registration findings and the isolated E..Z resource-preload design are tracked in +[tone implementation notes](agents/tones-notes.md#native-registration). Full shared-store reader integration +is deferred until its aliases and lifetime are mapped; playback retains the full-object apply path and reads +the stock per-player Tone Plan override properties. The editor's dynamic rows and viewport limit are recorded +in the [demo-first editor notes](agents/tones-notes.md#demo-first-editor-implementation). + ## Find a topic ### Start with the model diff --git a/docs/NATIVE-FORMAT.md b/docs/NATIVE-FORMAT.md index 74452f3..625e04e 100644 --- a/docs/NATIVE-FORMAT.md +++ b/docs/NATIVE-FORMAT.md @@ -9,6 +9,10 @@ that it works. ## Why +The tone-slot loader implementation and static site evidence are recorded in +[tone research notes](agents/tones-notes.md). The writer fields are specified in +[Tone slots A through Z](release/NATIVE-FORMAT.md#tone-slots-a-through-z). + In the native format, the string order is positional throughout the package. The game cannot read this format directly, so RS Extended Range translates it while loading. The result is stock records plus an internal [extension block](architecture/extension-block.md) and internal manifest keys. Tools never write that internal form. diff --git a/docs/agents/tones-notes.md b/docs/agents/tones-notes.md new file mode 100644 index 0000000..1eaa9cb --- /dev/null +++ b/docs/agents/tones-notes.md @@ -0,0 +1,445 @@ +# 26 tone slots: implementation notes + +2026-11-17. September 2022 Steam build, image base `0x400000`, PE checksum `0x00B13D7C`. +No game installation or in-game test was performed. Builds, uv and pytest were not run, as requested by the brief. +Milestone 2 used direct clang-format and standard-library static checks; the caller must run all normal gates. + +## Evidence and implementation + +- **CONFIRMED (static):** milestone 1's nine patterns each match once in executable sections of the unpacked PE; + each expected byte sequence matches at the stated address. Checked with a standard-library Python PE reader. + These are pattern/byte checks, not the full `tools/sitecheck.py` gate or live-hook validation. +- **CONFIRMED (static evidence):** `0x56774C` exposes Attributes.Tones in EAX and its parent arrangement at `[EBP+0Ch]`; + the arrangement identity comes from `[EBP-3A0h]` (`0x567448..0x5675EE`). +- **CONFIRMED (static evidence):** the five wrapped lookups call `0x559DB0`, stdcall(time, out id), ret 8. + Automatic consumer `0x464ADD` has ESI=session; the other four have EBX=session. +- **CONFIRMED (static evidence):** `0x7DF400` takes stack arguments session and force, ret 8 at `0x7DF697`. + Force=true bypasses the accessor and applies Base; its after callback restores the native timeline selection. +- **CONFIRMED (static evidence):** `0x7D3D50` takes ESI=&definition plus stack(manager, player, activation=3), + ret 0Ch at `0x7D3F5C`. The bridge restores the C++ caller's ESI through a second full call-in after return. + `0x465251` supplies the manager global address `0x136042C`. +- **CONFIRMED (static evidence):** manifest string unwrapping uses virtual +60h and value+8 (`0x8899F0`); + the automatic consumer's separate JSON path uses +64h (`0x465119..0x46516C`). + definition lookup unwraps collection entries through virtual +34h and canonical objects through +5Ch + (`0x7D37FF..0x7D3949`). References are retained/released through virtual +0/+4. + +Implementation extends the earlier worker's code. It keeps the stock registration grid unchanged, captures E..Z +in per-arrangement side tables, and owns Base/A..Z playback only with both an internal manifest marker and a +native SNG load token. The manifest rewriter generates `RsxrToneSlots=26` only for valid native attributes with +nonempty extra names; that field is reserved, not an authoring requirement. XI1 marks both native and stock +loads, with a fresh generation for reused native SNG addresses. A later non-extended manifest clears stale +capture data. Definitions are released outside the loader mutex. Two players have independent selections. +Repeated polling does not repeat decision logs; forced refreshes reapply but log only changed decisions. + +## First-run silence investigation + +- **CONFIRMED (code reading):** `game.cpp:Name` originally used the automatic consumer's +64h accessor for + manifest fields. The stock manifest reader `0x8899F0` uses +60h, including the `Key` lookup from `0x7D384B`. + The adapter and its owned JSON fixture now use that manifest contract. The regression supplies only +60h + and checks that `Tone_E` is readable; the existing definition/apply tests use the corrected fixture too. +- **CONFIRMED (code reading):** the rewriter's `ToneMarker` preserves `Tone_E..Z` and replaces `ExtendedRange` + with `RsxrToneSlots=26` for valid native attributes containing nonempty extra names. `Capture` used to discard + an arrangement silently if name reading failed; `FindArrangement` also returned silently for missing manifest + capture or a missing native SNG token. All original `tones26:` decision logs came after those gates. +- **CONFIRMED (code reading):** playback reset compared `selection.session`, which is set only after a successful + apply. Rejections therefore reset on every poll. Playback now tracks its observed session separately, so failed + applications retain their rejection budget as well as the once-per-load diagnostics. +- **HYPOTHESIS:** the accessor mismatch explains the first run's silence. The original log cannot establish + the selected arrangement or which silent gate failed; audibility and live association still need a rerun. + +Manifest capture logs its UUID, extra slot letters and marker, including rejected capture decisions. +XI1 now logs each SNG load and assigns a fresh generation to native and stock loads. The first consumer call +logs arrangement UUID, SNG address, player and either `extra tones 2 (E,F), active`, `no extra tones`, or a +specific rejection (feature disabled, SNG load not observed/not native, manifest not captured, missing/invalid +marker, or marked manifest with no readable extra names). The first successful timeline lookup logs +`first event raw=0 time=...`, even when extension eligibility fails. These decisions are retained independently +of successful tone application and reset for a new load, arrangement or player session. Existing applied/rejected +selection lines remain. Native tests cover inactive reasons, reloads, first-event logging and rejection spam. +Build, unit tests, pytest and the game were not run for this diagnostic change, as required by the brief. + +## Second-run empty capture investigation + +- **CONFIRMED (static evidence):** `[EBP+0Ch]` at `0x56774C` is the parent arrangement, not its Attributes child. + The stock lookups at `0x5676BF` and `0x567742` use `Attributes.Tone_Base` and `Attributes.Tones`, respectively. + Passing that parent to `Capture` made its direct `RsxrToneSlots` and `Tone_E..Z` lookups miss both fields. + The hook now resolves `Attributes` with the stock object-member contract (`0x889CA0`, virtual +18h then +5Ch) + before capture. The string accessor remains +60h. The earlier description of the loader argument was incorrect. +- The new hook regression supplies a parent with a nested Attributes object, checks E/F capture and native + playback eligibility, then removes Attributes and checks that the previous capture is discarded. +- A separate manifest regression uses wholly synthetic Python `json.dumps(indent=2, ensure_ascii=False)` text + with the demo's nesting and relevant key order, six tone definitions, nonempty E/F and empty G..Z. It compares + all output bytes against the expected marker/tuning replacements for Lead and Rhythm, and checks that the + unmarked form is left untouched. The production manifest rewriter is unchanged. +- **HYPOTHESIS:** correcting the parent/child mismatch resolves the second run's `extra tones=0 ... marker=0`. + The regression tests have been added but were not executed: builds, uv and pytest are forbidden by this brief. + The caller still needs the native test run and an in-game rerun to establish audible E/F changes. + +## Native registration + +2026-11-17, milestone 2 static investigation. Standard-library Python parsed the PE sections and checked call +targets/patterns; LLVM decoded selected code ranges from a temporary copy with its malformed TLS-directory size +corrected for the decoder. No game bytes or listings were saved in this checkout. + +- **CONFIRMED (`0x7D1510..0x7D1550`, `0x5A8700`):** the manager allocates a `0x14`-byte resource-store object + at `+0x1A4`. Its outer vector is at `+8/+0Ch/+10h`. Construction calls `0x5A8AA0`, which sizes it to + **18 records** (`0x5A8ABE`, `0x5A8AF2`), each 12 bytes, for `0xD8` bytes of initial record storage. + Allocation goes through `0x5A8BA0 -> 0x8FB9C0` (`0x5A8BE6`). Each record is itself a begin/end/capacity + vector of reference-counted resource pointers, not a tone-definition pointer. +- **CONFIRMED (`0x5A87B4..0x5A87E3`, `0x7D43D6..0x7D4404`):** records 0..7 are a different four-per-player + resource-registration path. `0x7D6D09..0x7D6D38` writes song Base/A..D into records 8..17 with stride five. + Both paths call resource-vector builder `0x5A70A0`. +- **CONFIRMED (`0x5A70D9..0x5A737F`):** the builder reads GearList, visits fourteen gear-category names, + constructs `0xB0`-byte resource objects and calls `0x5A7AF0`. That routine looks up resource definitions and + either attaches existing resources (`0x5A7D43..0x5A7D65`) or queues asynchronous loading with a resource-object + callback (`0x5A7DA7..0x5A7E22`). Registration therefore requests/retains gear resources; return does not prove + that asynchronous loading has finished, or that a sound has been activated. +- **CONFIRMED (`0x5A8800`, caller `0x7C0839`):** whole-store clearing walks the actual outer-vector length. + **CONFIRMED (`0x5A8900`, callers `0x65D91D`, `0x73C4AD`):** another clear path hard-codes record byte ranges + `0x30..0x60` and `0x9C..0xD8`. **CONFIRMED (`0x5A8A00`, caller `0x7DD5DC`):** song-resource clearing + hard-codes two groups of five starting at byte `0x60`. These paths release resources and reset each end pointer. +- **CONFIRMED (`0x5A8750`, `0x5A8EF0`):** store destruction destroys the nested vectors and frees their game + allocations. `0x5A8EF0` is cdecl with stack arguments (record end, record begin), walking backwards by 12. +- **CONFIRMED (`0x7D6CE0..0x7D6D62`):** stock registration takes EAX=player and stack(manager, definition, + slot), returns with `ret 0Ch`, and consumes one caller-owned definition reference. It has no boolean result. +- **HYPOTHESIS:** all surviving aliases/readers of the shared store have been identified. The mapped direct + writers and cleanup paths do not constitute an exhaustive pointer-flow proof, including asynchronous resource + callbacks and other manager users. Tone Plan and activation do not become extensible merely by enlarging this store. + +### Design and implementation scope + +The preferred replacement of the live manager store is blocked by that incomplete alias/lifetime map and the +fixed cleanup partitions. Keep the stock store, strides, bounds, activation and Tone Plan unchanged. Implement +only isolated E..Z pre-registration: a mod-owned 62-record buffer (eight reserved plus two rows of 27), with +short-lived manager/store views passed to the **unmodified** stock registration call. For logical native slot +`s` (Base=0, A=1, E=5, Z=26), a view begins at record `player*22+s`; stock `(player, slot=0)` then addresses +record `8+player*27+s`. The original manager is never exchanged, mutated or published to another thread. +Only resource objects, not these temporary views, escape the synchronous stock routine. + +Run after stock session registration, gated by the existing native SNG and manifest checks; if that hook occurs +before eligibility is available, the first eligible playback lookup makes the same bounded attempt. Keep resources +per observed player/load and release them through the stock nested-vector destructor on replacement. Log one +decision for every declared extra slot per attempt; `ok` means a well-formed resource vector was constructed, +including an empty vector for gearless definitions. It does not mean preload completion. Missing definitions or +unavailable registration infrastructure reject that slot, and milestone 1 still applies its normal on-demand path. +Playback continues using full-object apply even after successful resource registration, just as stock registration +does not replace activation. Complete first-class reader integration remains deferred, not claimed by this change. + +Implementation/check plan: add owned ABI/mapping/cleanup tests first; add the isolated store and EAX call-in; +wire a full-mode registration wrap and two call references in the tones failure group and emulator tables; +connect per-load registration state; check patterns/expected bytes and source hygiene with plain Python/Git. +Build, uv, pytest and in-game gates are explicitly delegated to the caller by this brief. + +**CONFIRMED (source inspection):** `native_registration.{h,cpp}` owns the isolated vectors and bridges the +stock EAX ABI. `state.cpp` attempts each declared extra slot once per eligible observed player/load, after stock +registration or at the first eligible lookup. The original timeline/full-object apply path still handles every +selection, including rejected registration. Native tests cover the real call-in ABI with an owned stand-in, +E/Z endpoints for both players, reference consumption, unavailable cleanup, native gating, repeated setup, +reload cleanup and bounded rejection logs. The emulator test adds inactive registration-wrap preservation. +These tests are written but **unexecuted** under the brief's restrictions. + +**CONFIRMED (static checks):** all three milestone-2 patterns below match exactly once at their stated sites, +and expected bytes/call targets agree. Direct clang-format dry-run and `git diff --check` passed; changed Python +files parse with `ast`, local includes and documentation file links resolve, and touched files remain below +800 lines (`emu_harness.py`: 763). Full formatting/layout gates require the caller's dependency environment. +The owned cleanup fixture now populates resource vectors and checks the absolute first record and one release +per retained synthetic resource, in addition to relative player/slot spacing. A read-only code review found no +concrete ABI/indexing defect within this isolated contract; it does not validate the game's asynchronous behavior. + +In game, expect exactly one `tones26: register player=0 slot=5 key='...' ok` for E and slot 6 for F per +observed load (player 1 has separate decisions). A missing/duplicate Key must instead show +`rejected: missing or ambiguous definition`; an unavailable adapter shows `rejected: registration unavailable or failed`. +Existing `id=4`/`id=5 ... applied` logs must still follow timeline selections. Seeking, polling and forced refresh +must not repeat registration decisions. Check native -> stock -> native and co-op for resource lifetime/aliasing. + +**HYPOTHESIS:** isolated registration requests finish early enough to avoid first-use asset stalls. Live resource +readiness, async-callback lifetime, resource sharing between slots/players, and teardown still need game validation. +A trapped fault in stock registration has ambiguous by-value reference ownership; it is rejected without retrying +that decision, and may retain a reference. Resources are released on the next observed session/load/eligibility +change (or shutdown), not immediately on song exit. Full store-reader redirection and Tone Plan remain blocked/deferred. + +## Tone Plan editor + +2026-11-17, milestone 3 static investigation. Plain Python and the standard library parsed the unpacked PE +section table and inspected instruction operands, direct calls, strings and references. The image checksum is +`0x00B13D7C`. No game listings or extracted assets are retained in this checkout. The original design-only +investigation is preserved below; the subsequent implementation and its remaining limits are recorded under +[Demo-first editor implementation](#demo-first-editor-implementation). + +### Screen, rows and data sources + +- **CONFIRMED (`0x5D0C07`, string `0x11B5230`; constructor `0x6498D0`):** this menu is registered as + `LAS_SongOptionsTonePlan`; its movie name is `UIMenu_LAS_SongOptions_TonePlan` (`0x11B5248`). Its page + vtable is `0x11B5390`. The builder at vtable `+0xB0` is `0x64B980`; its select handler at `+0xD8` is + `0x64BBE0`. Do not confuse it with the destination tone chooser, `LearnASong_SongOptions_Tone` + (`0x64BC97`), whose builder is `0x648850` and whose selection/update path includes `0x649210`. +- **CONFIRMED (`0x64BB29..0x64BB96`, `0x625B86..0x625C62`):** the builder obtains the selected arrangement's + **Attributes object**, through `0x625960`, and passes page and Attributes as the two stack arguments to + `0x649A00` and `0x64AC30`. Both helpers return with `ret 8`. This differs from `ToneLoad`, which receives + the parent arrangement. `PersistentID` is read directly from Attributes at `0x64AC87`. +- **CONFIRMED (`0x649B56..0x649C73`):** `0x649A00` builds two local five-string tables, each with `0x18`-byte + string objects: `ToneBase`, `ToneA`..`ToneD` at working ESP `+0x1C0`, and `Tone_Base`, `Tone_A`..`Tone_D` + at working ESP `+0x148`. The stock strings are constructed and destroyed locally; they cannot be replaced + by placing 27 objects on the existing stack. The row index is at working ESP `+0x54`; its byte offset + (`index * 0x18`) is saved at `+0x34`. ESP here means the stable body ESP after the three register pushes, + outside temporary call arguments. +- **CONFIRMED (`0x649D12..0x649D71`, `0x649E60..0x649EB8`, `0x649F58`):** each nonempty manifest `Tone_*` + name supplies a definition Key. The builder constructs `LAS_DefaultToneKeys` and `LAS_DefaultToneMappings` + in the selected player's `CustomTone` context. It searches the supplied `Tones` collection by its actual + length (`0x64A104..0x64A385`), reading definition `Key` and `Name` (`0x64A18A`, `0x64A1CE`). A matching + definition supplies the default display name. There is no access here to the manager's registration vectors. +- **CONFIRMED (`0x64AB5B..0x64AB67`):** the outer row loop increments its logical slot index, compares it + with **5** at `0x64AB64`, and loops to `0x649CA5`. Empty slot names take the skip/cleanup path + (`0x649DF0..0x649E16`). Thus the number of emitted buttons is not necessarily the outer loop bound. +- **CONFIRMED (`0x64A483..0x64A529`, `0x64A550..0x64A8DC`):** a row becomes `toneButton%i` below page + `+0x1C4`. Its fields include `DefaultToneName`, `Label`, `ToneNameExtension` (`ToneBase` / `ToneA`..), + `ToneKey`, `ID`, `SortOrder` and `States.Default`. The ID is the button name; the profile override property + is separately formatted as `LAS_ToneCustomData_%s`. An existing custom object's `Name` overrides the Label + (`0x64A5B9..0x64A61A`). IDs are also appended to the string vectors at page `+0x214` and `+0x220` + (`0x64A94C`, `0x64AA69`). These are not evidence of an unlimited Flash viewport or working scrolling. + +### Selecting, editing and the timeline graphic + +- **CONFIRMED (`0x64BD48..0x64BE62`, `0x64BFB5..0x64C0EC`):** selection obtains the focused button with + `0x5DAF00`, reads its `ToneNameExtension` and `ToneKey`, and prepares `LAS_ToneNameBeingEdited` plus + `LAS_TempDefaultToneName` in the player's context. It walks `LAS_DefaultToneKeys` by collection length; + entries containing the selected Key add `ToneExtension` records to the edit list. The destination state + passed to `0x76DD90` is `LearnASong_SongOptions_Tone` (`0x64C18E..0x64C1AD`). This path carries strings, + rather than a switch on five numeric tone IDs. +- **CONFIRMED (`0x6492B3..0x649303`, `0x64938F..0x649483`):** the chooser's update path walks the edit list, + reads each `ToneExtension`, formats `LAS_ToneCustomData_`, removes the previous member, and + obtains the replacement from the selected custom tone (`0x649630`). It copies that replacement into the + player's context. `0x649630` reads `CustomToneName` from the focused chooser entry and searches the available + tone collection by Key (`0x6496C8..0x649813`). This establishes a context update, **not** durable per-song + save/reload behavior for E..Z. The `EditTonePlan` notification at `0x6494CD` calls the mission/achievement + path `0x4C5900`; it must not be assumed to be a profile persistence API. +- **CONFIRMED (`0x64AE1F..0x64AF03`, `0x64B03F..0x64B0D8`):** `0x64AC30` resolves the arrangement resource + by PersistentID through `0x568A50` / `0x572840`, obtains its song object at resource `+8`, and scans the song's + `+0xD0` vector in **0x104-byte records**. It matches the record's text at `+4` against `tone_base` and + `tone_a`..`tone_d`. This is separate from numeric tone changes at song `+0xDC`; widening the numeric timeline + does not widen this graphic. +- **CONFIRMED (`0x64AF09..0x64AFE5`):** the graphic's ten stack strings are **five interleaved pairs** with + pair stride `0x30`: event label followed by `ToneBase` / `ToneA`..`ToneD`. They are not two contiguous + five-string tables. The match-loop bound is 5 at `0x64B0C7`, with a second unmatched-label bound at + `0x64B0D1`. Name-table reads occur at `0x64B1D0` and `0x64B56F`; the latter is the final-block path. + Output goes to `ToneBlockObject.DataArray` with `ToneName`, `BlockStart` and `BlockEnd` + (`0x64AFFB`, `0x64B23D`, `0x64B2A2`, `0x64B35E`, `0x64B5D2`). +- **CONFIRMED (source inspection, `state.cpp:Object` / `Handle`):** native playback applies the captured + manifest E..Z objects directly. It does not consult the player's `LAS_ToneCustomData_ToneE`..`ToneZ` + context members. Eligible native Base/A..D also use the mod's direct-object path. Therefore displaying extra + buttons and letting the chooser update context would still leave audible playback ignoring those edits. + +### Native route and implementation blockers + +**HYPOTHESIS / proposed design:** own 27 rows per editor instance, identified by player, arrangement UUID, +native SNG generation and page lifetime. Include Base plus the declared nonempty A..Z names, preserving logical +letters across holes and duplicate Keys. Keep logical slot IDs separate from visible button IDs. Confirm the +resource's song `+8` against the XI1 native-load token, plus the existing captured manifest marker; a menu must +not borrow the last gameplay session's eligibility. Retain any referenced game objects for the build/edit +transaction and release them outside the loader mutex. + +Redirect both row-table reads and the loop bound through full mid-hooks behind `kRsxrGateTones`. Leave the +original five stack objects and their destructors intact; the game must never destroy mod-owned string views. +Supply all logical mappings to `LAS_DefaultToneKeys` / `LAS_DefaultToneMappings`, including hidden rows. +Extend the graphic's paired event/name source, both bounds and both name reads together. Its separate event +labels must be reconciled with native numeric E..Z changes; do not fabricate or mutate the game's SNG vector. + +**HYPOTHESIS / proposed paging:** use five physical `toneButton0`..`toneButton4` entries if the movie cannot +scroll a longer list. Adapt `arrangements/hooks.cpp`'s focus-edge Up/Down and PageUp/PageDown window movement, +root rebuilding and focus-list swapping. Keep each physical button's `ToneNameExtension`, `ToneKey` and override +property tied to the logical row; remap the `%i` button argument only, not the logical mapping arrays. Preserve +`States` across rebuilding and restore focus before a select can run. Do not reuse the arrangement page's +vtable, record offsets or UI state string. Log once on a real editor entry, not on each window rebuild: +`tones26: toneplan rows=7 (Base,A..F)` for the six-tone demo; `rows=27 (Base,A..Z)` at capacity. Sparse-slot +logs should list the actual letters instead of implying a contiguous range. + +**Historical investigation stop (before implementation):** the display-table contract is mapped, but the complete edit-to-playback contract is +not. Two pieces remain unestablished: (1) how the updated `CustomTone` context is saved/restored for the same +song/arrangement and player, including reset-to-default and shared default Keys; (2) the Tone Plan movie's +viewport, button removal/redraw and focus-state behavior during a rebuild. The executable's dynamic button +construction alone proves neither. The arrangement implementation documents movie-specific redraw behavior; +it cannot safely be copied to this different movie without establishing those contracts. The known native +playback bypass above must also be changed with explicit custom-override precedence and invalidation when the +chosen definition changes without a slot-ID change. Until then, a table-only patch fails the requested picking +and editing behavior even if its rows render. This is an unresolved integration blocker, not proof that native +extension is impossible. No production hooks, emulator entries, unit tests or user-facing completion claims +were added. The changelog's existing limitation is deliberately retained. + +To resume: trace the `CustomTone` context's per-song transfer on leaving/returning to this menu and native +session setup; establish an owned/reference-safe override resolver for `state.cpp:Object`, including Base/A..D; +then validate the five-button rebuild on the actual Tone Plan movie. Only after those contracts are known, +implement the table/count/paging hooks together and add tests for stock fallback, E/Z edits and reset, duplicate +Keys, sparse slots, same-slot replacement, native/stock/native, reopen and two players. The expected test order +is owned ABI/model tests, inactive emulator preservation, pattern/expected-byte checks, then caller build and +in-game gates. These tests have not been written or run in this design-only change. + +### Candidate anchors (not installed) + +**CONFIRMED (standard-library static scan):** each complete pattern below matches once in executable PE +sections at the stated address. These are research anchors, not entries in `sites.json` and not a complete +hook set. Bytes are shown solely as prospective short signatures. Longer signatures are needed for the two +graphic name reads: their identical 13-byte sequences match **both** `0x64B1D0` and `0x64B56F`. + +| Purpose | Expected address | Unique anchor pattern | Initial complete instruction bytes | +|---|---|---|---| +| Row-builder call | `0x64BB4C` | `E8 AF DE FF FF 85 C0 75 33 8B 16 8B 42` | `E8 AF DE FF FF` | +| Manifest-field string source | `0x649D12` | `8D BC 04 48 01 00 00 C6 84 24 30 01 00 00 00` | `8D BC 04 48 01 00 00` | +| Slot-extension string source | `0x649E60` | `8D 84 04 C0 01 00 00 8D 48 10 89 44 24 44` | `8D 84 04 C0 01 00 00` | +| Row bound and loop branch | `0x64AB64` | `83 F8 05 0F 8C 38 F1 FF FF` | `83 F8 05 0F 8C 38 F1 FF FF` | +| Graphic paired-table source | `0x64B07A` | `8D B5 18 FF FF FF 8B 95 94 FE FF FF 8B 7E 04` | `8D B5 18 FF FF FF` | +| Graphic match bound | `0x64B0C7` | `83 F8 05 72 B4 E9 AD 03 00 00` | `83 F8 05 72 B4` | +| Graphic unmatched-label bound | `0x64B0D1` | `83 BD A8 FE FF FF 05 0F 83 A0 03 00 00` | `83 BD A8 FE FF FF 05` | + +**HYPOTHESIS (player navigation; not tested live here):** Learn a Song -> choose the native demo song and +arrangement -> Tone Plan -> select a tone row -> the stock tone chooser. If navigation differs, confirm by +identifying the movie above and the destination `LearnASong_SongOptions_Tone`; do not substitute the F9 overlay +or the general Tone Designer. The exact string returned by `RsxrUi_ReadState` for the Tone Plan page has not +been established here; the registration name must not be used as an input gate without checking it. No +`tones26: toneplan` line is emitted by the current build: the lines above are acceptance targets for the future +implementation. + +**CONFIRMED (handoff checks):** all seven candidate anchors above were checked again for unique executable-section +matches, exact initial bytes and complete instruction spans. Relative documentation file links resolve and +`git diff --check` passes. These checks do not validate movie behavior, profile persistence or live hooking. +Builds, uv, pytest, MkDocs and in-game tests were not run; the brief delegates the executable gates to the caller. + +### Demo-first editor implementation + +2026-11-17, milestone 3 part 2. Implementation is saved but has not been built or executed in the game. +The brief forbids build, uv and pytest; native/emulator tests are added for the caller to run. + +- **CONFIRMED (static, `0x64BB4C`, `0x649D12`, `0x649E60`, `0x64AB64`):** the row-builder wrap passes the + current Attributes object to `PlanSlots`. Only the internal native manifest marker `RsxrToneSlots=26` plus + a nonempty E..Z field enables its 27-slot loop. There is no dependence on the last gameplay session. The two + name reads use mod-owned, stable `0x18`-byte game-string views for Base/A..Z and `Tone_Base`/`Tone_A`..`Tone_Z`. + All five original stack strings in each table and their destructors remain untouched. The stock builder skips + empty names and creates every row, mapping, button ID, SortOrder and focus-vector entry itself. Nested builder + calls restore the outer mask; unmarked and marked-without-extras arrangements replay the stock instructions. +- **CONFIRMED (static movie inspection; `0x6498D0` identifies the movie):** the user's extracted + `las_songoptionstoneplan.gfx` has SHA256 + `46761d713d3dcdcd090fea5b56ed863b6f5c596398d125fad3c3e3b7f3ed2d03`. + DoInitAction sprite 25's `SongOptionsTonePlanScene.InitButtons` calls its parent. Sprite 22's + `SongOptionsScene2.PopulateButtons` loops over `mSortedData.length`, creates/updates each button by its ID + and sets it visible; there is **no fixed five-button set**. Its `BuildButtonDataObject` computes Y from + `270 + (SortOrder + 1) * 35`, with font size 30. Thus arbitrary counts are instantiated, but the layout + does not fit 27 rows in the viewport. No paging, scrolling, movie mutation or row compaction is implemented. + **HYPOTHESIS:** E/F in the six-tone demo remain visible and selectable with stock layout; full plans and sparse + high-letter plans overflow the viewport and need a later layout change. Live focus/rendering is untested. +- **CONFIRMED (static, `0x64BE44..0x64C1AD`, `0x6492B3..0x649483`):** the existing selection handler reads + the supplied extension/Key, builds `LAS_ToneNameBeingEdited` using `LAS_DefaultToneKeys`, and opens the stock + chooser. Its update loop writes `LAS_ToneCustomData_ToneE`..`ToneZ` using the same object/property format as + A..D. `TonePlanEdit` only logs this decision; it does not replace the string-based selection/edit code. + Shared default Keys retain the game's behavior of editing all matching extensions. +- **CONFIRMED (static, `0x464BAA..0x464C05`, `0x465259`, `0x41B310..0x41B498`):** automatic stock A playback + resolves `CustomTone//LAS_ToneCustomData_ToneA` through virtual `+18h` then `+5Ch`, with the + manifest object as fallback, and passes the chosen object to full apply `0x7D3D50`. Registration also reads + this property (`0x7E9B7E..0x7E9C17`); Base uses the corresponding `ToneBase` property (`0x7DEED8..0x7DEF46`). + `game.cpp:Override` now performs that same retained lookup for all 27 slots, only after native playback + eligibility succeeds. `state.cpp:Handle` detects same-slot object replacement or removal, retains the last + applied custom object to prevent dangling identity comparisons, and restores the manifest default on removal. + Stock-only sessions return to stock before the new lookup. References are released outside the loader mutex. +- **HYPOTHESIS:** the game's context transfer saves/restores E..Z across leaving/reopening an arrangement, + changing songs and restarting the game exactly as it does A..D. This change uses the stock chooser's property + writer and stock playback's property consumer; it adds no separate persistence store. Durable profile behavior, + chooser reset and co-op must be checked live. The `0x64AC30` timeline graphic still reads its stock textual + five-pair table; native numeric E..Z events are not added to that graphic by this demo change. + +Decision logs (once per editor build, accepted extra-slot selection, or changed playback selection/override): + +```text +tones26: toneplan rows=7 (Base,A,B,C,D,E,F used) +tones26: toneplan edit slot=E key='...' stock chooser +tones26: override slot=E key='...' applied +tones26: override slot=E key='...' none +``` + +The last line means no custom object was applied (default fallback or rejected apply). Repeated polling and +forced refresh of an unchanged successful selection do not repeat override decisions. Missing/invalid IDs +retain the existing bounded rejection logs. A same-Key replacement still reapplies because its object changed. + +All six new patterns below matched exactly once in executable PE sections; expected bytes matched, and +Capstone confirmed complete instruction spans. This is a direct static check, not the full sitecheck gate. +References are never written. All six belong to the existing optional Tones failure group. + +| ID | Expected address | Pattern | Expected bytes | +|---|---|---|---| +| `TonePlanBuild` | `0x64BB4C` | `E8 AF DE FF FF 85 C0 75 33 8B 16 8B 42` | `E8 AF DE FF FF` | +| `TonePlanField` | `0x649D12` | `8D BC 04 48 01 00 00 C6 84 24 30 01 00 00 00` | `8D BC 04 48 01 00 00` | +| `TonePlanExtension` | `0x649E60` | `8D 84 04 C0 01 00 00 8D 48 10 89 44 24 44` | `8D 84 04 C0 01 00 00` | +| `TonePlanBound` | `0x64AB64` | `83 F8 05 0F 8C 38 F1 FF FF` | `83 F8 05 0F 8C 38 F1 FF FF` | +| `TonePlanEdit` | `0x64BE44` | `8D 4C 24 0C 51 B9 D8 50 1B 01 E8 1D 06 23 00` | `8D 4C 24 0C 51` | +| `ToneContext` | `0x464B9B` | `8B 0D CC 04 36 01 8B 49 14 50 8D 54 24 24` (offset 2) | `CC 04 36 01` | + +Native tests cover name-view layout, sparse E/Z, invalid/missing marker, no extras, disabled feature, source/bound +redirection, nested stock fallback, per-player retained context lookup, repeated polling, same-Key replacement, +removal/default reset, Base/A overrides and stock transition cleanup. Emulator tests add inactive row sites and +the builder's argument/result/stack preservation. The reference/export lists and registry ref count are updated; +`emu_harness.py` remains below 800 lines. Caller gates and the six-tone demo are still required. + +**CONFIRMED (static verification):** direct clang-format, the existing blank-line/layout tools and Ruff passed; +changed Python files parse, relative documentation file links resolve, and `git diff --check` passes. +`emu_harness.py` has 766 lines. The native and emulator tests were not executed. No build, uv, pytest, game-folder +write, asset export, generated-header edit or commit was performed. + +## Sites + +The full patterns and exact displaced bytes are also in `sites.json`; references are never written. + +| ID | Expected site | Kind | Pattern | Expected bytes | +|---|---|---|---|---| +| `ToneRegister` | `0x7E9AF0` | `jmp` | `55 8B EC 83 EC 08 53 8B 5D 08 80 BB A6 05 00 00 01 56 57 0F 84 4F 03 00 00` | `55 8B EC 83 EC 08` | +| `ToneRegisterCall` | `0x7E9B69` | `callref` | `E8 72 D1 FE FF 8B 4D FC 85 C9 0F 84 E8 02 00 00` | `E8 72 D1 FE FF` | +| `ToneResourceDestroy` | `0x5A876D` | `callref` | `E8 7E 07 00 00 83 C4 08 8D 46 08 E8 E3 3A 2B 00` | `E8 7E 07 00 00` | +| `ToneLoad` | `0x56774C` | `jmp` | `89 85 5C FC FF FF 85 C0 0F 84 76 01 00 00 8B C8` | `89 85 5C FC FF FF` | +| `ToneAuto` | `0x464ADD` | `call` | `E8 ?? ?? ?? ?? 84 C0 0F 94 C3 85 FF 74 17 8D 47` | `E8 CE 52 0F 00` | +| `ToneSetup` | `0x7DF1CF` | `call` | `E8 DC AB D7 FF 84 C0 74 0B C6 44 24 13 01 EB 09` | `E8 DC AB D7 FF` | +| `ToneSeek` | `0x7DF485` | `call` | `E8 26 A9 D7 FF 84 C0 74 0F C6 44 24 13 01 EB 0D` | `E8 26 A9 D7 FF` | +| `ToneResume` | `0x7ECAB7` | `call` | `E8 F4 D2 D6 FF 84 C0 74 0B C6 44 24 13 01 EB 09` | `E8 F4 D2 D6 FF` | +| `ToneOverride` | `0x474BCE` | `call` | `E8 DD 51 0E 00 84 C0 74 0B C6 44 24 13 01 EB 09` | `E8 DD 51 0E 00` | +| `ToneRefresh` | `0x7DF400` | `jmp` | `55 8B EC 83 E4 F8 83 EC 34 A1 ?? ?? ?? ?? 33 C4 89 44 24 30 8A 45 0C 53 8B 5D 08 56 C7 44 24 10 00 00 00 00 80 BB 44 05 00 00 01 57` | `55 8B EC 83 E4 F8` | +| `ToneApply` | `0x465259` | `callref` | `8B 45 08 8B 40 0C 8B 40 08 8B 0D ?? ?? ?? ?? 6A 03 50 51 E8 ?? ?? ?? ??` | `E8 F2 EA 36 00` | +| `ToneManager` | `0x465251` | `ref` | `8B 45 08 8B 40 0C 8B 40 08 8B 0D ?? ?? ?? ?? 6A 03 50 51 E8 ?? ?? ?? ??` | `2C 04 36 01` | + +## Caller gates and live demo + +Run `scripts/format.ps1`, `build.ps1`, `uv run pytest tools/tests -q`, `uv run python tools/sitecheck.py`, +`uv run python tools/check_exports.py bin/Release/dinput8.dll`, and the strict MkDocs build. +New native tests cover slot selection, optional-group isolation, the actual apply bridge ABI with an owned +stand-in, duplicate Key rejection, manifest/SNG gating, stale manifest replacement, independent player objects, +native reload generations, and the automatic callback's F/sentinel suppression. Python tests cover +native/stock/native timeline preservation and the six-tone demo's output. They have not been executed here. + +Standard-library static checks also parsed the three changed Python files, checked changed-source whitespace +and local include paths, checked the edited documentation's relative file links, and counted the touched +manifest helpers below 100 source lines. `git diff --check` passed. These do not replace the caller gates. + +Generate the demo using `tools/tone_demo.py` with an author-owned native package and six distinct, complete +existing Keys. It writes A..F and 20 chronological changes; it does not generate Ubisoft assets or definitions. +The caller must hear six different sounds and inspect lines of the form +`tones26: arrangement=... player=0 id=4 key='...' applied` and the corresponding `id=5` line. +Before the first event expect `id=26` (Base). Check all A..F transitions, seek before/on/after E and F, +Riff Repeater rewind, restart, pause/tuner/resume, two players with different definitions, and leaving the native +song for stock content. Missing/duplicate Keys and invalid IDs must log `rejected` without switching sounds. + +## Open risks and follow-ups + +- **HYPOTHESIS:** the runtime JSON lifetime and apply ABI behave as the static evidence indicates; live execution, + audibility, asset availability/preload, stack/register preservation and co-op still require the owner's demo. +- **HYPOTHESIS:** the five accessor callers plus forced refresh cover all practical seek/restart/pause paths. +- Native sessions with extra slots now prefer the stock per-player Tone Plan custom objects, including A..D/Base. + Durable profile transfer, emulated-bass/multiplayer precedence, and long-plan layout remain follow-ups; + stock-only sessions keep stock code. +- Retained manifest objects are cached per arrangement until replacement or shutdown. SNG tokens are removed on + address reuse, not at destruction; bounded cache eviction/destructor cleanup is a hardening follow-up. +- Native eligibility follows the independently validated native manifest and SNXR body; no new archive-owner + association is introduced. A manually assembled PSAR containing both native payloads is not distinguished. +- **CONFIRMED (2026-11-17, M3 build, owner's game):** the stock Tone Plan editor has no visible entry on PC + Remastered. The Learn a Song song page (arrow keys move nothing; Ctrl opens Role/Input), the in-song pause menu + (resume, restart, tuner, mixer, chords, quit), Riff Repeater and its advanced settings offer no tone item. In the + exe, the only reference to the `LearnASong_SongOptions_Tone` state is the Tone Plan select handler `0x64BBE0` + (vtable slot at `0x11B5468`), and `EditTonePlan` is referenced only from the chooser (`0x649210`). The menus open + each other; nothing found opens the first one. **HYPOTHESIS:** these menus are console-era leftovers that the + Remastered movies never open. So the editor rows/edit/override code is untested in game. A player-facing tone + edit would need our own entry (pushing that state) or a Sound Designer route. +- Run log the same day: the 6-tone chart still registers E,F (`register player=0 slot=5 key='Cleanalt' ok`, + `slot=6 key='Mod' ok`); the override path logs `override slot=Base key='Clean' none` and + `override slot=A key='Clean' none` (no stored override, stock chooser unreachable). diff --git a/docs/release/CHANGELOG.md b/docs/release/CHANGELOG.md index 5fb4442..c46c430 100644 --- a/docs/release/CHANGELOG.md +++ b/docs/release/CHANGELOG.md @@ -4,6 +4,14 @@ [README](../../README.md) · [Install](INSTALL.md) · [Settings](SETTINGS.md) · [Charting](CHARTING.md) · **Changelog** +## Unreleased + +### Added + +- Charts in the native format can use 26 tone slots, A through Z, plus Base. The game itself only has Base and A + through D. Tone changes to the new slots work like the stock ones. A test tool builds a chart with six tones and + 20 tone changes from your own package. + ## 1.0.0-beta.5 ### Changed diff --git a/docs/release/NATIVE-FORMAT.md b/docs/release/NATIVE-FORMAT.md index 5f8f8d3..4c14679 100644 --- a/docs/release/NATIVE-FORMAT.md +++ b/docs/release/NATIVE-FORMAT.md @@ -73,6 +73,46 @@ entry in the HSAN header file: - Stock arrangements and arrangements without a `Tuning`, such as vocals, have no marker. All other fields keep their stock meaning. +## Tone slots A through Z + +A native arrangement can name up to 26 tone-change destinations, `Tone_A` through `Tone_Z`, plus its separate +`Tone_Base`. Put the extra names in the arrangement's `Attributes` next to the stock names: + +```json +"Tone_Base": "clean", +"Tone_A": "clean", +"Tone_B": "crunch", +"Tone_C": "drive", +"Tone_D": "lead", +"Tone_E": "ambient", +"Tone_F": "fuzz" +``` + +Keep complete definitions in `Attributes.Tones` in the full manifest, as for stock tones. Each name must match +exactly one definition's `Key`, compared without case sensitivity. An unused slot may be absent or an empty +string. Names must fit in 255 UTF-8 bytes. Use the same slot names in the manifest JSON and its HSAN entry. +Do not write `RsxrToneSlots`: the loader generates that internal field from valid native attributes. + +The SNG tone section retains its stock binary layout: a `u32` event count followed by records containing +`float32 time` and `u32 id`, eight bytes each. Raw IDs `0` through `25` mean A through Z. In particular, ID `5` +means F. Base is selected before the first event; it has no timeline ID. Times must be finite, nonnegative and +chronological. The game selects the last event strictly earlier than the current song time. There is no limit +of 26 changes: only the number of named destinations is limited. + +Extra slots require both native manifest attributes and an `SNXR` chart, with at least one nonempty extra +slot E through Z. Stock arrangements and native arrangements without extra slots use stock tone handling. +A missing or ambiguous definition or an out-of-range ID is rejected and leaves the previous sound active. +The stock Tone Plan editor still shows Base and A through D; paging for E through Z is a follow-up. + +To prepare a six-tone, 20-change demo from your own native package and six existing definitions, run: + +```powershell +python tools/tone_demo.py SOURCE.psarc DEMO_rsxr_p.psarc --arrangement PERSISTENT_ID --keys KEY_A KEY_B KEY_C KEY_D KEY_E KEY_F +``` + +The first change is at 5 seconds, then every 3 seconds; `--start` and `--interval` change those times. +Choose times within your song and run the generator outside the game folder. + ## Charts The SNG wrapper is the plain-package wrapper. All its numeric values and the inflated body are little-endian. diff --git a/mkdocs.yml b/mkdocs.yml index 67f3cc7..11f812f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -141,3 +141,4 @@ nav: - Code structure: docs/agents/code-structure.md - Hook sites: docs/agents/hook-sites.md - Docs and testing: docs/agents/docs-and-testing.md + - Tone slot research: docs/agents/tones-notes.md diff --git a/sites.json b/sites.json index 175b54d..d6e8904 100644 --- a/sites.json +++ b/sites.json @@ -1,6 +1,18 @@ { "pe_checksum": "0x00B13D7C", "sites": [ + {"id": "ToneRegister", "kind": "jmp", "length": 6, "pattern": "55 8B EC 83 EC 08 53 8B 5D 08 80 BB A6 05 00 00 01 56 57 0F 84 4F 03 00 00", "offset": 0, "expect": "55 8B EC 83 EC 08", "note": "CONFIRMED static 0x7E9AF0: stdcall(session), ret 4 at 0x7E9E5E. Wrap after stock Base/A..D registration requests native E..Z resources in an isolated mod store; never replaces the live manager store."}, + {"id": "ToneRegisterCall", "kind": "callref", "pattern": "E8 72 D1 FE FF 8B 4D FC 85 C9 0F 84 E8 02 00 00", "offset": 0, "expect": "E8 72 D1 FE FF", "note": "CONFIRMED static 0x7E9B69 -> 0x7D6CE0: EAX player, stack(manager, owned definition, slot), ret 0Ch. Void resource registration; the private view maps extra slots without changing stock bounds/stride."}, + {"id": "ToneResourceDestroy", "kind": "callref", "pattern": "E8 7E 07 00 00 83 C4 08 8D 46 08 E8 E3 3A 2B 00", "offset": 0, "expect": "E8 7E 07 00 00", "note": "CONFIRMED static 0x5A876D -> 0x5A8EF0: cdecl(record end, record begin); destroys nested resource vectors and frees game allocations. Used only on mod-owned registration records."}, + {"id": "ToneLoad", "kind": "jmp", "length": 6, "pattern": "89 85 5C FC FF FF 85 C0 0F 84 76 01 00 00 8B C8", "offset": 0, "expect": "89 85 5C FC FF FF", "note": "CONFIRMED static 0x56774C: EAX Attributes.Tones; parent arrangement [EBP+0Ch] (resolve Attributes child), arrangement identity [EBP-3A0h]. Capture native E..Z definitions in side tables."}, + {"id": "ToneAuto", "kind": "call", "pattern": "E8 ?? ?? ?? ?? 84 C0 0F 94 C3 85 FF 74 17 8D 47", "offset": 0, "expect": "E8 CE 52 0F 00", "note": "CONFIRMED static 0x464ADD: automatic tone lookup 0x559DB0, ESI session, stdcall(time, out id). Wrap preserves stock sessions; extended sessions own Base and A..Z."}, + {"id": "ToneSetup", "kind": "call", "pattern": "E8 DC AB D7 FF 84 C0 74 0B C6 44 24 13 01 EB 09", "offset": 0, "expect": "E8 DC AB D7 FF", "note": "CONFIRMED static 0x7DF1CF: setup tone lookup, EBX session; stdcall(time, out id)."}, + {"id": "ToneSeek", "kind": "call", "pattern": "E8 26 A9 D7 FF 84 C0 74 0F C6 44 24 13 01 EB 0D", "offset": 0, "expect": "E8 26 A9 D7 FF", "note": "CONFIRMED static 0x7DF485: refresh tone lookup, EBX session; stdcall(time, out id). Force path covered by ToneRefresh."}, + {"id": "ToneResume", "kind": "call", "pattern": "E8 F4 D2 D6 FF 84 C0 74 0B C6 44 24 13 01 EB 09", "offset": 0, "expect": "E8 F4 D2 D6 FF", "note": "CONFIRMED static 0x7ECAB7: alternate session tone lookup, EBX session; stdcall(time, out id)."}, + {"id": "ToneOverride", "kind": "call", "pattern": "E8 DD 51 0E 00 84 C0 74 0B C6 44 24 13 01 EB 09", "offset": 0, "expect": "E8 DD 51 0E 00", "note": "CONFIRMED static 0x474BCE: override tone lookup, EBX session; stdcall(time, out id)."}, + {"id": "ToneRefresh", "kind": "jmp", "length": 6, "pattern": "55 8B EC 83 E4 F8 83 EC 34 A1 ?? ?? ?? ?? 33 C4 89 44 24 30 8A 45 0C 53 8B 5D 08 56 C7 44 24 10 00 00 00 00 80 BB 44 05 00 00 01 57", "offset": 0, "expect": "55 8B EC 83 E4 F8", "note": "CONFIRMED static 0x7DF400: stdcall(session, force), ret 8 at 0x7DF697. Wrap after force=true restores the native timeline selection after the stock Base refresh."}, + {"id": "ToneApply", "kind": "callref", "pattern": "8B 45 08 8B 40 0C 8B 40 08 8B 0D ?? ?? ?? ?? 6A 03 50 51 E8 ?? ?? ?? ??", "offset": "0x13", "expect": "E8 F2 EA 36 00", "note": "CONFIRMED static 0x465259: full-object apply 0x7D3D50; ESI=&definition, stdcall(manager, player, 3). Never writes the stock registration grid."}, + {"id": "ToneManager", "kind": "ref", "pattern": "8B 45 08 8B 40 0C 8B 40 08 8B 0D ?? ?? ?? ?? 6A 03 50 51 E8 ?? ?? ?? ??", "offset": "0xB", "expect": "2C 04 36 01", "note": "CONFIRMED static 0x465251: address of manager pointer 0x136042C used by stock full-object apply."}, {"id": "MenuMovieSetup", "kind": "jmp", "length": 6, "pattern": "55 8B EC 83 E4 F8 83 EC 14 56 8B F1 80 BE 21 01 00 00 00", "offset": 0, "expect": "55 8B EC 83 E4 F8", "note": "CONFIRMED 0xC167A0: remember menu movie and owner before setup; ECX = movie"}, {"id": "MenuLoadUpdate", "kind": "jmp", "length": 6, "pattern": "55 8B EC 83 E4 F8 83 EC 14 8B 45 08 53 8B 58 0C 83 C3 04", "offset": 0, "expect": "55 8B EC 83 E4 F8", "note": "CONFIRMED 0x59DB80: load-group update, stack argument = loader; game-thread movie retries"}, {"id": "MenuMovieResult", "kind": "jmp", "length": 5, "pattern": "8D 8E 8C 00 00 00 8D 71 10 8B C1 39 71 14 74 02 8B 01 3B 06 74 38 8B 55 08 6A 00 83 EC 08 8B C4 89 10 8B 55 0C 89 50 04 83 EC 18 8B C4 8D 50 10 89 02 89 50 14 8B 16 39 71 14 74 02 8B 09 52 51 E8 ?? ?? ?? ?? 8B 07 8B 50 3C 8B CF FF D2 5F 5E 8B E5 5D C2 08 00", "offset": "0x4E", "expect": "5F 5E 8B E5 5D", "note": "CONFIRMED 0xC19335: movie request epilogue after the asset locator call; AL = accepted, ESI = movie + 9Ch"}, @@ -687,6 +699,12 @@ {"id": "CMIX", "kind": "jmp", "length": 5, "pattern": "8D 04 52 03 C0 D9 94 81 90 08 00 00 8D 94 52 14 01 00 00 D9 94 81 94 08", "offset": "0x0", "expect": "8D 04 52 03 C0", "note": "CONFIRMED 00518CA4: native colour publication / bounded fallback"}, {"id": "CMINIT", "kind": "jmp", "length": 6, "pattern": "5F 8B C6 5B 8B E5 5D C3 CC CC CC CC CC CC CC CC CC CC CC 55 8B EC 56 8B", "offset": "0x0", "expect": "5F 8B C6 5B 8B E5", "note": "CONFIRMED 0051853D: native colour publication / bounded fallback"}, {"id": "CMBUILD", "kind": "jmp", "length": 6, "pattern": "FF 5E 5B 8B E5 5D C3 CC CC CC CC CC CC CC CC CC CC CC CC CC CC 55 8B EC 53", "offset": "0x1", "expect": "5E 5B 8B E5 5D C3", "note": "CONFIRMED 0051966C: native colour publication / bounded fallback"}, - {"id": "CMFALL", "kind": "jmp", "length": 5, "pattern": "8B 44 95 E4 56 C7 45 E0 00 00 00 00 83 FA 06 73 5A 8B 35 8C F5 35 01 8B", "offset": "0x0", "expect": "8B 44 95 E4 56", "note": "CONFIRMED 0075835A: native colour publication / bounded fallback"} + {"id": "CMFALL", "kind": "jmp", "length": 5, "pattern": "8B 44 95 E4 56 C7 45 E0 00 00 00 00 83 FA 06 73 5A 8B 35 8C F5 35 01 8B", "offset": "0x0", "expect": "8B 44 95 E4 56", "note": "CONFIRMED 0075835A: native colour publication / bounded fallback"}, + {"id": "TonePlanBuild", "kind": "call", "pattern": "E8 AF DE FF FF 85 C0 75 33 8B 16 8B 42", "offset": 0, "expect": "E8 AF DE FF FF", "note": "CONFIRMED static 0x0064bb4c: Wrap row construction with the selected Attributes marker and extra-slot mask; ret 8."}, + {"id": "TonePlanField", "kind": "jmp", "pattern": "8D BC 04 48 01 00 00 C6 84 24 30 01 00 00 00", "offset": 0, "expect": "8D BC 04 48 01 00 00", "note": "CONFIRMED static 0x00649d12: Redirect only the manifest-field name view; original local strings and cleanup stay stock.", "length": 7}, + {"id": "TonePlanExtension", "kind": "jmp", "pattern": "8D 84 04 C0 01 00 00 8D 48 10 89 44 24 44", "offset": 0, "expect": "8D 84 04 C0 01 00 00", "note": "CONFIRMED static 0x00649e60: Redirect only the slot-extension view; stock mappings, row fields and chooser identity consume it.", "length": 7}, + {"id": "TonePlanBound", "kind": "jmp", "pattern": "83 F8 05 0F 8C 38 F1 FF FF", "offset": 0, "expect": "83 F8 05 0F 8C 38 F1 FF FF", "note": "CONFIRMED static 0x0064ab64: Native extra arrangements compare against 27 and branch to 0x649CA5; all other calls replay CMP 5/JL.", "length": 9}, + {"id": "TonePlanEdit", "kind": "jmp", "pattern": "8D 4C 24 0C 51 B9 D8 50 1B 01 E8 1D 06 23 00", "offset": 0, "expect": "8D 4C 24 0C 51", "note": "CONFIRMED static 0x0064be44: Observe the valid ToneNameExtension at ESP+4Ch and ToneKey at ESP+94h before stock edit-list construction.", "length": 5}, + {"id": "ToneContext", "kind": "ref", "pattern": "8B 0D CC 04 36 01 8B 49 14 50 8D 54 24 24", "offset": 2, "expect": "CC 04 36 01", "note": "CONFIRMED static 0x00464b9b: Resolve the player-context manager global used by stock Tone Plan override playback at 0x464BDD."} ] } diff --git a/src/features/native/hooks.cpp b/src/features/native/hooks.cpp index 2d0e6e6..2ad5a4c 100644 --- a/src/features/native/hooks.cpp +++ b/src/features/native/hooks.cpp @@ -1,6 +1,7 @@ // The three hooks that translate a native package (native.h) while the game loads it. Everything after them (the // game, XB1, the N-slot chord data, the manifest readers of the tuner and C-lite) sees the current form only. #include "features/native/native.h" +#include "features/tones/tones.h" #include "model/nativemanifest.h" #include "model/nativesng.h" #include "platform/log.h" @@ -117,7 +118,15 @@ extern "C" void __cdecl RsxrNative_OnJson(const char** cursor) { // cannot be converted continues at the loader's own failure exit instead (the target of the `jne rel32` that ends 3 // bytes before the site; it destroys both streams and returns false), with the site's stack. Must not throw. extern "C" __declspec(dllexport) void __cdecl Rsxr_Mid_XI1(RsxrMid::Context& c) { - if (RsxrNative_OnBody(RsxrMid::Dword(c.esp + 0x24), RsxrMid::Dword(c.esp + 0x2C))) { + const uint32_t buffer = RsxrMid::Dword(c.esp + 0x24); + const uint32_t size = RsxrMid::Dword(c.esp + 0x2C); + const bool native = + size >= 4 && Rsxr_SafeRead(reinterpret_cast(uintptr_t(buffer)), 0) == 0x52584E53u; + const bool accepted = RsxrNative_OnBody(buffer, size); + + RsxrTones_SongLoaded(c.ebx, accepted && native); + + if (accepted) { return; } diff --git a/src/features/tones/game.cpp b/src/features/tones/game.cpp new file mode 100644 index 0000000..abc18a3 --- /dev/null +++ b/src/features/tones/game.cpp @@ -0,0 +1,193 @@ +// Game JSON operations and the stock full-object apply bridge. No registration grid writes. +#include "features/tones/game.h" +#include "features/tones/toneplan.h" +#include "model/gamestring.h" +#include "platform/midhook.h" +#include "platform/safecopy.h" +#include "platform/seh.h" +#include +#include + +extern "C" uintptr_t g_rsxr_tone_apply, g_rsxr_tone_manager, g_rsxr_tone_context; + +namespace rsxrtones { +namespace { +using Unary = uint32_t(__thiscall*)(void*); +using Find = uint32_t(__thiscall*)(void*, const char*); + +struct Bridge { + uint32_t definition = 0, esi = 0, ret = 0; +}; + +thread_local Bridge g_bridge; + +void ApplyDone(RsxrMid::Context& c) { + c.esi = g_bridge.esi; + c.jump = g_bridge.ret; +} + +RsxrMid::CallIn g_applyDone{&ApplyDone, RsxrMid::Mode::Full}; + +uint32_t Virtual(uint32_t object, size_t offset) { + const uint32_t address = Read(Read(object), offset); + if (!object || !address) { + return 0; + } + + __try { + return reinterpret_cast(address)(reinterpret_cast(object)); + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + return 0; + } +} + +uint32_t Member(uint32_t object, const char* key, size_t offset = 0x14) { + const uint32_t address = Read(Read(object), offset); + if (!object || !address) { + return 0; + } + + __try { + return reinterpret_cast(address)(reinterpret_cast(object), key); + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + return 0; + } +} + +// CONFIRMED: 0x7D3D64 reads [ESI]; ret 0Ch. Stack = manager, player, activation kind (stock uses 3). +void ApplyEntry(RsxrMid::Context& c) { + // The game's custom ABI takes ESI as input and leaves it untouched. Restore the C++ caller's ESI after ret 0Ch. + g_bridge.esi = c.esi; + g_bridge.ret = RsxrMid::Dword(c.esp); + const uint32_t done = static_cast(g_applyDone.Entry()); + + if (!Rsxr_SafeStore(reinterpret_cast(uintptr_t(c.esp)), &done, sizeof done)) { + c.eax = 0; + RsxrMid::Ret(c, 12); + return; + } + + c.esi = static_cast(reinterpret_cast(&g_bridge.definition)); + c.jump = static_cast(g_rsxr_tone_apply); +} + +RsxrMid::CallIn g_apply{&ApplyEntry, RsxrMid::Mode::Full, 12}; +} // namespace + +uint32_t Read(uint32_t base, size_t offset) { + return Rsxr_SafeRead(reinterpret_cast(uintptr_t(base)), offset); +} + +uint32_t Attributes(uint32_t arrangement) { + // CONFIRMED: 0x889CA0 resolves an object member through virtual +18h, then +5Ch. + return Virtual(Member(arrangement, "Attributes", 0x18), 0x5C); +} + +bool Name(uint32_t attributes, const char* key, char* text, size_t size) { + // CONFIRMED: manifest reader 0x8899F0 uses virtual +60h, then value+8 -> game string. + // +64h belongs to the automatic consumer's different JSON access path (0x465119). + const uint32_t value = Virtual(Member(attributes, key), 0x60); + + return value && rsxr::ReadGameString(reinterpret_cast(uintptr_t(Read(value, 8))), text, size); +} + +bool Reference(uint32_t object, bool retain) { + const uint32_t address = Read(Read(object), retain ? 0 : 4); + if (!object || !address) { + return false; + } + + __try { + reinterpret_cast(address)(reinterpret_cast(object)); + return true; + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + return false; + } +} + +uint32_t Definition(uint32_t collection, const char* key) { + // CONFIRMED: 0x7D3790 scans the JSON collection at +10h/+14h, unwraps each value through +34h, + // compares Key case-insensitively, then returns the canonical object through virtual +5Ch. + const uint32_t begin = Read(collection, 0x10), end = Read(collection, 0x14); + if (!begin || end < begin || (end - begin) % 4 || (end - begin) / 4 > 4096) { + return 0; + } + + uint32_t result = 0; + bool matched = false; + + for (uint32_t at = begin; at < end; at += 4) { + uint32_t node = Read(at); + const uint32_t wrapped = Virtual(node, 0x34); + + if (wrapped) { + node = Read(Read(wrapped, 0xC), 8); + + if (!node) { + node = Read(wrapped, 0x10); + } + } + + char name[256]{}; + + if (!Name(node, "Key", name, sizeof name) || _stricmp(name, key)) { + continue; + } + + if (matched) { + return 0; // ambiguous Key: refuse rather than choose a definition by collection order + } + + matched = true; + result = Virtual(node, 0x5C); + } + + return result && Reference(result, true) ? result : 0; +} + +bool Apply(uint32_t object, uint32_t player) { + const uintptr_t entry = g_apply.Entry(); + const uint32_t manager = Read(static_cast(g_rsxr_tone_manager)); + if (!entry || !g_applyDone.Entry() || !g_rsxr_tone_apply || !object || !manager || player >= 2) { + return false; + } + + const Bridge previous = g_bridge; + bool applied = false; + + g_bridge.definition = object; + + __try { + applied = reinterpret_cast(entry)(manager, player, 3) != 0; + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + applied = false; + } + + g_bridge = previous; + + return applied; +} + +uint32_t Override(uint32_t player, uint32_t slot) { + const char* extension = SlotExtension(slot); + if (player >= 2 || !extension) { + return 0; + } + + // CONFIRMED: 0x41B310 resolves CustomTone/ from manager+14h's context at +20h. + // Stock playback 0x464BDD and registration 0x7E9B83 then resolve the slot member through +18h/+5Ch. + uint32_t context = Read(Read(Read(static_cast(g_rsxr_tone_context)), 0x14), 0x20); + + context = Virtual(Member(context, "CustomTone", 0x18), 0x5C); + const char playerKey[2] = {static_cast('0' + player), 0}; + + context = Virtual(Member(context, playerKey, 0x18), 0x5C); + char property[64]{}; + + strcpy_s(property, "LAS_ToneCustomData_"); + strcat_s(property, extension); + const uint32_t object = Virtual(Member(context, property, 0x18), 0x5C); + + return object && Reference(object, true) ? object : 0; +} +} // namespace rsxrtones diff --git a/src/features/tones/game.h b/src/features/tones/game.h new file mode 100644 index 0000000..0fce083 --- /dev/null +++ b/src/features/tones/game.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include + +namespace rsxrtones { +uint32_t Read(uint32_t base, size_t offset = 0); +uint32_t Attributes(uint32_t arrangement); +bool Name(uint32_t attributes, const char* key, char* text, size_t size); +uint32_t Definition(uint32_t collection, const char* key); +// Retained canonical object from CustomTone//LAS_ToneCustomData_, or zero. +uint32_t Override(uint32_t player, uint32_t slot); +bool Reference(uint32_t object, bool retain); +bool Apply(uint32_t object, uint32_t player); +} // namespace rsxrtones diff --git a/src/features/tones/hooks.cpp b/src/features/tones/hooks.cpp new file mode 100644 index 0000000..27612fb --- /dev/null +++ b/src/features/tones/hooks.cpp @@ -0,0 +1,95 @@ +#include "features/tones/game.h" +#include "features/tones/state.h" +#include "features/tones/tones.h" +#include "platform/log.h" +#include "platform/midhook.h" +#include "platform/safecopy.h" + +namespace { +constexpr RsxrMid::Wrap kTimeline{2}; +constexpr RsxrMid::Wrap kRefresh{2}; + +void TimelineAfter(RsxrMid::Context& c, bool automatic) { + auto& frame = RsxrMid::Frame(c, kTimeline); + const uint32_t session = frame.user; + const bool event = (c.eax & 0xFF) != 0; + const uint32_t raw = rsxrtones::Read(frame.Arg(1)); + const RsxrMid::GameFcw fcw(c); + + if (rsxrtones::Handle(session, event, raw, !automatic)) { + // Own all selections in an extended session. UINT_MAX has no stock switch case; success keeps the + // other consumers out of their Base fallback. F (5) and Base (26) never enter the stock sentinel logic. + const uint32_t ignored = rsxrtones::kInvalid; + + if (Rsxr_SafeStore(reinterpret_cast(uintptr_t(frame.Arg(1))), &ignored, sizeof ignored)) { + c.eax = (c.eax & 0xFFFFFF00u) | 1u; + } + } +} +} // namespace + +// 0x56774C: EAX = Attributes.Tones collection, [EBP+0Ch] = parent arrangement, [EBP-3A0h] = UUID. +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneLoad(RsxrMid::Context& c) { + rsxrtones::Identity id; + const RsxrMid::GameFcw fcw(c); + + if (Rsxr_SafeCopy(id.data(), reinterpret_cast(uintptr_t(c.ebp - 0x3A0)), sizeof id)) { + rsxrtones::Capture(rsxrtones::Attributes(rsxrtones::Read(c.ebp, 0xC)), c.eax, id); + } else { + RsxrLog("tones26: manifest rejected: unreadable arrangement identity"); + } +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneAutoBefore(RsxrMid::Context& c) { + RsxrMid::Frame(c, kTimeline).user = c.esi; +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneOtherBefore(RsxrMid::Context& c) { + RsxrMid::Frame(c, kTimeline).user = c.ebx; +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneAutoAfter(RsxrMid::Context& c) { + TimelineAfter(c, true); +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneOtherAfter(RsxrMid::Context& c) { + TimelineAfter(c, false); +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneRegisterAfter(RsxrMid::Context& c) { + const RsxrMid::GameFcw fcw(c); + + rsxrtones::PreRegister(RsxrMid::Frame(c, {1}).Arg(0)); +} + +// 0x7DF400 can deliberately bypass the accessor (force=true). Preserve its work, then restore the timeline tone. +extern "C" __declspec(dllexport) void Rsxr_Mid_ToneRefreshAfter(RsxrMid::Context& c) { + auto& frame = RsxrMid::Frame(c, kRefresh); + if (!(frame.Arg(1) & 0xFF)) { + return; + } + + const uint32_t session = frame.Arg(0), song = rsxrtones::Read(session, 0x78); + const uint32_t begin = rsxrtones::Read(song, 0xDC), end = rsxrtones::Read(song, 0xE0); + if (end < begin || (end - begin) % 8 || (end - begin) / 8 > 1000000) { + return; + } + + const float time = Rsxr_SafeRead(reinterpret_cast(uintptr_t(session)), 0x3B4); + uint32_t raw = 0; + bool event = false; + + for (uint32_t at = end; at > begin;) { + at -= 8; + + if (Rsxr_SafeRead(reinterpret_cast(uintptr_t(at)), 0) < time) { + raw = rsxrtones::Read(at, 4); + event = true; + break; + } + } + + const RsxrMid::GameFcw fcw(c); + + (void)rsxrtones::Handle(session, event, raw, true); +} diff --git a/src/features/tones/hooks_toneplan.cpp b/src/features/tones/hooks_toneplan.cpp new file mode 100644 index 0000000..eb189df --- /dev/null +++ b/src/features/tones/hooks_toneplan.cpp @@ -0,0 +1,63 @@ +#include "features/tones/game.h" +#include "features/tones/toneplan.h" +#include "model/gamestring.h" +#include "platform/log.h" +#include "platform/midhook.h" +#include + +extern "C" uintptr_t g_rsxr_resume_TonePlanField, g_rsxr_resume_TonePlanExtension; +extern "C" uintptr_t g_rsxr_resume_TonePlanBound; + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanBefore(RsxrMid::Context& c) { + const RsxrMid::GameFcw fcw(c); + auto& frame = RsxrMid::Frame(c, {2}); + + frame.user = rsxrtones::BeginPlan(frame.Arg(1)); +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanAfter(RsxrMid::Context& c) { + rsxrtones::EndPlan(RsxrMid::Frame(c, {2}).user); +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanField(RsxrMid::Context& c) { + if (rsxrtones::PlanActive() && c.eax % 0x18 == 0) { + const uint32_t name = rsxrtones::PlanName(c.eax / 0x18, true); + + if (name) { + c.edi = name; + c.jump = static_cast(g_rsxr_resume_TonePlanField); + } + } +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanExtension(RsxrMid::Context& c) { + if (rsxrtones::PlanActive() && c.eax % 0x18 == 0) { + const uint32_t name = rsxrtones::PlanName(c.eax / 0x18, false); + + if (name) { + c.eax = name; + c.jump = static_cast(g_rsxr_resume_TonePlanExtension); + } + } +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanBound(RsxrMid::Context& c) { + if (rsxrtones::PlanActive()) { + c.Compare32(c.eax, 27); + // The displaced CMP/JL pair's signed comparison. Derive the back edge from the resolved fallthrough. + const uint32_t resume = static_cast(g_rsxr_resume_TonePlanBound); + + c.jump = static_cast(c.eax) < 27 ? resume - 0xEC8 : resume; + } +} + +extern "C" __declspec(dllexport) void Rsxr_Mid_TonePlanEdit(RsxrMid::Context& c) { + char extension[16]{}, key[256]{}; + + if (rsxr::ReadGameString(reinterpret_cast(uintptr_t(c.esp + 0x4C)), extension, sizeof extension) && + std::strlen(extension) == 5 && std::strncmp(extension, "Tone", 4) == 0 && extension[4] >= 'E' && + extension[4] <= 'Z') { + (void)rsxr::ReadGameString(reinterpret_cast(uintptr_t(c.esp + 0x94)), key, sizeof key); + RsxrLog("tones26: toneplan edit slot=%c key='%s' stock chooser", extension[4], key); + } +} diff --git a/src/features/tones/native_registration.cpp b/src/features/tones/native_registration.cpp new file mode 100644 index 0000000..e627747 --- /dev/null +++ b/src/features/tones/native_registration.cpp @@ -0,0 +1,78 @@ +#include "features/tones/native_registration.h" +#include "features/tones/game.h" +#include "platform/midhook.h" +#include "platform/seh.h" +#include + +extern "C" uintptr_t g_rsxr_tone_register, g_rsxr_tone_destroy; + +namespace rsxrtones { +namespace { +thread_local uint32_t g_registerPlayer = 0; + +void RegisterEntry(RsxrMid::Context& c) { + // CONFIRMED: 0x7D6CE0 takes player in EAX; all remaining arguments and cleanup are stdcall. + c.eax = g_registerPlayer; + c.jump = static_cast(g_rsxr_tone_register); +} + +RsxrMid::CallIn g_register{&RegisterEntry, RsxrMid::Mode::Full, 12}; + +uint32_t Address(const void* pointer) { + return static_cast(reinterpret_cast(pointer)); +} +} // namespace + +NativeRegistration::~NativeRegistration() { + if (!destroy_) { + return; + } + + __try { + // CONFIRMED: 0x5A8EF0 destroys nested vectors, cdecl(record end, record begin). + reinterpret_cast(destroy_)(Address(records_.data() + records_.size()), + Address(records_.data())); + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + // Do not retry a partially completed resource release. + } +} + +bool NativeRegistration::Register(uint32_t definition, uint32_t player, uint32_t slot) { + const uintptr_t entry = g_register.Entry(); + if (!definition || player >= 2 || slot < 5 || slot > 26 || !entry || !g_rsxr_tone_register || + !g_rsxr_tone_destroy) { + return false; + } + + // The stock routine reads only manager+1A4, store+8 and its selected record. Shift a private view, + // not the live manager pointer: stock slot zero reaches 8 + player*27 + logical slot in our buffer. + uint32_t view[5]{0, 0, Address(records_.data() + player * 22 + slot), 0, 0}; + uint32_t manager[0x1A8 / 4]{}; + + manager[0x1A4 / 4] = Address(view); + + if (!Reference(definition, true)) { + return false; + } + + const uint32_t previous = g_registerPlayer; + bool completed = false; + + destroy_ = g_rsxr_tone_destroy; + g_registerPlayer = player; + + __try { + // Stock consumes this call's retained definition reference. Its return register is unspecified. + reinterpret_cast(entry)(Address(manager), definition, 0); + completed = true; + } __except (Rsxr_FaultFilter(GetExceptionCode())) { + completed = false; + } + + g_registerPlayer = previous; + const Record& record = records_[8 + player * 27 + slot]; + + return completed && record.end >= record.begin && record.capacity >= record.end && + (record.end - record.begin) % 4 == 0; +} +} // namespace rsxrtones diff --git a/src/features/tones/native_registration.h b/src/features/tones/native_registration.h new file mode 100644 index 0000000..1bcac60 --- /dev/null +++ b/src/features/tones/native_registration.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include + +namespace rsxrtones { +// Owns only isolated resource vectors. Never installed in the game's live manager. +class NativeRegistration { +public: + NativeRegistration() = default; + ~NativeRegistration(); + NativeRegistration(const NativeRegistration&) = delete; + NativeRegistration& operator=(const NativeRegistration&) = delete; + bool Register(uint32_t definition, uint32_t player, uint32_t slot); + +private: + struct Record { + uint32_t begin = 0, end = 0, capacity = 0; + }; + + static_assert(sizeof(Record) == 12); + std::array records_{}; // eight reserved records, two rows of Base/A..Z + uintptr_t destroy_ = 0; +}; +} // namespace rsxrtones diff --git a/src/features/tones/registration.cpp b/src/features/tones/registration.cpp new file mode 100644 index 0000000..80bdcee --- /dev/null +++ b/src/features/tones/registration.cpp @@ -0,0 +1,54 @@ +#include "features/tones/tones.h" +#include "model/gates.h" +#include "model/groups.h" + +uintptr_t g_rsxr_tones = 1; +extern "C" __declspec(dllexport) uintptr_t g_rsxr_tone_apply = 0, g_rsxr_tone_manager = 0; +extern "C" __declspec(dllexport) uintptr_t g_rsxr_tone_register = 0, g_rsxr_tone_destroy = 0; +extern "C" __declspec(dllexport) uintptr_t g_rsxr_tone_context = 0; +extern "C" __declspec(dllexport) uintptr_t g_rsxr_resume_TonePlanField = 0, g_rsxr_resume_TonePlanExtension = 0, + g_rsxr_resume_TonePlanBound = 0; + +extern "C" { +void Rsxr_Mid_ToneLoad(RsxrMid::Context&); +void Rsxr_Mid_ToneAutoBefore(RsxrMid::Context&); +void Rsxr_Mid_ToneOtherBefore(RsxrMid::Context&); +void Rsxr_Mid_ToneAutoAfter(RsxrMid::Context&); +void Rsxr_Mid_ToneOtherAfter(RsxrMid::Context&); +void Rsxr_Mid_ToneRefreshAfter(RsxrMid::Context&); +void Rsxr_Mid_ToneRegisterAfter(RsxrMid::Context&); +void Rsxr_Mid_TonePlanBefore(RsxrMid::Context&); +void Rsxr_Mid_TonePlanAfter(RsxrMid::Context&); +void Rsxr_Mid_TonePlanField(RsxrMid::Context&); +void Rsxr_Mid_TonePlanExtension(RsxrMid::Context&); +void Rsxr_Mid_TonePlanBound(RsxrMid::Context&); +void Rsxr_Mid_TonePlanEdit(RsxrMid::Context&); +} + +namespace { +const RsxrHook kHooks[] = { + Rsxr_Mid("ToneLoad", &Rsxr_Mid_ToneLoad).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneAuto"), {2}, &Rsxr_Mid_ToneAutoBefore, &Rsxr_Mid_ToneAutoAfter).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneSetup"), {2}, &Rsxr_Mid_ToneOtherBefore, &Rsxr_Mid_ToneOtherAfter).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneSeek"), {2}, &Rsxr_Mid_ToneOtherBefore, &Rsxr_Mid_ToneOtherAfter).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneResume"), {2}, &Rsxr_Mid_ToneOtherBefore, &Rsxr_Mid_ToneOtherAfter) + .Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneOverride"), {2}, &Rsxr_Mid_ToneOtherBefore, &Rsxr_Mid_ToneOtherAfter) + .Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneRefresh"), {2}, nullptr, &Rsxr_Mid_ToneRefreshAfter).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("ToneRegister"), {1}, nullptr, &Rsxr_Mid_ToneRegisterAfter).Gate(kRsxrGateTones), + Rsxr_Ref("ToneApply", &g_rsxr_tone_apply).Gate(kRsxrGateTones), + Rsxr_Ref("ToneManager", &g_rsxr_tone_manager).Gate(kRsxrGateTones), + Rsxr_Ref("ToneRegisterCall", &g_rsxr_tone_register).Gate(kRsxrGateTones), + Rsxr_Ref("ToneResourceDestroy", &g_rsxr_tone_destroy).Gate(kRsxrGateTones), + Rsxr_WrapRow(Rsxr_Site("TonePlanBuild"), {2}, &Rsxr_Mid_TonePlanBefore, &Rsxr_Mid_TonePlanAfter) + .Gate(kRsxrGateTones), + Rsxr_Mid("TonePlanField", &Rsxr_Mid_TonePlanField, &g_rsxr_resume_TonePlanField).Gate(kRsxrGateTones), + Rsxr_Mid("TonePlanExtension", &Rsxr_Mid_TonePlanExtension, &g_rsxr_resume_TonePlanExtension).Gate(kRsxrGateTones), + Rsxr_Mid("TonePlanBound", &Rsxr_Mid_TonePlanBound, &g_rsxr_resume_TonePlanBound).Gate(kRsxrGateTones), + Rsxr_Mid("TonePlanEdit", &Rsxr_Mid_TonePlanEdit).Gate(kRsxrGateTones), + Rsxr_Ref("ToneContext", &g_rsxr_tone_context).Gate(kRsxrGateTones), +}; +} + +extern const RsxrHookTable kRsxrToneHooks = {Rsxr_Group(RsxrFeature::Tones), kHooks, sizeof kHooks / sizeof kHooks[0]}; diff --git a/src/features/tones/selection.h b/src/features/tones/selection.h new file mode 100644 index 0000000..2b3ae06 --- /dev/null +++ b/src/features/tones/selection.h @@ -0,0 +1,21 @@ +#pragma once +#include + +namespace rsxrtones { +constexpr uint32_t kSlots = 26, kBase = 26, kInvalid = 0xFFFFFFFFu; + +constexpr uint32_t Select(bool event, uint32_t raw) { + return !event ? kBase : raw < kSlots ? raw : kInvalid; +} + +struct Player { + uint32_t session = 0, selected = kInvalid; + + bool Needs(uint32_t owner, uint32_t id) const { return session != owner || selected != id; } + + void Applied(uint32_t owner, uint32_t id) { + session = owner; + selected = id; + } +}; +} // namespace rsxrtones diff --git a/src/features/tones/state.cpp b/src/features/tones/state.cpp new file mode 100644 index 0000000..eb43881 --- /dev/null +++ b/src/features/tones/state.cpp @@ -0,0 +1,381 @@ +#include "features/tones/state.h" +#include "features/tones/game.h" +#include "features/tones/native_registration.h" +#include "features/tones/toneplan.h" +#include "features/tones/tones.h" +#include "model/gamestring.h" +#include "model/manifest.h" +#include "platform/log.h" +#include "platform/safecopy.h" +#include +#include +#include + +extern "C" uintptr_t g_rsxr_tone_manager; + +namespace rsxrtones { +namespace { +struct Playback { + Player selection; + uint32_t song = 0, session = 0; + uint64_t generation = 0; + Identity id{}; + std::shared_ptr arrangement; + const char* inactive = nullptr; + uint32_t rejected = kInvalid; + bool rejection = false, firstEvent = false; + bool registrationAttempted = false; + std::shared_ptr registration; + std::shared_ptr custom; + uint32_t rejectedObject = 0; +}; + +struct Song { + uint64_t generation; + bool native; +}; + +struct State { + std::mutex mutex; + std::map> arrangements; + std::map songs; + uint64_t generation = 0; + Playback players[2]; // accessed only by the game thread; loaders touch only the two containers above +}; + +State g_state; + +bool IdentityAt(uint32_t address, Identity& id) { + return address && Rsxr_SafeCopy(id.data(), reinterpret_cast(uintptr_t(address)), sizeof id); +} + +std::shared_ptr FindArrangement(uint32_t session, uint32_t song, uint64_t& generation, Identity& id, + const char*& inactive) { + if (!IdentityAt(session + 0x68, id)) { + inactive = "rejected: unreadable arrangement identity"; + return {}; + } + + std::lock_guard lock(g_state.mutex); + const auto it = g_state.arrangements.find(id); + const auto loaded = g_state.songs.find(song); + + if (loaded == g_state.songs.end()) { + inactive = "rejected: SNG load not observed"; + } else { + generation = loaded->second.generation; + inactive = loaded->second.native ? nullptr : "rejected: SNG is not native"; + } + + if (!g_rsxr_tones) { + inactive = "rejected: feature disabled"; + } + + const auto arrangement = it == g_state.arrangements.end() ? nullptr : it->second; + + if (!inactive) { + inactive = arrangement ? arrangement->inactive : "rejected: manifest not captured"; + } + + return arrangement; +} + +void Replace(const Identity& id, std::shared_ptr arrangement) { + // Release replaced game objects outside the mutex: game vtables may enter other hooks. + std::shared_ptr old; + + { + std::lock_guard lock(g_state.mutex); + const auto it = g_state.arrangements.find(id); + + if (it != g_state.arrangements.end()) { + old = std::move(it->second); + g_state.arrangements.erase(it); + } + + if (arrangement) { + g_state.arrangements.emplace(id, std::move(arrangement)); + } + } +} + +void Log(const Arrangement& a, uint32_t player, uint32_t id, const char* key, bool applied) { + RsxrLog("tones26: arrangement=%08X%08X%08X%08X player=%u id=%u key='%s' %s", a.id[0], a.id[1], a.id[2], a.id[3], + player, id, key, applied ? "applied" : "rejected"); +} + +void LogDecision(const Playback& p, uint32_t player) { + const auto& id = p.id; + + if (p.inactive) { + RsxrLog("tones26: arrangement=%08X%08X%08X%08X song=%08X player=%u %s", id[0], id[1], id[2], id[3], p.song, + player, p.inactive); + } else { + const auto& slots = p.arrangement->slots; + + RsxrLog("tones26: arrangement=%08X%08X%08X%08X song=%08X player=%u extra tones %zu (%s), active", id[0], id[1], + id[2], id[3], p.song, player, (slots.size() + 1) / 2, slots.c_str()); + } +} + +Playback& Observe(uint32_t session, uint32_t song, uint32_t player, bool event, uint32_t raw) { + uint64_t generation = 0; + Identity id{}; + const char* inactive = nullptr; + const auto arrangement = FindArrangement(session, song, generation, id, inactive); + Playback& p = g_state.players[player]; + const bool load = p.song != song || p.generation != generation || p.session != session || p.id != id; + + if (load || p.arrangement != arrangement || p.inactive != inactive) { + const bool firstEvent = !load && p.firstEvent; + + p = {}; + p.song = song; + p.session = session; + p.generation = generation; + p.id = id; + p.arrangement = arrangement; + p.inactive = inactive; + p.firstEvent = firstEvent; + LogDecision(p, player); + } + + if (event && !p.firstEvent) { + const float time = Rsxr_SafeRead(reinterpret_cast(uintptr_t(session)), 0x3B4); + + p.firstEvent = true; + RsxrLog("tones26: arrangement=%08X%08X%08X%08X song=%08X player=%u first event raw=%u time=%.3f", id[0], id[1], + id[2], id[3], song, player, raw, static_cast(time)); + } + + return p; +} + +uint32_t Object(const Arrangement& a, uint32_t session, uint32_t id, char (&key)[256]) { + if (id >= 4 && id < kSlots) { + const Tone& tone = a.extra[id - 4]; + + strcpy_s(key, tone.key.c_str()); + + return tone.object; + } + + const uint32_t index = id == kBase ? 0 : id + 1; + + (void)rsxr::ReadGameString(reinterpret_cast(uintptr_t(session + 0x198 + 0x18 * index)), key, + sizeof key); + + return Read(session, 0x228 + 4 * index); +} + +void LogOverride(uint32_t id, const char* key, bool applied) { + const uint32_t slot = id == kBase ? 0 : id + 1; + const char* extension = SlotExtension(slot); + + if (extension) { + RsxrLog("tones26: override slot=%s key='%s' %s", extension + 4, key, applied ? "applied" : "none"); + } +} + +void RegisterExtras(Playback& playback, uint32_t player) { + if (playback.inactive || playback.registrationAttempted) { + return; + } + + playback.registrationAttempted = true; + const auto arrangement = playback.arrangement; + std::shared_ptr registration; + + try { + registration = std::make_shared(); + } catch (...) { + // Still log one rejected decision per declared slot below. + } + + playback.registration = registration; + const bool manager = Read(static_cast(g_rsxr_tone_manager)) != 0; + + for (uint32_t id = 4; id < kSlots; ++id) { + const Tone& tone = arrangement->extra[id - 4]; + if (tone.key.empty()) { + continue; + } + + const bool ok = manager && registration && registration->Register(tone.object, player, id + 1); + const char* reason = !tone.object ? "rejected: missing or ambiguous definition" + : !manager ? "rejected: tone manager unavailable" + : !registration ? "rejected: resource store allocation failed" + : "rejected: registration unavailable or failed"; + + RsxrLog("tones26: register player=%u slot=%u key='%s' %s", player, id + 1, tone.key.c_str(), + ok ? "ok" : reason); + } +} +} // namespace + +Tone::~Tone() { + if (object) { + (void)Reference(object, false); + } +} + +void Capture(uint32_t attributes, uint32_t collection, const Identity& id) { + double marker = 0; + + if (!attributes) { + Replace(id, {}); + return; + } + + auto arrangement = std::make_shared(); + const bool eligible = + rsxr::JsonNumber(reinterpret_cast(uintptr_t(attributes)), "RsxrToneSlots", &marker) && marker == 26; + + arrangement->id = id; + + for (uint32_t i = 4; i < kSlots; ++i) { + char field[] = "Tone_E"; + char key[256]{}; + + field[5] = static_cast('A' + i); + + if (!Name(attributes, field, key, sizeof key) || !key[0]) { + continue; + } + + Tone& tone = arrangement->extra[i - 4]; + + tone.key = key; + + if (!arrangement->slots.empty()) { + arrangement->slots += ','; + } + + arrangement->slots += field[5]; + + if (g_rsxr_tones && eligible) { + tone.object = Definition(collection, key); + } + } + + if (!arrangement->slots.empty()) { + arrangement->inactive = eligible ? nullptr : "rejected: missing or invalid RsxrToneSlots"; + } else if (eligible) { + arrangement->inactive = "rejected: marked manifest has no readable extra tones"; + } + + RsxrLog("tones26: manifest arrangement=%08X%08X%08X%08X extra tones=%zu slots=%s marker=%.0f %s", id[0], id[1], + id[2], id[3], (arrangement->slots.size() + 1) / 2, arrangement->slots.c_str(), marker, + arrangement->inactive ? arrangement->inactive : "captured"); + Replace(id, std::move(arrangement)); +} + +bool Handle(uint32_t session, bool event, uint32_t raw, bool force) { + if (!session) { + return false; + } + + const uint32_t player = Read(session, 8), song = Read(session, 0x78); + if (player >= 2) { + return false; + } + + Playback& playback = Observe(session, song, player, event, raw); + if (playback.inactive) { + return false; + } + + RegisterExtras(playback, player); + const auto& arrangement = playback.arrangement; + const uint32_t id = Select(event, raw), rejected = event ? raw : kBase; + Tone custom; + + const bool declared = id < 4 || id == kBase || (id < kSlots && !arrangement->extra[id - 4].key.empty()); + + if (declared) { + custom.object = Override(player, id == kBase ? 0 : id + 1); + } + + const bool overrideChanged = custom.object != (playback.custom ? playback.custom->object : 0); + + if (!force && !playback.rejection && !overrideChanged && !playback.selection.Needs(session, id)) { + return true; + } + + char key[256]{}; + const uint32_t object = custom.object ? custom.object : id == kInvalid ? 0 : Object(*arrangement, session, id, key); + + if (custom.object) { + (void)Name(custom.object, "Key", key, sizeof key); + } + + const bool changed = playback.selection.Needs(session, id) || playback.rejection || overrideChanged; + const bool applied = object && Apply(object, player); + + if (applied) { + if (overrideChanged) { + auto retained = custom.object ? std::make_shared() : nullptr; + + if (retained) { + retained->object = custom.object; + custom.object = 0; + } + + playback.custom = std::move(retained); + } + + playback.selection.Applied(session, id); + playback.rejection = false; + + if (changed) { + Log(*arrangement, player, id, key, true); + LogOverride(id, key, playback.custom != nullptr); + } + } else if (!playback.rejection || playback.rejected != rejected || playback.rejectedObject != object) { + playback.rejection = true; + playback.rejected = rejected; + playback.rejectedObject = object; + Log(*arrangement, player, rejected, key, false); + LogOverride(id, key, false); + } + + return true; +} + +void PreRegister(uint32_t session) { + if (!session) { + return; + } + + const uint32_t player = Read(session, 8); + if (player >= 2) { + return; + } + + Playback& playback = Observe(session, Read(session, 0x78), player, false, 0); + + RegisterExtras(playback, player); +} +} // namespace rsxrtones + +void RsxrTones_SongLoaded(uint32_t song, bool native) { + if (!song) { + return; + } + + try { + uint64_t generation = 0; + + { + std::lock_guard lock(rsxrtones::g_state.mutex); + + generation = ++rsxrtones::g_state.generation; + rsxrtones::g_state.songs.insert_or_assign(song, rsxrtones::Song{generation, native}); + } + + RsxrLog("tones26: song=%08X load=%llu %s", song, static_cast(generation), + native ? "native SNG accepted" : "stock or rejected SNG; extended tones inactive"); + } catch (...) { + RsxrLog("tones26: SNG marker allocation failed; extended tones unavailable for song=%08X", song); + } +} diff --git a/src/features/tones/state.h b/src/features/tones/state.h new file mode 100644 index 0000000..1376738 --- /dev/null +++ b/src/features/tones/state.h @@ -0,0 +1,31 @@ +#pragma once +#include "features/tones/selection.h" +#include +#include +#include + +namespace rsxrtones { +using Identity = std::array; + +struct Tone { + std::string key; + uint32_t object = 0; + + Tone() = default; + Tone(const Tone&) = delete; + Tone& operator=(const Tone&) = delete; + ~Tone(); +}; + +struct Arrangement { + Identity id{}; + std::array extra; + std::string slots; + const char* inactive = "no extra tones"; +}; + +void Capture(uint32_t attributes, uint32_t collection, const Identity& id); +void PreRegister(uint32_t session); +// True means a native arrangement with extra slots owns this consumer, including rejected IDs. +bool Handle(uint32_t session, bool event, uint32_t raw, bool force); +} // namespace rsxrtones diff --git a/src/features/tones/toneplan.cpp b/src/features/tones/toneplan.cpp new file mode 100644 index 0000000..193d454 --- /dev/null +++ b/src/features/tones/toneplan.cpp @@ -0,0 +1,118 @@ +#include "features/tones/toneplan.h" +#include "features/tones/game.h" +#include "features/tones/tones.h" +#include "model/manifest.h" +#include "platform/log.h" +#include +#include + +namespace rsxrtones { +namespace { +struct NameView { + char text[16]{}; + uint32_t end = 0, capacity = 0; + + void Set(const char* value) { + strcpy_s(text, value); + end = static_cast(reinterpret_cast(text) + std::strlen(text)); + capacity = static_cast(reinterpret_cast(&end)); + } +}; + +static_assert(sizeof(NameView) == 0x18); + +struct Names { + std::array extensions, fields; + + Names() { + extensions[0].Set("ToneBase"); + fields[0].Set("Tone_Base"); + + for (uint32_t slot = 1; slot < 27; ++slot) { + char extension[] = "ToneA", field[] = "Tone_A"; + + extension[4] = field[5] = static_cast('A' + slot - 1); + extensions[slot].Set(extension); + fields[slot].Set(field); + } + } +}; + +struct PlanState { + Names names; + uint32_t slots = 0; // menu/game thread only; the synchronous builder wrap restores nested calls +}; + +PlanState g_plan; +} // namespace + +const char* SlotExtension(uint32_t slot) { + return slot < 27 ? g_plan.names.extensions[slot].text : nullptr; +} + +uint32_t PlanName(uint32_t slot, bool manifestField) { + if (slot >= 27) { + return 0; + } + + const auto& name = manifestField ? g_plan.names.fields[slot] : g_plan.names.extensions[slot]; + + return static_cast(reinterpret_cast(&name)); +} + +uint32_t PlanSlots(uint32_t attributes) { + double marker = 0; + if (!g_rsxr_tones || !attributes || + !rsxr::JsonNumber(reinterpret_cast(uintptr_t(attributes)), "RsxrToneSlots", &marker) || marker != 26) { + return 0; + } + + uint32_t slots = 0; + + for (uint32_t slot = 0; slot < 27; ++slot) { + char key[256]{}; + + if (Name(attributes, g_plan.names.fields[slot].text, key, sizeof key) && key[0]) { + slots |= 1u << slot; + } + } + + return (slots & ~31u) ? slots : 0; +} + +uint32_t BeginPlan(uint32_t attributes) { + const uint32_t previous = g_plan.slots; + const uint32_t slots = PlanSlots(attributes); + + g_plan.slots = slots; + + if (slots) { + char used[64]{}; + unsigned rows = 0; + + for (uint32_t slot = 0; slot < 27; ++slot) { + if (!(slots & (1u << slot))) { + continue; + } + + if (rows++) { + strcat_s(used, ","); + } + + strcat_s(used, slot ? SlotExtension(slot) + 4 : "Base"); + } + + RsxrLog("tones26: toneplan rows=%u (%s used)", rows, used); + } + + return previous; +} + +void EndPlan(uint32_t previous) { + g_plan.slots = previous; +} + +bool PlanActive() { + return g_plan.slots != 0; +} +} // namespace rsxrtones diff --git a/src/features/tones/toneplan.h b/src/features/tones/toneplan.h new file mode 100644 index 0000000..68b789d --- /dev/null +++ b/src/features/tones/toneplan.h @@ -0,0 +1,12 @@ +#pragma once +#include + +namespace rsxrtones { +// Logical slots: Base=0, A=1, E=5, Z=26. Zero mask leaves the stock builder untouched. +uint32_t PlanSlots(uint32_t attributes); +uint32_t PlanName(uint32_t slot, bool manifestField); +const char* SlotExtension(uint32_t slot); +uint32_t BeginPlan(uint32_t attributes); +void EndPlan(uint32_t previous); +bool PlanActive(); +} // namespace rsxrtones diff --git a/src/features/tones/tones.h b/src/features/tones/tones.h new file mode 100644 index 0000000..f68caf6 --- /dev/null +++ b/src/features/tones/tones.h @@ -0,0 +1,8 @@ +#pragma once +#include "platform/hooktable.h" + +extern const RsxrHookTable kRsxrToneHooks; +extern uintptr_t g_rsxr_tones; + +// Called at XI1 for every SNG load. Each load gets a generation, including stock loads at reused addresses. +void RsxrTones_SongLoaded(uint32_t song, bool native); diff --git a/src/hook_rules.cpp b/src/hook_rules.cpp index 7ace7c3..ffe913c 100644 --- a/src/hook_rules.cpp +++ b/src/hook_rules.cpp @@ -17,6 +17,7 @@ #include "features/string7/string7.h" #include "features/strings/strings.h" #include "features/testdrive/testdrive.h" +#include "features/tones/tones.h" #include "features/tuner/tuner.h" #include "model/gates.h" @@ -44,6 +45,7 @@ const GroupSwitches kGroupSwitches[] = { {RsxrFeature::Clite, &g_rsxr_clite, nullptr}, {RsxrFeature::Glow, &g_rsxr_glow_fix, nullptr}, {RsxrFeature::MenuLoad, &g_rsxr_menu_retry, nullptr}, + {RsxrFeature::Tones, &g_rsxr_tones, nullptr}, }; // Marks one group failed and clears its switches (no cascade). @@ -138,6 +140,9 @@ bool Rsxr_ShouldPatch(const RsxrHook& h, bool diagnostics, bool privateOn, bool if (g_featureOff[size_t(Rsxr_FeatureOf(h))]) { return false; } + if ((h.gates & kRsxrGateTones) && !g_rsxr_tones) { + return false; + } if ((h.gates & kRsxrGateMenuLoad) && !g_rsxr_menu_retry) { return false; } diff --git a/src/model/gates.h b/src/model/gates.h index 34e1bab..1ab745a 100644 --- a/src/model/gates.h +++ b/src/model/gates.h @@ -21,3 +21,4 @@ constexpr uint32_t kRsxrGateTestVariant = 1u << 13; constexpr uint32_t kRsxrGateGlow = 1u << 14; constexpr uint32_t kRsxrGateDiagrams = 1u << 15; constexpr uint32_t kRsxrGateMenuLoad = 1u << 16; +constexpr uint32_t kRsxrGateTones = 1u << 17; diff --git a/src/model/groups.cpp b/src/model/groups.cpp index a3d8785..d59cdc8 100644 --- a/src/model/groups.cpp +++ b/src/model/groups.cpp @@ -19,7 +19,8 @@ const char* Rsxr_FeatureName(RsxrFeature f) { "[psarc] plain", "C-lite", "RSMods glow correction", - "menu loading retry"}; + "menu loading retry", + "26 tone slots"}; static_assert(sizeof n / sizeof n[0] == size_t(RsxrFeature::Count), "one name per RsxrFeature"); return size_t(f) < size_t(RsxrFeature::Count) ? n[size_t(f)] : "?"; diff --git a/src/model/groups.h b/src/model/groups.h index 4744223..433e6ee 100644 --- a/src/model/groups.h +++ b/src/model/groups.h @@ -22,6 +22,7 @@ enum class RsxrFeature { Clite, Glow, MenuLoad, + Tones, Count }; diff --git a/src/model/nativemanifest.cpp b/src/model/nativemanifest.cpp index dd7017b..4ad5551 100644 --- a/src/model/nativemanifest.cpp +++ b/src/model/nativemanifest.cpp @@ -308,6 +308,28 @@ std::string Tuning(const Scanner& sc, const Object& arrangement, const Object& m return out + "}"; } +void ToneMarker(const Scanner& sc, const Object& o, const Member& marker, bool valid, std::vector& edits, + size_t markerEdit) { + bool extraTone = false, reserved = false; + + for (const Member& m : o.members) { + const std::string_view key = sc.Text(m.keyBegin, m.keyEnd); + const std::string_view value = sc.Text(m.valueBegin, m.valueEnd); + + extraTone |= key.size() == 6 && key.substr(0, 5) == "Tone_" && key[5] >= 'E' && key[5] <= 'Z' && + value.size() > 2 && value.front() == '"' && value.back() == '"'; + + if (key == "RsxrToneSlots") { + reserved = true; + edits.push_back({m.valueBegin, m.valueEnd, "0"}); + } + } + + if (valid && extraTone && !reserved) { + edits[markerEdit] = {marker.begin, marker.valueEnd, "\"RsxrToneSlots\": 26"}; + } +} + bool Rewrite(const char* text, size_t size, std::string* out, ManifestStats* stats) { static const Object kNone; Scanner sc(text, size); @@ -324,7 +346,8 @@ bool Rewrite(const char* text, size_t size, std::string* out, ManifestStats* sta continue; } - // The marker goes, with the comma that separated it from its neighbour. + // Remove the authoring marker; an eligible tone arrangement replaces this edit below. + const size_t markerEdit = edits.size(); const size_t index = static_cast(marker - o.members.data()); if (index + 1 < o.members.size()) { @@ -363,6 +386,8 @@ bool Rewrite(const char* text, size_t size, std::string* out, ManifestStats* sta edits.push_back({m.valueBegin, m.valueEnd, std::move(current)}); } + ToneMarker(sc, o, *marker, valid, edits, markerEdit); + ++(valid ? found.rewritten : found.bad); } diff --git a/src/model/nativemanifest.h b/src/model/nativemanifest.h index 19bdb33..2b795fc 100644 --- a/src/model/nativemanifest.h +++ b/src/model/nativemanifest.h @@ -22,7 +22,9 @@ size_t JsonExtent(const char* text, size_t limit); // False when `text` (a manifest .json or .hsan, `size` bytes, no terminator needed) has no native arrangement or is // not JSON this scanner accepts: *out is untouched and the game parses the original. True: *out is the whole text -// with every native arrangement in the internal form and the marker removed. An arrangement that is marked but +// with every native arrangement in the internal form and the marker removed. Valid arrangements with nonempty +// Tone_E..Tone_Z names get the internal RsxrToneSlots=26 field for the tone loader; writers never emit it. +// An arrangement that is marked but // invalid (unknown version, a string count the instrument does not have, Tuning keys that are not // exactly string0..stringN-1 with number values) gets a six-entry Tuning from what is there, so the stock readers // never meet a seventh "stringI" key; it counts in stats->bad. No C++ exception escapes. diff --git a/src/registry.cpp b/src/registry.cpp index 1f486cf..32986af 100644 --- a/src/registry.cpp +++ b/src/registry.cpp @@ -21,6 +21,7 @@ #include "features/string7/string7.h" #include "features/strings/strings.h" #include "features/testdrive/testdrive.h" +#include "features/tones/tones.h" #include "features/tuner/tuner.h" #include "hook_rules.h" #include "platform/isolate.h" @@ -36,7 +37,7 @@ const RsxrHookTable* const kTables[] = { &kRsxrNextgridHooks, &kRsxrFretHooks, &kRsxrStringsHooks, &kRsxrSceneHooks, &kRsxrString7Hooks, &kRsxrPitchHooks, &kRsxrPitchCoreHooks, &kRsxrNslotHooks, &kRsxrChordFrameHooks, &kRsxrFretgridCoreHooks, &kRsxrTestVariantHooks, &kRsxrArrangementHooks, - &kRsxrNslotEightHooks, &kRsxrMenuLoadHooks, &kRsxrNativeHooks, + &kRsxrNslotEightHooks, &kRsxrMenuLoadHooks, &kRsxrNativeHooks, &kRsxrToneHooks, #if RSXR_PRIVATE &kRsxrPrivateHooks, // the private extras (src/features/extras/extras.h) #endif diff --git a/tests/model/test_nativemanifest.cpp b/tests/model/test_nativemanifest.cpp index ecd939f..f51eacb 100644 --- a/tests/model/test_nativemanifest.cpp +++ b/tests/model/test_nativemanifest.cpp @@ -1,4 +1,5 @@ // The native manifest rewriter (model/nativemanifest.h): native Tuning objects become the current form. +#include "../tones/manifest_fixture.h" #include "model/nativemanifest.h" #include "test.h" #include @@ -59,6 +60,55 @@ TEST(nativemanifest_guitar_strings_move_to_their_slots) { "\"RsxrString6\": -7, \"RsxrString7\": -8")); } +TEST(nativemanifest_tone_marker_requires_valid_native_attributes_and_extra_names) { + std::string native = Attributes("Lead", {0, 0, 0, 0, 0, 0, 0}); + + native.insert(1, "\"Tone_E\": \"crunch\", \"Tone_F\": \"lead\", "); + + const std::string out = Run(native); + + CHECK(out.find("\"RsxrToneSlots\": 26") != std::string::npos); + CHECK(out.find("\"Tone_E\": \"crunch\"") != std::string::npos); + CHECK(out.find("ExtendedRange") == std::string::npos); + CHECK(Run(Attributes("Lead", {0, 0, 0, 0, 0, 0, 0})).find("RsxrToneSlots") == std::string::npos); + + std::string invalid = Attributes("Lead", {0, 0, 0, 0, 0}); + + invalid.insert(1, "\"Tone_E\": \"crunch\", "); + CHECK(Run(invalid).find("RsxrToneSlots") == std::string::npos); + CHECK(Run("{\"Tone_E\":\"crunch\"}") == ""); + + native.insert(1, "\"RsxrToneSlots\":26, "); + CHECK(Run(native).find("\"RsxrToneSlots\":0") != std::string::npos); + CHECK(Run(native).find("\"RsxrToneSlots\": 26") == std::string::npos); +} + +TEST(nativemanifest_demo_layout_preserves_extra_fields_inside_attributes) { + for (const char* name : {"Lead", "Rhythm"}) { + std::string input = tonetest::kManifest; + + input.replace(input.find("Lead"), 4, name); + + std::string want = input; + const std::string marker = "\"ExtendedRange\": {\n \"Version\": 1\n }"; + const size_t tuning = want.find("\"Tuning\": {"); + const size_t end = want.find('}', tuning); + + want.replace(tuning, end + 1 - tuning, + "\"Tuning\": {\"string0\": -2, \"string1\": -2, \"string2\": -2, \"string3\": -2, " + "\"string4\": -2, \"string5\": -2, \"RsxrString6\": -2}"); + want.replace(want.find(marker), marker.size(), "\"RsxrToneSlots\": 26"); + + ManifestStats stats; + + CHECK(Run(input, &stats) == want); // all other bytes, including Tones and empty G..Z, survive + CHECK_EQ(stats.rewritten, 1); + CHECK_EQ(stats.bad, 0); + input.erase(input.find(" " + marker), marker.size() + 10); // remove marker, comma and newline + CHECK(Run(input) == ""); + } +} + TEST(nativemanifest_bass_strings_move_to_their_slots) { CHECK(Run(Attributes("Bass", {1, 2, 3, 4})) == Current("\"string0\": 1, \"string1\": 2, \"string2\": 3, \"string3\": 4, \"string4\": 0, \"string5\": 0", diff --git a/tests/test_hook_rules.cpp b/tests/test_hook_rules.cpp index f16984b..e04ee98 100644 --- a/tests/test_hook_rules.cpp +++ b/tests/test_hook_rules.cpp @@ -11,6 +11,7 @@ #include "features/pitch/pitch.h" #include "features/publish/publish.h" #include "features/strings/strings.h" +#include "features/tones/tones.h" #include "features/tuner/tuner.h" #include "hook_rules.h" #include "test.h" @@ -24,7 +25,7 @@ uintptr_t* const kSwitches[] = {&g_rsxr_native_colours, &g_rsxr_native_pegset &g_rsxr_native_fretgrid, &g_rsxr_native_pitch, &g_rsxr_native_nextgrid, &g_rsxr_diagrams, &g_rsxr_publish_ports, &g_rsxr_native_publish, &g_rsxr_native_chordloops, &g_rsxr_native_tuner, &g_rsxr_clite, - &g_rsxr_glow_fix, &g_rsxr_menu_retry}; + &g_rsxr_glow_fix, &g_rsxr_menu_retry, &g_rsxr_tones}; constexpr size_t kSwitchCount = sizeof kSwitches / sizeof kSwitches[0]; // Bit i: kSwitches[i] cleared. @@ -43,6 +44,7 @@ enum : unsigned { sClite = 1u << 11, sGlow = 1u << 12, sMenu = 1u << 13, + sTones = 1u << 14, }; constexpr unsigned G(F f) { @@ -77,6 +79,7 @@ const Expect kCascade[] = { {F::Clite, true, kUnit, kUnitOff}, {F::Glow, true, G(F::Glow), sGlow}, {F::MenuLoad, true, G(F::MenuLoad), sMenu}, + {F::Tones, true, G(F::Tones), sTones}, {F::Count, false, 0, 0}, }; diff --git a/tests/test_registry.cpp b/tests/test_registry.cpp index 372b13c..3fb7589 100644 --- a/tests/test_registry.cpp +++ b/tests/test_registry.cpp @@ -91,17 +91,20 @@ TEST(ref_sites_are_never_written) { } CHECK_EQ(refs, - 12 + kRsxrPrivateRefSites); // X_CM, X_TCS, X_THEAD, X_DT (7th string line), X_WTHR (W's threshold) + 14 + kRsxrPrivateRefSites); // X_CM, X_TCS, X_THEAD, X_DT (7th string line), X_WTHR (W's threshold) // + the private extras' refs (src/features/extras/extras.h) // + X_TMGR, X_FADEMGR (tuner; the B-phase refs went in 1.0) // + X_DDSH (the 7-string model's textures) // + X_MCMP, X_MTAB (the N-slot chord matcher) + X_PEGNAMES (N-slot PegSet) + // + ToneManager (extended tone apply) + // + ToneContext (stock Tone Plan custom overrides) // + X_TBASS (the tuner's bass open MIDI table, extended bass) - CHECK_EQ(callRefs, 38); // MenuMovieRequest (menu loading retry) + X_SPAWN, X_ADV3 (neck targets, N9) + the string + CHECK_EQ(callRefs, 41); // MenuMovieRequest (menu loading retry) + X_SPAWN, X_ADV3 (neck targets, N9) + the string // object calls the native strings use // + X_WORLD, X_ROOT (entity root nodes, features/scene) // + X_SETSCALE (F1/F2 fret bars), X_EULER (peg placement) // + X_PEGSELECT, X_PEGPLACE, X_PEGLAYER (N-slot PegSet) + // + ToneRegisterCall, ToneResourceDestroy (extended tone registration) // + X_PULSE, X_LSPAWN, X_DESPAWN, X_BLACK, X_PEGRESET, X_MSG, X_FADEIN, // X_FADEOUT (tuner) + X_FIXSTR, X_STRPARAMS (edited headstock) // + X_DETACH (the 7th string's ghost, issue #16) @@ -110,7 +113,7 @@ TEST(ref_sites_are_never_written) { // + X_STRCON, X_STRASG, X_LOC, X_STRDTOR (tuning names, issue #15) // + X_MSORT, X_MINS1, X_MINS2 (the N-slot chord matcher's sort) // + X_EVREL (the tracker's eval release, RL1/RL2) - // + X_ATTACH (native GuitarStrings, issue #18 stage 4) + // + X_ATTACH (native GuitarStrings, issue #18 stage 4), ToneApply (26 tone slots) } TEST(r7_r7b_n9_are_gone_the_native_grid_replaces_them) { diff --git a/tests/tones/json_fixture.h b/tests/tones/json_fixture.h new file mode 100644 index 0000000..b609c29 --- /dev/null +++ b/tests/tones/json_fixture.h @@ -0,0 +1,73 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace tonetest { +inline uint32_t Addr(const void* p) { + return static_cast(reinterpret_cast(p)); +} + +// Minimal owned JSON objects with the same vtable/string contracts used by the production adapter. +struct Node { + uintptr_t* table = methods; + uint32_t padding = 0; + double number = 26; + uintptr_t methods[26]{}; + uint32_t stringValue[3]{}, gameString[6]{}; + std::string text; + std::map members; + uint32_t refs = 0; + bool canonical = true; + + explicit Node(const char* value = "") : text(value) { + methods[0] = reinterpret_cast(&Retain); + methods[1] = reinterpret_cast(&Release); + methods[0x14 / 4] = reinterpret_cast(&Find); + methods[0x18 / 4] = reinterpret_cast(&Find); + methods[0x34 / 4] = reinterpret_cast(&Unwrap); + methods[0x50 / 4] = reinterpret_cast(&Number); + methods[0x5C / 4] = reinterpret_cast(&Canonical); + methods[0x60 / 4] = reinterpret_cast(&String); + stringValue[2] = Addr(gameString); + gameString[0] = Addr(text.c_str()); + gameString[4] = gameString[0] + static_cast(text.size()); + } + + static uint32_t __fastcall Retain(Node* self, void*) { return ++self->refs; } + + static uint32_t __fastcall Release(Node* self, void*) { return --self->refs; } + + static uint32_t __fastcall Find(Node* self, void*, const char* key) { + const auto found = self->members.find(key); + + return found == self->members.end() ? 0 : Addr(found->second); + } + + static uint32_t __fastcall Unwrap(Node*, void*) { return 0; } + + static uint32_t __fastcall Number(Node* self, void*) { return Addr(self); } + + static uint32_t __fastcall Canonical(Node* self, void*) { return self->canonical ? Addr(self) : 0; } + + static uint32_t __fastcall String(Node* self, void*) { return Addr(self->stringValue); } +}; + +struct Context { + Node root, custom, players[2]; + std::array manager{}, context{}; + uint32_t managerAddress = Addr(manager.data()); + + Context() { + manager[0x14 / 4] = Addr(context.data()); + context[0x20 / 4] = Addr(&root); + root.members["CustomTone"] = &custom; + custom.members["0"] = &players[0]; + custom.members["1"] = &players[1]; + } + + uint32_t Global() const { return Addr(&managerAddress); } +}; +} // namespace tonetest diff --git a/tests/tones/manifest_fixture.h b/tests/tones/manifest_fixture.h new file mode 100644 index 0000000..7aa3c3f --- /dev/null +++ b/tests/tones/manifest_fixture.h @@ -0,0 +1,117 @@ +#pragma once + +namespace tonetest { +// Synthetic Python json.dumps(indent=2, ensure_ascii=False); demo nesting and relevant key order. +inline constexpr char kManifest[] = R"json({ + "Entries": { + "0123456789ABCDEF0123456789ABCDEF": { + "Attributes": { + "ArrangementName": "Lead", + "ArrangementProperties": { + "pathLead": 1 + }, + "SongName": "Synthetic étude", + "Tone_A": "alpha", + "Tone_B": "bravo", + "Tone_Base": "alpha", + "Tone_C": "charlie", + "Tone_D": "delta", + "Tone_Multiplayer": "", + "Tones": [ + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "alpha", + "Name": "alpha" + }, + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "bravo", + "Name": "bravo" + }, + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "charlie", + "Name": "charlie" + }, + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "delta", + "Name": "delta" + }, + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "echo", + "Name": "echo" + }, + { + "GearList": [], + "ToneDescriptors": [], + "NameSeparator": " ", + "IsCustom": true, + "Volume": 0.0, + "Key": "foxtrot", + "Name": "foxtrot" + } + ], + "ExtendedRange": { + "Version": 1 + }, + "Tuning": { + "string0": -2, + "string1": -2, + "string2": -2, + "string3": -2, + "string4": -2, + "string5": -2, + "string6": -2 + }, + "Tone_E": "echo", + "Tone_F": "foxtrot", + "Tone_G": "", + "Tone_H": "", + "Tone_I": "", + "Tone_J": "", + "Tone_K": "", + "Tone_L": "", + "Tone_M": "", + "Tone_N": "", + "Tone_O": "", + "Tone_P": "", + "Tone_Q": "", + "Tone_R": "", + "Tone_S": "", + "Tone_T": "", + "Tone_U": "", + "Tone_V": "", + "Tone_W": "", + "Tone_X": "", + "Tone_Y": "", + "Tone_Z": "" + } + } + }, + "ModelName": "Synthetic", + "IterationVersion": 2, + "InsertRoot": "Static.Songs.Entries" +})json"; +} // namespace tonetest diff --git a/tests/tones/test_apply.cpp b/tests/tones/test_apply.cpp new file mode 100644 index 0000000..0d4c81c --- /dev/null +++ b/tests/tones/test_apply.cpp @@ -0,0 +1,53 @@ +#include "features/tones/game.h" +#include "platform/midhook.h" +#include "test.h" +#include "testutil.h" +#include + +extern "C" uintptr_t g_rsxr_tone_apply, g_rsxr_tone_manager; + +namespace { +struct Call { + uint32_t object = 0, manager = 0, player = 0, kind = 0; + uint32_t result = 1, calls = 0; +}; + +Call g_call; + +// A stock-ABI stand-in executed through the real call-in/return bridge, including ret 0Ch. +void StockApply(RsxrMid::Context& c) { + g_call.object = RsxrMid::Dword(c.esi); + g_call.manager = RsxrMid::Dword(c.esp + 4); + g_call.player = RsxrMid::Dword(c.esp + 8); + g_call.kind = RsxrMid::Dword(c.esp + 12); + ++g_call.calls; + c.eax = g_call.result; +} + +RsxrMid::CallIn g_stockApply{&StockApply, RsxrMid::Mode::Full, 12}; +} // namespace + +TEST(tone_apply_passes_the_full_object_and_player_through_the_stock_abi) { + rsxrtest::Restore restoreApply(g_rsxr_tone_apply), restoreManager(g_rsxr_tone_manager); + uint32_t manager = 0x12345678; + + g_call = {}; + g_rsxr_tone_manager = reinterpret_cast(&manager); + g_rsxr_tone_apply = g_stockApply.Entry(); + CHECK(g_rsxr_tone_apply); + CHECK(rsxrtones::Apply(0x11112222, 1)); + CHECK_EQ(g_call.object, uint32_t(0x11112222)); + CHECK_EQ(g_call.manager, manager); + CHECK_EQ(g_call.player, uint32_t(1)); + CHECK_EQ(g_call.kind, uint32_t(3)); + CHECK_EQ(g_call.calls, uint32_t(1)); + + g_call.result = 0; + CHECK(!rsxrtones::Apply(0x33334444, 0)); + CHECK_EQ(g_call.object, uint32_t(0x33334444)); + CHECK_EQ(g_call.player, uint32_t(0)); + CHECK_EQ(g_call.calls, uint32_t(2)); + CHECK(!rsxrtones::Apply(1, 2)); + CHECK(!rsxrtones::Apply(0, 0)); + CHECK_EQ(g_call.calls, uint32_t(2)); +} diff --git a/tests/tones/test_native_registration.cpp b/tests/tones/test_native_registration.cpp new file mode 100644 index 0000000..e822e29 --- /dev/null +++ b/tests/tones/test_native_registration.cpp @@ -0,0 +1,174 @@ +#include "features/tones/game.h" +#include "features/tones/native_registration.h" +#include "features/tones/state.h" +#include "features/tones/tones.h" +#include "json_fixture.h" +#include "platform/midhook.h" +#include "test.h" +#include "testutil.h" + +extern "C" uintptr_t g_rsxr_tone_register, g_rsxr_tone_destroy; +extern "C" uintptr_t g_rsxr_tone_manager; +extern "C" void Rsxr_Mid_ToneRegisterAfter(RsxrMid::Context&); + +namespace { +struct Calls { + uint32_t player = 0, slot = 0, definition = 0, entry = 0, manager = 0, count = 0; + uint32_t destroyed = 0, records = 0, firstEntry = 0, firstOffset = 0, released = 0; +}; + +Calls g_calls; +uint32_t g_resourceRefs = 0; +uint32_t g_resources[]{tonetest::Addr(&g_resourceRefs)}; + +void RegisterObject(RsxrMid::Context& c) { + g_calls.player = c.eax; + g_calls.manager = RsxrMid::Dword(c.esp + 4); + g_calls.definition = RsxrMid::Dword(c.esp + 8); + g_calls.slot = RsxrMid::Dword(c.esp + 12); + const uint32_t store = rsxrtones::Read(g_calls.manager, 0x1A4); + + g_calls.entry = rsxrtones::Read(store, 8) + 12 * (8 + 5 * c.eax + g_calls.slot); + if (!g_calls.count) { + g_calls.firstEntry = g_calls.entry; + } + + auto* record = RsxrMid::Ptr(g_calls.entry); + + record[0] = tonetest::Addr(g_resources); + record[1] = record[0] + 4; + record[2] = record[1]; + ++g_resourceRefs; + ++g_calls.count; + (void)rsxrtones::Reference(g_calls.definition, false); // stock consumes its by-value argument + c.eax = 0xDEADBEEF; // this is a void routine, not an acceptance flag +} + +RsxrMid::CallIn g_register{&RegisterObject, RsxrMid::Mode::Full, 12}; + +void __cdecl DestroyRecords(uint32_t end, uint32_t begin) { + ++g_calls.destroyed; + g_calls.records = (end - begin) / 12; + g_calls.firstOffset = (g_calls.firstEntry - begin) / 12; + + for (uint32_t at = begin; at < end; at += 12) { + const uint32_t resourceBegin = rsxrtones::Read(at), resourceEnd = rsxrtones::Read(at, 4); + + if (!resourceBegin) { + CHECK_EQ(resourceEnd, uint32_t(0)); + continue; + } + + CHECK_EQ(resourceBegin, tonetest::Addr(g_resources)); + CHECK_EQ(resourceEnd, resourceBegin + 4); + CHECK_EQ(rsxrtones::Read(at, 8), resourceEnd); + CHECK_EQ(rsxrtones::Read(resourceBegin), tonetest::Addr(&g_resourceRefs)); + CHECK(g_resourceRefs > 0); + --g_resourceRefs; + ++g_calls.released; + } +} +} // namespace + +TEST(tone_native_registration_uses_an_isolated_store_and_preserves_definition_ownership) { + rsxrtest::Restore restoreRegister(g_rsxr_tone_register), restoreDestroy(g_rsxr_tone_destroy); + tonetest::Node definition; + + g_calls = {}; + g_rsxr_tone_register = g_register.Entry(); + g_rsxr_tone_destroy = reinterpret_cast(&DestroyRecords); + CHECK(g_rsxr_tone_register); + + { + rsxrtones::NativeRegistration store; + + CHECK(store.Register(tonetest::Addr(&definition), 0, 5)); + CHECK_EQ(definition.refs, uint32_t(0)); + CHECK_EQ(g_calls.definition, tonetest::Addr(&definition)); + CHECK_EQ(g_calls.player, uint32_t(0)); + CHECK_EQ(g_calls.slot, uint32_t(0)); + const uint32_t first = g_calls.entry; + + CHECK(store.Register(tonetest::Addr(&definition), 1, 5)); + CHECK_EQ(g_calls.player, uint32_t(1)); + CHECK_EQ(g_calls.entry - first, uint32_t(27 * 12)); + CHECK(store.Register(tonetest::Addr(&definition), 0, 26)); + CHECK_EQ(g_calls.entry - first, uint32_t(21 * 12)); + CHECK(store.Register(tonetest::Addr(&definition), 1, 26)); + CHECK_EQ(g_calls.entry - first, uint32_t(48 * 12)); + CHECK_EQ(g_calls.destroyed, uint32_t(0)); + CHECK(!store.Register(0, 0, 5)); + CHECK(!store.Register(tonetest::Addr(&definition), 2, 5)); + CHECK(!store.Register(tonetest::Addr(&definition), 0, 4)); + CHECK(!store.Register(tonetest::Addr(&definition), 0, 27)); + CHECK_EQ(g_calls.count, uint32_t(4)); + CHECK_EQ(g_resourceRefs, uint32_t(4)); + } + + CHECK_EQ(g_calls.destroyed, uint32_t(1)); + CHECK_EQ(g_calls.records, uint32_t(62)); + CHECK_EQ(g_calls.firstOffset, uint32_t(13)); // absolute Base/A..D reservation, not just relative spacing + CHECK_EQ(g_calls.released, uint32_t(4)); + CHECK_EQ(g_resourceRefs, uint32_t(0)); + CHECK_EQ(definition.refs, uint32_t(0)); +} + +TEST(tone_native_registration_rejects_unavailable_cleanup_before_taking_a_reference) { + rsxrtest::Restore restoreRegister(g_rsxr_tone_register), restoreDestroy(g_rsxr_tone_destroy); + tonetest::Node definition; + rsxrtones::NativeRegistration store; + + g_calls = {}; + g_rsxr_tone_register = g_register.Entry(); + g_rsxr_tone_destroy = 0; + CHECK(!store.Register(tonetest::Addr(&definition), 0, 5)); + CHECK_EQ(g_calls.count, uint32_t(0)); + CHECK_EQ(definition.refs, uint32_t(0)); +} + +TEST(tone_native_registration_hook_requires_native_data_and_attempts_once_per_load) { + rsxrtest::Restore restoreRegister(g_rsxr_tone_register), restoreDestroy(g_rsxr_tone_destroy), + restoreManager(g_rsxr_tone_manager), restoreGate(g_rsxr_tones); + tonetest::Node attributes, definition, marker, key("registered-echo"); + const rsxrtones::Identity id{0x8910, 2, 3, 4}; + std::array session{}; + uint32_t node = tonetest::Addr(&definition), collection[6]{}, manager = 0x1234, stack[6]{}; + const uint32_t address = tonetest::Addr(session.data()), song = 0x891011; + RsxrMid::Context context{}; + + g_calls = {}; + g_rsxr_tones = 1; + g_rsxr_tone_register = g_register.Entry(); + g_rsxr_tone_destroy = reinterpret_cast(&DestroyRecords); + g_rsxr_tone_manager = reinterpret_cast(&manager); + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &key; + definition.members["Key"] = &key; + collection[4] = tonetest::Addr(&node); + collection[5] = collection[4] + 4; + session[0x78 / 4] = song; + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + context.esp = tonetest::Addr(stack); + stack[5] = address; + rsxrtones::Capture(tonetest::Addr(&attributes), tonetest::Addr(collection), id); + RsxrTones_SongLoaded(song, false); + Rsxr_Mid_ToneRegisterAfter(context); + CHECK_EQ(g_calls.count, uint32_t(0)); + RsxrTones_SongLoaded(song, true); + Rsxr_Mid_ToneRegisterAfter(context); + Rsxr_Mid_ToneRegisterAfter(context); + CHECK_EQ(g_calls.count, uint32_t(1)); + CHECK_EQ(definition.refs, uint32_t(1)); + RsxrTones_SongLoaded(song, true); + rsxrtones::PreRegister(address); + CHECK_EQ(g_calls.count, uint32_t(2)); + CHECK_EQ(g_calls.destroyed, uint32_t(1)); + g_rsxr_tones = 0; + rsxrtones::PreRegister(address); + CHECK_EQ(g_calls.count, uint32_t(2)); + CHECK_EQ(g_calls.destroyed, uint32_t(2)); + rsxrtones::Capture(0, 0, id); + rsxrtones::PreRegister(address); + CHECK_EQ(definition.refs, uint32_t(0)); + RsxrTones_SongLoaded(song, false); +} diff --git a/tests/tones/test_registration.cpp b/tests/tones/test_registration.cpp new file mode 100644 index 0000000..d9ec5d5 --- /dev/null +++ b/tests/tones/test_registration.cpp @@ -0,0 +1,34 @@ +#include "features/tones/tones.h" +#include "hook_rules.h" +#include "model/gates.h" +#include "model/groups.h" +#include "test.h" +#include "testutil.h" + +TEST(tone_hooks_form_one_optional_failure_group) { + rsxrtest::Restore restore(g_rsxr_tones); + + Rsxr_ResetFeatureFailures(); + + for (const auto* id : + {"ToneLoad", "ToneAuto", "ToneSetup", "ToneSeek", "ToneResume", "ToneOverride", "ToneRefresh", "ToneApply", + "ToneManager", "ToneRegister", "ToneRegisterCall", "ToneResourceDestroy", "TonePlanBuild", "TonePlanField", + "TonePlanExtension", "TonePlanBound", "TonePlanEdit", "ToneContext"}) { + const auto* h = Rsxr_FindHook(id); + + CHECK(h); + CHECK(Rsxr_FeatureOf(*h) == RsxrFeature::Tones); + CHECK(h->gates & kRsxrGateTones); + g_rsxr_tones = 1; + CHECK(Rsxr_ShouldPatch(*h, false, false, true, true) == !h->ref); + g_rsxr_tones = 0; + CHECK(!Rsxr_ShouldPatch(*h, false, false, true, true)); + } + + g_rsxr_tones = 1; + CHECK(!Rsxr_IsSevenUnit(RsxrFeature::Tones)); + CHECK(Rsxr_DisableFeature(RsxrFeature::Tones)); + CHECK_EQ(g_rsxr_tones, uintptr_t(0)); + CHECK(!Rsxr_FeatureDisabled(RsxrFeature::Core)); + Rsxr_ResetFeatureFailures(); +} diff --git a/tests/tones/test_selection.cpp b/tests/tones/test_selection.cpp new file mode 100644 index 0000000..dfc7cd4 --- /dev/null +++ b/tests/tones/test_selection.cpp @@ -0,0 +1,23 @@ +#include "features/tones/selection.h" +#include "test.h" + +TEST(tone_slots_include_f_without_using_the_stock_sentinel) { + CHECK(rsxrtones::Select(true, 4) == 4); + CHECK(rsxrtones::Select(true, 5) == 5); + CHECK(rsxrtones::Select(true, 25) == 25); + CHECK(rsxrtones::Select(false, 5) == rsxrtones::kBase); + CHECK(rsxrtones::Select(true, 26) == rsxrtones::kInvalid); + CHECK(rsxrtones::Select(true, 0xFFFFFFFFu) == rsxrtones::kInvalid); +} + +TEST(tone_players_and_arrangements_have_independent_selection) { + rsxrtones::Player players[2]; + + CHECK(players[0].Needs(100, 5)); + players[0].Applied(100, 5); + CHECK(!players[0].Needs(100, 5)); + CHECK(players[1].Needs(100, 5)); + CHECK(players[0].Needs(101, 5)); + CHECK(players[0].Needs(100, rsxrtones::kBase)); + CHECK(players[0].Needs(100, 0)); +} diff --git a/tests/tones/test_state.cpp b/tests/tones/test_state.cpp new file mode 100644 index 0000000..aa031e9 --- /dev/null +++ b/tests/tones/test_state.cpp @@ -0,0 +1,361 @@ +#include "features/tones/game.h" +#include "features/tones/state.h" +#include "features/tones/tones.h" +#include "json_fixture.h" +#include "platform/log.h" +#include "test.h" +#include "testutil.h" +#include +#include + +extern "C" uintptr_t g_rsxr_tone_apply, g_rsxr_tone_manager; +extern "C" uintptr_t g_rsxr_tone_context; +extern "C" void Rsxr_Mid_ToneAutoBefore(RsxrMid::Context&); +extern "C" void Rsxr_Mid_ToneAutoAfter(RsxrMid::Context&); +extern "C" void Rsxr_Mid_ToneLoad(RsxrMid::Context&); + +namespace { +uint32_t g_objects[8]{}, g_players[8]{}, g_calls = 0; + +void ApplyObject(RsxrMid::Context& c) { + if (g_calls < 8) { + g_objects[g_calls] = RsxrMid::Dword(c.esi); + g_players[g_calls] = RsxrMid::Dword(c.esp + 8); + } + + ++g_calls; + c.eax = 1; +} + +RsxrMid::CallIn g_applyObject{&ApplyObject, RsxrMid::Mode::Full, 12}; + +std::vector g_logs; + +void CaptureLog(const char* text) { + g_logs.emplace_back(text); +} + +struct Logging { + Logging() { + g_logs.clear(); + RsxrLog_SetSink(CaptureLog); + } + + ~Logging() { RsxrLog_SetSink(nullptr); } +}; + +size_t Lines(const char* text) { + size_t count = 0; + + for (const auto& line : g_logs) { + count += line.find(text) != std::string::npos; + } + + return count; +} +} // namespace + +TEST(tone_names_use_the_manifest_string_accessor) { + // 0x8899F0 reads virtual +60h. +64h is intentionally absent from this fixture. + tonetest::Node attributes, key("Cleanalt"); + char text[256]{}; + + attributes.members["Tone_E"] = &key; + CHECK(rsxrtones::Name(tonetest::Addr(&attributes), "Tone_E", text, sizeof text)); + CHECK(std::strcmp(text, "Cleanalt") == 0); + CHECK(!rsxrtones::Name(tonetest::Addr(&attributes), "Tone_F", text, sizeof text)); +} + +TEST(tone_load_hook_resolves_attributes_from_the_parent_arrangement) { + rsxrtest::Restore restore(g_rsxr_tones); + const Logging logging; + tonetest::Node parent, attributes, marker, echo("echo"), foxtrot("foxtrot"); + const rsxrtones::Identity id{0x6789, 2, 3, 4}; + std::array frame{}, session{}; + RsxrMid::Context context{}; + const uint32_t song = 0x6789AB, address = tonetest::Addr(session.data()); + + g_rsxr_tones = 1; + parent.members["Attributes"] = &attributes; + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &echo; + attributes.members["Tone_F"] = &foxtrot; + context.ebp = tonetest::Addr(frame.data()) + 0x3A0; + frame[0x3AC / 4] = tonetest::Addr(&parent); // [EBP+0Ch] is the parent, as at 0x56774C + std::memcpy(frame.data(), id.data(), sizeof id); + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + session[0x78 / 4] = song; + Rsxr_Mid_ToneLoad(context); + CHECK_EQ(Lines("extra tones=2 slots=E,F marker=26 captured"), size_t(1)); + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK(rsxrtones::Handle(address, true, 5, false)); + parent.members.clear(); + Rsxr_Mid_ToneLoad(context); // missing Attributes must discard the previous capture + CHECK(!rsxrtones::Handle(address, true, 4, false)); + RsxrTones_SongLoaded(song, false); +} + +TEST(tone_load_decisions_and_first_event_are_bounded_even_when_application_fails) { + rsxrtest::Restore restore(g_rsxr_tones); + const Logging logging; + tonetest::Node attributes, marker, extra("missing"); + const rsxrtones::Identity id{0x4567, 2, 3, 4}; + std::array session{}; + const uint32_t song = 0x456789, address = tonetest::Addr(session.data()); + const float time = 8.25f; + + g_rsxr_tones = 1; + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &extra; + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + std::memcpy(reinterpret_cast(session.data()) + 0x3B4, &time, sizeof time); + session[0x78 / 4] = song; + rsxrtones::Capture(tonetest::Addr(&attributes), 0, id); + RsxrTones_SongLoaded(song, true); + + for (int i = 0; i < 4; ++i) { + CHECK(rsxrtones::Handle(address, true, 4, false)); + } + + CHECK_EQ(Lines("player=0 extra tones 1 (E), active"), size_t(1)); + CHECK_EQ(Lines("first event raw=4 time=8.250"), size_t(1)); + CHECK_EQ(Lines("id=4 key='missing' rejected"), size_t(1)); + CHECK_EQ(Lines("register player=0 slot=5 key='missing' rejected: missing or ambiguous definition"), size_t(1)); + CHECK(rsxrtones::Handle(address, false, 0, false)); + CHECK(rsxrtones::Handle(address, true, 0, false)); + CHECK_EQ(Lines("id=26 key='' rejected"), size_t(1)); + CHECK_EQ(Lines("id=0 key='' rejected"), size_t(1)); + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(address, true, 5, false)); + CHECK_EQ(Lines("first event raw="), size_t(2)); + CHECK_EQ(Lines("player=0 extra tones 1 (E), active"), size_t(2)); + CHECK_EQ(Lines("register player=0 slot=5 key='missing' rejected: missing or ambiguous definition"), size_t(2)); + RsxrTones_SongLoaded(song, false); + CHECK(!rsxrtones::Handle(address, true, 4, false)); + CHECK(!rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(Lines("rejected: SNG is not native"), size_t(1)); + rsxrtones::Capture(0, 0, id); +} + +TEST(tone_inactive_sessions_explain_missing_capture_marker_and_extra_tones) { + rsxrtest::Restore restore(g_rsxr_tones); + const Logging logging; + tonetest::Node attributes, extra("Cleanalt"); + const rsxrtones::Identity id{0x5678, 2, 3, 4}; + std::array session{}; + const uint32_t song = 0x56789A, address = tonetest::Addr(session.data()); + + g_rsxr_tones = 1; + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + session[0x78 / 4] = song; + RsxrTones_SongLoaded(song, true); + CHECK(!rsxrtones::Handle(address, false, 0, false)); + CHECK(!rsxrtones::Handle(address, false, 0, false)); + CHECK_EQ(Lines("rejected: manifest not captured"), size_t(1)); + rsxrtones::Capture(tonetest::Addr(&attributes), 0, id); + CHECK(!rsxrtones::Handle(address, false, 0, false)); + CHECK_EQ(Lines("player=0 no extra tones"), size_t(1)); + attributes.members["Tone_E"] = &extra; + rsxrtones::Capture(tonetest::Addr(&attributes), 0, id); + CHECK(!rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(Lines("player=0 rejected: missing or invalid RsxrToneSlots"), size_t(1)); // the capture logs it too + g_rsxr_tones = 0; + CHECK(!rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(Lines("rejected: feature disabled"), size_t(1)); + g_rsxr_tones = 1; + rsxrtones::Capture(0, 0, id); + RsxrTones_SongLoaded(song, false); +} + +TEST(tone_definition_lookup_rejects_ambiguous_case_insensitive_keys) { + tonetest::Node first, second, firstKey("crunch"), secondKey("CRUNCH"); + + first.members["Key"] = &firstKey; + second.members["Key"] = &secondKey; + + uint32_t nodes[] = {tonetest::Addr(&first), tonetest::Addr(&second)}; + uint32_t collection[6]{}; + + collection[4] = tonetest::Addr(nodes); + collection[5] = collection[4] + 4; + CHECK_EQ(rsxrtones::Definition(tonetest::Addr(collection), "CRUNCH"), tonetest::Addr(&first)); + CHECK_EQ(first.refs, uint32_t(1)); + CHECK(rsxrtones::Reference(tonetest::Addr(&first), false)); + collection[5] += 4; + CHECK_EQ(rsxrtones::Definition(tonetest::Addr(collection), "crunch"), uint32_t(0)); + first.canonical = false; + CHECK_EQ(rsxrtones::Definition(tonetest::Addr(collection), "crunch"), uint32_t(0)); + CHECK_EQ(first.refs, uint32_t(0)); + CHECK_EQ(second.refs, uint32_t(0)); +} + +TEST(tone_state_requires_native_sng_and_discards_replaced_manifest_data) { + rsxrtest::Restore restore(g_rsxr_tones); + tonetest::Node attributes, marker, extra("missing-definition"); + const rsxrtones::Identity id{0x1234, 2, 3, 4}; + std::array session{}; + const uint32_t song = 0x123456, address = tonetest::Addr(session.data()); + + g_rsxr_tones = 1; + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &extra; + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + session[0x78 / 4] = song; + rsxrtones::Capture(tonetest::Addr(&attributes), 0, id); + RsxrTones_SongLoaded(song, false); + CHECK(!rsxrtones::Handle(address, true, 4, false)); + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(address, true, 4, false)); // missing definition is owned/rejected, never a stock ID + CHECK(rsxrtones::Handle(address, true, 5, false)); // F must not become the stock sentinel + CHECK(rsxrtones::Handle(address, true, 1000, false)); + RsxrTones_SongLoaded(song, false); + CHECK(!rsxrtones::Handle(address, true, 4, false)); + RsxrTones_SongLoaded(song, true); + rsxrtones::Capture(0, 0, id); // same arrangement identity, now without native extra fields + CHECK(!rsxrtones::Handle(address, true, 4, false)); + RsxrTones_SongLoaded(song, false); +} + +TEST(tone_players_apply_their_own_definitions_and_reload_resets_selection) { + rsxrtest::Restore restore(g_rsxr_tones), restoreApply(g_rsxr_tone_apply), + restoreManager(g_rsxr_tone_manager); + tonetest::Node attributes[2], definitions[2], marker, keys[2]{tonetest::Node("first"), tonetest::Node("second")}; + std::array sessions[2]{}; + const rsxrtones::Identity ids[2]{{0x2345, 2, 3, 4}, {0x3456, 2, 3, 4}}; + uint32_t manager = 0x1234, nodes[2]{}, collections[2][6]{}; + const uint32_t song = 0x234567; + + g_rsxr_tones = 1; + g_rsxr_tone_apply = g_applyObject.Entry(); + g_rsxr_tone_manager = reinterpret_cast(&manager); + g_calls = 0; + CHECK(g_rsxr_tone_apply); + + for (uint32_t i = 0; i < 2; ++i) { + attributes[i].members["RsxrToneSlots"] = ▮ + attributes[i].members["Tone_E"] = &keys[i]; + definitions[i].members["Key"] = &keys[i]; + nodes[i] = tonetest::Addr(&definitions[i]); + collections[i][4] = tonetest::Addr(&nodes[i]); + collections[i][5] = collections[i][4] + 4; + sessions[i][2] = i; + sessions[i][0x78 / 4] = song; + sessions[i][0x228 / 4] = nodes[i]; // Base for the before-first-event check + std::memcpy(reinterpret_cast(sessions[i].data()) + 0x68, ids[i].data(), sizeof ids[i]); + rsxrtones::Capture(tonetest::Addr(&attributes[i]), tonetest::Addr(collections[i]), ids[i]); + CHECK_EQ(definitions[i].refs, uint32_t(1)); + } + + attributes[1].members["Tone_F"] = &keys[1]; + rsxrtones::Capture(tonetest::Addr(&attributes[1]), tonetest::Addr(collections[1]), ids[1]); + + const uint32_t first = tonetest::Addr(sessions[0].data()), second = tonetest::Addr(sessions[1].data()); + + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(first, true, 4, false)); + CHECK(rsxrtones::Handle(second, true, 4, false)); + CHECK(rsxrtones::Handle(first, true, 4, false)); + CHECK_EQ(g_calls, uint32_t(2)); + CHECK_EQ(g_objects[0], nodes[0]); + CHECK_EQ(g_players[0], uint32_t(0)); + CHECK_EQ(g_objects[1], nodes[1]); + CHECK_EQ(g_players[1], uint32_t(1)); + + uint32_t raw = 5, stack[7]{}; + RsxrMid::Context context{}; + + context.esp = tonetest::Addr(stack); + context.esi = second; + context.eax = 1; + stack[6] = tonetest::Addr(&raw); + Rsxr_Mid_ToneAutoBefore(context); + Rsxr_Mid_ToneAutoAfter(context); + CHECK_EQ(g_calls, uint32_t(3)); + CHECK_EQ(g_objects[2], nodes[1]); + CHECK_EQ(g_players[2], uint32_t(1)); + CHECK_EQ(raw, rsxrtones::kInvalid); // stock dispatch must never see F as its no-tone sentinel + CHECK((context.eax & 0xFF) == 1); + RsxrTones_SongLoaded(song, true); // native reload at the same song and session addresses + CHECK(rsxrtones::Handle(first, true, 4, false)); + CHECK_EQ(g_calls, uint32_t(4)); + CHECK(rsxrtones::Handle(first, false, 0, true)); + CHECK_EQ(g_calls, uint32_t(5)); + CHECK(rsxrtones::Handle(first, true, 5, false)); // undeclared F is rejected, not Base + CHECK_EQ(g_calls, uint32_t(5)); + + for (uint32_t i = 0; i < 2; ++i) { + rsxrtones::Capture(0, 0, ids[i]); + CHECK(!rsxrtones::Handle(tonetest::Addr(sessions[i].data()), true, 4, false)); + CHECK_EQ(definitions[i].refs, uint32_t(0)); + } + + RsxrTones_SongLoaded(song, false); +} + +TEST(toneplan_playback_honours_replacement_and_reset_without_a_new_timeline_id) { + rsxrtest::Restore restore(g_rsxr_tones), restoreApply(g_rsxr_tone_apply), + restoreManager(g_rsxr_tone_manager), restoreContext(g_rsxr_tone_context); + const Logging logging; + tonetest::Context context; + tonetest::Node attributes, marker, key("echo"), original, edited, replacement; + const rsxrtones::Identity id{0xABCDE, 2, 3, 4}; + std::array session{}; + uint32_t manager = 0x1234, node = tonetest::Addr(&original), collection[6]{}; + const uint32_t song = 0xABCDEF, address = tonetest::Addr(session.data()); + + g_rsxr_tones = 1; + g_rsxr_tone_apply = g_applyObject.Entry(); + g_rsxr_tone_manager = tonetest::Addr(&manager); + g_rsxr_tone_context = context.Global(); + g_calls = 0; + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &key; + original.members["Key"] = &key; + edited.members["Key"] = &key; + replacement.members["Key"] = &key; // same Key, different object: still must reapply + collection[4] = tonetest::Addr(&node); + collection[5] = collection[4] + 4; + session[0x78 / 4] = song; + session[0x228 / 4] = node; + session[0x22C / 4] = node; + std::memcpy(reinterpret_cast(session.data()) + 0x68, id.data(), sizeof id); + rsxrtones::Capture(tonetest::Addr(&attributes), tonetest::Addr(collection), id); + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(g_objects[0], node); + context.players[0].members["LAS_ToneCustomData_ToneE"] = &edited; + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(g_calls, 2u); + CHECK_EQ(g_objects[1], tonetest::Addr(&edited)); + CHECK_EQ(edited.refs, 1u); + CHECK_EQ(Lines("override slot=E key='echo' applied"), size_t(1)); + context.players[0].members["LAS_ToneCustomData_ToneE"] = &replacement; + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(g_objects[2], tonetest::Addr(&replacement)); + CHECK_EQ(edited.refs, 0u); + context.players[0].members.erase("LAS_ToneCustomData_ToneE"); + CHECK(rsxrtones::Handle(address, true, 4, false)); + CHECK_EQ(g_objects[3], node); + CHECK_EQ(replacement.refs, 0u); + CHECK_EQ(Lines("override slot=E key='echo' none"), size_t(2)); + context.players[0].members["LAS_ToneCustomData_ToneBase"] = &edited; + context.players[0].members["LAS_ToneCustomData_ToneA"] = &replacement; + CHECK(rsxrtones::Handle(address, false, 0, false)); + CHECK_EQ(g_objects[4], tonetest::Addr(&edited)); + CHECK(rsxrtones::Handle(address, true, 0, false)); + CHECK_EQ(g_objects[5], tonetest::Addr(&replacement)); + RsxrTones_SongLoaded(song, false); + CHECK(!rsxrtones::Handle(address, true, 0, false)); + CHECK_EQ(replacement.refs, 0u); + CHECK_EQ(g_calls, 6u); + context.players[0].members["LAS_ToneCustomData_ToneZ"] = &edited; + RsxrTones_SongLoaded(song, true); + CHECK(rsxrtones::Handle(address, true, 25, false)); // unused Z cannot borrow a stale context override + CHECK_EQ(g_calls, 6u); + CHECK_EQ(edited.refs, 0u); + rsxrtones::Capture(0, 0, id); + CHECK(!rsxrtones::Handle(address, true, 0, false)); + CHECK_EQ(original.refs, 0u); +} diff --git a/tests/tones/test_toneplan.cpp b/tests/tones/test_toneplan.cpp new file mode 100644 index 0000000..7ce0b74 --- /dev/null +++ b/tests/tones/test_toneplan.cpp @@ -0,0 +1,132 @@ +#include "features/tones/game.h" +#include "features/tones/toneplan.h" +#include "features/tones/tones.h" +#include "json_fixture.h" +#include "model/gamestring.h" +#include "test.h" +#include "testutil.h" +#include + +extern "C" uintptr_t g_rsxr_tone_context; +extern "C" uintptr_t g_rsxr_resume_TonePlanField, g_rsxr_resume_TonePlanExtension, g_rsxr_resume_TonePlanBound; +extern "C" void Rsxr_Mid_TonePlanBefore(RsxrMid::Context&); +extern "C" void Rsxr_Mid_TonePlanAfter(RsxrMid::Context&); +extern "C" void Rsxr_Mid_TonePlanField(RsxrMid::Context&); +extern "C" void Rsxr_Mid_TonePlanExtension(RsxrMid::Context&); +extern "C" void Rsxr_Mid_TonePlanBound(RsxrMid::Context&); + +TEST(toneplan_uses_only_marked_extra_arrangements_and_preserves_sparse_letters) { + rsxrtest::Restore restore(g_rsxr_tones); + tonetest::Node attributes, marker, base("clean"), echo("same"), zulu("same"); + + g_rsxr_tones = 1; + attributes.members["Tone_Base"] = &base; + attributes.members["Tone_E"] = &echo; + attributes.members["Tone_Z"] = &zulu; + CHECK_EQ(rsxrtones::PlanSlots(tonetest::Addr(&attributes)), 0u); + attributes.members["RsxrToneSlots"] = ▮ + CHECK_EQ(rsxrtones::PlanSlots(tonetest::Addr(&attributes)), (1u << 26) | (1u << 5) | 1u); + attributes.members.erase("Tone_E"); + attributes.members.erase("Tone_Z"); + CHECK_EQ(rsxrtones::PlanSlots(tonetest::Addr(&attributes)), 0u); + attributes.members["Tone_Z"] = &zulu; + marker.number = 25; + CHECK_EQ(rsxrtones::PlanSlots(tonetest::Addr(&attributes)), 0u); + marker.number = 26; + g_rsxr_tones = 0; + CHECK_EQ(rsxrtones::PlanSlots(tonetest::Addr(&attributes)), 0u); +} + +TEST(toneplan_name_views_have_the_game_string_layout_for_all_27_slots) { + for (uint32_t slot = 0; slot < 27; ++slot) { + char extension[16]{}, field[16]{}; + + CHECK(rsxr::ReadGameString(reinterpret_cast(uintptr_t(rsxrtones::PlanName(slot, false))), extension, + sizeof extension)); + CHECK(rsxr::ReadGameString(reinterpret_cast(uintptr_t(rsxrtones::PlanName(slot, true))), field, + sizeof field)); + CHECK(std::strcmp(extension, rsxrtones::SlotExtension(slot)) == 0); + CHECK(std::strncmp(field, "Tone_", 5) == 0); + + if (slot) { + CHECK_EQ(extension[4], static_cast('A' + slot - 1)); + CHECK_EQ(field[5], static_cast('A' + slot - 1)); + } + } + + CHECK_EQ(rsxrtones::PlanName(27, true), 0u); + CHECK(rsxrtones::SlotExtension(27) == nullptr); + CHECK(std::strcmp(rsxrtones::SlotExtension(0), "ToneBase") == 0); +} + +TEST(toneplan_wrap_redirects_both_sources_and_bound_and_restores_nested_stock_calls) { + rsxrtest::Restore restore(g_rsxr_tones), restoreField(g_rsxr_resume_TonePlanField), + restoreExtension(g_rsxr_resume_TonePlanExtension), restoreBound(g_rsxr_resume_TonePlanBound); + tonetest::Node attributes, marker, echo("echo"); + uint32_t frame[7]{}; + RsxrMid::Context c{}; + + g_rsxr_tones = 1; + g_rsxr_resume_TonePlanField = 0x649D19; + g_rsxr_resume_TonePlanExtension = 0x649E67; + g_rsxr_resume_TonePlanBound = 0x64AB6D; + attributes.members["RsxrToneSlots"] = ▮ + attributes.members["Tone_E"] = &echo; + c.esp = tonetest::Addr(frame); + frame[6] = tonetest::Addr(&attributes); + Rsxr_Mid_TonePlanBefore(c); + CHECK(rsxrtones::PlanActive()); + + for (uint32_t slot : {0u, 5u, 26u}) { + c.eax = slot * 0x18; + Rsxr_Mid_TonePlanField(c); + CHECK_EQ(c.edi, rsxrtones::PlanName(slot, true)); + CHECK_EQ(c.jump, uint32_t(g_rsxr_resume_TonePlanField)); + Rsxr_Mid_TonePlanExtension(c); + CHECK_EQ(c.eax, rsxrtones::PlanName(slot, false)); + CHECK_EQ(c.jump, uint32_t(g_rsxr_resume_TonePlanExtension)); + } + + c.eax = 26; + Rsxr_Mid_TonePlanBound(c); + CHECK_EQ(c.jump, 0x649CA5u); + CHECK(c.eflags & 1u); + c.eax = 27; + Rsxr_Mid_TonePlanBound(c); + CHECK_EQ(c.jump, 0x64AB6Du); + CHECK(c.eflags & 0x40u); + const uint32_t outer = rsxrtones::BeginPlan(0); + + CHECK(!rsxrtones::PlanActive()); + c.eax = 5; + c.jump = 123; + c.eflags = 456; + Rsxr_Mid_TonePlanBound(c); + CHECK_EQ(c.jump, 123u); + CHECK_EQ(c.eflags, 456u); + rsxrtones::EndPlan(outer); + CHECK(rsxrtones::PlanActive()); + Rsxr_Mid_TonePlanAfter(c); + CHECK(!rsxrtones::PlanActive()); +} + +TEST(toneplan_override_reads_the_stock_player_context_and_retains_the_object) { + rsxrtest::Restore restore(g_rsxr_tone_context); + tonetest::Context context; + tonetest::Node echo, zulu; + + g_rsxr_tone_context = context.Global(); + context.players[0].members["LAS_ToneCustomData_ToneE"] = &echo; + context.players[1].members["LAS_ToneCustomData_ToneZ"] = &zulu; + CHECK_EQ(rsxrtones::Override(0, 5), tonetest::Addr(&echo)); + CHECK_EQ(echo.refs, 1u); + CHECK(rsxrtones::Reference(tonetest::Addr(&echo), false)); + CHECK_EQ(rsxrtones::Override(1, 26), tonetest::Addr(&zulu)); + CHECK(rsxrtones::Reference(tonetest::Addr(&zulu), false)); + CHECK_EQ(rsxrtones::Override(1, 5), 0u); + CHECK_EQ(rsxrtones::Override(2, 26), 0u); + context.players[0].members.clear(); + CHECK_EQ(rsxrtones::Override(0, 5), 0u); + CHECK_EQ(echo.refs, 0u); + CHECK_EQ(zulu.refs, 0u); +} diff --git a/tools/check_exports.py b/tools/check_exports.py index c6a12e4..ea54848 100644 --- a/tools/check_exports.py +++ b/tools/check_exports.py @@ -43,6 +43,28 @@ "RsxrMid_Thunk", "RsxrMid_ThunkLight", "RsxrMid_ThunkSse", + # Tone sites are installed by emu_harness.py, including both callbacks of each wrapper. + "Rsxr_Mid_ToneLoad", + "Rsxr_Mid_ToneAutoBefore", + "Rsxr_Mid_ToneOtherBefore", + "Rsxr_Mid_ToneAutoAfter", + "Rsxr_Mid_ToneOtherAfter", + "Rsxr_Mid_ToneRefreshAfter", + "Rsxr_Mid_ToneRegisterAfter", + "g_rsxr_tone_apply", + "g_rsxr_tone_manager", + "g_rsxr_tone_register", + "g_rsxr_tone_destroy", + "g_rsxr_tone_context", + "Rsxr_Mid_TonePlanBefore", + "Rsxr_Mid_TonePlanAfter", + "Rsxr_Mid_TonePlanField", + "Rsxr_Mid_TonePlanExtension", + "Rsxr_Mid_TonePlanBound", + "Rsxr_Mid_TonePlanEdit", + "g_rsxr_resume_TonePlanField", + "g_rsxr_resume_TonePlanExtension", + "g_rsxr_resume_TonePlanBound", ] FORBIDDEN_IMPORTS = ["d3d9.dll"] IMAGE_BASE = 0x5E000000 diff --git a/tools/native_chart.py b/tools/native_chart.py index 94d06c3..97ad44e 100644 --- a/tools/native_chart.py +++ b/tools/native_chart.py @@ -23,6 +23,7 @@ import argparse import json +import math import struct import zlib from dataclasses import dataclass, field @@ -74,6 +75,7 @@ class _Layout: sections: list = field(default_factory=list) notes: list = field(default_factory=list) tuning: tuple = (0, 0) + tones: tuple = (0, 0) end: int = 0 @@ -93,8 +95,12 @@ def _walk(data, width, start=0): for _ in range(reader.count(8)): # NewLinkedDifficulties reader.take(4) reader.array(4) - for size in (260, 260, 8, 8): # Actions, Events, Tones, DNA + for size in (260, 260): # Actions, Events reader.array(size) + tone_start = reader.pos + reader.array(8) + layout.tones = (tone_start, reader.pos) + reader.array(8) # DNA layout.sections = reader.array(88) for _ in range(reader.count(36)): # Levels reader.take(4) # difficulty @@ -460,6 +466,45 @@ def pack_sng(body): return _pack("II", 0x4A, 1) + bytes(16) + _pack("I", len(body)) + zlib.compress(body, 9) + bytes(56) +def tone_names(attributes): + """A..Z names, with empty strings for unused slots (Base is separate).""" + result = [attributes.get(f"Tone_{chr(65 + i)}", "") for i in range(26)] + if any(not isinstance(key, str) for key in result): + raise ValueError("Tone_A..Tone_Z must be strings") + return result + + +def _tone_layout(body): + if body.startswith(b"SNXR"): + _, width, _, start = _native_header(body) + return _walk(body, width, start) + return _walk(body, 6) + + +def read_tone_changes(body): + """Read the complete timeline from a native or internal stock body, without remapping raw IDs.""" + start, end = _tone_layout(body).tones + return list(struct.iter_unpack(" int: JMP_BUILDERS = ("RsxrMid_Build", "RsxrMid_BuildLight", "RsxrMid_BuildSse") # by mode -# Ref sites (never written): the variable Rsxr_Startup stores the site's dword in. -REF_VARS = { - "X_DKEY": "g_rsxr_dkey", - "X_DNUMBER": "g_rsxr_dnumber", - "X_DSET": "g_rsxr_dset", - "X_DDROP": "g_rsxr_ddrop", - "X_ATTACH": "g_rsxr_fn_attach", - "X_CM": "g_rsxr_colormgr", - "X_TCS": "g_rsxr_texlist_cs", - "X_THEAD": "g_rsxr_texlist_head", - "X_SPAWN": "g_rsxr_fn_spawn", - "X_ADV3": "g_rsxr_fn_adv3", - "X_ALLOC": "g_rsxr_fn_alloc", - "X_STRCTOR": "g_rsxr_fn_strctor", - "X_SHAPE": "g_rsxr_fn_shape", - "X_SHOW": "g_rsxr_fn_show", - "X_DETACH": "g_rsxr_fn_detach", - "X_SETPOS": "g_rsxr_fn_setpos", - "X_SETROT": "g_rsxr_fn_setrot", - "X_DT": "g_rsxr_frame_global", - "X_WORLD": "g_rsxr_fn_world", - "X_ROOT": "g_rsxr_fn_root", - "X_SETSCALE": "g_rsxr_fn_setscale", - "MenuMovieRequest": "g_rsxr_menu_request", - "X_EULER": "g_rsxr_fn_euler", - "X_PEGNAMES": "g_rsxr_pegnames", - "X_PEGSELECT": "g_rsxr_fn_pegselect", - "X_PEGPLACE": "g_rsxr_fn_pegplace", - "X_PEGLAYER": "g_rsxr_fn_peglayer", - "X_TMGR": "g_rsxr_tuner_mgr", - "X_WTHR": "g_rsxr_wrong_const", - "X_FADEMGR": "g_rsxr_fade_mgr", - "X_FADEIN": "g_rsxr_fn_fadein", - "X_FADEOUT": "g_rsxr_fn_fadeout", - "X_FIXSTR": "g_rsxr_fn_fixstr", - "X_STRPARAMS": "g_rsxr_fn_strparams", - "X_TBASS": "g_rsxr_tuner_bassbase", - "X_DDSH": "g_rsxr_fn_dds", - "X_NFCTOR": "g_rsxr_fn_nfctor", - "X_NFDTOR": "g_rsxr_fn_nfdtor", - "X_GETDET": "g_rsxr_fn_getdet", - **private_features.get("EXPORTS", {}), # the private extras - "X_SST": "g_rsxr_fn_sst", - "X_STRCON": "g_rsxr_fn_strcon", - "X_STRASG": "g_rsxr_fn_strasg", - "X_LOC": "g_rsxr_fn_loc", - "X_STRDTOR": "g_rsxr_fn_strdtor", - "X_MSORT": "g_rsxr_fn_msort", - "X_MINS1": "g_rsxr_fn_mins1", - "X_MINS2": "g_rsxr_fn_mins2", - "X_MCMP": "g_rsxr_fn_mcmp", - "X_MTAB": "g_rsxr_matcher_table", - "X_EVREL": "g_rsxr_fn_evrel", -} +from emu_refs import REF_VARS # noqa: E402 + # Void cdecl loggers called by stubs that also call testable C code (NG9 -> Rsxr_NeckRow6N runs for # real, its once-per-song logger Rsxr_NeckLog needs Win32 and is replaced with `ret`). VOID_C_EXPORTS = ("Rsxr_NeckLog", "Rsxr_S7LogMask", "Rsxr_HeadLog", "Rsxr_DiagNoteHead", "RsxrPitch_FloorLog") diff --git a/tools/tests/emu_refs.py b/tools/tests/emu_refs.py new file mode 100644 index 0000000..4c1c46c --- /dev/null +++ b/tools/tests/emu_refs.py @@ -0,0 +1,63 @@ +"""Ref sites of the emulator harness (emu_harness.py): kept apart to keep the harness under the line limit.""" + +import private_features + +# Ref sites (never written): the variable Rsxr_Startup stores the site's dword in. +REF_VARS = { + "X_DKEY": "g_rsxr_dkey", + "X_DNUMBER": "g_rsxr_dnumber", + "X_DSET": "g_rsxr_dset", + "X_DDROP": "g_rsxr_ddrop", + "X_ATTACH": "g_rsxr_fn_attach", + "X_CM": "g_rsxr_colormgr", + "X_TCS": "g_rsxr_texlist_cs", + "X_THEAD": "g_rsxr_texlist_head", + "X_SPAWN": "g_rsxr_fn_spawn", + "X_ADV3": "g_rsxr_fn_adv3", + "X_ALLOC": "g_rsxr_fn_alloc", + "X_STRCTOR": "g_rsxr_fn_strctor", + "X_SHAPE": "g_rsxr_fn_shape", + "X_SHOW": "g_rsxr_fn_show", + "X_DETACH": "g_rsxr_fn_detach", + "X_SETPOS": "g_rsxr_fn_setpos", + "X_SETROT": "g_rsxr_fn_setrot", + "X_DT": "g_rsxr_frame_global", + "X_WORLD": "g_rsxr_fn_world", + "X_ROOT": "g_rsxr_fn_root", + "X_SETSCALE": "g_rsxr_fn_setscale", + "MenuMovieRequest": "g_rsxr_menu_request", + "X_EULER": "g_rsxr_fn_euler", + "X_PEGNAMES": "g_rsxr_pegnames", + "X_PEGSELECT": "g_rsxr_fn_pegselect", + "X_PEGPLACE": "g_rsxr_fn_pegplace", + "X_PEGLAYER": "g_rsxr_fn_peglayer", + "X_TMGR": "g_rsxr_tuner_mgr", + "X_WTHR": "g_rsxr_wrong_const", + "X_FADEMGR": "g_rsxr_fade_mgr", + "X_FADEIN": "g_rsxr_fn_fadein", + "X_FADEOUT": "g_rsxr_fn_fadeout", + "X_FIXSTR": "g_rsxr_fn_fixstr", + "X_STRPARAMS": "g_rsxr_fn_strparams", + "X_TBASS": "g_rsxr_tuner_bassbase", + "X_DDSH": "g_rsxr_fn_dds", + "X_NFCTOR": "g_rsxr_fn_nfctor", + "X_NFDTOR": "g_rsxr_fn_nfdtor", + "X_GETDET": "g_rsxr_fn_getdet", + **private_features.get("EXPORTS", {}), # the private extras + "X_SST": "g_rsxr_fn_sst", + "X_STRCON": "g_rsxr_fn_strcon", + "X_STRASG": "g_rsxr_fn_strasg", + "X_LOC": "g_rsxr_fn_loc", + "X_STRDTOR": "g_rsxr_fn_strdtor", + "X_MSORT": "g_rsxr_fn_msort", + "X_MINS1": "g_rsxr_fn_mins1", + "X_MINS2": "g_rsxr_fn_mins2", + "X_MCMP": "g_rsxr_fn_mcmp", + "X_MTAB": "g_rsxr_matcher_table", + "X_EVREL": "g_rsxr_fn_evrel", + "ToneApply": "g_rsxr_tone_apply", + "ToneManager": "g_rsxr_tone_manager", + "ToneRegisterCall": "g_rsxr_tone_register", + "ToneResourceDestroy": "g_rsxr_tone_destroy", + "ToneContext": "g_rsxr_tone_context", +} diff --git a/tools/tests/test_emu_tones.py b/tools/tests/test_emu_tones.py new file mode 100644 index 0000000..1025b37 --- /dev/null +++ b/tools/tests/test_emu_tones.py @@ -0,0 +1,105 @@ +"""Tone wrappers preserve stock results without an active extended session. + +The real callbacks run with no session (timeline/registration) or force=false (refresh), avoiding the +loader's runtime-constructed manifest cache. Owned stand-ins isolate the game callees' stack ABI. +""" + +import struct + +import pytest +from unicorn.x86_const import UC_X86_REG_EAX, UC_X86_REG_EBX, UC_X86_REG_EFLAGS, UC_X86_REG_ESI, UC_X86_REG_ESP + +from emu_harness import RET_MAGIC, S7_ESP, S7_MEM, S7_REGS, needs_emu, run_s7_site, site_target, site_va, stack + +pytestmark = needs_emu + + +@pytest.mark.parametrize("sid", ["ToneAuto", "ToneSetup", "ToneSeek", "ToneResume", "ToneOverride"]) +@pytest.mark.parametrize("raw,result", [(0, 0xA1B2C300), (3, 0xA1B2C301), (5, 0xA1B2C301)]) +def test_timeline_without_session_preserves_stock_result(emus, sid, raw, result): + # The lookup writes the output ID and returns a bool in AL; upper EAX bits must survive too. + callee = site_target(sid) + code = bytes.fromhex("8B 44 24 08 C7 00") + struct.pack("{...}` declarations in the features' -hooks.h. No DLL or game needed.""" +hooks.h, or inline aggregate initializers in a row (omitted cleanup defaults to Stdcall). No DLL or game needed.""" from __future__ import annotations @@ -12,8 +12,13 @@ REPO = Path(__file__).resolve().parents[2] FEATURES = REPO / "src" / "features" -ROW = re.compile(r'Rsxr_WrapRow\(\s*Rsxr_Site\(\s*"(\w+)"\).*?(kRsxrWrap\w+),\s*(&\w+|nullptr),\s*(&\w+|nullptr)', re.S) +ROW = re.compile( + r'Rsxr_WrapRow\(\s*Rsxr_Site\(\s*"(\w+)"[^)]*\)(?:\s*\.\w+\([^)]*\))*,\s*' + r"(kRsxrWrap\w+|\{[^}]*\}),\s*(&\w+|nullptr),\s*(&\w+|nullptr)", + re.S, +) FRAME = re.compile(r"inline constexpr RsxrMid::Wrap (kRsxrWrap\w+)\{(\d+), RsxrMid::Conv::(\w+)(?:, (\d+))?\}") +INLINE_FRAME = re.compile(r"\{\s*(\d+)(?:,\s*RsxrMid::Conv::(Stdcall|Cdecl)(?:,\s*(\d+))?)?\s*\}") def callback(token: str) -> str | None: @@ -29,8 +34,15 @@ def registered() -> dict[str, tuple]: rows = {} for source in FEATURES.glob("*/registration.cpp"): for sid, frame, before, after in ROW.findall(source.read_text(encoding="utf-8")): - assert frame in frames, f"{sid}: {frame} is not declared in a feature's hooks.h" - rows[sid] = (*frames[frame], callback(before), callback(after)) + if frame.startswith("{"): + inline = INLINE_FRAME.fullmatch(frame) + assert inline, f"{sid}: unrecognised inline frame {frame}" + args, conv, locals_ = inline.groups() + layout = (int(args), 0 if conv == "Cdecl" else 4 * int(args), int(locals_ or 0)) + else: + assert frame in frames, f"{sid}: {frame} is not declared in a feature's hooks.h" + layout = frames[frame] + rows[sid] = (*layout, callback(before), callback(after)) return rows diff --git a/tools/tests/test_tone_slots.py b/tools/tests/test_tone_slots.py new file mode 100644 index 0000000..1ee8ddd --- /dev/null +++ b/tools/tests/test_tone_slots.py @@ -0,0 +1,230 @@ +"""Tone IDs survive native conversion; F is an event, not the game's no-event sentinel.""" + +import json +from copy import deepcopy + +import native_chart as nc +import pytest +import psarc_plain +import tone_demo +from test_native_chart import core + + +def test_native_tone_timeline_round_trip(): + body, _ = core(0, 7, native=True) + native = b"SNXR\x01\x00\x07\x00" + body + bytes(256) + changes = [(float(i + 1), i % 6) for i in range(20)] + native = nc.with_tone_changes(native, changes) + assert nc.read_tone_changes(native) == changes + stock = nc.to_stock(native) + assert nc.read_tone_changes(stock) == changes + assert nc.read_tone_changes(nc.to_native(stock, 0)) == changes + + +@pytest.mark.parametrize("changes", [[(1.0, 26)], [(1.0, -1)], [(2.0, 0), (1.0, 4)], [(float("nan"), 0)]]) +def test_reject_invalid_tone_events(changes): + body, _ = core(0, 7, native=True) + with pytest.raises(ValueError): + nc.with_tone_changes(b"SNXR\x01\x00\x07\x00" + body + bytes(256), changes) + + +def test_extra_names_and_definitions_survive_manifest_conversion(): + attrs = { + "ArrangementName": "Lead", + "ExtendedRange": {"Version": 1}, + "Tuning": {f"string{i}": 0 for i in range(7)}, + "Tone_Base": "clean", + **{f"Tone_{chr(65 + i)}": f"tone{i}" for i in range(26)}, + "Tones": [{"Key": f"tone{i}"} for i in range(26)], + } + raw = json.dumps({"Entries": {"test": {"Attributes": attrs}}}).encode() + back = nc.manifest_to_native(nc.manifest_to_stock(raw)) + actual = json.loads(back)["Entries"]["test"]["Attributes"] + assert nc.tone_names(actual) == [f"tone{i}" for i in range(26)] + assert actual["Tones"] == attrs["Tones"] + + +def test_demo_writes_six_distinct_names_and_twenty_events(tmp_path): + body, _ = core(0, 7, native=True) + keys = [f"original{i}" for i in range(6)] + attrs = { + "ArrangementName": "Lead", + "ExtendedRange": {"Version": 1}, + "Tuning": {f"string{i}": 0 for i in range(7)}, + "SongAsset": "urn:application:musicgame-song:demo_lead", + "Tones": [{"Key": key, "OriginalTestData": i} for i, key in enumerate(keys)], + } + manifest = json.dumps({"Entries": {"TEST_ID": {"Attributes": attrs}}}).encode() + files = { + "manifests/songs/demo_lead.json": manifest, + "manifests/songs/demo.hsan": manifest, + "songs/bin/generic/demo_lead.sng": nc.pack_sng(b"SNXR\x01\x00\x07\x00" + body + bytes(256)), + } + source, destination = tmp_path / "source.psarc", tmp_path / "demo_rsxr_p.psarc" + psarc_plain.write(source, files, list(files), magic=b"PSXR") + original = source.read_bytes() + tone_demo.generate(source, destination, "test_id", keys) + actual, _ = psarc_plain.read(destination) + result = json.loads(actual["manifests/songs/demo_lead.json"])["Entries"]["TEST_ID"]["Attributes"] + assert nc.tone_names(result) == keys + [""] * 20 + assert result["Tone_Base"] == keys[0] + assert result["Tones"] == attrs["Tones"] + assert nc.read_tone_changes(nc.unpack_sng(actual["songs/bin/generic/demo_lead.sng"])) == [ + (5.0 + 3 * i, i % 6) for i in range(20) + ] + assert source.read_bytes() == original + + +def variant_package(tmp_path, tones): + """Synthetic gear names and control keys; no definitions from a game package.""" + body, _ = core(0, 7, native=True) + attrs = { + "ArrangementName": "Lead", + "ExtendedRange": {"Version": 1}, + "Tuning": {f"string{i}": 0 for i in range(7)}, + "SongAsset": "urn:application:musicgame-song:demo_lead", + "Tones": tones, + } + header = deepcopy(attrs) + del header["Tones"] + files = { + "manifests/songs/demo_lead.json": json.dumps({"Entries": {"TEST_ID": {"Attributes": attrs}}}).encode(), + "manifests/songs/demo.hsan": json.dumps({"Entries": {"TEST_ID": {"Attributes": header}}}).encode(), + "songs/bin/generic/demo_lead.sng": nc.pack_sng(b"SNXR\x01\x00\x07\x00" + body + bytes(256)), + "audio/synthetic.wem": b"synthetic audio placeholder", + } + source = tmp_path / "source.psarc" + psarc_plain.write(source, files, list(files), magic=b"PSXR") + return source, files + + +@pytest.fixture +def variant_tone(): + return { + "Key": "source", + "Name": "Synthetic source", + "NameSeparator": " - ", + "Volume": "-20.000", + "IsCustom": True, + "ToneDescriptors": ["synthetic"], + "GearList": { + "Amp": { + "Key": "SyntheticAmp", + "Type": "Amps", + "KnobValues": { + "SyntheticAmp_Gain": 32, + "SyntheticAmp_Bass": 45, + "SyntheticAmp_Treble": 67, + "SyntheticAmp_Mid": 54, + }, + }, + "Cabinet": {"Key": "SyntheticCab", "Type": "Cabinets", "KnobValues": {}}, + }, + } + + +@pytest.mark.parametrize("count", [6, 26]) +@pytest.mark.parametrize("drive_control", ["Gain", "Loudness1"]) +def test_demo_variants_fill_slots_cycle_and_preserve_native_package( + tmp_path, variant_tone, capsys, count, drive_control +): + source_knobs = variant_tone["GearList"]["Amp"]["KnobValues"] + source_knobs[f"SyntheticAmp_{drive_control}"] = source_knobs.pop("SyntheticAmp_Gain") + source, original_files = variant_package(tmp_path, [variant_tone]) + original = source.read_bytes() + destination = tmp_path / "demo_rsxr_p.psarc" + tone_demo.generate(source, destination, "test_id", variants=count, start=2.0, interval=1.5) + files, meta = psarc_plain.read(destination) + assert meta["magic"] == b"PSXR" + assert nc._check_native_package(files) + attrs = json.loads(files["manifests/songs/demo_lead.json"])["Entries"]["TEST_ID"]["Attributes"] + header = json.loads(files["manifests/songs/demo.hsan"])["Entries"]["TEST_ID"]["Attributes"] + keys = [f"RsxrDemo{chr(65 + i)}" for i in range(count)] + assert nc.tone_names(attrs) == nc.tone_names(header) == keys + [""] * (26 - count) + assert attrs["Tone_Base"] == header["Tone_Base"] == keys[0] + definitions = {tone["Key"]: tone for tone in attrs["Tones"]} + assert len(definitions) == len(attrs["Tones"]) == count + 1 + assert definitions["source"] == variant_tone + changes = nc.read_tone_changes(nc.unpack_sng(files["songs/bin/generic/demo_lead.sng"])) + assert changes == [(2.0 + i * 1.5, i % count) for i in range(count + 1)] + assert [ident for _, ident in changes[:-1]] == list(range(count)) + settings = set() + table = capsys.readouterr().out + for i, key in enumerate(keys): + expected = deepcopy(variant_tone) + expected.update(Key=key, Name=f"Demo {chr(65 + i)}") + knobs = expected["GearList"]["Amp"]["KnobValues"] + knobs[f"SyntheticAmp_{drive_control}"] = (10, 50, 90)[i % 3] + knobs["SyntheticAmp_Bass"] = (0, 50, 100)[(i // 3) % 3] + knobs["SyntheticAmp_Treble"] = (0, 50, 100)[i // 9] + assert definitions[key] == expected + settings.add(tuple(knobs.values())) + assert f"{chr(65 + i)} -> {key} ->" in table + for name in (f"SyntheticAmp_{drive_control}", "SyntheticAmp_Bass", "SyntheticAmp_Treble"): + assert f"{name}={knobs[name]}" in table + assert len(settings) == count + assert files["audio/synthetic.wem"] == original_files["audio/synthetic.wem"] + assert source.read_bytes() == original + + +@pytest.mark.parametrize("variants", [5, 27, 6.5]) +def test_demo_rejects_invalid_variant_count(tmp_path, variant_tone, variants): + source, _ = variant_package(tmp_path, [variant_tone]) + destination = tmp_path / "demo_rsxr_p.psarc" + with pytest.raises(ValueError, match="6.*26"): + tone_demo.generate(source, destination, "test_id", variants=variants) + assert not destination.exists() + + +@pytest.mark.parametrize("control", ["Gain", "Bass", "Treble"]) +def test_demo_rejects_variants_without_suitable_existing_controls(tmp_path, variant_tone, control): + del variant_tone["GearList"]["Amp"]["KnobValues"][f"SyntheticAmp_{control}"] + source, _ = variant_package(tmp_path, [variant_tone]) + destination = tmp_path / "demo_rsxr_p.psarc" + with pytest.raises(ValueError, match="amp.*controls"): + tone_demo.generate(source, destination, "test_id", variants=26) + assert not destination.exists() + + +def test_demo_rejects_variant_key_collision(tmp_path, variant_tone): + variant_tone["Key"] = "rsxrdemoa" + source, _ = variant_package(tmp_path, [variant_tone]) + with pytest.raises(ValueError, match="already exists"): + tone_demo.generate(source, tmp_path / "demo_rsxr_p.psarc", "test_id", variants=26) + + +def test_demo_rejects_keys_and_variants_together(tmp_path): + with pytest.raises(ValueError, match="either"): + tone_demo.generate(tmp_path / "source.psarc", tmp_path / "demo.psarc", "test_id", ["x"] * 6, variants=26) + + +def test_demo_variant_cli(tmp_path, variant_tone): + source, _ = variant_package(tmp_path, [variant_tone]) + destination = tmp_path / "demo_rsxr_p.psarc" + tone_demo.main( + [ + str(source), + str(destination), + "--arrangement", + "test_id", + "--variants", + "26", + "--start", + "0", + "--interval", + "2", + ] + ) + files, _ = psarc_plain.read(destination) + assert nc.read_tone_changes(nc.unpack_sng(files["songs/bin/generic/demo_lead.sng"])) == [ + (float(2 * i), i % 26) for i in range(27) + ] + + +@pytest.mark.parametrize( + "options", [["--variants", "5"], ["--variants", "27"], ["--variants", "26", "--keys", *"abcdef"]] +) +def test_demo_cli_rejects_invalid_modes(options): + with pytest.raises(SystemExit) as error: + tone_demo.main(["source.psarc", "demo.psarc", "--arrangement", "test_id", *options]) + assert error.value.code == 2 diff --git a/tools/tone_demo.py b/tools/tone_demo.py new file mode 100644 index 0000000..67d7207 --- /dev/null +++ b/tools/tone_demo.py @@ -0,0 +1,157 @@ +"""Create a tone-slot test from an author's native package. + + python tools/tone_demo.py SOURCE.psarc DEMO_rsxr_p.psarc --arrangement PERSISTENT_ID --keys KEY_A KEY_B KEY_C KEY_D KEY_E KEY_F + python tools/tone_demo.py SOURCE.psarc DEMO_rsxr_p.psarc --arrangement PERSISTENT_ID --variants 26 + +Uses only the supplied package's definitions, audio and chart. A Key the arrangement lacks is copied from +another arrangement of the same package. Run outside the game folder. +The first change is at --start seconds (default 5), then every --interval seconds (default 3). +--keys retains the A..F / 20-change test. --variants N (6..26) clones a definition with existing amp +drive, bass and treble controls. It visits each generated slot once, then returns to A. +For zero-based slot i: drive = (10, 50, 90)[i % 3], bass = (0, 50, 100)[(i // 3) % 3], +treble = (0, 50, 100)[i // 9]. Drive uses Gain, Drive, Loudness1, Loudness or Volume (in that order). +These are amp knob percentages, not the tone's overall Volume. All other fields are copied unchanged. +No gear or knob keys are invented; packages without suitable controls are rejected. +Choose times that fit the supplied song. Tone Plan paging is not part of this demo. +""" + +import argparse +import json +import math +from copy import deepcopy +from pathlib import Path + +import native_chart as nc +import psarc_plain + + +def _variant_controls(tone): + gear = tone.get("GearList") + amp = gear.get("Amp") if isinstance(gear, dict) else None + knobs = amp.get("KnobValues") if isinstance(amp, dict) else None + if not isinstance(knobs, dict) or not amp.get("Key"): + return None + names = { + key.rsplit("_", 1)[-1].casefold(): key + for key, value in knobs.items() + if type(value) in (int, float) and math.isfinite(value) and 0 <= value <= 100 + } + drive = next((names[name] for name in ("gain", "drive", "loudness1", "loudness", "volume") if name in names), None) + if drive and "bass" in names and "treble" in names: + return drive, names["bass"], names["treble"] + return None + + +def _variant_tones(pool, count): + for original in pool.values(): + controls = _variant_controls(original) + if controls: + break + else: + raise ValueError("variants need existing amp drive, bass and treble controls in the range 0..100") + definitions, rows = {}, [] + for i in range(count): + letter = chr(65 + i) + key = f"RsxrDemo{letter}" + if key.casefold() in pool: + raise ValueError(f"variant Key already exists: {key}") + tone = deepcopy(original) + tone.update(Key=key, Name=f"Demo {letter}") + settings = ((10, 50, 90)[i % 3], (0, 50, 100)[(i // 3) % 3], (0, 50, 100)[i // 9]) + tone["GearList"]["Amp"]["KnobValues"].update(zip(controls, settings)) + definitions[key.casefold()] = tone + changes = ", ".join(f"{name}={value}" for name, value in zip(controls, settings)) + rows.append(f"{letter} -> {key} -> {original['Key']}: Amp {changes}") + return definitions, rows + + +def _add_definitions(attrs, keys, pool): + definitions = attrs.setdefault("Tones", []) + for key in keys: + if not any(str(t.get("Key", "")).casefold() == key.casefold() for t in definitions) and key.casefold() in pool: + definitions.append(deepcopy(pool[key.casefold()])) + if sum(str(t.get("Key", "")).casefold() == key.casefold() for t in definitions) != 1: + raise ValueError(f"missing or duplicate definition for {key}") + + +def generate(source, destination, arrangement, keys=None, start=5.0, interval=3.0, variants=None): + if Path(source).resolve() == Path(destination).resolve(): + raise ValueError("source and destination must differ") + if variants is not None: + if keys is not None: + raise ValueError("provide either six tone Keys or --variants") + if type(variants) is not int or not 6 <= variants <= 26: + raise ValueError("variants must be an integer from 6 to 26") + elif keys is None or len(keys) != 6 or len({key.casefold() for key in keys}) != 6: + raise ValueError("provide six distinct tone Keys") + if not math.isfinite(start) or start < 0 or not math.isfinite(interval) or interval <= 0: + raise ValueError("provide a finite nonnegative start and a finite positive interval") + if Path(source).read_bytes()[:4] != b"PSXR": + raise ValueError("the source must be a plain native PSXR package") + files, meta = psarc_plain.read(source) + pool = {} + for name in files: + if name.lower().startswith("manifests/") and name.lower().endswith(".json"): + for entry in json.loads(files[name].decode("utf-8-sig")).get("Entries", {}).values(): + for tone in entry.get("Attributes", {}).get("Tones") or []: + pool.setdefault(str(tone.get("Key", "")).casefold(), tone) + if variants is not None: + definitions, rows = _variant_tones(pool, variants) + pool.update(definitions) + keys = [tone["Key"] for tone in definitions.values()] + else: + rows = [f"{chr(65 + i)} -> {key} -> existing definition (unchanged)" for i, key in enumerate(keys)] + target, found = None, False + for name in files: + if not name.lower().startswith("manifests/") or not name.lower().endswith((".json", ".hsan")): + continue + manifest = json.loads(files[name].decode("utf-8-sig")) + for ident, entry in manifest.get("Entries", {}).items(): + if ident.casefold() != arrangement.casefold(): + continue + attrs = entry["Attributes"] + if attrs.get("ExtendedRange") != {"Version": 1}: + raise ValueError("the selected arrangement must be native") + if name.lower().endswith(".json"): + _add_definitions(attrs, keys, pool) + target = str(attrs.get("SongAsset", "")).rsplit(":", 1)[-1].lower() or Path(name).stem.lower() + found = True + for i in range(26): + attrs[f"Tone_{chr(65 + i)}"] = keys[i] if i < len(keys) else "" + attrs["Tone_Base"] = keys[0] + files[name] = json.dumps(manifest, indent=2, ensure_ascii=False).encode() + if not found: + raise ValueError("arrangement not found in a full manifest") + sngs = [name for name in files if name.lower().endswith(".sng") and Path(name).stem.lower() == target] + if len(sngs) != 1: + raise ValueError("arrangement has no unique SNG") + name = sngs[0] + count = len(keys) + 1 if variants is not None else 20 + changes = [(start + i * interval, i % len(keys)) for i in range(count)] + body = nc.with_tone_changes(nc.unpack_sng(files[name]), changes) + files[name] = nc.pack_sng(body) + nc._check_native_package(files) + psarc_plain.write(destination, files, meta["names"], meta["ver"], meta["flags"], b"PSXR") + print("Slot -> Key -> changes") + print("\n".join(rows)) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("source", type=Path) + parser.add_argument("destination", type=Path) + parser.add_argument("--arrangement", required=True) + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--keys", nargs=6) + mode.add_argument("--variants", type=int, choices=range(6, 27), metavar="N") + parser.add_argument("--start", type=float, default=5.0) + parser.add_argument("--interval", type=float, default=3.0) + args = parser.parse_args(argv) + try: + generate(args.source, args.destination, args.arrangement, args.keys, args.start, args.interval, args.variants) + except (ValueError, OSError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main()