diff --git a/BozoEngine b/BozoEngine index a36a4d2..6cf6faf 160000 --- a/BozoEngine +++ b/BozoEngine @@ -1 +1 @@ -Subproject commit a36a4d23f2843a85d28cd177b5f3c554c618c6c4 +Subproject commit 6cf6fafcbe1d9d106f60813ded96fd10a76a13e3 diff --git a/README.md b/README.md index 2913445..f15a4d0 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ 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 | ✅ | +| 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 | 🔧 | @@ -402,6 +403,8 @@ use physical US positions: |---|---| | F2 | Settings: Controls (per-player buttons, sticks, triggers, mouse and sensitivity), Video (resolution, window mode, render scale, presentation frame rate and texture upscaling), Cheats. Controls save to `input.ini`; video saves to `video.ini`. | | F3 | Toggle the frame-rate counter. | +| F5 / F7 | Save / load a save state in the current slot (`states/slot.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. | diff --git a/bozo/tmb_headless.cpp b/bozo/tmb_headless.cpp index 32f7513..78d96d2 100644 --- a/bozo/tmb_headless.cpp +++ b/bozo/tmb_headless.cpp @@ -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(std::stoull(value())); + else if (a == "--load-state") + opt.loadState = value(); + else if (a == "--load-state-at") + opt.loadStateFrame = static_cast(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); diff --git a/bozo/tmb_window.cpp b/bozo/tmb_window.cpp index 7cc683e..4f4a012 100644 --- a/bozo/tmb_window.cpp +++ b/bozo/tmb_window.cpp @@ -1,246 +1,266 @@ -// 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 (/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 /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] +// +// 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 (/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 /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_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" #include "tmb_scene.h" - -#include -#include -#include -#include -#include - -#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(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 (/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 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 +#include +#include +#include +#include + +#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(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 if (a == "--save-state") + opt.saveState = value(); + else if (a == "--save-state-at") + opt.saveStateFrame = static_cast(std::stoull(value())); + else if (a == "--load-state") + opt.loadState = value(); + else if (a == "--load-state-at") + opt.loadStateFrame = static_cast(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] " + "[--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 (/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 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(a.dropped), static_cast(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(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(a.dropped), static_cast(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(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)); }; + return bozo::app::runWindow(window, game, &pad); +} diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index d42e2a1..ecc2c22 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -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. diff --git a/docs/SAVE_STATES.md b/docs/SAVE_STATES.md new file mode 100644 index 0000000..08f367d --- /dev/null +++ b/docs/SAVE_STATES.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.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. diff --git a/runtime/tmb_2d.cpp b/runtime/tmb_2d.cpp index 18ce0af..e2caec9 100644 --- a/runtime/tmb_2d.cpp +++ b/runtime/tmb_2d.cpp @@ -1,875 +1,875 @@ -// TMB's 2D drawn natively, its builders rewritten from the game's code: each draws from the game's own variables -// (Renderer::drawOverlay, published with the frame), and none of them sends GS packets. TMB_NATIVE_2D=0: the game's -// own builders (their GS packets) instead. -// -// The font (fontBuildPrim, fontDmaFontData): fontSpritePrint* call fontBuildPrim for each printable character, which -// adds a sprite at the font's cursor (records of 0x20 bytes at 0x504540 USA, 0x38 at 0x50caf0 PAL, by font size: +0 -// cell width, +2 cell height, +4 / +6 the glyph's size in the texture, +8 / +0xa on screen, +0xe the advance, +0x10 / -// +0x12 the cursor, +0x18 the colour; 12.4 fixed point, the cursor from the current view's top-left corner) to the -// font's packet, which fontDmaFontData sends to the GS. Here the same sprite is drawn natively, and fontDmaFontData -// only resets what it would after sending (the font's texture from the texture pack: no upload). - -#include "tmb_port.h" -#include "bozo/render/renderer.h" -#include "bozo/render/texture.h" -#include "bozo/render/movie.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace tmb::native -{ - bool enabled(); -} - -namespace tmb::textures -{ - std::shared_ptr font(); -} - -namespace tmb::native -{ - bool menusDrawn(); -} - -namespace tmb::twod -{ - void publish(); - - namespace - { - // The movie pictures (sceMpegGetPicture, below), shared by loadImage and the loading bar. - std::mutex g_movieMutex; - std::shared_ptr g_moviePicture; // under g_movieMutex - // The picture loadImage last put in the display buffers (under g_movieMutex): the one shown through the display's - // circuit 2 (bozo::render::setDisplayPicture). - std::shared_ptr g_menuPicture; - std::atomic g_imageReplaced{false}; // loadImage drew a picture instead of transferring it (this vblank) - - constexpr uint32_t kFontBuildPrim = 0x001C4918u; - // displayDialog (a match's pause, won / lost and results overlays): where its loop flushes the font, and its D2 - // kick of the darkening sprite that follows (inline; its offsets differ between the regions). - constexpr uint32_t kDialogFontReturn = 0x163940u, kDialogKick = 0x163a50u; - constexpr uint32_t kFontDmaFontData = 0x001C3FB8u; - constexpr uint32_t kFontRecords = 0x504540u, kFontRecordBytes = 0x20u; - constexpr uint32_t kViews = 0x4dfcd0u; - constexpr int32_t kGpNumViews = -0x322c; - constexpr int32_t kGpCurView = -0x3228, kGpFontMode = -0x3034, kGpFontUpload = -0x3630, kGpFontCount = -0x303c, - kGpFontAt = -0x3038, kGpFontTagAt = -0x3030, kGpFontStart = -0x302c; - - // The font's packet "sent" (fontDmaFontData) since the last publish: the frame's 2D is complete. - std::atomic g_flushed{false}; - std::atomic g_rdram{nullptr}; // guest memory, from the font's hooks (the publish has none) - std::atomic g_gp{0}; // the game's gp, from the same hooks - uint32_t noteGp(uint32_t gp) // an override's gp, kept for those read where no register is at hand (viewClip) - { - g_gp.store(gp, std::memory_order_relaxed); - return gp; - } - - bool on() - { - static const bool s_on = [] - { - const char *value = std::getenv("TMB_NATIVE_2D"); - return !(value && *value == '0'); - }(); - return s_on && tmb::native::enabled(); - } - - 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 setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1fffffcu), &value, 4); } - void setHalf(uint8_t *rdram, uint32_t address, uint16_t value) { std::memcpy(rdram + (address & 0x1fffffeu), &value, 2); } - - // fontBuildPrim(size, character, packet): one glyph at the font's cursor, which then advances. - void fontBuildPrimOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (!on()) - { - fontBuildPrim__FicP6QwData_0x1c4918(rdram, ctx, runtime); - return; - } - const uint32_t gp = noteGp(getRegU32(ctx, 28)); - const uint32_t record = kFontRecords + getRegU32(ctx, 4) * kFontRecordBytes; - int32_t c = static_cast(getRegU32(ctx, 5) & 0xffu); - // The current view's top-left corner, as viewGetCenter / viewGetWH give it. - const uint32_t view = word(rdram, gp + kGpCurView); - const uint32_t viewport = word(rdram, kViews + view * 16u + 4u); - const int32_t centreX = static_cast(word(rdram, viewport + 0x18u)), centreY = static_cast(word(rdram, viewport + 0x1cu)); - const int32_t viewW = half(rdram, viewport + 4u), viewH = half(rdram, viewport + 6u); - const int32_t left = centreX * 16 - viewW * 8, top = centreY * 16 - viewH * 8; - if (c >= 'a' && c <= 'z') - c -= 0x20; - const int32_t glyph = c - 0x21, row = glyph >> 3, column = glyph - (row << 3); - const int32_t u0 = half(rdram, record + 0u) * column + 8, v0 = half(rdram, record + 2u) * row + 8; - const int32_t u1 = half(rdram, record + 4u) + u0, v1 = half(rdram, record + 6u) + v0; - const int32_t x0 = static_cast(half(rdram, record + 0x10u) + left), y0 = static_cast(half(rdram, record + 0x12u) + top); - const int32_t x1 = static_cast(half(rdram, record + 8u) + x0), y1 = static_cast(half(rdram, record + 0xau) + y0); - uint32_t rgba; - std::memcpy(&rgba, rdram + record + 0x18u, 4); - - // The sprite as two triangles: positions in GS pixels (12.4 / 16), texture coordinates over the 128 x 128 font. - bozo::render::Vertex corners[4]; - const float xs[2] = {x0 / 16.0f, x1 / 16.0f}, ys[2] = {y0 / 16.0f, y1 / 16.0f}; - const float us[2] = {u0 / 16.0f / 128.0f, u1 / 16.0f / 128.0f}, vs[2] = {v0 / 16.0f / 128.0f, v1 / 16.0f / 128.0f}; - for (int i = 0; i < 4; ++i) - { - corners[i].x = xs[i & 1]; - corners[i].y = ys[i >> 1]; - corners[i].u = us[i & 1]; - corners[i].v = vs[i >> 1]; - corners[i].rgba = rgba; - corners[i].fog = 1.0f; - } - const bozo::render::Vertex triangles[6] = {corners[0], corners[1], corners[2], corners[1], corners[3], corners[2]}; - // fontInitPacket's state: ALPHA (Cs - Cd) As + Cd, TEST alpha greater than 8, TEX1 bilinear. - bozo::render::Material material; - material.textured = true; - material.tex0 = 0xf0f7f0f7u; // the font's own GPU copy - material.blend = bozo::render::Material::Blend::Alpha; - material.alphaTest = true; - material.alphaRef = 8; - material.clampU = material.clampV = true; - // TMB_NATIVE_LOG_2D=1: the first glyphs, where they land. - static const bool s_log = std::getenv("TMB_NATIVE_LOG_2D") != nullptr; - static uint32_t s_logged = 0; - static std::unordered_map s_seen; // each glyph at each place once - const uint64_t place = (static_cast(static_cast(c)) << 40) ^ (static_cast(x0) << 20) ^ static_cast(y0); - if (s_log && s_logged < 6000u && !s_seen[place] && (s_seen[place] = true) && ++s_logged) - std::fprintf(stderr, "[tmb:2d] glyph %c: (%.1f %.1f)-(%.1f %.1f) uv (%.3f %.3f)-(%.3f %.3f) rgba %08x view %u centre %d %d size %dx%d\n", - static_cast(c), xs[0], ys[0], xs[1], ys[1], us[0], vs[0], us[1], vs[1], rgba, view, centreX, centreY, viewW, viewH); - bozo::render::Renderer::instance().drawOverlay(material, triangles, 6u, tmb::textures::font()); - - // What fontBuildPrim leaves: its sprites' tag started (mode 2, where it would be), the cursor advanced, the - // glyph counted. - if (word(rdram, gp + kGpFontMode) != 2u) - { - setWord(rdram, gp + kGpFontMode, 2u); - setWord(rdram, gp + kGpFontTagAt, word(rdram, gp + kGpFontAt)); - } - setHalf(rdram, record + 0x10u, static_cast(half(rdram, record + 0x10u) + half(rdram, record + 0xeu))); - setWord(rdram, gp + kGpFontCount, word(rdram, gp + kGpFontCount) + 1u); - ctx->pc = getRegU32(ctx, 31); // jr $ra - } - - void dialogDim(uint8_t *rdram, uint32_t gp); - - // fontDmaFontData: what it leaves after sending the font's packet (nothing sent: the glyphs are drawn natively). - void fontDmaFontDataOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (!on()) - { - fontDmaFontData__Fv_0x1c3fb8(rdram, ctx, runtime); - return; - } - const uint32_t gp = noteGp(getRegU32(ctx, 28)); - dialogDim(rdram, getRegU32(ctx, 31) == kDialogFontReturn ? gp : 0u); - g_rdram.store(rdram, std::memory_order_relaxed); - g_gp.store(gp, std::memory_order_relaxed); - ctx->pc = getRegU32(ctx, 31); // jr $ra - if (word(rdram, gp + kGpFontMode) == 0u) - return; - g_flushed.store(true, std::memory_order_relaxed); - setWord(rdram, gp + kGpFontUpload, 0u); - setWord(rdram, gp + kGpFontMode, 1u); - setWord(rdram, gp + kGpFontCount, 0u); - const uint32_t start = word(rdram, gp + kGpFontStart); - setWord(rdram, gp + kGpFontAt, start); - setWord(rdram, gp + kGpFontTagAt, start - 2u); - } - // ---- the HUD (Hud::Update's builders): flat-coloured sprites, lines and triangles, drawn natively ---- - // - // Each builder override runs the game's own builder (its game logic: the closest enemy, the hit slots, the - // radar's state), then draws what that builder would have sent from the same variables. The packet the game - // builders fill is never sent: each override leaves the Hud's qword count (Hud + 4) at 1, under the 2 that - // Update__3Hudi needs to kick its DMA (whichever builder runs last on each path is overridden). - - constexpr uint32_t kRadar = 0x0013EB40u, kHealthBar = 0x00141AF0u, kSeparator = 0x0013E140u, - kRearViewEdge = 0x0013E3E0u, kLaser = 0x001425B8u, k4pSeparator = 0x0013E838u; - constexpr uint32_t kTurbo4p = 0x00141338u, kEnergy4p = 0x001418A8u, kHealth4p = 0x001415A0u; - constexpr int32_t kGpGame = -0x4154, kGpSettings = -0x4148, kGpRearLarge = -0x3224; - constexpr int32_t kGpThreat[4] = {-0x38bc, -0x38f8, -0x37a4, -0x3760}; - constexpr uint32_t kSetTeams = 0x1a30c, kSetTeam = 0x1a320, kSetFade = 0x1a360, kAlphaConstants = 0x4e6e70u; - constexpr uint32_t kVehicleBytes = 0x2d00; - - float flt(const uint8_t *rdram, uint32_t address) - { - float value; - std::memcpy(&value, rdram + (address & 0x1fffffcu), 4); - return value; - } - double dbl(const uint8_t *rdram, uint32_t address) - { - double value; - std::memcpy(&value, rdram + (address & 0x1fffff8u), 8); - return value; - } - int8_t byte(const uint8_t *rdram, uint32_t address) { return static_cast(rdram[address & 0x1ffffffu]); } - - // A view's centre and size (viewGetCenter / viewGetWH), in GS pixels. - struct View - { - int32_t cx = 2048, cy = 2048, w = 640, h = 448; - }; - View viewOf(const uint8_t *rdram, uint32_t view) - { - View v; - const uint32_t def = word(rdram, kViews + view * 16u + 4u); - v.cx = static_cast(word(rdram, def + 0x18u)); - v.cy = static_cast(word(rdram, def + 0x1cu)); - v.w = half(rdram, def + 4u); - v.h = half(rdram, def + 6u); - return v; - } - // viewGetScreenDisplay: 0 one view, 1 split side by side, 2 split one over the other (view 0's type). - int screenDisplay(const uint8_t *rdram) - { - switch (word(rdram, kViews + 8u)) - { - case 1: case 2: case 5: case 6: case 15: case 16: return 2; - case 3: case 4: case 7: case 8: return 1; - default: return 0; - } - } - - // The HUD's primitives on the overlay: GS pixel coordinates, colours as the GS has them (0x80 is 1.0); ABE: the - // packet's ALPHA_1 (Cs - Cd) As + Cd, else opaque. - void hudTriangles(const bozo::render::Vertex *v, uint32_t count, bool blend) - { - bozo::render::Material material; - material.textured = false; - material.blend = blend ? bozo::render::Material::Blend::Alpha : bozo::render::Material::Blend::Opaque; - bozo::render::Renderer::instance().drawOverlay(material, v, count, nullptr); - } - uint32_t rgba(uint32_t r, uint32_t g, uint32_t b, uint32_t a) { return (r & 0xffu) | ((g & 0xffu) << 8) | ((b & 0xffu) << 16) | ((a & 0xffu) << 24); } - bozo::render::Vertex vertex(float x, float y, uint32_t colour) - { - bozo::render::Vertex v; - v.x = x; - v.y = y; - v.rgba = colour; - v.fog = 1.0f; - return v; - } - // A SPRITE from (x0, y0) to (x1, y1), as the GS fills it (corners in either order). - void hudSprite(float x0, float y0, float x1, float y1, uint32_t colour, bool blend) - { - const float l = std::min(x0, x1), r = std::max(x0, x1), t = std::min(y0, y1), b = std::max(y0, y1); - const bozo::render::Vertex v[6] = {vertex(l, t, colour), vertex(r, t, colour), vertex(l, b, colour), - vertex(r, t, colour), vertex(r, b, colour), vertex(l, b, colour)}; - hudTriangles(v, 6u, blend); - } - // A LINE, one pixel wide. - void hudLine(float x0, float y0, float x1, float y1, uint32_t colour, bool blend) - { - const float dx = x1 - x0, dy = y1 - y0, length = std::sqrt(dx * dx + dy * dy); - if (!(length > 0.0f)) - return; - const float nx = -dy / length * 0.5f, ny = dx / length * 0.5f; - const bozo::render::Vertex v[6] = {vertex(x0 + nx, y0 + ny, colour), vertex(x1 + nx, y1 + ny, colour), vertex(x0 - nx, y0 - ny, colour), - vertex(x1 + nx, y1 + ny, colour), vertex(x1 - nx, y1 - ny, colour), vertex(x0 - nx, y0 - ny, colour)}; - hudTriangles(v, 6u, blend); - } - - // mathfTransform3dTo2d(view, p, out): p plus the view's translation (viewGetWeTrans) through its world-to-screen - // matrix (viewGetWorldToScreenMat; mathfMulVec4x4: each row's xyz dot the point, plus its w), divided by w: - // out = (x / w, y / w, w, z / w). - constexpr uint32_t kViewTranslations = 0x4a1240u, kViewMatrices = 0x4e0230u; - void project(const uint8_t *rdram, uint32_t view, const float p[4], float out[4]) - { - const uint32_t translation = kViewTranslations + view * 0xf0u, matrix = kViewMatrices + view * 64u; - float q[3], r[4]; - for (int k = 0; k < 3; ++k) - q[k] = p[k] + flt(rdram, translation + 4u * k); - for (int row = 0; row < 4; ++row) - r[row] = flt(rdram, matrix + 16u * row) * q[0] + flt(rdram, matrix + 16u * row + 4u) * q[1] + flt(rdram, matrix + 16u * row + 8u) * q[2] + - flt(rdram, matrix + 16u * row + 12u); - static const bool s_log = std::getenv("TMB_NATIVE_LOG_HUD") != nullptr; - static uint32_t s_logs = 0; - if (s_log && s_logs++ % 400u == 0u && s_logs < 4000u) - { - std::fprintf(stderr, "[tmb:2d] view %u translation (%.1f %.1f %.1f %.1f) at %#x, matrix at %#x:", view, flt(rdram, translation), flt(rdram, translation + 4u), - flt(rdram, translation + 8u), flt(rdram, translation + 12u), translation, matrix); - for (int k = 0; k < 16; ++k) - std::fprintf(stderr, " %.3f", flt(rdram, matrix + 4u * k)); - std::fprintf(stderr, "%s", "\n"); - } - const float inverse = 1.0f / r[3]; - out[0] = r[0] * inverse; - out[1] = r[1] * inverse; - out[2] = r[3]; - out[3] = r[2] * inverse; - } - - // GetIdColor__3HudiPUcT2T2: a car's colour by its id. - uint32_t idColour(uint32_t id) - { - switch (id) - { - case 0x20: return rgba(0x31, 0x5b, 0x01, 0); - case 0x40: return rgba(0xdd, 0xbf, 0x28, 0); - case 0x60: return rgba(0x34, 0x42, 0xff, 0); - case 0x80: return rgba(0x5f, 0xaa, 0xba, 0); - case 0xa0: return rgba(0x84, 0x47, 0x1b, 0); - case 0xc0: return rgba(0xd0, 0x8f, 0xcd, 0); - case 0xe0: return rgba(0xcc, 0xb9, 0xe1, 0); - case 0x100: return rgba(0x7a, 0x64, 0x3d, 0); - case 0x120: return rgba(0x75, 0x3d, 0xb4, 0); - case 0x140: return rgba(0xa4, 0x1f, 0x26, 0); - case 0x160: return rgba(0x4e, 0x44, 0x99, 0); - case 0x180: return rgba(0x7f, 0xa1, 0x5c, 0); - case 0x1a0: return rgba(0x4b, 0xe9, 0x47, 0); - case 0x1c0: return rgba(0x86, 0x5c, 0x00, 0); - case 0x1e0: return rgba(0xff, 0x60, 0x00, 0); - case 0x200: return rgba(0xa4, 0x1f, 0x26, 0); - case 0x220: return rgba(0xff, 0x60, 0x00, 0); - case 0x13e2: return rgba(0x64, 0x64, 0x64, 0); - default: return rgba(0xff, 0xff, 0xff, 0); - } - } - - // mathfManhatDist: the largest of |dx|, |dy|, |dz|, plus 0.34375 the middle one and 0.25 the smallest. - float manhattan(const uint8_t *rdram, uint32_t a, uint32_t b) - { - float d[3]; - for (int k = 0; k < 3; ++k) - d[k] = std::fabs(flt(rdram, b + 4u * k) - flt(rdram, a + 4u * k)); - std::sort(d, d + 3); - return d[2] + d[1] * 0.34375f + d[0] * 0.25f; - } - - // BuildRadarStuff's own primitives (its health bars come through BuildHealthBar): the blips, then a triangle - // over each enemy on screen. Drawn before the game's builder runs, which clears the enemies' hit flags. - void radar(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, uint32_t hud, uint32_t viewIndex) - { - const uint32_t gp = noteGp(getRegU32(ctx, 28)); - // Part A: the blips (Hud + 0x1c of them), around the radar's centre (Hud + 0x800 / 0x804, pixels). - const int32_t centreX = static_cast(word(rdram, hud + 0x800u)) << 4, centreY = static_cast(word(rdram, hud + 0x804u)) << 4; - const uint32_t blips = std::min(word(rdram, hud + 0x1cu), 100u); - for (uint32_t i = 0; i < blips; ++i) - { - if (rdram[(hud + 0x534u + i) & 0x1ffffffu] == 0u) - continue; - const float x = static_cast(centreX + static_cast(word(rdram, hud + 0x20u + 4u * i))) / 16.0f; - const float y = static_cast(centreY - static_cast(word(rdram, hud + 0x1b0u + 4u * i))) / 16.0f; - const uint32_t r = rdram[(hud + 0x340u + i) & 0x1ffffffu], g = rdram[(hud + 0x3a4u + i) & 0x1ffffffu], b = rdram[(hud + 0x408u + i) & 0x1ffffffu]; - switch (word(rdram, hud + 0x5e4u + 4u * i)) - { - case 0: - hudSprite(x - 15.0f / 16.0f, y + 15.0f / 16.0f, x + 15.0f / 16.0f, y - 15.0f / 16.0f, rgba(r, g, b, 0xff), true); - break; - case 1: - hudLine(x - 5.0f, y, x + 6.0f, y, rgba(0xff, 0, 0, 0xff), false); - hudLine(x - 0.5f, y + 3.0f, x - 0.5f, y - 3.0f, rgba(0xff, 0, 0, 0xff), false); - hudLine(x + 0.5f, y + 3.0f, x + 0.5f, y - 3.0f, rgba(0xff, 0, 0, 0xff), false); - break; - case 2: - hudLine(x - 4.5f, y, x + 4.5f, y, rgba(r, g, b, 0xff), false); - hudLine(x - 0.5f, y + 2.25f, x - 0.5f, y - 2.25f, rgba(r, g, b, 0xff), false); - hudLine(x + 0.5f, y + 2.25f, x + 0.5f, y - 2.25f, rgba(r, g, b, 0xff), false); - break; - default: - break; - } - } - - // Part B: a triangle over each enemy on screen, its car's colour (red when a threat is near it). - const uint32_t game = word(rdram, gp + kGpGame), settings = word(rdram, gp + kGpSettings); - const uint32_t player = word(rdram, hud + 0x5e0u); - const uint32_t cars = word(rdram, game + 0x1b3db4u); - const View clipView = viewOf(rdram, viewIndex); - const uint32_t current = word(rdram, gp + kGpCurView); - for (uint32_t i = 0; i < cars && i < 64u; ++i) - { - const uint32_t car = game + i * kVehicleBytes; - if (word(rdram, car + 0x20b0u) == word(rdram, player + 0x20b0u) || byte(rdram, car + 0x487u) || byte(rdram, car + 0x475u)) - continue; - const uint32_t id = word(rdram, car + 0x20a8u); - if (word(rdram, car + 0x580u) - 1u >= 2u && !(id == 0x200u && word(rdram, game + 0x1ab430u) == 3u)) - continue; - uint32_t colour = idColour(id); - if (static_cast(word(rdram, game + 0x1b3db8u)) >= 3 && word(rdram, settings + kSetTeams) == 1u) - colour = word(rdram, settings + kSetTeam + 4u * i) == 0u ? rgba(0x1a, 0x8e, 0x28, 0) : rgba(0xff, 0xff, 0xff, 0); - const uint32_t threats[3] = {0x19bbc8u, 0x19bc0cu, 0x19bc30u}; - for (uint32_t k = 0; k < 4u; ++k) - for (int t = 0; t < 3; ++t) - { - const uint32_t object = word(rdram, game + threats[t] + 4u * k); - if (object && word(rdram, object + 0xcu) && manhattan(rdram, car + 0x1d0u, object + 0x10u) < flt(rdram, gp + kGpThreat[t])) - colour = rgba(0xff, 0, 0, 0); - } - if (word(rdram, player + 0x20a8u) == 0x120u && word(rdram, player + 0x24d0u)) - { - const uint32_t target = word(rdram, word(rdram, player + 0x24d0u) + 0x130u) + 0x10u; - if (manhattan(rdram, car + 0x1d0u, target) < flt(rdram, gp + kGpThreat[3])) - colour = rgba(0xff, 0, 0, 0); - } - if (word(rdram, car + 0x24bcu)) - colour = rgba(0xff, 0, 0, 0); - // The point over the car, projected as the game does (mathfTransform3dTo2d). - const uint32_t at = id == 0x200u ? word(rdram, game + 0x1ab500u) + 0x10u : car + 0x1d0u; - float p[4] = {flt(rdram, at), flt(rdram, at + 4u), flt(rdram, at + 8u), flt(rdram, at + 12u)}; - p[2] += (id == 0xc0u && word(rdram, car + 0x243cu)) ? 20.0f : id == 0x200u ? -75.0f : 10.0f; - float s[4]; - project(rdram, current, p, s); - const float sx = std::round(s[0]), sy = std::round(s[1]); - // TMB_NATIVE_LOG_HUD=1: now and then, each car's projected marker and whether it shows. - static const bool s_logHud = std::getenv("TMB_NATIVE_LOG_HUD") != nullptr; - static uint32_t s_hudLogs = 0; - if (s_logHud && s_hudLogs++ % 97u == 0u && s_hudLogs < 4000u) - std::fprintf(stderr, "[tmb:2d] radar car %u id %#x: p (%.1f %.1f %.1f) -> (%.1f %.1f) w %.2f, view %d %d %dx%d, hidden %d%s", i, id, p[0], - p[1], p[2], s[0], s[1], s[2], clipView.cx, clipView.cy, clipView.w, clipView.h, byte(rdram, car + 0x480u), "\n"); - if (s[2] <= 1.0f || s[0] < clipView.cx - clipView.w * 0.5f || s[0] > clipView.cx + clipView.w * 0.5f || - s[1] < clipView.cy - clipView.h * 0.5f || s[1] > clipView.cy + clipView.h * 0.5f || byte(rdram, car + 0x480u)) - continue; - uint32_t alpha = 0x80; - if (id != 0x200u && word(rdram, settings + kSetFade) == 1u) - { - // the distance in the player's frame, in its plane (mathfMulVec by the player's rotation) - float d[3], local[3] = {0, 0, 0}; - for (int k = 0; k < 3; ++k) - d[k] = flt(rdram, player + 0x1d0u + 4u * k) - flt(rdram, car + 0x1d0u + 4u * k); - for (int row = 0; row < 3; ++row) - for (int k = 0; k < 3; ++k) - local[row] += flt(rdram, player + 0xd0u + 16u * row + 4u * k) * d[k]; - const double distance = std::sqrt(local[0] * local[0] + local[1] * local[1]); - if (distance > 600.0) - alpha = distance > 2000.0 ? 0x1eu - : static_cast(static_cast((dbl(rdram, kAlphaConstants) - distance) / dbl(rdram, kAlphaConstants + 8u) * - dbl(rdram, kAlphaConstants + 16u)) + 0x1e); - } - colour = (colour & 0xffffffu) | (std::min(alpha, 0xffu) << 24); - const bozo::render::Vertex v[3] = {vertex(sx - 12.0f, sy - 6.0f, colour), vertex(sx, sy, colour), vertex(sx + 12.0f, sy - 6.0f, colour)}; - hudTriangles(v, 3u, true); - } - } - - void radarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4); - if (on()) - radar(rdram, ctx, runtime, hud, getRegU32(ctx, 6)); - BuildRadarStuff__3HudP6QwDatai_0x13eb40(rdram, ctx, runtime); - if (on()) - setWord(rdram, hud + 4u, 1u); - } - - // BuildHealthBar(hud, packet, x, y, w, h, car): a bar measured from the current view's bottom-left corner, filling - // from its right end, green / yellow / red by the health left. - void healthBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), car = getRegU32(ctx, 10); - const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); - const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); - const uint32_t gp = noteGp(getRegU32(ctx, 28)); - BuildHealthBar__3HudP6QwDataiiiiP7Vehicle_0x141af0(rdram, ctx, runtime); - if (!on()) - return; - const uint32_t game = word(rdram, gp + kGpGame); - int32_t fill = 0; - if (word(rdram, game + 0x1b3db0u) == 20u && word(rdram, game + 0x1ab500u) && word(rdram, car + 0x20a8u) == 0x200u) - { - const int32_t current = static_cast(word(rdram, game + 0x1ab43cu)), most = static_cast(word(rdram, game + 0x1ab438u)); - fill = most ? std::min((w - 4) * current / most + 1, w - 4) : 0; - if (current <= 0) - fill = 0; - } - else - { - const float hp = flt(rdram, car + 0x3f4u), most = flt(rdram, car + 0x3f0u); - fill = most != 0.0f ? std::min(static_cast(static_cast(w - 4) * hp / most + 1.0f), w - 4) : 0; - if (hp <= 0.0f) - fill = 0; - } - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float left = static_cast(v.cx - v.w / 2 + x), top = static_cast(v.cy + v.h / 2 - y); - hudSprite(left, top, left + w, top + h, rgba(0, 0, 0, 0x40), true); - const uint32_t colour = word(rdram, hud + 0x5ccu) ? rgba(0, 0, 0, 0x40) - : rgba(word(rdram, hud + 0x5c0u), word(rdram, hud + 0x5c4u), 0, 0x40); - const float right = left - 2.0f + w; - hudSprite(right - fill, top + 1.0f, right, top + h - 1.0f, colour, true); - } - - // BuildSeparator: the black line between the two views of a split screen (drawn by view 0's HUD). - void separatorOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - BuildSeparator__3HudP6QwData_0x13e140(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const int display = screenDisplay(rdram); - if (display == 0 || word(rdram, gp + kGpCurView) != 0u) - return; - const View v = viewOf(rdram, 0); - const bool rearLarge = word(rdram, gp + kGpRearLarge) != 0u; - float x0 = 0, y0 = 0; - if (display == 2) - { - x0 = static_cast(v.cx - v.w / 2); - y0 = static_cast(rearLarge ? v.cy - v.h / 2 : v.cy + v.h / 2 - 2); - } - else - { - x0 = static_cast(v.cx + v.w / 2 - 2); - y0 = static_cast(v.cy - v.h / 2); - } - const float x1 = static_cast(v.cx + v.w / 2), y1 = static_cast(rearLarge ? v.cy - v.h / 2 + 2 : v.cy + v.h / 2); - hudSprite(x0, y0, x1, y1, rgba(0, 0, 0, 0x80), false); - } - - // BuildRearViewEdge(hud, packet, view): the black frame around the small rear view. - void rearViewEdgeOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), viewIndex = getRegU32(ctx, 6); - BuildRearViewEdge__3HudP6QwDatai_0x13e3e0(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const View v = viewOf(rdram, viewIndex); - const float l = static_cast(v.cx - v.w / 2 - 3), r = l + v.w + 1, t = static_cast(v.cy - v.h / 2), b = t + v.h; - const uint32_t black = rgba(0, 0, 0, 0x80); - hudSprite(l, t, r, t + 1, black, false); - hudSprite(r, t, r + 1, b, black, false); - hudSprite(r, b, l, b - 1, black, false); - hudSprite(l + 3, b - 1, l + 4, t + 1, black, false); - } - - // boundFAngle: an angle into [-pi, pi). - float boundAngle(float a) - { - constexpr float kPi = 3.14159265f, kTwoPi = 6.28318531f; - return a - kTwoPi * std::floor((a + kPi) / kTwoPi); - } - // mathfRotMatrixRPH(m, angles): the rotation of angles (x, y, z) (sines and cosines as the game combines them), - // rows of three. - void rotationRph(const float angles[3], float m[3][3]) - { - const float sx = std::sin(angles[0]), cx = std::cos(angles[0]), sy = std::sin(angles[1]), cy = std::cos(angles[1]); - const float sz = std::sin(angles[2]), cz = std::cos(angles[2]); - m[0][0] = cy * cz + sy * sx * sz; - m[0][1] = -cy * sz + sy * sx * cz; - m[0][2] = -sy * cx; - m[1][0] = cx * sz; - m[1][1] = cx * cz; - m[1][2] = sx; - m[2][0] = sy * cz - cy * sx * sz; - m[2][1] = -sy * sz - cy * sx * cz; - m[2][2] = cy * cx; - } - constexpr uint32_t kLaserOffsets = 0x4e6ef0u; // {0.006, -7.05, 4.08}, then {0.016, 9.204, 1.649} - - // BuildLaserStuff: the laser sight, a line from the gun (the car's frame by one offset, then its turret's angles - // by another) to its target (car + 0x2438), both projected as mathfTransform3dTo2d; alpha 0x1a red. - void laserOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - BuildLaserStuff__3HudP6QwData_0x1425b8(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const uint32_t car = word(rdram, hud + 0x5e0u), target = word(rdram, car + 0x2438u); - if (!car || !target) - return; - const uint32_t body = word(rdram, car + 0x2018u); - float p[4] = {flt(rdram, car + 0x1d0u), flt(rdram, car + 0x1d4u), flt(rdram, car + 0x1d8u), 1.0f}; - const float c1[3] = {flt(rdram, kLaserOffsets), flt(rdram, kLaserOffsets + 4u), flt(rdram, kLaserOffsets + 8u)}; - const float c2[3] = {flt(rdram, kLaserOffsets + 16u), flt(rdram, kLaserOffsets + 20u), flt(rdram, kLaserOffsets + 24u)}; - for (int k = 0; k < 3; ++k) // mathfMulTransVec(body + 0x20, c1): rows weighted by c1 - p[k] += flt(rdram, body + 0x20u + 4u * k) * c1[0] + flt(rdram, body + 0x30u + 4u * k) * c1[1] + flt(rdram, body + 0x40u + 4u * k) * c1[2]; - float angles[3], r[3][3]; - for (int k = 0; k < 3; ++k) - angles[k] = boundAngle(flt(rdram, car + 0x23d0u + 4u * k) + flt(rdram, body + 0x60u + 4u * k)); - rotationRph(angles, r); - for (int k = 0; k < 3; ++k) - p[k] += r[0][k] * c2[0] + r[1][k] * c2[1] + r[2][k] * c2[2]; - const uint32_t view = word(rdram, gp + kGpCurView); - float a[4], b[4]; - const float q[4] = {flt(rdram, target + 0x10u), flt(rdram, target + 0x14u), flt(rdram, target + 0x18u), 1.0f}; - project(rdram, view, p, a); - project(rdram, view, q, b); - hudLine(std::trunc(a[0]), std::trunc(a[1]), std::trunc(b[0]), std::trunc(b[1]), rgba(0xff, 0x28, 0x28, 0x1a), true); - } - // build4PTurboBar / build4PEnergyBar(hud, packet, x, y, w, h): a horizontal bar of the current view's bottom-left - // corner (y up from its bottom), filling from its right end; opaque. - void horizontalBar4p(uint8_t *rdram, uint32_t gp, int32_t x, int32_t y, int32_t w, int32_t h, int32_t fill, uint32_t colour) - { - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float x0 = static_cast(v.cx - v.w / 2 - 2 + x + w - fill), y0 = static_cast(v.cy + v.h / 2 + 1 - y); - hudSprite(x0, y0, x0 + fill, y0 - 2 + h, colour, false); - } - void turbo4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); - const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); - build4PTurboBar__3HudP6QwDataiiii_0x141338(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const float turbo = flt(rdram, word(rdram, hud + 0x5e0u) + 0x410u); - const int32_t fill = turbo <= 0.0f ? 0 : std::min(static_cast(static_cast(w - 4) * turbo / 100.0f + 1.0f), w - 4); - horizontalBar4p(rdram, gp, x, y, w, h, fill, rgba(0x14, 0x58, 0x80, 0x20)); - } - void energy4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); - const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); - build4PEnergyBar__3HudP6QwDataiiii_0x1418a8(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const uint32_t car = word(rdram, hud + 0x5e0u); - const int32_t current = static_cast(word(rdram, car + 0x2214u)), most = static_cast(word(rdram, car + 0x2218u)); - const int32_t fill = current <= 0 || most == 0 ? 0 : std::min((w - 4) * current / most + 1, w - 4); - horizontalBar4p(rdram, gp, x, y, w, h, fill, rgba(0x89, 0x44, 0x20, 0x20)); - } - // build4PHealthBar(hud, packet, x, y, w, h): a vertical bar rising from the current view's bottom edge (y up), red / - // yellow / green by the health left; blended. - void health4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); - const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); - build4PHealthBar__3HudP6QwDataiiii_0x1415a0(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const uint32_t car = word(rdram, hud + 0x5e0u); - const float hp = flt(rdram, car + 0x3f4u), most = flt(rdram, car + 0x3f0u); - const int32_t fill = hp <= 0.0f || most == 0.0f ? 0 : std::min(static_cast(static_cast(h - 4) * hp / most + 1.0f), h - 4); - const uint32_t colour = word(rdram, hud + 0x5ccu) ? rgba(0, 0, 0, 0x3f) - : rgba(word(rdram, hud + 0x5c0u), word(rdram, hud + 0x5c4u), word(rdram, hud + 0x5c8u), 0x40); - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float x0 = static_cast(v.cx - v.w / 2 + x), y0 = static_cast(v.cy + v.h / 2 - (y + fill)); - hudSprite(x0, y0, x0 + w, y0 + fill, colour, true); - } - - constexpr uint32_t kChargeUp = 0x00140AA8u; - - // BuildChargeUpBar(hud, packet): the charge (car + 0x220c of car + 0x2210) as a bar 4 pixels high, 108 long at - // full charge, from 54 pixels left of the current view's centre, 10 to 14 pixels above its bottom edge; ABE, alpha - // 0x30. Its colour is the Hud's (+ 0x5a0 red, + 0x5a4 green, blue 0): green under half charge, easing to yellow - // under 75%, then to red (smoothEasyIn, state the game's builder keeps); from 85% it blinks black (+ 0x5a8 set - // for 15 of every 30 frames, counted at + 0x5ac). - void chargeUpOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - BuildChargeUpBar__3HudP6QwData_0x140aa8(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - const uint32_t car = word(rdram, hud + 0x5e0u); - const int32_t charge = static_cast(word(rdram, car + 0x220cu)), most = static_cast(word(rdram, car + 0x2210u)); - if (most == 0) - return; - const int32_t length = charge * 108 / most; - const uint32_t colour = word(rdram, hud + 0x5a8u) ? rgba(0, 0, 0, 0x30) : rgba(word(rdram, hud + 0x5a0u), word(rdram, hud + 0x5a4u), 0, 0x30); - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float x0 = static_cast(v.cx - 54), y0 = static_cast(v.cy + v.h / 2 - 14); - hudSprite(x0, y0, x0 + length, y0 + 4.0f, colour, true); - } - - // in install(): - - constexpr uint32_t kOverheat = 0x00140DF8u; - - // BuildOverheatBar(hud, packet): a small lamp right of the current view's centre, its colour by the heat of the - // car's weapon (car + 0x2220 of car + 0x2224, in percent): the game's own builder eases Hud + 0x5b0 (red) and - // Hud + 0x5b4 (green) between green (under 50), yellow (under 75), orange to red (under 85), and red over that, - // when Hud + 0x5b8 blinks it off (on 15 frames of every 30, counted by Hud + 0x5bc). Two blended sprites: a - // black backing of 20 x 7, then the lamp of 16 x 5 inside it (black while blinked off); alpha 0x30. - void overheatOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); - BuildOverheatBar__3HudP6QwData_0x140df8(rdram, ctx, runtime); - if (!on()) - return; - setWord(rdram, hud + 4u, 1u); - // From the current view's centre: 30 left of its right edge, 40 under its centre (10 over it when the - // screen is split one view over the other). - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float x = static_cast(v.cx + (v.w >> 1) - 30), y = static_cast(screenDisplay(rdram) == 2 ? v.cy - 10 : v.cy + 40); - hudSprite(x, y, x + 20.0f, y + 7.0f, rgba(0, 0, 0, 0x30), true); - const uint32_t colour = word(rdram, hud + 0x5b8u) ? rgba(0, 0, 0, 0x30) - : rgba(word(rdram, hud + 0x5b0u), word(rdram, hud + 0x5b4u), 0, 0x30); - hudSprite(x + 2.0f, y + 1.0f, x + 18.0f, y + 6.0f, colour, true); - } - - void separator4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t hud = getRegU32(ctx, 4); - Build4pSeparater__3HudP6QwDatai_0x13e838(rdram, ctx, runtime); - if (on()) - setWord(rdram, hud + 4u, 1u); - } - - // ---- the loading bar (Shell::LoadLevelFiles): buildProgressBar and, on the loads without the shell, the vblank - // callback that sends it between the load's steps; drawn and published here, as no game frame ends meanwhile ---- - constexpr uint32_t kBuildProgressBar = 0x001FC2A8u, kBarVSync = 0x00202238u, - kInformProgressBar = 0x001FC8D0u; - constexpr int32_t kGpBarMode = -0x3290, kGpBarFlip = -0x328c, kGpBarShown = -0x3280, kGpBarProgress = -0x327c; - std::atomic g_barGp{0}; // the game's gp at buildProgressBar (the vblank callback's own may differ) - - // The bar over view 0 (initProgressBar's viewCreate: 0x11 on the first load after the shell, a frame view; 0x12 - // on the others, a field view): the fill (0x4c, 0x1a, 0x0d), progress / 1024 of its width, over the top half of - // the view (first load) or, 6 and 2 smaller, the whole of it over a dark track (0x13, 6, 0x10); opaque. - // Published mapped by view 0's frame buffer (its own rectangle is the bar's). - void loadingBar(uint8_t *rdram, uint32_t gp) - { - const bool track = word(rdram, gp + kGpBarMode) != 0u; - const int32_t progress = static_cast(std::min(word(rdram, gp + kGpBarProgress), 0x400u)); - View v = viewOf(rdram, 0); - if (track) - v.w -= 6, v.h -= 2; - const int32_t left = v.cx - (v.w >> 1), top = v.cy - (v.h >> 1); - if (track) - hudSprite(static_cast(left), static_cast(top), static_cast(left + v.w), static_cast(top + v.h), - rgba(0x13, 0x06, 0x10, 0x80), false); - const int32_t bottom = track ? top + v.h : top + (v.h >> 1); - hudSprite(static_cast(left), static_cast(top), static_cast(left + ((v.w * progress) >> 10)), - static_cast(bottom), rgba(0x4c, 0x1a, 0x0d, 0x80), false); - const uint32_t def = word(rdram, kViews + 4u); - const float width = half(rdram, def + 8u), height = half(rdram, def + 0xau); - bozo::render::Screen screen; - screen.width = width > 0.0f ? width : 640.0f; - screen.height = height > 0.0f ? height : 448.0f; - screen.originX = 2048.0f - screen.width * 0.5f; - screen.originY = 2048.0f - screen.height * 0.5f; - bozo::render::Renderer::instance().publishOverlay(screen); - } - - // buildProgressBar(progress): the bar at min(progress, 1024) / 1024, drawn instead of sent. - void buildProgressBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (!on()) - { - buildProgressBar__FUi_0x1fc2a8(rdram, ctx, runtime); - return; - } - const uint32_t gp = noteGp(getRegU32(ctx, 28)); - g_barGp.store(gp, std::memory_order_relaxed); - g_rdram.store(rdram, std::memory_order_relaxed); - if (getRegU32(ctx, 4) == 0u) // a load's start: the picture the menus were drawn over is gone - { - std::lock_guard lock(g_movieMutex); - g_menuPicture.reset(); - bozo::render::clearDisplayPicture(); - } - setWord(rdram, gp + kGpBarProgress, std::min(getRegU32(ctx, 4), 0x400u)); - loadingBar(rdram, gp); - ctx->pc = getRegU32(ctx, 31); // jr $ra - } - - // informProgressBar(fraction): a load's step done; it works out the progress and hands it to buildProgressBar - // with a tail jump, which the recompiled code makes a direct call (past buildProgressBarOverride): the game's - // own buildProgressBar runs and keeps the progress (gp - 0x327c), its packet sent unread; the bar drawn here. - void informProgressBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t gp = getRegU32(ctx, 28); - informProgressBar__Ff_0x1fc8d0(rdram, ctx, runtime); - if (!on()) - return; - noteGp(gp); - g_barGp.store(gp, std::memory_order_relaxed); - g_rdram.store(rdram, std::memory_order_relaxed); - loadingBar(rdram, gp); - } - - // finishShellLoop (a memory card save started from a match's overlay): the current view darkened by a quarter - // (black, alpha 0x21, the font's (Cs - Cd) As + Cd), over the overlay's text; drawn instead of sent. - constexpr uint32_t kFinishShellLoop = 0x0019F790u; - void finishShellLoopOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (!on()) - { - finishShellLoop__Fv_0x19f790(rdram, ctx, runtime); - return; - } - const View v = viewOf(rdram, word(rdram, getRegU32(ctx, 28) + kGpCurView)); - const float left = static_cast(v.cx - (v.w >> 1)), top = static_cast(v.cy - (v.h >> 1)); - hudSprite(left, top, left + static_cast(v.w), top + static_cast(v.h), rgba(0, 0, 0, 0x21), true); - g_flushed.store(true, std::memory_order_relaxed); - publish(); - ctx->pc = getRegU32(ctx, 31); // jr $ra - } - - // displayDialog's darkening, after the overlay's text (its font flush): the current view a quarter darker - // towards (0, 0, 10) (alpha 0x21, the font's (Cs - Cd) As + Cd). Its kick is patched out (dialogKick). - void dialogDim(uint8_t *rdram, uint32_t gp) - { - if (gp == 0u) - return; - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - const float left = static_cast(v.cx - (v.w >> 1)), top = static_cast(v.cy - (v.h >> 1)); - hudSprite(left, top, left + static_cast(v.w), top + static_cast(v.h), rgba(0, 0, 0x0a, 0x21), true); - } - // bozo:store kDialogKick (the generated code sets ctx->pc before that store: tools/tmb_overrides_list.py) - bool dialogKick(uint32_t pc, uint32_t address, uint32_t) - { - return pc == kDialogKick && address == 0x1000a000u && on(); - } - - // ---- movies: the pictures the MPEG decoder hands to sceMpegGetPicture, shown under the 2D by loadImage (each - // vblank while a movie plays) instead of the GS image transfers the game built of them ---- - constexpr uint32_t kLoadImage = 0x001DF838u; - // handler_endimage's work (the GIF DMA end interrupt the transfer raised): with the picture still held (the flag at - // gp + kImageHeld), voBufDecCount on the movie's picture buffer frees it for the decoder. - constexpr uint32_t kVoBufDecCount = 0x001FEF58u, kVoBuf = 0x004C4A18u; - constexpr int32_t kImageHeld = -0x36d8; - - void moviePicture(uint32_t, uint32_t width, uint32_t height, const uint8_t *rgba) - { - static uint64_t s_version = 0; - bozo::render::Texture picture; - picture.width = width; - picture.height = height; - picture.key = 0x4d4f5649u; // one picture at a time: its GPU copy replaced - picture.version = ++s_version; - picture.rgba.resize(static_cast(width) * height); - std::memcpy(picture.rgba.data(), rgba, picture.rgba.size() * 4u); - auto shared = std::make_shared(std::move(picture)); - std::lock_guard lock(g_movieMutex); - g_moviePicture = std::move(shared); - } - - // loadImage(chain): the last picture, centred in the frame (as dispSetTags places it: a 640 x 448 frame in NTSC, - // 640 x 512 in PAL); no transfer. It goes in the buffer the display reads through circuit 2: the shell's menus - // are drawn over it with alpha 0 where it shows (PMODE merges the circuits by the frame's alpha), and it stays - // there after the clip ends (blitLastMovieFrame) until a load starts. A movie on its own (no menu frames) is - // also shown under the overlay. - void showOnCircuit2(const bozo::render::Texture &picture) - { - constexpr uint32_t kFrameWidth = 640u, kFrameHeight = 448u; - auto frame = std::make_shared>(static_cast(kFrameWidth) * kFrameHeight, 0x80000000u); - const uint32_t width = std::min(picture.width, kFrameWidth), height = std::min(picture.height, kFrameHeight); - const uint32_t x0 = (kFrameWidth - width) / 2u, y0 = (kFrameHeight - height) / 2u; - for (uint32_t y = 0; y < height; ++y) - for (uint32_t x = 0; x < width; ++x) - (*frame)[(y0 + y) * kFrameWidth + x0 + x] = (picture.rgba[y * picture.width + x] & 0x00ffffffu) | 0x80000000u; - bozo::render::setDisplayPicture(std::move(frame), kFrameWidth, kFrameHeight); - } - +// TMB's 2D drawn natively, its builders rewritten from the game's code: each draws from the game's own variables +// (Renderer::drawOverlay, published with the frame), and none of them sends GS packets. TMB_NATIVE_2D=0: the game's +// own builders (their GS packets) instead. +// +// The font (fontBuildPrim, fontDmaFontData): fontSpritePrint* call fontBuildPrim for each printable character, which +// adds a sprite at the font's cursor (records of 0x20 bytes at 0x504540 USA, 0x38 at 0x50caf0 PAL, by font size: +0 +// cell width, +2 cell height, +4 / +6 the glyph's size in the texture, +8 / +0xa on screen, +0xe the advance, +0x10 / +// +0x12 the cursor, +0x18 the colour; 12.4 fixed point, the cursor from the current view's top-left corner) to the +// font's packet, which fontDmaFontData sends to the GS. Here the same sprite is drawn natively, and fontDmaFontData +// only resets what it would after sending (the font's texture from the texture pack: no upload). + +#include "tmb_port.h" +#include "bozo/render/renderer.h" +#include "bozo/render/texture.h" +#include "bozo/render/movie.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tmb::native +{ + bool enabled(); +} + +namespace tmb::textures +{ + std::shared_ptr font(); +} + +namespace tmb::native +{ + bool menusDrawn(); +} + +namespace tmb::twod +{ + void publish(); + + namespace + { + // The movie pictures (sceMpegGetPicture, below), shared by loadImage and the loading bar. + std::mutex g_movieMutex; + std::shared_ptr g_moviePicture; // under g_movieMutex + // The picture loadImage last put in the display buffers (under g_movieMutex): the one shown through the display's + // circuit 2 (bozo::render::setDisplayPicture). + std::shared_ptr g_menuPicture; + std::atomic g_imageReplaced{false}; // loadImage drew a picture instead of transferring it (this vblank) + + constexpr uint32_t kFontBuildPrim = 0x001C4918u; + // displayDialog (a match's pause, won / lost and results overlays): where its loop flushes the font, and its D2 + // kick of the darkening sprite that follows (inline; its offsets differ between the regions). + constexpr uint32_t kDialogFontReturn = 0x163940u, kDialogKick = 0x163a50u; + constexpr uint32_t kFontDmaFontData = 0x001C3FB8u; + constexpr uint32_t kFontRecords = 0x504540u, kFontRecordBytes = 0x20u; + constexpr uint32_t kViews = 0x4dfcd0u; + constexpr int32_t kGpNumViews = -0x322c; + constexpr int32_t kGpCurView = -0x3228, kGpFontMode = -0x3034, kGpFontUpload = -0x3630, kGpFontCount = -0x303c, + kGpFontAt = -0x3038, kGpFontTagAt = -0x3030, kGpFontStart = -0x302c; + + // The font's packet "sent" (fontDmaFontData) since the last publish: the frame's 2D is complete. + std::atomic g_flushed{false}; + std::atomic g_rdram{nullptr}; // guest memory, from the font's hooks (the publish has none) + std::atomic g_gp{0}; // the game's gp, from the same hooks + uint32_t noteGp(uint32_t gp) // an override's gp, kept for those read where no register is at hand (viewClip) + { + g_gp.store(gp, std::memory_order_relaxed); + return gp; + } + + bool on() + { + static const bool s_on = [] + { + const char *value = std::getenv("TMB_NATIVE_2D"); + return !(value && *value == '0'); + }(); + return s_on && tmb::native::enabled(); + } + + 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 setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1fffffcu), &value, 4); } + void setHalf(uint8_t *rdram, uint32_t address, uint16_t value) { std::memcpy(rdram + (address & 0x1fffffeu), &value, 2); } + + // fontBuildPrim(size, character, packet): one glyph at the font's cursor, which then advances. + void fontBuildPrimOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (!on()) + { + fontBuildPrim__FicP6QwData_0x1c4918(rdram, ctx, runtime); + return; + } + const uint32_t gp = noteGp(getRegU32(ctx, 28)); + const uint32_t record = kFontRecords + getRegU32(ctx, 4) * kFontRecordBytes; + int32_t c = static_cast(getRegU32(ctx, 5) & 0xffu); + // The current view's top-left corner, as viewGetCenter / viewGetWH give it. + const uint32_t view = word(rdram, gp + kGpCurView); + const uint32_t viewport = word(rdram, kViews + view * 16u + 4u); + const int32_t centreX = static_cast(word(rdram, viewport + 0x18u)), centreY = static_cast(word(rdram, viewport + 0x1cu)); + const int32_t viewW = half(rdram, viewport + 4u), viewH = half(rdram, viewport + 6u); + const int32_t left = centreX * 16 - viewW * 8, top = centreY * 16 - viewH * 8; + if (c >= 'a' && c <= 'z') + c -= 0x20; + const int32_t glyph = c - 0x21, row = glyph >> 3, column = glyph - (row << 3); + const int32_t u0 = half(rdram, record + 0u) * column + 8, v0 = half(rdram, record + 2u) * row + 8; + const int32_t u1 = half(rdram, record + 4u) + u0, v1 = half(rdram, record + 6u) + v0; + const int32_t x0 = static_cast(half(rdram, record + 0x10u) + left), y0 = static_cast(half(rdram, record + 0x12u) + top); + const int32_t x1 = static_cast(half(rdram, record + 8u) + x0), y1 = static_cast(half(rdram, record + 0xau) + y0); + uint32_t rgba; + std::memcpy(&rgba, rdram + record + 0x18u, 4); + + // The sprite as two triangles: positions in GS pixels (12.4 / 16), texture coordinates over the 128 x 128 font. + bozo::render::Vertex corners[4]; + const float xs[2] = {x0 / 16.0f, x1 / 16.0f}, ys[2] = {y0 / 16.0f, y1 / 16.0f}; + const float us[2] = {u0 / 16.0f / 128.0f, u1 / 16.0f / 128.0f}, vs[2] = {v0 / 16.0f / 128.0f, v1 / 16.0f / 128.0f}; + for (int i = 0; i < 4; ++i) + { + corners[i].x = xs[i & 1]; + corners[i].y = ys[i >> 1]; + corners[i].u = us[i & 1]; + corners[i].v = vs[i >> 1]; + corners[i].rgba = rgba; + corners[i].fog = 1.0f; + } + const bozo::render::Vertex triangles[6] = {corners[0], corners[1], corners[2], corners[1], corners[3], corners[2]}; + // fontInitPacket's state: ALPHA (Cs - Cd) As + Cd, TEST alpha greater than 8, TEX1 bilinear. + bozo::render::Material material; + material.textured = true; + material.tex0 = 0xf0f7f0f7u; // the font's own GPU copy + material.blend = bozo::render::Material::Blend::Alpha; + material.alphaTest = true; + material.alphaRef = 8; + material.clampU = material.clampV = true; + // TMB_NATIVE_LOG_2D=1: the first glyphs, where they land. + static const bool s_log = std::getenv("TMB_NATIVE_LOG_2D") != nullptr; + static uint32_t s_logged = 0; + static std::unordered_map s_seen; // each glyph at each place once + const uint64_t place = (static_cast(static_cast(c)) << 40) ^ (static_cast(x0) << 20) ^ static_cast(y0); + if (s_log && s_logged < 6000u && !s_seen[place] && (s_seen[place] = true) && ++s_logged) + std::fprintf(stderr, "[tmb:2d] glyph %c: (%.1f %.1f)-(%.1f %.1f) uv (%.3f %.3f)-(%.3f %.3f) rgba %08x view %u centre %d %d size %dx%d\n", + static_cast(c), xs[0], ys[0], xs[1], ys[1], us[0], vs[0], us[1], vs[1], rgba, view, centreX, centreY, viewW, viewH); + bozo::render::Renderer::instance().drawOverlay(material, triangles, 6u, tmb::textures::font()); + + // What fontBuildPrim leaves: its sprites' tag started (mode 2, where it would be), the cursor advanced, the + // glyph counted. + if (word(rdram, gp + kGpFontMode) != 2u) + { + setWord(rdram, gp + kGpFontMode, 2u); + setWord(rdram, gp + kGpFontTagAt, word(rdram, gp + kGpFontAt)); + } + setHalf(rdram, record + 0x10u, static_cast(half(rdram, record + 0x10u) + half(rdram, record + 0xeu))); + setWord(rdram, gp + kGpFontCount, word(rdram, gp + kGpFontCount) + 1u); + ctx->pc = getRegU32(ctx, 31); // jr $ra + } + + void dialogDim(uint8_t *rdram, uint32_t gp); + + // fontDmaFontData: what it leaves after sending the font's packet (nothing sent: the glyphs are drawn natively). + void fontDmaFontDataOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (!on()) + { + fontDmaFontData__Fv_0x1c3fb8(rdram, ctx, runtime); + return; + } + const uint32_t gp = noteGp(getRegU32(ctx, 28)); + dialogDim(rdram, getRegU32(ctx, 31) == kDialogFontReturn ? gp : 0u); + g_rdram.store(rdram, std::memory_order_relaxed); + g_gp.store(gp, std::memory_order_relaxed); + ctx->pc = getRegU32(ctx, 31); // jr $ra + if (word(rdram, gp + kGpFontMode) == 0u) + return; + g_flushed.store(true, std::memory_order_relaxed); + setWord(rdram, gp + kGpFontUpload, 0u); + setWord(rdram, gp + kGpFontMode, 1u); + setWord(rdram, gp + kGpFontCount, 0u); + const uint32_t start = word(rdram, gp + kGpFontStart); + setWord(rdram, gp + kGpFontAt, start); + setWord(rdram, gp + kGpFontTagAt, start - 2u); + } + // ---- the HUD (Hud::Update's builders): flat-coloured sprites, lines and triangles, drawn natively ---- + // + // Each builder override runs the game's own builder (its game logic: the closest enemy, the hit slots, the + // radar's state), then draws what that builder would have sent from the same variables. The packet the game + // builders fill is never sent: each override leaves the Hud's qword count (Hud + 4) at 1, under the 2 that + // Update__3Hudi needs to kick its DMA (whichever builder runs last on each path is overridden). + + constexpr uint32_t kRadar = 0x0013EB40u, kHealthBar = 0x00141AF0u, kSeparator = 0x0013E140u, + kRearViewEdge = 0x0013E3E0u, kLaser = 0x001425B8u, k4pSeparator = 0x0013E838u; + constexpr uint32_t kTurbo4p = 0x00141338u, kEnergy4p = 0x001418A8u, kHealth4p = 0x001415A0u; + constexpr int32_t kGpGame = -0x4154, kGpSettings = -0x4148, kGpRearLarge = -0x3224; + constexpr int32_t kGpThreat[4] = {-0x38bc, -0x38f8, -0x37a4, -0x3760}; + constexpr uint32_t kSetTeams = 0x1a30c, kSetTeam = 0x1a320, kSetFade = 0x1a360, kAlphaConstants = 0x4e6e70u; + constexpr uint32_t kVehicleBytes = 0x2d00; + + float flt(const uint8_t *rdram, uint32_t address) + { + float value; + std::memcpy(&value, rdram + (address & 0x1fffffcu), 4); + return value; + } + double dbl(const uint8_t *rdram, uint32_t address) + { + double value; + std::memcpy(&value, rdram + (address & 0x1fffff8u), 8); + return value; + } + int8_t byte(const uint8_t *rdram, uint32_t address) { return static_cast(rdram[address & 0x1ffffffu]); } + + // A view's centre and size (viewGetCenter / viewGetWH), in GS pixels. + struct View + { + int32_t cx = 2048, cy = 2048, w = 640, h = 448; + }; + View viewOf(const uint8_t *rdram, uint32_t view) + { + View v; + const uint32_t def = word(rdram, kViews + view * 16u + 4u); + v.cx = static_cast(word(rdram, def + 0x18u)); + v.cy = static_cast(word(rdram, def + 0x1cu)); + v.w = half(rdram, def + 4u); + v.h = half(rdram, def + 6u); + return v; + } + // viewGetScreenDisplay: 0 one view, 1 split side by side, 2 split one over the other (view 0's type). + int screenDisplay(const uint8_t *rdram) + { + switch (word(rdram, kViews + 8u)) + { + case 1: case 2: case 5: case 6: case 15: case 16: return 2; + case 3: case 4: case 7: case 8: return 1; + default: return 0; + } + } + + // The HUD's primitives on the overlay: GS pixel coordinates, colours as the GS has them (0x80 is 1.0); ABE: the + // packet's ALPHA_1 (Cs - Cd) As + Cd, else opaque. + void hudTriangles(const bozo::render::Vertex *v, uint32_t count, bool blend) + { + bozo::render::Material material; + material.textured = false; + material.blend = blend ? bozo::render::Material::Blend::Alpha : bozo::render::Material::Blend::Opaque; + bozo::render::Renderer::instance().drawOverlay(material, v, count, nullptr); + } + uint32_t rgba(uint32_t r, uint32_t g, uint32_t b, uint32_t a) { return (r & 0xffu) | ((g & 0xffu) << 8) | ((b & 0xffu) << 16) | ((a & 0xffu) << 24); } + bozo::render::Vertex vertex(float x, float y, uint32_t colour) + { + bozo::render::Vertex v; + v.x = x; + v.y = y; + v.rgba = colour; + v.fog = 1.0f; + return v; + } + // A SPRITE from (x0, y0) to (x1, y1), as the GS fills it (corners in either order). + void hudSprite(float x0, float y0, float x1, float y1, uint32_t colour, bool blend) + { + const float l = std::min(x0, x1), r = std::max(x0, x1), t = std::min(y0, y1), b = std::max(y0, y1); + const bozo::render::Vertex v[6] = {vertex(l, t, colour), vertex(r, t, colour), vertex(l, b, colour), + vertex(r, t, colour), vertex(r, b, colour), vertex(l, b, colour)}; + hudTriangles(v, 6u, blend); + } + // A LINE, one pixel wide. + void hudLine(float x0, float y0, float x1, float y1, uint32_t colour, bool blend) + { + const float dx = x1 - x0, dy = y1 - y0, length = std::sqrt(dx * dx + dy * dy); + if (!(length > 0.0f)) + return; + const float nx = -dy / length * 0.5f, ny = dx / length * 0.5f; + const bozo::render::Vertex v[6] = {vertex(x0 + nx, y0 + ny, colour), vertex(x1 + nx, y1 + ny, colour), vertex(x0 - nx, y0 - ny, colour), + vertex(x1 + nx, y1 + ny, colour), vertex(x1 - nx, y1 - ny, colour), vertex(x0 - nx, y0 - ny, colour)}; + hudTriangles(v, 6u, blend); + } + + // mathfTransform3dTo2d(view, p, out): p plus the view's translation (viewGetWeTrans) through its world-to-screen + // matrix (viewGetWorldToScreenMat; mathfMulVec4x4: each row's xyz dot the point, plus its w), divided by w: + // out = (x / w, y / w, w, z / w). + constexpr uint32_t kViewTranslations = 0x4a1240u, kViewMatrices = 0x4e0230u; + void project(const uint8_t *rdram, uint32_t view, const float p[4], float out[4]) + { + const uint32_t translation = kViewTranslations + view * 0xf0u, matrix = kViewMatrices + view * 64u; + float q[3], r[4]; + for (int k = 0; k < 3; ++k) + q[k] = p[k] + flt(rdram, translation + 4u * k); + for (int row = 0; row < 4; ++row) + r[row] = flt(rdram, matrix + 16u * row) * q[0] + flt(rdram, matrix + 16u * row + 4u) * q[1] + flt(rdram, matrix + 16u * row + 8u) * q[2] + + flt(rdram, matrix + 16u * row + 12u); + static const bool s_log = std::getenv("TMB_NATIVE_LOG_HUD") != nullptr; + static uint32_t s_logs = 0; + if (s_log && s_logs++ % 400u == 0u && s_logs < 4000u) + { + std::fprintf(stderr, "[tmb:2d] view %u translation (%.1f %.1f %.1f %.1f) at %#x, matrix at %#x:", view, flt(rdram, translation), flt(rdram, translation + 4u), + flt(rdram, translation + 8u), flt(rdram, translation + 12u), translation, matrix); + for (int k = 0; k < 16; ++k) + std::fprintf(stderr, " %.3f", flt(rdram, matrix + 4u * k)); + std::fprintf(stderr, "%s", "\n"); + } + const float inverse = 1.0f / r[3]; + out[0] = r[0] * inverse; + out[1] = r[1] * inverse; + out[2] = r[3]; + out[3] = r[2] * inverse; + } + + // GetIdColor__3HudiPUcT2T2: a car's colour by its id. + uint32_t idColour(uint32_t id) + { + switch (id) + { + case 0x20: return rgba(0x31, 0x5b, 0x01, 0); + case 0x40: return rgba(0xdd, 0xbf, 0x28, 0); + case 0x60: return rgba(0x34, 0x42, 0xff, 0); + case 0x80: return rgba(0x5f, 0xaa, 0xba, 0); + case 0xa0: return rgba(0x84, 0x47, 0x1b, 0); + case 0xc0: return rgba(0xd0, 0x8f, 0xcd, 0); + case 0xe0: return rgba(0xcc, 0xb9, 0xe1, 0); + case 0x100: return rgba(0x7a, 0x64, 0x3d, 0); + case 0x120: return rgba(0x75, 0x3d, 0xb4, 0); + case 0x140: return rgba(0xa4, 0x1f, 0x26, 0); + case 0x160: return rgba(0x4e, 0x44, 0x99, 0); + case 0x180: return rgba(0x7f, 0xa1, 0x5c, 0); + case 0x1a0: return rgba(0x4b, 0xe9, 0x47, 0); + case 0x1c0: return rgba(0x86, 0x5c, 0x00, 0); + case 0x1e0: return rgba(0xff, 0x60, 0x00, 0); + case 0x200: return rgba(0xa4, 0x1f, 0x26, 0); + case 0x220: return rgba(0xff, 0x60, 0x00, 0); + case 0x13e2: return rgba(0x64, 0x64, 0x64, 0); + default: return rgba(0xff, 0xff, 0xff, 0); + } + } + + // mathfManhatDist: the largest of |dx|, |dy|, |dz|, plus 0.34375 the middle one and 0.25 the smallest. + float manhattan(const uint8_t *rdram, uint32_t a, uint32_t b) + { + float d[3]; + for (int k = 0; k < 3; ++k) + d[k] = std::fabs(flt(rdram, b + 4u * k) - flt(rdram, a + 4u * k)); + std::sort(d, d + 3); + return d[2] + d[1] * 0.34375f + d[0] * 0.25f; + } + + // BuildRadarStuff's own primitives (its health bars come through BuildHealthBar): the blips, then a triangle + // over each enemy on screen. Drawn before the game's builder runs, which clears the enemies' hit flags. + void radar(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, uint32_t hud, uint32_t viewIndex) + { + const uint32_t gp = noteGp(getRegU32(ctx, 28)); + // Part A: the blips (Hud + 0x1c of them), around the radar's centre (Hud + 0x800 / 0x804, pixels). + const int32_t centreX = static_cast(word(rdram, hud + 0x800u)) << 4, centreY = static_cast(word(rdram, hud + 0x804u)) << 4; + const uint32_t blips = std::min(word(rdram, hud + 0x1cu), 100u); + for (uint32_t i = 0; i < blips; ++i) + { + if (rdram[(hud + 0x534u + i) & 0x1ffffffu] == 0u) + continue; + const float x = static_cast(centreX + static_cast(word(rdram, hud + 0x20u + 4u * i))) / 16.0f; + const float y = static_cast(centreY - static_cast(word(rdram, hud + 0x1b0u + 4u * i))) / 16.0f; + const uint32_t r = rdram[(hud + 0x340u + i) & 0x1ffffffu], g = rdram[(hud + 0x3a4u + i) & 0x1ffffffu], b = rdram[(hud + 0x408u + i) & 0x1ffffffu]; + switch (word(rdram, hud + 0x5e4u + 4u * i)) + { + case 0: + hudSprite(x - 15.0f / 16.0f, y + 15.0f / 16.0f, x + 15.0f / 16.0f, y - 15.0f / 16.0f, rgba(r, g, b, 0xff), true); + break; + case 1: + hudLine(x - 5.0f, y, x + 6.0f, y, rgba(0xff, 0, 0, 0xff), false); + hudLine(x - 0.5f, y + 3.0f, x - 0.5f, y - 3.0f, rgba(0xff, 0, 0, 0xff), false); + hudLine(x + 0.5f, y + 3.0f, x + 0.5f, y - 3.0f, rgba(0xff, 0, 0, 0xff), false); + break; + case 2: + hudLine(x - 4.5f, y, x + 4.5f, y, rgba(r, g, b, 0xff), false); + hudLine(x - 0.5f, y + 2.25f, x - 0.5f, y - 2.25f, rgba(r, g, b, 0xff), false); + hudLine(x + 0.5f, y + 2.25f, x + 0.5f, y - 2.25f, rgba(r, g, b, 0xff), false); + break; + default: + break; + } + } + + // Part B: a triangle over each enemy on screen, its car's colour (red when a threat is near it). + const uint32_t game = word(rdram, gp + kGpGame), settings = word(rdram, gp + kGpSettings); + const uint32_t player = word(rdram, hud + 0x5e0u); + const uint32_t cars = word(rdram, game + 0x1b3db4u); + const View clipView = viewOf(rdram, viewIndex); + const uint32_t current = word(rdram, gp + kGpCurView); + for (uint32_t i = 0; i < cars && i < 64u; ++i) + { + const uint32_t car = game + i * kVehicleBytes; + if (word(rdram, car + 0x20b0u) == word(rdram, player + 0x20b0u) || byte(rdram, car + 0x487u) || byte(rdram, car + 0x475u)) + continue; + const uint32_t id = word(rdram, car + 0x20a8u); + if (word(rdram, car + 0x580u) - 1u >= 2u && !(id == 0x200u && word(rdram, game + 0x1ab430u) == 3u)) + continue; + uint32_t colour = idColour(id); + if (static_cast(word(rdram, game + 0x1b3db8u)) >= 3 && word(rdram, settings + kSetTeams) == 1u) + colour = word(rdram, settings + kSetTeam + 4u * i) == 0u ? rgba(0x1a, 0x8e, 0x28, 0) : rgba(0xff, 0xff, 0xff, 0); + const uint32_t threats[3] = {0x19bbc8u, 0x19bc0cu, 0x19bc30u}; + for (uint32_t k = 0; k < 4u; ++k) + for (int t = 0; t < 3; ++t) + { + const uint32_t object = word(rdram, game + threats[t] + 4u * k); + if (object && word(rdram, object + 0xcu) && manhattan(rdram, car + 0x1d0u, object + 0x10u) < flt(rdram, gp + kGpThreat[t])) + colour = rgba(0xff, 0, 0, 0); + } + if (word(rdram, player + 0x20a8u) == 0x120u && word(rdram, player + 0x24d0u)) + { + const uint32_t target = word(rdram, word(rdram, player + 0x24d0u) + 0x130u) + 0x10u; + if (manhattan(rdram, car + 0x1d0u, target) < flt(rdram, gp + kGpThreat[3])) + colour = rgba(0xff, 0, 0, 0); + } + if (word(rdram, car + 0x24bcu)) + colour = rgba(0xff, 0, 0, 0); + // The point over the car, projected as the game does (mathfTransform3dTo2d). + const uint32_t at = id == 0x200u ? word(rdram, game + 0x1ab500u) + 0x10u : car + 0x1d0u; + float p[4] = {flt(rdram, at), flt(rdram, at + 4u), flt(rdram, at + 8u), flt(rdram, at + 12u)}; + p[2] += (id == 0xc0u && word(rdram, car + 0x243cu)) ? 20.0f : id == 0x200u ? -75.0f : 10.0f; + float s[4]; + project(rdram, current, p, s); + const float sx = std::round(s[0]), sy = std::round(s[1]); + // TMB_NATIVE_LOG_HUD=1: now and then, each car's projected marker and whether it shows. + static const bool s_logHud = std::getenv("TMB_NATIVE_LOG_HUD") != nullptr; + static uint32_t s_hudLogs = 0; + if (s_logHud && s_hudLogs++ % 97u == 0u && s_hudLogs < 4000u) + std::fprintf(stderr, "[tmb:2d] radar car %u id %#x: p (%.1f %.1f %.1f) -> (%.1f %.1f) w %.2f, view %d %d %dx%d, hidden %d%s", i, id, p[0], + p[1], p[2], s[0], s[1], s[2], clipView.cx, clipView.cy, clipView.w, clipView.h, byte(rdram, car + 0x480u), "\n"); + if (s[2] <= 1.0f || s[0] < clipView.cx - clipView.w * 0.5f || s[0] > clipView.cx + clipView.w * 0.5f || + s[1] < clipView.cy - clipView.h * 0.5f || s[1] > clipView.cy + clipView.h * 0.5f || byte(rdram, car + 0x480u)) + continue; + uint32_t alpha = 0x80; + if (id != 0x200u && word(rdram, settings + kSetFade) == 1u) + { + // the distance in the player's frame, in its plane (mathfMulVec by the player's rotation) + float d[3], local[3] = {0, 0, 0}; + for (int k = 0; k < 3; ++k) + d[k] = flt(rdram, player + 0x1d0u + 4u * k) - flt(rdram, car + 0x1d0u + 4u * k); + for (int row = 0; row < 3; ++row) + for (int k = 0; k < 3; ++k) + local[row] += flt(rdram, player + 0xd0u + 16u * row + 4u * k) * d[k]; + const double distance = std::sqrt(local[0] * local[0] + local[1] * local[1]); + if (distance > 600.0) + alpha = distance > 2000.0 ? 0x1eu + : static_cast(static_cast((dbl(rdram, kAlphaConstants) - distance) / dbl(rdram, kAlphaConstants + 8u) * + dbl(rdram, kAlphaConstants + 16u)) + 0x1e); + } + colour = (colour & 0xffffffu) | (std::min(alpha, 0xffu) << 24); + const bozo::render::Vertex v[3] = {vertex(sx - 12.0f, sy - 6.0f, colour), vertex(sx, sy, colour), vertex(sx + 12.0f, sy - 6.0f, colour)}; + hudTriangles(v, 3u, true); + } + } + + void radarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4); + if (on()) + radar(rdram, ctx, runtime, hud, getRegU32(ctx, 6)); + BuildRadarStuff__3HudP6QwDatai_0x13eb40(rdram, ctx, runtime); + if (on()) + setWord(rdram, hud + 4u, 1u); + } + + // BuildHealthBar(hud, packet, x, y, w, h, car): a bar measured from the current view's bottom-left corner, filling + // from its right end, green / yellow / red by the health left. + void healthBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), car = getRegU32(ctx, 10); + const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); + const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); + const uint32_t gp = noteGp(getRegU32(ctx, 28)); + BuildHealthBar__3HudP6QwDataiiiiP7Vehicle_0x141af0(rdram, ctx, runtime); + if (!on()) + return; + const uint32_t game = word(rdram, gp + kGpGame); + int32_t fill = 0; + if (word(rdram, game + 0x1b3db0u) == 20u && word(rdram, game + 0x1ab500u) && word(rdram, car + 0x20a8u) == 0x200u) + { + const int32_t current = static_cast(word(rdram, game + 0x1ab43cu)), most = static_cast(word(rdram, game + 0x1ab438u)); + fill = most ? std::min((w - 4) * current / most + 1, w - 4) : 0; + if (current <= 0) + fill = 0; + } + else + { + const float hp = flt(rdram, car + 0x3f4u), most = flt(rdram, car + 0x3f0u); + fill = most != 0.0f ? std::min(static_cast(static_cast(w - 4) * hp / most + 1.0f), w - 4) : 0; + if (hp <= 0.0f) + fill = 0; + } + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float left = static_cast(v.cx - v.w / 2 + x), top = static_cast(v.cy + v.h / 2 - y); + hudSprite(left, top, left + w, top + h, rgba(0, 0, 0, 0x40), true); + const uint32_t colour = word(rdram, hud + 0x5ccu) ? rgba(0, 0, 0, 0x40) + : rgba(word(rdram, hud + 0x5c0u), word(rdram, hud + 0x5c4u), 0, 0x40); + const float right = left - 2.0f + w; + hudSprite(right - fill, top + 1.0f, right, top + h - 1.0f, colour, true); + } + + // BuildSeparator: the black line between the two views of a split screen (drawn by view 0's HUD). + void separatorOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + BuildSeparator__3HudP6QwData_0x13e140(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const int display = screenDisplay(rdram); + if (display == 0 || word(rdram, gp + kGpCurView) != 0u) + return; + const View v = viewOf(rdram, 0); + const bool rearLarge = word(rdram, gp + kGpRearLarge) != 0u; + float x0 = 0, y0 = 0; + if (display == 2) + { + x0 = static_cast(v.cx - v.w / 2); + y0 = static_cast(rearLarge ? v.cy - v.h / 2 : v.cy + v.h / 2 - 2); + } + else + { + x0 = static_cast(v.cx + v.w / 2 - 2); + y0 = static_cast(v.cy - v.h / 2); + } + const float x1 = static_cast(v.cx + v.w / 2), y1 = static_cast(rearLarge ? v.cy - v.h / 2 + 2 : v.cy + v.h / 2); + hudSprite(x0, y0, x1, y1, rgba(0, 0, 0, 0x80), false); + } + + // BuildRearViewEdge(hud, packet, view): the black frame around the small rear view. + void rearViewEdgeOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), viewIndex = getRegU32(ctx, 6); + BuildRearViewEdge__3HudP6QwDatai_0x13e3e0(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const View v = viewOf(rdram, viewIndex); + const float l = static_cast(v.cx - v.w / 2 - 3), r = l + v.w + 1, t = static_cast(v.cy - v.h / 2), b = t + v.h; + const uint32_t black = rgba(0, 0, 0, 0x80); + hudSprite(l, t, r, t + 1, black, false); + hudSprite(r, t, r + 1, b, black, false); + hudSprite(r, b, l, b - 1, black, false); + hudSprite(l + 3, b - 1, l + 4, t + 1, black, false); + } + + // boundFAngle: an angle into [-pi, pi). + float boundAngle(float a) + { + constexpr float kPi = 3.14159265f, kTwoPi = 6.28318531f; + return a - kTwoPi * std::floor((a + kPi) / kTwoPi); + } + // mathfRotMatrixRPH(m, angles): the rotation of angles (x, y, z) (sines and cosines as the game combines them), + // rows of three. + void rotationRph(const float angles[3], float m[3][3]) + { + const float sx = std::sin(angles[0]), cx = std::cos(angles[0]), sy = std::sin(angles[1]), cy = std::cos(angles[1]); + const float sz = std::sin(angles[2]), cz = std::cos(angles[2]); + m[0][0] = cy * cz + sy * sx * sz; + m[0][1] = -cy * sz + sy * sx * cz; + m[0][2] = -sy * cx; + m[1][0] = cx * sz; + m[1][1] = cx * cz; + m[1][2] = sx; + m[2][0] = sy * cz - cy * sx * sz; + m[2][1] = -sy * sz - cy * sx * cz; + m[2][2] = cy * cx; + } + constexpr uint32_t kLaserOffsets = 0x4e6ef0u; // {0.006, -7.05, 4.08}, then {0.016, 9.204, 1.649} + + // BuildLaserStuff: the laser sight, a line from the gun (the car's frame by one offset, then its turret's angles + // by another) to its target (car + 0x2438), both projected as mathfTransform3dTo2d; alpha 0x1a red. + void laserOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + BuildLaserStuff__3HudP6QwData_0x1425b8(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const uint32_t car = word(rdram, hud + 0x5e0u), target = word(rdram, car + 0x2438u); + if (!car || !target) + return; + const uint32_t body = word(rdram, car + 0x2018u); + float p[4] = {flt(rdram, car + 0x1d0u), flt(rdram, car + 0x1d4u), flt(rdram, car + 0x1d8u), 1.0f}; + const float c1[3] = {flt(rdram, kLaserOffsets), flt(rdram, kLaserOffsets + 4u), flt(rdram, kLaserOffsets + 8u)}; + const float c2[3] = {flt(rdram, kLaserOffsets + 16u), flt(rdram, kLaserOffsets + 20u), flt(rdram, kLaserOffsets + 24u)}; + for (int k = 0; k < 3; ++k) // mathfMulTransVec(body + 0x20, c1): rows weighted by c1 + p[k] += flt(rdram, body + 0x20u + 4u * k) * c1[0] + flt(rdram, body + 0x30u + 4u * k) * c1[1] + flt(rdram, body + 0x40u + 4u * k) * c1[2]; + float angles[3], r[3][3]; + for (int k = 0; k < 3; ++k) + angles[k] = boundAngle(flt(rdram, car + 0x23d0u + 4u * k) + flt(rdram, body + 0x60u + 4u * k)); + rotationRph(angles, r); + for (int k = 0; k < 3; ++k) + p[k] += r[0][k] * c2[0] + r[1][k] * c2[1] + r[2][k] * c2[2]; + const uint32_t view = word(rdram, gp + kGpCurView); + float a[4], b[4]; + const float q[4] = {flt(rdram, target + 0x10u), flt(rdram, target + 0x14u), flt(rdram, target + 0x18u), 1.0f}; + project(rdram, view, p, a); + project(rdram, view, q, b); + hudLine(std::trunc(a[0]), std::trunc(a[1]), std::trunc(b[0]), std::trunc(b[1]), rgba(0xff, 0x28, 0x28, 0x1a), true); + } + // build4PTurboBar / build4PEnergyBar(hud, packet, x, y, w, h): a horizontal bar of the current view's bottom-left + // corner (y up from its bottom), filling from its right end; opaque. + void horizontalBar4p(uint8_t *rdram, uint32_t gp, int32_t x, int32_t y, int32_t w, int32_t h, int32_t fill, uint32_t colour) + { + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float x0 = static_cast(v.cx - v.w / 2 - 2 + x + w - fill), y0 = static_cast(v.cy + v.h / 2 + 1 - y); + hudSprite(x0, y0, x0 + fill, y0 - 2 + h, colour, false); + } + void turbo4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); + const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); + build4PTurboBar__3HudP6QwDataiiii_0x141338(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const float turbo = flt(rdram, word(rdram, hud + 0x5e0u) + 0x410u); + const int32_t fill = turbo <= 0.0f ? 0 : std::min(static_cast(static_cast(w - 4) * turbo / 100.0f + 1.0f), w - 4); + horizontalBar4p(rdram, gp, x, y, w, h, fill, rgba(0x14, 0x58, 0x80, 0x20)); + } + void energy4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); + const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); + build4PEnergyBar__3HudP6QwDataiiii_0x1418a8(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const uint32_t car = word(rdram, hud + 0x5e0u); + const int32_t current = static_cast(word(rdram, car + 0x2214u)), most = static_cast(word(rdram, car + 0x2218u)); + const int32_t fill = current <= 0 || most == 0 ? 0 : std::min((w - 4) * current / most + 1, w - 4); + horizontalBar4p(rdram, gp, x, y, w, h, fill, rgba(0x89, 0x44, 0x20, 0x20)); + } + // build4PHealthBar(hud, packet, x, y, w, h): a vertical bar rising from the current view's bottom edge (y up), red / + // yellow / green by the health left; blended. + void health4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + const int32_t x = static_cast(getRegU32(ctx, 6)), y = static_cast(getRegU32(ctx, 7)); + const int32_t w = static_cast(getRegU32(ctx, 8)), h = static_cast(getRegU32(ctx, 9)); + build4PHealthBar__3HudP6QwDataiiii_0x1415a0(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const uint32_t car = word(rdram, hud + 0x5e0u); + const float hp = flt(rdram, car + 0x3f4u), most = flt(rdram, car + 0x3f0u); + const int32_t fill = hp <= 0.0f || most == 0.0f ? 0 : std::min(static_cast(static_cast(h - 4) * hp / most + 1.0f), h - 4); + const uint32_t colour = word(rdram, hud + 0x5ccu) ? rgba(0, 0, 0, 0x3f) + : rgba(word(rdram, hud + 0x5c0u), word(rdram, hud + 0x5c4u), word(rdram, hud + 0x5c8u), 0x40); + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float x0 = static_cast(v.cx - v.w / 2 + x), y0 = static_cast(v.cy + v.h / 2 - (y + fill)); + hudSprite(x0, y0, x0 + w, y0 + fill, colour, true); + } + + constexpr uint32_t kChargeUp = 0x00140AA8u; + + // BuildChargeUpBar(hud, packet): the charge (car + 0x220c of car + 0x2210) as a bar 4 pixels high, 108 long at + // full charge, from 54 pixels left of the current view's centre, 10 to 14 pixels above its bottom edge; ABE, alpha + // 0x30. Its colour is the Hud's (+ 0x5a0 red, + 0x5a4 green, blue 0): green under half charge, easing to yellow + // under 75%, then to red (smoothEasyIn, state the game's builder keeps); from 85% it blinks black (+ 0x5a8 set + // for 15 of every 30 frames, counted at + 0x5ac). + void chargeUpOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + BuildChargeUpBar__3HudP6QwData_0x140aa8(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + const uint32_t car = word(rdram, hud + 0x5e0u); + const int32_t charge = static_cast(word(rdram, car + 0x220cu)), most = static_cast(word(rdram, car + 0x2210u)); + if (most == 0) + return; + const int32_t length = charge * 108 / most; + const uint32_t colour = word(rdram, hud + 0x5a8u) ? rgba(0, 0, 0, 0x30) : rgba(word(rdram, hud + 0x5a0u), word(rdram, hud + 0x5a4u), 0, 0x30); + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float x0 = static_cast(v.cx - 54), y0 = static_cast(v.cy + v.h / 2 - 14); + hudSprite(x0, y0, x0 + length, y0 + 4.0f, colour, true); + } + + // in install(): + + constexpr uint32_t kOverheat = 0x00140DF8u; + + // BuildOverheatBar(hud, packet): a small lamp right of the current view's centre, its colour by the heat of the + // car's weapon (car + 0x2220 of car + 0x2224, in percent): the game's own builder eases Hud + 0x5b0 (red) and + // Hud + 0x5b4 (green) between green (under 50), yellow (under 75), orange to red (under 85), and red over that, + // when Hud + 0x5b8 blinks it off (on 15 frames of every 30, counted by Hud + 0x5bc). Two blended sprites: a + // black backing of 20 x 7, then the lamp of 16 x 5 inside it (black while blinked off); alpha 0x30. + void overheatOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4), gp = noteGp(getRegU32(ctx, 28)); + BuildOverheatBar__3HudP6QwData_0x140df8(rdram, ctx, runtime); + if (!on()) + return; + setWord(rdram, hud + 4u, 1u); + // From the current view's centre: 30 left of its right edge, 40 under its centre (10 over it when the + // screen is split one view over the other). + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float x = static_cast(v.cx + (v.w >> 1) - 30), y = static_cast(screenDisplay(rdram) == 2 ? v.cy - 10 : v.cy + 40); + hudSprite(x, y, x + 20.0f, y + 7.0f, rgba(0, 0, 0, 0x30), true); + const uint32_t colour = word(rdram, hud + 0x5b8u) ? rgba(0, 0, 0, 0x30) + : rgba(word(rdram, hud + 0x5b0u), word(rdram, hud + 0x5b4u), 0, 0x30); + hudSprite(x + 2.0f, y + 1.0f, x + 18.0f, y + 6.0f, colour, true); + } + + void separator4pOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t hud = getRegU32(ctx, 4); + Build4pSeparater__3HudP6QwDatai_0x13e838(rdram, ctx, runtime); + if (on()) + setWord(rdram, hud + 4u, 1u); + } + + // ---- the loading bar (Shell::LoadLevelFiles): buildProgressBar and, on the loads without the shell, the vblank + // callback that sends it between the load's steps; drawn and published here, as no game frame ends meanwhile ---- + constexpr uint32_t kBuildProgressBar = 0x001FC2A8u, kBarVSync = 0x00202238u, + kInformProgressBar = 0x001FC8D0u; + constexpr int32_t kGpBarMode = -0x3290, kGpBarFlip = -0x328c, kGpBarShown = -0x3280, kGpBarProgress = -0x327c; + std::atomic g_barGp{0}; // the game's gp at buildProgressBar (the vblank callback's own may differ) + + // The bar over view 0 (initProgressBar's viewCreate: 0x11 on the first load after the shell, a frame view; 0x12 + // on the others, a field view): the fill (0x4c, 0x1a, 0x0d), progress / 1024 of its width, over the top half of + // the view (first load) or, 6 and 2 smaller, the whole of it over a dark track (0x13, 6, 0x10); opaque. + // Published mapped by view 0's frame buffer (its own rectangle is the bar's). + void loadingBar(uint8_t *rdram, uint32_t gp) + { + const bool track = word(rdram, gp + kGpBarMode) != 0u; + const int32_t progress = static_cast(std::min(word(rdram, gp + kGpBarProgress), 0x400u)); + View v = viewOf(rdram, 0); + if (track) + v.w -= 6, v.h -= 2; + const int32_t left = v.cx - (v.w >> 1), top = v.cy - (v.h >> 1); + if (track) + hudSprite(static_cast(left), static_cast(top), static_cast(left + v.w), static_cast(top + v.h), + rgba(0x13, 0x06, 0x10, 0x80), false); + const int32_t bottom = track ? top + v.h : top + (v.h >> 1); + hudSprite(static_cast(left), static_cast(top), static_cast(left + ((v.w * progress) >> 10)), + static_cast(bottom), rgba(0x4c, 0x1a, 0x0d, 0x80), false); + const uint32_t def = word(rdram, kViews + 4u); + const float width = half(rdram, def + 8u), height = half(rdram, def + 0xau); + bozo::render::Screen screen; + screen.width = width > 0.0f ? width : 640.0f; + screen.height = height > 0.0f ? height : 448.0f; + screen.originX = 2048.0f - screen.width * 0.5f; + screen.originY = 2048.0f - screen.height * 0.5f; + bozo::render::Renderer::instance().publishOverlay(screen); + } + + // buildProgressBar(progress): the bar at min(progress, 1024) / 1024, drawn instead of sent. + void buildProgressBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (!on()) + { + buildProgressBar__FUi_0x1fc2a8(rdram, ctx, runtime); + return; + } + const uint32_t gp = noteGp(getRegU32(ctx, 28)); + g_barGp.store(gp, std::memory_order_relaxed); + g_rdram.store(rdram, std::memory_order_relaxed); + if (getRegU32(ctx, 4) == 0u) // a load's start: the picture the menus were drawn over is gone + { + std::lock_guard lock(g_movieMutex); + g_menuPicture.reset(); + bozo::render::clearDisplayPicture(); + } + setWord(rdram, gp + kGpBarProgress, std::min(getRegU32(ctx, 4), 0x400u)); + loadingBar(rdram, gp); + ctx->pc = getRegU32(ctx, 31); // jr $ra + } + + // informProgressBar(fraction): a load's step done; it works out the progress and hands it to buildProgressBar + // with a tail jump, which the recompiled code makes a direct call (past buildProgressBarOverride): the game's + // own buildProgressBar runs and keeps the progress (gp - 0x327c), its packet sent unread; the bar drawn here. + void informProgressBarOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t gp = getRegU32(ctx, 28); + informProgressBar__Ff_0x1fc8d0(rdram, ctx, runtime); + if (!on()) + return; + noteGp(gp); + g_barGp.store(gp, std::memory_order_relaxed); + g_rdram.store(rdram, std::memory_order_relaxed); + loadingBar(rdram, gp); + } + + // finishShellLoop (a memory card save started from a match's overlay): the current view darkened by a quarter + // (black, alpha 0x21, the font's (Cs - Cd) As + Cd), over the overlay's text; drawn instead of sent. + constexpr uint32_t kFinishShellLoop = 0x0019F790u; + void finishShellLoopOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (!on()) + { + finishShellLoop__Fv_0x19f790(rdram, ctx, runtime); + return; + } + const View v = viewOf(rdram, word(rdram, getRegU32(ctx, 28) + kGpCurView)); + const float left = static_cast(v.cx - (v.w >> 1)), top = static_cast(v.cy - (v.h >> 1)); + hudSprite(left, top, left + static_cast(v.w), top + static_cast(v.h), rgba(0, 0, 0, 0x21), true); + g_flushed.store(true, std::memory_order_relaxed); + publish(); + ctx->pc = getRegU32(ctx, 31); // jr $ra + } + + // displayDialog's darkening, after the overlay's text (its font flush): the current view a quarter darker + // towards (0, 0, 10) (alpha 0x21, the font's (Cs - Cd) As + Cd). Its kick is patched out (dialogKick). + void dialogDim(uint8_t *rdram, uint32_t gp) + { + if (gp == 0u) + return; + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + const float left = static_cast(v.cx - (v.w >> 1)), top = static_cast(v.cy - (v.h >> 1)); + hudSprite(left, top, left + static_cast(v.w), top + static_cast(v.h), rgba(0, 0, 0x0a, 0x21), true); + } + // bozo:store kDialogKick (the generated code sets ctx->pc before that store: tools/tmb_overrides_list.py) + bool dialogKick(uint32_t pc, uint32_t address, uint32_t) + { + return pc == kDialogKick && address == 0x1000a000u && on(); + } + + // ---- movies: the pictures the MPEG decoder hands to sceMpegGetPicture, shown under the 2D by loadImage (each + // vblank while a movie plays) instead of the GS image transfers the game built of them ---- + constexpr uint32_t kLoadImage = 0x001DF838u; + // handler_endimage's work (the GIF DMA end interrupt the transfer raised): with the picture still held (the flag at + // gp + kImageHeld), voBufDecCount on the movie's picture buffer frees it for the decoder. + constexpr uint32_t kVoBufDecCount = 0x001FEF58u, kVoBuf = 0x004C4A18u; + constexpr int32_t kImageHeld = -0x36d8; + + void moviePicture(uint32_t, uint32_t width, uint32_t height, const uint8_t *rgba) + { + static uint64_t s_version = 0; + bozo::render::Texture picture; + picture.width = width; + picture.height = height; + picture.key = 0x4d4f5649u; // one picture at a time: its GPU copy replaced + picture.version = ++s_version; + picture.rgba.resize(static_cast(width) * height); + std::memcpy(picture.rgba.data(), rgba, picture.rgba.size() * 4u); + auto shared = std::make_shared(std::move(picture)); + std::lock_guard lock(g_movieMutex); + g_moviePicture = std::move(shared); + } + + // loadImage(chain): the last picture, centred in the frame (as dispSetTags places it: a 640 x 448 frame in NTSC, + // 640 x 512 in PAL); no transfer. It goes in the buffer the display reads through circuit 2: the shell's menus + // are drawn over it with alpha 0 where it shows (PMODE merges the circuits by the frame's alpha), and it stays + // there after the clip ends (blitLastMovieFrame) until a load starts. A movie on its own (no menu frames) is + // also shown under the overlay. + void showOnCircuit2(const bozo::render::Texture &picture) + { + constexpr uint32_t kFrameWidth = 640u, kFrameHeight = 448u; + auto frame = std::make_shared>(static_cast(kFrameWidth) * kFrameHeight, 0x80000000u); + const uint32_t width = std::min(picture.width, kFrameWidth), height = std::min(picture.height, kFrameHeight); + const uint32_t x0 = (kFrameWidth - width) / 2u, y0 = (kFrameHeight - height) / 2u; + for (uint32_t y = 0; y < height; ++y) + for (uint32_t x = 0; x < width; ++x) + (*frame)[(y0 + y) * kFrameWidth + x0 + x] = (picture.rgba[y * picture.width + x] & 0x00ffffffu) | 0x80000000u; + bozo::render::setDisplayPicture(std::move(frame), kFrameWidth, kFrameHeight); + } + void completeMoviePicture(uint8_t *rdram, R5900Context *ctx) { g_imageReplaced.store(true, std::memory_order_relaxed); @@ -884,251 +884,258 @@ namespace tmb::twod ctx->pc = getRegU32(ctx, 31); } - // The decoder's last picture shown natively (circuit 2, and the backdrop when the menus are not drawn natively). - // False when there is none to show natively (TMB_NATIVE_2D=0, or no picture yet). - bool presentMoviePicture() - { - std::shared_ptr picture; - { - std::lock_guard lock(g_movieMutex); - picture = g_moviePicture; - if (on() && picture && picture != g_menuPicture) - { - g_menuPicture = picture; - showOnCircuit2(*picture); - } - } - if (!on() || !picture) - return false; - constexpr float kFrameHeight = 448.0f; - bozo::render::Screen screen; - screen.originX = 2048.0f - 320.0f; - screen.originY = 2048.0f - kFrameHeight * 0.5f; - screen.width = 640.0f; - screen.height = kFrameHeight; - const float width = static_cast(picture->width), height = static_cast(picture->height); - if (!tmb::native::menusDrawn()) - bozo::render::Renderer::instance().setBackdrop(std::move(picture), screen, screen.originX + (640.0f - width) * 0.5f, - screen.originY + (kFrameHeight - height) * 0.5f, width, height); - return true; - } - - void loadImageOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - // Even an empty native presentation completes: there is no GIF interrupt to release its buffer. - if (presentMoviePicture() || bozo::port::nativeGraphics(runtime)) - completeMoviePicture(rdram, ctx); - else - loadImage__FPUi_0x1df838(rdram, ctx, runtime); - } - - // voBufDecCount natively: the movie's picture buffer's count down by one (not below zero). - void releaseMoviePicture(uint8_t *rdram) - { - const int32_t count = static_cast(word(rdram, kVoBuf + 0xcu)); - if (count > 0) - setWord(rdram, kVoBuf + 0xcu, static_cast(count - 1)); - } - - // The movie player's vblankHandler (Sony's ezmpeg sample, INTC vblank start while a movie plays), native. Each - // decoded picture (the oldest in the picture buffer, voBufGetTag) is shown for two fields: on an even field when - // its tag says 2 (then 1), on an odd field when it says 1 (then 0); the odd field's showing ended its GIF transfer, - // whose DMA end interrupt (handler_endimage) freed the picture's buffer (voBufDecCount): freed here at once. - // - // It used to run the game's own handler and free the buffer after it returned. Guest code inside an override - // leaves it when a scheduler event comes due (the vblank's end, a frame end's clock catch-up), and the rest of - // the handler then runs after the override has returned: the odd field's tag became 0 with its buffer never - // freed. That tag stayed the oldest, so no picture was shown again: the movie froze, the decoder waited for a - // free buffer forever (decBs0's voBufGetData loop), and a skip or a menu choice that stops the movie waited for - // the decoder (updateMpegMovieDecoding's videoDecIsFlushed loop): no game frame ended (one-player route, vehicle - // select, frame 4340). No guest code runs here, so nothing can leave it half done. - constexpr uint32_t kVblankHandler = 0x001C1890u; - constexpr int32_t kGpDisplayOn = -0x36dc, kGpField = -0x36d4, kGpPathBusy = -0x36d0, kGpShown = -0x36cc, - kGpNewest = -0x36bc; - constexpr uint32_t kVoTagStride = 0x85740u; // VoTag: its state word first, then the two fields' transfer chains - constexpr uint32_t kVideoDec = 0x004C4A30u; // its state at + 0xa8 (1 aborted, 2 flushing, 3 ended) - uint64_t g_movieShownAt = 0; // the vblank count when the handler last showed a picture - - void vblankHandlerNative(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t gp = getRegU32(ctx, 28); - const uint32_t field = static_cast(bozo::port::vblankCount(runtime) & 1u); // CSR.FIELD - setWord(rdram, gp + static_cast(kGpField), field); - if (word(rdram, gp + static_cast(kGpDisplayOn)) != 0u) - { - setWord(rdram, gp + static_cast(kGpPathBusy), 0u); // sceGsSyncPath: nothing in flight - const int32_t count = static_cast(word(rdram, kVoBuf + 0xcu)); - const int32_t size = static_cast(word(rdram, kVoBuf + 0x10u)); - if (count > 0 && size > 0) // voBufGetTag: none while the buffer is empty - { - const int32_t index = static_cast(word(rdram, kVoBuf + 0x8u)); - setWord(rdram, gp + static_cast(kGpNewest), static_cast((index - 1 + size) % size)); - const uint32_t oldest = static_cast(((index - count + size) % size + size) % size); - const uint32_t tag = word(rdram, kVoBuf + 0x4u) + oldest * kVoTagStride; - const uint32_t state = word(rdram, tag); - const bool even = field == 0u; - if ((even && state == 2u) || (!even && state == 1u)) - { - presentMoviePicture(); - // loadImage's completion: a picture still held from before is freed first (handler_endimage). - const uint32_t held = gp + static_cast(kImageHeld); - if (word(rdram, held) != 0u) - { - setWord(rdram, held, 0u); - releaseMoviePicture(rdram); - } - setWord(rdram, tag, even ? 1u : 0u); - if (!even) - releaseMoviePicture(rdram); // its transfer has ended - setWord(rdram, gp + static_cast(kGpShown), 1u); - g_movieShownAt = bozo::port::vblankCount(runtime); - } - else if (count >= size && bozo::port::vblankCount(runtime) - g_movieShownAt == 120u) - { - // A full picture buffer and nothing shown for 120 fields: the decoder waits for a buffer. - std::fprintf(stderr, - "[tmb:movie] stall: picture buffer full (%d of %d, next %d), oldest tag %u state %u at field %u, " - "held %u, decoder state %u\n", - count, size, index, oldest, state, field, word(rdram, gp + static_cast(kImageHeld)), - word(rdram, kVideoDec + 0xa8u)); - } - } - } - setReturnS32(ctx, 0); - ctx->pc = getRegU32(ctx, 31); // jr $ra - } - - // The game's GS image transfers (native graphics off, a diagnostic): the game's handler, then what - // handler_endimage did when the transfer it started ended (the GIF DMA end interrupt, never raised): the - // picture loadImage replaced is freed after the handler sets its held flag. - void vblankHandlerOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (bozo::port::nativeGraphics(runtime)) - { - vblankHandlerNative(rdram, ctx, runtime); - return; - } - g_imageReplaced.store(false, std::memory_order_relaxed); - vblankHandler__Fi_0x1c1890(rdram, ctx, runtime); - if (!g_imageReplaced.exchange(false, std::memory_order_relaxed)) - return; - const uint32_t held = getRegU32(ctx, 28) + static_cast(kImageHeld); - if (word(rdram, held) == 0u) - return; - setWord(rdram, held, 0u); - const uint32_t count = word(rdram, kVoBuf + 0xcu); - if (static_cast(count) > 0) - setWord(rdram, kVoBuf + 0xcu, count - 1u); - } - - // updateBarVSyncCallback: each vblank the bar creeps one 1024th (until the next step sets the real progress) - // and the field parity flips; the buffer swap and the packet's DMA are the GS's, not done. - void barVSyncOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - const uint32_t gp = g_barGp.load(std::memory_order_relaxed); - if (!on() || gp == 0u) - { - updateBarVSyncCallback__Fi_0x202238(rdram, ctx, runtime); - return; - } - setWord(rdram, gp + kGpBarFlip, word(rdram, gp + kGpBarFlip) ^ 1u); - setWord(rdram, gp + kGpBarProgress, std::min(word(rdram, gp + kGpBarProgress) + 1u, 0x400u)); - loadingBar(rdram, gp); - ctx->pc = getRegU32(ctx, 31); // jr $ra - } - } - - // The view the game draws now (viewGetCurView), as a clip in GS primitive coordinates (x0, y0, x1, y1): where the GS - // scissor cut each view of a split screen. False before the game's gp is known. - bool viewClip(const uint8_t *rdram, float (&clip)[4]) - { - const uint32_t gp = g_gp.load(std::memory_order_relaxed); - if (gp == 0u || !rdram) - return false; - const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); - if (v.w <= 0 || v.h <= 0) - return false; - clip[0] = static_cast(v.cx) - static_cast(v.w) * 0.5f; - clip[1] = static_cast(v.cy) - static_cast(v.h) * 0.5f; - clip[2] = static_cast(v.cx) + static_cast(v.w) * 0.5f; - clip[3] = static_cast(v.cy) + static_cast(v.h) * 0.5f; - return true; - } - - // At the end of a game frame (the adapter's publish): the 2D drawn since the last one goes on screen once the game - // sent it (fontDmaFontData); a frame end with nothing sent since leaves what shows (the menus end frames twice). - void publish() - { - if (!on()) - return; - // A level loading: its bar (no other 2D then). - if (const uint32_t barGp = g_barGp.load(std::memory_order_relaxed); barGp != 0u) - if (uint8_t *rdram = const_cast(g_rdram.load(std::memory_order_relaxed)); rdram && word(rdram, barGp + kGpBarShown) == 1u) - { - loadingBar(rdram, barGp); - return; - } - static uint32_t s_idle = 0; - if (g_flushed.exchange(false, std::memory_order_relaxed)) - s_idle = 0; - else if (++s_idle < 8u) - return; - // Mapped to the window by the game's own view 0 (its centre and size): a menu's 640 x 448, a match's 640 x 224. - const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed); - if (!rdram) - { - bozo::render::Renderer::instance().publishOverlay(); - return; - } - // The whole display: every view the game shows (viewGetNumViews), e.g. a rear view over the main one. - const uint32_t views = std::clamp(word(rdram, g_gp.load(std::memory_order_relaxed) + kGpNumViews), 1u, 4u); - float left = 1e9f, top = 1e9f, right = -1e9f, bottom = -1e9f; - for (uint32_t i = 0; i < views; ++i) - { - const View v = viewOf(rdram, i); - if (v.w <= 0 || v.h <= 0) - continue; - left = std::min(left, v.cx - v.w * 0.5f); - top = std::min(top, v.cy - v.h * 0.5f); - right = std::max(right, v.cx + v.w * 0.5f); - bottom = std::max(bottom, v.cy + v.h * 0.5f); - } - if (!(right > left && bottom > top)) - { - bozo::render::Renderer::instance().publishOverlay(); - return; - } - bozo::render::Screen screen; - screen.originX = left; - screen.originY = top; - screen.width = right - left; - screen.height = bottom - top; - bozo::render::Renderer::instance().publishOverlay(screen); - } - - void install(tmb::Registry &runtime) - { - runtime.registerFunction(kFontBuildPrim, &fontBuildPrimOverride); - runtime.registerFunction(kFontDmaFontData, &fontDmaFontDataOverride); - runtime.registerFunction(kRadar, &radarOverride); - runtime.registerFunction(kHealthBar, &healthBarOverride); - runtime.registerFunction(kSeparator, &separatorOverride); - runtime.registerFunction(kRearViewEdge, &rearViewEdgeOverride); - runtime.registerFunction(kLaser, &laserOverride); - runtime.registerFunction(k4pSeparator, &separator4pOverride); - runtime.registerFunction(kTurbo4p, &turbo4pOverride); - runtime.registerFunction(kEnergy4p, &energy4pOverride); - runtime.registerFunction(kHealth4p, &health4pOverride); - runtime.registerFunction(kChargeUp, &chargeUpOverride); - runtime.registerFunction(kBuildProgressBar, &buildProgressBarOverride); - runtime.registerFunction(kInformProgressBar, &informProgressBarOverride); - runtime.registerFunction(kBarVSync, &barVSyncOverride); - runtime.registerFunction(kFinishShellLoop, &finishShellLoopOverride); - bozo::port::setStorePatch(&dialogKick); - runtime.registerFunction(kLoadImage, &loadImageOverride); - runtime.registerFunction(kVblankHandler, &vblankHandlerOverride); - if (on()) - bozo::render::setMoviePictureHook(&moviePicture); - runtime.registerFunction(kOverheat, &overheatOverride); - } -} + // The decoder's last picture shown natively (circuit 2, and the backdrop when the menus are not drawn natively). + // False when there is none to show natively (TMB_NATIVE_2D=0, or no picture yet). + bool presentMoviePicture() + { + std::shared_ptr picture; + { + std::lock_guard lock(g_movieMutex); + picture = g_moviePicture; + if (on() && picture && picture != g_menuPicture) + { + g_menuPicture = picture; + showOnCircuit2(*picture); + } + } + if (!on() || !picture) + return false; + constexpr float kFrameHeight = 448.0f; + bozo::render::Screen screen; + screen.originX = 2048.0f - 320.0f; + screen.originY = 2048.0f - kFrameHeight * 0.5f; + screen.width = 640.0f; + screen.height = kFrameHeight; + const float width = static_cast(picture->width), height = static_cast(picture->height); + if (!tmb::native::menusDrawn()) + bozo::render::Renderer::instance().setBackdrop(std::move(picture), screen, screen.originX + (640.0f - width) * 0.5f, + screen.originY + (kFrameHeight - height) * 0.5f, width, height); + return true; + } + + void loadImageOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + // Even an empty native presentation completes: there is no GIF interrupt to release its buffer. + if (presentMoviePicture() || bozo::port::nativeGraphics(runtime)) + completeMoviePicture(rdram, ctx); + else + loadImage__FPUi_0x1df838(rdram, ctx, runtime); + } + + // voBufDecCount natively: the movie's picture buffer's count down by one (not below zero). + void releaseMoviePicture(uint8_t *rdram) + { + const int32_t count = static_cast(word(rdram, kVoBuf + 0xcu)); + if (count > 0) + setWord(rdram, kVoBuf + 0xcu, static_cast(count - 1)); + } + + // The movie player's vblankHandler (Sony's ezmpeg sample, INTC vblank start while a movie plays), native. Each + // decoded picture (the oldest in the picture buffer, voBufGetTag) is shown for two fields: on an even field when + // its tag says 2 (then 1), on an odd field when it says 1 (then 0); the odd field's showing ended its GIF transfer, + // whose DMA end interrupt (handler_endimage) freed the picture's buffer (voBufDecCount): freed here at once. + // + // It used to run the game's own handler and free the buffer after it returned. Guest code inside an override + // leaves it when a scheduler event comes due (the vblank's end, a frame end's clock catch-up), and the rest of + // the handler then runs after the override has returned: the odd field's tag became 0 with its buffer never + // freed. That tag stayed the oldest, so no picture was shown again: the movie froze, the decoder waited for a + // free buffer forever (decBs0's voBufGetData loop), and a skip or a menu choice that stops the movie waited for + // the decoder (updateMpegMovieDecoding's videoDecIsFlushed loop): no game frame ended (one-player route, vehicle + // select, frame 4340). No guest code runs here, so nothing can leave it half done. + constexpr uint32_t kVblankHandler = 0x001C1890u; + constexpr int32_t kGpDisplayOn = -0x36dc, kGpField = -0x36d4, kGpPathBusy = -0x36d0, kGpShown = -0x36cc, + kGpNewest = -0x36bc; + constexpr uint32_t kVoTagStride = 0x85740u; // VoTag: its state word first, then the two fields' transfer chains + constexpr uint32_t kVideoDec = 0x004C4A30u; // its state at + 0xa8 (1 aborted, 2 flushing, 3 ended) + uint64_t g_movieShownAt = 0; // the vblank count when the handler last showed a picture + + void vblankHandlerNative(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t gp = getRegU32(ctx, 28); + const uint32_t field = static_cast(bozo::port::vblankCount(runtime) & 1u); // CSR.FIELD + setWord(rdram, gp + static_cast(kGpField), field); + if (word(rdram, gp + static_cast(kGpDisplayOn)) != 0u) + { + setWord(rdram, gp + static_cast(kGpPathBusy), 0u); // sceGsSyncPath: nothing in flight + const int32_t count = static_cast(word(rdram, kVoBuf + 0xcu)); + const int32_t size = static_cast(word(rdram, kVoBuf + 0x10u)); + if (count > 0 && size > 0) // voBufGetTag: none while the buffer is empty + { + const int32_t index = static_cast(word(rdram, kVoBuf + 0x8u)); + setWord(rdram, gp + static_cast(kGpNewest), static_cast((index - 1 + size) % size)); + const uint32_t oldest = static_cast(((index - count + size) % size + size) % size); + const uint32_t tag = word(rdram, kVoBuf + 0x4u) + oldest * kVoTagStride; + const uint32_t state = word(rdram, tag); + const bool even = field == 0u; + if ((even && state == 2u) || (!even && state == 1u)) + { + presentMoviePicture(); + // loadImage's completion: a picture still held from before is freed first (handler_endimage). + const uint32_t held = gp + static_cast(kImageHeld); + if (word(rdram, held) != 0u) + { + setWord(rdram, held, 0u); + releaseMoviePicture(rdram); + } + setWord(rdram, tag, even ? 1u : 0u); + if (!even) + releaseMoviePicture(rdram); // its transfer has ended + setWord(rdram, gp + static_cast(kGpShown), 1u); + g_movieShownAt = bozo::port::vblankCount(runtime); + } + else if (count >= size && bozo::port::vblankCount(runtime) - g_movieShownAt == 120u) + { + // A full picture buffer and nothing shown for 120 fields: the decoder waits for a buffer. + std::fprintf(stderr, + "[tmb:movie] stall: picture buffer full (%d of %d, next %d), oldest tag %u state %u at field %u, " + "held %u, decoder state %u\n", + count, size, index, oldest, state, field, word(rdram, gp + static_cast(kImageHeld)), + word(rdram, kVideoDec + 0xa8u)); + } + } + } + setReturnS32(ctx, 0); + ctx->pc = getRegU32(ctx, 31); // jr $ra + } + + // The game's GS image transfers (native graphics off, a diagnostic): the game's handler, then what + // handler_endimage did when the transfer it started ended (the GIF DMA end interrupt, never raised): the + // picture loadImage replaced is freed after the handler sets its held flag. + void vblankHandlerOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (bozo::port::nativeGraphics(runtime)) + { + vblankHandlerNative(rdram, ctx, runtime); + return; + } + g_imageReplaced.store(false, std::memory_order_relaxed); + vblankHandler__Fi_0x1c1890(rdram, ctx, runtime); + if (!g_imageReplaced.exchange(false, std::memory_order_relaxed)) + return; + const uint32_t held = getRegU32(ctx, 28) + static_cast(kImageHeld); + if (word(rdram, held) == 0u) + return; + setWord(rdram, held, 0u); + const uint32_t count = word(rdram, kVoBuf + 0xcu); + if (static_cast(count) > 0) + setWord(rdram, kVoBuf + 0xcu, count - 1u); + } + + // updateBarVSyncCallback: each vblank the bar creeps one 1024th (until the next step sets the real progress) + // and the field parity flips; the buffer swap and the packet's DMA are the GS's, not done. + void barVSyncOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + const uint32_t gp = g_barGp.load(std::memory_order_relaxed); + if (!on() || gp == 0u) + { + updateBarVSyncCallback__Fi_0x202238(rdram, ctx, runtime); + return; + } + setWord(rdram, gp + kGpBarFlip, word(rdram, gp + kGpBarFlip) ^ 1u); + setWord(rdram, gp + kGpBarProgress, std::min(word(rdram, gp + kGpBarProgress) + 1u, 0x400u)); + loadingBar(rdram, gp); + ctx->pc = getRegU32(ctx, 31); // jr $ra + } + } + + // The view the game draws now (viewGetCurView), as a clip in GS primitive coordinates (x0, y0, x1, y1): where the GS + // scissor cut each view of a split screen. False before the game's gp is known. + bool viewClip(const uint8_t *rdram, float (&clip)[4]) + { + const uint32_t gp = g_gp.load(std::memory_order_relaxed); + if (gp == 0u || !rdram) + return false; + const View v = viewOf(rdram, word(rdram, gp + kGpCurView)); + if (v.w <= 0 || v.h <= 0) + return false; + clip[0] = static_cast(v.cx) - static_cast(v.w) * 0.5f; + clip[1] = static_cast(v.cy) - static_cast(v.h) * 0.5f; + clip[2] = static_cast(v.cx) + static_cast(v.w) * 0.5f; + clip[3] = static_cast(v.cy) + static_cast(v.h) * 0.5f; + return true; + } + + // At the end of a game frame (the adapter's publish): the 2D drawn since the last one goes on screen once the game + // sent it (fontDmaFontData); a frame end with nothing sent since leaves what shows (the menus end frames twice). + void publish() + { + if (!on()) + return; + // A level loading: its bar (no other 2D then). + if (const uint32_t barGp = g_barGp.load(std::memory_order_relaxed); barGp != 0u) + if (uint8_t *rdram = const_cast(g_rdram.load(std::memory_order_relaxed)); rdram && word(rdram, barGp + kGpBarShown) == 1u) + { + loadingBar(rdram, barGp); + return; + } + static uint32_t s_idle = 0; + if (g_flushed.exchange(false, std::memory_order_relaxed)) + s_idle = 0; + else if (++s_idle < 8u) + return; + // Mapped to the window by the game's own view 0 (its centre and size): a menu's 640 x 448, a match's 640 x 224. + const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed); + if (!rdram) + { + bozo::render::Renderer::instance().publishOverlay(); + return; + } + // The whole display: every view the game shows (viewGetNumViews), e.g. a rear view over the main one. + const uint32_t views = std::clamp(word(rdram, g_gp.load(std::memory_order_relaxed) + kGpNumViews), 1u, 4u); + float left = 1e9f, top = 1e9f, right = -1e9f, bottom = -1e9f; + for (uint32_t i = 0; i < views; ++i) + { + const View v = viewOf(rdram, i); + if (v.w <= 0 || v.h <= 0) + continue; + left = std::min(left, v.cx - v.w * 0.5f); + top = std::min(top, v.cy - v.h * 0.5f); + right = std::max(right, v.cx + v.w * 0.5f); + bottom = std::max(bottom, v.cy + v.h * 0.5f); + } + if (!(right > left && bottom > top)) + { + bozo::render::Renderer::instance().publishOverlay(); + return; + } + bozo::render::Screen screen; + screen.originX = left; + screen.originY = top; + screen.width = right - left; + screen.height = bottom - top; + bozo::render::Renderer::instance().publishOverlay(screen); + } + + void install(tmb::Registry &runtime) + { + runtime.registerFunction(kFontBuildPrim, &fontBuildPrimOverride); + runtime.registerFunction(kFontDmaFontData, &fontDmaFontDataOverride); + runtime.registerFunction(kRadar, &radarOverride); + runtime.registerFunction(kHealthBar, &healthBarOverride); + runtime.registerFunction(kSeparator, &separatorOverride); + runtime.registerFunction(kRearViewEdge, &rearViewEdgeOverride); + runtime.registerFunction(kLaser, &laserOverride); + runtime.registerFunction(k4pSeparator, &separator4pOverride); + runtime.registerFunction(kTurbo4p, &turbo4pOverride); + runtime.registerFunction(kEnergy4p, &energy4pOverride); + runtime.registerFunction(kHealth4p, &health4pOverride); + runtime.registerFunction(kChargeUp, &chargeUpOverride); + runtime.registerFunction(kBuildProgressBar, &buildProgressBarOverride); + runtime.registerFunction(kInformProgressBar, &informProgressBarOverride); + runtime.registerFunction(kBarVSync, &barVSyncOverride); + runtime.registerFunction(kFinishShellLoop, &finishShellLoopOverride); + bozo::port::setStorePatch(&dialogKick); + runtime.registerFunction(kLoadImage, &loadImageOverride); + runtime.registerFunction(kVblankHandler, &vblankHandlerOverride); + if (on()) + bozo::render::setMoviePictureHook(&moviePicture); + runtime.registerFunction(kOverheat, &overheatOverride); + } + // Save states (tmb_state.cpp): the pictures shown are the old run's. + void stateLoaded() + { + std::lock_guard lock(g_movieMutex); + g_moviePicture.reset(); + g_menuPicture.reset(); + } +} diff --git a/runtime/tmb_cheats.cpp b/runtime/tmb_cheats.cpp index 66a5c6a..f750a3d 100644 --- a/runtime/tmb_cheats.cpp +++ b/runtime/tmb_cheats.cpp @@ -1,461 +1,464 @@ -// 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 -#include -#include -#include -#include -#include -#include -#include - -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 g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0}; - std::atomic g_noAi{false}; - std::atomic 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 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 g_unlocked; // the lock words Unlock everything opened (put back when it goes off) - std::atomic g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off - std::atomic g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing) - std::atomic g_theGame{0}; - std::atomic 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 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(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(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(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(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6), - static_cast(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 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 &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(word(rdram, car + kEnergy)), static_cast(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(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(start)); - std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]); - } - s_lastLevel = static_cast(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(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(s_last[i]), - static_cast(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= (testing): every cheat switched on and off every 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(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(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(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(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(word(rdram, car + kEnergy)), - static_cast(word(rdram, car + kEnergyMax)), static_cast(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 +#include +#include +#include +#include +#include +#include +#include + +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 g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0}; + std::atomic g_noAi{false}; + std::atomic 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 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 g_unlocked; // the lock words Unlock everything opened (put back when it goes off) + std::atomic g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off + std::atomic g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing) + std::atomic g_theGame{0}; + std::atomic 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 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(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(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(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(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6), + static_cast(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 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 &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(word(rdram, car + kEnergy)), static_cast(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(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(start)); + std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]); + } + s_lastLevel = static_cast(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(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(s_last[i]), + static_cast(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= (testing): every cheat switched on and off every 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(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(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(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(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(word(rdram, car + kEnergy)), + static_cast(word(rdram, car + kEnergyMax)), static_cast(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); } +} diff --git a/runtime/tmb_meshes.cpp b/runtime/tmb_meshes.cpp index 1e0fcd3..6b13008 100644 --- a/runtime/tmb_meshes.cpp +++ b/runtime/tmb_meshes.cpp @@ -1,1167 +1,1168 @@ -// TMB's 3D objects drawn natively from the mesh pack (tools/tmb_mesh_pack.py: the disc's NGP files converted offline, -// generated_us/tmb_meshes.pack) and the EE state the game computes per object, at its per-object hook: no VIF or GIF -// packet is read for them. On with TMB_NATIVE=1; TMB_NATIVE_MESHES=0 turns it off. The kinds: rigid strips -// (setups 0xcc8, 0xd08, 0xce8, 0x1700), pool-less objects (the resume, 0xc78: the setup and pool of the object before -// them go on), sprites (0x3000), ribbons (0x3270), environment-mapped strips (0x1db8), skinned meshes (0x70, 0x90, -// 0xb0: their bones' matrices where skeletonTraverse wrote them, (*(inst + 0x14))[obj + 0x68]) and morphing objects -// (flag 42: setups 0xd28, 0xd48, 0xd68; three in the game, in CITY, MINICITY and FREEWAY). -// -// The morphing objects: their setups are the rigid ones' code (0xd28 = 0xcc8 unlit, 0xd48 = 0xce8 directional, 0xd68 -// = 0xd08 scaled: the same BAL to 0x1c08 and the same strip loop in vi13). What differs is their pool's vertex pass, -// MSCAL 2 (0x10 -> 0xd88) instead of MSCAL 0, which moves each position by its delta (the V3-32 @373 block, which the -// pack keeps) times VU 31 before the strips read it (it writes the moved position back at 181 + i). VU 31 is the -// morph weight pktAddVu1ObjAsm sends for flag 42 (UNPACK S-32 @31: in every lane the instance's float table entry -// obj+0x3c, (*(inst + 4))[*(s16 *)(obj + 0x3c)]; without an instance it sends none and VU 31 keeps the last one). -// -// - Which NGP file an object is in: fileOnlyNgpFile / fileAddNgpFile (address, size) after fileReadf / zipInflateAll -// read a file there (its name, tmb::textures::nameAt); the pack's file of that name, its size and CRC checked -// against the image as loaded. An object is keyed (file, obj - the file's address). -// - The object: pktAddVu1ObjAsm (hierTraverseAsm's per-object call; s5 the hierobject, s7 the instance, s0 the -// scratchpad cache, a3 "matrix changed", fp the flags' upper half). What the header it builds would put in VU1 +// TMB's 3D objects drawn natively from the mesh pack (tools/tmb_mesh_pack.py: the disc's NGP files converted offline, +// generated_us/tmb_meshes.pack) and the EE state the game computes per object, at its per-object hook: no VIF or GIF +// packet is read for them. On with TMB_NATIVE=1; TMB_NATIVE_MESHES=0 turns it off. The kinds: rigid strips +// (setups 0xcc8, 0xd08, 0xce8, 0x1700), pool-less objects (the resume, 0xc78: the setup and pool of the object before +// them go on), sprites (0x3000), ribbons (0x3270), environment-mapped strips (0x1db8), skinned meshes (0x70, 0x90, +// 0xb0: their bones' matrices where skeletonTraverse wrote them, (*(inst + 0x14))[obj + 0x68]) and morphing objects +// (flag 42: setups 0xd28, 0xd48, 0xd68; three in the game, in CITY, MINICITY and FREEWAY). +// +// The morphing objects: their setups are the rigid ones' code (0xd28 = 0xcc8 unlit, 0xd48 = 0xce8 directional, 0xd68 +// = 0xd08 scaled: the same BAL to 0x1c08 and the same strip loop in vi13). What differs is their pool's vertex pass, +// MSCAL 2 (0x10 -> 0xd88) instead of MSCAL 0, which moves each position by its delta (the V3-32 @373 block, which the +// pack keeps) times VU 31 before the strips read it (it writes the moved position back at 181 + i). VU 31 is the +// morph weight pktAddVu1ObjAsm sends for flag 42 (UNPACK S-32 @31: in every lane the instance's float table entry +// obj+0x3c, (*(inst + 4))[*(s16 *)(obj + 0x3c)]; without an instance it sends none and VU 31 keeps the last one). +// +// - Which NGP file an object is in: fileOnlyNgpFile / fileAddNgpFile (address, size) after fileReadf / zipInflateAll +// read a file there (its name, tmb::textures::nameAt); the pack's file of that name, its size and CRC checked +// against the image as loaded. An object is keyed (file, obj - the file's address). +// - The object: pktAddVu1ObjAsm (hierTraverseAsm's per-object call; s5 the hierobject, s7 the instance, s0 the +// scratchpad cache, a3 "matrix changed", fp the flags' upper half). What the header it builds would put in VU1 // memory now comes from native scene records: the object-to-camera matrix (when a3 says it changed, else the // last one), the car's light directions, and selected point lights. Historical checker hosts retain the original // VU0 context reads. Remaining per-object parameters come from game records: the -// texture offset (obj+0x20 / +0x24 or the instance's float table), depth factor and fog offset (obj+0x2c, +0x28: -// VU 4), the colour (obj+0x40 or the float table, times the fade in f20 / f22 and the car's colour: VU 5), the +// texture offset (obj+0x20 / +0x24 or the instance's float table), depth factor and fog offset (obj+0x2c, +0x28: +// VU 4), the colour (obj+0x40 or the float table, times the fade in f20 / f22 and the car's colour: VU 5), the // fog terms (the scratchpad cache -// pktCacheForAsm fills: VU 20-21), and the frame's camera, light colours and colour offset (VU 9-21: the constants -// block hier__Fi sends at each view, which the game keeps up to date in EE memory). The setup program is chosen +// pktCacheForAsm fills: VU 20-21), and the frame's camera, light colours and colour offset (VU 9-21: the constants +// block hier__Fi sends at each view, which the game keeps up to date in EE memory). The setup program is chosen // from the flags as pktAddVu1ObjAsm chooses it; the strips' maths are the adapter's (runtime/tmb_shading.h). -// - Vertex positions from the pack, each pool then read where the game keeps it in the loaded file (the pack gives -// its offset: a few meshes, a car's headlight beams among them, have their vertices moved by the game). -// - Textures by the object's texture numbers (obj+0x50[slot], tmb::textures::lookupId), with the TEX0 the game wrote -// in the object's register block (obj+0x70 + 0x30 * slot) for the size and palette. -// -// The draws are submitted in the order the game sends the objects, which its own calls give (no packet is read): -// a view's opaque objects in traversal order, then its alpha ones by the depth-sorted list pktLinkAlphaObjAsm builds -// (129 buckets of depth / 8, the farthest first, each bucket's newest first), when the view's chain is complete: -// hier__Fi's at its hierCheckVifComplete (right before its kick), hier2p's (a split screen's second view of a pair) at -// hier2pFlushDma, a view hier__Fi does not kick itself (the shell's menus) at the frame's end. Under the view's clip, -// before the particles drawn after it (particleDraw). The GS state of each draw (ALPHA_1, TEST_1, ZBUF_1.ZMSK) follows -// the objects in that order: the traversal's GS context block when the header brings one (a node's: its writes from the -// pack, recorded offline from the NGP files; the game's default one, ctxGetDefaultGSCtx: from EE memory), then the -// strips' register blocks. The skid marks' object (skidBuffer, which SkidMarks::draw fills each frame) is drawn from the -// marks themselves (skidSnapshot). Not drawn: hierObjectNode's C path (pktAddVu1Obj: not called in the arenas and -// menus seen), skinned objects without bones and resumes the pack path does not follow; their context blocks still -// count for the state. -// -// The generic parts are the fork's (PS2Recomp/docs/native_packs.md): the pack's container, loader and object store -// (runtime/native/native_mesh_pack.h: MeshPack, LoadedImages), the draws, the view's order, the GS state, the clip and -// the live toggles (runtime/native/native_mesh_draw.h: MeshDraw, MeshViewList, MeshSubmitter). What is TMB's here: the -// NGP files' binding, the hier hooks, the setup programs' meaning and shading, the GS context blocks' reading, the skid -// marks' object and the checks against the stream. -// -// TMB_NATIVE_VIF=1 (runtime/tmb_native.cpp): the adapter follows the VIF1 stream again; the hook marks the header's -// last qword (its VIF NOP's unused immediate) and the adapter submits the draws at that object's setup in the stream, -// with the stream's GS state (the comparison mode). With TMB_NATIVE_MESHES_CHECK=1 too, the draws stay in the game's -// order and the adapter reports, per object, the stream's order and GS state against them ([tmb:order]), besides its -// VU 0-21, matrix and strips against its own translation. - -#include "tmb_port.h" -#include "tmb_host.h" -#include "tmb_meshes.h" +// - Vertex positions from the pack, each pool then read where the game keeps it in the loaded file (the pack gives +// its offset: a few meshes, a car's headlight beams among them, have their vertices moved by the game). +// - Textures by the object's texture numbers (obj+0x50[slot], tmb::textures::lookupId), with the TEX0 the game wrote +// in the object's register block (obj+0x70 + 0x30 * slot) for the size and palette. +// +// The draws are submitted in the order the game sends the objects, which its own calls give (no packet is read): +// a view's opaque objects in traversal order, then its alpha ones by the depth-sorted list pktLinkAlphaObjAsm builds +// (129 buckets of depth / 8, the farthest first, each bucket's newest first), when the view's chain is complete: +// hier__Fi's at its hierCheckVifComplete (right before its kick), hier2p's (a split screen's second view of a pair) at +// hier2pFlushDma, a view hier__Fi does not kick itself (the shell's menus) at the frame's end. Under the view's clip, +// before the particles drawn after it (particleDraw). The GS state of each draw (ALPHA_1, TEST_1, ZBUF_1.ZMSK) follows +// the objects in that order: the traversal's GS context block when the header brings one (a node's: its writes from the +// pack, recorded offline from the NGP files; the game's default one, ctxGetDefaultGSCtx: from EE memory), then the +// strips' register blocks. The skid marks' object (skidBuffer, which SkidMarks::draw fills each frame) is drawn from the +// marks themselves (skidSnapshot). Not drawn: hierObjectNode's C path (pktAddVu1Obj: not called in the arenas and +// menus seen), skinned objects without bones and resumes the pack path does not follow; their context blocks still +// count for the state. +// +// The generic parts are the fork's (PS2Recomp/docs/native_packs.md): the pack's container, loader and object store +// (runtime/native/native_mesh_pack.h: MeshPack, LoadedImages), the draws, the view's order, the GS state, the clip and +// the live toggles (runtime/native/native_mesh_draw.h: MeshDraw, MeshViewList, MeshSubmitter). What is TMB's here: the +// NGP files' binding, the hier hooks, the setup programs' meaning and shading, the GS context blocks' reading, the skid +// marks' object and the checks against the stream. +// +// TMB_NATIVE_VIF=1 (runtime/tmb_native.cpp): the adapter follows the VIF1 stream again; the hook marks the header's +// last qword (its VIF NOP's unused immediate) and the adapter submits the draws at that object's setup in the stream, +// with the stream's GS state (the comparison mode). With TMB_NATIVE_MESHES_CHECK=1 too, the draws stay in the game's +// order and the adapter reports, per object, the stream's order and GS state against them ([tmb:order]), besides its +// VU 0-21, matrix and strips against its own translation. + +#include "bozo/state.h" +#include "tmb_port.h" +#include "tmb_host.h" +#include "tmb_meshes.h" #include "tmb_scene.h" #include "tmb_shading.h" -#include "bozo/render/mesh_draw.h" -#include "bozo/render/mesh_pack.h" -#include "bozo/render/renderer.h" -#include "bozo/render/texture.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef TMB_MESH_PACK -#define TMB_MESH_PACK "tmb_meshes.pack" -#endif - -namespace tmb::textures -{ - std::shared_ptr lookupId(uint32_t id, uint64_t tex0, uint64_t texa); - std::shared_ptr lookup(uint64_t tex0, uint64_t texa); - uint32_t idAtTbp(uint32_t tbp); - std::string nameAt(uint32_t address); -} -namespace tmb::textures::dump -{ - bool enabled(); -} - -namespace tmb::native -{ - bool enabled(); - bool vifObserved(); - void applyViewClip(); - uint32_t fogColour(); -} - -namespace tmb::meshes -{ - namespace - { - constexpr uint32_t kFileOnlyNgpFile = 0x001C2B18u; - constexpr uint32_t kFileAddNgpFile = 0x001C28A0u; - constexpr uint32_t kHierCacheForAsm = 0x002020E4u; - constexpr uint32_t kPktAddVu1ObjAsm = 0x001EAAE8u; - constexpr uint32_t kPktAddVu1Obj = 0x001E9BC0u; - // hierTraverseAsm's two calls of pktAddVu1ObjAsm: an opaque object (sent in traversal order) and an alpha one - // (linked into the depth-sorted list, sent after: it always sends its matrix and leaves VU1's matrix as is). - constexpr uint32_t kOpaqueReturn = 0x001D55B0u; - // The constants block hier__Fi sends to VU1 at each view (its VIF1 chain after the hier image's MPG): VU 5-8 - // from here, then VU 9-12, 13-16, 17-20, 21, each block after its STCYCL / UNPACK pair. An EE buffer the game - // keeps (the camera, plightUpdateParaLights' colours, fogUpdate's terms); no symbol holds it. - constexpr uint32_t kConstants = 0x002335F0u; +#include "bozo/render/mesh_draw.h" +#include "bozo/render/mesh_pack.h" +#include "bozo/render/renderer.h" +#include "bozo/render/texture.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef TMB_MESH_PACK +#define TMB_MESH_PACK "tmb_meshes.pack" +#endif + +namespace tmb::textures +{ + std::shared_ptr lookupId(uint32_t id, uint64_t tex0, uint64_t texa); + std::shared_ptr lookup(uint64_t tex0, uint64_t texa); + uint32_t idAtTbp(uint32_t tbp); + std::string nameAt(uint32_t address); +} +namespace tmb::textures::dump +{ + bool enabled(); +} + +namespace tmb::native +{ + bool enabled(); + bool vifObserved(); + void applyViewClip(); + uint32_t fogColour(); +} + +namespace tmb::meshes +{ + namespace + { + constexpr uint32_t kFileOnlyNgpFile = 0x001C2B18u; + constexpr uint32_t kFileAddNgpFile = 0x001C28A0u; + constexpr uint32_t kHierCacheForAsm = 0x002020E4u; + constexpr uint32_t kPktAddVu1ObjAsm = 0x001EAAE8u; + constexpr uint32_t kPktAddVu1Obj = 0x001E9BC0u; + // hierTraverseAsm's two calls of pktAddVu1ObjAsm: an opaque object (sent in traversal order) and an alpha one + // (linked into the depth-sorted list, sent after: it always sends its matrix and leaves VU1's matrix as is). + constexpr uint32_t kOpaqueReturn = 0x001D55B0u; + // The constants block hier__Fi sends to VU1 at each view (its VIF1 chain after the hier image's MPG): VU 5-8 + // from here, then VU 9-12, 13-16, 17-20, 21, each block after its STCYCL / UNPACK pair. An EE buffer the game + // keeps (the camera, plightUpdateParaLights' colours, fogUpdate's terms); no symbol holds it. + constexpr uint32_t kConstants = 0x002335F0u; constexpr uint32_t kDefaultLightRecords = kConstants + 0x10u; // VU 5-8 constexpr uint32_t kCameraRecord = kConstants + 0x58u; // VU 9-12 constexpr uint32_t kClipCameraRecord = kConstants + 0xa0u; // VU 13-16 constexpr uint32_t kLightColourRecords = kConstants + 0xe8u; // VU 17-20 constexpr uint32_t kFogRecord = kConstants + 0x130u; // VU 21 - - bool active() - { - static const bool s_on = [] - { - const char *value = std::getenv("TMB_NATIVE_MESHES"); - return !(value && *value == '0') && tmb::native::enabled(); // on with TMB_NATIVE=1 unless =0 - }(); - return s_on; - } - - // ---- the pack (the fork's MeshPack, runtime/native/native_mesh_pack.h) ---- - // - // TMB's objects in it (tools/tmb_mesh_pack.py): kind 0 rigid, 1 pool-less, 2 sprite, 3 ribbon, 4 skinned; the - // attributes (40 bytes) the hierobject's flags (obj+8, u64), bounding sphere (obj+0x10), ntex and texture - // numbers (obj+0x5a, obj+0x50) and, at 36, a pool-less object's pool object (the offset of the object whose - // pool it uses); the sections the morph deltas (kAux), where each pool's positions are in the image (kSources), - // the environment map's parameter batches (kParams) and a skinned object's bones and weights (kSkin); the - // file's register blocks the hier traversal's GS context blocks (ALPHA_1, TEST_1, ZBUF_1 writes). - using bozo::render::packs::MeshFile; - using bozo::render::packs::MeshObject; - using bozo::render::packs::MeshSection; - constexpr uint32_t kAux = bozo::render::packs::fourcc("AUX "); - constexpr uint32_t kSources = bozo::render::packs::fourcc("SRCS"); - constexpr uint32_t kParams = bozo::render::packs::fourcc("PRMS"); - constexpr uint32_t kSkin = bozo::render::packs::fourcc("SKIN"); - constexpr uint32_t kAttributeSize = 40u; - uint32_t poolFrom(const MeshObject &o) - { - return o.attributeSize >= kAttributeSize ? o.attribute(36u) : 0xffffffffu; - } - - template - T rd(const uint8_t *&p) - { - T v; - std::memcpy(&v, p, sizeof(T)); - p += sizeof(T); - return v; - } - - bozo::render::packs::MeshPack &pack() - { - static bozo::render::packs::MeshPack s_pack; - static bool s_loaded = false; - if (s_loaded) - return s_pack; - s_loaded = true; - const std::string pathText = packPath("TMB_MESH_PACK", TMB_MESH_PACK); - const char *path = pathText.c_str(); - if (!s_pack.load(path)) - { - if (s_pack.error() == "missing") - std::fprintf(stderr, "[tmb:mesh] no mesh pack at %s (tools/tmb_mesh_pack.py): objects stay on the stream path\n", path); - else - std::fprintf(stderr, "[tmb:mesh] %s: %s (%s: run tools/tmb_mesh_pack.py again)\n", path, s_pack.error().c_str(), - bozo::render::packs::MeshPack::kMagic); - return s_pack; - } - std::fprintf(stderr, "[tmb:mesh] mesh pack %s: %zu files, %zu objects\n", path, s_pack.files().size(), s_pack.objectCount()); - return s_pack; - } - - // ---- the NGP files as the game loaded them ---- - - bozo::render::packs::LoadedImages g_loaded; - - void noteNgp(uint8_t *rdram, R5900Context *ctx, bool only) - { - const uint32_t base = getRegU32(ctx, 4), size = getRegU32(ctx, 5); - const std::string name = tmb::textures::nameAt(base); - const bozo::render::packs::LoadedImages::Bound bound = g_loaded.bind(pack(), rdram, name, base, size, only); - if (bound.named && !bound.image.file) - std::fprintf(stderr, "[tmb:mesh] %s at %#x: %u bytes (crc %#x), the pack's is %u bytes (crc %#x): not used\n", name.c_str(), base, size, - bound.crc, bound.named->size, bound.named->crc); - std::fprintf(stderr, "[tmb:mesh] NGP %s at %#x (%u bytes)%s\n", name.empty() ? "?" : name.c_str(), base, size, - bound.image.file ? "" : ": no pack entry"); - } - - void fileOnlyNgpFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - noteNgp(rdram, ctx, true); - fileOnlyNgpFile__FPci_0x1c2b18(rdram, ctx, runtime); - } - void fileAddNgpFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - noteNgp(rdram, ctx, false); - fileAddNgpFile__FPci_0x1c28a0(rdram, ctx, runtime); - } - - // ---- EE memory ---- - - struct Ee - { - uint8_t *rdram; - uint8_t *scratch; - uint8_t *at(uint32_t address) const - { - return (address >> 28) == 7u ? scratch + (address & 0x3fffu) : rdram + (address & 0x1ffffffu); - } - uint32_t u32(uint32_t address) const - { - uint32_t v; - std::memcpy(&v, at(address), 4); - return v; - } - float f32(uint32_t address) const - { - float v; - std::memcpy(&v, at(address), 4); - return v; - } - int16_t s16(uint32_t address) const - { - int16_t v; - std::memcpy(&v, at(address), 2); - return v; - } - uint16_t u16(uint32_t address) const { return static_cast(s16(address)); } - uint64_t u64(uint32_t address) const - { - uint64_t v; - std::memcpy(&v, at(address), 8); - return v; - } - }; - - // The textures of every object of the loaded NGP files (TMB_TEXTURE_DUMP): each slot's texture number (obj + 0x50) - // and the TEX0 in its register block (obj + 0x70 + 0x30 * slot), looked up as a draw of it would be. - void dumpLoadedObjects(const uint8_t *rdram) - { - const auto u16 = [&](uint32_t a) { uint16_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 2); return v; }; - const auto u32 = [&](uint32_t a) { uint32_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 4); return v; }; - const auto u64 = [&](uint32_t a) { uint64_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 8); return v; }; - uint64_t objects = 0, slots = 0, found = 0; - g_loaded.forEach([&](const bozo::render::packs::LoadedImages::Image &image) - { - if (!image.file) - return true; - for (const bozo::render::packs::MeshObject &object : image.file->objects) - { - const uint32_t obj = image.base + object.offset; - ++objects; - const uint32_t count = std::min(u16(obj + 0x5au), 5u); - for (uint32_t slot = 0; slot < count; ++slot) - { - const uint32_t block = obj + 0x70u + 0x30u * slot; - for (uint32_t q = 0; q < 3u; ++q) - if ((u32(block + q * 16u + 8u) & 0xffu) == 0x06u) // TEX0_1 - { - ++slots; - if (tmb::textures::lookupId(u16(obj + 0x50u + 2u * slot), u64(block + q * 16u), 0u)) - ++found; - break; - } - } - } - return true; - }); - static uint64_t s_lastFound = ~0ull; - if (found != s_lastFound) - { - s_lastFound = found; - std::fprintf(stderr, "[tmb:texdump] loaded objects: %llu, texture slots %llu, %llu looked up\n", - static_cast(objects), static_cast(slots), - static_cast(found)); - } - } - - // ---- per object ---- - + + bool active() + { + static const bool s_on = [] + { + const char *value = std::getenv("TMB_NATIVE_MESHES"); + return !(value && *value == '0') && tmb::native::enabled(); // on with TMB_NATIVE=1 unless =0 + }(); + return s_on; + } + + // ---- the pack (the fork's MeshPack, runtime/native/native_mesh_pack.h) ---- + // + // TMB's objects in it (tools/tmb_mesh_pack.py): kind 0 rigid, 1 pool-less, 2 sprite, 3 ribbon, 4 skinned; the + // attributes (40 bytes) the hierobject's flags (obj+8, u64), bounding sphere (obj+0x10), ntex and texture + // numbers (obj+0x5a, obj+0x50) and, at 36, a pool-less object's pool object (the offset of the object whose + // pool it uses); the sections the morph deltas (kAux), where each pool's positions are in the image (kSources), + // the environment map's parameter batches (kParams) and a skinned object's bones and weights (kSkin); the + // file's register blocks the hier traversal's GS context blocks (ALPHA_1, TEST_1, ZBUF_1 writes). + using bozo::render::packs::MeshFile; + using bozo::render::packs::MeshObject; + using bozo::render::packs::MeshSection; + constexpr uint32_t kAux = bozo::render::packs::fourcc("AUX "); + constexpr uint32_t kSources = bozo::render::packs::fourcc("SRCS"); + constexpr uint32_t kParams = bozo::render::packs::fourcc("PRMS"); + constexpr uint32_t kSkin = bozo::render::packs::fourcc("SKIN"); + constexpr uint32_t kAttributeSize = 40u; + uint32_t poolFrom(const MeshObject &o) + { + return o.attributeSize >= kAttributeSize ? o.attribute(36u) : 0xffffffffu; + } + + template + T rd(const uint8_t *&p) + { + T v; + std::memcpy(&v, p, sizeof(T)); + p += sizeof(T); + return v; + } + + bozo::render::packs::MeshPack &pack() + { + static bozo::render::packs::MeshPack s_pack; + static bool s_loaded = false; + if (s_loaded) + return s_pack; + s_loaded = true; + const std::string pathText = packPath("TMB_MESH_PACK", TMB_MESH_PACK); + const char *path = pathText.c_str(); + if (!s_pack.load(path)) + { + if (s_pack.error() == "missing") + std::fprintf(stderr, "[tmb:mesh] no mesh pack at %s (tools/tmb_mesh_pack.py): objects stay on the stream path\n", path); + else + std::fprintf(stderr, "[tmb:mesh] %s: %s (%s: run tools/tmb_mesh_pack.py again)\n", path, s_pack.error().c_str(), + bozo::render::packs::MeshPack::kMagic); + return s_pack; + } + std::fprintf(stderr, "[tmb:mesh] mesh pack %s: %zu files, %zu objects\n", path, s_pack.files().size(), s_pack.objectCount()); + return s_pack; + } + + // ---- the NGP files as the game loaded them ---- + + bozo::render::packs::LoadedImages g_loaded; + + void noteNgp(uint8_t *rdram, R5900Context *ctx, bool only) + { + const uint32_t base = getRegU32(ctx, 4), size = getRegU32(ctx, 5); + const std::string name = tmb::textures::nameAt(base); + const bozo::render::packs::LoadedImages::Bound bound = g_loaded.bind(pack(), rdram, name, base, size, only); + if (bound.named && !bound.image.file) + std::fprintf(stderr, "[tmb:mesh] %s at %#x: %u bytes (crc %#x), the pack's is %u bytes (crc %#x): not used\n", name.c_str(), base, size, + bound.crc, bound.named->size, bound.named->crc); + std::fprintf(stderr, "[tmb:mesh] NGP %s at %#x (%u bytes)%s\n", name.empty() ? "?" : name.c_str(), base, size, + bound.image.file ? "" : ": no pack entry"); + } + + void fileOnlyNgpFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + noteNgp(rdram, ctx, true); + fileOnlyNgpFile__FPci_0x1c2b18(rdram, ctx, runtime); + } + void fileAddNgpFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + noteNgp(rdram, ctx, false); + fileAddNgpFile__FPci_0x1c28a0(rdram, ctx, runtime); + } + + // ---- EE memory ---- + + struct Ee + { + uint8_t *rdram; + uint8_t *scratch; + uint8_t *at(uint32_t address) const + { + return (address >> 28) == 7u ? scratch + (address & 0x3fffu) : rdram + (address & 0x1ffffffu); + } + uint32_t u32(uint32_t address) const + { + uint32_t v; + std::memcpy(&v, at(address), 4); + return v; + } + float f32(uint32_t address) const + { + float v; + std::memcpy(&v, at(address), 4); + return v; + } + int16_t s16(uint32_t address) const + { + int16_t v; + std::memcpy(&v, at(address), 2); + return v; + } + uint16_t u16(uint32_t address) const { return static_cast(s16(address)); } + uint64_t u64(uint32_t address) const + { + uint64_t v; + std::memcpy(&v, at(address), 8); + return v; + } + }; + + // The textures of every object of the loaded NGP files (TMB_TEXTURE_DUMP): each slot's texture number (obj + 0x50) + // and the TEX0 in its register block (obj + 0x70 + 0x30 * slot), looked up as a draw of it would be. + void dumpLoadedObjects(const uint8_t *rdram) + { + const auto u16 = [&](uint32_t a) { uint16_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 2); return v; }; + const auto u32 = [&](uint32_t a) { uint32_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 4); return v; }; + const auto u64 = [&](uint32_t a) { uint64_t v; std::memcpy(&v, rdram + (a & 0x1ffffffu), 8); return v; }; + uint64_t objects = 0, slots = 0, found = 0; + g_loaded.forEach([&](const bozo::render::packs::LoadedImages::Image &image) + { + if (!image.file) + return true; + for (const bozo::render::packs::MeshObject &object : image.file->objects) + { + const uint32_t obj = image.base + object.offset; + ++objects; + const uint32_t count = std::min(u16(obj + 0x5au), 5u); + for (uint32_t slot = 0; slot < count; ++slot) + { + const uint32_t block = obj + 0x70u + 0x30u * slot; + for (uint32_t q = 0; q < 3u; ++q) + if ((u32(block + q * 16u + 8u) & 0xffu) == 0x06u) // TEX0_1 + { + ++slots; + if (tmb::textures::lookupId(u16(obj + 0x50u + 2u * slot), u64(block + q * 16u), 0u)) + ++found; + break; + } + } + } + return true; + }); + static uint64_t s_lastFound = ~0ull; + if (found != s_lastFound) + { + s_lastFound = found; + std::fprintf(stderr, "[tmb:texdump] loaded objects: %llu, texture slots %llu, %llu looked up\n", + static_cast(objects), static_cast(slots), + static_cast(found)); + } + } + + // ---- per object ---- + tmb::shading::RetainedParameters g_checkerRetained; tmb::shading::RetainedParameters &retained(Runtime *runtime) { return bozo::port::nativeGraphics(runtime) ? tmb::scene::get(runtime).renderer : g_checkerRetained; } - - // The opaque object sent last (the chain's order), when this path drew it: what the resume (MSCAL 0xc78, the - // pool-less objects after it) goes on with, its setup, its object-to-screen matrix (vf1-4, before the depth - // factor) and the point lights VU1 then holds. - struct Previous - { - bool valid = false; - uint32_t file = 0, offset = 0, poolFrom = 0, pc = 0; - float screen[16] = {}, clip[16] = {}; - float object[16] = {}; // its object-to-camera matrix (VU 0-3), for interpolation's parts + + // The opaque object sent last (the chain's order), when this path drew it: what the resume (MSCAL 0xc78, the + // pool-less objects after it) goes on with, its setup, its object-to-screen matrix (vf1-4, before the depth + // factor) and the point lights VU1 then holds. + struct Previous + { + bool valid = false; + uint32_t file = 0, offset = 0, poolFrom = 0, pc = 0; + float screen[16] = {}, clip[16] = {}; + float object[16] = {}; // its object-to-camera matrix (VU 0-3), for interpolation's parts tmb::shading::PointLighting pointLights{}; - } g_previous; - - std::unordered_map g_drawn; // mark -> the object's draws - uint32_t g_nextMark = 1; - uint32_t g_frame = 0; - std::unordered_map g_keysThisFrame; - const uint8_t *g_rdramForDump = nullptr; // TMB_NATIVE_MESHES_DUMP - uint32_t g_firstSkinned = 0; // the frame of the first skinned object at the hook - - struct Stats - { - uint64_t calls = 0, cCalls = 0, drawn = 0, taken = 0, unclaimed = 0, noFile = 0, noObject = 0, kindOther = 0, - program = 0, extra = 0, unmarked = 0, triangles = 0, idMismatch = 0, resumed = 0, resumeOther = 0, sprites = 0, ribbons = 0, - skinned = 0, reflective = 0, morphed = 0, contextsPack = 0, contextsDefault = 0, contextsMissing = 0, - contextsDiffering = 0, skid = 0; - } g_stats; - - void vf(const R5900Context *ctx, int reg, float out[4]) { std::memcpy(out, ctx->vu0_vf[reg].f, 16); } - - // ---- the game's order ---- - // - // hier__Fi (and hier2p, the split screen's second view of a pair) builds a view's chain: the opaque objects in - // traversal order (pktAddVu1ObjAsm), each alpha one linked into a depth-sorted list of 129 buckets - // (pktInitReverseAlphaOT, pktLinkAlphaObjAsm: bucket depth / 8 + 1, 1 up to 8, clamped at 1016; a bucket's newest - // first), which pktAttachAlphaOT hangs after them, farthest bucket first. hier__Fi kicks its chain before it - // returns (hierFlushObjQ), hier2p's waits for hier2pFlushDma (the next view's turn in rtMain). The draws are - // submitted there, in that order, under the view's clip: what reached VU1 in that order. The particles, - // drawn after the view (particleDraw), come after them. - - constexpr uint32_t kHierCheckVifComplete = 0x001D47C8u; - constexpr uint32_t kHierKickReturn = 0x001D3400u; // hier__Fi's call of hierCheckVifComplete, before its kick - constexpr uint32_t kHier2pFlushDma = 0x001D28F0u; - constexpr uint32_t kHier2pCacheReturn = 0x001D2B24u; // hier2p's call of hierCacheForAsm, its view's start - constexpr uint32_t kPktLinkAlphaObjAsm = 0x001EAF84u; - - bool g_inHier2pFlush = false; - uint64_t g_unsentFlushes = 0; // views submitted at the frame's end (not kicked by hier__Fi) - uint64_t g_listDrops = 0, g_submitted[2] = {}, g_built[2] = {}, g_kicks[2] = {}; - // The vertex arrays of the objects drawn last, kept (cleared) for the next objects' batches: each one grew from - // nothing every frame, a few hundred objects' worth of allocations and copies (the game thread only). - std::vector> g_vertexPool; - - void recycleVertices(Drawn &drawn) - { - for (auto &batch : drawn.batches) - if (batch.vertices.capacity() != 0u && g_vertexPool.size() < 8192u) - { - batch.vertices.clear(); - g_vertexPool.push_back(std::move(batch.vertices)); - } - } - - std::vector pooledVertices() - { - if (g_vertexPool.empty()) - return {}; - std::vector vertices = std::move(g_vertexPool.back()); - g_vertexPool.pop_back(); - return vertices; - } - - struct ViewList : bozo::render::MeshViewList - { - // Built by hier2p: sent only by hier2pFlushDma. On the frame a split screen ends hier2p builds its view once - // more and nothing sends it (the game drops the chain), so it is dropped too rather than drawn in the next view. - bool hier2p = false; - void clear() - { - for (Drawn &drawn : opaque) - recycleVertices(drawn); - for (std::vector &bucket : buckets) - for (Drawn &drawn : bucket) - recycleVertices(drawn); - MeshViewList::clear(); - hier2p = false; - } - }; - // The view being built (the hook's objects): hier__Fi's until its kick, hier2p's until hier2pFlushDma. - ViewList g_lists[1]; - constexpr int g_building = 0; - - // The GS registers the hier objects' draws depend on, as their context and register blocks leave them in the - // order the objects are sent (they persist from one object to the next, as in the GS): the submitter's - // (runtime/native/native_mesh_draw.h), which follows them, makes each batch's material and clips its triangles. - using GsState = bozo::render::MeshGsState; - bozo::render::MeshSubmitter g_submitter; - - // A batch's material as the GS state has it (TMB_NATIVE_MESHES_CHECK compares it with the stream's). - struct Mat - { - uint64_t alpha = 0; // ALPHA_1 when blended, else 0 - uint64_t test = 0; - bool depthMasked = false; - bool operator==(const Mat &o) const { return alpha == o.alpha && test == o.test && depthMasked == o.depthMasked; } - }; - Mat matFor(const GsState &gs, const Batch &batch) - { - return Mat{batch.blended ? gs.alpha : 0u, gs.test, gs.depthMasked}; - } - - // TMB_NATIVE_VIF=1 with TMB_NATIVE_MESHES_CHECK=1: per mark, the hook's order and materials and the stream's. - struct CheckRecord - { - uint32_t frame = 0; - uint64_t hookOrder = ~0ull, streamOrder = ~0ull; - std::vector hook; - std::vector sets; // the batches' register writes (no vertices), the context's first - bool hasContext = false; - GsState stream; - bool streamSeen = false; - uint32_t object = 0, index = 0, frameOfKick = 0; - bool alphaList = false; - }; - std::unordered_map g_checks; - uint64_t g_hookSeq = 0, g_streamSeq = 0; - uint32_t g_submitIndex = 0; // the object's place in its view's chain - - bool checking() - { - static const bool s_on = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr; - return s_on; - } - - // TMB_LIVE_TOGGLES= (a diagnostic): words read from the file every 60 frames, while the game runs: - // nodepth (the hier objects drawn without the depth test), nofog, noclip (no view clip), flat (each object - // untextured in a colour of its own), opaque, noatest, notex, noguard (no clip volume), dump. - bozo::render::MeshLiveToggles &g_live = g_submitter.live; - void readLiveToggles() - { - static const char *s_path = std::getenv("TMB_LIVE_TOGGLES"); - if (!s_path) - return; - g_live.read(s_path, g_frame, "tmb"); - } - - // TMB_NATIVE_MESHES_CHECK=1: what the submitter applies, per marked object, recorded for compareOrders. - struct CheckObserver : bozo::render::MeshSubmitter::Observer - { - CheckRecord *record = nullptr; - void draw(const bozo::render::MeshDraw &d) override - { - const Drawn &drawn = static_cast(d); - record = nullptr; - if (drawn.mark == 0u) - return; - record = &g_checks[drawn.mark]; - record->frame = drawn.frame; - record->hookOrder = g_hookSeq++; - record->hasContext = drawn.hasContext; - record->object = drawn.object, record->alphaList = drawn.alphaList, record->index = g_submitIndex++; - if (drawn.hasContext) - record->sets.push_back(drawn.context); - } - void batch(const Batch &batch, const GsState &gs) override - { - if (!record) - return; - Batch sets; - sets.setsAlpha = batch.setsAlpha, sets.alpha = batch.alpha, sets.setsTest = batch.setsTest, sets.test = batch.test; - sets.setsZbuf = batch.setsZbuf, sets.depthMasked = batch.depthMasked, sets.blended = batch.blended; - sets.textured = !batch.vertices.empty(); // (whether it draws) - record->sets.push_back(sets); - if (!batch.vertices.empty()) - record->hook.push_back(matFor(gs, batch)); - } - } g_checkObserver; - - // A GS context block as the traversal keeps it (s4: the default one, ctxGetDefaultGSCtx, or a node's): its first - // quadword's VIF codes FLUSH, DIRECT n, then a PACKED GIF tag of n - 1 A+D writes. The writes this path follows. - bool readContext(const Ee &ee, uint32_t at, Batch &out) - { - const uint32_t code = ee.u32(at + 12u); - if (((code >> 24) & 0x7eu) != 0x50u) - return false; - const uint64_t tag = ee.u64(at + 16u), regs = ee.u64(at + 24u); - const uint32_t nloop = tag & 0x7fffu, flg = (tag >> 58) & 3u, nreg = (tag >> 60) & 0xfu; - if (flg != 0u || nreg != 1u || (regs & 0xfu) != 0xeu || nloop + 1u > (code & 0xffffu)) - return false; - for (uint32_t q = 0; q < nloop; ++q) - { - const uint64_t value = ee.u64(at + 32u + q * 16u); - const uint32_t address = ee.u32(at + 40u + q * 16u) & 0xffu; - if (address == 0x42u) - out.setsAlpha = true, out.alpha = value; - else if (address == 0x47u) - out.setsTest = true, out.test = value; - else if (address == 0x4eu) - out.setsZbuf = true, out.depthMasked = ((value >> 32) & 1u) != 0u; - } - return true; - } - - // The context block at `at`: from the pack when it is in a loaded NGP file, else the game's default context - // (the executable's data, as defaultContextInit / ctxGetDefaultGSCtx leave it in EE memory). - bool contextAt(const Ee &ee, uint32_t at, Batch &out) - { - const MeshFile *file = nullptr; - uint32_t base = 0; - g_loaded.forEach([&](const bozo::render::packs::LoadedImages::Image &l) - { - if (at >= l.base && at < l.base + l.size) - { - file = l.file; - base = l.base; - if (!file) - return false; - } - return true; - }); - if (!file) - { - if (at >= 0x00980000u && (at & 0x1ffffffu) < 0x02000000u && base != 0u) - { - ++g_stats.contextsMissing; // in a loaded file the pack does not have - return false; - } - ++g_stats.contextsDefault; - return readContext(ee, at, out); - } - const bozo::render::packs::RegisterBlock *block = file->block(at - base); - if (!block) - { - ++g_stats.contextsMissing; - static uint32_t s_logged = 0; - if (s_logged++ < 20u) - std::fprintf(stderr, "[tmb:mesh] GS context at %#x (%s + %#x): not in the pack\n", at, file->name.c_str(), at - base); - return false; - } - ++g_stats.contextsPack; - out.setsAlpha = false, out.alpha = 0; - out.setsTest = false, out.test = 0; - out.setsZbuf = false, out.depthMasked = false; - for (const auto &[address, value] : block->writes) - { - if (address == 0x42u) - out.setsAlpha = true, out.alpha = value; - else if (address == 0x47u) - out.setsTest = true, out.test = value; - else if (address == 0x4eu) - out.setsZbuf = true, out.depthMasked = ((value >> 32) & 1u) != 0u; - } - if (checking()) // the pack's against the block as the game has it now - { - Batch now; - if (!readContext(ee, at, now) || now.setsAlpha != out.setsAlpha || now.alpha != out.alpha || now.setsTest != out.setsTest || - now.test != out.test || now.setsZbuf != out.setsZbuf || now.depthMasked != out.depthMasked) - { - ++g_stats.contextsDiffering; - static uint32_t s_logged = 0; - if (s_logged++ < 20u) - std::fprintf(stderr, "[tmb:mesh] GS context at %#x (%s + %#x): the pack's differs from EE memory's\n", at, file->name.c_str(), - at - base); - } - } - return true; - } - + } g_previous; + + std::unordered_map g_drawn; // mark -> the object's draws + uint32_t g_nextMark = 1; + uint32_t g_frame = 0; + std::unordered_map g_keysThisFrame; + const uint8_t *g_rdramForDump = nullptr; // TMB_NATIVE_MESHES_DUMP + uint32_t g_firstSkinned = 0; // the frame of the first skinned object at the hook + + struct Stats + { + uint64_t calls = 0, cCalls = 0, drawn = 0, taken = 0, unclaimed = 0, noFile = 0, noObject = 0, kindOther = 0, + program = 0, extra = 0, unmarked = 0, triangles = 0, idMismatch = 0, resumed = 0, resumeOther = 0, sprites = 0, ribbons = 0, + skinned = 0, reflective = 0, morphed = 0, contextsPack = 0, contextsDefault = 0, contextsMissing = 0, + contextsDiffering = 0, skid = 0; + } g_stats; + + void vf(const R5900Context *ctx, int reg, float out[4]) { std::memcpy(out, ctx->vu0_vf[reg].f, 16); } + + // ---- the game's order ---- + // + // hier__Fi (and hier2p, the split screen's second view of a pair) builds a view's chain: the opaque objects in + // traversal order (pktAddVu1ObjAsm), each alpha one linked into a depth-sorted list of 129 buckets + // (pktInitReverseAlphaOT, pktLinkAlphaObjAsm: bucket depth / 8 + 1, 1 up to 8, clamped at 1016; a bucket's newest + // first), which pktAttachAlphaOT hangs after them, farthest bucket first. hier__Fi kicks its chain before it + // returns (hierFlushObjQ), hier2p's waits for hier2pFlushDma (the next view's turn in rtMain). The draws are + // submitted there, in that order, under the view's clip: what reached VU1 in that order. The particles, + // drawn after the view (particleDraw), come after them. + + constexpr uint32_t kHierCheckVifComplete = 0x001D47C8u; + constexpr uint32_t kHierKickReturn = 0x001D3400u; // hier__Fi's call of hierCheckVifComplete, before its kick + constexpr uint32_t kHier2pFlushDma = 0x001D28F0u; + constexpr uint32_t kHier2pCacheReturn = 0x001D2B24u; // hier2p's call of hierCacheForAsm, its view's start + constexpr uint32_t kPktLinkAlphaObjAsm = 0x001EAF84u; + + bool g_inHier2pFlush = false; + uint64_t g_unsentFlushes = 0; // views submitted at the frame's end (not kicked by hier__Fi) + uint64_t g_listDrops = 0, g_submitted[2] = {}, g_built[2] = {}, g_kicks[2] = {}; + // The vertex arrays of the objects drawn last, kept (cleared) for the next objects' batches: each one grew from + // nothing every frame, a few hundred objects' worth of allocations and copies (the game thread only). + std::vector> g_vertexPool; + + void recycleVertices(Drawn &drawn) + { + for (auto &batch : drawn.batches) + if (batch.vertices.capacity() != 0u && g_vertexPool.size() < 8192u) + { + batch.vertices.clear(); + g_vertexPool.push_back(std::move(batch.vertices)); + } + } + + std::vector pooledVertices() + { + if (g_vertexPool.empty()) + return {}; + std::vector vertices = std::move(g_vertexPool.back()); + g_vertexPool.pop_back(); + return vertices; + } + + struct ViewList : bozo::render::MeshViewList + { + // Built by hier2p: sent only by hier2pFlushDma. On the frame a split screen ends hier2p builds its view once + // more and nothing sends it (the game drops the chain), so it is dropped too rather than drawn in the next view. + bool hier2p = false; + void clear() + { + for (Drawn &drawn : opaque) + recycleVertices(drawn); + for (std::vector &bucket : buckets) + for (Drawn &drawn : bucket) + recycleVertices(drawn); + MeshViewList::clear(); + hier2p = false; + } + }; + // The view being built (the hook's objects): hier__Fi's until its kick, hier2p's until hier2pFlushDma. + ViewList g_lists[1]; + constexpr int g_building = 0; + + // The GS registers the hier objects' draws depend on, as their context and register blocks leave them in the + // order the objects are sent (they persist from one object to the next, as in the GS): the submitter's + // (runtime/native/native_mesh_draw.h), which follows them, makes each batch's material and clips its triangles. + using GsState = bozo::render::MeshGsState; + bozo::render::MeshSubmitter g_submitter; + + // A batch's material as the GS state has it (TMB_NATIVE_MESHES_CHECK compares it with the stream's). + struct Mat + { + uint64_t alpha = 0; // ALPHA_1 when blended, else 0 + uint64_t test = 0; + bool depthMasked = false; + bool operator==(const Mat &o) const { return alpha == o.alpha && test == o.test && depthMasked == o.depthMasked; } + }; + Mat matFor(const GsState &gs, const Batch &batch) + { + return Mat{batch.blended ? gs.alpha : 0u, gs.test, gs.depthMasked}; + } + + // TMB_NATIVE_VIF=1 with TMB_NATIVE_MESHES_CHECK=1: per mark, the hook's order and materials and the stream's. + struct CheckRecord + { + uint32_t frame = 0; + uint64_t hookOrder = ~0ull, streamOrder = ~0ull; + std::vector hook; + std::vector sets; // the batches' register writes (no vertices), the context's first + bool hasContext = false; + GsState stream; + bool streamSeen = false; + uint32_t object = 0, index = 0, frameOfKick = 0; + bool alphaList = false; + }; + std::unordered_map g_checks; + uint64_t g_hookSeq = 0, g_streamSeq = 0; + uint32_t g_submitIndex = 0; // the object's place in its view's chain + + bool checking() + { + static const bool s_on = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr; + return s_on; + } + + // TMB_LIVE_TOGGLES= (a diagnostic): words read from the file every 60 frames, while the game runs: + // nodepth (the hier objects drawn without the depth test), nofog, noclip (no view clip), flat (each object + // untextured in a colour of its own), opaque, noatest, notex, noguard (no clip volume), dump. + bozo::render::MeshLiveToggles &g_live = g_submitter.live; + void readLiveToggles() + { + static const char *s_path = std::getenv("TMB_LIVE_TOGGLES"); + if (!s_path) + return; + g_live.read(s_path, g_frame, "tmb"); + } + + // TMB_NATIVE_MESHES_CHECK=1: what the submitter applies, per marked object, recorded for compareOrders. + struct CheckObserver : bozo::render::MeshSubmitter::Observer + { + CheckRecord *record = nullptr; + void draw(const bozo::render::MeshDraw &d) override + { + const Drawn &drawn = static_cast(d); + record = nullptr; + if (drawn.mark == 0u) + return; + record = &g_checks[drawn.mark]; + record->frame = drawn.frame; + record->hookOrder = g_hookSeq++; + record->hasContext = drawn.hasContext; + record->object = drawn.object, record->alphaList = drawn.alphaList, record->index = g_submitIndex++; + if (drawn.hasContext) + record->sets.push_back(drawn.context); + } + void batch(const Batch &batch, const GsState &gs) override + { + if (!record) + return; + Batch sets; + sets.setsAlpha = batch.setsAlpha, sets.alpha = batch.alpha, sets.setsTest = batch.setsTest, sets.test = batch.test; + sets.setsZbuf = batch.setsZbuf, sets.depthMasked = batch.depthMasked, sets.blended = batch.blended; + sets.textured = !batch.vertices.empty(); // (whether it draws) + record->sets.push_back(sets); + if (!batch.vertices.empty()) + record->hook.push_back(matFor(gs, batch)); + } + } g_checkObserver; + + // A GS context block as the traversal keeps it (s4: the default one, ctxGetDefaultGSCtx, or a node's): its first + // quadword's VIF codes FLUSH, DIRECT n, then a PACKED GIF tag of n - 1 A+D writes. The writes this path follows. + bool readContext(const Ee &ee, uint32_t at, Batch &out) + { + const uint32_t code = ee.u32(at + 12u); + if (((code >> 24) & 0x7eu) != 0x50u) + return false; + const uint64_t tag = ee.u64(at + 16u), regs = ee.u64(at + 24u); + const uint32_t nloop = tag & 0x7fffu, flg = (tag >> 58) & 3u, nreg = (tag >> 60) & 0xfu; + if (flg != 0u || nreg != 1u || (regs & 0xfu) != 0xeu || nloop + 1u > (code & 0xffffu)) + return false; + for (uint32_t q = 0; q < nloop; ++q) + { + const uint64_t value = ee.u64(at + 32u + q * 16u); + const uint32_t address = ee.u32(at + 40u + q * 16u) & 0xffu; + if (address == 0x42u) + out.setsAlpha = true, out.alpha = value; + else if (address == 0x47u) + out.setsTest = true, out.test = value; + else if (address == 0x4eu) + out.setsZbuf = true, out.depthMasked = ((value >> 32) & 1u) != 0u; + } + return true; + } + + // The context block at `at`: from the pack when it is in a loaded NGP file, else the game's default context + // (the executable's data, as defaultContextInit / ctxGetDefaultGSCtx leave it in EE memory). + bool contextAt(const Ee &ee, uint32_t at, Batch &out) + { + const MeshFile *file = nullptr; + uint32_t base = 0; + g_loaded.forEach([&](const bozo::render::packs::LoadedImages::Image &l) + { + if (at >= l.base && at < l.base + l.size) + { + file = l.file; + base = l.base; + if (!file) + return false; + } + return true; + }); + if (!file) + { + if (at >= 0x00980000u && (at & 0x1ffffffu) < 0x02000000u && base != 0u) + { + ++g_stats.contextsMissing; // in a loaded file the pack does not have + return false; + } + ++g_stats.contextsDefault; + return readContext(ee, at, out); + } + const bozo::render::packs::RegisterBlock *block = file->block(at - base); + if (!block) + { + ++g_stats.contextsMissing; + static uint32_t s_logged = 0; + if (s_logged++ < 20u) + std::fprintf(stderr, "[tmb:mesh] GS context at %#x (%s + %#x): not in the pack\n", at, file->name.c_str(), at - base); + return false; + } + ++g_stats.contextsPack; + out.setsAlpha = false, out.alpha = 0; + out.setsTest = false, out.test = 0; + out.setsZbuf = false, out.depthMasked = false; + for (const auto &[address, value] : block->writes) + { + if (address == 0x42u) + out.setsAlpha = true, out.alpha = value; + else if (address == 0x47u) + out.setsTest = true, out.test = value; + else if (address == 0x4eu) + out.setsZbuf = true, out.depthMasked = ((value >> 32) & 1u) != 0u; + } + if (checking()) // the pack's against the block as the game has it now + { + Batch now; + if (!readContext(ee, at, now) || now.setsAlpha != out.setsAlpha || now.alpha != out.alpha || now.setsTest != out.setsTest || + now.test != out.test || now.setsZbuf != out.setsZbuf || now.depthMasked != out.depthMasked) + { + ++g_stats.contextsDiffering; + static uint32_t s_logged = 0; + if (s_logged++ < 20u) + std::fprintf(stderr, "[tmb:mesh] GS context at %#x (%s + %#x): the pack's differs from EE memory's\n", at, file->name.c_str(), + at - base); + } + } + return true; + } + template T record(const Ee &ee, uint32_t address) - { + { T out; std::memcpy(&out, ee.at(address), sizeof(out)); return out; - } - - // The setup pktAddVu1ObjAsm picks for these flags (its upper half, fp), clip state (s6), point lights and - // skeleton, in its order. - uint32_t setupFor(uint32_t fp, uint32_t s6, bool pointLights, bool skinned) - { - if (fp & 0x1000u) - return 0x0c78u; // bit 44: MSCAL 0xc78, the resume (the pool-less objects: the setup before them goes on) - if (skinned) - return (fp & 0x100u) ? 0x0070u : s6 == 1u ? 0x00b0u : 0x0090u; // directional, unlit (scaled), unlit - if ((fp >> 1) & 7u) - return 0x1db8u; // bits 33-35: environment map - const uint32_t sprite = (fp >> 5) & 3u; - if (sprite == 1u) - return 0x3270u; // ribbon - if (sprite == 2u) - return 0x3000u; // sprite - if ((fp >> 10) & 1u) - return (fp & 0x100u) ? 0x0d48u : s6 == 1u ? 0x0d68u : 0x0d28u; // bit 42: morph (directional, scaled, unlit) - if (pointLights) - return 0x1700u; - if (fp & 0x100u) - return 0x0ce8u; - return s6 == 1u ? 0x0d08u : 0x0cc8u; - } - - // The object's strips from the pack, shaded as the setup's strip program shades them. - // screen: the setup's matrix before the depth factor when it is not this object's (a resume), else null. - // bones: a skinned object's bone matrices in EE memory (16 floats each), else 0. + } + + // The setup pktAddVu1ObjAsm picks for these flags (its upper half, fp), clip state (s6), point lights and + // skeleton, in its order. + uint32_t setupFor(uint32_t fp, uint32_t s6, bool pointLights, bool skinned) + { + if (fp & 0x1000u) + return 0x0c78u; // bit 44: MSCAL 0xc78, the resume (the pool-less objects: the setup before them goes on) + if (skinned) + return (fp & 0x100u) ? 0x0070u : s6 == 1u ? 0x00b0u : 0x0090u; // directional, unlit (scaled), unlit + if ((fp >> 1) & 7u) + return 0x1db8u; // bits 33-35: environment map + const uint32_t sprite = (fp >> 5) & 3u; + if (sprite == 1u) + return 0x3270u; // ribbon + if (sprite == 2u) + return 0x3000u; // sprite + if ((fp >> 10) & 1u) + return (fp & 0x100u) ? 0x0d48u : s6 == 1u ? 0x0d68u : 0x0d28u; // bit 42: morph (directional, scaled, unlit) + if (pointLights) + return 0x1700u; + if (fp & 0x100u) + return 0x0ce8u; + return s6 == 1u ? 0x0d08u : 0x0cc8u; + } + + // The object's strips from the pack, shaded as the setup's strip program shades them. + // screen: the setup's matrix before the depth factor when it is not this object's (a resume), else null. + // bones: a skinned object's bone matrices in EE memory (16 floats each), else 0. void buildStrips(const tmb::shading::Parameters ¶meters, const Ee &ee, uint32_t obj, uint32_t fileBase, const MeshObject &object, uint32_t pc, Drawn &out, - const float *screen = nullptr, uint32_t bones = 0u) - { + const float *screen = nullptr, uint32_t bones = 0u) + { const tmb::shading::Shading mode = pc == 0x0ce8u || pc == 0x0d48u ? tmb::shading::Shading::Directional : pc == 0x1700u ? tmb::shading::Shading::Point : tmb::shading::Shading::Unlit; - // Sprites and ribbons: screen-space vertices, from the setup's matrix without the depth factor (their - // programs scale z themselves). - // The lit skinned strips (0x640) do not scale z either; the unlit ones (0x878, 0x9e8) do. - const bool sprite = pc == 0x3000u, ribbon = pc == 0x3270u; - out.screenSpace = sprite || ribbon; - const bool depthScaled = !out.screenSpace && pc != 0x0070u; - if (screen) - { - std::memcpy(out.matrix, screen, sizeof(out.matrix)); - if (depthScaled) - for (int j = 0; j < 4; ++j) + // Sprites and ribbons: screen-space vertices, from the setup's matrix without the depth factor (their + // programs scale z themselves). + // The lit skinned strips (0x640) do not scale z either; the unlit ones (0x878, 0x9e8) do. + const bool sprite = pc == 0x3000u, ribbon = pc == 0x3270u; + out.screenSpace = sprite || ribbon; + const bool depthScaled = !out.screenSpace && pc != 0x0070u; + if (screen) + { + std::memcpy(out.matrix, screen, sizeof(out.matrix)); + if (depthScaled) + for (int j = 0; j < 4; ++j) out.matrix[j * 4 + 2] *= parameters.depthScale; - } - else + } + else tmb::shading::objectToScreen(parameters, out.matrix, depthScaled); - const float *m = out.matrix; - const uint32_t positionCount = object.positionCount; - // x, y, z, w: the pack's, then each pool's from where the game keeps it in the loaded file (the V3-32 data of - // its packet: a few meshes have their vertices moved by the game, a car's headlight beams among them). - static thread_local std::vector s_positions; - s_positions.assign(object.positions, object.positions + static_cast(positionCount) * 4u); - // The morph deltas (the pools' @373 blocks), per position. - const MeshSection *aux = object.section(kAux); - const float *deltas = aux && aux->size >= positionCount * 16u ? reinterpret_cast(aux->data) : nullptr; - const MeshSection *sourceList = object.section(kSources); - const uint32_t sources = sourceList ? sourceList->size / 20u : 0u; - const uint8_t *p = sourceList ? sourceList->data : nullptr; - for (uint32_t i = 0; i < sources; ++i) - { - const uint32_t offset = rd(p), first = rd(p), count = rd(p); - const uint32_t pass = rd(p), deltaOffset = rd(p); - if (first + count > positionCount) - continue; - if (offset != 0xffffffffu) - { - const uint8_t *from = ee.at(fileBase + offset); - for (uint32_t v = 0; v < count; ++v) - std::memcpy(&s_positions[static_cast(first + v) * 4u], from + v * 12u, 12); - } - // The morph pass (0x10 -> 0xd88): each position plus its delta times VU 31 (MULAw.xyz ACC, vf5, vf0w; - // MADD.xyz vf10, vf7, vf6), the deltas read where the game keeps them in the loaded file (else the pack's). - if (pass == 0x10u && (deltas || deltaOffset != 0xffffffffu)) - { - const uint8_t *from = deltaOffset != 0xffffffffu ? ee.at(fileBase + deltaOffset) : nullptr; - for (uint32_t v = 0; v < count; ++v) - { - float delta[3]; - if (from) - std::memcpy(delta, from + v * 12u, 12); - else - std::memcpy(delta, deltas + static_cast(first + v) * 4u, 12); - float *pos = &s_positions[static_cast(first + v) * 4u]; - for (int k = 0; k < 3; ++k) + const float *m = out.matrix; + const uint32_t positionCount = object.positionCount; + // x, y, z, w: the pack's, then each pool's from where the game keeps it in the loaded file (the V3-32 data of + // its packet: a few meshes have their vertices moved by the game, a car's headlight beams among them). + static thread_local std::vector s_positions; + s_positions.assign(object.positions, object.positions + static_cast(positionCount) * 4u); + // The morph deltas (the pools' @373 blocks), per position. + const MeshSection *aux = object.section(kAux); + const float *deltas = aux && aux->size >= positionCount * 16u ? reinterpret_cast(aux->data) : nullptr; + const MeshSection *sourceList = object.section(kSources); + const uint32_t sources = sourceList ? sourceList->size / 20u : 0u; + const uint8_t *p = sourceList ? sourceList->data : nullptr; + for (uint32_t i = 0; i < sources; ++i) + { + const uint32_t offset = rd(p), first = rd(p), count = rd(p); + const uint32_t pass = rd(p), deltaOffset = rd(p); + if (first + count > positionCount) + continue; + if (offset != 0xffffffffu) + { + const uint8_t *from = ee.at(fileBase + offset); + for (uint32_t v = 0; v < count; ++v) + std::memcpy(&s_positions[static_cast(first + v) * 4u], from + v * 12u, 12); + } + // The morph pass (0x10 -> 0xd88): each position plus its delta times VU 31 (MULAw.xyz ACC, vf5, vf0w; + // MADD.xyz vf10, vf7, vf6), the deltas read where the game keeps them in the loaded file (else the pack's). + if (pass == 0x10u && (deltas || deltaOffset != 0xffffffffu)) + { + const uint8_t *from = deltaOffset != 0xffffffffu ? ee.at(fileBase + deltaOffset) : nullptr; + for (uint32_t v = 0; v < count; ++v) + { + float delta[3]; + if (from) + std::memcpy(delta, from + v * 12u, 12); + else + std::memcpy(delta, deltas + static_cast(first + v) * 4u, 12); + float *pos = &s_positions[static_cast(first + v) * 4u]; + for (int k = 0; k < 3; ++k) pos[k] += delta[k] * parameters.morphWeight; - } - ++g_stats.morphed; - } - } - const float *positions = s_positions.data(); - // The parameter batches (environment map: the alpha terms of the strips after them). - const MeshSection *paramList = object.section(kParams); - const uint32_t params = paramList ? paramList->size / 20u : 0u; - const uint8_t *paramAt = paramList ? paramList->data : nullptr; - const bool reflective = pc == 0x1db8u; + } + ++g_stats.morphed; + } + } + const float *positions = s_positions.data(); + // The parameter batches (environment map: the alpha terms of the strips after them). + const MeshSection *paramList = object.section(kParams); + const uint32_t params = paramList ? paramList->size / 20u : 0u; + const uint8_t *paramAt = paramList ? paramList->data : nullptr; + const bool reflective = pc == 0x1db8u; tmb::shading::Reflection reflection; - // A skinned object's vertex pass: each position and its normal blended by its bones' matrices, as they are - // in EE memory now (the chain sends them from there). - const MeshSection *skinList = object.section(kSkin); - const uint32_t skinCount = skinList ? skinList->size / 20u : 0u; - static thread_local std::vector s_skinNormals; - if (bones != 0u && skinCount == positionCount) - { - s_skinNormals.assign(static_cast(positionCount) * 3u, 0.0f); - for (uint32_t i = 0; i < skinCount; ++i) - { - const uint8_t *v = skinList->data + static_cast(i) * 20u; - const int count = std::min(v[0], 3); - int32_t raw[3]; - std::memcpy(raw, v + 8, 12); + // A skinned object's vertex pass: each position and its normal blended by its bones' matrices, as they are + // in EE memory now (the chain sends them from there). + const MeshSection *skinList = object.section(kSkin); + const uint32_t skinCount = skinList ? skinList->size / 20u : 0u; + static thread_local std::vector s_skinNormals; + if (bones != 0u && skinCount == positionCount) + { + s_skinNormals.assign(static_cast(positionCount) * 3u, 0.0f); + for (uint32_t i = 0; i < skinCount; ++i) + { + const uint8_t *v = skinList->data + static_cast(i) * 20u; + const int count = std::min(v[0], 3); + int32_t raw[3]; + std::memcpy(raw, v + 8, 12); const float weight[3] = {count == 1 ? 1.0f : tmb::shading::skinWeight(raw[0]), tmb::shading::skinWeight(raw[1]), tmb::shading::skinWeight(raw[2])}; - float matrix[3][16]; - const float *matrices[3] = {matrix[0], matrix[1], matrix[2]}; - for (int b = 0; b < 3; ++b) - std::memcpy(matrix[b], ee.at(bones + 64u * v[4 + b]), 64); - const float n[3] = {1.0f - static_cast(v[1]) / 128.0f, 1.0f - static_cast(v[2]) / 128.0f, 1.0f - static_cast(v[3]) / 128.0f}; - float *pos = &s_positions[static_cast(i) * 4u]; - const float bind[3] = {pos[0], pos[1], pos[2]}; + float matrix[3][16]; + const float *matrices[3] = {matrix[0], matrix[1], matrix[2]}; + for (int b = 0; b < 3; ++b) + std::memcpy(matrix[b], ee.at(bones + 64u * v[4 + b]), 64); + const float n[3] = {1.0f - static_cast(v[1]) / 128.0f, 1.0f - static_cast(v[2]) / 128.0f, 1.0f - static_cast(v[3]) / 128.0f}; + float *pos = &s_positions[static_cast(i) * 4u]; + const float bind[3] = {pos[0], pos[1], pos[2]}; tmb::shading::skinVertex(count, matrices, weight, bind, n, pos, &s_skinNormals[static_cast(i) * 3u]); - } - } - const bool skin = bones != 0u && skinCount == positionCount; - // The strips (the fork's StripHeader and StripVertex, 16 bytes each). - p = object.strips; - const uint32_t strips = object.stripCount; + } + } + const bool skin = bones != 0u && skinCount == positionCount; + // The strips (the fork's StripHeader and StripVertex, 16 bytes each). + p = object.strips; + const uint32_t strips = object.stripCount; const float uOffset = parameters.textureOffset[0], vOffset = parameters.textureOffset[1]; - // The material as the strip program and the GS keep it: a strip's header brings a texture (its slot's - // register block) or keeps the last; the setup starts untextured (as the adapter's useMaterial). - uint64_t tex0 = 0; - bool textured = false; - uint32_t texnum = ~0u; - Batch *batch = nullptr; - static thread_local std::vector s_strip; // kept from call to call (its capacity) - std::vector &strip = s_strip; - strip.clear(); - static const bool s_check = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr; - for (uint32_t si = 0; si < strips; ++si) - { - for (uint32_t i = 0; i < params; ++i) - { - uint32_t before; - std::memcpy(&before, paramAt + 20u * i, 4); - if (before == si) - { - float terms[4]; - std::memcpy(terms, paramAt + 20u * i + 4u, 16); + // The material as the strip program and the GS keep it: a strip's header brings a texture (its slot's + // register block) or keeps the last; the setup starts untextured (as the adapter's useMaterial). + uint64_t tex0 = 0; + bool textured = false; + uint32_t texnum = ~0u; + Batch *batch = nullptr; + static thread_local std::vector s_strip; // kept from call to call (its capacity) + std::vector &strip = s_strip; + strip.clear(); + static const bool s_check = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr; + for (uint32_t si = 0; si < strips; ++si) + { + for (uint32_t i = 0; i < params; ++i) + { + uint32_t before; + std::memcpy(&before, paramAt + 20u * i, 4); + if (before == si) + { + float terms[4]; + std::memcpy(terms, paramAt + 20u * i + 4u, 16); reflection = tmb::shading::reflection(terms + 1); - } - } - const uint16_t prim = rd(p); - rd(p); // gif flags (PRE: TMB's strips all carry their PRIM) - rd(p); // material header - const int32_t slot = rd(p); - const uint32_t vertexCount = rd(p); - const uint8_t *vertices = p; - p += static_cast(vertexCount) * 16u; - Batch writes; // the block's other GS registers - bool otherWrites = false; - if (slot >= 0 && slot < 5 && slot < static_cast(ee.u16(obj + 0x5au))) - { - // The slot's register block (A+D: TEX0_1 as texmGetTextureAddrs rewrote it this frame, TEX1_1, ...). - const uint32_t block = obj + 0x70u + 0x30u * static_cast(slot); - for (uint32_t q = 0; q < 3u; ++q) - { - const uint32_t address = ee.u32(block + q * 16u + 8u) & 0xffu; - const uint64_t value = ee.u64(block + q * 16u); - if (address == 0x06u) // TEX0_1 - { - tex0 = value; - textured = true; - writes.setsTex0 = true; - } - else if (address == 0x42u) // ALPHA_1 - writes.setsAlpha = otherWrites = true, writes.alpha = value; - else if (address == 0x47u) // TEST_1 - writes.setsTest = otherWrites = true, writes.test = value; - else if (address == 0x4eu) // ZBUF_1 - writes.setsZbuf = otherWrites = true, writes.depthMasked = ((value >> 32) & 1u) != 0u; - } - texnum = ee.u16(obj + 0x50u + 2u * static_cast(slot)); - } - const bool blended = (prim & 0x40u) != 0u, fogged = (prim & 0x20u) != 0u; - if (!batch || otherWrites || batch->tex0 != tex0 || batch->textured != textured || batch->blended != blended || - batch->fogged != fogged) - { - out.batches.emplace_back(std::move(writes)); - batch = &out.batches.back(); - batch->vertices = pooledVertices(); - batch->tex0 = tex0; - batch->textured = textured; - batch->blended = blended; - batch->fogged = fogged; - if (textured) - { - batch->texture = tmb::textures::lookupId(texnum, tex0, 0u); - if (s_check && tmb::textures::idAtTbp(static_cast(tex0 & 0x3fffu)) != texnum) - { - ++g_stats.idMismatch; - static uint32_t s_logged = 0; - if (s_logged++ < 20u) - std::fprintf(stderr, "[tmb:mesh] object %#x: texture number %u, texInfo has %u at TBP %u\n", obj, texnum, - tmb::textures::idAtTbp(static_cast(tex0 & 0x3fffu)), static_cast(tex0 & 0x3fffu)); - } - } - } - if (sprite || ribbon) - { - // One sprite (one point, one colour, four corners' texture coordinates) or one ribbon segment (two - // points, four colours and texture coordinates): the converter checked the shapes. - std::vector &triangles = batch->vertices; - const size_t from = triangles.size(); - const auto vertexAt = [&](uint32_t v) { return vertices + v * 16u; }; - const auto pointOf = [&](uint32_t v, float out4[4]) - { - uint16_t index; - std::memcpy(&index, vertexAt(v), 2); - if (index < positionCount) - std::memcpy(out4, positions + static_cast(index) * 4u, 16); - else - std::memset(out4, 0, 16); - }; - if (sprite && vertexCount == 4u) - { - float point[4]; - pointOf(0u, point); - const uint8_t *vx = vertexAt(0u); - const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; - int32_t st[4][2]; - for (uint32_t v = 0; v < 4u; ++v) - { - int16_t pair[2]; - std::memcpy(pair, vertexAt(v) + 10, 4); - st[v][0] = pair[0]; - st[v][1] = pair[1]; - } - bozo::render::Vertex quad[4]; - static const int kOrder[6] = {0, 1, 2, 1, 2, 3}; + } + } + const uint16_t prim = rd(p); + rd(p); // gif flags (PRE: TMB's strips all carry their PRIM) + rd(p); // material header + const int32_t slot = rd(p); + const uint32_t vertexCount = rd(p); + const uint8_t *vertices = p; + p += static_cast(vertexCount) * 16u; + Batch writes; // the block's other GS registers + bool otherWrites = false; + if (slot >= 0 && slot < 5 && slot < static_cast(ee.u16(obj + 0x5au))) + { + // The slot's register block (A+D: TEX0_1 as texmGetTextureAddrs rewrote it this frame, TEX1_1, ...). + const uint32_t block = obj + 0x70u + 0x30u * static_cast(slot); + for (uint32_t q = 0; q < 3u; ++q) + { + const uint32_t address = ee.u32(block + q * 16u + 8u) & 0xffu; + const uint64_t value = ee.u64(block + q * 16u); + if (address == 0x06u) // TEX0_1 + { + tex0 = value; + textured = true; + writes.setsTex0 = true; + } + else if (address == 0x42u) // ALPHA_1 + writes.setsAlpha = otherWrites = true, writes.alpha = value; + else if (address == 0x47u) // TEST_1 + writes.setsTest = otherWrites = true, writes.test = value; + else if (address == 0x4eu) // ZBUF_1 + writes.setsZbuf = otherWrites = true, writes.depthMasked = ((value >> 32) & 1u) != 0u; + } + texnum = ee.u16(obj + 0x50u + 2u * static_cast(slot)); + } + const bool blended = (prim & 0x40u) != 0u, fogged = (prim & 0x20u) != 0u; + if (!batch || otherWrites || batch->tex0 != tex0 || batch->textured != textured || batch->blended != blended || + batch->fogged != fogged) + { + out.batches.emplace_back(std::move(writes)); + batch = &out.batches.back(); + batch->vertices = pooledVertices(); + batch->tex0 = tex0; + batch->textured = textured; + batch->blended = blended; + batch->fogged = fogged; + if (textured) + { + batch->texture = tmb::textures::lookupId(texnum, tex0, 0u); + if (s_check && tmb::textures::idAtTbp(static_cast(tex0 & 0x3fffu)) != texnum) + { + ++g_stats.idMismatch; + static uint32_t s_logged = 0; + if (s_logged++ < 20u) + std::fprintf(stderr, "[tmb:mesh] object %#x: texture number %u, texInfo has %u at TBP %u\n", obj, texnum, + tmb::textures::idAtTbp(static_cast(tex0 & 0x3fffu)), static_cast(tex0 & 0x3fffu)); + } + } + } + if (sprite || ribbon) + { + // One sprite (one point, one colour, four corners' texture coordinates) or one ribbon segment (two + // points, four colours and texture coordinates): the converter checked the shapes. + std::vector &triangles = batch->vertices; + const size_t from = triangles.size(); + const auto vertexAt = [&](uint32_t v) { return vertices + v * 16u; }; + const auto pointOf = [&](uint32_t v, float out4[4]) + { + uint16_t index; + std::memcpy(&index, vertexAt(v), 2); + if (index < positionCount) + std::memcpy(out4, positions + static_cast(index) * 4u, 16); + else + std::memset(out4, 0, 16); + }; + if (sprite && vertexCount == 4u) + { + float point[4]; + pointOf(0u, point); + const uint8_t *vx = vertexAt(0u); + const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; + int32_t st[4][2]; + for (uint32_t v = 0; v < 4u; ++v) + { + int16_t pair[2]; + std::memcpy(pair, vertexAt(v) + 10, 4); + st[v][0] = pair[0]; + st[v][1] = pair[1]; + } + bozo::render::Vertex quad[4]; + static const int kOrder[6] = {0, 1, 2, 1, 2, 3}; if (tmb::shading::spriteQuad(parameters, m, point, rgba, st, quad)) - for (int i : kOrder) - triangles.push_back(quad[i]); - } - else if (ribbon && vertexCount == 4u) - { - // The strip as the program reads it from TOP: the tag (its NLOOP, the points), point j at 1 + 3j, - // colour j at 2 + 3j, texture coordinates j at 3 + 3j (Z and W from the row hierSetVu1Regs sets, - // 0x1000, by its mask 0x50505050). - float points[2][4]; - pointOf(0u, points[0]); - pointOf(2u, points[1]); - const auto read = [&](uint32_t r, uint32_t words[4]) - { - std::memset(words, 0, 16); - if (r == 0u) - words[0] = 2u; - else if (r % 3u == 1u && (r - 1u) / 3u < 2u) - std::memcpy(words, points[(r - 1u) / 3u], 16); - else if (r % 3u == 2u && (r - 2u) / 3u < 4u) - { - const uint8_t *vx = vertexAt((r - 2u) / 3u); - for (int k = 0; k < 4; ++k) - words[k] = vx[6 + k]; - } - else if (r % 3u == 0u && (r - 3u) / 3u < 4u) - { - int16_t pair[2]; - std::memcpy(pair, vertexAt((r - 3u) / 3u) + 10, 4); - words[0] = static_cast(static_cast(pair[0])); - words[1] = static_cast(static_cast(pair[1])); - words[2] = words[3] = 0x1000u; - } - }; + for (int i : kOrder) + triangles.push_back(quad[i]); + } + else if (ribbon && vertexCount == 4u) + { + // The strip as the program reads it from TOP: the tag (its NLOOP, the points), point j at 1 + 3j, + // colour j at 2 + 3j, texture coordinates j at 3 + 3j (Z and W from the row hierSetVu1Regs sets, + // 0x1000, by its mask 0x50505050). + float points[2][4]; + pointOf(0u, points[0]); + pointOf(2u, points[1]); + const auto read = [&](uint32_t r, uint32_t words[4]) + { + std::memset(words, 0, 16); + if (r == 0u) + words[0] = 2u; + else if (r % 3u == 1u && (r - 1u) / 3u < 2u) + std::memcpy(words, points[(r - 1u) / 3u], 16); + else if (r % 3u == 2u && (r - 2u) / 3u < 4u) + { + const uint8_t *vx = vertexAt((r - 2u) / 3u); + for (int k = 0; k < 4; ++k) + words[k] = vx[6 + k]; + } + else if (r % 3u == 0u && (r - 3u) / 3u < 4u) + { + int16_t pair[2]; + std::memcpy(pair, vertexAt((r - 3u) / 3u) + 10, 4); + words[0] = static_cast(static_cast(pair[0])); + words[1] = static_cast(static_cast(pair[1])); + words[2] = words[3] = 0x1000u; + } + }; tmb::shading::ribbonStrip(parameters, m, read, triangles); - } - if (s_check) - out.checkStrips.emplace_back(triangles.begin() + static_cast(from), triangles.end()); - continue; - } - if (reflective) - { - // An environment-mapped strip (0x1ec8, the water's 0x2248): texture coordinates from the reflected - // eye vector, alpha by the view angle. - strip.clear(); - for (uint32_t v = 0; v < vertexCount; ++v) - { - const uint8_t *vx = vertices + v * 16u; - uint16_t index; - std::memcpy(&index, vx, 2); - bozo::render::Vertex outV; - if (index >= positionCount) - { - outV.rgba = 0xdeadu; - strip.push_back(outV); - continue; - } - const int32_t normal[3] = {vx[2], vx[3], vx[4]}; - const int32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; + } + if (s_check) + out.checkStrips.emplace_back(triangles.begin() + static_cast(from), triangles.end()); + continue; + } + if (reflective) + { + // An environment-mapped strip (0x1ec8, the water's 0x2248): texture coordinates from the reflected + // eye vector, alpha by the view angle. + strip.clear(); + for (uint32_t v = 0; v < vertexCount; ++v) + { + const uint8_t *vx = vertices + v * 16u; + uint16_t index; + std::memcpy(&index, vx, 2); + bozo::render::Vertex outV; + if (index >= positionCount) + { + outV.rgba = 0xdeadu; + strip.push_back(outV); + continue; + } + const int32_t normal[3] = {vx[2], vx[3], vx[4]}; + const int32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; tmb::shading::reflectVertex(parameters, m, reflection, positions + static_cast(index) * 4u, normal, rgba, outV); - strip.push_back(outV); - } - const size_t from = batch->vertices.size(); - for (size_t i = 2; i < strip.size(); ++i) - { - if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) - continue; - batch->vertices.push_back(strip[i - 2]); - batch->vertices.push_back(strip[i - 1]); - batch->vertices.push_back(strip[i]); - } - if (s_check) - out.checkStrips.emplace_back(batch->vertices.begin() + static_cast(from), batch->vertices.end()); - continue; - } - if (skin) - { - // A skinned strip (0x640, 0x878, 0x9e8): the blended positions, the colour lit by the blended normal - // (0x70) or not, texture coordinates plus VU 4. - strip.clear(); - for (uint32_t v = 0; v < vertexCount; ++v) - { - const uint8_t *vx = vertices + v * 16u; - uint16_t index; - std::memcpy(&index, vx, 2); - bozo::render::Vertex outV; - if (index >= positionCount) - { - outV.rgba = 0xdeadu; - strip.push_back(outV); - continue; - } - const float *pos = positions + static_cast(index) * 4u; - outV.x = pos[0]; - outV.y = pos[1]; - outV.z = pos[2]; - const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; + strip.push_back(outV); + } + const size_t from = batch->vertices.size(); + for (size_t i = 2; i < strip.size(); ++i) + { + if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) + continue; + batch->vertices.push_back(strip[i - 2]); + batch->vertices.push_back(strip[i - 1]); + batch->vertices.push_back(strip[i]); + } + if (s_check) + out.checkStrips.emplace_back(batch->vertices.begin() + static_cast(from), batch->vertices.end()); + continue; + } + if (skin) + { + // A skinned strip (0x640, 0x878, 0x9e8): the blended positions, the colour lit by the blended normal + // (0x70) or not, texture coordinates plus VU 4. + strip.clear(); + for (uint32_t v = 0; v < vertexCount; ++v) + { + const uint8_t *vx = vertices + v * 16u; + uint16_t index; + std::memcpy(&index, vx, 2); + bozo::render::Vertex outV; + if (index >= positionCount) + { + outV.rgba = 0xdeadu; + strip.push_back(outV); + continue; + } + const float *pos = positions + static_cast(index) * 4u; + outV.x = pos[0]; + outV.y = pos[1]; + outV.z = pos[2]; + const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; outV.rgba = tmb::shading::skinShade(parameters, pc == 0x0070u, &s_skinNormals[static_cast(index) * 3u], rgba); - int16_t st[2]; - std::memcpy(st, vx + 10, 4); - outV.u = static_cast(st[0]) / 4096.0f + uOffset; - outV.v = static_cast(st[1]) / 4096.0f + vOffset; - const float w = m[3] * pos[0] + m[7] * pos[1] + m[11] * pos[2] + m[15]; + int16_t st[2]; + std::memcpy(st, vx + 10, 4); + outV.u = static_cast(st[0]) / 4096.0f + uOffset; + outV.v = static_cast(st[1]) / 4096.0f + vOffset; + const float w = m[3] * pos[0] + m[7] * pos[1] + m[11] * pos[2] + m[15]; outV.fog = tmb::shading::fogAt(parameters, w); - strip.push_back(outV); - } - const size_t from = batch->vertices.size(); - for (size_t i = 2; i < strip.size(); ++i) - { - if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) - continue; - batch->vertices.push_back(strip[i - 2]); - batch->vertices.push_back(strip[i - 1]); - batch->vertices.push_back(strip[i]); - } - if (s_check) - out.checkStrips.emplace_back(batch->vertices.begin() + static_cast(from), batch->vertices.end()); - continue; - } - strip.clear(); - for (uint32_t v = 0; v < vertexCount; ++v) - { - const uint8_t *vx = vertices + v * 16u; - uint16_t index; - std::memcpy(&index, vx, 2); - bozo::render::Vertex outV; - if (index >= positionCount) - { - outV.rgba = 0xdeadu; // a break: no triangle uses it - strip.push_back(outV); - continue; - } - const float *pos = positions + static_cast(index) * 4u; - outV.x = pos[0]; - outV.y = pos[1]; - outV.z = pos[2]; - const uint32_t normal[3] = {vx[2], vx[3], vx[4]}; - const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; + strip.push_back(outV); + } + const size_t from = batch->vertices.size(); + for (size_t i = 2; i < strip.size(); ++i) + { + if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) + continue; + batch->vertices.push_back(strip[i - 2]); + batch->vertices.push_back(strip[i - 1]); + batch->vertices.push_back(strip[i]); + } + if (s_check) + out.checkStrips.emplace_back(batch->vertices.begin() + static_cast(from), batch->vertices.end()); + continue; + } + strip.clear(); + for (uint32_t v = 0; v < vertexCount; ++v) + { + const uint8_t *vx = vertices + v * 16u; + uint16_t index; + std::memcpy(&index, vx, 2); + bozo::render::Vertex outV; + if (index >= positionCount) + { + outV.rgba = 0xdeadu; // a break: no triangle uses it + strip.push_back(outV); + continue; + } + const float *pos = positions + static_cast(index) * 4u; + outV.x = pos[0]; + outV.y = pos[1]; + outV.z = pos[2]; + const uint32_t normal[3] = {vx[2], vx[3], vx[4]}; + const uint32_t rgba[4] = {vx[6], vx[7], vx[8], vx[9]}; outV.rgba = tmb::shading::shade(mode, parameters, normal, rgba, pos); - int16_t st[2]; - std::memcpy(st, vx + 10, 4); - outV.u = static_cast(st[0]) / 4096.0f + uOffset; - outV.v = static_cast(st[1]) / 4096.0f + vOffset; - const float w = m[3] * pos[0] + m[7] * pos[1] + m[11] * pos[2] + m[15]; + int16_t st[2]; + std::memcpy(st, vx + 10, 4); + outV.u = static_cast(st[0]) / 4096.0f + uOffset; + outV.v = static_cast(st[1]) / 4096.0f + vOffset; + const float w = m[3] * pos[0] + m[7] * pos[1] + m[11] * pos[2] + m[15]; outV.fog = tmb::shading::fogAt(parameters, w); - strip.push_back(outV); - } - if (s_check) - out.checkStrips.push_back(strip); - for (size_t i = 2; i < strip.size(); ++i) - { - if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) - continue; - batch->vertices.push_back(strip[i - 2]); - batch->vertices.push_back(strip[i - 1]); - batch->vertices.push_back(strip[i]); - } - } - for (const Batch &b : out.batches) - g_stats.triangles += b.vertices.size() / 3u; - } - - // ---- the skid marks ---- - // - // SkidMarks::draw (rtMain, after the views) builds one hier object in skidBuffer from the marks, which the - // next frame's traversal sends (its header from the template at this+0x203a0, ALPHA_1 0x44 in its register - // block): per batch of up to 47 marks a pool of their four corners (this + 64 * mark: x, y, z at +0, +0x10, - // +0x20, +0x30), then per mark a strip of four vertices (unlit, setup 0xcc8: PRIM 0x7c, a triangle strip, textured, - // fogged, blended; the batch's first strip brings the texture of slot 0), colour the mark's (this+0x26168 + 4 * - // mark), alpha min(smcSkidColors[material].a, (0x1e0 - age) / 2) (material this+0x278d8 + 4 * mark, age - // this+0x29048 + 4 * mark), texture coordinates (1, 1), (0, 1), (1, 0), (0, 0) for the corners 0-3. The marks - // follow a list from this+0x2a7b8 (next: this+0x17708 + 12 * mark, -1 ends it), this+0x2a7c0 of them. Kept here - // as draw sees them (the update after it moves them), in the pack's object format, for the hook. - constexpr uint32_t kSkidDraw = 0x00169490u; - constexpr uint32_t kSkidBuffer = 0x00446810u; - constexpr uint32_t kSkidColors = 0x00446560u; - struct Skid - { - bool valid = false; - std::vector positions; - std::vector strips; - MeshObject object; // the skid object, over those - } g_skid; - - template - void put(std::vector &out, T value) - { - const size_t at = out.size(); - out.resize(at + sizeof(T)); - std::memcpy(out.data() + at, &value, sizeof(T)); - } - - void skidSnapshot(const Ee &ee, uint32_t self) - { - g_skid.valid = false; - const int32_t count = static_cast(ee.u32(self + 0x2a7c0u)); - if (ee.u32(self + 0x203a0u) == 0u || count <= 0) - return; - const auto next = [&](int32_t mark) { return static_cast(ee.u32(self + 0x17708u + 12u * static_cast(mark))); }; - const int32_t head = static_cast(ee.u32(self + 0x2a7b8u)); - std::vector positions; - struct Strip - { - bool first; - uint8_t rgba[4]; - }; - std::vector strips; - int32_t remaining = count, corners = head, mark = head; - while (remaining > 0) - { - const int32_t batch = remaining < 48 ? remaining : 47; - remaining = remaining < 48 ? 0 : remaining - 47; - // The pool: the marks' corners while the list lasts (VU memory keeps what was there past its end: zeros). - for (int32_t k = 0; k < batch; ++k) - { - for (uint32_t c = 0; c < 4u; ++c) - { - const bool have = corners != -1; - const uint32_t at = self + static_cast(corners) * 64u + c * 16u; - positions.push_back(have ? ee.f32(at) : 0.0f); - positions.push_back(have ? ee.f32(at + 4u) : 0.0f); - positions.push_back(have ? ee.f32(at + 8u) : 0.0f); - positions.push_back(0.0f); - } - if (corners != -1) - corners = next(corners); - } - for (int32_t k = 0; k < batch; ++k) - { - const uint32_t m = static_cast(mark); - const uint32_t colour = ee.u32(self + 0x26168u + 4u * m); - const uint32_t material = ee.u32(self + 0x278d8u + 4u * m); - const int32_t fade = (0x1e0 - static_cast(ee.u32(self + 0x29048u + 4u * m))) / 2; - const int32_t limit = ee.at(kSkidColors + 4u * material + 3u)[0]; - const uint32_t word = colour | (static_cast(std::min(limit, fade)) << 24); - Strip strip; - strip.first = k == 0; - std::memcpy(strip.rgba, &word, 4); - strips.push_back(strip); - mark = next(mark); - } - } - g_skid.positions = std::move(positions); // no pool sources: the positions are the object's; no parameters, no skin - std::vector &body = g_skid.strips; - body.clear(); - for (size_t k = 0; k < strips.size(); ++k) - { - put(body, 0x7cu); // PRIM: triangle strip, Gouraud, textured, fogged, blended - put(body, 3u); // PRE, EOP - put(body, strips[k].first ? 1u : 0u); - put(body, strips[k].first ? 0 : -1); - put(body, 4u); - for (uint32_t v = 0; v < 4u; ++v) - { - put(body, static_cast(k * 4u + v)); - for (int b = 0; b < 4; ++b) // normal, flags - put(body, 0u); - for (int b = 0; b < 4; ++b) - put(body, strips[k].rgba[b]); - put(body, static_cast((v & 1u) ? 0 : 0x1000)); - put(body, static_cast(v < 2u ? 0x1000 : 0)); - put(body, 0u); - } - } - MeshObject &object = g_skid.object; - object.offset = kSkidBuffer; // its "file" starts at 0 - object.kind = 0u; - object.positions = g_skid.positions.data(); - object.positionCount = static_cast(g_skid.positions.size() / 4u); - object.strips = body.data(); - object.stripCount = static_cast(strips.size()); - g_skid.valid = true; - } - - void skidDrawOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (active() && hookOrder()) - { - const Ee ee{rdram, bozo::port::scratchpad(runtime)}; - skidSnapshot(ee, getRegU32(ctx, 4)); - } - draw__9SkidMarks_0x169490(rdram, ctx, runtime); - } - - // An object this path does not draw: its GS context still changes the GS state for those after it (in the - // chain's order): kept in the view's list without draws. - void stateOnly(const Ee &ee, uint32_t extra, bool opaque) - { - if (extra == 0u || !hookOrder()) - return; - Drawn drawn; - drawn.frame = g_frame; - drawn.alphaList = !opaque; - drawn.hasContext = contextAt(ee, extra, drawn.context); - if (!drawn.hasContext) - return; - ViewList &list = g_lists[0]; - list.frame = g_frame; - if (opaque) - list.opaque.push_back(std::move(drawn)); - else - { - list.pendingAlpha = std::move(drawn); - list.pending = true; - } - } - - void pktAddVu1ObjAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - // Its arguments as the caller set them (it walks s4 through the extra qwords it copies). - const uint32_t obj = getRegU32(ctx, 21), inst = getRegU32(ctx, 23), spr = getRegU32(ctx, 16); - const uint32_t a3 = getRegU32(ctx, 7), extra = getRegU32(ctx, 20), s6 = getRegU32(ctx, 22); - pktAddVu1ObjAsm_0x1eaae8(rdram, ctx, runtime); - if (!active()) - return; - ++g_stats.calls; - g_rdramForDump = rdram; - const Ee ee{rdram, bozo::port::scratchpad(runtime)}; - const uint32_t fp = ee.u16(obj + 0xcu); // lh $fp, 0xC($s5): the flags' bits 32-47 - // TMB_NATIVE_MESHES_DUMP: the objects of the kinds other than the rigid strips, once each (a skinned one with - // its per-instance chain and bones), for the offline comparison with the dump. - if (static const bool s_dumpLog = std::getenv("TMB_NATIVE_MESHES_DUMP") != nullptr; s_dumpLog) - { - static std::unordered_map s_seen; - if (!s_seen[obj] && (ee.u32(obj + 0x64u) != 0u || ((fp >> 5) & 3u) || ((fp >> 1) & 7u) || (fp & 0x1400u))) - { - s_seen[obj] = true; - const uint32_t index = ee.u32(obj + 0x68u); - const bool skinned = ee.u32(obj + 0x64u) != 0u && inst != 0u; - if (skinned && g_firstSkinned == 0u) - g_firstSkinned = g_frame + 1u; - std::fprintf(stderr, "[tmb:mesh] dump object %#x inst %#x flags %#x skeleton %#x spr38 %#x index %u chain %#x bones %#x\n", obj, inst, fp, - ee.u32(obj + 0x64u), ee.u32(spr + 0x38u), index, skinned ? ee.u32(ee.u32(inst + 0x18u) + 4u * index) : 0u, - skinned ? ee.u32(ee.u32(inst + 0x14u) + 4u * index) : 0u); - } - } - const bool opaque = getRegU32(ctx, 31) == kOpaqueReturn; - if (!opaque) - g_lists[g_building].pending = false; // until this one is drawn here - + strip.push_back(outV); + } + if (s_check) + out.checkStrips.push_back(strip); + for (size_t i = 2; i < strip.size(); ++i) + { + if (strip[i].rgba == 0xdeadu || strip[i - 1].rgba == 0xdeadu || strip[i - 2].rgba == 0xdeadu) + continue; + batch->vertices.push_back(strip[i - 2]); + batch->vertices.push_back(strip[i - 1]); + batch->vertices.push_back(strip[i]); + } + } + for (const Batch &b : out.batches) + g_stats.triangles += b.vertices.size() / 3u; + } + + // ---- the skid marks ---- + // + // SkidMarks::draw (rtMain, after the views) builds one hier object in skidBuffer from the marks, which the + // next frame's traversal sends (its header from the template at this+0x203a0, ALPHA_1 0x44 in its register + // block): per batch of up to 47 marks a pool of their four corners (this + 64 * mark: x, y, z at +0, +0x10, + // +0x20, +0x30), then per mark a strip of four vertices (unlit, setup 0xcc8: PRIM 0x7c, a triangle strip, textured, + // fogged, blended; the batch's first strip brings the texture of slot 0), colour the mark's (this+0x26168 + 4 * + // mark), alpha min(smcSkidColors[material].a, (0x1e0 - age) / 2) (material this+0x278d8 + 4 * mark, age + // this+0x29048 + 4 * mark), texture coordinates (1, 1), (0, 1), (1, 0), (0, 0) for the corners 0-3. The marks + // follow a list from this+0x2a7b8 (next: this+0x17708 + 12 * mark, -1 ends it), this+0x2a7c0 of them. Kept here + // as draw sees them (the update after it moves them), in the pack's object format, for the hook. + constexpr uint32_t kSkidDraw = 0x00169490u; + constexpr uint32_t kSkidBuffer = 0x00446810u; + constexpr uint32_t kSkidColors = 0x00446560u; + struct Skid + { + bool valid = false; + std::vector positions; + std::vector strips; + MeshObject object; // the skid object, over those + } g_skid; + + template + void put(std::vector &out, T value) + { + const size_t at = out.size(); + out.resize(at + sizeof(T)); + std::memcpy(out.data() + at, &value, sizeof(T)); + } + + void skidSnapshot(const Ee &ee, uint32_t self) + { + g_skid.valid = false; + const int32_t count = static_cast(ee.u32(self + 0x2a7c0u)); + if (ee.u32(self + 0x203a0u) == 0u || count <= 0) + return; + const auto next = [&](int32_t mark) { return static_cast(ee.u32(self + 0x17708u + 12u * static_cast(mark))); }; + const int32_t head = static_cast(ee.u32(self + 0x2a7b8u)); + std::vector positions; + struct Strip + { + bool first; + uint8_t rgba[4]; + }; + std::vector strips; + int32_t remaining = count, corners = head, mark = head; + while (remaining > 0) + { + const int32_t batch = remaining < 48 ? remaining : 47; + remaining = remaining < 48 ? 0 : remaining - 47; + // The pool: the marks' corners while the list lasts (VU memory keeps what was there past its end: zeros). + for (int32_t k = 0; k < batch; ++k) + { + for (uint32_t c = 0; c < 4u; ++c) + { + const bool have = corners != -1; + const uint32_t at = self + static_cast(corners) * 64u + c * 16u; + positions.push_back(have ? ee.f32(at) : 0.0f); + positions.push_back(have ? ee.f32(at + 4u) : 0.0f); + positions.push_back(have ? ee.f32(at + 8u) : 0.0f); + positions.push_back(0.0f); + } + if (corners != -1) + corners = next(corners); + } + for (int32_t k = 0; k < batch; ++k) + { + const uint32_t m = static_cast(mark); + const uint32_t colour = ee.u32(self + 0x26168u + 4u * m); + const uint32_t material = ee.u32(self + 0x278d8u + 4u * m); + const int32_t fade = (0x1e0 - static_cast(ee.u32(self + 0x29048u + 4u * m))) / 2; + const int32_t limit = ee.at(kSkidColors + 4u * material + 3u)[0]; + const uint32_t word = colour | (static_cast(std::min(limit, fade)) << 24); + Strip strip; + strip.first = k == 0; + std::memcpy(strip.rgba, &word, 4); + strips.push_back(strip); + mark = next(mark); + } + } + g_skid.positions = std::move(positions); // no pool sources: the positions are the object's; no parameters, no skin + std::vector &body = g_skid.strips; + body.clear(); + for (size_t k = 0; k < strips.size(); ++k) + { + put(body, 0x7cu); // PRIM: triangle strip, Gouraud, textured, fogged, blended + put(body, 3u); // PRE, EOP + put(body, strips[k].first ? 1u : 0u); + put(body, strips[k].first ? 0 : -1); + put(body, 4u); + for (uint32_t v = 0; v < 4u; ++v) + { + put(body, static_cast(k * 4u + v)); + for (int b = 0; b < 4; ++b) // normal, flags + put(body, 0u); + for (int b = 0; b < 4; ++b) + put(body, strips[k].rgba[b]); + put(body, static_cast((v & 1u) ? 0 : 0x1000)); + put(body, static_cast(v < 2u ? 0x1000 : 0)); + put(body, 0u); + } + } + MeshObject &object = g_skid.object; + object.offset = kSkidBuffer; // its "file" starts at 0 + object.kind = 0u; + object.positions = g_skid.positions.data(); + object.positionCount = static_cast(g_skid.positions.size() / 4u); + object.strips = body.data(); + object.stripCount = static_cast(strips.size()); + g_skid.valid = true; + } + + void skidDrawOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (active() && hookOrder()) + { + const Ee ee{rdram, bozo::port::scratchpad(runtime)}; + skidSnapshot(ee, getRegU32(ctx, 4)); + } + draw__9SkidMarks_0x169490(rdram, ctx, runtime); + } + + // An object this path does not draw: its GS context still changes the GS state for those after it (in the + // chain's order): kept in the view's list without draws. + void stateOnly(const Ee &ee, uint32_t extra, bool opaque) + { + if (extra == 0u || !hookOrder()) + return; + Drawn drawn; + drawn.frame = g_frame; + drawn.alphaList = !opaque; + drawn.hasContext = contextAt(ee, extra, drawn.context); + if (!drawn.hasContext) + return; + ViewList &list = g_lists[0]; + list.frame = g_frame; + if (opaque) + list.opaque.push_back(std::move(drawn)); + else + { + list.pendingAlpha = std::move(drawn); + list.pending = true; + } + } + + void pktAddVu1ObjAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + // Its arguments as the caller set them (it walks s4 through the extra qwords it copies). + const uint32_t obj = getRegU32(ctx, 21), inst = getRegU32(ctx, 23), spr = getRegU32(ctx, 16); + const uint32_t a3 = getRegU32(ctx, 7), extra = getRegU32(ctx, 20), s6 = getRegU32(ctx, 22); + pktAddVu1ObjAsm_0x1eaae8(rdram, ctx, runtime); + if (!active()) + return; + ++g_stats.calls; + g_rdramForDump = rdram; + const Ee ee{rdram, bozo::port::scratchpad(runtime)}; + const uint32_t fp = ee.u16(obj + 0xcu); // lh $fp, 0xC($s5): the flags' bits 32-47 + // TMB_NATIVE_MESHES_DUMP: the objects of the kinds other than the rigid strips, once each (a skinned one with + // its per-instance chain and bones), for the offline comparison with the dump. + if (static const bool s_dumpLog = std::getenv("TMB_NATIVE_MESHES_DUMP") != nullptr; s_dumpLog) + { + static std::unordered_map s_seen; + if (!s_seen[obj] && (ee.u32(obj + 0x64u) != 0u || ((fp >> 5) & 3u) || ((fp >> 1) & 7u) || (fp & 0x1400u))) + { + s_seen[obj] = true; + const uint32_t index = ee.u32(obj + 0x68u); + const bool skinned = ee.u32(obj + 0x64u) != 0u && inst != 0u; + if (skinned && g_firstSkinned == 0u) + g_firstSkinned = g_frame + 1u; + std::fprintf(stderr, "[tmb:mesh] dump object %#x inst %#x flags %#x skeleton %#x spr38 %#x index %u chain %#x bones %#x\n", obj, inst, fp, + ee.u32(obj + 0x64u), ee.u32(spr + 0x38u), index, skinned ? ee.u32(ee.u32(inst + 0x18u) + 4u * index) : 0u, + skinned ? ee.u32(ee.u32(inst + 0x14u) + 4u * index) : 0u); + } + } + const bool opaque = getRegU32(ctx, 31) == kOpaqueReturn; + if (!opaque) + g_lists[g_building].pending = false; // until this one is drawn here + tmb::shading::Parameters parameters; auto &cache = retained(runtime); - // VU 0-3: the object-to-camera matrix (hierMulEoForObjAsm: vf1-3 the rotation, vf6 the translation), - // sent when it changed; VU1 keeps the last opaque object's otherwise. - float matrix[4][4]; - if (a3 != 0u) - { + // VU 0-3: the object-to-camera matrix (hierMulEoForObjAsm: vf1-3 the rotation, vf6 the translation), + // sent when it changed; VU1 keeps the last opaque object's otherwise. + float matrix[4][4]; + if (a3 != 0u) + { if (bozo::port::nativeGraphics(runtime)) std::memcpy(matrix, &tmb::scene::get(runtime).object, sizeof(matrix)); else @@ -1169,72 +1170,72 @@ namespace tmb::meshes vf(ctx, 1, matrix[0]); vf(ctx, 2, matrix[1]); vf(ctx, 3, matrix[2]); vf(ctx, 6, matrix[3]); } - if (opaque) + if (opaque) std::memcpy(&cache.opaqueObject, matrix, sizeof(matrix)); - } - else + } + else std::memcpy(matrix, &cache.opaqueObject, sizeof(matrix)); std::memcpy(¶meters.object, matrix, sizeof(matrix)); - // VU 6-8: a car's light directions in its own frame (vf7-9), sent when scratchpad 0x38 holds a car. - float lights[3][4]; - if (ee.u32(spr + 0x38u) != 0u) - { + // VU 6-8: a car's light directions in its own frame (vf7-9), sent when scratchpad 0x38 holds a car. + float lights[3][4]; + if (ee.u32(spr + 0x38u) != 0u) + { if (bozo::port::nativeGraphics(runtime)) std::memcpy(lights, &tmb::scene::get(runtime).objectDirections, sizeof(lights)); else { vf(ctx, 7, lights[0]); vf(ctx, 8, lights[1]); vf(ctx, 9, lights[2]); } - if (opaque) + if (opaque) for (unsigned i = 0; i < 3; ++i) for (unsigned axis = 0; axis < 3; ++axis) cache.opaqueDirections[i][axis] = lights[axis][i]; - } - else + } + else for (unsigned i = 0; i < 3; ++i) for (unsigned axis = 0; axis < 3; ++axis) lights[axis][i] = cache.opaqueDirections[i][axis]; for (unsigned i = 0; i < 3; ++i) for (unsigned axis = 0; axis < 3; ++axis) parameters.directional[i].direction[axis] = lights[axis][i]; - - // VU 4: texture offset (obj+0x20, +0x24, or the float table's scroll with flag 43), depth factor - // (obj+0x2c) and fog offset (obj+0x28). - const uint32_t table = inst != 0u ? ee.u32(inst + 4u) : 0u; // the instance's float table - const bool haveTable = inst != 0u; - const auto entry = [&](uint32_t field, float otherwise) - { - const int16_t index = ee.s16(obj + field); - return index >= 0 ? ee.f32(table + 4u * static_cast(index)) : otherwise; - }; + + // VU 4: texture offset (obj+0x20, +0x24, or the float table's scroll with flag 43), depth factor + // (obj+0x2c) and fog offset (obj+0x28). + const uint32_t table = inst != 0u ? ee.u32(inst + 4u) : 0u; // the instance's float table + const bool haveTable = inst != 0u; + const auto entry = [&](uint32_t field, float otherwise) + { + const int16_t index = ee.s16(obj + field); + return index >= 0 ? ee.f32(table + 4u * static_cast(index)) : otherwise; + }; float objectTerms[4] = {ee.f32(obj + 0x20u), ee.f32(obj + 0x24u), ee.f32(obj + 0x2cu), ee.f32(obj + 0x28u)}; - if (haveTable && ((fp >> 11) & 1u)) - { + if (haveTable && ((fp >> 11) & 1u)) + { objectTerms[0] = entry(0x30u, 0.0f); objectTerms[1] = entry(0x32u, 0.0f); - } + } parameters.textureOffset = {objectTerms[0], objectTerms[1]}; parameters.depthScale = objectTerms[2]; parameters.fogOffset = objectTerms[3]; - // VU 5: the colour, times the fade (f20 or f22, by f21 < f20) and the car's colour (CsColor, unless flag 36). - const float fade = ctx->f[21] < ctx->f[20] ? ctx->f[20] : ctx->f[22]; + // VU 5: the colour, times the fade (f20 or f22, by f21 < f20) and the car's colour (CsColor, unless flag 36). + const float fade = ctx->f[21] < ctx->f[20] ? ctx->f[20] : ctx->f[22]; float tint[4] = {ee.f32(obj + 0x40u), ee.f32(obj + 0x44u), ee.f32(obj + 0x48u), ee.f32(obj + 0x4cu) * fade}; - if (haveTable) - { + if (haveTable) + { tint[0] = entry(0x34u, tint[0]); tint[1] = entry(0x36u, tint[1]); tint[2] = entry(0x38u, tint[2]); - if (ee.s16(obj + 0x3au) >= 0) + if (ee.s16(obj + 0x3au) >= 0) tint[3] = entry(0x3au, 0.0f) * fade; - } - const uint32_t car = ee.u32(spr + 0x38u); - if (car != 0u && ee.u32(spr + 0x8cu) != 0u && !(fp & 0x10u)) - for (int k = 0; k < 3; ++k) + } + const uint32_t car = ee.u32(spr + 0x38u); + if (car != 0u && ee.u32(spr + 0x8cu) != 0u && !(fp & 0x10u)) + for (int k = 0; k < 3; ++k) tint[k] *= ee.f32(car + 0x80u + 4u * static_cast(k)); std::memcpy(¶meters.tint, tint, sizeof(tint)); - // VU 31: a morphing object's weight (flag 42: UNPACK S-32 @31 of the float table's entry obj+0x3c, in every - // lane), sent only with an instance; VU1 keeps the last one otherwise. - if (((fp >> 10) & 1u) && haveTable) - { - const int32_t index = ee.s16(obj + 0x3cu); - const float weight = ee.f32(table + 4u * static_cast(index)); + // VU 31: a morphing object's weight (flag 42: UNPACK S-32 @31 of the float table's entry obj+0x3c, in every + // lane), sent only with an instance; VU1 keeps the last one otherwise. + if (((fp >> 10) & 1u) && haveTable) + { + const int32_t index = ee.s16(obj + 0x3cu); + const float weight = ee.f32(table + 4u * static_cast(index)); cache.morphWeight = weight; - } - // VU 9-21: the frame's constants as the game keeps them; VU 20-21 the fog's (pktCacheForAsm's scratchpad - // cache: flag 41 picks the first set) while the fog is on. + } + // VU 9-21: the frame's constants as the game keeps them; VU 20-21 the fog's (pktCacheForAsm's scratchpad + // cache: flag 41 picks the first set) while the fog is on. parameters.morphWeight = cache.morphWeight; parameters.camera = record(ee, kCameraRecord); parameters.clipCamera = record(ee, kClipCameraRecord); @@ -1242,20 +1243,20 @@ namespace tmb::meshes parameters.directional[i].colour = record(ee, kLightColourRecords + 16u * i); parameters.colourOffset = record(ee, kLightColourRecords + 48u); parameters.fog = record(ee, kFogRecord); - if (ee.u32(spr + 0x90u) != 0u) - { - const bool first = (fp >> 9) & 1u; + if (ee.u32(spr + 0x90u) != 0u) + { + const bool first = (fp >> 9) & 1u; parameters.colourOffset = record(ee, spr + (first ? 0x120u : 0x150u)); parameters.fog = record(ee, spr + (first ? 0x130u : 0x160u)); - } + } // Selected native point-light records, packed for the existing shading adapter (original context in checker). const bool pointLights = ee.u32(spr + 0x9cu) != 0u && (bozo::port::nativeGraphics(runtime) ? tmb::scene::get(runtime).lighting.enabled : ctx->vi[14] != 0u); - if (pointLights) - { + if (pointLights) + { if (bozo::port::nativeGraphics(runtime)) parameters.point = tmb::scene::get(runtime).lighting; else // Historical checker ABI only; the native player never reads these registers. - { + { const auto lane = [&](unsigned reg, unsigned component) { return ctx->vu0_vf[reg].f[component]; }; for (unsigned i = 0; i < 3; ++i) { @@ -1266,358 +1267,358 @@ namespace tmb::meshes for (unsigned k = 0; k < 3; ++k) light.colour[k] = lane(20+i,k); } parameters.point.enabled = true; parameters.point.count = 3; - } - } - - // What this path draws: a rigid object (no skeleton) of the pack, with one of the four strip setups and - // no extra header qwords. - // A skinned object (a skeleton at obj+0x64, and its instance): its bones' matrices where skeletonTraverse - // wrote them, (*(inst + 0x14))[obj + 0x68] (the per-instance chain the header CALLs sends them to TOP). - const bool skinned = ee.u32(obj + 0x64u) != 0u; - const uint32_t boneLists = skinned && inst != 0u ? ee.u32(inst + 0x14u) : 0u; - const uint32_t bones = boneLists != 0u ? ee.u32(boneLists + 4u * ee.u32(obj + 0x68u)) : 0u; - const uint32_t pc = skinned && bones == 0u ? 0u : setupFor(fp, s6, pointLights, skinned); - // An opaque object this path does not draw: a resume after it is left to the stream too. - const Previous previous = g_previous; - if (opaque) - g_previous.valid = false; - if (pc == 0u) - { - ++g_stats.program; - stateOnly(ee, extra, opaque); - return; - } - // The resume: the setup before it goes on (in the chain's order, which only the opaque objects keep), with - // this header's VU 4-5 (and point lights). - const bool resume = pc == 0x0c78u; - // (Only after the rigid strip setups: the resume's way back into the others' loops is not known here.) - const bool rigidBefore = previous.pc == 0x0cc8u || previous.pc == 0x0d08u || previous.pc == 0x0ce8u || previous.pc == 0x1700u; - if (resume && (!opaque || !previous.valid || !rigidBefore)) - { - ++g_stats.program; - stateOnly(ee, extra, opaque); - return; - } - if (extra != 0u) - { - // TMB_NATIVE_MESHES_LOG_EXTRA=1: the extra qwords of the first headers that bring some (a diagnostic). - static const bool s_logExtra = std::getenv("TMB_NATIVE_MESHES_LOG_EXTRA") != nullptr; - static uint32_t s_logged = 0; - static std::unordered_map s_seen; // each kind once: its first qword's upper words - const uint64_t kind = (static_cast(ee.u32(extra + 8u)) << 32) | ee.u32(extra + 12u); - if (s_logExtra && !s_seen[kind] && s_logged++ < 60u) - { - s_seen[kind] = true; - std::string text; - const uint32_t count = ee.u16(extra + 0xcu) + 1u; - for (uint32_t q = 0; q < std::min(count, 4u); ++q) - { - char item[48]; - std::snprintf(item, sizeof(item), " [%08x %08x %08x %08x]", ee.u32(extra + q * 16u), ee.u32(extra + q * 16u + 4u), - ee.u32(extra + q * 16u + 8u), ee.u32(extra + q * 16u + 12u)); - text += item; - } - std::fprintf(stderr, "[tmb:mesh] object %#x (setup %#x): %u extra qwords at %#x:%s\n", obj, pc, count, extra, text.c_str()); - } - // The extra qwords are the group's parameter block: in the arenas seen so far only a DIRECT of A+D - // writes (ALPHA_1, TEST_1, ...), GS state the adapter follows in the stream before the setup, which - // submitDrawn takes. Drawn here as the others. - ++g_stats.extra; - } - bozo::render::packs::LoadedImages::Image file; - const bool inFile = g_loaded.find(obj, file); - // The skid marks' object (skidBuffer, which SkidMarks::draw fills): drawn from the marks themselves. - const bool skid = obj == kSkidBuffer && g_skid.valid && !resume; - if (!skid && (!inFile || !file.file)) - { - ++g_stats.noFile; - static std::unordered_map s_seen; - if (!s_seen[obj] && s_seen.size() < 40u) - { - s_seen[obj] = true; - std::fprintf(stderr, "[tmb:mesh] object %#x (setup %#x, flags %#x, inst %#x, %s): outside the loaded NGP files (file %s)\n", obj, pc, fp, - inst, opaque ? "opaque" : "alpha", tmb::textures::nameAt(obj).c_str()); - } - stateOnly(ee, extra, opaque); - return; - } - const uint32_t fileIndex = skid ? 0xffffu : file.index, fileBase = skid ? 0u : file.base; - const uint32_t offset = obj - fileBase; - const MeshObject *it = skid ? (g_skid.object.offset == offset ? &g_skid.object : nullptr) : file.file->object(offset); - if (!it) - { - ++g_stats.noObject; - // TMB_NATIVE_MESHES_LOG_MISSING=1: the first objects of a loaded file the pack does not have. - static const bool s_logMissing = std::getenv("TMB_NATIVE_MESHES_LOG_MISSING") != nullptr; - static std::unordered_map s_seen; - if (s_logMissing && !s_seen[obj] && s_seen.size() < 40u) - { - s_seen[obj] = true; - std::fprintf(stderr, "[tmb:mesh] object %#x (%s + %#x, setup %#x, flags %#x, %s): not in the pack\n", obj, - file.file->name.c_str(), offset, pc, fp, opaque ? "opaque" : "alpha"); - } - stateOnly(ee, extra, opaque); - return; - } - // The pack's kind as the flags pick the program: rigid or pool-less for the strip setups, sprite, ribbon. - const uint32_t kindFor = pc == 0x3000u ? 2u : pc == 0x3270u ? 3u : skinned && !resume ? 4u : 1u; - if (kindFor == 1u ? it->kind > 1u : it->kind != kindFor) - { - ++g_stats.kindOther; - stateOnly(ee, extra, opaque); - return; - } - // A resume draws a pool-less object with the pool (and setup) the object before it left: that object must be - // its pool's (or another pool-less object of that pool). - if (resume && (it->kind != 1u || previous.file != fileIndex || - (poolFrom(*it) != previous.offset && poolFrom(*it) != previous.poolFrom))) - { - ++g_stats.resumeOther; - stateOnly(ee, extra, opaque); - return; - } - const uint32_t drawPc = resume ? previous.pc : pc; - if (resume && drawPc == 0x1700u && !pointLights) + } + } + + // What this path draws: a rigid object (no skeleton) of the pack, with one of the four strip setups and + // no extra header qwords. + // A skinned object (a skeleton at obj+0x64, and its instance): its bones' matrices where skeletonTraverse + // wrote them, (*(inst + 0x14))[obj + 0x68] (the per-instance chain the header CALLs sends them to TOP). + const bool skinned = ee.u32(obj + 0x64u) != 0u; + const uint32_t boneLists = skinned && inst != 0u ? ee.u32(inst + 0x14u) : 0u; + const uint32_t bones = boneLists != 0u ? ee.u32(boneLists + 4u * ee.u32(obj + 0x68u)) : 0u; + const uint32_t pc = skinned && bones == 0u ? 0u : setupFor(fp, s6, pointLights, skinned); + // An opaque object this path does not draw: a resume after it is left to the stream too. + const Previous previous = g_previous; + if (opaque) + g_previous.valid = false; + if (pc == 0u) + { + ++g_stats.program; + stateOnly(ee, extra, opaque); + return; + } + // The resume: the setup before it goes on (in the chain's order, which only the opaque objects keep), with + // this header's VU 4-5 (and point lights). + const bool resume = pc == 0x0c78u; + // (Only after the rigid strip setups: the resume's way back into the others' loops is not known here.) + const bool rigidBefore = previous.pc == 0x0cc8u || previous.pc == 0x0d08u || previous.pc == 0x0ce8u || previous.pc == 0x1700u; + if (resume && (!opaque || !previous.valid || !rigidBefore)) + { + ++g_stats.program; + stateOnly(ee, extra, opaque); + return; + } + if (extra != 0u) + { + // TMB_NATIVE_MESHES_LOG_EXTRA=1: the extra qwords of the first headers that bring some (a diagnostic). + static const bool s_logExtra = std::getenv("TMB_NATIVE_MESHES_LOG_EXTRA") != nullptr; + static uint32_t s_logged = 0; + static std::unordered_map s_seen; // each kind once: its first qword's upper words + const uint64_t kind = (static_cast(ee.u32(extra + 8u)) << 32) | ee.u32(extra + 12u); + if (s_logExtra && !s_seen[kind] && s_logged++ < 60u) + { + s_seen[kind] = true; + std::string text; + const uint32_t count = ee.u16(extra + 0xcu) + 1u; + for (uint32_t q = 0; q < std::min(count, 4u); ++q) + { + char item[48]; + std::snprintf(item, sizeof(item), " [%08x %08x %08x %08x]", ee.u32(extra + q * 16u), ee.u32(extra + q * 16u + 4u), + ee.u32(extra + q * 16u + 8u), ee.u32(extra + q * 16u + 12u)); + text += item; + } + std::fprintf(stderr, "[tmb:mesh] object %#x (setup %#x): %u extra qwords at %#x:%s\n", obj, pc, count, extra, text.c_str()); + } + // The extra qwords are the group's parameter block: in the arenas seen so far only a DIRECT of A+D + // writes (ALPHA_1, TEST_1, ...), GS state the adapter follows in the stream before the setup, which + // submitDrawn takes. Drawn here as the others. + ++g_stats.extra; + } + bozo::render::packs::LoadedImages::Image file; + const bool inFile = g_loaded.find(obj, file); + // The skid marks' object (skidBuffer, which SkidMarks::draw fills): drawn from the marks themselves. + const bool skid = obj == kSkidBuffer && g_skid.valid && !resume; + if (!skid && (!inFile || !file.file)) + { + ++g_stats.noFile; + static std::unordered_map s_seen; + if (!s_seen[obj] && s_seen.size() < 40u) + { + s_seen[obj] = true; + std::fprintf(stderr, "[tmb:mesh] object %#x (setup %#x, flags %#x, inst %#x, %s): outside the loaded NGP files (file %s)\n", obj, pc, fp, + inst, opaque ? "opaque" : "alpha", tmb::textures::nameAt(obj).c_str()); + } + stateOnly(ee, extra, opaque); + return; + } + const uint32_t fileIndex = skid ? 0xffffu : file.index, fileBase = skid ? 0u : file.base; + const uint32_t offset = obj - fileBase; + const MeshObject *it = skid ? (g_skid.object.offset == offset ? &g_skid.object : nullptr) : file.file->object(offset); + if (!it) + { + ++g_stats.noObject; + // TMB_NATIVE_MESHES_LOG_MISSING=1: the first objects of a loaded file the pack does not have. + static const bool s_logMissing = std::getenv("TMB_NATIVE_MESHES_LOG_MISSING") != nullptr; + static std::unordered_map s_seen; + if (s_logMissing && !s_seen[obj] && s_seen.size() < 40u) + { + s_seen[obj] = true; + std::fprintf(stderr, "[tmb:mesh] object %#x (%s + %#x, setup %#x, flags %#x, %s): not in the pack\n", obj, + file.file->name.c_str(), offset, pc, fp, opaque ? "opaque" : "alpha"); + } + stateOnly(ee, extra, opaque); + return; + } + // The pack's kind as the flags pick the program: rigid or pool-less for the strip setups, sprite, ribbon. + const uint32_t kindFor = pc == 0x3000u ? 2u : pc == 0x3270u ? 3u : skinned && !resume ? 4u : 1u; + if (kindFor == 1u ? it->kind > 1u : it->kind != kindFor) + { + ++g_stats.kindOther; + stateOnly(ee, extra, opaque); + return; + } + // A resume draws a pool-less object with the pool (and setup) the object before it left: that object must be + // its pool's (or another pool-less object of that pool). + if (resume && (it->kind != 1u || previous.file != fileIndex || + (poolFrom(*it) != previous.offset && poolFrom(*it) != previous.poolFrom))) + { + ++g_stats.resumeOther; + stateOnly(ee, extra, opaque); + return; + } + const uint32_t drawPc = resume ? previous.pc : pc; + if (resume && drawPc == 0x1700u && !pointLights) parameters.point = previous.pointLights; - - // TMB_NATIVE_VIF=1 (the adapter follows the stream): the header's last qword, NOP, BASE, OFFSET, MSCAL - // (pktAddVu1ObjAsm leaves the END tag after it, at the packet's write pointer), gets the mark in the NOP's - // immediate. In the game's order (the default) nothing of the packet is read or written. - bool marking = tmb::native::vifObserved(); - uint8_t *last = nullptr; - uint32_t words[4] = {}; - if (marking) - { - const uint32_t writePointer = ee.u32(getRegU32(ctx, 4) + 8u); - last = ee.at(writePointer - 0x10u); - std::memcpy(words, last, 16); - // pktCacheForAsm's setup codes are MSCALF (0x15). - if (words[0] != 0u || (words[3] & ~0x01000000u) != (0x14000000u | (pc >> 3))) - { - ++g_stats.unmarked; - static uint32_t s_logged = 0; - if (s_logged++ < 10u) - std::fprintf(stderr, "[tmb:mesh] object %#x: header end %08x %08x %08x %08x, expected NOP .. MSCAL %#x: left to the stream\n", obj, - words[0], words[1], words[2], words[3], pc); - if (!hookOrder()) - return; - marking = false; // the comparison: drawn in the hook order all the same, not compared - } - } - - Drawn drawn; - drawn.alphaList = !opaque; - // The traversal's GS context (s4), when this header brings it: a node's, in an NGP file (its writes from the - // pack, recorded offline), or the game's default one (ctxGetDefaultGSCtx: the executable's, in EE memory). - if (extra != 0u) - drawn.hasContext = contextAt(ee, extra, drawn.context); - drawn.setupPc = pc; - drawn.resumes = resume ? drawPc : 0u; - drawn.frame = g_frame; - drawn.object = obj; - drawn.file = fileIndex; - drawn.offset = offset; - // The setup's matrix: this object's, or (a resume) the one before it, which 0xc78 keeps (it runs 0x1700's - // setup again, which makes it anew). - float screen[16], clip[16], object[16]; - if (resume && drawPc != 0x1700u) - { - std::memcpy(screen, previous.screen, sizeof(screen)); - std::memcpy(clip, previous.clip, sizeof(clip)); - std::memcpy(object, previous.object, sizeof(object)); - } - else - { - for (int j = 0; j < 4; ++j) - for (int i = 0; i < 4; ++i) + + // TMB_NATIVE_VIF=1 (the adapter follows the stream): the header's last qword, NOP, BASE, OFFSET, MSCAL + // (pktAddVu1ObjAsm leaves the END tag after it, at the packet's write pointer), gets the mark in the NOP's + // immediate. In the game's order (the default) nothing of the packet is read or written. + bool marking = tmb::native::vifObserved(); + uint8_t *last = nullptr; + uint32_t words[4] = {}; + if (marking) + { + const uint32_t writePointer = ee.u32(getRegU32(ctx, 4) + 8u); + last = ee.at(writePointer - 0x10u); + std::memcpy(words, last, 16); + // pktCacheForAsm's setup codes are MSCALF (0x15). + if (words[0] != 0u || (words[3] & ~0x01000000u) != (0x14000000u | (pc >> 3))) + { + ++g_stats.unmarked; + static uint32_t s_logged = 0; + if (s_logged++ < 10u) + std::fprintf(stderr, "[tmb:mesh] object %#x: header end %08x %08x %08x %08x, expected NOP .. MSCAL %#x: left to the stream\n", obj, + words[0], words[1], words[2], words[3], pc); + if (!hookOrder()) + return; + marking = false; // the comparison: drawn in the hook order all the same, not compared + } + } + + Drawn drawn; + drawn.alphaList = !opaque; + // The traversal's GS context (s4), when this header brings it: a node's, in an NGP file (its writes from the + // pack, recorded offline), or the game's default one (ctxGetDefaultGSCtx: the executable's, in EE memory). + if (extra != 0u) + drawn.hasContext = contextAt(ee, extra, drawn.context); + drawn.setupPc = pc; + drawn.resumes = resume ? drawPc : 0u; + drawn.frame = g_frame; + drawn.object = obj; + drawn.file = fileIndex; + drawn.offset = offset; + // The setup's matrix: this object's, or (a resume) the one before it, which 0xc78 keeps (it runs 0x1700's + // setup again, which makes it anew). + float screen[16], clip[16], object[16]; + if (resume && drawPc != 0x1700u) + { + std::memcpy(screen, previous.screen, sizeof(screen)); + std::memcpy(clip, previous.clip, sizeof(clip)); + std::memcpy(object, previous.object, sizeof(object)); + } + else + { + for (int j = 0; j < 4; ++j) + for (int i = 0; i < 4; ++i) object[j * 4 + i] = parameters.object[j][i]; tmb::shading::objectToScreen(parameters, screen, false); - for (int j = 0; j < 4; ++j) - for (int k = 0; k < 4; ++k) + for (int j = 0; j < 4; ++j) + for (int k = 0; k < 4; ++k) clip[j * 4 + k] = parameters.clipCamera[0][k] * parameters.object[j][0] + parameters.clipCamera[1][k] * parameters.object[j][1] + parameters.clipCamera[2][k] * parameters.object[j][2] + parameters.clipCamera[3][k] * parameters.object[j][3]; - } + } buildStrips(parameters, ee, obj, fileBase, *it, drawPc, drawn, screen, it->kind == 4u ? bones : 0u); - std::memcpy(drawn.clip, clip, sizeof(clip)); - drawn.hasClip = !drawn.screenSpace && it->kind != 4u; // (the skinned programs: not modelled) - // For interpolation (Renderer::setParts): the matrix as camera (VU 9-12, the view's projection, its z row - // scaled by the object's depth factor as buildStrips scales the matrix's) times the object (VU 0-3: object to - // camera, the camera's turn included), interpolated apart so a turning object or camera keeps its shape. - if (!drawn.screenSpace) - { - const bool depthScaled = drawPc != 0x0070u; - for (int i = 0; i < 4; ++i) - for (int k = 0; k < 4; ++k) + std::memcpy(drawn.clip, clip, sizeof(clip)); + drawn.hasClip = !drawn.screenSpace && it->kind != 4u; // (the skinned programs: not modelled) + // For interpolation (Renderer::setParts): the matrix as camera (VU 9-12, the view's projection, its z row + // scaled by the object's depth factor as buildStrips scales the matrix's) times the object (VU 0-3: object to + // camera, the camera's turn included), interpolated apart so a turning object or camera keeps its shape. + if (!drawn.screenSpace) + { + const bool depthScaled = drawPc != 0x0070u; + for (int i = 0; i < 4; ++i) + for (int k = 0; k < 4; ++k) drawn.partCamera[i * 4 + k] = parameters.camera[i][k] * (k == 2 && depthScaled ? parameters.depthScale : 1.0f); - std::memcpy(drawn.partObject, object, sizeof(object)); - drawn.hasParts = true; - } - g_stats.skid += skid ? 1u : 0u; - if (opaque) - { - g_previous.valid = true; - g_previous.file = fileIndex; - g_previous.offset = offset; - g_previous.poolFrom = it->kind == 1u ? poolFrom(*it) : offset; - g_previous.pc = drawPc; - std::memcpy(g_previous.screen, screen, sizeof(screen)); - std::memcpy(g_previous.clip, clip, sizeof(clip)); - std::memcpy(g_previous.object, object, sizeof(object)); + std::memcpy(drawn.partObject, object, sizeof(object)); + drawn.hasParts = true; + } + g_stats.skid += skid ? 1u : 0u; + if (opaque) + { + g_previous.valid = true; + g_previous.file = fileIndex; + g_previous.offset = offset; + g_previous.poolFrom = it->kind == 1u ? poolFrom(*it) : offset; + g_previous.pc = drawPc; + std::memcpy(g_previous.screen, screen, sizeof(screen)); + std::memcpy(g_previous.clip, clip, sizeof(clip)); + std::memcpy(g_previous.object, object, sizeof(object)); g_previous.pointLights = parameters.point; - } - // Its key for interpolation (Renderer::setKey): the object (file, offset) and its instance (two cars of one model - // apart), with how many had both before it this frame (a model placed several times, the views of a split - // screen); the renderer matches alike ones by where they are (the key's base), since that count changes as they - // are culled. - const uint64_t hash = ((static_cast(fileIndex) << 32 | offset) * 0x9e3779b97f4a7c15ull) ^ (static_cast(inst) * 0xc4ceb9fe1a85ec53ull); - const uint32_t occurrence = g_keysThisFrame[hash]++; - drawn.key = (hash ^ (static_cast(occurrence) * 0xc2b2ae3d27d4eb4full)) | 1u; - drawn.keyBase = hash | 1u; // alike objects (the same model without an instance of its own): matched by place - // PS2X_INTERP_LOG=1: each key the first time it is made (what the renderer's jump lines name). - static const bool s_logKeys = std::getenv("PS2X_INTERP_LOG") != nullptr; - if (s_logKeys) - { - static std::unordered_map s_seen; - if (!s_seen[drawn.key] && s_seen.size() < 20000u) - { - s_seen[drawn.key] = true; - std::fprintf(stderr, "[interp-key] %016llx obj %#x file %u offset %#x inst %#x occurrence %u setup %#x%s\n", - static_cast(drawn.key), obj, fileIndex, offset, inst, occurrence, drawPc, - opaque ? "" : " alpha"); - } - } - if (marking) - { - const uint32_t mark = g_nextMark; - g_nextMark = (g_nextMark + 1u) & 0xffffffu; - if (g_nextMark == 0u) - g_nextMark = 1u; - // A VIF NOP (cmd 0, no interrupt) whatever its immediate and NUM. The resume's last qword is three NOPs - // and the MSCAL: each carries the mark (the adapter keeps the last NOP's before the MSCAL). - for (int k = 0; k < 3; ++k) - if (k == 0 || words[k] == 0u) - words[k] = mark; - else - break; - std::memcpy(last, words, 12); - drawn.mark = mark; - } - if (hookOrder()) - { - ViewList &list = g_lists[g_building]; - ++g_built[g_building]; - list.frame = g_frame; - if (marking) // the comparison: the adapter takes a copy at the mark (checked, not drawn) - g_drawn[drawn.mark] = drawn; - if (opaque) - list.opaque.push_back(std::move(drawn)); - else - { - list.pendingAlpha = std::move(drawn); - list.pending = true; - } - } - else - g_drawn[drawn.mark] = std::move(drawn); - ++g_stats.drawn; - g_stats.resumed += resume ? 1u : 0u; - g_stats.sprites += pc == 0x3000u ? 1u : 0u; - g_stats.ribbons += pc == 0x3270u ? 1u : 0u; - g_stats.skinned += it->kind == 4u ? 1u : 0u; - g_stats.reflective += pc == 0x1db8u ? 1u : 0u; - } - - void pktAddVu1ObjOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (active()) - { - ++g_stats.cCalls; // hierObjectNode's C path: left to the stream for now - g_previous.valid = false; - if (static const bool s_dumpLog = std::getenv("TMB_NATIVE_MESHES_DUMP") != nullptr; s_dumpLog) - { - const Ee ee{rdram, bozo::port::scratchpad(runtime)}; - const uint32_t obj = getRegU32(ctx, 6), inst = ee.u32(0x70000020u); - static std::unordered_map s_seen; - if (!s_seen[obj]) - { - s_seen[obj] = true; - const uint32_t index = ee.u32(obj + 0x68u); - const bool skinned = ee.u32(obj + 0x64u) != 0u && inst != 0u; - std::fprintf(stderr, "[tmb:mesh] dump C object %#x inst %#x flags %#x skeleton %#x index %u chain %#x bones %#x\n", obj, inst, - ee.u16(obj + 0xcu), ee.u32(obj + 0x64u), index, skinned ? ee.u32(ee.u32(inst + 0x18u) + 4u * index) : 0u, - skinned ? ee.u32(ee.u32(inst + 0x14u) + 4u * index) : 0u); - } - } - } - pktAddVu1Obj__FP9Vu1DmaPktP6QwDataP11_hierobjecti_0x1e9bc0(rdram, ctx, runtime); - } - - // pktLinkAlphaObjAsm links the alpha object pktAddVu1ObjAsm just built into the view's depth-sorted list, by the - // depth in VU0 vf30.x: its bucket as it computes it. - void pktLinkAlphaObjAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (active() && hookOrder()) - { - ViewList &list = g_lists[g_building]; - if (list.pending) - { - float depth[4]; + } + // Its key for interpolation (Renderer::setKey): the object (file, offset) and its instance (two cars of one model + // apart), with how many had both before it this frame (a model placed several times, the views of a split + // screen); the renderer matches alike ones by where they are (the key's base), since that count changes as they + // are culled. + const uint64_t hash = ((static_cast(fileIndex) << 32 | offset) * 0x9e3779b97f4a7c15ull) ^ (static_cast(inst) * 0xc4ceb9fe1a85ec53ull); + const uint32_t occurrence = g_keysThisFrame[hash]++; + drawn.key = (hash ^ (static_cast(occurrence) * 0xc2b2ae3d27d4eb4full)) | 1u; + drawn.keyBase = hash | 1u; // alike objects (the same model without an instance of its own): matched by place + // PS2X_INTERP_LOG=1: each key the first time it is made (what the renderer's jump lines name). + static const bool s_logKeys = std::getenv("PS2X_INTERP_LOG") != nullptr; + if (s_logKeys) + { + static std::unordered_map s_seen; + if (!s_seen[drawn.key] && s_seen.size() < 20000u) + { + s_seen[drawn.key] = true; + std::fprintf(stderr, "[interp-key] %016llx obj %#x file %u offset %#x inst %#x occurrence %u setup %#x%s\n", + static_cast(drawn.key), obj, fileIndex, offset, inst, occurrence, drawPc, + opaque ? "" : " alpha"); + } + } + if (marking) + { + const uint32_t mark = g_nextMark; + g_nextMark = (g_nextMark + 1u) & 0xffffffu; + if (g_nextMark == 0u) + g_nextMark = 1u; + // A VIF NOP (cmd 0, no interrupt) whatever its immediate and NUM. The resume's last qword is three NOPs + // and the MSCAL: each carries the mark (the adapter keeps the last NOP's before the MSCAL). + for (int k = 0; k < 3; ++k) + if (k == 0 || words[k] == 0u) + words[k] = mark; + else + break; + std::memcpy(last, words, 12); + drawn.mark = mark; + } + if (hookOrder()) + { + ViewList &list = g_lists[g_building]; + ++g_built[g_building]; + list.frame = g_frame; + if (marking) // the comparison: the adapter takes a copy at the mark (checked, not drawn) + g_drawn[drawn.mark] = drawn; + if (opaque) + list.opaque.push_back(std::move(drawn)); + else + { + list.pendingAlpha = std::move(drawn); + list.pending = true; + } + } + else + g_drawn[drawn.mark] = std::move(drawn); + ++g_stats.drawn; + g_stats.resumed += resume ? 1u : 0u; + g_stats.sprites += pc == 0x3000u ? 1u : 0u; + g_stats.ribbons += pc == 0x3270u ? 1u : 0u; + g_stats.skinned += it->kind == 4u ? 1u : 0u; + g_stats.reflective += pc == 0x1db8u ? 1u : 0u; + } + + void pktAddVu1ObjOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (active()) + { + ++g_stats.cCalls; // hierObjectNode's C path: left to the stream for now + g_previous.valid = false; + if (static const bool s_dumpLog = std::getenv("TMB_NATIVE_MESHES_DUMP") != nullptr; s_dumpLog) + { + const Ee ee{rdram, bozo::port::scratchpad(runtime)}; + const uint32_t obj = getRegU32(ctx, 6), inst = ee.u32(0x70000020u); + static std::unordered_map s_seen; + if (!s_seen[obj]) + { + s_seen[obj] = true; + const uint32_t index = ee.u32(obj + 0x68u); + const bool skinned = ee.u32(obj + 0x64u) != 0u && inst != 0u; + std::fprintf(stderr, "[tmb:mesh] dump C object %#x inst %#x flags %#x skeleton %#x index %u chain %#x bones %#x\n", obj, inst, + ee.u16(obj + 0xcu), ee.u32(obj + 0x64u), index, skinned ? ee.u32(ee.u32(inst + 0x18u) + 4u * index) : 0u, + skinned ? ee.u32(ee.u32(inst + 0x14u) + 4u * index) : 0u); + } + } + } + pktAddVu1Obj__FP9Vu1DmaPktP6QwDataP11_hierobjecti_0x1e9bc0(rdram, ctx, runtime); + } + + // pktLinkAlphaObjAsm links the alpha object pktAddVu1ObjAsm just built into the view's depth-sorted list, by the + // depth in VU0 vf30.x: its bucket as it computes it. + void pktLinkAlphaObjAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (active() && hookOrder()) + { + ViewList &list = g_lists[g_building]; + if (list.pending) + { + float depth[4]; if (bozo::port::nativeGraphics(runtime)) std::memcpy(depth, &tmb::scene::get(runtime).nearRange, sizeof(depth)); else vf(ctx, 30, depth); - int32_t bucket = 1; - if (depth[0] > 8.0f) - bucket = tmb::cvtWS((depth[0] > 1024.0f ? 1016.0f : depth[0]) * 0.125f) + 1; - list.link(std::clamp(bucket, 0, 128)); - } - } - pktLinkAlphaObjAsm_0x1eaf84(rdram, ctx, runtime); - } - - // The draws of a view's chain in the order the chain sends them: the opaque objects, then the alpha list's - // buckets from the farthest, each bucket's newest first. - void submitList(ViewList &list) - { - if (list.empty()) - { - list.clear(); - return; - } - tmb::native::applyViewClip(); - if (g_live.noClip) - bozo::render::Renderer::instance().clearClip(); - g_submitIndex = 0; - const int which = g_inHier2pFlush ? 1 : 0; // hier__Fi's, hier2p's - ++g_kicks[which]; - g_submitted[which] += list.size(); - g_submitter.submitInOrder(list); - list.clear(); - } - - // A view built and not kicked: the menus' (sent with the frame) now; hier2p's never sent by the game, dropped. - void sendUnkicked(ViewList &list) - { - if (list.empty()) - return; - if (list.hier2p) - { - ++g_listDrops; - list.clear(); - return; - } - ++g_unsentFlushes; - submitList(list); - } - - // hier__Fi, its chain built (the alpha list attached when it has objects) and queued, asks hierCheckVifComplete - // whether VIF1 is free: kicked now (hierFlushObjQ) or by hierDmaHandler when the transfer before it ends, but in - // this order either way. Its view's draws are submitted there. (Not at hier__Fi's return: a recompiled function - // can return to the dispatcher before its end. Not at hierFlushObjQ: the DMA handler calls it too.) A view with - // no object kicks nothing. - void hierCheckVifCompleteOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - if (active() && hookOrder() && getRegU32(ctx, 31) == kHierKickReturn) - submitList(g_lists[0]); + int32_t bucket = 1; + if (depth[0] > 8.0f) + bucket = tmb::cvtWS((depth[0] > 1024.0f ? 1016.0f : depth[0]) * 0.125f) + 1; + list.link(std::clamp(bucket, 0, 128)); + } + } + pktLinkAlphaObjAsm_0x1eaf84(rdram, ctx, runtime); + } + + // The draws of a view's chain in the order the chain sends them: the opaque objects, then the alpha list's + // buckets from the farthest, each bucket's newest first. + void submitList(ViewList &list) + { + if (list.empty()) + { + list.clear(); + return; + } + tmb::native::applyViewClip(); + if (g_live.noClip) + bozo::render::Renderer::instance().clearClip(); + g_submitIndex = 0; + const int which = g_inHier2pFlush ? 1 : 0; // hier__Fi's, hier2p's + ++g_kicks[which]; + g_submitted[which] += list.size(); + g_submitter.submitInOrder(list); + list.clear(); + } + + // A view built and not kicked: the menus' (sent with the frame) now; hier2p's never sent by the game, dropped. + void sendUnkicked(ViewList &list) + { + if (list.empty()) + return; + if (list.hier2p) + { + ++g_listDrops; + list.clear(); + return; + } + ++g_unsentFlushes; + submitList(list); + } + + // hier__Fi, its chain built (the alpha list attached when it has objects) and queued, asks hierCheckVifComplete + // whether VIF1 is free: kicked now (hierFlushObjQ) or by hierDmaHandler when the transfer before it ends, but in + // this order either way. Its view's draws are submitted there. (Not at hier__Fi's return: a recompiled function + // can return to the dispatcher before its end. Not at hierFlushObjQ: the DMA handler calls it too.) A view with + // no object kicks nothing. + void hierCheckVifCompleteOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + if (active() && hookOrder() && getRegU32(ctx, 31) == kHierKickReturn) + submitList(g_lists[0]); if (bozo::port::nativeGraphics(runtime)) { // submitList copied the view into the native renderer. Its game-side queue is immediately reusable. @@ -1626,14 +1627,14 @@ namespace tmb::meshes } else hierCheckVifComplete__Fv_0x1d47c8(rdram, ctx, runtime); - } - - void hier2pFlushDmaOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - g_inHier2pFlush = true; - if (active() && hookOrder()) - submitList(g_lists[0]); // what hier2p built, at its view's turn (nothing is built in between) - g_inHier2pFlush = false; + } + + void hier2pFlushDmaOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + g_inHier2pFlush = true; + if (active() && hookOrder()) + submitList(g_lists[0]); // what hier2p built, at its view's turn (nothing is built in between) + g_inHier2pFlush = false; if (bozo::port::nativeGraphics(runtime)) { const uint32_t gp = getRegU32(ctx, 28); @@ -1644,269 +1645,299 @@ namespace tmb::meshes } else hier2pFlushDma__Fv_0x1d28f0(rdram, ctx, runtime); - } - - // At each view hier__Fi sends the constants block (VU 5-8 among it: the light directions until a car sends - // its own), then calls hierCacheForAsm. - void hierCacheForAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - hierCacheForAsm_0x2020e4(rdram, ctx, runtime); - if (!active()) - return; - const Ee ee{rdram, bozo::port::scratchpad(runtime)}; + } + + // At each view hier__Fi sends the constants block (VU 5-8 among it: the light directions until a car sends + // its own), then calls hierCacheForAsm. + void hierCacheForAsmOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + hierCacheForAsm_0x2020e4(rdram, ctx, runtime); + if (!active()) + return; + const Ee ee{rdram, bozo::port::scratchpad(runtime)}; auto &cache = retained(runtime); for (unsigned light = 0; light < 3; ++light) for (unsigned axis = 0; axis < 3; ++axis) cache.opaqueDirections[light][axis] = ee.f32(kDefaultLightRecords + 16u + axis * 16u + light * 4u); - g_previous.valid = false; - // A view before it whose chain hier__Fi did not kick (the menus send theirs with the frame): its objects first. - if (hookOrder()) - { - sendUnkicked(g_lists[0]); - g_lists[0].hier2p = getRegU32(ctx, 31) == kHier2pCacheReturn; - } - } - } - - bool enabled() { return active(); } - - std::string packPath(const char *envName, const char *builtIn) - { - if (const char *path = std::getenv(envName); path && *path) - return path; - std::error_code ec; - if (std::filesystem::exists(builtIn, ec)) - return builtIn; - // A copy of the runner with its data (the pack beside the game's files, or beside the runner). - const std::filesystem::path name = std::filesystem::path(builtIn).filename(); - for (const std::filesystem::path &dir : {std::filesystem::path(tmb::host::elfDirectory()), std::filesystem::path(tmb::host::executableDirectory())}) - if (!dir.empty() && std::filesystem::exists(dir / name, ec)) - return (dir / name).string(); - return builtIn; - } - - // The game's order unless the adapter follows the stream (TMB_NATIVE_VIF=1), where TMB_NATIVE_MESHES_CHECK=1 keeps - // it to compare the two. - bool hookOrder() - { - return !tmb::native::vifObserved() || checking(); - } - - void streamReached(uint32_t mark, uint64_t alpha, uint64_t test, bool depthMasked) - { - CheckRecord &record = g_checks[mark]; - record.streamOrder = g_streamSeq++; - record.stream = GsState{alpha, test, depthMasked}; - record.streamSeen = true; - if (record.frame == 0u) - record.frame = g_frame; - } - - namespace - { - // TMB_NATIVE_VIF=1 with TMB_NATIVE_MESHES_CHECK=1, at a frame's end: the objects of the frame before, the hook's - // order and materials against the stream's. - void compareOrders() - { - static uint64_t s_objects = 0, s_unreached = 0, s_unsubmitted = 0, s_orderDiffs = 0, s_matDiffs = 0, s_batches = 0; - std::vector> hook, stream; - std::vector done; - for (auto &[mark, record] : g_checks) - { - if (g_frame - record.frame < 2u) - continue; - done.push_back(mark); - if (record.hookOrder == ~0ull) - { - ++s_unsubmitted; - continue; - } - ++s_objects; - if (!record.streamSeen) - { - static uint32_t s_logged = 0; - if (s_logged++ < 30u) - std::fprintf(stderr, "[tmb:order] mark %u: object %#x (%s, #%u in its view, frame %u) not reached in the stream\n", mark, - record.object, record.alphaList ? "alpha" : "opaque", record.index, record.frame); - ++s_unreached; - continue; - } - hook.push_back({record.hookOrder, mark}); - stream.push_back({record.streamOrder, mark}); - // The stream's materials: its state at the mark, then the object's writes. - GsState gs = record.stream; - size_t k = 0; - bool differs = false; - for (size_t i = 0; i < record.sets.size(); ++i) - { - const Batch &sets = record.sets[i]; - gs.apply(sets); - if (i == 0u && record.hasContext) - continue; - if (!sets.textured) // draws nothing - continue; - ++s_batches; - const Mat m = matFor(gs, sets); - if (k < record.hook.size() && !(record.hook[k] == m)) - { - differs = true; - static uint32_t s_logged = 0; - if (s_logged++ < 40u) - std::fprintf(stderr, "[tmb:order] mark %u batch %zu: hook alpha %#llx test %#llx zmsk %d, stream alpha %#llx test %#llx zmsk %d (context %d; object %#x, %s, #%u in its view)\n", - mark, k, static_cast(record.hook[k].alpha), static_cast(record.hook[k].test), - record.hook[k].depthMasked ? 1 : 0, static_cast(m.alpha), static_cast(m.test), - m.depthMasked ? 1 : 0, record.hasContext ? 1 : 0, record.object, record.alphaList ? "alpha" : "opaque", - record.index); - } - ++k; - } - s_matDiffs += differs ? 1u : 0u; - } - for (uint32_t mark : done) - g_checks.erase(mark); - std::sort(hook.begin(), hook.end()); - std::sort(stream.begin(), stream.end()); - for (size_t i = 0; i < hook.size(); ++i) - if (hook[i].second != stream[i].second) - { - ++s_orderDiffs; - static uint32_t s_logged = 0; - if (s_logged++ < 20u) - std::fprintf(stderr, "[tmb:order] position %zu of %zu: hook mark %u, stream mark %u\n", i, hook.size(), hook[i].second, stream[i].second); - } - static uint32_t s_frames = 0; - if (++s_frames % 250u == 0u) - std::fprintf(stderr, "[tmb:order] %llu objects submitted at the hook: %llu not reached in the stream, %llu out of the stream's order, %llu with a " - "material differing (%llu batches); %llu marked, never submitted\n", - static_cast(s_objects), static_cast(s_unreached), static_cast(s_orderDiffs), - static_cast(s_matDiffs), static_cast(s_batches), static_cast(s_unsubmitted)); - } - } - - // The adapter, at the setup MSCAL a marked header ends with: the object's draws (false: not one of ours). - bool take(uint32_t mark, Drawn &out) - { - const auto it = g_drawn.find(mark); - if (it == g_drawn.end()) - return false; - out = std::move(it->second); - g_drawn.erase(it); - ++g_stats.taken; - return true; - } - - // The end of a published frame: objects never reached in the stream are dropped (VU1 drew them, or their chain - // was not sent), and every 250 frames the counts. - void flushUnsent() - { - if (!active() || !hookOrder()) - return; - sendUnkicked(g_lists[0]); - } - - void endFrame() - { - if (!active()) - return; - ++g_frame; - g_live.dumping = false; - if (g_frame % 60u == 0u) - readLiveToggles(); - g_keysThisFrame.clear(); - if (checking() && tmb::native::vifObserved()) - compareOrders(); - // A view built and never kicked (its chain not sent): dropped. - for (ViewList &list : g_lists) - if (!list.empty() && g_frame - list.frame > 2u) - { - ++g_stats.unclaimed; - list.clear(); - } - for (auto it = g_drawn.begin(); it != g_drawn.end();) - if (g_frame - it->second.frame > 2u) - { - ++g_stats.unclaimed; - it = g_drawn.erase(it); - } - else - ++it; + g_previous.valid = false; + // A view before it whose chain hier__Fi did not kick (the menus send theirs with the frame): its objects first. + if (hookOrder()) + { + sendUnkicked(g_lists[0]); + g_lists[0].hier2p = getRegU32(ctx, 31) == kHier2pCacheReturn; + } + } + } + + bool enabled() { return active(); } + + std::string packPath(const char *envName, const char *builtIn) + { + if (const char *path = std::getenv(envName); path && *path) + return path; + std::error_code ec; + if (std::filesystem::exists(builtIn, ec)) + return builtIn; + // A copy of the runner with its data (the pack beside the game's files, or beside the runner). + const std::filesystem::path name = std::filesystem::path(builtIn).filename(); + for (const std::filesystem::path &dir : {std::filesystem::path(tmb::host::elfDirectory()), std::filesystem::path(tmb::host::executableDirectory())}) + if (!dir.empty() && std::filesystem::exists(dir / name, ec)) + return (dir / name).string(); + return builtIn; + } + + // The game's order unless the adapter follows the stream (TMB_NATIVE_VIF=1), where TMB_NATIVE_MESHES_CHECK=1 keeps + // it to compare the two. + bool hookOrder() + { + return !tmb::native::vifObserved() || checking(); + } + + void streamReached(uint32_t mark, uint64_t alpha, uint64_t test, bool depthMasked) + { + CheckRecord &record = g_checks[mark]; + record.streamOrder = g_streamSeq++; + record.stream = GsState{alpha, test, depthMasked}; + record.streamSeen = true; + if (record.frame == 0u) + record.frame = g_frame; + } + + namespace + { + // TMB_NATIVE_VIF=1 with TMB_NATIVE_MESHES_CHECK=1, at a frame's end: the objects of the frame before, the hook's + // order and materials against the stream's. + void compareOrders() + { + static uint64_t s_objects = 0, s_unreached = 0, s_unsubmitted = 0, s_orderDiffs = 0, s_matDiffs = 0, s_batches = 0; + std::vector> hook, stream; + std::vector done; + for (auto &[mark, record] : g_checks) + { + if (g_frame - record.frame < 2u) + continue; + done.push_back(mark); + if (record.hookOrder == ~0ull) + { + ++s_unsubmitted; + continue; + } + ++s_objects; + if (!record.streamSeen) + { + static uint32_t s_logged = 0; + if (s_logged++ < 30u) + std::fprintf(stderr, "[tmb:order] mark %u: object %#x (%s, #%u in its view, frame %u) not reached in the stream\n", mark, + record.object, record.alphaList ? "alpha" : "opaque", record.index, record.frame); + ++s_unreached; + continue; + } + hook.push_back({record.hookOrder, mark}); + stream.push_back({record.streamOrder, mark}); + // The stream's materials: its state at the mark, then the object's writes. + GsState gs = record.stream; + size_t k = 0; + bool differs = false; + for (size_t i = 0; i < record.sets.size(); ++i) + { + const Batch &sets = record.sets[i]; + gs.apply(sets); + if (i == 0u && record.hasContext) + continue; + if (!sets.textured) // draws nothing + continue; + ++s_batches; + const Mat m = matFor(gs, sets); + if (k < record.hook.size() && !(record.hook[k] == m)) + { + differs = true; + static uint32_t s_logged = 0; + if (s_logged++ < 40u) + std::fprintf(stderr, "[tmb:order] mark %u batch %zu: hook alpha %#llx test %#llx zmsk %d, stream alpha %#llx test %#llx zmsk %d (context %d; object %#x, %s, #%u in its view)\n", + mark, k, static_cast(record.hook[k].alpha), static_cast(record.hook[k].test), + record.hook[k].depthMasked ? 1 : 0, static_cast(m.alpha), static_cast(m.test), + m.depthMasked ? 1 : 0, record.hasContext ? 1 : 0, record.object, record.alphaList ? "alpha" : "opaque", + record.index); + } + ++k; + } + s_matDiffs += differs ? 1u : 0u; + } + for (uint32_t mark : done) + g_checks.erase(mark); + std::sort(hook.begin(), hook.end()); + std::sort(stream.begin(), stream.end()); + for (size_t i = 0; i < hook.size(); ++i) + if (hook[i].second != stream[i].second) + { + ++s_orderDiffs; + static uint32_t s_logged = 0; + if (s_logged++ < 20u) + std::fprintf(stderr, "[tmb:order] position %zu of %zu: hook mark %u, stream mark %u\n", i, hook.size(), hook[i].second, stream[i].second); + } + static uint32_t s_frames = 0; + if (++s_frames % 250u == 0u) + std::fprintf(stderr, "[tmb:order] %llu objects submitted at the hook: %llu not reached in the stream, %llu out of the stream's order, %llu with a " + "material differing (%llu batches); %llu marked, never submitted\n", + static_cast(s_objects), static_cast(s_unreached), static_cast(s_orderDiffs), + static_cast(s_matDiffs), static_cast(s_batches), static_cast(s_unsubmitted)); + } + } + + // The adapter, at the setup MSCAL a marked header ends with: the object's draws (false: not one of ours). + bool take(uint32_t mark, Drawn &out) + { + const auto it = g_drawn.find(mark); + if (it == g_drawn.end()) + return false; + out = std::move(it->second); + g_drawn.erase(it); + ++g_stats.taken; + return true; + } + + // The end of a published frame: objects never reached in the stream are dropped (VU1 drew them, or their chain + // was not sent), and every 250 frames the counts. + void flushUnsent() + { + if (!active() || !hookOrder()) + return; + sendUnkicked(g_lists[0]); + } + + void endFrame() + { + if (!active()) + return; + ++g_frame; + g_live.dumping = false; + if (g_frame % 60u == 0u) + readLiveToggles(); + g_keysThisFrame.clear(); + if (checking() && tmb::native::vifObserved()) + compareOrders(); + // A view built and never kicked (its chain not sent): dropped. + for (ViewList &list : g_lists) + if (!list.empty() && g_frame - list.frame > 2u) + { + ++g_stats.unclaimed; + list.clear(); + } + for (auto it = g_drawn.begin(); it != g_drawn.end();) + if (g_frame - it->second.frame > 2u) + { + ++g_stats.unclaimed; + it = g_drawn.erase(it); + } + else + ++it; // TMB_TEXTURE_DUMP (runtime/tmb_texture_dump.cpp): every 250 frames, the textures of every object in the loaded // NGP files, drawn or not, through the same lookup as their draws (their slots' texture numbers and TEX0), so a // dump covers a whole arena and the cars loaded, not only what the camera saw. if (g_rdramForDump && g_frame % 250u == 125u && tmb::textures::dump::enabled()) dumpLoadedObjects(g_rdramForDump); - // TMB_NATIVE_MESHES_DUMP=,: EE memory at that frame (a diagnostic, to compare the loaded NGP - // images with the disc's offline). - if (static const char *s_dump = std::getenv("TMB_NATIVE_MESHES_DUMP"); s_dump && g_rdramForDump) - { - static std::string s_path; - static uint32_t s_at = [&] - { - std::string spec(s_dump); - const size_t comma = spec.rfind(','); - s_path = spec.substr(0, comma); - return comma == std::string::npos ? 0u : static_cast(std::strtoul(spec.c_str() + comma + 1, nullptr, 10)); - }(); - if (s_at == 0u && g_firstSkinned != 0u) - s_at = g_firstSkinned + 300u; // frame 0: 300 frames after the first skinned object - if (g_frame == s_at) - if (FILE *f = std::fopen(s_path.c_str(), "wb")) - { - std::fwrite(g_rdramForDump, 1, 0x2000000u, f); - std::fclose(f); - std::fprintf(stderr, "[tmb:mesh] EE memory dumped to %s at frame %u\n", s_path.c_str(), g_frame); - } - } - if (g_frame % 250u == 0u) - { - if (hookOrder()) - std::fprintf(stderr, "[tmb:mesh] per 250 frames, the game's order: %llu objects built; views kicked by hier__Fi %llu (%llu objects), by " - "hier2pFlushDma %llu (%llu objects), sent unkicked %llu; %llu dropped\n", - static_cast(g_built[0]), static_cast(g_kicks[0]), - static_cast(g_submitted[0]), static_cast(g_kicks[1]), - static_cast(g_submitted[1]), static_cast(g_unsentFlushes), - static_cast(g_listDrops)); - g_listDrops = g_built[0] = g_built[1] = g_kicks[0] = g_kicks[1] = g_submitted[0] = g_submitted[1] = g_unsentFlushes = 0; - std::fprintf(stderr, - "[tmb:mesh] per 250 frames: %llu objects at the hook (%llu by the C path), %llu drawn from the pack (%llu triangles), " - "%llu taken in the stream, %llu unclaimed; left to the stream: %llu by program (%llu drawn with a group GS-state block), %llu outside " - "the loaded files, %llu not in the pack, %llu of another kind in the pack, %llu unmarked; %llu texture number mismatches; " - "%llu resumes drawn, %llu resumes not after their pool's object; %llu sprites, %llu ribbons, %llu skinned, %llu environment-mapped, " - "%llu morphing drawn, %llu skid marks' objects; GS contexts: %llu from the pack, %llu the game's default, %llu not in the pack, %llu differing from EE memory\n", - static_cast(g_stats.calls), static_cast(g_stats.cCalls), - static_cast(g_stats.drawn), static_cast(g_stats.triangles), - static_cast(g_stats.taken), static_cast(g_stats.unclaimed), - static_cast(g_stats.program), static_cast(g_stats.extra), - static_cast(g_stats.noFile), static_cast(g_stats.noObject), - static_cast(g_stats.kindOther), static_cast(g_stats.unmarked), - static_cast(g_stats.idMismatch), static_cast(g_stats.resumed), - static_cast(g_stats.resumeOther), static_cast(g_stats.sprites), - static_cast(g_stats.ribbons), static_cast(g_stats.skinned), - static_cast(g_stats.reflective), static_cast(g_stats.morphed), - static_cast(g_stats.skid), static_cast(g_stats.contextsPack), static_cast(g_stats.contextsDefault), - static_cast(g_stats.contextsMissing), static_cast(g_stats.contextsDiffering)); - g_stats = Stats{}; - } - } - - void install(tmb::Registry &runtime) - { - if (!active()) - return; - pack(); - g_submitter.tag = "tmb"; - g_submitter.fogColour = &tmb::native::fogColour; - if (checking()) - g_submitter.observer = &g_checkObserver; - runtime.registerFunction(kFileOnlyNgpFile, &fileOnlyNgpFileOverride); - runtime.registerFunction(kFileAddNgpFile, &fileAddNgpFileOverride); - runtime.registerFunction(kHierCacheForAsm, &hierCacheForAsmOverride); - runtime.registerFunction(kPktAddVu1ObjAsm, &pktAddVu1ObjAsmOverride); - runtime.registerFunction(kPktAddVu1Obj, &pktAddVu1ObjOverride); - runtime.registerFunction(kPktLinkAlphaObjAsm, &pktLinkAlphaObjAsmOverride); - runtime.registerFunction(kHierCheckVifComplete, &hierCheckVifCompleteOverride); - runtime.registerFunction(kSkidDraw, &skidDrawOverride); - runtime.registerFunction(kHier2pFlushDma, &hier2pFlushDmaOverride); - std::fprintf(stderr, "[tmb:mesh] TMB_NATIVE_MESHES=1: hier objects drawn from the mesh pack at pktAddVu1ObjAsm\n"); - } -} + // TMB_NATIVE_MESHES_DUMP=,: EE memory at that frame (a diagnostic, to compare the loaded NGP + // images with the disc's offline). + if (static const char *s_dump = std::getenv("TMB_NATIVE_MESHES_DUMP"); s_dump && g_rdramForDump) + { + static std::string s_path; + static uint32_t s_at = [&] + { + std::string spec(s_dump); + const size_t comma = spec.rfind(','); + s_path = spec.substr(0, comma); + return comma == std::string::npos ? 0u : static_cast(std::strtoul(spec.c_str() + comma + 1, nullptr, 10)); + }(); + if (s_at == 0u && g_firstSkinned != 0u) + s_at = g_firstSkinned + 300u; // frame 0: 300 frames after the first skinned object + if (g_frame == s_at) + if (FILE *f = std::fopen(s_path.c_str(), "wb")) + { + std::fwrite(g_rdramForDump, 1, 0x2000000u, f); + std::fclose(f); + std::fprintf(stderr, "[tmb:mesh] EE memory dumped to %s at frame %u\n", s_path.c_str(), g_frame); + } + } + if (g_frame % 250u == 0u) + { + if (hookOrder()) + std::fprintf(stderr, "[tmb:mesh] per 250 frames, the game's order: %llu objects built; views kicked by hier__Fi %llu (%llu objects), by " + "hier2pFlushDma %llu (%llu objects), sent unkicked %llu; %llu dropped\n", + static_cast(g_built[0]), static_cast(g_kicks[0]), + static_cast(g_submitted[0]), static_cast(g_kicks[1]), + static_cast(g_submitted[1]), static_cast(g_unsentFlushes), + static_cast(g_listDrops)); + g_listDrops = g_built[0] = g_built[1] = g_kicks[0] = g_kicks[1] = g_submitted[0] = g_submitted[1] = g_unsentFlushes = 0; + std::fprintf(stderr, + "[tmb:mesh] per 250 frames: %llu objects at the hook (%llu by the C path), %llu drawn from the pack (%llu triangles), " + "%llu taken in the stream, %llu unclaimed; left to the stream: %llu by program (%llu drawn with a group GS-state block), %llu outside " + "the loaded files, %llu not in the pack, %llu of another kind in the pack, %llu unmarked; %llu texture number mismatches; " + "%llu resumes drawn, %llu resumes not after their pool's object; %llu sprites, %llu ribbons, %llu skinned, %llu environment-mapped, " + "%llu morphing drawn, %llu skid marks' objects; GS contexts: %llu from the pack, %llu the game's default, %llu not in the pack, %llu differing from EE memory\n", + static_cast(g_stats.calls), static_cast(g_stats.cCalls), + static_cast(g_stats.drawn), static_cast(g_stats.triangles), + static_cast(g_stats.taken), static_cast(g_stats.unclaimed), + static_cast(g_stats.program), static_cast(g_stats.extra), + static_cast(g_stats.noFile), static_cast(g_stats.noObject), + static_cast(g_stats.kindOther), static_cast(g_stats.unmarked), + static_cast(g_stats.idMismatch), static_cast(g_stats.resumed), + static_cast(g_stats.resumeOther), static_cast(g_stats.sprites), + static_cast(g_stats.ribbons), static_cast(g_stats.skinned), + static_cast(g_stats.reflective), static_cast(g_stats.morphed), + static_cast(g_stats.skid), static_cast(g_stats.contextsPack), static_cast(g_stats.contextsDefault), + static_cast(g_stats.contextsMissing), static_cast(g_stats.contextsDiffering)); + g_stats = Stats{}; + } + } + + void install(tmb::Registry &runtime) + { + if (!active()) + return; + pack(); + g_submitter.tag = "tmb"; + g_submitter.fogColour = &tmb::native::fogColour; + if (checking()) + g_submitter.observer = &g_checkObserver; + runtime.registerFunction(kFileOnlyNgpFile, &fileOnlyNgpFileOverride); + runtime.registerFunction(kFileAddNgpFile, &fileAddNgpFileOverride); + runtime.registerFunction(kHierCacheForAsm, &hierCacheForAsmOverride); + runtime.registerFunction(kPktAddVu1ObjAsm, &pktAddVu1ObjAsmOverride); + runtime.registerFunction(kPktAddVu1Obj, &pktAddVu1ObjOverride); + runtime.registerFunction(kPktLinkAlphaObjAsm, &pktLinkAlphaObjAsmOverride); + runtime.registerFunction(kHierCheckVifComplete, &hierCheckVifCompleteOverride); + runtime.registerFunction(kSkidDraw, &skidDrawOverride); + runtime.registerFunction(kHier2pFlushDma, &hier2pFlushDmaOverride); + std::fprintf(stderr, "[tmb:mesh] TMB_NATIVE_MESHES=1: hier objects drawn from the mesh pack at pktAddVu1ObjAsm\n"); + } + // Save states (tmb_state.cpp): the NGP files the game bound (as bound: the game changes the images in memory after + // it loads them, so they are not bound again), the marks' counter (written into the game's DMA chains). The skid + // marks' object is the frame's. + void state(bozo::state::Archive &a) + { + std::vector images; + if (!a.loading()) + images = g_loaded.images(); + uint64_t n = bozo::state::count(a, images.size()); + if (a.loading()) + images.assign(n, {}); + for (auto &image : images) + { + bool file = image.file != nullptr; + bozo::state::fields(a, image.base, image.size, image.index, file); + if (a.loading()) + { + const auto &files = pack().files(); + if (file && image.index >= files.size()) + throw bozo::state::Error("save state: a bound NGP file the mesh pack does not have"); + image.file = file ? &files[image.index] : nullptr; + } + } + bozo::state::fields(a, g_nextMark, g_frame); + if (a.loading()) + { + g_loaded.restore(std::move(images)); + g_skid.valid = false; + } + } +} diff --git a/runtime/tmb_overrides.cpp b/runtime/tmb_overrides.cpp index ac3b8a7..3a8edbe 100644 --- a/runtime/tmb_overrides.cpp +++ b/runtime/tmb_overrides.cpp @@ -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" @@ -1179,4 +1180,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) diff --git a/runtime/tmb_particles.cpp b/runtime/tmb_particles.cpp index 0b749be..2515549 100644 --- a/runtime/tmb_particles.cpp +++ b/runtime/tmb_particles.cpp @@ -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" @@ -2637,4 +2638,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); + } } diff --git a/runtime/tmb_state.cpp b/runtime/tmb_state.cpp new file mode 100644 index 0000000..4901492 --- /dev/null +++ b/runtime/tmb_state.cpp @@ -0,0 +1,49 @@ +// 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 +#include + +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(); } + + 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); + 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(); + }, + [] { return std::string(); }}); + } +} diff --git a/runtime/tmb_state.h b/runtime/tmb_state.h new file mode 100644 index 0000000..b5b5fa2 --- /dev/null +++ b/runtime/tmb_state.h @@ -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); +} diff --git a/runtime/tmb_textures.cpp b/runtime/tmb_textures.cpp index 9a75f1a..e666265 100644 --- a/runtime/tmb_textures.cpp +++ b/runtime/tmb_textures.cpp @@ -1,586 +1,703 @@ -// TMB's textures for the native renderer, from the native texture pack converted offline from the disc's files -// (tools/tmb_texture_pack.py, scripts/recomp.sh): nothing is read from the game's texture records, GS packets or GS -// memory while the game runs. The runtime only follows TMB's texture code, at hooks: -// - which disc file goes where: fileReadf / zipInflateAll (name, destination), then fileOnlyTexFile / -// fileAddTexFile / fileOnlyResFile / fileAddResFile (destination) list the level's .TEX and .RTX files in order; -// - texmInit sets up each .TEX record in order (texmSetupTexture: its texture id, width, height, format): the n-th -// setup is the pack's n-th record of those files, so a texture id names a pack record; -// - texmLoadResTexture loads each .RTX record in order (sceGsSetDefLoadImage: its VRAM block, format, size): a palette's or -// an H texture's VRAM block names a pack record; -// - fontInit: the font's VRAM blocks (the pack's FONT file). -// A draw's TEX0 then finds its texture: TBP0 -> the texture id the game's own table (texInfo: TBP | ... | resident -// << 31 per id, word 1 of 4) has there, CBP -> the palette loaded at that block. -// -// Each hook checks the pack record against the game's own arguments (format, size) and reports a mismatch. -// -// The pack's container, its loader and the decoders (PSM, CSM1 palettes, TEXA alpha) are the fork's -// (runtime/native/native_texture_pack.h, tools/native_pack/texture.py); what is TMB's here is the key scheme above. - -#include "tmb_port.h" -#include "bozo/render/texture.h" -#include "bozo/render/texture_pack.h" -#include "tmb_meshes.h" -#include "tmb_texture_dump.h" -#include "bozo/hash.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef TMB_TEXTURE_PACK -#define TMB_TEXTURE_PACK "tmb_textures.pack" -#endif - -namespace tmb::textures -{ - namespace - { - using Texture = bozo::render::Texture; - - constexpr uint32_t kTexInfo = 0x004D1930u; // texInfo[1000], 16 bytes each - constexpr uint32_t kFileReadf = 0x001C21D0u; - constexpr uint32_t kZipInflateAll = 0x00200A20u; - constexpr uint32_t kFileOnlyTexFile = 0x001C2B60u; - constexpr uint32_t kFileAddTexFile = 0x001C2940u; - constexpr uint32_t kFileOnlyResFile = 0x001C2BA8u; - constexpr uint32_t kFileAddResFile = 0x001C29D8u; - constexpr uint32_t kTexmInit = 0x001F8868u; - constexpr uint32_t kTexmSetupTexture = 0x001F8F60u; - constexpr uint32_t kTexmResInit = 0x001F88F8u; - constexpr uint32_t kSceGsSetDefLoadImage = 0x00203F30u; - constexpr uint32_t kTexmLoadResTexture = 0x001F89B8u; - constexpr uint32_t kResLoadReturn = 0x001F8AB4u; // texmLoadResTexture's call of sceGsSetDefLoadImage - constexpr uint32_t kFontInit = 0x001C3E48u; - - using bozo::render::packs::psmIndexed; - using bozo::render::packs::psmIsH; - using Record = bozo::render::packs::TextureRecord; - bool isH(uint32_t psm) { return psmIsH(psm); } - bool indexed(uint32_t psm) { return psmIndexed(psm); } - - struct Store - { - std::mutex mutex; - bool loaded = false; - bozo::render::packs::TexturePack pack; // file name -> its records in order - std::unordered_map nameAt; // destination -> the disc file read there - std::vector texFiles, resFiles; // the level's, in the game's order - uint32_t texOrdinal = 0, resOrdinal = 0; - std::unordered_map byId; // texture id -> .TEX record - // VRAM block -> the .RTX record loaded there, and where in the block (its first texel, as loaded) - struct Placement - { - const Record *record = nullptr; - uint32_t x = 0, y = 0; - }; - std::unordered_map byBlock; // palettes - std::unordered_map hAt; // (block << 8 | psm) -> H texture - std::vector idAt = std::vector(16384u, 0xffffu); // TBP -> texture id (texInfo, refresh) - uint32_t fontTbp = ~0u; - std::unordered_map> decoded; - uint64_t decodes = 0; - const uint8_t *rdram = nullptr; - bool dump = false; // TMB_TEXTURE_DUMP (tmb_texture_dump.h): the records' origins kept for its index - std::unordered_map origin; // record -> "FILE#n" - }; - Store &store() - { - static Store s_store; - return s_store; - } - - void loadPack(Store &s) - { - if (s.loaded) - return; - s.loaded = true; - const std::string pathText = tmb::meshes::packPath("TMB_TEXTURE_PACK", TMB_TEXTURE_PACK); - const char *path = pathText.c_str(); - s.dump = tmb::textures::dump::enabled(); - if (!s.pack.load(path)) - { - std::fprintf(stderr, "[tmb:tex] no texture pack at %s (tools/tmb_texture_pack.py): the native draws are untextured\n", path); - return; - } - std::fprintf(stderr, "[tmb:tex] texture pack %s: %zu files, %zu records\n", path, s.pack.fileCount(), s.pack.recordCount()); - } - - // "cdrom0:\LVL\JUNKYARD.TEX;1" -> "JUNKYARD.TEX" - std::string baseName(const uint8_t *rdram, uint32_t address) - { - std::string name; - for (uint32_t i = 0; i < 256u; ++i) - { - const char c = static_cast(rdram[(address + i) & 0x1ffffffu]); - if (c == '\0' || c == ';') - break; - if (c == '\\' || c == '/' || c == ':') - name.clear(); - else - name.push_back(static_cast(c >= 'a' && c <= 'z' ? c - 32 : c)); - } - return name; - } - - // The n-th record of the listed files. - const Record *nth(Store &s, const std::vector &files, uint32_t n) - { - const Record *r = s.pack.nth(files, n); - if (r && s.dump && !s.origin.count(r)) // which file and which of its records, for the dump's index - { - uint32_t left = n; - for (const std::string &name : files) - { - const std::vector *records = s.pack.file(name); - if (!records) - break; - if (left < records->size()) - { - s.origin[r] = name + "#" + std::to_string(left); - break; - } - left -= static_cast(records->size()); - } - } - return r; - } - - std::string originOf(const Store &s, const Record *r) - { - if (!r) - return std::string(); - const auto it = s.origin.find(r); - return it != s.origin.end() ? it->second : std::string("?"); - } - - uint64_t texelHash(const Record &r) - { - const uint32_t seed[3] = {r.psm, r.width, r.height}; - return bozo::hash::xxh64(r.texels.data(), r.texels.size(), bozo::hash::xxh64(seed, sizeof(seed), 0)); - } - - void mismatch(const char *what, uint32_t n, const Record *r, uint32_t psm, uint32_t width, uint32_t height) - { - static uint32_t s_reported = 0; - if (s_reported++ < 20u) - std::fprintf(stderr, "[tmb:tex] %s #%u: the game sets up psm %#x %ux%u, the pack has %s\n", what, n, psm, width, - height, r ? (std::to_string(r->psm) + " " + std::to_string(r->width) + "x" + std::to_string(r->height)).c_str() : "nothing"); - } - - void noteFile(uint8_t *rdram, R5900Context *ctx) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - s.rdram = rdram; - s.nameAt[getRegU32(ctx, 5)] = baseName(rdram, getRegU32(ctx, 4)); - } - void fileReadfOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - noteFile(rdram, ctx); - fileReadf__FPcPv_0x1c21d0(rdram, ctx, runtime); - } - void zipInflateAllOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - noteFile(rdram, ctx); - zipInflateAll__FPcPv_0x200a20(rdram, ctx, runtime); - } - - void listFile(R5900Context *ctx, bool tex, bool only) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - std::vector &files = tex ? s.texFiles : s.resFiles; - if (only) - files.clear(); - // A new list of .TEX files: its records are set up from the first. The shell sets up its textures without - // texmInit (back from a match the count would go on from the level's, past the shell's records). - if (only && tex) - { - s.texOrdinal = 0; - s.byId.clear(); - s.decoded.clear(); - } - const auto it = s.nameAt.find(getRegU32(ctx, 4)); - files.push_back(it != s.nameAt.end() ? it->second : std::string("?")); - } - void fileOnlyTexFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - listFile(ctx, true, true); - fileOnlyTexFile__FPci_0x1c2b60(rdram, ctx, runtime); - } - void fileAddTexFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - listFile(ctx, true, false); - fileAddTexFile__FPci_0x1c2940(rdram, ctx, runtime); - } - void fileOnlyResFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - listFile(ctx, false, true); - fileOnlyResFile__FPci_0x1c2ba8(rdram, ctx, runtime); - } - void fileAddResFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - listFile(ctx, false, false); - fileAddResFile__FPci_0x1c29d8(rdram, ctx, runtime); - } - - void texmInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - loadPack(s); - s.rdram = rdram; - s.texOrdinal = 0; - s.byId.clear(); - s.decoded.clear(); - } - texmInit__F10_vramAddrs_0x1f8868(rdram, ctx, runtime); - Store &s = store(); - std::lock_guard lock(s.mutex); - std::string files; - for (const std::string &f : s.texFiles) - files += " " + f; - std::fprintf(stderr, "[tmb:tex] texmInit: %u textures set up from%s\n", s.texOrdinal, files.c_str()); - } - - // texmSetupTexture(id, width, height, psm, ...): once per .TEX record, in order. - void texmSetupTextureOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - const uint32_t id = getRegU32(ctx, 4) & 0xffffu, width = getRegU32(ctx, 5), height = getRegU32(ctx, 6), - psm = getRegU32(ctx, 7) & 0x3fu; - const uint32_t n = s.texOrdinal++; - const Record *r = nth(s, s.texFiles, n); - if (n == 0u) - std::fprintf(stderr, "[tmb:tex] texmSetupTexture: the first of %zu files (id %u, psm %#x %ux%u)\n", s.texFiles.size(), id, psm, - width, height); - if (r && r->psm == psm && r->width == width && r->height == height) - s.byId[id] = r; - else - mismatch("texture", n, r, psm, width, height); - } - texmSetupTexture__FiiiiiP6QwDataii_0x1f8f60(rdram, ctx, runtime); - } - - void texmResInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - loadPack(s); - s.rdram = rdram; - s.resOrdinal = 0; - s.byBlock.clear(); - s.hAt.clear(); - s.decoded.clear(); - } - texmResInit__F10_vramAddrsP6QwData_0x1f88f8(rdram, ctx, runtime); - Store &s = store(); - std::lock_guard lock(s.mutex); - std::string files; - for (const std::string &f : s.resFiles) - files += " " + f; - std::fprintf(stderr, "[tmb:tex] texmResInit: %u palettes and resident textures loaded from%s\n", s.resOrdinal, files.c_str()); - } - - // The shell calls it itself when texmResInit's check (texmResCheckForData) found nothing to load yet; texmResInit - // tail-jumps into it (a direct call: its records are counted from texmResInit's override). - void texmLoadResTextureOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - loadPack(s); - s.rdram = rdram; - s.resOrdinal = 0; - s.byBlock.clear(); - s.hAt.clear(); - s.decoded.clear(); - } - texmLoadResTexture__FP6QwData_0x1f89b8(rdram, ctx, runtime); - Store &s = store(); - std::lock_guard lock(s.mutex); - std::fprintf(stderr, "[tmb:tex] texmLoadResTexture: %u palettes and resident textures loaded\n", s.resOrdinal); - } - - // sceGsSetDefLoadImage(image, dbp, dbw, dpsm, x, y, w, h), called by texmLoadResTexture (its return address) - // once per .RTX record, in order. - void sceGsSetDefLoadImageOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - if (getRegU32(ctx, 31) == kResLoadReturn) - { - const uint32_t block = getRegU32(ctx, 5) & 0x3fffu, psm = getRegU32(ctx, 7) & 0x3fu; - const uint32_t width = getRegU32(ctx, 10) & 0xffffu, height = getRegU32(ctx, 11) & 0xffffu; - const uint32_t n = s.resOrdinal++; - const Record *r = nth(s, s.resFiles, n); - if (r && r->psm == psm && r->width == width && r->height == height) - { - if (isH(psm)) // T8H / T4HL / T4HH share their blocks' words (top byte, its low / high nibble) - s.hAt[(static_cast(block) << 8) | psm] = r; - else - s.byBlock[block] = {r, getRegU32(ctx, 8) & 0x7ffu, getRegU32(ctx, 9) & 0x7ffu}; - } - else - mismatch("resident record", n, r, psm, width, height); - } - } - bozo::port::callLibrary(runtime, ctx, kSceGsSetDefLoadImage); // the library (BozoEngine's), not the game's copy - } - - void fontInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) - { - { - Store &s = store(); - std::lock_guard lock(s.mutex); - loadPack(s); - s.fontTbp = static_cast((static_cast(getRegU32(ctx, 4)) - 0x840) / 64); - } - fontInit__F10_vramAddrs_0x1c3e48(rdram, ctx, runtime); - } - - // A record's entry as RGBA with the GS's alpha (0x80 is 1.0), as bozo::render::TextureCache gives it. - uint32_t colour(const Record &r, uint32_t index, uint64_t texa) - { - return bozo::render::packs::recordColour(r, index, texa); - } - } - - // TBP -> texture id, from the game's table as it left it after building the frame the adapter reads (called at - // each chain the adapter reads, before its draws). - void refresh(const uint8_t *rdram) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - if (rdram) - s.rdram = rdram; - if (!s.rdram) - return; - std::fill(s.idAt.begin(), s.idAt.end(), uint16_t{0xffff}); - const uint8_t *table = s.rdram + kTexInfo; - for (uint32_t id = 0; id < 1000u; ++id) - { - uint32_t info; - std::memcpy(&info, table + id * 16u + 4u, 4); - if ((info >> 31) != 0u) - s.idAt[info & 0x3fffu] = static_cast(id); - } - } - - namespace - { - // The texture TEX0 shows, its texels found by the TBP (texInfo) or, with id set, by that texture id (the - // number a hierobject keeps at +0x50, texmSetupTexture's id); the palette by CBP either way. - std::shared_ptr lookupLocked(Store &s, uint64_t tex0, uint64_t texa, uint32_t id) - { - const uint32_t tbp = tex0 & 0x3fffu, psm = (tex0 >> 20) & 0x3fu; - const uint32_t cbp = (tex0 >> 37) & 0x3fffu, csa = (tex0 >> 56) & 0x1fu; - const uint32_t width = 1u << std::min(10u, (tex0 >> 26) & 0xfu); - const uint32_t height = 1u << std::min(10u, (tex0 >> 30) & 0xfu); - - const Record *texels = nullptr, *palette = nullptr; - const std::vector *font = s.pack.file("FONT"); - const Record *fontPalette = font && font->size() > 1u ? &(*font)[1] : nullptr; - if (tbp == s.fontTbp && font) - { - texels = &(*font)[0]; - palette = fontPalette; - } - else if (isH(psm)) - { - const auto it = s.hAt.find((static_cast(tbp) << 8) | psm); - texels = it != s.hAt.end() ? it->second : nullptr; - } - else if (id != ~0u) - { - const auto it = s.byId.find(id); - texels = it != s.byId.end() && it->second->psm == psm ? it->second : nullptr; - } - else if (s.idAt[tbp] != 0xffffu) - { - const auto it = s.byId.find(s.idAt[tbp]); - texels = it != s.byId.end() && it->second->psm == psm ? it->second : nullptr; - } - // A palette entry at (px, py) of the CLUT area at CBP (CSM1, CT32 / CT16 blocks of 8 x 8, the second column of - // blocks at block + 1, the second row at + 2): from the record loaded over it. - const auto paletteEntry = [&](uint32_t px, uint32_t py, uint32_t &out) - { - for (int pass = 0; pass < 2; ++pass) - { - const uint32_t block = pass == 0 ? cbp : cbp + (px >> 3) + ((py >> 3) << 1); - const uint32_t lx = pass == 0 ? px : (px & 7u), ly = pass == 0 ? py : (py & 7u); - const auto it = s.byBlock.find(block); - if (it == s.byBlock.end() || !it->second.record) - continue; - const Store::Placement &p = it->second; - if (lx >= p.x && ly >= p.y && lx - p.x < p.record->width && ly - p.y < p.record->height) - { - out = colour(*p.record, (ly - p.y) * p.record->width + (lx - p.x), texa); - return true; - } - } - return false; - }; - bool paletteFound = palette != nullptr; - if (texels && indexed(psm) && !palette) - { - uint32_t ignored; - for (uint32_t i = 0; i < 16u && !paletteFound; ++i) - { - uint32_t px = 0, py = 0; - bozo::render::csm1Position(bozo::render::packs::psmEightBit(psm) ? i : (csa * 16u + i) & 0xffu, px, py); - paletteFound = paletteEntry(px, py, ignored); - } - if (const auto it = s.byBlock.find(cbp); it != s.byBlock.end()) - palette = it->second.record; - } - if (!texels || (indexed(psm) && !paletteFound)) - { - static std::unordered_map s_reported; - const uint64_t reportKey = tex0 & ~(uint64_t{7} << 61); - if (!s_reported[reportKey]) - { - s_reported[reportKey] = true; - std::fprintf(stderr, "[tmb:tex] TEX0 %#llx (tbp %u psm %#x %ux%u cbp %u): no %s set up there\n", - static_cast(tex0), tbp, psm, width, height, cbp, texels ? "palette" : "texture"); - } - return nullptr; - } - - const uint64_t key = (reinterpret_cast(texels) * 0x9e3779b97f4a7c15ull) ^ - (reinterpret_cast(palette) * 0xc2b2ae3d27d4eb4full) ^ - (tex0 & ~((uint64_t{3} << 35) | (uint64_t{7} << 61))) ^ (texa * 0x165667b19e3779f9ull); - if (const auto found = s.decoded.find(key); found != s.decoded.end()) - return found->second; - - uint32_t colours[256] = {}; - if (indexed(psm)) - bozo::render::packs::csm1Palette(psm, csa, - [&](uint32_t px, uint32_t py, uint32_t &out) - { - if (palette && palette == fontPalette) - { - if (px < palette->width && py < palette->height) - out = colour(*palette, py * palette->width + px, texa); - } - else - paletteEntry(px, py, out); - }, - colours); - - Texture texture; - texture.key = key; - texture.version = ++s.decodes; - bozo::render::packs::decodeRecord(texture, width, height, psm, *texels, colours, texa); - // A texture with no texel showing: reported once (a palette or texels taken from the wrong record). - if (std::all_of(texture.rgba.begin(), texture.rgba.end(), [](uint32_t c) { return (c >> 24) == 0u; })) - { - static std::unordered_map s_reported; - if (!s_reported[tex0]) - { - s_reported[tex0] = true; - std::fprintf(stderr, "[tmb:tex] TEX0 %#llx (tbp %u psm %#x %ux%u cbp %u csa %u): every texel transparent (texels %ux%u psm %#x, palette %ux%u psm %#x)\n", - static_cast(tex0), tbp, psm, width, height, cbp, csa, texels->width, texels->height, - texels->psm, palette ? palette->width : 0u, palette ? palette->height : 0u, palette ? palette->psm : 0u); - } - } - if (s.dump) - tmb::textures::dump::note(texture, {tbp == s.fontTbp && font ? std::string("FONT#0") : originOf(s, texels), - indexed(psm) ? (palette == fontPalette && palette ? std::string("FONT#1") : originOf(s, palette)) : std::string(), - psm, tex0, texa, texelHash(*texels)}); - auto shared = std::make_shared(std::move(texture)); - s.decoded[key] = shared; - return shared; - } - } - - // The texture a draw's TEX0 shows (null when the game set up none there: reported once). - std::shared_ptr lookup(uint64_t tex0, uint64_t texa) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - return lookupLocked(s, tex0, texa, ~0u); - } - - // The same with the texels taken by texture id (a hierobject's texture number, +0x50), not from the TBP. - std::shared_ptr lookupId(uint32_t id, uint64_t tex0, uint64_t texa) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - return lookupLocked(s, tex0, texa, id); - } - - // The texture id texInfo gives the TBP now (0xffff: none), to check a lookup by id against it. - uint32_t idAtTbp(uint32_t tbp) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - return s.idAt[tbp & 0x3fffu]; - } - - // The disc file fileReadf / zipInflateAll last read to this address ("" if none): the mesh pack's NGP binding. - std::string nameAt(uint32_t address) - { - Store &s = store(); - std::lock_guard lock(s.mutex); - const auto it = s.nameAt.find(address); - return it != s.nameAt.end() ? it->second : std::string(); - } - - // The font's texture (the pack's FONT, at the VRAM block fontInit gave it), for the 2D rewritten natively. - std::shared_ptr font() - { - Store &s = store(); - std::lock_guard lock(s.mutex); - loadPack(s); - static std::shared_ptr s_font; - const std::vector *records = s.pack.file("FONT"); - if (s_font || !records || records->size() < 2u) - return s_font; - const Record &texels = (*records)[0], &palette = (*records)[1]; - Texture texture; - texture.width = texels.width; - texture.height = texels.height; - texture.key = 0xf0f7f0f7u; - texture.version = ++s.decodes; - texture.rgba.resize(static_cast(texels.width) * texels.height); - for (size_t i = 0; i < texture.rgba.size(); ++i) - { - uint32_t px = 0, py = 0; - bozo::render::csm1Position(texels.texels[i] & 0xfu, px, py); - texture.rgba[i] = px < palette.width && py < palette.height ? colour(palette, py * palette.width + px, 0u) : 0u; - } - if (s.dump) - tmb::textures::dump::note(texture, {"FONT#0", "FONT#1", texels.psm, 0u, 0u, texelHash(texels)}); - s_font = std::make_shared(std::move(texture)); - return s_font; - } - - void install(tmb::Registry &runtime) - { - runtime.registerFunction(kFileReadf, &fileReadfOverride); - runtime.registerFunction(kZipInflateAll, &zipInflateAllOverride); - runtime.registerFunction(kFileOnlyTexFile, &fileOnlyTexFileOverride); - runtime.registerFunction(kFileAddTexFile, &fileAddTexFileOverride); - runtime.registerFunction(kFileOnlyResFile, &fileOnlyResFileOverride); - runtime.registerFunction(kFileAddResFile, &fileAddResFileOverride); - runtime.registerFunction(kTexmInit, &texmInitOverride); - runtime.registerFunction(kTexmSetupTexture, &texmSetupTextureOverride); - runtime.registerFunction(kTexmResInit, &texmResInitOverride); - runtime.registerFunction(kTexmLoadResTexture, &texmLoadResTextureOverride); - runtime.registerFunction(kSceGsSetDefLoadImage, &sceGsSetDefLoadImageOverride); - runtime.registerFunction(kFontInit, &fontInitOverride); - } -} +// TMB's textures for the native renderer, from the native texture pack converted offline from the disc's files +// (tools/tmb_texture_pack.py, scripts/recomp.sh): nothing is read from the game's texture records, GS packets or GS +// memory while the game runs. The runtime only follows TMB's texture code, at hooks: +// - which disc file goes where: fileReadf / zipInflateAll (name, destination), then fileOnlyTexFile / +// fileAddTexFile / fileOnlyResFile / fileAddResFile (destination) list the level's .TEX and .RTX files in order; +// - texmInit sets up each .TEX record in order (texmSetupTexture: its texture id, width, height, format): the n-th +// setup is the pack's n-th record of those files, so a texture id names a pack record; +// - texmLoadResTexture loads each .RTX record in order (sceGsSetDefLoadImage: its VRAM block, format, size): a palette's or +// an H texture's VRAM block names a pack record; +// - fontInit: the font's VRAM blocks (the pack's FONT file). +// A draw's TEX0 then finds its texture: TBP0 -> the texture id the game's own table (texInfo: TBP | ... | resident +// << 31 per id, word 1 of 4) has there, CBP -> the palette loaded at that block. +// +// Each hook checks the pack record against the game's own arguments (format, size) and reports a mismatch. +// +// The pack's container, its loader and the decoders (PSM, CSM1 palettes, TEXA alpha) are the fork's +// (runtime/native/native_texture_pack.h, tools/native_pack/texture.py); what is TMB's here is the key scheme above. + +#include "bozo/state.h" +#include "tmb_port.h" +#include "bozo/render/texture.h" +#include "bozo/render/texture_pack.h" +#include "tmb_meshes.h" +#include "tmb_texture_dump.h" +#include "bozo/hash.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef TMB_TEXTURE_PACK +#define TMB_TEXTURE_PACK "tmb_textures.pack" +#endif + +namespace tmb::textures +{ + namespace + { + using Texture = bozo::render::Texture; + + constexpr uint32_t kTexInfo = 0x004D1930u; // texInfo[1000], 16 bytes each + constexpr uint32_t kFileReadf = 0x001C21D0u; + constexpr uint32_t kZipInflateAll = 0x00200A20u; + constexpr uint32_t kFileOnlyTexFile = 0x001C2B60u; + constexpr uint32_t kFileAddTexFile = 0x001C2940u; + constexpr uint32_t kFileOnlyResFile = 0x001C2BA8u; + constexpr uint32_t kFileAddResFile = 0x001C29D8u; + constexpr uint32_t kTexmInit = 0x001F8868u; + constexpr uint32_t kTexmSetupTexture = 0x001F8F60u; + constexpr uint32_t kTexmResInit = 0x001F88F8u; + constexpr uint32_t kSceGsSetDefLoadImage = 0x00203F30u; + constexpr uint32_t kTexmLoadResTexture = 0x001F89B8u; + constexpr uint32_t kResLoadReturn = 0x001F8AB4u; // texmLoadResTexture's call of sceGsSetDefLoadImage + constexpr uint32_t kFontInit = 0x001C3E48u; + + using bozo::render::packs::psmIndexed; + using bozo::render::packs::psmIsH; + using Record = bozo::render::packs::TextureRecord; + bool isH(uint32_t psm) { return psmIsH(psm); } + bool indexed(uint32_t psm) { return psmIndexed(psm); } + + struct Store + { + std::mutex mutex; + bool loaded = false; + bozo::render::packs::TexturePack pack; // file name -> its records in order + std::unordered_map nameAt; // destination -> the disc file read there + std::vector texFiles, resFiles; // the level's, in the game's order + uint32_t texOrdinal = 0, resOrdinal = 0; + std::unordered_map byId; // texture id -> .TEX record + // VRAM block -> the .RTX record loaded there, and where in the block (its first texel, as loaded) + struct Placement + { + const Record *record = nullptr; + uint32_t x = 0, y = 0; + }; + std::unordered_map byBlock; // palettes + std::unordered_map hAt; // (block << 8 | psm) -> H texture + std::vector idAt = std::vector(16384u, 0xffffu); // TBP -> texture id (texInfo, refresh) + uint32_t fontTbp = ~0u; + std::unordered_map> decoded; + uint64_t decodes = 0; + const uint8_t *rdram = nullptr; + bool dump = false; // TMB_TEXTURE_DUMP (tmb_texture_dump.h): the records' origins kept for its index + std::unordered_map origin; // record -> "FILE#n" + }; + Store &store() + { + static Store s_store; + return s_store; + } + + void loadPack(Store &s) + { + if (s.loaded) + return; + s.loaded = true; + const std::string pathText = tmb::meshes::packPath("TMB_TEXTURE_PACK", TMB_TEXTURE_PACK); + const char *path = pathText.c_str(); + s.dump = tmb::textures::dump::enabled(); + if (!s.pack.load(path)) + { + std::fprintf(stderr, "[tmb:tex] no texture pack at %s (tools/tmb_texture_pack.py): the native draws are untextured\n", path); + return; + } + std::fprintf(stderr, "[tmb:tex] texture pack %s: %zu files, %zu records\n", path, s.pack.fileCount(), s.pack.recordCount()); + } + + // "cdrom0:\LVL\JUNKYARD.TEX;1" -> "JUNKYARD.TEX" + std::string baseName(const uint8_t *rdram, uint32_t address) + { + std::string name; + for (uint32_t i = 0; i < 256u; ++i) + { + const char c = static_cast(rdram[(address + i) & 0x1ffffffu]); + if (c == '\0' || c == ';') + break; + if (c == '\\' || c == '/' || c == ':') + name.clear(); + else + name.push_back(static_cast(c >= 'a' && c <= 'z' ? c - 32 : c)); + } + return name; + } + + // The n-th record of the listed files. + const Record *nth(Store &s, const std::vector &files, uint32_t n) + { + const Record *r = s.pack.nth(files, n); + if (r && s.dump && !s.origin.count(r)) // which file and which of its records, for the dump's index + { + uint32_t left = n; + for (const std::string &name : files) + { + const std::vector *records = s.pack.file(name); + if (!records) + break; + if (left < records->size()) + { + s.origin[r] = name + "#" + std::to_string(left); + break; + } + left -= static_cast(records->size()); + } + } + return r; + } + + std::string originOf(const Store &s, const Record *r) + { + if (!r) + return std::string(); + const auto it = s.origin.find(r); + return it != s.origin.end() ? it->second : std::string("?"); + } + + uint64_t texelHash(const Record &r) + { + const uint32_t seed[3] = {r.psm, r.width, r.height}; + return bozo::hash::xxh64(r.texels.data(), r.texels.size(), bozo::hash::xxh64(seed, sizeof(seed), 0)); + } + + void mismatch(const char *what, uint32_t n, const Record *r, uint32_t psm, uint32_t width, uint32_t height) + { + static uint32_t s_reported = 0; + if (s_reported++ < 20u) + std::fprintf(stderr, "[tmb:tex] %s #%u: the game sets up psm %#x %ux%u, the pack has %s\n", what, n, psm, width, + height, r ? (std::to_string(r->psm) + " " + std::to_string(r->width) + "x" + std::to_string(r->height)).c_str() : "nothing"); + } + + void noteFile(uint8_t *rdram, R5900Context *ctx) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + s.rdram = rdram; + s.nameAt[getRegU32(ctx, 5)] = baseName(rdram, getRegU32(ctx, 4)); + } + void fileReadfOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + noteFile(rdram, ctx); + fileReadf__FPcPv_0x1c21d0(rdram, ctx, runtime); + } + void zipInflateAllOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + noteFile(rdram, ctx); + zipInflateAll__FPcPv_0x200a20(rdram, ctx, runtime); + } + + void listFile(R5900Context *ctx, bool tex, bool only) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + std::vector &files = tex ? s.texFiles : s.resFiles; + if (only) + files.clear(); + // A new list of .TEX files: its records are set up from the first. The shell sets up its textures without + // texmInit (back from a match the count would go on from the level's, past the shell's records). + if (only && tex) + { + s.texOrdinal = 0; + s.byId.clear(); + s.decoded.clear(); + } + const auto it = s.nameAt.find(getRegU32(ctx, 4)); + files.push_back(it != s.nameAt.end() ? it->second : std::string("?")); + } + void fileOnlyTexFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + listFile(ctx, true, true); + fileOnlyTexFile__FPci_0x1c2b60(rdram, ctx, runtime); + } + void fileAddTexFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + listFile(ctx, true, false); + fileAddTexFile__FPci_0x1c2940(rdram, ctx, runtime); + } + void fileOnlyResFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + listFile(ctx, false, true); + fileOnlyResFile__FPci_0x1c2ba8(rdram, ctx, runtime); + } + void fileAddResFileOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + listFile(ctx, false, false); + fileAddResFile__FPci_0x1c29d8(rdram, ctx, runtime); + } + + void texmInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + s.rdram = rdram; + s.texOrdinal = 0; + s.byId.clear(); + s.decoded.clear(); + } + texmInit__F10_vramAddrs_0x1f8868(rdram, ctx, runtime); + Store &s = store(); + std::lock_guard lock(s.mutex); + std::string files; + for (const std::string &f : s.texFiles) + files += " " + f; + std::fprintf(stderr, "[tmb:tex] texmInit: %u textures set up from%s\n", s.texOrdinal, files.c_str()); + } + + // texmSetupTexture(id, width, height, psm, ...): once per .TEX record, in order. + void texmSetupTextureOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + const uint32_t id = getRegU32(ctx, 4) & 0xffffu, width = getRegU32(ctx, 5), height = getRegU32(ctx, 6), + psm = getRegU32(ctx, 7) & 0x3fu; + const uint32_t n = s.texOrdinal++; + const Record *r = nth(s, s.texFiles, n); + if (n == 0u) + std::fprintf(stderr, "[tmb:tex] texmSetupTexture: the first of %zu files (id %u, psm %#x %ux%u)\n", s.texFiles.size(), id, psm, + width, height); + if (r && r->psm == psm && r->width == width && r->height == height) + s.byId[id] = r; + else + mismatch("texture", n, r, psm, width, height); + } + texmSetupTexture__FiiiiiP6QwDataii_0x1f8f60(rdram, ctx, runtime); + } + + void texmResInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + s.rdram = rdram; + s.resOrdinal = 0; + s.byBlock.clear(); + s.hAt.clear(); + s.decoded.clear(); + } + texmResInit__F10_vramAddrsP6QwData_0x1f88f8(rdram, ctx, runtime); + Store &s = store(); + std::lock_guard lock(s.mutex); + std::string files; + for (const std::string &f : s.resFiles) + files += " " + f; + std::fprintf(stderr, "[tmb:tex] texmResInit: %u palettes and resident textures loaded from%s\n", s.resOrdinal, files.c_str()); + } + + // The shell calls it itself when texmResInit's check (texmResCheckForData) found nothing to load yet; texmResInit + // tail-jumps into it (a direct call: its records are counted from texmResInit's override). + void texmLoadResTextureOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + s.rdram = rdram; + s.resOrdinal = 0; + s.byBlock.clear(); + s.hAt.clear(); + s.decoded.clear(); + } + texmLoadResTexture__FP6QwData_0x1f89b8(rdram, ctx, runtime); + Store &s = store(); + std::lock_guard lock(s.mutex); + std::fprintf(stderr, "[tmb:tex] texmLoadResTexture: %u palettes and resident textures loaded\n", s.resOrdinal); + } + + // sceGsSetDefLoadImage(image, dbp, dbw, dpsm, x, y, w, h), called by texmLoadResTexture (its return address) + // once per .RTX record, in order. + void sceGsSetDefLoadImageOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + if (getRegU32(ctx, 31) == kResLoadReturn) + { + const uint32_t block = getRegU32(ctx, 5) & 0x3fffu, psm = getRegU32(ctx, 7) & 0x3fu; + const uint32_t width = getRegU32(ctx, 10) & 0xffffu, height = getRegU32(ctx, 11) & 0xffffu; + const uint32_t n = s.resOrdinal++; + const Record *r = nth(s, s.resFiles, n); + if (r && r->psm == psm && r->width == width && r->height == height) + { + if (isH(psm)) // T8H / T4HL / T4HH share their blocks' words (top byte, its low / high nibble) + s.hAt[(static_cast(block) << 8) | psm] = r; + else + s.byBlock[block] = {r, getRegU32(ctx, 8) & 0x7ffu, getRegU32(ctx, 9) & 0x7ffu}; + } + else + mismatch("resident record", n, r, psm, width, height); + } + } + bozo::port::callLibrary(runtime, ctx, kSceGsSetDefLoadImage); // the library (BozoEngine's), not the game's copy + } + + void fontInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) + { + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + s.fontTbp = static_cast((static_cast(getRegU32(ctx, 4)) - 0x840) / 64); + } + fontInit__F10_vramAddrs_0x1c3e48(rdram, ctx, runtime); + } + + // A record's entry as RGBA with the GS's alpha (0x80 is 1.0), as bozo::render::TextureCache gives it. + uint32_t colour(const Record &r, uint32_t index, uint64_t texa) + { + return bozo::render::packs::recordColour(r, index, texa); + } + } + + // TBP -> texture id, from the game's table as it left it after building the frame the adapter reads (called at + // each chain the adapter reads, before its draws). + void refresh(const uint8_t *rdram) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + if (rdram) + s.rdram = rdram; + if (!s.rdram) + return; + std::fill(s.idAt.begin(), s.idAt.end(), uint16_t{0xffff}); + const uint8_t *table = s.rdram + kTexInfo; + for (uint32_t id = 0; id < 1000u; ++id) + { + uint32_t info; + std::memcpy(&info, table + id * 16u + 4u, 4); + if ((info >> 31) != 0u) + s.idAt[info & 0x3fffu] = static_cast(id); + } + } + + namespace + { + // The texture TEX0 shows, its texels found by the TBP (texInfo) or, with id set, by that texture id (the + // number a hierobject keeps at +0x50, texmSetupTexture's id); the palette by CBP either way. + std::shared_ptr lookupLocked(Store &s, uint64_t tex0, uint64_t texa, uint32_t id) + { + const uint32_t tbp = tex0 & 0x3fffu, psm = (tex0 >> 20) & 0x3fu; + const uint32_t cbp = (tex0 >> 37) & 0x3fffu, csa = (tex0 >> 56) & 0x1fu; + const uint32_t width = 1u << std::min(10u, (tex0 >> 26) & 0xfu); + const uint32_t height = 1u << std::min(10u, (tex0 >> 30) & 0xfu); + + const Record *texels = nullptr, *palette = nullptr; + const std::vector *font = s.pack.file("FONT"); + const Record *fontPalette = font && font->size() > 1u ? &(*font)[1] : nullptr; + if (tbp == s.fontTbp && font) + { + texels = &(*font)[0]; + palette = fontPalette; + } + else if (isH(psm)) + { + const auto it = s.hAt.find((static_cast(tbp) << 8) | psm); + texels = it != s.hAt.end() ? it->second : nullptr; + } + else if (id != ~0u) + { + const auto it = s.byId.find(id); + texels = it != s.byId.end() && it->second->psm == psm ? it->second : nullptr; + } + else if (s.idAt[tbp] != 0xffffu) + { + const auto it = s.byId.find(s.idAt[tbp]); + texels = it != s.byId.end() && it->second->psm == psm ? it->second : nullptr; + } + // A palette entry at (px, py) of the CLUT area at CBP (CSM1, CT32 / CT16 blocks of 8 x 8, the second column of + // blocks at block + 1, the second row at + 2): from the record loaded over it. + const auto paletteEntry = [&](uint32_t px, uint32_t py, uint32_t &out) + { + for (int pass = 0; pass < 2; ++pass) + { + const uint32_t block = pass == 0 ? cbp : cbp + (px >> 3) + ((py >> 3) << 1); + const uint32_t lx = pass == 0 ? px : (px & 7u), ly = pass == 0 ? py : (py & 7u); + const auto it = s.byBlock.find(block); + if (it == s.byBlock.end() || !it->second.record) + continue; + const Store::Placement &p = it->second; + if (lx >= p.x && ly >= p.y && lx - p.x < p.record->width && ly - p.y < p.record->height) + { + out = colour(*p.record, (ly - p.y) * p.record->width + (lx - p.x), texa); + return true; + } + } + return false; + }; + bool paletteFound = palette != nullptr; + if (texels && indexed(psm) && !palette) + { + uint32_t ignored; + for (uint32_t i = 0; i < 16u && !paletteFound; ++i) + { + uint32_t px = 0, py = 0; + bozo::render::csm1Position(bozo::render::packs::psmEightBit(psm) ? i : (csa * 16u + i) & 0xffu, px, py); + paletteFound = paletteEntry(px, py, ignored); + } + if (const auto it = s.byBlock.find(cbp); it != s.byBlock.end()) + palette = it->second.record; + } + if (!texels || (indexed(psm) && !paletteFound)) + { + static std::unordered_map s_reported; + const uint64_t reportKey = tex0 & ~(uint64_t{7} << 61); + if (!s_reported[reportKey]) + { + s_reported[reportKey] = true; + std::fprintf(stderr, "[tmb:tex] TEX0 %#llx (tbp %u psm %#x %ux%u cbp %u): no %s set up there\n", + static_cast(tex0), tbp, psm, width, height, cbp, texels ? "palette" : "texture"); + } + return nullptr; + } + + const uint64_t key = (reinterpret_cast(texels) * 0x9e3779b97f4a7c15ull) ^ + (reinterpret_cast(palette) * 0xc2b2ae3d27d4eb4full) ^ + (tex0 & ~((uint64_t{3} << 35) | (uint64_t{7} << 61))) ^ (texa * 0x165667b19e3779f9ull); + if (const auto found = s.decoded.find(key); found != s.decoded.end()) + return found->second; + + uint32_t colours[256] = {}; + if (indexed(psm)) + bozo::render::packs::csm1Palette(psm, csa, + [&](uint32_t px, uint32_t py, uint32_t &out) + { + if (palette && palette == fontPalette) + { + if (px < palette->width && py < palette->height) + out = colour(*palette, py * palette->width + px, texa); + } + else + paletteEntry(px, py, out); + }, + colours); + + Texture texture; + texture.key = key; + texture.version = ++s.decodes; + bozo::render::packs::decodeRecord(texture, width, height, psm, *texels, colours, texa); + // A texture with no texel showing: reported once (a palette or texels taken from the wrong record). + if (std::all_of(texture.rgba.begin(), texture.rgba.end(), [](uint32_t c) { return (c >> 24) == 0u; })) + { + static std::unordered_map s_reported; + if (!s_reported[tex0]) + { + s_reported[tex0] = true; + std::fprintf(stderr, "[tmb:tex] TEX0 %#llx (tbp %u psm %#x %ux%u cbp %u csa %u): every texel transparent (texels %ux%u psm %#x, palette %ux%u psm %#x)\n", + static_cast(tex0), tbp, psm, width, height, cbp, csa, texels->width, texels->height, + texels->psm, palette ? palette->width : 0u, palette ? palette->height : 0u, palette ? palette->psm : 0u); + } + } + if (s.dump) + tmb::textures::dump::note(texture, {tbp == s.fontTbp && font ? std::string("FONT#0") : originOf(s, texels), + indexed(psm) ? (palette == fontPalette && palette ? std::string("FONT#1") : originOf(s, palette)) : std::string(), + psm, tex0, texa, texelHash(*texels)}); + auto shared = std::make_shared(std::move(texture)); + s.decoded[key] = shared; + return shared; + } + } + + // The texture a draw's TEX0 shows (null when the game set up none there: reported once). + std::shared_ptr lookup(uint64_t tex0, uint64_t texa) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + return lookupLocked(s, tex0, texa, ~0u); + } + + // The same with the texels taken by texture id (a hierobject's texture number, +0x50), not from the TBP. + std::shared_ptr lookupId(uint32_t id, uint64_t tex0, uint64_t texa) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + return lookupLocked(s, tex0, texa, id); + } + + // The texture id texInfo gives the TBP now (0xffff: none), to check a lookup by id against it. + uint32_t idAtTbp(uint32_t tbp) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + return s.idAt[tbp & 0x3fffu]; + } + + // The disc file fileReadf / zipInflateAll last read to this address ("" if none): the mesh pack's NGP binding. + std::string nameAt(uint32_t address) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + const auto it = s.nameAt.find(address); + return it != s.nameAt.end() ? it->second : std::string(); + } + + // The font's texture (the pack's FONT, at the VRAM block fontInit gave it), for the 2D rewritten natively. + std::shared_ptr font() + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + static std::shared_ptr s_font; + const std::vector *records = s.pack.file("FONT"); + if (s_font || !records || records->size() < 2u) + return s_font; + const Record &texels = (*records)[0], &palette = (*records)[1]; + Texture texture; + texture.width = texels.width; + texture.height = texels.height; + texture.key = 0xf0f7f0f7u; + texture.version = ++s.decodes; + texture.rgba.resize(static_cast(texels.width) * texels.height); + for (size_t i = 0; i < texture.rgba.size(); ++i) + { + uint32_t px = 0, py = 0; + bozo::render::csm1Position(texels.texels[i] & 0xfu, px, py); + texture.rgba[i] = px < palette.width && py < palette.height ? colour(palette, py * palette.width + px, 0u) : 0u; + } + if (s.dump) + tmb::textures::dump::note(texture, {"FONT#0", "FONT#1", texels.psm, 0u, 0u, texelHash(texels)}); + s_font = std::make_shared(std::move(texture)); + return s_font; + } + + void install(tmb::Registry &runtime) + { + runtime.registerFunction(kFileReadf, &fileReadfOverride); + runtime.registerFunction(kZipInflateAll, &zipInflateAllOverride); + runtime.registerFunction(kFileOnlyTexFile, &fileOnlyTexFileOverride); + runtime.registerFunction(kFileAddTexFile, &fileAddTexFileOverride); + runtime.registerFunction(kFileOnlyResFile, &fileOnlyResFileOverride); + runtime.registerFunction(kFileAddResFile, &fileAddResFileOverride); + runtime.registerFunction(kTexmInit, &texmInitOverride); + runtime.registerFunction(kTexmSetupTexture, &texmSetupTextureOverride); + runtime.registerFunction(kTexmResInit, &texmResInitOverride); + runtime.registerFunction(kTexmLoadResTexture, &texmLoadResTextureOverride); + runtime.registerFunction(kSceGsSetDefLoadImage, &sceGsSetDefLoadImageOverride); + runtime.registerFunction(kFontInit, &fontInitOverride); + } + // Save states (tmb_state.cpp): what the game told the hooks once (the disc file read at each address, the level's + // file lists and set-up order, the records placed in VRAM), with the pack's records as (file, index). Decoded + // pictures are dropped on a load. + void state(bozo::state::Archive &a) + { + Store &s = store(); + std::lock_guard lock(s.mutex); + loadPack(s); + // Every file name the game read or listed: a record is found in one of them. + std::vector names = s.texFiles; + names.insert(names.end(), s.resFiles.begin(), s.resFiles.end()); + names.push_back("FONT"); + auto ioRecord = [&](const Record *&r, const std::vector &where) + { + std::string file; + int64_t index = -1; + if (!a.loading() && r) + { + for (const std::string &name : where) + if (const std::vector *records = s.pack.file(name); + records && !records->empty() && r >= records->data() && r < records->data() + records->size()) + { + file = name; + index = r - records->data(); + break; + } + if (index < 0) + throw bozo::state::Error("save state: a texture record outside the files the game read"); + } + bozo::state::fields(a, file, index); + if (a.loading()) + { + const std::vector *records = index < 0 ? nullptr : s.pack.file(file); + if (index >= 0 && (!records || static_cast(index) >= records->size())) + throw bozo::state::Error("save state: a texture record the pack does not have"); + r = index < 0 ? nullptr : &(*records)[static_cast(index)]; + } + }; + bozo::state::fields(a, s.nameAt, s.texFiles, s.resFiles, s.texOrdinal, s.resOrdinal, s.idAt, s.fontTbp); + if (a.loading()) + { + names = s.texFiles; + names.insert(names.end(), s.resFiles.begin(), s.resFiles.end()); + names.push_back("FONT"); + for (const auto &[at, name] : s.nameAt) + names.push_back(name); + } + else + for (const auto &[at, name] : s.nameAt) + names.push_back(name); + uint64_t n = bozo::state::count(a, s.byId.size()); + if (!a.loading()) + for (auto &[id, r] : s.byId) + { + uint32_t key = id; + bozo::state::io(a, key); + ioRecord(r, names); + } + else + { + s.byId.clear(); + for (uint64_t i = 0; i < n; ++i) + { + uint32_t key = 0; + const Record *r = nullptr; + bozo::state::io(a, key); + ioRecord(r, names); + s.byId[key] = r; + } + } + n = bozo::state::count(a, s.byBlock.size()); + if (!a.loading()) + for (auto &[block, p] : s.byBlock) + { + uint32_t key = block; + bozo::state::fields(a, key, p.x, p.y); + ioRecord(p.record, names); + } + else + { + s.byBlock.clear(); + for (uint64_t i = 0; i < n; ++i) + { + uint32_t key = 0; + Store::Placement p; + bozo::state::fields(a, key, p.x, p.y); + ioRecord(p.record, names); + s.byBlock[key] = p; + } + } + n = bozo::state::count(a, s.hAt.size()); + if (!a.loading()) + for (auto &[key, r] : s.hAt) + { + uint64_t k = key; + bozo::state::io(a, k); + ioRecord(r, names); + } + else + { + s.hAt.clear(); + for (uint64_t i = 0; i < n; ++i) + { + uint64_t k = 0; + const Record *r = nullptr; + bozo::state::io(a, k); + ioRecord(r, names); + s.hAt[k] = r; + } + } + if (a.loading()) + { + s.decoded.clear(); + s.origin.clear(); + } + } +}