mirror of
https://github.com/TheBozos/TMB_Recomp.git
synced 2026-12-01 12:54:41 -10:00
Compare commits
17
Commits
No files matched your search
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://recomp.fyi/schema/v1.json",
|
||||
"game": "Twisted Metal: Black",
|
||||
"wikidata": "Q2978434",
|
||||
"system": "PS2",
|
||||
"type": "recomp",
|
||||
"original": {
|
||||
"region": "USA",
|
||||
"serial": "SCUS-97101"
|
||||
},
|
||||
"project": "TMB_Recomp",
|
||||
"status": "released",
|
||||
"targets": ["Windows"],
|
||||
"toolchain": "Ps2recomp",
|
||||
"approach": "Static recompilation with a PS2Recomp fork; native PC renderer, sound and timing, no GS, VU or SPU2 emulation in the default mode.",
|
||||
"started": "2026-10-22",
|
||||
"maintainers": [
|
||||
{ "name": "boubou666", "link": "https://github.com/boubou666" },
|
||||
{ "name": "Arzaroth", "link": "https://github.com/Arzaroth" }
|
||||
],
|
||||
"links": [
|
||||
{ "label": "Releases", "url": "https://github.com/TheBozos/TMB_Recomp/releases" },
|
||||
{ "label": "RecompWatcher (The Bozos' projects)", "url": "https://thebozos.github.io/RecompWatcher/" }
|
||||
],
|
||||
"help": [
|
||||
"Playtesting story levels 2 to 8 to the endings",
|
||||
"Testing on high-refresh monitors (the experimental smoothed frame rate)",
|
||||
"Testing on Linux"
|
||||
],
|
||||
"notes": "Playable at 60 fps on Windows, built by the launcher from the player's own USA disc. Every Challenge arena played, split screen for 2 to 4 players, memory card saves, rebindable controls including keyboard and mouse, video settings and cheats. Next: story levels 2 to 8 checked to the end, widescreen."
|
||||
}
|
||||
+65
-1
@@ -7,6 +7,67 @@ 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
|
||||
|
||||
- **The launcher updates the game itself**: when a new version is out, "Update" on the Play tab downloads it, checks
|
||||
it, installs it over this one and restarts the launcher; then "Rebuild now" prepares the game again (only what
|
||||
changed). Your saves and settings stay. Unzipping a new release by hand still works too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Smoother frame times**: the game does less work each frame (about 2 ms less per frame in our tests), so slower PCs
|
||||
drop fewer frames in busy fights. The lens flares no longer read the whole picture back from the graphics card
|
||||
each frame.
|
||||
|
||||
### Known limits
|
||||
|
||||
- Players on 0.1.0 or 0.2.0 update to this version by hand one last time (unzip it over the old one, then Rebuild);
|
||||
from 0.3.0 on, the launcher's Update button does it.
|
||||
- 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.2.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
@@ -62,6 +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.2.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
@@ -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
-1
Submodule PS2Recomp updated: 65a7c92513...df2dfe2137.
@@ -48,8 +48,9 @@ You build the game yourself, on your PC, from **your own disc**: nothing of the
|
||||
logs are in `%APPDATA%\TMB_Recomp` (the launcher's Maintenance tab opens it).
|
||||
|
||||
The launcher says when a newer release is out (it asks GitHub for the latest version number at start; Settings
|
||||
turns that off; nothing is downloaded by itself). After an update, unzip the new release where the old one was (replacing the files): the
|
||||
launcher sees the code changed since the game was built and offers **Rebuild now** (also Rebuild in the Maintenance
|
||||
turns that off; nothing is downloaded by itself). Its **Update** button downloads the new release's zip, checks it against the
|
||||
release's SHA-256, installs it over this one and restarts (`tools/apply_update.py`); unzipping the new release where the old
|
||||
one was (replacing the files) does the same by hand. The launcher then sees the code changed since the game was built and offers **Rebuild now** (also Rebuild in the Maintenance
|
||||
tab); only what changed is built again, the files the new release no longer has are removed, and the saves stay. To uninstall, delete the folder (and `%APPDATA%\TMB_Recomp` for the saves
|
||||
and settings). Releases are Windows only for now; on Linux the port builds from source (below), but has not been
|
||||
tested there since the native work of November 2026.
|
||||
@@ -290,13 +291,19 @@ rem -DLAUNCHER_FONT_DIR=<folder with Exo2[wght].ttf and O
|
||||
configure time, never committed). The icon is TMB's variant of The Bozos' logo, the clown with its head on fire (`launcher/tmb.ico`; the game's window uses the same, `runtime/app/tmb.ico`; drawn by `docs/branding/make_logo.py`). No game art.
|
||||
- Updates: at start (Settings: "Check for updates at start") and from Maintenance's "Check for updates", one HTTPS
|
||||
GET of `api.github.com/repos/TheBozos/TMB_Recomp/releases/latest` through WinHTTP; a newer `tag_name` shows
|
||||
"Version X is available" with a link to its release page (built from the tag). Offline or no release: silent. When
|
||||
"Version X is available" with a link to its release page (built from the tag). Offline or no release: silent. Update
|
||||
downloads `releases/download/<tag>/TMB_Recomp-<version>.zip` and its `.sha256` (addresses built from the tag, not read
|
||||
from the API's answer) into `update\`, then runs `source\tools\apply_update.py` with the kit's Python: it checks the
|
||||
SHA-256 and every name in the zip (one `TMB_Recomp\` folder, no `..`, nothing under `build\` or `game\`, the version
|
||||
asked for), unpacks it whole to `update\staging`, then moves the files over the release; a file in use (the launcher
|
||||
itself) is renamed `*.tmb-old` first and deleted at the next start. The launcher then starts its new exe. When
|
||||
`source\release.ini`'s commit differs from the one in `game\built_from.ini` (written by tmb_build), the Play tab
|
||||
offers "Rebuild now".
|
||||
- `--selftest <iso> --shots <dir> [--wrong <image>] [--error-demo] [--cancel] [--play-seconds s] [--crash-seconds s]`:
|
||||
the whole flow unattended, a screenshot of each screen and `selftest.log` (with `PS2X_USER_DIR` set, the real user
|
||||
folder is untouched). `--screens`: the tabs' screenshots only; `--ui-scale <x>`: another DPI scale; `--update-url
|
||||
<url>`: the update check asks another address (a test server).
|
||||
<url>`: the update check asks another address (a test server); `--download-prefix <url>` downloads the release from
|
||||
there, `--update-now` presses Update once a newer release is found.
|
||||
|
||||
### The release (maintainers)
|
||||
|
||||
@@ -460,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>` |
|
||||
|
||||
@@ -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.
|
||||
@@ -53,6 +53,8 @@ Release: `TMB_Recomp-<version>.zip`, SHA-256 `<from the .sha256>`, commit `<comm
|
||||
|
||||
- [ ] With an older release published: "Version X is available" on the Play tab, "Open the release page" opens it.
|
||||
- [ ] Settings, "Check for updates at start: off": no request at start (a proxy log, or offline: nothing changes).
|
||||
- [ ] With an older release installed: **Update** on the Play tab downloads, installs and restarts the launcher on the
|
||||
new version (Maintenance shows it); no `update\` folder or `*.tmb-old` file is left after the next start.
|
||||
- [ ] Unzip the new release over the old one: the Play tab says the new version is installed and offers **Rebuild
|
||||
now**; after it, the notice is gone, the memory cards (`%APPDATA%\TMB_Recomp\mc0`, `mc1`) and settings are
|
||||
unchanged, the game plays.
|
||||
|
||||
+264
-10
@@ -24,6 +24,7 @@
|
||||
#include "rlImGui.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -56,6 +57,9 @@ static const char *kCommit = TMB_COMMIT;
|
||||
// The update check: GitHub's latest release of the main repository (drafts and pre-releases are never "latest").
|
||||
static const char *kLatestReleaseApi = "https://api.github.com/repos/TheBozos/TMB_Recomp/releases/latest";
|
||||
static const char *kReleasePagePrefix = "https://github.com/TheBozos/TMB_Recomp/releases/tag/";
|
||||
// A release's files (the Update button): <prefix><tag>/TMB_Recomp-<version>.zip and its .sha256, the address made
|
||||
// here from the tag like the page's, never one read from the API's response.
|
||||
static const char *kReleaseDownloadPrefix = "https://github.com/TheBozos/TMB_Recomp/releases/download/";
|
||||
|
||||
// ---- language ----
|
||||
|
||||
@@ -171,7 +175,7 @@ struct UpdateCheck
|
||||
};
|
||||
std::mutex mutex;
|
||||
State state = State::Idle;
|
||||
std::string version, page, error;
|
||||
std::string version, page, error, tag;
|
||||
bool manual = false; // the button: say the outcome, even "you have the latest"
|
||||
std::thread worker;
|
||||
|
||||
@@ -203,13 +207,17 @@ struct UpdateCheck
|
||||
return;
|
||||
}
|
||||
version = tag[0] == 'v' || tag[0] == 'V' ? tag.substr(1) : tag;
|
||||
this->tag = tag;
|
||||
page = kReleasePagePrefix + tag;
|
||||
state = newerVersion(tag, kVersion) ? State::Available : State::Latest; });
|
||||
}
|
||||
|
||||
State get(std::string *v = nullptr, std::string *p = nullptr, std::string *e = nullptr, bool *byHand = nullptr)
|
||||
State get(std::string *v = nullptr, std::string *p = nullptr, std::string *e = nullptr, bool *byHand = nullptr,
|
||||
std::string *t = nullptr)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
if (t)
|
||||
*t = tag;
|
||||
if (v)
|
||||
*v = version;
|
||||
if (p)
|
||||
@@ -371,6 +379,36 @@ struct App
|
||||
// The update check, and the code the game was built from (an update unzipped over the release: Rebuild).
|
||||
UpdateCheck updates;
|
||||
std::string updateUrl = kLatestReleaseApi;
|
||||
|
||||
// Installing an update (the Update button): the release's zip and .sha256 downloaded into the update folder (a
|
||||
// thread), then source/tools/apply_update.py (the kit's Python) checks and installs them, and the launcher starts
|
||||
// its new self.
|
||||
enum class UpdateStep
|
||||
{
|
||||
Idle,
|
||||
Downloading,
|
||||
Installing,
|
||||
Restarting,
|
||||
Failed
|
||||
};
|
||||
UpdateStep updateStep = UpdateStep::Idle;
|
||||
std::string updateVersion, updateError, updatePhase; // updatePhase: apply_update's step (verify, extract...)
|
||||
std::string downloadPrefix = kReleaseDownloadPrefix;
|
||||
std::vector<std::string> restartArgs; // this launcher's arguments, given to the new one
|
||||
std::atomic<uint64_t> updateDone{0}, updateTotal{0};
|
||||
std::atomic<bool> updateCancel{false}, downloadFinished{false};
|
||||
std::mutex downloadMutex;
|
||||
bool downloadOk = false;
|
||||
std::string downloadError;
|
||||
std::thread downloader;
|
||||
plat::Process installer;
|
||||
|
||||
~App()
|
||||
{
|
||||
updateCancel = true; // a download stops at its next block
|
||||
if (downloader.joinable())
|
||||
downloader.join();
|
||||
}
|
||||
std::string sourceCommit, sourceVersion, builtCommit;
|
||||
bool runCounted = false; // this build run's time is already in cfg.pendingSeconds
|
||||
// "What's new": CHANGELOG.md's section for the installed version (the release's top folder, else source\).
|
||||
@@ -415,6 +453,171 @@ struct App
|
||||
missingPart = "kit\\";
|
||||
phase = !missingPart.empty() ? Phase::Incomplete : cfg.disc.empty() ? Phase::Welcome : Phase::Ready;
|
||||
readStamps();
|
||||
cleanUpdateLeftovers();
|
||||
}
|
||||
|
||||
// -- updates
|
||||
|
||||
std::string updateDir() const { return plat::str(plat::path(p.release) / L"update"); }
|
||||
|
||||
// An update's leftovers: the files apply_update.py set aside because they were in use (this launcher's old exe,
|
||||
// the kit's Python), listed in update/old_files.txt; deleted now, or at a later start if still in use.
|
||||
void cleanUpdateLeftovers()
|
||||
{
|
||||
const fs::path list = plat::path(updateDir()) / L"old_files.txt";
|
||||
std::error_code ec;
|
||||
if (!fs::exists(list, ec))
|
||||
return;
|
||||
std::ifstream in(list);
|
||||
std::string line, kept;
|
||||
while (std::getline(in, line))
|
||||
{
|
||||
if (!line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
// Only what it set aside in this release folder.
|
||||
if (line.rfind(p.release, 0) != 0 || line.find(".tmb-old") == std::string::npos)
|
||||
continue;
|
||||
const fs::path file = plat::path(line);
|
||||
if (!fs::remove(file, ec) && fs::exists(file, ec))
|
||||
kept += line + "\n";
|
||||
}
|
||||
in.close();
|
||||
if (kept.empty())
|
||||
{
|
||||
fs::remove(list, ec);
|
||||
fs::remove(plat::path(updateDir()), ec); // only when empty (a stopped download's files stay)
|
||||
}
|
||||
else if (std::ofstream out{list, std::ios::trunc})
|
||||
out << kept;
|
||||
}
|
||||
|
||||
bool updating() const
|
||||
{
|
||||
return updateStep == UpdateStep::Downloading || updateStep == UpdateStep::Installing || updateStep == UpdateStep::Restarting;
|
||||
}
|
||||
|
||||
void startUpdate(const std::string &tag, const std::string &version)
|
||||
{
|
||||
if (updating() || building || gameRunning || checking || tag.empty() || version.empty())
|
||||
return;
|
||||
std::error_code ec;
|
||||
fs::create_directories(plat::path(updateDir()), ec);
|
||||
updateVersion = version;
|
||||
updateError.clear();
|
||||
updatePhase.clear();
|
||||
updateCancel = false;
|
||||
downloadFinished = false;
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
updateStep = UpdateStep::Downloading;
|
||||
if (downloader.joinable())
|
||||
downloader.join();
|
||||
const std::string name = "TMB_Recomp-" + version + ".zip";
|
||||
const std::string url = downloadPrefix + tag + "/" + name;
|
||||
const std::string zip = plat::str(plat::path(updateDir()) / plat::path(name));
|
||||
downloader = std::thread([this, url, zip]
|
||||
{
|
||||
const std::string agent = std::string("TMB-Launcher/") + kVersion;
|
||||
std::atomic<uint64_t> shaDone{0}, shaTotal{0};
|
||||
std::string error;
|
||||
const bool ok = plat::httpDownload(url + ".sha256", agent, zip + ".sha256", shaDone, shaTotal, updateCancel, error, 4096) &&
|
||||
plat::httpDownload(url, agent, zip, updateDone, updateTotal, updateCancel, error);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downloadMutex);
|
||||
downloadOk = ok;
|
||||
downloadError = error;
|
||||
}
|
||||
downloadFinished = true; });
|
||||
}
|
||||
|
||||
void cancelUpdate()
|
||||
{
|
||||
if (updateStep == UpdateStep::Downloading)
|
||||
updateCancel = true;
|
||||
}
|
||||
|
||||
void pollUpdate()
|
||||
{
|
||||
if (updateStep == UpdateStep::Downloading && downloadFinished)
|
||||
{
|
||||
downloader.join();
|
||||
bool ok;
|
||||
std::string error;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downloadMutex);
|
||||
ok = downloadOk;
|
||||
error = downloadError;
|
||||
}
|
||||
if (!ok)
|
||||
{
|
||||
updateStep = updateCancel ? UpdateStep::Idle : UpdateStep::Failed;
|
||||
updateError = std::string(L("The download failed: ", "Le téléchargement a échoué : ")) + error + ".";
|
||||
return;
|
||||
}
|
||||
const std::string zip = plat::str(plat::path(updateDir()) / plat::path("TMB_Recomp-" + updateVersion + ".zip"));
|
||||
const std::vector<std::string> args = {"-I", "-X", "utf8", plat::str(plat::path(p.source) / L"tools" / L"apply_update.py"),
|
||||
"--zip", zip, "--sha256", zip + ".sha256", "--version", updateVersion,
|
||||
"--install", p.release};
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
std::string startError;
|
||||
if (!installer.start(p.python, args, p.release, true, startError))
|
||||
{
|
||||
updateStep = UpdateStep::Failed;
|
||||
updateError = std::string(L("The update could not start: ", "La mise à jour n'a pas pu démarrer : ")) + startError;
|
||||
return;
|
||||
}
|
||||
updateStep = UpdateStep::Installing;
|
||||
return;
|
||||
}
|
||||
if (updateStep != UpdateStep::Installing)
|
||||
return;
|
||||
auto feed = [&](const std::string &line)
|
||||
{
|
||||
unsigned long long a = 0, b = 0;
|
||||
if (line.rfind("step ", 0) == 0)
|
||||
{
|
||||
updatePhase = line.substr(5);
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
}
|
||||
else if (line.rfind("progress ", 0) == 0 && std::sscanf(line.c_str() + 9, "%llu %llu", &a, &b) == 2)
|
||||
{
|
||||
updateDone = a;
|
||||
updateTotal = b;
|
||||
}
|
||||
else if (line.rfind("error ", 0) == 0)
|
||||
updateError = line.substr(6);
|
||||
else if (line.rfind("done ", 0) == 0)
|
||||
updatePhase = "done";
|
||||
};
|
||||
for (const std::string &line : installer.takeLines())
|
||||
feed(line);
|
||||
if (installer.running())
|
||||
return;
|
||||
installer.drain(2000);
|
||||
for (const std::string &line : installer.takeLines())
|
||||
feed(line);
|
||||
if (installer.exitCode() != 0 || updatePhase != "done")
|
||||
{
|
||||
updateStep = UpdateStep::Failed;
|
||||
if (updateError.empty())
|
||||
updateError = std::string(L("The update stopped (exit code ", "La mise à jour s'est arrêtée (code ")) +
|
||||
std::to_string(installer.exitCode()) + ").";
|
||||
return;
|
||||
}
|
||||
// Installed: the new launcher (now at this exe's path) takes over, and offers Rebuild.
|
||||
plat::Process next;
|
||||
std::string startError;
|
||||
if (next.start(plat::exePath(), restartArgs, p.release, false, startError))
|
||||
{
|
||||
updateStep = UpdateStep::Restarting;
|
||||
quit = true;
|
||||
return;
|
||||
}
|
||||
updateStep = UpdateStep::Failed;
|
||||
updateError = std::string(L("Version ", "La version ")) + updateVersion +
|
||||
L(" is installed: start the launcher again. ", " est installée : relancez le lanceur. ") + startError;
|
||||
}
|
||||
|
||||
// The source's commit (source\release.ini, else the launcher's own) and the one the game was built from.
|
||||
@@ -1005,16 +1208,50 @@ static void drawReady(App &app, float inner)
|
||||
// One note at a time (both do not fit the card at the window's smallest size): Rebuild first; the footer and
|
||||
// Maintenance still say a newer release is out.
|
||||
const bool rebuildShown = built && !app.cfg.buildPending && app.codeChanged() && !app.building;
|
||||
if (!rebuildShown && app.updates.get(&newVersion, &page) == UpdateCheck::State::Available &&
|
||||
newVersion != app.sourceVersion)
|
||||
std::string newTag;
|
||||
if (app.updating())
|
||||
{
|
||||
// Downloading, then apply_update.py's steps, each with its bar.
|
||||
gap(12);
|
||||
const std::string what = std::string(L("Updating to version ", "Mise à jour vers la version ")) + app.updateVersion + "\xE2\x80\xA6";
|
||||
const uint64_t done = app.updateDone, total = app.updateTotal;
|
||||
char detail[160];
|
||||
if (app.updateStep == App::UpdateStep::Downloading)
|
||||
std::snprintf(detail, sizeof(detail), L("Downloading: %.0f of %.0f MB.", "Téléchargement : %.0f sur %.0f Mo."), done / 1e6, total / 1e6);
|
||||
else
|
||||
std::snprintf(detail, sizeof(detail), "%s",
|
||||
app.updatePhase == "verify" ? L("Checking the download.", "Vérification du téléchargement.")
|
||||
: app.updatePhase == "extract" ? L("Unpacking.", "Décompression.")
|
||||
: app.updatePhase == "install" ? L("Installing.", "Installation.")
|
||||
: L("Finishing.", "Finalisation."));
|
||||
noteBox(what.c_str(), detail, ui::color::wip, inner);
|
||||
gap(6);
|
||||
ui::progressBar(total ? static_cast<float>(static_cast<double>(done) / static_cast<double>(total)) : 0.0f, ImVec2(inner, S(18)), app.time);
|
||||
if (app.updateStep == App::UpdateStep::Downloading)
|
||||
{
|
||||
gap(6);
|
||||
if (ui::button(L("Stop", "Arrêter"), ImVec2(0, S(48))))
|
||||
app.cancelUpdate();
|
||||
}
|
||||
}
|
||||
else if (!rebuildShown && app.updates.get(&newVersion, &page, nullptr, nullptr, &newTag) == UpdateCheck::State::Available &&
|
||||
newVersion != app.sourceVersion)
|
||||
{
|
||||
gap(12);
|
||||
const bool failed = app.updateStep == App::UpdateStep::Failed;
|
||||
std::string what = std::string(L("Version ", "La version ")) + newVersion + L(" is available.", " est disponible.");
|
||||
noteBox(what.c_str(),
|
||||
L("Download it from the release page and unzip it where you unzipped this one (replace the files), then Rebuild.",
|
||||
"Téléchargez-la depuis la page de la version et décompressez-la au même endroit que celle-ci (remplacez les fichiers), puis Reconstruire."),
|
||||
ui::color::cross, inner);
|
||||
failed ? app.updateError
|
||||
: std::string(L("Update downloads and installs it here, then the launcher restarts and Rebuild prepares the game again "
|
||||
"(only what changed). Your saves and settings stay.",
|
||||
"Mettre à jour la télécharge et l'installe ici, puis le lanceur redémarre et Reconstruire prépare "
|
||||
"à nouveau le jeu (seulement ce qui a changé). Vos sauvegardes et réglages restent.")),
|
||||
failed ? ui::color::early : ui::color::cross, inner);
|
||||
gap(6);
|
||||
if (ui::button(failed ? L("Try again", "Réessayer") : L("Update", "Mettre à jour"), ImVec2(0, S(48)), ui::Kind::Primary,
|
||||
!app.building && !app.gameRunning))
|
||||
app.startUpdate(newTag, newVersion);
|
||||
ImGui::SameLine(0, S(12));
|
||||
if (ui::button(L("Open the release page", "Ouvrir la page de la version"), ImVec2(0, S(48))))
|
||||
plat::open(page);
|
||||
}
|
||||
@@ -1765,8 +2002,8 @@ int main(int argc, char **argv)
|
||||
bool errorDemo = false, cancel = false, screensOnly = false;
|
||||
double playSeconds = 40, crashSeconds = 0;
|
||||
float uiScale = 0;
|
||||
std::string updateUrl, selfCheckFile, reportPath;
|
||||
bool versionOnly = false;
|
||||
std::string updateUrl, selfCheckFile, reportPath, downloadPrefix;
|
||||
bool versionOnly = false, updateNow = false;
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
const std::vector<std::string> args = plat::arguments(); // UTF-8, from the wide command line
|
||||
@@ -1796,6 +2033,10 @@ int main(int argc, char **argv)
|
||||
uiScale = static_cast<float>(std::atof(next().c_str()));
|
||||
else if (a == "--update-url") // a test: another address answering as GitHub's latest-release API
|
||||
updateUrl = next();
|
||||
else if (a == "--download-prefix") // a test: another address serving <tag>/TMB_Recomp-<version>.zip
|
||||
downloadPrefix = next();
|
||||
else if (a == "--update-now") // a test: presses Update once the check finds a newer release
|
||||
updateNow = true;
|
||||
else if (a == "--self-check") // no window: the release folder and the disc check on a file (see selfCheck)
|
||||
selfCheckFile = next();
|
||||
else if (a == "--report")
|
||||
@@ -1841,6 +2082,9 @@ int main(int argc, char **argv)
|
||||
// The update check at start (setting "update_check"): not for a development launcher, unless pointed somewhere.
|
||||
if (!updateUrl.empty())
|
||||
app.updateUrl = updateUrl;
|
||||
if (!downloadPrefix.empty())
|
||||
app.downloadPrefix = downloadPrefix;
|
||||
app.restartArgs = args;
|
||||
if (app.cfg.updateCheck && (std::strcmp(kVersion, "dev") != 0 || !updateUrl.empty()))
|
||||
app.updates.start(app.updateUrl, false);
|
||||
|
||||
@@ -1870,12 +2114,22 @@ int main(int argc, char **argv)
|
||||
{
|
||||
if (app.building)
|
||||
app.wantQuit = true;
|
||||
else
|
||||
else if (app.updateStep != App::UpdateStep::Installing) // installing: not stopped half way
|
||||
break;
|
||||
}
|
||||
app.time = plat::now() - t0;
|
||||
app.pollCheck();
|
||||
app.pollBuild();
|
||||
app.pollUpdate();
|
||||
if (updateNow && app.updateStep == App::UpdateStep::Idle)
|
||||
{
|
||||
std::string version, tag;
|
||||
if (app.updates.get(&version, nullptr, nullptr, nullptr, &tag) == UpdateCheck::State::Available)
|
||||
{
|
||||
updateNow = false;
|
||||
app.startUpdate(tag, version);
|
||||
}
|
||||
}
|
||||
app.pollGame();
|
||||
if (!selftestIso.empty())
|
||||
test.tick(app);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// The launcher's operating-system layer (platform_win.cpp): everything that needs <windows.h>, kept out of the
|
||||
// raylib / ImGui translation units (their names clash: CloseWindow, DrawText, Rectangle...). Strings are UTF-8.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
@@ -80,4 +81,14 @@ namespace plat
|
||||
// Blocking, with short timeouts: call it from a thread.
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes = 1 << 20);
|
||||
|
||||
// The same GET streamed into a file (a release's zip, through GitHub's redirect to its storage): bytes written so
|
||||
// far and the size the server announced (0 when it did not) into done and total, stopped when cancel turns true.
|
||||
// False with error set on a failure, a status other than 200 or a stop; the file is then removed.
|
||||
bool httpDownload(const std::string &url, const std::string &userAgent, const std::string &file, std::atomic<uint64_t> &done,
|
||||
std::atomic<uint64_t> &total, const std::atomic<bool> &cancel, std::string &error,
|
||||
uint64_t maxBytes = uint64_t(1) << 31);
|
||||
|
||||
// This program's own file (the launcher's exe, to start it again after an update).
|
||||
std::string exePath();
|
||||
}
|
||||
+168
-72
@@ -16,6 +16,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
namespace plat
|
||||
@@ -423,95 +424,190 @@ namespace plat
|
||||
reinterpret_cast<LPARAM>(&ctx));
|
||||
}
|
||||
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes)
|
||||
namespace
|
||||
{
|
||||
body.clear();
|
||||
status = 0;
|
||||
std::wstring wurl = widen(url);
|
||||
URL_COMPONENTS parts{};
|
||||
parts.dwStructSize = sizeof(parts);
|
||||
wchar_t host[256] = {}, pathBuf[2048] = {};
|
||||
parts.lpszHostName = host;
|
||||
parts.dwHostNameLength = 256;
|
||||
parts.lpszUrlPath = pathBuf;
|
||||
parts.dwUrlPathLength = 2048;
|
||||
if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &parts) ||
|
||||
(parts.nScheme != INTERNET_SCHEME_HTTPS && parts.nScheme != INTERNET_SCHEME_HTTP))
|
||||
{
|
||||
error = "bad URL";
|
||||
return false;
|
||||
}
|
||||
struct Handle
|
||||
struct Internet
|
||||
{
|
||||
HINTERNET h = nullptr;
|
||||
~Handle()
|
||||
~Internet()
|
||||
{
|
||||
if (h)
|
||||
WinHttpCloseHandle(h);
|
||||
}
|
||||
} session, connection, request;
|
||||
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY (Windows 8.1+): the proxy Windows itself uses.
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), 4 /* WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY */,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,
|
||||
WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
};
|
||||
|
||||
// A GET whose body goes to sink (false from it stops the read): the shared part of httpGet and httpDownload.
|
||||
// receiveMs: the longest wait for data (a large download through a slow line needs more than a version check).
|
||||
bool httpRequest(const std::string &url, const std::string &userAgent, const wchar_t *headers, int receiveMs,
|
||||
long &status, uint64_t &contentLength, std::string &error,
|
||||
const std::function<bool(const char *, size_t)> &sink)
|
||||
{
|
||||
status = 0;
|
||||
contentLength = 0;
|
||||
std::wstring wurl = widen(url);
|
||||
URL_COMPONENTS parts{};
|
||||
parts.dwStructSize = sizeof(parts);
|
||||
wchar_t host[256] = {}, pathBuf[2048] = {};
|
||||
parts.lpszHostName = host;
|
||||
parts.dwHostNameLength = 256;
|
||||
parts.lpszUrlPath = pathBuf;
|
||||
parts.dwUrlPathLength = 2048;
|
||||
if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &parts) ||
|
||||
(parts.nScheme != INTERNET_SCHEME_HTTPS && parts.nScheme != INTERNET_SCHEME_HTTP))
|
||||
{
|
||||
error = "bad URL";
|
||||
return false;
|
||||
}
|
||||
Internet session, connection, request;
|
||||
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY (Windows 8.1+): the proxy Windows itself uses.
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), 4 /* WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY */,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,
|
||||
WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, receiveMs);
|
||||
connection.h = WinHttpConnect(session.h, host, parts.nPort, 0);
|
||||
if (!connection.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
request.h = WinHttpOpenRequest(connection.h, L"GET", pathBuf, nullptr, WINHTTP_NO_REFERER,
|
||||
WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
|
||||
if (!request.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
// Redirects are followed (GitHub sends a release's files from its storage), never from HTTPS to HTTP.
|
||||
if (!WinHttpSendRequest(request.h, headers, static_cast<DWORD>(-1L), WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
|
||||
!WinHttpReceiveResponse(request.h, nullptr))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
DWORD code = 0, size = sizeof(code);
|
||||
WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
&code, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
status = static_cast<long>(code);
|
||||
wchar_t length[32] = {};
|
||||
DWORD lengthSize = sizeof(length);
|
||||
if (WinHttpQueryHeaders(request.h, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, length, &lengthSize,
|
||||
WINHTTP_NO_HEADER_INDEX))
|
||||
contentLength = std::wcstoull(length, nullptr, 10);
|
||||
std::string chunk;
|
||||
for (;;)
|
||||
{
|
||||
DWORD available = 0;
|
||||
if (!WinHttpQueryDataAvailable(request.h, &available))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (available == 0)
|
||||
break;
|
||||
chunk.resize(available);
|
||||
DWORD read = 0;
|
||||
if (!WinHttpReadData(request.h, chunk.data(), available, &read))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (!sink(chunk.data(), read))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes)
|
||||
{
|
||||
body.clear();
|
||||
uint64_t length = 0;
|
||||
return httpRequest(url, userAgent, L"Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n", 8000,
|
||||
status, length, error, [&](const char *data, size_t n)
|
||||
{
|
||||
body.append(data, n);
|
||||
if (body.size() <= maxBytes)
|
||||
return true;
|
||||
error = "response too large";
|
||||
return false; });
|
||||
}
|
||||
|
||||
bool httpDownload(const std::string &url, const std::string &userAgent, const std::string &file, std::atomic<uint64_t> &done,
|
||||
std::atomic<uint64_t> &total, const std::atomic<bool> &cancel, std::string &error, uint64_t maxBytes)
|
||||
{
|
||||
done = 0;
|
||||
total = 0;
|
||||
HANDLE out = CreateFileW(widen(file).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (out == INVALID_HANDLE_VALUE)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, 8000);
|
||||
connection.h = WinHttpConnect(session.h, host, parts.nPort, 0);
|
||||
if (!connection.h)
|
||||
long status = 0;
|
||||
uint64_t length = 0;
|
||||
bool sized = false;
|
||||
bool ok = httpRequest(url, userAgent, L"Accept: application/octet-stream\r\n", 30000, status, length, error,
|
||||
[&](const char *data, size_t n)
|
||||
{
|
||||
if (!sized)
|
||||
{
|
||||
sized = true;
|
||||
total = length;
|
||||
}
|
||||
if (status != 200)
|
||||
return false; // an error page: not written
|
||||
if (cancel.load())
|
||||
{
|
||||
error = "stopped";
|
||||
return false;
|
||||
}
|
||||
DWORD written = 0;
|
||||
if (!WriteFile(out, data, static_cast<DWORD>(n), &written, nullptr) || written != n)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
done += n;
|
||||
if (done.load() <= maxBytes)
|
||||
return true;
|
||||
error = "download too large";
|
||||
return false; });
|
||||
CloseHandle(out);
|
||||
if (ok && status != 200)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
ok = false;
|
||||
error = "HTTP " + std::to_string(status);
|
||||
}
|
||||
request.h = WinHttpOpenRequest(connection.h, L"GET", pathBuf, nullptr, WINHTTP_NO_REFERER,
|
||||
WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
|
||||
if (!request.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
const wchar_t *headers = L"Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n";
|
||||
if (!WinHttpSendRequest(request.h, headers, static_cast<DWORD>(-1L), WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
|
||||
!WinHttpReceiveResponse(request.h, nullptr))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
DWORD code = 0, size = sizeof(code);
|
||||
WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
&code, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
status = static_cast<long>(code);
|
||||
else if (!ok && error.empty())
|
||||
error = status != 200 ? "HTTP " + std::to_string(status) : "download failed";
|
||||
if (!ok)
|
||||
DeleteFileW(widen(file).c_str());
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::string exePath()
|
||||
{
|
||||
std::wstring buffer(MAX_PATH, L'\0');
|
||||
for (;;)
|
||||
{
|
||||
DWORD available = 0;
|
||||
if (!WinHttpQueryDataAvailable(request.h, &available))
|
||||
const DWORD n = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
|
||||
if (n == 0)
|
||||
return {};
|
||||
if (n < buffer.size())
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (available == 0)
|
||||
break;
|
||||
std::string chunk(available, '\0');
|
||||
DWORD read = 0;
|
||||
if (!WinHttpReadData(request.h, chunk.data(), available, &read))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
body.append(chunk.data(), read);
|
||||
if (body.size() > maxBytes)
|
||||
{
|
||||
error = "response too large";
|
||||
return false;
|
||||
buffer.resize(n);
|
||||
return narrow(buffer);
|
||||
}
|
||||
buffer.resize(buffer.size() * 2);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+84
-1
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
+30
-1
@@ -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,17 +3469,38 @@ 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();
|
||||
uint32_t found = 0;
|
||||
for (uint32_t y = 0; y < 4u; ++y)
|
||||
for (uint32_t x = 0; x < 4u; ++x)
|
||||
{
|
||||
uint32_t sample = 0;
|
||||
if (renderer.depthAt(view.originX + static_cast<float>((x0 + x) & 0x7ffu) + 0.5f,
|
||||
view.originY + static_cast<float>((y0 + y) & 0x7ffu) + 0.5f, sample))
|
||||
{
|
||||
z[y * 4u + x] = std::min<uint32_t>(sample, 0xffffffu);
|
||||
++found;
|
||||
}
|
||||
}
|
||||
// TMB_NATIVE_LOG_FLARES=1: every 300 blocks, how many of their samples the native depth had (not read yet: far).
|
||||
static const bool s_log = std::getenv("TMB_NATIVE_LOG_FLARES") != nullptr;
|
||||
static uint32_t s_blocks = 0, s_found = 0, s_near = 0;
|
||||
if (s_log)
|
||||
{
|
||||
s_found += found;
|
||||
for (uint32_t i = 0; i < 16u; ++i)
|
||||
s_near += z[i] != 0u && z[i] < 0xffffffu ? 1u : 0u;
|
||||
if (++s_blocks % 300u == 0u)
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:native] flare depth: %u blocks, %u of %u samples read, %u in front of the far plane\n", 300u,
|
||||
s_found, 300u * 16u, s_near);
|
||||
s_found = s_near = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""apply_update: installs a downloaded release over this one, for the launcher's Update button.
|
||||
|
||||
python -I tools/apply_update.py --zip <TMB_Recomp-x.y.z.zip> --sha256 <its .sha256 file> --version x.y.z
|
||||
--install <the release folder> [--keep-zip]
|
||||
|
||||
Checks the zip's SHA-256 against the release's .sha256, checks every name in it (one top folder TMB_Recomp/, no
|
||||
absolute or parent paths, nothing under build/, game/ or update/, the launcher and source/release.ini of the version
|
||||
asked for), extracts it whole to <install>/update/staging, and only then moves its files over the release folder.
|
||||
A file in use (the launcher that started this, the kit's Python running it) is renamed to <name>.tmb-old first, as
|
||||
Windows lets a running program's file be renamed but not replaced; those are listed in update/old_files.txt for the
|
||||
launcher to delete at its next start. The player's own folders (build/, game/) and saves (%APPDATA%) are never
|
||||
touched; tmb_build removes the source files a release no longer has (source/release_files.txt).
|
||||
|
||||
Prints one line per event for the launcher: "step <verify|extract|install|clean>", "progress <done> <total>" (bytes),
|
||||
"done <version>", or "error <message>" (exit code 1).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
TOP = 'TMB_Recomp/'
|
||||
LAUNCHER = 'TMB Launcher.exe'
|
||||
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def say(*parts):
|
||||
print(*parts, flush=True)
|
||||
|
||||
|
||||
def sha256_of(path):
|
||||
h = hashlib.sha256()
|
||||
total = os.path.getsize(path)
|
||||
done = 0
|
||||
with open(path, 'rb') as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b''):
|
||||
h.update(block)
|
||||
done += len(block)
|
||||
if done % (16 << 20) < (1 << 20):
|
||||
say('progress', done, total)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def expected_sha256(path):
|
||||
with open(path, 'r', encoding='utf-8', errors='replace') as f:
|
||||
token = f.read().split()
|
||||
if not token or len(token[0]) != 64 or any(c not in '0123456789abcdefABCDEF' for c in token[0]):
|
||||
raise UpdateError('the .sha256 file does not hold a SHA-256')
|
||||
return token[0].lower()
|
||||
|
||||
|
||||
def checked_names(zf, version):
|
||||
"""The zip's file entries as (entry, path under the top folder), after checking every name."""
|
||||
files = []
|
||||
for info in zf.infolist():
|
||||
name = info.filename
|
||||
if not name.startswith(TOP) or '\\' in name or ':' in name or name.startswith('/'):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
rel = name[len(TOP):]
|
||||
if any(part in ('..', '.') for part in rel.split('/')):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
if rel.startswith(PROTECTED) or rel.rstrip('/') in ('build', 'game', 'update'):
|
||||
raise UpdateError('the zip holds %r, a folder of the player\'s own' % name)
|
||||
if not name.endswith('/'):
|
||||
files.append((info, rel))
|
||||
rels = {rel for _info, rel in files}
|
||||
if LAUNCHER not in rels or 'source/release.ini' not in rels:
|
||||
raise UpdateError('this is not a TMB_Recomp release (no launcher or source/release.ini)')
|
||||
stamp = zf.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
|
||||
found = ''
|
||||
for line in stamp.splitlines():
|
||||
key, _, value = line.partition('=')
|
||||
if key.strip() == 'version':
|
||||
found = value.strip()
|
||||
if found != version:
|
||||
raise UpdateError('the zip is version %r, not %r' % (found, version))
|
||||
return files
|
||||
|
||||
|
||||
def remove_tree(path):
|
||||
def onerror(func, p, _exc):
|
||||
os.chmod(p, 0o666)
|
||||
func(p)
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, onerror=onerror)
|
||||
|
||||
|
||||
def replace(src, dst, old_files):
|
||||
"""Moves src over dst; a dst in use is renamed aside first (<dst>.tmb-old, or .tmb-old2... if that one is too)."""
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
return
|
||||
except PermissionError:
|
||||
pass
|
||||
for n in range(1, 100):
|
||||
aside = dst + ('.tmb-old' if n == 1 else '.tmb-old%d' % n)
|
||||
try:
|
||||
if os.path.exists(aside):
|
||||
os.remove(aside)
|
||||
os.rename(dst, aside)
|
||||
break
|
||||
except OSError:
|
||||
continue
|
||||
else:
|
||||
raise UpdateError('%s is in use and could not be set aside' % dst)
|
||||
old_files.append(aside)
|
||||
os.replace(src, dst)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--zip', required=True)
|
||||
ap.add_argument('--sha256', required=True)
|
||||
ap.add_argument('--version', required=True)
|
||||
ap.add_argument('--install', required=True)
|
||||
ap.add_argument('--keep-zip', action='store_true')
|
||||
args = ap.parse_args()
|
||||
install = os.path.abspath(args.install)
|
||||
work = os.path.join(install, 'update')
|
||||
staging = os.path.join(work, 'staging')
|
||||
|
||||
say('step verify')
|
||||
want = expected_sha256(args.sha256)
|
||||
got = sha256_of(args.zip)
|
||||
if got != want:
|
||||
raise UpdateError('the download is damaged (SHA-256 %s, expected %s): try again' % (got, want))
|
||||
|
||||
say('step extract')
|
||||
remove_tree(staging)
|
||||
with zipfile.ZipFile(args.zip) as zf:
|
||||
files = checked_names(zf, args.version)
|
||||
total = sum(info.file_size for info, _rel in files)
|
||||
if shutil.disk_usage(install).free < total + (256 << 20):
|
||||
raise UpdateError('not enough free space: %d MB needed' % ((total >> 20) + 256))
|
||||
done = 0
|
||||
for info, rel in files:
|
||||
target = os.path.join(staging, *rel.split('/'))
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with zf.open(info) as src, open(target, 'wb') as dst:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
done += info.file_size
|
||||
say('progress', done, total)
|
||||
|
||||
# Everything is extracted and checked: only moves on the same disk from here.
|
||||
say('step install')
|
||||
old_files = []
|
||||
for n, (_info, rel) in enumerate(files):
|
||||
replace(os.path.join(staging, *rel.split('/')), os.path.join(install, *rel.split('/')), old_files)
|
||||
if n % 200 == 0:
|
||||
say('progress', n, len(files))
|
||||
say('progress', len(files), len(files))
|
||||
if old_files:
|
||||
with open(os.path.join(work, 'old_files.txt'), 'a', encoding='utf-8') as f:
|
||||
f.write(''.join(path + '\n' for path in old_files))
|
||||
|
||||
say('step clean')
|
||||
remove_tree(staging)
|
||||
if not args.keep_zip:
|
||||
for path in (args.zip, args.sha256):
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
say('done', args.version)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (UpdateError, OSError, zipfile.BadZipFile) as e:
|
||||
say('error', e)
|
||||
sys.exit(1)
|
||||
+28
-4
@@ -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']:
|
||||
|
||||
@@ -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())
|
||||
@@ -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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user