PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
web: run the GS on the page thread and the emulation in a worker
Samir Nuri1785aaf6aada
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 319e5e3..093623e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -7,8 +7,8 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)set(PS2_GENERATED "" CACHE PATH "Folder with the C++ generated for a game")if(EMSCRIPTEN)- add_compile_options(-msimd128 -mtail-call -fwasm-exceptions)- add_link_options(-msimd128 -mtail-call -fwasm-exceptions)+ add_compile_options(-msimd128 -mtail-call -fwasm-exceptions -pthread)+ add_link_options(-msimd128 -mtail-call -fwasm-exceptions -pthread)endif()if(NOT EMSCRIPTEN)@@ -39,6 +39,7 @@ add_library(ps2runtime STATICruntime/src/ipu/ipu.cppruntime/src/gs/gs.cppruntime/src/gs/gif.cpp+ runtime/src/gs/queue.cppruntime/src/gs/raster.cppruntime/src/iop/cpu.cppruntime/src/iop/kernel.cpp@@ -85,8 +86,8 @@ if(PS2_GENERATED)set(PS2_WEB_ELF "" CACHE FILEPATH "Game executable preloaded as /game/core.elf")add_executable(ps2web host/web.cpp)target_link_libraries(ps2web PRIVATE ps2game ps2runtime)- target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=67108864 -sSTACK_SIZE=16777216 -sENVIRONMENT=web- -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives+ target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sPTHREAD_POOL_SIZE=1 -sSTACK_SIZE=16777216 -sENVIRONMENT=web+ -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms-sEXPORTED_RUNTIME_METHODS=callMain,addRunDependency,removeRunDependency,HEAPU8,ENV--shell-file ${CMAKE_SOURCE_DIR}/web/shell.html --preload-file ${PS2_WEB_ELF}@/game/core.elf)set_target_properties(ps2web PROPERTIES SUFFIX ".html" LINK_DEPENDS ${CMAKE_SOURCE_DIR}/web/shell.html)diff --git a/host/web.cpp b/host/web.cppindex 5d6790b..62f9fc0 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -2,8 +2,11 @@#include "ps2/system.hpp"#include <emscripten.h>+#include <pthread.h>+#include <unistd.h>#include <algorithm>+#include <atomic>#include <cstdio>#include <cstring>#include <list>@@ -14,25 +17,32 @@void register_generated_code();void register_generated_vu();-EM_ASYNC_JS(int, ps2web_fetch, (double offset, int size, void *out), {+EM_JS_DEPS(ps2web, "$stringToNewUTF8,$UTF8ToString");++EM_JS(int, ps2web_fetch, (const char *url, double offset, int size, void *out), {+ const target = UTF8ToString(url);for (let attempt = 0; attempt < 4; ++attempt) {try {- const response = await fetch(Module.discUrl, {headers: {Range: 'bytes=' + offset + '-' + (offset + size - 1)}});- if (response.status !== 206 && response.status !== 200) continue;- const bytes = new Uint8Array(await response.arrayBuffer());+ const xhr = new XMLHttpRequest();+ xhr.open('GET', target, false);+ xhr.responseType = 'arraybuffer';+ xhr.setRequestHeader('Range', 'bytes=' + offset + '-' + (offset + size - 1));+ xhr.send();+ if (xhr.status !== 206 && xhr.status !== 200) continue;+ let bytes = new Uint8Array(xhr.response);+ if (xhr.status === 200) bytes = bytes.subarray(offset, offset + size);const length = Math.min(bytes.length, size);HEAPU8.set(bytes.subarray(0, length), out);return length;} catch (e) {- console.warn('disc fetch failed', e);+ console.warn('disc read failed', e);}}return 0;});EM_JS(double, ps2web_disc_size, (), { return Module.discSize || 0; });-EM_JS(void, ps2web_audio, (const std::int16_t *samples, int frames), { Module.pushAudio(HEAP16.subarray(samples >> 1, (samples >> 1) + frames * 2)); });-EM_JS(double, ps2web_audio_queued_ms, (), { return Module.audioQueuedMs ? Module.audioQueuedMs() : 0; });+EM_JS(char *, ps2web_disc_url, (), { return stringToNewUTF8(new URL(Module.discUrl, location.href).href); });EM_JS(void, ps2web_frame_done, (), { if (Module.onFrame) Module.onFrame(); });EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {const canvas = Module.canvas;@@ -52,20 +62,25 @@ EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {ctx.drawImage(Module.blitSource, (canvas.width - w) / 2, (canvas.height - h) / 2, w, h);});-EM_JS(void, ps2web_snapshot, (const std::uint32_t *rgba, int width, int height), {- const pixels = new Uint8ClampedArray(HEAPU8.buffer, rgba, width * height * 4).slice();- Module.snapshot = {width: width, height: height, pixels: pixels};- Module.wantSnapshot = false;-});-namespace {constexpr std::size_t kChunk = 1u << 20;constexpr std::size_t kCacheChunks = 64;+constexpr std::uint32_t kAudioFrames = 1u << 14;++struct AudioRing {+ std::atomic<std::uint32_t> write{0}, read{0};+ std::uint32_t capacity = kAudioFrames;+ std::atomic<std::uint32_t> active{0};+ std::int16_t samples[kAudioFrames * 2];+};++AudioRing g_audio;std::unordered_map<std::uint64_t, std::list<std::pair<std::uint64_t, std::vector<std::uint8_t>>>::iterator> g_chunks;std::list<std::pair<std::uint64_t, std::vector<std::uint8_t>>> g_lru;std::uint64_t g_disc_size = 0;+char *g_disc_url = nullptr;const std::vector<std::uint8_t> *chunk(std::uint64_t index) {auto it = g_chunks.find(index);@@ -76,7 +91,7 @@ const std::vector<std::uint8_t> *chunk(std::uint64_t index) {const std::uint64_t offset = index * kChunk;const std::size_t size = static_cast<std::size_t>(std::min<std::uint64_t>(kChunk, g_disc_size - offset));std::vector<std::uint8_t> data(size);- if (ps2web_fetch(static_cast<double>(offset), static_cast<int>(size), data.data()) <= 0) return nullptr;+ if (ps2web_fetch(g_disc_url, static_cast<double>(offset), static_cast<int>(size), data.data()) <= 0) return nullptr;if (g_lru.size() >= kCacheChunks) {g_chunks.erase(g_lru.back().first);g_lru.pop_back();@@ -101,38 +116,57 @@ std::size_t read_disc(std::uint64_t offset, void *out, std::size_t size) {return done;}-bool g_window_tried = false, g_window = false, g_copy = false;-std::vector<std::uint32_t> g_frame;+void push_audio(const std::int16_t *samples, std::size_t frames) {+ std::uint32_t write = g_audio.write.load(std::memory_order_relaxed);+ const std::uint32_t read = g_audio.read.load(std::memory_order_acquire);+ for (std::size_t i = 0; i < frames && write - read < kAudioFrames; ++i, ++write) {+ const std::uint32_t at = (write & (kAudioFrames - 1)) * 2;+ g_audio.samples[at] = samples[i * 2];+ g_audio.samples[at + 1] = samples[i * 2 + 1];+ }+ g_audio.write.store(write, std::memory_order_release);+}-void on_vblank() {- if (!g_window_tried) {- g_window_tried = true;- const bool no_surface = EM_ASM_INT({ return Module.noSurface ? 1 : 0; });- g_copy = EM_ASM_INT({ return Module.presentCopy ? 1 : 0; });- if (!g_copy && !no_surface) {- ps2::WindowTarget target;- target.kind = ps2::WindowTarget::Canvas;- target.selector = "#canvas";- target.width = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.width; }));- target.height = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.height; }));- g_window = ps2::attach_window(target);- }- g_copy = g_copy || (!g_window && !no_surface);- std::fprintf(stderr, "[web] %s\n", g_window ? "presenting through WebGPU" : g_copy ? "presenting through a 2D canvas copy" : "not presenting");+double audio_queued_ms() { return static_cast<double>(g_audio.write.load() - g_audio.read.load()) / 48.0; }++double g_next_frame = 0.0;+std::atomic<double> g_emulation_idle{0.0}, g_render_idle{0.0};++void pace() {+ ps2::post_present();+ if (g_audio.active.load()) {+ while (audio_queued_ms() > 80.0) usleep(1000);+ g_next_frame = 0.0;+ return;}- if (g_window) ps2::present_frame();- std::uint32_t w = 0, h = 0;- if (g_copy && ps2::copy_frame(g_frame, w, h)) ps2web_blit(g_frame.data(), static_cast<int>(w), static_cast<int>(h));- if (EM_ASM_INT({ return Module.wantSnapshot ? 1 : 0; })) {- std::vector<std::uint32_t> rgba;- std::uint32_t w = 0, h = 0;- if (ps2::display_frame(rgba, w, h)) {- ps2web_snapshot(rgba.data(), static_cast<int>(w), static_cast<int>(h));- }+ const double period = ps2::g_options.pal ? 20.0 : 1000.0 / 59.94;+ const double now = emscripten_get_now();+ if (g_next_frame == 0.0 || now - g_next_frame > 200.0) g_next_frame = now;+ g_next_frame += period;+ if (g_next_frame > now) usleep(static_cast<useconds_t>((g_next_frame - now) * 1000.0));+}++void on_vblank() {+ const double start = emscripten_get_now();+ pace();+ g_emulation_idle.store(g_emulation_idle.load() + emscripten_get_now() - start);+}++struct Launch {+ std::vector<std::string> args;+};++void *emulate(void *data) {+ const Launch &launch = *static_cast<const Launch *>(data);+ if (g_disc_size && !ps2::disc::open("disc", g_disc_size, read_disc)) std::fprintf(stderr, "[web] cannot read the disc image\n");+ std::uint32_t entry = 0;+ if (!ps2::load_elf("/game/core.elf", entry)) {+ std::fprintf(stderr, "cannot load the game executable\n");+ return nullptr;}- ps2web_frame_done();- ps2::browser_yield();- while (ps2web_audio_queued_ms() > 80.0) emscripten_sleep(2);+ ps2::boot(entry, launch.args);+ ps2::run();+ return nullptr;}}@@ -152,16 +186,15 @@ extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_resize(int width, int height) {extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_gpu_ms() { return ps2::gpu_busy_ms(); }extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_frames() { return static_cast<double>(ps2::frames_run()); }extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_primitives() { return static_cast<double>(ps2::primitives_drawn()); }+extern "C" EMSCRIPTEN_KEEPALIVE void *ps2web_audio_ring() { return &g_audio; }+extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_audio_queued_ms() { return audio_queued_ms(); }+extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_idle_ms(int render) { return render ? g_render_idle.load() : g_emulation_idle.load(); }int main(int argc, char **argv) {- if (argc < 2) {- std::fprintf(stderr, "usage: ps2web <elf> [--arg text]...\n");- return 1;- }- std::vector<std::string> args;+ static Launch launch;for (int i = 2; i < argc; ++i) {const std::string a = argv[i];- if (a == "--arg" && i + 1 < argc) args.push_back(argv[++i]);+ if (a == "--arg" && i + 1 < argc) launch.args.push_back(argv[++i]);else if (a == "--frames" && i + 1 < argc) ps2::g_options.max_frames = std::strtoull(argv[++i], nullptr, 10);else if (a == "--press" && i + 1 < argc) {ps2::Press press;@@ -169,16 +202,48 @@ int main(int argc, char **argv) {}}g_disc_size = static_cast<std::uint64_t>(ps2web_disc_size());- if (g_disc_size && !ps2::disc::open("disc", g_disc_size, read_disc)) std::fprintf(stderr, "[web] cannot read the disc image\n");+ g_disc_url = ps2web_disc_url();ps2::g_options.on_vblank = on_vblank;- ps2::set_audio_sink([](const std::int16_t *samples, std::size_t frames) { ps2web_audio(samples, static_cast<int>(frames)); });+ ps2::set_audio_sink(push_audio);register_generated_code();register_generated_vu();- std::uint32_t entry = 0;- if (!ps2::load_elf(argv[1], entry)) {- std::fprintf(stderr, "cannot load %s\n", argv[1]);++ ps2::init_graphics();+ const bool no_surface = EM_ASM_INT({ return Module.noSurface ? 1 : 0; });+ bool copy = EM_ASM_INT({ return Module.presentCopy ? 1 : 0; });+ bool surface = false;+ if (!copy && !no_surface) {+ ps2::WindowTarget target;+ target.kind = ps2::WindowTarget::Canvas;+ target.selector = "#canvas";+ target.width = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.width; }));+ target.height = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.height; }));+ surface = ps2::attach_window(target);+ }+ copy = copy || (!surface && !no_surface);+ std::fprintf(stderr, "[web] %s\n", surface ? "presenting through WebGPU" : copy ? "presenting through a 2D canvas copy" : "not presenting");++ ps2::start_render_thread();+ pthread_attr_t attr;+ pthread_attr_init(&attr);+ pthread_attr_setstacksize(&attr, 16u << 20);+ pthread_t thread;+ if (pthread_create(&thread, &attr, emulate, &launch) != 0) {+ std::fprintf(stderr, "[web] cannot start the emulation thread\n");return 1;}- ps2::boot(entry, args);- return ps2::run();+ const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> blit = [](const std::uint32_t *rgba, std::uint32_t width, std::uint32_t height) {+ ps2web_blit(rgba, static_cast<int>(width), static_cast<int>(height));+ };+ const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> none;+ for (;;) {+ if (ps2::render_pending(surface, copy ? blit : none)) {+ ps2web_frame_done();+ ps2::browser_yield();+ } else {+ const double start = emscripten_get_now();+ ps2::wait_render_work(50);+ g_render_idle.store(g_render_idle.load() + emscripten_get_now() - start);+ }+ }}diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hppindex b31d4cc..c2b0758 100644--- a/runtime/include/ps2/system.hpp+++ b/runtime/include/ps2/system.hpp@@ -84,6 +84,11 @@ struct WindowTarget {bool attach_window(const WindowTarget &target);void resize_window(std::uint32_t width, std::uint32_t height);bool present_frame();+void init_graphics();+void start_render_thread();+void post_present();+bool render_pending(bool surface, const std::function<void(const std::uint32_t *rgba, std::uint32_t width, std::uint32_t height)> ©);+void wait_render_work(int timeout_ms);// Latest frame for hosts that draw it themselves, fields blended; may lag a frame and is false while none is ready.bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);// Parses "frame:button[+button][:frames]" as used by --press.diff --git a/runtime/src/dmac.cpp b/runtime/src/dmac.cppindex d226c41..6ae704e 100644--- a/runtime/src/dmac.cpp+++ b/runtime/src/dmac.cpp@@ -44,15 +44,22 @@ std::uint8_t *target(std::uint32_t address) {void deliver(int ch, std::uint32_t address, std::uint32_t qwc) {if (!qwc) return;- std::vector<std::uint8_t> buffer(static_cast<std::size_t>(qwc) * 16);- for (std::uint32_t i = 0; i < qwc; ++i) std::memcpy(buffer.data() + i * 16, source(address + i * 16), 16);+ static std::vector<std::uint8_t> buffer;+ const std::size_t bytes = static_cast<std::size_t>(qwc) * 16;+ const std::size_t room = (address & 0x80000000u) ? kScratchpadSize - (address & (kScratchpadSize - 1)) : kRamSize - (address & (kRamSize - 16));+ const std::uint8_t *data = source(address);+ if (bytes > room || ch == 9) {+ buffer.resize(bytes);+ for (std::uint32_t i = 0; i < qwc; ++i) std::memcpy(buffer.data() + i * 16, source(address + i * 16), 16);+ data = buffer.data();+ }switch (ch) {- case 0: vif::transfer(0, buffer.data(), qwc); break;- case 1: vif::transfer(1, buffer.data(), qwc); break;- case 2: gif::transfer(3, buffer.data(), qwc); break;+ case 0: vif::transfer(0, data, qwc); break;+ case 1: vif::transfer(1, data, qwc); break;+ case 2: gif::transfer(3, data, qwc); break;case 9:for (std::uint32_t i = 0; i < qwc; ++i)- std::memcpy(g_spr + ((g_ch[9].sadr + i * 16) & (kScratchpadSize - 1)), buffer.data() + i * 16, 16);+ std::memcpy(g_spr + ((g_ch[9].sadr + i * 16) & (kScratchpadSize - 1)), data + i * 16, 16);g_ch[9].sadr = (g_ch[9].sadr + qwc * 16) & (kScratchpadSize - 1);break;default:diff --git a/runtime/src/gs/gif.cpp b/runtime/src/gs/gif.cppindex dc76f42..7e7e3ea 100644--- a/runtime/src/gs/gif.cpp+++ b/runtime/src/gs/gif.cpp@@ -1,6 +1,7 @@#include "gif.hpp"#include "gs.hpp"+#include "queue.hpp"#include <algorithm>#include <cstdio>@@ -15,21 +16,15 @@ struct Path {std::uint32_t nloop = 0, loop = 0, nreg = 0, reg = 0, flg = 0;std::uint64_t regs = 0;bool eop = false;+ bool address_data = false;};Path g_paths[4];std::uint32_t g_stat = 0;std::uint64_t g_tags[4][4];-}--void reset() {- for (Path &p : g_paths) p = Path{};- g_stat = 0;-}--void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {- Path &p = g_paths[path];+template <typename Sink>+void walk(Path &p, const std::uint8_t *data, std::uint32_t qwc, Sink &sink) {for (std::uint32_t i = 0; i < qwc; ++i) {Reg128 q;std::memcpy(&q, data + static_cast<std::size_t>(i) * 16, 16);@@ -40,17 +35,15 @@ void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {p.nreg = static_cast<std::uint32_t>(q.d[0] >> 60) & 0xFu;if (!p.nreg) p.nreg = 16;p.regs = q.d[1];- ++g_tags[path][p.flg];p.loop = 0;p.reg = 0;- gs::g_state.q = 1.0f;- if (((q.d[0] >> 46) & 1u) && p.flg == 0) gs::write(0x00, (q.d[0] >> 47) & 0x7FFu);+ sink.tag(p, q);p.active = p.nloop != 0;continue;}switch (p.flg) {case 0:- gs::write_packed(static_cast<std::uint32_t>(p.regs >> (p.reg * 4)) & 0xFu, q);+ sink.packed(static_cast<std::uint32_t>(p.regs >> (p.reg * 4)) & 0xFu, q);if (++p.reg >= p.nreg) {p.reg = 0;if (++p.loop >= p.nloop) p.active = false;@@ -58,7 +51,7 @@ void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {break;case 1:for (int half = 0; half < 2 && p.active; ++half) {- gs::write(static_cast<std::uint32_t>(p.regs >> (p.reg * 4)) & 0xFu, q.d[half]);+ sink.reglist(static_cast<std::uint32_t>(p.regs >> (p.reg * 4)) & 0xFu, q.d[half]);if (++p.reg >= p.nreg) {p.reg = 0;if (++p.loop >= p.nloop) p.active = false;@@ -67,7 +60,7 @@ void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {break;default: {const std::uint32_t run = std::min(qwc - i, p.nloop - p.loop);- gs::write_image(data + static_cast<std::size_t>(i) * 16, run);+ sink.image(data + static_cast<std::size_t>(i) * 16, run);p.loop += run;i += run - 1;if (p.loop >= p.nloop) p.active = false;@@ -77,6 +70,107 @@ void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {}}+struct GsSink {+ int path;+ void tag(const Path &p, const Reg128 &q) {+ ++g_tags[path][p.flg];+ gs::g_state.q = 1.0f;+ if (((q.d[0] >> 46) & 1u) && p.flg == 0) gs::write(0x00, (q.d[0] >> 47) & 0x7FFu);+ }+ void packed(std::uint32_t reg, const Reg128 &q) { gs::write_packed(reg, q); }+ void reglist(std::uint32_t reg, std::uint64_t value) { gs::write(reg, value); }+ void image(const std::uint8_t *data, std::uint32_t qwords) { gs::write_image(data, qwords); }+};++void scan(Path &p, const std::uint8_t *data, std::uint32_t qwc) {+ std::uint32_t i = 0;+ while (i < qwc) {+ Reg128 q;+ if (!p.active) {+ std::memcpy(&q, data + static_cast<std::size_t>(i) * 16, 16);+ p.nloop = static_cast<std::uint32_t>(q.d[0]) & 0x7FFFu;+ p.flg = static_cast<std::uint32_t>(q.d[0] >> 58) & 3u;+ p.nreg = static_cast<std::uint32_t>(q.d[0] >> 60) & 0xFu;+ if (!p.nreg) p.nreg = 16;+ p.regs = q.d[1];+ p.loop = 0;+ p.reg = 0;+ p.address_data = false;+ if (p.flg == 0)+ for (std::uint32_t r = 0; r < p.nreg; ++r) p.address_data = p.address_data || ((p.regs >> (r * 4)) & 0xFu) == 0xEu;+ p.active = p.nloop != 0;+ ++i;+ continue;+ }+ if (p.flg == 0 && p.address_data) {+ for (; i < qwc && p.active; ++i) {+ const std::uint8_t *at = data + static_cast<std::size_t>(i) * 16;+ if (((p.regs >> (p.reg * 4)) & 0xFu) == 0xEu && at[8] >= 0x60 && at[8] <= 0x62) {+ std::uint64_t value;+ std::memcpy(&value, at, 8);+ gs::signal(at[8], value);+ }+ if (++p.reg >= p.nreg) {+ p.reg = 0;+ if (++p.loop >= p.nloop) p.active = false;+ }+ }+ continue;+ }+ const std::uint64_t done = static_cast<std::uint64_t>(p.loop) * p.nreg + p.reg;+ const std::uint64_t left = static_cast<std::uint64_t>(p.nloop) * p.nreg - done;+ std::uint64_t take, used;+ if (p.flg == 0) {+ take = used = std::min<std::uint64_t>(left, qwc - i);+ } else if (p.flg == 1) {+ take = std::min<std::uint64_t>((left + 1) / 2, qwc - i);+ used = std::min<std::uint64_t>(take * 2, left);+ } else {+ take = std::min<std::uint64_t>(p.nloop - p.loop, qwc - i);+ p.loop += static_cast<std::uint32_t>(take);+ if (p.loop >= p.nloop) p.active = false;+ i += static_cast<std::uint32_t>(take);+ continue;+ }+ p.loop = static_cast<std::uint32_t>((done + used) / p.nreg);+ p.reg = static_cast<std::uint32_t>((done + used) % p.nreg);+ if (used == left) p.active = false;+ i += static_cast<std::uint32_t>(take);+ }+}++Path g_scan[4];++}++void reset() {+ g_stat = 0;+ if (gs::queue::active()) {+ for (Path &p : g_scan) p = Path{};+ gs::queue::post(gs::queue::kGifReset, 0, 0, nullptr, 0);+ return;+ }+ render_reset();+}++void render_reset() {+ for (Path &p : g_paths) p = Path{};+}++void render(int path, const std::uint8_t *data, std::uint32_t qwc) {+ GsSink sink{path};+ walk(g_paths[path], data, qwc, sink);+}++void transfer(int path, const std::uint8_t *data, std::uint32_t qwc) {+ if (!gs::queue::active()) {+ render(path, data, qwc);+ return;+ }+ scan(g_scan[path], data, qwc);+ gs::queue::post(gs::queue::kGif, static_cast<std::uint32_t>(path), qwc, data, qwc * 16);+}+bool busy(int path) { return g_paths[path].active; }void stats() {diff --git a/runtime/src/gs/gif.hpp b/runtime/src/gs/gif.hppindex 504305c..86492b7 100644--- a/runtime/src/gs/gif.hpp+++ b/runtime/src/gs/gif.hpp@@ -7,6 +7,8 @@ namespace ps2::gif {void reset();void stats();void transfer(int path, const std::uint8_t *data, std::uint32_t qwc);+void render(int path, const std::uint8_t *data, std::uint32_t qwc);+void render_reset();bool busy(int path);std::uint32_t read(std::uint32_t a);void write(std::uint32_t a, std::uint32_t v);diff --git a/runtime/src/gs/gs.cpp b/runtime/src/gs/gs.cppindex 563d7ce..5e8542a 100644--- a/runtime/src/gs/gs.cpp+++ b/runtime/src/gs/gs.cpp@@ -1,5 +1,7 @@#include "gs.hpp"+#include "gif.hpp"+#include "queue.hpp"#include "raster.hpp"#include "../hw.hpp"#ifdef PS2_GPU@@ -7,6 +9,8 @@#endif#include <algorithm>+#include <atomic>+#include <functional>#include <cstdio>#include <cstdlib>#include <cstring>@@ -341,26 +345,34 @@ void write_pixel(std::uint32_t psm, std::uint32_t bp, std::uint32_t bw, std::uin}}-void reset() {+void init() {static bool built = false;- if (!built) {- build_tables();- built = true;+ if (built) return;+ build_tables();+ built = true;#ifdef PS2_GPU- const char *backend = std::getenv("PS2_GS");- const gpu::Mode wanted = !backend || std::strcmp(backend, "gpu") == 0 ? gpu::Mode::primary : std::strcmp(backend, "both") == 0 ? gpu::Mode::mirror : gpu::Mode::off;- if (wanted != gpu::Mode::off && !gpu::init(wanted)) std::fprintf(stderr, "[gs] WebGPU unavailable, using the software renderer\n");+ const char *backend = std::getenv("PS2_GS");+ const gpu::Mode wanted = !backend || std::strcmp(backend, "gpu") == 0 ? gpu::Mode::primary : std::strcmp(backend, "both") == 0 ? gpu::Mode::mirror : gpu::Mode::off;+ if (wanted != gpu::Mode::off && !gpu::init(wanted)) std::fprintf(stderr, "[gs] WebGPU unavailable, using the software renderer\n");#endif- }+}++void render_reset() {+ init();std::memset(&g_state, 0, sizeof g_state);std::memset(g_memory, 0, sizeof g_memory);- g_csr = 0x551B4000ull;- g_imr = 0x7F00ull;g_transfer = Transfer{};g_primitives = 0;raster::reset();}+void reset() {+ g_csr = 0x551B4000ull;+ g_imr = 0x7F00ull;+ if (queue::active()) queue::post(queue::kReset, 0, 0, nullptr, 0);+ else render_reset();+}+void kick(bool draw) {State &s = g_state;const std::uint32_t prim = static_cast<std::uint32_t>(s.prim) & 7u;@@ -497,21 +509,28 @@ void write(std::uint32_t reg, std::uint64_t value) {case 0x54:feed_image(reinterpret_cast<const std::uint8_t *>(&value), 8);break;- case 0x60: {- const std::uint32_t mask = static_cast<std::uint32_t>(value >> 32), id = static_cast<std::uint32_t>(value);+ case 0x60: case 0x61: case 0x62:+ if (!queue::active()) signal(reg, value);+ break;+ default:+ break;+ }+}++void signal(std::uint32_t reg, std::uint64_t value) {+ const std::uint32_t mask = static_cast<std::uint32_t>(value >> 32), id = static_cast<std::uint32_t>(value);+ switch (reg) {+ case 0x60:g_siglblid = (g_siglblid & ~static_cast<std::uint64_t>(mask)) | (id & mask);raise(1);break;- }case 0x61: raise(2); break;case 0x62: {- const std::uint32_t mask = static_cast<std::uint32_t>(value >> 32), id = static_cast<std::uint32_t>(value);const std::uint64_t label = (g_siglblid >> 32 & ~static_cast<std::uint64_t>(mask)) | (id & mask);g_siglblid = (g_siglblid & 0xFFFFFFFFull) | (label << 32);break;}- default:- break;+ default: break;}}@@ -556,7 +575,20 @@ void write_packed(std::uint32_t reg, const Reg128 &q) {void write_image(const std::uint8_t *data, std::uint32_t qwords) { feed_image(data, static_cast<std::size_t>(qwords) * 16); }+std::atomic<std::uint32_t> g_downloads{0};+void read_image(std::uint8_t *data, std::uint32_t qwords) {+ if (!queue::active()) {+ render_read_image(data, qwords);+ return;+ }+ const std::uint32_t seen = g_downloads.load();+ const std::uintptr_t target = reinterpret_cast<std::uintptr_t>(data);+ queue::post(queue::kDownload, qwords, 0, &target, sizeof target);+ while (g_downloads.load() == seen) queue::wait(g_downloads, seen);+}++void render_read_image(std::uint8_t *data, std::uint32_t qwords) {const std::size_t bytes = static_cast<std::size_t>(qwords) * 16;std::memset(data, 0, bytes);if (!g_transfer.active || (g_state.trxdir & 3u) != 1) return;@@ -634,7 +666,8 @@ void write_privileged(std::uint32_t address, std::uint64_t value) {g_csr &= ~(value & 0x1Fu);if (value & 0x200u) {g_csr = 0x551B4000ull;- g_state.count = 0;+ if (queue::active()) queue::post(queue::kVertexReset, 0, 0, nullptr, 0);+ else g_state.count = 0;}break;case 0x1010: g_imr = value; break;@@ -648,8 +681,9 @@ void vblank(bool start) {if (start) {g_odd_field = !g_odd_field;raise(8);+ if (queue::active()) queue::post(queue::kVblank, 0, 0, nullptr, 0);#ifdef PS2_GPU- if (gpu_on()) gpu::flush();+ else if (gpu_on()) gpu::flush();#endif}}@@ -683,27 +717,33 @@ double gpu_busy_ms() {#endif}-bool present() {+DisplayRegs display_regs() { return DisplayRegs{g_pmode, g_smode2, {g_dispfb[0], g_dispfb[1]}, {g_display[0], g_display[1]}}; }++bool present() { return present(display_regs()); }++bool present(const DisplayRegs &r) {#ifdef PS2_GPUif (!gpu::has_surface()) return false;- const int circuit = (g_pmode & 2u) ? 1 : (g_pmode & 1u) ? 0 : -1;+ const int circuit = (r.pmode & 2u) ? 1 : (r.pmode & 1u) ? 0 : -1;if (circuit < 0) return true;- const std::uint64_t fb = g_dispfb[circuit], disp = g_display[circuit];+ const std::uint64_t fb = r.dispfb[circuit], disp = r.display[circuit];const std::uint32_t magh = (static_cast<std::uint32_t>(disp >> 23) & 0xFu) + 1, magv = (static_cast<std::uint32_t>(disp >> 27) & 3u) + 1;const std::uint32_t width = ((static_cast<std::uint32_t>(disp >> 32) & 0xFFFu) + 1) / magh, height = ((static_cast<std::uint32_t>(disp >> 44) & 0x7FFu) + 1) / magv;if (!width || !height || width > 2048 || height > 2048) return true;const gpu::DisplaySource src{(static_cast<std::uint32_t>(fb) & 0x1FFu) * 32, static_cast<std::uint32_t>(fb >> 9) & 0x3Fu, static_cast<std::uint32_t>(fb >> 15) & 0x1Fu,- static_cast<std::uint32_t>(fb >> 32) & 0x7FFu, static_cast<std::uint32_t>(fb >> 43) & 0x7FFu, width, height, (g_smode2 & 3u) == 3u};+ static_cast<std::uint32_t>(fb >> 32) & 0x7FFu, static_cast<std::uint32_t>(fb >> 43) & 0x7FFu, width, height, (r.smode2 & 3u) == 3u};return gpu::present(src);#elsereturn false;#endif}-bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) {- const int circuit = (g_pmode & 2u) ? 1 : (g_pmode & 1u) ? 0 : -1;+bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) { return display(display_regs(), rgba, width, height); }++bool display(const DisplayRegs &r, std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) {+ const int circuit = (r.pmode & 2u) ? 1 : (r.pmode & 1u) ? 0 : -1;if (circuit < 0) return false;- const std::uint64_t fb = g_dispfb[circuit], disp = g_display[circuit];+ const std::uint64_t fb = r.dispfb[circuit], disp = r.display[circuit];const std::uint32_t fbp = static_cast<std::uint32_t>(fb) & 0x1FFu, fbw = static_cast<std::uint32_t>(fb >> 9) & 0x3Fu;const std::uint32_t psm = static_cast<std::uint32_t>(fb >> 15) & 0x1Fu;const std::uint32_t dbx = static_cast<std::uint32_t>(fb >> 32) & 0x7FFu, dby = static_cast<std::uint32_t>(fb >> 43) & 0x7FFu;@@ -712,7 +752,7 @@ bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32width = dw / magh;height = dh / magv;if (!width || !height || width > 2048 || height > 2048) return false;- const bool halved = (g_smode2 & 3u) == 3u;+ const bool halved = (r.smode2 & 3u) == 3u;#ifdef PS2_GPUif (gpu_on()) {const gpu::DisplaySource src{fbp * 32, fbw, psm, dbx, dby, width, height, halved};@@ -747,30 +787,32 @@ bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32return true;}-bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) {+bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) { return copy_frame(display_regs(), rgba, width, height); }++bool copy_frame(const DisplayRegs &r, std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) {static std::vector<std::uint32_t> previous;bool got = false;#ifdef PS2_GPUif (gpu_on() && !cpu_raster()) {- const int circuit = (g_pmode & 2u) ? 1 : (g_pmode & 1u) ? 0 : -1;+ const int circuit = (r.pmode & 2u) ? 1 : (r.pmode & 1u) ? 0 : -1;if (circuit < 0) return false;- const std::uint64_t fb = g_dispfb[circuit], disp = g_display[circuit];+ const std::uint64_t fb = r.dispfb[circuit], disp = r.display[circuit];const std::uint32_t magh = (static_cast<std::uint32_t>(disp >> 23) & 0xFu) + 1, magv = (static_cast<std::uint32_t>(disp >> 27) & 3u) + 1;const std::uint32_t w = ((static_cast<std::uint32_t>(disp >> 32) & 0xFFFu) + 1) / magh, h = ((static_cast<std::uint32_t>(disp >> 44) & 0x7FFu) + 1) / magv;if (!w || !h || w > 2048 || h > 2048) return false;const gpu::DisplaySource src{(static_cast<std::uint32_t>(fb) & 0x1FFu) * 32, static_cast<std::uint32_t>(fb >> 9) & 0x3Fu, static_cast<std::uint32_t>(fb >> 15) & 0x1Fu,- static_cast<std::uint32_t>(fb >> 32) & 0x7FFu, static_cast<std::uint32_t>(fb >> 43) & 0x7FFu, w, h, (g_smode2 & 3u) == 3u};+ static_cast<std::uint32_t>(fb >> 32) & 0x7FFu, static_cast<std::uint32_t>(fb >> 43) & 0x7FFu, w, h, (r.smode2 & 3u) == 3u};got = gpu::display_async(src, rgba, width, height);} else#endif- got = display(rgba, width, height);+ got = display(r, rgba, width, height);if (!got) return false;if (previous.size() != rgba.size()) {previous = rgba;return true;}static const bool weave_off = std::getenv("PS2_NO_DEINTERLACE") != nullptr;- const bool blend = (g_smode2 & 3u) == 3u && !weave_off;+ const bool blend = (r.smode2 & 3u) == 3u && !weave_off;for (std::size_t i = 0; i < rgba.size(); ++i) {const std::uint32_t c = rgba[i];if (blend) rgba[i] = (c & previous[i]) + (((c ^ previous[i]) & 0xFEFEFEFEu) >> 1);@@ -779,6 +821,60 @@ bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uinreturn true;}+std::atomic<std::uint32_t> g_presented{0};+std::uint32_t g_posted_presents = 0;++void start_thread() { queue::start(32u << 20); }++void post_present() {+ const DisplayRegs regs = display_regs();+ queue::post(queue::kPresent, 0, 0, ®s, sizeof regs);+ ++g_posted_presents;+ for (std::uint32_t done = g_presented.load(); g_posted_presents - done > 2; done = g_presented.load()) queue::wait(g_presented, done);+}++bool render_pending(const std::function<void(const DisplayRegs &)> &on_present) {+ queue::Header h;+ const std::uint8_t *payload = nullptr;+ while (queue::peek(h, payload)) {+ bool presented = false;+ switch (h.type) {+ case queue::kGif: gif::render(static_cast<int>(h.arg0), payload, h.arg1); break;+ case queue::kGifReset: gif::render_reset(); break;+ case queue::kReset: render_reset(); break;+ case queue::kVertexReset: g_state.count = 0; break;+ case queue::kVblank:+#ifdef PS2_GPU+ if (gpu_on()) gpu::flush();+#endif+ break;+ case queue::kPresent: {+ DisplayRegs regs;+ std::memcpy(®s, payload, sizeof regs);+ on_present(regs);+ presented = true;+ break;+ }+ case queue::kDownload: {+ std::uintptr_t target;+ std::memcpy(&target, payload, sizeof target);+ render_read_image(reinterpret_cast<std::uint8_t *>(target), h.arg0);+ g_downloads.fetch_add(1);+ queue::notify(g_downloads);+ break;+ }+ default: break;+ }+ queue::pop(h);+ if (presented) {+ g_presented.fetch_add(1);+ queue::notify(g_presented);+ return true;+ }+ }+ return false;+}+std::uint64_t primitives_drawn() { return g_primitives; }void dump_region(const char *spec) {diff --git a/runtime/src/gs/gs.hpp b/runtime/src/gs/gs.hppindex 6f9c17e..5678212 100644--- a/runtime/src/gs/gs.hpp+++ b/runtime/src/gs/gs.hpp@@ -3,6 +3,7 @@#include "ps2/cpu.hpp"#include <cstdint>+#include <functional>#include <vector>namespace ps2::gs {@@ -40,11 +41,15 @@ struct State {extern State g_state;std::uint8_t *memory();+void init();void reset();void write(std::uint32_t reg, std::uint64_t value);+void signal(std::uint32_t reg, std::uint64_t value);void write_packed(std::uint32_t reg, const Reg128 &q);void write_image(const std::uint8_t *data, std::uint32_t qwords);void read_image(std::uint8_t *data, std::uint32_t qwords);+void render_read_image(std::uint8_t *data, std::uint32_t qwords);+void render_reset();std::uint64_t read_privileged(std::uint32_t address);void write_privileged(std::uint32_t address, std::uint64_t value);@@ -55,12 +60,23 @@ std::uint32_t address32(std::uint32_t bp, std::uint32_t bw, std::uint32_t x, stdstd::uint32_t read_pixel(std::uint32_t psm, std::uint32_t bp, std::uint32_t bw, std::uint32_t x, std::uint32_t y);void write_pixel(std::uint32_t psm, std::uint32_t bp, std::uint32_t bw, std::uint32_t x, std::uint32_t y, std::uint32_t value);+struct DisplayRegs {+ std::uint64_t pmode, smode2, dispfb[2], display[2];+};+DisplayRegs display_regs();+bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);+bool display(const DisplayRegs ®s, std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);// Frame for hosts that draw it themselves, with interlaced fields blended like present(); may lag a frame.bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);+bool copy_frame(const DisplayRegs ®s, std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);bool attach_window(int kind, void *display, std::uint64_t window, void *surface, const char *selector, std::uint32_t width, std::uint32_t height);void resize_window(std::uint32_t width, std::uint32_t height);bool present();+bool present(const DisplayRegs ®s);+void start_thread();+void post_present();+bool render_pending(const std::function<void(const DisplayRegs &)> &on_present);double gpu_busy_ms();std::uint64_t primitives_drawn();void stats();diff --git a/runtime/src/gs/queue.cpp b/runtime/src/gs/queue.cppnew file mode 100644index 0000000..d368f10--- /dev/null+++ b/runtime/src/gs/queue.cpp@@ -0,0 +1,128 @@+#include "queue.hpp"++#include <algorithm>+#include <climits>+#include <cstring>+#include <memory>++#ifdef __EMSCRIPTEN__+#include <emscripten.h>+#include <emscripten/threading.h>+#else+#include <chrono>+#include <thread>+#endif++namespace ps2::gs::queue {++namespace {++std::unique_ptr<std::uint8_t[]> g_buffer;+std::uint64_t g_capacity = 0;+bool g_active = false;+alignas(64) std::atomic<std::uint64_t> g_head{0};+alignas(64) std::atomic<std::uint64_t> g_tail{0};+alignas(64) std::atomic<std::uint32_t> g_posted{0};+alignas(64) std::atomic<std::uint32_t> g_freed{0};+std::atomic<std::uint32_t> g_consumer_waiting{0}, g_producer_waiting{0};++constexpr std::uint64_t align16(std::uint64_t n) { return (n + 15) & ~15ull; }++}++#ifdef __EMSCRIPTEN__+EM_ASYNC_JS(void, ps2_wait_async, (std::atomic<std::uint32_t> *word, std::uint32_t seen, int timeout_ms), {+ const result = Atomics.waitAsync(HEAP32, word >> 2, seen, timeout_ms);+ if (result.async) await result.value;+});+#endif++void wait(std::atomic<std::uint32_t> &value, std::uint32_t seen) {+#ifdef __EMSCRIPTEN__+ emscripten_futex_wait(&value, seen, INFINITY);+#else+ value.wait(seen);+#endif+}++void notify(std::atomic<std::uint32_t> &value) {+#ifdef __EMSCRIPTEN__+ emscripten_futex_wake(&value, INT_MAX);+#else+ value.notify_all();+#endif+}++bool active() { return g_active; }++void start(std::size_t capacity) {+ g_capacity = capacity;+ g_buffer = std::make_unique<std::uint8_t[]>(capacity);+ g_active = true;+}++void post(Type type, std::uint32_t arg0, std::uint32_t arg1, const void *data, std::uint32_t bytes) {+ const std::uint64_t need = sizeof(Header) + align16(bytes);+ std::uint64_t head = g_head.load(std::memory_order_relaxed);+ for (;;) {+ const std::uint64_t pos = head % g_capacity;+ const std::uint64_t pad = pos + need > g_capacity ? g_capacity - pos : 0;+ const std::uint32_t seen = g_freed.load(std::memory_order_acquire);+ if (head + pad + need - g_tail.load(std::memory_order_acquire) <= g_capacity) {+ if (pad) {+ const Header wrap{kWrap, 0, 0, 0};+ std::memcpy(g_buffer.get() + pos, &wrap, sizeof wrap);+ head += pad;+ }+ break;+ }+ g_producer_waiting.store(1);+ if (head + pad + need - g_tail.load() > g_capacity) wait(g_freed, seen);+ }+ std::uint8_t *at = g_buffer.get() + head % g_capacity;+ const Header h{type, bytes, arg0, arg1};+ std::memcpy(at, &h, sizeof h);+ if (bytes) std::memcpy(at + sizeof h, data, bytes);+ g_head.store(head + need, std::memory_order_release);+ g_posted.fetch_add(1);+ if (g_consumer_waiting.exchange(0)) notify(g_posted);+}++bool peek(Header &header, const std::uint8_t *&payload) {+ std::uint64_t tail = g_tail.load(std::memory_order_relaxed);+ const std::uint64_t head = g_head.load(std::memory_order_acquire);+ while (tail != head) {+ const std::uint64_t pos = tail % g_capacity;+ std::memcpy(&header, g_buffer.get() + pos, sizeof header);+ if (header.type != kWrap) {+ payload = g_buffer.get() + pos + sizeof header;+ return true;+ }+ tail += g_capacity - pos;+ g_tail.store(tail, std::memory_order_release);+ }+ return false;+}++void pop(const Header &header) {+ g_tail.store(g_tail.load(std::memory_order_relaxed) + sizeof(Header) + align16(header.bytes), std::memory_order_release);+ g_freed.fetch_add(1);+ if (g_producer_waiting.exchange(0)) notify(g_freed);+}++void wait_for_work(int timeout_ms) {+ const std::uint32_t seen = g_posted.load();+ g_consumer_waiting.store(1);+ if (g_head.load() != g_tail.load()) {+ g_consumer_waiting.store(0);+ return;+ }+#ifdef __EMSCRIPTEN__+ ps2_wait_async(&g_posted, seen, timeout_ms);+#else+ (void)seen;+ std::this_thread::sleep_for(std::chrono::milliseconds(std::min(timeout_ms, 1)));+#endif+}++}diff --git a/runtime/src/gs/queue.hpp b/runtime/src/gs/queue.hppnew file mode 100644index 0000000..e87f779--- /dev/null+++ b/runtime/src/gs/queue.hpp@@ -0,0 +1,27 @@+#pragma once++#include <atomic>+#include <cstddef>+#include <cstdint>++namespace ps2::gs::queue {++enum Type : std::uint32_t { kWrap, kGif, kGifReset, kReset, kVertexReset, kVblank, kPresent, kDownload };++struct Header {+ std::uint32_t type, bytes, arg0, arg1;+};++bool active();+void start(std::size_t capacity);++void post(Type type, std::uint32_t arg0, std::uint32_t arg1, const void *data, std::uint32_t bytes);++bool peek(Header &header, const std::uint8_t *&payload);+void pop(const Header &header);+void wait_for_work(int timeout_ms);++void wait(std::atomic<std::uint32_t> &value, std::uint32_t seen);+void notify(std::atomic<std::uint32_t> &value);++}diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex e428a89..5ec2443 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -2,6 +2,7 @@#include "gs/gif.hpp"#include "vif.hpp"#include "gs/gs.hpp"+#include "gs/queue.hpp"#include "hw.hpp"#include "iop/iop.hpp"#include "iop/sif.hpp"@@ -281,6 +282,23 @@ bool display_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::bool attach_window(const WindowTarget &t) { return gs::attach_window(static_cast<int>(t.kind), t.display, t.window, t.surface, t.selector, t.width, t.height); }void resize_window(std::uint32_t width, std::uint32_t height) { gs::resize_window(width, height); }bool present_frame() { return gs::present(); }+void init_graphics() { gs::init(); }+void start_render_thread() { gs::start_thread(); }+void post_present() { gs::post_present(); }++bool render_pending(bool surface, const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> ©) {+ static std::vector<std::uint32_t> frame;+ return gs::render_pending([&](const gs::DisplayRegs ®s) {+ if (surface) {+ gs::present(regs);+ return;+ }+ std::uint32_t width = 0, height = 0;+ if (copy && gs::copy_frame(regs, frame, width, height)) copy(frame.data(), width, height);+ });+}++void wait_render_work(int timeout_ms) { gs::queue::wait_for_work(timeout_ms); }bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) { return gs::copy_frame(rgba, width, height); }bool parse_press(const std::string &spec, Press &press) {diff --git a/runtime/src/vif.cpp b/runtime/src/vif.cppindex 2792bdc..46f61cd 100644--- a/runtime/src/vif.cpp+++ b/runtime/src/vif.cpp@@ -222,17 +222,23 @@ void execute(int unit, std::uint32_t cmd, const std::uint32_t *data) {}}-void process(int unit) {+std::size_t run(int unit, const std::uint32_t *words, std::size_t count) {Unit &u = g_units[unit];std::size_t pos = 0;- while (pos < u.pending.size() && !u.stalled) {- const std::uint32_t cmd = u.pending[pos];+ while (pos < count && !u.stalled) {+ const std::uint32_t cmd = words[pos];const std::size_t start = pos + 1;const std::uint32_t need = data_words(unit, cmd);- if (start + need > u.pending.size()) break;- execute(unit, cmd, u.pending.data() + start);+ if (start + need > count) break;+ execute(unit, cmd, words + start);pos = start + need;}+ return pos;+}++void process(int unit) {+ Unit &u = g_units[unit];+ const std::size_t pos = run(unit, u.pending.data(), u.pending.size());u.pending.erase(u.pending.begin(), u.pending.begin() + static_cast<std::ptrdiff_t>(pos));}@@ -253,6 +259,13 @@ void stats() {void transfer(int unit, const std::uint8_t *data, std::uint32_t qwc) {Unit &u = g_units[unit];+ if (u.pending.empty() && !u.stalled) {+ const auto *words = reinterpret_cast<const std::uint32_t *>(data);+ const std::size_t count = static_cast<std::size_t>(qwc) * 4;+ const std::size_t pos = run(unit, words, count);+ if (pos < count) u.pending.assign(words + pos, words + count);+ return;+ }const std::size_t old = u.pending.size();u.pending.resize(old + static_cast<std::size_t>(qwc) * 4);std::memcpy(u.pending.data() + old, data, static_cast<std::size_t>(qwc) * 16);diff --git a/scripts/serve.py b/scripts/serve.pyindex 5333837..ac70383 100755--- a/scripts/serve.py+++ b/scripts/serve.py@@ -33,6 +33,9 @@ class Handler(http.server.BaseHTTPRequestHandler):self.send_header('Content-Length', str(length))self.send_header('Accept-Ranges', 'bytes')self.send_header('Cache-Control', 'no-cache')+ self.send_header('Cross-Origin-Opener-Policy', 'same-origin')+ self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')+ self.send_header('Cross-Origin-Resource-Policy', 'same-origin')self.end_headers()def do_HEAD(self):diff --git a/web/shell.html b/web/shell.htmlindex a23c36e..99841a1 100644--- a/web/shell.html+++ b/web/shell.html@@ -41,36 +41,47 @@ window.addEventListener('resize', fitCanvas);const workletSource = `class Output extends AudioWorkletProcessor {- constructor() {+ constructor(options) {super();- this.queue = [];- this.offset = 0;- this.consumed = 0;- this.port.onmessage = (e) => this.queue.push(e.data);+ const { buffer, base } = options.processorOptions;+ this.ring = new Uint32Array(buffer, base, 4);+ this.capacity = this.ring[2];+ this.samples = new Int16Array(buffer, base + 16, this.capacity * 2);+ this.left = 0;+ this.right = 0;}process(inputs, outputs) {const left = outputs[0][0], right = outputs[0][1];+ const write = Atomics.load(this.ring, 0), mask = this.capacity - 1;+ let read = Atomics.load(this.ring, 1);for (let i = 0; i < left.length; ++i) {- if (!this.queue.length) { left[i] = right[i] = 0; continue; }- const block = this.queue[0];- left[i] = block[this.offset];- right[i] = block[this.offset + 1];- this.offset += 2;- ++this.consumed;- if (this.offset >= block.length) { this.queue.shift(); this.offset = 0; }+ if (read !== write) {+ const at = (read & mask) * 2;+ this.left = this.samples[at] / 32768;+ this.right = this.samples[at + 1] / 32768;+ read = (read + 1) >>> 0;+ } else {+ this.left *= 0.995;+ this.right *= 0.995;+ }+ left[i] = this.left;+ right[i] = this.right;}- if ((currentFrame & 1023) < left.length) this.port.postMessage(this.consumed);+ Atomics.store(this.ring, 1, read);+ Atomics.store(this.ring, 3, 1);return true;}}registerProcessor('ps2-output', Output);`;-let audio = null, node = null, posted = 0, consumed = 0;+let audio = null, node = null;async function startAudio() {audio = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });await audio.audioWorklet.addModule(URL.createObjectURL(new Blob([workletSource], { type: 'application/javascript' })));- node = new AudioWorkletNode(audio, 'ps2-output', { outputChannelCount: [2] });- node.port.onmessage = (e) => { consumed = e.data; };+ node = new AudioWorkletNode(audio, 'ps2-output', {+ outputChannelCount: [2],+ processorOptions: { buffer: Module.HEAPU8.buffer, base: Module._ps2web_audio_ring() },+ });node.connect(audio.destination);}@@ -155,7 +166,7 @@ async function chooseGpu() {return 'GPU cannot draw to the page, copying frames';}-let frames = 0, last = performance.now(), lastGpu = 0;+let frames = 0, last = performance.now(), lastGpu = 0, lastEmuIdle = 0, lastRenderIdle = 0;var Module = {canvas,arguments: ['/game/core.elf', '--arg', params.get('arg') || 'cdrom0:\\CORE.GT4;1'].concat(params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),@@ -167,6 +178,10 @@ var Module = {setStatus: (text) => { if (text) statusEl.textContent = text; },onRuntimeInitialized: () => {const start = document.getElementById('start');+ if (!crossOriginIsolated) {+ start.textContent = 'This page needs cross-origin isolation (COOP and COEP headers)';+ return;+ }start.disabled = false;start.textContent = 'Start';},@@ -180,14 +195,7 @@ var Module = {Module.removeRunDependency('disc');});}],- pushAudio: (samples) => {- if (!node) return;- const block = new Float32Array(samples.length);- for (let i = 0; i < samples.length; ++i) block[i] = samples[i] / 32768;- node.port.postMessage(block, [block.buffer]);- posted += samples.length / 2;- },- audioQueuedMs: () => (node ? (posted - consumed) / 48 : 0),+ audioQueuedMs: () => Module._ps2web_audio_queued_ms(),onFrame: () => {pollInput();++frames;@@ -195,8 +203,12 @@ var Module = {if (now - last >= 1000) {const gpu = Module._ps2web_gpu_ms();const memory = (Module.HEAPU8.length / 1048576).toFixed(0);- statsEl.textContent = 'frame ' + Module._ps2web_frames() + ' prims ' + Module._ps2web_primitives() + ' ' + (frames * 1000 / (now - last)).toFixed(1) + ' fps GPU ' + ((gpu - lastGpu) / (now - last) * 100).toFixed(0) ++ const emuIdle = Module._ps2web_idle_ms(0), renderIdle = Module._ps2web_idle_ms(1), span = now - last;+ statsEl.textContent = 'frame ' + Module._ps2web_frames() + ' ' + (frames * 1000 / span).toFixed(1) + ' fps GPU ' + ((gpu - lastGpu) / span * 100).toFixed(0) ++ '% idle emu ' + ((emuIdle - lastEmuIdle) / span * 100).toFixed(0) + '% gs ' + ((renderIdle - lastRenderIdle) / span * 100).toFixed(0) +'% heap ' + memory + ' MB audio ' + Module.audioQueuedMs().toFixed(0) + ' ms';+ lastEmuIdle = emuIdle;+ lastRenderIdle = renderIdle;lastGpu = gpu;frames = 0;last = now;