Author SHA1 Message Date
Thomas MartinandClaude Opus 5.5 c83a9249f1 PS2Recomp: deterministic mode's disc reads take a PS2 drive's time (df2dfe2)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 23:14:32 +01:00
Thomas MartinandClaude Opus 5.5 63cbddc1b4 Line endings of tmb_cheats.cpp, tmb_native.cpp and tmb_overrides.cpp back to LF (the harness commit had turned them CRLF)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 19:24:46 +01:00
Thomas MartinandClaude Opus 5.5 ff176683d2 Reference harness (phase 0 of BozoEngine): TMB's side of PS2X_DETERMINISTIC=1 (one field's EE cycles per frame, inMatch and the menus' window in game frames, flare depth far, the Cheats tab off) and of PS2X_REFERENCE (the build name and the 362 stub addresses from the generated stub list); tools/ref_compare.py, tools/ref_pad_script.py, docs/REFERENCE_HARNESS.md. PS2Recomp: native/determinism
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 19:23:44 +01:00
Thomas MartinandClaude Opus 5.5 a7869c0af8 CHANGELOG: 0.3.2 (Story: start at, Black Vista Highway's road, movie sound volume)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:27:25 +01:00
Thomas MartinandClaude Opus 5.5 e189cb3b23 PS2Recomp: VP2S's native libsd fix (the sound data input's volume is BVOL, not AVOL); TMB writes BVOL 0x7efa when its movie streams start and 0 when they stop
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:14:59 +01:00
Thomas MartinandClaude Opus 5.5 a11583c0bf Mesh pack: a hierobject's packet may start up to 0x100 bytes after its texture blocks, zeros between (LOOP pads some to an alignment): 1730 objects of LOOP.NGP (Black Vista Highway's road and walls) and 87 each of DEATH1/2/5 were left out; every object packed before is byte-identical. TMB_NATIVE_MESHES_LOG_MISSING names the objects a loaded file's pack lacks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:12:38 +01:00
Thomas MartinandClaude Opus 5.5 1152e7fca0 Cheats: Story: start at (TMB_STORY_LEVEL), a new story begins at the chosen level of the game's level table (Shell + 0x18000 + 0x2354, replaced when a new story sets the Junkyard), labelled by the stage card each one shows; TMB_LOG_PROGRESS logs the Shell's progress words
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:04:18 +01:00
Thomas MartinandClaude Opus 5.5 abf529224c make_build_kit: FFmpeg's tarball falls back to the same file on the build-deps pre-release when ffmpeg.org does not answer (same pinned SHA-256)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:19:07 +01:00
Thomas MartinandClaude Opus 5.5 82f5b47119 make_build_kit: a download is tried five times, further apart each time (ffmpeg.org dropped the release runner's connections twice; a tag's run starts with an empty download cache)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:15:29 +01:00
Thomas MartinandClaude Opus 5.5 257401cbbb CHANGELOG: 0.3.1 (about a third less processor time per frame)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:06:11 +01:00
Thomas MartinandClaude Opus 5.5 06b9261112 PS2Recomp: guest loads and stores inlined with a main-RAM fast path, one function lookup per guest call (1P match: 7.5 -> 6.1 ms of work per frame; 639/639 fork tests)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 11:51:06 +01:00
Thomas MartinandClaude Opus 5.5 dc653bb996 Fewer allocations per frame: the fork's frame arrays recycled and its key map only when interpolating; TMB's per-object vertex arrays and strip buffer reused (the allocation waits in Renderer::draw and buildStrips: 8.3% -> 2.8% of the game thread)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 11:11:13 +01:00
13 changed files with 696 additions and 15 deletions

No files matched your search

