mirror of
https://github.com/TheBozos/TMB_Recomp.git
synced 2026-12-01 12:54:41 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb17ea2508 | ||
|
|
c00c238331 | ||
|
|
14027a5026 | ||
|
|
2e37b81b0d | ||
|
|
13a63bcafd | ||
|
|
3f6623f47e | ||
|
|
f0806c5ef0 | ||
|
|
6db6a16b0d | ||
|
|
7ccc02b050 | ||
|
|
8d808aaf2a | ||
|
|
06d323c49d | ||
|
|
80ba27ab07 | ||
|
|
254f994459 | ||
|
|
f620ab163b | ||
|
|
ce069120c1 | ||
|
|
b84fefaf95 | ||
|
|
159d4a5de3 | ||
|
|
979544ce35 | ||
|
|
7f3a59ce5b | ||
|
|
d1e53a845c | ||
|
|
8dbb7b0c23 | ||
|
|
09e8c8b45f | ||
|
|
6e27203fcc | ||
|
|
894a16a651 | ||
|
|
9cea4513b1 | ||
|
|
38ff9f8ea3 | ||
|
|
d003ced242 | ||
|
|
6043791a00 | ||
|
|
dbb8c73b23 | ||
|
|
de1f627801 | ||
|
|
ad371920d7 | ||
|
|
5531425daf | ||
|
|
56e2f2e932 | ||
|
|
3b05396300 | ||
|
|
2a7eff7a3a | ||
|
|
de7bfb32aa | ||
|
|
89d530697c | ||
|
|
28159632e2 | ||
|
|
c821465d6a | ||
|
|
a0d9386896 | ||
|
|
0aedf924ed | ||
|
|
e1797b1315 | ||
|
|
ccd52e8401 | ||
|
|
ae2ac42953 | ||
|
|
153336ae0c | ||
|
|
b1aa812ed7 | ||
|
|
cd5262a7a0 | ||
|
|
4eddae4fa3 | ||
|
|
fb17656603 | ||
|
|
a67b0cd9fe | ||
|
|
a58a702260 | ||
|
|
8d971a3f3d | ||
|
|
280f1855d5 | ||
|
|
60c90259bb | ||
|
|
de7941263b | ||
|
|
e05ff6b93e | ||
|
|
50e7052a6e | ||
|
|
7439f7778e | ||
|
|
a9b68c9e17 | ||
|
|
388ced5206 | ||
|
|
ab52b55073 | ||
|
|
c1a35042b2 | ||
|
|
bd387fcd8e | ||
|
|
27dda815d7 | ||
|
|
65db7e4c89 | ||
|
|
99e51f0983 | ||
|
|
e25bafb110 | ||
|
|
2e8b9929fe | ||
|
|
b5375c9b1e | ||
|
|
bc4c16996a | ||
|
|
9a10e59096 | ||
|
|
d1c9116ddf | ||
|
|
777f9647d5 | ||
|
|
80450ea784 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -80,13 +80,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:
|
||||
@@ -127,13 +129,13 @@ jobs:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: python tools/make_build_kit.py --install-packages --msys "$MSYS2_ROOT" --downloads "$WORK/downloads"
|
||||
|
||||
- name: Build kit (toolchain, Python, SDL3 and ImGui sources, FFmpeg)
|
||||
- name: Build kit (toolchain, Python, SDL3 and ImGui sources, FFmpeg, Real-ESRGAN)
|
||||
env:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
FFMPEG_CACHED: ${{ steps.ffmpeg.outputs.cache-hit }}
|
||||
run: |
|
||||
set -eu
|
||||
steps="--only toolchain --only python --only deps"
|
||||
steps="--only toolchain --only python --only deps --only realesrgan"
|
||||
if [ "$FFMPEG_CACHED" != true ]; then steps="$steps --only ffmpeg"; fi
|
||||
python tools/make_build_kit.py --out "$WORK/kit" --msys "$MSYS2_ROOT" --downloads "$WORK/downloads" \
|
||||
--work "$WORK/kit-work" $steps --only manifest
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "BozoEngine"]
|
||||
path = BozoEngine
|
||||
url = https://github.com/TheBozos/BozoEngine.git
|
||||
-1
Submodule BozoEngine deleted from 4a8f70a502.
+126
-1
@@ -7,6 +7,126 @@ under "Unreleased" as they land, then move them under the new version's heading
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
- **Enhanced textures (AI), made on your PC from your own disc.** In the launcher's Settings, **Make enhanced
|
||||
textures** reads every arena and car from your disc, including the cars' player versions, and upscales their
|
||||
textures 4x with Real-ESRGAN. It takes about 5 to 15 minutes with a recent graphics card and about 700 MB, and
|
||||
needs a Vulkan graphics driver. It shows its progress; **Stop** keeps what is done for next time, and **Remove**
|
||||
deletes the result. Switch the pack on or off there or in the game (F2, Video tab, Texture pack). Real-ESRGAN now
|
||||
comes in the build kit, with its licences in `kit\licenses\realesrgan`. Nothing of the game is downloaded,
|
||||
shipped or sent anywhere.
|
||||
- **Texture upscaling** (off by default): the game's own textures can be drawn from 2x or 4x copies with an
|
||||
edge-directed or smooth filter, in F2's Video tab or with `texture_upscale` / `texture_filter` in `video.ini`. It is
|
||||
BozoEngine's renderer option, from the Soulcalibur III port. Replays are unchanged by it.
|
||||
- Loading the pack or the upscaled copies never holds up a frame. One-player, four-player and the story arenas keep
|
||||
their frame rate with the full pack and 4x upscaling (timing in
|
||||
[`docs/TEXTURE_UPSCALING.md`](docs/TEXTURE_UPSCALING.md)).
|
||||
|
||||
### Fixed
|
||||
|
||||
- The launcher's Settings no longer reset the game's frame rate and texture upscaling in `video.ini` when they
|
||||
saved the window.
|
||||
|
||||
### Changed
|
||||
|
||||
- BozoEngine is updated to `a36a4d2`. Native callbacks now run on the game's own thread stack instead of a fixed
|
||||
area at the top of RAM. TMB declares where its code uses the stack pointer as data (`hierTraverseAsm`,
|
||||
`sysSetSp`/`sysRestoreSp`), so a callback taken there still finds the real stack. One-player and four-player
|
||||
replays match the previous build on every frame's draws, scratchpad, calls, threads and timing. Sound differs on
|
||||
four menu frames only, with equal sample counts.
|
||||
|
||||
### Developer changes
|
||||
|
||||
- `TMB_TEXTURE_DUMP=1|<folder>` writes each texture the renderer receives as a PNG named by its identity, and every
|
||||
250 frames every texture of the loaded levels' objects, drawn or not.
|
||||
- `tools/tmb_texture_dump_all.py` dumps every arena, AI car and player car in headless runs (2,289 textures on the
|
||||
USA disc). `tools/tmb_texture_upscale.py` (Python) and `tmb-texture-pack` (native, built and staged with the game)
|
||||
turn the dump into a pack; `tools/tmb_texture_enhance.py` is the launcher's driver for both.
|
||||
- Larger texture copies go to the GPU at most 4 MB per frame, and a copy already there is shared when the game moves
|
||||
the texture in its VRAM (BozoEngine).
|
||||
|
||||
### Known limits
|
||||
|
||||
- Only the USA disc is supported. Windows is the validated player target; the migrated Linux player build is not yet
|
||||
validated.
|
||||
- Enhanced textures need a Vulkan graphics driver and were only tested on one NVIDIA card. The menus and the font
|
||||
are left to the engine's upscaling, because the AI model garbles small lettering.
|
||||
- Full campaign endings, a fresh standard-user Windows installation and four physical controllers still need
|
||||
player/hardware acceptance. Widescreen is not implemented; presentation above 60 Hz remains experimental for
|
||||
effects that update at game rate.
|
||||
|
||||
## [0.5.0] - 2026-11-09
|
||||
|
||||
### Changed
|
||||
@@ -191,7 +311,12 @@ 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.5.0...HEAD
|
||||
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.3...HEAD
|
||||
[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
|
||||
[0.3.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.1...v0.3.2
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -45,6 +45,16 @@ remains available for comparison. The steps below describe the native packages.
|
||||
first time; you can stop it and resume where it left off.
|
||||
6. Click **Play**. **F2** opens controls, video and cheats. Memory cards, settings and logs live in
|
||||
`%APPDATA%\TMB_Recomp` (the launcher's Maintenance tab opens it).
|
||||
7. Optional: **Settings → Make enhanced textures** upscales every arena's and car's textures with Real-ESRGAN (included
|
||||
in `kit\`), 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. 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.
|
||||
|
||||
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
|
||||
@@ -109,6 +119,9 @@ 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 | 🔧 |
|
||||
@@ -177,7 +190,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.
|
||||
|
||||
@@ -198,10 +214,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"
|
||||
@@ -265,6 +282,10 @@ rem -DLAUNCHER_FONT_DIR=<folder containing Exo2[wght].ttf and OFL.txt>
|
||||
A crash report is offered if one appeared in the user folder.
|
||||
- Window settings live in `video.ini`; disc choice, language, background motion and build state live in `launcher.ini`
|
||||
in the user folder. The launcher's Settings tab controls the starting window; F2 in the game controls the game settings.
|
||||
The launcher keeps `video.ini`'s other keys (frame rate, texture upscaling, texture pack) when it writes the window.
|
||||
- Enhanced textures (Settings): `source/tools/tmb_texture_enhance.py` with the kit's Python dumps the textures with
|
||||
`game/tmb-headless.exe`, then `game/tmb-texture-pack.exe` upscales them with `kit/realesrgan` into
|
||||
`%APPDATA%\TMB_Recomp\texture_pack` (resumed when stopped; Remove deletes it).
|
||||
- The team's RecompWatcher styling remains: PS2 BIOS blue, glowing boot towers, glass cards, Exo 2 (SIL OFL), and TMB's
|
||||
flaming-clown icon (`launcher/tmb.ico`, `runtime/app/tmb.ico`). No game art is used for the icon.
|
||||
- Update checks use GitHub's latest-release API. The native updater fetches `TMB_Recomp-<version>-bozo.zip` and its
|
||||
@@ -302,7 +323,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.
|
||||
@@ -339,7 +361,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
|
||||
@@ -392,12 +415,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 and presentation frame rate), 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.
|
||||
@@ -427,6 +461,8 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
|
||||
| `PS2X_USER_DIR=<dir>` | Separate cards, settings, logs and crash reports; required for agent/unattended tests |
|
||||
| `PS2X_INPUT_CONFIG=<file>`, `PS2X_VIDEO_CONFIG=<file>` | Other controls/video configuration files |
|
||||
| `PS2X_WINDOW_SIZE=<w>x<h>`, `PS2X_WINDOW_MODE=windowed\|fullscreen\|borderless`, `PS2X_RENDER_SCALE=<x>` | Starting window mode, size and internal render scale, over `video.ini` |
|
||||
| `PS2X_TEXTURE_PACK=<folder>\|off`, `PS2X_TEXTURE_PACK_RELOAD=1` | Texture replacements: `<identity>.png` files you made from your own disc (default: `texture_pack` in the user folder; see [`docs/TEXTURE_UPSCALING.md`](docs/TEXTURE_UPSCALING.md)); reload re-reads changed files while playing |
|
||||
| `PS2X_TEXTURE_UPSCALE=off\|2x\|4x`, `PS2X_TEXTURE_FILTER=edge\|smooth`, `PS2X_TEXTURE_STATS=1` | Texture upscaling (off by default) and its filter, over `video.ini`; the stats log texture memory every 10 s |
|
||||
| `PS2X_FRAME_RATE=game\|monitor\|<n>` | Presentation at game rate, monitor rate or a fixed rate; higher rates interpolate without speeding up the game |
|
||||
| `PS2X_SHOW_FPS=1` | Show FPS at launch; F3 toggles it |
|
||||
| `PS2X_FRAME_STATS=1` | Game-thread work measurements independently of the cap |
|
||||
@@ -436,17 +472,20 @@ 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 |
|
||||
| `TMB_KILL_ENEMIES=<s>`, `TMB_PLAYER_HEALTH_CAP=<x>` | Test-only story progression or player-health cap; see the handoff's save-cheat comparison limit |
|
||||
| `TMB_TEXTURE_DUMP=1\|<folder>` | Write each texture the renderer gets once, as `<identity>.png` plus `index.tsv` (in `$PS2X_USER_DIR/texture_dump` for `1`); for building texture packs from your own disc, never to share ([`docs/TEXTURE_UPSCALING.md`](docs/TEXTURE_UPSCALING.md)) |
|
||||
|
||||
The former GS/IOP/VIF interpreter switches are not alternate player engines in this tree. Native pacing remains
|
||||
active even if an old environment contains `TMB_NATIVE_FRAMES=0`.
|
||||
@@ -480,7 +519,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
@@ -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
@@ -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, ®istry, 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);
|
||||
|
||||
@@ -0,0 +1,829 @@
|
||||
// tmb-texture-pack: a texture replacement pack made from a texture dump with Real-ESRGAN, on the player's PC from their
|
||||
// own disc (docs/TEXTURE_UPSCALING.md). The native counterpart of tools/tmb_texture_upscale.py, for the launcher's
|
||||
// "Enhance textures" step: no Python packages, built with the game.
|
||||
//
|
||||
// tmb-texture-pack <dump folder> <pack folder> --esrgan <realesrgan-ncnn-vulkan.exe> [--models <folder>]
|
||||
// [--model realesrgan-x4plus] [--min-size 32] [--detail 1.0] [--skip SHELL1,FONT] [--jobs N]
|
||||
// [--work <folder>]
|
||||
//
|
||||
// Per texture (index.tsv's rows, <identity>.png, GS alpha as the dump wrote it):
|
||||
// - colour: transparent texels take their visible neighbours' colour, then Real-ESRGAN 4x over a 16-texel border taken
|
||||
// from the opposite edges (repeating textures stay seamless); the original's high frequencies (bicubic minus its
|
||||
// Gaussian blur, sigma 3 at the output size) added back, since the model flattens gravel and rust;
|
||||
// - alpha: one value kept; two values cut at the midpoint of a bicubic; otherwise the visible shape (bicubic of the
|
||||
// visible mask cut at half) keeps everything outside it at 0, a few levels (<= 4) snapped to the nearest one;
|
||||
// - flat areas (a texel equal to its 8 neighbours) kept exactly; menus and font (--skip) and textures under --min-size
|
||||
// left to the engine's own upscaling.
|
||||
// Files already in the pack are kept (a run can be resumed). Output for the launcher: "step <name>", "progress <done>
|
||||
// <total>", "error <text>", "done <count>" lines on stdout.
|
||||
|
||||
#include "bozo/render/png_read.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr int kScale = 4, kPad = 16;
|
||||
|
||||
std::mutex g_out;
|
||||
void say(const std::string &line)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_out);
|
||||
std::fputs((line + "\n").c_str(), stdout);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
// ---- PNG writing: zlib with LZ77 (hash chains) and the fixed Huffman code (RFC 1950 / 1951) ----
|
||||
|
||||
struct BitWriter
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
uint32_t buffer = 0;
|
||||
int count = 0;
|
||||
void put(uint32_t bits, int n)
|
||||
{
|
||||
buffer |= bits << count;
|
||||
count += n;
|
||||
while (count >= 8)
|
||||
{
|
||||
out.push_back(static_cast<uint8_t>(buffer));
|
||||
buffer >>= 8;
|
||||
count -= 8;
|
||||
}
|
||||
}
|
||||
void putReversed(uint32_t code, int n) // Huffman codes go most significant bit first
|
||||
{
|
||||
uint32_t r = 0;
|
||||
for (int i = 0; i < n; ++i)
|
||||
r |= ((code >> i) & 1u) << (n - 1 - i);
|
||||
put(r, n);
|
||||
}
|
||||
void flush()
|
||||
{
|
||||
if (count > 0)
|
||||
out.push_back(static_cast<uint8_t>(buffer));
|
||||
buffer = 0;
|
||||
count = 0;
|
||||
}
|
||||
};
|
||||
|
||||
void literal(BitWriter &w, int v)
|
||||
{
|
||||
if (v < 144)
|
||||
w.putReversed(0x30 + v, 8);
|
||||
else if (v < 256)
|
||||
w.putReversed(0x190 + v - 144, 9);
|
||||
else if (v < 280)
|
||||
w.putReversed(v - 256, 7);
|
||||
else
|
||||
w.putReversed(0xc0 + v - 280, 8);
|
||||
}
|
||||
|
||||
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
|
||||
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
|
||||
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
|
||||
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
|
||||
|
||||
std::vector<uint8_t> deflate(const std::vector<uint8_t> &data)
|
||||
{
|
||||
BitWriter w;
|
||||
w.put(0x78, 8);
|
||||
w.put(0x01, 8);
|
||||
w.put(1, 1); // the last (only) block
|
||||
w.put(1, 2); // fixed Huffman codes
|
||||
constexpr int kHashBits = 15, kWindow = 32768, kChain = 32;
|
||||
std::vector<int32_t> head(1u << kHashBits, -1), prev(data.size(), -1);
|
||||
const auto hash = [&](size_t i) { return ((data[i] << 10) ^ (data[i + 1] << 5) ^ data[i + 2]) & ((1u << kHashBits) - 1u); };
|
||||
size_t i = 0;
|
||||
while (i < data.size())
|
||||
{
|
||||
int bestLen = 0, bestDist = 0;
|
||||
if (i + 3 <= data.size())
|
||||
{
|
||||
const uint32_t h = hash(i);
|
||||
int32_t candidate = head[h];
|
||||
for (int chain = 0; candidate >= 0 && chain < kChain && static_cast<int>(i) - candidate <= kWindow; ++chain)
|
||||
{
|
||||
const size_t limit = std::min<size_t>(258, data.size() - i);
|
||||
size_t len = 0;
|
||||
while (len < limit && data[candidate + len] == data[i + len])
|
||||
++len;
|
||||
if (static_cast<int>(len) > bestLen)
|
||||
{
|
||||
bestLen = static_cast<int>(len);
|
||||
bestDist = static_cast<int>(i) - candidate;
|
||||
if (len == limit)
|
||||
break;
|
||||
}
|
||||
candidate = prev[candidate];
|
||||
}
|
||||
prev[i] = head[h];
|
||||
head[h] = static_cast<int32_t>(i);
|
||||
}
|
||||
if (bestLen >= 3)
|
||||
{
|
||||
int s = 0;
|
||||
while (s < 28 && kLengthBase[s + 1] <= bestLen)
|
||||
++s;
|
||||
literal(w, 257 + s);
|
||||
w.put(static_cast<uint32_t>(bestLen - kLengthBase[s]), kLengthExtra[s]);
|
||||
int d = 0;
|
||||
while (d < 29 && kDistBase[d + 1] <= bestDist)
|
||||
++d;
|
||||
w.putReversed(static_cast<uint32_t>(d), 5);
|
||||
w.put(static_cast<uint32_t>(bestDist - kDistBase[d]), kDistExtra[d]);
|
||||
for (size_t k = 1; k < static_cast<size_t>(bestLen); ++k) // the matched bytes join the hash chains
|
||||
if (i + k + 3 <= data.size())
|
||||
{
|
||||
const uint32_t h = hash(i + k);
|
||||
prev[i + k] = head[h];
|
||||
head[h] = static_cast<int32_t>(i + k);
|
||||
}
|
||||
i += static_cast<size_t>(bestLen);
|
||||
}
|
||||
else
|
||||
literal(w, data[i++]);
|
||||
}
|
||||
literal(w, 256);
|
||||
w.flush();
|
||||
uint32_t a = 1, b = 0;
|
||||
for (uint8_t c : data)
|
||||
{
|
||||
a = (a + c) % 65521u;
|
||||
b = (b + a) % 65521u;
|
||||
}
|
||||
for (int s = 24; s >= 0; s -= 8)
|
||||
w.out.push_back(static_cast<uint8_t>(((b << 16) | a) >> s));
|
||||
return w.out;
|
||||
}
|
||||
|
||||
uint32_t crc32(const uint8_t *p, size_t n, uint32_t c = 0)
|
||||
{
|
||||
static const std::array<uint32_t, 256> table = []
|
||||
{
|
||||
std::array<uint32_t, 256> t{};
|
||||
for (uint32_t k = 0; k < 256; ++k)
|
||||
{
|
||||
uint32_t v = k;
|
||||
for (int j = 0; j < 8; ++j)
|
||||
v = (v & 1u) ? 0xedb88320u ^ (v >> 1) : v >> 1;
|
||||
t[k] = v;
|
||||
}
|
||||
return t;
|
||||
}();
|
||||
c = ~c;
|
||||
for (size_t k = 0; k < n; ++k)
|
||||
c = table[(c ^ p[k]) & 0xffu] ^ (c >> 8);
|
||||
return ~c;
|
||||
}
|
||||
|
||||
void be32(std::vector<uint8_t> &o, uint32_t v)
|
||||
{
|
||||
for (int s = 24; s >= 0; s -= 8)
|
||||
o.push_back(static_cast<uint8_t>(v >> s));
|
||||
}
|
||||
|
||||
void chunk(std::vector<uint8_t> &o, const char *type, const std::vector<uint8_t> &d)
|
||||
{
|
||||
be32(o, static_cast<uint32_t>(d.size()));
|
||||
const size_t at = o.size();
|
||||
o.insert(o.end(), type, type + 4);
|
||||
o.insert(o.end(), d.begin(), d.end());
|
||||
be32(o, crc32(o.data() + at, o.size() - at));
|
||||
}
|
||||
|
||||
// channels 3 (RGB) or 4 (RGBA), rows top-down; each row filtered with Sub (a good choice for photographs).
|
||||
bool writePng(const fs::path &path, const uint8_t *pixels, int width, int height, int channels)
|
||||
{
|
||||
std::vector<uint8_t> raw;
|
||||
raw.reserve((static_cast<size_t>(width) * channels + 1) * height);
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
raw.push_back(1);
|
||||
const uint8_t *row = pixels + static_cast<size_t>(y) * width * channels;
|
||||
for (int x = 0; x < width * channels; ++x)
|
||||
raw.push_back(static_cast<uint8_t>(row[x] - (x >= channels ? row[x - channels] : 0)));
|
||||
}
|
||||
std::vector<uint8_t> png = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, header;
|
||||
be32(header, static_cast<uint32_t>(width));
|
||||
be32(header, static_cast<uint32_t>(height));
|
||||
header.insert(header.end(), {8, static_cast<uint8_t>(channels == 4 ? 6 : 2), 0, 0, 0});
|
||||
chunk(png, "IHDR", header);
|
||||
chunk(png, "IDAT", deflate(raw));
|
||||
chunk(png, "IEND", {});
|
||||
const fs::path temp = path.string() + ".part";
|
||||
{
|
||||
std::ofstream out(temp, std::ios::binary);
|
||||
out.write(reinterpret_cast<const char *>(png.data()), static_cast<std::streamsize>(png.size()));
|
||||
if (!out)
|
||||
return false;
|
||||
}
|
||||
std::error_code ec;
|
||||
fs::rename(temp, path, ec); // whole files only: an interrupted run leaves no half-written replacement
|
||||
return !ec;
|
||||
}
|
||||
|
||||
// ---- images ----
|
||||
|
||||
struct Image // float channels, row-major
|
||||
{
|
||||
int w = 0, h = 0, c = 0;
|
||||
std::vector<float> v;
|
||||
float &at(int x, int y, int k) { return v[(static_cast<size_t>(y) * w + x) * c + k]; }
|
||||
float at(int x, int y, int k) const { return v[(static_cast<size_t>(y) * w + x) * c + k]; }
|
||||
};
|
||||
|
||||
int wrap(int v, int n) { return ((v % n) + n) % n; }
|
||||
|
||||
// A border of `pad` texels taken from the opposite edges.
|
||||
Image wrapPad(const Image &in, int pad)
|
||||
{
|
||||
Image out{in.w + 2 * pad, in.h + 2 * pad, in.c, {}};
|
||||
out.v.resize(static_cast<size_t>(out.w) * out.h * out.c);
|
||||
for (int y = 0; y < out.h; ++y)
|
||||
for (int x = 0; x < out.w; ++x)
|
||||
for (int k = 0; k < in.c; ++k)
|
||||
out.at(x, y, k) = in.at(wrap(x - pad, in.w), wrap(y - pad, in.h), k);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Bicubic (Keys, a = -0.5, as Pillow's) by `scale`, pixel centres aligned; edges clamped.
|
||||
float cubic(float t)
|
||||
{
|
||||
t = std::fabs(t);
|
||||
if (t < 1.0f)
|
||||
return (1.5f * t - 2.5f) * t * t + 1.0f;
|
||||
if (t < 2.0f)
|
||||
return ((-0.5f * t + 2.5f) * t - 4.0f) * t + 2.0f;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
Image bicubic(const Image &in, int scale)
|
||||
{
|
||||
Image mid{in.w * scale, in.h, in.c, {}};
|
||||
mid.v.assign(static_cast<size_t>(mid.w) * mid.h * mid.c, 0.0f);
|
||||
for (int x = 0; x < mid.w; ++x)
|
||||
{
|
||||
const float s = (x + 0.5f) / scale - 0.5f;
|
||||
const int base = static_cast<int>(std::floor(s));
|
||||
float wsum = 0, wt[4];
|
||||
for (int t = 0; t < 4; ++t)
|
||||
wsum += wt[t] = cubic(s - static_cast<float>(base - 1 + t));
|
||||
for (int y = 0; y < in.h; ++y)
|
||||
for (int k = 0; k < in.c; ++k)
|
||||
{
|
||||
float acc = 0;
|
||||
for (int t = 0; t < 4; ++t)
|
||||
acc += wt[t] * in.at(std::clamp(base - 1 + t, 0, in.w - 1), y, k);
|
||||
mid.at(x, y, k) = acc / wsum;
|
||||
}
|
||||
}
|
||||
Image out{mid.w, in.h * scale, in.c, {}};
|
||||
out.v.assign(static_cast<size_t>(out.w) * out.h * out.c, 0.0f);
|
||||
for (int y = 0; y < out.h; ++y)
|
||||
{
|
||||
const float s = (y + 0.5f) / scale - 0.5f;
|
||||
const int base = static_cast<int>(std::floor(s));
|
||||
float wsum = 0, wt[4];
|
||||
for (int t = 0; t < 4; ++t)
|
||||
wsum += wt[t] = cubic(s - static_cast<float>(base - 1 + t));
|
||||
for (int x = 0; x < out.w; ++x)
|
||||
for (int k = 0; k < in.c; ++k)
|
||||
{
|
||||
float acc = 0;
|
||||
for (int t = 0; t < 4; ++t)
|
||||
acc += wt[t] * mid.at(x, std::clamp(base - 1 + t, 0, mid.h - 1), k);
|
||||
out.at(x, y, k) = acc / wsum;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Image gaussian(const Image &in, float sigma)
|
||||
{
|
||||
const int r = static_cast<int>(std::ceil(sigma * 3.0f));
|
||||
std::vector<float> kernel(2 * r + 1);
|
||||
float sum = 0;
|
||||
for (int i = -r; i <= r; ++i)
|
||||
sum += kernel[i + r] = std::exp(-(i * i) / (2.0f * sigma * sigma));
|
||||
for (float &k : kernel)
|
||||
k /= sum;
|
||||
Image tmp = in, out = in;
|
||||
for (int y = 0; y < in.h; ++y)
|
||||
for (int x = 0; x < in.w; ++x)
|
||||
for (int k = 0; k < in.c; ++k)
|
||||
{
|
||||
float acc = 0;
|
||||
for (int i = -r; i <= r; ++i)
|
||||
acc += kernel[i + r] * in.at(std::clamp(x + i, 0, in.w - 1), y, k);
|
||||
tmp.at(x, y, k) = acc;
|
||||
}
|
||||
for (int y = 0; y < in.h; ++y)
|
||||
for (int x = 0; x < in.w; ++x)
|
||||
for (int k = 0; k < in.c; ++k)
|
||||
{
|
||||
float acc = 0;
|
||||
for (int i = -r; i <= r; ++i)
|
||||
acc += kernel[i + r] * tmp.at(x, std::clamp(y + i, 0, in.h - 1), k);
|
||||
out.at(x, y, k) = acc;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- the steps ----
|
||||
|
||||
struct Texture
|
||||
{
|
||||
std::string identity;
|
||||
uint32_t w = 0, h = 0;
|
||||
std::vector<uint32_t> rgba; // GS alpha, R in the low byte
|
||||
Image rgb; // colour with transparent texels filled from their neighbours
|
||||
};
|
||||
|
||||
Image bleed(const Texture &t)
|
||||
{
|
||||
Image rgb{static_cast<int>(t.w), static_cast<int>(t.h), 3, {}};
|
||||
rgb.v.resize(static_cast<size_t>(t.w) * t.h * 3);
|
||||
std::vector<uint8_t> known(t.rgba.size());
|
||||
bool any = false, all = true;
|
||||
for (size_t i = 0; i < t.rgba.size(); ++i)
|
||||
{
|
||||
for (int k = 0; k < 3; ++k)
|
||||
rgb.v[i * 3 + k] = static_cast<float>((t.rgba[i] >> (8 * k)) & 0xffu);
|
||||
known[i] = (t.rgba[i] >> 24) != 0u;
|
||||
any |= known[i] != 0;
|
||||
all &= known[i] != 0;
|
||||
}
|
||||
if (!any || all)
|
||||
return rgb;
|
||||
const int w = rgb.w, h = rgb.h;
|
||||
for (int pass = 0; pass < 16; ++pass)
|
||||
{
|
||||
std::vector<uint8_t> next = known;
|
||||
bool grew = false, done = true;
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * w + x;
|
||||
if (known[i])
|
||||
continue;
|
||||
float acc[3] = {0, 0, 0};
|
||||
int n = 0;
|
||||
for (int dy = -1; dy <= 1; ++dy)
|
||||
for (int dx = -1; dx <= 1; ++dx)
|
||||
{
|
||||
const size_t j = static_cast<size_t>(wrap(y + dy, h)) * w + wrap(x + dx, w);
|
||||
if ((dx || dy) && known[j])
|
||||
{
|
||||
for (int k = 0; k < 3; ++k)
|
||||
acc[k] += rgb.v[j * 3 + k];
|
||||
++n;
|
||||
}
|
||||
}
|
||||
if (n)
|
||||
{
|
||||
for (int k = 0; k < 3; ++k)
|
||||
rgb.v[i * 3 + k] = acc[k] / static_cast<float>(n);
|
||||
next[i] = 1;
|
||||
grew = true;
|
||||
}
|
||||
else
|
||||
done = false;
|
||||
}
|
||||
known.swap(next);
|
||||
if (done || !grew)
|
||||
break;
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> upscaleAlpha(const Texture &t)
|
||||
{
|
||||
const int w = static_cast<int>(t.w), h = static_cast<int>(t.h), W = w * kScale, H = h * kScale;
|
||||
std::vector<uint8_t> values;
|
||||
Image a{w, h, 1, {}}, mask{w, h, 1, {}};
|
||||
a.v.resize(t.rgba.size());
|
||||
mask.v.resize(t.rgba.size());
|
||||
for (size_t i = 0; i < t.rgba.size(); ++i)
|
||||
{
|
||||
const uint8_t v = static_cast<uint8_t>(t.rgba[i] >> 24);
|
||||
a.v[i] = v;
|
||||
mask.v[i] = v ? 255.0f : 0.0f;
|
||||
values.push_back(v);
|
||||
}
|
||||
std::sort(values.begin(), values.end());
|
||||
values.erase(std::unique(values.begin(), values.end()), values.end());
|
||||
std::vector<uint8_t> out(static_cast<size_t>(W) * H, values[0]);
|
||||
if (values.size() == 1)
|
||||
return out;
|
||||
const auto up = [&](const Image &img)
|
||||
{
|
||||
const Image big = bicubic(wrapPad(img, kPad), kScale);
|
||||
Image crop{W, H, 1, {}};
|
||||
crop.v.resize(static_cast<size_t>(W) * H);
|
||||
for (int y = 0; y < H; ++y)
|
||||
for (int x = 0; x < W; ++x)
|
||||
crop.at(x, y, 0) = big.at(x + kPad * kScale, y + kPad * kScale, 0);
|
||||
return crop;
|
||||
};
|
||||
const Image big = up(a);
|
||||
if (values.size() == 2)
|
||||
{
|
||||
const float mid = (values[0] + values[1]) / 2.0f;
|
||||
for (size_t i = 0; i < out.size(); ++i)
|
||||
out[i] = big.v[i] >= mid ? values[1] : values[0];
|
||||
return out;
|
||||
}
|
||||
const bool hasZero = values[0] == 0;
|
||||
const Image shape = hasZero ? up(mask) : Image{};
|
||||
std::vector<uint8_t> visible(values.begin() + (hasZero ? 1 : 0), values.end());
|
||||
const bool has128 = std::binary_search(values.begin(), values.end(), uint8_t{128});
|
||||
for (size_t i = 0; i < out.size(); ++i)
|
||||
{
|
||||
if (hasZero && shape.v[i] < 128.0f)
|
||||
{
|
||||
out[i] = 0;
|
||||
continue;
|
||||
}
|
||||
float v = std::clamp(big.v[i], static_cast<float>(visible.front()), static_cast<float>(visible.back()));
|
||||
if (values.size() <= 4)
|
||||
{
|
||||
uint8_t best = visible[0];
|
||||
for (uint8_t level : visible)
|
||||
if (std::fabs(level - v) < std::fabs(best - v))
|
||||
best = level;
|
||||
v = best;
|
||||
}
|
||||
else if (has128 && std::fabs(v - 128.0f) <= 2.0f)
|
||||
v = 128.0f;
|
||||
out[i] = static_cast<uint8_t>(std::lround(v));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Texels equal to their 8 neighbours (colour and alpha within 1, wrap-around).
|
||||
std::vector<uint8_t> flatTexels(const Texture &t)
|
||||
{
|
||||
const int w = static_cast<int>(t.w), h = static_cast<int>(t.h);
|
||||
std::vector<uint8_t> flat(t.rgba.size(), 1);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const uint32_t c = t.rgba[static_cast<size_t>(y) * w + x];
|
||||
for (int dy = -1; dy <= 1 && flat[static_cast<size_t>(y) * w + x]; ++dy)
|
||||
for (int dx = -1; dx <= 1; ++dx)
|
||||
{
|
||||
const uint32_t d = t.rgba[static_cast<size_t>(wrap(y + dy, h)) * w + wrap(x + dx, w)];
|
||||
bool same = true;
|
||||
for (int k = 0; k < 4; ++k)
|
||||
same &= std::abs(static_cast<int>((c >> (8 * k)) & 0xffu) - static_cast<int>((d >> (8 * k)) & 0xffu)) <= 1;
|
||||
if (!same)
|
||||
{
|
||||
flat[static_cast<size_t>(y) * w + x] = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return flat;
|
||||
}
|
||||
|
||||
bool load(const fs::path &dump, const std::string &identity, Texture &t, std::string &why)
|
||||
{
|
||||
t.identity = identity;
|
||||
if (!bozo::render::readPng((dump / (identity + ".png")).string(), t.w, t.h, t.rgba, &why))
|
||||
return false;
|
||||
t.rgb = bleed(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool finish(const fs::path &dump, const std::string &identity, const fs::path &esrganOut, const fs::path &pack, float detail,
|
||||
std::string &why)
|
||||
{
|
||||
Texture t;
|
||||
if (!load(dump, identity, t, why))
|
||||
return false;
|
||||
uint32_t ow = 0, oh = 0;
|
||||
std::vector<uint32_t> model;
|
||||
if (!bozo::render::readPng(esrganOut.string(), ow, oh, model, &why))
|
||||
return false;
|
||||
const int w = static_cast<int>(t.w), h = static_cast<int>(t.h), W = w * kScale, H = h * kScale;
|
||||
if (ow != static_cast<uint32_t>((w + 2 * kPad) * kScale) || oh != static_cast<uint32_t>((h + 2 * kPad) * kScale))
|
||||
{
|
||||
why = "Real-ESRGAN's output has another size";
|
||||
return false;
|
||||
}
|
||||
Image hf;
|
||||
if (detail != 0.0f)
|
||||
{
|
||||
const Image big = bicubic(wrapPad(t.rgb, kPad), kScale);
|
||||
const Image blur = gaussian(big, 3.0f);
|
||||
hf = big;
|
||||
for (size_t i = 0; i < hf.v.size(); ++i)
|
||||
hf.v[i] = big.v[i] - blur.v[i];
|
||||
}
|
||||
const std::vector<uint8_t> alpha = upscaleAlpha(t), flat = flatTexels(t);
|
||||
std::vector<uint8_t> pixels(static_cast<size_t>(W) * H * 4);
|
||||
for (int y = 0; y < H; ++y)
|
||||
for (int x = 0; x < W; ++x)
|
||||
{
|
||||
uint8_t *p = &pixels[(static_cast<size_t>(y) * W + x) * 4];
|
||||
const size_t src = static_cast<size_t>(y / kScale) * w + x / kScale;
|
||||
if (flat[src])
|
||||
{
|
||||
for (int k = 0; k < 4; ++k)
|
||||
p[k] = static_cast<uint8_t>(t.rgba[src] >> (8 * k));
|
||||
continue;
|
||||
}
|
||||
const uint32_t m = model[static_cast<size_t>(y + kPad * kScale) * ow + x + kPad * kScale];
|
||||
for (int k = 0; k < 3; ++k)
|
||||
{
|
||||
float v = static_cast<float>((m >> (8 * k)) & 0xffu);
|
||||
if (detail != 0.0f)
|
||||
v += detail * hf.at(x + kPad * kScale, y + kPad * kScale, k);
|
||||
p[k] = static_cast<uint8_t>(std::clamp(std::lround(v), 0L, 255L));
|
||||
}
|
||||
p[3] = alpha[static_cast<size_t>(y) * W + x];
|
||||
}
|
||||
if (!writePng(pack / (t.identity + ".png"), pixels.data(), W, H, 4))
|
||||
{
|
||||
why = "cannot write the replacement";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Real-ESRGAN over a folder; progress from its output folder while it runs.
|
||||
int runEsrgan(const fs::path &exe, const fs::path &models, const std::string &model, const fs::path &in, const fs::path &out,
|
||||
size_t total)
|
||||
{
|
||||
std::vector<std::string> args = {exe.string(), "-i", in.string(), "-o", out.string(), "-n", model, "-m", models.string(),
|
||||
"-s", std::to_string(kScale), "-f", "png"};
|
||||
const auto count = [&]
|
||||
{
|
||||
size_t n = 0;
|
||||
std::error_code ec;
|
||||
for (fs::directory_iterator it(out, ec), end; !ec && it != end; it.increment(ec))
|
||||
++n;
|
||||
return n;
|
||||
};
|
||||
#if defined(_WIN32)
|
||||
std::wstring command;
|
||||
for (const std::string &a : args)
|
||||
{
|
||||
const std::wstring wa = fs::path(a).wstring();
|
||||
command += L"\"" + wa + L"\" ";
|
||||
}
|
||||
STARTUPINFOW si{};
|
||||
si.cb = sizeof(si);
|
||||
si.dwFlags = STARTF_USESTDHANDLES;
|
||||
si.hStdOutput = si.hStdError = CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
|
||||
PROCESS_INFORMATION pi{};
|
||||
if (!CreateProcessW(nullptr, command.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS,
|
||||
nullptr, nullptr, &si, &pi))
|
||||
{
|
||||
CloseHandle(si.hStdOutput);
|
||||
return -1;
|
||||
}
|
||||
while (WaitForSingleObject(pi.hProcess, 500) == WAIT_TIMEOUT)
|
||||
say("progress " + std::to_string(count()) + " " + std::to_string(total));
|
||||
DWORD code = 1;
|
||||
GetExitCodeProcess(pi.hProcess, &code);
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
CloseHandle(si.hStdOutput);
|
||||
return static_cast<int>(code);
|
||||
#else
|
||||
const pid_t pid = fork();
|
||||
if (pid == 0)
|
||||
{
|
||||
std::vector<char *> argv;
|
||||
for (std::string &a : args)
|
||||
argv.push_back(a.data());
|
||||
argv.push_back(nullptr);
|
||||
if (std::freopen("/dev/null", "w", stdout) && std::freopen("/dev/null", "w", stderr))
|
||||
execv(argv[0], argv.data());
|
||||
_exit(127);
|
||||
}
|
||||
if (pid < 0)
|
||||
return -1;
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, WNOHANG) == 0)
|
||||
{
|
||||
say("progress " + std::to_string(count()) + " " + std::to_string(total));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::vector<std::string> split(const std::string &s, char c)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
std::stringstream in(s);
|
||||
for (std::string part; std::getline(in, part, c);)
|
||||
out.push_back(part);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
std::vector<std::string> positional;
|
||||
fs::path esrgan, models, work;
|
||||
std::string model = "realesrgan-x4plus", skipList = "SHELL1,FONT";
|
||||
int minSize = 32;
|
||||
float detail = 1.0f;
|
||||
unsigned jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
|
||||
for (int i = 1; i < argc; ++i)
|
||||
{
|
||||
const std::string a = argv[i];
|
||||
const auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
|
||||
if (a == "--esrgan")
|
||||
esrgan = fs::path(next());
|
||||
else if (a == "--models")
|
||||
models = fs::path(next());
|
||||
else if (a == "--model")
|
||||
model = next();
|
||||
else if (a == "--min-size")
|
||||
minSize = std::atoi(next().c_str());
|
||||
else if (a == "--detail")
|
||||
detail = static_cast<float>(std::atof(next().c_str()));
|
||||
else if (a == "--skip")
|
||||
skipList = next();
|
||||
else if (a == "--jobs")
|
||||
jobs = static_cast<unsigned>(std::max(1, std::atoi(next().c_str())));
|
||||
else if (a == "--work")
|
||||
work = fs::path(next());
|
||||
else
|
||||
positional.push_back(a);
|
||||
}
|
||||
if (positional.size() != 2 || esrgan.empty())
|
||||
{
|
||||
std::fprintf(stderr, "usage: tmb-texture-pack <dump folder> <pack folder> --esrgan <realesrgan-ncnn-vulkan> [--models <folder>] "
|
||||
"[--model realesrgan-x4plus] [--min-size 32] [--detail 1.0] [--skip SHELL1,FONT] [--jobs N] [--work <folder>]\n");
|
||||
return 2;
|
||||
}
|
||||
const fs::path dump = fs::path(positional[0]), pack = fs::path(positional[1]);
|
||||
if (models.empty())
|
||||
models = esrgan.parent_path() / "models";
|
||||
if (work.empty())
|
||||
work = pack.parent_path() / (pack.filename().string() + ".work");
|
||||
std::vector<std::string> skip;
|
||||
for (std::string s : split(skipList, ','))
|
||||
if (!s.empty())
|
||||
{
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](char c) { return static_cast<char>(std::toupper(static_cast<unsigned char>(c))); });
|
||||
skip.push_back(s.substr(0, s.find('.')));
|
||||
}
|
||||
|
||||
std::ifstream index(dump / "index.tsv");
|
||||
if (!index)
|
||||
{
|
||||
say("error no texture dump in " + dump.string() + " (index.tsv)");
|
||||
return 1;
|
||||
}
|
||||
std::error_code ec;
|
||||
fs::create_directories(pack, ec);
|
||||
fs::remove_all(work, ec);
|
||||
fs::create_directories(work / "in", ec);
|
||||
fs::create_directories(work / "out", ec);
|
||||
|
||||
// ---- the textures to make: padded colour into the model's folder ----
|
||||
say("step prepare");
|
||||
// One row per identity: the dump's parallel runs can each list a texture they all load, and two threads writing
|
||||
// the same file into the model's folder would collide.
|
||||
std::vector<std::string> rows;
|
||||
std::unordered_set<std::string> seen;
|
||||
std::string line;
|
||||
std::getline(index, line); // the header
|
||||
while (std::getline(index, line))
|
||||
{
|
||||
if (!line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
if (!line.empty() && seen.insert(line.substr(0, line.find('\t'))).second)
|
||||
rows.push_back(line);
|
||||
}
|
||||
std::vector<std::string> todo; // identities (re-read when finished: a whole dump does not stay in memory)
|
||||
std::mutex todoMutex;
|
||||
std::atomic<size_t> next{0}, prepared{0};
|
||||
std::atomic<bool> failed{false};
|
||||
std::string failure;
|
||||
const auto prepare = [&]
|
||||
{
|
||||
for (size_t r; (r = next++) < rows.size();)
|
||||
{
|
||||
const std::vector<std::string> f = split(rows[r], '\t');
|
||||
if (f.size() < 5)
|
||||
continue;
|
||||
const std::string file = f[4].substr(0, f[4].find('#'));
|
||||
const std::string base = file.substr(0, file.find('.'));
|
||||
if (std::find(skip.begin(), skip.end(), base) != skip.end() || std::atoi(f[1].c_str()) < minSize ||
|
||||
std::atoi(f[2].c_str()) < minSize || fs::exists(pack / (f[0] + ".png")))
|
||||
continue;
|
||||
Texture t;
|
||||
std::string why;
|
||||
if (!load(dump, f[0], t, why))
|
||||
continue;
|
||||
const Image padded = wrapPad(t.rgb, kPad);
|
||||
std::vector<uint8_t> bytes(padded.v.size());
|
||||
for (size_t i = 0; i < bytes.size(); ++i)
|
||||
bytes[i] = static_cast<uint8_t>(std::clamp(std::lround(padded.v[i]), 0L, 255L));
|
||||
if (!writePng(work / "in" / (t.identity + ".png"), bytes.data(), padded.w, padded.h, 3))
|
||||
{
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(todoMutex);
|
||||
todo.push_back(t.identity);
|
||||
++prepared;
|
||||
}
|
||||
};
|
||||
{
|
||||
std::vector<std::thread> pool;
|
||||
for (unsigned j = 0; j < jobs; ++j)
|
||||
pool.emplace_back(prepare);
|
||||
for (std::thread &t : pool)
|
||||
t.join();
|
||||
}
|
||||
if (failed)
|
||||
{
|
||||
say("error cannot write to " + work.string());
|
||||
return 1;
|
||||
}
|
||||
if (todo.empty())
|
||||
{
|
||||
say("done 0");
|
||||
fs::remove_all(work, ec);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- the model ----
|
||||
say("step upscale");
|
||||
const int code = runEsrgan(esrgan, models, model, work / "in", work / "out", todo.size());
|
||||
if (code != 0)
|
||||
{
|
||||
say("error Real-ESRGAN stopped (exit code " + std::to_string(code) + "): it needs a Vulkan graphics driver");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- the replacements ----
|
||||
say("step finish");
|
||||
next = 0;
|
||||
std::atomic<size_t> finished{0}, errors{0};
|
||||
const auto finishAll = [&]
|
||||
{
|
||||
for (size_t i; (i = next++) < todo.size();)
|
||||
{
|
||||
std::string why;
|
||||
if (!finish(dump, todo[i], work / "out" / (todo[i] + ".png"), pack, detail, why))
|
||||
{
|
||||
++errors;
|
||||
say("warning " + todo[i] + ": " + why);
|
||||
}
|
||||
const size_t n = ++finished;
|
||||
if (n % 16 == 0 || n == todo.size())
|
||||
say("progress " + std::to_string(n) + " " + std::to_string(todo.size()));
|
||||
}
|
||||
};
|
||||
{
|
||||
std::vector<std::thread> pool;
|
||||
for (unsigned j = 0; j < jobs; ++j)
|
||||
pool.emplace_back(finishAll);
|
||||
for (std::thread &t : pool)
|
||||
t.join();
|
||||
}
|
||||
fs::remove_all(work, ec);
|
||||
say("done " + std::to_string(todo.size() - errors));
|
||||
return errors == todo.size() ? 1 : 0;
|
||||
}
|
||||
+300
-244
@@ -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, ®istry, 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, ®istry, 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);
|
||||
}
|
||||
+17
-4
@@ -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")
|
||||
@@ -203,6 +206,16 @@ tmb_native_manifest(tmb-headless)
|
||||
target_link_libraries(tmb-headless PRIVATE tmb_runtime tmb_generated bozo_host)
|
||||
target_compile_definitions(tmb-headless PRIVATE BOZO_RUN_DEFAULT_ELF="${TMB_ELF}")
|
||||
|
||||
# The launcher's "Enhance textures" step (tools/tmb_texture_enhance.py): a texture dump made into a replacement pack with
|
||||
# Real-ESRGAN, on the player's PC (docs/TEXTURE_UPSCALING.md). Reads PNGs with BozoEngine's reader; no other dependency.
|
||||
add_executable(tmb-texture-pack bozo/tmb_texture_pack.cpp)
|
||||
tmb_native_manifest(tmb-texture-pack)
|
||||
target_link_libraries(tmb-texture-pack PRIVATE bozo_render)
|
||||
target_compile_options(tmb-texture-pack PRIVATE -Wall -Wextra)
|
||||
if(MINGW)
|
||||
target_link_options(tmb-texture-pack PRIVATE -static)
|
||||
endif()
|
||||
|
||||
# Explicit target: exact native matrix/ABI checks against the owner's generated leaf functions. No disc or game run.
|
||||
add_executable(tmb-native-math-tests EXCLUDE_FROM_ALL tests/native_math_tests.cpp tests/native_direction_callers.cpp)
|
||||
target_include_directories(tmb-native-math-tests PRIVATE "${CMAKE_SOURCE_DIR}/runtime" ${gen_dir})
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"version": "0.6.0",
|
||||
"sha256": "d29bae3852abea4a6eee7b091141e637cd2db417383b476ac9778f3f3ff60957"
|
||||
}
|
||||
@@ -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()
|
||||
+33
-3
@@ -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.
|
||||
@@ -87,8 +88,8 @@ forwards for velocity reconstruction, forces, impact offsets and morph hit place
|
||||
Coverage is 119/269 known forward returns (150 remain), with 134/134 known inverses native.
|
||||
|
||||
Native graphics DMA/register removal: implementation and validation details are in
|
||||
[`NATIVE_GRAPHICS.md`](NATIVE_GRAPHICS.md). The source uses BozoEngine `4a8f70a`, including native graphics completion
|
||||
and the current shared native port services. The published v0.4.0 package remains the earlier release described above.
|
||||
[`NATIVE_GRAPHICS.md`](NATIVE_GRAPHICS.md). The source uses BozoEngine `a36a4d2` (see the bump notes below), including native graphics
|
||||
completion and the current shared native port services. The published v0.4.0 package remains the earlier release described above.
|
||||
|
||||
The player runtime's two camera matrix products now use typed native records without VU context state.
|
||||
[`NATIVE_MATH.md`](NATIVE_MATH.md) records exact helper/default-run comparisons, the traced HUD position.W
|
||||
@@ -249,13 +250,42 @@ 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.
|
||||
- Heat haze defaults on, as requested. `BOZO_HEAT_HAZE=0` is the comparison switch.
|
||||
- Existing cards/settings keep their format and `%APPDATA%\TMB_Recomp` location. Agent runs must set a scratch `PS2X_USER_DIR`.
|
||||
|
||||
## BozoEngine `db7591c`: owned handler stacks and texture upscaling (2026-11-10)
|
||||
|
||||
The pin moved from `4a8f70a` to engine main `db7591c` (232 commits). The bump brings SC3's texture upscaling (engine
|
||||
PR #83: `texture_upscale` off/2x/4x, `texture_filter` edge/smooth, in the Video tab) and VP2S's owned handler stacks
|
||||
(engine PR #75): native callbacks run on the interrupted thread's own stack, below its live SP.
|
||||
|
||||
That second change needed two fixes:
|
||||
- TMB's crt0 calls `SetupThread(0x8ff800, 0)` (a top, no size). Engine PR #85 declares the 1 MB below such a top.
|
||||
- TMB's hand-written code uses SP as data: `hierTraverseAsm` saves it at `s0 + 0x270`, sets it to 0 at `0x1d5450`,
|
||||
and restores it at `0x1d5718` and `0x1d5734` (a delay slot); `sysSetSp`/`sysRestoreSp` switch it.
|
||||
`runtime/tmb_stack_switch.cpp` parks the real SP with the kernel at each switch and resumes it once restored.
|
||||
|
||||
Validation (headless, private user folders; evidence in `D:/BozoScratch/texture-upscaling`):
|
||||
- Compared with the previous pin, the 1P route (9,500 frames, `ch1p_frames.txt`) and the actual 4P route
|
||||
(8,500 frames) match on every frame for draws, scratchpad, calls, threads and EE cycles.
|
||||
- Sound hashes differ on frames 1595, 1596, 1603 and 1611 only (menu), with equal sample counts throughout.
|
||||
- RAM differs from frame 4, because callback frames now live on the game's stack rather than at `0x1ffxxxx`.
|
||||
- Windowed 1P runs at off/2x/4x and a 4P run at 4x complete. Captures show the copyright movie, the menus, the
|
||||
arena and four views.
|
||||
- At 4x, the 1P route kept about 250 MB of copies (25 ms of worker time each); at 2x, 64 MB (7 ms each).
|
||||
|
||||
## BozoEngine `563454e`: texture replacements (2026-11-10)
|
||||
|
||||
Engine PR #86 adds texture replacements (`<identity>.png` in the user folder's `texture_pack`, read by workers) and a
|
||||
12 MB-per-present budget for larger copies. TMB's side is `tools/tmb_texture_upscale.py` (Real-ESRGAN over a
|
||||
`TMB_TEXTURE_DUMP` dump). Frame-pacing measurements with the bench lock are in `docs/TEXTURE_UPSCALING.md`: 1P and 4P
|
||||
hold 60 with a pack and 4x upscaling. Before the budget, 4x upscaling alone fell to 31 presents/s on the 1P route.
|
||||
Evidence: `D:/BozoScratch/texture-upscaling` (t-*.log, fps_summary.py); Real-ESRGAN in `D:/BozoScratch/esrgan`.
|
||||
|
||||
## Validation recorded in this continuation
|
||||
|
||||
- Engine: all 5 local CTest checks pass, including the corrected FMAC overflow case and its new boundary cases.
|
||||
|
||||
@@ -3,6 +3,83 @@
|
||||
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.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
|
||||
the release commit and engine `4a8f70a`;
|
||||
- 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 published v0.4.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.
|
||||
|
||||
v0.4.0 was published on 2026-11-06 after tagged CI, asset/hash audits and the owner's release request.
|
||||
The released portable package was updated, rebuilt and played locally with a scratch user folder. Unchecked items
|
||||
remain documented limitations; publication does not turn them into passing checks. See [HANDOFF.md](HANDOFF.md).
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,379 @@
|
||||
# Texture upscaling: investigation and plan
|
||||
|
||||
This document covers where TMB's textures come from in the native renderer, and how to identify each one across
|
||||
runs. It compares the upscaling options and their legal limits, and gives a staged plan. It also documents the
|
||||
first step that exists now: a texture dump behind an environment switch (`TMB_TEXTURE_DUMP`).
|
||||
|
||||
The investigation was written against main `777f964` (release 0.5.0) and BozoEngine `4a8f70a`. Everything here
|
||||
concerns the USA build in native graphics mode. Nothing in this plan routes through GS emulation or the historical
|
||||
checker.
|
||||
|
||||
## Status (2026-11-10): runtime upscaling is in the game
|
||||
|
||||
BozoEngine already had option B below as a renderer feature: the Soulcalibur III port's
|
||||
[engine PR #83](https://github.com/TheBozos/BozoEngine/pull/83). TMB gets it with the pin at `db7591c` and needs
|
||||
no code of its own, because `decodeRecord` marks every pack texture as an asset.
|
||||
|
||||
- **Settings:** `texture_upscale = off|2x|4x` and `texture_filter = edge|smooth` in `video.ini`, the F2 Video tab,
|
||||
or `PS2X_TEXTURE_UPSCALE` / `PS2X_TEXTURE_FILTER`. It is off by default.
|
||||
- **Filters:** the filters are the engine's own MIT code, written from published method descriptions (no
|
||||
GPL xBR/xBRZ code).
|
||||
- **Where it applies:** upscaling is present-side only, so the draw-list digests and replays do not change.
|
||||
Mip levels shift so that minified sampling is unchanged.
|
||||
- **Measured on TMB's 1P route (windowed, RTX 5070 Ti):**
|
||||
- 4x kept about 250 MB of copies, made in 25 ms of worker time each.
|
||||
- 2x kept 64 MB, made in 7 ms each.
|
||||
- **What it looks like:** edges of painted detail (grille bars, rust, decals) are smoother and less blocky. No
|
||||
detail is invented: it is filtering, not the offline AI path (option A).
|
||||
|
||||
## For players: the launcher's "Enhanced textures"
|
||||
|
||||
The launcher's Settings tab has an **Enhanced textures (AI)** section. It is opt-in, works from the player's own disc on
|
||||
their PC, and nothing of the game is downloaded or shipped.
|
||||
|
||||
1. **Make enhanced textures** runs `tools/tmb_texture_enhance.py` with the kit's Python:
|
||||
- the staged `game/tmb-headless.exe` dumps every arena and car (`tools/tmb_texture_dump_all.py`, its pad scripts
|
||||
in `tools/texture_dump/`);
|
||||
- the staged `game/tmb-texture-pack.exe` (`bozo/tmb_texture_pack.cpp`, the native counterpart of
|
||||
`tools/tmb_texture_upscale.py`) upscales them with the kit's Real-ESRGAN (`kit/realesrgan`, from
|
||||
`tools/make_build_kit.py`'s `realesrgan` step: the pinned upstream release zip, with its licences);
|
||||
- the result goes into `texture_pack.new`, which replaces `<user folder>\texture_pack`. The dump and work
|
||||
folders are then removed.
|
||||
2. Progress shows per step, with **Stop**: a stopped run goes on where it stopped next time. **Remove** deletes the
|
||||
pack, and **In the game: on/off** writes `video.ini`'s `texture_pack`. The game's own F2 → Video has the same
|
||||
switch.
|
||||
3. On this PC (RTX 5070 Ti) the launcher made 2,162 replacements in 5 min 10 s. Run-to-run counts vary by a few
|
||||
textures (2,161 to 2,164).
|
||||
|
||||
`tools/tmb_build.py` builds and stages the two tools with the game (the compile and stage steps). A release whose kit
|
||||
has no `realesrgan/` greys the button out with a note.
|
||||
|
||||
## Status (2026-11-10, later): AI texture packs (option A)
|
||||
|
||||
The engine reads **texture replacements**
|
||||
([BozoEngine `docs/texture-replace.md`](https://github.com/TheBozos/BozoEngine/blob/main/docs/texture-replace.md)):
|
||||
`<identity>.png` files in `<user folder>\texture_pack`, or set by `texture_pack` in `video.ini` or
|
||||
`PS2X_TEXTURE_PACK`. Each file is the texture's size or 2, 4 or 8 times it, read by worker threads. A replacement
|
||||
takes precedence over texture upscaling, which still covers textures without one.
|
||||
|
||||
**Making a pack from your own disc:**
|
||||
|
||||
1. Dump the textures. `TMB_TEXTURE_DUMP=1` (or `=<folder>`) writes each texture once as `<identity>.png`, with
|
||||
`index.tsv`. Every 250 frames it also writes every texture of every object in the loaded mesh files, drawn or
|
||||
not, so one match covers its whole arena and the cars loaded. For everything at once, run:
|
||||
```bash
|
||||
python tools/tmb_texture_dump_all.py <build>/tmb-headless.exe <disc.iso> <dump folder>
|
||||
```
|
||||
It runs headless through:
|
||||
- the 21 story levels (`TMB_STORY_LEVEL`, with every arena, the bosses and the story's cars). Level n's player
|
||||
picks the car n RIGHT presses along on the car-select screen, so levels 0 to 14 load the 15 player-only car
|
||||
versions (`PCAR/xxP` files; about 10% of each car's textures differ from its AI version);
|
||||
- the four-player route;
|
||||
- two Challenge matches with other opponents.
|
||||
|
||||
On the USA disc that is 2,289 textures (2,175 replacements in the pack): all arenas, every AI car and every player car.
|
||||
2. Get Real-ESRGAN's ncnn-vulkan build yourself (xinntao/Real-ESRGAN, BSD-3-Clause; release v0.2.5.0,
|
||||
`realesrgan-ncnn-vulkan-20220424-windows.zip`).
|
||||
3. Make the pack:
|
||||
```bash
|
||||
python tools/tmb_texture_upscale.py <texture_dump> "%APPDATA%/TMB_Recomp/texture_pack" --esrgan <folder>/realesrgan-ncnn-vulkan.exe
|
||||
```
|
||||
The tool needs Python with numpy and Pillow. It upscales 4x with `realesrgan-x4plus` over borders taken from
|
||||
the opposite edges, so repeating textures stay seamless, then adds the original's fine grain back, because the
|
||||
model flattens gravel and rust.
|
||||
- **Alpha:** keeps the GS alpha convention. See-through areas stay exactly see-through: the visible shape is
|
||||
smoothed, a few-level alpha is snapped back to its levels, and nothing spills into transparent texels.
|
||||
- **Flat areas** (a texel equal to its 8 neighbours) are kept exactly, so a black background stays black.
|
||||
- **Left out:** the menus and the font (`--skip`, default `SHELL1,FONT`) are left to the engine's upscaling,
|
||||
because the model garbles small lettering. Textures under 32 texels are left out too.
|
||||
|
||||
With `PS2X_TEXTURE_PACK_RELOAD=1`, changed files are drawn again while playing.
|
||||
|
||||
Packs are the player's own: never commit, ship or share them.
|
||||
|
||||
**Measured** (Junkyard 1P route, 273 replacements from that route's dump, RTX 5070 Ti, Ryzen 7 7800X3D):
|
||||
- Making the pack took 28 s, 11 s of it in Real-ESRGAN, and produced 71 MB of PNGs.
|
||||
- In game, each replacement is read in about 7 ms on a worker. The 1P route kept 241 MB of copies and sent 309 MB
|
||||
of textures to the GPU.
|
||||
- Frame pacing, measured with the bench lock held over the match's 2-second windows, holds 60:
|
||||
|
||||
| Run | Game fps min / avg | Presents min | Longest gap |
|
||||
|---|---|---|---|
|
||||
| 1P, upscaling off (baseline) | 59.32 / 60.00 | 57.5 | 88 ms |
|
||||
| 1P, 4x upscaling | 59.47 / 60.03 | 57.5 | 47 ms |
|
||||
| 1P, pack | 59.58 / 60.00 | 59.9 | 25 ms |
|
||||
| 1P, pack + 4x upscaling | 59.72 / 60.02 | 59.4 | 28 ms |
|
||||
| 4P baseline | 59.94 / 60.00 | 59.9 | 22 ms |
|
||||
| 4P, pack + 4x upscaling | 59.90 / 60.00 | 59.9 | 22 ms |
|
||||
|
||||
Before BozoEngine's upload budget (12 MB of larger copies per present), 1P at 4x upscaling fell to 31 presents/s
|
||||
for about 20 s while the arena's copies arrived. One of three 4P pack + 4x runs had a single 237 ms gap at a
|
||||
moment when no texture was sent; the other two did not.
|
||||
|
||||
**Full pack** (all arenas and cars, `tmb_texture_dump_all.py` then `tmb_texture_upscale.py`):
|
||||
- The dump takes about 10 minutes with 3 headless jobs. The pack has 2,164 replacements (609 MB of PNGs) and
|
||||
takes about 4 minutes, 85 s of it in Real-ESRGAN.
|
||||
- Final timing, bench lock held, game fps min / avg after the level load:
|
||||
|
||||
| Scene | Off | Pack + 4x upscaling |
|
||||
|---|---|---|
|
||||
| Junkyard 1P route | 59.63 / 60.00 | 59.57 / 60.02 |
|
||||
| Suburbs | 59.91 / 60.00 | 59.40 / 59.98 |
|
||||
| Downtown | 59.66 / 60.01 | 59.91 / 60.00 |
|
||||
| Prison | 49.33 / 59.27 | 47.83 / 58.65 |
|
||||
| 4P | 59.57 / 59.89 | 59.08, 59.51, 59.96 / 60.00 (three runs) |
|
||||
|
||||
Prison's story route dips below 60 with everything off too; in an earlier pair the pack run was the better one.
|
||||
Downtown and 4P show occasional present-only stutters (the game stays at 60) with or without a pack, with no
|
||||
texture uploads at those moments. That is an existing presentation issue, separate from textures.
|
||||
- Two fixes came out of this:
|
||||
- The engine's texture workers run at the lowest thread priority.
|
||||
- The engine no longer makes an upscaled copy of a texture whose replacement is being read.
|
||||
- **The menu hints bug:** "select" and "back" were drawn over dark boxes. The model tinted their black background
|
||||
and bicubic alpha spread into transparent texels. Fixed by the flat and alpha rules above and by leaving the
|
||||
menus to the engine.
|
||||
|
||||
**What it looks like:** ground, walls, rust and decals gain real detail, and edges are clean. The model can invent
|
||||
shapes from blurred stripes, for example "teeth" on one truck's radiator panel. Hand-fixing a file and reloading is
|
||||
the remedy. Textures the dump never saw (other arenas, cars, the story) are covered once they have been dumped.
|
||||
|
||||
## 1. Where textures come from
|
||||
|
||||
### Offline: the texture pack
|
||||
|
||||
`tools/tmb_texture_pack.py` converts the player's own disc during the build's `packs` step (the launcher's
|
||||
"Prepare the game"). The output is `tmb_textures.pack` (BozoEngine's `PS2XTEX1`), which is never committed. For
|
||||
each disc file (`*.TEX`, `*.RTX` and the ELF's font as `FONT`), it holds the records in the order the game sets
|
||||
them up. Each record stores its PSM, width, height and unpacked texels: one byte per index for T4/T8/H formats,
|
||||
and 2 or 4 bytes per texel for CT16/CT24/CT32.
|
||||
|
||||
On the current USA disc, the pack has 109 files and 14,105 records. About 6,800 are direct-colour records,
|
||||
mostly CT32 palettes. About 6,800 are T4/T8 textures and about 500 are H-format resident textures. The largest
|
||||
textures are 256×256. Decoded as RGBA8, the whole pack is about 238 MiB, and the largest level file
|
||||
(`SUBURB.TEX`) is about 14 MiB. A level loads one `.TEX` plus the shell, car and resident files.
|
||||
|
||||
### At run time: `runtime/tmb_textures.cpp`
|
||||
|
||||
The runtime never reads GS memory or the game's texture records. It follows the game's texture code at hooks:
|
||||
|
||||
| Hook | What it records |
|
||||
| --- | --- |
|
||||
| `fileReadf`, `zipInflateAll` | which disc file was read to which address |
|
||||
| `fileOnlyTexFile` / `fileAddTexFile`, `fileOnlyResFile` / `fileAddResFile` | the level's `.TEX` and `.RTX` lists, in order |
|
||||
| `texmSetupTexture` | the n-th setup is the pack's n-th `.TEX` record, keyed by the game's texture id |
|
||||
| `sceGsSetDefLoadImage` (from `texmLoadResTexture`) | the n-th `.RTX` record and the VRAM block it was loaded to (palettes, H textures) |
|
||||
| `fontInit` | the font's VRAM block |
|
||||
|
||||
Each hook checks the game's PSM and size against the pack record. `lookupLocked(tex0, texa, id)` then turns a
|
||||
draw's `TEX0` into a `bozo::render::Texture`: texels come from the texture id (meshes, particles) or from TBP
|
||||
through `texInfo`. The palette is assembled from the RTX records placed at CBP (CSM1 layout, CSA for T4), and
|
||||
alpha follows `TEXA`. `bozo::render::packs::decodeRecord` produces RGBA8 with **GS alpha (0x80 = 1.0)**. Results
|
||||
are cached per (texels record, palette record, TEX0 without the clamp bits, TEXA). The cache is cleared at each
|
||||
`texmInit` / `texmResInit` / `texmLoadResTexture`.
|
||||
|
||||
The consumers are:
|
||||
|
||||
- **Meshes** (`tmb_meshes.cpp:729`): `lookupId(obj+0x50[slot], TEX0 from the object's register block, 0)`.
|
||||
- **Particles** (`tmb_particles.cpp:425`): `lookupId(id, tex0, kTexa)`.
|
||||
- **Font and 2D** (`tmb_2d.cpp:160`): `tmb::textures::font()`. The other HUD/menu builders draw untextured
|
||||
geometry (`drawOverlay(..., nullptr)`). Today, the font is the only image-based 2D asset.
|
||||
- **Movies** (`tmb_2d.cpp` `moviePicture`): FFmpeg-decoded pictures, a new image each frame (key `0x4d4f5649`).
|
||||
They are out of scope for texture replacement.
|
||||
- **Render targets**: heat haze (`Material::sampleTarget`) and aux targets (`fromFrame`, `target`, `source`).
|
||||
These are frame copies, not assets, and are out of scope.
|
||||
|
||||
### In the engine: `BozoEngine/runtime/render/`
|
||||
|
||||
- `renderer.cpp` hashes each texture into the **draw-list hash** that recordings and replays compare: the XXH64
|
||||
of its RGBA, seeded with the XXH64 of `{width, height}`.
|
||||
- `present_gl.cpp` `Gpu::texture(key, source)` uploads each `Texture` once per (TEX0, TEXA, region) key as
|
||||
`GL_RGBA8`. The upload uses `GL_LINEAR` (or `GL_NEAREST` per material), **no mipmaps**, and REPEAT or
|
||||
CLAMP_TO_EDGE per material. `overlayTexture` converts GS alpha to 255 for the 2D.
|
||||
- The vertex UVs are **normalised (0..1)** (`Vertex::u/v`, the GS's S/Q and T/Q), and TMB never uses
|
||||
REGION_REPEAT. A texture with N times the pixels therefore needs no UV, draw or game change.
|
||||
|
||||
### The substitution point
|
||||
|
||||
There are two candidate places:
|
||||
|
||||
1. **In `lookupLocked`** (TMB), replacing the decoded `Texture`. This is simple, but it changes the draw-list hash.
|
||||
Every recording and replay comparison would then depend on the installed pack, so it is rejected.
|
||||
2. **At the GPU upload in `present_gl.cpp`** (engine): `Gpu::texture` / `overlayTexture` look up the texture's
|
||||
identity in a replacement set and upload the replacement instead. The game, the `Texture` object, the draw
|
||||
list and its hashes stay unchanged, and a replacement is purely presentation. **Recommended.** This needs a
|
||||
public BozoEngine change first (team rule), and the change is generic, so every port on the engine can use it.
|
||||
|
||||
## 2. Stable identity
|
||||
|
||||
**Primary key: the decoded image.** The key is the XXH64 of the RGBA8 texels with GS alpha, seeded with the
|
||||
XXH64 of `{width, height}`. It is exactly the value the renderer already computes for the draw-list hash
|
||||
(`textureIdentity`), so the dump's file names, the replacement lookup and the recorded draw hashes share one
|
||||
identity.
|
||||
|
||||
- It is stable across runs, machines and builds, because it depends only on the disc's data and the decoders.
|
||||
It changes only if a decoder changes, which would also be visible in the draw-hash comparisons.
|
||||
- Palettes are already folded in: a T4/T8 record shown with two palettes (vehicle colour variants, a different
|
||||
CSA) gives two images and two identities. Each variant needs its own replacement, which is correct, because
|
||||
the colours differ.
|
||||
- The `TEX0` size can exceed the record (`decodeRecord` pads with zeros), giving a different image and a
|
||||
different identity. That is also correct.
|
||||
- Identical images from different records (common for small solid or gradient textures) share one identity
|
||||
and one replacement, which is a feature.
|
||||
|
||||
**Secondary keys, kept in the dump's index only:**
|
||||
|
||||
- `texel_hash`: the XXH64 of the record's texels, seeded with `{psm, width, height}`. It groups the palette
|
||||
variants of one record, so a tool can upscale them as a batch or apply one artist mask to all of them.
|
||||
- The record's origin (`JUNKYARD.TEX#12`, `CARS.RTX#3`, `FONT#0`), the palette's origin, PSM, TEX0 and TEXA.
|
||||
These are diagnostics only and are not used as keys, because a record's ordinal depends on the pack layout.
|
||||
|
||||
**What could complicate this, and how TMB fares:**
|
||||
|
||||
- **CLUT animation.** The native path takes palettes from the pack, not from live EE memory, so a palette is
|
||||
static per record and VRAM block. If the game rewrote a palette from EE memory, the native renderer would not
|
||||
show it either. Animated surfaces in TMB scroll their UVs (the texture offset at `obj+0x20/+0x24` or the float
|
||||
table), which normalised UVs handle at any resolution.
|
||||
- **Mipmaps.** The game's mip table (`texmActivateTexture`, up to seven levels) is bookkeeping only. The pack and
|
||||
the renderer use level 0. Replacements are identified by level 0 alone, and their mips should be generated on
|
||||
the GPU (see 4).
|
||||
- **Render targets and movies.** They have no identity worth keeping and are excluded. The dump never sees them,
|
||||
because they never pass through `lookupLocked`.
|
||||
- **GS alpha above 0x80.** Most of TMB's textures use it: in the measured run, 204 of 274 have texels above 0x80,
|
||||
and 181 reach 0xFF (2.0), mostly through palettes. The shader multiplies before clamping, so these values
|
||||
matter. The dump therefore stores the GS alpha byte **unchanged** (128 = opaque), which makes a PNG round-trip
|
||||
to the same identity. Tools that want straight alpha must convert it themselves and keep the range above 1.0.
|
||||
|
||||
## 3. Upscaling options and legality
|
||||
|
||||
| Option | Quality | Cost to the player | Legal footprint |
|
||||
| --- | --- | --- | --- |
|
||||
| **A. Offline AI upscaling** (ESRGAN family) into a pack built on the player's PC | Best for world, vehicle and photographic textures; models trained on game art also suit the HUD and font | One-time GPU job per level/car set; disk space for the pack | Clean if the pack is generated locally from the player's disc and the upscaler and model licences permit redistribution or download |
|
||||
| **B. Runtime pixel-art filter** at upload (xBR/xBRZ, ScaleFX-style) | Good for the font and flat, aliased art; looks painterly on photographic textures | CPU or GPU work at upload; no pack | No game data at all; check the filter's code licence (xBRZ is GPL-3.0 and cannot go into an MIT runtime; the ScaleFX/xBR shaders need checking) |
|
||||
| **C. Better sampling only**: mipmaps, trilinear and anisotropic filtering | Removes shimmering at distance; no new detail | Negligible | None |
|
||||
|
||||
**Recommendation: C first, then A as an optional, opt-in "Enhance textures" step. B only for the font, if anyone
|
||||
asks for it.**
|
||||
|
||||
- **C** is a pure renderer improvement that every texture benefits from, and it is a prerequisite for A:
|
||||
upscaled textures without mipmaps alias badly at distance.
|
||||
- **A** gives the "beyond the original" look the owner asked for. Run the upscaler outside the game:
|
||||
[Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan) is a single executable on any
|
||||
Vulkan GPU with no Python, and its code and the `realesrgan-x4plus` weights are BSD-3. Many community models
|
||||
are CC-BY-NC or carry no licence, so only explicitly licensed models may be offered by default.
|
||||
- **Never ship game-derived data.** No PNG, replacement pack, palette or texel dump goes in the repository, a
|
||||
release, the build kit or a download. The pack is built on the player's PC from their own disc, like
|
||||
`tmb_textures.pack` and `tmb_meshes.pack`. A list of identities and record origins with **no pixels** (the
|
||||
dump's `index.tsv` holds only hashes, names and register values) is not game data, and could ship to tell the player's
|
||||
tool which palette variants exist (see plan step 5).
|
||||
- **Hand-made packs** from the community are outside the project. The loader would accept them as a local folder,
|
||||
like any player-supplied file, but the project neither hosts nor links them.
|
||||
|
||||
## 4. Feasibility
|
||||
|
||||
**VRAM.** A level is about 10–14 MiB of RGBA8 today, plus the shell, cars and resident textures. At 4× (16× the
|
||||
texels) with a full mip chain (×1.33), one level is about 200–300 MiB as RGBA8, or about 50–75 MiB as BC7. Both
|
||||
fit easily on any GPU that runs the port. At 8×, the RGBA8 figure is four times that again. BC7 compression at
|
||||
pack-build time, uploaded with `glCompressedTexImage2D` behind the extension check, is the recommended path past
|
||||
4×. The texture cache is cleared per level, so replacements are released with it.
|
||||
|
||||
**Load time.** Decoding PNGs at runtime is slow (about 10–30 ms for a 1024² image). For development only, the
|
||||
loader should read PNGs directly from a folder. For players, the "Prepare" step converts the PNGs into one
|
||||
container with an identity index and, ideally, pre-built mips and BC7 data, read by memory-mapping. A replacement
|
||||
is loaded at its first upload; with an mmapped container that costs well under a millisecond per texture. A level's
|
||||
replacements can also be read ahead at `texmInit` on a worker thread.
|
||||
|
||||
**UV, wrap and clamp.**
|
||||
|
||||
- UVs are normalised, so they need no change.
|
||||
- The replacement must have the **same aspect ratio and an integer scale** of the original. The loader rejects
|
||||
anything else and logs it.
|
||||
- Repeating textures need **seamless** upscaling: before upscaling, pad the image by wrapping it (tile it 3×3 or
|
||||
add a wrapped border), upscale, then crop the centre. Clamped ones are padded by edge extension. The upload
|
||||
path knows the wrap mode per material, not per texture, so the dump should also record whether an identity was
|
||||
ever drawn with REPEAT (plan step 2).
|
||||
- The game's `nearest` materials (`Material::nearest`) keep nearest sampling, which suits a pixel-art look. They
|
||||
will not look smoother unless they switch to linear filtering when a replacement is present.
|
||||
|
||||
**Alpha.**
|
||||
|
||||
- 3D textures go to the GPU with GS alpha (0..0xFF, where 0x80 is 1.0), and the shader multiplies by 255/128.
|
||||
Replacements keep that convention, as the dump writes it. Two concerns remain: an upscaler must not clip the
|
||||
alpha channel, and opaque texels (exactly 128) should stay exactly 128 after resampling.
|
||||
- Alpha-tested cutouts (fences, foliage, particles with `alphaTest`) need their alpha upscaled separately with a
|
||||
sharp, threshold-preserving filter (nearest, or bicubic followed by a threshold at the material's `alphaRef`),
|
||||
then recombined.
|
||||
- Before upscaling, bleed the colour of opaque texels into the transparent ones to avoid dark fringes, because the
|
||||
upscaler sees straight, not premultiplied, alpha.
|
||||
|
||||
**Plugging in.**
|
||||
|
||||
- **Engine (BozoEngine PR first):** `bozo::render::Replacements` holds an identity → image map with lazy load, and
|
||||
`Gpu::texture` / `overlayTexture` consult it before `makeTexture`. Add mip generation and `GL_LINEAR_MIPMAP_LINEAR`
|
||||
plus anisotropy for all textures (the C option) behind a video setting. Replay determinism holds because nothing
|
||||
above the GPU upload changes.
|
||||
- **TMB:** call `Replacements::load(<user folder>/textures/…)` at startup when the setting is on, and add a "Textures"
|
||||
row in the video settings tab (Original / Enhanced) with a hot reload.
|
||||
- **Launcher:** an optional step after "Prepare the game", "Enhance textures". It dumps or regenerates the textures
|
||||
from the player's pack, runs the upscaler, and builds the container in the user folder. It shows progress, can be
|
||||
resumed, and can be removed.
|
||||
|
||||
**Development workflow: dump, replace, hot-reload.**
|
||||
|
||||
1. Run with `TMB_TEXTURE_DUMP=1` and a scratch `PS2X_USER_DIR`. Each texture the renderer is given appears once as
|
||||
`texture_dump/<identity>.png`, with an `index.tsv` line.
|
||||
2. Upscale or edit any PNG and put it in `<user>/textures/replace/<identity>.png` (the planned layout).
|
||||
3. A hot-reload key (planned) re-reads that folder and drops the GPU copies of changed identities. The game itself
|
||||
is unaffected.
|
||||
|
||||
## 5. Plan
|
||||
|
||||
1. **Done (this change): texture dump.** `runtime/tmb_texture_dump.{h,cpp}`, with hooks in `tmb_textures.cpp`
|
||||
(`lookupLocked`, `font()`). It is off unless `TMB_TEXTURE_DUMP` is set: `1` writes to
|
||||
`$PS2X_USER_DIR/texture_dump`, any other value is a folder. It has no effect on the game, the renderer or the
|
||||
hashes. The PNG writer is dependency-free because the headless programs do not link `bozo_app`.
|
||||
2. **Dump coverage.** Record per identity whether it was drawn with REPEAT or CLAMP and whether it is alpha-tested
|
||||
(from the mesh and particle batches). Write a script that plays every arena and car (existing pad scripts and
|
||||
`tools/arena_script.py`) to dump everything, then report the counts per level.
|
||||
3. **Engine PR: sampling (option C).** Mipmaps, trilinear and anisotropic filtering behind a video setting
|
||||
(default on after visual checks). This is independently useful.
|
||||
4. **Engine PR: replacements.** An identity-keyed loader (a PNG folder for development, a container for players),
|
||||
upload in `present_gl.cpp` (GS alpha kept), integer-scale checks, hot reload, and a log line
|
||||
per replaced texture. Add a test that the draw-list hash is identical with and without replacements.
|
||||
5. **TMB: settings and launcher step.** Add the "Textures: Original / Enhanced" setting. Add the launcher step:
|
||||
regenerate the textures from the player's own pack, upscale them with a pinned upscaler and model (downloaded
|
||||
from upstream with a checksum, or included in the build kit only if both licences allow it), pad for wrap,
|
||||
handle alpha, encode as BC7, and write the container. To avoid making players play everything first, the
|
||||
generator can use a shipped **manifest without pixels** (identity, record origins, palette origin, PSM, TEX0,
|
||||
TEXA) from step 2's full dump. It reproduces each image from the player's pack and checks the identity (a
|
||||
mismatch means a different disc revision, and that entry is skipped).
|
||||
6. **Qualification.** Recordings must be identical with and without a pack. Check visuals per arena, VRAM and
|
||||
load-time measurements (bench lock only for those), and a 4P run.
|
||||
|
||||
**Risks:**
|
||||
|
||||
- Upscaler output quality varies, and text and HUD need different models than world textures.
|
||||
- AI artefacts on tiny textures (8×8 and 16×16 make up half the records): skip textures below a size threshold
|
||||
or upscale them with plain filtering.
|
||||
- Seams on tiling textures without wrap padding.
|
||||
- Disk and time cost of the launcher step (minutes to an hour, depending on GPU and scale).
|
||||
- Licence drift of models.
|
||||
- Identities change if a decoder fix lands. Mitigation: the dump index records `texel_hash` plus origins, so a
|
||||
tool can remap old replacements to new identities.
|
||||
|
||||
## 6. Prototype results
|
||||
|
||||
The dump was validated on a headless US build of this branch on the established 1P route
|
||||
(`ch1p_frames.txt`, 9,500 frames: boot movies, shell, Junkyard match). Each run used a private `PS2X_USER_DIR`.
|
||||
Local evidence is in `D:/BozoScratch/texture-upscaling`, and none of it is committed.
|
||||
|
||||
- The recordings with and without `TMB_TEXTURE_DUMP=1` are **byte-identical** (`.ref`, 760,240 bytes).
|
||||
- The run wrote 274 PNGs (15 MB) with 274 index lines, and no texture had an unknown origin. By file: JUNKYARD.TEX
|
||||
165, SHELL1.TEX 30, JUNKYARD.RTX 28 (H textures), car files 51 (MGA, STA, RLA, SUA, …) and FONT 1. By size:
|
||||
256² 28, 128² 113, 64² 104, 32² 28, 16² 1.
|
||||
- Of the 274 identities, only two pairs share a texel record (palette variants). This route shows mostly a single
|
||||
palette per record.
|
||||
- All 274 PNGs decode back to RGBA whose XXH64 equals the file's name, the renderer's identity
|
||||
(`verify_dump.py` in the evidence folder, an independent Python XXH64).
|
||||
- The font and a Junkyard ground texture were inspected visually.
|
||||
|
||||
This is one route. The full dump that steps 2 and 5 need (all arenas, all cars, story, 4P) is not done yet.
|
||||
@@ -25,10 +25,15 @@ 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,6 +105,10 @@ bool VideoConfig::load(const std::string &file)
|
||||
renderScale = v["render_scale"];
|
||||
if (!v["gs_scale"].empty())
|
||||
gsScale = std::clamp(std::atoi(v["gs_scale"].c_str()), 1, 4);
|
||||
others.clear();
|
||||
for (const auto &[key, value] : v)
|
||||
if (key != "size" && key != "mode" && key != "render_scale" && key != "gs_scale" && !value.empty())
|
||||
others[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -122,6 +126,8 @@ bool VideoConfig::save(const std::string &file) const
|
||||
text += "mode = " + mode + "\n";
|
||||
text += "render_scale = " + renderScale + "\n";
|
||||
text += "gs_scale = " + std::to_string(gsScale) + "\n";
|
||||
for (const auto &[key, value] : others) // the game's own settings (frame_rate, texture_upscale...): kept
|
||||
text += key + " = " + value + "\n";
|
||||
return writeAtomically(file, text);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// The launcher's own settings (launcher.ini in the user folder) and the game's window settings (video.ini there, in
|
||||
// the format of the fork's ps2xRuntime/src/lib/ps2_video_settings.cpp: the runner reads it when its window opens).
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -30,6 +31,11 @@ struct VideoConfig
|
||||
std::string renderScale = "1";
|
||||
int gsScale = 1;
|
||||
bool exists = false;
|
||||
// The game's other keys (frame_rate, texture_upscale, texture_filter, texture_pack...), written back as they were.
|
||||
std::map<std::string, std::string> others;
|
||||
// texture_pack: "off" turns the player's texture pack off; unset, the game uses texture_pack in the user folder.
|
||||
bool texturePackOff() const { auto it = others.find("texture_pack"); return it != others.end() && it->second == "off"; }
|
||||
void setTexturePackOff(bool off) { if (off) others["texture_pack"] = "off"; else others.erase("texture_pack"); }
|
||||
|
||||
bool load(const std::string &file);
|
||||
bool save(const std::string &file) const;
|
||||
|
||||
+214
-2
@@ -402,6 +402,15 @@ struct App
|
||||
std::thread downloader;
|
||||
plat::Process installer;
|
||||
|
||||
// -- enhanced textures: an AI-upscaled texture pack made on this PC from the player's own disc
|
||||
// (tools/tmb_texture_enhance.py: the staged headless game dumps the textures, tmb-texture-pack upscales them with the
|
||||
// kit's Real-ESRGAN into <user>\texture_pack). Nothing is downloaded or shipped.
|
||||
plat::Process enhancer;
|
||||
bool enhancing = false, enhanceRemoving = false, enhanceFinished = false; // finished: its "done" line seen
|
||||
std::string enhanceStep, enhanceError, enhanceNotice;
|
||||
unsigned long long enhanceDone = 0, enhanceTotal = 0;
|
||||
int packFiles = -1; // texture_pack's replacements (-1: not counted yet)
|
||||
|
||||
~App()
|
||||
{
|
||||
updateCancel = true; // a download stops at its next block
|
||||
@@ -644,6 +653,100 @@ struct App
|
||||
|
||||
std::vector<std::string> pythonArgs() const { return {"-I", "-X", "utf8", p.script}; }
|
||||
|
||||
// -- enhanced textures
|
||||
|
||||
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")) &&
|
||||
exists(plat::str(plat::path(p.source) / L"tools" / L"tmb_texture_enhance.py"));
|
||||
}
|
||||
void countPack()
|
||||
{
|
||||
packFiles = 0;
|
||||
std::error_code ec;
|
||||
for (fs::directory_iterator it(plat::path(packDir()), ec), end; !ec && it != end; it.increment(ec))
|
||||
if (it->path().extension() == L".png")
|
||||
++packFiles;
|
||||
}
|
||||
|
||||
void startEnhance(bool remove)
|
||||
{
|
||||
if (enhancing || building)
|
||||
return;
|
||||
std::vector<std::string> args = {"-I", "-X", "utf8", plat::str(plat::path(p.source) / L"tools" / L"tmb_texture_enhance.py"),
|
||||
"--user", p.user};
|
||||
if (remove)
|
||||
args.push_back("--remove");
|
||||
else
|
||||
args.insert(args.end(), {"--game", p.game, "--kit", p.kit});
|
||||
enhanceStep.clear();
|
||||
enhanceError.clear();
|
||||
enhanceNotice.clear();
|
||||
enhanceDone = enhanceTotal = 0;
|
||||
enhanceFinished = false;
|
||||
std::string error;
|
||||
if (!enhancer.start(p.python, args, p.source, true, error))
|
||||
{
|
||||
enhanceError = std::string(L("It could not start: ", "Impossible de démarrer : ")) + error;
|
||||
return;
|
||||
}
|
||||
enhancing = true;
|
||||
enhanceRemoving = remove;
|
||||
}
|
||||
|
||||
void cancelEnhance()
|
||||
{
|
||||
if (!enhancing)
|
||||
return;
|
||||
enhancer.kill();
|
||||
enhancing = false;
|
||||
enhanceNotice = L("Stopped. Make them again to go on where it stopped.",
|
||||
"Arrêté. Relancez pour reprendre là où ça s'est arrêté.");
|
||||
}
|
||||
|
||||
void pollEnhance()
|
||||
{
|
||||
if (!enhancing)
|
||||
return;
|
||||
auto feed = [&](const std::string &line)
|
||||
{
|
||||
unsigned long long a = 0, b = 0;
|
||||
if (line.rfind("step ", 0) == 0)
|
||||
{
|
||||
enhanceStep = line.substr(5);
|
||||
enhanceDone = enhanceTotal = 0;
|
||||
}
|
||||
else if (line.rfind("progress ", 0) == 0 && std::sscanf(line.c_str() + 9, "%llu %llu", &a, &b) == 2)
|
||||
{
|
||||
enhanceDone = a;
|
||||
enhanceTotal = b;
|
||||
}
|
||||
else if (line.rfind("error ", 0) == 0)
|
||||
enhanceError = line.substr(6);
|
||||
else if (line.rfind("done ", 0) == 0)
|
||||
enhanceFinished = true;
|
||||
};
|
||||
for (const std::string &line : enhancer.takeLines())
|
||||
feed(line);
|
||||
if (enhancer.running())
|
||||
return;
|
||||
enhancer.drain(2000);
|
||||
for (const std::string &line : enhancer.takeLines())
|
||||
feed(line);
|
||||
enhancing = false;
|
||||
countPack();
|
||||
if (enhancer.exitCode() == 0 && enhanceFinished)
|
||||
{
|
||||
enhanceNotice = enhanceRemoving ? L("Removed: the game uses its own textures.", "Supprimées : le jeu utilise ses propres textures.")
|
||||
: L("Done. The game uses them the next time it starts.",
|
||||
"Terminé. Le jeu les utilisera au prochain démarrage.");
|
||||
enhanceError.clear();
|
||||
}
|
||||
else if (enhanceError.empty())
|
||||
enhanceError = std::string(L("It stopped (exit code ", "Arrêt (code ")) + std::to_string(enhancer.exitCode()) + ").";
|
||||
}
|
||||
|
||||
// -- the disc
|
||||
|
||||
void pickDisc()
|
||||
@@ -1274,6 +1377,73 @@ static void drawReady(App &app, float inner)
|
||||
}
|
||||
}
|
||||
|
||||
// Enhanced textures: make (or remove) the AI texture pack, and turn it on or off (video.ini's texture_pack).
|
||||
static void drawEnhancedTextures(App &app, float inner)
|
||||
{
|
||||
if (app.packFiles < 0)
|
||||
app.countPack();
|
||||
ui::text(L("Enhanced textures (AI)", "Textures améliorées (IA)"), 17, ui::color::inkFaint);
|
||||
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + inner);
|
||||
ui::textWrapped(L("Every arena and car upscaled with Real-ESRGAN, on this PC, from your own disc: about 15 minutes "
|
||||
"(up to an hour on older graphics cards), 700 MB, Vulkan needed. Nothing is downloaded or sent.",
|
||||
"Chaque arène et véhicule agrandis avec Real-ESRGAN, sur ce PC, depuis votre disque : environ 15 minutes "
|
||||
"(jusqu'à une heure sur les cartes anciennes), 700 Mo, Vulkan requis. Rien n'est téléchargé ni envoyé."),
|
||||
15, ui::color::inkDim);
|
||||
ImGui::PopTextWrapPos();
|
||||
gap(6);
|
||||
if (app.enhancing)
|
||||
{
|
||||
const char *what = app.enhanceRemoving ? L("Removing\xE2\x80\xA6", "Suppression\xE2\x80\xA6")
|
||||
: app.enhanceStep == "dump" ? L("Reading the textures of every arena and car\xE2\x80\xA6",
|
||||
"Lecture des textures de chaque arène et véhicule\xE2\x80\xA6")
|
||||
: app.enhanceStep == "upscale" ? L("Upscaling with Real-ESRGAN\xE2\x80\xA6", "Agrandissement avec Real-ESRGAN\xE2\x80\xA6")
|
||||
: app.enhanceStep == "finish" ? L("Writing the textures\xE2\x80\xA6", "Écriture des textures\xE2\x80\xA6")
|
||||
: L("Preparing\xE2\x80\xA6", "Préparation\xE2\x80\xA6");
|
||||
ui::text(what, 17, ui::color::ink);
|
||||
ui::progressBar(app.enhanceTotal ? static_cast<float>(static_cast<double>(app.enhanceDone) / static_cast<double>(app.enhanceTotal)) : 0.0f,
|
||||
ImVec2(inner, S(14)), app.time);
|
||||
if (!app.enhanceRemoving && ui::button(L("Stop##enhance", "Arrêter##enhance"), ImVec2(S(160), S(36)), ui::Kind::Danger, true, 17))
|
||||
app.cancelEnhance();
|
||||
return;
|
||||
}
|
||||
const bool ready = app.built() && !app.building && !app.gameRunning && app.hasRealEsrgan();
|
||||
if (ui::button(app.packFiles > 0 ? L("Make again##enhance", "Refaire##enhance") : L("Make enhanced textures##enhance", "Créer les textures améliorées##enhance"),
|
||||
ImVec2(app.packFiles > 0 ? S(130) : S(290), S(36)), app.packFiles > 0 ? ui::Kind::Normal : ui::Kind::Primary, ready, 17))
|
||||
app.startEnhance(false);
|
||||
if (app.packFiles > 0)
|
||||
{
|
||||
ImGui::SameLine(0, S(10));
|
||||
if (ui::button(L("Remove##enhance", "Supprimer##enhance"), ImVec2(S(130), S(36)), ui::Kind::Normal, !app.gameRunning, 17))
|
||||
app.startEnhance(true);
|
||||
ImGui::SameLine(0, S(12));
|
||||
const bool on = !app.video.texturePackOff();
|
||||
char id[96];
|
||||
std::snprintf(id, sizeof(id), "%s##packon", on ? L("In the game: on", "Dans le jeu : oui") : L("In the game: off", "Dans le jeu : non"));
|
||||
if (ui::pill(id, on, 17))
|
||||
{
|
||||
app.video.setTexturePackOff(on);
|
||||
app.video.save(app.p.videoIni);
|
||||
app.video.exists = true;
|
||||
}
|
||||
}
|
||||
if (!app.hasRealEsrgan())
|
||||
ui::text(L("This release's build kit has no Real-ESRGAN.", "Le kit de cette version n'a pas Real-ESRGAN."), 15, ui::color::inkFaint);
|
||||
else if (!app.built())
|
||||
ui::text(L("Prepare the game first.", "Préparez d'abord le jeu."), 15, ui::color::inkFaint);
|
||||
else if (app.packFiles > 0 && app.enhanceError.empty() && app.enhanceNotice.empty()) // a result replaces the count
|
||||
{
|
||||
const std::string count = std::to_string(app.packFiles) + L(" enhanced textures, in your user folder.",
|
||||
" textures améliorées, dans votre dossier utilisateur.");
|
||||
ui::text(count.c_str(), 15, ui::color::inkFaint);
|
||||
}
|
||||
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + inner);
|
||||
if (!app.enhanceError.empty())
|
||||
ui::textWrapped(app.enhanceError.c_str(), 15, ui::color::early);
|
||||
else if (!app.enhanceNotice.empty())
|
||||
ui::textWrapped(app.enhanceNotice.c_str(), 15, ui::color::good);
|
||||
ImGui::PopTextWrapPos();
|
||||
}
|
||||
|
||||
static void drawSettings(App &app, float inner)
|
||||
{
|
||||
heading(L("Settings", "Réglages"));
|
||||
@@ -1285,6 +1455,8 @@ static void drawSettings(App &app, float inner)
|
||||
gap(10);
|
||||
VideoConfig &v = app.video;
|
||||
bool changed = false;
|
||||
const ImVec2 columns = ImGui::GetCursorPos(); // Window and Resolution on the left, Enhanced textures on the right
|
||||
const float half = inner * 0.5f;
|
||||
ui::text(L("Window", "Fenêtre"), 17, ui::color::inkFaint);
|
||||
const char *modes[3] = {"windowed", "fullscreen", "borderless"};
|
||||
const char *modeNames[3] = {L("Windowed", "Fenêtré"), L("Full screen", "Plein écran"), L("Borderless window", "Fenêtre sans bordure")};
|
||||
@@ -1350,6 +1522,12 @@ static void drawSettings(App &app, float inner)
|
||||
if (v.exists)
|
||||
ui::text(L("Saved. The game uses it the next time it starts.", "Enregistré. Le jeu l'utilisera au prochain démarrage."), 16,
|
||||
ui::color::good);
|
||||
const float leftBottom = ImGui::GetCursorPosY();
|
||||
ImGui::SetCursorPos(ImVec2(columns.x + half + S(12), columns.y));
|
||||
ImGui::BeginGroup();
|
||||
drawEnhancedTextures(app, half - S(12));
|
||||
ImGui::EndGroup();
|
||||
ImGui::SetCursorPos(ImVec2(columns.x, std::max(leftBottom, ImGui::GetItemRectMax().y - ImGui::GetWindowPos().y + ImGui::GetScrollY())));
|
||||
gap(12);
|
||||
ui::text(L("Launcher", "Lanceur"), 17, ui::color::inkFaint);
|
||||
if (ui::pill("English##en", !g_fr, 18))
|
||||
@@ -1614,7 +1792,7 @@ static void drawFrame(App &app)
|
||||
struct Selftest
|
||||
{
|
||||
std::string iso, shots, wrong;
|
||||
bool errorDemo = false, cancel = false, screensOnly = false;
|
||||
bool errorDemo = false, cancel = false, screensOnly = false, enhanceOnly = false;
|
||||
bool failed = false;
|
||||
double playSeconds = 40, crashSeconds = 0;
|
||||
std::FILE *log = nullptr;
|
||||
@@ -1660,6 +1838,31 @@ struct Selftest
|
||||
}};
|
||||
}
|
||||
|
||||
// --enhance (a test): Settings, then Make enhanced textures, its progress and its end, then quit.
|
||||
void buildEnhance()
|
||||
{
|
||||
steps.push_back({"settings", [](App &app, double) { app.tab = Tab::Settings; return true; }});
|
||||
steps.push_back(shot("e1-settings", 0.5));
|
||||
steps.push_back({"make", [this](App &app, double)
|
||||
{
|
||||
app.startEnhance(false);
|
||||
say("enhance started: %s", app.enhancing ? "yes" : app.enhanceError);
|
||||
return true;
|
||||
}});
|
||||
steps.push_back({"dumping", [](App &app, double t) { return (app.enhanceStep == "dump" && app.enhanceDone > 0) || !app.enhancing || t > 600; }});
|
||||
steps.push_back(shot("e2-dumping"));
|
||||
steps.push_back({"upscaling", [](App &app, double t) { return app.enhanceStep == "upscale" || !app.enhancing || t > 3600; }});
|
||||
steps.push_back(shot("e3-upscaling", 3.0));
|
||||
steps.push_back({"finished", [](App &app, double t) { return !app.enhancing || t > 3600; }});
|
||||
steps.push_back(shot("e4-done", 0.5));
|
||||
steps.push_back({"quit", [this](App &app, double)
|
||||
{
|
||||
say("enhance: %s textures, %s", std::to_string(app.packFiles), app.enhanceError.empty() ? "ok: " + app.enhanceNotice : "error: " + app.enhanceError);
|
||||
app.quit = true;
|
||||
return true;
|
||||
}});
|
||||
}
|
||||
|
||||
// --screens: the three tabs as they are now (a layout check at a --ui-scale, the update notice), then quit.
|
||||
void buildScreens()
|
||||
{
|
||||
@@ -1701,6 +1904,11 @@ struct Selftest
|
||||
buildScreens();
|
||||
return;
|
||||
}
|
||||
if (enhanceOnly)
|
||||
{
|
||||
buildEnhance();
|
||||
return;
|
||||
}
|
||||
steps.push_back(shot("01-welcome", 1.5));
|
||||
steps.push_back({"french welcome", [](App &app, double) { g_fr = true; (void)app; return true; }});
|
||||
steps.push_back(shot("02-welcome-fr"));
|
||||
@@ -2020,7 +2228,7 @@ static int selfCheck(const std::string &release, const std::string &file, const
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
std::string release, selftestIso, shots, wrong;
|
||||
bool errorDemo = false, cancel = false, screensOnly = false;
|
||||
bool errorDemo = false, cancel = false, screensOnly = false, enhanceOnly = false;
|
||||
double playSeconds = 40, crashSeconds = 0;
|
||||
float uiScale = 0;
|
||||
std::string updateUrl, selfCheckFile, reportPath, downloadPrefix;
|
||||
@@ -2050,6 +2258,8 @@ int main(int argc, char **argv)
|
||||
crashSeconds = std::atof(next().c_str());
|
||||
else if (a == "--screens")
|
||||
screensOnly = true;
|
||||
else if (a == "--enhance") // a test (with --selftest): Settings' Make enhanced textures, to its end
|
||||
enhanceOnly = true;
|
||||
else if (a == "--ui-scale") // a test: the layout at another DPI scale (1.5 = Windows' 150 %)
|
||||
uiScale = static_cast<float>(std::atof(next().c_str()));
|
||||
else if (a == "--update-url") // a test: another address answering as GitHub's latest-release API
|
||||
@@ -2105,6 +2315,7 @@ int main(int argc, char **argv)
|
||||
test.playSeconds = playSeconds;
|
||||
test.crashSeconds = crashSeconds;
|
||||
test.screensOnly = screensOnly;
|
||||
test.enhanceOnly = enhanceOnly;
|
||||
test.log = _wfopen((plat::path(test.shots) / L"selftest.log").c_str(), L"w");
|
||||
test.t0 = plat::now();
|
||||
test.say("release %s, user folder %s", app.p.release, app.p.user);
|
||||
@@ -2125,6 +2336,7 @@ int main(int argc, char **argv)
|
||||
app.pollCheck();
|
||||
app.pollBuild();
|
||||
app.pollUpdate();
|
||||
app.pollEnhance();
|
||||
if (updateNow && app.updateStep == App::UpdateStep::Idle)
|
||||
{
|
||||
std::string version, tag;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"$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"],
|
||||
"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"],
|
||||
"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" } } }
|
||||
}
|
||||
+1137
-1120
File diff suppressed because it is too large.
Load diff
+492
-461
@@ -1,461 +1,492 @@
|
||||
// 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));
|
||||
}
|
||||
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); }
|
||||
}
|
||||
@@ -16,6 +16,7 @@ namespace tmb::math { bool hudInstruction(uint8_t *, R5900Context *, Runtime *,
|
||||
namespace tmb::math { bool vehicleInstruction(uint8_t *, R5900Context *, Runtime *, uint32_t); }
|
||||
namespace tmb::math { bool contactInstruction(uint8_t *, R5900Context *, Runtime *, uint32_t); }
|
||||
namespace tmb::math { bool cameraInstruction(uint8_t *, R5900Context *, Runtime *, uint32_t); }
|
||||
namespace tmb::stackSwitch { bool instruction(uint8_t *, R5900Context *, Runtime *, uint32_t); }
|
||||
|
||||
namespace tmb::graphics
|
||||
{
|
||||
@@ -69,6 +70,7 @@ namespace tmb::graphics
|
||||
|
||||
bool instruction(uint8_t *ram, R5900Context *ctx, Runtime *rt, uint32_t pc)
|
||||
{
|
||||
if (tmb::stackSwitch::instruction(ram, ctx, rt, pc)) return true;
|
||||
if (tmb::scene::instruction(ram, ctx, rt, pc)) return true;
|
||||
if (tmb::packets::instruction(ram, ctx, rt, pc)) return true;
|
||||
if (tmb::textureInputs::instruction(ram, ctx, rt, pc)) return true;
|
||||
|
||||
@@ -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(©, 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(©, kArgs[i++], a);
|
||||
copy.pc = address;
|
||||
fn(rdram, ©, rt);
|
||||
}
|
||||
uint32_t result() const { return getRegU32(©, 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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+1813
-1731
File diff suppressed because it is too large.
Load diff
+30
-4
@@ -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();
|
||||
|
||||
@@ -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"
|
||||
@@ -11,6 +12,7 @@
|
||||
#include "tmb_host.h"
|
||||
|
||||
namespace tmb::graphics { void install(Registry &); }
|
||||
namespace tmb::stackSwitch { void install(Registry &); }
|
||||
namespace tmb::math { void install(Registry &); }
|
||||
namespace tmb::hierarchy { void install(Registry &); }
|
||||
|
||||
@@ -54,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);
|
||||
@@ -494,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));
|
||||
@@ -543,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
|
||||
@@ -1107,6 +1122,7 @@ namespace
|
||||
tmb::meshes::install(runtime); // rigid objects from the offline mesh pack (runtime/tmb_meshes.cpp)
|
||||
tmb::particles::install(runtime); // particles drawn from their structs (runtime/tmb_particles.cpp)
|
||||
tmb::graphics::install(runtime); // direct submission/completion; retired graphics MMIO is rejected
|
||||
tmb::stackSwitch::install(runtime); // the game's SP switches parked for native callbacks (tmb_stack_switch.cpp)
|
||||
tmb::math::install(runtime); // matrix records computed natively, with no VU context dependency
|
||||
tmb::hierarchy::install(runtime); // collision hierarchy calculations over game records
|
||||
if (const char *trace = std::getenv("TMB_TRACE_HIER"); trace && *trace == '1')
|
||||
@@ -1136,6 +1152,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));
|
||||
@@ -1177,4 +1195,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)
|
||||
@@ -48,6 +48,7 @@
|
||||
// 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 "tmb_port.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
@@ -67,7 +68,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]);
|
||||
@@ -2414,7 +2416,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 +2426,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 +2641,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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// The game's deliberate stack-pointer switches, declared to BozoEngine's kernel. Native callbacks (interrupt and alarm
|
||||
// handlers) run on the interrupted thread's own stack, below its live stack pointer (the engine's owned handler
|
||||
// stacks). On a PS2 they run on the kernel's stack, so TMB's hand-written code may use SP as an ordinary register:
|
||||
// - hierTraverseAsm saves SP at s0 + 0x270 (0x1d5438), sets it to 0 (0x1d5450), loads a pointer into it (0x1d547c)
|
||||
// and restores it from s0 + 0x270 on its two exits (0x1d5718, and 0x1d5734 in a branch's delay slot);
|
||||
// - sysSetSp / sysRestoreSp move SP to a work stack and back.
|
||||
// Each switch parks the real SP with the kernel first (Kernel::parkThreadStack) and resumes it once restored, so a
|
||||
// callback taken in between still finds the thread's stack. Native graphics only: the historical checker keeps the
|
||||
// original instructions and the recorded hosts' handler stacks.
|
||||
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/ee/kernel.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace tmb::stackSwitch
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr uint32_t kParkSp = 0x001d5450u; // addu sp, zero, zero
|
||||
constexpr uint32_t kRestoreSp = 0x001d5718u, kRestoreSpDelay = 0x001d5734u; // ld sp, 0x270(s0)
|
||||
constexpr uint32_t kSysSetSp = 0x001eeae0u, kSysRestoreSp = 0x001eeaf0u;
|
||||
|
||||
// bozo:native kStackSwitch (literals: tools/tmb_overrides_list.py reads them)
|
||||
constexpr uint32_t kStackSwitch[] = {0x001d5450u, 0x001d5718u, 0x001d5734u};
|
||||
static_assert(kStackSwitch[0] == kParkSp && kStackSwitch[1] == kRestoreSp && kStackSwitch[2] == kRestoreSpDelay);
|
||||
|
||||
void sysSetSpOverride(uint8_t *ram, R5900Context *ctx, Runtime *rt)
|
||||
{
|
||||
const uint32_t sp = getRegU32(ctx, 29);
|
||||
if (bozo::port::nativeGraphics(rt))
|
||||
bozo::port::kernel(rt).parkThreadStack(sp);
|
||||
setRegU64(ctx, 2, static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(sp)))); // move v0, sp
|
||||
ctx->r[29].ud[0] = ctx->r[4].ud[0]; // move sp, a0
|
||||
ctx->pc = getRegU32(ctx, 31);
|
||||
(void)ram;
|
||||
}
|
||||
|
||||
void sysRestoreSpOverride(uint8_t *ram, R5900Context *ctx, Runtime *rt)
|
||||
{
|
||||
ctx->r[29].ud[0] = ctx->r[4].ud[0]; // move sp, a0
|
||||
if (bozo::port::nativeGraphics(rt))
|
||||
bozo::port::kernel(rt).resumeThreadStack(getRegU32(ctx, 29));
|
||||
ctx->pc = getRegU32(ctx, 31);
|
||||
(void)ram;
|
||||
}
|
||||
}
|
||||
|
||||
bool instruction(uint8_t *ram, R5900Context *ctx, Runtime *rt, uint32_t pc)
|
||||
{
|
||||
if (!std::binary_search(std::begin(kStackSwitch), std::end(kStackSwitch), pc))
|
||||
return false;
|
||||
if (pc == kParkSp)
|
||||
{
|
||||
bozo::port::kernel(rt).parkThreadStack(getRegU32(ctx, 29));
|
||||
ctx->r[29].ud[0] = 0;
|
||||
return true;
|
||||
}
|
||||
ctx->r[29].ud[0] = bozo::load<uint64_t>(ram, ctx, rt, getRegU32(ctx, 16) + 0x270u);
|
||||
bozo::port::kernel(rt).resumeThreadStack(getRegU32(ctx, 29));
|
||||
return true;
|
||||
}
|
||||
|
||||
void install(Registry &runtime)
|
||||
{
|
||||
runtime.registerFunction(kSysSetSp, &sysSetSpOverride);
|
||||
runtime.registerFunction(kSysRestoreSp, &sysRestoreSpOverride);
|
||||
}
|
||||
}
|
||||
@@ -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(); }});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// The texture dump (tmb_texture_dump.h). A development tool for building texture replacement packs from the player's
|
||||
// own disc: the PNGs it writes are the player's, made on their PC, and never part of the repository or a release.
|
||||
//
|
||||
// Each file is <identity as 16 hex digits>.png: the texture exactly as the renderer gets it, alpha included as the GS's
|
||||
// (128 is opaque, up to 255 = 2.0, which most of TMB's palettes use), so the PNG round-trips to the same identity.
|
||||
// Tools that want straight alpha double it (and must keep the values above 128). index.tsv gets one line per new
|
||||
// file: identity, width, height, psm, the records it was decoded from (the palette: the one at CBP), tex0, texa, the
|
||||
// texels' hash and the largest alpha.
|
||||
|
||||
#include "tmb_texture_dump.h"
|
||||
|
||||
#include "bozo/hash.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace tmb::textures::dump
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct State
|
||||
{
|
||||
std::mutex mutex;
|
||||
bool resolved = false;
|
||||
std::filesystem::path folder; // empty: off
|
||||
std::unordered_set<uint64_t> written;
|
||||
uint64_t files = 0;
|
||||
};
|
||||
State &state()
|
||||
{
|
||||
static State s_state;
|
||||
return s_state;
|
||||
}
|
||||
|
||||
void resolve(State &s)
|
||||
{
|
||||
if (s.resolved)
|
||||
return;
|
||||
s.resolved = true;
|
||||
const char *value = std::getenv("TMB_TEXTURE_DUMP");
|
||||
if (!value || !*value || std::string(value) == "0")
|
||||
return;
|
||||
if (std::string(value) == "1")
|
||||
{
|
||||
const char *user = std::getenv("PS2X_USER_DIR");
|
||||
s.folder = std::filesystem::path(user && *user ? user : ".") / "texture_dump";
|
||||
}
|
||||
else
|
||||
s.folder = std::filesystem::u8path(value);
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(s.folder, ec);
|
||||
if (ec)
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:texdump] cannot create %s: %s (no dump)\n", s.folder.u8string().c_str(), ec.message().c_str());
|
||||
s.folder.clear();
|
||||
return;
|
||||
}
|
||||
std::fprintf(stderr, "[tmb:texdump] dumping textures to %s\n", s.folder.u8string().c_str());
|
||||
const std::filesystem::path index = s.folder / "index.tsv";
|
||||
if (!std::filesystem::exists(index, ec))
|
||||
{
|
||||
std::ofstream out(index, std::ios::binary);
|
||||
out << "identity\twidth\theight\tpsm\ttexels\tpalette\ttex0\ttexa\ttexel_hash\tmax_alpha\n";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a PNG with no dependency: zlib's stored blocks (the same approach as BozoEngine's app/png.cpp, which
|
||||
// the headless programs this runtime is part of do not link) ----
|
||||
|
||||
uint32_t crc32(const uint8_t *data, size_t size, uint32_t crc = 0)
|
||||
{
|
||||
static const std::array<uint32_t, 256> table = []
|
||||
{
|
||||
std::array<uint32_t, 256> t{};
|
||||
for (uint32_t n = 0; n < 256u; ++n)
|
||||
{
|
||||
uint32_t c = n;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
c = (c & 1u) ? 0xedb88320u ^ (c >> 1) : c >> 1;
|
||||
t[n] = c;
|
||||
}
|
||||
return t;
|
||||
}();
|
||||
crc = ~crc;
|
||||
for (size_t i = 0; i < size; ++i)
|
||||
crc = table[(crc ^ data[i]) & 0xffu] ^ (crc >> 8);
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
void putBe32(std::vector<uint8_t> &out, uint32_t v)
|
||||
{
|
||||
for (int shift = 24; shift >= 0; shift -= 8)
|
||||
out.push_back(static_cast<uint8_t>(v >> shift));
|
||||
}
|
||||
|
||||
void chunk(std::vector<uint8_t> &out, const char type[4], const std::vector<uint8_t> &data)
|
||||
{
|
||||
putBe32(out, static_cast<uint32_t>(data.size()));
|
||||
const size_t start = out.size();
|
||||
out.insert(out.end(), type, type + 4);
|
||||
out.insert(out.end(), data.begin(), data.end());
|
||||
putBe32(out, crc32(out.data() + start, out.size() - start));
|
||||
}
|
||||
|
||||
bool writePng(const std::filesystem::path &path, const std::vector<uint8_t> &rgba, uint32_t width, uint32_t height)
|
||||
{
|
||||
std::vector<uint8_t> raw; // each row: filter 0, then its pixels
|
||||
raw.reserve((static_cast<size_t>(width) * 4u + 1u) * height);
|
||||
for (uint32_t y = 0; y < height; ++y)
|
||||
{
|
||||
raw.push_back(0);
|
||||
const uint8_t *row = rgba.data() + static_cast<size_t>(y) * width * 4u;
|
||||
raw.insert(raw.end(), row, row + static_cast<size_t>(width) * 4u);
|
||||
}
|
||||
std::vector<uint8_t> z = {0x78, 0x01};
|
||||
for (size_t at = 0;;) // raw is never empty: height >= 1, a filter byte per row
|
||||
{
|
||||
const size_t n = std::min<size_t>(65535u, raw.size() - at);
|
||||
const bool last = at + n == raw.size();
|
||||
z.push_back(last ? 1 : 0);
|
||||
z.push_back(static_cast<uint8_t>(n));
|
||||
z.push_back(static_cast<uint8_t>(n >> 8));
|
||||
z.push_back(static_cast<uint8_t>(~n));
|
||||
z.push_back(static_cast<uint8_t>(~n >> 8));
|
||||
z.insert(z.end(), raw.begin() + static_cast<std::ptrdiff_t>(at), raw.begin() + static_cast<std::ptrdiff_t>(at + n));
|
||||
at += n;
|
||||
if (last)
|
||||
break;
|
||||
}
|
||||
uint32_t a = 1, b = 0;
|
||||
for (uint8_t c : raw)
|
||||
{
|
||||
a = (a + c) % 65521u;
|
||||
b = (b + a) % 65521u;
|
||||
}
|
||||
putBe32(z, (b << 16) | a);
|
||||
|
||||
std::vector<uint8_t> png = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'};
|
||||
std::vector<uint8_t> header;
|
||||
putBe32(header, width);
|
||||
putBe32(header, height);
|
||||
header.insert(header.end(), {8, 6, 0, 0, 0}); // 8 bits, RGBA, deflate, no filter choice, no interlace
|
||||
chunk(png, "IHDR", header);
|
||||
chunk(png, "IDAT", z);
|
||||
chunk(png, "IEND", {});
|
||||
std::ofstream out(path, std::ios::binary);
|
||||
out.write(reinterpret_cast<const char *>(png.data()), static_cast<std::streamsize>(png.size()));
|
||||
return static_cast<bool>(out);
|
||||
}
|
||||
}
|
||||
|
||||
bool enabled()
|
||||
{
|
||||
State &s = state();
|
||||
std::lock_guard<std::mutex> lock(s.mutex);
|
||||
resolve(s);
|
||||
return !s.folder.empty();
|
||||
}
|
||||
|
||||
uint64_t identity(const bozo::render::Texture &texture)
|
||||
{
|
||||
const uint32_t size[2] = {texture.width, texture.height};
|
||||
return bozo::hash::xxh64(texture.rgba.data(), texture.rgba.size() * sizeof(uint32_t), bozo::hash::xxh64(size, sizeof(size), 0));
|
||||
}
|
||||
|
||||
void note(const bozo::render::Texture &texture, const Source &source)
|
||||
{
|
||||
State &s = state();
|
||||
std::lock_guard<std::mutex> lock(s.mutex);
|
||||
resolve(s);
|
||||
if (s.folder.empty() || texture.width == 0u || texture.height == 0u ||
|
||||
texture.rgba.size() != static_cast<size_t>(texture.width) * texture.height)
|
||||
return;
|
||||
const uint64_t id = identity(texture);
|
||||
if (!s.written.insert(id).second)
|
||||
return;
|
||||
|
||||
char name[32];
|
||||
std::snprintf(name, sizeof(name), "%016llx", static_cast<unsigned long long>(id));
|
||||
const std::filesystem::path path = s.folder / (std::string(name) + ".png");
|
||||
std::error_code ec;
|
||||
if (std::filesystem::exists(path, ec)) // an earlier run's (its index line is there too)
|
||||
return;
|
||||
|
||||
std::vector<uint8_t> rgba(texture.rgba.size() * 4u);
|
||||
uint32_t maxAlpha = 0;
|
||||
for (size_t i = 0; i < texture.rgba.size(); ++i)
|
||||
{
|
||||
const uint32_t c = texture.rgba[i], alpha = c >> 24;
|
||||
maxAlpha = std::max(maxAlpha, alpha);
|
||||
rgba[i * 4u + 0u] = static_cast<uint8_t>(c);
|
||||
rgba[i * 4u + 1u] = static_cast<uint8_t>(c >> 8);
|
||||
rgba[i * 4u + 2u] = static_cast<uint8_t>(c >> 16);
|
||||
rgba[i * 4u + 3u] = static_cast<uint8_t>(alpha); // GS alpha as is: lossless, 128 = opaque
|
||||
}
|
||||
if (!writePng(path, rgba, texture.width, texture.height))
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:texdump] cannot write %s\n", path.u8string().c_str());
|
||||
return;
|
||||
}
|
||||
std::ofstream index(s.folder / "index.tsv", std::ios::binary | std::ios::app);
|
||||
char line[512];
|
||||
std::snprintf(line, sizeof(line), "%s\t%u\t%u\t%#x\t%s\t%s\t%#llx\t%#llx\t%016llx\t%u\n", name, texture.width, texture.height,
|
||||
source.psm, source.texels.empty() ? "?" : source.texels.c_str(), source.palette.empty() ? "-" : source.palette.c_str(),
|
||||
static_cast<unsigned long long>(source.tex0), static_cast<unsigned long long>(source.texa),
|
||||
static_cast<unsigned long long>(source.texelHash), maxAlpha);
|
||||
index << line;
|
||||
++s.files;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// The texture dump for replacement packs (docs/TEXTURE_UPSCALING.md): with TMB_TEXTURE_DUMP set, every texture the
|
||||
// native renderer is given is written once as a PNG (its GS alpha as is) named by its identity, with a line in index.tsv saying where it
|
||||
// came from. Off by default; nothing changes in what the game or the renderer sees.
|
||||
#pragma once
|
||||
|
||||
#include "bozo/render/texture.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace tmb::textures::dump
|
||||
{
|
||||
// Where a decoded texture came from, for the index (the pack record it was decoded from, its palette's).
|
||||
struct Source
|
||||
{
|
||||
std::string texels; // "JUNKYARD.TEX#12", "SHELL.RTX#3", "FONT#0" ("" unknown)
|
||||
std::string palette; // the palette record's, "" for a direct-colour texture
|
||||
uint32_t psm = 0;
|
||||
uint64_t tex0 = 0, texa = 0;
|
||||
uint64_t texelHash = 0; // XXH64 of the record's texels (its psm, width and height as the seed)
|
||||
};
|
||||
|
||||
// TMB_TEXTURE_DUMP: unset, empty or "0" off; "1" into $PS2X_USER_DIR/texture_dump (the current folder's
|
||||
// texture_dump without PS2X_USER_DIR); anything else is the folder itself.
|
||||
bool enabled();
|
||||
|
||||
// The texture's identity: XXH64 of its RGBA texels seeded with XXH64 of {width, height}, the value
|
||||
// bozo::render::Renderer's draw-list hash gives the same texture.
|
||||
uint64_t identity(const bozo::render::Texture &texture);
|
||||
|
||||
// Writes the texture (once per identity and run; an existing file is kept) and its index line.
|
||||
void note(const bozo::render::Texture &texture, const Source &source);
|
||||
}
|
||||
+703
-544
File diff suppressed because it is too large.
Load diff
@@ -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(©, 29, (getRegU32(ctx, 29) - 0x200u) & ~0xFu);
|
||||
copy.leaving = 0;
|
||||
copy.pc = kViewTweakSetFov;
|
||||
viewTweakSetFov__Fv_0x1fdea0(rdram, ©, 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, ©, 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);
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+221
-7
@@ -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
|
||||
@@ -18,7 +21,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 +126,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:
|
||||
@@ -186,5 +289,116 @@ 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']
|
||||
self.assertEqual(prepare['program'], ['kit/python/python.exe'])
|
||||
self.assertIn('kit/python/python.exe', REQUIRED)
|
||||
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'])
|
||||
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()
|
||||
+57
-7
@@ -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]
|
||||
@@ -20,11 +20,14 @@ The kit (tmb_build uses it when it sits in <TMB_Recomp>/kit or next to the TMB_R
|
||||
deps/ <name>-src: the FetchContent sources BozoEngine's CMake files pin (the same release archives, the same
|
||||
SHA-256), unpacked: sdl3-src (SDL 3.4.20) and imgui-src (Dear ImGui v1.92.7-docking, b1bcb12a)
|
||||
python/ the Windows embeddable Python (python.org, pinned, SHA-256 checked)
|
||||
realesrgan/ Real-ESRGAN's ncnn-vulkan program, its OpenMP runtime and the realesrgan-x4plus model (the upstream
|
||||
release zip, pinned, SHA-256 checked): the launcher's optional "Enhance textures" step upscales the
|
||||
player's own textures with it on their PC (tools/tmb_texture_enhance.py; nothing of the game ships)
|
||||
sources/ the FFmpeg tarball the kit's FFmpeg is built from (LGPL: its corresponding source)
|
||||
licenses/ each package's license files (licenses/deps/<name>: SDL3's zlib licence, ImGui's MIT)
|
||||
kit_manifest.json versions, sources, hashes, licenses, sizes
|
||||
|
||||
Steps (--only <step> runs one): toolchain, python, deps, ffmpeg, manifest; then --zip.
|
||||
Steps (--only <step> runs one): toolchain, python, deps, ffmpeg, realesrgan, manifest; then --zip.
|
||||
|
||||
The toolchain's MSYS2 packages are pinned in tools/build_kit_packages.json (committed): the packages the kit is made of
|
||||
and every package they depend on, each with its exact version, its file on repo.msys2.org and that file's SHA-256. The
|
||||
@@ -55,7 +58,7 @@ ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
sys.path.insert(0, os.path.join(ROOT, 'tools'))
|
||||
from tmb_build import pe_imports, cmake_rc_flags # noqa: E402
|
||||
|
||||
KIT_VERSION = 2 # 2: BozoEngine (SDL3 and ImGui sources, no prebuilt recompilers, no swscale)
|
||||
KIT_VERSION = 3 # 2: BozoEngine (SDL3 and ImGui sources, no prebuilt recompilers, no swscale); 3: + realesrgan/
|
||||
|
||||
# ---- pinned downloads (official upstream; a mirror of ours only as a fallback, held to the same SHA-256) ----
|
||||
FFMPEG = {
|
||||
@@ -75,6 +78,26 @@ PYTHON = {
|
||||
'sha256': '90905e64a840557d8c1bc4f5b74db3d7ee85e3ffb217611cac1c7813acea4159',
|
||||
'license': 'PSF-2.0',
|
||||
}
|
||||
# Real-ESRGAN (xinntao/Real-ESRGAN): the ncnn-vulkan build of its release v0.2.5.0, of which the kit keeps the program,
|
||||
# vcomp140.dll (Microsoft's OpenMP runtime it loads, Visual C++ redistributable) and the realesrgan-x4plus model. The zip
|
||||
# carries no licence file: the licences come from the upstream repositories at pinned commits.
|
||||
REALESRGAN = {
|
||||
'version': 'v0.2.5.0 (realesrgan-ncnn-vulkan 20220424)',
|
||||
'url': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip',
|
||||
'sha256': 'abc02804e17982a3be33675e4d471e91ea374e65b70167abc09e31acb412802d',
|
||||
'keep': ['realesrgan-ncnn-vulkan.exe', 'vcomp140.dll', 'models/realesrgan-x4plus.bin', 'models/realesrgan-x4plus.param'],
|
||||
'license': 'MIT (realesrgan-ncnn-vulkan) and BSD-3-Clause (Real-ESRGAN, its model; ncnn); vcomp140.dll: Microsoft '
|
||||
'Visual C++ redistributable',
|
||||
'licenses': [
|
||||
{'file': 'Real-ESRGAN-ncnn-vulkan-LICENSE',
|
||||
'url': 'https://raw.githubusercontent.com/xinntao/Real-ESRGAN-ncnn-vulkan/37026f49824c5cf84062e7c6a5dd71445dcf610f/LICENSE',
|
||||
'sha256': '5abb941454de437b0e90d78dcb72e3688f74e14bcd4e24393273cb5cd0e9c937'},
|
||||
{'file': 'Real-ESRGAN-LICENSE', 'url': 'https://raw.githubusercontent.com/xinntao/Real-ESRGAN/v0.2.5.0/LICENSE',
|
||||
'sha256': '4a699ec4863d96a91fc265948a0c90033f7e8735d515524dcf3444736406e0c2'},
|
||||
{'file': 'ncnn-LICENSE.txt', 'url': 'https://raw.githubusercontent.com/Tencent/ncnn/20220420/LICENSE.txt',
|
||||
'sha256': '6495f972a09ad7f64ccd953e79adba91a93d862edc7135e6d95210bbf4002a01'},
|
||||
],
|
||||
}
|
||||
# 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 = [
|
||||
@@ -240,7 +263,7 @@ def run(cmd, cwd=None, env=None, logfile=None):
|
||||
|
||||
def download(spec, downloads):
|
||||
os.makedirs(downloads, exist_ok=True)
|
||||
path = os.path.join(downloads, spec['url'].rsplit('/', 1)[1])
|
||||
path = os.path.join(downloads, spec.get('file') or spec['url'].rsplit('/', 1)[1])
|
||||
if not (os.path.isfile(path) and sha256_file(path) == spec['sha256']):
|
||||
# A few tries, further apart each time: an upstream site sometimes drops or times out a CI runner's connection
|
||||
# (GitHub's release runs start with an empty download cache: a tag's run cannot read another tag's cache).
|
||||
@@ -606,6 +629,30 @@ class Kit:
|
||||
self.part('python', dict(PYTHON, file=os.path.basename(z)))
|
||||
log(' python %s' % out.strip())
|
||||
|
||||
# -- realesrgan
|
||||
|
||||
def step_realesrgan(self):
|
||||
z = download(REALESRGAN, 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']:
|
||||
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)
|
||||
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'])
|
||||
|
||||
# -- deps
|
||||
|
||||
def step_deps(self):
|
||||
@@ -721,9 +768,9 @@ class Kit:
|
||||
# -- manifest
|
||||
|
||||
def step_manifest(self):
|
||||
parts = {n: self.part(n) for n in ('toolchain', 'python', 'deps', 'ffmpeg')}
|
||||
parts = {n: self.part(n) for n in ('toolchain', 'python', 'deps', 'ffmpeg', 'realesrgan')}
|
||||
sizes = {}
|
||||
for d in ('ucrt64', 'ffmpeg', 'deps', 'python', 'sources', 'licenses'):
|
||||
for d in ('ucrt64', 'ffmpeg', 'deps', 'python', 'realesrgan', 'sources', 'licenses'):
|
||||
sizes[d] = dir_size(os.path.join(self.out, d))[0]
|
||||
manifest = {
|
||||
'kit': 'TMB_Recomp build kit', 'kit_version': KIT_VERSION, 'engine': 'BozoEngine',
|
||||
@@ -734,9 +781,11 @@ class Kit:
|
||||
'ffmpeg': 'static FFmpeg: avcodec (mpeg2video decoder, mpegvideo parser), avutil',
|
||||
'deps': '<name>-src FetchContent sources: sdl3 (SDL 3.4.20), imgui (Dear ImGui b1bcb12a)',
|
||||
'python': 'Windows embeddable Python',
|
||||
'realesrgan': 'Real-ESRGAN ncnn-vulkan and its realesrgan-x4plus model (the optional texture step)',
|
||||
'sources': 'FFmpeg source tarball',
|
||||
'licenses': 'license files per component'},
|
||||
'toolchain': parts['toolchain'], 'ffmpeg': parts['ffmpeg'], 'python': parts['python'],
|
||||
'realesrgan': parts['realesrgan'],
|
||||
'deps': parts['deps'], 'bytes': sizes, 'total_bytes': sum(sizes.values()),
|
||||
'licenses': {
|
||||
'gcc': 'GPL-3.0-or-later; the runtime libraries it links into a program (libgcc, libstdc++, '
|
||||
@@ -749,6 +798,7 @@ class Kit:
|
||||
'ffmpeg': 'LGPL-2.1-or-later, configured without --enable-gpl / --enable-version3 / '
|
||||
'--enable-nonfree; its source in sources/',
|
||||
'python': 'PSF-2.0',
|
||||
'realesrgan': REALESRGAN['license'],
|
||||
'deps': {d['name']: d['license'] for d in DEPS},
|
||||
'gpl_source_note': 'GCC, binutils and the other MSYS2 binaries are redistributed unmodified: their '
|
||||
'corresponding sources are the MSYS2 source packages of the versions listed in '
|
||||
@@ -1085,7 +1135,7 @@ def write_pc(path, lib, version, mk):
|
||||
% (lib, lib, version, lib, private))
|
||||
|
||||
|
||||
STEPS = ['toolchain', 'python', 'deps', 'ffmpeg', 'manifest']
|
||||
STEPS = ['toolchain', 'python', 'deps', 'ffmpeg', 'realesrgan', 'manifest']
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+35
-31
@@ -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.
|
||||
@@ -60,14 +62,14 @@ 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'
|
||||
# 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).
|
||||
@@ -248,8 +250,9 @@ def audit_tree(folder, allow_pe=False, rel_prefix=''):
|
||||
|
||||
|
||||
def allowed_extension(rel):
|
||||
"""Files of the toolchain or the libraries that share an extension with the game's (none so far but these)."""
|
||||
return rel.startswith(('kit/ucrt64/', 'kit/deps/', 'kit/python/', 'kit/ffmpeg/', 'kit/sources/')) and \
|
||||
"""Files of the toolchain or the libraries that share an extension with the game's (Real-ESRGAN's model: .bin)."""
|
||||
return rel.startswith(('kit/ucrt64/', 'kit/deps/', 'kit/python/', 'kit/ffmpeg/', 'kit/sources/',
|
||||
'kit/realesrgan/')) and \
|
||||
not rel.lower().endswith(('.elf', '.irx', '.iso', '.pack', '.pss', '.vag', '.cue'))
|
||||
|
||||
|
||||
@@ -374,7 +377,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)
|
||||
|
||||
@@ -395,21 +398,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('\\', '/')
|
||||
@@ -418,14 +416,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
|
||||
@@ -638,7 +636,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:',
|
||||
@@ -774,6 +772,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
|
||||
|
||||
@@ -851,7 +853,7 @@ class Release:
|
||||
'Subsequent BozoEngine updates use `-bozo.zip` with either installation folder name.',
|
||||
'',
|
||||
'## 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']),
|
||||
@@ -999,7 +1001,7 @@ def verify_zip(path, top=TOP):
|
||||
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'):
|
||||
@@ -1162,6 +1164,8 @@ Version {version}
|
||||
|
||||
|
||||
def main():
|
||||
for stream in (sys.stdout, sys.stderr): # the changelog's text, whatever the console's code page (cp1252 on CI)
|
||||
stream.reconfigure(encoding='utf-8', errors='replace')
|
||||
ap = argparse.ArgumentParser(description='Makes the TMB_Recomp release zip (see the docstring).')
|
||||
ap.add_argument('--version', help='MAJOR.MINOR.PATCH[-pre] (default: the commit\'s tag, v stripped)')
|
||||
ap.add_argument('--commit', help='the commit to release (default HEAD); only committed files count')
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
1292:CROSS/18,2127:DOWN/11,2305:CROSS/9,2622:CROSS/15,2801:DOWN/9,2860:DOWN/9,2920:DOWN/9,2979:DOWN/9,3098:CROSS/9,3400:CROSS/9,3728:CROSS/9,4027:CROSS/4,4481:RIGHT/7,4671:CROSS/18,5403:CROSS/1000000,5599:LEFT/36,5700:RIGHT/45,5771:CIRCLE/9,5771:L1/9,5771:R1/9,5813:R1/9,5825:LEFT/27,5855:R1/9,5872:L1/9,5896:R1/9,5938:R1/9,5944:CIRCLE/9,5974:L1/9,5974:RIGHT/35,5980:R1/9,6021:R1/9,6051:LEFT/44,6063:R1/9,6075:L1/9,6104:R1/9,6116:CIRCLE/9,6146:R1/9,6152:RIGHT/26,6175:L1/9,6187:R1/9,6229:R1/8,6270:R1/9,6276:L1/9,6276:LEFT/36,6288:CIRCLE/9,6312:R1/9,6354:R1/8,6377:L1/9,6395:R1/9,6425:RIGHT/44,6437:R1/9,6461:CIRCLE/8,6478:L1/9,6478:R1/9,6502:LEFT/27,6520:R1/9,6561:R1/9,6579:L1/9,6603:R1/9,6603:RIGHT/36,6633:CIRCLE/9,6645:R1/9,6680:L1/9,6686:R1/9,6728:LEFT/44,6728:R1/9,6769:R1/9,6781:L1/9,6805:CIRCLE/9,6811:R1/9,6853:R1/9,6876:RIGHT/27,6882:L1/9,6894:R1/9,6936:R1/8,6953:LEFT/36,6977:CIRCLE/9,6977:R1/9,6983:L1/9,7019:R1/9,7054:RIGHT/44,7060:R1/9,7084:L1/9,7101:R1/9,7143:R1/9,7149:CIRCLE/9,7178:LEFT/27,7184:L1/9,7184:R1/9,7226:R1/9,7267:R1/9,7285:L1/9,7309:R1/9,7321:CIRCLE/9,7327:RIGHT/35,7351:R1/8,7386:L1/9,7392:R1/9,7404:LEFT/45,7434:R1/9,7475:R1/9,7487:L1/9,7493:CIRCLE/9,7505:RIGHT/27,7517:R1/9,7558:R1/9,7588:L1/9,7600:R1/8,7629:LEFT/36,7641:R1/9,7665:CIRCLE/9,7683:R1/9,7689:L1/9,7724:R1/9,7766:R1/9,7778:RIGHT/44,7790:L1/9,7808:R1/8,7837:CIRCLE/9,7849:R1/9,7855:LEFT/27,7891:L1/9,7891:R1/9,7932:R1/9,7956:RIGHT/36,7974:R1/9,7992:L1/9,8010:CIRCLE/9,8016:R1/8,8057:R1/9,8081:LEFT/44,8092:L1/9,8098:R1/9,8140:R1/9,8182:CIRCLE/8,8182:R1/8,8193:L1/9,8223:R1/9,8229:RIGHT/27,8265:R1/9,8295:L1/8,8306:LEFT/36,8306:R1/9,8348:R1/9,8354:CIRCLE/9,8390:R1/8,8396:L1/8,8407:RIGHT/45,8431:R1/9,8473:R1/8,8496:L1/9,8514:R1/9,8526:CIRCLE/9,8532:LEFT/27,8555:R1/10,8597:L1/9,8597:R1/9,8639:R1/9,8680:R1/9,8680:RIGHT/36,8698:CIRCLE/9,8698:L1/9,8722:R1/9,8758:LEFT/44,8764:R1/9,8799:L1/9,8805:R1/9,8847:R1/9,8859:RIGHT/27,8871:CIRCLE/9,8888:R1/9,8900:L1/9,8930:R1/9,8972:R1/9,8984:LEFT/35,9001:L1/9,9013:R1/9,9043:CIRCLE/9,9055:R1/9,9097:R1/8,9102:L1/9,9132:RIGHT/45,9138:R1/9,9180:R1/9,9204:L1/8,9210:LEFT/26,9215:CIRCLE/9,9221:R1/9,9263:R1/9,9304:L1/9,9304:R1/9,9310:RIGHT/36,9346:R1/9,9387:CIRCLE/9,9387:R1/9,9405:L1/9,9429:R1/9,9435:LEFT/44,9470:R1/9,9506:L1/9,9512:R1/9,9553:R1/9,9559:CIRCLE/9,9583:RIGHT/27,9595:R1/9,9607:L1/9,9637:R1/9,9661:LEFT/35,9678:R1/9,9708:L1/9,9720:R1/9,9732:CIRCLE/9,9761:R1/9,9761:RIGHT/45,9803:R1/9,9809:L1/9,9844:R1/9,9886:LEFT/27,9886:R1/9,9904:CIRCLE/9,9910:L1/9,9927:R1/9,9969:R1/9,10011:L1/9,10011:R1/9,10035:RIGHT/35,10052:R1/9,10076:CIRCLE/9,10094:R1/9,10112:L1/8,10112:LEFT/44,10135:R1/9,10177:R1/9,10212:L1/9,10212:RIGHT/27,10218:R1/9,10248:CIRCLE/9,10259:R1/9,10301:R1/9,10313:L1/9,10336:LEFT/36,10342:R1/9,10384:R1/9,10413:L1/9,10419:CIRCLE/9,10425:R1/9,10467:R1/9,10485:RIGHT/44,10508:R1/9,10514:L1/9,10550:R1/9,10562:LEFT/26,10591:CIRCLE/9,10591:R1/9,10615:L1/9,10632:R1/9,10662:RIGHT/35,10674:R1/9,10715:L1/9,10715:R1/9,10757:R1/9,10763:CIRCLE/9,10787:LEFT/44,10798:R1/9,10816:L1/9,10840:R1/9,10881:R1/9,10917:L1/9,10923:R1/9,10935:CIRCLE/9,10935:RIGHT/27,10964:R1/9,11006:R1/9,11012:LEFT/36,11018:L1/9,11048:R1/8,11089:R1/9,11106:CIRCLE/9,11112:RIGHT/45,11118:L1/9,11130:R1/9,11172:R1/9,11213:R1/9,11219:L1/9,11237:LEFT/27,11255:R1/9,11279:CIRCLE/9,11296:R1/9,11320:L1/9,11338:R1/9,11380:R1/9,11386:RIGHT/35,11421:L1/9,11421:R1/9,11451:CIRCLE/9,11463:LEFT/45,11463:R1/9,11505:R1/9,11523:L1/8,11546:R1/9,11564:RIGHT/27,11588:R1/9,11623:CIRCLE/9,11623:L1/9,11629:R1/9,11671:R1/8,11688:LEFT/36,11712:R1/9,11724:L1/9,11754:R1/8,11795:CIRCLE/9,11795:R1/9,11825:L1/8,11836:R1/9,11836:RIGHT/45,11878:R1/9,11913:LEFT/27,11919:R1/9,11925:L1/9,11961:R1/9,11967:CIRCLE/8,12002:R1/9,12014:RIGHT/35,12026:L1/9,12044:R1/8,12085:R1/9,12126:L1/9,12126:R1/9,12138:CIRCLE/9,12138:LEFT/44,12168:R1/8,12209:R1/9,12227:L1/9,12251:R1/8,12286:RIGHT/27,12292:R1/9,12310:CIRCLE/9,12328:L1/9,12334:R1/9,12363:LEFT/36,12375:R1/9,12417:R1/9,12429:L1/9,12458:R1/9,12464:RIGHT/45,12482:CIRCLE/9,12500:R1/9,12530:L1/9,12541:R1/9,12583:R1/9,12589:LEFT/27,12624:R1/9,12630:L1/9,12654:CIRCLE/9,12666:R1/8,12707:R1/9,12731:L1/8,12736:RIGHT/36,12748:R1/9,12789:R1/9,12813:LEFT/45,12825:CIRCLE/9,12831:L1/9,12831:R1/9,12872:R1/9,12914:R1/9,12914:RIGHT/27,12932:L1/9,12955:R1/9,12997:CIRCLE/9,12997:R1/9,13032:L1/9,13038:LEFT/36,13038:R1/9,13080:R1/9,13122:R1/9,13134:L1/9,13163:R1/9,13169:CIRCLE/9,13187:RIGHT/44,13205:R1/9,13234:L1/9,13246:R1/9,13264:LEFT/27,13288:R1/9,13329:R1/9,13335:L1/9,13341:CIRCLE/9,13365:RIGHT/35,13370:R1/9,13411:R1/9,13435:L1/9,13453:R1/9,13488:LEFT/44,13494:R1/9,13512:CIRCLE/9,13535:L1/9,13535:R1/9,13577:R1/9,13618:R1/9,13636:L1/9,13636:RIGHT/26,13660:R1/8,13683:CIRCLE/9,13701:R1/9,13713:LEFT/35,13736:L1/9,13742:R1/9,13783:R1/9,13813:RIGHT/44,13825:R1/9,13836:L1/9,13854:CIRCLE/9,13866:R1/9,13907:R1/9,13937:L1/9,13937:LEFT/27,13949:R1/9,13990:R1/9,14026:CIRCLE/9,14032:R1/8,14038:L1/8,14073:R1/9,14085:RIGHT/35,14114:R1/9,14138:L1/9,14156:R1/9,14162:LEFT/4Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
3498:CROSS/15,5445:CROSS/312,5658:RIGHT/45,5741:CROSS/312,5782:LEFT/27,5824:CIRCLE/9,5824:L1/9,5824:R1/9,5872:R1/9,5920:R1/9,5926:L1/9,5932:RIGHT/36,5967:R1/9,5997:CIRCLE/9,6009:LEFT/45,6015:R1/9,6027:L1/9,6039:CROSS/312,6062:R1/9,6110:R1/9,6110:RIGHT/27,6127:L1/9,6157:R1/9,6169:CIRCLE/9,6204:R1/9,6228:L1/9,6234:LEFT/36,6252:R1/9,6299:R1/9,6329:L1/9,6335:CROSS/312,6341:CIRCLE/9,6347:R1/9,6383:RIGHT/45,6394:R1/9,6430:L1/9,6442:R1/9,6460:LEFT/27,6489:R1/9,6513:CIRCLE/9,6531:L1/9,6537:R1/9,6561:RIGHT/36,6585:R1/9,6632:CROSS/312,6632:L1/9,6632:R1/9,6680:R1/9,6686:CIRCLE/9,6686:LEFT/45,6727:R1/9,6733:L1/9,6775:R1/9,6822:R1/9,6834:L1/9,6834:RIGHT/27,6858:CIRCLE/9,6870:R1/9,6911:LEFT/36,6917:R1/9,6929:CROSS/312,6935:L1/9,6965:R1/9,7012:R1/9,7012:RIGHT/45,7030:CIRCLE/9,7036:L1/9,7060:R1/9,7107:R1/9,7137:L1/9,7137:LEFT/27,7154:R1/9,7202:CIRCLE/9,7202:R1/9,7225:CROSS/312,7237:L1/9,7249:R1/9,7284:RIGHT/36,7296:R1/9,7338:L1/9,7344:R1/9,7362:LEFT/45,7374:CIRCLE/9,7392:R1/9,7439:L1/9,7439:R1/9,7463:RIGHT/27,7487:R1/9,7522:CROSS/312,7534:R1/9,7540:L1/9,7546:CIRCLE/9,7582:R1/9,7587:LEFT/36,7629:R1/9,7640:L1/9,7676:R1/9,7718:CIRCLE/9,7724:R1/9,7736:RIGHT/45,7742:L1/9,7771:R1/9,7813:LEFT/27,7819:CROSS/312,7819:R1/9,7843:L1/9,7866:R1/9,7890:CIRCLE/9,7914:R1/9,7914:RIGHT/36,7944:L1/9,7962:R1/9,8009:R1/9,8039:LEFT/45,8045:L1/9,8056:R1/9,8062:CIRCLE/9,8104:R1/9,8116:CROSS/312,8145:L1/9,8151:R1/9,8187:RIGHT/27,8199:R1/9,8234:CIRCLE/9,8246:L1/9,8246:R1/9,8264:LEFT/36,8294:R1/9,8341:R1/9,8347:L1/9,8365:RIGHT/45,8389:R1/9,8407:CIRCLE/9,8413:CROSS/312,8436:R1/9,8448:L1/9,8484:R1/9,8490:LEFT/27,8531:R1/9,8549:L1/9,8579:CIRCLE/9,8579:R1/9,8627:R1/9,8638:RIGHT/36,8650:L1/9,8674:R1/9,8710:CROSS/312,8715:LEFT/45,8721:R1/9,8751:CIRCLE/9,8751:L1/9,8769:R1/9,8816:R1/9,8816:RIGHT/27,8852:L1/9,8864:R1/9,8912:R1/9,8924:CIRCLE/9,8941:LEFT/36,8953:L1/9,8959:R1/9,9007:CROSS/312,9007:R1/9,9054:L1/9,9054:R1/9,9090:RIGHT/45,9096:CIRCLE/9,9102:R1/9,9149:R1/9,9155:L1/9,9167:LEFT/27,9197:R1/9,9244:R1/9,9256:L1/9,9268:CIRCLE/9,9268:RIGHT/36,9292:R1/9,9303:CROSS/312,9339:R1/9,9357:L1/9,9387:R1/9,9393:LEFT/45,9434:R1/9,9440:CIRCLE/9,9458:L1/9,9481:R1/9,9529:R1/9,9541:RIGHT/27,9559:L1/9,9577:R1/9,9600:CROSS/312,9612:CIRCLE/9,9618:LEFT/36,9624:R1/9,9660:L1/9,9672:R1/9,9719:R1/9,9719:RIGHT/45,9761:L1/9,9767:R1/9,9785:CIRCLE/9,9814:R1/9,9844:LEFT/27,9861:L1/9,9861:R1/9,9897:CROSS/312,9909:R1/9,9957:CIRCLE/9,9957:R1/9,9963:L1/9,9992:RIGHT/36,10004:R1/9,10052:R1/9,10063:L1/9,10069:LEFT/45,10099:R1/9,10129:CIRCLE/9,10146:R1/9,10164:L1/9,10170:RIGHT/27,10194:CROSS/312,10194:R1/9,10241:R1/9,10265:L1/9,10289:R1/9,10295:LEFT/36,10300:CIRCLE/9,10336:R1/9,10366:L1/9,10383:R1/9,10430:R1/9,10442:RIGHT/45,10466:L1/9,10472:CIRCLE/9,10478:R1/9,10490:CROSS/312,10519:LEFT/27,10525:R1/9,10567:L1/9,10573:R1/9,10620:R1/9,10620:RIGHT/36,10644:CIRCLE/9,10667:L1/9,10667:R1/9,10715:R1/9,10745:LEFT/45,10762:R1/9,10768:L1/9,10786:CROSS/312,10810:R1/9,10815:CIRCLE/9,10857:R1/9,10869:L1/9,10893:RIGHT/27,10905:R1/9,10952:R1/9,10970:L1/9,10970:LEFT/36,10988:CIRCLE/9,11000:R1/9,11047:R1/9,11071:L1/9,11071:RIGHT/45,11083:CROSS/312,11094:R1/9,11141:R1/9,11159:CIRCLE/9,11171:L1/9,11189:R1/9,11195:LEFT/27,11236:R1/9,11272:L1/9,11284:R1/9,11332:CIRCLE/9,11332:R1/9,11343:RIGHT/36,11373:L1/9,11379:CROSS/312,11379:R1/9,11421:LEFT/45,11427:R1/9,11474:L1/9,11474:R1/9,11504:CIRCLE/9,11522:R1/9,11522:RIGHT/27,11569:R1/9,11575:L1/9,11616:R1/9,11646:LEFT/36,11664:R1/9,11676:CIRCLE/9,11676:CROSS/312,11676:L1/9,11711:R1/9,11759:R1/9,11777:L1/9,11794:RIGHT/45,11806:R1/9,11847:CIRCLE/9,11853:R1/9,11871:LEFT/27,11877:L1/9,11901:R1/9,11948:R1/9,11972:CROSS/312,11972:RIGHT/36,11978:L1/9,11996:R1/9,12019:CIRCLE/9,12043:R1/9,12079:L1/9,12090:R1/9,12096:LEFT/45,12137:R1/9,12179:L1/9,12185:R1/9,12191:CIRCLE/9,12232:R1/9,12244:RIGHT/27,12268:CROSS/312,12280:L1/9,12280:R1/9,12321:LEFT/36,12327:R1/9,12363:CIRCLE/9,12374:R1/9,12380:L1/9,12422:R1/9,12422:RIGHT/45,12470:R1/9,12481:L1/9,12517:R1/9,12535:CIRCLE/9,12547:LEFT/27,12565:CROSS/312,12565:R1/9,12582:L1/9,12612:R1/9,12659:R1/9,12683:L1/9,12695:RIGHT/36,12706:CIRCLE/9,12706:R1/9,12753:R1/9,12771:LEFT/45,12783:L1/9,12801:R1/9,12848:R1/9,12860:CROSS/312,12872:RIGHT/27,12878:CIRCLE/9,12883:L1/9,12895:R1/9,12943:R1/9,12985:L1/9,12991:R1/9,12996:LEFT/36,13038:R1/9,13050:CIRCLE/9,13085:L1/9,13085:R1/9,13133:R1/9,13145:RIGHT/45,13157:CROSS/312,13180:R1/9,13186:L1/9,13222:CIRCLE/9,13222:LEFT/27,13228:R1/9,13275:R1/9,13287:L1/9,13322:R1/9,13322:RIGHT/36,13370:R1/9,13388:L1/9,13393:CIRCLE/9,13417:R1/9,13446:LEFT/45,13452:CROSS/312,13464:R1/9,13488:L1/9,13511:R1/9,13559:R1/9,13565:CIRCLE/9,13588:L1/9,13594:RIGHT/27,13606:R1/9,13653:R1/9,13671:LEFT/36,13688:L1/9,13700:R1/9,13736:CIRCLE/9,13747:CROSS/312,13747:R1/9,13771:RIGHT/45,13789:L1/9,13794:R1/9,13842:R1/9,13889:L1/9,13889:R1/9,13895:LEFT/27,13907:CIRCLE/9,13936:R1/9,13984:R1/9,13990:L1/9,14031:R1/9,14043:CROSS/312,14043:RIGHT/36,14078:CIRCLE/9,14078:R1/9,14090:L1/9,14120:LEFT/45,14125:R1/9,14173:R1/9,14190:L1/9,14220:RLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
3727:CROSS/15,5486:CROSS/312,5717:LEFT/27,5782:CROSS/312,5866:RIGHT/36,5878:CIRCLE/9,5878:L1/9,5878:R1/9,5932:R1/9,5943:LEFT/45,5979:L1/9,5985:R1/9,6039:R1/9,6045:RIGHT/27,6050:CIRCLE/9,6080:CROSS/312,6080:L1/9,6092:R1/9,6145:R1/9,6169:LEFT/36,6181:L1/9,6198:R1/9,6222:CIRCLE/9,6252:R1/9,6281:L1/9,6305:R1/9,6317:RIGHT/45,6359:R1/9,6377:CROSS/312,6383:L1/9,6394:CIRCLE/9,6394:LEFT/27,6412:R1/9,6466:R1/9,6484:L1/9,6495:RIGHT/36,6519:R1/9,6567:CIRCLE/9,6573:R1/9,6585:L1/9,6620:LEFT/45,6626:R1/9,6674:CROSS/312,6680:R1/9,6686:L1/9,6733:R1/9,6739:CIRCLE/9,6769:RIGHT/27,6787:L1/9,6787:R1/9,6840:R1/9,6846:LEFT/36,6888:L1/9,6893:R1/9,6911:CIRCLE/9,6947:R1/9,6947:RIGHT/45,6971:CROSS/312,6988:L1/9,7000:R1/9,7054:R1/9,7071:LEFT/27,7083:CIRCLE/9,7089:L1/9,7107:R1/9,7160:R1/9,7190:L1/9,7213:R1/9,7219:RIGHT/36,7255:CIRCLE/9,7267:CROSS/312,7267:R1/9,7290:L1/9,7296:LEFT/45,7320:R1/9,7374:R1/9,7392:L1/9,7397:RIGHT/27,7427:CIRCLE/9,7427:R1/9,7481:R1/9,7493:L1/9,7522:LEFT/36,7534:R1/9,7564:CROSS/312,7587:R1/9,7593:L1/9,7599:CIRCLE/9,7640:R1/9,7670:RIGHT/45,7694:L1/9,7694:R1/9,7748:LEFT/27,7748:R1/9,7771:CIRCLE/9,7795:L1/9,7801:R1/9,7848:RIGHT/36,7854:R1/9,7860:CROSS/312,7896:L1/9,7908:R1/9,7944:CIRCLE/9,7962:R1/9,7973:LEFT/45,7997:L1/9,8015:R1/9,8068:R1/9,8098:L1/9,8116:CIRCLE/9,8122:R1/9,8122:RIGHT/27,8157:CROSS/312,8175:R1/9,8199:L1/9,8199:LEFT/36,8228:R1/9,8282:R1/9,8288:CIRCLE/9,8300:L1/9,8300:RIGHT/45,8336:R1/9,8389:R1/9,8401:L1/9,8425:LEFT/27,8442:R1/9,8454:CROSS/312,8460:CIRCLE/9,8495:R1/9,8501:L1/9,8549:R1/9,8573:RIGHT/36,8603:L1/9,8603:R1/9,8633:CIRCLE/9,8650:LEFT/45,8656:R1/9,8704:L1/9,8710:R1/9,8751:CROSS/312,8751:RIGHT/27,8763:R1/9,8805:CIRCLE/9,8805:L1/9,8816:R1/9,8870:R1/9,8876:LEFT/36,8906:L1/9,8924:R1/9,8977:CIRCLE/9,8977:R1/9,9007:L1/9,9025:RIGHT/45,9031:R1/9,9048:CROSS/312,9084:R1/9,9102:LEFT/27,9108:L1/9,9137:R1/9,9149:CIRCLE/9,9191:R1/9,9203:RIGHT/36,9209:L1/9,9244:R1/9,9298:R1/9,9309:L1/9,9321:CIRCLE/9,9327:LEFT/45,9345:CROSS/312,9351:R1/9,9405:R1/9,9411:L1/9,9458:R1/9,9476:RIGHT/27,9493:CIRCLE/9,9511:L1/9,9511:R1/9,9553:LEFT/36,9565:R1/9,9612:L1/9,9618:R1/9,9642:CROSS/312,9654:RIGHT/45,9666:CIRCLE/9,9672:R1/9,9713:L1/9,9725:R1/9,9779:LEFT/27,9779:R1/9,9814:L1/9,9832:R1/9,9838:CIRCLE/9,9885:R1/9,9915:L1/9,9927:RIGHT/36,9939:CROSS/312,9939:R1/9,9992:R1/9,10004:LEFT/45,10010:CIRCLE/9,10016:L1/9,10046:R1/9,10099:R1/9,10105:RIGHT/27,10117:L1/9,10152:R1/9,10182:CIRCLE/9,10206:R1/9,10217:L1/9,10229:LEFT/36,10235:CROSS/312,10259:R1/9,10312:R1/9,10318:L1/9,10354:CIRCLE/9,10366:R1/9,10377:RIGHT/45,10418:L1/9,10418:R1/9,10454:LEFT/27,10472:R1/9,10519:L1/9,10525:CIRCLE/9,10525:R1/9,10531:CROSS/312,10555:RIGHT/36,10579:R1/9,10620:L1/9,10632:R1/9,10679:LEFT/45,10685:R1/9,10697:CIRCLE/9,10721:L1/9,10739:R1/9,10792:R1/9,10821:L1/9,10827:CROSS/312,10827:RIGHT/27,10845:R1/9,10869:CIRCLE/9,10899:R1/9,10905:LEFT/36,10922:L1/9,10952:R1/9,11005:R1/9,11005:RIGHT/45,11023:L1/9,11041:CIRCLE/9,11059:R1/9,11112:R1/9,11124:CROSS/312,11124:L1/9,11129:LEFT/27,11165:R1/9,11212:CIRCLE/9,11218:R1/9,11224:L1/9,11272:R1/9,11278:RIGHT/36,11326:L1/9,11326:R1/9,11355:LEFT/45,11379:R1/9,11385:CIRCLE/9,11421:CROSS/312,11427:L1/9,11433:R1/9,11457:RIGHT/27,11486:R1/9,11528:L1/9,11540:R1/9,11557:CIRCLE/9,11581:LEFT/36,11593:R1/9,11628:L1/9,11646:R1/9,11700:R1/9,11717:CROSS/312,11729:CIRCLE/9,11729:L1/9,11729:RIGHT/45,11753:R1/9,11806:LEFT/27,11806:R1/9,11830:L1/9,11859:R1/9,11901:CIRCLE/9,11907:RIGHT/36,11913:R1/9,11931:L1/9,11966:R1/9,12013:CROSS/312,12019:R1/9,12031:L1/9,12031:LEFT/45,12073:CIRCLE/9,12073:R1/9,12126:R1/9,12132:L1/9,12179:R1/9,12179:RIGHT/27,12232:L1/9,12232:R1/9,12244:CIRCLE/9,12256:LEFT/36,12286:R1/9,12309:CROSS/312,12333:L1/9,12339:R1/9,12357:RIGHT/45,12392:R1/9,12416:CIRCLE/9,12434:L1/9,12446:R1/9,12481:LEFT/27,12499:R1/9,12535:L1/9,12553:R1/9,12588:CIRCLE/9,12606:CROSS/312,12606:R1/9,12629:RIGHT/36,12635:L1/9,12659:R1/9,12706:LEFT/45,12712:R1/9,12736:L1/9,12759:CIRCLE/9,12765:R1/9,12807:RIGHT/27,12818:R1/9,12836:L1/9,12872:R1/9,12901:CROSS/312,12925:R1/9,12931:CIRCLE/9,12931:LEFT/36,12937:L1/9,12979:R1/9,13032:R1/9,13038:L1/9,13079:RIGHT/45,13085:R1/9,13103:CIRCLE/9,13139:L1/9,13139:R1/9,13157:LEFT/27,13192:R1/9,13198:CROSS/312,13240:L1/9,13246:R1/9,13257:RIGHT/36,13275:CIRCLE/9,13299:R1/9,13340:L1/9,13352:R1/9,13382:LEFT/45,13405:R1/9,13440:L1/9,13446:CIRCLE/9,13458:R1/9,13494:CROSS/312,13511:R1/9,13529:RIGHT/27,13541:L1/9,13565:R1/9,13606:LEFT/36,13618:CIRCLE/9,13618:R1/9,13641:L1/9,13671:R1/9,13706:RIGHT/45,13724:R1/9,13742:L1/9,13777:R1/9,13789:CIRCLE/9,13789:CROSS/312,13830:LEFT/27,13830:R1/9,13842:L1/9,13883:R1/9,13936:R1/9,13942:L1/9,13960:CIRCLE/9,13978:RIGHT/36,13990:R1/9,14043:L1/9,14043:R1/9,14055:LEFT/45,14084:CROSS/312,14096:R1/9,14131:CIRCLE/9,14143:L1/9,14149:R1/9,14155:RIGHT/27,14202:R1/9,14244:L1/9,14256:R1/9,14279:LEFT/36,14303:CIRCLE/9,14309:R1/9,14344:L1/9,14362:R1/9,14380:CROSS/312,14415:R1/9,14427:RIGHT/45,14445:L1/9,14468:R1/9,14474:CIRCLE/9,14504:LEFT/27,14522:R1/9,14546:L1/9,14575:R1/9,14605:RIGHT/36,Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
3923:CROSS/15,5528:CROSS/312,5777:RIGHT/36,5824:CROSS/312,5854:LEFT/45,5932:CIRCLE/9,5932:L1/9,5932:R1/9,5955:RIGHT/27,5991:R1/9,6033:L1/9,6050:R1/9,6080:LEFT/36,6104:CIRCLE/9,6110:R1/9,6121:CROSS/312,6133:L1/9,6169:R1/9,6228:R1/9,6228:RIGHT/45,6234:L1/9,6275:CIRCLE/9,6287:R1/9,6305:LEFT/27,6335:L1/9,6347:R1/9,6406:R1/9,6406:RIGHT/36,6418:CROSS/312,6436:L1/9,6448:CIRCLE/9,6466:R1/9,6525:R1/9,6531:LEFT/45,6537:L1/9,6585:R1/9,6620:CIRCLE/9,6638:L1/9,6644:R1/9,6680:RIGHT/27,6703:R1/9,6715:CROSS/312,6739:L1/9,6757:LEFT/36,6763:R1/9,6793:CIRCLE/9,6822:R1/9,6840:L1/9,6858:RIGHT/45,6882:R1/9,6941:L1/9,6941:R1/9,6965:CIRCLE/9,6982:LEFT/27,7000:R1/9,7012:CROSS/312,7042:L1/9,7060:R1/9,7119:R1/9,7131:RIGHT/36,7137:CIRCLE/9,7142:L1/9,7178:R1/9,7207:LEFT/45,7237:R1/9,7243:L1/9,7296:R1/9,7308:CIRCLE/9,7308:CROSS/312,7308:RIGHT/27,7344:L1/9,7356:R1/9,7415:R1/9,7433:LEFT/36,7445:L1/9,7475:R1/9,7481:CIRCLE/9,7534:R1/9,7546:L1/9,7582:RIGHT/45,7593:R1/9,7605:CROSS/312,7646:L1/9,7652:CIRCLE/9,7652:R1/9,7658:LEFT/27,7712:R1/9,7748:L1/9,7760:RIGHT/36,7771:R1/9,7825:CIRCLE/9,7831:R1/9,7848:L1/9,7884:LEFT/45,7890:R1/9,7902:CROSS/312,7950:L1/9,7950:R1/9,7997:CIRCLE/9,8009:R1/9,8033:RIGHT/27,8051:L1/9,8068:R1/9,8110:LEFT/36,8127:R1/9,8151:L1/9,8169:CIRCLE/9,8187:R1/9,8199:CROSS/312,8211:RIGHT/45,8246:R1/9,8252:L1/9,8306:R1/9,8336:LEFT/27,8341:CIRCLE/9,8353:L1/9,8365:R1/9,8425:R1/9,8454:L1/9,8484:R1/9,8484:RIGHT/36,8495:CROSS/312,8513:CIRCLE/9,8543:R1/9,8555:L1/9,8561:LEFT/45,8603:R1/9,8656:L1/9,8662:R1/9,8662:RIGHT/27,8686:CIRCLE/9,8721:R1/9,8757:L1/9,8781:R1/9,8787:LEFT/36,8793:CROSS/312,8840:R1/9,8858:CIRCLE/9,8858:L1/9,8900:R1/9,8935:RIGHT/45,8959:L1/9,8959:R1/9,9013:LEFT/27,9019:R1/9,9031:CIRCLE/9,9060:L1/9,9078:R1/9,9090:CROSS/312,9114:RIGHT/36,9137:R1/9,9161:L1/9,9197:R1/9,9203:CIRCLE/9,9238:LEFT/45,9256:R1/9,9262:L1/9,9315:R1/9,9363:L1/9,9375:CIRCLE/9,9375:R1/9,9387:CROSS/312,9387:RIGHT/27,9434:R1/9,9464:L1/9,9464:LEFT/36,9493:R1/9,9547:CIRCLE/9,9553:R1/9,9565:L1/9,9565:RIGHT/45,9612:R1/9,9666:L1/9,9672:R1/9,9684:CROSS/312,9689:LEFT/27,9719:CIRCLE/9,9731:R1/9,9767:L1/9,9791:R1/9,9838:RIGHT/36,9850:R1/9,9867:L1/9,9891:CIRCLE/9,9909:R1/9,9915:LEFT/45,9968:L1/9,9968:R1/9,9980:CROSS/312,10016:RIGHT/27,10028:R1/9,10063:CIRCLE/9,10069:L1/9,10087:R1/9,10140:LEFT/36,10146:R1/9,10170:L1/9,10206:R1/9,10235:CIRCLE/9,10265:R1/9,10271:L1/9,10277:CROSS/312,10289:RIGHT/45,10324:R1/9,10366:LEFT/27,10371:L1/9,10383:R1/9,10407:CIRCLE/9,10442:R1/9,10466:RIGHT/36,10472:L1/9,10502:R1/9,10561:R1/9,10573:CROSS/312,10573:L1/9,10579:CIRCLE/9,10590:LEFT/45,10620:R1/9,10673:L1/9,10679:R1/9,10739:R1/9,10739:RIGHT/27,10751:CIRCLE/9,10774:L1/9,10798:R1/9,10815:LEFT/36,10857:R1/9,10869:CROSS/312,10875:L1/9,10916:R1/9,10916:RIGHT/45,10922:CIRCLE/9,10976:L1/9,10976:R1/9,11035:R1/9,11041:LEFT/27,11077:L1/9,11094:CIRCLE/9,11094:R1/9,11153:R1/9,11165:CROSS/312,11177:L1/9,11189:RIGHT/36,11212:R1/9,11266:CIRCLE/9,11266:LEFT/45,11272:R1/9,11278:L1/9,11332:R1/9,11367:RIGHT/27,11379:L1/9,11391:R1/9,11439:CIRCLE/9,11451:R1/9,11462:CROSS/312,11480:L1/9,11492:LEFT/36,11510:R1/9,11569:R1/9,11581:L1/9,11611:CIRCLE/9,11628:R1/9,11640:RIGHT/45,11682:L1/9,11688:R1/9,11717:LEFT/27,11747:R1/9,11759:CROSS/312,11783:CIRCLE/9,11783:L1/9,11806:R1/9,11818:RIGHT/36,11865:R1/9,11883:L1/9,11925:R1/9,11942:LEFT/45,11954:CIRCLE/9,11984:L1/9,11984:R1/9,12043:R1/9,12055:CROSS/312,12084:L1/9,12090:RIGHT/27,12102:R1/9,12126:CIRCLE/9,12161:R1/9,12167:LEFT/36,12185:L1/9,12220:R1/9,12268:RIGHT/45,12280:R1/9,12286:L1/9,12298:CIRCLE/9,12339:R1/9,12351:CROSS/312,12386:L1/9,12392:LEFT/27,12398:R1/9,12458:R1/9,12470:CIRCLE/9,12487:L1/9,12517:R1/9,12541:RIGHT/36,12577:R1/9,12588:L1/9,12618:LEFT/45,12635:R1/9,12641:CIRCLE/9,12647:CROSS/312,12689:L1/9,12695:R1/9,12718:RIGHT/27,12753:R1/9,12789:L1/9,12812:CIRCLE/9,12812:R1/9,12842:LEFT/36,12872:R1/9,12889:L1/9,12931:R1/9,12943:CROSS/312,12985:CIRCLE/9,12991:L1/9,12991:R1/9,12991:RIGHT/45,13050:R1/9,13068:LEFT/27,13091:L1/9,13109:R1/9,13157:CIRCLE/9,13169:R1/9,13169:RIGHT/36,13192:L1/9,13228:R1/9,13240:CROSS/312,13287:R1/9,13293:L1/9,13293:LEFT/45,13328:CIRCLE/9,13346:R1/9,13393:L1/9,13405:R1/9,13440:RIGHT/27,13464:R1/9,13494:L1/9,13500:CIRCLE/9,13517:LEFT/36,13523:R1/9,13535:CROSS/312,13582:R1/9,13594:L1/9,13618:RIGHT/45,13641:R1/9,13671:CIRCLE/9,13694:L1/9,13700:R1/9,13742:LEFT/27,13759:R1/9,13794:L1/9,13818:R1/9,13830:CROSS/312,13842:CIRCLE/9,13877:R1/9,13889:RIGHT/36,13895:L1/9,13936:R1/9,13966:LEFT/45,13996:L1/9,13996:R1/9,14013:CIRCLE/9,14055:R1/9,14067:RIGHT/27,14096:L1/9,14114:R1/9,14125:CROSS/312,14173:R1/9,14185:CIRCLE/9,14190:LEFT/36,14196:L1/9,14232:R1/9,14291:R1/9,14297:L1/9,14338:RIGHT/45,14350:R1/9,14356:CIRCLE/9,14397:L1/9,14409:R1/9,14415:LEFT/27,14421:CROSS/312,14468:R1/9,14498:L1/9,14516:RIGHT/36,14528:CIRCLE/9,14528:R1/9,14587:R1/9,14599:L1/9,14640:LEFT/45,14646:R1/9,14699:CIRCLE/9,14699:L1/9,14705:R1/9,14717:CROSS/312,14765:R1/9,14788:RIGHT/27,14800:L1/9,14824:R1/9,14866:LEFT/36,14872:CIRCLE/9,14884:R1/9,14902:L1/9,14943:R1/9,1496Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
1257:CROSS/18,3334:CROSS/9,3638:CROSS/9,3934:CROSS/13,4253:CROSS/3,4545:CROSS/149,4743:LEFT/36,4773:CROSS/148,4773:R1/9,4826:R1/9,4856:RIGHT/44,4879:R1/9,4933:R1/9,4986:R1/9,4992:LEFT/27,5010:CROSS/148,5039:R1/9,5093:R1/8,5146:R1/9,5152:RIGHT/36,5200:R1/9,5200:UP/11,5241:LEFT/44,5247:CROSS/148,5253:R1/8,5306:R1/9,5353:RIGHT/27,5359:R1/9,5412:R1/9,5466:R1/9,5484:CROSS/148,5489:LEFT/36,5519:R1/9,5573:R1/8,5626:R1/9,5650:RIGHT/44,5679:R1/9,5720:CROSS/149,5732:R1/9,5738:LEFT/27,5786:R1/9,5839:R1/9,5851:RIGHT/35,5892:R1/9,5946:R1/8,5957:CROSS/149,5987:LEFT/44,5999:R1/9,6052:R1/9,6106:R1/8,6147:RIGHT/27,6159:R1/9,6195:CROSS/148,6212:R1/9,6236:LEFT/36,6266:R1/9,6319:R1/9,6349:RIGHT/44,6373:R1/8,6385:UP/11,6426:R1/9,6432:CROSS/148,6479:R1/9,6485:LEFT/27,6532:R1/9,6586:R1/9,6639:R1/9,6645:RIGHT/35,6668:CROSS/149,6692:R1/9,6734:LEFT/44,6745:R1/9,6799:R1/9,6846:RIGHT/27,6852:R1/9,6906:CROSS/148,6906:R1/9,6959:R1/9,6983:LEFT/36,7013:R1/9,7066:R1/9,7120:R1/9,7143:CROSS/149,7143:RIGHT/45,7173:R1/9,7226:R1/10,7233:LEFT/27,7280:R1/9,7334:R1/8,7345:RIGHT/36,7381:CROSS/148,7387:R1/9,7440:R1/9,7482:LEFT/45,7494:R1/9,7547:R1/9,7571:UP/12,7601:R1/9,7618:CROSS/149,7642:RIGHT/27,7654:R1/9,7708:R1/9,7731:LEFT/36,7761:R1/9,7814:R1/9,7844:RIGHT/45,7856:CROSS/149,7868:R1/9,7921:R1/9,7975:R1/9,7981:LEFT/27,8028:R1/9,8081:R1/10,8093:CROSS/149,8135:R1/9,8141:RIGHT/36,8188:R1/9,8230:LEFT/45,8242:R1/9,8295:R1/9,8331:CROSS/149,8343:RIGHT/27,8349:R1/9,8402:R1/9,8456:R1/9,8480:LEFT/36,8510:R1/8,8563:R1/9,8569:CROSS/148,8617:R1/9,8640:RIGHT/45,8670:R1/9,8723:R1/9,8729:LEFT/27,8759:UP/12,8777:R1/9,8806:CROSS/149,8830:R1/9,8842:RIGHT/36,8884:R1/9,8937:R1/9,8979:LEFT/44,8991:R1/8,9044:CROSS/148,9044:R1/9,9097:R1/9,9139:RIGHT/26,9150:R1/9,9204:R1/9,9228:LEFT/35,9257:R1/9,9281:CROSS/149,9311:R1/9,9341:RIGHT/44,9365:R1/9,9418:R1/9,9472:R1/8,9477:LEFT/27,9519:CROSS/149,9525:R1/9,9578:R1/9,9632:R1/9,9638:RIGHT/35,9685:R1/9,9727:LEFT/44,9739:R1/8,9756:CROSS/149,9792:R1/9,9840:RIGHT/26,9846:R1/9,9899:R1/9,9947:UP/12,9953:R1/9,9976:LEFT/36,9994:CROSS/148,10006:R1/9,10059:R1/9,10113:R1/9,10136:RIGHT/45,10166:R1/9,10220:R1/9,10226:LEFT/26,10232:CROSS/148,10273:R1/9,10327:R1/9,10339:RIGHT/36,10380:R1/9,10434:R1/9,10470:CROSS/148,10476:LEFT/45,10488:R1/9,10541:R1/9,10595:R1/9,10636:RIGHT/27,10648:R1/9,10702:R1/9,10708:CROSS/148,10725:LEFT/36,10755:R1/9,10809:R1/9,10838:RIGHT/45,10862:R1/9,10916:R1/9,10946:CROSS/148,10969:R1/9,10975:LEFT/27,11023:R1/9,11077:R1/8,11130:R1/9,11136:RIGHT/35,11136:UP/12,11183:CROSS/149,11183:R1/9,11225:LEFT/44,11237:R1/9,11290:R1/9,11338:RIGHT/27,11344:R1/9,11397:R1/9,11421:CROSS/149,11451:R1/9,11474:LEFT/36,11504:R1/9,11558:R1/9,11612:R1/9,11635:RIGHT/45,11659:CROSS/149,11665:R1/9,11719:R1/9,11725:LEFT/26,11772:R1/9,11826:R1/9,11838:RIGHT/36,11880:R1/9,11898:CROSS/148,11933:R1/9,11975:LEFT/45,11987:R1/9,12041:R1/8,12094:R1/9,12136:CROSS/149,12136:RIGHT/27,12148:R1/9,12201:R1/9,12225:LEFT/36,12255:R1/9,12308:R1/9,12326:UP/12,12338:RIGHT/44,12362:R1/9,12374:CROSS/148,12415:R1/9,12468:R1/9,12474:LEFT/27,12522:R1/9,12576:R1/9,12611:CROSS/149,12629:R1/9,12635:RIGHT/36,12683:R1/9,12724:LEFT/45,12736:R1/9,12790:R1/9,12838:RIGHT/26,12844:R1/8,12850:CROSS/149,12897:R1/9,12951:R1/9
|
||||
+156
-9
@@ -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)
|
||||
@@ -95,6 +95,9 @@ STEPS = ['verify', 'extract', 'configure', 'tools', 'recompile', 'packs', 'compi
|
||||
# FetchContent sources (BozoEngine's runtime/CMakeLists.txt): <name>-src in the kit's deps/.
|
||||
FETCH_NAMES = ['sdl3', 'imgui']
|
||||
GAME_EXE = 'tmb'
|
||||
# Staged next to the game for the launcher's optional "Enhance textures" step (tools/tmb_texture_enhance.py): the
|
||||
# headless runner dumps the player's textures, tmb-texture-pack makes them into a pack with the kit's Real-ESRGAN.
|
||||
TOOL_EXES = ['tmb-headless', 'tmb-texture-pack']
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
KIT_MANIFEST = 'kit_manifest.json'
|
||||
|
||||
@@ -103,19 +106,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
|
||||
@@ -633,7 +663,7 @@ class Build:
|
||||
self.cmake_build_targets('tmb_packs', percent=ninja_percent)
|
||||
|
||||
def step_compile(self):
|
||||
self.cmake_build_targets(GAME_EXE, percent=ninja_percent)
|
||||
self.cmake_build_targets(GAME_EXE, *TOOL_EXES, percent=ninja_percent)
|
||||
|
||||
def exe_path(self):
|
||||
return os.path.join(self.cmake_build, GAME_EXE + EXE)
|
||||
@@ -657,6 +687,18 @@ class Build:
|
||||
for dll in runtime_dlls(exe, [os.path.dirname(exe), self.find_toolchain()]):
|
||||
shutil.copy2(dll, os.path.join(self.game, os.path.basename(dll)))
|
||||
staged.append(dll)
|
||||
for tool in TOOL_EXES:
|
||||
src, dst = os.path.join(self.cmake_build, tool + EXE), os.path.join(self.game, tool + EXE)
|
||||
if not os.path.isfile(src):
|
||||
raise BuildError('no %s at %s' % (tool, src))
|
||||
if os.path.exists(dst):
|
||||
os.remove(dst)
|
||||
if self.args.debug_info == 'no' and os.path.isfile(strip):
|
||||
self.run([strip, '--strip-debug', '-o', dst, src])
|
||||
shutil.copystat(src, dst)
|
||||
else:
|
||||
shutil.copy2(src, dst)
|
||||
staged.append(src)
|
||||
shutil.copy2(self.elf(), os.path.join(self.game, ELF_NAME))
|
||||
for name in ('tmb_textures.pack', 'tmb_meshes.pack'):
|
||||
shutil.copy2(os.path.join(self.cmake_build, 'packs', name), os.path.join(self.game, name))
|
||||
@@ -683,7 +725,8 @@ class Build:
|
||||
'build_type': self.args.build_type, 'debug_info': self.args.debug_info,
|
||||
'toolchain': self.find_toolchain(), 'kit': self.kit, 'exe': name,
|
||||
'files': [os.path.basename(p) for p in staged]}, f, indent=1)
|
||||
emit('INFO', 'stage', '%s, %.1f MB, %d DLLs staged' % (name, os.path.getsize(dest) / 1e6, len(staged) - 1))
|
||||
emit('INFO', 'stage', '%s, %.1f MB, %d DLLs and %d tools staged'
|
||||
% (name, os.path.getsize(dest) / 1e6, sum(1 for p in staged if p.lower().endswith('.dll')), len(TOOL_EXES)))
|
||||
|
||||
def write_built_from(self):
|
||||
"""<game>/built_from.ini: the release stamp (<TMB_Recomp>/release.ini, written by tools/make_release.py) of the
|
||||
@@ -712,6 +755,7 @@ class Build:
|
||||
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
|
||||
@@ -724,7 +768,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}
|
||||
@@ -753,6 +797,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
|
||||
|
||||
|
||||
@@ -810,12 +856,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, '
|
||||
@@ -828,13 +875,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())
|
||||
@@ -888,6 +950,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
|
||||
|
||||
@@ -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')):
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dumps the textures of every arena and car from your own disc into one folder, for a full texture pack
|
||||
(docs/TEXTURE_UPSCALING.md; then tools/tmb_texture_upscale.py). Headless runs of the native build, each with its own
|
||||
user folder under <work>, TMB_UNLOCK_ALL=1 and TMB_TEXTURE_DUMP=<dump>:
|
||||
|
||||
- the 21 story levels (TMB_STORY_LEVEL=0..20 on BozoEngine's reference story script): every arena, the bosses and the
|
||||
AI cars the story brings. Level n's player drives the car n RIGHT presses from the first on the car-select screen,
|
||||
so levels 0 to 14 load the 15 player-only versions (xxP: about 10% of each car's textures differ from its AI
|
||||
version);
|
||||
- the actual four-player route (BozoEngine's reference p1..p4 scripts, player 1's intro press dropped, as
|
||||
docs/HANDOFF.md describes): the AI versions four players drive;
|
||||
- two Challenge matches in the Junkyard with other opponents (AXA, HSA, RLA, TKA, TXA).
|
||||
|
||||
Each run's dump covers every object of the NGP files loaded (runtime/tmb_meshes.cpp's dumpLoadedObjects), drawn or not.
|
||||
|
||||
tools/tmb_texture_dump_all.py <tmb-headless> <disc .iso> <dump folder> [--work <folder>] [--jobs 3]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
|
||||
# The pad scripts (button timings, copied from BozoEngine's reference/tmb/scripts, which a release leaves out).
|
||||
SCRIPTS = os.path.join(ROOT, 'tools', 'texture_dump')
|
||||
COMPLETE = 'complete' # in the dump folder once every run finished
|
||||
PLAYER_CARS = 15 # the car-select screen's cars with every car unlocked (TTP, PCP, SUP, MGP, RKP, DCP, SPP, SIP, HSP,
|
||||
# TXP, AXP, TKP, RLP, STP, B1P), then the list wraps
|
||||
|
||||
|
||||
def story(text, rights, at=3790, step=45, pick=3934):
|
||||
"""The story script with `rights` RIGHT presses on the car-select screen (shown from frame 3744 to the pick at
|
||||
3934 in tmb-headless), every press from the pick on moved later to make room."""
|
||||
shift = rights * step
|
||||
out = []
|
||||
for entry in text.strip().split(','):
|
||||
frame, press = entry.split(':')
|
||||
frame = int(frame)
|
||||
out.append((frame + shift if frame >= pick else frame, press))
|
||||
out += [(at + i * step, 'RIGHT/12') for i in range(rights)]
|
||||
out.sort(key=lambda e: e[0])
|
||||
return ','.join(f'{f}:{p}' for f, p in out) + '\n', shift
|
||||
|
||||
|
||||
def challenge(opponent_rights, end=330.0):
|
||||
"""tools/arena_script.py's Challenge route in the Junkyard, the opponent chosen by RIGHT presses."""
|
||||
e = ['25:CROSS/300', '62:CROSS/250', '72:DOWN/200', '80:CROSS/250', '92:CROSS/250', '112:RIGHT/200', '150:CROSS/250',
|
||||
'162:CROSS/250']
|
||||
t = 168
|
||||
for _ in range(opponent_rights):
|
||||
e.append(f'{t}:RIGHT/200')
|
||||
t += 3
|
||||
e += [f'{t + 2}:CROSS/250', f'{t + 10}:SQUARE/250']
|
||||
t += 25
|
||||
while t < end:
|
||||
e.append(f'{t:.1f}:CROSS/5200')
|
||||
t += 5
|
||||
out = []
|
||||
for entry in e:
|
||||
s, press = entry.split(':')
|
||||
b, ms = press.split('/')
|
||||
out.append(f'{round(float(s) * 60)}:{b}/{max(1, round(float(ms) * .06))}')
|
||||
return ','.join(out) + '\n'
|
||||
|
||||
|
||||
def dump_all(headless, iso, dump, work, jobs=3, report=print, elf=None):
|
||||
"""Every run, `jobs` at a time; report(done, total, name, code) after each. True when they all finished and the
|
||||
dump folder is marked complete (a later call then does nothing)."""
|
||||
dump, work = os.path.abspath(dump), os.path.abspath(work)
|
||||
if os.path.isfile(os.path.join(dump, COMPLETE)):
|
||||
return True
|
||||
os.makedirs(work, exist_ok=True)
|
||||
p1 = os.path.join(work, 'p1_4p.txt')
|
||||
with open(os.path.join(SCRIPTS, 'p1_frames.txt'), encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
with open(p1, 'w', encoding='utf-8') as f:
|
||||
f.write(text.replace('1292:CROSS/18,', '', 1))
|
||||
with open(os.path.join(SCRIPTS, 'story_frames.txt'), encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
runs = []
|
||||
for n in range(21):
|
||||
script, shift = story(text, n if n < PLAYER_CARS else 0)
|
||||
path = os.path.join(work, f'story{n}.txt')
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
f.write(script)
|
||||
runs.append((f'story{n}', {'TMB_STORY_LEVEL': str(n), 'TMB_PLAYER_GOD': '1'}, 7000 + shift, ['--pad-script', path]))
|
||||
runs.append(('four-player', {}, 8500, ['--pad-script', '1=' + p1] +
|
||||
[a for i in (2, 3, 4) for a in ('--pad-script', f'{i}={os.path.join(SCRIPTS, f"p{i}_frames.txt")}')]))
|
||||
for rights in (2, 4):
|
||||
script = os.path.join(work, f'challenge{rights}.txt')
|
||||
with open(script, 'w', encoding='utf-8') as f:
|
||||
f.write(challenge(rights))
|
||||
runs.append((f'challenge{rights}', {}, 20500, ['--pad-script', script]))
|
||||
done = [0]
|
||||
|
||||
def run(entry):
|
||||
name, extra, frames, pads = entry
|
||||
env = dict(os.environ, PS2X_USER_DIR=os.path.join(work, name), TMB_TEXTURE_DUMP=dump, TMB_UNLOCK_ALL='1',
|
||||
PS2X_NO_DIALOGS='1', **extra)
|
||||
os.makedirs(env['PS2X_USER_DIR'], exist_ok=True)
|
||||
flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0) | getattr(subprocess, 'BELOW_NORMAL_PRIORITY_CLASS', 0)
|
||||
with open(os.path.join(work, name + '.log'), 'w', encoding='utf-8') as log:
|
||||
code = subprocess.call([headless] + (['--elf', elf] if elf else []) + ['--iso', iso, '--frames', str(frames)] + pads, env=env,
|
||||
stdout=log, stderr=subprocess.STDOUT, creationflags=flags)
|
||||
done[0] += 1
|
||||
report(done[0], len(runs), name, code)
|
||||
return code
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max(1, jobs)) as pool:
|
||||
codes = list(pool.map(run, runs))
|
||||
if any(codes):
|
||||
return False
|
||||
with open(os.path.join(dump, COMPLETE), 'w', encoding='utf-8') as f:
|
||||
f.write('%d runs\n' % len(runs))
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('headless')
|
||||
p.add_argument('iso')
|
||||
p.add_argument('dump')
|
||||
p.add_argument('--work', help='user folders and logs (default: <dump>/../texture-dump-runs)')
|
||||
p.add_argument('--jobs', type=int, default=3)
|
||||
args = p.parse_args()
|
||||
work = args.work or os.path.join(args.dump, '..', 'texture-dump-runs')
|
||||
ok = dump_all(args.headless, args.iso, args.dump, work, args.jobs,
|
||||
lambda n, total, name, code: print(f'{name}: exit {code} ({n}/{total})', flush=True))
|
||||
count = sum(1 for n in os.listdir(args.dump) if n.endswith('.png')) if os.path.isdir(args.dump) else 0
|
||||
print(f'{count} textures in {args.dump}')
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The launcher's "Enhance textures" step: an AI-upscaled texture pack made on the player's PC from their own disc, into
|
||||
their user folder's texture_pack, which the game then draws instead of the original textures (docs/TEXTURE_UPSCALING.md).
|
||||
Nothing of the game is downloaded or shipped: the textures come from the player's game, the tools from the release.
|
||||
|
||||
tools/tmb_texture_enhance.py --game <game folder> --kit <kit folder> --user <user folder> [--jobs 3]
|
||||
tools/tmb_texture_enhance.py --user <user folder> --remove
|
||||
|
||||
- dump: tools/tmb_texture_dump_all.py's headless runs with the staged tmb-headless.exe and disc.iso (every arena and
|
||||
car; resumed when a finished dump is already there);
|
||||
- upscale: the staged tmb-texture-pack.exe with the kit's Real-ESRGAN (kit/realesrgan) into texture_pack.new, which then
|
||||
replaces texture_pack (the game never sees half a pack; files already made are kept, so a stopped run goes on);
|
||||
- the dump and the work folders are removed at the end (texture_work: the game's own textures, on the player's PC).
|
||||
|
||||
Output for the launcher, one per line: "step <dump|prepare|upscale|finish>", "progress <done> <total>", "error <text>",
|
||||
"done <replacements>". Standard library only (the kit's Python).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from tmb_texture_dump_all import dump_all # noqa: E402
|
||||
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
|
||||
|
||||
def say(line):
|
||||
print(line, flush=True)
|
||||
|
||||
|
||||
def fail(text):
|
||||
say('error ' + text)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def remove(path):
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
return not os.path.exists(path)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('--game')
|
||||
p.add_argument('--kit')
|
||||
p.add_argument('--user', required=True)
|
||||
p.add_argument('--jobs', type=int, default=max(1, min(3, (os.cpu_count() or 4) // 4)))
|
||||
p.add_argument('--remove', action='store_true', help='delete the pack (and anything a stopped run left)')
|
||||
args = p.parse_args()
|
||||
pack = os.path.join(args.user, 'texture_pack')
|
||||
fresh, work = pack + '.new', os.path.join(args.user, 'texture_work')
|
||||
if args.remove:
|
||||
ok = all(remove(d) for d in (pack, fresh, work))
|
||||
if not ok:
|
||||
fail('the pack could not be deleted (is the game running?)')
|
||||
say('done 0')
|
||||
return
|
||||
if not args.game or not args.kit:
|
||||
fail('--game and --kit are needed')
|
||||
|
||||
headless = os.path.join(args.game, 'tmb-headless' + EXE)
|
||||
packer = os.path.join(args.game, 'tmb-texture-pack' + EXE)
|
||||
iso = os.path.join(args.game, 'disc.iso')
|
||||
esrgan = os.path.join(args.kit, 'realesrgan', 'realesrgan-ncnn-vulkan' + EXE)
|
||||
if not (os.path.isfile(headless) and os.path.isfile(packer)):
|
||||
fail('the game was built before this step existed: Rebuild it first (Maintenance)')
|
||||
if not os.path.isfile(iso):
|
||||
fail('the game has no disc image: prepare the game first')
|
||||
if not os.path.isfile(esrgan):
|
||||
fail('this build kit has no Real-ESRGAN: update TMB_Recomp to a release with it')
|
||||
|
||||
# ---- the dump ----
|
||||
say('step dump')
|
||||
say('progress 0 1')
|
||||
elf = os.path.join(args.game, 'SCUS_971.01')
|
||||
ok = dump_all(headless, iso, os.path.join(work, 'dump'), os.path.join(work, 'runs'), args.jobs,
|
||||
lambda done, total, name, code: say('progress %d %d' % (done, total)), elf if os.path.isfile(elf) else None)
|
||||
if not ok:
|
||||
fail('a texture dump run stopped (its log is in %s)' % os.path.join(work, 'runs'))
|
||||
|
||||
# ---- the pack ----
|
||||
flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
||||
proc = subprocess.Popen([packer, os.path.join(work, 'dump'), fresh, '--esrgan', esrgan, '--work', os.path.join(work, 'pack')],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8', errors='replace',
|
||||
creationflags=flags)
|
||||
made, error = None, None
|
||||
for line in proc.stdout:
|
||||
line = line.rstrip('\r\n')
|
||||
if line.startswith(('step ', 'progress ')):
|
||||
say(line)
|
||||
elif line.startswith('error '):
|
||||
error = line[6:]
|
||||
elif line.startswith('done '):
|
||||
made = int(line[5:] or 0)
|
||||
if proc.wait() != 0 or made is None:
|
||||
fail(error or 'the texture pack could not be made (exit code %d)' % proc.returncode)
|
||||
|
||||
# ---- in place ----
|
||||
old = pack + '.old'
|
||||
remove(old)
|
||||
if os.path.isdir(pack):
|
||||
os.replace(pack, old)
|
||||
os.replace(fresh, pack)
|
||||
remove(old)
|
||||
remove(work)
|
||||
count = sum(1 for n in os.listdir(pack) if n.endswith('.png'))
|
||||
say('done %d' % count)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -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')):
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Makes a texture replacement pack from a texture dump with Real-ESRGAN, on the player's own PC from their own disc's
|
||||
textures (docs/TEXTURE_UPSCALING.md). Nothing it reads or writes is part of the repository or a release.
|
||||
|
||||
tools/tmb_texture_upscale.py <dump folder> <pack folder> --esrgan <realesrgan-ncnn-vulkan.exe>
|
||||
[--models <its models folder>] [--model realesrgan-x4plus] [--min-size 32] [--detail 1.0]
|
||||
|
||||
- The dump: TMB_TEXTURE_DUMP=1 (runtime/tmb_texture_dump.cpp): <identity>.png and index.tsv, alpha as the GS's (128 is
|
||||
opaque, up to 255). The pack: <identity>.png 4 times as large each way, the same alpha convention, which the engine
|
||||
reads from <user folder>/texture_pack (or video.ini's texture_pack, PS2X_TEXTURE_PACK).
|
||||
- Colour: Real-ESRGAN (xinntao/Real-ESRGAN, BSD-3-Clause; its ncnn-vulkan executable and models, fetched by the player)
|
||||
over the texture with a 16-texel border taken from the opposite edges, so a repeating texture stays seamless. Its model
|
||||
removes fine grain (gravel, rust become flat), so the original's high frequencies (bicubic minus its blur) are added
|
||||
back, scaled by --detail. Texels with no alpha get their neighbours' colour first, so no dark fringe bleeds in.
|
||||
- Alpha: bicubic over the same border. Two-valued alpha (cut-outs) is cut again at the midpoint, so edges stay sharp but
|
||||
follow the smoothed shape; otherwise held within the texture's own range, and values near opaque (128) snapped to it.
|
||||
- Flat areas (a texel equal to its 8 neighbours) are kept exactly: a black background stays black.
|
||||
- The menus and the font (--skip) are left to the engine's texture upscaling: the model garbles small lettering.
|
||||
- Textures smaller than --min-size on either side are left out (the model invents little from 8x8 or 16x16; the
|
||||
engine's own texture upscaling covers them when it is on).
|
||||
|
||||
Needs Python 3 with numpy and Pillow.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image, ImageFilter
|
||||
except ImportError:
|
||||
sys.exit('tmb_texture_upscale.py needs numpy and Pillow (python -m pip install numpy pillow)')
|
||||
|
||||
PAD = 16
|
||||
SCALE = 4
|
||||
|
||||
|
||||
def wrap_pad(a, pad):
|
||||
return np.pad(a, [(pad, pad), (pad, pad)] + [(0, 0)] * (a.ndim - 2), mode='wrap')
|
||||
|
||||
|
||||
def bleed(rgb, alpha):
|
||||
"""Colour of transparent texels from their visible neighbours (a few dilation passes), wrap-around."""
|
||||
rgb = rgb.astype(np.float32)
|
||||
known = alpha > 0
|
||||
if known.all() or not known.any():
|
||||
return rgb
|
||||
for _ in range(16):
|
||||
if known.all():
|
||||
break
|
||||
acc = np.zeros_like(rgb)
|
||||
cnt = np.zeros(known.shape, np.float32)
|
||||
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1)):
|
||||
k = np.roll(np.roll(known, dy, 0), dx, 1)
|
||||
acc += np.roll(np.roll(rgb, dy, 0), dx, 1) * k[..., None]
|
||||
cnt += k
|
||||
grow = ~known & (cnt > 0)
|
||||
rgb[grow] = acc[grow] / cnt[grow][:, None]
|
||||
known = known | grow
|
||||
return rgb
|
||||
|
||||
|
||||
def upscale_alpha(alpha):
|
||||
h, w = alpha.shape
|
||||
values = np.unique(alpha)
|
||||
if len(values) == 1:
|
||||
return np.full((h * SCALE, w * SCALE), values[0], np.uint8)
|
||||
def up(a):
|
||||
padded = Image.fromarray(wrap_pad(a, PAD).astype(np.uint8), 'L')
|
||||
big = np.asarray(padded.resize((padded.width * SCALE, padded.height * SCALE), Image.BICUBIC), np.float32)
|
||||
return big[PAD * SCALE:(PAD + h) * SCALE, PAD * SCALE:(PAD + w) * SCALE]
|
||||
|
||||
big = up(alpha)
|
||||
if len(values) == 2:
|
||||
lo, hi = float(values[0]), float(values[1])
|
||||
return np.where(big >= (lo + hi) / 2, hi, lo).astype(np.uint8)
|
||||
# Where the texture is see-through stays exactly so: the shape of its visible texels, smoothed and cut at half
|
||||
# (bicubic alone spreads small alphas into transparent areas, which a blended draw shows as a dark box).
|
||||
shape = up((alpha > 0).astype(np.uint8) * 255) >= 128 if values[0] == 0 else np.ones(big.shape, bool)
|
||||
visible = values[values > 0]
|
||||
big = np.clip(big, float(visible.min()), float(visible.max()))
|
||||
if len(values) <= 4:
|
||||
# A few levels (cut-outs, 0 / 127 / 255): each texel snapped to the nearest one.
|
||||
big = visible[np.abs(big[..., None] - visible[None, None, :].astype(np.float32)).argmin(axis=-1)].astype(np.float32)
|
||||
elif 128 in values:
|
||||
big[np.abs(big - 128) <= 2] = 128
|
||||
return np.where(shape, np.rint(big), 0).astype(np.uint8)
|
||||
|
||||
|
||||
def flat(im):
|
||||
"""Texels equal to their 8 neighbours (colour and alpha, wrap-around), at the output size: kept exactly, so a
|
||||
black or flat background stays as it was (the model and the grain would tint it, and a blended draw shows that)."""
|
||||
a = im.astype(np.int16)
|
||||
same = np.ones(a.shape[:2], bool)
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
same &= (np.abs(np.roll(np.roll(a, dy, 0), dx, 1) - a) <= 1).all(axis=-1)
|
||||
return np.kron(same, np.ones((SCALE, SCALE), bool))
|
||||
|
||||
|
||||
def detail(rgb, sigma):
|
||||
"""The original's high frequencies at the output size: bicubic minus its blur, over the wrapped border."""
|
||||
h, w = rgb.shape[:2]
|
||||
padded = Image.fromarray(wrap_pad(np.clip(rgb, 0, 255).astype(np.uint8), PAD), 'RGB')
|
||||
big = padded.resize((padded.width * SCALE, padded.height * SCALE), Image.BICUBIC)
|
||||
hf = np.asarray(big, np.float32) - np.asarray(big.filter(ImageFilter.GaussianBlur(sigma)), np.float32)
|
||||
return hf[PAD * SCALE:(PAD + h) * SCALE, PAD * SCALE:(PAD + w) * SCALE]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('dump')
|
||||
p.add_argument('pack')
|
||||
p.add_argument('--esrgan', required=True, help='realesrgan-ncnn-vulkan executable')
|
||||
p.add_argument('--models', help="its models folder (default: 'models' beside it)")
|
||||
p.add_argument('--model', default='realesrgan-x4plus')
|
||||
p.add_argument('--min-size', type=int, default=32)
|
||||
p.add_argument('--detail', type=float, default=1.0, help='how much of the original grain is added back (0: none)')
|
||||
p.add_argument('--work', help='scratch folder (default: <pack>/.work, removed after)')
|
||||
p.add_argument('--skip', default='SHELL1,FONT',
|
||||
help="files whose textures are left to the engine's upscaling (comma-separated; default the menus and "
|
||||
"the font: the model garbles small lettering)")
|
||||
args = p.parse_args()
|
||||
|
||||
models = args.models or os.path.join(os.path.dirname(os.path.abspath(args.esrgan)), 'models')
|
||||
work = args.work or os.path.join(args.pack, '.work')
|
||||
src_dir, out_dir = os.path.join(work, 'in'), os.path.join(work, 'out')
|
||||
for d in (args.pack, src_dir, out_dir):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
|
||||
skip = {name.strip().upper().split('.')[0] for name in args.skip.split(',') if name.strip()}
|
||||
with open(os.path.join(args.dump, 'index.tsv'), encoding='utf-8') as f:
|
||||
rows = list(csv.DictReader(f, delimiter='\t'))
|
||||
todo = []
|
||||
for row in rows:
|
||||
ident, w, h = row['identity'], int(row['width']), int(row['height'])
|
||||
if min(w, h) < args.min_size or os.path.exists(os.path.join(args.pack, ident + '.png')):
|
||||
continue
|
||||
if row['texels'].split('#')[0].split('.')[0] in skip:
|
||||
continue
|
||||
im = np.asarray(Image.open(os.path.join(args.dump, ident + '.png')).convert('RGBA'))
|
||||
rgb = bleed(im[..., :3], im[..., 3])
|
||||
Image.fromarray(wrap_pad(np.clip(rgb, 0, 255).astype(np.uint8), PAD), 'RGB').save(os.path.join(src_dir, ident + '.png'))
|
||||
todo.append((ident, im, rgb))
|
||||
print('%d textures to upscale (%d in the dump, %d below %d texels or already done)' % (len(todo), len(rows), len(rows) - len(todo),
|
||||
args.min_size))
|
||||
if not todo:
|
||||
return
|
||||
start = time.time()
|
||||
subprocess.run([args.esrgan, '-i', src_dir, '-o', out_dir, '-n', args.model, '-m', models, '-s', str(SCALE), '-f', 'png'],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
print('Real-ESRGAN: %.1f s' % (time.time() - start))
|
||||
for ident, im, rgb in todo:
|
||||
h, w = im.shape[:2]
|
||||
out = np.asarray(Image.open(os.path.join(out_dir, ident + '.png')).convert('RGB'), np.float32)
|
||||
out = out[PAD * SCALE:(PAD + h) * SCALE, PAD * SCALE:(PAD + w) * SCALE]
|
||||
if args.detail:
|
||||
out = out + args.detail * detail(rgb, 3.0)
|
||||
a = upscale_alpha(im[..., 3])
|
||||
pixels = np.dstack([np.clip(np.rint(out), 0, 255).astype(np.uint8), a])
|
||||
keep = flat(im)
|
||||
pixels[keep] = np.kron(im, np.ones((SCALE, SCALE, 1), np.uint8))[keep]
|
||||
Image.fromarray(pixels, 'RGBA').save(os.path.join(args.pack, ident + '.png'), compress_level=6)
|
||||
if not args.work:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
print('%d replacements written to %s' % (len(todo), args.pack))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user