76 Commits
Author SHA1 Message Date
boubou666 5864909a50 Merge pull request #134 from TheBozos/claude/release-0.8.1
Changelog: 0.8.1
2026-12-03 17:58:21 +01:00
Thomas MartinandClaude Opus 5.5 f7c06f2912 Changelog: 0.8.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-03 17:57:40 +01:00
boubou666 372a05850f Merge pull request #133 from TheBozos/claude/prison-retry-red
Loading bar: drawn only while shown (red flashes after a lost level's retry)
2026-12-03 17:12:37 +01:00
Thomas MartinandClaude Opus 5.5 4cdb0ec911 Loading bar: drawn only while shown (red flashes after a lost level's retry)
A reload inside a match (story's retry after a game over) leaves the bar's
vblank callback running once the load ends; the native override drew the last
load's full bar over every frame it ran in, flashing the screen red (reported
on Prison Passage, Linux v0.8.0; reproduced on Windows). The callback and
informProgressBar now draw only while the game shows the bar (gp - 0x3280),
as the game's own informProgressBar returns at once without it.

Testing switches to reach a lost level by script: TMB_KILL_PLAYER=<s> and
TMB_PLAYER_LIVES=<n>.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-03 17:11:27 +01:00
boubou666 0ca92a14ad Merge pull request #132 from TheBozos/claude/checklist-0.8.0
Release checklist: v0.8.0
2026-12-02 18:20:20 +01:00
boubou666 86179adf38 Merge pull request #131 from TheBozos/claude/no-pycache
Releases without Python's bytecode cache; the Linux launcher closes the game with one SIGTERM
2026-12-02 18:20:15 +01:00
Thomas MartinandClaude Opus 5.5 b066822107 Release checklist: v0.8.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 18:19:29 +01:00
Thomas MartinandClaude Opus 5.5 57cf629e50 Linux launcher: one SIGTERM per close request
The selftest asks the game to close every frame until it exits. SDL
turns the first SIGTERM into a quit and restores the default handlers
while shutting down, so a later one killed the game mid-shutdown (exit
143, a failed selftest). Windows' WM_CLOSE is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 18:14:08 +01:00
Thomas MartinandClaude Opus 5.5 9217669e76 Releases: no Python bytecode cache in source/
make_release imports tmb_build from the exported source, which leaves
source/tools/__pycache__ (with the build machine's paths) in every zip
and the Linux archive since earlier releases. The step that packs now
removes the caches, and the audits refuse one under source/.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 18:05:03 +01:00
boubou666 7aac19c03d Merge pull request #130 from TheBozos/claude/release-0.8.0
Changelog: 0.8.0
2026-12-02 17:22:38 +01:00
Thomas MartinandClaude Opus 5.5 435a0e092e Changelog: 0.8.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 17:21:43 +01:00
boubou666 8fcd3a5be8 Merge pull request #129 from TheBozos/claude/engine-crt-trig
BozoEngine 0.7.8: the same game on Linux as on Windows (sine and cosine, open point L1)
2026-12-02 16:56:52 +01:00
Thomas MartinandClaude Opus 5.5 5268eddd89 Changelog: BozoEngine 0.7.8
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 16:56:08 +01:00
Thomas MartinandClaude Opus 5.5 753c816cd8 BozoEngine 0.7.8
The Universal CRT's float sine and cosine on every platform (engine PR
#197, open point L1): a Linux build's game state equals Windows'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 16:49:22 +01:00
Thomas MartinandClaude Opus 5.5 15c439eb4f Snow and 2D rotations: the reference C runtime's sine and cosine on every platform
crtSinf and crtCosf (BozoEngine's bozo/libs/crt_math.h) instead of
std::sin and std::cos: the same bits as the Universal CRT that mingw-w64
calls, so a Linux build draws as the Windows one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 16:26:11 +01:00
boubou666 11694614a3 Merge pull request #128 from TheBozos/claude/linux
Linux build: the same launcher, a Linux release and RecompLauncher on Linux
2026-12-02 15:47:59 +01:00
Thomas MartinandClaude Opus 5.5 fa7fe981bc Docs: the Linux download in the README and the changelog
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:38:41 +01:00
Thomas MartinandClaude Opus 5.5 6da09e8712 Enhanced textures on Linux: Real-ESRGAN's Linux build in the Linux kit
make_build_kit.py --linux keeps realesrgan-ncnn-vulkan (its v0.2.5.0
ubuntu build, SHA-256 pinned) and the x4plus model; the Linux archive
carries it and its licences, the audit allows it as the archive's second
program, and the launcher looks for it without .exe on Linux.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:35:52 +01:00
Thomas MartinandClaude Opus 5.5 0e66d19c58 RecompLauncher on Linux: kit/python3 for prepare, game/tmb for start
The Linux archive's kit/python3 runs the system's python3, after
kit/python/python.exe in prepare's program list; start tries game/tmb
after game/tmb.exe. system names Linux's OpenGL 3.3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:27:36 +01:00
Thomas MartinandClaude Opus 5.5 1473dd3e0c Tests: the Linux archive's audit and reproducibility, its update, the prerequisites message and the Linux kit
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:25:05 +01:00
Thomas MartinandClaude Opus 5.5 ecb61b81f9 Release workflow: a Linux job on Ubuntu 22.04 whose archive the draft carries
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:24:47 +01:00
Thomas MartinandClaude Opus 5.5 2e4f88fcab make_release.py --linux: the Linux player's .tar.gz
TMB_Recomp-<version>-linux.tar.gz (folder TMB_Recomp_Bozo): the same
source/ as the zips, a kit of the libraries' sources only (the compiler,
Python and FFmpeg are the system's), tmb-launcher built for Linux, the
licences, a README and recomplauncher.json. Reproducible (sorted entries,
the commit's time, no owner), audited like the zips (verify_tar), in the
release notes and attached to the draft when present.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:24:05 +01:00
Thomas MartinandClaude Opus 5.5 b98492db76 Updater: install the Linux release's .tar.gz
apply_update.py reads a release's zip or .tar.gz the same way (any
compression; links and devices refused), checks for the platform's
launcher, and keeps the executable bits it carries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:22:54 +01:00
Thomas MartinandClaude Opus 5.5 1754616537 Launcher and build on Linux (from SoulCaliburIII_Recomp's Linux port)
The launcher's platform layer for Linux (platform_linux.cpp: XDG user
folder, the desktop portal or zenity for the disc, xdg-open, the font
embedded, a process group per build, libcurl loaded for the update
check), tmb-launcher built with libstdc++ and libgcc linked in. The game
exe, release package and Python are chosen per platform.

tmb_build.py on Linux uses a kit of the libraries' sources only, and
names the distribution's packages when a prerequisite is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 15:22:33 +01:00
Thomas MartinandClaude Opus 5.5 fb17ea2508 Engine fetch: the unpacked release's files dated now
cmake/bozo_engine_fetch.cmake unpacked the pinned BozoEngine release with the
archive's own file dates, older than objects already built. After a pin bump
Ninja then kept port objects compiled against the previous release's headers
(found in Shinobido_WOTN_Recomp, 0.7.0 -> 0.7.3: shino_gs_state.cpp and
shino_render.cpp stayed on the old renderer.h, the picture lost its objects and
HUD while the game state was identical). Every unpacked file is now touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 12:31:23 +01:00
boubou666 c00c238331 Merge pull request #127 from TheBozos/claude/checklist-0.7.3
Release checklist: v0.7.3
2026-12-01 01:56:22 +01:00
Thomas MartinandClaude Opus 5.5 14027a5026 Release checklist: v0.7.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:55:27 +01:00
boubou666 2e37b81b0d Merge pull request #126 from TheBozos/claude/release-0.7.3
Changelog: 0.7.3
2026-12-01 01:21:18 +01:00
Thomas MartinandClaude Opus 5.5 13a63bcafd Changelog: 0.7.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:20:28 +01:00
boubou666 3f6623f47e Merge pull request #125 from TheBozos/claude/recomplauncher
Support RecompLauncher: ship recomplauncher.json
2026-12-01 01:19:01 +01:00
Thomas MartinandClaude Opus 5.5 f0806c5ef0 Support RecompLauncher: ship recomplauncher.json
Releases carry RecompLauncher's manifest at the zip's top: the USA disc
check (Redump's dump), prepare with the release's own build (--progress-lines,
--disc optional for keeps_copy), start with PS2X_USER_DIR in {data}, the
video settings and the memory cards. As in DC_Recomp#67.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:12:45 +01:00
boubou666 6db6a16b0d Merge pull request #124 from TheBozos/claude/checklist-0.7.2
Release checklist: v0.7.2
2026-11-30 22:37:16 +01:00
Thomas MartinandClaude Opus 5.5 7ccc02b050 Release checklist: v0.7.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 22:36:22 +01:00
boubou666 8d808aaf2a Merge pull request #123 from TheBozos/claude/release-0.7.2
Changelog: 0.7.2
2026-11-30 19:49:04 +01:00
Thomas MartinandClaude Opus 5.5 06d323c49d Changelog: 0.7.2
BozoEngine from its releases (#121) and BozoEngine 0.6.0 (#122).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:48:14 +01:00
boubou666 80ba27ab07 Merge pull request #122 from TheBozos/claude/engine-0.6.0
BozoEngine 0.6.0
2026-11-30 19:33:44 +01:00
Thomas MartinandClaude Opus 5.5 254f994459 BozoEngine 0.6.0
The pin moves from 0.4.0 to 0.6.0: Amplitude's sound held to the host's time without clicks (#164), the render scale
over 1 averaged (#168), SPU2 output IRQs (#165), the movie library's work-area entries (#161), the disc stream (#167),
ReferSemaStatus (#166), sceSifGetOtherData (#170) and other ports' opt-in answers (#150, #160, #169).

Checked against v0.7.1 (0.4.0), same kit: the 1P route (9,500 frames, with sound) and the 4P route (8,500) give
identical records on every field and frame, and the 1P WAV is byte-identical; the 11 native test suites pass; a hidden
window run of the 1P route at render scale 2 plays through with fewer dropped sound frames (1,463 vs 3,238) and
underruns (9 vs 11).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:32:31 +01:00
boubou666 f620ab163b Merge pull request #121 from TheBozos/claude/engine-release-pin
Build on BozoEngine's releases instead of the submodule
2026-11-30 19:11:13 +01:00
Thomas MartinandClaude Opus 5.5 ce069120c1 Build on BozoEngine's releases instead of the submodule
cmake/bozo_engine.json pins a BozoEngine release by version and SHA-256 (0.4.0, the same source as the b29bc39
submodule pin minus reference/), and cmake/bozo_engine_fetch.cmake downloads, checks and unpacks it into
BozoEngine/ (ignored) when its .release stamp does not match: the scheme SoulCaliburIII_Recomp uses. cmake/bozo.cmake
and launcher/CMakeLists.txt include it unless given another tree; tmb_build runs it in a git checkout; make_release
fetches it into the release's source/BozoEngine, so a player's build stays offline, and release.ini stamps
engine_version. The release workflow fetches it after checkout (the kit reads the engine's library pins). The
submodule and .gitmodules are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:00:25 +01:00
boubou666 b84fefaf95 Merge pull request #120 from TheBozos/claude/release-0.7.1-checklist
Release checklist: v0.7.1's checks
2026-11-30 18:33:02 +01:00
Thomas MartinandClaude Opus 5.5 159d4a5de3 Release checklist: v0.7.1's checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 18:32:06 +01:00
boubou666 979544ce35 Merge pull request #119 from TheBozos/claude/release-0.7.1
Changelog: 0.7.1
2026-11-30 17:48:08 +01:00
Thomas MartinandClaude Opus 5.5 7f3a59ce5b Changelog: 0.7.1
The release zip file-time fix (#118). Adds the missing 0.7.0 and 0.7.1 compare links.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 17:47:02 +01:00
boubou666 d1e53a845c Merge pull request #118 from TheBozos/claude/settle-source-times
tmb_build: settle source and kit times before configuring
2026-11-30 17:45:53 +01:00
Thomas MartinandClaude Opus 5.5 8dbb7b0c23 tmb_build: settle source and kit times before configuring
A release zip dates every file at its commit's time, which an unzip reads as local time: west of UTC the files are
in the future and ninja loops ("manifest 'build.ninja' still dirty after 100 tries"), and an update unzipped over a
newer build can leave a changed file uncompiled. Ported from DC_Recomp's settle_source_times (DC_Recomp#60, 0.5.2):
the kit's future times are clamped to now, and the release source and kit/deps keep a size+time+SHA-1 record in
<out>/source_times.json so changed or new files are dated now and unchanged ones keep their time. A git checkout is
left alone. With the tests from DC's suite.

Checked end to end: the v0.7.0 player zip dated +3 h loops as shipped and passes Prepare's tools step fixed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 17:21:09 +01:00
boubou666 09e8c8b45f Merge pull request #117 from TheBozos/claude/release-0.7.0-checklist
Release checklist: v0.7.0's checks
2026-11-27 10:47:10 +01:00
Thomas MartinandClaude Opus 5.5 6e27203fcc Release checklist: v0.7.0's checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 10:46:18 +01:00
boubou666 894a16a651 Merge pull request #116 from TheBozos/claude/release-0.7.0
Changelog: 0.7.0
2026-11-27 10:22:16 +01:00
Thomas MartinandClaude Opus 5.5 9cea4513b1 Changelog: 0.7.0
Save states (#106), PC SETTINGS in the Options screen and the pause menu,
QUIT GAME, widescreen with its HUD and dialogs, and the quit-music fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 10:10:25 +01:00
boubou666 38ff9f8ea3 Merge pull request #115 from TheBozos/claude/engine-snd-unload
Quitting a match no longer leaves its music over the menus
2026-11-27 02:56:35 +01:00
Thomas MartinandClaude Opus 5.5 d003ced242 Quitting a match no longer leaves its music over the menus (BozoEngine b29bc39)
BozoEngine at master b29bc39: #159, the 989SND driver stops a bank's
sounds still playing when the game unloads it (quitting a match from the
pause unloads the level's banks without a StopAllSounds, and the match's
music, played from its bank, went on over the menus), with the other
ports' merges since e2dff55 (#155-#158).

Checked: a headless quit from the pause, sound recorded: after the quit
the mean level goes from 4207 (match music over the menu's) to 2136 (the
menu's own); the 11 native suites pass; the 1P and 4P replays match main on
every recorded field, RAM image and sound; the pinned boot and match1p
checks match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:55:32 +01:00
boubou666 6043791a00 Merge pull request #114 from TheBozos/claude/widescreen-hud
Widescreen: dialogs centred at 4:3, HUD at the 16:9 edges
2026-11-27 02:17:44 +01:00
Thomas MartinandClaude Opus 5.5 dbb8c73b23 Widescreen: the HUD at the 16:9 edges
The match HUD's two clusters are hier meshes on coordinate systems the game
hangs in front of the camera each frame (Hud::updateHUDPosition 0x13CC90:
the view's matrix, its translation plus the cluster's camera-space offset,
Hud + 0x810 the radar's, + 0x820 the weapon's; x right, y the depth). Seen
through the same focal length they kept their 4:3 places. With the views
wide, each cluster's x goes out by the width gained on its side,
(w - 640) / 2 * y / D (D the views' focal length, viewFovH), for the call,
and is put back after it, so a narrowed view finds the game's values. The
radar's centre and blips follow (computed in the same call); the markers
and bars over the cars are the world's.

The game reaches Hud::updateHUDPosition and Hud::Update by a jump from
TheGame::HudUpdateHUDPosition (0x15BD20) and TheGame::HudUpdate
(0x15BD40), so those are the ones overridden (a jump does not reach an
override). The HUD text Hud::Update draws from a 640 layout through
fontSpritePrintXY / CenteredXY (the ammo count and KILLS on the right,
DEMO in the middle) goes with its cluster: x past 400 by the width gained,
past 240 by half of it.

Checked: the 11 native suites pass; the 1P and 4P replays match main on
every recorded field, RAM image and sound; the pinned boot and match1p
checks match. Hidden window runs with widescreen on: the radar, name and
health at the top left, the weapon panel, its ammo count, energy and lives
at the bottom right, in the single view and the rear-view layout; the
markers over the cars on them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:16:41 +01:00
Thomas MartinandClaude Opus 5.5 de1f627801 Widescreen: the dialogs over a match shown 4:3 and centred
The dialogs over a match (displayDialog 0x163500: the pause, the results,
won and lost) lay their text and darkening out for a 640-wide view (centred
at x 320 from the view's left edge, the darkening band 640 wide). With one
player the pause kept the match's widened view, so its menu sat left of
centre in a 16:9 picture.

displayDialog's override now narrows every widened viewport back to 640 and
rebuilds the views (viewTweakSetFov) before the game's dialog; the picture
is 4:3 while it shows, and the match's next frame end widens the views
again. Every widened viewport is remembered, not only those shown: the
pause's full-screen view (viewport 0x4DEF80) is handed out again by
viewCreate while still 853 wide from earlier in the match.

Checked in hidden window runs with widescreen on: the 1P pause menu and its
PC SETTINGS pages centred at 4:3, the match back at 16:9 after Start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:40:04 +01:00
boubou666 ad371920d7 Merge pull request #113 from TheBozos/claude/pause-pc-settings
PC SETTINGS in the pause menu
2026-11-27 01:16:49 +01:00
Thomas MartinandClaude Opus 5.5 5531425daf PC SETTINGS in the pause menu
The in-match pause (displayDialog types 0 and 16, its page
pauseLevelOverlay 0x166960 in the dialog's own loop) gets a PC SETTINGS line
under RESUME, QUIT, SET VIBRATION and ADJUST REAR VIEW (under SET
VIBRATION with several players), opening the same pages (Video, Cheats,
Save states, QUIT GAME) drawn in the pause's style:
- getCurrentMenuSelection (0x167AF8), for the pause's call (return
  0x166AE4): the count one more, so the cursor reaches the new line (the
  wrap uses the count itself).
- checkInputForPauseExit (0x167670, return 0x166D64): Cross on that line
  opens the pages and the pause stays (returns 0), instead of the game's
  hidden TWEAK action at that index closing it.
- pauseLevelOverlay: after the game's menu, the line through setMenuFont
  (highlighted as the game's lines) and fontSpritePrintCenteredXY; while
  the pages are open, the pages instead (returns 0, the dialog goes on).
  Their input is the pausing player's pad (inputGetPlayerPad of
  gPlayerThatPaused, inputGetInput in uiGetInput's order), their sounds the
  pause's (playRTShellSound 0x2A / 0x2B / 0x2C), their fonts the pause's
  (setTitleFont; setMenuFont's sizes 0x12 / 0x10 and colours). A new pause
  starts on the game's menu.
- tmb_2d.cpp: displayDialog's darkening is left out under the pages.

runPage serves both: the Options screen's input (uiGetInput's flags),
sounds and sub-pixel fonts, or the pause's.

Checked: the 11 native suites pass; the 1P and 4P replays match main
89d5306 on every recorded field, RAM image and sound; the pinned boot and
match1p checks match. A hidden window run in a 1P match: paused, Up onto
PC SETTINGS, Cross to the pages, Video and Cheats pages, Triangle back to
the pause menu, Start resumed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:12:43 +01:00
boubou666 56e2f2e932 Merge pull request #112 from TheBozos/claude/quit-and-widescreen
Widescreen in 1P/2P matches, and QUIT GAME in PC SETTINGS
2026-11-27 00:50:46 +01:00
Thomas MartinandClaude Opus 5.5 3b05396300 Widescreen in 1P/2P matches, and QUIT GAME in PC SETTINGS
Widescreen (runtime/tmb_widescreen.cpp; off by default: Video's
Widescreen in F2 or PC SETTINGS, video.ini `widescreen`, PS2X_WIDESCREEN):
at each match frame's end, when every view is the screen's full width (one
player, or two one above the other), each view's width goes from 640 to
853 about the same centre and the game's own viewTweakSetFov (0x1FDEA0)
rebuilds its frustum planes and projection from it, on a copy of the
context. The game then culls, projects and clips a scene 4/3 as wide with
the same focal length: more at the sides, nothing stretched. The 3D screen
(tmb_native.cpp) and the 2D overlay follow the views' width, so the HUD
keeps its shape; the window shows 16:9 (BozoEngine's setPictureAspect)
while a view is wide. The menus, the pause dialog and the next level make
their views again at 640 (viewCreate), so they stay 4:3; three- and
four-player splits stay 4:3; the loading bar and movie pictures are drawn
centred.

QUIT GAME at the bottom of PC SETTINGS' first page: Cross shows "PRESS X
AGAIN", a second Cross ends the game (the host's stop; the window closes),
Back or a move disarms it.

BozoEngine at master e2dff55 (#154: video::Settings::widescreen,
offerWidescreen, setPictureAspect; #153 libmpeg's demux in runs).

Checked: the 11 native suites pass; the 1P (9,500) and 4P (8,500) replays
match main 89d5306 on every recorded field, RAM image and sound; the
pinned boot and match1p checks match. Hidden window runs with widescreen
on: 1P matches at 16:9 (cars, rain and target markers to the edges, the
radar round), the menus 4:3, a 4P split 4:3, the pause screen as without
it; QUIT GAME ended the game at the second Cross.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:36:29 +01:00
boubou666 2a7eff7a3a Merge pull request #111 from TheBozos/claude/pc-settings-menu
PC SETTINGS in the game's Options screen: video, cheats and save states with the pad
2026-11-26 21:24:04 +01:00
Thomas MartinandClaude Opus 5.5 de7bfb32aa PC SETTINGS in the game's Options screen: video, cheats and save states with the pad
A ninth line under the game's Options (after SAVE SETTINGS TO MEMORY CARD)
opens pages drawn with the game's own font and steered with the pad:
- Video: display mode, resolution, render scale, frame rate, anti-aliasing,
  texture smoothing, upscaling and its filter, texture pack, pause in
  background, fast forward; APPLY AND SAVE posts them to the window and
  writes video.ini (bozo::app::video::post).
- Cheats: unlock everything, infinite health / ammo / energy (off, player 1,
  all players), no AI, weak enemies; at once (tmb::cheats::values /
  setValues, the F2 tab's switches).
- Save states: the slot, LOAD, SAVE (the host's requests, the slot's
  picture through BozoEngine's captureStatePicture, as F5 / F7).
Triangle or Circle goes back; the controls stay in F2.

runtime/tmb_menu.cpp, from the game's code (uiOptions 0x1911F0):
- uiGetInput's override (for the Options page's call, 0x19128C) lets the
  cursor (options_main_line) reach 8: every other use of the cursor is a
  compare, so 8 selects none of the game's lines. Cross there opens the
  pages instead of the game's accept-and-leave.
- uiOptions' override draws the line after the game's page and, while the
  pages are open, draws them instead (the 3D shell stays the game's, its
  sliders hidden by blankSliders as the controls page does).
- The game's font, sound and input functions run on a copy of the context
  (BozoEngine kernel.md section 3b): guest code there never leaves the
  override. Calling them on the thread's context let fontSpritePrint leave
  at a checkpoint and return later into uiMain on the pages' stack.
- Only where the graphics are native (every free run); a save state's load
  closes the pages.

BozoEngine at master 5d34d41 (#151's captureStatePicture, with the other
ports' merges since f93b5af).

Checked: the 11 native suites pass; the 1P (9,500) and 4P (8,500) replays
match main 89d5306 on every recorded field, RAM image and sound, before and
after the engine move; the pinned boot and match1p checks match (match1p
16000/16000 frames). Hidden window runs: the line, Up from DIFFICULTY onto
it and Down off it, each page, render scale applied and saved, slot 0
saved (state and picture) and loaded, and 8,100 frames on the Video page
without a fault.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:22:56 +01:00
boubou666 89d530697c Merge pull request #110 from TheBozos/claude/no-lives-left-wording
Wording: the "No lives left" screen, not an attract demo; BozoEngine at f93b5af
2026-11-24 11:31:46 +01:00
Thomas MartinandClaude Opus 5.5 28159632e2 BozoEngine at master f93b5af (#137 merged: the readbacks' wording)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:24:43 +01:00
Thomas MartinandClaude Opus 5.5 c821465d6a Wording: the checker's flares note names the "No lives left" screen, not an attract demo
Frames 13736 on in match1p are the game-over screen after the 1P match
(tmb-check's hidden captures at 13740 and 15900). Comment only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:21:39 +01:00
boubou666 a0d9386896 Merge pull request #109 from TheBozos/claude/match1p-check
Pinned match1p passes again: the checker's particles by game frame
2026-11-24 11:16:52 +01:00
Thomas MartinandClaude Opus 5.5 0aedf924ed BozoEngine at master 822e8ef (#136 merged; same tree as 0b961a4)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:15:21 +01:00
Thomas MartinandClaude Opus 5.5 e1797b1315 Pinned match1p passes again: the checker's particles by game frame
tmb-check's particleDraw chose TMB's path or the game's by host time
(effectsInStream: a match or menu frame within 0.1 s), and the lens flares'
native path no longer needed a match (889b086). The reference (TMB a7869c0,
paced at 60 fps) drew all 13,716 particleDraws itself from frame 5593 and
left the flares to the game from 13736, six frames after the last match
frame (13729), with the attract demo's GS readbacks. So the check stopped at
5593, 13731 or 13737 by the host's speed, and at 13736 on the readback.

Without native graphics (only the checker; every free run has them) the
same choices by game frame: particles within 6 frames of a match or menu
frame's end, flares natively within 6 of a match frame's (checkedEffects,
checkedFlares). Free runs are unchanged. BozoEngine at 0b961a4 answers the
readback as the reference's stub in its log host.

match1p --pinned: 16000/16000 frames, 74,615,923 records, 0 divergences;
draws 15999/16000 (the log's last frame, as before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:04:14 +01:00
boubou666 ccd52e8401 Merge pull request #108 from TheBozos/claude/pinned-boot-hidden
Pinned boot check passes again (BozoEngine 5b830b6); hidden pinned captures
2026-11-24 00:21:57 +01:00
Thomas MartinandClaude Opus 5.5 ae2ac42953 BozoEngine at master 5b830b6: the pinned boot check passes again
BozoEngine #132: sceGsResetGraph's display mode kept in the library. tmb-check on boot.clg diverged at frame 4
(sceGsSetDefDispEnv read the mode back from scratchpad 0x100, which the game reuses); it now matches all 3000 frames
and 4,650,558 records, and runs hidden with its captures (tmb-check --window --hidden). The game's display
environments now hold the reference's SMODE2 / DISPLAY; sound, calls, draws and threads unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:20:49 +01:00
boubou666 153336ae0c Merge pull request #107 from TheBozos/claude/hidden-window-captures
Hidden, muted test runs on BozoEngine master; native suites on the engine's float shortcuts
2026-11-23 23:15:18 +01:00
Thomas MartinandClaude Opus 5.5 b1aa812ed7 BozoEngine at master e15775a (#131 merged; same tree as 7521b3e)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:13:46 +01:00
Thomas MartinandClaude Opus 5.5 cd5262a7a0 Hidden test runs: tmb-check --window --hidden; the native suites on engine master's float shortcuts
- BozoEngine at claude/ps2f-mul-min-normal (7521b3e, BozoEngine #131 on master 3222624): hidden windows, and the
  fix for products that rounded up to the smallest normals in ps2f's and VU0's host shortcuts.
- tmb-check --window --hidden: the pinned pixel captures without showing the window (the offscreen picture).
- README: --hidden, --capture-scene; --no-sound keeps --wav.
- Native suites (tests/host_control.h): engine master's ps2f and VU0 shortcuts use the host's arithmetic, exact only
  when the host rounds to nearest (the game's word) and leaving SSE's sticky status flags. The original now runs at
  the caller's word rounding to nearest, native code still at the varied caller word (generated callers on both sides
  at nearest), and the control word is compared without the status flags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:02:21 +01:00
Thomas MartinandClaude Opus 5.5 4eddae4fa3 WIP: hidden-window test runs (--hidden, --capture-scene) on BozoEngine master 3222624
Not qualified yet: the bumped engine's 1P/4P headless replays and a 4P save-state
round trip match; the hidden window routes ran (the 4P one paced slowly, to recheck).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 20:26:03 +01:00
boubou666 fb17656603 Merge pull request #106 from TheBozos/claude/save-states
Save states: F5/F7 slots, --save-state / --load-state, 989SND saved
2026-11-18 19:59:32 +01:00
Thomas MartinandClaude Opus 5.5 a67b0cd9fe Save states: TMB's section, command-line options and window slots
TMB adds its own part to BozoEngine's save states (runtime/tmb_state.cpp):
- the overrides' frame pacing (the parity written to the game's memory, the
  field carry and clock debt) and movie sound queue;
- the native hierarchy's retained scene records;
- the NGP files the game bound, saved as bound, and the DMA marks' counter;
- what the game told the texture hooks once (files read per address, the
  level's lists, VRAM placements), with pack records as (file, index);
- the particles' stripe and arc records, and the cheats' opened lock words.

Decoded textures, the skid marks' object and the 2D pictures are dropped on a
load.

Options: --save-state FILE --save-state-at N, --load-state FILE
[--load-state-at N], and tmb-headless --dump-ram FILE. In the window: F5 save,
F7 load, F6 / Shift+F6 slots, and the F2 Save states tab.

BozoEngine moves to the save-state work with the 989SND driver saved
(unloaded banks kept: their headers were read after being freed).

Checked headless, for a menu state and 1P/4P match states loaded in a new
process and mid-run: the end-of-route EE RAM and the sound after the save are
identical to the run that never stopped. The default 1P/4P replays match the
previous build on every recorded field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 19:58:16 +01:00
boubou666 a58a702260 Merge pull request #105 from TheBozos/claude/release-0.6.0-checklist
Record the 0.6.0 release verification in the checklist
2026-11-11 13:22:25 +01:00
Thomas MartinandClaude Opus 5.5 8d971a3f3d Record the 0.6.0 release verification in the checklist
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:21:06 +01:00
53 changed files with 8607 additions and 4408 deletions

No files matched your search

+2
View File
@@ -13,6 +13,8 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.14'
- name: The BozoEngine release cmake/bozo_engine.json pins (the RecompLauncher settings check reads it)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Release, migration and timing checks
run: python -m unittest discover -s tests -v
- name: Python syntax
+107 -4
View File
@@ -3,8 +3,10 @@
#
# git tag v0.1.0 && git push origin v0.1.0 (or Actions > Release > Run workflow, with the tag)
#
# On a version tag it makes the build kit from the pinned MSYS2 packages (tools/build_kit_packages.json), the release
# zips TMB_Recomp-<version>-bozo.zip (folder TMB_Recomp_Bozo) and TMB_Recomp-<version>.zip (folder TMB_Recomp for
# On a version tag the linux job makes TMB_Recomp-<version>-linux.tar.gz (folder TMB_Recomp_Bozo: the Linux launcher,
# the code, the libraries' sources; make_release.py --linux) on the oldest supported Ubuntu, so the launcher runs on
# older glibc. Then the build job makes the build kit from the pinned MSYS2 packages (tools/build_kit_packages.json), the
# release zips TMB_Recomp-<version>-bozo.zip (folder TMB_Recomp_Bozo) and TMB_Recomp-<version>.zip (folder TMB_Recomp for
# the previous updater). Both carry BozoEngine. It adds hashes and corresponding sources, checks without game data, and creates a DRAFT
# GitHub release with CHANGELOG.md's section for the version as its body. Nothing is ever published by this workflow:
# the owner runs docs/RELEASE_CHECKLIST.md on a clean PC, then publishes the draft by hand.
@@ -46,8 +48,99 @@ concurrency:
cancel-in-progress: false
jobs:
linux:
if: github.event_name != 'release'
runs-on: ubuntu-22.04
timeout-minutes: 60
env:
TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || (github.event_name == 'push' && github.ref_name || '') }}
TEST_VERSION: ${{ inputs.version }}
steps:
- name: Version from the tag (or a test build's)
run: |
set -eu
if [ -n "$TAG" ]; then
echo "VERSION=${TAG#v}" >> "$GITHUB_ENV"
echo "TEST_BUILD=" >> "$GITHUB_ENV"
else
echo "VERSION=${TEST_VERSION:-0.0.0-test.$GITHUB_RUN_NUMBER}" >> "$GITHUB_ENV"
echo "TEST_BUILD=1" >> "$GITHUB_ENV"
fi
echo "WORK=$RUNNER_TEMP/tmb" >> "$GITHUB_ENV"
- name: Check out the tag or the branch
uses: actions/checkout@v4
with:
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
fetch-depth: 0
persist-credentials: false
- name: Python
uses: actions/setup-python@v5
with:
python-version: '3.14'
- name: The launcher's build tools and SDL3's video and audio development files
run: |
sudo apt-get update -q
sudo apt-get install -y -q cmake ninja-build g++ pkg-config libx11-dev libxext-dev \
libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev libwayland-dev \
wayland-protocols libdecor-0-dev libegl-dev libgl-dev libgles-dev libpipewire-0.3-dev libpulse-dev \
libasound2-dev libudev-dev libdbus-1-dev libibus-1.0-dev
- name: Cache the downloads (SDL3, ImGui, the font)
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/tmb/downloads
key: tmb-linux-downloads-${{ hashFiles('tools/make_build_kit.py', 'tools/make_release.py', 'cmake/bozo_engine.json') }}
restore-keys: tmb-linux-downloads-
- name: Make the Linux release (.tar.gz, .sha256)
run: |
set -eu
if [ -n "$TEST_BUILD" ]; then extra="--allow-missing-changelog"; else extra=""; fi
python tools/make_release.py --linux --version "$VERSION" --out "$WORK/release" \
--downloads "$WORK/downloads" $extra
- name: Smoke checks (no game data anywhere)
run: |
set -eu
rel="$WORK/release"
name="TMB_Recomp-$VERSION-linux.tar.gz"
python tools/make_release.py --verify-zip "$rel/$name"
(cd "$rel" && sha256sum -c "$name.sha256")
t="$WORK/smoke/Jérôme Games"
rm -rf "$t" && mkdir -p "$t/user"
tar xzf "$rel/$name" -C "$t"
app="$t/TMB_Recomp_Bozo"
head -c 1048576 /dev/zero > "$t/not_a_disc.iso"
if python3 -I -X utf8 "$app/source/tools/tmb_build.py" --check --disc "$t/not_a_disc.iso" > "$t/check.txt" 2>&1; then
cat "$t/check.txt"; echo "::error::tmb_build --check accepted a file of zeros"; exit 1
fi
cat "$t/check.txt"
grep -q "is not an ISO9660 disc image" "$t/check.txt"
"$app/tmb-launcher" --version
if ! PS2X_USER_DIR="$t/user" "$app/tmb-launcher" --self-check "$t/not_a_disc.iso" --report "$t/self-check.txt"; then
cat "$t/self-check.txt"; echo "::error::the launcher's self-check failed"; exit 1
fi
cat "$t/self-check.txt"
grep -q "^version $VERSION$" "$t/self-check.txt"
readelf -d "$app/tmb-launcher" | grep NEEDED
- name: Keep the archive (the run's artifact; the build job attaches it to the draft)
uses: actions/upload-artifact@v4
with:
name: TMB_Recomp-${{ env.VERSION }}-linux
path: |
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz.sha256
if-no-files-found: error
retention-days: 14
compression-level: 0
build:
if: github.event_name != 'release'
needs: linux
runs-on: windows-latest
timeout-minutes: 150
permissions:
@@ -80,13 +173,15 @@ jobs:
fi
echo "WORK=$(cygpath -m "$RUNNER_TEMP")/tmb" >> "$GITHUB_ENV"
- name: Check out the tag or the branch (and the BozoEngine submodule at its recorded commit)
- name: Check out the tag or the branch
uses: actions/checkout@v4
with:
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
submodules: true
persist-credentials: false
- name: The BozoEngine release cmake/bozo_engine.json pins (SHA-256 checked; the kit reads its library pins)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Python
uses: actions/setup-python@v5
with:
@@ -138,6 +233,12 @@ jobs:
python tools/make_build_kit.py --out "$WORK/kit" --msys "$MSYS2_ROOT" --downloads "$WORK/downloads" \
--work "$WORK/kit-work" $steps --only manifest
- name: The Linux release (the linux job's), so the notes and the draft carry it
uses: actions/download-artifact@v4
with:
name: TMB_Recomp-${{ env.VERSION }}-linux
path: ${{ runner.temp }}/tmb/release
- name: Make the release (zip, .sha256, sources zip, notes from CHANGELOG.md)
env:
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
@@ -193,6 +294,8 @@ jobs:
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}.zip.sha256
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo-sources.zip
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo-sources.zip.sha256
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz.sha256
${{ runner.temp }}/tmb/release/RELEASE_NOTES.md
if-no-files-found: error
retention-days: 14
+4
View File
@@ -17,6 +17,10 @@ SLUS_*
*.irx
*.IMG
# The BozoEngine release cmake/bozo_engine.json pins (cmake/bozo_engine_fetch.cmake)
/BozoEngine/
/.BozoEngine-unpack/
# Local build trees
build/
out/
-3
View File
@@ -1,3 +0,0 @@
[submodule "BozoEngine"]
path = BozoEngine
url = https://github.com/TheBozos/BozoEngine.git
Submodule BozoEngine deleted from a36a4d23f2.
+113 -1
View File
@@ -7,6 +7,112 @@ under "Unreleased" as they land, then move them under the new version's heading
## [Unreleased]
## [0.8.1] - 2026-12-03
### Fixed
- **Red flashes after retrying a lost level** (reported on Prison Passage in story mode). The level's reload left the
loading bar's vblank callback running, and the native 2D drew the last load's full bar over the match's frames. It is
now drawn only while the game shows it (as the game's own `informProgressBar` does too).
- Linux: closing the game from the launcher sends it one stop signal, not one a frame (a second one could kill the game
while it was closing).
- The packages no longer carry Python's bytecode cache (`source/tools/__pycache__`), which held the build machine's
paths.
### Added
- Testing switches: `TMB_KILL_PLAYER=<s>` (player 1's car takes a fatal hit every `<s>` seconds) and
`TMB_PLAYER_LIVES=<n>` (player 1's story lives kept at most `n`), to reach a lost level and its retry in a script.
## [0.8.0] - 2026-12-02
### Added
- **A Linux download**, `TMB_Recomp-<version>-linux.tar.gz`: the same launcher for Linux (`tmb-launcher`), the code,
the SDL3 and Dear ImGui sources and Real-ESRGAN's Linux build. It builds the game with your system's compiler, Python
and FFmpeg; **Prepare the game** names the packages to install for your distribution when one is missing, the Update
button installs the next Linux release, and **Make enhanced textures** works as on Windows (Vulkan needed). Saves
and settings are in `~/.local/share/tmb_recomp`.
- RecompLauncher can install and run the Linux download too (`recomplauncher.json`: `kit/python3`, the system's, for
the setup step; `game/tmb` to play).
### Changed
- **BozoEngine 0.7.8** (from 0.6.0). The game's sine and cosine (the C runtime's `sinf` and `cosf` the reference
build used) are computed the same way on every platform, bit for bit as on Windows, so the Linux build plays exactly
as the Windows one: the same game state on every frame of the checked 1P and 4P routes, where it drifted after about
90 seconds before. The snow's sway and the 2D rotations use them too. Windows plays as before (every checked frame
identical).
## [0.7.3] - 2026-12-01
### Added
- **RecompLauncher support.** Releases carry a `recomplauncher.json`, so [RecompLauncher](https://recomplauncher.com)
can install TMB_Recomp, check the disc against the USA dump, prepare the game with the release's own build, start
it, show the video settings (display mode, widescreen, frame rate, render scale, anti-aliasing, texture smoothing)
on the game's page and back up the memory cards. A game set up there keeps its saves, settings and logs in its
`recompdata` folder.
- Preparing again without a disc image uses the one the earlier preparation kept in the game folder, so an update can
be built after the original image was deleted.
## [0.7.2] - 2026-11-30
### Changed
- **BozoEngine comes from its releases instead of a git submodule.** `cmake/bozo_engine.json` pins a release by
version and SHA-256 (0.4.0, the same code as the commit pinned before), and configuring fetches it into
`BozoEngine/` (`cmake/bozo_engine_fetch.cmake`, the scheme SoulCaliburIII_Recomp uses). A player's release still
ships the engine's source in `source\BozoEngine` and builds offline; `release.ini` now stamps `engine_version`. To
work on the engine and TMB together, point `BOZO_ENGINE_DIR` (or `tmb_build.py --engine`) at a BozoEngine checkout.
- **BozoEngine 0.6.0** (from 0.4.0). In the window, the sound is held to the real time without clicks (engine PR #164),
and a render scale over 1 averages the pixels under each window pixel instead of picking one (#168). The rest
(SPU2 output interrupts, the movie library's work-area layout, the disc stream, ReferSemaStatus,
sceSifGetOtherData and opt-in library answers for other ports) leaves TMB's runs unchanged: the 1P and 4P replay
routes give the same record on every frame.
## [0.7.1] - 2026-11-30
### Fixed
- **A release unzipped by hand no longer trips the build on its file times.** The zip dates every file at its
commit's time, which an unzip reads as local time: west of UTC, within hours of a release, the files were in the
future and Prepare stopped with ninja's "manifest 'build.ninja' still dirty after 100 tries"; and an update unzipped
over a game built after its commit could leave a changed file uncompiled. `tools/tmb_build.py` now settles the times
before configuring: nothing in the source or the kit stays in the future, and with a record of each source and kit
dependency file (`<work folder>/source_times.json`) a changed or new file is dated now and an unchanged one keeps its
old time. A git checkout is left alone; the launcher's Update was not affected.
## [0.7.0] - 2026-11-27
### Added
- **Save states.** F5 saves and F7 loads the current slot, F6 / Shift+F6 pick the slot (0 to 9), and F2 has a
**Save states** tab listing them with a picture of each. They go to `states/slot<n>.state` in the user folder (about
40 MB each). A state loads only into the build that wrote it, and a save waits while a movie plays. For scripted
runs: `--save-state FILE --save-state-at N` and `--load-state FILE`.
- **PC SETTINGS in the game's own Options screen.** A ninth line under SAVE SETTINGS TO MEMORY CARD opens pages
drawn in the game's font and steered with the pad: **Video** (display mode, resolution, render scale, frame rate,
anti-aliasing, texture smoothing, upscaling and its filter, texture pack, pause in background, fast forward; APPLY
AND SAVE writes `video.ini`), **Cheats** (unlock everything, infinite health / ammo / energy, no AI, weak enemies;
at once) and **Save states** (the slot, LOAD, SAVE, as F5 / F7). Triangle or Circle goes back. The controls stay in
F2.
- **PC SETTINGS in the pause menu** too: a fifth line under RESUME, QUIT, SET VIBRATION and ADJUST REAR VIEW (a
fourth with several players) opens the same pages in the pause menu's style, on the pausing player's pad.
- **QUIT GAME** at the bottom of PC SETTINGS: Cross, then Cross again, ends the game and closes the window.
- **Widescreen (16:9)**, off by default: in F2's Video tab, PC SETTINGS → Video, or `widescreen = on` in `video.ini`
(`PS2X_WIDESCREEN=1`). In one-player and two-player matches the game draws a 16:9 picture: it shows more at the
sides (its own views made wider, culling and all), nothing is stretched, and the HUD keeps its shape. The menus,
movies and loading screens stay 4:3, centred, and three- and four-player split screens stay 4:3. The pause menu and
the other dialogs over a match (results, won, lost) are shown 4:3 and centred. The HUD goes to the 16:9 edges: the
radar, name and health to the left, the weapons, energy and lives to the right; the markers over the cars stay
on them.
### Fixed
- Quitting a match from the pause menu no longer leaves the match's music playing over the menus (BozoEngine's
989SND driver now stops a bank's sounds when the game unloads it).
## [0.6.0] - 2026-11-11
### Added
@@ -242,7 +348,13 @@ 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.6.0...HEAD
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.8.1...HEAD
[0.8.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.8.0...v0.8.1
[0.8.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.3...v0.8.0
[0.7.3]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.2...v0.7.3
[0.7.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.1...v0.7.2
[0.7.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.0...v0.7.1
[0.7.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.2...v0.4.0
+1 -1
View File
@@ -23,7 +23,7 @@ SOFTWARE.
---
This licence covers TMB_Recomp's own files. It does not cover:
- BozoEngine/ (the recompiler and runtime, a separate MIT project): see BozoEngine/LICENSE.
- BozoEngine/ (the recompiler and runtime, a separate MIT project, fetched from its releases): see BozoEngine/LICENSE.
- Anything from Twisted Metal: Black. No game data, code or art is in this repository or its releases;
players build the port from their own disc.
- Third-party components with their own licences (SDL3, Dear ImGui, the Exo 2 font, and the build
+56 -12
View File
@@ -24,7 +24,7 @@ PC services. BozoEngine replaces the PS2Recomp fork completely; the player build
> |---|---|
> | `SCUS_971.01` | `3ff17f4897552e355d0bb8c3abfa5125fe3ff2ef` |
## For players (Windows)
## For players (Windows and Linux)
You build the game yourself, on your PC, from **your own disc**: nothing of the game is in the download.
@@ -50,6 +50,28 @@ remains available for comparison. The steps below describe the native packages.
graphics driver is needed. The game then uses them; turn them off there or in F2 → Video → Texture pack. Nothing is
downloaded or sent, and the result is yours alone: do not share it.
**RecompLauncher.** Releases carry a [`recomplauncher.json`](recomplauncher.json), so
[RecompLauncher](https://recomplauncher.com) can install TMB_Recomp, check your disc, prepare the game with the same
build, show the video settings on the game's page and back up the memory cards. A game set up there keeps its saves,
settings and logs in its own `recompdata` folder, not in `%APPDATA%\TMB_Recomp`: copy `mc0` across to bring saves
from TMB Launcher. Enhanced textures are made by TMB Launcher only.
**Linux.** Download `TMB_Recomp-<version>-linux.tar.gz` and check it (`sha256sum`). It holds the same launcher
(`tmb-launcher`), our code, the SDL3 and Dear ImGui sources and Real-ESRGAN, but no compiler: the game is built with
your system's. Install GCC, CMake, Ninja, pkg-config, Python 3 and the FFmpeg (`libavcodec`, `libavutil`), X11 or
Wayland, OpenGL and audio development files; on Debian or Ubuntu:
```bash
sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev libx11-dev \
libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev \
libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev libasound2-dev libudev-dev
```
On Fedora, Arch or openSUSE, **Prepare the game** names the packages when one is missing. Then `tar xzf` it anywhere
with about 10 GB free, run `TMB_Recomp_Bozo/tmb-launcher` and follow steps 4 to 7 above. The disc picker is your
desktop's file dialog (xdg-desktop-portal) or zenity. Saves and settings are in `~/.local/share/tmb_recomp`; Update
installs the next Linux release. Enhanced textures need a Vulkan driver, as on Windows.
Requires **Windows 10 version 1903 or newer / Windows 11, an AVX2 and FMA capable CPU, and OpenGL 3.3**.
Original heat haze around fire and explosions is enabled by default. `BOZO_HEAT_HAZE=0` disables it for comparisons
with the older PC port. Menus and movies use their native timing, independently of the presentation frame rate.
@@ -113,12 +135,15 @@ those comparisons from actual native play. [docs/RECOMP_NOTES.md](docs/RECOMP_NO
| Original heat haze enabled by default | ✅ |
| Multi-player split-screen, 2 to 4 players; frame-keyed scripts for unattended checks | ✅ |
| Settings (F2): controls, video, cheats; windowed / fullscreen / borderless | ✅ |
| PC SETTINGS in the game's Options screen and pause menu: video, cheats and save states with the pad | ✅ |
| Widescreen 16:9 in one- and two-player matches (more at the sides, HUD unstretched; menus stay 4:3) | ✅ |
| Save states (F5 save, F7 load, ten slots; `--save-state` / `--load-state` for scripted runs) | ✅ |
| Higher internal resolution (2× by default; Video's render scale) | ✅ |
| Interpolated presentation above 60 Hz; rain, snow, flares and some trails still update at game rate | 🧪 |
| Every Challenge arena rechecked on BozoEngine | 🔧 |
| Every story level to the endings | 🔧 |
| Fresh standard-user Windows installation and four physical controllers | 🔧 |
| Linux player build validated on the new runtime | ⏳ |
| Linux player build: the launcher builds from the disc, plays and updates (Ubuntu 24.04, X11, Mesa) | 🧪 |
| Widescreen | ⏳ |
**Native port**: the shared goal of The Bozos' ports is to draw and play sound directly from the game's own data,
@@ -181,7 +206,10 @@ Your USA disc
The executable retains its symbols, so this port does not need a Ghidra function-map pass.
`runtime/tmb_overrides.cpp` contains game-specific bindings; `bozo/` contains the real-time host, headless host and
checker. Generic recompiler/runtime work lives in the [BozoEngine](https://github.com/TheBozos/BozoEngine) submodule.
checker. Generic recompiler/runtime work lives in [BozoEngine](https://github.com/TheBozos/BozoEngine): TMB builds on
one of its releases, pinned by version and SHA-256 in `cmake/bozo_engine.json` and fetched into `BozoEngine/` when
configuring (`cmake/bozo_engine_fetch.cmake`; a release's `source\BozoEngine` comes with it, so a player's build stays
offline).
Its [clean-room specifications and validation](https://github.com/TheBozos/BozoEngine/tree/main/docs) describe the engine.
PS2Recomp remains credited in the project's history and available in the v0.3.2 release, but is no longer a dependency.
@@ -189,8 +217,8 @@ PS2Recomp remains credited in the project's history and available in the v0.3.2
The player package brings its own build tools. To build from the repository:
- Windows 10 version 1903 or newer / Windows 11; Windows is the validated player target. Linux portability is not yet
validated for this migration.
- Windows 10 version 1903 or newer / Windows 11, or a 64-bit Linux with X11 or Wayland (GCC 13 or newer).
Windows is the most tested target.
- An **AVX2 and FMA capable CPU**, OpenGL 3.3, about 10 GB free for preparation, and your own USA disc.
- CMake 3.21+, Ninja, Python 3 and a C++20 compiler. The matching kit's GCC is the validated Windows configuration;
MSVC is not supported for this port.
@@ -202,10 +230,11 @@ The player package brings its own build tools. To build from the repository:
### One command, from your disc (Windows)
Clone the repository with its BozoEngine submodule, then use the same pipeline as the launcher:
Clone the repository, then use the same pipeline as the launcher (it fetches the pinned BozoEngine release into
`BozoEngine/` the first time; `cmake -P cmake/bozo_engine_fetch.cmake` does it alone):
```bat
git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git
git clone https://github.com/TheBozos/TMB_Recomp.git
cd TMB_Recomp
python tools\tmb_build.py --disc "D:\Discs\Twisted Metal - Black (USA).iso" --out D:\TMB-build --kit D:\tmb_kit_bozo\kit
"D:\TMB-build\TMB\Play TMB.cmd"
@@ -310,7 +339,8 @@ Follow [docs/RELEASE_CHECKLIST.md](docs/RELEASE_CHECKLIST.md) and include the co
Releases are built by `.github/workflows/release.yml` when the owner asks. An ordinary push does not publish one.
1. Move `CHANGELOG.md`'s Unreleased entries into `## [<version>] - <date>`, update its links, and merge through a PR
with green checks. Engine changes must already be public before updating the submodule pin.
with green checks. Engine changes must already be in a BozoEngine release before the pin moves: set its version and its
`.sha256` in `cmake/bozo_engine.json`.
2. Tag that merged commit (`v<version>`) and push the tag, or run the workflow against the already pushed tag.
3. The workflow checks the changelog, assembles the pinned kit, makes both player ZIPs and corresponding sources,
verifies hashes/contents and runs the bundled-toolchain/launcher checks, then creates a **draft** release.
@@ -347,7 +377,8 @@ cmake --build D:/TMB-dev -j 8
D:/TMB-dev/tmb.exe --iso "D:/Discs/Twisted Metal - Black (USA).iso"
```
`BOZO_ENGINE_DIR` selects another engine tree. `TMB_WINDOW=OFF` builds headless tools only.
`BOZO_ENGINE_DIR` selects another engine tree (a BozoEngine checkout, to work on the engine and TMB together;
`tools/tmb_build.py --engine <tree>` likewise); without it the pinned release is used. `TMB_WINDOW=OFF` builds headless tools only.
`BOZO_BUILD_TOOLS=OFF` removes the optional zlib-dependent recording/checking tools from a player build.
### Windows
@@ -400,12 +431,23 @@ use physical US positions:
| Key | What it does |
|---|---|
| F2 | Settings: Controls (per-player buttons, sticks, triggers, mouse and sensitivity), Video (resolution, window mode, render scale, presentation frame rate and texture upscaling), Cheats. Controls save to `input.ini`; video saves to `video.ini`. |
| F2 | Settings: Controls (per-player buttons, sticks, triggers, mouse and sensitivity), Video (resolution, window mode, render scale, presentation frame rate, texture upscaling and widescreen), Cheats. Controls save to `input.ini`; video saves to `video.ini`. |
| F3 | Toggle the frame-rate counter. |
| F5 / F7 | Save / load a save state in the current slot (`states/slot<n>.state` in the user folder). A state loads only into the build that wrote it; a save waits while a movie plays. |
| F6, Shift+F6 | Next / previous save-state slot (0-9); F2 → Save states lists them. |
| F11, Alt+Enter | Switch between the window and the last fullscreen mode. |
| F8 | Capture consecutive presents (the sequence settings below). |
| F9 | Start/stop a capture burst, ten captures per second. |
In the game, **Options → PC SETTINGS** (the last line, under the memory card lines), and **PC SETTINGS** in the pause
menu during a match, have the same Video, Cheats and Save states with the pad: Up / Down to choose, Left / Right to change, Cross to open or act (Video's APPLY AND SAVE,
Save states' LOAD and SAVE), Triangle or Circle to go back. The controls are rebound in F2. **QUIT GAME** at the
bottom of PC SETTINGS closes the game (press Cross twice).
**Widescreen** (Video: Widescreen, off by default; `widescreen = on` in `video.ini`, `PS2X_WIDESCREEN=1`): one- and
two-player matches are drawn 16:9, showing more at the sides with nothing stretched, the HUD at the screen's edges. Menus, movies, loading screens
and three- or four-player split screens stay 4:3.
The picture stays 4:3 inside the window. Video can present at game rate, a fixed higher rate, or the monitor's rate
with interpolation; the game itself keeps its 60 Hz timing. Interpolation adds about one game frame of latency and
remains experimental for effects that only update at game rate.
@@ -446,13 +488,15 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
| `--pad-script [n=]<file>` | Frame-keyed scripted input for player n (1–4); repeat for multiple players |
| `--quit-after <frames>` | End an unattended windowed run |
| `--capture-dir <dir> --capture-frames n,n` | Capture chosen game frames |
| `--hidden` | Test run that never shows the window: captures read the game's offscreen picture (add `--no-sound` so nothing plays; `--wav` still records) |
| `--capture-scene` | Captures read the game's picture without overlays, in a shown window |
| `PS2X_CAPTURE_WINDOW_DIR=<dir>` | F8/F9 capture destination |
| `PS2X_CAPTURE_SEQUENCE=<n>`, `PS2X_CAPTURE_SEQUENCE_AT=<s>[,<s>...]` | Consecutive presents at F8 or the chosen times, with interpolation timing metadata |
| `PS2X_CAPTURE_BURST_AT=<s>[,<s>...]` | Start/stop an F9-style burst at the chosen times |
| `PS2X_CAPTURE_DIR=<dir>`, `PS2X_CAPTURE_INTERVAL=<s>` | Periodic picture captures |
| `--audio-stats`, `--audio-latency <ms>` | Audio queue/underrun diagnostics and queue target |
| `--wav <file>`, `PS2X_AUDIO_RECORD=<file>` | Record the native mixer output |
| `--no-sound` | Disable device playback for a diagnostic run |
| `--no-sound` | Disable device playback (test runs; `--wav` still records) |
| `PS2X_SETTINGS_OPEN=Controls\|Video\|Cheats` | Open F2 directly on a tab for UI tests |
| `PS2X_LOG_FILE=<file>\|0`, `PS2X_NO_DIALOGS=1`, `PS2X_TEST_CRASH=<s>` | Another log/none, suppress unattended dialogs, or intentionally test crash handling |
| `TMB_CHEATS_LOG=1`, `TMB_CHEATS_TOGGLE=<s>` | Cheat diagnostics and periodic switching for tests |
@@ -491,7 +535,7 @@ captures, generated game code and disc data are local-only and never release con
| Path | Contents |
|---|---|
| `BozoEngine/` | the native recompiler/runtime submodule (MIT) |
| `BozoEngine/` | the native recompiler/runtime (MIT): the release `cmake/bozo_engine.json` pins, fetched, not committed |
| `bozo/` | TMB's windowed host, headless host and recorded-run checker |
| `cmake/bozo.cmake` | the native game build and generated-code integration |
| `recomp/` | game-specific recompiler declarations |
+4 -1
View File
@@ -6,10 +6,11 @@
// --window (builds with TMB_WINDOW): the same pinned run, its frames shown in a window as they are made (BozoEngine's
// window, the renderer's present), to capture the pictures of chosen frames (milestone M5's pixel comparison):
// tmb-check <log.clg> ... --window --capture-frames n,n,... [--capture-dir dir] [--width w --height h]
// [--render-scale s] [--aspect a]
// [--render-scale s] [--aspect a] [--hidden]
// --capture-frames n: the picture once n frames have ended, i.e. the reference record n - 1's frame (frame_<n>.png). The
// run is held at that frame's end until the window has read it back, so the picture is exactly that frame's. The window
// is 640x448 at render scale 1 by default; --aspect is the picture's shape inside it (4:3 by default, letterboxed).
// --hidden: the window is never shown, and the captures read the game's offscreen picture (the same pixels).
#include "run_main.h"
#if TMB_CHECK_WINDOW
@@ -86,6 +87,8 @@ namespace
window.renderScale = std::stof(value());
else if (a == "--aspect")
window.aspect = std::stof(value());
else if (a == "--hidden")
window.hidden = true;
else
rest.push_back(args[k]);
}
+26 -2
View File
@@ -3,17 +3,21 @@
//
// tmb-headless [--frames n] [--elf SCUS_971.01] [--iso image] [--pad-script [n=]file]... [--card-dir dir]
// [--out run.ref] [--report n] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]
// [--save-state file --save-state-at n] [--load-state file [--load-state-at n]] [--dump-ram file]
//
// --pad-script n=file: player n's frame-keyed script (1 when omitted; players 2-4 are the multitap's slots, as the
// reference's PS2X_PAD2_SCRIPT..PS2X_PAD4_SCRIPT).
//
// --wav: the sound the mixer made (48 kHz stereo, 16-bit), from game frame a to b (all of it by default); --no-sound:
// the mixer is not brought up at the frames' ends (as before milestone M3).
// --save-state / --load-state: BozoEngine's save states (BozoEngine/docs/save-states.md): the whole run written when n
// frames have ended, or loaded before the first frame (or when n frames have ended). --dump-ram: EE RAM at the run's end.
// Every --report frames (500 by default) and at the end: the frame, the EE clock, the function that waited for the
// frame's end (the game's loop: uiTitle_Main__Fv at the title), the Shell (the menus' object, gp - 0x4148) and the
// overrides that ran.
#include "tmb_host.h"
#include "tmb_port.h"
#include "tmb_state.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
@@ -39,7 +43,7 @@ int main(int argc, char **argv)
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
uint64_t report = 500;
std::string wavPath;
std::string wavPath, dumpRam;
uint64_t wavFrom = 0, wavTo = UINT64_MAX;
for (int k = 1; k < argc; ++k)
{
@@ -84,10 +88,21 @@ int main(int argc, char **argv)
}
else if (a == "--no-sound")
opt.sound = false;
else if (a == "--save-state")
opt.saveState = value();
else if (a == "--save-state-at")
opt.saveStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--load-state")
opt.loadState = value();
else if (a == "--load-state-at")
opt.loadStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--dump-ram")
dumpRam = value();
else
{
std::fprintf(stderr, "usage: tmb-headless [--frames n] [--elf path] [--iso image] [--pad-script [n=]file]... [--card-dir dir] "
"[--out run.ref] [--report n] [--print] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]\n");
"[--out run.ref] [--report n] [--print] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound] "
"[--save-state file --save-state-at n] [--load-state file [--load-state-at n]] [--dump-ram file]\n");
return 2;
}
}
@@ -120,9 +135,12 @@ int main(int argc, char **argv)
return 2;
}
opt.gameTag = "SCUS-97101";
bozo::host::FreeHost host(opt);
host.onStateMessage = [](bool, const std::string &message) { std::printf("[state] %s\n", message.c_str()); };
bozo::ee::Dispatcher d(host);
tmb::scene::Binding scene(&d.runtime());
tmb::addStateSection(host, &d.runtime());
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
@@ -196,6 +214,12 @@ int main(int argc, char **argv)
};
}
const uint64_t frames = host.run();
if (!dumpRam.empty())
if (FILE *f = std::fopen(dumpRam.c_str(), "wb"))
{
std::fwrite(d.runtime().memory.ram(), 1, 0x2000000u, f);
std::fclose(f);
}
if (wav.isOpen())
{
std::printf("wav: %s, %.1f s of sound\n", wavPath.c_str(), wav.frames() / 48000.0);
+300 -244
View File
@@ -1,246 +1,302 @@
// tmb: Twisted Metal: Black on BozoEngine in a window, in real time (phase 4, milestones M1 and M2). The free host as
// tmb-headless runs it (every library native, the disc image read, TMB's overrides native), with the host's clock: the
// game's frames held to the field rate (TMB's native frame end, bozo::app::FramePacer), each one presented in an SDL3
// window through OpenGL 3.3 (bozo::app::runWindow). The players' pads: the keyboard, mouse and up to four gamepads
// through input.ini's bindings (bozo::app::DevicePad; with the game's multitap, players 2-4 are its slots), or the
// frame-keyed scripts given.
//
// tmb [--iso image] [--elf SCUS_971.01] [--card-dir dir] [--width w --height h] [--fullscreen] [--no-vsync]
// [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--pad-script [n=]file]...
// [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]
//
// The user folder (%APPDATA%\TMB_Recomp, as the fork's TMB; PS2X_USER_DIR overrides it) holds input.ini, the memory
// cards (mc0, mc1; --card-dir overrides) and the logs (logs/TMB_Recomp.log). Without --elf the game data is looked for
// as the fork's TMB did (<exe>/game/SCUS_971.01, then the same in the user folder).
//
// Milestone M4, as the fork's TMB: F2 the settings window (Controls: input.ini; Video: video.ini in the user folder,
// --width / --height / --fullscreen (borderless) / --render-scale over it; Cheats: runtime/tmb_cheats.cpp), F3 the
// frame rate counter (PS2X_SHOW_FPS=1 from the start), F8 a capture sequence (PS2X_CAPTURE_SEQUENCE presents,
// PS2X_CAPTURE_SEQUENCE_AT seconds), F9 a burst of captures, ten a second; --capture-frames saves the game's picture at
// the first present after each of those game frames. The captures go to --capture-dir, else PS2X_CAPTURE_WINDOW_DIR,
// else <user folder>/captures. F11 / Alt+Enter: between the window and the last full-screen mode. --quit-after: close
// after that many frames. PS2X_FRAME_STATS=1: the frames' work times every 2 s (the FramePacer).
//
// Sound (milestone M3): the mixer's samples, made on the EE clock at each frame's end, go to the default playback device
// (bozo::app::AudioDevice: a queue of --audio-latency ms, 32 by default, plus the device's buffer). --audio-stats: the
// queue, latency and underruns every 2 s. --wav (or PS2X_AUDIO_RECORD): what the mixer made, also to a WAV file.
#include "tmb_host.h"
#include "tmb_port.h"
#include "bozo/app/app.h"
#include "bozo/app/audio_device.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
#include "bozo/app/device_pad.h"
#include "bozo/app/input_bindings.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"
#include "bozo/ee/dispatcher.h"
#include "bozo/host/free_host.h"
// tmb: Twisted Metal: Black on BozoEngine in a window, in real time (phase 4, milestones M1 and M2). The free host as
// tmb-headless runs it (every library native, the disc image read, TMB's overrides native), with the host's clock: the
// game's frames held to the field rate (TMB's native frame end, bozo::app::FramePacer), each one presented in an SDL3
// window through OpenGL 3.3 (bozo::app::runWindow). The players' pads: the keyboard, mouse and up to four gamepads
// through input.ini's bindings (bozo::app::DevicePad; with the game's multitap, players 2-4 are its slots), or the
// frame-keyed scripts given.
//
// tmb [--iso image] [--elf SCUS_971.01] [--card-dir dir] [--width w --height h] [--fullscreen] [--no-vsync]
// [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--pad-script [n=]file]...
// [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file] [--hidden] [--capture-scene]
// [--save-state file --save-state-at n] [--load-state file [--load-state-at n]]
//
// --hidden: a test run that shows nothing (the window is never shown; --capture-frames reads the game's offscreen
// picture). --capture-scene: captures read that picture (no overlays) in a shown window too.
//
// The user folder (%APPDATA%\TMB_Recomp, as the fork's TMB; PS2X_USER_DIR overrides it) holds input.ini, the memory
// cards (mc0, mc1; --card-dir overrides) and the logs (logs/TMB_Recomp.log). Without --elf the game data is looked for
// as the fork's TMB did (<exe>/game/SCUS_971.01, then the same in the user folder).
//
// Milestone M4, as the fork's TMB: F2 the settings window (Controls: input.ini; Video: video.ini in the user folder,
// --width / --height / --fullscreen (borderless) / --render-scale over it; Cheats: runtime/tmb_cheats.cpp; Video,
// Cheats and Save states also in the game's Options screen, PC SETTINGS: runtime/tmb_menu.cpp), F3 the
// frame rate counter (PS2X_SHOW_FPS=1 from the start), F8 a capture sequence (PS2X_CAPTURE_SEQUENCE presents,
// PS2X_CAPTURE_SEQUENCE_AT seconds), F9 a burst of captures, ten a second; --capture-frames saves the game's picture at
// the first present after each of those game frames. The captures go to --capture-dir, else PS2X_CAPTURE_WINDOW_DIR,
// else <user folder>/captures. F11 / Alt+Enter: between the window and the last full-screen mode. --quit-after: close
// after that many frames. PS2X_FRAME_STATS=1: the frames' work times every 2 s (the FramePacer).
//
// Sound (milestone M3): the mixer's samples, made on the EE clock at each frame's end, go to the default playback device
// (bozo::app::AudioDevice: a queue of --audio-latency ms, 32 by default, plus the device's buffer). --audio-stats: the
// queue, latency and underruns every 2 s. --wav (or PS2X_AUDIO_RECORD): what the mixer made, also to a WAV file.
#include "tmb_state.h"
#include "tmb_host.h"
#include "tmb_menu.h"
#include "tmb_port.h"
#include "bozo/app/app.h"
#include "bozo/app/audio_device.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
#include "bozo/app/device_pad.h"
#include "bozo/app/input_bindings.h"
#include "bozo/app/panel.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"
#include "bozo/ee/dispatcher.h"
#include "bozo/host/free_host.h"
#include "tmb_scene.h"
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <sstream>
#include <string>
#ifndef BOZO_RUN_DEFAULT_ELF
#define BOZO_RUN_DEFAULT_ELF ""
#endif
int main(int argc, char **argv)
{
// The fork's TMB identity (its PS2X_APP_* CMake values): the same user folder, so the cards and input.ini carry over.
bozo::app::Identity identity;
identity.title = "Twisted Metal: Black";
identity.folder = "TMB_Recomp";
identity.xdgFolder = "tmb_recomp";
identity.bootElf = "SCUS_971.01";
identity.dataFolder = "game";
bozo::app::setIdentity(identity);
bozo::app::startLogging();
bozo::app::installCrashHandler();
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
opt.realTime = true;
opt.quiet = true;
bozo::app::WindowOptions window;
window.title = "Twisted Metal: Black (BozoEngine)";
bozo::app::AudioOptions audio;
bool sound = true;
std::string wavPath;
if (const char *record = std::getenv("PS2X_AUDIO_RECORD"); record && *record)
wavPath = record;
// The command line's window options, over video.ini (applied once the user folder is known, below).
int width = 0, height = 0;
bool fullscreen = false;
float renderScale = 0.0f;
for (int k = 1; k < argc; ++k)
{
const std::string a = argv[k];
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
if (a == "--elf")
opt.elf = value();
else if (a == "--iso")
opt.iso = value();
else if (a == "--card-dir")
opt.cardDir = value();
else if (a == "--pad-script")
{
// [n=]file: player n's script (1 when omitted; players 2-4: the multitap's slots)
std::string v = value();
int player = 1;
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
{
player = v[0] - '0';
v = v.substr(2);
}
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
}
else if (a == "--width")
width = std::stoi(value());
else if (a == "--height")
height = std::stoi(value());
else if (a == "--fullscreen")
fullscreen = true;
else if (a == "--no-vsync")
window.vsync = false;
else if (a == "--render-scale")
renderScale = std::stof(value());
else if (a == "--capture-dir")
window.captureDir = value();
else if (a == "--capture-frames")
{
std::stringstream list(value());
for (std::string item; std::getline(list, item, ',');)
if (!item.empty())
window.captureFrames.push_back(std::stoull(item));
}
else if (a == "--quit-after")
window.quitAfterFrames = std::stoull(value());
else if (a == "--print")
opt.printGameOutput = true;
else if (a == "--no-sound")
sound = false;
else if (a == "--audio-latency")
audio.latencyMs = std::stod(value());
else if (a == "--audio-stats")
audio.stats = true;
else if (a == "--wav")
wavPath = value();
else
{
std::fprintf(stderr, "usage: tmb [--iso image] [--elf path] [--card-dir dir] [--width w] [--height h] [--fullscreen] "
"[--no-vsync] [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] "
"[--pad-script [n=]file]... [--print] [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]\n");
return 2;
}
}
// The window as the player set it (video.ini in the user folder, the fork's file; PS2X_WINDOW_SIZE / _MODE,
// PS2X_RENDER_SCALE over it), then the command line over both.
bozo::app::video::loadAtStartup(window.width, window.height);
{
bozo::app::video::Settings &v = bozo::app::video::edited();
if (width > 0 && height > 0)
v.width = width, v.height = height;
if (fullscreen)
v.mode = bozo::app::video::WindowMode::Borderless;
if (renderScale > 0.0f)
v.renderScale = renderScale;
}
window.videoSettings = true;
std::error_code ec;
if (opt.elf.empty() || !std::filesystem::is_regular_file(opt.elf, ec))
{
std::string searched;
const std::filesystem::path found = bozo::app::findGameData(&searched);
if (found.empty())
{
std::fprintf(stderr, "tmb: no ELF (--elf); looked for the game data at\n%s", searched.c_str());
return 2;
}
opt.elf = found.string();
}
// The memory cards in the user folder (<user>/mc0, mc1: the fork's layout, its saves read as they are).
if (opt.cardDir.empty() && !bozo::app::userDirectory().empty())
opt.cardDir = bozo::app::userDirectory().string();
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
if (opt.iso.empty())
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
if (opt.iso.empty())
{
std::fprintf(stderr, "tmb: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
return 2;
}
// Real time: the host's clock reaches the game (frame steps, the EE charged the real time a frame took).
bozo::det::setEnabled(false);
const bozo::port::Port *port = bozo::port::port();
bozo::port::Registry registry;
port->install(registry);
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
if (!missing.empty())
{
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate)\n", missing.size());
return 2;
}
bozo::host::FreeHost host(opt);
bozo::ee::Dispatcher d(host);
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
{
std::fprintf(stderr, "tmb: %s\n", error.c_str());
return 2;
}
bozo::app::DevicePad pad;
bool scripted = !opt.padScript.empty();
for (const std::string &script : opt.playerScripts)
scripted = scripted || !script.empty();
if (!scripted)
host.libraries().pad.input = &pad;
const std::string pads = scripted ? std::string("the scripts") : "the PC's devices (" + bozo::app::input::configPath() + ")";
std::fprintf(stderr, "tmb: user folder %s, memory cards in %s, pads from %s\n", bozo::app::userDirectory().string().c_str(),
opt.cardDir.empty() ? "memory" : opt.cardDir.c_str(), pads.c_str());
std::fprintf(stderr, "tmb: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
opt.iso.c_str());
// The sound: what the mixer makes at each frame's end, to the device (and the WAV file).
bozo::app::AudioDevice device(audio);
bozo::audio::WavWriter wav;
if (!wavPath.empty() && !wav.open(wavPath))
std::fprintf(stderr, "tmb: cannot write %s\n", wavPath.c_str());
if (sound)
device.open();
if (device.isOpen() || wav.isOpen())
host.onAudio = [&](uint64_t, const int16_t *samples, size_t count) {
device.push(samples, count);
wav.write(samples, count);
};
bozo::app::Game game;
game.run = [&]
{
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <sstream>
#include <string>
#ifndef BOZO_RUN_DEFAULT_ELF
#define BOZO_RUN_DEFAULT_ELF ""
#endif
int main(int argc, char **argv)
{
// The fork's TMB identity (its PS2X_APP_* CMake values): the same user folder, so the cards and input.ini carry over.
bozo::app::Identity identity;
identity.title = "Twisted Metal: Black";
identity.folder = "TMB_Recomp";
identity.xdgFolder = "tmb_recomp";
identity.bootElf = "SCUS_971.01";
identity.dataFolder = "game";
bozo::app::setIdentity(identity);
bozo::app::startLogging();
bozo::app::installCrashHandler();
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
opt.realTime = true;
opt.quiet = true;
bozo::app::WindowOptions window;
window.title = "Twisted Metal: Black (BozoEngine)";
bozo::app::AudioOptions audio;
bool sound = true;
std::string wavPath;
if (const char *record = std::getenv("PS2X_AUDIO_RECORD"); record && *record)
wavPath = record;
// The command line's window options, over video.ini (applied once the user folder is known, below).
int width = 0, height = 0;
bool fullscreen = false;
float renderScale = 0.0f;
for (int k = 1; k < argc; ++k)
{
const std::string a = argv[k];
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
if (a == "--elf")
opt.elf = value();
else if (a == "--iso")
opt.iso = value();
else if (a == "--card-dir")
opt.cardDir = value();
else if (a == "--pad-script")
{
// [n=]file: player n's script (1 when omitted; players 2-4: the multitap's slots)
std::string v = value();
int player = 1;
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
{
player = v[0] - '0';
v = v.substr(2);
}
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
}
else if (a == "--width")
width = std::stoi(value());
else if (a == "--height")
height = std::stoi(value());
else if (a == "--fullscreen")
fullscreen = true;
else if (a == "--no-vsync")
window.vsync = false;
else if (a == "--render-scale")
renderScale = std::stof(value());
else if (a == "--capture-dir")
window.captureDir = value();
else if (a == "--capture-frames")
{
std::stringstream list(value());
for (std::string item; std::getline(list, item, ',');)
if (!item.empty())
window.captureFrames.push_back(std::stoull(item));
}
else if (a == "--hidden")
window.hidden = true; // a test run that shows nothing: captures read the game's offscreen picture
else if (a == "--capture-scene")
window.captureScene = true; // captures read the game's picture (no overlays) even in a shown window
else if (a == "--quit-after")
window.quitAfterFrames = std::stoull(value());
else if (a == "--print")
opt.printGameOutput = true;
else if (a == "--no-sound")
sound = false;
else if (a == "--audio-latency")
audio.latencyMs = std::stod(value());
else if (a == "--audio-stats")
audio.stats = true;
else if (a == "--wav")
wavPath = value();
else if (a == "--save-state")
opt.saveState = value();
else if (a == "--save-state-at")
opt.saveStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--load-state")
opt.loadState = value();
else if (a == "--load-state-at")
opt.loadStateFrame = static_cast<uint32_t>(std::stoull(value()));
else
{
std::fprintf(stderr, "usage: tmb [--iso image] [--elf path] [--card-dir dir] [--width w] [--height h] [--fullscreen] "
"[--no-vsync] [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--hidden] [--capture-scene] "
"[--pad-script [n=]file]... [--print] [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file] "
"[--save-state file --save-state-at n] [--load-state file [--load-state-at n]]\n");
return 2;
}
}
// The window as the player set it (video.ini in the user folder, the fork's file; PS2X_WINDOW_SIZE / _MODE,
// PS2X_RENDER_SCALE over it), then the command line over both.
bozo::app::video::loadAtStartup(window.width, window.height);
{
bozo::app::video::Settings &v = bozo::app::video::edited();
if (width > 0 && height > 0)
v.width = width, v.height = height;
if (fullscreen)
v.mode = bozo::app::video::WindowMode::Borderless;
if (renderScale > 0.0f)
v.renderScale = renderScale;
}
window.videoSettings = true;
std::error_code ec;
if (opt.elf.empty() || !std::filesystem::is_regular_file(opt.elf, ec))
{
std::string searched;
const std::filesystem::path found = bozo::app::findGameData(&searched);
if (found.empty())
{
std::fprintf(stderr, "tmb: no ELF (--elf); looked for the game data at\n%s", searched.c_str());
return 2;
}
opt.elf = found.string();
}
// The memory cards in the user folder (<user>/mc0, mc1: the fork's layout, its saves read as they are).
if (opt.cardDir.empty() && !bozo::app::userDirectory().empty())
opt.cardDir = bozo::app::userDirectory().string();
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
if (opt.iso.empty())
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
if (opt.iso.empty())
{
std::fprintf(stderr, "tmb: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
return 2;
}
// Real time: the host's clock reaches the game (frame steps, the EE charged the real time a frame took).
bozo::det::setEnabled(false);
const bozo::port::Port *port = bozo::port::port();
bozo::port::Registry registry;
port->install(registry);
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
if (!missing.empty())
{
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate)\n", missing.size());
return 2;
}
opt.gameTag = "SCUS-97101";
bozo::host::FreeHost host(opt);
bozo::ee::Dispatcher d(host);
// Save states (BozoEngine/docs/save-states.md): TMB's section, F5 save, F7 load, F6 / Shift+F6 the slot, the F2 tab.
tmb::addStateSection(host, &d.runtime());
host.onStateMessage = [](bool, const std::string &message)
{
std::fprintf(stderr, "[state] %s\n", message.c_str());
bozo::app::notify(message);
};
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
{
std::fprintf(stderr, "tmb: %s\n", error.c_str());
return 2;
}
bozo::app::DevicePad pad;
bool scripted = !opt.padScript.empty();
for (const std::string &script : opt.playerScripts)
scripted = scripted || !script.empty();
if (!scripted)
host.libraries().pad.input = &pad;
const std::string pads = scripted ? std::string("the scripts") : "the PC's devices (" + bozo::app::input::configPath() + ")";
std::fprintf(stderr, "tmb: user folder %s, memory cards in %s, pads from %s\n", bozo::app::userDirectory().string().c_str(),
opt.cardDir.empty() ? "memory" : opt.cardDir.c_str(), pads.c_str());
std::fprintf(stderr, "tmb: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
opt.iso.c_str());
// The sound: what the mixer makes at each frame's end, to the device (and the WAV file).
bozo::app::AudioDevice device(audio);
bozo::audio::WavWriter wav;
if (!wavPath.empty() && !wav.open(wavPath))
std::fprintf(stderr, "tmb: cannot write %s\n", wavPath.c_str());
if (sound)
device.open();
if (device.isOpen() || wav.isOpen())
host.onAudio = [&](uint64_t, const int16_t *samples, size_t count) {
device.push(samples, count);
wav.write(samples, count);
};
bozo::app::Game game;
game.run = [&]
{
tmb::scene::Binding scene(&d.runtime());
const uint64_t frames = host.run();
if (device.isOpen())
{
const bozo::app::AudioDevice::Stats a = device.stats();
std::fprintf(stderr, "tmb: sound: %.1f s pushed, %llu frames dropped, %llu underruns (%.1f ms of silence); queue %.1f ms "
"(%.1f-%.1f) + device %.1f ms; ratio %.4f\n",
a.pushed / 48000.0, static_cast<unsigned long long>(a.dropped), static_cast<unsigned long long>(a.underruns),
a.missing / 48.0, a.queueMs, a.minQueueMs, a.maxQueueMs, a.deviceMs, a.ratio);
device.close();
}
wav.close();
std::fprintf(stderr, "tmb: the game ended after %llu frames: %s\n", static_cast<unsigned long long>(frames),
host.endReason().empty() ? "every thread ended" : host.endReason().c_str());
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
};
game.stop = [&] { host.requestStop(); };
game.framesEnded = [&] { return host.framesEnded(); };
return bozo::app::runWindow(window, game, &pad);
}
const uint64_t frames = host.run();
if (device.isOpen())
{
const bozo::app::AudioDevice::Stats a = device.stats();
std::fprintf(stderr, "tmb: sound: %.1f s pushed, %llu frames dropped, %llu underruns (%.1f ms of silence); queue %.1f ms "
"(%.1f-%.1f) + device %.1f ms; ratio %.4f\n",
a.pushed / 48000.0, static_cast<unsigned long long>(a.dropped), static_cast<unsigned long long>(a.underruns),
a.missing / 48.0, a.queueMs, a.minQueueMs, a.maxQueueMs, a.deviceMs, a.ratio);
device.close();
}
wav.close();
std::fprintf(stderr, "tmb: the game ended after %llu frames: %s\n", static_cast<unsigned long long>(frames),
host.endReason().empty() ? "every thread ended" : host.endReason().c_str());
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
};
game.stop = [&] { host.requestStop(); };
game.framesEnded = [&] { return host.framesEnded(); };
game.saveState = [&](int slot) { host.requestSave(bozo::app::stateSlotPath(slot)); };
game.loadState = [&](int slot) { host.requestLoad(bozo::app::stateSlotPath(slot)); };
// PC SETTINGS in the game's Options screen (runtime/tmb_menu.cpp): the window's video settings and save states.
tmb::menu::Hooks menuHooks;
menuHooks.videoShared = [] { return bozo::app::video::shared(); };
menuHooks.videoApply = [](const bozo::app::video::Settings &s) { bozo::app::video::post(s, true); };
menuHooks.texturePackFolder = [](const std::string &s) { return bozo::app::video::texturePackFolder(s); };
menuHooks.stateSlot = [] { return bozo::app::stateSlot(); };
menuHooks.setStateSlot = [](int slot) { bozo::app::setStateSlot(slot); };
menuHooks.slotSummary = [](int slot) { return bozo::app::stateSlotSummary(slot); };
menuHooks.saveState = [&](int slot)
{
host.requestSave(bozo::app::stateSlotPath(slot));
bozo::app::captureStatePicture(slot); // the slot's picture, as F5 takes it
return true;
};
menuHooks.loadState = [&](int slot)
{
host.requestLoad(bozo::app::stateSlotPath(slot));
return true;
};
menuHooks.quit = [&] { host.requestStop(); };
menuHooks.widescreen = [] { return bozo::app::video::shared().applied.widescreen; };
menuHooks.setPictureAspect = [](float aspect) { bozo::app::setPictureAspect(aspect); };
bozo::app::video::offerWidescreen(true); // runtime/tmb_widescreen.cpp
tmb::menu::setHooks(std::move(menuHooks));
return bozo::app::runWindow(window, game, &pad);
}
+7 -4
View File
@@ -16,10 +16,13 @@
# The generated code: bozo-recomp with the externals bozo-externals writes from the ELF (the stubs BozoEngine answers),
# recomp/tmb_stubs.txt and TMB's override list (tools/tmb_overrides_list.py, from runtime/*.cpp).
# BozoEngine: the submodule (BozoEngine/, at the commit TMB pins) unless BOZO_ENGINE_DIR names another tree (development).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)")
if(NOT BOZO_ENGINE_DIR AND EXISTS "${CMAKE_SOURCE_DIR}/BozoEngine/CMakeLists.txt")
set(BOZO_ENGINE_DIR "${CMAKE_SOURCE_DIR}/BozoEngine" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)" FORCE)
# BozoEngine: the release cmake/bozo_engine.json pins, fetched into BozoEngine/ (cmake/bozo_engine_fetch.cmake), unless
# BOZO_ENGINE_DIR names another tree (development: a BozoEngine checkout).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)")
if(NOT BOZO_ENGINE_DIR OR BOZO_ENGINE_DIR STREQUAL "${CMAKE_SOURCE_DIR}/BozoEngine")
include("${CMAKE_CURRENT_LIST_DIR}/bozo_engine_fetch.cmake")
set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json")
endif()
set(TMB_ELF "" CACHE FILEPATH "TMB's executable (SCUS_971.01), extracted from the disc")
set(TMB_GEN_FILES 32 CACHE STRING "How many .cpp files the generated code is split into")
+4
View File
@@ -0,0 +1,4 @@
{
"version": "0.7.8",
"sha256": "a4c85d057b00bf8fe34a75cba88ef7e30213f4019b287053a88b5a6e7a1095f7"
}
+56
View File
@@ -0,0 +1,56 @@
# The BozoEngine release cmake/bozo_engine.json pins, in BozoEngine/ beside cmake/: the release's archive
# (https://github.com/TheBozos/BozoEngine/releases), SHA-256 checked, unpacked, and its version and hash written to
# BozoEngine/.release; nothing is downloaded while those match the pin (a release's source\BozoEngine comes with it, so
# a player's build stays offline). Included by cmake/bozo.cmake and launcher/CMakeLists.txt when they are not given
# another tree, run by tools/tmb_build.py in a git checkout and by tools/make_release.py, or on its own:
# cmake [-DBOZO_ENGINE_DOWNLOADS=<dir>] -P cmake/bozo_engine_fetch.cmake
# BOZO_ENGINE_DOWNLOADS is where the archive goes (default build/). The same scheme as SoulCaliburIII_Recomp's.
cmake_minimum_required(VERSION 3.20)
get_filename_component(bozo_engine_root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
file(READ "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json" bozo_engine_pin)
string(JSON bozo_engine_version GET "${bozo_engine_pin}" version)
string(JSON bozo_engine_sha256 GET "${bozo_engine_pin}" sha256)
set(bozo_engine_tree "${bozo_engine_root}/BozoEngine")
set(bozo_engine_want "${bozo_engine_version} ${bozo_engine_sha256}")
set(bozo_engine_have "")
if(EXISTS "${bozo_engine_tree}/.release")
file(READ "${bozo_engine_tree}/.release" bozo_engine_have)
string(STRIP "${bozo_engine_have}" bozo_engine_have)
elseif(EXISTS "${bozo_engine_tree}")
file(GLOB bozo_engine_entries "${bozo_engine_tree}/*" "${bozo_engine_tree}/.*")
if(bozo_engine_entries)
message(FATAL_ERROR "BozoEngine: ${bozo_engine_tree} is not a pinned release (the old submodule's checkout?): "
"move it away (to build on it there: -DBOZO_ENGINE_DIR=<its new place>, or "
"tools/tmb_build.py --engine <its new place>)")
endif()
endif()
if(NOT bozo_engine_have STREQUAL bozo_engine_want)
if(NOT BOZO_ENGINE_DOWNLOADS)
set(BOZO_ENGINE_DOWNLOADS "${bozo_engine_root}/build")
endif()
set(bozo_engine_name "BozoEngine-${bozo_engine_version}")
set(bozo_engine_archive "${BOZO_ENGINE_DOWNLOADS}/${bozo_engine_name}.tar.gz")
set(bozo_engine_url
"https://github.com/TheBozos/BozoEngine/releases/download/v${bozo_engine_version}/${bozo_engine_name}.tar.gz")
message(STATUS "BozoEngine ${bozo_engine_version}: ${bozo_engine_url}")
file(DOWNLOAD "${bozo_engine_url}" "${bozo_engine_archive}" EXPECTED_HASH SHA256=${bozo_engine_sha256}
TLS_VERIFY ON STATUS bozo_engine_status)
list(GET bozo_engine_status 0 bozo_engine_code)
if(bozo_engine_code)
list(GET bozo_engine_status 1 bozo_engine_error)
message(FATAL_ERROR "BozoEngine ${bozo_engine_version}: ${bozo_engine_error}")
endif()
set(bozo_engine_unpack "${bozo_engine_root}/.BozoEngine-unpack")
file(REMOVE_RECURSE "${bozo_engine_tree}" "${bozo_engine_unpack}")
file(ARCHIVE_EXTRACT INPUT "${bozo_engine_archive}" DESTINATION "${bozo_engine_unpack}")
# Its files dated now: unpacked with the archive's own dates (the release's, older than objects built since), a
# build made on the last release kept objects compiled against the old headers after a pin bump (Shinobido 0.7.0 ->
# 0.7.3: two files built on the old renderer.h, objects and the HUD missing from the picture).
file(GLOB_RECURSE bozo_engine_files LIST_DIRECTORIES false "${bozo_engine_unpack}/*")
file(TOUCH_NOCREATE ${bozo_engine_files})
file(WRITE "${bozo_engine_unpack}/${bozo_engine_name}/.release" "${bozo_engine_want}\n")
file(RENAME "${bozo_engine_unpack}/${bozo_engine_name}" "${bozo_engine_tree}")
file(REMOVE_RECURSE "${bozo_engine_unpack}")
endif()
+2 -1
View File
@@ -15,6 +15,7 @@ The earlier v0.3.2 release remains in Git history and on GitHub for comparison;
## Architecture and build
[`SAVE_STATES.md`](SAVE_STATES.md) adds save states (F5/F7/F6, `--save-state` / `--load-state`), with the 989SND driver saved in BozoEngine.
[`NATIVE_PERSISTENT_FORWARD.md`](NATIVE_PERSISTENT_FORWARD.md) adds the last three forwards: 269/269 forward returns are native.
[`NATIVE_BLOW_DEBRIS_FORWARD.md`](NATIVE_BLOW_DEBRIS_FORWARD.md) adds the BlowDebris forwards (one dead-W-slot RAM hash difference, proven).
[`NATIVE_HUD_LASER_FORWARD.md`](NATIVE_HUD_LASER_FORWARD.md) adds the HUD laser forwards.
@@ -249,7 +250,7 @@ no upload tag at the audited calls; game texture-manager bookkeeping and other p
[`NATIVE_GRAPHICS_SERVICES.md`](NATIVE_GRAPHICS_SERVICES.md) records removal of the engine GS device/GIF
reader state and TMB's old packet-based flare adapter, independent/combined tests and unsupported readback limits.
- One submodule: `BozoEngine`. No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
- No submodule: BozoEngine is the release `cmake/bozo_engine.json` pins (fetched into `BozoEngine/`). No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
- `tools/tmb_build.py`: verify → extract → configure → native tools → recompile → packs → compile → stage.
- `scripts/build_runtime.sh` and the other retained shortcuts use that same pipeline.
- Native frame pacing is unconditional. A legacy `TMB_NATIVE_FRAMES=0` environment setting cannot bypass it.
+91
View File
@@ -3,6 +3,97 @@
Use a scratch `PS2X_USER_DIR` for every automated run. Keep game data and generated code out of Git and release ZIPs.
Publication is separate from a successful build; this checklist records what was actually verified.
v0.8.0 was published on 2026-12-02 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,028-file payload, and are stamped with
the release commit and engine version `0.7.8`; the sources ZIP matches its hash; both carry the commit's
`recomplauncher.json`;
- the Linux archive (`TMB_Recomp-0.8.0-linux.tar.gz`, new) matches its hash and passes `verify_tar`. Its `source/`
is the zips' but for line ends; `tmb-launcher`, `kit/python3` and Real-ESRGAN are executable;
- the release's engine change (BozoEngine 0.7.8, #129) was checked before tagging: headless 1P (9,500 frames) and 4P
(8,500 frames) Windows records are identical to engine 0.6.0's, and the Linux build's game state equals Windows' on
every frame (the draw hash differs by GCC's fused multiply-adds only);
- Windows: a fresh install in a path with spaces and accents was built offline from the disc with only the bundled
kit, stopped and resumed, played and exited normally, with menu/movie timing passing; the v0.7.3 install was
updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration ZIP; player data was kept
in both update cases; Enhanced textures made 2,190 replacements;
- Linux (Docker, Ubuntu 24.04, Mesa llvmpipe, Xvfb): the archive unpacked into a path with spaces and accents passes
the launcher's self-check; the launcher's self-test prepared the game from the disc (stopped and resumed) in 3:49
and played 40 s, but reported a failure when closing it: the game was killed by a repeated close signal (exit 143),
a self-test-only problem fixed after the release (#131, checked on this archive: exit 0). RecompLauncher's prepare
through `kit/python3` built the game in 160 s ("Ready to play"), said "Already built" when run again, and its start
played 600 frames with the cards in `recompdata`;
- known leftover: `source/tools/__pycache__/tmb_build.cpython-314.pyc` is in every package, as in earlier releases
(removed for the next one, #131).
v0.7.3 was published on 2026-12-01 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,011-file payload, and are stamped with
the release commit and engine version `0.6.0`; the sources ZIP matches its hash;
- the release's change (RecompLauncher support, #125): both ZIPs carry the commit's `recomplauncher.json` at their
top. On the `-bozo.zip`, unpacked into a path with accents, RecompLauncher's prepare and start (run as its
`lib.rs` does, with DC's `rl_sim.py`) built the game in 158 s ending "Ready to play", said "Already built" when run
again, played 600 frames hidden and muted at 59.7 frames/s with the cards and logs in `recompdata`, and prepared
again from the kept `disc.iso` without the player's image;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,181 replacements.
v0.7.2 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,009-file payload, and are stamped with
the release commit and engine version `0.6.0`; the sources ZIP matches its hash and holds the pinned engine release
(`source/BozoEngine/.release`);
- the release's changes (engine fetched from a pinned BozoEngine release, #121; BozoEngine 0.6.0, #122) were checked
before tagging: a clean checkout builds with no submodule, and headless 1P (9,500 frames) and 4P (8,500 frames)
records match the previous engine on every field;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,191 replacements.
v0.7.1 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
the release commit and engine `b29bc39`; the sources ZIP matches its hash;
- the release's fix (source and kit file times settled before configuring, #118) was checked end to end: the v0.7.0
player ZIP with every file dated 3 h ahead loops ninja ("still dirty after 100 tries") as shipped and passes
Prepare's tools step with the fix;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing (a first
run failed movie 2 at 28.3 pictures/s while another port's run shared the bench; the rerun passed);
- the v0.7.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,186 replacements.
v0.7.0 was published on 2026-11-27 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
the release commit and engine `b29bc39`; the sources ZIP matches its hash;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.6.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,191 replacements;
- the release's new features (PC SETTINGS in the Options screen and the pause menu, QUIT GAME, widescreen, its HUD
and dialogs, the quit-music fix) were played by the owner on the development PC before the tag.
v0.6.0 was published on 2026-11-11 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 7,974-file payload, and are stamped with
the release commit and engine `a36a4d2`. Real-ESRGAN, its licences and the enhanced-texture tools are in the kit;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- on that install, the launcher's Enhanced textures dumped and upscaled 2,181 replacements in 4 min 18 s. An earlier
draft failed here because the dump listed some textures more than once; it was rebuilt with the fix (#104);
- the v0.5.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- with the bench lock, the pack at 4x held 59.1 to 59.5 minimum and 59.9 average game fps in 1P, three story arenas
and 4P, the same as with it off (one RTX 5070 Ti).
v0.5.0 was published on 2026-11-09 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 7,889-file payload, and are stamped with
+70
View File
@@ -0,0 +1,70 @@
# Save states
TMB uses BozoEngine's save states (`BozoEngine/docs/save-states.md`). A state holds the whole run at a frame's end.
It can be loaded back in the same process or in a new one, and the run then goes on exactly as the saved run did.
## Using them
- **Window:**
- F5 saves in the current slot and F7 loads it.
- F6 and Shift+F6 change the slot (0-9). F2 → Save states lists the slots.
- The files are `states/slot<n>.state` in the user folder, about 40 MB each.
- **Command line** (`tmb` and `tmb-headless`):
- `--save-state FILE --save-state-at N` writes a state when N frames have ended.
- `--load-state FILE [--load-state-at N]` loads one before the first frame, or when N frames have ended.
- Frame numbers stay absolute after a load: `--frames`, `--quit-after` and `--capture-frames` still count from the
start of the run.
- `tmb-headless --dump-ram FILE` writes EE RAM at the run's end.
- **Limits:**
- A state loads only into the build that wrote it. Make the states again after a change to a section's layout.
- A save waits while a movie plays, and says why.
- Recorded runs (`--out`) do not follow a load.
For checks, keep a few named states, for example the title, a 1P match or a 4P match. Note the frame and pad script
that made each one, then start runs from them instead of replaying the scripts from boot.
## What is saved
The engine saves the runtime, its libraries and the host:
- EE memory, threads, the kernel, timers, pads, cards, CD and MPEG;
- the 989SND sound driver: banks, handles, its IOP memory, mixer, libsd and 989SND's own model.
Two engine changes came with this:
- **989SND unloaded banks:** the engine used to destroy a bank's header while busy voices still read its program
records, a use-after-free. Unloaded banks are now kept, as 989SND's IOP memory is.
- **`LoadedImages::images` / `restore`:** these let a port save the mesh files it bound.
TMB adds its own section, `tmb` (`runtime/tmb_state.cpp`):
| Part | Saved | Why |
| --- | --- | --- |
| Overrides | Frame pacing parity, frame-end cycle, field carry, clock debt; the movie sound's queue | The parity is written to the game's memory; the pacing carries over between frames |
| Native hierarchy | `tmb::scene::Scene` whole: frames, lights, renderer parameters | The records the game's VU programs kept between draws |
| Meshes | The NGP files the game bound (base, size, pack file), the DMA marks' counter | Told once when the game loads a level. The images change in memory afterwards, so they cannot be bound again |
| Textures | Disc file per address, the level's file lists and set-up order, the records placed in VRAM, TBP → texture id | Told once at load time; records saved as (file, index) |
| Particles | Stripe scroll, arc VU records, texture choices, per system | Kept between frames |
| Cheats | The lock words Unlock everything opened | Put back when it goes off |
On a load, the decoded textures, the skid marks' object and the 2D menu and movie pictures are dropped. They are
caches of the old run's memory.
## How it was checked
Headless runs are deterministic. Each check saves at frame N on the 1P or 4P route (A), then:
- loads that state in a new process (B);
- loads it in the middle of a run, at a later frame (C).
All three run to the route's end.
| Route | Saved at | End-of-route EE RAM (B, C against A) | Sound after the save |
| --- | --- | --- | --- |
| 1P, menus | 3,000 | identical | byte-identical |
| 1P, match | 7,000 | identical | byte-identical |
| 4P, match | 7,000 | identical | byte-identical |
The native renderer's batch counts and EE cycles after the load match the run that never stopped.
The default replays still match the build without save states on every recorded field. That covers 1P 9,500 frames
and 4P 8,500 frames, including RAM, sound and the sampled RAM images.
A window run that loaded a match state showed the same scene, HUD and sound as the run that saved it.
+43 -28
View File
@@ -4,31 +4,34 @@ project(TMB_Launcher LANGUAGES C CXX)
# No C++ modules are used; keep GCC's module mapper out of relocatable kits with spaced/non-ASCII paths.
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
# TMB Launcher.exe: what a player double-clicks. It checks their disc image, runs tools/tmb_build.py with the build kit
# (kit\python), shows its progress, and starts the game. Its own small project (the game's CMake needs the disc): SDL3
# and Dear ImGui at the releases BozoEngine pins (its runtime/CMakeLists.txt: the same archives and SHA-256), ImGui's own
# SDL3 and OpenGL 3 backends, BozoEngine's PNG writer (the selftest's screenshots); built static, a GUI-subsystem exe
# that needs no DLL. Windows only.
# TMB Launcher.exe (tmb-launcher on Linux): what a player double-clicks. It checks their disc image, runs
# tools/tmb_build.py with the build kit's Python (the system's python3 on Linux), shows its progress, and starts the
# game. Its own small project (the game's CMake needs the disc): SDL3 and Dear ImGui at the releases BozoEngine pins
# (its runtime/CMakeLists.txt: the same archives and SHA-256), ImGui's own SDL3 and OpenGL 3 backends, BozoEngine's PNG
# writer (the selftest's screenshots). On Windows a static GUI-subsystem exe that needs no DLL; on Linux libstdc++ and
# libgcc linked in, libcurl loaded when the update check runs.
#
# cmake -S launcher -B build/launcher -G Ninja -DCMAKE_BUILD_TYPE=Release
# cmake --build build/launcher -> build/launcher/TMB Launcher.exe
# cmake --build build/launcher -> build/launcher/TMB Launcher.exe, or build/launcher/tmb-launcher
#
# Offline (the build kit): -DFETCHCONTENT_SOURCE_DIR_SDL3=<kit>/deps/sdl3-src -DFETCHCONTENT_SOURCE_DIR_IMGUI=<kit>/deps/
# imgui-src and -DLAUNCHER_FONT_DIR=<dir with Exo2[wght].ttf and OFL.txt>.
if(NOT WIN32)
message(FATAL_ERROR "The launcher is Windows only (Linux players run tools/tmb_build.py).")
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# BozoEngine's tree (the submodule beside launcher/): its PNG writer only.
set(LAUNCHER_BOZO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../BozoEngine" CACHE PATH "BozoEngine's source tree")
# BozoEngine's tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/ beside launcher/): its PNG writer
# only.
set(LAUNCHER_BOZO_DIR "" CACHE PATH "BozoEngine's source tree (default: the pinned release, in BozoEngine/)")
if(NOT LAUNCHER_BOZO_DIR)
include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/bozo_engine_fetch.cmake")
set(LAUNCHER_BOZO_DIR "${bozo_engine_tree}")
endif()
if(NOT EXISTS "${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR} (git submodule update --init BozoEngine)")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR}")
endif()
include(FetchContent)
@@ -105,23 +108,35 @@ if(LAUNCHER_VERSION MATCHES "^v?([0-9]+)[.]([0-9]+)[.]([0-9]+)")
endif()
list(JOIN LAUNCHER_VERSION_NUMBERS "," LAUNCHER_FILEVERSION)
set(LAUNCHER_ICON "${_icon}")
set(LAUNCHER_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/launcher.manifest")
set(LAUNCHER_EXO2 "${_font_dir}/exo2.ttf")
set(LAUNCHER_OFL "${_font_dir}/OFL.txt")
configure_file(launcher.rc.in "${CMAKE_BINARY_DIR}/launcher.rc" @ONLY)
set_source_files_properties("${CMAKE_BINARY_DIR}/launcher.rc" PROPERTIES OBJECT_DEPENDS "${_icon};${LAUNCHER_EXO2};${LAUNCHER_MANIFEST}")
enable_language(RC)
set(LAUNCHER_SOURCES src/main.cpp src/ui.cpp src/window.cpp src/build_model.cpp src/config.cpp
"${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
add_executable(tmb_launcher WIN32
src/main.cpp src/ui.cpp src/window.cpp src/build_model.cpp src/config.cpp src/platform_win.cpp
"${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp"
"${CMAKE_BINARY_DIR}/launcher.rc")
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "TMB Launcher")
target_include_directories(tmb_launcher PRIVATE "${LAUNCHER_BOZO_DIR}/runtime/include")
target_link_libraries(tmb_launcher PRIVATE launcher_imgui comdlg32 shell32 ole32 winhttp)
target_compile_definitions(tmb_launcher PRIVATE TMB_VERSION="${LAUNCHER_VERSION}" TMB_COMMIT="${LAUNCHER_COMMIT}")
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
# No DLL besides Windows' own: libstdc++, libgcc and winpthread linked in; no debug information.
target_link_options(tmb_launcher PRIVATE -static -s)
if(WIN32)
set(LAUNCHER_ICON "${_icon}")
set(LAUNCHER_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/launcher.manifest")
configure_file(launcher.rc.in "${CMAKE_BINARY_DIR}/launcher.rc" @ONLY)
set_source_files_properties("${CMAKE_BINARY_DIR}/launcher.rc" PROPERTIES OBJECT_DEPENDS "${_icon};${LAUNCHER_EXO2};${LAUNCHER_MANIFEST}")
enable_language(RC)
add_executable(tmb_launcher WIN32 ${LAUNCHER_SOURCES} src/platform_win.cpp "${CMAKE_BINARY_DIR}/launcher.rc")
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "TMB Launcher")
target_link_libraries(tmb_launcher PRIVATE launcher_imgui comdlg32 shell32 ole32 winhttp)
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
# No DLL besides Windows' own: libstdc++, libgcc and winpthread linked in; no debug information.
target_link_options(tmb_launcher PRIVATE -static -s)
endif()
else()
# The font and its licence assembled into the executable (.incbin), read back by plat::resource.
add_executable(tmb_launcher ${LAUNCHER_SOURCES} src/platform_linux.cpp)
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "tmb-launcher")
set_source_files_properties(src/platform_linux.cpp PROPERTIES
COMPILE_DEFINITIONS "TMB_EXO2_FILE=\"${LAUNCHER_EXO2}\";TMB_OFL_FILE=\"${LAUNCHER_OFL}\""
OBJECT_DEPENDS "${LAUNCHER_EXO2};${LAUNCHER_OFL}")
find_package(Threads REQUIRED)
target_link_libraries(tmb_launcher PRIVATE launcher_imgui Threads::Threads ${CMAKE_DL_LIBS})
target_link_options(tmb_launcher PRIVATE -static-libstdc++ -static-libgcc -s)
endif()
target_include_directories(tmb_launcher PRIVATE "${LAUNCHER_BOZO_DIR}/runtime/include")
target_compile_definitions(tmb_launcher PRIVATE TMB_VERSION="${LAUNCHER_VERSION}" TMB_COMMIT="${LAUNCHER_COMMIT}")
+49 -13
View File
@@ -4,13 +4,15 @@
// SDL3 and OpenGL 3 backends; window.h).
//
// The release folder it expects (its own folder, or --release <dir>):
// TMB Launcher.exe
// TMB Launcher.exe (tmb-launcher on Linux)
// source\ the TMB_Recomp code (tools\tmb_build.py, BozoEngine\...)
// kit\ the build kit (kit\python\python.exe, the compiler...)
// kit\ the build kit (kit\python\python.exe, the compiler...); on Linux only kit_manifest.json and deps\, the
// system's python3 and compiler doing the rest
// build\ tmb_build's work folder (made here)
// game\ the game folder the build stages (made here): tmb.exe, SCUS_971.01, disc.iso, the packs
// The player's settings: launcher.ini in the runner's user folder (%APPDATA%\TMB_Recomp, or PS2X_USER_DIR), next to
// the game's video.ini, which the Settings tab writes in the runner's format.
// game\ the game folder the build stages (made here): tmb.exe (tmb on Linux), SCUS_971.01, disc.iso, the packs
// The player's settings: launcher.ini in the runner's user folder (%APPDATA%\TMB_Recomp,
// ~/.local/share/tmb_recomp on Linux, or PS2X_USER_DIR), next to the game's video.ini, which the Settings tab
// writes in the runner's format.
//
// --selftest <iso> --shots <dir>: the whole flow without a hand on it, a screenshot of each screen (see selftest()).
@@ -60,7 +62,13 @@ static const char *kReleasePagePrefix = "https://github.com/TheBozos/TMB_Recomp/
// BozoEngine: the release's other zip, TMB_Recomp-<version>.zip, is the fork build's), 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/";
#ifdef _WIN32
static std::string releaseZipName(const std::string &version) { return "TMB_Recomp-" + version + "-bozo.zip"; }
static const wchar_t *kGameExeName = L"tmb.exe";
#else
static std::string releaseZipName(const std::string &version) { return "TMB_Recomp-" + version + "-linux.tar.gz"; }
static const wchar_t *kGameExeName = L"tmb";
#endif
// ---- language ----
@@ -353,6 +361,7 @@ struct App
Phase phase = Phase::Welcome;
Tab tab = Tab::Play;
std::string missingPart; // Incomplete: what is not there
bool missingPython = false; // Linux: no python3 on the PATH
// The disc check (tmb_build.py --check).
plat::Process checker;
@@ -435,12 +444,16 @@ struct App
p.release = plat::str(r);
p.source = plat::str(r / L"source");
p.kit = plat::str(r / L"kit");
#ifdef _WIN32
p.python = plat::str(r / L"kit" / L"python" / L"python.exe");
#else
p.python = plat::findProgram("python3");
#endif
p.script = plat::str(r / L"source" / L"tools" / L"tmb_build.py");
p.buildOut = plat::str(r / L"build");
p.buildLogs = plat::str(r / L"build" / L"logs");
p.game = plat::str(r / L"game");
p.gameExe = plat::str(r / L"game" / L"tmb.exe");
p.gameExe = plat::str(r / L"game" / kGameExeName);
p.elf = plat::str(r / L"game" / L"SCUS_971.01");
p.iso = plat::str(r / L"game" / L"disc.iso");
p.releaseIni = plat::str(r / L"source" / L"release.ini");
@@ -457,9 +470,18 @@ struct App
video.load(p.videoIni);
if (!exists(p.script))
missingPart = "source\\tools\\tmb_build.py";
missingPart = plat::str(fs::path(L"source") / L"tools" / L"tmb_build.py");
#ifdef _WIN32
else if (!exists(p.python) || !exists(plat::str(r / L"kit" / L"kit_manifest.json")))
missingPart = "kit\\";
#else
else if (!exists(plat::str(r / L"kit" / L"kit_manifest.json")))
#endif
missingPart = plat::str(fs::path(L"kit") / L"");
else if (p.python.empty())
{
missingPart = "python3";
missingPython = true;
}
phase = !missingPart.empty() ? Phase::Incomplete : cfg.disc.empty() ? Phase::Welcome : Phase::Ready;
readStamps();
cleanUpdateLeftovers();
@@ -658,7 +680,12 @@ struct App
std::string packDir() const { return plat::str(plat::path(p.user) / L"texture_pack"); }
bool hasRealEsrgan() const
{
return exists(plat::str(plat::path(p.kit) / L"realesrgan" / L"realesrgan-ncnn-vulkan.exe")) &&
#ifdef _WIN32
const wchar_t *program = L"realesrgan-ncnn-vulkan.exe";
#else
const wchar_t *program = L"realesrgan-ncnn-vulkan";
#endif
return exists(plat::str(plat::path(p.kit) / L"realesrgan" / program)) &&
exists(plat::str(plat::path(p.source) / L"tools" / L"tmb_texture_enhance.py"));
}
void countPack()
@@ -1624,9 +1651,14 @@ static void drawIncomplete(App &app)
{
heading(L("Some files are missing", "Des fichiers manquent"), ui::color::early);
gap(4);
std::string text = std::string(L("The launcher did not find ", "Le lanceur ne trouve pas ")) + app.missingPart +
L(" next to it. Unzip the whole download again, keeping its folders together.",
" à côté de lui. Décompressez à nouveau tout le téléchargement, en gardant ses dossiers ensemble.");
std::string text = app.missingPython
? std::string(L("Python 3 is not installed. Install your distribution's python3 package, then start "
"the launcher again.",
"Python 3 n'est pas installé. Installez le paquet python3 de votre distribution, puis "
"relancez le lanceur."))
: std::string(L("The launcher did not find ", "Le lanceur ne trouve pas ")) + app.missingPart +
L(" next to it. Unzip the whole download again, keeping its folders together.",
" à côté de lui. Décompressez à nouveau tout le téléchargement, en gardant ses dossiers ensemble.");
ui::textWrapped(text.c_str(), 19, ui::color::ink);
ui::text(app.p.release.c_str(), 15, ui::color::inkFaint);
}
@@ -2178,7 +2210,7 @@ static int selfCheck(const std::string &release, const std::string &file, const
}
if (released && app.sourceVersion != kVersion)
{
say("FAIL source\\release.ini says " + app.sourceVersion + ", the launcher " + kVersion);
say("FAIL " + plat::str(fs::path(L"source") / L"release.ini") + " says " + app.sourceVersion + ", the launcher " + kVersion);
ok = false;
}
if (app.missingPart.empty())
@@ -2316,7 +2348,11 @@ int main(int argc, char **argv)
test.crashSeconds = crashSeconds;
test.screensOnly = screensOnly;
test.enhanceOnly = enhanceOnly;
#ifdef _WIN32
test.log = _wfopen((plat::path(test.shots) / L"selftest.log").c_str(), L"w");
#else
test.log = std::fopen((plat::path(test.shots) / "selftest.log").c_str(), "w");
#endif
test.t0 = plat::now();
test.say("release %s, user folder %s", app.p.release, app.p.user);
test.build();
+16 -11
View File
@@ -1,7 +1,7 @@
#pragma once
// The launcher's operating-system layer (platform_win.cpp): everything that needs <windows.h>, kept out of the
// ImGui and SDL translation units. Strings are UTF-8.
// The launcher's operating-system layer (platform_win.cpp, platform_linux.cpp): everything that needs <windows.h> or
// POSIX, kept out of the ImGui translation units. Strings are UTF-8.
#include <atomic>
#include <cstddef>
@@ -22,26 +22,30 @@ namespace plat
std::string exeDirectory();
// The command line's arguments (without the program), UTF-8.
std::vector<std::string> arguments();
// The runner's user folder: PS2X_USER_DIR, else %APPDATA%\TMB_Recomp (created).
// The runner's user folder: PS2X_USER_DIR, else %APPDATA%\TMB_Recomp on Windows and
// $XDG_DATA_HOME/tmb_recomp (~/.local/share/...) on Linux, as the game resolves it (created).
std::string userDirectory();
std::string getEnv(const char *name);
void setEnv(const char *name, const std::string &value);
// "fr" when Windows' display language is French, else "en".
// "fr" when the system's display language is French, else "en".
std::string systemLanguage();
// A program's full path, searched on the PATH; "" when absent.
std::string findProgram(const std::string &name);
// The native Open dialog for a disc image; "" when cancelled.
// The native Open dialog for a disc image (on Linux the desktop portal or zenity); "" when cancelled.
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
const std::string &allFilesName);
// Opens a file, folder or URL as Explorer would.
// Opens a file, folder or URL as Explorer (xdg-open) would.
void open(const std::string &target);
void showInFolder(const std::string &file);
// A resource of the launcher's exe (RCDATA), or nullptr.
// A resource of the launcher's exe (RCDATA on Windows, embedded at build time on Linux), or nullptr.
const void *resource(const char *name, size_t &size);
// A child process. With output: stdout and stderr through one pipe, read line by line by a thread; started with
// CREATE_NO_WINDOW and in a job object, so kill() ends it and everything it started (and so does the launcher
// exiting). Without output: a plain GUI process (the game), not tied to the launcher.
// CREATE_NO_WINDOW and in a job object on Windows, in its own process group on Linux, so kill() ends it and
// everything it started (and so does the launcher exiting). Without output: a plain GUI process (the game), not
// tied to the launcher.
class Process
{
public:
@@ -60,7 +64,7 @@ namespace plat
std::vector<std::string> takeLines();
// Ends the process (and with output, its whole tree).
void kill();
// Asks the process's top-level windows to close (WM_CLOSE), as the window's X would.
// Asks the process's top-level windows to close (WM_CLOSE; SIGTERM on Linux), as the window's X would.
void requestClose();
// Waits until its output pipe is drained (after it exited).
void drain(int timeoutMs);
@@ -76,7 +80,8 @@ namespace plat
std::vector<std::pair<std::string, uint64_t>> listFiles(const std::string &folder, const std::string &suffix);
uint64_t freeBytes(const std::string &folder);
// An HTTP(S) GET through WinHTTP (the system's proxy settings and certificate store; nothing else linked): the
// An HTTP(S) GET through WinHTTP (the system's proxy settings and certificate store; nothing else linked), or the
// system's libcurl on Linux (loaded when first used, so the launcher starts without it): the
// body (at most maxBytes) and the status code. False with error set when the server could not be reached.
// Blocking, with short timeouts: call it from a thread.
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
+795
View File
@@ -0,0 +1,795 @@
// The launcher's Linux layer (platform.h).
#include "platform.h"
#include <SDL3/SDL.h>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <mutex>
#include <thread>
#include <type_traits>
#include <dlfcn.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/wait.h>
#include <unistd.h>
extern "C"
{
extern const unsigned char tmb_res_exo2[], tmb_res_exo2_end[];
extern const unsigned char tmb_res_ofl[], tmb_res_ofl_end[];
}
#define TMB_INCBIN(symbol, file) \
asm(".section .rodata\n.global " #symbol "\n.balign 16\n" #symbol ":\n.incbin \"" file "\"\n.global " #symbol \
"_end\n" #symbol "_end:\n.byte 0\n.previous\n")
TMB_INCBIN(tmb_res_exo2, TMB_EXO2_FILE);
TMB_INCBIN(tmb_res_ofl, TMB_OFL_FILE);
namespace plat
{
namespace
{
std::string readLink(const char *link)
{
std::string buffer(PATH_MAX, '\0');
for (;;)
{
const ssize_t n = readlink(link, buffer.data(), buffer.size());
if (n < 0)
return {};
if (static_cast<size_t>(n) < buffer.size())
{
buffer.resize(static_cast<size_t>(n));
return buffer;
}
buffer.resize(buffer.size() * 2);
}
}
const std::string g_exePath = readLink("/proc/self/exe");
std::string localeLanguage()
{
for (const char *name : {"LC_ALL", "LC_MESSAGES", "LANG"})
if (const char *v = std::getenv(name); v && *v)
return std::string(v).substr(0, 2);
return "en";
}
}
std::wstring widen(const std::string &utf8)
{
std::wstring out;
for (size_t i = 0; i < utf8.size();)
{
const unsigned char c = static_cast<unsigned char>(utf8[i]);
const int extra = c < 0x80 ? 0 : (c >> 5) == 6 ? 1 : (c >> 4) == 14 ? 2 : (c >> 3) == 30 ? 3 : -1;
if (extra < 0 || i + extra >= utf8.size() + (extra == 0 ? 1 : 0))
{
out.push_back(0xFFFD);
++i;
continue;
}
char32_t code = extra == 0 ? c : c & (0x3F >> extra);
bool valid = true;
for (int k = 1; k <= extra; ++k)
{
const unsigned char d = static_cast<unsigned char>(utf8[i + k]);
valid = valid && (d >> 6) == 2;
code = (code << 6) | (d & 0x3F);
}
out.push_back(valid ? static_cast<wchar_t>(code) : 0xFFFD);
i += valid ? extra + 1 : 1;
}
return out;
}
std::string narrow(const std::wstring &wide)
{
std::string out;
for (const wchar_t w : wide)
{
const char32_t c = static_cast<char32_t>(w);
if (c < 0x80)
out.push_back(static_cast<char>(c));
else if (c < 0x800)
out += {static_cast<char>(0xC0 | (c >> 6)), static_cast<char>(0x80 | (c & 0x3F))};
else if (c < 0x10000)
out += {static_cast<char>(0xE0 | (c >> 12)), static_cast<char>(0x80 | ((c >> 6) & 0x3F)),
static_cast<char>(0x80 | (c & 0x3F))};
else
out += {static_cast<char>(0xF0 | (c >> 18)), static_cast<char>(0x80 | ((c >> 12) & 0x3F)),
static_cast<char>(0x80 | ((c >> 6) & 0x3F)), static_cast<char>(0x80 | (c & 0x3F))};
}
return out;
}
std::filesystem::path path(const std::string &utf8) { return std::filesystem::path(utf8); }
std::string str(const std::filesystem::path &p) { return p.string(); }
std::string exeDirectory()
{
return g_exePath.empty() ? "." : std::filesystem::path(g_exePath).parent_path().string();
}
std::vector<std::string> arguments()
{
std::vector<std::string> out;
std::ifstream in("/proc/self/cmdline", std::ios::binary);
std::string arg;
bool first = true;
while (std::getline(in, arg, '\0'))
{
if (!first)
out.push_back(arg);
first = false;
}
return out;
}
std::string getEnv(const char *name)
{
const char *v = std::getenv(name);
return v ? v : "";
}
void setEnv(const char *name, const std::string &value)
{
if (value.empty())
unsetenv(name);
else
::setenv(name, value.c_str(), 1);
}
std::string userDirectory()
{
std::filesystem::path dir;
if (const std::string forced = getEnv("PS2X_USER_DIR"); !forced.empty())
dir = forced;
else if (const std::string data = getEnv("XDG_DATA_HOME"); !data.empty())
dir = std::filesystem::path(data) / "tmb_recomp";
else if (const std::string home = getEnv("HOME"); !home.empty())
dir = std::filesystem::path(home) / ".local" / "share" / "tmb_recomp";
else
dir = std::filesystem::path(exeDirectory()) / "user";
std::error_code ec;
std::filesystem::create_directories(dir, ec);
return std::filesystem::absolute(dir, ec).lexically_normal().string();
}
std::string systemLanguage() { return localeLanguage() == "fr" ? "fr" : "en"; }
std::string systemGameLanguage()
{
const std::string l = localeLanguage();
return l == "fr" || l == "de" || l == "es" || l == "it" ? l : "en";
}
std::string findProgram(const std::string &name)
{
if (name.find('/') != std::string::npos)
return access(name.c_str(), X_OK) == 0 ? name : std::string();
const std::string pathVar = getEnv("PATH").empty() ? "/usr/local/bin:/usr/bin:/bin" : getEnv("PATH");
size_t start = 0;
for (;;)
{
const size_t end = pathVar.find(':', start);
std::string dir = pathVar.substr(start, end == std::string::npos ? std::string::npos : end - start);
if (!dir.empty())
{
const std::string candidate = dir + "/" + name;
struct stat st{};
if (stat(candidate.c_str(), &st) == 0 && S_ISREG(st.st_mode) && access(candidate.c_str(), X_OK) == 0)
return candidate;
}
if (end == std::string::npos)
return {};
start = end + 1;
}
}
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
const std::string &allFilesName)
{
(void)title;
struct Result
{
std::atomic<bool> done{false};
std::string file, error;
} result;
const std::string discs = filterName + " (*.iso, *.bin, *.cue)";
const SDL_DialogFileFilter filters[] = {{discs.c_str(), "iso;bin;cue;ISO;BIN;CUE"}, {allFilesName.c_str(), "*"}};
SDL_ShowOpenFileDialog(
[](void *user, const char *const *files, int)
{
auto *r = static_cast<Result *>(user);
if (!files)
r->error = SDL_GetError();
else if (files[0])
r->file = files[0];
r->done = true;
},
&result, static_cast<SDL_Window *>(ownerWindow), filters, 2, nullptr, false);
while (!result.done)
{
SDL_PumpEvents();
SDL_Delay(20);
}
if (result.file.empty() && !result.error.empty())
messageBox("TMB Launcher", "No file dialog could open (" + result.error +
"). Install zenity or your desktop's xdg-desktop-portal, then try again.");
return result.file;
}
namespace
{
void spawnDetached(const std::vector<std::string> &argv)
{
std::vector<char *> args;
for (const std::string &a : argv)
args.push_back(const_cast<char *>(a.c_str()));
args.push_back(nullptr);
const pid_t pid = fork();
if (pid == 0)
{
if (fork() == 0)
{
setsid();
const int null = ::open("/dev/null", O_RDWR | O_CLOEXEC);
if (null >= 0)
{
dup2(null, 0);
dup2(null, 1);
dup2(null, 2);
}
execvp(args[0], args.data());
}
_exit(0);
}
if (pid > 0)
waitpid(pid, nullptr, 0);
}
}
void open(const std::string &target) { spawnDetached({"xdg-open", target}); }
void showInFolder(const std::string &file)
{
spawnDetached({"xdg-open", std::filesystem::path(file).parent_path().string()});
}
const void *resource(const char *name, size_t &size)
{
size = 0;
if (std::strcmp(name, "EXO2") == 0)
{
size = static_cast<size_t>(tmb_res_exo2_end - tmb_res_exo2);
return tmb_res_exo2;
}
if (std::strcmp(name, "OFL") == 0)
{
size = static_cast<size_t>(tmb_res_ofl_end - tmb_res_ofl);
return tmb_res_ofl;
}
return nullptr;
}
double now()
{
using namespace std::chrono;
return duration<double>(steady_clock::now().time_since_epoch()).count();
}
std::vector<std::pair<std::string, uint64_t>> listFiles(const std::string &folder, const std::string &suffix)
{
std::vector<std::pair<std::string, uint64_t>> out;
std::error_code ec;
for (const auto &entry : std::filesystem::directory_iterator(folder, ec))
{
const std::string name = entry.path().filename().string();
if (!entry.is_regular_file(ec) || name.size() < suffix.size() ||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
continue;
struct stat st{};
if (stat(entry.path().c_str(), &st) != 0)
continue;
const uint64_t ticks = (static_cast<uint64_t>(st.st_mtim.tv_sec) + 11644473600ull) * 10000000ull +
static_cast<uint64_t>(st.st_mtim.tv_nsec) / 100u;
out.emplace_back(folder + "/" + name, ticks);
}
return out;
}
uint64_t freeBytes(const std::string &folder)
{
struct statvfs st{};
if (statvfs(folder.c_str(), &st) != 0)
return 0;
return static_cast<uint64_t>(st.f_bavail) * st.f_frsize;
}
struct Process::Impl
{
pid_t pid = 0;
bool group = false, reaped = false;
bool closeAsked = false; // requestClose's SIGTERM: sent once
int status = 0;
int readFd = -1;
std::thread reader;
std::atomic<bool> stop{false};
std::mutex mutex;
std::deque<std::string> lines;
std::atomic<bool> readerDone{true};
~Impl()
{
if (group && pid > 0 && !reap())
{
::kill(-pid, SIGKILL);
waitpid(pid, &status, 0);
reaped = true;
}
if (reader.joinable())
{
for (int i = 0; i < 200 && !readerDone; ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
stop = true;
reader.join();
}
if (readFd >= 0)
close(readFd);
}
bool reap()
{
if (reaped || pid <= 0)
return reaped;
const pid_t got = waitpid(pid, &status, WNOHANG);
if (got == pid || (got < 0 && errno == ECHILD))
reaped = true;
return reaped;
}
void readLoop()
{
std::string pending;
char buffer[4096];
while (!stop)
{
pollfd p{readFd, POLLIN, 0};
const int ready = poll(&p, 1, 100);
if (ready < 0 && errno == EINTR)
continue;
if (ready == 0)
continue;
if (ready < 0)
break;
const ssize_t got = read(readFd, buffer, sizeof(buffer));
if (got < 0 && errno == EINTR)
continue;
if (got <= 0)
break;
pending.append(buffer, static_cast<size_t>(got));
size_t at;
while ((at = pending.find('\n')) != std::string::npos)
{
std::string line = pending.substr(0, at);
if (!line.empty() && line.back() == '\r')
line.pop_back();
pending.erase(0, at + 1);
std::lock_guard<std::mutex> lock(mutex);
lines.push_back(std::move(line));
}
}
if (!pending.empty())
{
std::lock_guard<std::mutex> lock(mutex);
lines.push_back(pending);
}
readerDone = true;
}
};
Process::Process() : impl(std::make_unique<Impl>()) {}
Process::~Process() = default;
bool Process::start(const std::string &exe, const std::vector<std::string> &args, const std::string &cwd,
bool captureOutput, std::string &error)
{
impl = std::make_unique<Impl>();
std::vector<std::string> argv{exe};
argv.insert(argv.end(), args.begin(), args.end());
std::vector<char *> cargv;
for (std::string &a : argv)
cargv.push_back(a.data());
cargv.push_back(nullptr);
int out[2] = {-1, -1}, report[2] = {-1, -1};
if ((captureOutput && pipe2(out, O_CLOEXEC) != 0) || pipe2(report, O_CLOEXEC) != 0)
{
error = std::strerror(errno);
for (int fd : {out[0], out[1], report[0], report[1]})
if (fd >= 0)
close(fd);
return false;
}
const pid_t parent = getpid();
const pid_t pid = fork();
if (pid < 0)
{
error = std::strerror(errno);
for (int fd : {out[0], out[1], report[0], report[1]})
if (fd >= 0)
close(fd);
return false;
}
if (pid == 0)
{
setsid();
if (captureOutput)
{
prctl(PR_SET_PDEATHSIG, SIGKILL);
if (getppid() != parent)
_exit(127);
}
sigset_t none;
sigemptyset(&none);
sigprocmask(SIG_SETMASK, &none, nullptr);
const int null = ::open("/dev/null", O_RDWR | O_CLOEXEC);
if (null >= 0)
{
dup2(null, 0);
if (!captureOutput)
{
dup2(null, 1);
dup2(null, 2);
}
}
if (captureOutput)
{
dup2(out[1], 1);
dup2(out[1], 2);
}
if (!cwd.empty() && chdir(cwd.c_str()) != 0)
{
const int e = errno;
(void)!write(report[1], &e, sizeof(e));
_exit(127);
}
execvp(cargv[0], cargv.data());
const int e = errno;
(void)!write(report[1], &e, sizeof(e));
_exit(127);
}
close(report[1]);
if (captureOutput)
close(out[1]);
int childErrno = 0;
ssize_t n;
do
n = read(report[0], &childErrno, sizeof(childErrno));
while (n < 0 && errno == EINTR);
close(report[0]);
if (n == sizeof(childErrno))
{
waitpid(pid, nullptr, 0);
if (captureOutput)
close(out[0]);
error = exe + ": " + std::strerror(childErrno);
return false;
}
impl->pid = pid;
impl->closeAsked = false;
impl->group = captureOutput;
if (captureOutput)
{
impl->readFd = out[0];
impl->readerDone = false;
impl->reader = std::thread([self = impl.get()] { self->readLoop(); });
}
return true;
}
bool Process::running() { return impl->pid > 0 && !impl->reap(); }
long Process::exitCode()
{
if (impl->pid <= 0 || !impl->reap())
return -1;
if (WIFEXITED(impl->status))
return WEXITSTATUS(impl->status);
if (WIFSIGNALED(impl->status))
return 128 + WTERMSIG(impl->status);
return -1;
}
uint32_t Process::pid() const { return static_cast<uint32_t>(impl->pid); }
std::vector<std::string> Process::takeLines()
{
std::lock_guard<std::mutex> lock(impl->mutex);
std::vector<std::string> out(impl->lines.begin(), impl->lines.end());
impl->lines.clear();
return out;
}
void Process::kill()
{
if (impl->pid <= 0)
return;
if (impl->group)
::kill(-impl->pid, SIGKILL);
else if (!impl->reap())
::kill(impl->pid, SIGKILL);
}
void Process::drain(int timeoutMs)
{
const double end = now() + timeoutMs / 1000.0;
while (!impl->readerDone && now() < end)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void Process::requestClose()
{
// Once: the game's SDL turns SIGTERM into a quit, then restores the default handlers as it shuts down, so a
// second one (a caller asking every frame, as WM_CLOSE may be on Windows) would kill it mid-shutdown (exit 143).
if (impl->pid > 0 && !impl->closeAsked && !impl->reap())
{
impl->closeAsked = true;
::kill(impl->pid, SIGTERM);
}
}
namespace
{
using CURL = void;
struct curl_slist;
using curl_off_t = long long;
constexpr int kOptUrl = 10002, kOptUserAgent = 10018, kOptHttpHeader = 10023, kOptWriteFunction = 20011,
kOptWriteData = 10001, kOptFollow = 52, kOptMaxRedirs = 68, kOptConnectTimeoutMs = 156,
kOptLowSpeedLimit = 19, kOptLowSpeedTime = 20, kOptNoSignal = 99, kOptProtocols = 181,
kOptRedirProtocols = 182, kOptErrorBuffer = 10010, kOptXferInfoFunction = 20219,
kOptXferInfoData = 10057, kOptNoProgress = 43;
constexpr int kInfoResponseCode = 0x200000 + 2, kInfoContentLength = 0x600000 + 15;
constexpr long kProtoHttp = 1, kProtoHttps = 2;
constexpr int kCurlOk = 0, kErrorSize = 256;
struct Curl
{
bool loaded = false;
int (*global_init)(long) = nullptr;
CURL *(*easy_init)() = nullptr;
int (*easy_setopt)(CURL *, int, ...) = nullptr;
int (*easy_perform)(CURL *) = nullptr;
int (*easy_getinfo)(CURL *, int, ...) = nullptr;
void (*easy_cleanup)(CURL *) = nullptr;
const char *(*easy_strerror)(int) = nullptr;
curl_slist *(*slist_append)(curl_slist *, const char *) = nullptr;
void (*slist_free_all)(curl_slist *) = nullptr;
Curl()
{
void *lib = nullptr;
for (const char *name : {"libcurl.so.4", "libcurl-gnutls.so.4", "libcurl-nss.so.4", "libcurl.so"})
if ((lib = dlopen(name, RTLD_NOW | RTLD_LOCAL)))
break;
if (!lib)
return;
auto get = [&](auto &fn, const char *name)
{ fn = reinterpret_cast<std::remove_reference_t<decltype(fn)>>(dlsym(lib, name)); return fn != nullptr; };
loaded = get(global_init, "curl_global_init") && get(easy_init, "curl_easy_init") &&
get(easy_setopt, "curl_easy_setopt") && get(easy_perform, "curl_easy_perform") &&
get(easy_getinfo, "curl_easy_getinfo") && get(easy_cleanup, "curl_easy_cleanup") &&
get(easy_strerror, "curl_easy_strerror") && get(slist_append, "curl_slist_append") &&
get(slist_free_all, "curl_slist_free_all");
if (loaded)
global_init(3);
}
};
Curl &curl()
{
static Curl c;
return c;
}
struct Transfer
{
CURL *handle = nullptr;
long status = 0;
uint64_t length = 0;
bool sized = false, aborted = false;
const std::function<bool(Transfer &, const char *, size_t)> *sink = nullptr;
const std::atomic<bool> *cancel = nullptr;
void readHeaders()
{
if (sized)
return;
sized = true;
curl().easy_getinfo(handle, kInfoResponseCode, &status);
curl_off_t n = -1;
if (curl().easy_getinfo(handle, kInfoContentLength, &n) == kCurlOk && n > 0)
length = static_cast<uint64_t>(n);
}
};
size_t writeCallback(char *data, size_t size, size_t count, void *user)
{
auto *t = static_cast<Transfer *>(user);
t->readHeaders();
const size_t n = size * count;
if (!(*t->sink)(*t, data, n))
{
t->aborted = true;
return 0;
}
return n;
}
int progressCallback(void *user, curl_off_t, curl_off_t, curl_off_t, curl_off_t)
{
auto *t = static_cast<Transfer *>(user);
if (!t->cancel || !t->cancel->load())
return 0;
t->aborted = true;
return 1;
}
bool httpRequest(const std::string &url, const std::string &userAgent, const std::vector<std::string> &headers,
int receiveMs, long &status, std::string &error,
const std::function<bool(Transfer &, const char *, size_t)> &sink,
const std::atomic<bool> *cancel = nullptr)
{
status = 0;
Curl &c = curl();
if (!c.loaded)
{
error = "libcurl is not installed";
return false;
}
if (url.rfind("https://", 0) != 0 && url.rfind("http://", 0) != 0)
{
error = "bad URL";
return false;
}
Transfer t;
t.handle = c.easy_init();
if (!t.handle)
{
error = "libcurl could not start";
return false;
}
t.sink = &sink;
t.cancel = cancel;
curl_slist *list = nullptr;
for (const std::string &h : headers)
list = c.slist_append(list, h.c_str());
char errorBuffer[kErrorSize] = {};
const long https = url.rfind("https://", 0) == 0;
c.easy_setopt(t.handle, kOptUrl, url.c_str());
c.easy_setopt(t.handle, kOptUserAgent, userAgent.c_str());
c.easy_setopt(t.handle, kOptHttpHeader, list);
c.easy_setopt(t.handle, kOptFollow, 1L);
c.easy_setopt(t.handle, kOptMaxRedirs, 10L);
c.easy_setopt(t.handle, kOptProtocols, kProtoHttp | kProtoHttps);
c.easy_setopt(t.handle, kOptRedirProtocols, https ? kProtoHttps : kProtoHttp | kProtoHttps);
c.easy_setopt(t.handle, kOptConnectTimeoutMs, 5000L);
c.easy_setopt(t.handle, kOptLowSpeedLimit, 1L);
c.easy_setopt(t.handle, kOptLowSpeedTime, static_cast<long>((receiveMs + 999) / 1000));
c.easy_setopt(t.handle, kOptNoSignal, 1L);
c.easy_setopt(t.handle, kOptErrorBuffer, errorBuffer);
c.easy_setopt(t.handle, kOptWriteFunction, &writeCallback);
c.easy_setopt(t.handle, kOptWriteData, &t);
if (cancel)
{
c.easy_setopt(t.handle, kOptXferInfoFunction, &progressCallback);
c.easy_setopt(t.handle, kOptXferInfoData, &t);
c.easy_setopt(t.handle, kOptNoProgress, 0L);
}
const int code = c.easy_perform(t.handle);
t.readHeaders();
status = t.status;
c.easy_cleanup(t.handle);
if (list)
c.slist_free_all(list);
if (t.aborted)
return false;
if (code != kCurlOk)
{
error = errorBuffer[0] ? errorBuffer : c.easy_strerror(code);
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();
return httpRequest(url, userAgent, {"Accept: application/vnd.github+json", "X-GitHub-Api-Version: 2022-11-28"},
8000, status, error, [&](Transfer &, 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;
std::FILE *out = std::fopen(file.c_str(), "wb");
if (!out)
{
error = std::strerror(errno);
return false;
}
long status = 0;
bool ok = httpRequest(url, userAgent, {"Accept: application/octet-stream"}, 30000, status, error,
[&](Transfer &t, const char *data, size_t n)
{
total = t.length;
if (t.status != 200)
return false;
if (cancel.load())
{
error = "stopped";
return false;
}
if (std::fwrite(data, 1, n, out) != n)
{
error = std::strerror(errno);
return false;
}
done += n;
if (done.load() <= maxBytes)
return true;
error = "download too large";
return false; }, &cancel);
if (!ok && error.empty() && cancel.load())
error = "stopped";
if (std::fclose(out) != 0 && ok)
{
ok = false;
error = std::strerror(errno);
}
if (ok && status != 200)
{
ok = false;
error = "HTTP " + std::to_string(status);
}
else if (!ok && error.empty())
error = status != 200 ? "HTTP " + std::to_string(status) : "download failed";
if (!ok)
std::remove(file.c_str());
return ok;
}
std::string exePath() { return g_exePath; }
void messageBox(const std::string &title, const std::string &text)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.c_str(), text.c_str(), nullptr);
}
}
+17
View File
@@ -110,6 +110,23 @@ namespace plat
return PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_FRENCH ? "fr" : "en";
}
std::string findProgram(const std::string &name)
{
std::wstring buffer(MAX_PATH, L'\0');
for (;;)
{
const DWORD n = SearchPathW(nullptr, widen(name).c_str(), L".exe", static_cast<DWORD>(buffer.size()), buffer.data(), nullptr);
if (n == 0)
return {};
if (n < buffer.size())
{
buffer.resize(n);
return narrow(buffer);
}
buffer.resize(n);
}
}
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
const std::string &allFilesName)
{
+12 -1
View File
@@ -41,10 +41,21 @@ namespace ui
std::snprintf(cfg.Name, sizeof(cfg.Name), "Exo 2");
fonts.text = io.Fonts->AddFontFromMemoryTTF(const_cast<void *>(exo), static_cast<int>(size), S(20), &cfg);
}
#ifdef _WIN32
const std::string windir = plat::getEnv("WINDIR").empty() ? "C:\\Windows" : plat::getEnv("WINDIR");
std::vector<std::string> monoFiles;
for (const char *name : {"CascadiaMono.ttf", "CascadiaCode.ttf", "consola.ttf"})
monoFiles.push_back(windir + "\\Fonts\\" + name);
#else
const std::vector<std::string> monoFiles = {
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", "/usr/share/fonts/TTF/DejaVuSansMono.ttf",
"/usr/share/fonts/dejavu-sans-mono-fonts/DejaVuSansMono.ttf", "/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
"/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
"/usr/share/fonts/liberation-mono/LiberationMono-Regular.ttf", "/usr/share/fonts/TTF/LiberationMono-Regular.ttf",
"/usr/share/fonts/noto/NotoSansMono-Regular.ttf", "/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf"};
#endif
for (const std::string &file : monoFiles)
{
const std::string file = windir + "\\Fonts\\" + name;
std::error_code ec;
if (std::filesystem::exists(plat::path(file), ec))
{
+131
View File
@@ -0,0 +1,131 @@
{
"$schema": "https://recomplauncher.com/schema/recomplauncher.json",
"format": 1,
"name": "Twisted Metal: Black",
"repo": "TheBozos/TMB_Recomp",
"inputs": [
{
"id": "game",
"label": "Your disc image of the USA release, serial SCUS-97101 (.iso, or .bin/.cue).",
"formats": [{ "type": "file" }],
"check": { "iso9660": "SCUS_971.01", "ids": ["SCUS-97101"] },
"dumps": [{ "name": "USA", "size": 3799744512, "crc32": "347e93f9" }]
}
],
"prepare": {
"program": ["kit/python/python.exe", "kit/python3"],
"args": ["-I", "-X", "utf8", "{install}/source/tools/tmb_build.py", "--disc={input:game}",
"--out", "{install}/build", "--game", "{install}/game", "--progress-lines"],
"label": "Building the game from your disc",
"done": ["{install}/game/built_from.ini"],
"keeps_copy": true
},
"start": {
"program": ["game/tmb.exe", "game/tmb"],
"args": ["--elf", "{install}/game/SCUS_971.01", "--iso", "{install}/game/disc.iso"],
"env": { "PS2X_USER_DIR": "{data}" }
},
"folders": {
"game": [{ "path": "{install}/game" }],
"saves": [{ "path": "{data}/mc0" }],
"logs": [{ "path": "{data}/logs" }]
},
"saves": ["{data}/mc0", "{data}/mc1"],
"config": [{ "format": "ini", "file": [{ "path": "{data}/video.ini" }] }],
"settings": [
{
"id": "mode", "label": "Display mode",
"choices": [
{ "label": "Windowed", "set": { "video/mode": "windowed" } },
{ "label": "Borderless", "set": { "video/mode": "borderless" } },
{ "label": "Full screen", "set": { "video/mode": "fullscreen" } }
],
"defaults": { "video/mode": "windowed" }
},
{
"id": "widescreen", "label": "Widescreen",
"help": "16:9 with more of the arena at the sides in one- and two-player matches; menus, movies and four-player matches stay 4:3.",
"choices": [
{ "label": "Off (4:3)", "set": { "video/widescreen": "off" } },
{ "label": "On (16:9)", "set": { "video/widescreen": "on" } }
],
"defaults": { "video/widescreen": "off" }
},
{
"id": "frame_rate", "label": "Frame rate",
"help": "Above 60, frames between the game's are drawn in between; the game itself still runs at its own speed.",
"choices": [
{ "label": "60 (the game's)", "set": { "video/frame_rate": "game" } },
{ "label": "Monitor's refresh", "set": { "video/frame_rate": "monitor" } },
{ "label": "120", "set": { "video/frame_rate": "120" } },
{ "label": "144", "set": { "video/frame_rate": "144" } },
{ "label": "240", "set": { "video/frame_rate": "240" } }
],
"defaults": { "video/frame_rate": "game" }
},
{
"id": "render_scale", "label": "Render scale",
"help": "The 3D drawn at this many times the window's size.",
"choices": [
{ "label": "1x", "set": { "video/render_scale": "1" } },
{ "label": "1.5x", "set": { "video/render_scale": "1.5" } },
{ "label": "2x", "set": { "video/render_scale": "2" } },
{ "label": "3x", "set": { "video/render_scale": "3" } },
{ "label": "4x", "set": { "video/render_scale": "4" } }
],
"defaults": { "video/render_scale": "1" }
},
{
"id": "anti_aliasing", "label": "Anti-aliasing",
"help": "Smooths the edges of the 3D (MSAA).",
"choices": [
{ "label": "Off", "set": { "video/anti_aliasing": "off" } },
{ "label": "2x", "set": { "video/anti_aliasing": "2x" } },
{ "label": "4x", "set": { "video/anti_aliasing": "4x" } },
{ "label": "8x", "set": { "video/anti_aliasing": "8x" } }
],
"defaults": { "video/anti_aliasing": "off" }
},
{
"id": "texture_smoothing", "label": "Texture smoothing",
"help": "Off samples textures as the PS2 does; the others stop distant textures shimmering.",
"choices": [
{ "label": "Off", "set": { "video/texture_smoothing": "off" } },
{ "label": "Trilinear", "set": { "video/texture_smoothing": "trilinear" } },
{ "label": "4x anisotropic", "set": { "video/texture_smoothing": "4x" } },
{ "label": "8x anisotropic", "set": { "video/texture_smoothing": "8x" } },
{ "label": "16x anisotropic", "set": { "video/texture_smoothing": "16x" } }
],
"defaults": { "video/texture_smoothing": "off" }
},
{
"id": "pause_in_background", "label": "Pause in the background", "advanced": true,
"help": "Holds the game while another window has the focus.",
"choices": [
{ "label": "Off", "set": { "video/pause_in_background": "off" } },
{ "label": "On", "set": { "video/pause_in_background": "on" } }
],
"defaults": { "video/pause_in_background": "off" }
},
{
"id": "fast_forward", "label": "Fast-forward speed", "advanced": true,
"help": "The game's speed while fast forward is held (` on the keyboard, or the touchpad).",
"choices": [
{ "label": "2x", "set": { "video/fast_forward": "2x" } },
{ "label": "3x", "set": { "video/fast_forward": "3x" } },
{ "label": "5x", "set": { "video/fast_forward": "5x" } },
{ "label": "10x", "set": { "video/fast_forward": "10x" } },
{ "label": "Unlimited", "set": { "video/fast_forward": "unlimited" } }
],
"defaults": { "video/fast_forward": "3x" }
}
],
"actions": [
{ "id": "logs", "label": "Logs", "help": "The game's logs, for a bug report.", "open": "logs" }
],
"looks": { "graphics": "opengl" },
"system": {
"windows": { "version": "10", "graphics": { "opengl": "3.3" } },
"linux": { "graphics": { "opengl": "3.3" } }
}
}
+1146 -1120
View File
File diff suppressed because it is too large. Load diff
+496 -461
View File
@@ -1,461 +1,496 @@
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
//
// What the game keeps, from its own code:
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
// (aiUpdateInputs, 0x1014A0).
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
// reaches 0).
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
// bar, Hud::build4PEnergyBar).
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
#include "tmb_port.h"
#include "bozo/app/determinism.h"
#if defined(BOZO_SETTINGS_UI)
#include "bozo/app/settings_tabs.h"
#include "imgui.h"
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace tmb::cheats
{
namespace
{
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
constexpr int kMaxPlayers = 4;
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
constexpr struct
{
uint32_t offset, count;
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
// One bit per player (bit 0: player 1).
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)
std::atomic<uint32_t> g_theGame{0};
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value = 0;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
float flt(const uint8_t *rdram, uint32_t address)
{
float value = 0.0f;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
int playerCount(const uint8_t *rdram, uint32_t game)
{
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
}
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
{
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
}
// The players whose bit is set in `mask` that own `vehicle`.
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
{
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (mask == 0u || vehicle == 0u)
return false;
for (int player = 0; player < playerCount(rdram, game); ++player)
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
return true;
return false;
}
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
// every player.
uint32_t envMask(const char *name)
{
const char *value = std::getenv(name);
if (!value || !*value || std::string(value) == "0")
return 0u;
uint32_t mask = 0u;
for (const char *c = value; *c; ++c)
{
if (*c < '1' || *c > '0' + kMaxPlayers)
return (1u << kMaxPlayers) - 1u;
mask |= 1u << (*c - '1');
}
return mask;
}
float envFloat(const char *name)
{
const char *value = std::getenv(name);
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
}
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_noAi.load(std::memory_order_relaxed))
{
ctx->pc = kAiUpdateFrozenInput;
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
return;
}
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
}
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
// so nothing the car fires or detonates is counted (and the selected weapon stays).
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_decrements.fetch_add(1, std::memory_order_relaxed);
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
{
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
ctx->pc = getRegU32(ctx, 31); // jr $ra
return;
}
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
}
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
// since then stay, the card is written only when the player saves).
void applyUnlocks(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
const uint32_t progress = shell + kShellProgress;
if (g_unlockAll.load(std::memory_order_relaxed))
{
for (const auto &locks : kLocks)
for (uint32_t i = 0; i < locks.count; ++i)
{
const uint32_t address = progress + locks.offset + i * 4u;
if (word(rdram, address) == 1u)
{
setWord(rdram, address, 0u);
g_unlocked.push_back(address);
}
}
}
else if (!g_unlocked.empty())
{
for (const uint32_t address : g_unlocked)
if (word(rdram, address) == 0u)
setWord(rdram, address, 1u);
g_unlocked.clear();
}
}
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
applyUnlocks(rdram, getRegU32(ctx, 28));
Screen(rdram, ctx, runtime);
}
#if defined(BOZO_SETTINGS_UI)
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
{
ImGui::PushID(label);
uint32_t mask = flags.load(std::memory_order_relaxed);
// On for every player of the match (every player when there is none yet).
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
bool all = (mask & present) == present;
if (ImGui::Checkbox(label, &all))
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
for (int player = 0; player < std::max(players, 1); ++player)
{
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
bool on = mask >> player & 1u;
char name[8];
std::snprintf(name, sizeof(name), "P%d", player + 1);
if (ImGui::Checkbox(name, &on))
mask = on ? mask | 1u << player : mask & ~(1u << player);
}
flags.store(mask, std::memory_order_relaxed);
ImGui::PopID();
}
void drawTab()
{
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;
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
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);
perPlayer("Infinite energy", g_infiniteEnergy, players);
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
ImGui::SeparatorText("Opponents");
bool noAi = g_noAi.load(std::memory_order_relaxed);
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
g_noAi.store(noAi, std::memory_order_relaxed);
float cap = g_enemyCap.load(std::memory_order_relaxed);
bool weak = cap >= 0.0f;
if (ImGui::Checkbox("Weak enemies", &weak))
cap = weak ? 10.0f : -1.0f;
if (weak)
{
ImGui::SameLine();
ImGui::SetNextItemWidth(200.0f);
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
}
g_enemyCap.store(cap, std::memory_order_relaxed);
if (rdram && players)
{
const uint32_t car = playerVehicle(rdram, game, 0);
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
}
}
#endif
}
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);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (game == 0u)
return;
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
// tab would (checks that each acts while playing, not only from launch).
static const double s_toggle = []
{
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0 && !bozo::det::enabled()) // deterministic mode: nothing the user does may change the run
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
static bool s_on = false;
if (now >= s_next)
{
s_next = now + s_toggle;
s_on = !s_on;
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
g_infiniteHealth.store(all);
g_infiniteAmmo.store(all);
g_infiniteEnergy.store(all);
g_noAi.store(s_on);
g_enemyCap.store(s_on ? 10.0f : -1.0f);
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
}
}
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
const int players = playerCount(rdram, game);
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
if (car == 0u)
continue;
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
// Topped up while alive (a car already dead is left to respawn).
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
setFlt(rdram, car + kHealth, most);
if (energy >> player & 1u)
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
if (player == 0 && playerCap >= 0.0f)
{
static uint32_t s_frames = 0;
if (++s_frames % 250u == 0u)
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
if (now > playerCap)
setFlt(rdram, car + kHealth, playerCap);
}
}
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
if (enemyCap >= 0.0f)
{
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
static uint32_t s_enemyFrames = 0;
const bool log = ++s_enemyFrames % 500u == 0u;
std::string line;
for (int32_t index = 0; index < count; ++index)
{
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
const float now = flt(rdram, vehicle + kHealth);
if (log)
{
char text[48];
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
line += text;
}
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
setFlt(rdram, vehicle + kHealth, enemyCap);
}
if (log)
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
}
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
static uint32_t s_logFrames = 0;
if (s_log && ++s_logFrames % 250u == 0u)
{
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
g_decrementsSkipped.exchange(0));
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
std::string counts;
for (uint32_t slot = 1; slot <= 8; ++slot)
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
}
}
}
void install(tmb::Registry &runtime)
{
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"));
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
#if defined(BOZO_SETTINGS_UI)
bozo::app::ui::registerTab("Cheats", &drawTab);
#endif
}
}
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
//
// What the game keeps, from its own code:
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
// (aiUpdateInputs, 0x1014A0).
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
// reaches 0).
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
// bar, Hud::build4PEnergyBar).
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
#include "bozo/state.h"
#include "tmb_port.h"
#include "bozo/app/determinism.h"
#if defined(BOZO_SETTINGS_UI)
#include "bozo/app/settings_tabs.h"
#include "imgui.h"
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace tmb::cheats
{
namespace
{
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
constexpr int kMaxPlayers = 4;
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
constexpr struct
{
uint32_t offset, count;
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
// One bit per player (bit 0: player 1).
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)
std::atomic<uint32_t> g_theGame{0};
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value = 0;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
float flt(const uint8_t *rdram, uint32_t address)
{
float value = 0.0f;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
int playerCount(const uint8_t *rdram, uint32_t game)
{
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
}
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
{
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
}
// The players whose bit is set in `mask` that own `vehicle`.
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
{
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (mask == 0u || vehicle == 0u)
return false;
for (int player = 0; player < playerCount(rdram, game); ++player)
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
return true;
return false;
}
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
// every player.
uint32_t envMask(const char *name)
{
const char *value = std::getenv(name);
if (!value || !*value || std::string(value) == "0")
return 0u;
uint32_t mask = 0u;
for (const char *c = value; *c; ++c)
{
if (*c < '1' || *c > '0' + kMaxPlayers)
return (1u << kMaxPlayers) - 1u;
mask |= 1u << (*c - '1');
}
return mask;
}
float envFloat(const char *name)
{
const char *value = std::getenv(name);
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
}
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_noAi.load(std::memory_order_relaxed))
{
ctx->pc = kAiUpdateFrozenInput;
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
return;
}
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
}
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
// so nothing the car fires or detonates is counted (and the selected weapon stays).
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_decrements.fetch_add(1, std::memory_order_relaxed);
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
{
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
ctx->pc = getRegU32(ctx, 31); // jr $ra
return;
}
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
}
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
// since then stay, the card is written only when the player saves).
void applyUnlocks(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
const uint32_t progress = shell + kShellProgress;
if (g_unlockAll.load(std::memory_order_relaxed))
{
for (const auto &locks : kLocks)
for (uint32_t i = 0; i < locks.count; ++i)
{
const uint32_t address = progress + locks.offset + i * 4u;
if (word(rdram, address) == 1u)
{
setWord(rdram, address, 0u);
g_unlocked.push_back(address);
}
}
}
else if (!g_unlocked.empty())
{
for (const uint32_t address : g_unlocked)
if (word(rdram, address) == 0u)
setWord(rdram, address, 1u);
g_unlocked.clear();
}
}
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
applyUnlocks(rdram, getRegU32(ctx, 28));
Screen(rdram, ctx, runtime);
}
#if defined(BOZO_SETTINGS_UI)
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
{
ImGui::PushID(label);
uint32_t mask = flags.load(std::memory_order_relaxed);
// On for every player of the match (every player when there is none yet).
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
bool all = (mask & present) == present;
if (ImGui::Checkbox(label, &all))
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
for (int player = 0; player < std::max(players, 1); ++player)
{
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
bool on = mask >> player & 1u;
char name[8];
std::snprintf(name, sizeof(name), "P%d", player + 1);
if (ImGui::Checkbox(name, &on))
mask = on ? mask | 1u << player : mask & ~(1u << player);
}
flags.store(mask, std::memory_order_relaxed);
ImGui::PopID();
}
void drawTab()
{
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;
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
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);
perPlayer("Infinite energy", g_infiniteEnergy, players);
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
ImGui::SeparatorText("Opponents");
bool noAi = g_noAi.load(std::memory_order_relaxed);
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
g_noAi.store(noAi, std::memory_order_relaxed);
float cap = g_enemyCap.load(std::memory_order_relaxed);
bool weak = cap >= 0.0f;
if (ImGui::Checkbox("Weak enemies", &weak))
cap = weak ? 10.0f : -1.0f;
if (weak)
{
ImGui::SameLine();
ImGui::SetNextItemWidth(200.0f);
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
}
g_enemyCap.store(cap, std::memory_order_relaxed);
if (rdram && players)
{
const uint32_t car = playerVehicle(rdram, game, 0);
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
}
}
#endif
}
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
// The Cheats tab's switches, for the game's own Options screen (runtime/tmb_menu.cpp): read, and set at once.
struct Values
{
bool unlockAll = false, noAi = false;
uint32_t health = 0u, ammo = 0u, energy = 0u; // one bit per player
float enemyCap = -1.0f; // weak enemies: < 0 off
};
Values values()
{
Values v;
v.unlockAll = g_unlockAll.load(std::memory_order_relaxed);
v.noAi = g_noAi.load(std::memory_order_relaxed);
v.health = g_infiniteHealth.load(std::memory_order_relaxed);
v.ammo = g_infiniteAmmo.load(std::memory_order_relaxed);
v.energy = g_infiniteEnergy.load(std::memory_order_relaxed);
v.enemyCap = g_enemyCap.load(std::memory_order_relaxed);
return v;
}
void setValues(const Values &v)
{
g_unlockAll.store(v.unlockAll, std::memory_order_relaxed);
g_noAi.store(v.noAi, std::memory_order_relaxed);
g_infiniteHealth.store(v.health, std::memory_order_relaxed);
g_infiniteAmmo.store(v.ammo, std::memory_order_relaxed);
g_infiniteEnergy.store(v.energy, std::memory_order_relaxed);
g_enemyCap.store(v.enemyCap, 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));
// TMB_PLAYER_LIVES=<n> (testing, story's game over): player 1's lives (InitPlayerLives' + 0x2370) kept at most n.
static const int s_lives = [] { const char *v = std::getenv("TMB_PLAYER_LIVES"); return v && *v ? std::atoi(v) : -1; }();
if (s_lives >= 0 && static_cast<int32_t>(word(rdram, progress + 0x2370u)) > s_lives)
setWord(rdram, progress + 0x2370u, static_cast<uint32_t>(s_lives));
}
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);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (game == 0u)
return;
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
// tab would (checks that each acts while playing, not only from launch).
static const double s_toggle = []
{
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0 && !bozo::det::enabled()) // deterministic mode: nothing the user does may change the run
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
static bool s_on = false;
if (now >= s_next)
{
s_next = now + s_toggle;
s_on = !s_on;
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
g_infiniteHealth.store(all);
g_infiniteAmmo.store(all);
g_infiniteEnergy.store(all);
g_noAi.store(s_on);
g_enemyCap.store(s_on ? 10.0f : -1.0f);
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
}
}
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
const int players = playerCount(rdram, game);
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
if (car == 0u)
continue;
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
// Topped up while alive (a car already dead is left to respawn).
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
setFlt(rdram, car + kHealth, most);
if (energy >> player & 1u)
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
if (player == 0 && playerCap >= 0.0f)
{
static uint32_t s_frames = 0;
if (++s_frames % 250u == 0u)
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
if (now > playerCap)
setFlt(rdram, car + kHealth, playerCap);
}
}
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
if (enemyCap >= 0.0f)
{
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
static uint32_t s_enemyFrames = 0;
const bool log = ++s_enemyFrames % 500u == 0u;
std::string line;
for (int32_t index = 0; index < count; ++index)
{
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
const float now = flt(rdram, vehicle + kHealth);
if (log)
{
char text[48];
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
line += text;
}
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
setFlt(rdram, vehicle + kHealth, enemyCap);
}
if (log)
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
}
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
static uint32_t s_logFrames = 0;
if (s_log && ++s_logFrames % 250u == 0u)
{
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
g_decrementsSkipped.exchange(0));
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
std::string counts;
for (uint32_t slot = 1; slot <= 8; ++slot)
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
}
}
}
void install(tmb::Registry &runtime)
{
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"));
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
#if defined(BOZO_SETTINGS_UI)
bozo::app::ui::registerTab("Cheats", &drawTab);
#endif
}
// Save states (tmb_state.cpp): the lock words Unlock everything opened (put back when it goes off).
void state(bozo::state::Archive &a) { bozo::state::io(a, g_unlocked); }
}
+900
View File
@@ -0,0 +1,900 @@
// PC SETTINGS in the game's own Options screen (a ninth line under the game's eight) and in its pause menu (a line under
// its own, below), and behind it pages drawn with the
// game's font and steered with the pad, for what the settings window (F2) offers besides the controls: Video (the
// window's settings, applied and saved to video.ini; widescreen: runtime/tmb_widescreen.cpp), Cheats
// (runtime/tmb_cheats.cpp's switches, at once) and Save states (the slot, load, save), and QUIT GAME (a second Cross
// ends the game). The controls stay in F2.
//
// The Options screen (uiOptions, 0x1911F0, screen 10 of uiMain's table; one call a frame), from its code:
// - Its cursor is options_main_line (0x4FB2F4), 0 to 7 (DIFFICULTY ... SAVE SETTINGS TO MEMORY CARD); options_subScreen
// (0x4FB2F0) is 0 on that page (1 the controls, 2 the brightness). Up and Down wrap the cursor (0x1915AC, 0x1915E8:
// 0 - 1 gives 7, 7 + 1 gives 0) from the button flags uiGetInput (0x199880, called at 0x191284) sets that frame, one
// press one flag (up 0x4FB368, down 0x4FB36C, left 0x4FB360, right 0x4FB364, square 0x4FB370, triangle 0x4FB374,
// circle 0x4FB378, cross 0x4FB37C). Every other use of the cursor compares it with a line, so 8 matches none: no line
// is highlighted and no line's handler runs. The game puts it back to 0 when the screen ends (0x191338).
// - Cross on a line without a handler of its own accepts the settings and leaves (0x1923D4); Triangle restores them and
// leaves, Square sets the defaults.
// - The lines: x 0x320, y 0x550 + 0x210 a line in 12.4 sub-pixels from the view's corner, through fontSetColor,
// fontSetCharSizesInSubPixels, fontSetCursorAtSubPixel and fontSpritePrint on font 0; the selected line in
// (0x60, 0x4C, 0x36) at sizes (307, 332, -48, 48), the others in (0x30, 0x26, 0x1C) at (288, 312, -48, 48); the title
// centred at (0x1400, 0x100) in (0x29, 0x1E, 0x0E). The sounds: playShellSFXSound(shell + 0x1A144, n), 0 down, 1 up,
// 2 accept, 3 back, 5 a value changed.
//
// Here: uiGetInput's override, when the Options page called it, lets the cursor reach 8 (Down on 7, Up on 0) and takes
// Cross on 8; uiOptions' override draws the line after the game's page, and while the pages are open draws them
// instead of the game's (the 3D shell behind them stays the game's; its sliders hidden by the game's blankSliders, as
// its controls page does). The pages read the pad through the game's uiGetInput and draw through the game's font
// functions, so they look and answer as the game's, on a copy of the context (Guest, below). Its legend (X apply all,
// Triangle cancel, Square default) stays the game's: Cross acts, Triangle backs out. The lines' text uses the font's
// glyphs (capitals, digits, space, ( ) and -; no apostrophe). A save state's load closes the pages (stateLoaded).
//
// Only where the game's graphics are native (every free run): the reference checker runs the game's own code.
#include "tmb_port.h"
#include "tmb_menu.h"
#include <algorithm>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <mutex>
#include <string>
#include <vector>
namespace tmb::cheats
{
struct Values
{
bool unlockAll = false, noAi = false;
uint32_t health = 0u, ammo = 0u, energy = 0u;
float enemyCap = -1.0f;
};
Values values();
void setValues(const Values &v);
}
namespace tmb::menu
{
namespace
{
constexpr uint32_t kUiOptions = 0x001911F0u, kUiGetInput = 0x00199880u, kOptionsInputReturn = 0x0019128Cu;
constexpr uint32_t kFontSetColor = 0x001C4258u, kFontSetSizes = 0x001C4700u, kFontSetCursor = 0x001C47B8u,
kFontPrint = 0x001C47D8u, kFontPrintCentered = 0x001C4568u, kPlaySound = 0x00179720u,
kBlankSliders = 0x0019DE38u;
// The pause menu (pauseLevelOverlay 0x166960, in displayDialog's own loop; types 0 and 16 the pause).
constexpr uint32_t kPauseOverlay = 0x00166960u, kMenuSelection = 0x00167AF8u, kPauseExit = 0x00167670u,
kPauseSelectionReturn = 0x00166AE4u, kPauseExitReturn = 0x00166D64u, kPauseReturn0 = 0x001637E4u,
kPauseReturn16 = 0x001637F4u;
constexpr uint32_t kSetMenuFont = 0x00167810u, kSetTitleFont = 0x00167AC8u, kFontSetSize = 0x001C4330u,
kFontPrintXY = 0x001C44A8u, kFontPrintCenteredXY = 0x001C44D8u, kPlayRtSound = 0x00179768u,
kInputGetInput = 0x001D8770u, kInputGetPlayerPad = 0x001D8658u;
constexpr uint32_t kCurrentMenuSelection = 0x004FAD30u, kPlayerThatPaused = 0x004FAE64u;
constexpr uint32_t kScreen = 0x004FB144u, kTransitioning = 0x004FB1ACu, kSubScreen = 0x004FB2F0u, kLine = 0x004FB2F4u;
constexpr uint32_t kShellPointer = 0x004FAD28u, kShellSound = 0x1A144u;
constexpr uint32_t kLeft = 0x004FB360u, kRight = 0x004FB364u, kUp = 0x004FB368u, kDown = 0x004FB36Cu,
kTriangle = 0x004FB374u, kCircle = 0x004FB378u, kCross = 0x004FB37Cu;
// The flags a leaving page sets (still_processing_triangle, _x, _x_main_options, _x_controls, _x_brightness).
constexpr uint32_t kBusy[] = {0x004FB2FCu, 0x004FB300u, 0x004FB304u, 0x004FB308u, 0x004FB30Cu};
constexpr uint32_t kOptionsScreen = 10u, kLastLine = 7u, kPcLine = 8u;
constexpr int32_t kLineX = 0x320, kPcLineY = 0x17C0;
constexpr int kSoundDown = 0, kSoundUp = 1, kSoundAccept = 2, kSoundBack = 3, kSoundValue = 5;
std::mutex g_hooksMutex;
Hooks g_hooks; // under g_hooksMutex
Hooks hooks()
{
std::lock_guard lock(g_hooksMutex);
return g_hooks;
}
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFCu), &value, 4); }
// The game's functions called from an override, with their arguments in a0..a3, t0, on a copy of the thread's
// context (BozoEngine kernel.md section 3b, "Guest code on an override's own context"): guest code there never
// leaves the override (an event due waits for the thread's own code), so the override's own code after each
// call runs on the game's state as that call left it, and the thread's registers are never touched. The copy's
// stack starts 0x200 bytes below the thread's (the callees' frames go below that); the strings printed go in
// the free space between the two.
struct Guest
{
uint8_t *rdram;
PS2Runtime *rt;
R5900Context copy;
uint32_t text = 0u;
bool pause = false; // the pause menu's pages: its pad, sounds and fonts (pixels, not sub-pixels)
Guest(uint8_t *memory, const R5900Context *ctx, PS2Runtime *runtime) : rdram(memory), rt(runtime), copy(*ctx)
{
const uint32_t frame = (getRegU32(ctx, 29) - 0x200u) & ~0xFu;
SET_GPR_U32(&copy, 29, frame);
copy.leaving = 0;
text = (frame + 0x20u) & 0x1FFFFFFu;
}
void call(void (*fn)(uint8_t *, R5900Context *, Runtime *), uint32_t address, std::initializer_list<uint32_t> args)
{
static constexpr int kArgs[] = {4, 5, 6, 7, 8};
int i = 0;
for (const uint32_t a : args)
SET_GPR_U32(&copy, kArgs[i++], a);
copy.pc = address;
fn(rdram, &copy, rt);
}
uint32_t result() const { return getRegU32(&copy, 2); }
uint32_t string(const std::string &s)
{
const size_t n = std::min<size_t>(s.size(), 255u);
std::memcpy(rdram + text, s.data(), n);
rdram[text + n] = 0;
return text;
}
void sound(int which)
{
if (pause)
{
// The pause's own sounds (getCurrentMenuSelection, checkInputForPauseExit): 0x2C down, 0x2B up,
// 0x2A accept.
const uint32_t code = which == kSoundDown || which == kSoundValue ? 0x2Cu : which == kSoundAccept ? 0x2Au : 0x2Bu;
call(&playRTShellSound__Fi_0x179768, kPlayRtSound, {code});
return;
}
const uint32_t shell = word(rdram, kShellPointer);
if (shell != 0u)
call(&playShellSFXSound__10ShellSoundi_0x179720, kPlaySound, {shell + kShellSound, static_cast<uint32_t>(which)});
}
void color(uint32_t r, uint32_t g, uint32_t b) { call(&fontSetColor__Fiiii_0x1c4258, kFontSetColor, {0u, r, g, b}); }
// The game's two sizes (the selected line 1.6 times the font's 12 x 13, the others 1.5), times `scale`:
// fontSetCharSizesInSubPixels(font, width, height, -48, 48), as uiOptions sets them.
void sizes(bool large, float scale = 1.0f)
{
const float k = (large ? 1.6f : 1.5f) * scale;
call(&fontSetCharSizesInSubPixels__Fiiiii_0x1c4700, kFontSetSizes,
{0u, static_cast<uint32_t>(std::lround(12.0f * k * 16.0f)), static_cast<uint32_t>(std::lround(13.0f * k * 16.0f)),
static_cast<uint32_t>(-48), 48u});
}
void print(int32_t x, int32_t y, const std::string &s)
{
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, static_cast<uint32_t>(x), static_cast<uint32_t>(y)});
call(&fontSpritePrint__FiPc_0x1c47d8, kFontPrint, {0u, string(s)});
}
// Centred on x, as the game centres its values: the cursor set, then fontSpritePrintCentered.
void printCentered(int32_t x, int32_t y, const std::string &s)
{
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, static_cast<uint32_t>(x), static_cast<uint32_t>(y)});
call(&fontSpritePrintCentered__FiPc_0x1c4568, kFontPrintCentered, {0u, string(s)});
}
void title(const std::string &s)
{
color(0x29u, 0x1Eu, 0x0Eu);
sizes(true);
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, 0x1400u, 0x100u});
call(&fontSpritePrintCentered__FiPc_0x1c4568, kFontPrintCentered, {0u, string(s)});
}
};
void setSizes(Guest &g, bool large, float scale) { g.sizes(large, scale); }
bool active(PS2Runtime *rt) { return bozo::port::nativeGraphics(rt); }
bool optionsPageIdle(const uint8_t *rdram)
{
if (word(rdram, kScreen) != kOptionsScreen || word(rdram, kSubScreen) != 0u || word(rdram, kTransitioning) != 0u)
return false;
for (const uint32_t flag : kBusy)
if (word(rdram, flag) != 0u)
return false;
return true;
}
// ---- The pages ----
enum class Page
{
Closed,
Top,
Video,
Cheats,
States
};
struct Row
{
std::string label;
std::string value; // "" a line Cross acts on
bool info = false; // a line the cursor skips
};
struct Menu
{
Page page = Page::Closed;
int line = 0;
Page lastTop = Page::Video;
bozo::app::video::Settings video; // the Video page's edits (Apply and save sends them)
std::vector<std::pair<int, int>> resolutions;
int monitorRefresh = 0;
std::string status; // a line under the page: what Cross did
bool quitArmed = false; // QUIT GAME pressed once: a second Cross quits
bool inPause = false; // opened from the pause menu (its style and pad), not the Options screen
} g_menu;
std::string upper(std::string s)
{
for (char &c : s)
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return s;
}
template <typename T> int indexOf(const std::vector<T> &list, const T &value, int fallback = 0)
{
for (size_t i = 0; i < list.size(); ++i)
if (list[i] == value)
return static_cast<int>(i);
return fallback;
}
template <typename T> T step(const std::vector<T> &list, const T &value, int delta)
{
const int n = static_cast<int>(list.size());
const int i = indexOf(list, value, delta > 0 ? -1 : 0);
return list[static_cast<size_t>(((i + delta) % n + n) % n)];
}
// Video.
const std::vector<int> kModes = {0, 1, 2};
const std::vector<float> kScales = {0.5f, 0.75f, 1.0f, 1.5f, 2.0f};
const std::vector<int> kUpscales = {1, 2, 4};
const std::vector<int> kSmoothings = {0, 1, 2, 4, 8, 16};
const std::vector<int> kAntiAliasings = {0, 2, 4, 8};
const std::vector<int> kFastForwards = {200, 300, 400, 0};
std::string modeText(bozo::app::video::WindowMode m)
{
switch (m)
{
case bozo::app::video::WindowMode::Fullscreen: return "FULLSCREEN";
case bozo::app::video::WindowMode::Borderless: return "BORDERLESS";
default: return "WINDOWED";
}
}
std::string scaleText(float s)
{
char text[16];
std::snprintf(text, sizeof(text), "%d", static_cast<int>(std::lround(s * 100.0f)));
return std::string(text) + " PERCENT";
}
std::string timesText(int n) { return std::to_string(n) + "X"; }
std::string onOff(bool on) { return on ? "ON" : "OFF"; }
bool packOn(const std::string &pack) { return pack != "off" && pack != "0"; }
std::vector<int> frameRates(const Menu &m)
{
std::vector<int> rates = {0, -1};
if (m.video.frameRate > 0)
rates.push_back(m.video.frameRate);
return rates;
}
std::string frameRateText(int rate, int refresh)
{
if (rate == 0)
return "60 (GAME)";
if (rate < 0)
return refresh > 0 ? "MONITOR (" + std::to_string(refresh) + ")" : "MONITOR";
return std::to_string(rate);
}
enum VideoLine
{
VMode,
VResolution,
VScale,
VFrameRate,
VAntiAliasing,
VSmoothing,
VUpscale,
VFilter,
VPack,
VWide,
VPause,
VFast,
VApply,
VCount
};
std::vector<Row> videoRows(const Menu &m, const Hooks &h)
{
const auto &v = m.video;
std::vector<Row> rows(VCount);
rows[VMode] = {"DISPLAY", modeText(v.mode)};
rows[VResolution] = {"RESOLUTION", std::to_string(v.width) + " X " + std::to_string(v.height)};
rows[VScale] = {"RENDER SCALE", scaleText(v.renderScale)};
rows[VFrameRate] = {"FRAME RATE", frameRateText(v.frameRate, m.monitorRefresh)};
rows[VAntiAliasing] = {"ANTIALIASING", v.antiAliasing ? timesText(v.antiAliasing) : "OFF"};
rows[VSmoothing] = {"TEXTURE SMOOTHING", v.textureSmoothing == 0 ? "OFF" : v.textureSmoothing == 1 ? "TRILINEAR"
: timesText(v.textureSmoothing)};
rows[VUpscale] = {"TEXTURE UPSCALING", v.textureUpscale.factor > 1 ? timesText(v.textureUpscale.factor) : "OFF"};
rows[VFilter] = {"UPSCALING FILTER", v.textureUpscale.filter == bozo::render::UpscaleFilter::Smooth ? "SMOOTH" : "EDGE"};
const bool pack = h.texturePackFolder && !h.texturePackFolder(packOn(v.texturePack) ? v.texturePack : "").empty();
rows[VPack] = {"TEXTURE PACK", pack ? onOff(packOn(v.texturePack)) : "NONE"};
rows[VWide] = {"WIDESCREEN", onOff(v.widescreen)};
rows[VPause] = {"PAUSE IN BACKGROUND", onOff(v.pauseInBackground)};
rows[VFast] = {"FAST FORWARD", v.fastForward == 0 ? "UNLIMITED" : timesText(v.fastForward / 100)};
rows[VApply] = {"APPLY AND SAVE", ""};
return rows;
}
bool videoChange(Menu &m, int line, int delta)
{
auto &v = m.video;
switch (line)
{
case VMode:
v.mode = static_cast<bozo::app::video::WindowMode>(step(kModes, static_cast<int>(v.mode), delta));
return true;
case VResolution:
{
if (m.resolutions.empty())
return false;
const auto next = step(m.resolutions, std::make_pair(v.width, v.height), delta);
v.width = next.first, v.height = next.second;
return true;
}
case VScale:
{
int i = 2;
for (size_t k = 0; k < kScales.size(); ++k)
if (std::fabs(v.renderScale - kScales[k]) < 0.01f)
i = static_cast<int>(k);
const int n = static_cast<int>(kScales.size());
v.renderScale = kScales[static_cast<size_t>(((i + delta) % n + n) % n)];
return true;
}
case VFrameRate: v.frameRate = step(frameRates(m), v.frameRate, delta); return true;
case VAntiAliasing: v.antiAliasing = step(kAntiAliasings, v.antiAliasing, delta); return true;
case VSmoothing: v.textureSmoothing = step(kSmoothings, v.textureSmoothing, delta); return true;
case VUpscale:
v.textureUpscale.factor = static_cast<uint8_t>(step(kUpscales, static_cast<int>(v.textureUpscale.factor), delta));
return true;
case VFilter:
v.textureUpscale.filter = v.textureUpscale.filter == bozo::render::UpscaleFilter::Smooth ? bozo::render::UpscaleFilter::Edge
: bozo::render::UpscaleFilter::Smooth;
return true;
case VPack:
{
static std::string s_lastOn; // the folder a set texture_pack named, given back when turned on again
if (packOn(v.texturePack) && !v.texturePack.empty())
s_lastOn = v.texturePack;
const Hooks h = hooks();
if (!h.texturePackFolder || h.texturePackFolder(packOn(v.texturePack) ? v.texturePack : s_lastOn).empty())
return false;
v.texturePack = packOn(v.texturePack) ? "off" : s_lastOn;
return true;
}
case VWide: v.widescreen = !v.widescreen; return true;
case VPause: v.pauseInBackground = !v.pauseInBackground; return true;
case VFast: v.fastForward = step(kFastForwards, v.fastForward, delta); return true;
default: return false;
}
}
// Cheats.
enum CheatLine
{
CUnlock,
CHealth,
CAmmo,
CEnergy,
CNoAi,
CWeak,
CCount
};
const std::vector<uint32_t> kMasks = {0u, 1u, 0xFu};
const std::vector<float> kCaps = {-1.0f, 10.0f, 25.0f, 50.0f, 100.0f};
std::string maskText(uint32_t mask)
{
if (mask == 0u)
return "OFF";
if (mask == 1u)
return "PLAYER 1";
if ((mask & 0xFu) == 0xFu)
return "ALL PLAYERS";
std::string players = "PLAYERS";
for (int p = 0; p < 4; ++p)
if (mask >> p & 1u)
players += " " + std::to_string(p + 1);
return players;
}
std::vector<Row> cheatRows()
{
const cheats::Values c = cheats::values();
std::vector<Row> rows(CCount);
rows[CUnlock] = {"UNLOCK EVERYTHING", onOff(c.unlockAll)};
rows[CHealth] = {"INFINITE HEALTH", maskText(c.health)};
rows[CAmmo] = {"INFINITE AMMO", maskText(c.ammo)};
rows[CEnergy] = {"INFINITE ENERGY", maskText(c.energy)};
rows[CNoAi] = {"NO AI", onOff(c.noAi)};
rows[CWeak] = {"WEAK ENEMIES", c.enemyCap < 0.0f ? "OFF" : "HEALTH " + std::to_string(static_cast<int>(std::lround(c.enemyCap)))};
return rows;
}
bool cheatChange(int line, int delta)
{
cheats::Values c = cheats::values();
const auto mask = [&](uint32_t &m) { m = step(kMasks, m, delta); };
switch (line)
{
case CUnlock: c.unlockAll = !c.unlockAll; break;
case CHealth: mask(c.health); break;
case CAmmo: mask(c.ammo); break;
case CEnergy: mask(c.energy); break;
case CNoAi: c.noAi = !c.noAi; break;
case CWeak:
{
int i = c.enemyCap < 0.0f ? 0 : 1;
for (size_t k = 1; k < kCaps.size(); ++k)
if (std::fabs(c.enemyCap - kCaps[k]) < 0.5f)
i = static_cast<int>(k);
const int n = static_cast<int>(kCaps.size());
c.enemyCap = kCaps[static_cast<size_t>(((i + delta) % n + n) % n)];
break;
}
default: return false;
}
cheats::setValues(c);
return true;
}
// Save states.
enum StateLine
{
SSlot,
SSummary,
SLoad,
SSave,
SCount
};
std::vector<Row> stateRows(const Hooks &h)
{
const int slot = h.stateSlot ? h.stateSlot() : 0;
std::string summary = h.slotSummary ? upper(h.slotSummary(slot)) : "";
if (const size_t colon = summary.find(": "); colon != std::string::npos)
summary = summary.substr(colon + 2);
std::vector<Row> rows(SCount);
rows[SSlot] = {"SLOT", std::to_string(slot)};
rows[SSummary] = {" " + summary, "", true};
rows[SLoad] = {"LOAD", ""};
rows[SSave] = {"SAVE", ""};
return rows;
}
// The top page: the pages this program can offer.
std::vector<Page> topPages(const Hooks &h)
{
std::vector<Page> pages;
if (h.videoShared && h.videoApply && h.videoShared().open)
pages.push_back(Page::Video);
pages.push_back(Page::Cheats);
if (h.stateSlot && h.saveState && h.loadState)
pages.push_back(Page::States);
return pages;
}
const char *pageName(Page p)
{
switch (p)
{
case Page::Video: return "VIDEO";
case Page::Cheats: return "CHEATS";
case Page::States: return "SAVE STATES";
default: return "";
}
}
std::vector<Row> rowsOf(const Menu &m, const Hooks &h)
{
switch (m.page)
{
case Page::Top:
{
std::vector<Row> rows;
for (const Page p : topPages(h))
rows.push_back({pageName(p), ""});
if (h.quit)
rows.push_back({m.quitArmed ? "QUIT GAME: PRESS X AGAIN" : "QUIT GAME", ""});
return rows;
}
case Page::Video: return videoRows(m, h);
case Page::Cheats: return cheatRows();
case Page::States: return stateRows(h);
default: return {};
}
}
int nextLine(const std::vector<Row> &rows, int line, int delta)
{
const int n = static_cast<int>(rows.size());
for (int k = 0; k < n; ++k)
{
line = ((line + delta) % n + n) % n;
if (!rows[static_cast<size_t>(line)].info)
return line;
}
return line;
}
void open(Menu &m, Page page, const Hooks &h)
{
m.page = page;
m.line = 0;
m.status.clear();
m.quitArmed = false;
if (page == Page::Video && h.videoShared)
{
const bozo::app::video::Shared s = h.videoShared();
m.video = s.applied;
m.resolutions = s.resolutions;
m.monitorRefresh = s.monitorRefresh;
}
}
// The pages in the pause's own style: its fonts (setTitleFont's title; the selected line at size 0x12 in
// (0x78, 0x6E, 0x00), the others at 0x10 in (0x46, 0x46, 0x46), as setMenuFont), in pixels of the paused view.
void drawPause(Guest &g, const Menu &m, const std::vector<Row> &rows)
{
g.call(&setTitleFont__Fv_0x167ac8, kSetTitleFont, {});
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, 0x12u, g.string(m.page == Page::Top ? "PC SETTINGS" : pageName(m.page))});
const int32_t top = m.page == Page::Top ? 0x40 : 0x26, spacing = 0xB;
for (size_t i = 0; i < rows.size(); ++i)
{
const Row &r = rows[i];
const bool selected = static_cast<int>(i) == m.line && !r.info;
const uint32_t y = static_cast<uint32_t>(top + static_cast<int32_t>(i) * spacing);
g.call(&fontSetSize__Fii_0x1c4330, kFontSetSize, {0u, selected ? 0x12u : 0x10u});
if (selected)
g.color(0x78u, 0x6Eu, 0x00u);
else
g.color(0x46u, 0x46u, 0x46u);
if (m.page == Page::Top)
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY, {0u, 0x140u, y, g.string(r.label)});
else
{
g.call(&fontSpritePrintXY__FiiiPc_0x1c44a8, kFontPrintXY, {0u, 0x3Cu, y, g.string(r.label)});
if (!r.value.empty())
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x1C0u, y, g.string(selected ? "\\ " + r.value + " ]" : r.value)});
}
}
if (!m.status.empty())
{
g.call(&fontSetSize__Fii_0x1c4330, kFontSetSize, {0u, 0x10u});
g.color(0x78u, 0x6Eu, 0x00u);
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, static_cast<uint32_t>(top + static_cast<int32_t>(rows.size()) * spacing + 4), g.string(m.status)});
}
}
// A frame of the open pages: the pad's presses (uiGetInput's flags), then the page drawn.
void runPage(Guest &g)
{
Menu &m = g_menu;
const Hooks h = hooks();
// This frame's press: the Options page's from uiGetInput's flags; the pause's from the pausing player's pad
// (inputGetInput, one press a frame in uiGetInput's order), as the pause reads it.
uint32_t press = 0u;
if (g.pause)
{
g.call(&inputGetPlayerPad__Fi_0x1d8658, kInputGetPlayerPad, {word(g.rdram, kPlayerThatPaused)});
const uint32_t pad = g.result();
static constexpr std::pair<uint32_t, uint32_t> kMasks[] = {{0x40u, kDown}, {0x10u, kUp}, {0x4000u, kCross}, {0x80u, kLeft},
{0x20u, kRight}, {0x1000u, kTriangle}, {0x2000u, kCircle}};
for (const auto &[mask, flag] : kMasks)
{
g.call(&inputGetInput__Fii_0x1d8770, kInputGetInput, {mask, pad});
if (g.result() != 0u)
{
press = flag;
break;
}
}
}
else
g.call(&uiGetInput__Fv_0x199880, kUiGetInput, {});
const auto pressed = [&](uint32_t flag) { return g.pause ? press == flag : word(g.rdram, flag) != 0u; };
std::vector<Row> rows = rowsOf(m, h);
if (m.page != Page::Closed && rows.empty())
m.page = Page::Top, rows = rowsOf(m, h);
m.line = std::clamp(m.line, 0, std::max(0, static_cast<int>(rows.size()) - 1));
if (pressed(kTriangle) || pressed(kCircle))
{
if (m.quitArmed)
{
m.quitArmed = false; // Back only disarms QUIT GAME
g.sound(kSoundBack);
rows = rowsOf(m, h);
goto draw;
}
g.sound(kSoundBack);
if (m.page == Page::Top)
{
m.page = Page::Closed;
return; // the game's page again from the next frame, its cursor on PC SETTINGS
}
const Page from = m.page;
open(m, Page::Top, h);
const std::vector<Page> pages = topPages(h);
m.line = std::max(0, indexOf(pages, from));
rows = rowsOf(m, h);
}
else if (pressed(kUp) || pressed(kDown))
{
m.line = nextLine(rows, m.line, pressed(kUp) ? -1 : 1);
m.quitArmed = false;
g.sound(pressed(kUp) ? kSoundUp : kSoundDown);
m.status.clear();
}
else if (pressed(kLeft) || pressed(kRight))
{
const int delta = pressed(kLeft) ? -1 : 1;
bool changed = false;
if (m.page == Page::Video)
changed = videoChange(m, m.line, delta);
else if (m.page == Page::Cheats)
changed = cheatChange(m.line, delta);
else if (m.page == Page::States && m.line == SSlot && h.stateSlot && h.setStateSlot)
{
h.setStateSlot(h.stateSlot() + delta);
changed = true;
}
if (changed)
{
g.sound(kSoundValue);
m.status.clear();
rows = rowsOf(m, h);
}
}
else if (pressed(kCross))
{
if (m.page == Page::Top)
{
const std::vector<Page> pages = topPages(h);
if (m.line < static_cast<int>(pages.size()))
{
g.sound(kSoundAccept);
open(m, pages[static_cast<size_t>(m.line)], h);
rows = rowsOf(m, h);
}
else if (h.quit && m.line == static_cast<int>(pages.size()))
{
// QUIT GAME: a second Cross ends the game (the window closes, as closing it does).
g.sound(kSoundAccept);
if (m.quitArmed)
h.quit();
m.quitArmed = !m.quitArmed;
rows = rowsOf(m, h);
}
}
else if (m.page == Page::Video && m.line == VApply && h.videoApply)
{
h.videoApply(m.video);
g.sound(kSoundAccept);
m.status = "APPLIED AND SAVED";
}
else if (m.page == Page::States && (m.line == SLoad || m.line == SSave) && h.stateSlot)
{
const int slot = h.stateSlot();
const bool empty = h.slotSummary && upper(h.slotSummary(slot)).find("EMPTY") != std::string::npos;
if (m.line == SLoad && empty)
{
g.sound(kSoundBack);
m.status = "SLOT " + std::to_string(slot) + " IS EMPTY";
}
else
{
const bool ok = m.line == SLoad ? (h.loadState && h.loadState(slot)) : (h.saveState && h.saveState(slot));
g.sound(ok ? kSoundAccept : kSoundBack);
m.status = !ok ? "NOT AVAILABLE" : m.line == SLoad ? "LOADING SLOT " + std::to_string(slot) : "SAVING IN SLOT " + std::to_string(slot);
}
}
}
draw:
if (g.pause)
{
drawPause(g, m, rows);
return;
}
// The page's sliders hidden, as the game's controls page hides them (uiOptions shows them again on its page).
g.call(&blankSliders__Fi_0x19de38, kBlankSliders, {0u});
// Drawn: the title, then each line (the selected one larger and brighter, as the game's), its value to the right.
g.title(m.page == Page::Top ? "PC SETTINGS" : pageName(m.page));
const bool wide = m.page == Page::Top;
const int32_t top = wide ? 0x550 : 0x4A0, spacing = wide ? 0x210 : 0x1A0;
const float scale = wide ? 1.0f : 0.8f;
for (size_t i = 0; i < rows.size(); ++i)
{
const Row &r = rows[i];
const bool selected = static_cast<int>(i) == m.line && !r.info;
const int32_t y = top + static_cast<int32_t>(i) * spacing;
if (selected)
g.color(0x60u, 0x4Cu, 0x36u);
else
g.color(0x30u, 0x26u, 0x1Cu);
setSizes(g, selected, scale);
g.print(kLineX, y, r.label);
if (!r.value.empty())
g.printCentered(0x1D00, y, selected ? "\\ " + r.value + " ]" : r.value);
}
if (!m.status.empty())
{
g.color(0x60u, 0x4Cu, 0x36u);
setSizes(g, false, scale);
g.printCentered(0x1400, top + static_cast<int32_t>(rows.size()) * spacing + spacing / 2, m.status);
}
}
// ---- The overrides ----
// uiGetInput: the game's, then, for the Options page's call, the cursor let onto line 8 and Cross taken there.
void uiGetInputOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
uiGetInput__Fv_0x199880(rdram, ctx, runtime);
// A call that left (an event due) goes on from the dispatcher: its flags are not all set yet.
if (ctx->leaving || ra != kOptionsInputReturn || !active(runtime) || !optionsPageIdle(rdram))
return;
const uint32_t line = word(rdram, kLine);
int sound = -1;
if (line == kLastLine && word(rdram, kDown))
{
setWord(rdram, kDown, 0u); // the game would wrap to 0
setWord(rdram, kLine, kPcLine);
sound = kSoundDown;
}
else if (line == 0u && word(rdram, kUp))
setWord(rdram, kLine, kPcLine + 1u); // the game's Up then gives 8
else if (line == kPcLine)
{
if (word(rdram, kDown))
setWord(rdram, kLine, kLastLine); // the game's Down then wraps to 0
else if (word(rdram, kCross))
{
setWord(rdram, kCross, 0u); // not the game's accept-and-leave
sound = kSoundAccept;
open(g_menu, Page::Top, hooks());
g_menu.inPause = false;
}
setWord(rdram, kLeft, 0u);
setWord(rdram, kRight, 0u);
}
if (sound >= 0)
{
Guest g(rdram, ctx, runtime);
g.sound(sound);
}
}
// uiOptions: the game's page and the PC SETTINGS line under it, or, while they are open, the PC pages instead.
void uiOptionsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_menu.page != Page::Closed && (g_menu.inPause || !active(runtime) || !optionsPageIdle(rdram)))
g_menu.page = Page::Closed;
const bool pages = g_menu.page != Page::Closed;
if (!pages)
uiOptions__Fv_0x1911f0(rdram, ctx, runtime); // returns with pc its return address (or where it left)
if (active(runtime) && optionsPageIdle(rdram))
{
Guest g(rdram, ctx, runtime);
if (pages)
runPage(g);
else
{
const bool selected = word(rdram, kLine) == kPcLine;
if (selected)
g.color(0x60u, 0x4Cu, 0x36u);
else
g.color(0x30u, 0x26u, 0x1Cu);
setSizes(g, selected, 1.0f);
g.print(kLineX, kPcLineY, "PC SETTINGS");
}
}
if (pages)
ctx->pc = getRegU32(ctx, 31); // jr $ra: the game's page not run
}
// ---- The pause menu (displayDialog's pauseLevelOverlay, types 0 and 16) ----
// getCurrentMenuSelection(count, pad) moves the cursor (gCurrentMenuSelection) on the pausing player's pad,
// wrapping at `count` (4 in one player: RESUME, QUIT, SET VIBRATION, ADJUST REAR VIEW; 3 with more players);
// checkInputForPauseExit returns 2 for Cross; at index `count` the game keeps a hidden TWEAK action, which Cross
// there would run. So: for the pause's call (return 0x166AE4) the count is one more (PC SETTINGS at `count`),
// Cross there (return 0x166D64) opens the pages instead, and pauseLevelOverlay draws the line after its menu,
// or, while the pages are open, the pages instead (displayDialog's loop goes on: 3D, font flush, frame).
uint32_t g_pauseCount = 0u;
bool g_pauseMenuShown = false; // the overlay drew its menu this frame (not the QUIT confirmation or the save)
std::chrono::steady_clock::time_point g_lastPause{};
void menuSelectionOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (getRegU32(ctx, 31) == kPauseSelectionReturn && active(runtime))
{
g_pauseCount = getRegU32(ctx, 4);
g_pauseMenuShown = true;
SET_GPR_U32(ctx, 4, g_pauseCount + 1u);
}
getCurrentMenuSelection__Fii_0x167af8(rdram, ctx, runtime);
}
void pauseExitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
checkInputForPauseExit__Fi_0x167670(rdram, ctx, runtime);
if (ctx->leaving || ra != kPauseExitReturn || !active(runtime) || !g_pauseMenuShown)
return;
if (getRegU32(ctx, 2) == 2u && word(rdram, kCurrentMenuSelection) == g_pauseCount)
{
SET_GPR_U32(ctx, 2, 0u); // the pause stays (not TWEAK)
open(g_menu, Page::Top, hooks());
g_menu.inPause = true;
}
}
void pauseOverlayOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
const bool pause = (ra == kPauseReturn0 || ra == kPauseReturn16) && active(runtime);
if (pause)
{
// A new pause (the overlay not called for a while) starts on the game's menu.
const auto now = std::chrono::steady_clock::now();
if (now - g_lastPause > std::chrono::milliseconds(500) && g_menu.inPause)
g_menu.page = Page::Closed;
g_lastPause = now;
if (g_menu.inPause && g_menu.page != Page::Closed)
{
Guest g(rdram, ctx, runtime);
g.pause = true;
runPage(g);
SET_GPR_U32(ctx, 2, 0u); // the dialog stays
ctx->pc = ra;
return;
}
}
g_pauseMenuShown = false;
pauseLevelOverlay__Fv_0x166960(rdram, ctx, runtime);
if (!pause || ctx->leaving || !g_pauseMenuShown)
return;
Guest g(rdram, ctx, runtime);
g.pause = true;
g.call(&setMenuFont__Fi_0x167810, kSetMenuFont, {g_pauseCount}); // highlighted as the game's lines
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, 0x61u + 0xBu * g_pauseCount, g.string("PC SETTINGS")});
}
}
Hooks currentHooks() { return hooks(); }
bool pausePagesOpen() { return g_menu.inPause && g_menu.page != Page::Closed; }
void setHooks(Hooks h)
{
std::lock_guard lock(g_hooksMutex);
g_hooks = std::move(h);
}
void stateLoaded() { g_menu.page = Page::Closed; }
void install(tmb::Registry &runtime)
{
runtime.registerFunction(kUiGetInput, &uiGetInputOverride);
runtime.registerFunction(kUiOptions, &uiOptionsOverride);
runtime.registerFunction(kMenuSelection, &menuSelectionOverride);
runtime.registerFunction(kPauseExit, &pauseExitOverride);
runtime.registerFunction(kPauseOverlay, &pauseOverlayOverride);
}
}
+40
View File
@@ -0,0 +1,40 @@
// PC SETTINGS in the game's own Options screen (runtime/tmb_menu.cpp): what the settings window (F2) offers besides the
// controls (video, cheats, save states), on pages drawn with the game's font and steered with the pad. The window's
// parts (its video settings and save states) come from the window program through these hooks; without them (the
// headless program) those pages are not offered.
#pragma once
#include "bozo/app/video_settings.h"
#include <functional>
#include <string>
namespace tmb::menu
{
struct Hooks
{
// Video: what is applied now (with the sizes to offer), and a change applied and saved to video.ini.
std::function<bozo::app::video::Shared()> videoShared;
std::function<void(const bozo::app::video::Settings &)> videoApply;
// The texture pack's folder a texture_pack setting names ("" none).
std::function<std::string(const std::string &)> texturePackFolder;
// Save states: the slot F5 / F7 use, its summary ("Slot 3: saved ..." or "Slot 3: empty"), save and load.
std::function<int()> stateSlot;
std::function<void(int)> setStateSlot;
std::function<std::string(int)> slotSummary;
std::function<bool(int)> saveState, loadState;
// Ends the game (the window closes): QUIT GAME, confirmed by a second Cross.
std::function<void()> quit;
// Widescreen (runtime/tmb_widescreen.cpp): the setting applied now, and the window's picture shape (0 the
// default 4:3, 16:9 while a view is wide).
std::function<bool()> widescreen;
std::function<void(float)> setPictureAspect;
};
void setHooks(Hooks hooks);
Hooks currentHooks();
// The pages are open over the pause menu (tmb_2d.cpp: displayDialog's darkening left out under them).
bool pausePagesOpen();
// A save state was loaded: the pages close (what they showed is gone).
void stateLoaded();
}
+1808 -1777
View File
File diff suppressed because it is too large. Load diff
+30 -4
View File
@@ -22,6 +22,11 @@
#include <cstdlib>
#include <cstring>
namespace tmb::widescreen
{
float screenWidth();
}
namespace tmb::twod
{
void publish();
@@ -45,6 +50,13 @@ namespace tmb::native
}
double g_lastMatchFrame = -1.0, g_lastMenuFrame = -1.0;
bool inMatch() { return g_lastMatchFrame >= 0.0 && hostSeconds() - g_lastMatchFrame < 0.1; }
// The same by game frame, not host time, for the reference checker (checkedEffects): the frames (bozo::det) at
// the last match frame's end and the last menu frame's (counted outside a match only, as g_lastMenuFrame).
int64_t g_checkMatchEnd = -1, g_checkMenuEnd = -1;
// 0.1 s as the reference ran (60 frames a second): match1p's last match frame ends at 13729 and its flares stay
// native to 13735 (6 frames on), the game's from 13736.
bool checkRecent(int64_t at) { return at >= 0 && static_cast<int64_t>(bozo::det::frame()) - at <= 6; }
bool checkInMatch() { return checkRecent(g_checkMatchEnd); }
// The menus natively too (TMB_NATIVE_MENUS=0: not drawn). Their frames end at sceGsSyncV (onMenuFrameEnd).
bool menusNative()
@@ -105,6 +117,9 @@ namespace tmb::native
// A match draws fields (the frame's every other line), the shell's menus whole frames.
const float lines = menusNative() ? 2.0f : 1.0f;
screen.originY = 2048.0f - 112.0f * lines; // NTSC: a 640 x 224 field
// Widescreen: the views 853 wide about the same centre (runtime/tmb_widescreen.cpp).
screen.width = tmb::widescreen::screenWidth();
screen.originX = 2048.0f - screen.width * 0.5f;
screen.height = 224.0f * lines;
// GS Z is z / w itself (the microprograms write FTOI4 of z / w into XYZF2's 24-bit Z, that word over 16).
screen.gsZScale = 1.0f;
@@ -139,10 +154,16 @@ namespace tmb::native
return on;
}
// For the particles drawn natively (runtime/tmb_particles.cpp): whether the effects are drawn natively now (a match
// or a native menu), and the group the next natively drawn program gets.
bool effectsInStream() { return enabled() && (inMatch() || menusNative()); }
// For the particles in the reference checker (tmb-check: no native graphics). Not the match and menu flags' host
// time, which made the check stop at match1p frame 5593 or 13737 by the host's speed: the reference's choices (TMB
// a7869c0, which recorded it), by game frame. The particles natively within 0.1 s of a match or menu frame's end (its
// effectsInStream); the lens flares natively only within 0.1 s of a match frame's (its flareDepthNative needed
// inMatch: the "No lives left" screen's frames after the match end as menu frames, their flares the game's, with its
// GS readback).
bool checkedEffects() { return enabled() && (checkInMatch() || checkRecent(g_checkMenuEnd)); }
bool checkedFlares() { return enabled() && checkInMatch(); }
// For the particles drawn natively: the group the next natively drawn program gets.
uint64_t nextStreamGroup() { return g_group + 1u; }
// For the movie pictures (runtime/tmb_2d.cpp): whether the shell's menus are drawn natively now.
@@ -208,6 +229,7 @@ namespace tmb::native
{
if (!enabled())
return;
g_checkMatchEnd = static_cast<int64_t>(bozo::det::frame());
g_lastMatchFrame = hostSeconds();
publish();
}
@@ -216,7 +238,11 @@ namespace tmb::native
// of it (empty with TMB_NATIVE_MENUS=0, so the last match frame does not stay over a menu).
void onMenuFrameEnd()
{
if (!enabled() || inMatch())
if (!enabled())
return;
if (!checkInMatch())
g_checkMenuEnd = static_cast<int64_t>(bozo::det::frame());
if (inMatch())
return;
g_lastMenuFrame = hostSeconds();
publish();
+65
View File
@@ -2,6 +2,7 @@
// BozoEngine (bozo/port.h). The fork's scheduler experiments, GS lag, VIF1 thread and IOP defaults stayed behind with
// the emulation (BozoEngine's phase4-inventory.md section 3).
#include "bozo/state.h"
#include "tmb_port.h"
#include "bozo/app/determinism.h"
@@ -55,6 +56,17 @@ namespace tmb::cheats
void logProgress(uint8_t *rdram, uint32_t gp);
}
namespace tmb::menu
{
void install(tmb::Registry &runtime);
}
namespace tmb::widescreen
{
void update(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, bool match);
void install(tmb::Registry &runtime);
}
namespace tmb::meshes
{
void install(tmb::Registry &runtime);
@@ -495,6 +507,7 @@ namespace
g_lastMatchFrameNoted.store(hitchClock(), std::memory_order_relaxed);
tmb::cheats::onFrame(rdram); // the Cheats tab (runtime/tmb_cheats.cpp)
const uint32_t gp = getRegU32(ctx, 28);
tmb::widescreen::update(rdram, ctx, runtime, true); // widescreen: the match's views (runtime/tmb_widescreen.cpp)
tmb::native::onFrameEnd(); // TMB_NATIVE: publish the frame's native draws
timerEndOfRealTimeProcessing__Fv_0x1f67f0(rdram, ctx, runtime);
int32_t *frameTicks = reinterpret_cast<int32_t *>(rdram + ((gp + kFrameTicksGpOffset) & 0x1FFFFFFu));
@@ -544,6 +557,7 @@ namespace
{
g_pacer.setCap(static_cast<uint32_t>(fieldRate(rdram, gp)));
g_pacer.setPaced(bozo::port::realTime(runtime)); // a headless or checked run is not held to real time
tmb::widescreen::update(rdram, ctx, runtime, false); // the window's picture shape as the views are now
tmb::native::onMenuFrameEnd(); // TMB_NATIVE: publishes a menu frame's native draws (not in a match)
const double step = g_pacer.frameEnd();
tmb::cheats::logProgress(rdram, gp); // TMB_LOG_PROGRESS
@@ -848,6 +862,44 @@ namespace
const char *value = std::getenv("TMB_KILL_ENEMIES");
return value && *value ? static_cast<uint32_t>(std::atof(value) * 50.0) : 0u;
}();
// TMB_KILL_PLAYER=<s> (testing, story's lost lives and game over): player 1's car takes the same hit every <s>
// seconds.
static const uint32_t s_playerInterval = []
{
const char *value = std::getenv("TMB_KILL_PLAYER");
return value && *value ? static_cast<uint32_t>(std::atof(value) * 50.0) : 0u;
}();
static uint32_t s_playerUpdates = 0;
if (s_playerInterval != 0u && g_theGame != 0u && ++s_playerUpdates % s_playerInterval == 0u)
{
float health = 0.0f;
std::memcpy(&health, rdram + ((0x00257B50u + 1012u) & 0x1FFFFFFu), 4);
if (health > 0.0f)
{
rdram[0x00257B50u + 0x475u] = 1u; // takes hits (0 in a story started past the first level)
R5900Context call = *ctx;
SET_GPR_U32(&call, 4, 0x00257B50u);
SET_GPR_U32(&call, 5, 0x00257B50u);
SET_GPR_U32(&call, 6, 10000u);
// The attacker: the first opponent still alive (the player's own index, 0, does no damage).
int32_t count = 0, attacker = 1;
std::memcpy(&count, rdram + ((g_theGame + 0x001B3DB4u) & 0x1FFFFFFu), 4);
for (int32_t index = 1; index < std::min(count, 64); ++index)
{
float other = 0.0f;
std::memcpy(&other, rdram + ((g_theGame + static_cast<uint32_t>(index) * 0x2D00u + 1012u) & 0x1FFFFFFu), 4);
if (other > 0.0f)
{
attacker = index;
break;
}
}
SET_GPR_U32(&call, 7, static_cast<uint32_t>(attacker));
vehicleTakeHit__7VehicleP8_fvectorii_0x1ad208(rdram, &call, runtime);
std::memcpy(&health, rdram + ((0x00257B50u + 1012u) & 0x1FFFFFFu), 4);
std::fprintf(stderr, "[tmb:kill] player 1 hit by vehicle %d: health %.0f\n", attacker, health);
}
}
static uint32_t s_updates = 0;
if (s_interval == 0u || g_theGame == 0u || ++s_updates % s_interval != 0u)
return;
@@ -1138,6 +1190,8 @@ namespace
runtime.registerFunction(kMtapPortClose, &mtapPortClose);
runtime.registerFunction(kMtapGetConnection, &mtapGetConnection);
tmb::cheats::install(runtime); // TMB_NO_AI, infinite health / ammo / energy, weak enemies (runtime/tmb_cheats.cpp)
tmb::menu::install(runtime); // PC SETTINGS in the game's Options screen (runtime/tmb_menu.cpp)
tmb::widescreen::install(runtime); // the dialogs over a widescreen match back at 640 (runtime/tmb_widescreen.cpp)
if (const char *fx = std::getenv("TMB_FX_TEST"); fx && *fx)
{
g_fxTest.period = std::max(0.5, std::atof(fx));
@@ -1179,4 +1233,15 @@ namespace tmb
}
}
namespace tmb
{
// Save states (tmb_state.cpp): the overrides' own state (the frame pacing's parity, carry and clock debt, the
// movie sound's queue).
void overridesState(bozo::state::Archive &a)
{
bozo::state::fields(a, g_syncVParity, g_frameEndCycle, g_fieldCarry, g_clockDebt, g_theGame, g_moviePcm, g_pcmCalls,
g_sendCalls);
}
}
BOZO_PORT("Twisted Metal - Black (USA)", "SCUS_971.01", kTmbPalEntry, &applyTmb)
+57 -6
View File
@@ -48,6 +48,8 @@
// TMB_NATIVE_PARTICLES_CHECK=1 (a diagnostic): nothing drawn here; types 1, 4, 6 (not on a sphere), 7 and 8 computed and
// compared with what runtime/tmb_native.cpp's translations draw from the same systems' packets.
#include "bozo/state.h"
#include "bozo/libs/crt_math.h"
#include "tmb_port.h"
#include "bozo/render/renderer.h"
#include "bozo/render/texture.h"
@@ -67,7 +69,8 @@
namespace tmb::native
{
bool enabled();
bool effectsInStream();
bool checkedEffects();
bool checkedFlares();
uint64_t nextStreamGroup();
bool flareDepthNative();
bool flareDepthBlock(uint32_t x0, uint32_t y0, uint32_t z[16]);
@@ -1665,7 +1668,8 @@ namespace tmb::particles
// sways: its homogeneous x (head and tail) plus 160 sin(a), a from the flake two before (the sine of one flake is
// read in the next one's step, which moves the flake after it): a = (|f - 1/2| - 1/4) 2 pi, f = frac(W - VU 12.w),
// W the flake's random number (VU1's, seeded from VU 21.x; the first flake's W is VU 15.z, the second's sway
// sin(1) from the prologue). Dropped when a corner leaves the guard band (as the rain).
// sin(1) from the prologue; the reference C runtime's sine, crtSinf, the same bits on every platform). Dropped when
// a corner leaves the guard band (as the rain).
void drawSnow(Batch &batch, const Precip &s, const ViewConstants &view)
{
const float(&c5)[4] = view.vu[5];
@@ -1675,7 +1679,7 @@ namespace tmb::particles
DropWalk walk(s);
uint32_t random = vuRandNext(vuRandInit(s.mul[0])); // RINIT vf19x; the prologue's RNEXT
float weight = s.step[2]; // the first flake's W: VU 15.z
float sway = 0.0f, swayNext = 160.0f * std::sin(1.0f);
float sway = 0.0f, swayNext = 160.0f * bozo::libs::crtSinf(1.0f);
for (uint32_t n = 0; n < s.drops; ++n, walk.advance())
{
float h[4], t[4];
@@ -1690,7 +1694,7 @@ namespace tmb::particles
f += 1.0f;
const float angle = (std::fabs(f) - 0.25f) * 6.28319f;
sway = swayNext;
swayNext = 160.0f * std::sin(angle);
swayNext = 160.0f * bozo::libs::crtSinf(angle);
random = vuRandNext(random);
weight = vuRandFloat(random);
if (h[3] == 0.0f || t[3] == 0.0f)
@@ -2414,7 +2418,8 @@ namespace tmb::particles
const uint32_t view = getRegU32(ctx, 4), gp = getRegU32(ctx, 28);
g_view = view;
const bool toggledAll = toggledOff() && !settings().toggleFlares;
if (!settings().on || (!bozo::port::nativeGraphics(runtime) && !tmb::native::effectsInStream()) ||
// Without native graphics (only the reference checker, tmb-check) as the reference chose (checkedEffects).
if (!settings().on || (!bozo::port::nativeGraphics(runtime) && !tmb::native::checkedEffects()) ||
u32(rdram, gp + static_cast<uint32_t>(kGpColours)) == 0u || toggledAll)
{
g_flaresNative = false;
@@ -2423,8 +2428,9 @@ namespace tmb::particles
return;
}
// The lens flares here too unless left to the game (the check, TMB_NATIVE_PARTICLES_FLARES=0, the flares' toggle
// period, the native depth off: their GS readback then).
// period, the native depth off: their GS readback then; in the reference checker outside a match, checkedFlares).
const bool flaresNative = settings().flares && !settings().check && !(settings().toggleFlares && toggledOff()) &&
(bozo::port::nativeGraphics(runtime) || tmb::native::checkedFlares()) &&
tmb::native::flareDepthNative();
// The frustum (viewGetWH, viewGetFov): the half extents' slopes and the sphere test's factors.
@@ -2637,4 +2643,49 @@ namespace tmb::particles
runtime.registerFunction(kLensRender, &lensRenderOverride);
std::fprintf(stderr, "[tmb:particles] native particles on (types mask %#x)\n", settings().types);
}
// Save states (tmb_state.cpp): the stripes' scroll, the arcs' VU records and the texture choices, per system.
void state(bozo::state::Archive &a)
{
uint64_t n = bozo::state::count(a, g_stripes.size());
if (!a.loading())
for (auto &[ps, st] : g_stripes)
{
uint32_t key = ps;
bozo::state::io(a, key);
bozo::state::pod(a, st);
}
else
{
g_stripes.clear();
for (uint64_t i = 0; i < n; ++i)
{
uint32_t key = 0;
StripeState st;
bozo::state::io(a, key);
bozo::state::pod(a, st);
g_stripes[key] = st;
}
}
n = bozo::state::count(a, g_arcs.size());
if (!a.loading())
for (auto &[ps, st] : g_arcs)
{
uint32_t key = ps;
bozo::state::io(a, key);
bozo::state::pod(a, st);
}
else
{
g_arcs.clear();
for (uint64_t i = 0; i < n; ++i)
{
uint32_t key = 0;
ArcState st;
bozo::state::io(a, key);
bozo::state::pod(a, st);
g_arcs[key] = st;
}
}
bozo::state::io(a, g_texIndex);
}
}
+53
View File
@@ -0,0 +1,53 @@
// Save states: TMB's section (tmb_state.h). The engine saves the runtime, its libraries (989SND included) and the host;
// this adds what TMB keeps itself: what the game told its hooks once, the native renderer's retained records, and the
// overrides' own counters. Caches decoded from guest memory are dropped on a load.
#include "tmb_state.h"
#include "tmb_scene.h"
#include "bozo/host/free_host.h"
#include "bozo/state.h"
#include <string>
#include <type_traits>
namespace tmb
{
void overridesState(bozo::state::Archive &a); // tmb_overrides.cpp
namespace meshes { void state(bozo::state::Archive &); }
namespace textures { void state(bozo::state::Archive &); }
namespace particles { void state(bozo::state::Archive &); }
namespace cheats { void state(bozo::state::Archive &); }
namespace twod { void stateLoaded(); }
namespace menu { void stateLoaded(); }
void addStateSection(bozo::host::FreeHost &host, Runtime *runtime)
{
host.stateSections()->add({"tmb",
[runtime](bozo::state::Archive &a) {
overridesState(a);
// The native hierarchy's retained records (the frames, lights, renderer
// parameters the game's VU programs kept between draws).
static_assert(std::is_trivially_copyable_v<scene::Scene>);
a.begin("scene");
bozo::state::pod(a, scene::get(runtime));
a.end();
a.begin("meshes");
meshes::state(a);
a.end();
a.begin("textures");
textures::state(a);
a.end();
a.begin("particles");
particles::state(a);
a.end();
cheats::state(a);
if (a.loading())
{
twod::stateLoaded();
menu::stateLoaded();
}
},
[] { return std::string(); }});
}
}
+16
View File
@@ -0,0 +1,16 @@
// Save states: TMB's own part of BozoEngine's save states (BozoEngine/docs/save-states.md).
#pragma once
#include "bozo/runtime.h"
namespace bozo::host
{
class FreeHost;
}
namespace tmb
{
// Adds the "tmb" section to the host's save states: what TMB's overrides and native code keep about the game.
// On a load, the caches decoded from the old run's guest memory are dropped.
void addStateSection(bozo::host::FreeHost &host, Runtime *runtime);
}
+703 -586
View File
File diff suppressed because it is too large. Load diff
+254
View File
@@ -0,0 +1,254 @@
// Widescreen (the Video settings' widescreen, video.ini): in a match whose views are each the screen's full width (one
// player, or two players one above the other), the game is made to draw a 16:9 picture. Each view's width goes from
// 640 to 853 pixels about the same centre, then the game's own viewTweakSetFov (0x1FDEA0: viewSetFov for every view,
// with its horizontal FOV and the view's definition) rebuilds the frustum planes it culls with and the projection it
// clips with from that width. The game then projects, culls and clips a scene 4/3 as wide with the same focal length:
// more at the sides, nothing stretched. The 3D screen (tmb_native.cpp) and the 2D overlay (the views' union,
// tmb_2d.cpp) follow the views' width; the HUD, drawn about the screen's centre in its 640 pixels, stays in the middle;
// the window shows a 16:9 picture (bozo::app::setPictureAspect, through the menu's hooks) while a view is wide.
//
// The views, from the game's code: viewNumViews (0x4FBC44) views, each a 16-byte record at 0x4DFCD0 whose word +4 is
// its viewport (viewGetWH: width u16 +4, height +6; viewSetFov's planes and projection from them). viewCreate makes
// them again at each screen's start (the menus get theirs back at 640), so only a match frame's end widens them, and
// one ends them narrow again when widescreen is switched off or the layout is split in four.
//
// The dialogs over a match (displayDialog 0x163500: the pause, the results, won and lost) lay their text and darkening
// out for a 640-wide view (centred at x 320 from the view's left edge, the band 640 wide), and with one player the
// pause keeps the match's view: so the views go back to 640 before the dialog starts (its picture 4:3, centred), and the
// match's next frame end widens them again.
//
// The HUD (a match's, one or two players over and under): its two clusters are hier meshes on coordinate systems the
// game hangs in front of the camera each frame (Hud::updateHUDPosition 0x13CC90: the view's matrix, its translation
// plus the cluster's camera-space offset, Hud + 0x810 the radar's, + 0x820 the weapon's, x right, y the depth). Seen
// through the same focal length D (viewport + 0) they keep their 4:3 places; for the 16:9 picture each goes out by
// the width gained on its side, (w - 640) / 2 pixels, that is x - / + that * y / D for the call (the offsets put back
// after it, so a narrowed view finds them as the game set them). The radar's centre and its blips follow (computed in
// the same call); the markers and bars over the cars are the world's. (The game reaches both Hud functions by a jump
// from TheGame's HudUpdateHUDPosition 0x15BD20 and HudUpdate 0x15BD40, which are the ones overridden.) The HUD's text
// drawn from a 640 layout (Hud::Update 0x13D908: the ammo count and KILLS on the right, DEMO in the middle) goes with its cluster: x past 400
// by the width gained, x past 240 by half of it, from the view's left edge (fontBuildPrim's).
//
// Off (the default) or in the headless program (no hooks), nothing changes: replays and the reference check are the
// game's own picture.
#include "tmb_port.h"
#include "tmb_menu.h"
#include <algorithm>
#include <atomic>
#include <vector>
#include <cstring>
namespace tmb::widescreen
{
namespace
{
constexpr uint32_t kViews = 0x004DFCD0u, kNumViews = 0x004FBC44u, kViewTweakSetFov = 0x001FDEA0u,
kDisplayDialog = 0x00163500u, kHudPositionCall = 0x0015BD20u, kHudUpdateCall = 0x0015BD40u,
kFontPrintXY = 0x001C44A8u, kFontPrintCenteredXY = 0x001C44D8u;
constexpr uint32_t kViewFovH = 0x004FBC04u, kHuds = 0x001ABE50u, kHudStride = 0xA00u, kRadarOffset = 0x810u,
kWeaponOffset = 0x820u;
constexpr uint16_t kNarrow = 640, kWide = 853; // 640 * 4 / 3
constexpr float kWideAspect = 16.0f / 9.0f;
std::atomic<bool> g_wide{false};
// Every viewport widened (the views' records point at a few fixed ones, which viewCreate hands out again: the
// pause's full-screen view may be one widened earlier in the match and not shown since), narrowed together.
std::vector<uint32_t> g_widened;
float g_aspectSet = -1.0f;
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
uint16_t half(const uint8_t *rdram, uint32_t address)
{
uint16_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFEu), 2);
return value;
}
void setHalf(uint8_t *rdram, uint32_t address, uint16_t value) { std::memcpy(rdram + (address & 0x1FFFFFEu), &value, 2); }
float flt(const uint8_t *rdram, uint32_t address)
{
float value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFCu), &value, 4); }
// The view's viewport (0 none).
uint32_t viewport(const uint8_t *rdram, uint32_t view)
{
const uint32_t v = word(rdram, kViews + view * 16u + 4u);
return v >= 0x100000u && v < 0x2000000u ? v : 0u;
}
}
namespace
{
// The game's own rebuild of every view's frustum and projection, on a copy of the context (guest code there
// never leaves the override: BozoEngine kernel.md section 3b), its stack below the thread's.
void rebuildViews(uint8_t *rdram, const R5900Context *ctx, PS2Runtime *runtime)
{
R5900Context copy = *ctx;
SET_GPR_U32(&copy, 29, (getRegU32(ctx, 29) - 0x200u) & ~0xFu);
copy.leaving = 0;
copy.pc = kViewTweakSetFov;
viewTweakSetFov__Fv_0x1fdea0(rdram, &copy, runtime);
}
}
namespace
{
// Every widened viewport back at 640; whether one was.
bool narrowAll(uint8_t *rdram)
{
bool changed = false;
for (const uint32_t vp : g_widened)
if (half(rdram, vp + 4u) == kWide)
setHalf(rdram, vp + 4u, kNarrow), changed = true;
g_widened.clear();
return changed;
}
}
bool wide() { return g_wide.load(std::memory_order_relaxed); }
float screenWidth() { return wide() ? kNarrow * 4.0f / 3.0f : static_cast<float>(kNarrow); }
// At a frame's end: in a match (`match`), the views widened or narrowed as the setting and the layout want; at
// every frame end, whether a view is wide now and the window's picture shaped to it.
void update(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, bool match)
{
if (!bozo::port::nativeGraphics(runtime))
return;
const tmb::menu::Hooks h = tmb::menu::currentHooks();
if (!h.setPictureAspect)
return; // the headless program: no window, no widescreen
const uint32_t count = std::min<uint32_t>(word(rdram, kNumViews), 4u);
if (match)
{
bool fullWidth = count > 0u;
for (uint32_t i = 0; i < count; ++i)
{
const uint32_t vp = viewport(rdram, i);
const uint16_t w = vp ? half(rdram, vp + 4u) : 0;
fullWidth = fullWidth && (w == kNarrow || w == kWide);
}
const bool want = fullWidth && h.widescreen && h.widescreen();
bool changed = false;
for (uint32_t i = 0; i < count; ++i)
if (const uint32_t vp = viewport(rdram, i))
{
const uint16_t w = half(rdram, vp + 4u);
if (want && w == kNarrow)
{
setHalf(rdram, vp + 4u, kWide), changed = true;
if (std::find(g_widened.begin(), g_widened.end(), vp) == g_widened.end())
g_widened.push_back(vp);
}
}
if (!want)
changed = narrowAll(rdram) || changed;
if (changed)
rebuildViews(rdram, ctx, runtime);
}
bool anyWide = false;
for (uint32_t i = 0; i < count; ++i)
if (const uint32_t vp = viewport(rdram, i))
anyWide = anyWide || half(rdram, vp + 4u) == kWide;
g_wide.store(anyWide, std::memory_order_relaxed);
const float aspect = anyWide ? kWideAspect : 0.0f;
if (aspect != g_aspectSet)
{
g_aspectSet = aspect;
h.setPictureAspect(aspect);
}
}
namespace
{
// displayDialog(type): the views narrow again first (above), then the game's dialog.
void displayDialogOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (bozo::port::nativeGraphics(runtime))
{
if (narrowAll(rdram))
{
rebuildViews(rdram, ctx, runtime);
g_wide.store(false, std::memory_order_relaxed);
const tmb::menu::Hooks h = tmb::menu::currentHooks();
if (h.setPictureAspect)
h.setPictureAspect(0.0f), g_aspectSet = 0.0f;
}
}
displayDialog__F13_shellOverlay_0x163500(rdram, ctx, runtime);
}
}
namespace
{
// TheGame::HudUpdateHUDPosition(this, i) (0x15BD20, which jumps on to Hud::updateHUDPosition of the Hud at
// TheGame + 0x1ABE50 + i * 0xA00): the clusters' offsets out by the width gained, for the call (above).
void updateHudPositionOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
// The focal length every view is given (viewTweakSetFov's viewFovH), while the match's views are wide.
const uint32_t hud = getRegU32(ctx, 4) + kHuds + getRegU32(ctx, 5) * kHudStride;
const float d = flt(rdram, kViewFovH);
if (!bozo::port::nativeGraphics(runtime) || !wide() || !(d > 1.0f))
{
HudUpdateHUDPosition__7TheGamei_0x15bd20(rdram, ctx, runtime);
return;
}
const float gained = (kWide - kNarrow) * 0.5f;
const float radar = flt(rdram, hud + kRadarOffset), weapon = flt(rdram, hud + kWeaponOffset);
setFlt(rdram, hud + kRadarOffset, radar - gained * flt(rdram, hud + kRadarOffset + 4u) / d);
setFlt(rdram, hud + kWeaponOffset, weapon + gained * flt(rdram, hud + kWeaponOffset + 4u) / d);
// On a copy of the context: the call ends here (it never leaves), so the offsets go back after all of it.
R5900Context copy = *ctx;
copy.leaving = 0;
HudUpdateHUDPosition__7TheGamei_0x15bd20(rdram, &copy, runtime);
setFlt(rdram, hud + kRadarOffset, radar);
setFlt(rdram, hud + kWeaponOffset, weapon);
ctx->pc = getRegU32(ctx, 31);
}
bool g_inHudUpdate = false;
void hudUpdateOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_inHudUpdate = true;
HudUpdate__7TheGamei_0x15bd40(rdram, ctx, runtime); // on to Hud::Update
g_inHudUpdate = false;
}
// fontSpritePrintXY / CenteredXY (font, x, y, text) from Hud::Update: x from its 640 layout, moved with its cluster.
void shiftHudText(R5900Context *ctx)
{
if (!g_inHudUpdate || !wide())
return;
const int32_t x = static_cast<int32_t>(getRegU32(ctx, 5));
const int32_t gained = kWide - kNarrow;
SET_GPR_U32(ctx, 5, static_cast<uint32_t>(x > 400 ? x + gained : x > 240 ? x + gained / 2 : x));
}
void fontPrintXYOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
shiftHudText(ctx);
fontSpritePrintXY__FiiiPc_0x1c44a8(rdram, ctx, runtime);
}
void fontPrintCenteredXYOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
shiftHudText(ctx);
fontSpritePrintCenteredXY__FiiiPc_0x1c44d8(rdram, ctx, runtime);
}
}
void install(tmb::Registry &runtime)
{
runtime.registerFunction(kDisplayDialog, &displayDialogOverride);
runtime.registerFunction(kHudPositionCall, &updateHudPositionOverride);
runtime.registerFunction(kHudUpdateCall, &hudUpdateOverride);
runtime.registerFunction(kFontPrintXY, &fontPrintXYOverride);
runtime.registerFunction(kFontPrintCenteredXY, &fontPrintCenteredXYOverride);
}
}
+16
View File
@@ -0,0 +1,16 @@
// The host's floating-point control word (MXCSR) in the native tests.
//
// BozoEngine's ps2f takes the host's own float add / mul where it gives the PS2's bits (operands and result normal,
// rounded to nearest: BozoEngine e1518bf). So the game's original code is exact only when the host rounds to nearest,
// as the game runs, and it leaves the sticky status flags set as SSE does. The tests run the original at the caller's
// word rounding to nearest (its flush-to-zero and denormals-are-zero kept, which both sides follow), the native code at
// the caller's varied word, and compare the control word without the six status flags (nothing reads them).
#pragma once
namespace tmb::test
{
// The word the original runs at: the caller's, rounding to nearest, the status flags clear.
inline unsigned referenceControl(unsigned control) { return control & ~0x603fu; }
// The control part equal: rounding, flush to zero, denormals-are-zero, the masks (not the status flags).
inline bool sameControl(unsigned a, unsigned b) { return ((a ^ b) & ~0x3fu) == 0; }
}
+8 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_contact_math.h"
#include "tmb_native_math.h"
#include "tmb_contact_original.h"
@@ -201,7 +202,7 @@ namespace
if (kind == 6 && ctx.pc == 0xbad0000) return;
throw std::runtime_error("contact continuation did not reach query boundary");
};
const auto control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const auto control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
auto a = initial, b = initial;
_mm_setcsr(control); run(false, a); const auto refControl = _mm_getcsr(); const auto refYields = services.yields;
for (unsigned i = 0; i < outputs; ++i) std::memcpy(ram + output[i] + 12, payload(output[i]) + 12, 4);
@@ -215,10 +216,10 @@ namespace
const bool untouched = !std::memcmp(reinterpret_cast<uint8_t *>(&initial) + vuAt, reinterpret_cast<uint8_t *>(&b) + vuAt, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&a) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&b) + vuAt, 0, vuBytes);
if (std::memcmp(&a, &b, sizeof(a)) || !untouched || after != refControl || refYields != services.yields ||
if (std::memcmp(&a, &b, sizeof(a)) || !untouched || !tmb::test::sameControl(after, refControl) || refYields != services.yields ||
std::memcmp(expectedAll.get(), ram + base, bytes) || std::memcmp(expectedAll.get() + bytes, ram + globals, globalBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{ std::fprintf(stderr, "FAIL contact continuation %u case %u mode %u CPU%d VU%d FP%d data%d globals%d\n",kind,n,mode,std::memcmp(&a,&b,sizeof(a)),untouched,after==refControl,std::memcmp(expectedAll.get(),ram+base,bytes),std::memcmp(expectedAll.get()+bytes,ram+globals,globalBytes)); throw std::runtime_error("contact continuation differs"); }
{ std::fprintf(stderr, "FAIL contact continuation %u case %u mode %u CPU%d VU%d FP%d data%d globals%d\n",kind,n,mode,std::memcmp(&a,&b,sizeof(a)),untouched,tmb::test::sameControl(after, refControl),std::memcmp(expectedAll.get(),ram+base,bytes),std::memcmp(expectedAll.get()+bytes,ram+globals,globalBytes)); throw std::runtime_error("contact continuation differs"); }
++cases;
}
host.enabled = true; rt.services = nullptr;
@@ -279,11 +280,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -292,10 +294,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL contact block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
+8 -7
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Run the generated BSP collision setup through its real XYZ consumers. No copied game code is committed.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "bozo/libs/libraries.h"
@@ -123,7 +124,7 @@ void testDirectionCallers()
const float radius = 6.5f; std::memcpy(&initial.fu[20], &radius, 4);
std::memcpy(input.get(), ram + 0x10000, arenaBytes);
std::memcpy(input.get() + arenaBytes, ram + globals, globalBytes);
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](RecompiledFunction direction, R5900Context &ctx)
{
services.yields = 0; rt->functions.setOverride(0x1da298, direction);
@@ -145,7 +146,7 @@ void testDirectionCallers()
std::memcpy(ram + 0x10000, input.get(), arenaBytes);
std::memcpy(ram + globals, input.get() + arenaBytes, globalBytes);
run(nativeDirection, b); const unsigned after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != control || referenceYields != services.yields ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, control) || referenceYields != services.yields ||
std::memcmp(expected.get(), ram + 0x10000, arenaBytes) ||
std::memcmp(expected.get() + arenaBytes, ram + globals, globalBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
@@ -248,7 +249,7 @@ void testDirectionCallers()
setRegU32(&initial, 6, address(output)); word(output + 12, bits());
// Both light directions may execute in one continuation; both opaque W words must stay untouched.
std::memcpy(input.get(), ram + 0x10000, arenaBytes);
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](RecompiledFunction direction, R5900Context &ctx)
{
services.yields = 0; rt->functions.setOverride(0x1da298, direction);
@@ -269,12 +270,12 @@ void testDirectionCallers()
_mm_setcsr(control); run(nativeDirection, b);
const unsigned after = _mm_getcsr(); _mm_setcsr(saved);
// Original scalar normalization can raise host exception flags; compare its complete FP effects too.
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != referenceControl || referenceYields != services.yields ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, referenceControl) || referenceYields != services.yields ||
std::memcmp(expected.get(), ram + 0x10000, arenaBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL vehicle/light caller %x case %u mode %u CPU%d data%d FP%d yields %u/%u\n",
caller, n, mode, cpuEqual(a, b), std::memcmp(expected.get(), ram + 0x10000, arenaBytes), after == referenceControl,
caller, n, mode, cpuEqual(a, b), std::memcmp(expected.get(), ram + 0x10000, arenaBytes), tmb::test::sameControl(after, referenceControl),
referenceYields, services.yields);
throw std::runtime_error("vehicle/light direction consumer differs");
}
@@ -307,7 +308,7 @@ void testDirectionCallers()
const uint32_t alias = n % 3 == 0 ? 0x80000000 : n % 3 == 1 ? 0x20000000 : 0;
setRegU32(&initial, 4, vehicle | alias); setRegU32(&initial, 5, n % 4);
setRegU32(&initial, 29, sp | alias); initial.pc = 0x118178; initial.cycleLimit = 0;
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](R5900Context &ctx)
{
services.yields = 0;
@@ -324,7 +325,7 @@ void testDirectionCallers()
const uint32_t poisonedW = bits(); std::memcpy(ram + result + 12, &poisonedW, 4);
_mm_setcsr(control); run(b); const auto after = _mm_getcsr(); _mm_setcsr(saved);
std::memcpy(ram + result + 12, input.get() + result - 0x10000 + 12, 4);
require(!std::memcmp(&a, &b, sizeof(a)) && after == referenceControl && services.yields == referenceYields &&
require(!std::memcmp(&a, &b, sizeof(a)) && tmb::test::sameControl(after, referenceControl) && services.yields == referenceYields &&
!std::memcmp(expected.get(), ram + 0x10000, arenaBytes) &&
(n >= 4 || !std::memcmp(whole.get(), ram, bozo::kFlatBytes)), "contact position W affected XYZ consumer");
++contactCases;
+4 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Real hierarchy helper consumers compiled from the local game ELF; no copied game implementation.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "tmb_hierarchy_math.h"
@@ -2826,7 +2827,7 @@ void testHierarchyHelperCallers()
require(ctx.pc==0xbad0000,"peel-out coordinate-system consumer returned early");
}
};
const unsigned control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
auto a = initial, b = initial; _mm_setcsr(control);
try { run(false, a); }
catch (...) { std::fprintf(stderr, "hierarchy original kind %u case %u\n", kind, n); throw; }
@@ -3467,10 +3468,10 @@ void testHierarchyHelperCallers()
// Full rear-view entries retain the original rotation producer's identity-helper VU writes.
const auto &expectedVu=kind == 148 && sawDirectionEntry ? directionEntry : kind==195 && sawForceInverseEntry ? forceInverseEntry : initial;
if(kind==195 && sawForceInverseEntry) require(vuUntouched(forceReferenceEntry,forceInverseEntry),"force-field original producer effects differ");
if (!cpuEqual(a,b) || !(kind>=236 ? weaponVuRetired(initial,a,b) : vuUntouched(expectedVu,b)) || after != refControl || services.yields != refYields || services.randomCalls != refRandomCalls ||
if (!cpuEqual(a,b) || !(kind>=236 ? weaponVuRetired(initial,a,b) : vuUntouched(expectedVu,b)) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || services.randomCalls != refRandomCalls ||
services.weatherPoints != refWeatherPoints || services.weatherIdentities != refWeatherIdentities || services.spatialCalls != refSpatialCalls || auditedInverseCalls != refAuditedInverseCalls || services.aiActions != refAiActions || services.vehicleLightActions != refVehicleLightActions || services.finalActions != refFinalActions || services.rigidActions != refRigidActions || rigidDirectionCalls != refRigidDirections || driverDirectionCalls != refDriverDirections || services.driverActions != refDriverActions || services.driverQueryEndpoints != refDriverEndpoints || services.collisionActions != refCollisionActions || services.collisionVelocities != refCollisionVelocities || collisionDirectionCalls != refCollisionDirections || attachmentDirectionCalls != refAttachmentDirections || services.attachmentActions != refAttachmentActions || minionDirectionCalls != refMinionDirections || services.minionActions != refMinionActions || services.minionPoints != refMinionPoints || weaponDirectionCalls != refWeaponDirections || services.weaponInputs != refWeaponInputs || services.weaponBases != refWeaponBases || services.weaponOutputs != refWeaponOutputs || services.weaponTargets != refWeaponTargets || !dataEqual() ||
(wholeCase && std::memcmp(whole.get(),ram,bozo::kFlatBytes)))
{ std::fprintf(stderr,"FAIL hierarchy %x case %u mode %u CPU%d VU%d FP%d data%d\n",callers[kind],n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("hierarchy consumer differs"); }
{ std::fprintf(stderr,"FAIL hierarchy %x case %u mode %u CPU%d VU%d FP%d data%d\n",callers[kind],n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("hierarchy consumer differs"); }
++cases;
}
require(aiShotPublications[0] && aiShotPublications[1],"AI fixtures did not publish front/rear attack states");
+11 -7
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Differential checks against complete generated helpers, including the original VCALLMS library path.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_hierarchy_math.h"
#include "bozo/ee/dispatcher.h"
@@ -107,7 +108,7 @@ int main()
d.updateLimit(&initial); // the dispatcher supplies this scheduler cache before executing a helper
R5900Context original=initial,native=initial;
const unsigned control = ((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
if (kind == 2) bspPlaneTest2Vec__FP6_planeP8_fvectorT1T1_0x201660(ram,&original,&rt);
else if (kind) mathfMulVec__FPA3_fP8_fvectorT1_0x1da1e8(ram,&original,&rt);
else hdHatSphereTestAsm__FP8_fvectorfT0T0_0x1cf7c0(ram,&original,&rt);
@@ -119,10 +120,11 @@ int main()
if (n<32) { std::memcpy(full.get(),ram,bozo::kFlatBytes); ++memoryCases; }
std::memcpy(arena,input.data(),input.size());
const auto before=host.microCalls;
_mm_setcsr(control);
(kind == 2 ? plane : kind ? inverse : sphere)(ram,&native,&rt);
nativeMicros += host.microCalls-before;
const unsigned after=_mm_getcsr(); _mm_setcsr(saved);
if (!compareCpu(original,native,initial) || std::memcmp(arena,expected.data(),input.size()) || after!=control ||
if (!compareCpu(original,native,initial) || std::memcmp(arena,expected.data(),input.size()) || !tmb::test::sameControl(after,control) ||
(n<32 && std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{
if(!kind) {
@@ -130,7 +132,7 @@ int main()
for(unsigned v:{14u,15u,17u,18u,20u,21u,22u,23u,24u,27u})std::fprintf(stderr,"vf%u %08x %08x %08x %08x\n",v,original.vu0_vf[v].u[0],original.vu0_vf[v].u[1],original.vu0_vf[v].u[2],original.vu0_vf[v].u[3]);
}
std::fprintf(stderr,"FAIL kind %u mode %u case %u: CPU %d data %d host %d return %x/%x\n",kind,mode,n,
compareCpu(original,native,initial),std::memcmp(arena,expected.data(),input.size()),after==control,
compareCpu(original,native,initial),std::memcmp(arena,expected.data(),input.size()),tmb::test::sameControl(after,control),
getRegU32(&native,2),getRegU32(&original,2));
for (size_t i=0;i<sizeof(native);++i) if ((i<vuAt || i>=vuAt+vuBytes) && ((uint8_t *)&original)[i]!=((uint8_t *)&native)[i])
std::fprintf(stderr,"CPU byte %zu original %02x native %02x\n",i,((uint8_t *)&original)[i],((uint8_t *)&native)[i]);
@@ -155,11 +157,12 @@ int main()
setRegU32(&initial,28,0x14854);setRegU32(&initial,31,0xbad0000);d.updateLimit(&initial);
auto original=initial,native=initial;
const unsigned control=((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
hdHatSphereTestAsm__FP8_fvectorfT0T0_0x1cf7c0(ram,&original,&rt);
_mm_setcsr(control);
const auto before=host.microCalls;sphere(ram,&native,&rt);
const auto after=_mm_getcsr();_mm_setcsr(saved);
if (!compareCpu(original,native,initial) || after!=control || host.microCalls!=before) {
if (!compareCpu(original,native,initial) || !tmb::test::sameControl(after,control) || host.microCalls!=before) {
std::fprintf(stderr,"FAIL sphere edge %u mode %u return %x/%x\n",n,mode,getRegU32(&native,2),getRegU32(&original,2));return 5;
}
++edges;
@@ -196,7 +199,7 @@ int main()
for(auto &v:initial.vu0_vf)for(auto &b:v.u)b=randomBits();initial.vu0_vf[0]={};initial.vu0_vf[0].u[3]=0x3f800000;
d.updateLimit(&initial);auto original=initial,native=initial;
const unsigned control=((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
rt.functions.setOverride(0x201660,&referencePlane);
try { bspVecTestIn__FP8_hierbspP8_fvectorT1_0x201318(ram,&original,&rt); }
catch(const bozo::ee::StopGuest &) { if(original.pc!=0xbad0000)throw; } // recursive root return to dispatcher
@@ -204,10 +207,11 @@ int main()
if(n<8)std::memcpy(full.get(),ram,bozo::kFlatBytes);
std::memcpy(ram+0x10000,callerInput.get(),callerBytes);
rt.functions.setOverride(0x201660,plane);
_mm_setcsr(tmb::test::referenceControl(control)); // the generated caller runs on both sides: the game's rounding
try { bspVecTestIn__FP8_hierbspP8_fvectorT1_0x201318(ram,&native,&rt); }
catch(const bozo::ee::StopGuest &) { if(native.pc!=0xbad0000)throw; }
const unsigned after=_mm_getcsr();_mm_setcsr(saved);
if(!compareCpu(original,native,initial)||std::memcmp(callerExpected.get(),ram+0x10000,callerBytes)||after!=control||
if(!compareCpu(original,native,initial)||std::memcmp(callerExpected.get(),ram+0x10000,callerBytes)||!tmb::test::sameControl(after,tmb::test::referenceControl(control))||
(n<8&&std::memcmp(full.get(),ram,bozo::kFlatBytes))||native.pc!=0xbad0000) {
std::fprintf(stderr,"FAIL complete BSP caller %u mode %u CPU %d data %d pc %x\n",n,mode,compareCpu(original,native,initial),std::memcmp(callerExpected.get(),ram+0x10000,callerBytes),native.pc);return 6;
}
+5 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_hud_math.h"
#include "tmb_native_math.h"
#include "tmb_hud_original.h"
@@ -92,11 +93,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -105,10 +107,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL HUD block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
+5 -3
View File
@@ -1,4 +1,5 @@
// Exact, independent-original comparisons: record values, overlapping memory, the complete CPU ABI and untouched VU state.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "bozo/libs/libraries.h"
@@ -99,7 +100,7 @@ int main()
R5900Context original = initial, native = initial;
// Deliberately vary caller rounding and denormal settings. Native code must restore the whole word.
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
helper.original(rt->memory.flat(), &original, rt.get());
if (helper.direction) // direction outputs are XYZ; the native record contract retains destination W
std::memcpy(arena + (output - physicalBase) + 12, input.data() + (output - physicalBase) + 12, 4);
@@ -110,6 +111,7 @@ int main()
++fullMemoryCases;
}
std::memcpy(arena, input.data(), input.size());
_mm_setcsr(control);
registry.find(helper.address)(rt->memory.flat(), &native, rt.get());
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
@@ -119,11 +121,11 @@ int main()
std::memset(reinterpret_cast<uint8_t *>(&original) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&native) + vuAt, 0, vuBytes);
if (std::memcmp(arena, expected.data(), expected.size()) || std::memcmp(&original, &native, sizeof(native)) ||
!untouched || after != control || (n < 32 && std::memcmp(rt->memory.flat(), wholeRam.get(), bozo::kFlatBytes)))
!untouched || !tmb::test::sameControl(after, control) || (n < 32 && std::memcmp(rt->memory.flat(), wholeRam.get(), bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL %s case %u host mode %u: data %d, CPU %d, untouched VU %d, host control %d\n",
helper.name, n, mode, std::memcmp(arena, expected.data(), expected.size()),
std::memcmp(&original, &native, sizeof(native)), untouched, after == control);
std::memcmp(&original, &native, sizeof(native)), untouched, tmb::test::sameControl(after, control));
for (size_t i = 0; i < arenaBytes; i += 4)
if (std::memcmp(arena + i, expected.data() + i, 4))
{
+7 -6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: MIT
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_projection_math.h"
#include "tmb_vehicle_math.h"
@@ -78,17 +79,17 @@ int main()
setRegU32(&initial,31,caller); initial.pc=kind==2?0x1db0f0:0x1da238;
if(kind==2)setRegU32(&initial,4,(output+(n&15))|alias);
const unsigned control=((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0);
_mm_setcsr(control); auto original=initial,native=initial;
_mm_setcsr(tmb::test::referenceControl(control)); auto original=initial,native=initial;
const auto fn=kind==2?mathfUnitMatrixAsm__FPA3_f_0x1db0f0:mathfMulVec4x4__FPA3_fP8_fvectorT1_0x1da238;
fn(ram,&original,&rt); std::memcpy(expected,ram+flat,512);
if(n<16){std::memcpy(full.get(),ram,bozo::kFlatBytes);++memoryCases;}
std::memcpy(ram+flat,input,512); (kind==2?identity:point)(ram,&native,&rt);
std::memcpy(ram+flat,input,512); _mm_setcsr(control); (kind==2?identity:point)(ram,&native,&rt);
const unsigned after=_mm_getcsr(); _mm_setcsr(saved);
if(std::memcmp(expected,ram+flat,512)||!cpu(original,native,initial)||after!=control||
if(std::memcmp(expected,ram+flat,512)||!cpu(original,native,initial)||!tmb::test::sameControl(after, control)||
(n<16&&std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{
std::fprintf(stderr,"FAIL projection kind%u case%u mode%u data%d CPU%d FP%d\n",kind,n,mode,
std::memcmp(expected,ram+flat,512),cpu(original,native,initial),after==control);return 1;
std::memcmp(expected,ram+flat,512),cpu(original,native,initial),tmb::test::sameControl(after, control));return 1;
}
++cases;
}
@@ -136,7 +137,7 @@ int main()
const uint64_t ret=0xbad0000;std::memcpy(ram+0x30000+0x120,&ret,8);
}
d.updateLimit(&initial); std::memcpy(arenaInput.get(),ram+0x10000,0x40000);
const unsigned control=((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0);
const unsigned control=tmb::test::referenceControl(((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0)); // generated code on both sides: the game's rounding
_mm_setcsr(control); auto a=initial,b=initial;
rt.functions.setOverride(0x1da238,mathfMulVec4x4__FPA3_fP8_fvectorT1_0x1da238);
rt.functions.setOverride(0x1db0f0,mathfUnitMatrixAsm__FPA3_f_0x1db0f0);
@@ -146,7 +147,7 @@ int main()
rt.functions.setOverride(0x1da238,point);rt.functions.setOverride(0x1db0f0,identity);
try{caller(ram,&b,&rt);}catch(const bozo::ee::StopGuest&){require(b.pc==0xbad0000,"native caller stopped early");}
const unsigned after=_mm_getcsr();_mm_setcsr(saved);
if(!cpu(a,b,initial)||std::memcmp(arenaExpected.get(),ram+0x10000,0x40000)||after!=control||
if(!cpu(a,b,initial)||std::memcmp(arenaExpected.get(),ram+0x10000,0x40000)||!tmb::test::sameControl(after, control)||
(n<8&&std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{std::fprintf(stderr,"FAIL caller kind%u case%u mode%u CPU%d\n",kind,n,mode,cpu(a,b,initial));return 2;}
++callers;
+7 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Actual sphere/LOD decisions and hierarchy-helper consumers, compiled from the local game ELF.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "tmb_hierarchy_math.h"
@@ -145,7 +146,7 @@ void testSphereLodCallers()
std::memset(ram + 0x13000, 0, 12); word(0x14000, 0x40400000); word(0x14004, 0x40800000); word(0x14008, 0);
}
snapshot(input.get()); auto a = initial, b = initial;
const unsigned control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
host.enabled = false; services.yields = 0; services.stop = 0xffffffff;
_mm_setcsr(control);
try { function(ram, &a, rt.get()); }
@@ -156,9 +157,9 @@ void testSphereLodCallers()
snapshot(expected.get()); if (n < 4) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++memoryCases; }
restore(); host.enabled = true; services.yields = 0;
_mm_setcsr(control); function(ram, &b, rt.get()); const auto after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != refControl || services.yields != refYields || !dataEqual() ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || !dataEqual() ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{ std::fprintf(stderr, "FAIL sphere/LOD kind %u case %u mode %u CPU%d VU%d FP%d data%d\n", kind,n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("sphere/LOD caller differs"); }
{ std::fprintf(stderr, "FAIL sphere/LOD kind %u case %u mode %u CPU%d VU%d FP%d data%d\n", kind,n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("sphere/LOD caller differs"); }
require(b.pc == 0xbad0000 && getRegU32(&b, 29) == address(sp), "sphere/LOD return ABI"); ++cases;
}
std::printf("sphere/LOD: %u complete generated callers, %u whole-memory checks; complete CPU/clock/FP/selection exact outside retired VU/local W; native VU untouched\n", cases, memoryCases);
@@ -221,16 +222,16 @@ void testSphereLodCallers()
throw std::runtime_error("hierarchy helper continuation did not reach its query boundary");
};
auto a = initial, b = initial;
const auto control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const auto control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
_mm_setcsr(control);
try { run(false, a); }
catch (...) { std::fprintf(stderr, "hierarchy original kind %u case %u\n", kind, n); throw; }
const auto refControl = _mm_getcsr(); const auto refYields = services.yields;
snapshot(expected.get()); if (n < 4) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++helperMemory; }
restore(); _mm_setcsr(control); run(true, b); const auto after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a,b) || !vuUntouched(initial,b) || after != refControl || services.yields != refYields || !dataEqual() ||
if (!cpuEqual(a,b) || !vuUntouched(initial,b) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || !dataEqual() ||
(n < 4 && std::memcmp(whole.get(),ram,bozo::kFlatBytes)))
{ std::fprintf(stderr,"FAIL hierarchy helper %x case %u mode %u CPU%d VU%d FP%d data%d\n",caller,n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("hierarchy helper consumer differs"); }
{ std::fprintf(stderr,"FAIL hierarchy helper %x case %u mode %u CPU%d VU%d FP%d data%d\n",caller,n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("hierarchy helper consumer differs"); }
++helperCases;
}
_mm_setcsr(saved);
+8 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_vehicle_math.h"
#include "tmb_native_math.h"
#include "tmb_vehicle_original.h"
@@ -100,11 +101,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -113,10 +115,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL vehicle block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
@@ -177,7 +179,7 @@ int main()
for (auto &v : initial.vu0_vf) for (auto &bits : v.u) bits = randomBits();
initial.vu0_vf[0] = Vu0Vector{}; initial.vu0_vf[0].u[3] = 0x3f800000;
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
_mm_setcsr(control);
host.enabled = false;
vehicleSetCsMat__7Vehicle_0x1ab250(ram, &original, rt.get());
@@ -195,10 +197,10 @@ int main()
std::memset(reinterpret_cast<uint8_t *>(&native) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&original) + vuAt, 0, vuBytes);
if (std::memcmp(ram + vehicle, callerExpected.get(), callerBytes) || std::memcmp(&original, &native, sizeof(native)) ||
!untouched || after != control || (n < 4 && std::memcmp(ram, whole.get(), bozo::kFlatBytes)))
!untouched || !tmb::test::sameControl(after, control) || (n < 4 && std::memcmp(ram, whole.get(), bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL complete vehicleSetCsMat case %u mode %u: memory %d CPU %d VU %d host %d\n", n, mode,
std::memcmp(ram + vehicle, callerExpected.get(), callerBytes), std::memcmp(&original, &native, sizeof(native)), untouched, after == control);
std::memcmp(ram + vehicle, callerExpected.get(), callerBytes), std::memcmp(&original, &native, sizeof(native)), untouched, tmb::test::sameControl(after, control));
return 8;
}
if (native.cycles != 16 || native.checkpoints != 2 || native.pc != 0xbad0000) return 9;
+326 -7
View File
@@ -1,5 +1,8 @@
"""Player-facing migration and timing regression checks; no game data required."""
import configparser
import contextlib
import json
import os
import re
import sys
import tempfile
import io
@@ -11,6 +14,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import apply_update
import check_timing
import make_release
import tmb_build
@@ -18,7 +22,7 @@ from unittest.mock import patch
from types import SimpleNamespace
REQUIRED = (
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'recomplauncher.json', 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp',
@@ -123,11 +127,111 @@ class ReleaseTests(unittest.TestCase):
self.assertFalse((root / 'PS2Recomp').exists())
self.assertTrue((root / 'tools/linked').exists())
def test_only_native_engine_is_a_submodule(self):
config = configparser.ConfigParser()
config.read(ROOT / '.gitmodules')
self.assertEqual(config.sections(), ['submodule "BozoEngine"'])
self.assertEqual(config[config.sections()[0]]['path'], 'BozoEngine')
@staticmethod
def release_source(folder, files):
"""A release's source folder: the files, dated as an unzip of the release zip dates them, and its listing."""
root = Path(folder) / 'source'
for name, data in files.items():
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_bytes(data)
(root / 'release_files.txt').write_text(''.join(n + '\n' for n in sorted(files)) + 'release_files.txt\n',
encoding='utf-8')
return root
@staticmethod
def date(root, ns):
for p in root.rglob('*'):
if p.is_file():
os.utime(p, ns=(ns, ns))
def settle(self, root, out, now, kit=None):
with patch.object(tmb_build, 'ROOT', str(root)), contextlib.redirect_stdout(io.StringIO()):
tmb_build.settle_source_times(str(out), kit, now_ns=now)
def test_source_dated_in_the_future_is_dated_now(self):
# Issue 60: the zip's commit time, read as local time west of UTC, is hours ahead; ninja then never settles.
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'CMakeLists.txt': b'project', 'runtime/a.cpp': b'a'})
kit = Path(folder) / 'kit'
(kit / 'deps/sdl3-src').mkdir(parents=True)
(kit / 'deps/sdl3-src/CMakeLists.txt').write_bytes(b'sdl')
module = kit / 'ucrt64/share/cmake/Modules/FindPython.cmake' # build.ninja's input too
module.parent.mkdir(parents=True)
module.write_bytes(b'module')
self.date(root, now + 3 * 3600 * 10**9)
self.date(kit, now + 3 * 3600 * 10**9)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now, str(kit))
for p in (root / 'CMakeLists.txt', root / 'runtime/a.cpp', kit / 'deps/sdl3-src/CMakeLists.txt', module):
self.assertEqual(p.stat().st_mtime_ns, now)
record = json.loads((out / tmb_build.SOURCE_TIMES).read_text(encoding='utf-8'))
self.assertIn('source/runtime/a.cpp', record)
self.assertIn('deps/sdl3-src/CMakeLists.txt', record)
def test_first_build_keeps_past_times(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, now - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now - 10**12)
def test_update_dates_changed_files_now_and_restores_unchanged_ones(self):
# An update unzipped over a game built after the update's commit: its files are older than the build's.
built, commit, now = 1_800_000_000 * 10**9, 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/same.cpp': b'same', 'runtime/fixed.cpp': b'old'})
self.date(root, built - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, built)
(root / 'runtime/fixed.cpp').write_bytes(b'new')
(root / 'runtime/added.cpp').write_bytes(b'added')
with open(root / 'release_files.txt', 'a', encoding='utf-8') as f:
f.write('runtime/added.cpp\n')
self.date(root, commit)
self.settle(root, out, now)
self.assertEqual((root / 'runtime/same.cpp').stat().st_mtime_ns, built - 10**12)
self.assertEqual((root / 'runtime/fixed.cpp').stat().st_mtime_ns, now)
self.assertEqual((root / 'runtime/added.cpp').stat().st_mtime_ns, now)
def test_update_without_a_record_over_a_build_rebuilds_everything(self):
# 0.5.1 and earlier wrote no record: an update over their build cannot tell what changed.
commit, now = 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, commit)
out = Path(folder) / 'build'
(out / 'build').mkdir(parents=True)
(out / 'build/build.ninja').write_bytes(b'')
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now)
def test_checkout_is_left_alone(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = Path(folder) / 'source'
root.mkdir()
(root / 'CMakeLists.txt').write_bytes(b'project')
os.utime(root / 'CMakeLists.txt', ns=(now + 10**12, now + 10**12))
self.settle(root, Path(folder), now)
self.assertEqual((root / 'CMakeLists.txt').stat().st_mtime_ns, now + 10**12)
self.assertFalse((Path(folder) / tmb_build.SOURCE_TIMES).exists())
def test_engine_is_a_pinned_release(self):
# BozoEngine comes from its releases (cmake/bozo_engine.json, fetched by cmake/bozo_engine_fetch.cmake), no
# longer from a submodule.
self.assertFalse((ROOT / '.gitmodules').exists())
pin = json.loads((ROOT / 'cmake/bozo_engine.json').read_text(encoding='utf-8'))
self.assertRegex(pin['version'], r'^[0-9]+\.[0-9]+\.[0-9]+$')
self.assertRegex(pin['sha256'], r'^[0-9a-f]{64}$')
fetch = (ROOT / 'cmake/bozo_engine_fetch.cmake').read_text(encoding='utf-8')
self.assertIn('EXPECTED_HASH SHA256=${bozo_engine_sha256}', fetch)
self.assertIn('/BozoEngine/', (ROOT / '.gitignore').read_text(encoding='utf-8').splitlines())
def test_migration_zip_supports_the_existing_installation_layout(self):
with tempfile.TemporaryDirectory() as folder:
@@ -162,6 +266,106 @@ class ReleaseTests(unittest.TestCase):
archive.writestr('TMB_Recomp_Bozo/source/hidden.dat', b'\x7fELF' + b'\0' * 100)
self.assertTrue(any('an ELF file' in error for error in make_release.verify_zip(path)))
def test_no_bytecode_cache_in_a_release(self):
with tempfile.TemporaryDirectory() as folder:
stage = Path(folder) / 'stage'
(stage / 'source/tools/__pycache__').mkdir(parents=True)
(stage / 'source/tools/__pycache__/tmb_build.cpython-314.pyc').write_bytes(b'cache')
(stage / 'source/tools/tmb_build.py').write_text('x')
make_release.remove_bytecode_caches(str(stage))
self.assertFalse((stage / 'source/tools/__pycache__').exists())
self.assertTrue((stage / 'source/tools/tmb_build.py').exists())
path = Path(folder) / 'cached.zip'
with zipfile.ZipFile(path, 'w') as archive:
for name in REQUIRED:
archive.writestr('TMB_Recomp_Bozo/' + name, b'fixture')
archive.writestr('TMB_Recomp_Bozo/source/tools/__pycache__/tmb_build.cpython-314.pyc', b'cache')
self.assertTrue(any('bytecode cache' in p for p in make_release.verify_zip(str(path))))
tar = self.linux_release(folder, [('source/tools/__pycache__/x.pyc', b'cache')])
self.assertTrue(any('bytecode cache' in p for p in make_release.verify_tar(str(tar))))
def linux_release(self, folder, extra=()):
stage = Path(folder) / 'stage'
for name in make_release.LINUX_REQUIRED:
file = stage / name
file.parent.mkdir(parents=True, exist_ok=True)
file.write_bytes(b'\x7fELF launcher' if name == 'tmb-launcher' else b'version = 0.1.1\n')
(stage / 'tmb-launcher').chmod(0o755)
for name, data in extra:
(stage / name).parent.mkdir(parents=True, exist_ok=True)
(stage / name).write_bytes(data)
path = Path(folder) / 'TMB_Recomp-0.1.1-linux.tar.gz'
make_release.tar_dir(str(stage), str(path), 'TMB_Recomp_Bozo', 1700000000)
return path
def test_linux_release_has_one_folder_the_launcher_and_no_other_elf(self):
with tempfile.TemporaryDirectory() as folder:
good = self.linux_release(folder)
self.assertEqual(make_release.verify_tar(str(good)), [])
with tarfile.open(good) as tf:
if sys.platform != 'win32':
self.assertEqual(tf.getmember('TMB_Recomp_Bozo/tmb-launcher').mode, 0o755)
self.assertEqual(tf.getmember('TMB_Recomp_Bozo/README.txt').mode, 0o644)
bad = self.linux_release(folder, [('source/tool', b'\x7fELF other'), ('game/SCUS_971.01', b'x')])
problems = make_release.verify_tar(str(bad))
self.assertTrue(any('source/tool: an ELF file' in p for p in problems), problems)
self.assertTrue(any('SCUS_971.01' in p for p in problems), problems)
def test_linux_release_is_reproducible(self):
with tempfile.TemporaryDirectory() as a, tempfile.TemporaryDirectory() as b:
self.assertEqual(self.linux_release(a).read_bytes(), self.linux_release(b).read_bytes())
def test_update_installs_a_linux_release_with_its_launcher_executable(self):
with tempfile.TemporaryDirectory() as folder:
path = self.linux_release(folder)
make_release.write_sha256(str(path))
install = Path(folder) / 'install'
(install / 'game').mkdir(parents=True)
(install / 'game/keep.txt').write_bytes(b'player')
out = subprocess.run([sys.executable, '-I', str(ROOT / 'tools/apply_update.py'), '--zip', str(path),
'--sha256', str(path) + '.sha256', '--version', '0.1.1', '--install', str(install),
'--keep-zip'], stdout=subprocess.PIPE, universal_newlines=True)
self.assertEqual(out.returncode, 0, out.stdout)
self.assertIn('done 0.1.1', out.stdout)
self.assertTrue(os.access(install / 'tmb-launcher', os.X_OK) or sys.platform == 'win32')
self.assertEqual((install / 'game/keep.txt').read_bytes(), b'player')
def test_update_refuses_a_link_in_a_linux_release(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'linked.tar.gz'
with tarfile.open(path, 'w:gz') as tf:
link = tarfile.TarInfo('TMB_Recomp_Bozo/source/escape')
link.type, link.linkname = tarfile.SYMTYPE, '/etc'
tf.addfile(link)
with self.assertRaises(apply_update.UpdateError):
apply_update.Archive(str(path))
class LinuxBuildTests(unittest.TestCase):
def test_missing_tools_are_named_with_the_distribution_command(self):
with patch.object(tmb_build.shutil, 'which', lambda name, **_k: None if name == 'ninja' else '/usr/bin/' + name), \
patch.object(tmb_build.subprocess, 'run', lambda cmd, **_k: SimpleNamespace(
returncode=1 if cmd[-1] in ('libavutil', 'x11', 'wayland-client') else 0)):
missing = tmb_build.linux_missing()
self.assertEqual(missing, ['ninja', 'FFmpeg (libavutil)', 'X11 or Wayland (x11 or wayland-client)'])
with patch.object(tmb_build, 'linux_family', lambda: 'fedora'):
self.assertIn('sudo dnf install', tmb_build.linux_missing_message(missing))
with patch.object(tmb_build, 'linux_family', lambda: None):
self.assertIn('sudo apt install', tmb_build.linux_missing_message(missing))
def test_a_linux_kit_gives_the_libraries_sources_and_keeps_the_system_toolchain(self):
with tempfile.TemporaryDirectory() as folder:
kit = Path(folder) / 'kit'
(kit / 'deps').mkdir(parents=True)
(kit / 'kit_manifest.json').write_text('{"platform": "linux"}')
args = SimpleNamespace(out=str(Path(folder) / 'out'), game=None, toolchain=None, fetch_cache=None,
debug_info=None, kit=str(kit), no_kit=False)
build = tmb_build.Build(args)
self.assertEqual(build.kit, str(kit))
self.assertIsNone(args.toolchain)
self.assertIsNone(build.ffmpeg_root)
self.assertEqual(args.fetch_cache, str(kit / 'deps'))
class TimingTests(unittest.TestCase):
LOG = '''[tmb:clock] frame 300: EE 5.000 s, PC 5.000 s, debt 0.0 ms; ticks 2880000 fields 300
@@ -186,5 +390,120 @@ class TimingTests(unittest.TestCase):
self.assertTrue(check_timing.check('')[0].startswith('FAIL:'))
class RecompLauncherTests(unittest.TestCase):
"""recomplauncher.json (RecompLauncher's manifest, recomplauncher.com/sdk) and what it runs."""
def manifest(self):
return json.loads((ROOT / 'recomplauncher.json').read_text(encoding='utf-8'))
def test_progress_lines_follow_the_steps(self):
self.assertEqual(tmb_build.progress_line(('PROGRESS', 'verify', '1/8', 'Checking the disc')),
'progress 0.000 Checking the disc')
before = sum(tmb_build.STEP_WEIGHTS[s] for s in tmb_build.STEPS[:tmb_build.STEPS.index('packs')])
half = (before + tmb_build.STEP_WEIGHTS['packs'] / 2) / sum(tmb_build.STEP_WEIGHTS.values())
self.assertEqual(tmb_build.progress_line(('PERCENT', 'packs', 50)),
'progress %.3f %s (50%%)' % (half, tmb_build.STEP_TITLES['packs']))
for other in (('SKIP', 'verify', '1/8'), ('DONE', 'stage', '8/8', 1.0), ('INFO', 'total', '1 s'),
('ERROR', 'compile', 'x')):
self.assertIsNone(tmb_build.progress_line(other))
self.assertEqual(set(tmb_build.STEP_WEIGHTS), set(tmb_build.STEPS))
# The launcher's own step weights (its progress bar), so both bars move alike.
model = (ROOT / 'launcher' / 'src' / 'build_model.cpp').read_text(encoding='utf-8')
self.assertEqual(dict((k, int(v)) for k, v in re.findall(r'\{"([a-z]+)", ([0-9]+)\}', model)),
tmb_build.STEP_WEIGHTS)
shares = []
for step in tmb_build.STEPS:
for parts in (('PROGRESS', step, '', ''), ('PERCENT', step, 37), ('PERCENT', step, 100)):
shares.append(float(tmb_build.progress_line(parts).split()[1]))
self.assertEqual(shares, sorted(shares))
self.assertTrue(0 <= shares[0] and shares[-1] < 1)
def test_a_missing_disc_says_why_and_an_earlier_build_keeps_one(self):
with tempfile.TemporaryDirectory() as folder:
def run(*extra):
return subprocess.run([sys.executable, '-I', '-X', 'utf8', str(ROOT / 'tools' / 'tmb_build.py'),
'--out', str(Path(folder) / 'build'), '--game', str(Path(folder) / 'game')]
+ list(extra), capture_output=True, text=True, encoding='utf-8')
r = run('--progress-lines')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify no disc image given', r.stdout.strip().splitlines()[-1])
# No --disc: the disc image an earlier build kept in the game folder (keeps_copy). Here it is not a disc.
(Path(folder) / 'game').mkdir()
(Path(folder) / 'game' / 'disc.iso').write_bytes(b'\0' * 65536)
r = run('--check')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify disc.iso', r.stdout)
def test_manifest_runs_what_the_release_ships(self):
m = self.manifest()
self.assertEqual(m['format'], 1)
self.assertEqual(m['repo'], 'TheBozos/TMB_Recomp')
disc = m['inputs'][0]
self.assertEqual(disc['id'], 'game')
self.assertEqual(disc['check']['iso9660'], tmb_build.ELF_NAME)
self.assertEqual(disc['check']['ids'], ['SCUS-97101'])
# Redump's Twisted Metal: Black (USA), SCUS-97101 v1.00: its one dump, a DVD-5 (redump.org/disc/15035).
self.assertEqual(disc['dumps'], [{'name': 'USA', 'size': 3799744512, 'crc32': '347e93f9'}])
prepare, start = m['prepare'], m['start']
# Windows: the kit's Python; Linux: kit/python3, the system's (the first that exists runs).
self.assertEqual(prepare['program'], ['kit/python/python.exe', 'kit/python3'])
self.assertIn('kit/python/python.exe', REQUIRED)
self.assertIn('kit/python3', make_release.LINUX_REQUIRED)
self.assertTrue(make_release.LINUX_PYTHON3.startswith('#!/bin/sh'))
self.assertIn('{install}/source/tools/tmb_build.py', prepare['args'])
self.assertIn('source/tools/tmb_build.py', REQUIRED)
# The disc as one argument: RecompLauncher leaves it out when the player's copy is gone (keeps_copy).
self.assertTrue(prepare['keeps_copy'])
self.assertEqual([a for a in prepare['args'] if '{input:game}' in a], ['--disc={input:game}'])
help_text = subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'tmb_build.py'), '--help'],
capture_output=True, text=True, check=True).stdout
for flag in (a.split('=', 1)[0] for a in prepare['args'] if a.startswith('--')):
self.assertIn(flag, help_text)
self.assertIn('--progress-lines', prepare['args'])
# The working folder is the program's (kit/python): every path RecompLauncher passes is {install}'s.
for a in prepare['args']:
if '/' in a:
self.assertTrue(a.split('=', 1)[-1].startswith(('{install}/', '{input:')), a)
self.assertEqual(prepare['done'], ['{install}/game/built_from.ini'])
self.assertEqual(start['program'], ['game/' + tmb_build.GAME_EXE + '.exe', 'game/' + tmb_build.GAME_EXE])
self.assertEqual(set(m['system']), {'windows', 'linux'})
self.assertEqual(start['args'], ['--elf', '{install}/game/' + tmb_build.ELF_NAME, '--iso',
'{install}/game/disc.iso'])
# Everything the game writes (cards, settings, logs, save states) in RecompLauncher's {data}.
self.assertEqual(start['env'], {'PS2X_USER_DIR': '{data}'})
self.assertEqual(m['saves'], ['{data}/mc0', '{data}/mc1'])
def test_settings_are_keys_the_game_reads(self):
m = self.manifest()
self.assertEqual(m['config'], [{'format': 'ini', 'file': [{'path': '{data}/video.ini'}]}])
source = ROOT / 'BozoEngine' / 'runtime' / 'app' / 'video_settings.cpp'
if not source.is_file():
self.skipTest('no BozoEngine tree (cmake -P cmake/bozo_engine_fetch.cmake)')
written = set(re.findall(r'<< "([a-z_]+) = "', source.read_text(encoding='utf-8')))
self.assertIn('widescreen', written)
ids = [s['id'] for s in m['settings']]
self.assertEqual(len(ids), len(set(ids)))
for setting in m['settings']:
keys = set(setting['defaults'])
for choice in setting['choices']:
self.assertEqual(set(choice['set']), keys, setting['id'])
for key in keys:
section, name = key.split('/')
self.assertEqual(section, 'video')
self.assertIn(name, written)
values = [c['set'][k] for c in setting['choices'] for k in keys]
self.assertEqual(len(values), len(set(values)), setting['id'])
self.assertIn(setting['defaults'], [c['set'] for c in setting['choices']], setting['id'])
def test_release_zip_carries_the_manifest_at_its_top(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'no_manifest.zip'
with zipfile.ZipFile(path, 'w') as archive:
for name in REQUIRED:
if name != 'recomplauncher.json':
archive.writestr('TMB_Recomp_Bozo/' + name, b'fixture')
self.assertIn('TMB_Recomp_Bozo/recomplauncher.json is missing', make_release.verify_zip(path))
if __name__ == '__main__':
unittest.main()
+55 -18
View File
@@ -3,6 +3,7 @@
python -I tools/apply_update.py --zip <TMB_Recomp-x.y.z-bozo.zip> --sha256 <its .sha256 file> --version x.y.z
--install <the release folder> [--keep-zip]
python3 -I tools/apply_update.py --zip <TMB_Recomp-x.y.z-linux.tar.gz> ... (the Linux release)
Checks the zip's SHA-256 against the release's .sha256, checks every name in it (one top folder TMB_Recomp_Bozo/, no
absolute or parent paths, nothing under build/, game/ or update/, the launcher and source/release.ini of the version
@@ -20,10 +21,11 @@ import hashlib
import os
import shutil
import sys
import tarfile
import zipfile
TOP = 'TMB_Recomp_Bozo/' # the BozoEngine build's zip (tools/make_release.py's TOP)
LAUNCHER = 'TMB Launcher.exe'
LAUNCHERS = {'zip': 'TMB Launcher.exe', 'tar': 'tmb-launcher'}
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
@@ -56,11 +58,41 @@ def expected_sha256(path):
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."""
class Archive:
"""A release's zip (Windows) or .tar.gz (Linux): its entries as (name, is_dir, size, mode), read the same way."""
def __init__(self, path):
if tarfile.is_tarfile(path):
self.kind, self.tf = 'tar', tarfile.open(path, 'r:*')
self.members = {}
for m in self.tf.getmembers():
if not (m.isfile() or m.isdir()):
raise UpdateError('unexpected entry in the archive: %r (a link or device)' % m.name)
name = m.name + ('/' if m.isdir() and not m.name.endswith('/') else '')
self.members[name] = m
else:
self.kind, self.zf = 'zip', zipfile.ZipFile(path)
def entries(self):
if self.kind == 'tar':
return [(n, m.isdir(), m.size, m.mode) for n, m in self.members.items()]
return [(i.filename, i.filename.endswith('/'), i.file_size, None) for i in self.zf.infolist()]
def open(self, name):
return self.tf.extractfile(self.members[name]) if self.kind == 'tar' else self.zf.open(name)
def read(self, name):
with self.open(name) as f:
return f.read()
def close(self):
(self.tf if self.kind == 'tar' else self.zf).close()
def checked_names(archive, version):
"""The archive's file entries as (name, size, mode, path under the top folder), after checking every name."""
files = []
for info in zf.infolist():
name = info.filename
for name, is_dir, size, mode in archive.entries():
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):]
@@ -68,12 +100,12 @@ def checked_names(zf, version):
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:
if not is_dir:
files.append((name, size, mode, rel))
rels = {f[3] for f in files}
if LAUNCHERS[archive.kind] 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')
stamp = archive.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
found = ''
for line in stamp.splitlines():
key, _, value = line.partition('=')
@@ -135,24 +167,29 @@ def main():
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)
archive = Archive(args.zip)
try:
files = checked_names(archive, args.version)
total = sum(f[1] for f 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:
for name, size, mode, 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:
with archive.open(name) as src, open(target, 'wb') as dst:
shutil.copyfileobj(src, dst, 1 << 20)
done += info.file_size
if mode is not None:
os.chmod(target, 0o755 if mode & 0o111 else 0o644)
done += size
say('progress', done, total)
finally:
archive.close()
# 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):
for n, (_name, _size, _mode, 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))
@@ -175,6 +212,6 @@ def main():
if __name__ == '__main__':
try:
main()
except (UpdateError, OSError, zipfile.BadZipFile) as e:
except (UpdateError, OSError, zipfile.BadZipFile, tarfile.TarError) as e:
say('error', e)
sys.exit(1)
+24 -10
View File
@@ -2,7 +2,7 @@
"""make_build_kit: assembles the build kit tools/tmb_build.py uses on a PC with nothing installed (no MSYS2, git,
network or Python): a compiler, CMake and Ninja, a minimal static FFmpeg, the libraries' sources (SDL3, Dear ImGui)
and an embeddable Python. The game is built on BozoEngine, whose sources come with TMB_Recomp's (the BozoEngine
submodule, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
release cmake/bozo_engine.json pins, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
developer's PC (MSYS2 UCRT64 installed, network for the downloads); the kit is build output, never committed.
python tools/make_build_kit.py --out D:/tmb_kit/kit [--downloads D:/tmb_kit/downloads] [--zip D:/tmb_kit/kit.zip]
@@ -98,6 +98,15 @@ REALESRGAN = {
'sha256': '6495f972a09ad7f64ccd953e79adba91a93d862edc7135e6d95210bbf4002a01'},
],
}
# The same release's Linux build (--linux: the Linux release's kit). It loads the system's libvulkan and libgomp
# (GCC's OpenMP runtime, there with the compiler the build needs), so nothing beside it is kept.
REALESRGAN_LINUX = dict(REALESRGAN,
url='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/'
'realesrgan-ncnn-vulkan-20220424-ubuntu.zip',
sha256='e5aa6eb131234b87c0c51f82b89390f5e3e642b7b70f2b9bbe95b6a285a40c96',
keep=['realesrgan-ncnn-vulkan', 'models/realesrgan-x4plus.bin',
'models/realesrgan-x4plus.param'],
license='MIT (realesrgan-ncnn-vulkan) and BSD-3-Clause (Real-ESRGAN, its model; ncnn)')
# FetchContent sources: the release archives BozoEngine's CMake files pin (runtime/CMakeLists.txt: URL and URL_HASH),
# unpacked as deps/<name>-src for tmb_build's FETCHCONTENT_SOURCE_DIR_<NAME>. 'top': the archive's top folder.
DEPS = [
@@ -632,26 +641,30 @@ class Kit:
# -- realesrgan
def step_realesrgan(self):
z = download(REALESRGAN, self.downloads)
spec = REALESRGAN_LINUX if self.args.linux else REALESRGAN
z = download(spec, self.downloads)
dst = os.path.join(self.out, 'realesrgan')
rmtree(dst)
with zipfile.ZipFile(z) as zf:
names = set(zf.namelist())
for keep in REALESRGAN['keep']:
for keep in spec['keep']:
if keep not in names:
raise KitError('%s: %s is not in the zip' % (os.path.basename(z), keep))
target = os.path.join(dst, *keep.split('/'))
os.makedirs(os.path.dirname(target), exist_ok=True)
with zf.open(keep) as src, open(target, 'wb') as out:
shutil.copyfileobj(src, out)
if '.' not in os.path.basename(keep): # the Linux program
os.chmod(target, 0o755)
lic = self.licenses_dir('realesrgan')
for spec in REALESRGAN['licenses']:
shutil.copy2(download(spec, self.downloads), os.path.join(lic, spec['file']))
with open(os.path.join(lic, 'vcomp140.txt'), 'w', encoding='utf-8', newline='\n') as f:
f.write('vcomp140.dll is Microsoft\'s OpenMP runtime, part of the Visual C++ Redistributable, shipped in the '
'Real-ESRGAN release zip next to the program that loads it.\n')
self.part('realesrgan', {k: v for k, v in REALESRGAN.items() if k != 'licenses'})
log(' realesrgan %s' % REALESRGAN['version'])
for license_spec in spec['licenses']:
shutil.copy2(download(license_spec, self.downloads), os.path.join(lic, license_spec['file']))
if not self.args.linux:
with open(os.path.join(lic, 'vcomp140.txt'), 'w', encoding='utf-8', newline='\n') as f:
f.write('vcomp140.dll is Microsoft\'s OpenMP runtime, part of the Visual C++ Redistributable, shipped in '
'the Real-ESRGAN release zip next to the program that loads it.\n')
self.part('realesrgan', {k: v for k, v in spec.items() if k != 'licenses'})
log(' realesrgan %s (%s)' % (spec['version'], 'Linux' if self.args.linux else 'Windows'))
# -- deps
@@ -1147,6 +1160,7 @@ def main():
ap.add_argument('--only', choices=STEPS, action='append', help='run only these steps')
ap.add_argument('--zip', help='also write the kit as this .zip')
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
ap.add_argument('--linux', action='store_true', help='the Linux release\'s parts (realesrgan: its Linux build)')
ap.add_argument('--install-packages', action='store_true', help='only install the pinned MSYS2 packages '
'(tools/build_kit_packages.json) into --msys with pacman -U, their files SHA-256 checked')
ap.add_argument('--install-dry-run', action='store_true', help='with --install-packages: pacman --print only')
+427 -32
View File
@@ -8,9 +8,10 @@ redistributes.
python tools/make_release.py --out D:/tmb_release --publish --dry-run (the version from the commit's tag)
What it does, from <commit> (default HEAD; only committed files count, the working tree is never read):
export git archive of the commit and of the BozoEngine submodule at the commit it records (without its
reference/ records, which the build never reads) -> source\\ (no .git, no build/, nothing generated);
source\\release.ini stamps the version and both commits. The tree is audited: no ELF, IRX, disc image,
export git archive of the commit -> source\\ (no .git, no build/, nothing generated), and the BozoEngine
release its cmake/bozo_engine.json pins -> source\\BozoEngine (cmake/bozo_engine_fetch.cmake: the
release's archive, SHA-256 checked); source\\release.ini stamps the version, the commit and the
engine's version. The tree is audited: no ELF, IRX, disc image,
pack, generated code or disc file name may be in it.
kit the build kit (--kit <dir>: an existing one, hard-linked into the release; else assembled by
tools/make_build_kit.py, which needs MSYS2 and the network): a BozoEngine kit (kit_version 2: SDL3 and
@@ -27,7 +28,8 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
changelog CHANGELOG.md's section for the version (## [x.y.z], Keep a Changelog), from the commit: the release
refuses to be made without one (an empty one, or only "Unreleased", too) unless
--allow-missing-changelog (test builds). CHANGELOG.md is shipped at the zip's top (the launcher's
"What's new" reads it) and the section is the release notes' "What's new".
"What's new" reads it) and the section is the release notes' "What's new". recomplauncher.json (the
commit's) is shipped at the zip's top too, where RecompLauncher reads it.
zip TMB_Recomp-<version>.zip (deflate, entries sorted, every timestamp the commit's), <zip>.sha256,
RELEASE_NOTES.md (the changelog section, the hashes, the source offer: the GitHub release's body). The
zip's names are audited again.
@@ -43,6 +45,7 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
Standard library only (Python 3.8+; the kit's embeddable Python runs it too). Needs git; gh only for --publish.
"""
import argparse
import gzip
import hashlib
import io
import json
@@ -60,14 +63,17 @@ import zipfile
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
REPO = 'TheBozos/TMB_Recomp'
ENGINE_REPO = 'TheBozos/BozoEngine'
ENGINE_DIR = 'BozoEngine' # the submodule
# What BozoEngine's export leaves out (its reference records: hashes of recorded runs, never read by the build).
ENGINE_SKIP = ('reference',)
ENGINE_DIR = 'BozoEngine' # the release cmake/bozo_engine.json pins
NAME = 'TMB_Recomp'
# The BozoEngine build: its zips are <NAME>-<version>-bozo(.zip, -sources.zip) and the folder in them TOP, so they
# sit beside the fork build's (<NAME>-<version>.zip, folder TMB_Recomp) on a release page and on a player's disk.
FLAVOR = 'bozo'
TOP = 'TMB_Recomp_Bozo'
# The Linux release: <NAME>-<version>-linux.tar.gz, the same top folder, the launcher built for Linux.
LINUX_SUFFIX = '-linux.tar.gz'
LINUX_LAUNCHER = 'tmb-launcher'
# RecompLauncher's manifest (recomplauncher.com/sdk): at the repo's top, shipped at the zip's top.
RECOMPLAUNCHER_JSON = 'recomplauncher.json'
VERSION_RE = re.compile(r'^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$')
MSYS2_SOURCES = 'https://repo.msys2.org/mingw/sources/'
# The launcher's font (launcher/CMakeLists.txt pins the same commit and hash).
@@ -265,6 +271,15 @@ def parse_ini(path):
return out
def remove_bytecode_caches(folder):
"""Python's bytecode caches (__pycache__/) a step left in the release folder (importing tmb_build from the
exported source writes one): they hold the build machine's paths, and the player's Python makes its own."""
for dirpath, dirnames, _files in os.walk(folder):
if '__pycache__' in dirnames:
rmtree(os.path.join(dirpath, '__pycache__'))
dirnames.remove('__pycache__')
def pe_imports_of(path, tools_dir):
sys.path.insert(0, tools_dir)
try:
@@ -375,7 +390,7 @@ class Release:
self.migration_zip = os.path.join(self.out, '%s-%s.zip' % (NAME, self.version))
self.sources_zip = os.path.join(self.out, self.name + '-sources.zip')
self.commit_date = int(git('show', '-s', '--format=%ct', self.commit))
self.engine_commit = None
self.engine_version = None
self.manifest = None
self.msys_sources = [] # (package base, version, licence, url, file, sha256)
@@ -396,21 +411,16 @@ class Release:
rmtree(self.stage)
os.makedirs(self.source)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.commit], self.source, ROOT)
entry = git('ls-tree', self.commit, ENGINE_DIR).split()
if len(entry) < 3 or entry[0] != '160000':
raise ReleaseError('%s is not a submodule at %s' % (ENGINE_DIR, self.commit))
self.engine_commit = entry[2]
engine_repo = os.path.join(ROOT, ENGINE_DIR)
try:
git('cat-file', '-e', self.engine_commit + '^{commit}', cwd=engine_repo)
except ReleaseError:
raise ReleaseError('the submodule does not have %s: git submodule update --init %s'
% (self.engine_commit, ENGINE_DIR))
engine_dst = os.path.join(self.source, ENGINE_DIR)
os.makedirs(engine_dst, exist_ok=True)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.engine_commit], engine_dst, engine_repo)
for skip in ENGINE_SKIP:
rmtree(os.path.join(engine_dst, skip))
with open(os.path.join(self.source, 'cmake', 'bozo_engine.json'), encoding='utf-8') as f:
self.engine_version = json.load(f)['version']
cmake = shutil.which('cmake')
if not cmake and os.path.isfile(os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')):
cmake = os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')
if not cmake:
raise ReleaseError('no cmake on PATH: it fetches the BozoEngine release (cmake/bozo_engine_fetch.cmake)')
os.makedirs(self.downloads, exist_ok=True)
run([cmake, '-DBOZO_ENGINE_DOWNLOADS=' + self.downloads, '-P',
os.path.join(self.source, 'cmake', 'bozo_engine_fetch.cmake')])
# The list of the source's files: tmb_build removes the ones a newer release unzipped over this one no longer
# has (CMake globs runtime/*.cpp: a deleted file left behind would still be compiled).
files = sorted(os.path.relpath(os.path.join(d, n), self.source).replace('\\', '/')
@@ -419,14 +429,14 @@ class Release:
write_text(os.path.join(self.source, 'release_files.txt'), '\n'.join(sorted(set(files))) + '\n')
write_text(os.path.join(self.source, 'release.ini'),
'# The TMB_Recomp release this folder is (tools/make_release.py writes this file).\n'
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_commit = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_commit,
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_version = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_version,
time.strftime('%Y-%m-%d', time.gmtime(self.commit_date))))
problems = audit_tree(self.source, rel_prefix='source/')
if problems:
raise ReleaseError('the source export holds what looks like game data:\n ' + '\n '.join(problems[:20]))
n = sum(len(f) for _d, _s, f in os.walk(self.source))
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_commit[:12], n,
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_version, n,
dir_size(self.source) / 1e6))
# -- the kit
@@ -639,7 +649,7 @@ class Release:
'TMB_Recomp (source\\, this release\'s code; MIT, LICENSES\\TMB_Recomp)',
' https://github.com/%s/tree/%s' % (REPO, self.commit),
'BozoEngine, the recompiler and runtime the game is built on (source\\BozoEngine; MIT, LICENSES\\BozoEngine)',
' https://github.com/%s/tree/%s' % (ENGINE_REPO, self.engine_commit),
' https://github.com/%s/releases/tag/v%s' % (ENGINE_REPO, self.engine_version),
' The whole source is in source\\ already, the launcher\'s too (source\\launcher).',
'',
'The build kit (kit\\) redistributes these programs and libraries unmodified. Their corresponding source:',
@@ -775,6 +785,10 @@ class Release:
at = at + 1 if at >= 0 else len(text)
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text, crlf=True)
# RecompLauncher's manifest at the top, next to the launcher, where RecompLauncher reads it: the commit's.
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
f.write(manifest)
# -- the changelog
@@ -800,6 +814,7 @@ class Release:
return '_A test build: no changelog entry for %s._' % self.version
def step_zip(self):
remove_bytecode_caches(self.stage)
problems = [p for p in audit_tree(self.stage, allow_pe=True)]
if problems:
raise ReleaseError('the release folder holds what looks like game data:\n ' + '\n '.join(problems[:20]))
@@ -851,8 +866,13 @@ class Release:
'Then **Rebuild now** when the launcher offers it. Saves and settings stay in `%APPDATA%\\TMB_Recomp`. '
'Subsequent BozoEngine updates use `-bozo.zip` with either installation folder name.',
'',
]
linux = self.linux_archive()
if linux:
lines += linux_download_lines(os.path.basename(linux), sha256_of_file_record(linux))
lines += [
'## Build information', '',
'- Code: %s (`%s`), BozoEngine `%s`' % (REPO, self.commit, self.engine_commit),
'- Code: %s (`%s`), BozoEngine %s' % (REPO, self.commit, self.engine_version),
'- Build kit: GCC %s, CMake %s, Ninja %s (MSYS2 UCRT64), FFmpeg %s (LGPL, static), Python %s'
% (self.pkg_version('gcc'), self.pkg_version('cmake'), self.pkg_version('ninja'),
self.manifest['ffmpeg']['version'], self.manifest['python']['version']),
@@ -865,6 +885,9 @@ class Release:
sdig = f.read().split()[0]
lines.append('- `%s-sources.zip`: %.1f MB, SHA-256 `%s`' % (self.name, os.path.getsize(self.sources_zip) / 1e6,
sdig))
if linux:
lines.append('- `%s`: %.1f MB, SHA-256 `%s`' % (os.path.basename(linux), os.path.getsize(linux) / 1e6,
sha256_of_file_record(linux)))
lines += [
'', '## Source code and licences', '',
'The code is in the zip (`source\\`) and at the commit above: our own code and BozoEngine (the recompiler '
@@ -882,6 +905,11 @@ class Release:
write_text(os.path.join(self.out, 'RELEASE_NOTES.md'), '\n'.join(lines))
log(' RELEASE_NOTES.md (the changelog section for %s, the hashes, the source offer)' % self.version)
def linux_archive(self):
"""The Linux release a run with --linux left in --out (with its .sha256), else None."""
path = os.path.join(self.out, linux_archive_name(self.version))
return path if os.path.isfile(path) and os.path.isfile(path + '.sha256') else None
def pkg_version(self, name):
info = self.manifest['toolchain']['msys2_packages'].get(name)
return info['version'] if info else '?'
@@ -892,6 +920,11 @@ class Release:
assets += [self.sources_zip, self.sources_zip + '.sha256']
else:
log(' WARNING: no %s: the GPL source would not be attached' % os.path.basename(self.sources_zip))
linux = self.linux_archive()
if linux:
assets += [linux, linux + '.sha256']
else:
log(' WARNING: no %s: the release would have no Linux download' % linux_archive_name(self.version))
cmd = ['gh', 'release', 'create', 'v' + self.version, '--repo', REPO, '--draft', '--target', self.commit,
'--title', '%s %s' % (NAME, self.version), '--notes-file', os.path.join(self.out, 'RELEASE_NOTES.md')]
if '-' in self.version:
@@ -930,6 +963,13 @@ class Release:
problems = verify_zip(self.migration_zip, top=NAME)
if problems or not sha256_matches(self.migration_zip):
raise ReleaseError('migration zip audit or SHA-256 failed: %s' % problems)
linux = self.linux_archive()
if linux:
problems = verify_tar(linux)
if problems:
raise ReleaseError('%s:\n %s' % (linux, '\n '.join(problems[:40])))
if not sha256_matches(linux):
raise ReleaseError('%s does not match its .sha256' % linux)
self.publish()
def main(self):
@@ -955,6 +995,229 @@ class Release:
log('done in %.0f s: %s' % (time.time() - t0, self.zip))
class LinuxRelease(Release):
"""--linux: <name>-linux.tar.gz, the Linux player's download. The same source/ as the zip's, a kit/ with only
the libraries' sources (deps/: SDL3, Dear ImGui; the compiler, Python and FFmpeg are the system's), the launcher
built for Linux (tmb-launcher), the licences and a README. No GPL binary is redistributed: no sources zip."""
def __init__(self, args):
super().__init__(args)
self.archive = os.path.join(self.out, linux_archive_name(self.version))
self.stage = os.path.join(self.out, self.name + '-linux')
self.source = os.path.join(self.stage, 'source')
self.kit = os.path.join(self.stage, 'kit')
def step_kit(self):
rmtree(self.kit)
if self.args.kit:
src = os.path.join(os.path.abspath(self.args.kit), 'deps')
if not os.path.isdir(src):
raise ReleaseError('%s has no deps/ (--kit)' % self.args.kit)
link_tree(src, os.path.join(self.kit, 'deps'))
deps = realesrgan = {}
else:
work = os.path.join(self.work, 'kit-work')
run(self.kit_tool() + ['--out', self.kit, '--only', 'deps', '--only', 'realesrgan', '--linux',
'--downloads', self.downloads, '--work', work])
with open(os.path.join(self.kit, '.parts', 'deps.json')) as f:
deps = json.load(f)
with open(os.path.join(self.kit, '.parts', 'realesrgan.json')) as f:
realesrgan = json.load(f)
rmtree(os.path.join(self.kit, '.parts'))
for name in ('sdl3', 'imgui'):
if not os.path.isdir(os.path.join(self.kit, 'deps', name + '-src')):
raise ReleaseError('the Linux kit has no deps/%s-src' % name)
# recomplauncher.json's prepare runs kit/python/python.exe on Windows and this on Linux: the system's python3.
write_text(os.path.join(self.kit, 'python3'), LINUX_PYTHON3)
os.chmod(os.path.join(self.kit, 'python3'), 0o755)
self.manifest = {'kit': NAME + ' build kit', 'kit_version': self.kit_version(), 'engine': 'BozoEngine',
'platform': 'linux', 'made_from': self.commit,
'layout': {'deps': '<name>-src FetchContent sources: sdl3, imgui (the compiler, Python and '
'FFmpeg are the system\'s)',
'realesrgan': 'Real-ESRGAN ncnn-vulkan (Linux) and its realesrgan-x4plus model '
'(the optional enhanced textures)',
'licenses': 'license files per component'},
'deps': deps, 'realesrgan': realesrgan}
with open(os.path.join(self.kit, 'kit_manifest.json'), 'w') as f:
json.dump(self.manifest, f, indent=1)
log(' kit (Linux, libraries\' sources only): %.1f MB' % (dir_size(self.kit) / 1e6))
def kit_version(self):
text = open(os.path.join(self.source, 'tools', 'make_build_kit.py'), encoding='utf-8').read()
m = re.search(r'^KIT_VERSION = (\d+)', text, re.M)
return int(m.group(1)) if m else None
def step_launcher(self):
build = os.path.join(self.work, 'launcher-build')
rmtree(build)
deps = os.path.join(self.kit, 'deps')
logf = os.path.join(self.work, 'launcher.log')
cmake = shutil.which('cmake')
if not cmake or not shutil.which('ninja'):
raise ReleaseError('the Linux launcher needs cmake and ninja on the PATH')
run([cmake, '-S', os.path.join(self.source, 'launcher'), '-B', build, '-G', 'Ninja',
'-DCMAKE_BUILD_TYPE=Release', '-DFETCHCONTENT_FULLY_DISCONNECTED=ON',
'-DFETCHCONTENT_SOURCE_DIR_SDL3=' + os.path.join(deps, 'sdl3-src'),
'-DFETCHCONTENT_SOURCE_DIR_IMGUI=' + os.path.join(deps, 'imgui-src'),
'-DLAUNCHER_FONT_DIR=' + self.font_dir(),
'-DLAUNCHER_VERSION=' + self.version, '-DLAUNCHER_COMMIT=' + self.commit], logfile=logf)
run([cmake, '--build', build, '-j', str(self.args.jobs)], logfile=logf)
exe = os.path.join(build, LINUX_LAUNCHER)
if not os.path.isfile(exe):
raise ReleaseError('the launcher build made no %s' % exe)
dest = os.path.join(self.stage, LINUX_LAUNCHER)
strip = shutil.which('strip')
if strip:
run([strip, '-o', dest, exe], logfile=logf)
else:
shutil.copy2(exe, dest)
os.chmod(dest, 0o755)
libs = linked_libraries(dest)
log(' %s: %.1f MB, needs %s' % (LINUX_LAUNCHER, os.path.getsize(dest) / 1e6, ', '.join(libs) or '?'))
def step_licenses(self):
lic = os.path.join(self.stage, 'LICENSES')
rmtree(lic)
for name, src in (('TMB_Recomp', os.path.join(self.source, 'LICENSE')),
('BozoEngine', os.path.join(self.source, ENGINE_DIR, 'LICENSE'))):
if not os.path.isfile(src):
raise ReleaseError('%s has no LICENSE at this commit (%s)' % (name, src))
os.makedirs(os.path.join(lic, name))
shutil.copy2(src, os.path.join(lic, name, 'LICENSE'))
for name in sorted(os.listdir(os.path.join(self.kit, 'deps'))):
src = os.path.join(self.kit, 'deps', name)
files = [n for n in os.listdir(src) if re.match(r'(LICEN[CS]E|COPYING|NOTICE)', n, re.I)
and os.path.isfile(os.path.join(src, n))]
if files:
d = os.path.join(lic, 'libraries', name[:-4] if name.endswith('-src') else name)
os.makedirs(d, exist_ok=True)
for n in files:
shutil.copy2(os.path.join(src, n), d)
esrgan = os.path.join(self.kit, 'licenses', 'realesrgan')
if os.path.isdir(esrgan):
shutil.copytree(esrgan, os.path.join(lic, 'realesrgan'))
os.makedirs(os.path.join(lic, 'launcher-font-exo2'))
shutil.copy2(os.path.join(self.font_dir(), 'OFL.txt'), os.path.join(lic, 'launcher-font-exo2', 'OFL.txt'))
write_text(os.path.join(lic, 'README.txt'), LINUX_LICENSES_README.format(name=self.name))
log(' LICENSES: %d files' % sum(len(f) for _d, _s, f in os.walk(lic)))
def step_readme(self):
write_text(os.path.join(self.stage, 'README.txt'),
LINUX_README.format(version=self.version, name=self.name, repo=REPO,
archive=os.path.basename(self.archive)))
text = self.changelog_text()
if text is not None:
text = text.replace('\r\n', '\n')
if changelog_section(text, self.version) is None and self.args.allow_missing_changelog:
at = text.find('\n## ')
at = at + 1 if at >= 0 else len(text)
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text)
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
f.write(manifest)
def step_tar(self):
remove_bytecode_caches(self.stage)
problems = audit_tree(self.stage, allow_pe=True)
problems = [p for p in problems if not p.startswith(tuple(n + ':' for n in LINUX_PROGRAMS))]
if problems:
raise ReleaseError('the release folder holds what looks like game data:\n ' + '\n '.join(problems[:20]))
t = time.time()
tar_dir(self.stage, self.archive, TOP, self.commit_date)
problems = verify_tar(self.archive)
if problems:
raise ReleaseError('%s:\n %s' % (self.archive, '\n '.join(problems[:40])))
digest = write_sha256(self.archive)
with tarfile.open(self.archive) as tf:
n = len(tf.getmembers())
log(' %s: %d entries, %.1f MB (unpacked %.1f MB), %.0f s, SHA-256 %s'
% (os.path.basename(self.archive), n, os.path.getsize(self.archive) / 1e6, dir_size(self.stage) / 1e6,
time.time() - t, digest))
def main(self):
os.makedirs(self.work, exist_ok=True)
log('%s from %s' % (os.path.basename(self.archive), self.commit))
self.changelog_section = self.changelog()
t0 = time.time()
for name, fn in (('export', self.step_export), ('kit', self.step_kit), ('launcher', self.step_launcher),
('licenses', self.step_licenses), ('readme', self.step_readme), ('tar', self.step_tar)):
log('[%s]' % name)
t = time.time()
fn()
log(' %.1f s' % (time.time() - t))
if not self.args.keep_work:
rmtree(self.work)
log('done in %.0f s: %s' % (time.time() - t0, self.archive))
def linked_libraries(path):
"""The shared libraries an ELF program needs (its DT_NEEDED entries, from readelf), or [] without readelf."""
readelf = shutil.which('readelf')
if not readelf:
return []
out = subprocess.run([readelf, '-d', path], stdout=subprocess.PIPE, universal_newlines=True).stdout
return re.findall(r'\(NEEDED\)\s+Shared library: \[([^\]]+)\]', out)
def tar_dir(folder, path, top, mtime):
"""A reproducible .tar.gz of folder under top/: entries sorted, every time mtime, owner root, modes 755 / 644
(755 for what is executable in folder), no link, gzip without a name or time."""
entries = []
for dirpath, dirnames, filenames in os.walk(folder):
dirnames.sort()
rel_dir = os.path.relpath(dirpath, folder).replace('\\', '/')
rel_dir = '' if rel_dir == '.' else rel_dir
entries.append((rel_dir, dirpath, True))
for n in sorted(filenames):
entries.append(((rel_dir + '/' if rel_dir else '') + n, os.path.join(dirpath, n), False))
entries.sort(key=lambda e: e[0])
with open(path, 'wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as gz, \
tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tf:
for rel, full, is_dir in entries:
if os.path.islink(full):
raise ReleaseError('%s is a link: a release holds none' % full)
info = tarfile.TarInfo(top + ('/' + rel if rel else ''))
info.mtime, info.uid, info.gid, info.uname, info.gname = mtime, 0, 0, '', ''
if is_dir:
info.type, info.mode = tarfile.DIRTYPE, 0o755
tf.addfile(info)
else:
info.size = os.path.getsize(full)
info.mode = 0o755 if os.stat(full).st_mode & 0o111 else 0o644
with open(full, 'rb') as f:
tf.addfile(info, f)
def linux_archive_name(version):
return '%s-%s%s' % (NAME, version, LINUX_SUFFIX)
def sha256_of_file_record(path):
with open(path + '.sha256') as f:
return f.read().split()[0]
def linux_download_lines(archive, digest):
return [
'## Linux', '',
'1. `%s` below. Check it: `sha256sum %s` must print' % (archive, archive), '',
' ```', ' %s' % digest, ' ```', '',
'2. Install what the build needs (GCC, CMake, Ninja, pkg-config, Python 3, the FFmpeg, X11/Wayland, OpenGL and '
'audio development files). On Debian or Ubuntu:', '',
' ```', ' %s' % LINUX_APT, ' ```', '',
' The launcher names the packages for Fedora, Arch and openSUSE when one is missing.',
'3. `tar xzf %s`, then run `%s/%s`, select your disc image, **Prepare the game**, **Play**.'
% (archive, TOP, LINUX_LAUNCHER), '',
'Saves and settings are in `~/.local/share/tmb_recomp`.', '']
LINUX_APT = ('sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev '
'libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev '
'libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev '
'libasound2-dev libudev-dev')
CHANGELOG_HEADING = re.compile(r'^##[ \t]+\[?([^\]\s]+)\]?(.*)$', re.M)
@@ -994,13 +1257,15 @@ def verify_zip(path, top=TOP):
continue
if game_name(rel) or (rel.lower().endswith(GAME_EXTENSIONS) and not allowed_extension(rel)):
problems.append('%s: named like a file of the game' % n)
if rel.startswith('source/') and ('/__pycache__/' in rel or rel.endswith('.pyc')):
problems.append('%s: a Python bytecode cache (it holds the build machine paths)' % n)
with zf.open(info) as f:
head = f.read(0x8006)
if head[:4] == b'\x7fELF':
problems.append('%s: an ELF file' % n)
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
problems.append('%s: an ISO9660 volume' % n)
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp'):
@@ -1009,6 +1274,61 @@ def verify_zip(path, top=TOP):
return problems
# kit/python3 (Linux): what recomplauncher.json's prepare runs after kit/python/python.exe, the system's python3.
LINUX_PYTHON3 = '''#!/bin/sh
# The system's Python 3, for recomplauncher.json's prepare (Windows: kit/python/python.exe).
exec python3 "$@"
'''
# The ELF programs a Linux release carries: its launcher and Real-ESRGAN (the enhanced textures).
LINUX_PROGRAMS = (LINUX_LAUNCHER, 'kit/realesrgan/realesrgan-ncnn-vulkan')
LINUX_REQUIRED = (LINUX_LAUNCHER, 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'kit/python3', 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt', 'kit/deps/sdl3-src/CMakeLists.txt',
'kit/deps/imgui-src/imgui.cpp')
def verify_tar(path, top=TOP):
"""The Linux release audited as verify_zip audits the zip: one top folder, only files and folders, no game file,
no ELF but the launcher, the files a Linux release must have."""
problems = []
with tarfile.open(path) as tf:
members = tf.getmembers()
names = set()
tops = set(m.name.split('/', 1)[0] for m in members)
if tops != {top}:
problems.append('the archive\'s top folders are %s, expected %s only' % (sorted(tops), top))
for m in members:
n = m.name
rel = n.split('/', 1)[1] if '/' in n else ''
names.add(rel)
if not (m.isfile() or m.isdir()):
problems.append('%s: not a file or a folder' % n)
continue
if n.startswith('/') or '..' in n.split('/'):
problems.append('%s: an absolute or parent path' % n)
if rel.lower().startswith('source/ps2recomp/'):
problems.append('%s: PS2Recomp in a BozoEngine release' % n)
if m.isdir():
if rel and game_name(rel + '/'):
problems.append('%s: a generated / game folder' % n)
continue
if game_name(rel) or (rel.lower().endswith(GAME_EXTENSIONS) and not allowed_extension(rel)):
problems.append('%s: named like a file of the game' % n)
if rel.startswith('source/') and ('/__pycache__/' in rel or rel.endswith('.pyc')):
problems.append('%s: a Python bytecode cache (it holds the build machine paths)' % n)
head = tf.extractfile(m).read(0x8006)
if head[:4] == b'\x7fELF' and rel not in LINUX_PROGRAMS:
problems.append('%s: an ELF file' % n)
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
problems.append('%s: an ISO9660 volume' % n)
for need in LINUX_REQUIRED:
if need not in names:
problems.append('%s/%s is missing' % (top, need))
return problems
def link_tree_file(src, dst):
try:
os.link(src, dst)
@@ -1161,6 +1481,79 @@ Un projet de fans non officiel, ni affilié ni approuvé par eux.
Version {version}
"""
LINUX_LICENSES_README = """{name} (Linux): licences
TMB_Recomp/LICENSE TMB_Recomp's own code in source/ (MIT)
BozoEngine/LICENSE BozoEngine, the recompiler and runtime in source/BozoEngine (MIT)
libraries/ the libraries compiled into the game and the launcher (SDL3, Dear ImGui), their sources in
kit/deps
realesrgan/ Real-ESRGAN ncnn-vulkan and its model in kit/realesrgan (MIT, BSD-3-Clause), the
optional enhanced textures
launcher-font-exo2/ the launcher's font, Exo 2 (SIL Open Font License 1.1)
No GPL program is redistributed: the compiler, Python and FFmpeg are your system's.
Twisted Metal: Black is (c) Sony Interactive Entertainment. Nothing of the game is in this download.
"""
LINUX_README = """Twisted Metal: Black - PC port ({name}, Linux)
by The Bozos (boubou666 & Arzaroth)
What this is
A native PC version of Twisted Metal: Black (PS2), built on your own PC from YOUR OWN disc.
Nothing of the game is in this download: no game files, no code taken from the game.
Requires a 64-bit Linux with X11 or Wayland, OpenGL 3.3, and an AVX2 and FMA capable CPU.
You need a disc image of the USA release (SCUS-97101): a .iso, or a .bin with its .cue.
The European disc and other games are refused with an explanation.
Before you start: check the download
sha256sum {archive}
The hash printed must be the same as on the release page (and in {archive}.sha256).
What the build needs
GCC (C++20), CMake 3.21 or newer, Ninja, pkg-config, Python 3, and the development files of FFmpeg (libavcodec,
libavutil), X11 or Wayland, OpenGL (EGL or GLX) and PipeWire, PulseAudio or ALSA. On Debian or Ubuntu:
sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev \\
libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev \\
libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev \\
libasound2-dev libudev-dev
On Fedora, Arch or openSUSE, "Prepare the game" names the packages to install when one is missing.
The disc picker uses your desktop's file dialog (xdg-desktop-portal) or zenity.
Install
1. tar xzf {archive} wherever you like, with about 10 GB free: that makes TMB_Recomp_Bozo/.
Keep the folders together: tmb-launcher, source/ and kit/.
2. Run TMB_Recomp_Bozo/tmb-launcher.
3. Click "Select your disc image..." and pick your USA disc image.
4. Click "Prepare the game". It takes a few minutes, once (converting the textures and models, then compiling).
You can stop it; it continues later.
5. Click "Play". In the game, F2 opens controls, video and cheats.
6. Optional: Settings > "Make enhanced textures" upscales every arena's and car's textures with Real-ESRGAN (in
kit/realesrgan), on your PC from your own disc: about 15 minutes with a recent graphics card, about 700 MB, and a
Vulkan graphics driver is needed. Nothing is downloaded or sent, and the result is yours alone: do not share it.
Without the launcher: python3 source/tools/tmb_build.py --disc <your image> --out build --game game, then
game/play_tmb.sh.
Your saves and settings
~/.local/share/tmb_recomp (the launcher's Maintenance tab opens it). They stay when you update.
Updates
The launcher tells you when a new version is out, and its Update button installs it. Or extract the new archive
where you extracted this one and click "Rebuild now": only what changed is built again. Your saves stay.
Uninstall
Delete this folder, and ~/.local/share/tmb_recomp to remove your saves and settings too.
Help
https://github.com/{repo}/issues
When preparing fails, the launcher's "Copy details" button copies what we need to know.
Licences and source code: LICENSES/. Our code is MIT, and so is BozoEngine, the recompiler and runtime it is built on.
Twisted Metal: Black (c) Sony Interactive Entertainment, developed by Incognito Entertainment.
An unofficial fan project, not affiliated with or endorsed by them.
Version {version}
"""
def main():
for stream in (sys.stdout, sys.stderr): # the changelog's text, whatever the console's code page (cp1252 on CI)
@@ -1186,11 +1579,13 @@ def main():
'CHANGELOG.md has no section for the version (never for a real release)')
ap.add_argument('--check-changelog', action='store_true', help='only print CHANGELOG.md\'s section for the version '
'(--version or the commit\'s tag) at the commit; exit 1 when it is missing')
ap.add_argument('--verify-zip', metavar='ZIP', help='only audit a release zip (no game file, the expected files)')
ap.add_argument('--verify-zip', metavar='ZIP', help='only audit a release zip or Linux .tar.gz (no game file, the '
'expected files)')
ap.add_argument('--linux', action='store_true', help='the Linux release (<name>-linux.tar.gz) instead of the zip')
args = ap.parse_args()
try:
if args.verify_zip:
problems = verify_zip(args.verify_zip)
problems = (verify_tar if args.verify_zip.endswith('.tar.gz') else verify_zip)(args.verify_zip)
if problems:
raise ReleaseError('%s:\n %s' % (args.verify_zip, '\n '.join(problems[:40])))
log('%s: no game file, the expected files present' % args.verify_zip)
@@ -1218,7 +1613,7 @@ def main():
if args.publish_only:
Release(args).publish_made()
return
Release(args).main()
(LinuxRelease if args.linux else Release)(args).main()
except ReleaseError as e:
sys.exit('make_release: %s' % e)
+220 -11
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""tmb_build: from the player's own Twisted Metal: Black disc (USA, SCUS-97101) to a game folder that runs, in one
command. Nothing derived from the game is distributed: the disc's files, the generated code, the packs and the
executable are all made here, on the player's PC. The game is built on BozoEngine (the BozoEngine submodule, at the
commit this code pins; --engine <dir> for another tree).
executable are all made here, on the player's PC. The game is built on BozoEngine (the release cmake/bozo_engine.json
pins, in BozoEngine/: a release's source has it, a git checkout fetches it; --engine <dir> for another tree).
python tools/tmb_build.py --disc "Twisted Metal - Black (USA).iso" --out D:/TMB
python tools/tmb_build.py --disc D:/TMB_Recomp/game_us --out D:/TMB (an extracted disc folder)
@@ -22,7 +22,7 @@ again; within a step CMake and Ninja rebuild only what changed):
packs the texture and mesh packs (tools/tmb_texture_pack.py, tools/tmb_mesh_pack.py on BozoEngine's
tools/native_pack) -> <out>/build/packs
compile the game (tmb: SDL3, OpenGL 3.3)
stage <game>: tmb.exe, SCUS_971.01, the packs, disc.iso, "Play TMB.cmd"
stage <game>: tmb.exe, SCUS_971.01, the packs, disc.iso, "Play TMB.cmd" (on Linux: tmb, play_tmb.sh)
The build kit (tools/make_build_kit.py): a folder with kit_manifest.json, the compiler (ucrt64/), a minimal static
FFmpeg (ffmpeg/), the libraries' sources (deps/: SDL3, Dear ImGui) and an embeddable Python. Used when it sits in
@@ -30,6 +30,9 @@ FFmpeg (ffmpeg/), the libraries' sources (deps/: SDL3, Dear ImGui) and an embedd
nothing else is needed (no MSYS2, git, network or installed Python), and the game is the player's build: statically
linked (no DLL), FFmpeg from the kit.
kit/python/python.exe -I tools/tmb_build.py --disc "Twisted Metal - Black (USA).iso" --out D:/TMB
The Linux release's kit has deps/ only: the compiler, Python and FFmpeg are the system's. On Linux the build first
checks for GCC, CMake, Ninja, pkg-config and the FFmpeg, X11 or Wayland, OpenGL and audio development files, and names
the packages to install (ERROR verify) when one is missing.
Without a kit: --toolchain <dir> (a folder whose bin/ has g++, cmake, ninja: an MSYS2 UCRT64 prefix such as
C:/msys64/ucrt64), else the PATH, else C:/msys64/ucrt64; FFmpeg through pkg-config; SDL3 and ImGui downloaded by CMake
@@ -106,19 +109,46 @@ class BuildError(Exception):
pass
# --progress-lines: RecompLauncher's setup step (recomplauncher.json's prepare) reads "progress <0 to 1> <text>" lines.
PROGRESS_LINES = False
# Each step's share of the bar: its usual seconds on a first build (launcher/src/build_model.cpp's kSteps).
STEP_WEIGHTS = {'verify': 1, 'extract': 2, 'configure': 60, 'tools': 7, 'recompile': 2, 'packs': 32, 'compile': 55,
'stage': 1}
def emit(*parts):
print(' '.join(str(p) for p in parts), flush=True)
if PROGRESS_LINES:
line = progress_line(parts)
if line:
print(line, flush=True)
def progress_line(parts):
"""RecompLauncher's line for a PROGRESS (a step starts) or PERCENT (it moves on) line, else None: the share of the
whole build done, and the step's title (recomplauncher.com/sdk, prepare)."""
if len(parts) < 3 or parts[0] not in ('PROGRESS', 'PERCENT') or parts[1] not in STEP_WEIGHTS:
return None
step = parts[1]
pct = int(parts[2]) if parts[0] == 'PERCENT' else 0
before = sum(STEP_WEIGHTS[s] for s in STEPS[:STEPS.index(step)])
done = (before + STEP_WEIGHTS[step] * min(max(pct, 0), 100) / 100) / sum(STEP_WEIGHTS.values())
return 'progress %.3f %s%s' % (min(done, 0.999), STEP_TITLES[step], ' (%d%%)' % pct if parts[0] == 'PERCENT' else '')
def load_engine(path=None):
"""BozoEngine's tree (--engine, else the submodule) and its disc reader."""
"""BozoEngine's tree (--engine, else the pinned release, fetched in a git checkout) and its disc reader."""
global ENGINE, ps2_disc
if path:
ENGINE = os.path.abspath(path)
tools = os.path.join(ENGINE, 'tools', 'native_pack')
fetch = os.path.join(ROOT, 'cmake', 'bozo_engine_fetch.cmake')
if not path and os.path.exists(os.path.join(ROOT, '.git')) and shutil.which('cmake'):
# A checkout follows cmake/bozo_engine.json (nothing is downloaded while BozoEngine/.release matches it).
subprocess.run([shutil.which('cmake'), '-P', fetch], check=False)
if not os.path.isfile(os.path.join(tools, 'ps2_disc.py')):
raise SystemExit('ERROR verify BozoEngine is missing (%s): the release is incomplete, or in a git checkout run '
'"git submodule update --init BozoEngine"' % ENGINE)
'"cmake -P cmake/bozo_engine_fetch.cmake"' % ENGINE)
sys.path.insert(0, tools)
import ps2_disc as module # noqa: E402
ps2_disc = module
@@ -262,10 +292,12 @@ class Build:
self.kit = find_kit(args)
self.ffmpeg_root = None
if self.kit:
# The kit's parts unless the command line names others.
args.toolchain = args.toolchain or os.path.join(self.kit, 'ucrt64')
# The kit's parts unless the command line names others. A Linux kit has deps/ only.
if os.path.isdir(os.path.join(self.kit, 'ucrt64')):
args.toolchain = args.toolchain or os.path.join(self.kit, 'ucrt64')
args.fetch_cache = args.fetch_cache or os.path.join(self.kit, 'deps')
self.ffmpeg_root = os.path.join(self.kit, 'ffmpeg')
if os.path.isdir(os.path.join(self.kit, 'ffmpeg')):
self.ffmpeg_root = os.path.join(self.kit, 'ffmpeg')
if args.debug_info is None: # a player's build (the kit): no debug information
args.debug_info = 'no' if self.kit else 'yes'
@@ -725,9 +757,15 @@ class Build:
# -- driver
def main(self):
if os.name != 'nt':
missing = linux_missing(self.args.toolchain)
if missing:
emit('ERROR', 'verify', linux_missing_message(missing))
return 1
redo_from = STEPS.index(self.args.redo) if self.args.redo else len(STEPS)
n = len(STEPS)
dirty = False
ran = False
total_start = time.time()
for i, step in enumerate(STEPS, 1):
self.step = step
@@ -740,7 +778,7 @@ class Build:
emit('INFO', 'stopped', 'after ' + step)
return 0
continue
dirty = True # every later step runs again (Ninja only redoes what changed)
dirty = ran = True # every later step runs again (Ninja only redoes what changed)
emit('PROGRESS', step, '%d/%d' % (i, n), STEP_TITLES[step])
t = time.time()
self.state[step] = {'done': False}
@@ -769,6 +807,8 @@ class Build:
launcher = os.path.join(self.game, 'Play TMB.cmd' if os.name == 'nt' else 'play_tmb.sh')
emit('INFO', 'total', '%.1f s' % (time.time() - total_start))
emit('RESULT', self.game, launcher)
if PROGRESS_LINES:
print('progress 1 %s' % ('Ready to play' if ran else 'Already built'), flush=True)
return 0
@@ -787,6 +827,74 @@ def find_kit(args):
return None
LINUX_TOOLS = ('gcc', 'g++', 'cmake', 'ninja', 'pkg-config')
LINUX_MODULES = (('FFmpeg', ('libavcodec', 'libavutil')),
('X11 or Wayland', ('x11|wayland-client',)),
('OpenGL', ('gl|egl',)),
('PipeWire, PulseAudio or ALSA', ('libpipewire-0.3|libpulse|alsa',)))
LINUX_X11_EXTENSIONS = ('xext', 'xcursor', 'xi', 'xfixes', 'xrandr', 'xscrnsaver', 'xtst')
LINUX_PACKAGES = {
'debian': 'sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev '
'libx11-dev libxext-dev libxrandr-dev libxcursor-dev '
'libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev '
'libpipewire-0.3-dev libpulse-dev libasound2-dev libudev-dev',
'fedora': 'sudo dnf install gcc-c++ cmake ninja-build pkgconf python3 ffmpeg-free-devel libX11-devel libXext-devel '
'libXrandr-devel libXcursor-devel libXi-devel libXScrnSaver-devel libXtst-devel libXfixes-devel libxkbcommon-devel wayland-devel '
'libdecor-devel mesa-libEGL-devel mesa-libGL-devel pipewire-devel pulseaudio-libs-devel alsa-lib-devel '
'systemd-devel',
'arch': 'sudo pacman -S --needed base-devel cmake ninja pkgconf python ffmpeg libx11 libxext libxrandr libxcursor '
'libxi libxss libxtst libxfixes libxkbcommon wayland libdecor mesa libpipewire libpulse alsa-lib',
'suse': 'sudo zypper install gcc-c++ cmake ninja pkg-config python3 ffmpeg-7-libavcodec-devel '
'ffmpeg-7-libavutil-devel '
'libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXi-devel libXss-devel libXtst-devel libXfixes-devel libxkbcommon-devel '
'wayland-devel libdecor-devel Mesa-libEGL-devel Mesa-libGL-devel pipewire-devel libpulse-devel '
'alsa-devel systemd-devel',
}
def linux_family():
try:
with open('/etc/os-release', encoding='utf-8') as f:
fields = dict(l.rstrip('\n').split('=', 1) for l in f if '=' in l)
except OSError:
return None
ids = ' '.join(fields.get(k, '').strip('"') for k in ('ID', 'ID_LIKE')).split()
for family, names in (('debian', ('debian', 'ubuntu')), ('fedora', ('fedora', 'rhel', 'centos')),
('arch', ('arch', 'archlinux')), ('suse', ('suse', 'opensuse'))):
if any(i in names or i.startswith('opensuse') and family == 'suse' for i in ids):
return family
return None
def linux_missing(toolchain=None):
"""What the Linux build needs and this system lacks: tools on the PATH and pkg-config modules."""
missing = []
if not toolchain:
missing += [t for t in LINUX_TOOLS if not shutil.which(t)]
elif not shutil.which('pkg-config'):
missing.append('pkg-config')
if shutil.which('pkg-config'):
for what, modules in LINUX_MODULES:
lacking = [m for m in modules if not any(
subprocess.run(['pkg-config', '--exists', alt]).returncode == 0 for alt in m.split('|'))]
if lacking:
missing.append('%s (%s)' % (what, ', '.join(m.replace('|', ' or ') for m in lacking)))
if subprocess.run(['pkg-config', '--exists', 'x11']).returncode == 0:
lacking = [m for m in LINUX_X11_EXTENSIONS if subprocess.run(['pkg-config', '--exists', m]).returncode != 0]
if lacking:
missing.append('X11 extensions (%s)' % ', '.join(lacking))
return missing
def linux_missing_message(missing):
family = linux_family()
install = LINUX_PACKAGES.get(family)
return ('the build needs %s. %s' % (', '.join(missing),
'Install them with: %s' % install if install else
'Install your distribution\'s packages for them (GCC, CMake, Ninja, pkg-config, the FFmpeg, X11, Wayland, '
'OpenGL and audio development files); on Debian or Ubuntu: %s' % LINUX_PACKAGES['debian']))
STEP_TITLES = {
'verify': 'Checking the disc',
'extract': 'Reading the disc\'s files',
@@ -826,12 +934,13 @@ def check_disc(path):
def main():
ap = argparse.ArgumentParser(description='Builds Twisted Metal: Black (USA) as a native PC game from your own disc.')
ap.add_argument('--disc', required=True, help='the disc image (.iso, .bin, .cue) or an extracted disc folder')
ap.add_argument('--disc', help='the disc image (.iso, .bin, .cue) or an extracted disc folder (default: the '
'disc.iso an earlier build left in the game folder)')
ap.add_argument('--out', default='tmb_build', help='the work folder; the game ends up in <out>/TMB')
ap.add_argument('--game', help='the game folder to stage (default: <out>/TMB)')
ap.add_argument('--check', action='store_true', help='only check the disc (no work folder): OK <message> or '
'ERROR verify <message>')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the BozoEngine submodule)')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)')
ap.add_argument('--kit', help='the build kit folder (default: <TMB_Recomp>/kit or <its parent>/kit if present)')
ap.add_argument('--no-kit', action='store_true', help='do not use a build kit even if one is found')
ap.add_argument('--toolchain', help='compiler folder (with bin/g++, cmake, ninja), default: the kit, PATH, '
@@ -844,13 +953,28 @@ def main():
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
ap.add_argument('--redo', choices=STEPS, help='run this step and the ones after it again')
ap.add_argument('--stop-after', choices=STEPS, help='stop once this step is done')
ap.add_argument('--progress-lines', action='store_true', help='also print "progress <0 to 1> <text>" lines, for '
'RecompLauncher (recomplauncher.json)')
args = ap.parse_args()
global PROGRESS_LINES
PROGRESS_LINES = args.progress_lines
if not args.disc:
# Built before: the game folder keeps the disc image (a link to the player's, or a copy), so an update builds
# again without it (RecompLauncher's keeps_copy, after the player deleted their own).
kept = os.path.join(os.path.abspath(args.game) if args.game else os.path.join(os.path.abspath(args.out), 'TMB'),
'disc.iso')
if not os.path.isfile(kept):
emit('ERROR', 'verify', 'no disc image given (--disc) and none kept from an earlier build: pick your '
'Twisted Metal: Black disc image (USA, SCUS-97101)')
sys.exit(1)
args.disc = kept
load_engine(args.engine)
if args.check:
sys.exit(check_disc(args.disc))
os.makedirs(os.path.abspath(args.out), exist_ok=True)
if not os.environ.get(ALIAS_ENV):
remove_stale_sources()
settle_source_times(os.path.abspath(args.out), find_kit(args))
if needs_ascii_aliases(args):
sys.exit(run_through_aliases(args))
sys.exit(Build(args).main())
@@ -904,6 +1028,91 @@ def remove_stale_sources():
emit('INFO', 'update', '%d files of an earlier release removed from %s' % (removed, ROOT))
SOURCE_TIMES = 'source_times.json'
def settle_source_times(out, kit, now_ns=None):
"""A release zip dates every file at its commit's time (tools/make_release.py), which an unzip takes as local
time. Two failures follow for ninja, which only compares times:
- dated in the future (unzipped west of UTC within hours of the commit): build.ninja, regenerated, stays older
than CMakeLists.txt forever ("manifest 'build.ninja' still dirty after 100 tries");
- dated before the player's last build (an update unzipped over a game built after the commit): a changed file
looks older than its object and is not compiled again.
So the release's source files (release_files.txt) and the kit's FetchContent sources (deps/) are re-dated here,
from <out>/source_times.json (each file's size, time and SHA-1 as the last run left them): a file whose content changed,
or new to this release, is dated now; one unchanged gets its time back; nothing stays in the future. Without that
record and with a build folder from before, every file is dated now: everything is built again, once. The rest of
the kit (the toolchain: CMake's own modules are build.ninja's inputs too, the compiler's headers every object's)
only comes back from the future. A git checkout (no release_files.txt) is left alone: git dates the files it
writes now."""
listing = os.path.join(ROOT, 'release_files.txt')
if not os.path.isfile(listing):
return
now = now_ns if now_ns is not None else time.time_ns()
future = 0
if kit and os.path.isdir(kit):
for dirpath, _dirs, names in os.walk(kit):
for n in names:
p = os.path.join(dirpath, n)
try:
if os.stat(p).st_mtime_ns > now:
os.utime(p, ns=(now, now))
future += 1
except OSError:
pass
files = []
with open(listing, encoding='utf-8') as f:
files += [('source/' + l.strip(), os.path.join(ROOT, *l.strip().split('/'))) for l in f if l.strip()]
deps = os.path.join(kit, 'deps') if kit else None
if deps and os.path.isdir(deps):
for dirpath, dirs, names in os.walk(deps):
dirs.sort()
for n in sorted(names):
p = os.path.join(dirpath, n)
files.append(('deps/' + os.path.relpath(p, deps).replace('\\', '/'), p))
record_path = os.path.join(out, SOURCE_TIMES)
try:
with open(record_path, encoding='utf-8') as f:
old = json.load(f)
if not isinstance(old, dict):
old = None
except (OSError, ValueError):
old = None
built_before = os.path.isfile(os.path.join(out, 'build', 'build.ninja'))
record, changed = {}, 0
for key, path in files:
try:
st = os.stat(path)
except OSError:
continue
mtime = st.st_mtime_ns
rec = old.get(key) if old else None
if rec and rec[0] == st.st_size and rec[1] == mtime:
digest, target = rec[2], mtime # untouched since the last build
else:
digest = sha1_file(path)
if rec and rec[2] == digest:
target = rec[1] # the same content: its time at the last build
elif rec or old is not None or built_before:
target = now # changed, new to this release, or unknown with a build from before
changed += 1
else:
target = mtime # a first build: nothing to be older than
if target > now:
target = now
future += 1
if target != mtime:
os.utime(path, ns=(target, target))
record[key] = [st.st_size, target, digest]
tmp = record_path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(record, f, separators=(',', ':'))
os.replace(tmp, record_path)
if changed or future:
emit('INFO', 'update', '%d source files dated now (%d changed or new, %d were dated in the future)'
% (changed + future, changed, future))
# ---- folders whose path is not ASCII (Windows) ----
#
# MSYS2's binutils open files in the ANSI code page: ld cannot open an object or library whose path, read from the
+1 -1
View File
@@ -77,7 +77,7 @@ import struct
import sys
import zlib
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):
+1 -1
View File
@@ -25,7 +25,7 @@ import struct
import sys
import zlib
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):