PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Edge antialiasing in the web shell's blit shader
Riccardo Giorato39b6ac08cf95
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 20f54f1..15f054c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -103,7 +103,7 @@ if(PS2_GENERATED)endif()target_link_libraries(ps2web PRIVATE ps2game ps2runtime)target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sPTHREAD_POOL_SIZE=2 -sALLOW_TABLE_GROWTH=1 -lidbfs.js -sSTACK_SIZE=16777216 -sENVIRONMENT=web- -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_pad_connected,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreted+ -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_pad_connected,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreted,_ps2web_video_options-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 efae408..a8e0bfb 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -1,5 +1,6 @@#include "ps2/disc.hpp"#include "ps2/system.hpp"+#include "ps2/video.hpp"#include <emscripten.h>#include <emscripten/threading.h>@@ -341,6 +342,8 @@ extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_resize(int width, int height) {ps2::resize_window(static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height));}+extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_video_options(int flags) { ps2::set_video_options(static_cast<std::uint32_t>(flags)); }+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()); }@@ -408,6 +411,10 @@ int main(int argc, char **argv) {surface = ps2::attach_window(target);}copy = copy || (!surface && !no_surface);+ EM_ASM({+ Module.videoEffectsAvailable = !!$0;+ if (Module.refreshVideoControls) Module.refreshVideoControls();+ }, surface);std::fprintf(stderr, "[web] %s\n", surface ? "presenting through WebGPU" : copy ? "presenting through a 2D canvas copy" : "not presenting");ps2::start_render_thread();diff --git a/runtime/include/ps2/video.hpp b/runtime/include/ps2/video.hppnew file mode 100644index 0000000..f3366ad--- /dev/null+++ b/runtime/include/ps2/video.hpp@@ -0,0 +1,9 @@+#pragma once+#include <cstdint>++namespace ps2 {+// Display-only options, independent of emulated GS state and save states.+// bit 0: edge antialiasing.+void set_video_options(std::uint32_t options);+std::uint32_t video_options();+}diff --git a/runtime/src/gs/gpu/blit.wgsl b/runtime/src/gs/gpu/blit.wgslindex 2bc9939..ac992f6 100644--- a/runtime/src/gs/gpu/blit.wgsl+++ b/runtime/src/gs/gpu/blit.wgsl@@ -6,7 +6,7 @@ struct Blit {blend: u32,out_width: u32,out_height: u32,- pad: u32,+ options: u32,}@group(0) @binding(0) var<storage, read> pixels: array<u32>;@@ -48,11 +48,38 @@ fn sample(base: u32, uv: vec2<f32>) -> vec4<f32> {return mix(top, bottom, f.y);}+fn scene(uv: vec2<f32>) -> vec3<f32> {+ var c = sample(blit.current, uv).rgb;+ if (blit.blend != 0u) { c = (c + sample(blit.previous, uv).rgb) * 0.5; }+ return c;+}++fn luma(c: vec3<f32>) -> f32 { return dot(c, vec3<f32>(0.299, 0.587, 0.114)); }++fn edge_aa(uv: vec2<f32>, center: vec3<f32>) -> vec3<f32> {+ // Fast approximate edge AA, evaluated in image space. Flat regions return+ // unchanged, while edge direction controls subpixel reconstruction.+ let texel_step = 1.0 / vec2<f32>(f32(blit.width), f32(blit.height));+ let nw = luma(scene(uv + texel_step * vec2<f32>(-1.0, -1.0)));+ let ne = luma(scene(uv + texel_step * vec2<f32>(1.0, -1.0)));+ let sw = luma(scene(uv + texel_step * vec2<f32>(-1.0, 1.0)));+ let se = luma(scene(uv + texel_step * vec2<f32>(1.0, 1.0)));+ let m = luma(center);+ let low = min(m, min(min(nw, ne), min(sw, se)));+ let high = max(m, max(max(nw, ne), max(sw, se)));+ if (high - low < max(0.0312, high * 0.125)) { return center; }+ var direction = vec2<f32>(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se));+ let reduce = max((nw + ne + sw + se) * 0.03125, 0.0078125);+ direction = clamp(direction / (min(abs(direction.x), abs(direction.y)) + reduce), vec2<f32>(-8.0), vec2<f32>(8.0)) * texel_step;+ let a = 0.5 * (scene(uv - direction / 6.0) + scene(uv + direction / 6.0));+ let b = a * 0.5 + 0.25 * (scene(uv - direction * 0.5) + scene(uv + direction * 0.5));+ let lb = luma(b);+ return select(b, a, lb < low || lb > high);+}+@fragmentfn fs(in: VertexOut) -> @location(0) vec4<f32> {- 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);+ var c = scene(in.uv);+ if ((blit.options & 1u) != 0u) { c = edge_aa(in.uv, c); }+ return vec4<f32>(clamp(c, vec3<f32>(0.0), vec3<f32>(1.0)), 1.0);}diff --git a/runtime/src/gs/gpu/gpu.cpp b/runtime/src/gs/gpu/gpu.cppindex dc1f3b2..149cdf0 100644--- a/runtime/src/gs/gpu/gpu.cpp+++ b/runtime/src/gs/gpu/gpu.cpp@@ -1,5 +1,6 @@#include "gpu.hpp"#include "ps2/system.hpp"+#include "ps2/video.hpp"#include <webgpu/webgpu.h>#ifndef __EMSCRIPTEN__@@ -1747,7 +1748,7 @@ bool present(const DisplaySource &src) {const float sw = static_cast<float>(g_surface_width), sh = static_cast<float>(g_surface_height);const float aspect = g_options.widescreen ? 16.0f / 9.0f : 4.0f / 3.0f;const float vw = std::min(sw, sh * aspect), vh = vw / aspect;- const std::uint32_t blit[8] = {src.width * g_scale, src.height * g_scale, current, previous, blend ? 1u : 0u, static_cast<std::uint32_t>(vw), static_cast<std::uint32_t>(vh), 0};+ const std::uint32_t blit[8] = {src.width * g_scale, src.height * g_scale, current, previous, blend ? 1u : 0u, static_cast<std::uint32_t>(vw), static_cast<std::uint32_t>(vh), ps2::video_options()};wgpuQueueWriteBuffer(g_queue, g_blit_params, 0, blit, sizeof blit);++g_field;g_have_previous = true;diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex 76865f5..0e5bd3a 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -16,6 +16,7 @@#include "ps2/memory.hpp"#include "ps2/state.hpp"#include "ps2/system.hpp"+#include "ps2/video.hpp"#ifdef __EMSCRIPTEN__#include <emscripten.h>@@ -56,6 +57,7 @@ std::uint64_t g_frames = 0;std::uint64_t g_iop_synced = 0;bool g_state_request = false;bool g_resumed = false;+std::atomic<std::uint32_t> g_video_options{0};std::uint64_t next_event_time() {std::uint64_t t = UINT64_MAX;@@ -241,6 +243,9 @@ void halt(const std::string &reason) {bool halted() { return g_halted; }const std::string &halt_reason() { return g_halt_reason; }+void set_video_options(std::uint32_t options) { g_video_options.store(options, std::memory_order_relaxed); }+std::uint32_t video_options() { return g_video_options.load(std::memory_order_relaxed); }+namespace {constexpr char kStateMagic[8] = {'P', 'S', '2', 'S', 'T', 'A', 'T', 'E'};diff --git a/web/shell.html b/web/shell.htmlindex 41aa0ec..a9fde1f 100644--- a/web/shell.html+++ b/web/shell.html@@ -15,6 +15,7 @@#stats { font-variant-numeric: tabular-nums; color: #9ad; }select { background: #2a3a55; color: #fff; border: 0; padding: 5px 8px; border-radius: 4px; }button { background: #2a3a55; color: #fff; border: 0; padding: 6px 14px; border-radius: 4px; cursor: pointer; }+ #aa-label { display: flex; align-items: center; gap: 6px; color: #9ad; white-space: nowrap; }#overlay { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,.6); padding: 16px; }#panel { display: flex; flex-direction: column; align-items: center; gap: 14px; max-width: 520px; text-align: center; }#help { margin: 0; line-height: 1.5; color: #e8c37a; }@@ -116,6 +117,7 @@<option value="4:3">4:3</option><option value="16:9">16:9</option></select>+ <label id="aa-label" title="Smooth jagged edges, applied immediately"><input id="aa" type="checkbox" disabled> Smooth edges</label><button id="controls-toggle" type="button" hidden>Hide controls</button><button id="export-card" type="button" title="Download the memory card in slot 1 as a .ps2 file">Export card</button><button id="import-card" type="button" title="Put a .ps2 memory card file in slot 1">Import card</button>@@ -290,6 +292,22 @@ aspectSelect.addEventListener('change', () => {location.href = url.href;});+// Edge antialiasing is a display option, so it lives outside the save state+// and takes effect on the next presented frame.+const aaInput = document.getElementById('aa');+const aaLabel = document.getElementById('aa-label');+let aa = false;+try { aa = localStorage.getItem('ps2web-aa') === '1'; } catch (e) {}+aaInput.checked = aa;+function applyVideo() {+ if (Module._ps2web_video_options) Module._ps2web_video_options(aa ? 1 : 0);+}+aaInput.addEventListener('change', () => {+ aa = aaInput.checked;+ try { localStorage.setItem('ps2web-aa', aa ? '1' : '0'); } catch (e) {}+ applyVideo();+});+const controlsButton = document.getElementById('controls-toggle');let hideControls = false;try { hideControls = localStorage.getItem('ps2web-hide-controls') === '1'; } catch (e) {}@@ -581,6 +599,12 @@ var Module = {statusEl.textContent = 'Halted: ' + reason;statusEl.style.color = '#f66';},+ refreshVideoControls: () => {+ const available = Module.videoEffectsAvailable ?? (!!navigator.gpu && !Module.gpuHelp && !Module.presentCopy && !Module.noSurface);+ aaInput.disabled = !available;+ aaLabel.title = available ? 'Smooth jagged edges, applied immediately' : 'Antialiasing needs direct WebGPU presentation';+ applyVideo();+ },print: (text) => console.log(text),printErr: (text) => console.log(text),setStatus: (text) => {