PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Blend interlaced fields, follow SetGsCrt for the field rate, show load
Samir Nuri9bf719be36d4
diff --git a/host/main.cpp b/host/main.cppindex b22b2e3..19c17ff 100644--- a/host/main.cpp+++ b/host/main.cpp@@ -50,7 +50,7 @@ bool parse_press(const std::string &spec, ps2::Press &press) {int usage() {std::fprintf(stderr,"usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"- " [--disc image.iso] [--trace-syscalls] [--trace-io] [--trace-threads]\n"+ " [--disc image.iso] [--pal | --ntsc] [--trace-syscalls] [--trace-io] [--trace-threads]\n"" [--trace-iop] [--trace-iop-hle] [--frames-dir dir] [--frame-every n]\n"" [--press frame:button[+button][:frames]]... [--window]\n");return 2;@@ -66,7 +66,10 @@ int main(int argc, char **argv) {const std::string a = argv[i];if (a == "--arg" && i + 1 < argc) 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 == "--ntsc") ps2::g_options.pal = false;+ else if (a == "--ntsc" || a == "--pal") {+ ps2::g_options.pal = a == "--pal";+ ps2::g_options.rate_forced = true;+ }else if (a == "--misses" && i + 1 < argc) ps2::g_options.misses_path = argv[++i];else if (a == "--trace-syscalls") ps2::g_options.trace_syscalls = true;else if (a == "--trace-io") ps2::g_options.trace_io = true;diff --git a/host/window.cpp b/host/window.cppindex 173d592..253cb3a 100644--- a/host/window.cpp+++ b/host/window.cpp@@ -4,6 +4,8 @@#include <SDL.h>#include <SDL_syswm.h>+#include <sys/resource.h>+#include <unistd.h>#include <algorithm>#include <cstdio>@@ -194,19 +196,43 @@ void pace() {}}+double process_cpu_seconds() {+ rusage usage{};+ getrusage(RUSAGE_SELF, &usage);+ return static_cast<double>(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + static_cast<double>(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1e6;+}++double resident_mb() {+ long pages = 0, resident = 0;+ if (std::FILE *f = std::fopen("/proc/self/statm", "r")) {+ if (std::fscanf(f, "%ld %ld", &pages, &resident) != 2) resident = 0;+ std::fclose(f);+ }+ return static_cast<double>(resident) * static_cast<double>(sysconf(_SC_PAGESIZE)) / (1024.0 * 1024.0);+}+void show_speed() {static std::uint64_t start = 0, frames = 0;+ static double cpu_start = 0.0, gpu_start = 0.0;const std::uint64_t now = SDL_GetPerformanceCounter();- if (!start) start = now;+ if (!start) {+ start = now;+ cpu_start = process_cpu_seconds();+ gpu_start = ps2::gpu_busy_ms();+ }++frames;const double seconds = static_cast<double>(now - start) / static_cast<double>(SDL_GetPerformanceFrequency());if (seconds < 1.0) return;- char title[128];+ const double cpu = process_cpu_seconds(), gpu = ps2::gpu_busy_ms();+ char title[192];const double queued = g_audio ? SDL_GetQueuedAudioSize(g_audio) / static_cast<double>(kAudioBytesPerMs) : 0.0;- std::snprintf(title, sizeof title, "ps2-web-recomp %.1f fps audio %.0f ms", static_cast<double>(frames) / seconds, queued);+ std::snprintf(title, sizeof title, "ps2-web-recomp %.1f fps CPU %.0f%% GPU %.0f%% RAM %.0f MB audio %.0f ms", static_cast<double>(frames) / seconds,+ (cpu - cpu_start) / seconds * 100.0, (gpu - gpu_start) / (seconds * 10.0), resident_mb(), queued);SDL_SetWindowTitle(g_window, title);start = now;frames = 0;+ cpu_start = cpu;+ gpu_start = gpu;}void on_vblank() {diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hppindex abe81c9..03ef68a 100644--- a/runtime/include/ps2/system.hpp+++ b/runtime/include/ps2/system.hpp@@ -26,6 +26,7 @@ struct Options {bool trace_io = false;bool trace_threads = false;bool pal = true;+ bool rate_forced = false;std::uint64_t max_frames = 0;std::string misses_path;std::string disc_path;@@ -83,6 +84,8 @@ struct WindowTarget {bool attach_window(const WindowTarget &target);void resize_window(std::uint32_t width, std::uint32_t height);bool present_frame();+// GPU time spent on emulation so far, estimated from timestamp queries (0 when unsupported).+double gpu_busy_ms();void set_pad_buttons(std::uint16_t pressed);void set_pad_axis(int axis, std::uint8_t value);void set_audio_sink(std::function<void(const std::int16_t *samples, std::size_t frames)> sink);diff --git a/runtime/src/gs/gpu/blit.wgsl b/runtime/src/gs/gpu/blit.wgslindex 7582bf2..4ecbba5 100644--- a/runtime/src/gs/gpu/blit.wgsl+++ b/runtime/src/gs/gpu/blit.wgsl@@ -1,8 +1,12 @@struct Blit {width: u32,height: u32,+ current: u32,+ previous: u32,+ blend: u32,pad0: u32,pad1: u32,+ pad2: u32,}@group(0) @binding(0) var<storage, read> pixels: array<u32>;@@ -22,20 +26,28 @@ fn vs(@builtin(vertex_index) i: u32) -> VertexOut {return o;}-fn texel(x: i32, y: i32) -> vec4<f32> {+fn texel(base: u32, x: i32, y: i32) -> vec4<f32> {let cx = u32(clamp(x, 0, i32(blit.width) - 1));let cy = u32(clamp(y, 0, i32(blit.height) - 1));- return unpack4x8unorm(pixels[cy * blit.width + cx]);+ return unpack4x8unorm(pixels[base + cy * blit.width + cx]);+}++fn sample(base: u32, uv: vec2<f32>) -> vec4<f32> {+ let p = uv * vec2<f32>(f32(blit.width), f32(blit.height)) - 0.5;+ let origin = floor(p);+ let f = p - origin;+ let x = i32(origin.x);+ let y = i32(origin.y);+ let top = mix(texel(base, x, y), texel(base, x + 1, y), f.x);+ let bottom = mix(texel(base, x, y + 1), texel(base, x + 1, y + 1), f.x);+ return mix(top, bottom, f.y);}@fragmentfn fs(in: VertexOut) -> @location(0) vec4<f32> {- let p = in.uv * vec2<f32>(f32(blit.width), f32(blit.height)) - 0.5;- let base = floor(p);- let f = p - base;- let x = i32(base.x);- let y = i32(base.y);- let top = mix(texel(x, y), texel(x + 1, y), f.x);- let bottom = mix(texel(x, y + 1), texel(x + 1, y + 1), f.x);- return vec4<f32>(mix(top, bottom, f.y).rgb, 1.0);+ var c = sample(blit.current, in.uv);+ if (blit.blend != 0u) {+ c = (c + sample(blit.previous, in.uv)) * 0.5;+ }+ return vec4<f32>(c.rgb, 1.0);}diff --git a/runtime/src/gs/gpu/gpu.cpp b/runtime/src/gs/gpu/gpu.cppindex 3ce2e7f..fab23bd 100644--- a/runtime/src/gs/gpu/gpu.cpp+++ b/runtime/src/gs/gpu/gpu.cpp@@ -49,6 +49,15 @@ std::uint32_t g_surface_width = 0, g_surface_height = 0;WGPURenderPipeline g_blit = nullptr;WGPUBindGroup g_blit_group = nullptr;WGPUBuffer g_blit_params = nullptr;+std::uint32_t g_field = 0, g_last_width = 0, g_last_height = 0;+bool g_have_previous = false;+constexpr std::uint32_t kFieldWords = 2u << 20;++bool g_timestamps = false;+WGPUQuerySet g_queries = nullptr;+WGPUBuffer g_query_resolve = nullptr, g_query_read = nullptr;+bool g_query_pending = false, g_query_ready = false;+std::uint64_t g_measured_ns = 0, g_measured = 0, g_total_passes = 0;WGPUDevice g_device = nullptr;WGPUQueue g_queue = nullptr;WGPUBuffer g_vram = nullptr, g_tables = nullptr, g_params = nullptr, g_data = nullptr, g_clut = nullptr, g_scratch = nullptr, g_readback = nullptr;@@ -429,10 +438,31 @@ void submit(WGPUTextureView present_view = nullptr) {ensure_capacity();if (!g_arena.empty()) wgpuQueueWriteBuffer(g_queue, g_data, 0, g_arena.data(), g_arena.size() * 4);wgpuQueueWriteBuffer(g_queue, g_params, 0, g_param_records.data(), g_param_records.size() * kParamStride);+ if (g_query_ready) {+ const void *mapped = wgpuBufferGetConstMappedRange(g_query_read, 0, 16);+ if (mapped) {+ std::uint64_t t[2];+ std::memcpy(t, mapped, sizeof t);+ if (t[1] > t[0]) {+ g_measured_ns += t[1] - t[0];+ ++g_measured;+ }+ }+ wgpuBufferUnmap(g_query_read);+ g_query_ready = g_query_pending = false;+ }+ const bool measure = g_timestamps && !g_query_pending;WGPUCommandEncoder enc = wgpuDeviceCreateCommandEncoder(g_device, nullptr);- WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(enc, nullptr);+ WGPUPassTimestampWrites writes = WGPU_PASS_TIMESTAMP_WRITES_INIT;+ writes.querySet = g_queries;+ writes.beginningOfPassWriteIndex = 0;+ writes.endOfPassWriteIndex = 1;+ WGPUComputePassDescriptor cd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT;+ if (measure) cd.timestampWrites = &writes;+ WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(enc, &cd);Pipeline current = kPipelines;++g_submits;+ ++g_total_passes;for (const Command &c : g_commands) {++g_dispatches[c.pipeline];if (c.pipeline != current) {@@ -445,6 +475,10 @@ void submit(WGPUTextureView present_view = nullptr) {}wgpuComputePassEncoderEnd(pass);wgpuComputePassEncoderRelease(pass);+ if (measure) {+ wgpuCommandEncoderResolveQuerySet(enc, g_queries, 0, 2, g_query_resolve, 0);+ wgpuCommandEncoderCopyBufferToBuffer(enc, g_query_resolve, 0, g_query_read, 0, 16);+ }if (present_view) {WGPURenderPassColorAttachment color = WGPU_RENDER_PASS_COLOR_ATTACHMENT_INIT;color.view = present_view;@@ -468,6 +502,21 @@ void submit(WGPUTextureView present_view = nullptr) {wgpuQueueSubmit(g_queue, 1, &cmd);wgpuCommandBufferRelease(cmd);wgpuCommandEncoderRelease(enc);+ if (measure) {+ g_query_pending = true;+ WGPUBufferMapCallbackInfo cb = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT;+ cb.mode = WGPUCallbackMode_AllowProcessEvents;+ cb.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void *, void *) {+ if (status == WGPUMapAsyncStatus_Success) g_query_ready = true;+ else g_query_pending = false;+ };+ wgpuBufferMapAsync(g_query_read, WGPUMapMode_Read, 0, 16, cb);+ }+#ifdef __EMSCRIPTEN__+ wgpuInstanceProcessEvents(g_instance);+#else+ wgpuDevicePoll(g_device, false, nullptr);+#endifg_commands.clear();g_param_records.clear();g_arena.clear();@@ -601,6 +650,12 @@ bool init(Mode m) {limits.maxBufferSize = supported.maxBufferSize;WGPUDeviceDescriptor dd = WGPU_DEVICE_DESCRIPTOR_INIT;dd.requiredLimits = &limits;+ const WGPUFeatureName timestamp_feature = WGPUFeatureName_TimestampQuery;+ g_timestamps = wgpuAdapterHasFeature(adapter, WGPUFeatureName_TimestampQuery);+ if (g_timestamps) {+ dd.requiredFeatureCount = 1;+ dd.requiredFeatures = ×tamp_feature;+ }dd.uncapturedErrorCallbackInfo.callback = on_error;bool device_done = false;WGPURequestDeviceCallbackInfo dcb = WGPU_REQUEST_DEVICE_CALLBACK_INFO_INIT;@@ -626,6 +681,14 @@ bool init(Mode m) {g_clut = make_buffer(static_cast<std::uint64_t>(kClutSlots) * kClutEntries * 4, WGPUBufferUsage_Storage);g_scratch = make_buffer(kScratchBytes, WGPUBufferUsage_Storage | WGPUBufferUsage_CopySrc);g_readback = make_buffer(kScratchBytes, WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst);+ if (g_timestamps) {+ WGPUQuerySetDescriptor qd = WGPU_QUERY_SET_DESCRIPTOR_INIT;+ qd.type = WGPUQueryType_Timestamp;+ qd.count = 2;+ g_queries = wgpuDeviceCreateQuerySet(g_device, &qd);+ g_query_resolve = make_buffer(16, WGPUBufferUsage_QueryResolve | WGPUBufferUsage_CopySrc);+ g_query_read = make_buffer(16, WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst);+ }WGPUBindGroupLayoutEntry le[6] = {};const WGPUBufferBindingType types[6] = {WGPUBufferBindingType_Storage, WGPUBufferBindingType_ReadOnlyStorage, WGPUBufferBindingType_Uniform,@@ -953,8 +1016,9 @@ bool attach_surface(const SurfaceTarget &target) {break;}g_present_mode = WGPUPresentMode_Fifo;- for (std::size_t i = 0; i < caps.presentModeCount; ++i)- if (caps.presentModes[i] == WGPUPresentMode_Mailbox) g_present_mode = WGPUPresentMode_Mailbox;+ for (const WGPUPresentMode wanted : {WGPUPresentMode_Immediate, WGPUPresentMode_Mailbox})+ for (std::size_t i = 0; i < caps.presentModeCount; ++i)+ if (caps.presentModes[i] == wanted) g_present_mode = wanted;wgpuSurfaceCapabilitiesFreeMembers(caps);g_surface_width = target.width;g_surface_height = target.height;@@ -995,14 +1059,14 @@ bool attach_surface(const SurfaceTarget &target) {g_blit = wgpuDeviceCreateRenderPipeline(g_device, &rd);wgpuShaderModuleRelease(module);wgpuPipelineLayoutRelease(pipeline_layout);- g_blit_params = make_buffer(16, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);+ g_blit_params = make_buffer(32, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);WGPUBindGroupEntry be[2] = {WGPU_BIND_GROUP_ENTRY_INIT, WGPU_BIND_GROUP_ENTRY_INIT};be[0].binding = 0;be[0].buffer = g_scratch;be[0].size = WGPU_WHOLE_SIZE;be[1].binding = 1;be[1].buffer = g_blit_params;- be[1].size = 16;+ be[1].size = 32;WGPUBindGroupDescriptor bd = WGPU_BIND_GROUP_DESCRIPTOR_INIT;bd.layout = layout;bd.entryCount = 2;@@ -1024,10 +1088,17 @@ bool has_surface() { return g_surface != nullptr; }bool present(const DisplaySource &src) {if (!g_surface) return false;flush_all();- const std::uint32_t param = push_params({src.fbp, src.fbw, src.psm, src.dbx, src.dby, src.width, src.height, src.halved ? 1u : 0u});+ const std::uint32_t current = (g_field & 1u) * kFieldWords, previous = ((g_field + 1) & 1u) * kFieldWords;+ static const bool weave_off = std::getenv("PS2_NO_DEINTERLACE") != nullptr;+ const bool blend = src.halved && g_have_previous && g_last_width == src.width && g_last_height == src.height && !weave_off;+ const std::uint32_t param = push_params({src.fbp, src.fbw, src.psm, src.dbx, src.dby, src.width, src.height, src.halved ? 1u : 0u, current});g_commands.push_back({kDisplay, (src.width + 7) / 8, (src.height + 7) / 8, param});- const std::uint32_t size[4] = {src.width, src.height, 0, 0};- wgpuQueueWriteBuffer(g_queue, g_blit_params, 0, size, sizeof size);+ const std::uint32_t blit[8] = {src.width, src.height, current, previous, blend ? 1u : 0u, 0, 0, 0};+ wgpuQueueWriteBuffer(g_queue, g_blit_params, 0, blit, sizeof blit);+ ++g_field;+ g_have_previous = true;+ g_last_width = src.width;+ g_last_height = src.height;WGPUSurfaceTexture st = WGPU_SURFACE_TEXTURE_INIT;wgpuSurfaceGetCurrentTexture(g_surface, &st);if (st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal && st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) {@@ -1046,6 +1117,11 @@ bool present(const DisplaySource &src) {return true;}+double busy_ms() {+ if (!g_measured) return 0.0;+ return static_cast<double>(g_measured_ns) / static_cast<double>(g_measured) * static_cast<double>(g_total_passes) / 1e6;+}+bool display(const DisplaySource &src, std::vector<std::uint32_t> &rgba) {flush_all();const std::uint32_t param = push_params({src.fbp, src.fbw, src.psm, src.dbx, src.dby, src.width, src.height, src.halved ? 1u : 0u});diff --git a/runtime/src/gs/gpu/gpu.hpp b/runtime/src/gs/gpu/gpu.hppindex 498c520..fc31458 100644--- a/runtime/src/gs/gpu/gpu.hpp+++ b/runtime/src/gs/gpu/gpu.hpp@@ -37,6 +37,7 @@ bool attach_surface(const SurfaceTarget &target);void resize_surface(std::uint32_t width, std::uint32_t height);bool has_surface();bool present(const DisplaySource &src);+double busy_ms();void stats();}diff --git a/runtime/src/gs/gpu/gs.wgsl b/runtime/src/gs/gpu/gs.wgslindex 7aac5bb..0e1620a 100644--- a/runtime/src/gs/gpu/gs.wgsl+++ b/runtime/src/gs/gpu/gs.wgsl@@ -263,7 +263,7 @@ fn display(@builtin(global_invocation_id) gid: vec3<u32>) {if (psm == PSMCT16 || psm == PSMCT16S) {c = ((c & 0x1Fu) << 3u) | ((c & 0x3E0u) << 6u) | ((c & 0x7C00u) << 9u);}- scratch[gid.y * w + gid.x] = c | 0xFF000000u;+ scratch[prm(8u) + gid.y * w + gid.x] = c | 0xFF000000u;}struct Setup {diff --git a/runtime/src/gs/gs.cpp b/runtime/src/gs/gs.cppindex aeee2ba..dcaf6db 100644--- a/runtime/src/gs/gs.cpp+++ b/runtime/src/gs/gs.cpp@@ -675,6 +675,14 @@ void resize_window(std::uint32_t width, std::uint32_t height) {#endif}+double gpu_busy_ms() {+#ifdef PS2_GPU+ return gpu::busy_ms();+#else+ return 0.0;+#endif+}+bool present() {#ifdef PS2_GPUif (!gpu::has_surface()) return false;diff --git a/runtime/src/gs/gs.hpp b/runtime/src/gs/gs.hppindex d9712b6..d072e30 100644--- a/runtime/src/gs/gs.hpp+++ b/runtime/src/gs/gs.hpp@@ -59,6 +59,7 @@ bool display(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32bool 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();+double gpu_busy_ms();std::uint64_t primitives_drawn();void stats();diff --git a/runtime/src/hw.cpp b/runtime/src/hw.cppindex df8cca6..1d9de29 100644--- a/runtime/src/hw.cpp+++ b/runtime/src/hw.cpp@@ -164,6 +164,7 @@ void gs_set_crt(std::uint32_t interlace, std::uint32_t mode, std::uint32_t fieldg_crt[1] = mode;g_crt[2] = field;std::fprintf(stderr, "[gs] SetGsCrt interlace %u mode 0x%X field %u\n", interlace, mode, field);+ if (!g_options.rate_forced) g_options.pal = mode == 3u;}void dmac_raise(unsigned channel) {diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex b49bb51..cbbbf7f 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -277,6 +277,7 @@ 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(); }+double gpu_busy_ms() { return gs::gpu_busy_ms(); }void set_pad_buttons(std::uint16_t pressed) { iop::sio2::set_buttons(0, pressed); }void set_pad_axis(int axis, std::uint8_t value) { iop::sio2::set_axis(0, axis, value); }void set_audio_sink(std::function<void(const std::int16_t *, std::size_t)> sink) { iop::spu2::set_sink(std::move(sink)); }