+41 -1
View File
@@ -7,6 +7,44 @@ under "Unreleased" as they land, then move them under the new version's heading
## [Unreleased]
## [0.3.2] - 2026-11-02
### Added
- **Story: start at** (F2, Cheats): a new story can begin at any of its stages, Midtown Suburbs to Warhawk's Rooftop,
instead of the Junkyard, then goes on from there as usual. Handy to try the later stages without playing through.
### Fixed
- **Black Vista Highway** (story stage 3) had no road: most of the level's ground and walls were not drawn. Some
pieces of three Challenge arenas (DEATH1, DEATH2, DEATH5) were missing for the same reason. "Rebuild now" after
updating fixes them.
- **Movie sound volume**: the movies' sound now plays at the volume the game sets for it (it used a default
volume before; a fix from the Valkyrie Profile 2 port, which shares the sound code).
### Known limits
- Story stages past the first are reachable and load correctly, but most have not been played to the end yet.
- No widescreen yet.
- Only the USA disc (SCUS-97101) is supported.
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
## [0.3.1] - 2026-11-02
### Changed
- **Faster**: the game now needs about a third less processor time per frame than in 0.3.0 (in our tests a busy
match went from about 7.5 to 5 milliseconds of work per frame, out of the 16.7 a frame lasts at 60 frames per
second). Older or slower PCs that dropped below 60 in big fights or in split screen should hold it much better.
Nothing changes in how the game looks or plays.
### Known limits
- Story levels 2 to 8 are not checked to the end yet.
- No widescreen yet.
- Only the USA disc (SCUS-97101) is supported.
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
## [0.3.0] - 2026-11-02
### Added
@@ -85,7 +123,9 @@ The first release. You build the game on your own PC from your own USA disc; not
- Technical: built from TMB_Recomp's code and the PS2Recomp fork (`native/renderer`) with the build kit's GCC 16.2,
FFmpeg 9.0.2 and Python 3.14; the default mode has no GS, VU or SPU2 emulation and no IOP hardware model.
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.0...HEAD
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.2...HEAD
[0.3.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.1...v0.3.2
[0.3.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/TheBozos/TMB_Recomp/releases/tag/v0.1.0
+50 -1
View File
@@ -93,7 +93,56 @@ if(TMB_VU1_AOT_SOURCES)
target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_vu1_aot>)
endif()
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES})
# The reference harness (docs/REFERENCE_HARNESS.md): the game's library and kernel stubs (the generated code's stub
# list, ps2_recompiled_stubs.h: name_0xaddress) whose calls PS2X_REFERENCE records, and the build's name (the two
# repositories' commits when configured), as a source in the build tree.
set(_tmb_stub_list "${TMB_GENERATED_DIR}/ps2_recompiled_stubs.h")
set(_tmb_call_names "")
set(_tmb_call_count 0)
if(EXISTS "${_tmb_stub_list}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_tmb_stub_list}")
file(STRINGS "${_tmb_stub_list}" _tmb_stub_lines REGEX "^void [A-Za-z0-9_]+_0x[0-9a-fA-F]+\\(")
foreach(_tmb_line IN LISTS _tmb_stub_lines)
if(_tmb_line MATCHES "^void ([A-Za-z0-9_]+)_0x([0-9a-fA-F]+)\\(")
string(APPEND _tmb_call_names " {0x${CMAKE_MATCH_2}u, \"${CMAKE_MATCH_1}\"},\n")
math(EXPR _tmb_call_count "${_tmb_call_count} + 1")
endif()
endforeach()
endif()
if(_tmb_call_count EQUAL 0)
set(_tmb_call_names " {0u, \"\"},\n")
endif()
find_package(Git QUIET)
set(_tmb_commit "unknown")
set(_tmb_fork_commit "unknown")
if(GIT_FOUND)
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE _tmb_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/PS2Recomp"
OUTPUT_VARIABLE _tmb_fork_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
endif()
file(WRITE "${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in"
"// Generated by CMakeLists.txt from ${_tmb_stub_list}: do not edit.
#include \"runtime/ps2_reference.h\"
#include <cstddef>
namespace tmb
{
extern const char *const kBuildName;
extern const ps2x::reference::CallName kCallNames[];
extern const size_t kCallNameCount;
const char *const kBuildName = \"TMB_Recomp ${_tmb_commit} fork ${_tmb_fork_commit}\";
const ps2x::reference::CallName kCallNames[] = {
${_tmb_call_names} };
const size_t kCallNameCount = ${_tmb_call_count};
}
")
configure_file("${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in" "${CMAKE_BINARY_DIR}/tmb_call_names.cpp" COPYONLY)
set_source_files_properties("${CMAKE_BINARY_DIR}/tmb_call_names.cpp" PROPERTIES
SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
message(STATUS "TMB_Recomp: ${_tmb_call_count} stub addresses for the reference records")
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES} "${CMAKE_BINARY_DIR}/tmb_call_names.cpp")
target_include_directories(ps2EntryRunner PRIVATE "${TMB_GENERATED_DIR}")
list(LENGTH TMB_GENERATED_SOURCES _tmb_count)
+1
View File
@@ -467,6 +467,7 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
| Cheat | | Variable |
|---|---|---|
| Unlock everything | every level (Freeway, Prison Passage, Skyscrapers, Minion's Stadium...), every vehicle (Yellow Jacket, Axel, Warthog, Manslaughter, Minion...) and every movie, opened in the menus; switched off, put back; saving while it is on keeps them on the card | `TMB_UNLOCK_ALL=1` |
| Story: start at | a new story begins at the chosen level instead of the Junkyard (every stage: Midtown Suburbs or Expressway 104, Downtown or Black Vista Highway, Minion's Stadium, Prison Passage, Blackfield Asylum, Abandoned Skyscrapers, Warhawk's Rooftop; and the other arenas), then goes on as the game chains them; for testing the later stages without playing through | `TMB_STORY_LEVEL=<level number>` (the game's level table: 1 Junkyard, 0 Suburbs, 2 Expressway, 5 Downtown, 6 Black Vista, 14 Stadium, 3 Prison, 16 Asylum, 4 Skyscrapers, 13 their second part, 20 Warhawk's Rooftop) |
| Infinite health | per player: the car's health held at its maximum (the game's own, as its health bar shows it) | `TMB_PLAYER_GOD=<players>` |
| Infinite ammo | per player: pickup weapons and the special are not spent (the HUD's counts stay) | `TMB_INFINITE_AMMO=<players>` |
| Infinite energy | per player: the energy bar (freeze, mines, shield...) held full | `TMB_INFINITE_ENERGY=<players>` |
+121
View File
@@ -0,0 +1,121 @@
# The reference harness
Phase 0 of BozoEngine (its spec: `D:\BozoEngine\docs\specs\harness.md`): TMB on its current runtime (the PS2Recomp
fork) runs deterministically and records, per game frame, what the guest computed. Two runs with the same scripted
input write the same file; a later runtime must write the same records.
## Running
```sh
PS2X_DETERMINISTIC=1 PS2X_REFERENCE=run.ref PS2X_REFERENCE_FRAMES=9000 PS2X_USER_DIR=<empty folder> \
PS2X_PAD_SCRIPT="<frame:BUTTON/frames,...>" build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
tools/ref_compare.py a.ref b.ref
```
- `PS2X_DETERMINISTIC=1`: the deterministic mode (below). Off, every path is as before.
- `PS2X_REFERENCE=<file.ref>`: the recorder. Works in either mode (only deterministic runs compare equal).
- `PS2X_REFERENCE_FRAMES=<n>`: the process exits (0) once n frames are recorded.
- `PS2X_REFERENCE_CALLS=<n>` (default 120), `PS2X_REFERENCE_CALLS_FROM=<f>`: the full call lists of n frames from
frame f, as text, in `<file>.ref.calls`.
- `PS2X_REFERENCE_DUMP=<f>[-<g>][,...]`: RAM (32 MB) then scratchpad (16 KB) of those frames in `<file>.ref.ram.<f>`.
- `PS2X_REFERENCE_MASK=<address>:<bytes>[,...]`: RAM hashed as zeros there (listed in the header). None is needed for
TMB; `PS2X_REFERENCE_CHECK_HOST=1` scans RAM every 600 frames for words that look like host addresses (into the
host's copy of RAM or the scratchpad, or near the runtime's own data) and logs them.
- `PS2X_REFERENCE_RUN=<name>`: the run's name in the header (default: the file's stem).
- `PS2X_USER_DIR=<folder>`: a fresh folder per run, so the memory cards start pristine and the settings default.
Pad scripts in deterministic mode are keyed on game frames: `frame:BUTTON/frames` (held 30 frames when not given);
`PS2X_PAD2_SCRIPT` .. `PS2X_PAD4_SCRIPT` alike. `tools/ref_pad_script.py` converts a timed script: run it once with
`PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1` (the pad on the wall clock, each change logged with its
frame; that run is not deterministic), then `--log <its log> --from-log` gives pad 1's presses at the frames they
landed, and `--log <log> "<timed script>"` maps any other timed script through the same anchors.
## What deterministic mode does
The run-to-run variation found in the code (`D:\BozoEngine\docs\notes\tmb-determinism.md`) and what each became:
| # | Source | Deterministic mode |
|---|---|---|
| 1 | The frame step from host time (`FramePacer::frameEnd`), the EE cycles charged at the frame end from it, TMB's field carry | `FramePacer` returns exactly one period of the cap (1/60 s); TMB charges exactly `294912000 / field rate` EE cycles less what the frame accounted (`nativeFrameEnd`), so one field per frame, no carry. The window is still held to 60 fps (pacing only) |
| 2 | `sceCdReadClock` from the host's date (TMB seeds its RNG from it) | 2001-06-18 12:00:00 (`ps2x::det::fixedDate`); OSD time zone UTC |
| 3 | The IOP on the host clock (`PS2X_IOP_WALLCLOCK`, which TMB sets), the IOP thread | Ignored: the IOP advances only by the EE cycles accounted, on the EE thread (`PS2X_IOP_THREAD` ignored) |
| 4 | The native mixer rendered on the audio device thread | Mixed on the IOP's clock: 768 IOP cycles per 48 kHz sample, brought up to the current IOP cycle before every libsd call and at the end of every IOP slice (`NativeMixer::advanceTo`), so envelopes, ended voices, input positions and the input's half interrupts change only at IOP points. The device only drains a 16384-sample queue (silence when dry, oldest dropped when full). The emulated SPU2 is never on the wall clock |
| 5 | Pad scripts in seconds; host keyboard / gamepads; players from plugged gamepads | Scripts in game frames (the frame count only moves at frame ends: latched per frame); no host input (`PS2X_PAD_NO_HOST` forced, `PS2X_PAD_INPUT` / `PS2X_PAD_RECORD` off); players 2-4 present only by their scripts; a pad port with no player behind it (port 2 while the multitap is on port 1) reads at rest instead of falling back to the host's keyboard and first gamepad (found by the first proof runs: its sticks read 0x7f or 0x80 with the window's focus) |
| 6 | EE wall-clock catch-up (`PS2X_EE_CATCHUP`, on by default) and host deadlines | Off; every scheduled event is due by its cycle alone; vblank holds ignored; an idle wait still sleeps (pacing) but always charges exactly the cycles to the next event; `waitHostDeadline` (other ports' frame waits) completes at the next dispatch point |
| 7 | Movies: picture clock from host time, host-deadline waits, decode time charged to the EE | Frame-clocked: pictures paced by the vblank count (which follows EE cycles), no host deadline, decode time not charged. A movie still plays whole (it ends no game frame, so the pad script's frame clock stands still through it) |
| 8 | Lens flare depth read back from the GPU into guest RAM; `inMatch` from a 100 ms host-time window | Flare samples all far (0); `inMatch` / the menus' window measured in game frames (frame count / 60), so a frame's kind follows the kinds of the frames before it |
| 9 | Memory card contents and dates; file dates | A fresh `PS2X_USER_DIR` per run (pristine card); every card and file date is the fixed date |
| 10 | Settings window actions (Cheats tab) | The tab shows nothing but a note; only the environment's cheats apply (from launch). `TMB_CHEATS_TOGGLE` off |
Beyond the list: the MPEG decode charge and `waitHostDeadline` (above), the OSD time zone, file `getstat` dates.
Left as they are (checked: no guest-visible effect, or not used by TMB's native port): the GS front end and VIF1
thread (absent in the native port), the CD read-ahead threads (the guest waits for them synchronously), the renderer's
present thread (reads published frames only), host-side statistics and traces.
## The record file
Little-endian, packed. Hashes: XXH64 (seed 0) for `ram`, `scratchpad`, `calls`, `draws`, `threads`; the sound is
FNV-1a 64. No hash ever takes a host pointer: textures are identified by their content.
Header (240 bytes, then `maskCount` pairs of u32 {address, bytes}):
| Offset | Type | Field |
|---|---|---|
| 0 | char[8] | magic `PS2XREF1` |
| 8 | u32 | version (1) |
| 12 | u32 | headerBytes (240 + 8 x maskCount: where the records start) |
| 16 | u32 | recordBytes (80) |
| 20 | u32 | hash (1: XXH64 seed 0, sound FNV-1a 64) |
| 24 | u32 | ramBytes (33554432) |
| 28 | u32 | scratchpadBytes (16384) |
| 32 | u64 | elfHash: XXH64 of the ELF file |
| 40 | u32 | flags: bit 0 deterministic mode |
| 44 | u32 | maskCount |
| 48 | char[64] | run name |
| 112 | char[64] | build ("TMB_Recomp <commit> fork <commit>", as configured) |
| 176 | char[64] | the ELF's file name |
Record (80 bytes), one per game frame. A game frame ends where the game hands its picture over
(`EeScheduler::presentGuestFrame`: TMB's `timer1Handler` / `sceGsSyncV`, menus and loading screens included; movies
end none). Frame 0 is everything up to the first one.
| Offset | Type | Field |
|---|---|---|
| 0 | u32 | frame |
| 4 | i32 | thread: the guest thread running at the frame end |
| 8 | u64 | ram: XXH64 of the 32 MB of EE RAM (masked ranges as zeros) at the frame end |
| 16 | u64 | scratchpad: XXH64 of the 16 KB scratchpad |
| 24 | u64 | calls: XXH64 of the frame's calls, each 7 u32 {id, a0, a1, a2, a3, v0, flags}, in call order |
| 32 | u64 | draws: the frame's published draw lists (below) |
| 40 | u64 | sound: FNV-1a 64 of the stereo int16 samples mixed during the frame (0 when none) |
| 48 | u64 | threads: XXH64 of i32 {running thread, then the ready threads in run order} |
| 56 | u64 | eeCycle: the EE cycle count at the frame end |
| 64 | u32 | callCount |
| 68 | u32 | drawBatches |
| 72 | u32 | drawVertices |
| 76 | u32 | soundSamples (800 a frame once the mix runs at one field per frame) |
Calls: the dispatcher's calls (JAL / JALR) to the game's library and kernel stubs, the 362 addresses of the generated
code's stub list (`ps2_recompiled_stubs.h`, compiled into `build/.../tmb_call_names.cpp` at configure time), and raw
`syscall`s. `id` is FNV-1a 32 of the stub's name with the top bit clear, or `0x80000000 | number` for a syscall;
`a0`-`a3` the argument registers' low words; `v0` the result's low word; `flags` 1 when the call blocked (its result
comes later), 2 when the frame ended inside it (`sceGsSyncV`, TMB's frame end). A tail jump compiled to a direct call
is not seen. The `.calls` side file lists them as text: name, id, a0-a3, result.
Draws: per published list (kind 1 the 3D frame at `Renderer::endFrame`, 2 the 2D overlay at `publishOverlay`, 3 a
movie picture at `setBackdrop`) h = XXH64(kind), then per batch h = XXH64(words, h) of 8 u64 {tex0, texa, region,
the flags packed (textured, blend << 8, alphaRef << 16, alphaTest << 24, depthTest << 25, depthWrite << 26, clampU
<< 27, clampV << 28, fog << 29, sampleTarget << 30, fromGsContext << 31, alphaBlend << 32, context << 40), fogColour,
texture identity (XXH64 of its RGBA texels seeded with XXH64 of {width, height}; 0 for none), vertex count, 0}, then
each GS write {address, value} of a GS-context batch, the matrix (16 floats), the clip (4 floats) and the vertices
(32 bytes each: x, y, z, u, v, rgba, fog, q). The frame's `draws` folds each list's h in order: d = XXH64({d, h}).
## Comparing
`tools/ref_compare.py a.ref b.ref [--ignore field,...]` prints both headers, then either `identical: N frames
compared` or the first frame where any field differs, every field that differs there with both values, and the first
frame each field differs at. With RAM dumps of that frame from both runs (`PS2X_REFERENCE_DUMP=<frame>`), the first
differing 32-byte block (address, both runs' bytes); with both runs' call lists of the first frame whose calls differ
(`PS2X_REFERENCE_CALLS_FROM=<frame> PS2X_REFERENCE_CALLS=1`), the two lists side by side from their first difference.
Exit status 0 when identical, 1 when not.
+84 -1
View File
@@ -28,6 +28,7 @@
#include "ps2_runtime.h"
#include "ps2_recompiled_functions.h"
#include "runtime/ps2_debug_ui.h"
#include "runtime/ps2_determinism.h"
#if defined(PS2X_ENABLE_DEBUG_UI)
#include "imgui.h"
#endif
@@ -64,6 +65,25 @@ namespace tmb::cheats
std::atomic<uint32_t> g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0};
std::atomic<bool> g_noAi{false};
std::atomic<bool> g_unlockAll{false};
// Story: start at a level (-1: off). The story's state is the level being played, Shell + 0x18000 + 0x2354 (the
// index of the game's level table: GetLevelName, LoadLevelDB), the one last won at + 0x2358, the mode at
// + 0x235C (1: one-player story); a new story sets the level to 1, the Junkyard, and each level won sets the
// next (EvaluateOnePlayerStoryStatus).
std::atomic<int> g_storyStart{-1};
constexpr uint32_t kStoryLevel = 0x2354u, kStoryLastWon = 0x2358u, kGameMode = 0x235Cu;
constexpr int kLevelCount = 21;
// The levels by the level table's index (its names at 0x426070, 16 bytes each), with the card the story shows
// when it starts there (the stage, of 8). Two stages have two arenas (the story picks one); ASYLUM and ROOFTOP2
// show no card (reached from inside another level); the others are arenas the story does not use.
constexpr const char *kLevelNames[kLevelCount] = {
"Stage 2: Midtown Suburbs (SUBURB)", "Stage 1: Junkyard (JUNKYARD)", "Stage 2: Midtown Expressway 104 (FREEWAY)",
"Stage 5: Prison Passage to Blackfield Asylum (PRISON)", "Stage 7: Abandoned Skyscrapers (ROOFTOP)",
"Stage 3: Downtown Business District (CITY)", "Stage 3: Black Vista Highway (LOOP)", "Arena DEATH1", "Arena DEATH2",
"Arena DEATH3", "Arena DEATH4", "Arena DEATH5", "Arena DEATH6", "Rooftops, second part (ROOFTOP2)",
"Stage 4: Minion's Stadium (STADIUM)", "Arena SHIP", "Blackfield Asylum (ASYLUM)", "Arena MINICITY", "Arena MINIBURB",
"Arena JUNK2", "Stage 8: Warhawk's Rooftop (ROOFBOSS)"};
// The picker's order: the story's, then the rest.
constexpr int kLevelOrder[kLevelCount] = {1, 0, 2, 5, 6, 14, 3, 16, 4, 13, 20, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19};
std::vector<uint32_t> g_unlocked; // the lock words Unlock everything opened (put back when it goes off)
std::atomic<float> g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off
std::atomic<float> g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing)
@@ -223,6 +243,12 @@ namespace tmb::cheats
void drawTab()
{
// Deterministic mode: nothing the user does may change the run (only the environment's cheats, from launch).
if (ps2x::det::enabled())
{
ImGui::TextDisabled("Off in deterministic mode (PS2X_DETERMINISTIC=1): the environment's cheats only.");
return;
}
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
const int players = rdram ? playerCount(rdram, game) : 0;
@@ -233,6 +259,20 @@ namespace tmb::cheats
g_unlockAll.store(unlock, std::memory_order_relaxed);
ImGui::TextDisabled("Opened in the menus; saving the game while it is on keeps them on the card.");
int start = g_storyStart.load(std::memory_order_relaxed);
ImGui::SetNextItemWidth(420.0f);
if (ImGui::BeginCombo("Story: start at", start < 0 ? "the first level (as the game)" : kLevelNames[start]))
{
if (ImGui::Selectable("the first level (as the game)", start < 0))
start = -1;
for (const int i : kLevelOrder)
if (ImGui::Selectable(kLevelNames[i], start == i))
start = i;
ImGui::EndCombo();
}
g_storyStart.store(start, std::memory_order_relaxed);
ImGui::TextDisabled("For testing: a new story begins at this level, then goes on as the game chains them.");
ImGui::SeparatorText("Players");
perPlayer("Infinite health", g_infiniteHealth, players);
perPlayer("Infinite ammo", g_infiniteAmmo, players);
@@ -267,6 +307,47 @@ namespace tmb::cheats
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
// Once a frame (timerEndOfRealTimeProcessing, the frame's processing done).
// TMB_LOG_PROGRESS=1 (finding the story's state): each word of Shell + 0x18000 + 0x2180 to + 0x2500 that changes,
// with the time, from every frame end (the menus' too).
void logProgress(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
// Story: start at a level. When a new story sets its first level (the Junkyard, nothing won yet), that level
// is replaced, before the game loads it (it does once the character is chosen); the game's own chain goes on
// from there.
{
const uint32_t progress = shell + kShellProgress;
const int level = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
static int s_lastLevel = -2;
const int start = g_storyStart.load(std::memory_order_relaxed);
if (start >= 0 && level == 1 && s_lastLevel != 1 && word(rdram, progress + kGameMode) == 1u &&
word(rdram, progress + kStoryLastWon) == 0u && start != 1)
{
setWord(rdram, progress + kStoryLevel, static_cast<uint32_t>(start));
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
}
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
}
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
if (!s_on)
return;
static uint32_t s_last[0xE0] = {};
static bool s_seen = false;
static const auto s_start = std::chrono::steady_clock::now();
const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
for (uint32_t i = 0; i < 0xE0u; ++i)
{
const uint32_t value = word(rdram, shell + kShellProgress + 0x2180u + i * 4u);
if (s_seen && value != s_last[i])
std::fprintf(stderr, "[tmb:progress] t=%.1f +0x%x: %d -> %d\n", t, 0x2180u + i * 4u, static_cast<int32_t>(s_last[i]),
static_cast<int32_t>(value));
s_last[i] = value;
}
s_seen = true;
}
void onFrame(uint8_t *rdram)
{
g_rdram.store(rdram, std::memory_order_relaxed);
@@ -280,7 +361,7 @@ namespace tmb::cheats
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0)
if (s_toggle > 0.0 && !ps2x::det::enabled())
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
@@ -368,6 +449,8 @@ namespace tmb::cheats
{
g_noAi.store(std::getenv("TMB_NO_AI") && *std::getenv("TMB_NO_AI") == '1');
g_unlockAll.store(std::getenv("TMB_UNLOCK_ALL") && *std::getenv("TMB_UNLOCK_ALL") == '1');
if (const char *level = std::getenv("TMB_STORY_LEVEL"); level && *level)
g_storyStart.store(std::clamp(std::atoi(level), -1, kLevelCount - 1));
g_infiniteHealth.store(envMask("TMB_PLAYER_GOD"));
g_infiniteAmmo.store(envMask("TMB_INFINITE_AMMO"));
g_infiniteEnergy.store(envMask("TMB_INFINITE_ENERGY"));
+41 -1
View File
@@ -307,6 +307,29 @@ namespace tmb::meshes
bool g_inHier2pFlush = false;
uint64_t g_unsentFlushes = 0; // views submitted at the frame's end (not kicked by hier__Fi)
uint64_t g_listDrops = 0, g_submitted[2] = {}, g_built[2] = {}, g_kicks[2] = {};
// The vertex arrays of the objects drawn last, kept (cleared) for the next objects' batches: each one grew from
// nothing every frame, a few hundred objects' worth of allocations and copies (the game thread only).
std::vector<std::vector<ps2x::native::Vertex>> g_vertexPool;
void recycleVertices(Drawn &drawn)
{
for (auto &batch : drawn.batches)
if (batch.vertices.capacity() != 0u && g_vertexPool.size() < 8192u)
{
batch.vertices.clear();
g_vertexPool.push_back(std::move(batch.vertices));
}
}
std::vector<ps2x::native::Vertex> pooledVertices()
{
if (g_vertexPool.empty())
return {};
std::vector<ps2x::native::Vertex> vertices = std::move(g_vertexPool.back());
g_vertexPool.pop_back();
return vertices;
}
struct ViewList : ps2x::native::MeshViewList<Drawn>
{
// Built by hier2p: sent only by hier2pFlushDma. On the frame a split screen ends hier2p builds its view once
@@ -314,6 +337,11 @@ namespace tmb::meshes
bool hier2p = false;
void clear()
{
for (Drawn &drawn : opaque)
recycleVertices(drawn);
for (std::vector<Drawn> &bucket : buckets)
for (Drawn &drawn : bucket)
recycleVertices(drawn);
MeshViewList<Drawn>::clear();
hier2p = false;
}
@@ -638,7 +666,9 @@ namespace tmb::meshes
bool textured = false;
uint32_t texnum = ~0u;
Batch *batch = nullptr;
std::vector<ps2x::native::Vertex> strip;
static thread_local std::vector<ps2x::native::Vertex> s_strip; // kept from call to call (its capacity)
std::vector<ps2x::native::Vertex> &strip = s_strip;
strip.clear();
static const bool s_check = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr;
for (uint32_t si = 0; si < strips; ++si)
{
@@ -691,6 +721,7 @@ namespace tmb::meshes
{
out.batches.emplace_back(std::move(writes));
batch = &out.batches.back();
batch->vertices = pooledVertices();
batch->tex0 = tex0;
batch->textured = textured;
batch->blended = blended;
@@ -1255,6 +1286,15 @@ namespace tmb::meshes
if (!it)
{
++g_stats.noObject;
// TMB_NATIVE_MESHES_LOG_MISSING=1: the first objects of a loaded file the pack does not have.
static const bool s_logMissing = std::getenv("TMB_NATIVE_MESHES_LOG_MISSING") != nullptr;
static std::unordered_map<uint32_t, bool> s_seen;
if (s_logMissing && !s_seen[obj] && s_seen.size() < 40u)
{
s_seen[obj] = true;
std::fprintf(stderr, "[tmb:mesh] object %#x (%s + %#x, setup %#x, flags %#x, %s): not in the pack\n", obj,
file.file->name.c_str(), offset, pc, fp, opaque ? "opaque" : "alpha");
}
stateOnly(ee, extra, opaque);
return;
}
+11 -1
View File
@@ -25,6 +25,7 @@
#include "runtime/native/native_vu1_sandbox.h"
#include "runtime/ps2_memory.h"
#include "runtime/native/native_display.h"
#include "runtime/ps2_determinism.h"
#include "runtime/native/native_gs_hook.h"
#include "tmb_host.h"
#include "tmb_meshes.h"
@@ -198,9 +199,13 @@ namespace tmb::native
}
// A match is under way while its frames end (the end of real-time processing, onFrameEnd) less than 100 ms
// apart on the host's clock; the menus (the shell overlay's loop) end none.
// apart on the host's clock; the menus (the shell overlay's loop) end none. PS2X_DETERMINISTIC=1: the clock is
// the game frames ended (a sixtieth of a second each), so which frames count as a match's or a menu's is the
// kinds of the frames before, never the host's timing.
double hostSeconds()
{
if (ps2x::det::enabled())
return static_cast<double>(ps2x::det::frame()) / 60.0;
static const auto s_start = std::chrono::steady_clock::now();
return std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
}
@@ -3401,6 +3406,9 @@ namespace tmb::native
}
if (!s_on || !enabled() || !inMatch())
return;
// Deterministic mode: every sample far (as the caller cleared them): the GPU's depth is host timing.
if (ps2x::det::enabled())
return;
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
renderer.wantDepth();
uint64_t bitbltbuf = 0, trxpos = 0, trxreg = 0;
@@ -3461,6 +3469,8 @@ namespace tmb::native
std::fill(z, z + 16, 0u);
if (!flareDepthNative())
return false;
if (ps2x::det::enabled()) // deterministic mode: all far (the GPU's depth is host timing)
return true;
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
renderer.wantDepth();
const ps2x::native::Screen view = screen();
+23 -1
View File
@@ -9,6 +9,8 @@
#include "runtime/gs/gs_draw_estimate.h"
#include "runtime/ps2_memory.h"
#include "runtime/native/native_display.h"
#include "runtime/ps2_determinism.h"
#include "runtime/ps2_reference.h"
#include "runtime/sampling_profiler_gate.h"
#include "tmb_host.h"
#include <string>
@@ -41,6 +43,11 @@ namespace tmb
{
extern std::atomic<bool> g_rainLiftOff; // runtime/vu1/tmb_vu1_rain.cpp
extern std::atomic<uint64_t> g_rainLiftedStrips;
// The build's name and the game's stub addresses for the reference records (tmb_call_names.cpp, which CMake
// generates in the build tree from the generated code's stub list).
extern const char *const kBuildName;
extern const ps2x::reference::CallName kCallNames[];
extern const size_t kCallNameCount;
}
namespace tmb::native
@@ -75,6 +82,7 @@ namespace tmb::cheats
void install(PS2Runtime &runtime);
void setTheGame(uint32_t game);
void onFrame(uint8_t *rdram);
void logProgress(uint8_t *rdram, uint32_t gp);
}
namespace tmb::meshes
@@ -1104,6 +1112,7 @@ namespace
tmb::native::onMenuFrameEnd(); // TMB_NATIVE: publishes a menu frame's native draws (not in a match)
const double step = pacer.frameEnd();
g_lastFrameEndSeconds.store(hitchClock(), std::memory_order_relaxed);
tmb::cheats::logProgress(rdram, gp); // TMB_LOG_PROGRESS
// The fps overlay in the menus (a match's frames are counted at timerEndOfRealTimeProcessing).
if (hitchClock() - g_lastMatchFrameNoted.load(std::memory_order_relaxed) > 0.5)
runtime->noteGameFrame();
@@ -1123,7 +1132,10 @@ namespace
s_last = now;
}
EeScheduler &scheduler = runtime->eeScheduler();
const uint64_t real = static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
// PS2X_DETERMINISTIC=1: exactly one field's EE cycles (the step is one field too).
const uint64_t real = ps2x::det::enabled()
? EeScheduler::kEeClockHz / static_cast<uint64_t>(fieldRate(rdram, gp))
: static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
const uint64_t accounted = scheduler.currentCycle() - g_frameEndCycle;
for (uint64_t debt = real > accounted ? real - accounted : 0u; debt != 0u;)
{
@@ -1720,6 +1732,16 @@ namespace
g_traceIdle = true;
runtime.eeScheduler().setIdleObserver([](const EeScheduler::IdleRecord &record) { g_frameIdle.push_back(record); });
}
// PS2X_REFERENCE (the reference harness, docs/REFERENCE_HARNESS.md): the build, and the game's library and
// kernel stubs whose calls the records hash (their addresses from the generated stub list: tmb_call_names.cpp).
if (ps2x::reference::active())
{
ps2x::reference::setBuild(tmb::kBuildName);
ps2x::reference::setCallNames(tmb::kCallNames, tmb::kCallNameCount);
}
if (ps2x::det::enabled())
std::cout << "[tmb] deterministic mode (PS2X_DETERMINISTIC=1): a field per frame, fixed date, pad scripts in frames"
<< std::endl;
runtime.registerFunction(kVblankHandler, &vblankHandlerOverride);
runtime.registerFunction(kHier, &hierOverride);
tmb::native::install(); // TMB_NATIVE
+28 -4
View File
@@ -45,6 +45,7 @@ import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.request
import zipfile
@@ -54,10 +55,13 @@ from tmb_build import pe_imports, cmake_rc_flags # noqa: E402
KIT_VERSION = 1
# ---- pinned downloads (official upstream only) ----
# ---- pinned downloads (official upstream; a mirror of ours only as a fallback, held to the same SHA-256) ----
FFMPEG = {
'version': '9.0.2',
'url': 'https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.xz',
# Tried only when the upstream address fails: the same file on our build-deps pre-release (ffmpeg.org dropped
# the release runner's connections), held to the same SHA-256.
'mirrors': ['https://github.com/TheBozos/TMB_Recomp/releases/download/build-deps/ffmpeg-9.0.2.tar.xz'],
'sha256': '8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e',
# ffmpeg-9.0.2.tar.xz.asc checked once with gpg against https://ffmpeg.org/ffmpeg-devel.asc:
'signing_key': 'FCF986EA15E6E293A5644F10B4322F04D67658D8 (FFmpeg release signing key)',
@@ -243,10 +247,30 @@ def download(spec, downloads):
os.makedirs(downloads, exist_ok=True)
path = os.path.join(downloads, spec['url'].rsplit('/', 1)[1])
if not (os.path.isfile(path) and sha256_file(path) == spec['sha256']):
log(' downloading %s' % spec['url'])
# A few tries, further apart each time: an upstream site sometimes drops or times out a CI runner's connection
# (GitHub's release runs start with an empty download cache: a tag's run cannot read another tag's cache).
# Then the spec's mirrors, if any; a file from any of them must have the pinned SHA-256.
tmp = path + '.part'
with urllib.request.urlopen(spec['url']) as r, open(tmp, 'wb') as f:
shutil.copyfileobj(r, f, 1 << 20)
tries = [(spec['url'], wait) for wait in (0, 20, 60, 120)]
tries += [(mirror, wait) for mirror in spec.get('mirrors', ()) for wait in (0, 20, 60)]
error = None
for url, wait in tries:
if wait:
log(' %s failed (%s): again in %d s' % (url, error, wait))
time.sleep(wait)
log(' downloading %s' % url)
try:
with urllib.request.urlopen(url, timeout=120) as r, open(tmp, 'wb') as f:
shutil.copyfileobj(r, f, 1 << 20)
except (urllib.error.URLError, OSError) as e:
error = e
continue
digest = sha256_file(tmp)
if digest == spec['sha256']:
break
error = 'SHA-256 %s, expected %s' % (digest, spec['sha256'])
else:
raise KitError('%s: could not download (%s)' % (spec['url'], error))
os.replace(tmp, path)
digest = sha256_file(path)
if digest != spec['sha256']:
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Compares two reference records (PS2X_REFERENCE=<file.ref>, docs/REFERENCE_HARNESS.md) frame by frame.
tools/ref_compare.py a.ref b.ref [--ignore eeCycle,...] [--lines 24]
Reports the frames compared and the first frame where a field differs (every field that differs there, and the first
frame each field differs at). For `ram`, when both runs dumped that frame (PS2X_REFERENCE_DUMP=<frame>: <file>.ram.<frame>),
the first differing 32-byte block (its address and both runs' bytes); for `calls`, when both have the frame's call list
(PS2X_REFERENCE_CALLS / _FROM: <file>.calls), the two lists side by side from their first difference.
Exit status 0: identical over the frames both have (and the same length); 1: they differ; 2: unreadable input.
"""
import argparse
import os
import struct
import sys
HEADER = struct.Struct('<8sIIIIIIQII64s64s64s')
RECORD = struct.Struct('<IiQQQQQQQIIII')
FIELDS = ('frame', 'thread', 'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads', 'eeCycle', 'callCount',
'drawBatches', 'drawVertices', 'soundSamples')
# The order fields are reported in (the guest's state first, then what it went through, then the counters).
COMPARED = ('ram', 'scratchpad', 'calls', 'callCount', 'draws', 'drawBatches', 'drawVertices', 'sound', 'soundSamples',
'threads', 'thread', 'eeCycle')
HEXED = {'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads'}
class Reference:
def __init__(self, path):
self.path = path
with open(path, 'rb') as f:
data = f.read()
if len(data) < HEADER.size:
raise ValueError(f'{path}: too short for a header')
(magic, version, header_bytes, record_bytes, hash_id, ram_bytes, sp_bytes, elf_hash, flags, mask_count, run,
build, elf) = HEADER.unpack_from(data, 0)
if magic != b'PS2XREF1':
raise ValueError(f'{path}: not a reference record (magic {magic!r})')
if record_bytes != RECORD.size:
raise ValueError(f'{path}: records of {record_bytes} bytes, this tool reads {RECORD.size}')
self.version, self.hash_id, self.elf_hash, self.flags = version, hash_id, elf_hash, flags
self.ram_bytes, self.sp_bytes = ram_bytes, sp_bytes
self.run, self.build, self.elf = (s.split(b'\0', 1)[0].decode(errors='replace') for s in (run, build, elf))
self.masks = [struct.unpack_from('<II', data, HEADER.size + 8 * i) for i in range(mask_count)]
body = data[header_bytes:]
count = len(body) // RECORD.size
self.records = [dict(zip(FIELDS, RECORD.unpack_from(body, i * RECORD.size))) for i in range(count)]
self.partial = len(body) % RECORD.size
def describe(self):
return (f'{self.path}: run "{self.run}", build "{self.build}", ELF {self.elf} {self.elf_hash:016x}, '
f'{"deterministic" if self.flags & 1 else "NOT deterministic"}, {len(self.records)} frames'
+ (f', {len(self.masks)} masked ranges' if self.masks else '')
+ (f' (+{self.partial} bytes of a cut record)' if self.partial else ''))
def value(field, v):
return f'{v:016x}' if field in HEXED else str(v)
def ram_block(a, b, frame):
"""The first differing 32-byte block of RAM (then the scratchpad) between the two runs' dumps of `frame`."""
pa, pb = f'{a.path}.ram.{frame}', f'{b.path}.ram.{frame}'
if not (os.path.exists(pa) and os.path.exists(pb)):
return f' (no RAM dumps of frame {frame}: run both again with PS2X_REFERENCE_DUMP={frame} for the first differing block)'
with open(pa, 'rb') as fa, open(pb, 'rb') as fb:
da, db = fa.read(), fb.read()
lines = []
for offset in range(0, min(len(da), len(db)), 32):
if da[offset:offset + 32] != db[offset:offset + 32]:
where = f'RAM {offset:08x}' if offset < a.ram_bytes else f'scratchpad {offset - a.ram_bytes:04x}'
lines.append(f' first differing 32-byte block: {where}')
lines.append(f' {a.run:>12}: {da[offset:offset + 32].hex(" ", 4)}')
lines.append(f' {b.run:>12}: {db[offset:offset + 32].hex(" ", 4)}')
differing = sum(1 for o in range(0, min(len(da), len(db)), 32) if da[o:o + 32] != db[o:o + 32])
lines.append(f' ({differing} blocks differ in all)')
return '\n'.join(lines)
return ' (the dumps are the same: the hash differs elsewhere, a masked range?)'
def call_list(path, frame):
"""The call list of `frame` from <file>.calls, or None."""
calls = path + '.calls'
if not os.path.exists(calls):
return None
found, lines = False, []
with open(calls, encoding='utf-8', errors='replace') as f:
for line in f:
if line.startswith('frame '):
if found:
break
found = int(line.split()[1]) == frame
continue
if found:
lines.append(line.rstrip('\n').strip())
return lines if found else None
def call_lists(a, b, frame, shown):
la, lb = call_list(a.path, frame), call_list(b.path, frame)
if la is None or lb is None:
return (f' (no call lists of frame {frame} in both: run both with PS2X_REFERENCE_CALLS_FROM={frame} '
f'PS2X_REFERENCE_CALLS=1 to see them)')
first = next((i for i in range(max(len(la), len(lb))) if i >= len(la) or i >= len(lb) or la[i] != lb[i]), None)
if first is None:
return ' (the lists read the same: the difference is in a value the text rounds?)'
width = max([len(x) for x in la[first:first + shown]] + [len(a.run), 10])
out = [f' calls from #{first} ({len(la)} / {len(lb)} calls):', f' {a.run:<{width}} | {b.run}']
for i in range(first, min(max(len(la), len(lb)), first + shown)):
left = la[i] if i < len(la) else ''
right = lb[i] if i < len(lb) else ''
out.append(f' {"*" if left != right else " "} {left:<{width}} | {right}')
return '\n'.join(out)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('a')
parser.add_argument('b')
parser.add_argument('--ignore', default='', help='fields not compared, comma-separated (e.g. eeCycle)')
parser.add_argument('--lines', type=int, default=24, help='call list lines shown from the first difference')
args = parser.parse_args()
try:
a, b = Reference(args.a), Reference(args.b)
except (OSError, ValueError) as error:
print(error, file=sys.stderr)
return 2
print(a.describe())
print(b.describe())
if a.elf_hash != b.elf_hash:
print('warning: not the same ELF')
if a.masks != b.masks:
print('warning: not the same masked RAM ranges')
ignored = {f for f in args.ignore.split(',') if f}
unknown = ignored - set(COMPARED)
if unknown:
print(f'unknown fields: {", ".join(sorted(unknown))} (fields: {", ".join(COMPARED)})', file=sys.stderr)
return 2
fields = [f for f in COMPARED if f not in ignored]
frames = min(len(a.records), len(b.records))
first_by_field = {}
first = None
for i in range(frames):
ra, rb = a.records[i], b.records[i]
if ra['frame'] != i or rb['frame'] != i:
print(f'record {i}: frame numbers {ra["frame"]} / {rb["frame"]} (a record missing?)')
for f in fields:
if ra[f] != rb[f] and f not in first_by_field:
first_by_field[f] = i
if first is None and any(ra[f] != rb[f] for f in fields):
first = i
if first is None:
same = len(a.records) == len(b.records)
print(f'identical: {frames} frames compared ({", ".join(fields)})'
+ ('' if same else f'; lengths differ ({len(a.records)} / {len(b.records)} frames)'))
return 0 if same else 1
ra, rb = a.records[first], b.records[first]
print(f'first difference at frame {first} (of {frames} compared; the {first} before are identical):')
for f in fields:
if ra[f] != rb[f]:
print(f' {f:<13} {value(f, ra[f]):>16} {value(f, rb[f]):>16}')
print('first frame each field differs at: ' + ', '.join(f'{f} {n}' for f, n in sorted(first_by_field.items(), key=lambda x: x[1])))
if 'ram' in first_by_field and first_by_field['ram'] == first:
print(ram_block(a, b, first))
if 'calls' in first_by_field:
print(call_lists(a, b, first_by_field['calls'], args.lines))
return 1
if __name__ == '__main__':
sys.exit(main())
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""A timed pad script (PS2X_PAD_SCRIPT, seconds) as a frame-keyed one for deterministic mode (PS2X_DETERMINISTIC=1:
"frame:BUTTON/frames"), docs/REFERENCE_HARNESS.md.
tools/ref_pad_script.py --log calibration.log "<seconds script>" (or --script-file f)
tools/ref_pad_script.py --log calibration.log --from-log
Calibration: run the timed script once in deterministic mode with the pad on the wall clock and its changes logged
(PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1, stderr to calibration.log): each "[pad] frame N t=T" line
anchors second T to game frame N. A time between two anchors maps linearly between their frames, outside them at 60
frames a second from the nearest one; holds become frames at 60 a second (at least 1). --from-log: pad 1's script
rebuilt from the logged changes themselves (each press at the frame it began in the calibration run, held as long),
the closest to what the calibration run did. Without --log, seconds map to frames at 60 a second from frame 0
(`--offset` frames added): for scripts already written in game time, such as the driving part of a match counted
from its start.
"""
import argparse
import bisect
import re
import sys
BUTTONS = {0x0080: 'LEFT', 0x0040: 'DOWN', 0x0020: 'RIGHT', 0x0010: 'UP', 0x0008: 'START', 0x0004: 'R3', 0x0002: 'L3',
0x0001: 'SELECT', 0x8000: 'SQUARE', 0x4000: 'CROSS', 0x2000: 'CIRCLE', 0x1000: 'TRIANGLE', 0x0800: 'R1',
0x0400: 'L1', 0x0200: 'R2', 0x0100: 'L2'}
LOG_LINE = re.compile(r'\[pad\] frame (\d+) t=([0-9.]+): scripted ([0-9a-f]+)')
def anchors_from(log_path):
points = []
with open(log_path, encoding='utf-8', errors='replace') as f:
for line in f:
m = LOG_LINE.search(line)
if m:
points.append((float(m.group(2)), int(m.group(1))))
points.sort()
return points
def from_log(log_path):
"""Pad 1's presses as the calibration run logged them: frame pressed, button, frames held."""
presses, down, since = [], 0, {}
with open(log_path, encoding='utf-8', errors='replace') as f:
for line in f:
m = LOG_LINE.search(line)
if not m:
continue
frame, mask = int(m.group(1)), int(m.group(3), 16)
for bit, name in BUTTONS.items():
if mask & bit and not down & bit:
since[bit] = frame
elif down & bit and not mask & bit:
presses.append((since[bit], name, max(1, frame - since[bit])))
down = mask
for bit, name in BUTTONS.items():
if down & bit: # still held when the log ends: held to the end
presses.append((since[bit], name, 1000000))
presses.sort()
return ','.join(f'{f}:{b}/{h}' for f, b, h in presses)
def to_frame(seconds, anchors, offset):
if not anchors:
return offset + round(seconds * 60.0)
times = [t for t, _ in anchors]
i = bisect.bisect_right(times, seconds)
if i == 0:
t, f = anchors[0]
return max(0, f - round((t - seconds) * 60.0))
if i == len(anchors):
t, f = anchors[-1]
return f + round((seconds - t) * 60.0)
(t0, f0), (t1, f1) = anchors[i - 1], anchors[i]
if t1 == t0:
return f0
return round(f0 + (f1 - f0) * (seconds - t0) / (t1 - t0))
def convert(script, anchors, offset):
out = []
for entry in filter(None, (e.strip() for e in script.replace('\n', ',').split(','))):
when, _, press = entry.partition(':')
button, _, held = press.partition('/')
frames = max(1, round(float(held) * 60.0 / 1000.0)) if held else 30
out.append((to_frame(float(when), anchors, offset), button, frames))
out.sort()
return ','.join(f'{f}:{b}/{h}' for f, b, h in out)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('script', nargs='?', default=None)
parser.add_argument('--script-file')
parser.add_argument('--log', help="a calibration run's log (PS2X_PAD_LOG=1 lines)")
parser.add_argument('--from-log', action='store_true', help="pad 1's script from the logged changes")
parser.add_argument('--offset', type=int, default=0, help='frames added (without --log)')
args = parser.parse_args()
if args.from_log:
if not args.log:
parser.error('--from-log needs --log')
print(from_log(args.log))
return 0
script = open(args.script_file).read() if args.script_file else args.script
if not script:
parser.error('no script')
anchors = anchors_from(args.log) if args.log else []
print(convert(script, anchors, args.offset))
return 0
if __name__ == '__main__':
sys.exit(main())
+14 -4
View File
@@ -11,7 +11,8 @@ What it reads:
- the NGP files (LVL/*.NGP, SHELL/*.NGP: a zip entry, "IE" instead of "PK", raw deflate after the local header;
ACAR/PCAR car files: raw). Each is a memory image linked at EE 0x980000: a pointer is (value - 0x980000) in the file.
The .PTR file next to it lists the pointer words (its first count, then their byte offsets); a hierobject is a node
of type 0 (word 0 bits 0-5) whose +4 (a listed pointer) is its own prebuilt packet, at obj + 0x70 + 0x30 * ntex.
of type 0 (word 0 bits 0-5) whose +4 (a listed pointer) is its own prebuilt packet, at obj + 0x70 + 0x30 * ntex
or a little after it, zeros between (LOOP pads some packets to an alignment).
- the hierobject: +8 u64 flags (VU1 program choice), +0x10 bounding sphere, +0x50 u16[5] texture numbers (the file's
own, before the game adds the file's texture base), +0x5a ntex, +0x64 skeleton (0 = rigid).
- its packet: DMA tags (REF: data elsewhere in the file, next tag after it; CNT / RET: data after the tag, RET ends;
@@ -104,18 +105,27 @@ def load_pointers(path):
def find_objects(image, pointers):
"""Every hierobject: a type 0 node whose listed +4 pointer is its own packet."""
"""Every hierobject: a type 0 node whose listed +4 pointer is its own packet: right after its texture blocks, or up
to 0x100 bytes later with only zeros between (an aligned packet: LOOP's)."""
found = []
for slot in pointers:
obj = slot - 4
if obj < 0 or obj + 0x70 > len(image) or u32(image, obj) & 0x3f:
continue
ntex = u16(image, obj + 0x5a)
if ntex <= 5 and u32(image, obj + 4) - LINK == obj + 0x70 + 0x30 * ntex:
if ntex > 5:
continue
after, packet = obj + 0x70 + 0x30 * ntex, u32(image, obj + 4) - LINK
if packet == after or (after < packet < after + 0x100 and packet % 16 == 0 and not any(image[after:packet])):
found.append(obj)
return sorted(set(found))
def packet_start(image, obj):
"""Where an object's packet is: its +4 pointer (find_objects checked it)."""
return u32(image, obj + 4) - LINK
def packet_segments(image, start):
"""The DMA chain from start: [(VIF bytes, their offset in the image)] (the tag's two VIF codes first)."""
return dma_chain(image, start, LINK)
@@ -129,7 +139,7 @@ def packet_stream(image, obj):
def packet_stream_mapped(image, obj):
"""The same, with where each piece of it is in the image: (stream, [(stream offset, image offset, length)])."""
return chain_stream(image, obj + 0x70 + 0x30 * u16(image, obj + 0x5a), LINK)
return chain_stream(image, packet_start(image, obj), LINK)
class Strip: