diff --git a/.github/workflows/xenia-browser-bootstrap-fastlane.yml b/.github/workflows/xenia-browser-bootstrap-fastlane.yml index 4d494888..c0360592 100644 --- a/.github/workflows/xenia-browser-bootstrap-fastlane.yml +++ b/.github/workflows/xenia-browser-bootstrap-fastlane.yml @@ -34,6 +34,7 @@ on: - 'test-browser-thread-scheduler.mjs' - 'test-direct-call-sparse-window.mjs' - 'test-translation-window-consistency.mjs' + - 'test-xenos-predication.mjs' - 'test-hir-load-offset-addressing.mjs' - 'test-hir-cache-control.mjs' - 'test-hir-rotate-left.mjs' @@ -268,6 +269,9 @@ jobs: - name: Verify translations do not depend on decoder-window history run: timeout 90s node ./test-translation-window-consistency.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify PM4 type-3 predication on tiling bins + run: timeout 90s node ./test-xenos-predication.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify signed PPC LOAD_OFFSET effective addresses run: timeout 90s node ./test-hir-load-offset-addressing.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm diff --git a/.github/workflows/xenia-wasm32-bootstrap.yml b/.github/workflows/xenia-wasm32-bootstrap.yml index cca776c0..057d9ce6 100644 --- a/.github/workflows/xenia-wasm32-bootstrap.yml +++ b/.github/workflows/xenia-wasm32-bootstrap.yml @@ -21,6 +21,7 @@ on: - 'test-title-gpu-runtime.mjs' - 'test-direct-call-sparse-window.mjs' - 'test-translation-window-consistency.mjs' + - 'test-xenos-predication.mjs' - 'render360-title-gpu-traffic.mjs' - 'test-xenos-semantic-foundation.mjs' - 'test-xenos-title-state-foundation.mjs' @@ -191,6 +192,8 @@ jobs: run: node ./test-direct-call-sparse-window.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm - name: Verify translations do not depend on decoder-window history run: node ./test-translation-window-consistency.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify PM4 type-3 predication on tiling bins + run: node ./test-xenos-predication.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm - name: Verify locked foundations and XEX bring-up run: | node ./test-xenia-ppc-translation-probe.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm diff --git a/.gitignore b/.gitignore index bcfb06cc..9f8205b5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,21 @@ node_modules/ *.log build/ upstream/ +# Game data never goes in git (owner rule): discs, packages, decrypted images, captures, manifests +*.iso +*.xex +*.xcp +*.god +*.stfs +*.con +*.r360cap +*.gpucap +rexglue-manifest* +/games-local/ + +# iOS: personal signing values, build products +/ios/Signing.local.xcconfig +/ios/Render360.xcodeproj/ +/ios/build/ +*.ipa +/logs/ diff --git a/PROGRESS.md b/PROGRESS.md index c291264f..161be912 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -7,38 +7,189 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie HIR executor and guest JIT. File loading finishes (`db360.textures.cmp`, ~50 MB, is read in full); 7 title threads run. - CPU: guest JIT compiles Xenia HIR to WebAssembly. Headless speed is about - 180M guest instructions/s (6B instructions in ~62 s, down from 223 s). -- Deterministic headless runs (`run-title --deterministic 1000`): identical - flags give identical results up to at least 4B instructions. + 665M guest instructions/s over Banjo's first 30B instructions (see Step 1). +- Deterministic headless runs (`run-title --deterministic 1000`): two + identical runs match through 58.3B instructions (1098 checkpoints, same + frames, draws and GPU packets). Fixed: a JIT segment resumed after an + Asyncify rewind re-added its instruction count, which made the guest clock + depend on host timing. +- Infinite kernel waits with every thread blocked now let guest time pass + (up to 10 s) so timers and vblank can wake threads, instead of stopping as + a deadlock. - Shader path: Xenia SpirvShaderTranslator → Naga → WGSL. All shaders seen during loading compile in Chromium WebGPU (SwiftShader). -## Current blocker -At about 58B instructions the main thread blocks inside D3D `Swap` waiting -for a GPU timestamp. D3D's presentation watchdog thread then keeps -re-presenting the previous frame, and those replays rewrite older timestamps. -No new frame is presented after that (VdSwap stops at ~1540). Root cause not -yet confirmed: the open question is why the main thread's target timestamp -is never observed. Runs still diverge slightly past ~58B (kernel-call counts -differ between identical runs), which blocks exact replay of the stall. +## Fixed: Swap stall at ~58B instructions +Root cause: the command processor ignored PM4 type-3 predication. D3D +predicated tiling replays each frame's command buffer once per screen bin, +and packets meant for one bin (including D3D's GPU-to-CPU deferred callback +requests) ran in every pass. Each extra callback made D3D's worker thread +queue another frame, the ring backlog outgrew the vblank-paced swaps, and +the main thread waited forever for its frame. Ported Xenia's check +(`ExecutePacketType3`: skip predicated packets when `bin_select & bin_mask` +is 0, never run a predicated swap). + +After the fix (deterministic headless runs): +- 90B instructions: 2551 frames (VdSwap), was stuck at ~1542. +- 120B instructions: 3067 frames; the title polls the controller every + frame (XamInputGetState 4056 calls by 90B, was 20). +- Frame at 61B: the Rare logo intro renders (software renderer). + +## Verified: title screen, input and main menu +Headless deterministic run (`run-title --deterministic 1000`), software +renderer, controller input injected with `--press`: +- 61B instructions: Rare logo intro. +- 80B: title screen ("PRESS START TO PLAY") over a moving 3D flythrough. +- Start at 80B: the title asks "Gamer profile not online" (offline profile); + the player's answer is passed back (`--dialog-button 1` = "Continue + playing offline"; in the browser the page shows the dialog). +- 82B: main menu, Banjo's room, rendered in 3D. +- 85B: "Trial game" notice (the default license is trial, as in Xenia). +- 90B: "PRESS A TO PLAY THE GAME"; frames change every second and the run + reaches its instruction limit with no blocker. + +Fixed on the way (each with a kernel services test): +- XamShowMessageBoxUI (headless focused button, or the player's answer). +- XamUserCreateAchievementEnumerator (title XDBF via Xenia xdbf_utils). +- XexGetProcedureAddress (kernel export trampolines), + XamContentAggregateCreateEnumerator, XamGetPrivateEnumStructureFromHandle + (guest X_KENUMERATOR objects), XamTaskSchedule. +- A thread's exit left the kernel service status at "terminal" and the next + thread resuming mid-sleep returned it, ending the run. + +## Verified: in-game in Spiral Mountain +Same headless run, continued: A at "PRESS A TO PLAY THE GAME" starts the +opening cutscene (rainy night, "B SKIP"); B skips it, and by 108B the game +is in Spiral Mountain (first level) with the HUD (health honeycombs), the +"SPIRAL MOUNTAIN" title and in-game dialogue; frames keep changing to the +115B instruction limit (3268 frames presented). + +Two scheduler bugs blocked it (single host thread running all guest +threads as fibers): +- Least-run-first scheduling starved the busy main thread: a timer thread + looping Sleep(0) around a critical section kept winning, and the main + thread waited ~50B instructions for the lock. Lag is now bounded (8 + quanta), as CFS bounds it. +- The HIR interpreter polled for interrupts and preemption only at guest + calls. A function called once that loops waiting for another thread ran + 10B instructions without letting that thread run. It now polls every 4096 + instructions, as the guest JIT polls on backward branches. +Headless message-box answers are now given inside the call +(`--dialog-button`), so runs no longer depend on host timing. + +Known visual issue: Banjo's own model renders incompletely (small, +fragmented); the level, HUD and other characters render. + +## Verified: player control in gameplay +Continuing the same run: A clears the Bottles dialogue (116-120B), then the +left stick held forward (`--stick 122000:126000:0:1`) walks Banjo along the +path in Spiral Mountain: the camera follows him past Bottles (124B) and by +127B he has reached the boulder pit, which triggers the next dialogue. +Frames keep changing to the 127.5B instruction limit (3607 frames). + +## Step 1: CPU speed (in progress) +Benchmark: Banjo-Tooie, first 30B guest instructions headless +(`run-title --max-minstr 30000 --render-from-minstr 999999 --deterministic +1000`), same container, Node 22. MIPS = guest instructions per second. + +| Change | MIPS | Cache misses | +| --- | --- | --- | +| Baseline (start of step 1) | 274 | — | +| No per-call `PPCContext` zeroing | 355 | 19.6k | +| Native vector compares in the JIT | 347 | — | +| Flat executable-page generation table; guest function object only on a miss | 355 | 19.6k | +| Ring-buffer call/stack history (was a 32-entry shift per call); cached epilogue signature per tail target | 387 | 20.6k | +| Compiled-only tier: an evicted translation keeps its compiled code (when it holds no HIR pointers) and runs again without retranslating or recompiling | 503–543 | 2.7k | +| Small fast path for plain calls that hit the cache; interpreter kept out of the per-call entry; one read for `__restgprlr` register restores; cheap 64-bit key hash | 642 | 2.7k | +| Memo of cache lookups (99.9% hit; neutral); build at `-O3` instead of `-O2` | 663–671 | 2.7k | + +What the profile showed: 74.5M guest calls in 30B instructions. The +translation cache (192 MiB of HIR) holds ~1000 functions, fewer than one +frame touches, so per-frame functions were evicted and retranslated and +recompiled 100+ times each. The JIT's function table only grows, so every +recompile also leaked a module. The compiled-only tier fixes both. Only +0.11% of instructions are interpreted (interior entries and cold code). +The cache budget is now checked against real arena bytes (Xenia's `Arena` +chunks), not an estimate. Wasm memory at 30B: 668 MiB. + +Benchmark noise between identical runs is about ±4%. + +Next: cut the per-call path (JIT → resolver → cache → executor → JIT), which +is now the largest cost: 74.5M guest calls go through ~10 host frames each, +all instrumented by Asyncify for guest-thread fibers. + +## Step 2: WebGPU renderer (in progress) +A port of Xenia's Vulkan backend (docs/gpu/WEBGPU_BACKEND.md). + +- **Core side:** records a command stream. +- **Replay:** `render360-webgpu-backend.mjs` replays it into WebGPU. +- **Shaders:** Xenia's SPIR-V shader translator, converted to WGSL by Naga. +- **Vertex fetch:** read from a 512 MiB shared memory buffer. +- **Texture cache:** a port of `TextureCache`/`VulkanTextureCache`. Xenia's own texture load compute shaders do the untiling and format conversion. +- **Resolves:** the host render targets owning the tiles are dumped into an EDRAM buffer. Xenia's resolve copy shaders then write shared memory. + +Measured on a Banjo-Tooie main menu capture (2 frames; headless Chromium, SwiftShader): + +| Stage | Draws replayed | Validation errors | Result | +| --- | --- | --- | --- | +| Draw path, placeholder textures | 1390 | 0 | geometry only | +| Texture cache | 2400 | 0 | 144 textures loaded, menu art and text correct | + +The menu is drawn in screen tiles (predicated tiling) and assembled by +resolves, so the presented frame needs the resolve path. + +Opt-in in the browser: `?gpu=xenos` switches the page to the WebGPU play +path. The software renderer then does no work, and each frame presents the +swapped front buffer from the GPU. + +## Not yet +- Speed: reaching gameplay takes ~1 hour headless with the software + renderer; the browser needs the WebGPU renderer and faster CPU emulation + to be playable in real time. +- Audio: XMA decoding (Xenia uses FFmpeg's XMA/WMA Pro decoder). +- Banjo's model looks small and partly fragmented in some frames. ## Tests (latest build) -- Regression runner: 59 pass, 9 fail. The 9 failures are pre-existing +- Regression runner: 61 of 70 pass. The 9 failures are pre-existing foundation tests (fpu/vmx/wasm-backend probes, guest-control, translation probe) and are unchanged by recent work. -- Xenia PPC instruction suite with JIT forced: pass (1406 functions). -- Guest JIT differential test: pass (73 instructions). -- New: `test-translation-window-consistency.mjs` fails before the window fix - and passes after it. +- Xenia PPC instruction suite with JIT forced: pass (1398 tests, 1406 + functions compiled). +- Guest JIT differential test: pass (2920 cases, 73 instructions). +- `test-translation-window-consistency.mjs` fails before the window fix and + passes after it. +- `test-xenos-predication.mjs` fails before the predication fix and passes + after it. ## Not done yet -- Interactive gameplay: not reached. +- Interactive gameplay: reached and controllable headlessly; not yet at a + playable speed in the browser. - WebGPU real-time renderer: only the shader pipeline is proven; draws, render targets, textures and resolves are not implemented. Frames come from the CPU software renderer. - Audio: XMA decoding not implemented (XMA register window only). -## Next task -Make headless runs fully deterministic past 58B, then reproduce the Swap -stall with a watch on the fence word and dumps of the replayed indirect -buffers, and fix the earliest confirmed cause. +## Native iOS app on the iPhone 11 (2026-10-17) + +Native app (`ios/`, SwiftUI + Metal, core from `native/build-native.sh`), signed +with the free Personal Team, installed with `devicectl`; see `docs/IOS_APP.md`. +Interpreter only (no arm64 JIT backend exists yet). + +Measured, Banjo-Tooie (host clock, phone telemetry to `tools/telemetry-server.py`): + +| Device | Run | Guest instr. | Frames | MIPS | Memory used / free | Thermal | +| --- | --- | --- | --- | --- | --- | --- | +| iPhone 11 | 94 s, then stopped from the app | 867M | 92 (VdSwap, 1280x720) | 11-13 cool, 5.8 once "serious" | 532 MB / 1816 MB | serious | +| 2018 MBP (native run-title, `--deterministic 1000`) | 554 s | 5000M | 132 | 9.0 | – | – | + +- Entitlements on the signed app: increased-memory-limit granted (≈2.1 GB + available at start); extended-virtual-addressing is not available to a free team. +- JIT probe on the phone: not available (no StikDebug). +- Game FPS ≈ 1, emulation speed ≈ 1% of real time: the 30 FPS bar is far off. + Limit: CPU (interpreted PPC); gameplay (~127B instructions) is hours away. +- Fixed on the way: the play view booted the core twice; `MMIOHandler` null + lookup (wasm read zeros); ~20 r360_* exports truncated 64-bit pointers. + +Next: profile the native interpreter (9-13 MIPS is low even for an +interpreter), then an arm64 backend for JIT-enabled devices. Watch Dogs / +ReXGlue manifest not started. diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 043e90b8..67db7dbc 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -57,16 +57,18 @@ python3 "$ROOT/prepare-hir-stack-history-overlay.py" python3 "$ROOT/prepare-hir-tail-frame-overlay.py" python3 "$ROOT/prepare-hir-fiber-locals-overlay.py" python3 "$ROOT/prepare-hir-jit-overlay.py" +python3 "$ROOT/prepare-hir-hot-path-overlay.py" python3 "$ROOT/prepare-xenia-shader-interpreter-overlay.py" python3 "$ROOT/prepare-xenia-shader-translator-overlay.py" python3 "$ROOT/prepare-xenia-spirv-browser-overlay.py" python3 "$ROOT/prepare-wasm-fpu-overlay.py" python3 "$ROOT/prepare-wasm-backend-cfg-overlay.py" -# Optimization level for the browser CPU runtime. -O0 made the HIR executor, +# Optimization level for the browser CPU runtime (-O3: ~4% faster guest code +# than -O2 on Banjo-Tooie). -O0 made the HIR executor, # sparse memory and kernel services several times slower on phones. # Override with R360_OPT=-O0 when bisecting a suspected miscompile. -R360_OPT="${R360_OPT:--O2}" +R360_OPT="${R360_OPT:--O3}" case "$R360_OPT" in -O0|-O1|-O2|-O3|-Os|-Oz) ;; *) echo "ERROR: invalid R360_OPT=$R360_OPT" >&2; exit 2 ;; esac # Xenia ships Release builds with NDEBUG ("We rely on assert being compiled out # in NDEBUG", xenia/base/assert.h). Debug-only asserts fire on real retail code @@ -79,18 +81,7 @@ if [ -n "$LLVM_INCLUDE" ] && [ -d "$LLVM_INCLUDE" ]; then echo "LLVM headers: $LLVM_INCLUDE" fi -SOURCES=( - "third_party/fmt/src/format.cc" - "src/xenia/base/arena.cc" "src/xenia/base/cvar.cc" "src/xenia/base/utf8.cc" "src/xenia/base/filesystem_posix.cc" "src/xenia/base/memory.cc" "src/xenia/base/memory_posix.cc" "src/xenia/base/mapped_memory_posix.cc" "src/xenia/base/mutex.cc" "src/xenia/base/string.cc" "src/xenia/base/string_buffer.cc" - "src/xenia/memory.cc" "src/xenia/cpu/cpu_flags.cc" "src/xenia/cpu/mmio_handler.cc" "src/xenia/cpu/entry_table.cc" "src/xenia/cpu/module.cc" "src/xenia/cpu/stack_walker_posix.cc" "src/xenia/cpu/thread_state.cc" "src/xenia/cpu/processor.cc" "src/xenia/cpu/lzx.cc" - "src/xenia/cpu/backend/backend.cc" "src/xenia/cpu/backend/assembler.cc" "src/xenia/cpu/function.cc" "src/xenia/cpu/function_debug_info.cc" - "src/xenia/cpu/hir/opcodes.cc" "src/xenia/cpu/hir/block.cc" "src/xenia/cpu/hir/instr.cc" "src/xenia/cpu/hir/value.cc" "src/xenia/cpu/hir/hir_builder.cc" - "src/xenia/cpu/compiler/compiler.cc" "src/xenia/cpu/compiler/compiler_pass.cc" - "src/xenia/cpu/compiler/passes/conditional_group_pass.cc" "src/xenia/cpu/compiler/passes/conditional_group_subpass.cc" "src/xenia/cpu/compiler/passes/constant_propagation_pass.cc" "src/xenia/cpu/compiler/passes/context_promotion_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_simplification_pass.cc" "src/xenia/cpu/compiler/passes/data_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/dead_code_elimination_pass.cc" "src/xenia/cpu/compiler/passes/finalization_pass.cc" "src/xenia/cpu/compiler/passes/memory_sequence_combination_pass.cc" "src/xenia/cpu/compiler/passes/register_allocation_pass.cc" "src/xenia/cpu/compiler/passes/simplification_pass.cc" "src/xenia/cpu/compiler/passes/validation_pass.cc" "src/xenia/cpu/compiler/passes/value_reduction_pass.cc" - "src/xenia/cpu/ppc/ppc_context.cc" "src/xenia/cpu/ppc/ppc_opcode_table_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_lookup_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm.cc" "src/xenia/cpu/ppc/ppc_opcode_info.cc" "src/xenia/cpu/ppc/ppc_emit_alu.cc" "src/xenia/cpu/ppc/ppc_emit_control.cc" "src/xenia/cpu/ppc/ppc_emit_memory.cc" "src/xenia/cpu/ppc/ppc_emit_fpu.cc" "src/xenia/cpu/ppc/ppc_emit_altivec.cc" "src/xenia/cpu/ppc/ppc_scanner.cc" "src/xenia/cpu/ppc/ppc_hir_builder.cc" "src/xenia/cpu/ppc/ppc_translator.cc" "src/xenia/cpu/ppc/ppc_frontend.cc" - "src/xenia/gpu/gpu_flags.cc" "src/xenia/gpu/register_file.cc" "src/xenia/gpu/ucode.cc" "src/xenia/gpu/shader.cc" "src/xenia/gpu/shader_translator.cc" "src/xenia/gpu/shader_translator_disasm.cc" "src/xenia/gpu/shader_interpreter.cc" "src/xenia/gpu/draw_util.cc" "src/xenia/gpu/registers.cc" "src/xenia/gpu/xenos.cc" "src/xenia/gpu/texture_util.cc" "src/xenia/gpu/texture_info.cc" "src/xenia/gpu/texture_info_formats.cc" "src/xenia/ui/graphics_util.cc" "src/xenia/gpu/spirv_builder.cc" "src/xenia/gpu/spirv_shader.cc" "src/xenia/gpu/spirv_shader_translator.cc" - "third_party/glslang/SPIRV/SpvBuilder.cpp" -) +source "$ROOT/xenia-ppc-sources.sh" classify_failure() { local log="$1" @@ -168,55 +159,7 @@ queue_c() { } phase "Compiling wasm32 source matrix with $JOBS parallel job(s)" -for rel in "${SOURCES[@]}"; do - case "$rel" in - "src/xenia/base/arena.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/arena.cc" ;; - "src/xenia/base/cvar.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/cvar.cc" ;; - "src/xenia/base/utf8.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/utf8.cc" ;; - "src/xenia/memory.cc") queue_cpp "$rel" "$OVERLAY/xenia/memory.cc" ;; - "src/xenia/cpu/mmio_handler.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/mmio_handler.cc" ;; - "src/xenia/cpu/processor.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/processor.cc" ;; - "src/xenia/cpu/hir/value.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/hir/value.cc" ;; - "src/xenia/cpu/ppc/ppc_scanner.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_scanner.cc" ;; - "src/xenia/cpu/ppc/ppc_translator.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_translator.cc" ;; - "src/xenia/gpu/draw_util.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/draw_util.cc" ;; - "src/xenia/gpu/shader_translator.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/shader_translator.cc" ;; - "src/xenia/gpu/shader_interpreter.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/shader_interpreter.cc" ;; - *) queue_cpp "$rel" "$XENIA/$rel" ;; - esac -done - -queue_c "third_party/mspack/lzxd.c" "$XENIA/third_party/mspack/lzxd.c" -queue_c "third_party/crypto/rijndael-alg-fst.c" "$XENIA/third_party/crypto/rijndael-alg-fst.c" -queue_cpp "render360/browser_logging.cpp" "$ROOT/src/xenia_web_bootstrap/browser_logging.cpp" -queue_cpp "render360/browser_threading_sleep.cpp" "$ROOT/src/xenia_web_bootstrap/browser_threading_sleep.cpp" -queue_cpp "render360/hir_correctness_executor.cpp" "$OVERLAY/render360/hir_correctness_executor_vmx.cpp" -queue_cpp "render360/kernel_import_probe.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_import_probe.cpp" -queue_cpp "render360/kernel_runtime_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_runtime_foundation.cpp" -queue_cpp "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibers.cpp" -queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" -queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" -queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" -queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" -queue_cpp "render360/xenos_gpu_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp" -queue_cpp "render360/xenos_shader_interpreter_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp" -queue_cpp "render360/xenos_spirv_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp" -queue_cpp "render360/wasm_backend_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_probe.cpp" -queue_cpp "render360/wasm_backend_cfg_probe.cpp" "$OVERLAY/render360/wasm_backend_cfg_probe.cpp" -queue_cpp "render360/wasm_backend_memory_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_memory_probe.cpp" -queue_cpp "render360/wasm_backend_call_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_call_probe.cpp" -queue_cpp "render360/wasm_backend_fpu_probe.cpp" "$OVERLAY/render360/wasm_backend_fpu_probe_v2.cpp" -queue_cpp "render360/wasm_backend_vmx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_vmx_probe.cpp" -queue_cpp "render360/sparse_guest_memory.cpp" "$ROOT/src/xenia_web_bootstrap/sparse_guest_memory.cpp" -queue_cpp "render360/xex_guest_mapper.cpp" "$ROOT/src/xenia_web_bootstrap/xex_guest_mapper.cpp" -queue_cpp "render360/xex_pe_image.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_image.cpp" -queue_cpp "render360/xex_pe_guest_loader.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp" -queue_cpp "render360/xex_title_handoff.cpp" "$ROOT/src/xenia_web_bootstrap/xex_title_handoff.cpp" -queue_cpp "render360/xex_lzx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_lzx_probe.cpp" -queue_cpp "render360/xex_crypto_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_crypto_probe.cpp" -queue_cpp "render360/probe_backend.cpp" "$ROOT/src/xenia_web_bootstrap/probe_backend.cpp" -queue_cpp "render360/ppc_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_translation_probe.cpp" -queue_cpp "render360/ppc_context_abi_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_context_abi_probe.cpp" +r360_for_each_source queue_cpp queue_c wait || true @@ -229,7 +172,8 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 29 )) +r360_source_count +expected=$R360_SOURCE_COUNT actual=$(( passed + failed )) echo diff --git a/docs/IOS_APP.md b/docs/IOS_APP.md new file mode 100644 index 00000000..488cafe6 --- /dev/null +++ b/docs/IOS_APP.md @@ -0,0 +1,138 @@ +# Render360 native iOS app + +Native SwiftUI + Metal app for the iPhone. The emulator core is the same C++ +as the browser build (no WKWebView), compiled for arm64 by +`native/build-native.sh`. Status and measured numbers: `PROGRESS.md`. + +## What it does today + +- Boots titles through the same boot path as the web player + (`native/src/native_title.cpp`, a port of `handoffDefaultXex`). +- CPU: **HIR interpreter only.** There is no arm64 JIT backend yet (Xenia only + has x64). The app probes at startup whether the process may run JIT code + (sideloaded build with StikDebug) and reports it; nothing uses it yet. +- Graphics: guest frames come from the core's software renderer (the VdSwap + frontbuffer, as the browser's Canvas2D path) and are drawn with Metal, + capped at 30 FPS. The Xenos GPU backend (WebGPU recorder) is not ported to + Metal/wgpu yet, so ASTC/16F texture handling does not apply yet. +- Input: MFi / Xbox / PlayStation controllers (GameController.framework) and + on-screen touch controls. +- Overlay and telemetry use the web overlay's definitions + (`ios/Render360/PerfStats.swift` ports `render360-perf-overlay.mjs`). + +## Build + +Everything is quoted because the drive name has a space. Xcode tools are run +through a symlink (`~/r360`), because some Xcode steps break on the space. + +```sh +ln -sfn "/Volumes/EXTERNAL HD/Render360" ~/r360 +cd ~/r360 +bash fetch-xenia.sh # pinned Xenia, once +R360_NATIVE_TARGET=ios-arm64 bash native/build-native.sh # core: build/native-ios-arm64/librender360core.a (~12 min) +bash native/build-native.sh # optional: macOS core + build/native-macos-x86_64/run-title +``` + +`R360_SKIP_OVERLAYS=1` reuses the overlay sources and only recompiles changed +units. Generate and build the app (XcodeGen 2.44.1 from its GitHub release): + +```sh +cd ~/r360/ios +xcodegen generate +export TMPDIR=~/r360/build/xc/tmp; mkdir -p "$TMPDIR" # the internal disk is nearly full +xcodebuild -project Render360.xcodeproj -scheme Render360 -configuration Release \ + -destination 'id=' -derivedDataPath ~/r360/build/xc/dd \ + CLANG_MODULE_CACHE_PATH=~/r360/build/xc/mc \ + -allowProvisioningUpdates -allowProvisioningDeviceRegistration build +``` + +Find the UDID with `xcrun devicectl list devices --json-output /tmp/d.json` +(`hardwareProperties.udid`). + +## Signing with a free Apple ID + +1. Xcode > Settings > Accounts: add your Apple ID (a "Personal Team"). +2. Create `ios/Signing.local.xcconfig` (git-ignored): + ``` + DEVELOPMENT_TEAM = + R360_BUNDLE_ID = com.render360. + ``` +3. Build as above; `-allowProvisioningUpdates` creates the profile. + +Entitlements, checked on the signed app with `codesign -d --entitlements :-`: + +| Entitlement | Free team | +| --- | --- | +| `com.apple.developer.kernel.increased-memory-limit` | **granted** (the phone reports ~2.1 GB available) | +| `com.apple.developer.kernel.extended-virtual-addressing` | not in free-team profiles (not requested; needs the paid program) | + +## Install and the 7-day re-sign + +```sh +xcrun devicectl device install app --device ~/r360/build/xc/dd/Build/Products/Release-iphoneos/Render360.app +``` + +First launch: Settings > General > VPN & Device Management > trust the +developer; Developer Mode must be on. Free-team builds expire after 7 days. +The app reads `embedded.mobileprovision` and warns 2 days before. To renew, +rebuild and reinstall: installing over the app keeps its games and data. +**Never delete the app to reinstall** – that deletes the imported games. + +## Importing games (never put game files in git) + +Games live in the app's `Documents/Games//`, every file excluded from +iCloud backup. A multi-disc title (Watch Dogs) is one entry with several discs. + +- **Files app:** Import game > Choose files… (select all discs together), or + "Add a disc to an existing game". +- **AirDrop:** AirDrop the file and choose Render360. +- **From the Mac over Wi-Fi** (resumable): + ```sh + python3 tools/serve-games.py "/Volumes/EXTERNAL HD/Render360-games" --token + ``` + In the app: Import game > From my Mac > the printed address and token. + A game is a sub-folder (its files are its discs) or a single file. Downloads + write `.part` and continue with HTTP Range after a drop. +- **Cable (developer):** + ```sh + xcrun devicectl device copy to --device --domain-type appDataContainer \ + --domain-identifier --source --destination Documents/Games// + ``` + plus a `game.json` (`{"id","title","discs":[file names]}`) in the same folder. + +## Telemetry and diagnostics + +```sh +python3 tools/telemetry-server.py # port 8361; logs in logs/phone/ (git-ignored) +open http://localhost:8361/status +``` + +In the app: Settings > Telemetry to the Mac > `http://:8361`. The phone +POSTs one line per second: game FPS, average, 1% low, stutters, emulation +speed %, MIPS, interpreted %, memory used/free/lowest, thermal state, battery, +JIT availability, signing days left. `/summary.json` gives per-session +averages. iOS asks once for Local Network permission. + +Crash breadcrumbs: `Documents/Diagnostics/breadcrumbs.log` (fsynced lines; +`running.flag` detects a crash or jetsam kill). After such a run the app shows +the last lines and sends them to the Mac (`logs/phone/crash_*.txt`). Pull them: + +```sh +xcrun devicectl device copy from --device --domain-type appDataContainer \ + --domain-identifier --source Documents/Diagnostics/breadcrumbs.log --destination bc.log +``` + +Test hooks for unattended runs: +`xcrun devicectl device process launch --device --terminate-existing -e '{"R360_AUTOPLAY":"","R360_TELEMETRY":"http://:8361"}' ` + +## Known limits + +- **Speed:** interpreter only, ~11 MIPS on the iPhone 11 (~9 on the 2018 MBP). + Real time needs ~1000 MIPS, so games run about 100× too slow; Banjo-Tooie + needs ~127B instructions to reach gameplay (hours at this speed). +- Stopping a game exits the app (guest threads of a stopped run cannot be + unwound); the next launch starts clean. +- No audio (XMA decoding not implemented, as in the browser). +- Disc swap: the app can remount another disc (`r360_native_select_disc`), but + nothing triggers it yet when a title asks for the next disc. +- No Xenos GPU backend on Metal yet; frames are the software renderer's. diff --git a/docs/MAC_AGENT_PROMPT.md b/docs/MAC_AGENT_PROMPT.md new file mode 100644 index 00000000..d5f6a6d2 --- /dev/null +++ b/docs/MAC_AGENT_PROMPT.md @@ -0,0 +1,287 @@ +# Prompt for an AI agent working on the owner's MacBook + +Copy everything below the line into the agent. + +--- + +You are working on **Render360**, a Xbox 360 emulator that runs in the browser. +It is a port of the Xenia emulator to WebAssembly. You have access to the +owner's **2018 Intel MacBook Pro** and to their paired **iPhone 11**. + +The project lives on an external drive whose name contains a space. Always +quote paths: `"/Volumes/EXTERNAL HD/..."`. Find the clone with +`ls "/Volumes/EXTERNAL HD"`. If none is there, clone it there: + +``` +git clone https://github.com/matthewcodergamer/Render360 "/Volumes/EXTERNAL HD/Render360" +git -C "/Volumes/EXTERNAL HD/Render360" checkout claude/xbox-360-emulator-optimization-74g72w +``` + +Work on branch **`claude/xbox-360-emulator-optimization-74g72w`** (open PR #19). +- Commit small, focused changes with clear messages. +- Push with `git push -u origin claude/xbox-360-emulator-optimization-74g72w`. +- Do not force-push. Do not rewrite history. + +## Hard rules (from the owner, non-negotiable) + +1. **Game files never go into any Git repository or GitHub release.** That + covers ISOs, STFS/CON packages, decrypted XEX, extracted assets, GPU + captures, and game-derived shaders or recompiled code. They live only on + the Mac or the phone. + - Add new game-file extensions to `.gitignore` before working with them. + - Check `git status` before every commit. +2. **The owner's own legally dumped games only.** +3. **Keep the HIR interpreter** as the correctness fallback; never delete it. +4. **Port Xenia, don't imitate it.** When Xenia has code for something, + reuse or port that code, citing the Xenia file and function in a comment. +5. **Fail closed, and report honest numbers.** + - Never claim something works without having run it. + - Report measured FPS, speed and memory, plus what is limiting them. + - Don't hide a weak device behind a strong one: report each device + separately. +6. Update `PROGRESS.md` and the PR description after each step. + +## First task: lock down the test-games repository (do this before anything else) + +`matthewcodergamer/render360-test-games` is **public**, and release `v1` +holds a Banjo-Tooie package (asset `ABB9CAB336175357D09F2D922735D23C62F90DDD58`). +The cloud agent was refused repository-settings writes. Using the owner's own +`gh` login on the Mac: + +``` +gh repo edit matthewcodergamer/render360-test-games --visibility private --accept-visibility-change-consequences +gh release view v1 -R matthewcodergamer/render360-test-games +gh release delete-asset v1 ABB9CAB336175357D09F2D922735D23C62F90DDD58 -R matthewcodergamer/render360-test-games --yes # only after the owner has a local copy +``` + +Keep a local copy of the package on the Mac first. Ask the owner before +deleting the asset. + +## How the project works today + +### Core (C++ compiled to WebAssembly) + +Directory `src/xenia_web_bootstrap/`, plus Xenia sources from +`upstream/xenia` patched by `prepare-*.py` overlay scripts at build time. + +| File | What it does | +| --- | --- | +| `probe_backend.cpp` | Guest call resolver, translation cache (HIR builders + a compiled-only tier), tail-call trampoline (`TranslateNestedGuestAddress`) | +| `hir_correctness_executor.cpp` | The HIR **interpreter** (Xenia's PPC frontend → HIR → interpreted) | +| `hir_wasm_jit.cpp` + `hir_jit_glue.inc` | HIR → **WebAssembly JIT** (segment dispatcher, OSR, polls). Wasm-only | +| `guest_fibers.cpp` | Guest threads as cooperative fibers switched with **Emscripten Asyncify** (`#if defined(__wasm__)`). Wasm-only; the native build has no thread switching at all | +| `sparse_guest_memory.cpp` | Guest memory: page table, write watches for GPU invalidation | +| `kernel_xboxkrnl_services.cpp` | xboxkrnl/XAM kernel services ported from Xenia; interrupts, vblank, XMA register window (no audio decode yet) | +| `xenos_gpu_foundation.cpp` | PM4 command processor (ring buffer, draws, swaps) | +| `xenos_soft_renderer.cpp` | CPU software renderer (the frames the web player shows today) | +| `webgpu_backend.cpp/.h`, `webgpu_draws.cpp`, `webgpu_textures.cpp` | **WebGPU recorder**: a port of Xenia's Vulkan backend that records a command stream (ops 1–12 in `webgpu_backend.h`). Shaders come from Xenia's SPIR-V translator; Xenia's texture cache and its own `texture_load_*` / `resolve_*` compute shaders are used | + +### JavaScript + +| File | What it does | +| --- | --- | +| `render360-webgpu-backend.mjs` | Replays the recorded stream into WebGPU. Naga (`render360_spirv_wgsl*`) converts SPIR-V to WGSL | +| `render360-webgpu-play.mjs` | Browser play path, opt-in with `?gpu=xenos` | +| `render360-perf-overlay.mjs` | The 30 FPS bar overlay. Backtick toggles it; **L** downloads a JSON log with device info | +| `tools/run-title.mjs` | Headless runner (Node 22). The JSON report has a `perf` block | + +### Build + +`build-xenia-ppc-bootstrap.sh` then `link-xenia-ppc-bootstrap.sh`, with +emsdk sourced. Run `git -C upstream/xenia checkout -- .` before building, +because the overlays patch that tree. The output is +`build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm` (~3.9 MB). + +### Tests + +The tests are the `test-*.mjs` files at the repo root. + +| Test | Covers | +| --- | --- | +| `test-perf-overlay.mjs` | Overlay statistics | +| `test-webgpu-shared-memory*.mjs` | WebGPU shared memory | +| `test-webgpu-replay-capture-browser.mjs` | Replays a **local** GPU capture in headless Chromium; skips without one | +| `test-guest-jit-osr.mjs` | JIT OSR | + +Plus the PPC instruction suite and the JIT differential test. + +### Status (honest) + +- **Banjo-Tooie gameplay:** reaches controllable gameplay headlessly. +- **Wasm CPU:** ~660 guest MIPS on a fast x86 core. At the headless runner's + deterministic clock (1 ns per instruction) real time is ~1000 MIPS, so the + wasm CPU runs at roughly 65% of real time before graphics. +- **WebGPU renderer:** renders a correct Banjo main menu frame from a capture, + through draws, textures, EDRAM resolves and clears. +- **Known renderer bug:** the resolved image is shifted 32 px right. Suspects + are the window offset / resolve rectangle handling in `webgpu_draws.cpp` + `Resolve()` and the EDRAM dump in `render360-webgpu-backend.mjs` `dumpEdram()`. +- **Known CPU bug:** at ~105B instructions the game stalls when two functions + are JIT-compiled: `0x822398D8` (a table fixed-point loop) and `0x8227E6A0` + (a thunk ending in a direct tail call `call.2`). The prime suspect is + compiled tail calls interacting with the tail-call trampoline. The + interpreter is correct. +- **Audio:** none (XMA decoding not implemented). + +## Your task: Render360 as a native iOS app on the iPhone 11 + +**Why:** Safari kills the web tab for memory, so the browser version cannot +run Banjo on the phone. + +### Step 0: measure what exists, on the Mac's own browsers (one hour, do it first) + +Serve the repo locally, e.g. `python3 -m http.server 8080` from the repo +root; WebGPU needs localhost or https. Then open the player with +`?gpu=xenos` in Chrome and in Safari, load Banjo, and play for 5 minutes. +Press **L** to save the perf log. Report game FPS, 1% low, emulation speed +and interpreted %, for each browser separately. + +### Step 1: native core (macOS first, then iOS arm64) + +1. Add a CMake build, e.g. `native/CMakeLists.txt`, that compiles the same + source set as `build-xenia-ppc-bootstrap.sh`, including the overlays + produced by the `prepare-*.py` scripts, with clang for the host. Mirror + the shell script's source list exactly. Don't hand-pick files. +2. Provide native replacements for the wasm-only pieces: + - **Guest fibers:** replace Asyncify with one pthread per guest thread and + a baton (mutex + condition variable), so exactly one guest thread runs + at a time. That preserves today's cooperative scheduling and + determinism. Keep the same API as `guest_fibers.h`. + `swapcontext` is unavailable on iOS; don't use it. + - **JIT:** compile `hir_wasm_jit.cpp` out (stub `JitEnabled()` to false). + Native runs are **interpreter only** at first. + - **WASI / `export_name` / host imports:** route the `r360_*` exports to a + small C API header, e.g. `native/render360_core.h`, that the app calls. +3. Native headless runner (`native/run-title`): load a STFS/XEX from a path, + run N billion instructions, write the same JSON report as + `tools/run-title.mjs`. Verify on the Mac that Banjo reaches the same + swap counts as the wasm build at the same instruction counts + (deterministic mode). Report native MIPS, interpreter only, on the Mac. + +### Step 2: the iOS app shell (`ios/`) + +**Project and build** +- SwiftUI app with the core linked as a static library. +- Generate the Xcode project with XcodeGen (`ios/project.yml`) so it's + reviewable in git. +- **No WKWebView for the emulator.** +- If the Mac's Xcode can't build for the iPhone, add a GitHub Actions + workflow on `macos-latest`. It builds the unsigned app and uploads it as an + artifact: never game files, never signed builds with credentials. +- Signing happens on the Mac with the owner's **free Apple ID**: + - Builds expire after 7 days. + - Add an in-app reminder showing the days left, read from + `embedded.mobileprovision`. + +**Entitlements** +- `com.apple.developer.kernel.increased-memory-limit` and + `com.apple.developer.kernel.extended-virtual-addressing`. +- **Verify which ones a free (non-paid) account can actually use.** + Extended Virtual Addressing may need the paid program. Report what works; + don't assume. + +**Graphics** + +| Option | How | Tradeoff | +| --- | --- | --- | +| **(a) wgpu-native**, preferred to start | Port `render360-webgpu-backend.mjs` to C++ against wgpu-native's `webgpu.h` | wgpu accepts SPIR-V directly, so Xenia's shaders need no Naga step, and push constants are a native wgpu feature, so Xenia's load and resolve shaders can use them unmodified. The renderer logic stays shared with the web version | +| **(b) Metal directly** | Reuse the owner's GTA V port lessons | Faster at the end, more work | + +Whichever you choose, carry over: +- **ASTC** for BC textures, with a self-test at startup that compares against + a decoded reference. Today's web path decompresses BC to RGBA8, which uses + 4–8× the memory. +- **RG/RGBA16F** for 32-bit float textures that must filter. +- A **memory guard**: watch `os_proc_available_memory()`, shrink caches + before iOS kills the app, and log it. + +**CPU and JIT** +- Ship the interpreter, plus a **persistent translation cache** on disk: + keep translated HIR or a lighter form so a function is translated once, + ever. +- Add an optional JIT mode that turns on only when the process can map + executable memory: + - Detect it at startup by trying `mmap` with `MAP_JIT` / a dual mapping + and executing a tiny stub. + - It works with StikDebug on a sideloaded build. +- **No arm64 JIT backend exists yet** (Xenia only has x64). Treat the JIT + mode as a later project and report the interpreter speed honestly. + +**Telemetry, overlay and controls** (as in the owner's GTA port) +- An HTTP `/status` endpoint on the phone that the Mac can poll over Wi-Fi. + JSON: FPS, emulation speed, MIPS, interpreted %, memory in use, available + memory, thermal state. +- Crash breadcrumbs written to a file that survives restarts. +- A **30 FPS cap**. +- MFi / Xbox / PlayStation controllers via `GameController.framework`. +- On-screen touch controls. +- Same overlay fields as `render360-perf-overlay.mjs`. + +### Step 3: game import (never in any repo) + +- An in-app **Import game** with three sources: + - the Files app (document picker); + - AirDrop (open-in); + - a download from the Mac over Wi-Fi. +- Write `tools/serve-games.py` for the Mac side. It serves a folder over + HTTP with **Range** support, and the app resumes interrupted downloads. +- Store games in the app's `Documents/Games/`, with + `isExcludedFromBackup = true` on each file so they are excluded from + iCloud backup. +- **Multi-disc** titles: group discs under one game entry and let the core's + VFS swap discs. Watch Dogs has two discs. + +### Step 4: tests on the iPhone 11 (report each separately) + +1. **Banjo-Tooie:** boot to gameplay. Report: + - FPS, 1% low, emulation speed %, interpreted %; + - peak memory and available memory; + - thermal state after 10 minutes; + - time to reach gameplay. + + If it isn't real time (expected with interpreter only), say by how much + and what limits it: CPU, GPU or memory. +2. **Watch Dogs, record mode:** boot as far as it goes, recording every guest + function entry and indirect-branch target. Export a **ReXGlue manifest** + for the owner's native recompile. + - Check ReXGlue's actual expected input format first. Don't invent one. + - The manifest is game-derived: keep it on the Mac. Do not commit it. + +### Step 5: documentation + +Write `docs/IOS_APP.md` covering: +- building, on the Mac and in CI; +- signing with a free Apple ID; +- installing on the paired iPhone; +- the 7-day re-sign; +- importing games; +- the telemetry endpoint; +- known limits. + +Commit everything except game data and push to the branch above. + +## The 30 FPS bar (definition of done for any game) + +A game counts as supported only when it holds this bar: + +| Requirement | Threshold | +| --- | --- | +| Average FPS | ≥ 30 | +| 1% low | ≥ 25 | +| Emulation speed | ≥ 100% | +| Stutters (frames over 50 ms) | no more than one per minute | +| Audio | in sync | + +- Devices, reported separately: desktop Chrome, the 2018 MBP, the iPhone 11. +- Ladder: Banjo-Tooie → another Arcade title → a light retail game → a + mid-weight game → GTA IV → Watch Dogs. +- Move to the next game only after the current one passes on desktop. + +## How to report back + +After each step, add to `PROGRESS.md`: +- what you ran (exact commands); +- the measured numbers; +- what broke, and what you'd do next. + +Never report a step as done that you haven't run on the real device. diff --git a/docs/gpu/WEBGPU_BACKEND.md b/docs/gpu/WEBGPU_BACKEND.md new file mode 100644 index 00000000..0d41e297 --- /dev/null +++ b/docs/gpu/WEBGPU_BACKEND.md @@ -0,0 +1,78 @@ +# WebGPU Xenos backend (step 2) + +Goal: render titles on the GPU through WebGPU, as a port of Xenia's Vulkan +backend (`src/xenia/gpu/vulkan`), with no CPU drawing in the play path. The +software renderer (`xenos_soft_renderer.cpp`) stays as the reference that +GPU frames are compared against. + +## What Xenia's Vulkan backend does, and the WebGPU equivalent + +| Xenia (Vulkan) | Role | Render360 (WebGPU) | +| --- | --- | --- | +| `SharedMemory` + `VulkanSharedMemory` | 512 MiB GPU copy of guest physical memory; ranges a draw needs are uploaded on demand; CPU writes invalidate pages through physical-memory access watches | Same base class compiled to wasm. Watches: a per-page watch bit next to the executable-alias count in the sparse page table, so JIT inline stores (which already check that field) take the slow path and invalidate. Uploads go through a staging ring and `copyBufferToBuffer` in command order. | +| `PrimitiveProcessor` + `VulkanPrimitiveProcessor` | Index buffers, primitive type conversion (fans, quads, rectangles), 32-bit index endian handling | Same base class; converted index data is uploaded to a GPU buffer. | +| `SpirvShaderTranslator` + `VulkanPipelineCache` | Xenos microcode → SPIR-V; pipelines keyed by shaders and render state | The translator already builds into the core (`xenos_spirv_translation_probe.cpp`); SPIR-V → WGSL through Naga (`render360-spirv-wgsl-runtime.mjs`); one WebGPU render pipeline per Xenia pipeline description. Descriptor sets map 1:1 to bind groups (shared memory/EDRAM, constants, vertex textures, pixel textures — 4, the WebGPU limit). | +| `VulkanRenderTargetCache` (host render targets path) | EDRAM modelled with host render targets; ownership transfers between formats; resolves (EDRAM → shared memory) with compute shaders | Host render targets as WebGPU textures; transfers and resolves with Xenia's own compute shaders (`shaders/*.xesl`, built to SPIR-V by Xenia), converted to WGSL by Naga at build time. No fragment shader interlock path (WebGPU has none). | +| `TextureCache` + `VulkanTextureCache` | Texture keys from fetch constants; untiling and format conversion with compute shaders (`texture_load_*`); invalidation through shared-memory watches | Same base class; Xenia's `texture_load_*` shaders via Naga; WebGPU textures. | +| `VulkanCommandProcessor` | PM4 → draws, copies, swaps; system constants; submission | The core's PM4 processor (`xenos_gpu_foundation.cpp`) calls the backend per draw/copy/swap; the backend records a command stream (like Xenia's `DeferredCommandBuffer`) that `render360-webgpu-xenos.mjs` replays into a `GPUCommandEncoder` and submits at swap. | + +## Data flow per frame + +1. Guest CPU writes vertex/index/texture data → watch bits invalidate pages. +2. PM4 draw → backend: `PrimitiveProcessor`, `SharedMemory::RequestRange` + for vertex fetch and index ranges (uploads only invalid pages), texture + cache requests, render target cache update, pipeline lookup, system and + guest constants → command stream. +3. Resolve (copy draw) → render target cache resolve: compute dispatch that + writes the shared memory buffer and marks the range as GPU-written + (`RangeWrittenByGpu`, as Xenia does). +4. Swap → front buffer texture presented to the canvas; the encoder is + submitted. + +## Order of work (each with a test in headless Chromium + SwiftShader) + +1. Physical write watches in sparse guest memory (unit test: watched page, + JIT store, interpreter store, kernel write all invalidate exactly once). +2. Shared memory: base class + WebGPU subclass + JS buffer mirror (test: + upload, CPU write, re-request uploads only the dirty page; GPU readback + matches guest memory). +3. Pipeline + draw path: translated shaders, vertex fetch from shared + memory, system constants, one host render target, present (test: a + captured Banjo frame's draws match the software renderer within a + tolerance). +4. Render target cache with EDRAM transfers and resolves. +5. Texture cache with tiled/endian-swapped formats. +6. Play path switched to WebGPU; software renderer only for verification. + +## Status + +- Steps 1-3 done. `render360-webgpu-backend.mjs` replays the whole stream: + Naga turns the translated SPIR-V into WGSL, bind group layouts come from + the WGSL declarations, constants go to a dynamic-offset uniform ring, and + indices go to an index ring. Draws use the D3D12 viewport convention: + WebGPU clip space has Y up. +- Step 5 in progress (`webgpu_textures.cpp`), a port of Xenia's + `TextureCache` keys and bindings, and of `VulkanTextureCache`'s host + formats and `LoadTextureDataFromResidentMemoryImpl`. + - Xenia's own `texture_load_*` compute shaders untile and convert from + the shared memory buffer into a scratch buffer, which is then copied + into the texture. + - The SPIR-V travels in the stream on first use: `NonReadable` is + stripped, and the push constants become a uniform at group 2. + - Unsigned and signed versions are separate textures whenever their + formats differ, because WebGPU views cannot reinterpret unorm as snorm. + - S3TC/DXN/DXT5A are decompressed by Xenia's fallback shaders (BC is + optional in WebGPU and absent on iOS). + - 16-bit packed formats (565, 655, 1555, 4444) are loaded as 16bpb and + expanded to RGBA8. + - Xenia's 16-bit normalized outputs are converted to float16 in place. + - Host rows are padded to the 256-byte `bytesPerRow` WebGPU requires. + - Texture pages are re-checked against the sparse memory GPU watch + generations. +- Test: `test-webgpu-replay-capture-browser.mjs` replays a local capture + (`run-title.mjs --gpu-capture`) and compares it with the software frame. + +Rules kept: no game data, decrypted XEX or game-derived shaders in the +repository; translated shaders live only in the browser at run time. +Xenia's own compute shaders (resolve, texture load) are Xenia's code and are +converted from Xenia's SPIR-V by Naga in the browser. diff --git a/docs/recompile/RECORD_TO_RECOMPILE.md b/docs/recompile/RECORD_TO_RECOMPILE.md new file mode 100644 index 00000000..7b5eea99 --- /dev/null +++ b/docs/recompile/RECORD_TO_RECOMPILE.md @@ -0,0 +1,71 @@ +# Record-to-recompile (future, opt-in) + +Status: **planned, not built.** Current priority is getting titles working +(Banjo-Tooie first). This is an option people can turn on later so their +titles get cached/recompiled automatically instead of anyone hunting for +functions by hand. + +## Idea + +Run the game once on a path that can execute anything (interpreter or JIT), +record every piece of code it reaches, and feed that record to an +ahead-of-time recompiler. Each later session reports what it found that +was not recompiled yet, so coverage grows toward 100% without manual work. + +## Pipeline + +1. **Record.** Run the XEX on the interpreter/fallback path and log, with + hit counts: + - function entries; + - basic blocks; + - jump-table targets; + - resolved indirect calls (`bctr` / `bcctr`), including calls that + resolve to 0 (unresolved). + + Save this as a manifest in the recompiler's function-boundary format. + The manifest holds addresses and hashes only, never game code. +2. **Recompile.** Merge each new manifest into a master manifest, re-run + codegen and the build, and report: + - functions found; + - unresolved calls (target 0); + - new since the last run; + - coverage %. +3. **Run.** Fully native where the platform forbids runtime code + generation (iOS apps: no JIT). If execution reaches code that was not + recompiled, it does not crash: + - log the address to the manifest; + - show a quiet notice; + - fall back to an interpreter if one is built in, otherwise save and + exit cleanly. +4. **Grow.** Each session sends newly discovered addresses back to the + build machine; one command rebuilds and reinstalls. +5. **Persist.** Manifests are versioned in a private repo (addresses + only). The build cache lives on the build machine's drive, with a + backup copy elsewhere. + +## Rules + +- Only the player's own copy of the game. +- Game files and generated code are never committed or uploaded. Only + address/hash manifests are kept, in a private repo. +- Every run reports coverage % and the unresolved-call count. + +## What Render360 already has that this would build on + +- **Recording path:** the HIR interpreter + (`src/xenia_web_bootstrap/hir_correctness_executor.cpp`) executes any + guest function. Call resolution (`ResolveAddressCall*`, + `TranslateNestedGuestAddress` in `probe_backend.cpp`) sees every direct + and indirect call target, including unresolved ones (target 0). These + are the hook points for a manifest writer. +- **Compiled path:** the guest JIT (`hir_wasm_jit.cpp`) already compiles hot + functions to WebAssembly. In browsers runtime code generation is + allowed, so the Render360 form of "recompile" is an opt-in cache: + persist the compiled modules per function (keyed by address + code hash) + in the player's browser storage, so later sessions skip the interpreter + warm-up. Only the player's own browser holds generated code. +- **Determinism:** `run-title --deterministic` replays a run exactly, so a + recorded manifest can be checked against a replay. + +The ReXGlue / iPhone pipeline (Watch Dogs) lives outside this repository +and would follow the same manifest format and rules. diff --git a/ios/Render360/Controls.swift b/ios/Render360/Controls.swift new file mode 100644 index 00000000..3cd3a5bb --- /dev/null +++ b/ios/Render360/Controls.swift @@ -0,0 +1,199 @@ +import GameController +import SwiftUI + +/// XInput gamepad bits (XINPUT_GAMEPAD_*), as render360-guest-fibers.mjs. +enum XButton: UInt32 { + case up = 0x1, down = 0x2, left = 0x4, right = 0x8, start = 0x10, back = 0x20, ls = 0x40, rs = 0x80 + case lb = 0x100, rb = 0x200, a = 0x1000, b = 0x2000, x = 0x4000, y = 0x8000 +} + +/// Merges a hardware controller (MFi / Xbox / PlayStation via +/// GameController.framework) with the on-screen touch controls and feeds the +/// result to the emulator 60 times a second. +final class InputHub: ObservableObject { + @Published private(set) var controllerName: String? + var touch = PadState() + private weak var session: EmulatorSession? + private var link: CADisplayLink? + + init() { + NotificationCenter.default.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] _ in self?.refresh() } + NotificationCenter.default.addObserver(forName: .GCControllerDidDisconnect, object: nil, queue: .main) { [weak self] _ in self?.refresh() } + GCController.startWirelessControllerDiscovery {} + refresh() + } + + func attach(_ session: EmulatorSession) { + self.session = session + link?.invalidate() + let l = CADisplayLink(target: self, selector: #selector(tick)) + l.preferredFramesPerSecond = 60 + l.add(to: .main, forMode: .common) + link = l + } + + func detach() { link?.invalidate(); link = nil } + + private func refresh() { + let pad = GCController.controllers().first { $0.extendedGamepad != nil } + controllerName = pad?.vendorName ?? (pad != nil ? "Controller" : nil) + Breadcrumbs.shared.log("controller \(controllerName ?? "none")") + } + + @objc private func tick() { + var p = touch + if let g = GCController.controllers().first(where: { $0.extendedGamepad != nil })?.extendedGamepad { + func on(_ b: GCControllerButtonInput?, _ x: XButton) { if b?.isPressed == true { p.buttons |= x.rawValue } } + on(g.buttonA, .a); on(g.buttonB, .b); on(g.buttonX, .x); on(g.buttonY, .y) + on(g.leftShoulder, .lb); on(g.rightShoulder, .rb) + on(g.buttonMenu, .start); on(g.buttonOptions, .back) + on(g.leftThumbstickButton, .ls); on(g.rightThumbstickButton, .rs) + on(g.dpad.up, .up); on(g.dpad.down, .down); on(g.dpad.left, .left); on(g.dpad.right, .right) + p.leftTrigger = max(p.leftTrigger, UInt8(g.leftTrigger.value * 255)) + p.rightTrigger = max(p.rightTrigger, UInt8(g.rightTrigger.value * 255)) + if abs(g.leftThumbstick.xAxis.value) + abs(g.leftThumbstick.yAxis.value) > 0.05 { + p.lx = g.leftThumbstick.xAxis.value; p.ly = g.leftThumbstick.yAxis.value // Y up, as XInput + } + if abs(g.rightThumbstick.xAxis.value) + abs(g.rightThumbstick.yAxis.value) > 0.05 { + p.rx = g.rightThumbstick.xAxis.value; p.ry = g.rightThumbstick.yAxis.value + } + } + session?.setPad(p) + } +} + +/// On-screen controls: left stick, d-pad, A/B/X/Y, shoulders, triggers, +/// Start/Back. Hidden while a hardware controller is connected. +struct TouchControls: View { + @ObservedObject var input: InputHub + @State private var held: Set = [] + @State private var stick = CGSize.zero + @State private var lt = false + @State private var rt = false + + private func sync() { + var p = PadState() + for b in held { p.buttons |= b.rawValue } + p.leftTrigger = lt ? 255 : 0; p.rightTrigger = rt ? 255 : 0 + p.lx = Float(stick.width); p.ly = Float(-stick.height) + input.touch = p + } + + var body: some View { + GeometryReader { geo in + let s = min(geo.size.width, geo.size.height) + ZStack { + HStack(alignment: .bottom) { + VStack(spacing: s * 0.03) { + HStack { pad("LT", trigger: true, left: true); pad("LB", .lb) } + Stick(value: $stick, onChange: sync).frame(width: s * 0.34, height: s * 0.34) + DPad(held: $held, onChange: sync).frame(width: s * 0.26, height: s * 0.26) + } + Spacer() + VStack(spacing: s * 0.03) { + HStack { pad("RB", .rb); pad("RT", trigger: true, left: false) } + FaceButtons(held: $held, onChange: sync).frame(width: s * 0.36, height: s * 0.36) + } + } + .padding(.horizontal, s * 0.05).padding(.bottom, s * 0.04) + VStack { + Spacer() + HStack(spacing: s * 0.08) { pad("Back", .back); pad("Start", .start) }.padding(.bottom, s * 0.04) + } + } + } + .opacity(input.controllerName == nil ? 0.55 : 0) + .allowsHitTesting(input.controllerName == nil) + } + + @ViewBuilder private func pad(_ label: String, _ b: XButton? = nil, trigger: Bool = false, left: Bool = true) -> some View { + HoldButton(label: label) { down in + if trigger { if left { lt = down } else { rt = down } } + else if let b { if down { held.insert(b) } else { held.remove(b) } } + sync() + } + } +} + +struct HoldButton: View { + let label: String + var round = false + let changed: (Bool) -> Void + @State private var down = false + var body: some View { + Text(label) + .font(.system(size: 15, weight: .semibold, design: .rounded)) + .foregroundStyle(.white) + .frame(minWidth: round ? 52 : 64, minHeight: round ? 52 : 34) + .background(down ? Color.white.opacity(0.45) : Color.black.opacity(0.45), in: round ? AnyShape(Circle()) : AnyShape(Capsule())) + .overlay((round ? AnyShape(Circle()) : AnyShape(Capsule())).stroke(.white.opacity(0.6), lineWidth: 1)) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { _ in if !down { down = true; changed(true) } } + .onEnded { _ in down = false; changed(false) }) + .accessibilityLabel(label) + } +} + +struct FaceButtons: View { + @Binding var held: Set + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let d = g.size.width / 3 + ZStack { + face("Y", .y).position(x: g.size.width / 2, y: d / 2) + face("X", .x).position(x: d / 2, y: g.size.height / 2) + face("B", .b).position(x: g.size.width - d / 2, y: g.size.height / 2) + face("A", .a).position(x: g.size.width / 2, y: g.size.height - d / 2) + } + } + } + private func face(_ l: String, _ b: XButton) -> some View { + HoldButton(label: l, round: true) { down in if down { held.insert(b) } else { held.remove(b) }; onChange() } + } +} + +struct DPad: View { + @Binding var held: Set + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let d = g.size.width / 3 + ZStack { + dir("▲", .up).position(x: g.size.width / 2, y: d / 2) + dir("◀", .left).position(x: d / 2, y: g.size.height / 2) + dir("▶", .right).position(x: g.size.width - d / 2, y: g.size.height / 2) + dir("▼", .down).position(x: g.size.width / 2, y: g.size.height - d / 2) + } + } + } + private func dir(_ l: String, _ b: XButton) -> some View { + HoldButton(label: l, round: true) { down in if down { held.insert(b) } else { held.remove(b) }; onChange() } + } +} + +/// Analog stick: drag inside the circle; value is -1...1 per axis (y down). +struct Stick: View { + @Binding var value: CGSize + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let r = g.size.width / 2 + ZStack { + Circle().fill(.black.opacity(0.4)).overlay(Circle().stroke(.white.opacity(0.6))) + Circle().fill(.white.opacity(0.6)).frame(width: r * 0.8, height: r * 0.8) + .offset(x: value.width * r * 0.6, y: value.height * r * 0.6) + } + .contentShape(Circle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { v in + var dx = (v.location.x - r) / (r * 0.6), dy = (v.location.y - r) / (r * 0.6) + let len = sqrt(dx * dx + dy * dy) + if len > 1 { dx /= len; dy /= len } + value = CGSize(width: dx, height: dy); onChange() + } + .onEnded { _ in value = .zero; onChange() }) + } + .accessibilityLabel("Left stick") + } +} diff --git a/ios/Render360/Diagnostics.swift b/ios/Render360/Diagnostics.swift new file mode 100644 index 00000000..b4eae420 --- /dev/null +++ b/ios/Render360/Diagnostics.swift @@ -0,0 +1,172 @@ +import Foundation +import UIKit + +/// Crash breadcrumbs: Documents/Diagnostics/breadcrumbs.log, one fsynced line +/// per event, so the last lines survive a crash or a jetsam kill (which +/// writes no crash report for the app). running.flag marks a live session; if +/// it is still there at the next launch, the previous run did not end cleanly. +final class Breadcrumbs { + static let shared = Breadcrumbs() + let folder: URL + let file: URL + private let flag: URL + private(set) var previousRunCrashed = false + private(set) var previousTail: [String] = [] + + init() { + folder = GameLibrary.documents.appendingPathComponent("Diagnostics", isDirectory: true) + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + file = folder.appendingPathComponent("breadcrumbs.log") + flag = folder.appendingPathComponent("running.flag") + } + + func startSession() { + let fm = FileManager.default + previousRunCrashed = fm.fileExists(atPath: flag.path) + if let text = try? String(contentsOf: file) { + previousTail = Array(text.split(separator: "\n").suffix(40).map(String.init)) + // Keep the log bounded: last ~2000 lines. + let lines = text.split(separator: "\n") + if lines.count > 4000 { try? lines.suffix(2000).joined(separator: "\n").appending("\n").write(to: file, atomically: true, encoding: .utf8) } + } + try? Data().write(to: flag) + r360_breadcrumb_open(file.path) + r360_install_crash_handlers() + log("launch \(Bundle.main.bundleIdentifier ?? "") \(UIDevice.current.model) iOS \(UIDevice.current.systemVersion) previousCrashed=\(previousRunCrashed)") + } + + func endSession() { + log("clean exit") + try? FileManager.default.removeItem(at: flag) + } + + func log(_ line: String) { r360_breadcrumb(line) } +} + +/// Watches os_proc_available_memory() and logs/acts before iOS kills the app. +/// The interpreter-only core has no large GPU caches yet; its big consumer is +/// the HIR translation cache, which the core already bounds. Under pressure +/// the guard records breadcrumbs (so a jetsam kill is attributed) and tells +/// the UI; the lowest free memory of a run is kept for telemetry. +final class MemoryGuard { + private(set) var lowestAvailableMB: Double = .infinity + private var lastWarnMB = Double.infinity + private var lastCheck = 0.0 + var onPressure: ((Double) -> Void)? + + static var availableMB: Double { Double(r360_platform_available_memory()) / 1048576 } + static var footprintMB: Double { Double(r360_platform_footprint()) / 1048576 } + + func check() { + let t = PerfStats.nowMs() + guard t - lastCheck > 250 else { return } + lastCheck = t + let avail = Self.availableMB + lowestAvailableMB = min(lowestAvailableMB, avail) + // Same thresholds as the GTA V port's phone budget: act below 240 MB free. + if avail < 240, avail < lastWarnMB - 32 { + lastWarnMB = avail + Breadcrumbs.shared.log(String(format: "memory low: %.0f MB free, footprint %.0f MB", avail, Self.footprintMB)) + onPressure?(avail) + } else if avail > lastWarnMB + 96 { + lastWarnMB = .infinity + } + } +} + +/// Free Apple ID builds expire after 7 days: read the expiry from +/// embedded.mobileprovision to show the days left. +enum SigningInfo { + static var expiry: Date? { + guard let url = Bundle.main.url(forResource: "embedded", withExtension: "mobileprovision"), + let data = try? Data(contentsOf: url) else { return nil } + // The profile is CMS-signed; the plist sits in it as plain XML. + let text = String(decoding: data, as: UTF8.self) + guard let start = text.range(of: "") else { return nil } + let xml = Data(text[start.lowerBound.. [String: Any] { + let s = emulator?.perf.snapshot() ?? PerfStats.Snapshot() + let thermal = ["nominal", "fair", "serious", "critical"][min(3, ProcessInfo.processInfo.thermalState.rawValue)] + var game = "", state = "idle" + if let e = emulator { + game = e.game?.title ?? "" + switch e.state { + case .idle: state = "idle" + case .booting: state = "booting" + case .running: state = "running" + case .stopped(let b): state = "stopped: \(b)" + case .failed(let m): state = "failed: \(m)" + } + } + return [ + "session": sessionID, "time": Date().timeIntervalSince1970, "device": "iPhone 11", + "game": game, "state": state, + "fps": s.gameFps, "fpsAvg": s.gameAverageFps, "low1": s.gameLow1Fps, "presentedFps": s.presentedFps, + "stuttersPerMin": s.stuttersPerMinute, "speedPercent": s.emulationSpeedPercent, "idlePercent": s.idlePercent, + "mips": s.mips, "interpretedPercent": s.interpretedPercent, "bar30": s.barPass, + "guestInstructionsM": Double(r360_hir_total_instructions_millions()), "guestFrames": Double(r360_title_gpu_vd_swap_calls()), + "memFootprintMB": MemoryGuard.footprintMB, "memAvailableMB": MemoryGuard.availableMB, + "memLowestAvailableMB": memory?.lowestAvailableMB.isFinite == true ? memory!.lowestAvailableMB : MemoryGuard.availableMB, + "thermal": thermal, "battery": Double(UIDevice.current.batteryLevel), + "jit": r360_native_jit_available() == 1, "signingDaysLeft": SigningInfo.daysLeft ?? -1, + ] + } + + private func tick() { + guard let data = try? JSONSerialization.data(withJSONObject: status()) else { return } + log?.write(data); log?.write(Data("\n".utf8)) + guard !macURL.isEmpty, var comps = URLComponents(string: macURL + "/telemetry") else { return } + comps.queryItems = [URLQueryItem(name: "s", value: sessionID)] + guard let url = comps.url else { return } + var r = URLRequest(url: url, timeoutInterval: 2) + r.httpMethod = "POST" + r.setValue("application/json", forHTTPHeaderField: "Content-Type") + r.httpBody = data + URLSession.shared.dataTask(with: r).resume() + } + + /// Sends the previous run's breadcrumbs to the Mac (after a crash). + func sendCrashReport(_ lines: [String]) { + guard !macURL.isEmpty, let url = URL(string: macURL + "/crash?s=\(sessionID)") else { return } + var r = URLRequest(url: url, timeoutInterval: 5) + r.httpMethod = "POST" + r.httpBody = Data(lines.joined(separator: "\n").utf8) + URLSession.shared.dataTask(with: r).resume() + } +} diff --git a/ios/Render360/EmulatorSession.swift b/ios/Render360/EmulatorSession.swift new file mode 100644 index 00000000..243b4c70 --- /dev/null +++ b/ios/Render360/EmulatorSession.swift @@ -0,0 +1,219 @@ +import Foundation +import Combine +import QuartzCore + +/// Latest guest frame (RGBA8), handed from the guest thread to the Metal view. +final class FrameStore { + private let lock = NSLock() + private var pixels = [UInt8]() + private(set) var width = 0, height = 0, generation: UInt64 = 0 + + func store(_ src: UnsafeRawPointer, width: Int, height: Int) { + lock.lock(); defer { lock.unlock() } + let count = width * height * 4 + if pixels.count != count { pixels = [UInt8](repeating: 0, count: count) } + pixels.withUnsafeMutableBytes { $0.baseAddress!.copyMemory(from: src, byteCount: count) } + self.width = width; self.height = height + generation &+= 1 + } + + /// Runs `body` with the newest frame if it is newer than `since`. + func withFrame(newerThan since: UInt64, _ body: (UnsafeRawPointer, Int, Int, UInt64) -> Void) { + lock.lock(); defer { lock.unlock() } + guard generation != since, width > 0 else { return } + pixels.withUnsafeBytes { body($0.baseAddress!, width, height, generation) } + } +} + +/// Gamepad state shared between the UI (touch / GameController) and the guest thread. +struct PadState: Equatable { + var buttons: UInt32 = 0 // XINPUT_GAMEPAD_* bits + var leftTrigger: UInt8 = 0, rightTrigger: UInt8 = 0 + var lx: Float = 0, ly: Float = 0, rx: Float = 0, ry: Float = 0 +} + +/// One running title. The core runs on its own threads; this object only +/// starts it and reacts in the host slices (frames, input, stats, stop). +final class EmulatorSession: ObservableObject { + enum State: Equatable { case idle, booting, running, stopped(String), failed(String) } + + @Published private(set) var state: State = .idle + @Published private(set) var stats = PerfStats.Snapshot() + @Published var dialog: GuestDialog? + // The website's boot card: hidden at the first guest frame. + @Published private(set) var firstFrame = false + @Published private(set) var bootMessage = "Preparing Xbox 360 runtime…" + @Published private(set) var bootStage = "LAUNCH" + + let frames = FrameStore() + let perf = PerfStats() + private(set) var game: GameEntry? + private var stopRequested = false + private var padLock = NSLock() + private var pad = PadState() + private var lastSentPad = PadState(buttons: .max) + private var lastFrames: UInt32 = 0 + private var dialogAnswer: Int? + private var statsTimer: Timer? + private(set) var bootResult = R360BootResult() + var memory: MemoryGuard? + /// Metal layer of the GPU renderer (GPUFrameView); nil: software frames. + var gpuLayer: CAMetalLayer? + @Published private(set) var renderer = "starting" + private var useGPU = false + private var drawableLock = NSLock() + private var drawable = (w: UInt32(0), h: UInt32(0)) + private var lastPresent = 0.0 + + func setDrawableSize(_ size: CGSize) { + drawableLock.lock(); drawable = (UInt32(size.width), UInt32(size.height)); drawableLock.unlock() + } + + struct GuestDialog: Identifiable { + let id = UUID() + let title: String, text: String + let buttons: [String] + let focused: Int + } + + func setPad(_ newPad: PadState) { + padLock.lock(); pad = newPad; padLock.unlock() + } + + func answerDialog(_ button: Int) { + padLock.lock(); dialogAnswer = button; padLock.unlock() + dialog = nil + } + + func stop() { stopRequested = true; setPaused(false) } + + /// Pause holds the guest thread at its next host slice (the website's Pause). + private let pauseCondition = NSCondition() + private var paused = false + func setPaused(_ on: Bool) { + pauseCondition.lock(); paused = on; pauseCondition.broadcast(); pauseCondition.unlock() + } + + /// The core holds one title per process (a stopped run leaves parked + /// guest threads), so boot exactly once even if the view appears twice. + private static var booted = false + + func start(game: GameEntry) { + guard state == .idle, !Self.booted else { return } + Self.booted = true + self.game = game + state = .booting + Breadcrumbs.shared.log("boot \(game.title) discs=\(game.discs.count)") + let thread = Thread { [weak self] in self?.runCore(game) } + thread.name = "r360-boot" + thread.stackSize = 16 << 20 + thread.qualityOfService = .userInteractive + thread.start() + statsTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in + guard let self else { return } + self.stats = self.perf.snapshot() + let frames = r360_title_gpu_vd_swap_calls(), draws = r360_xenos_draws() + if frames > 0 && draws > 0 { self.firstFrame = true } + let threads = r360_fiber_count() > 0 ? r360_fiber_count() - 1 : 0 + self.bootMessage = String(format: "Running · %u frames presented (%.1f/s) · %u GPU draws · %u guest threads · %.0f MIPS", + frames, self.stats.gameFps, draws, threads, self.stats.mips) + self.bootStage = "EXECUTE" + } + } + + private func runCore(_ game: GameEntry) { + // GPU renderer when the view's layer exists (wait briefly for layout). + for _ in 0..<40 where gpuLayer == nil { Thread.sleep(forTimeInterval: 0.05) } + if let layer = gpuLayer, UserDefaults.standard.object(forKey: "r360.softwareRenderer") as? Bool != true { + useGPU = r360_gpu_backend_start(Unmanaged.passUnretained(layer).toOpaque()) == 1 + let why = useGPU ? "" : String(cString: r360_gpu_backend_error()) + Breadcrumbs.shared.log("renderer \(useGPU ? "gpu (wgpu/Metal)" : "software: \(why)")") + } + DispatchQueue.main.async { self.renderer = self.useGPU ? "Metal GPU" : "software" } + let paths = game.discURLs.map { $0.path } + var cStrings = paths.map { strdup($0) } + defer { cStrings.forEach { free($0) } } + var result = R360BootResult() + let ok: UInt32 = cStrings.withUnsafeMutableBufferPointer { buf -> UInt32 in + var options = R360BootOptions() + options.path = UnsafePointer(buf[0]) + let discs = buf.map { UnsafePointer($0) } + return discs.withUnsafeBufferPointer { dbuf -> UInt32 in + options.discs = UnsafePointer(dbuf.baseAddress.map { UnsafeRawPointer($0).assumingMemoryBound(to: UnsafePointer?.self) }) + options.disc_count = UInt32(discs.count) + options.license_full = game.ownedFullLicense ? 1 : 0 + options.dialog_button = -1 + options.slice_ms = 20 + options.on_slice = { user in + Unmanaged.fromOpaque(user!).takeUnretainedValue().onSlice() + } + options.user = Unmanaged.passUnretained(self).toOpaque() + // Host answers for XamShowMessageBoxUI (the player picks). + r360_xam_dialog_set_host_answers(1) + DispatchQueue.main.async { self.state = .running } + return r360_native_boot(&options, &result) + } + } + bootResult = result + let boundary = withUnsafeBytes(of: result.runtime_boundary) { String(cString: $0.bindMemory(to: CChar.self).baseAddress!) } + let error = withUnsafeBytes(of: result.error) { String(cString: $0.bindMemory(to: CChar.self).baseAddress!) } + Breadcrumbs.shared.log("run ended ok=\(ok) boundary=\(boundary) error=\(error)") + DispatchQueue.main.async { + self.statsTimer?.invalidate() + self.state = ok == 1 ? .stopped(boundary) : .failed(error) + } + } + + /// Called on the running guest thread about every 20 ms of host time. + private func onSlice() -> UInt32 { + let t = PerfStats.nowMs() + // Frames: decode the VdSwap frontbuffer (as render360-title-frontbuffer.mjs). + let swaps = r360_title_gpu_vd_swap_calls() + perf.submitted(t, frames: swaps) + if useGPU { + // Replay every slice; present new guest frames at most 30 per second. + let due = swaps != lastFrames && t - lastPresent >= 33 + drawableLock.lock(); let d = drawable; drawableLock.unlock() + if r360_gpu_backend_frame(due ? 1 : 0, d.w, d.h) == 1, due { + lastFrames = swaps; lastPresent = t + perf.framePresented(t) + } + } else if swaps != lastFrames { + lastFrames = swaps + if r360_xenos_frontbuffer_snapshot_capture() == 1, + let ptr = UnsafeRawPointer(bitPattern: r360_xenos_frontbuffer_snapshot_buffer()) { + let w = Int(r360_xenos_frontbuffer_snapshot_width()), h = Int(r360_xenos_frontbuffer_snapshot_height()) + if w > 0, h > 0, Int(r360_xenos_frontbuffer_snapshot_size()) == w * h * 4 { + frames.store(ptr, width: w, height: h) + } + } + } + perf.counters(t, instructions: r360_perf_counter(0), interpreted: r360_perf_counter(1), idleMs: r360_fiber_idle_ms()) + // Input: XInput state for user 0. + padLock.lock(); let p = pad; let answer = dialogAnswer; dialogAnswer = nil; padLock.unlock() + if p != lastSentPad { + lastSentPad = p + func axis(_ v: Float) -> UInt32 { UInt32(bitPattern: Int32(max(-32768, min(32767, (v * 32767).rounded())))) & 0xFFFF } + let left = axis(p.lx) | (axis(p.ly) << 16), right = axis(p.rx) | (axis(p.ry) << 16) + let triggers = UInt32(p.leftTrigger) | (UInt32(p.rightTrigger) << 8) + r360_input_set_gamepad(0, 1, p.buttons, triggers, left, right) + } + // System message boxes. + if let answer { r360_xam_dialog_answer(UInt32(answer)) } + if r360_xam_dialog_pending() != 0, dialog == nil { + func str(_ w: UInt32) -> String { + guard let ptr = UnsafeRawPointer(bitPattern: r360_xam_dialog_string_ptr(w)) else { return "" } + return String(decoding: UnsafeRawBufferPointer(start: ptr, count: Int(r360_xam_dialog_string_len(w))), as: UTF8.self) + } + let count = r360_xam_dialog_button_count() + let d = GuestDialog(title: str(0), text: str(1), buttons: (0../: its discs (Watch Dogs has two) plus a +/// small game.json. Game files stay on the device; every file is excluded +/// from iCloud/iTunes backup. +struct GameEntry: Codable, Identifiable, Equatable { + var id: String + var title: String + var discs: [String] // file names inside the game folder, disc order + var ownedFullLicense = false // XAM license mask (Xenia default: trial) + var addedAt = Date() + // Library metadata (the website's inspectFile fields), from r360_native_inspect. + var titleId: UInt32? = nil + var mediaId: UInt32? = nil + var contentType: String? = nil // "CON", "LIVE", "PIRS", "ISO", "XEX" + var lastPlayed: Date? = nil + + var folder: URL { GameLibrary.gamesRoot.appendingPathComponent(id, isDirectory: true) } + var discURLs: [URL] { discs.map { folder.appendingPathComponent($0) } } + var totalBytes: Int64 { + discURLs.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) ?? 0) } + } +} + +final class GameLibrary: ObservableObject { + static let shared = GameLibrary() + static var documents: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } + static var gamesRoot: URL { documents.appendingPathComponent("Games", isDirectory: true) } + + @Published private(set) var games: [GameEntry] = [] + + init() { reload() } + + func reload() { + let fm = FileManager.default + try? fm.createDirectory(at: Self.gamesRoot, withIntermediateDirectories: true) + Self.excludeFromBackup(Self.gamesRoot) + var found: [GameEntry] = [] + for dir in (try? fm.contentsOfDirectory(at: Self.gamesRoot, includingPropertiesForKeys: nil)) ?? [] { + let meta = dir.appendingPathComponent("game.json") + if let data = try? Data(contentsOf: meta), let entry = try? JSONDecoder().decode(GameEntry.self, from: data), + entry.discURLs.allSatisfy({ fm.fileExists(atPath: $0.path) }) { + found.append(entry) + } + } + games = found.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending } + } + + static func excludeFromBackup(_ url: URL) { + var u = url + var values = URLResourceValues() + values.isExcludedFromBackup = true + try? u.setResourceValues(values) + } + + /// Disc order from names ("Disc 1", "disc2", "_d1"...), else alphabetical. + static func discOrder(_ names: [String]) -> [String] { + func discNumber(_ s: String) -> Int? { + let lower = s.lowercased() + for marker in ["disc", "disk", "cd", "_d"] { + if let r = lower.range(of: marker) { + let digits = lower[r.upperBound...].drop { $0 == " " || $0 == "_" || $0 == "-" }.prefix { $0.isNumber } + if let n = Int(digits) { return n } + } + } + return nil + } + return names.sorted { a, b in + switch (discNumber(a), discNumber(b)) { + case let (x?, y?) where x != y: return x < y + default: return a.localizedStandardCompare(b) == .orderedAscending + } + } + } + + /// Creates (or extends, for another disc of the same title) a game entry + /// from files already moved into its folder. + @discardableResult + func register(id: String, title: String, discFiles: [String]) -> GameEntry { + let folder = Self.gamesRoot.appendingPathComponent(id, isDirectory: true) + var entry = games.first { $0.id == id } ?? GameEntry(id: id, title: title, discs: []) + entry.discs = Self.discOrder(Array(Set(entry.discs + discFiles))) + for disc in entry.discs { Self.excludeFromBackup(folder.appendingPathComponent(disc)) } + Self.excludeFromBackup(folder) + if let data = try? JSONEncoder().encode(entry) { try? data.write(to: folder.appendingPathComponent("game.json")) } + reload() + return entry + } + + /// Fills title / media id, display name and content type with the native + /// core (as the website's import does), once per game. + func inspectIfNeeded() { + for var entry in games where entry.titleId == nil { + guard let disc = entry.discURLs.first else { continue } + var info = R360GameInfo() + guard r360_native_inspect(disc.path, &info) == 1 else { continue } + func str(_ t: T) -> String { withUnsafeBytes(of: t) { String(cString: $0.bindMemory(to: CChar.self).baseAddress!) } } + entry.titleId = info.title_id + entry.mediaId = info.media_id + entry.contentType = str(info.source_type).uppercased() + let name = str(info.name) + if !name.isEmpty, entry.title.count == 42 || entry.title == disc.lastPathComponent { entry.title = name } + if let data = try? JSONEncoder().encode(entry) { try? data.write(to: entry.folder.appendingPathComponent("game.json")) } + } + DispatchQueue.main.async { self.reload() } + } + + func update(_ entry: GameEntry) { + if let data = try? JSONEncoder().encode(entry) { try? data.write(to: entry.folder.appendingPathComponent("game.json")) } + reload() + } + + func delete(_ entry: GameEntry) { + try? FileManager.default.removeItem(at: entry.folder) + reload() + } + + static func makeID(_ title: String) -> String { + let base = title.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" } + return String(base).split(separator: "-").joined(separator: "-").prefix(40) + "-" + String(UUID().uuidString.prefix(6)) + } + + /// Imports files from the Files app or AirDrop (open-in). Files that look + /// like discs of one title ("Watch Dogs Disc 1/2") become one entry. + /// `addTo` adds the files as further discs of an existing game. + func importFiles(_ urls: [URL], addTo existing: GameEntry? = nil) throws -> GameEntry { + guard !urls.isEmpty else { throw CocoaError(.fileNoSuchFile) } + let title = existing?.title ?? Self.titleFromDiscName(urls[0].deletingPathExtension().lastPathComponent) + let id = existing?.id ?? Self.makeID(title) + let folder = Self.gamesRoot.appendingPathComponent(id, isDirectory: true) + let fm = FileManager.default + try fm.createDirectory(at: folder, withIntermediateDirectories: true) + var names: [String] = [] + for url in urls { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let dest = folder.appendingPathComponent(url.lastPathComponent) + if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) } + // Inbox files (AirDrop/open-in) can be moved; picked files are copied. + // Inbox (AirDrop / open-in) and picker copies (tmp) are ours to move. + if url.path.contains("/Inbox/") || url.path.hasPrefix(fm.temporaryDirectory.path) || url.path.contains("/tmp/") { + try fm.moveItem(at: url, to: dest) + } else { + try fm.copyItem(at: url, to: dest) + } + names.append(dest.lastPathComponent) + Breadcrumbs.shared.log("import \(dest.lastPathComponent)") + } + return register(id: id, title: title, discs: names) + } + + private func register(id: String, title: String, discs: [String]) -> GameEntry { + register(id: id, title: title, discFiles: discs) + } + + /// "Watch Dogs (Disc 1)" -> "Watch Dogs". + static func titleFromDiscName(_ name: String) -> String { + var t = name + for pattern in ["\\s*[\\(\\[]?\\s*(disc|disk|cd)\\s*\\d+\\s*[\\)\\]]?", "_d\\d+$"] { + t = t.replacingOccurrences(of: pattern, with: "", options: [.regularExpression, .caseInsensitive]) + } + t = t.trimmingCharacters(in: .whitespaces) + return t.isEmpty ? name : t + } +} diff --git a/ios/Render360/Info.plist b/ios/Render360/Info.plist new file mode 100644 index 00000000..14b155ac --- /dev/null +++ b/ios/Render360/Info.plist @@ -0,0 +1,98 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Render360 + CFBundleDocumentTypes + + + CFBundleTypeName + Xbox 360 game + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + public.data + public.disk-image + com.render360.xbox360-game + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + GCSupportedGameControllers + + + ProfileName + ExtendedGamepad + + + GCSupportsControllerUserInteraction + + LSSupportsOpeningDocumentsInPlace + + NSBonjourServices + + _render360._tcp + + NSLocalNetworkUsageDescription + Render360 downloads your own game files from your Mac and serves live performance telemetry to it over Wi-Fi. + UIFileSharingEnabled + + UILaunchScreen + + UIRequiresFullScreen + + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + UIInterfaceOrientationPortrait + + UISupportsDocumentBrowser + + UTImportedTypeDeclarations + + + UTTypeConformsTo + + public.data + + UTTypeDescription + Xbox 360 game + UTTypeIdentifier + com.render360.xbox360-game + UTTypeTagSpecification + + public.filename-extension + + iso + xex + god + stfs + con + + + + + + diff --git a/ios/Render360/MacImport.swift b/ios/Render360/MacImport.swift new file mode 100644 index 00000000..b741d64f --- /dev/null +++ b/ios/Render360/MacImport.swift @@ -0,0 +1,154 @@ +import Foundation + +/// "Import from my Mac": lists tools/serve-games.py's /games.json and +/// downloads a game's discs with HTTP Range requests into Documents/Games. +/// A download writes .part and continues from its size, so an +/// interrupted download (Wi-Fi drop, app killed) resumes where it stopped. +final class MacImporter: NSObject, ObservableObject, URLSessionDataDelegate { + struct Catalogue: Decodable { let games: [RemoteGame] } + struct RemoteGame: Decodable, Identifiable { + let id: String, title: String + let discs: [RemoteDisc] + var totalBytes: Int64 { discs.reduce(0) { $0 + $1.size } } + } + struct RemoteDisc: Decodable { let name: String, path: String, size: Int64 } + + @Published var serverURL: String = UserDefaults.standard.string(forKey: "r360.macServer") ?? "http://192.168.1.2:8360" + @Published var token: String = UserDefaults.standard.string(forKey: "r360.macToken") ?? "" + @Published private(set) var games: [RemoteGame] = [] + @Published private(set) var status = "" + @Published private(set) var progress: Double = 0 + @Published private(set) var busy = false + + private var session: URLSession! + private var handle: FileHandle? + private var expected: Int64 = 0, received: Int64 = 0, total: Int64 = 0, doneBefore: Int64 = 0 + private var completion: ((Error?) -> Void)? + private var cancelled = false + + override init() { + super.init() + let config = URLSessionConfiguration.default + config.timeoutIntervalForRequest = 60 + config.waitsForConnectivity = true + session = URLSession(configuration: config, delegate: self, delegateQueue: nil) + } + + private func request(_ path: String) -> URLRequest? { + guard var comps = URLComponents(string: serverURL.trimmingCharacters(in: .whitespaces) + path) else { return nil } + if !token.isEmpty { comps.queryItems = (comps.queryItems ?? []) + [URLQueryItem(name: "token", value: token)] } + guard let url = comps.url else { return nil } + var r = URLRequest(url: url) + if !token.isEmpty { r.setValue(token, forHTTPHeaderField: "X-Render360-Token") } + return r + } + + func refresh() { + UserDefaults.standard.set(serverURL, forKey: "r360.macServer") + UserDefaults.standard.set(token, forKey: "r360.macToken") + guard let r = request("/games.json") else { status = "Invalid address"; return } + status = "Connecting…" + URLSession.shared.dataTask(with: r) { data, response, error in + DispatchQueue.main.async { + if let error { self.status = "Can't reach the Mac: \(error.localizedDescription)"; return } + guard (response as? HTTPURLResponse)?.statusCode == 200, let data, + let cat = try? JSONDecoder().decode(Catalogue.self, from: data) else { + self.status = "The Mac answered with an error (wrong token?)"; return + } + self.games = cat.games + self.status = cat.games.isEmpty ? "No games in the served folder" : "\(cat.games.count) game(s) on the Mac" + } + }.resume() + } + + func cancel() { cancelled = true; session.getAllTasks { $0.forEach { $0.cancel() } } } + + func download(_ game: RemoteGame, into library: GameLibrary) { + guard !busy else { return } + busy = true; cancelled = false + let id = "mac-" + game.id + let folder = GameLibrary.gamesRoot.appendingPathComponent(id, isDirectory: true) + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + GameLibrary.excludeFromBackup(folder) + total = game.totalBytes; doneBefore = 0 + Breadcrumbs.shared.log("mac download \(game.title) \(total) bytes") + func next(_ index: Int) { + if index == game.discs.count { + DispatchQueue.main.async { + library.register(id: id, title: game.title, discFiles: game.discs.map { $0.name }) + self.busy = false; self.status = "Imported \(game.title)"; self.progress = 1 + } + return + } + let disc = game.discs[index] + let dest = folder.appendingPathComponent(disc.name) + if let size = try? dest.resourceValues(forKeys: [.fileSizeKey]).fileSize, Int64(size) == disc.size { + doneBefore += disc.size; next(index + 1); return + } + fetch(disc, to: dest) { error in + if let error { + DispatchQueue.main.async { + self.busy = false + self.status = self.cancelled ? "Paused – tap Download to resume" : "Download stopped: \(error.localizedDescription) – tap Download to resume" + } + return + } + self.doneBefore += disc.size + next(index + 1) + } + } + next(0) + } + + private func fetch(_ disc: RemoteDisc, to dest: URL, completion: @escaping (Error?) -> Void) { + let part = dest.appendingPathExtension("part") + let fm = FileManager.default + if !fm.fileExists(atPath: part.path) { fm.createFile(atPath: part.path, contents: nil) } + GameLibrary.excludeFromBackup(part) + guard let h = try? FileHandle(forWritingTo: part) else { completion(CocoaError(.fileWriteUnknown)); return } + let have = (try? h.seekToEnd()).map(Int64.init) ?? 0 + handle = h; received = have; expected = disc.size + self.completion = { error in + try? h.close() + if error == nil { + try? fm.removeItem(at: dest) + do { try fm.moveItem(at: part, to: dest) } catch { completion(error); return } + GameLibrary.excludeFromBackup(dest) + } + completion(error) + } + if have >= disc.size { self.completion?(nil); return } + guard var r = request("/files/" + (disc.path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? disc.path)) else { + completion(URLError(.badURL)); return + } + r.setValue("bytes=\(have)-", forHTTPHeaderField: "Range") + session.dataTask(with: r).resume() + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + let code = (response as? HTTPURLResponse)?.statusCode ?? 0 + if code == 200, received > 0 { + // Server ignored Range: start the file over. + try? handle?.truncate(atOffset: 0); received = 0 + } + completionHandler(code == 200 || code == 206 ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + handle?.write(data) + received += Int64(data.count) + let p = total > 0 ? Double(doneBefore + received) / Double(total) : 0 + DispatchQueue.main.async { + self.progress = p + self.status = String(format: "Downloading… %.0f%% (%.0f / %.0f MB)", p * 100, + Double(self.doneBefore + self.received) / 1e6, Double(self.total) / 1e6) + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + let done = completion; completion = nil + if error == nil, received != expected { done?(URLError(.networkConnectionLost)); return } + done?(error) + } +} diff --git a/ios/Render360/MetalFrameView.swift b/ios/Render360/MetalFrameView.swift new file mode 100644 index 00000000..109fbd73 --- /dev/null +++ b/ios/Render360/MetalFrameView.swift @@ -0,0 +1,123 @@ +import MetalKit +import SwiftUI + +/// Presents the guest frontbuffer (FrameStore) with Metal: upload RGBA8 into a +/// texture, draw an aspect-fit quad. Presentation is capped at 30 FPS +/// (preferredFramesPerSecond), the target of the 30 FPS bar. +struct MetalFrameView: UIViewRepresentable { + let frames: FrameStore + let perf: PerfStats + + func makeCoordinator() -> Renderer { Renderer(frames: frames, perf: perf) } + + func makeUIView(context: Context) -> MTKView { + let view = MTKView(frame: .zero, device: context.coordinator.device) + view.colorPixelFormat = .bgra8Unorm + view.preferredFramesPerSecond = 30 + view.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1) + view.delegate = context.coordinator + view.framebufferOnly = true + view.contentScaleFactor = UIScreen.main.nativeScale + return view + } + + func updateUIView(_ uiView: MTKView, context: Context) {} + + final class Renderer: NSObject, MTKViewDelegate { + let device = MTLCreateSystemDefaultDevice()! + private let queue: MTLCommandQueue + private let pipeline: MTLRenderPipelineState + private let sampler: MTLSamplerState + private var texture: MTLTexture? + private var shown: UInt64 = 0 + private let frames: FrameStore + private let perf: PerfStats + + init(frames: FrameStore, perf: PerfStats) { + self.frames = frames + self.perf = perf + queue = device.makeCommandQueue()! + let source = """ + #include + using namespace metal; + struct VOut { float4 pos [[position]]; float2 uv; }; + vertex VOut vmain(uint vid [[vertex_id]], constant float2& scale [[buffer(0)]]) { + float2 p = float2(vid & 1, vid >> 1); + VOut o; o.pos = float4((p * 2.0 - 1.0) * scale, 0, 1); o.uv = float2(p.x, 1.0 - p.y); return o; + } + fragment float4 fmain(VOut in [[stage_in]], texture2d t [[texture(0)]], sampler s [[sampler(0)]]) { + return float4(t.sample(s, in.uv).rgb, 1.0); + } + """ + let library = try! device.makeLibrary(source: source, options: nil) + let desc = MTLRenderPipelineDescriptor() + desc.vertexFunction = library.makeFunction(name: "vmain") + desc.fragmentFunction = library.makeFunction(name: "fmain") + desc.colorAttachments[0].pixelFormat = .bgra8Unorm + pipeline = try! device.makeRenderPipelineState(descriptor: desc) + let sd = MTLSamplerDescriptor() + sd.minFilter = .linear; sd.magFilter = .linear + sampler = device.makeSamplerState(descriptor: sd)! + } + + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} + + func draw(in view: MTKView) { + frames.withFrame(newerThan: shown) { ptr, w, h, gen in + if texture?.width != w || texture?.height != h { + let td = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false) + td.usage = .shaderRead + texture = device.makeTexture(descriptor: td) + } + texture?.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0, withBytes: ptr, bytesPerRow: w * 4) + shown = gen + perf.framePresented(PerfStats.nowMs()) + } + guard let pass = view.currentRenderPassDescriptor, let drawable = view.currentDrawable, + let cmd = queue.makeCommandBuffer(), let enc = cmd.makeRenderCommandEncoder(descriptor: pass) else { return } + if let texture { + let vw = Float(view.drawableSize.width), vh = Float(view.drawableSize.height) + let fa = Float(texture.width) / Float(texture.height), va = vw / max(vh, 1) + var scale = fa > va ? SIMD2(1, va / fa) : SIMD2(fa / va, 1) + enc.setRenderPipelineState(pipeline) + enc.setVertexBytes(&scale, length: MemoryLayout>.size, index: 0) + enc.setFragmentTexture(texture, index: 0) + enc.setFragmentSamplerState(sampler, index: 0) + enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) + } + enc.endEncoding() + cmd.present(drawable) + cmd.commit() + } + } +} + +/// Surface for the native Xenos GPU renderer (wgpu-native on Metal): the +/// guest thread presents into this layer directly. +final class GPULayerView: UIView { + override class var layerClass: AnyClass { CAMetalLayer.self } + var metalLayer: CAMetalLayer { layer as! CAMetalLayer } + var onSize: ((CGSize) -> Void)? + override func layoutSubviews() { + super.layoutSubviews() + let scale = window?.screen.nativeScale ?? UIScreen.main.nativeScale + contentScaleFactor = scale + let size = CGSize(width: bounds.width * scale, height: bounds.height * scale) + metalLayer.drawableSize = size + onSize?(size) + } +} + +struct GPUFrameView: UIViewRepresentable { + let session: EmulatorSession + func makeUIView(context: Context) -> GPULayerView { + let v = GPULayerView() + v.backgroundColor = .black + v.metalLayer.pixelFormat = .bgra8Unorm + v.metalLayer.framebufferOnly = true + v.onSize = { [weak session] size in session?.setDrawableSize(size) } + session.gpuLayer = v.metalLayer + return v + } + func updateUIView(_ uiView: GPULayerView, context: Context) {} +} diff --git a/ios/Render360/NativeUI.swift b/ios/Render360/NativeUI.swift new file mode 100644 index 00000000..830f130c --- /dev/null +++ b/ios/Render360/NativeUI.swift @@ -0,0 +1,639 @@ +import SwiftUI +import UniformTypeIdentifiers + +// Native SwiftUI recreation of the Render360 website's screens (index.html, +// styles/base.css, styles/controller.css): library, game details, the boot +// card and the in-game touch controller + HUD, same layout and colors. + +extension Color { + init(hex: UInt32, alpha: Double = 1) { + self.init(.sRGB, red: Double((hex >> 16) & 0xFF) / 255, green: Double((hex >> 8) & 0xFF) / 255, + blue: Double(hex & 0xFF) / 255, opacity: alpha) + } + static let r360Group = Color(hex: 0x1C1C1E) + static let r360Separator = Color(hex: 0x38383A) + static let r360Secondary = Color(hex: 0x8E8E93) + static let r360Blue = Color(hex: 0x0A84FF) + static let r360Green = Color(hex: 0x30D158) +} + +func hex8(_ v: UInt32?) -> String { v.map { String(format: "%08X", $0) } ?? "Unknown" } + +// MARK: - Box art (library/cover-resolver.js: x360db by title id) + +final class CoverStore: ObservableObject { + static let shared = CoverStore() + @Published private(set) var images: [UInt32: UIImage] = [:] + private var loading = Set() + private let folder = GameLibrary.documents.appendingPathComponent("Covers", isDirectory: true) + + func image(for titleId: UInt32?) -> UIImage? { + guard let id = titleId, id != 0 else { return nil } + if let image = images[id] { return image } + let file = folder.appendingPathComponent(String(format: "%08X.jpg", id)) + if let image = UIImage(contentsOfFile: file.path) { + DispatchQueue.main.async { self.images[id] = image } + return image + } + guard !loading.contains(id) else { return nil } + loading.insert(id) + let url = URL(string: String(format: "https://raw.githubusercontent.com/xenia-manager/x360db/main/titles/%08X/artwork/boxart.jpg", id))! + URLSession.shared.dataTask(with: url) { data, response, _ in + guard let data, (response as? HTTPURLResponse)?.statusCode == 200, let image = UIImage(data: data) else { return } + try? FileManager.default.createDirectory(at: self.folder, withIntermediateDirectories: true) + try? data.write(to: file) + DispatchQueue.main.async { self.images[id] = image } + }.resume() + return nil + } +} + +struct CoverView: View { + let game: GameEntry + @ObservedObject var covers = CoverStore.shared + var body: some View { + ZStack { + if let image = covers.image(for: game.titleId) { + Image(uiImage: image).resizable().aspectRatio(contentMode: .fill) + } else { + LinearGradient(colors: [Color(hex: 0x2C2C2E), Color(hex: 0x1C1C1E)], startPoint: .top, endPoint: .bottom) + .overlay(Text(game.title).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white.opacity(0.8)) + .multilineTextAlignment(.center).padding(10)) + } + } + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } +} + +// MARK: - App shell + +struct NativeShell: View { + @EnvironmentObject var library: GameLibrary + @EnvironmentObject var input: InputHub + @StateObject private var session = EmulatorSession() + @State private var selected: GameEntry? + @State private var playing: GameEntry? + private let memory = MemoryGuard() + + var body: some View { + ZStack { + Color.black.ignoresSafeArea() + if let game = playing { + PlayScreen(game: game, session: session, onPause: { playing = nil }) + } else if let game = selected { + DetailScreen(game: game, onBack: { selected = nil }, onPlay: { play(game) }) + } else { + LibraryScreen(onOpen: { selected = $0 }) + } + } + .preferredColorScheme(.dark) + // iOS kills apps that keep the CPU busy in the background: pause the + // guest while Render360 is not in the foreground. + .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in + Breadcrumbs.shared.log("background: paused") + session.setPaused(true) + } + .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in + Breadcrumbs.shared.log("foreground") + if playing != nil { session.setPaused(false) } + } + .onAppear { + session.memory = memory + Telemetry.shared.emulator = session + Telemetry.shared.memory = memory + DispatchQueue.global(qos: .utility).async { GameLibrary.shared.inspectIfNeeded() } + if let url = ProcessInfo.processInfo.environment["R360_TELEMETRY"] { + UserDefaults.standard.set(url, forKey: "r360.telemetryServer") + } + if let id = ProcessInfo.processInfo.environment["R360_AUTOPLAY"], + let game = library.games.first(where: { $0.id == id }) { play(game) } + } + } + + private func play(_ game: GameEntry) { + if let active = session.game, active.id != game.id { + // One title per process (a stopped run's guest threads stay parked). + selected = game + return + } + UIApplication.shared.isIdleTimerDisabled = true + input.attach(session) + if session.state == .idle { session.start(game: game) } else { session.setPaused(false) } + playing = game + } +} + +// MARK: - Library (website #libraryView) + +struct LibraryScreen: View { + @EnvironmentObject var library: GameLibrary + let onOpen: (GameEntry) -> Void + @State private var search = "" + @State private var importing = false + @State private var macImport = false + @State private var importChoice = false + @State private var message: String? + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 4) { + Text("Render360").font(.system(size: 34, weight: .bold)) + HStack(spacing: 6) { + Circle().fill(Color.r360Green).frame(width: 9, height: 9) + Text("Emulator ready · Core build 75").font(.system(size: 15)).foregroundStyle(Color.r360Secondary) + } + } + Spacer() + Image(systemName: "gearshape").font(.system(size: 26)).foregroundStyle(Color.r360Secondary).padding(.trailing, 14) + Image(systemName: "person.crop.circle").font(.system(size: 28)).foregroundStyle(Color.r360Secondary) + } + .padding(.top, 18) + HStack { + Text("Library").font(.system(size: 40, weight: .bold)) + Spacer() + Button { macImport = true } label: { + ZStack(alignment: .bottomTrailing) { + Image(systemName: "display").font(.system(size: 24)).foregroundStyle(Color.r360Blue) + Text("MAC").font(.system(size: 9, weight: .heavy)).foregroundStyle(.white) + .padding(.horizontal, 5).padding(.vertical, 2) + .background(Color.r360Blue, in: Capsule()).offset(x: 10, y: 6) + } + } + .padding(.trailing, 26) + Button { importing = true } label: { + Image(systemName: "plus").font(.system(size: 30, weight: .regular)).foregroundStyle(Color.r360Blue) + } + } + .padding(.top, 36) + HStack(spacing: 8) { + Image(systemName: "magnifyingglass").foregroundStyle(Color.r360Secondary) + TextField("Search Games", text: $search).font(.system(size: 18)) + } + .padding(.horizontal, 14).frame(height: 44) + .background(Color.r360Group, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .padding(.top, 22) + let games = library.games.filter { search.isEmpty || $0.title.localizedCaseInsensitiveContains(search) } + if games.isEmpty { + VStack(spacing: 8) { + Text("No games yet").font(.system(size: 20, weight: .semibold)) + Text("Tap + to add your own dumped game (ISO, XEX, CON, LIVE or PIRS).") + .font(.system(size: 15)).foregroundStyle(Color.r360Secondary).multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity).padding(.top, 80) + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 138, maximum: 180), spacing: 16, alignment: .top)], + alignment: .leading, spacing: 22) { + ForEach(games) { game in + Button { onOpen(game) } label: { + VStack(alignment: .leading, spacing: 6) { + CoverView(game: game).aspectRatio(0.7, contentMode: .fit) + Text(game.title).font(.system(size: 17, weight: .semibold)).foregroundStyle(.white).lineLimit(1) + HStack(spacing: 6) { + Circle().fill(Color.r360Green).frame(width: 8, height: 8) + Text("Ready · \(game.contentType ?? "GAME")").font(.system(size: 14)).foregroundStyle(Color.r360Secondary) + } + } + } + .buttonStyle(.plain) + } + } + .padding(.top, 24) + if let message { Text(message).font(.footnote).foregroundStyle(Color.r360Secondary).padding(.top, 16) } + } + .padding(.horizontal, 16) + } + .scrollDismissesKeyboard(.immediately) + .fileImporter(isPresented: $importing, allowedContentTypes: [.data, .diskImage, .item], allowsMultipleSelection: true) { result in + do { + let urls = try result.get() + message = "Importing…" + DispatchQueue.global(qos: .userInitiated).async { + do { + let entry = try GameLibrary.shared.importFiles(urls) + GameLibrary.shared.inspectIfNeeded() + DispatchQueue.main.async { message = "Added \(entry.title)" } + } catch { + DispatchQueue.main.async { message = "Import failed: \(error.localizedDescription)" } + } + } + } catch { message = "Import failed: \(error.localizedDescription)" } + } + .sheet(isPresented: $macImport) { ImportView().environmentObject(library) } + } +} + +// MARK: - Game details (website #detailView) + +struct DetailScreen: View { + @EnvironmentObject var library: GameLibrary + let game: GameEntry + let onBack: () -> Void + let onPlay: () -> Void + @State private var confirmDelete = false + + var body: some View { + let current = library.games.first { $0.id == game.id } ?? game + ScrollView { + VStack(alignment: .leading, spacing: 0) { + HStack { + Button(action: onBack) { Text("‹ Library").font(.system(size: 20)).foregroundStyle(Color.r360Blue) } + Spacer() + Menu { + Toggle("I own the full game", isOn: Binding(get: { current.ownedFullLicense }, + set: { var g = current; g.ownedFullLicense = $0; library.update(g) })) + } label: { Text("Game Settings").font(.system(size: 20)).foregroundStyle(Color.r360Blue) } + } + .padding(.top, 12) + HStack(alignment: .top, spacing: 16) { + VStack(spacing: 10) { + CoverView(game: current).frame(width: 112, height: 158) + Text("Choose Cover").font(.system(size: 15)).foregroundStyle(Color.r360Blue) + } + VStack(alignment: .leading, spacing: 6) { + Text(current.title).font(.system(size: 30, weight: .bold)).lineLimit(2).minimumScaleFactor(0.6) + Text("Title ID \(hex8(current.titleId))").font(.system(size: 15)).foregroundStyle(Color.r360Secondary) + Text("Media ID \(hex8(current.mediaId))").font(.system(size: 15)).foregroundStyle(Color.r360Secondary) + Text("Testing").font(.system(size: 14, weight: .semibold)).foregroundStyle(Color.r360Green) + .padding(.horizontal, 11).padding(.vertical, 5) + .background(Color.r360Green.opacity(0.14), in: Capsule()).padding(.top, 4) + Button(action: onPlay) { + Text("Play").font(.system(size: 19, weight: .semibold)).foregroundStyle(.white) + .frame(maxWidth: .infinity).frame(height: 56) + .background(Color(hex: 0x3478F6), in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } + .padding(.top, 8) + } + } + .padding(.top, 26) + GroupTitle("GAME") + Group { + Row("Content", current.contentType ?? "—") + Row("Size", ByteCountFormatter.string(fromByteCount: current.totalBytes, countStyle: .file)) + Row("Source", current.discs.joined(separator: "\n")) + Row("Storage", "Render360/Games", last: true) + } + .groupStyle() + GroupTitle("MANAGE") + VStack(spacing: 0) { + Button { confirmDelete = true } label: { + HStack { Text("Remove from Library").foregroundStyle(.red); Spacer() }.padding(.horizontal, 16).frame(height: 56) + } + } + .groupStyle() + } + .padding(.horizontal, 16) + } + .alert("Remove \(current.title)?", isPresented: $confirmDelete) { + Button("Remove", role: .destructive) { library.delete(current); onBack() } + Button("Cancel", role: .cancel) {} + } message: { Text("The game files are deleted from this iPhone.") } + } + + private func GroupTitle(_ t: String) -> some View { + Text(t).font(.system(size: 15)).foregroundStyle(Color.r360Secondary).padding(.leading, 16).padding(.top, 34).padding(.bottom, 8) + } + private func Row(_ label: String, _ value: String, last: Bool = false) -> some View { + VStack(spacing: 0) { + HStack(alignment: .top) { + Text(label).font(.system(size: 19)) + Spacer(minLength: 20) + Text(value).font(.system(size: 19)).foregroundStyle(Color.r360Secondary).multilineTextAlignment(.trailing) + } + .padding(.horizontal, 16).padding(.vertical, 16) + if !last { Rectangle().fill(Color.r360Separator).frame(height: 0.5).padding(.leading, 16) } + } + } +} + +private extension View { + func groupStyle() -> some View { + background(Color.r360Group, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } +} + +// MARK: - In game (website #runtimeView: boot card, controller layer, HUD) + +struct PlayScreen: View { + let game: GameEntry + @ObservedObject var session: EmulatorSession + @EnvironmentObject var input: InputHub + let onPause: () -> Void + @State private var pauseSheet = false + + var body: some View { + GeometryReader { geo in + ZStack { + Color.black + MetalFrameView(frames: session.frames, perf: session.perf) + .opacity(session.renderer == "software" ? 1 : 0) + GPUFrameView(session: session).opacity(session.renderer == "software" ? 0 : 1) + if !session.firstFrame { BootCard(game: game, session: session) } + XeniOSControls(size: geo.size, input: input, onPause: { session.setPaused(true); pauseSheet = true }) + .opacity(input.controllerName == nil ? 1 : 0) + HUD(session: session).position(x: geo.size.width - (geo.size.width > geo.size.height ? 175 : 125), + y: geo.size.width > geo.size.height ? 60 : 210) + } + } + .ignoresSafeArea() + .statusBarHidden() + .persistentSystemOverlays(.hidden) + .confirmationDialog("Paused", isPresented: $pauseSheet, titleVisibility: .visible) { + Button("Resume") { session.setPaused(false) } + Button("Return to Game Details") { onPause() } + } + .alert(session.dialog?.title ?? "", isPresented: Binding(get: { session.dialog != nil }, set: { _ in })) { + ForEach(Array((session.dialog?.buttons ?? []).enumerated()), id: \.offset) { i, label in + Button(label) { session.answerDialog(i) } + } + } message: { Text(session.dialog?.text ?? "") } + } +} + +/// The website's boot card (spinner, title, progress line, stage). +struct BootCard: View { + let game: GameEntry + @ObservedObject var session: EmulatorSession + var body: some View { + VStack(spacing: 0) { + ProgressView().progressViewStyle(.circular).tint(.white).scaleEffect(1.4).padding(.bottom, 22) + Text(game.title).font(.system(size: 18, weight: .bold)) + Text(session.bootMessage).font(.system(size: 12)).foregroundStyle(Color.r360Secondary) + .multilineTextAlignment(.center).padding(.top, 7).frame(maxWidth: 420) + Text(session.bootStage).font(.system(size: 10, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color(hex: 0x636366)).padding(.top, 9) + } + .padding(24) + } +} + +/// HUD box (website #performanceHud as in the screenshots). +struct HUD: View { + @ObservedObject var session: EmulatorSession + var body: some View { + let s = session.stats + VStack(alignment: .leading, spacing: 1) { + HStack { Text("apple").bold(); Spacer(); Text("[Metal]").bold() } + HStack { Text("1.00x"); Spacer(); Text(session.firstFrame ? "REAL FRAME" : "BOOTING").foregroundStyle(Color(hex: 0xAEAEB2)); Spacer(); Text("30Hz") } + HStack { Text("FPS:"); Spacer(); Text(String(format: "%.1f", s.gameFps)).bold(); Text(String(format: "%.1f / %.1f", s.gameLow1Fps, s.gameAverageFps)).foregroundStyle(Color(hex: 0x8E8E93)) } + HStack { Text("Frm:"); Spacer(); Text(s.gameFps > 0 ? String(format: "%.1f ms", 1000 / s.gameFps) : "—").bold(); Text("\(r360_title_gpu_vd_swap_calls()) swaps").foregroundStyle(Color(hex: 0x8E8E93)) } + HStack { Text("CPU:"); Spacer(); Text(String(format: "%.0f MIPS", s.mips)).foregroundStyle(Color(hex: 0x5AC8FA)); Text("\(r360_xenos_packets()) PM4").foregroundStyle(Color(hex: 0x8E8E93)) } + HStack { Text("Mem:"); Spacer(); Text(String(format: "%.2f GB", MemoryGuard.footprintMB / 1024)).foregroundStyle(Color(hex: 0x30D158)); Text("\(r360_xenos_draws()) draws").foregroundStyle(Color(hex: 0x8E8E93)) } + } + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.white) + .padding(8) + .frame(width: 240) + .background(Color.black.opacity(0.82), in: RoundedRectangle(cornerRadius: 6)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(hex: 0x3A3A3C))) + .allowsHitTesting(false) + } +} + +/// The website's touch controller: positions from the landscape / portrait +/// screenshots of styles/controller.css, colors from its --x16-* palette. +struct ControllerLayer: View { + let size: CGSize + @ObservedObject var input: InputHub + let onPause: () -> Void + @State private var held: Set = [] + @State private var stick = CGSize.zero + + private struct Spec { let key: String; let x, y, w, h: CGFloat; let fill, edge: UInt32; let round: Bool } + + private var landscape: Bool { size.width > size.height } + + private var specs: [Spec] { + // Fractions of the screen (center x, center y, width, height). + if landscape { + return [ + Spec(key: "BACK", x: 0.441, y: 0.161, w: 0.068, h: 0.097, fill: 0x1C1C1F, edge: 0x3A3A3E, round: false), + Spec(key: "START", x: 0.532, y: 0.161, w: 0.073, h: 0.097, fill: 0x1C1C1F, edge: 0x3A3A3E, round: false), + Spec(key: "LB", x: 0.672, y: 0.169, w: 0.073, h: 0.097, fill: 0x151B26, edge: 0x2B3550, round: false), + Spec(key: "RB", x: 0.761, y: 0.169, w: 0.073, h: 0.097, fill: 0x151B26, edge: 0x2B3550, round: false), + Spec(key: "LT", x: 0.206, y: 0.466, w: 0.104, h: 0.094, fill: 0x151C1D, edge: 0x263A3A, round: false), + Spec(key: "RT", x: 0.857, y: 0.466, w: 0.103, h: 0.094, fill: 0x1E1616, edge: 0x402A27, round: false), + Spec(key: "Y", x: 0.749, y: 0.523, w: 0.056, h: 0.121, fill: 0x2A2216, edge: 0x6B5A2A, round: true), + Spec(key: "X", x: 0.695, y: 0.621, w: 0.056, h: 0.121, fill: 0x141C26, edge: 0x2B4050, round: true), + Spec(key: "B", x: 0.801, y: 0.621, w: 0.056, h: 0.121, fill: 0x241418, edge: 0x4D2E3B, round: true), + Spec(key: "A", x: 0.748, y: 0.720, w: 0.056, h: 0.121, fill: 0x152019, edge: 0x2A4A35, round: true)] + } + return [ + Spec(key: "BACK", x: 0.626, y: 0.131, w: 0.135, h: 0.034, fill: 0x1C1C1F, edge: 0x3A3A3E, round: false), + Spec(key: "START", x: 0.756, y: 0.131, w: 0.135, h: 0.034, fill: 0x1C1C1F, edge: 0x3A3A3E, round: false), + Spec(key: "LT", x: 0.123, y: 0.700, w: 0.145, h: 0.027, fill: 0x151C1D, edge: 0x263A3A, round: false), + Spec(key: "RT", x: 0.876, y: 0.699, w: 0.145, h: 0.027, fill: 0x1E1616, edge: 0x402A27, round: false), + Spec(key: "Y", x: 0.862, y: 0.752, w: 0.075, h: 0.035, fill: 0x2A2216, edge: 0x6B5A2A, round: true), + Spec(key: "X", x: 0.793, y: 0.781, w: 0.075, h: 0.035, fill: 0x141C26, edge: 0x2B4050, round: true), + Spec(key: "B", x: 0.932, y: 0.781, w: 0.075, h: 0.035, fill: 0x241418, edge: 0x4D2E3B, round: true), + Spec(key: "A", x: 0.862, y: 0.810, w: 0.075, h: 0.035, fill: 0x152019, edge: 0x2A4A35, round: true)] + } + + var body: some View { + ZStack { + // Pause (website #pauseButton). + let pause = landscape ? CGRect(x: 0.160, y: 0.161, width: 0.103, height: 0.097) + : CGRect(x: 0.085, y: 0.131, width: 0.111, height: 0.034) + Button(action: onPause) { + Text("Pause").font(.system(size: landscape ? 21 : 15, weight: .semibold)).foregroundStyle(.white.opacity(0.9)) + .frame(width: pause.width * size.width, height: pause.height * size.height) + .background(Color(hex: 0x33281B), in: Capsule()) + .overlay(Capsule().stroke(Color(hex: 0x846939), lineWidth: 1.5)) + } + .position(x: pause.minX * size.width, y: pause.minY * size.height) + ForEach(specs, id: \.key) { s in + let w = s.w * size.width, h = s.round ? s.w * size.width : s.h * size.height + let label = s.key == "BACK" ? "Back" : s.key == "START" ? "Start" : s.key + let down = held.contains(s.key) + Text(label).font(.system(size: landscape ? 21 : 13, weight: .semibold)).foregroundStyle(.white.opacity(0.9)) + .frame(width: w, height: h) + .background(Color(hex: s.fill).opacity(down ? 1 : 0.92), in: s.round ? AnyShape(Circle()) : AnyShape(Capsule())) + .overlay((s.round ? AnyShape(Circle()) : AnyShape(Capsule())).stroke(Color(hex: s.edge), lineWidth: 1.5)) + .brightness(down ? 0.15 : 0) + .scaleEffect(down ? 0.94 : 1) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { _ in if !held.contains(s.key) { held.insert(s.key); sync() } } + .onEnded { _ in held.remove(s.key); sync() }) + .position(x: s.x * size.width, y: s.y * size.height) + } + MovePad(landscape: landscape, value: $stick, onChange: sync) + .frame(width: (landscape ? 0.163 : 0.213) * size.width, height: (landscape ? 0.266 : 0.098) * size.height) + .position(x: (landscape ? 0.202 : 0.135) * size.width, y: (landscape ? 0.685 : 0.780) * size.height) + } + .frame(width: size.width, height: size.height) + } + + private func sync() { + var pad = PadState() + let bits: [String: UInt32] = ["A": 0x1000, "B": 0x2000, "X": 0x4000, "Y": 0x8000, "LB": 0x100, "RB": 0x200, + "START": 0x10, "BACK": 0x20] + for key in held { pad.buttons |= bits[key] ?? 0 } + pad.leftTrigger = held.contains("LT") ? 255 : 0 + pad.rightTrigger = held.contains("RT") ? 255 : 0 + pad.lx = Float(stick.width) + pad.ly = Float(-stick.height) // screen Y down, XInput Y up + input.touch = pad + } +} + +/// The website's "Move" pad: rounded slab with chevrons, analog stick input. +struct MovePad: View { + let landscape: Bool + @Binding var value: CGSize + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let w = g.size.width, h = g.size.height + ZStack { + RoundedRectangle(cornerRadius: min(w, h) / 2, style: .continuous).fill(Color(hex: 0x1E1B1E)) + .overlay(RoundedRectangle(cornerRadius: min(w, h) / 2, style: .continuous).stroke(Color(hex: 0x4C464F), lineWidth: 1.5)) + Text("Move").font(.system(size: landscape ? 21 : 13, weight: .semibold)).foregroundStyle(.white.opacity(0.74)) + Image(systemName: "chevron.up").position(x: w / 2, y: h * 0.14) + Image(systemName: "chevron.down").position(x: w / 2, y: h * 0.86) + Image(systemName: "chevron.left").position(x: w * 0.14, y: h / 2) + Image(systemName: "chevron.right").position(x: w * 0.86, y: h / 2) + } + .font(.system(size: landscape ? 26 : 16, weight: .regular)) + .foregroundStyle(.white.opacity(0.8)) + .offset(x: value.width * 6, y: value.height * 6) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { v in + var dx = (v.location.x - w / 2) / (w * 0.42), dy = (v.location.y - h / 2) / (h * 0.42) + let len = (dx * dx + dy * dy).squareRoot() + if len > 1 { dx /= len; dy /= len } + value = CGSize(width: dx, height: dy); onChange() + } + .onEnded { _ in value = .zero; onChange() }) + } + } +} + +// MARK: - XeniOS touch controls (port of xenios-jp/XeniOS +// src/xenia/hid/touch/touch_layout_ios_defaults.cc, BSD-3, "FPS Compact") + +struct XeniOSControls: View { + let size: CGSize + @ObservedObject var input: InputHub + let onPause: () -> Void + @State private var held: Set = [] + @State private var move = CGSize.zero + @State private var look = CGSize.zero + @State private var lastMoveTap = Date.distantPast + @State private var thumbs: Set = [] + + // Normalized frames {x, y, width, height} (top-left origin), XeniOS defaults. + private struct Button360 { let id, label, key: String; let frame: CGRect } + private let buttons: [Button360] = [ + .init(id: "back_button", label: "Back", key: "BACK", frame: CGRect(x: 0.390, y: 0.045, width: 0.080, height: 0.112)), + .init(id: "start_button", label: "Start", key: "START", frame: CGRect(x: 0.495, y: 0.045, width: 0.085, height: 0.112)), + .init(id: "lb", label: "LB", key: "LB", frame: CGRect(x: 0.660, y: 0.050, width: 0.085, height: 0.112)), + .init(id: "rb", label: "RB", key: "RB", frame: CGRect(x: 0.765, y: 0.050, width: 0.085, height: 0.112)), + .init(id: "aim_button", label: "LT", key: "LT", frame: CGRect(x: 0.095, y: 0.405, width: 0.120, height: 0.110)), + .init(id: "swap_button", label: "Y", key: "Y", frame: CGRect(x: 0.760, y: 0.455, width: 0.065, height: 0.115)), + .init(id: "reload_button", label: "X", key: "X", frame: CGRect(x: 0.700, y: 0.585, width: 0.065, height: 0.115)), + .init(id: "melee_button", label: "B", key: "B", frame: CGRect(x: 0.820, y: 0.585, width: 0.065, height: 0.115)), + .init(id: "jump_button", label: "A", key: "A", frame: CGRect(x: 0.760, y: 0.715, width: 0.065, height: 0.115)), + .init(id: "fire_button", label: "RT", key: "RT", frame: CGRect(x: 0.860, y: 0.405, width: 0.120, height: 0.110)), + ] + private let pauseFrame = CGRect(x: 0.040, y: 0.045, width: 0.120, height: 0.112) + private let moveFrame = CGRect(x: 0.055, y: 0.56, width: 0.190, height: 0.315) + + private func rect(_ f: CGRect) -> CGRect { + CGRect(x: f.minX * size.width, y: f.minY * size.height, width: f.width * size.width, height: f.height * size.height) + } + + var body: some View { + ZStack { + // look_zone: swipe anywhere else to look (right stick), lowest priority. + Color.clear.contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 2) + .onChanged { v in + look = CGSize(width: max(-1, min(1, v.translation.width / 70)), + height: max(-1, min(1, v.translation.height / 70))) + sync() + } + .onEnded { _ in look = .zero; sync() }) + let p = rect(pauseFrame) + Button(action: onPause) { + Image(systemName: "pause.fill").font(.system(size: min(p.height * 0.4, 22))) + .frame(width: p.width, height: p.height) + .background(.black.opacity(0.45), in: RoundedRectangle(cornerRadius: p.height / 3, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: p.height / 3, style: .continuous).stroke(.white.opacity(0.35))) + .foregroundStyle(.white.opacity(0.92)) + } + .position(x: p.midX, y: p.midY) + ForEach(buttons, id: \.id) { b in + let r = rect(b.frame) + let d = min(r.width, r.height) + let down = held.contains(b.key) + Text(b.label).font(.system(size: d * 0.36, weight: .bold)).foregroundStyle(.white.opacity(0.92)) + .frame(width: r.width, height: r.height) + .background(Ellipse().fill(.black.opacity(down ? 0.65 : 0.40))) + .overlay(Ellipse().stroke(.white.opacity(down ? 0.7 : 0.35), lineWidth: 1.5)) + .scaleEffect(down ? 0.93 : 1) + .opacity(0.92) + .contentShape(Ellipse()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { _ in + guard !held.contains(b.key) else { return } + held.insert(b.key); sync() + // melee_button: hold for right thumbstick click. + if b.key == "B" { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.30) { + if held.contains("B") { thumbs.insert("RS"); sync() } + } + } + } + .onEnded { _ in held.remove(b.key); if b.key == "B" { thumbs.remove("RS") }; sync() }) + .position(x: r.midX, y: r.midY) + } + let m = rect(moveFrame) + let md = min(m.width, m.height) + ZStack { + Circle().fill(.black.opacity(0.32)).overlay(Circle().stroke(.white.opacity(0.30), lineWidth: 1.5)) + // move_with_dpad_ring + ForEach(0..<4) { i in + Image(systemName: "chevron.up").font(.system(size: md * 0.11, weight: .semibold)) + .foregroundStyle(.white.opacity(0.45)).offset(y: -md * 0.40).rotationEffect(.degrees(Double(i) * 90)) + } + Circle().fill(.white.opacity(0.55)).frame(width: md * 0.38, height: md * 0.38) + .offset(x: move.width * md * 0.30, y: move.height * md * 0.30) + } + .frame(width: md, height: md) + .opacity(0.80) + .contentShape(Circle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { v in + if v.translation == .zero { + // double-tap forward: left thumbstick click + if Date().timeIntervalSince(lastMoveTap) < 0.30 { thumbs.insert("LS") } + lastMoveTap = Date() + } + var dx = (v.location.x - md / 2) / (md * 0.48), dy = (v.location.y - md / 2) / (md * 0.48) + let len = (dx * dx + dy * dy).squareRoot() + if len > 1 { dx /= len; dy /= len } + // deadzone 0.14 + move = len < 0.14 ? .zero : CGSize(width: dx, height: dy) + sync() + } + .onEnded { _ in move = .zero; thumbs.remove("LS"); sync() }) + .position(x: m.midX, y: m.midY) + } + .frame(width: size.width, height: size.height) + } + + private func sync() { + var pad = PadState() + let bits: [String: UInt32] = ["A": 0x1000, "B": 0x2000, "X": 0x4000, "Y": 0x8000, "LB": 0x100, "RB": 0x200, + "START": 0x10, "BACK": 0x20, "LS": 0x40, "RS": 0x80] + for key in held.union(thumbs) { pad.buttons |= bits[key] ?? 0 } + pad.leftTrigger = held.contains("LT") ? 255 : 0 + pad.rightTrigger = held.contains("RT") ? 255 : 0 + pad.lx = Float(move.width); pad.ly = Float(-move.height) + pad.rx = Float(look.width); pad.ry = Float(-look.height) + input.touch = pad + } +} diff --git a/ios/Render360/PerfStats.swift b/ios/Render360/PerfStats.swift new file mode 100644 index 00000000..9d3d5c57 --- /dev/null +++ b/ios/Render360/PerfStats.swift @@ -0,0 +1,103 @@ +import Foundation + +/// Swift port of PerfStats (render360-perf-overlay.mjs) so the phone reports +/// the same numbers as the web overlay and the 30 FPS bar means the same thing: +/// judged on guest frames (VdSwap presents per second), average >= 30 and +/// 1% low >= 25 over the last 60 s, emulation speed >= 100%, at most one frame +/// over 50 ms per minute. Emulation speed is 100% plus the headroom when the +/// guest had idle time; without idle time it is game FPS / 30. +final class PerfStats { + struct Snapshot: Codable { + var gameFps: Double = 0 + var gameAverageFps: Double = 0 + var gameLow1Fps: Double = 0 + var stuttersPerMinute: Double = 0 + var emulationSpeedPercent: Double = 0 + var idlePercent: Double = 0 + var mips: Double = 0 + var interpretedPercent: Double = 0 + var presentedFps: Double = 0 + var barAverage = false, barLow1 = false, barSpeed = false, barStutter = false, barPass = false + var windowSeconds: Double = 0 + } + + private let windowMs: Double + private var guestFrameTimes: [Double] = [] // ms, one per new guest frame + private var presentTimes: [Double] = [] + private var counterSamples: [(t: Double, instructions: Double, interpreted: Double, idleMs: Double)] = [] + private var lastSubmitted: UInt32 = 0 + private let lock = NSLock() + + init(windowMs: Double = 60000) { self.windowMs = windowMs } + + static func nowMs() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e6 } + + /// Guest frames submitted so far (cumulative VdSwap count). + func submitted(_ t: Double, frames: UInt32) { + lock.lock(); defer { lock.unlock() } + if frames > lastSubmitted { + for _ in 0..= cutoff }), i > 0 { guestFrameTimes.removeFirst(i) } + if let i = presentTimes.firstIndex(where: { $0 >= cutoff }), i > 0 { presentTimes.removeFirst(i) } + if let i = counterSamples.firstIndex(where: { $0.t >= t - 5000 }), i > 0 { counterSamples.removeFirst(i) } + } + + func snapshot(_ t: Double = PerfStats.nowMs()) -> Snapshot { + lock.lock(); defer { lock.unlock() } + var s = Snapshot() + let g = guestFrameTimes + s.gameFps = Double(g.filter { $0 > t - 1000 }.count) + s.presentedFps = Double(presentTimes.filter { $0 > t - 1000 }.count) + let span = g.count > 1 ? max(1, t - g[0]) : 0 + s.windowSeconds = span / 1000 + s.gameAverageFps = span > 0 ? Double(g.count - 1) * 1000 / span : s.gameFps + var deltas: [Double] = [] + if g.count > 1 { for i in 1.. g[i - 1] { deltas.append(g[i] - g[i - 1]) } } + if !deltas.isEmpty { + let worst = deltas.sorted(by: >).prefix(max(1, Int(ceil(Double(deltas.count) / 100)))) + s.gameLow1Fps = 1000 / (worst.reduce(0, +) / Double(worst.count)) + } + let stutters = Double(deltas.filter { $0 > 50 }.count) + let minutes = max(1.0 / 60, min(windowMs, span > 0 ? span : 1000) / 60000) + s.stuttersPerMinute = stutters / minutes + let cs = counterSamples + if cs.count > 1 { + let last = cs[cs.count - 1] + var first = cs.first(where: { $0.t >= t - 1000 }) ?? cs[0] + if first.t == last.t { first = cs[cs.count - 2] } + let dt = max(1, last.t - first.t) + let di = last.instructions - first.instructions + s.mips = di / dt / 1000 + s.interpretedPercent = di > 0 ? 100 * (last.interpreted - first.interpreted) / di : 0 + s.idlePercent = min(100, 100 * (last.idleMs - first.idleMs) / dt) + } + s.emulationSpeedPercent = s.idlePercent > 0 ? 100 / max(0.01, 1 - s.idlePercent / 100) + : min(100, 100 * s.gameFps / 30) + s.barAverage = s.gameAverageFps >= 30 + s.barLow1 = s.gameLow1Fps >= 25 + s.barSpeed = s.emulationSpeedPercent >= 100 + s.barStutter = s.stuttersPerMinute <= 1 + s.barPass = s.barAverage && s.barLow1 && s.barSpeed && s.barStutter && span >= 10000 + return s + } +} diff --git a/ios/Render360/R360Platform.h b/ios/Render360/R360Platform.h new file mode 100644 index 00000000..9c7e0eea --- /dev/null +++ b/ios/Render360/R360Platform.h @@ -0,0 +1,23 @@ +// Small C helpers Swift cannot call directly. +#pragma once +#include +#include + +// Bytes the process may still allocate before iOS jetsams it +// (os_proc_available_memory), and the current physical footprint. +uint64_t r360_platform_available_memory(void); +uint64_t r360_platform_footprint(void); +// Breadcrumbs: append one line and fsync, so the last lines survive a crash. +void r360_breadcrumb_open(const char* path); +void r360_breadcrumb(const char* line); +// Installs signal handlers that write a final breadcrumb on a crash. +void r360_install_crash_handlers(void); + +// Native Xenos GPU renderer (native/gpu, wgpu-native on Metal). +int r360_gpu_backend_start(void* metal_layer); +int r360_gpu_backend_frame(int present, unsigned width, unsigned height); +const char* r360_gpu_backend_error(void); +unsigned r360_gpu_backend_errors(void); + +// Largest flat guest address range this process can reserve (bytes). +uint64_t r360_platform_probe_flat_reserve(void); diff --git a/ios/Render360/R360Platform.m b/ios/Render360/R360Platform.m new file mode 100644 index 00000000..7a11fb2b --- /dev/null +++ b/ios/Render360/R360Platform.m @@ -0,0 +1,77 @@ +#import "R360Platform.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +uint64_t r360_platform_available_memory(void) { return (uint64_t)os_proc_available_memory(); } + +uint64_t r360_platform_footprint(void) { + task_vm_info_data_t info; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count) != KERN_SUCCESS) return 0; + return info.phys_footprint; +} + +static int g_breadcrumb_fd = -1; + +void r360_breadcrumb_open(const char* path) { + if (g_breadcrumb_fd >= 0) close(g_breadcrumb_fd); + g_breadcrumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644); +} + +static void write_line(const char* line) { + if (g_breadcrumb_fd < 0) return; + char stamp[32]; + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + const int n = snprintf(stamp, sizeof(stamp), "%lld.%03ld ", (long long)ts.tv_sec, ts.tv_nsec / 1000000); + write(g_breadcrumb_fd, stamp, (size_t)n); + write(g_breadcrumb_fd, line, strlen(line)); + write(g_breadcrumb_fd, "\n", 1); +} + +void r360_breadcrumb(const char* line) { + write_line(line); + if (g_breadcrumb_fd >= 0) fsync(g_breadcrumb_fd); +} + +static void crash_handler(int sig) { + // Async-signal-safe only: write + fsync, then re-raise for the system report. + char line[64]; + const char* name = sig == SIGSEGV ? "SIGSEGV" : sig == SIGBUS ? "SIGBUS" : sig == SIGILL ? "SIGILL" + : sig == SIGABRT ? "SIGABRT" : sig == SIGFPE ? "SIGFPE" : sig == SIGTRAP ? "SIGTRAP" : "signal"; + size_t n = 0; + const char* prefix = "CRASH "; + for (const char* p = prefix; *p; ++p) line[n++] = *p; + for (const char* p = name; *p && n < sizeof(line) - 2; ++p) line[n++] = *p; + line[n++] = '\n'; + if (g_breadcrumb_fd >= 0) { + write(g_breadcrumb_fd, line, n); + fsync(g_breadcrumb_fd); + } + signal(sig, SIG_DFL); + raise(sig); +} + +void r360_install_crash_handlers(void) { + const int signals[] = {SIGSEGV, SIGBUS, SIGILL, SIGABRT, SIGFPE, SIGTRAP}; + for (size_t i = 0; i < sizeof(signals) / sizeof(signals[0]); ++i) signal(signals[i], crash_handler); +} + +#include +// Probe for static recompilation (XenonRecomp's flat guest memory): can this +// process reserve Xenia's 4.5 GiB guest address range? Reserve only (no RAM). +uint64_t r360_platform_probe_flat_reserve(void) { + const uint64_t sizes[] = {0x120000000ull, 0x100000000ull, 0xC0000000ull, 0x80000000ull}; + for (unsigned i = 0; i < 4; ++i) { + void* p = mmap(NULL, sizes[i], PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (p != MAP_FAILED) { munmap(p, sizes[i]); return sizes[i]; } + } + return 0; +} diff --git a/ios/Render360/Render360-Bridging-Header.h b/ios/Render360/Render360-Bridging-Header.h new file mode 100644 index 00000000..e8116281 --- /dev/null +++ b/ios/Render360/Render360-Bridging-Header.h @@ -0,0 +1,3 @@ +// Exposes the Render360 C core (native/include) to Swift. +#import "render360_core.h" +#import "R360Platform.h" diff --git a/ios/Render360/Render360.entitlements b/ios/Render360/Render360.entitlements new file mode 100644 index 00000000..99f47167 --- /dev/null +++ b/ios/Render360/Render360.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.developer.kernel.increased-memory-limit + + + diff --git a/ios/Render360/Render360App.swift b/ios/Render360/Render360App.swift new file mode 100644 index 00000000..39232d22 --- /dev/null +++ b/ios/Render360/Render360App.swift @@ -0,0 +1,229 @@ +import SwiftUI +import UniformTypeIdentifiers + +@main +struct Render360App: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate + @StateObject private var library = GameLibrary.shared + @StateObject private var input = InputHub() + + var body: some Scene { + WindowGroup { + NativeShell() + .environmentObject(library) + .environmentObject(input) + .preferredColorScheme(.dark) + // AirDrop / "Open in Render360" / Files "Share" deliveries. + .onOpenURL { url in + _ = try? library.importFiles([url]) + } + } + } +} + +final class AppDelegate: NSObject, UIApplicationDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + Breadcrumbs.shared.startSession() + UIDevice.current.isBatteryMonitoringEnabled = true + // JIT is only usable when the process may map executable memory + // (sideloaded build + StikDebug). The core is interpreter-only today; + // the result is reported in telemetry and Settings. + Breadcrumbs.shared.log("jit probe start") + Breadcrumbs.shared.log("jit available=\(r360_native_jit_available())") + Breadcrumbs.shared.log(String(format: "flat guest reserve: %.2f GiB", Double(r360_platform_probe_flat_reserve()) / 1073741824)) + Telemetry.shared.start() + if Breadcrumbs.shared.previousRunCrashed { Telemetry.shared.sendCrashReport(Breadcrumbs.shared.previousTail) } + return true + } + func applicationWillTerminate(_ application: UIApplication) { Breadcrumbs.shared.endSession() } +} + +struct GameRow: View { + let game: GameEntry + var body: some View { + VStack(alignment: .leading, spacing: 3) { + Text(game.title).font(.headline) + Text("\(game.discs.count) disc\(game.discs.count == 1 ? "" : "s") · \(ByteCountFormatter.string(fromByteCount: game.totalBytes, countStyle: .file))\(game.ownedFullLicense ? " · full license" : "")") + .font(.caption).foregroundStyle(.secondary) + } + } +} + +struct ImportView: View { + @EnvironmentObject var library: GameLibrary + @Environment(\.dismiss) private var dismiss + @StateObject private var mac = MacImporter() + @State private var picking = false + @State private var addDiscsTo: GameEntry? + @State private var message = "" + + var body: some View { + NavigationStack { + Form { + Section("From the Files app") { + Button("Choose files…") { addDiscsTo = nil; picking = true } + Text("Pick every disc of a multi-disc game together (for example Watch Dogs disc 1 and 2); they become one game.") + .font(.caption).foregroundStyle(.secondary) + if !library.games.isEmpty { + Menu("Add a disc to an existing game") { + ForEach(library.games) { g in Button(g.title) { addDiscsTo = g; picking = true } } + } + } + } + Section("AirDrop") { + Text("AirDrop the file from your Mac and choose Render360 in the share sheet.").font(.caption).foregroundStyle(.secondary) + } + Section("From my Mac (Wi-Fi)") { + TextField("http://mac-address:8360", text: $mac.serverURL) + .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() + TextField("Token (optional)", text: $mac.token).textInputAutocapitalization(.never).autocorrectionDisabled() + Button("Show games on the Mac") { mac.refresh() }.disabled(mac.busy) + if !mac.status.isEmpty { Text(mac.status).font(.caption) } + if mac.busy { ProgressView(value: mac.progress); Button("Pause", role: .cancel) { mac.cancel() } } + ForEach(mac.games) { g in + Button { mac.download(g, into: library) } label: { + VStack(alignment: .leading) { + Text(g.title) + Text("\(g.discs.count) disc(s) · \(ByteCountFormatter.string(fromByteCount: g.totalBytes, countStyle: .file))") + .font(.caption).foregroundStyle(.secondary) + } + }.disabled(mac.busy) + } + } + if !message.isEmpty { Section { Text(message) } } + Section { + Text("Only import games you dumped from your own discs or console. Files stay on this iPhone and are excluded from iCloud backup.") + .font(.caption).foregroundStyle(.secondary) + } + } + .navigationTitle("Import game") + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } + .fileImporter(isPresented: $picking, allowedContentTypes: [.data, .diskImage, .item], allowsMultipleSelection: true) { result in + do { + let urls = try result.get() + let entry = try library.importFiles(urls, addTo: addDiscsTo) + message = "Imported \(entry.title) (\(entry.discs.count) disc\(entry.discs.count == 1 ? "" : "s"))" + } catch { + message = "Import failed: \(error.localizedDescription)" + } + } + } + } +} + +struct PlayView: View { + let game: GameEntry + @EnvironmentObject var input: InputHub + @StateObject private var session = EmulatorSession() + @Environment(\.dismiss) private var dismiss + @State private var showOverlay = true + @State private var memoryWarning: Double? + private let memory = MemoryGuard() + + var body: some View { + ZStack { + Color.black.ignoresSafeArea() + MetalFrameView(frames: session.frames, perf: session.perf).ignoresSafeArea() + GPUFrameView(session: session).ignoresSafeArea().opacity(session.renderer == "software" ? 0 : 1) + TouchControls(input: input).ignoresSafeArea() + VStack { + HStack(alignment: .top) { + if showOverlay { PerfOverlay(stats: session.stats, renderer: session.renderer, state: session.state, memory: memory) } + Spacer() + Button { showOverlay.toggle() } label: { Image(systemName: "speedometer") }.padding(6) + Button { + session.stop() + // Guest threads of a stopped run cannot be unwound; the + // app exits to release them (next launch starts clean). + Breadcrumbs.shared.endSession() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { exit(0) } + } label: { Image(systemName: "xmark.circle.fill").font(.title2) }.padding(6) + } + Spacer() + } + .padding(8) + if case .failed(let message) = session.state { + Text("Could not start: \(message)").padding().background(.red.opacity(0.8), in: RoundedRectangle(cornerRadius: 10)) + .onTapGesture { dismiss() } + } + } + .statusBarHidden() + .persistentSystemOverlays(.hidden) + .alert(session.dialog?.title ?? "", isPresented: Binding(get: { session.dialog != nil }, set: { _ in })) { + ForEach(Array((session.dialog?.buttons ?? []).enumerated()), id: \.offset) { i, label in + Button(label) { session.answerDialog(i) } + } + } message: { Text(session.dialog?.text ?? "") } + .onAppear { + UIApplication.shared.isIdleTimerDisabled = true + memory.onPressure = { mb in DispatchQueue.main.async { memoryWarning = mb } } + session.memory = memory + Telemetry.shared.emulator = session + Telemetry.shared.memory = memory + input.attach(session) + session.start(game: game) + } + .onDisappear { input.detach(); UIApplication.shared.isIdleTimerDisabled = false } + } +} + +struct PerfOverlay: View { + let stats: PerfStats.Snapshot + var renderer = "" + let state: EmulatorSession.State + let memory: MemoryGuard + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text(String(format: "Game FPS %.0f avg %.1f 1%% low %.1f stutters %.1f/min", stats.gameFps, stats.gameAverageFps, stats.gameLow1Fps, stats.stuttersPerMinute)) + Text(String(format: "Emulation speed %.0f%% idle %.0f%% %.0f MIPS interpreted %.1f%%", stats.emulationSpeedPercent, stats.idlePercent, stats.mips, stats.interpretedPercent)) + Text(String(format: "Memory %.0f MB used · %.0f MB free (lowest %.0f)", MemoryGuard.footprintMB, MemoryGuard.availableMB, + memory.lowestAvailableMB.isFinite ? memory.lowestAvailableMB : MemoryGuard.availableMB)) + Text(String(format: "Guest %.0fM instructions · %.0f frames%@", Double(r360_hir_total_instructions_millions()), + Double(r360_title_gpu_vd_swap_calls()), r360_title_gpu_vd_swap_calls() == 0 ? " · booting (first frame takes a few minutes)" : "")) + Text("Renderer: \(renderer)") + Text("30 FPS bar: \(stats.barPass ? "PASS" : "not met") · \(stateText) · thermal \(["nominal", "fair", "serious", "critical"][min(3, ProcessInfo.processInfo.thermalState.rawValue)])") + } + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.white) + .padding(6) + .background(.black.opacity(0.6), in: RoundedRectangle(cornerRadius: 6)) + } + private var stateText: String { + switch state { + case .idle: return "idle" + case .booting: return "booting" + case .running: return "running (interpreter)" + case .stopped(let b): return "stopped: \(b)" + case .failed: return "failed" + } + } +} + +struct SettingsView: View { + @Environment(\.dismiss) private var dismiss + @State private var telemetry = UserDefaults.standard.string(forKey: "r360.telemetryServer") ?? "" + var body: some View { + NavigationStack { + Form { + Section("Telemetry to the Mac") { + TextField("http://mac-address:8361", text: $telemetry) + .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() + .onSubmit { UserDefaults.standard.set(telemetry, forKey: "r360.telemetryServer") } + Text("Run tools/telemetry-server.py on the Mac, then open /status there.").font(.caption).foregroundStyle(.secondary) + } + Section("This build") { + LabeledContent("Signing expires", value: SigningInfo.expiry.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? "unknown") + LabeledContent("JIT", value: r360_native_jit_available() == 1 ? "available (not used yet)" : "not available — interpreter") + LabeledContent("Free memory", value: String(format: "%.0f MB", MemoryGuard.availableMB)) + } + Section("Diagnostics") { + ShareLink(item: Breadcrumbs.shared.file) { Label("Share breadcrumbs", systemImage: "square.and.arrow.up") } + } + } + .navigationTitle("Settings") + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { + UserDefaults.standard.set(telemetry, forKey: "r360.telemetryServer"); dismiss() + } } } + } + } +} diff --git a/ios/Signing.xcconfig b/ios/Signing.xcconfig new file mode 100644 index 00000000..d94fd394 --- /dev/null +++ b/ios/Signing.xcconfig @@ -0,0 +1,6 @@ +// Shared signing settings. Personal values go in Signing.local.xcconfig +// (git-ignored): DEVELOPMENT_TEAM = and +// R360_BUNDLE_ID = com..render360 (free teams need a +// bundle ID nobody else registered). +R360_BUNDLE_ID = com.render360.app +#include? "Signing.local.xcconfig" diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 00000000..72624d61 --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,83 @@ +# Render360 native iOS app. Generate the Xcode project with XcodeGen: +# cd ios && xcodegen generate +# The Render360 core is a static library built by native/build-native.sh +# (R360_NATIVE_TARGET=ios-arm64). See docs/IOS_APP.md. +name: Render360 +options: + bundleIdPrefix: com.render360 + deploymentTarget: + iOS: "16.0" + createIntermediateGroups: true +settings: + base: + # Free Apple ID ("Personal Team") signing: set your team in + # ios/Signing.local.xcconfig (git-ignored), see docs/IOS_APP.md. + CODE_SIGN_STYLE: Automatic + SWIFT_VERSION: "5.0" + IPHONEOS_DEPLOYMENT_TARGET: "16.0" + TARGETED_DEVICE_FAMILY: "1,2" + ENABLE_BITCODE: NO + CLANG_CXX_LANGUAGE_STANDARD: c++20 + ARCHS: arm64 +configFiles: + Debug: Signing.xcconfig + Release: Signing.xcconfig +targets: + Render360: + type: application + platform: iOS + sources: + - path: Render360 + excludes: + - "*.entitlements" + # Native Xenos GPU renderer (wgpu-native: ~/r360-deps/wgpu, docs/IOS_APP.md). + - path: ../native/gpu/xenos_wgpu.cpp + - path: ../native/gpu/xenos_wgpu_c.cpp + info: + path: Render360/Info.plist + properties: + CFBundleDisplayName: Render360 + CFBundleShortVersionString: "1.0" + CFBundleVersion: "1" + UILaunchScreen: {} + UIRequiresFullScreen: true + UIStatusBarHidden: true + UISupportedInterfaceOrientations: [UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight, UIInterfaceOrientationPortrait] + UIFileSharingEnabled: true + LSSupportsOpeningDocumentsInPlace: false + UISupportsDocumentBrowser: false + GCSupportsControllerUserInteraction: true + GCSupportedGameControllers: + - ProfileName: ExtendedGamepad + NSLocalNetworkUsageDescription: "Render360 downloads your own game files from your Mac and serves live performance telemetry to it over Wi-Fi." + NSBonjourServices: [_render360._tcp] + CFBundleDocumentTypes: + - CFBundleTypeName: Xbox 360 game + CFBundleTypeRole: Viewer + LSHandlerRank: Alternate + LSItemContentTypes: [public.data, public.disk-image, com.render360.xbox360-game] + UTImportedTypeDeclarations: + - UTTypeIdentifier: com.render360.xbox360-game + UTTypeDescription: Xbox 360 game + UTTypeConformsTo: [public.data] + UTTypeTagSpecification: + public.filename-extension: [iso, xex, god, stfs, con] + entitlements: + path: Render360/Render360.entitlements + properties: + com.apple.developer.kernel.increased-memory-limit: true + settings: + base: + ENABLE_USER_SCRIPT_SANDBOXING: NO + PRODUCT_BUNDLE_IDENTIFIER: $(R360_BUNDLE_ID) + SWIFT_OBJC_BRIDGING_HEADER: Render360/Render360-Bridging-Header.h + R360_WGPU_DIR: $(HOME)/r360-deps/wgpu/ios-aarch64-release + HEADER_SEARCH_PATHS: ["$(SRCROOT)/../native/include", "$(R360_WGPU_DIR)/include"] + LIBRARY_SEARCH_PATHS: ["$(SRCROOT)/../build/native-ios-arm64", "$(R360_WGPU_DIR)/lib"] + OTHER_LDFLAGS: ["-lrender360core", "$(R360_WGPU_DIR)/lib/libwgpu_native.a", "-lc++", "-Wl,-dead_strip"] + dependencies: + - sdk: Metal.framework + - sdk: MetalKit.framework + - sdk: GameController.framework + - sdk: Network.framework + - sdk: QuartzCore.framework diff --git a/link-xenia-ppc-bootstrap.sh b/link-xenia-ppc-bootstrap.sh index dd37121a..bbf823c9 100644 --- a/link-xenia-ppc-bootstrap.sh +++ b/link-xenia-ppc-bootstrap.sh @@ -148,7 +148,7 @@ EXPORT_LIST="$(IFS=,; echo "${EXPORTS[*]}")" # Xenos ExecuteBuffer has bounded nested command/constant scratch frames. Give # wasm32 an explicit 2 MiB stack so those frames cannot overwrite the sparse # guest-memory allocator while the source is being moved to static scratch. -R360_OPT="${R360_OPT:--O2}" +R360_OPT="${R360_OPT:--O3}" # Link without Binaryen optimization: Asyncify (below) must instrument the # module before any wasm-level inlining. A function that calls # asyncify.start_unwind is not instrumented itself, so inlining the fiber diff --git a/native/build-native.sh b/native/build-native.sh new file mode 100644 index 00000000..2cf564f3 --- /dev/null +++ b/native/build-native.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Native (non-wasm) build of the Render360 core as a static library. +# R360_NATIVE_TARGET=macos-x86_64 | macos-arm64 | ios-arm64 (default: host macOS) +# Uses the exact same source list and overlays as the wasm build +# (xenia-ppc-sources.sh). bash 3.2 compatible. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +XENIA="$ROOT/upstream/xenia" +OVERLAY="$ROOT/build/xenia-web-overlay" +TARGET="${R360_NATIVE_TARGET:-macos-$(uname -m)}" +OUT="$ROOT/build/native-$TARGET" +JOBS="${R360_BUILD_JOBS:-$(sysctl -n hw.ncpu 2>/dev/null || echo 2)}" +R360_OPT="${R360_OPT:--O3}" +case "$TARGET" in + macos-x86_64) SDK=macosx; ARCHFLAGS=(-arch x86_64 -mmacosx-version-min=12.0) ;; + macos-arm64) SDK=macosx; ARCHFLAGS=(-arch arm64 -mmacosx-version-min=12.0) ;; + ios-arm64) SDK=iphoneos; ARCHFLAGS=(-arch arm64 -miphoneos-version-min=16.0) ;; + *) echo "ERROR: unknown R360_NATIVE_TARGET=$TARGET" >&2; exit 2 ;; +esac +SYSROOT="$(xcrun --sdk "$SDK" --show-sdk-path)" +CXX="$(xcrun --sdk "$SDK" -f clang++)" +CC="$(xcrun --sdk "$SDK" -f clang)" +[ -d "$XENIA/src/xenia" ] || { echo "ERROR: run fetch-xenia.sh first" >&2; exit 2; } + +if [ "${R360_SKIP_OVERLAYS:-0}" != 1 ]; then # R360_SKIP_OVERLAYS=1 reuses build/xenia-web-overlay + git -C "$XENIA" checkout -- . + # Same overlay order as build-xenia-ppc-bootstrap.sh. + for s in $(sed -n 's#^python3 "\$ROOT/\(prepare-[a-z0-9-]*\.py\)"$#\1#p' "$ROOT/build-xenia-ppc-bootstrap.sh"); do + python3 "$ROOT/$s" >/dev/null + done +fi + +NATIVE_DEFS=(-DR360_NATIVE=1 -DNDEBUG) +COMMON=(-std=c++20 "$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" + -I"$ROOT/native/include" -I"$OVERLAY" -I"$ROOT/src/xenia_web_shims" -I"$ROOT/src/xenia_web_bootstrap" + -I"$XENIA/src" -I"$XENIA" -I"$XENIA/third_party/mspack" -I"$XENIA/third_party/fmt/include" + -I"$XENIA/third_party/utfcpp/source" -I"$XENIA/third_party/capstone/include" + -I"$XENIA/third_party/cpptoml/include" -I"$XENIA/third_party/cxxopts/include" -I"$XENIA/third_party/glslang" + -I"$XENIA/third_party/llvm/include" -include "$ROOT/native/include/r360_native_compat.h" + -Wno-everything) +COMMON_C=("$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" + -I"$XENIA/third_party/mspack" -I"$XENIA/third_party/crypto" -Wno-everything) + +mkdir -p "$OUT"; rm -f "$OUT"/*.fail +# Fresh overlays rewrite every source, so rebuild everything; with +# R360_SKIP_OVERLAYS=1 only units whose source is newer than the object. +[ "${R360_SKIP_OVERLAYS:-0}" = 1 ] || rm -f "$OUT"/*.o "$OUT"/*.log +up_to_date() { [ "${R360_SKIP_OVERLAYS:-0}" = 1 ] && [ -f "$1" ] && [ "$1" -nt "$2" ] && [ ! "$2" -nt "$1" ]; } +obj_for() { printf '%s/%s.o' "$OUT" "$(printf '%s' "$1" | tr '/' '_')"; } +throttle() { while [ "$(jobs -pr | wc -l | tr -d ' ')" -ge "$JOBS" ]; do sleep 0.2; done; } +cpp() { up_to_date "$(obj_for "$1")" "$2" && { : > "$(obj_for "$1").log"; return 0; }; throttle; ( o="$(obj_for "$1")"; "$CXX" "${COMMON[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +cc() { up_to_date "$(obj_for "$1")" "$2" && { : > "$(obj_for "$1").log"; return 0; }; throttle; ( o="$(obj_for "$1")"; "$CC" "${COMMON_C[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +# Native-only translation units (fiber baton, C API, JIT stub). +native_units() { + local f + for f in "$ROOT"/native/src/*.cpp; do [ -e "$f" ] && "$1" "native/$(basename "$f")" "$f"; done + return 0 +} + +source "$ROOT/xenia-ppc-sources.sh" +skip_wasm_only() { # wasm-only units replaced by native/src equivalents + case "$1" in render360/hir_wasm_jit.cpp) return 0 ;; esac + return 1 +} +cpp_filtered() { skip_wasm_only "$1" || cpp "$1" "$2"; } +r360_for_each_source cpp_filtered cc +native_units cpp +wait + +fails=$(find "$OUT" -maxdepth 1 -name '*.fail' | wc -l | tr -d ' ') +total=$(find "$OUT" -maxdepth 1 -name '*.o.log' | wc -l | tr -d ' ') +echo "native $TARGET: $((total - fails))/$total compiled" +if [ "$fails" -ne 0 ]; then + for f in "$OUT"/*.fail; do echo "----- ${f%.o.fail} -----"; grep -m5 'error:' "${f%.fail}.log" || head -5 "${f%.fail}.log"; done + exit 1 +fi +# Package core (render360_xenia_core.wasm: STFS mount/extract, XEX decode and +# image preparation; build-core.sh). It is a freestanding module whose names +# overlap the bootstrap's, so merge it into one relocatable object in which +# only its exports survive, renamed r360_* -> r360pkg_*. +PKG="$OUT/package-core" +rm -rf "$PKG"; mkdir -p "$PKG" +for f in "$ROOT/package-core.cpp" \ + "$ROOT"/src/xenia_web_bootstrap/xex_image_decoder.cpp "$ROOT"/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp \ + "$ROOT"/src/xenia_web_bootstrap/xex_image_preparer.cpp "$ROOT"/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp \ + "$ROOT"/src/xenia_web_bootstrap/xex_pe_image.cpp "$ROOT"/src/xenia_web_bootstrap/xex_pe_image_exports.cpp; do + "$CXX" -std=c++20 -O2 -g -fno-builtin "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" -I"$ROOT" -I"$ROOT/src/xenia_web_bootstrap" \ + -c "$f" -o "$PKG/$(basename "$f").o" +done +sed -n '/^EXPORTS=(/,/^)/p' "$ROOT/build-core.sh" | tr ' ' '\n' | grep '^r360_' | sort -u > "$PKG/names.txt" +awk '{print "_"$1" _r360pkg_"substr($1,6)}' "$PKG/names.txt" > "$PKG/aliases.txt" +awk '{print "_r360pkg_"substr($1,6)}' "$PKG/names.txt" > "$PKG/exports.txt" +xcrun --sdk "$SDK" ld -r "${ARCHFLAGS[@]:0:2}" "$PKG"/*.cpp.o -alias_list "$PKG/aliases.txt" \ + -exported_symbols_list "$PKG/exports.txt" -o "$OUT/zz_package_core.o" + +rm -f "$OUT/librender360core.a" +xcrun --sdk "$SDK" libtool -static -o "$OUT/librender360core.a" "$OUT"/*.o 2>&1 | grep -v 'has no symbols' || true +echo "built $OUT/librender360core.a" + +case "$TARGET" in + macos-*) + # Optional GPU path: wgpu-native release (https://github.com/gfx-rs/wgpu-native) + # unpacked at R360_WGPU_DIR (default ~/r360-deps/wgpu/-release). + WGPU_DIR="${R360_WGPU_DIR:-$HOME/r360-deps/wgpu/macos-$(uname -m)-release}" + GPU_ARGS=() + if [ -f "$WGPU_DIR/lib/libwgpu_native.a" ]; then + GPU_ARGS=(-DR360_WITH_WGPU=1 -I"$WGPU_DIR/include" "$ROOT/native/gpu/xenos_wgpu.cpp" "$WGPU_DIR/lib/libwgpu_native.a" + -lz -framework Metal -framework QuartzCore -framework Foundation -framework CoreGraphics -framework IOKit) + fi + "$CXX" -std=c++20 "$R360_OPT" -g "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" -I"$ROOT/native/include" \ + "$ROOT/native/tools/run_title.cpp" "$OUT/librender360core.a" ${GPU_ARGS[@]+"${GPU_ARGS[@]}"} -Wl,-dead_strip -o "$OUT/run-title" + echo "built $OUT/run-title" + ;; +esac diff --git a/native/gpu/xenos_wgpu.cpp b/native/gpu/xenos_wgpu.cpp new file mode 100644 index 00000000..5d515fe9 --- /dev/null +++ b/native/gpu/xenos_wgpu.cpp @@ -0,0 +1,2067 @@ +// Native port of render360-webgpu-backend.mjs (XenosWebGpuBackend) onto +// wgpu-native. Method names follow the JavaScript; keep them in step. +// +// Differences from the browser, all because wgpu-native is not a browser: +// * Xenia's SPIR-V goes to wgpu directly (no Naga-to-WGSL step), so bind +// group layouts come from reflecting the SPIR-V (ReflectBindings) instead +// of parsing WGSL text. +// * Push constants ("immediates") are native, so Xenia's texture_load_* and +// resolve shaders keep theirs instead of becoming a uniform buffer. +#include "xenos_wgpu.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render360_core.h" + +namespace r360gpu { +namespace { + +constexpr uint32_t GPU_STREAM_UPLOAD = 1, GPU_STREAM_SHADER = 2, GPU_STREAM_PIPELINE = 3, + GPU_STREAM_RENDER_TARGETS = 4, GPU_STREAM_DRAW = 5, GPU_STREAM_SWAP = 6, + GPU_STREAM_LOAD_SHADER = 7, GPU_STREAM_TEXTURE = 8, GPU_STREAM_TEXTURE_LOAD = 9, + GPU_STREAM_EDRAM_DUMP = 10, GPU_STREAM_RESOLVE = 11, GPU_STREAM_CLEAR = 12; +constexpr uint32_t EDRAM_TILES = 2048, EDRAM_TILE_DWORDS = 80 * 16; +constexpr uint64_t SHARED_MEMORY_BYTES = 512ull * 1024 * 1024; // Xenia SharedMemory::kBufferSize +constexpr uint64_t STAGING_BYTES = 16ull * 1024 * 1024; +constexpr uint32_t CONSTANT_WINDOW = 4096; +constexpr uint32_t DRAW_HEADER_WORDS = 26; +constexpr uint32_t kPassthroughVertexShader = 0x80000000u; // webgpu_backend.h + +WGPUStringView S(const char* s) { return WGPUStringView{s, s ? std::strlen(s) : 0}; } +WGPUStringView S(const std::string& s) { return WGPUStringView{s.data(), s.size()}; } +float F(uint32_t w) { float f; std::memcpy(&f, &w, 4); return f; } +bool Is64bpp(uint32_t guest) { return guest == 5 || guest == 7 || guest == 15; } + +// WebGpuTextureFormat (webgpu_textures.h). +WGPUTextureFormat TextureFormat(uint32_t i) { + static const WGPUTextureFormat k[] = { + WGPUTextureFormat_Undefined, WGPUTextureFormat_R8Unorm, WGPUTextureFormat_R8Snorm, WGPUTextureFormat_RG8Unorm, + WGPUTextureFormat_RG8Snorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_RGBA8Snorm, + WGPUTextureFormat_RGB10A2Unorm, WGPUTextureFormat_R16Float, WGPUTextureFormat_RG16Float, + WGPUTextureFormat_RGBA16Float, WGPUTextureFormat_R32Float, WGPUTextureFormat_RG32Float, + WGPUTextureFormat_RGBA32Float}; + return i < sizeof(k) / sizeof(k[0]) ? k[i] : WGPUTextureFormat_Undefined; +} +bool Unfilterable(WGPUTextureFormat f) { + return f == WGPUTextureFormat_R32Float || f == WGPUTextureFormat_RG32Float || f == WGPUTextureFormat_RGBA32Float; +} + +// xenos::ColorRenderTargetFormat -> host format (colorFormat in the JS). +WGPUTextureFormat ColorFormat(uint32_t guest) { + switch (guest) { + case 0: case 1: return WGPUTextureFormat_RGBA8Unorm; + case 2: case 10: return WGPUTextureFormat_RGB10A2Unorm; + case 3: case 12: case 5: case 7: return WGPUTextureFormat_RGBA16Float; + case 4: case 6: return WGPUTextureFormat_RG16Float; + case 14: return WGPUTextureFormat_R32Float; + case 15: return WGPUTextureFormat_RG32Float; + default: return WGPUTextureFormat_RGBA8Unorm; + } +} +bool Blendable(WGPUTextureFormat f) { return f != WGPUTextureFormat_R32Float && f != WGPUTextureFormat_RG32Float; } + +const WGPUCompareFunction COMPARE[] = {WGPUCompareFunction_Never, WGPUCompareFunction_Less, WGPUCompareFunction_Equal, + WGPUCompareFunction_LessEqual, WGPUCompareFunction_Greater, + WGPUCompareFunction_NotEqual, WGPUCompareFunction_GreaterEqual, + WGPUCompareFunction_Always}; +const WGPUStencilOperation STENCIL_OP[] = { + WGPUStencilOperation_Keep, WGPUStencilOperation_Zero, WGPUStencilOperation_Replace, + WGPUStencilOperation_IncrementClamp, WGPUStencilOperation_DecrementClamp, WGPUStencilOperation_Invert, + WGPUStencilOperation_IncrementWrap, WGPUStencilOperation_DecrementWrap}; + +WGPUBlendFactor BlendFactor(uint32_t f, bool alpha) { + switch (f) { + case 0: return WGPUBlendFactor_Zero; + case 1: return WGPUBlendFactor_One; + case 4: return alpha ? WGPUBlendFactor_SrcAlpha : WGPUBlendFactor_Src; + case 5: return alpha ? WGPUBlendFactor_OneMinusSrcAlpha : WGPUBlendFactor_OneMinusSrc; + case 6: return WGPUBlendFactor_SrcAlpha; + case 7: return WGPUBlendFactor_OneMinusSrcAlpha; + case 8: return alpha ? WGPUBlendFactor_DstAlpha : WGPUBlendFactor_Dst; + case 9: return alpha ? WGPUBlendFactor_OneMinusDstAlpha : WGPUBlendFactor_OneMinusDst; + case 10: return WGPUBlendFactor_DstAlpha; + case 11: return WGPUBlendFactor_OneMinusDstAlpha; + case 12: case 14: return WGPUBlendFactor_Constant; + case 13: case 15: return WGPUBlendFactor_OneMinusConstant; + case 16: return WGPUBlendFactor_SrcAlphaSaturated; + default: return WGPUBlendFactor_Zero; + } +} +const WGPUBlendOperation BLEND_OP[] = {WGPUBlendOperation_Add, WGPUBlendOperation_Subtract, WGPUBlendOperation_Min, + WGPUBlendOperation_Max, WGPUBlendOperation_ReverseSubtract}; + +// RB_BLENDCONTROL -> blend state; false: replace (blending off). +bool BlendState(uint32_t c, WGPUBlendState* out) { + const uint32_t cs = c & 31, cop = (c >> 5) & 7, cd = (c >> 8) & 31, as = (c >> 16) & 31, aop = (c >> 21) & 7, + ad = (c >> 24) & 31; + if (cs == 1 && cd == 0 && cop == 0 && as == 1 && ad == 0 && aop == 0) return false; + auto component = [](uint32_t src, uint32_t op, uint32_t dst, bool alpha) { + WGPUBlendComponent b{}; + b.operation = op < 5 ? BLEND_OP[op] : WGPUBlendOperation_Add; + if (b.operation == WGPUBlendOperation_Min || b.operation == WGPUBlendOperation_Max) { + b.srcFactor = b.dstFactor = WGPUBlendFactor_One; // WebGPU min/max require one + } else { + b.srcFactor = BlendFactor(src, alpha); + b.dstFactor = BlendFactor(dst, alpha); + } + return b; + }; + out->color = component(cs, cop, cd, false); + out->alpha = component(as, aop, ad, true); + return true; +} + +// --- SPIR-V reflection (what parseWgslBindings reads from Naga's WGSL) ------- + +struct Binding { + uint32_t group = 0, binding = 0; + enum Kind { kStorage, kUniform, kSampler, kTexture, kUnknown } kind = kUnknown; + bool write = false, comparison = false; + WGPUTextureViewDimension view = WGPUTextureViewDimension_2D; + WGPUTextureSampleType sample = WGPUTextureSampleType_Float; +}; + +// WGSL interpolation attribute of each fragment input location (what the +// pass-through vertex shader must declare to link with the pixel shader). +std::map ReflectInputInterpolation(const uint32_t* w, size_t n) { + std::unordered_map location; + std::unordered_map flat, noperspective, centroid, sample; + std::vector inputs; + for (size_t i = 5; i < n;) { + const uint32_t count = w[i] >> 16, op = w[i] & 0xFFFF; + if (!count || i + count > n) break; + const uint32_t* a = w + i + 1; + if (op == 71) { + if (a[1] == 30) location[a[0]] = a[2]; + else if (a[1] == 14) flat[a[0]] = 1; + else if (a[1] == 13) noperspective[a[0]] = 1; + else if (a[1] == 16) centroid[a[0]] = 1; + else if (a[1] == 17) sample[a[0]] = 1; + } else if (op == 59 && a[2] == 1) { + inputs.push_back(a[1]); + } + i += count; + } + std::map out; + for (uint32_t v : inputs) { + if (!location.count(v)) continue; + std::string q; + if (flat[v]) q = "@interpolate(flat)"; + else { + const char* type = noperspective[v] ? "linear" : "perspective"; + const char* sampling = centroid[v] ? ", centroid" : sample[v] ? ", sample" : ", center"; + q = std::string("@interpolate(") + type + sampling + ")"; + } + out[location[v]] = q; + } + return out; +} + +std::vector ReflectBindings(const uint32_t* w, size_t n) { + std::unordered_map set, bind, var_type, var_class, ptr_pointee, load_of, si_sampler, si_image; + std::unordered_map buffer_block; + std::unordered_map nonwritable_var, nonwritable_struct, depth_image, sampler_type, dref_sampler, + dref_image; + struct Img { uint32_t sampled, dim, depth, arrayed; }; + std::unordered_map images; + std::unordered_map int_sign, array_elem; // int type -> signedness; array -> element + std::unordered_map float_type; + std::vector vars; + for (size_t i = 5; i < n;) { + const uint32_t count = w[i] >> 16, op = w[i] & 0xFFFF; + if (!count || i + count > n) break; + const uint32_t* a = w + i + 1; + switch (op) { + case 71: // OpDecorate + if (a[1] == 34) set[a[0]] = a[2]; + else if (a[1] == 33) bind[a[0]] = a[2]; + else if (a[1] == 24) nonwritable_var[a[0]] = true; + else if (a[1] == 3) buffer_block[a[0]] = true; // BufferBlock: storage buffer (SPIR-V 1.0 style) + break; + case 72: // OpMemberDecorate NonWritable on a block member + if (a[2] == 24) nonwritable_struct[a[0]] = true; + break; + case 21: int_sign[a[0]] = a[2]; break; // OpTypeInt + case 22: float_type[a[0]] = true; break; // OpTypeFloat + case 25: images[a[0]] = {a[1], a[2], a[3], a[4]}; break; // OpTypeImage + case 26: sampler_type[a[0]] = true; break; // OpTypeSampler + case 28: case 29: array_elem[a[0]] = a[1]; break; // OpTypeArray / RuntimeArray + case 32: ptr_pointee[a[0]] = a[2]; break; // OpTypePointer + case 59: // OpVariable + var_type[a[1]] = a[0]; + var_class[a[1]] = a[2]; + vars.push_back(a[1]); + break; + case 61: load_of[a[1]] = a[2]; break; // OpLoad + case 86: si_image[a[1]] = a[2]; si_sampler[a[1]] = a[3]; break; // OpSampledImage + case 89: case 90: case 91: case 92: case 97: { // Dref sampling / gather + const uint32_t sampled_image = a[2]; + if (si_sampler.count(sampled_image)) { + dref_sampler[load_of[si_sampler[sampled_image]]] = true; + dref_image[load_of[si_image[sampled_image]]] = true; + } + break; + } + } + i += count; + } + std::vector out; + for (uint32_t v : vars) { + if (!set.count(v) || !bind.count(v)) continue; + Binding b; + b.group = set[v]; + b.binding = bind[v]; + uint32_t t = ptr_pointee[var_type[v]]; + while (array_elem.count(t)) t = array_elem[t]; + const uint32_t cls = var_class[v]; + if (cls == 12 || (cls == 2 && buffer_block[t])) { + b.kind = Binding::kStorage; + b.write = !nonwritable_var[v] && !nonwritable_struct[t]; + } else if (cls == 2) { + b.kind = Binding::kUniform; + } else if (sampler_type.count(t)) { + b.kind = Binding::kSampler; + b.comparison = dref_sampler[v]; + } else if (images.count(t)) { + const Img& img = images[t]; + b.kind = Binding::kTexture; + switch (img.dim) { + case 0: b.view = WGPUTextureViewDimension_1D; break; + case 2: b.view = WGPUTextureViewDimension_3D; break; + case 3: b.view = img.arrayed ? WGPUTextureViewDimension_CubeArray : WGPUTextureViewDimension_Cube; break; + default: b.view = img.arrayed ? WGPUTextureViewDimension_2DArray : WGPUTextureViewDimension_2D; break; + } + if (img.depth == 1 || dref_image[v]) b.sample = WGPUTextureSampleType_Depth; + else if (int_sign.count(img.sampled)) b.sample = int_sign[img.sampled] ? WGPUTextureSampleType_Sint : WGPUTextureSampleType_Uint; + else b.sample = WGPUTextureSampleType_Float; + } + out.push_back(b); + } + return out; +} + +// SPIR-V without NonReadable decorations (stripNonReadable). +std::vector StripNonReadable(const uint32_t* w, size_t n) { + std::vector out(w, w + std::min(n, 5)); + for (size_t i = 5; i < n;) { + const uint32_t count = w[i] >> 16, op = w[i] & 0xFFFF; + if (!count) break; + const bool drop = (op == 71 && w[i + 2] == 25) || (op == 72 && w[i + 3] == 25); + if (!drop) out.insert(out.end(), w + i, w + std::min(n, i + count)); + i += count; + } + return out; +} + +// --- WGSL of the passes the JavaScript writes itself -------------------------- + +std::string ExpandShader(uint32_t mode) { + const std::string head = "@group(0) @binding(0) var src: array;\n"; + const std::string index = "let i = id.x + id.y * 65535u * 64u; if (i >= arrayLength(&src)) { return; }"; + if (mode >= 5) { + const std::string conv = mode == 5 + ? "vec2(f32(v & 0xFFFFu), f32(v >> 16u)) / 65535.0" + : "max(vec2(f32((bitcast(v) << 16u) >> 16u), f32(bitcast(v) >> 16u)) / 32767.0, vec2(-1.0))"; + return head + "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) {\n " + index + + " let v = src[i]; src[i] = pack2x16float(" + conv + "); }"; + } + const char* unpack[] = { + "", + "vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 63u) / 63.0, f32((t >> 11u) & 31u) / 31.0, 1.0)", + "vec4(f32(t & 31u) / 31.0, f32((t >> 10u) & 63u) / 63.0, f32((t >> 5u) & 31u) / 31.0, 1.0)", + "vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 31u) / 31.0, f32((t >> 10u) & 31u) / 31.0, f32(t >> 15u))", + "vec4(f32(t & 15u), f32((t >> 4u) & 15u), f32((t >> 8u) & 15u), f32(t >> 12u)) / 15.0"}; + return head + "@group(0) @binding(1) var dst: array;\nfn texel(t: u32) -> u32 { return pack4x8unorm(" + + unpack[mode] + "); }\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) {\n " + + index + " let v = src[i]; dst[2u * i] = texel(v & 0xFFFFu); dst[2u * i + 1u] = texel(v >> 16u); }"; +} + +const char* CLEAR_SHADER = R"(@group(0) @binding(0) var value: vec4; +@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + return vec4(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0, 0.0, 1.0); +} +@fragment fn fs_color() -> @location(0) vec4 { return value; } +@fragment fn fs_depth() -> @builtin(frag_depth) f32 { return value.x; })"; + +std::string EdramDumpShader(bool depth) { + std::string s = R"(struct Dump { + base_tiles: u32, pitch_tiles: u32, msaa: u32, format: u32, + x0: u32, y0: u32, width: u32, height: u32, is_64bpp: u32, depth_float32: u32, pad0: u32, pad1: u32, +} +@group(0) @binding(0) var edram: array; +@group(0) @binding(1) var dump: Dump; +)"; + s += depth ? "@group(0) @binding(2) var depth_texture: texture_depth_2d;\n@group(0) @binding(3) var stencil_texture: texture_2d;\n" + : "@group(0) @binding(2) var color_texture: texture_2d;\n"; + s += R"( +fn edram_offset_dwords(pixel: vec2, sample: u32) -> u32 { + var s = pixel << vec2(select(0u, 1u, dump.msaa >= 2u), select(0u, 1u, dump.msaa >= 1u)); + s += (vec2(sample) >> vec2(1u, 0u)) & vec2(1u); + let ints_log2 = dump.is_64bpp; + let tile_size = vec2(80u >> ints_log2, 16u); + let tile = s / tile_size; + var base = dump.base_tiles + tile.y * dump.pitch_tiles + tile.x; + s -= tile * tile_size; +)"; + if (depth) s += " let half = tile_size.x >> 1u;\n s.x = select(s.x + half, s.x - half, s.x >= half);\n"; + s += R"( let address = base * 1280u + ((s.y * tile_size.x + s.x) << ints_log2); + return address % (1280u * 2048u); +} +fn f32_to_7e3(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x41FF8000u) { return 0x3FFu; } + if (u < 0x3E800000u) { + let shift = min(125u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC2000000u; + } + u += 0x7FFFu + ((u >> 16u) & 1u); + return (u >> 16u) & 0x3FFu; +} +fn f32_to_20e4(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x3FFFFFF8u) { return 0xFFFFFFu; } + if (u < 0x38800000u) { + let shift = min(113u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC8000000u; + } + u += 3u + ((u >> 3u) & 1u); + return (u >> 3u) & 0xFFFFFFu; +} +fn s16(f: f32) -> u32 { return u32(i32(round(clamp(f, -1.0, 1.0) * 32767.0))) & 0xFFFFu; } +fn to_unorm(f: f32, bits: u32) -> u32 { let m = f32((1u << bits) - 1u); return u32(round(clamp(f, 0.0, 1.0) * m)); } + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3) { + if (id.x >= dump.width || id.y >= dump.height) { return; } + let pixel = vec2(dump.x0 + id.x, dump.y0 + id.y); + var lo = 0u; + var hi = 0u; +)"; + if (depth) { + s += R"( let d = textureLoad(depth_texture, vec2(pixel), 0); + let stencil = textureLoad(stencil_texture, vec2(pixel), 0).x & 0xFFu; + let d24 = select(u32(round(clamp(d, 0.0, 1.0) * 16777215.0)), f32_to_20e4(d * 2.0), dump.format == 1u); + lo = (d24 << 8u) | stencil; +)"; + } else { + s += R"( let c = textureLoad(color_texture, vec2(pixel), 0); + switch dump.format { + case 0u, 1u: { lo = pack4x8unorm(c); } + case 2u, 10u: { lo = to_unorm(c.x, 10u) | (to_unorm(c.y, 10u) << 10u) | (to_unorm(c.z, 10u) << 20u) | (to_unorm(c.w, 2u) << 30u); } + case 3u, 12u: { lo = f32_to_7e3(c.x) | (f32_to_7e3(c.y) << 10u) | (f32_to_7e3(c.z) << 20u) | (to_unorm(c.w, 2u) << 30u); } + case 4u: { lo = s16(c.x) | (s16(c.y) << 16u); } + case 5u: { lo = s16(c.x) | (s16(c.y) << 16u); hi = s16(c.z) | (s16(c.w) << 16u); } + case 6u: { lo = pack2x16float(c.xy); } + case 7u: { lo = pack2x16float(c.xy); hi = pack2x16float(c.zw); } + case 14u: { lo = bitcast(c.x); } + case 15u: { lo = bitcast(c.x); hi = bitcast(c.y); } + default: { lo = pack4x8unorm(c); } + } +)"; + } + s += R"( let samples = select(select(1u, 2u, dump.msaa == 1u), 4u, dump.msaa >= 2u); + for (var s = 0u; s < samples; s++) { + let o = edram_offset_dwords(pixel, s); + edram[o] = lo; + if (dump.is_64bpp != 0u) { edram[o + 1u] = hi; } + } +})"; + return s; +} + +// Present: front buffer with the swap fetch constant's swizzle, aspect fit +// via the viewport. +const char* PRESENT_SHADER = R"(struct Out { @builtin(position) position: vec4, @location(0) uv: vec2 } +@vertex fn vs(@builtin(vertex_index) i: u32) -> Out { + let p = vec2(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0); + return Out(vec4(p, 0.0, 1.0), vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5)); +} +@group(0) @binding(0) var front: texture_2d_array; +@group(0) @binding(1) var front_sampler: sampler; +@group(0) @binding(2) var swizzle: vec4; +fn component(t: vec4, s: u32) -> f32 { + if (s >= 5u) { return 1.0; } + if (s == 4u) { return 0.0; } + return t[s]; +} +@fragment fn fs(i: Out) -> @location(0) vec4 { + let t = textureSample(front, front_sampler, i.uv, 0); + let s = swizzle.x; + return vec4(component(t, s & 7u), component(t, (s >> 3u) & 7u), component(t, (s >> 6u) & 7u), 1.0); +})"; + +// --- helpers ------------------------------------------------------------------ + +float Float7e3To32(uint32_t f10) { + f10 &= 0x3FF; + if (!f10) return 0; + int mantissa = f10 & 0x7F, exponent = f10 >> 7; + if (!exponent) { + const int lz = 7 - (31 - __builtin_clz(uint32_t(mantissa))); + exponent = 1 - lz; + mantissa = (mantissa << lz) & 0x7F; + } + return F(uint32_t(((exponent + 124) << 23) | (mantissa << 16))); +} +float Float20e4To32(uint32_t f24) { + f24 &= 0xFFFFFF; + if (!f24) return 0; + int mantissa = f24 & 0xFFFFF, exponent = f24 >> 20; + if (!exponent) { + const int lz = 20 - (31 - __builtin_clz(uint32_t(mantissa))); + exponent = 1 - lz; + mantissa = (mantissa << lz) & 0xFFFFF; + } + return F(uint32_t(((exponent + 112) << 23) | (mantissa << 3))); +} +float HalfToFloat(uint32_t h) { + const float s = (h & 0x8000) ? -1.f : 1.f; + const int e = (h >> 10) & 31, m = h & 1023; + if (!e) return s * m * std::ldexp(1.f, -24); + if (e == 31) return m ? NAN : s * INFINITY; + return s * (1 + m / 1024.f) * std::ldexp(1.f, e - 15); +} +WGPUColor ColorClearValue(uint32_t format, uint32_t lo, uint32_t hi) { + const uint64_t v = uint64_t(lo) | (uint64_t(hi) << 32); + auto bits = [&](int shift, int n) { return uint32_t((v >> shift) & ((1ull << n) - 1)); }; + auto s16 = [](uint32_t x) { return std::max(double(int16_t(x)) / 32767.0, -1.0); }; + switch (format) { + case 0: case 1: return {bits(0, 8) / 255.0, bits(8, 8) / 255.0, bits(16, 8) / 255.0, bits(24, 8) / 255.0}; + case 2: case 10: return {bits(0, 10) / 1023.0, bits(10, 10) / 1023.0, bits(20, 10) / 1023.0, bits(30, 2) / 3.0}; + case 3: case 12: return {Float7e3To32(bits(0, 10)), Float7e3To32(bits(10, 10)), Float7e3To32(bits(20, 10)), bits(30, 2) / 3.0}; + case 4: return {s16(bits(0, 16)), s16(bits(16, 16)), 0, 0}; + case 5: return {s16(bits(0, 16)), s16(bits(16, 16)), s16(bits(32, 16)), s16(bits(48, 16))}; + case 6: return {HalfToFloat(bits(0, 16)), HalfToFloat(bits(16, 16)), 0, 0}; + case 7: return {HalfToFloat(bits(0, 16)), HalfToFloat(bits(16, 16)), HalfToFloat(bits(32, 16)), HalfToFloat(bits(48, 16))}; + case 14: return {F(lo), 0, 0, 0}; + case 15: return {F(lo), F(hi), 0, 0}; + default: return {0, 0, 0, 0}; + } +} + +// A CPU ring written to a GPU buffer in one writeBuffer on flush (XenosRing). +struct Ring { + WGPUBuffer buffer = nullptr; + std::vector cpu; + uint64_t offset = 0, size = 0, limit = 0; + uint32_t align = 4; + bool Fits(uint64_t bytes) const { return offset + ((bytes + align - 1) & ~uint64_t(align - 1)) <= limit; } + uint32_t Push(const void* data, uint64_t bytes) { + const uint64_t at = offset; + std::memcpy(cpu.data() + at, data, bytes); + offset = at + ((bytes + align - 1) & ~uint64_t(align - 1)); + return uint32_t(at); + } + void Flush(WGPUQueue queue) { + if (offset) wgpuQueueWriteBuffer(queue, buffer, 0, cpu.data(), offset); + offset = 0; + } +}; + +struct Shader { + uint32_t id = 0, stage = 0; + std::map input_interpolation; // pixel shaders + std::vector textures, samplers; + std::vector bindings; + WGPUShaderModule module = nullptr; + std::string error; +}; + +struct GroupLayout { + std::string key; + WGPUBindGroupLayout layout = nullptr; + std::vector entries; + WGPUBindGroup group = nullptr; // placeholder / constant group +}; + +struct PipelineDescription { + uint32_t vertex_shader, pixel_shader, topology, cull_mode, front_face_cw, depth_compare, depth_write, stencil, + stencil_masks, color_formats[4], color_write_masks, blend_control[4], depth_format, msaa_samples; +}; + +struct Pipeline { + PipelineDescription d{}; + WGPURenderPipeline pipeline = nullptr; + GroupLayout* layouts[4] = {}; + std::string error; +}; + +struct RenderTargetsKey { + uint32_t surface_pitch = 0, msaa = 0, height = 0, color_base[4]{}, color_format[4]{}, depth_base = 0, + depth_format = 0; +}; + +struct Target { + std::string key; + uint32_t base = 0, guest_format = 0, msaa = 0, width = 0, height = 0; + bool depth = false, initialized = false, is64bpp = false; + uint32_t tile_width = 0, tile_height = 0, pitch_tiles = 0; + WGPUTexture texture = nullptr; + WGPUTextureView view = nullptr; + WGPUTextureFormat format = WGPUTextureFormat_Undefined; +}; + +struct Texture { + uint32_t id = 0, dimension = 0, width = 0, height = 0; + WGPUTexture texture = nullptr; + WGPUTextureFormat format = WGPUTextureFormat_Undefined; + std::map views; +}; + +struct LoadShader { + WGPUComputePipeline pipeline = nullptr; + WGPUBindGroupLayout layouts[2] = {}; + uint32_t immediate_size = 0; + std::string error; +}; + +class BackendImpl final : public Backend { + public: + WGPUInstance instance_ = nullptr; + WGPUAdapter adapter_ = nullptr; + WGPUDevice device_ = nullptr; + WGPUQueue queue_ = nullptr; + WGPUSurface surface_ = nullptr; + WGPUTextureFormat surface_format_ = WGPUTextureFormat_BGRA8Unorm; + uint32_t surface_w_ = 0, surface_h_ = 0; + std::string adapter_name_, last_error_; + Stats stats_; + bool float32_filterable_ = false, depth32_stencil8_ = false; + uint64_t shared_memory_bytes_ = SHARED_MEMORY_BYTES; + uint32_t uniform_align_ = 256; + + WGPUBuffer shared_memory_ = nullptr, staging_ = nullptr, edram_ = nullptr; + uint64_t staging_offset_ = 0; + WGPUCommandEncoder encoder_ = nullptr; + WGPURenderPassEncoder pass_ = nullptr; + struct { WGPURenderPipeline pipeline = nullptr; WGPUBindGroup groups[4] = {}; } pass_state_; + uint32_t pass_w_ = 0, pass_h_ = 0; + Ring uniforms_, indices_; + std::unordered_map shaders_; + std::unordered_map pipelines_; + std::map> layouts_; + std::map placeholders_; // key -> WGPUSampler / WGPUTextureView + std::map> targets_; + RenderTargetsKey bound_{}; + bool have_bound_ = false; + std::unordered_map load_shaders_; + std::unordered_map textures_; + std::unordered_map samplers_; + std::unordered_map texture_groups_; + WGPUBuffer scratch_ = nullptr; + uint64_t scratch_size_ = 0; + std::vector scratch_retired_; + std::vector tile_owner_ = std::vector(EDRAM_TILES, nullptr); + Texture* front_ = nullptr; + uint32_t front_swizzle_ = 0x688; + std::map expand_pipelines_; + WGPUComputePipeline dump_pipelines_[2] = {}; + std::map, WGPURenderPipeline> clear_pipelines_; + WGPUBindGroupLayout clear_layout_ = nullptr; + WGPUBindGroup clear_group_ = nullptr; + WGPURenderPipeline present_pipeline_ = nullptr; + WGPUBuffer present_swizzle_ = nullptr; + WGPUSampler present_sampler_ = nullptr; + + ~BackendImpl() override { + if (device_) wgpuDeviceRelease(device_); + if (instance_) wgpuInstanceRelease(instance_); + } + + uint32_t swaps() const override { return uint32_t(stats_.swaps); } + const Stats& stats() const override { return stats_; } + std::string last_error() const override { return last_error_; } + std::string adapter_name() const override { return adapter_name_; } + + void NoteError(const std::string& e) { + ++stats_.errors; + if (stats_.errors <= 20) std::fprintf(stderr, "R360_WGPU error: %s\n", e.c_str()); + last_error_ = e; + } + + WGPUBuffer MakeBuffer(const char* label, uint64_t size, WGPUBufferUsage usage) { + WGPUBufferDescriptor d = WGPU_BUFFER_DESCRIPTOR_INIT; + d.label = S(label); + d.size = size; + d.usage = usage; + return wgpuDeviceCreateBuffer(device_, &d); + } + + WGPUShaderModule WgslModule(const std::string& code, const char* label) { + WGPUShaderSourceWGSL src = WGPU_SHADER_SOURCE_WGSL_INIT; + src.code = S(code); + WGPUShaderModuleDescriptor d = WGPU_SHADER_MODULE_DESCRIPTOR_INIT; + d.nextInChain = &src.chain; + d.label = S(label); + return wgpuDeviceCreateShaderModule(device_, &d); + } + WGPUShaderModule SpirvModule(const uint32_t* words, size_t count, const char* label) { + WGPUShaderSourceSPIRV src = WGPU_SHADER_SOURCE_SPIRV_INIT; + src.codeSize = uint32_t(count); + src.code = words; + WGPUShaderModuleDescriptor d = WGPU_SHADER_MODULE_DESCRIPTOR_INIT; + d.nextInChain = &src.chain; + d.label = S(label); + return wgpuDeviceCreateShaderModule(device_, &d); + } + + // Errors raised inside a scope are returned instead of reaching the + // uncaptured-error handler (createRenderPipeline's throw in the JS). + void PushScope() { wgpuDevicePushErrorScope(device_, WGPUErrorFilter_Validation); } + std::string PopScope() { + struct R { std::string message; bool done = false; } r; + WGPUPopErrorScopeCallbackInfo info = WGPU_POP_ERROR_SCOPE_CALLBACK_INFO_INIT; + info.mode = WGPUCallbackMode_AllowProcessEvents; + info.callback = [](WGPUPopErrorScopeStatus, WGPUErrorType type, WGPUStringView message, void* u, void*) { + auto* r = static_cast(u); + if (type != WGPUErrorType_NoError) r->message.assign(message.data ? message.data : "", message.data ? message.length : 0); + r->done = true; + }; + info.userdata1 = &r; + wgpuDevicePopErrorScope(device_, info); + while (!r.done) wgpuInstanceProcessEvents(instance_); + return r.message; + } + + bool Init(void* metal_layer, std::string* error) { + WGPUInstanceDescriptor id = WGPU_INSTANCE_DESCRIPTOR_INIT; + instance_ = wgpuCreateInstance(&id); + if (!instance_) { *error = "wgpuCreateInstance failed"; return false; } + if (metal_layer) { + WGPUSurfaceSourceMetalLayer src = WGPU_SURFACE_SOURCE_METAL_LAYER_INIT; + src.layer = metal_layer; + WGPUSurfaceDescriptor sd = WGPU_SURFACE_DESCRIPTOR_INIT; + sd.nextInChain = &src.chain; + surface_ = wgpuInstanceCreateSurface(instance_, &sd); + } + WGPURequestAdapterOptions ao = WGPU_REQUEST_ADAPTER_OPTIONS_INIT; + ao.powerPreference = WGPUPowerPreference_HighPerformance; + ao.compatibleSurface = surface_; + struct A { WGPUAdapter adapter = nullptr; std::string message; bool done = false; } a; + WGPURequestAdapterCallbackInfo ai = WGPU_REQUEST_ADAPTER_CALLBACK_INFO_INIT; + ai.mode = WGPUCallbackMode_AllowProcessEvents; + ai.callback = [](WGPURequestAdapterStatus, WGPUAdapter adapter, WGPUStringView m, void* u, void*) { + auto* a = static_cast(u); + a->adapter = adapter; + if (m.data) a->message.assign(m.data, m.length); + a->done = true; + }; + ai.userdata1 = &a; + wgpuInstanceRequestAdapter(instance_, &ao, ai); + while (!a.done) wgpuInstanceProcessEvents(instance_); + if (!a.adapter) { *error = "no GPU adapter: " + a.message; return false; } + adapter_ = a.adapter; + WGPUAdapterInfo info = WGPU_ADAPTER_INFO_INIT; + wgpuAdapterGetInfo(adapter_, &info); + if (info.device.data) adapter_name_.assign(info.device.data, info.device.length); + wgpuAdapterInfoFreeMembers(info); + + WGPULimits limits = WGPU_LIMITS_INIT; + wgpuAdapterGetLimits(adapter_, &limits); + float32_filterable_ = wgpuAdapterHasFeature(adapter_, WGPUFeatureName_Float32Filterable); + depth32_stencil8_ = wgpuAdapterHasFeature(adapter_, WGPUFeatureName_Depth32FloatStencil8); + std::vector features; + if (float32_filterable_) features.push_back(WGPUFeatureName_Float32Filterable); + if (depth32_stencil8_) features.push_back(WGPUFeatureName_Depth32FloatStencil8); + features.push_back(WGPUFeatureName(WGPUNativeFeature_Immediates)); + if (wgpuAdapterHasFeature(adapter_, WGPUFeatureName(WGPUNativeFeature_TextureFormat16bitNorm))) + features.push_back(WGPUFeatureName(WGPUNativeFeature_TextureFormat16bitNorm)); + // Shared memory: Xenia's 512 MiB or the largest power of two allowed + // (sharedMemoryBytesForLimits). + const uint64_t max_buffer = std::min(limits.maxBufferSize, limits.maxStorageBufferBindingSize); + while (shared_memory_bytes_ > max_buffer) shared_memory_bytes_ /= 2; + WGPULimits required = limits; // everything the adapter offers + required.maxImmediateSize = std::max(limits.maxImmediateSize, 128); + uniform_align_ = limits.minUniformBufferOffsetAlignment ? limits.minUniformBufferOffsetAlignment : 256; + + WGPUDeviceDescriptor dd = WGPU_DEVICE_DESCRIPTOR_INIT; + dd.label = S("Render360 Xenos"); + dd.requiredFeatureCount = features.size(); + dd.requiredFeatures = features.data(); + dd.requiredLimits = &required; + dd.uncapturedErrorCallbackInfo.callback = [](WGPUDevice const*, WGPUErrorType, WGPUStringView m, void* u, void*) { + static_cast(u)->NoteError(std::string(m.data ? m.data : "", m.data ? m.length : 0)); + }; + dd.uncapturedErrorCallbackInfo.userdata1 = this; + struct D { WGPUDevice device = nullptr; std::string message; bool done = false; } d; + WGPURequestDeviceCallbackInfo di = WGPU_REQUEST_DEVICE_CALLBACK_INFO_INIT; + di.mode = WGPUCallbackMode_AllowProcessEvents; + di.callback = [](WGPURequestDeviceStatus, WGPUDevice device, WGPUStringView m, void* u, void*) { + auto* d = static_cast(u); + d->device = device; + if (m.data) d->message.assign(m.data, m.length); + d->done = true; + }; + di.userdata1 = &d; + wgpuAdapterRequestDevice(adapter_, &dd, di); + while (!d.done) wgpuInstanceProcessEvents(instance_); + if (!d.device) { *error = "no GPU device: " + d.message; return false; } + device_ = d.device; + queue_ = wgpuDeviceGetQueue(device_); + + shared_memory_ = MakeBuffer("Render360 shared memory", shared_memory_bytes_, + WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc); + staging_ = MakeBuffer("Render360 upload staging", STAGING_BYTES, WGPUBufferUsage_CopySrc | WGPUBufferUsage_CopyDst); + edram_ = MakeBuffer("Render360 EDRAM", uint64_t(EDRAM_TILES) * EDRAM_TILE_DWORDS * 4, + WGPUBufferUsage_Storage | WGPUBufferUsage_CopySrc | WGPUBufferUsage_CopyDst); + uniforms_.size = 8ull * 1024 * 1024 + CONSTANT_WINDOW; + uniforms_.limit = 8ull * 1024 * 1024; + uniforms_.align = uniform_align_; + uniforms_.cpu.resize(uniforms_.size); + uniforms_.buffer = MakeBuffer("Render360 constants", uniforms_.size, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst); + indices_.size = indices_.limit = 8ull * 1024 * 1024; + indices_.cpu.resize(indices_.size); + indices_.buffer = MakeBuffer("Render360 indices", indices_.size, WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst); + return true; + } + + WGPUCommandEncoder Encoder() { + if (!encoder_) { + WGPUCommandEncoderDescriptor d = WGPU_COMMAND_ENCODER_DESCRIPTOR_INIT; + encoder_ = wgpuDeviceCreateCommandEncoder(device_, &d); + } + return encoder_; + } + + void Submit() { + EndPass(); + uniforms_.Flush(queue_); + indices_.Flush(queue_); + if (encoder_) { + WGPUCommandBufferDescriptor d = WGPU_COMMAND_BUFFER_DESCRIPTOR_INIT; + WGPUCommandBuffer cmd = wgpuCommandEncoderFinish(encoder_, &d); + wgpuQueueSubmit(queue_, 1, &cmd); + wgpuCommandBufferRelease(cmd); + wgpuCommandEncoderRelease(encoder_); + encoder_ = nullptr; + ++stats_.submits; + } + for (WGPUBuffer b : scratch_retired_) { wgpuBufferDestroy(b); wgpuBufferRelease(b); } + scratch_retired_.clear(); + staging_offset_ = 0; + pre_shaded_offset_ = 0; + } + + void EndPass() { + if (pass_) { + wgpuRenderPassEncoderEnd(pass_); + wgpuRenderPassEncoderRelease(pass_); + pass_ = nullptr; + } + } + + void ReplayCore() override { + const uint32_t count = r360_gpu_stream_words(); + if (!count) return; + ReplayWords(reinterpret_cast(r360_gpu_stream_data()), count); + r360_gpu_stream_reset(); + } + + void ReplayWords(const uint32_t* words, size_t count) override { + for (size_t i = 0; i < count;) { + const uint32_t op = words[i] & 0xFF, n = words[i] >> 8; + if (i + 1 + n > count) break; + const uint32_t* p = words + i + 1; + switch (op) { + case GPU_STREAM_UPLOAD: Upload(p[0], p[1], reinterpret_cast(p + 2)); break; + case GPU_STREAM_SHADER: DefineShader(p, n); break; + case GPU_STREAM_PIPELINE: DefinePipeline(p, n); break; + case GPU_STREAM_RENDER_TARGETS: EndPass(); ParseRenderTargets(p); break; + case GPU_STREAM_DRAW: Draw(p, n); break; + case GPU_STREAM_SWAP: { + ++stats_.swaps; + auto it = n > 6 ? textures_.find(p[6]) : textures_.end(); + front_ = it == textures_.end() ? nullptr : &it->second; + front_swizzle_ = n > 7 ? p[7] : 0x688; + Submit(); + break; + } + case GPU_STREAM_EDRAM_DUMP: DumpEdram(p); break; + case GPU_STREAM_RESOLVE: Resolve(p); break; + case GPU_STREAM_CLEAR: Clear(p); break; + case GPU_STREAM_LOAD_SHADER: DefineLoadShader(p, n); break; + case GPU_STREAM_TEXTURE: DefineTexture(p); break; + case GPU_STREAM_TEXTURE_LOAD: LoadTexture(p, n); break; + default: + NoteError("unknown GPU stream op " + std::to_string(op)); + return; + } + i += 1 + n; + } + } + + void DefineShader(const uint32_t* p, uint32_t n) { + Shader s; + s.id = p[0]; + s.stage = p[1]; + const uint32_t tc = p[2], sc = p[3], words = p[4]; + s.textures.assign(p + 5, p + 5 + tc); + s.samplers.assign(p + 5 + tc, p + 5 + tc + sc); + const uint32_t* spirv = p + 5 + tc + sc; + if (5 + tc + sc + words > n) { s.error = "truncated"; shaders_[s.id] = s; return; } + s.bindings = ReflectBindings(spirv, words); + if (s.stage) s.input_interpolation = ReflectInputInterpolation(spirv, words); + // Xenia sets OpExecutionMode EarlyFragmentTests on pixel shaders without + // depth writes or kills; wgpu rejects the capability. It is only a hint: + // Metal tests depth early by itself for such shaders. + std::vector code; + code.reserve(words); + code.insert(code.end(), spirv, spirv + std::min(words, 5)); + for (uint32_t i = 5; i < words;) { + const uint32_t count = spirv[i] >> 16, op = spirv[i] & 0xFFFF; + if (!count || i + count > words) break; + if (!(op == 16 && count >= 3 && spirv[i + 2] == 9)) code.insert(code.end(), spirv + i, spirv + i + count); + i += count; + } + PushScope(); + char label[64]; + std::snprintf(label, sizeof(label), "Xenos %s shader %u", s.stage ? "pixel" : "vertex", s.id); + s.module = SpirvModule(code.data(), code.size(), label); + s.error = PopScope(); + if (!s.error.empty()) { + ++stats_.shader_failures; + if (stats_.shader_failures <= 5) std::fprintf(stderr, "R360_WGPU shader %u: %s\n", s.id, s.error.c_str()); + s.module = nullptr; + } + shaders_[s.id] = std::move(s); + ++stats_.shaders; + } + + WGPUTextureFormat DepthFormat(uint32_t guest) const { + return guest == 1 && depth32_stencil8_ ? WGPUTextureFormat_Depth32FloatStencil8 : WGPUTextureFormat_Depth24PlusStencil8; + } + + // groupLayout: bind group layout (and placeholder / constant group). + GroupLayout* Layout(uint32_t group, const std::vector& shaders, std::string* error) { + std::map entries; + if (group == 1) { + for (uint32_t b = 0; b < 5; ++b) { + WGPUBindGroupLayoutEntry e = WGPU_BIND_GROUP_LAYOUT_ENTRY_INIT; + e.binding = b; + e.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment; + e.buffer.type = WGPUBufferBindingType_Uniform; + e.buffer.hasDynamicOffset = true; + entries[b] = e; + } + } else { + for (const Shader* s : shaders) { + for (const Binding& d : s->bindings) { + if (d.group != group) continue; + const WGPUShaderStage vis = s->stage ? WGPUShaderStage_Fragment : WGPUShaderStage_Vertex; + auto it = entries.find(d.binding); + if (it != entries.end()) { it->second.visibility |= vis; continue; } + WGPUBindGroupLayoutEntry e = WGPU_BIND_GROUP_LAYOUT_ENTRY_INIT; + e.binding = d.binding; + e.visibility = vis; + switch (d.kind) { + case Binding::kStorage: + if (d.write && !s->stage) { *error = "vertex shader memory export is not supported yet"; return nullptr; } + e.buffer.type = d.write ? WGPUBufferBindingType_Storage : WGPUBufferBindingType_ReadOnlyStorage; + break; + case Binding::kUniform: e.buffer.type = WGPUBufferBindingType_Uniform; break; + case Binding::kSampler: + e.sampler.type = d.comparison ? WGPUSamplerBindingType_Comparison : WGPUSamplerBindingType_Filtering; + break; + case Binding::kTexture: + e.texture.sampleType = d.sample; + e.texture.viewDimension = d.view; + e.texture.multisampled = false; + break; + default: *error = "unsupported SPIR-V binding"; return nullptr; + } + entries[d.binding] = e; + } + } + } + std::string key = std::to_string(group) + ":"; + std::vector list; + for (auto& [b, e] : entries) { + list.push_back(e); + char k[96]; + std::snprintf(k, sizeof(k), "%u/%u/%d%d/%d/%d%d%d|", e.binding, unsigned(e.visibility), int(e.buffer.type), + int(e.buffer.hasDynamicOffset), int(e.sampler.type), int(e.texture.sampleType), + int(e.texture.viewDimension), 0); + key += k; + } + auto found = layouts_.find(key); + if (found != layouts_.end()) return found->second.get(); + auto gl = std::make_unique(); + gl->key = key; + gl->entries = list; + WGPUBindGroupLayoutDescriptor ld = WGPU_BIND_GROUP_LAYOUT_DESCRIPTOR_INIT; + ld.entryCount = list.size(); + ld.entries = list.data(); + gl->layout = wgpuDeviceCreateBindGroupLayout(device_, &ld); + std::vector ge; + for (const auto& e : list) { + WGPUBindGroupEntry g = WGPU_BIND_GROUP_ENTRY_INIT; + g.binding = e.binding; + if (group == 1) { + g.buffer = uniforms_.buffer; + g.size = CONSTANT_WINDOW; + } else { + Placeholder(e, &g); + } + ge.push_back(g); + } + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = gl->layout; + gd.entryCount = ge.size(); + gd.entries = ge.data(); + gl->group = wgpuDeviceCreateBindGroup(device_, &gd); + GroupLayout* raw = gl.get(); + layouts_[key] = std::move(gl); + return raw; + } + + // placeholderResource: shared memory, a 1x1 texture or a sampler. + void Placeholder(const WGPUBindGroupLayoutEntry& e, WGPUBindGroupEntry* g) { + if (e.buffer.type != WGPUBufferBindingType_BindingNotUsed && e.buffer.type != WGPUBufferBindingType_Undefined) { + g->buffer = shared_memory_; + g->size = shared_memory_bytes_; + return; + } + if (e.sampler.type != WGPUSamplerBindingType_BindingNotUsed && e.sampler.type != WGPUSamplerBindingType_Undefined) { + const bool cmp = e.sampler.type == WGPUSamplerBindingType_Comparison; + const std::string key = cmp ? "sampler:cmp" : "sampler:filter"; + if (!placeholders_.count(key)) { + WGPUSamplerDescriptor sd = WGPU_SAMPLER_DESCRIPTOR_INIT; + if (cmp) sd.compare = WGPUCompareFunction_Less; + else sd.magFilter = sd.minFilter = WGPUFilterMode_Linear; + placeholders_[key] = wgpuDeviceCreateSampler(device_, &sd); + } + g->sampler = static_cast(placeholders_[key]); + return; + } + const auto st = e.texture.sampleType; + const auto vd = e.texture.viewDimension; + const std::string key = "texture:" + std::to_string(int(st)) + ":" + std::to_string(int(vd)); + if (!placeholders_.count(key)) { + const WGPUTextureFormat format = st == WGPUTextureSampleType_Sint ? WGPUTextureFormat_RGBA8Sint + : st == WGPUTextureSampleType_Uint ? WGPUTextureFormat_RGBA8Uint + : st == WGPUTextureSampleType_Depth ? WGPUTextureFormat_Depth32Float + : WGPUTextureFormat_RGBA8Unorm; + const uint32_t layers = (vd == WGPUTextureViewDimension_Cube || vd == WGPUTextureViewDimension_CubeArray) ? 6 : 1; + WGPUTextureDescriptor td = WGPU_TEXTURE_DESCRIPTOR_INIT; + td.format = format; + td.dimension = vd == WGPUTextureViewDimension_3D ? WGPUTextureDimension_3D : WGPUTextureDimension_2D; + td.size = {1, 1, layers}; + td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst; + WGPUTexture tex = wgpuDeviceCreateTexture(device_, &td); + if (format != WGPUTextureFormat_Depth32Float) { + std::vector texel(4 * layers, 255); + WGPUTexelCopyTextureInfo dst = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT; + dst.texture = tex; + WGPUTexelCopyBufferLayout layout = WGPU_TEXEL_COPY_BUFFER_LAYOUT_INIT; + layout.bytesPerRow = 4; + layout.rowsPerImage = 1; + WGPUExtent3D size{1, 1, layers}; + wgpuQueueWriteTexture(queue_, &dst, texel.data(), texel.size(), &layout, &size); + } + WGPUTextureViewDescriptor vdsc = WGPU_TEXTURE_VIEW_DESCRIPTOR_INIT; + vdsc.dimension = vd; + placeholders_[key] = wgpuTextureCreateView(tex, &vdsc); + } + g->textureView = static_cast(placeholders_[key]); + } + + void DefinePipeline(const uint32_t* p, uint32_t n) { + const uint32_t id = p[0]; + Pipeline entry; + if (n < 21) { pipelines_[id] = entry; return; } + const uint32_t* w = p + 1; + PipelineDescription& d = entry.d; + d = {w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], w[8], {w[9], w[10], w[11], w[12]}, w[13], + {w[14], w[15], w[16], w[17]}, w[18], w[19]}; + auto fail = [&](const std::string& e) { + entry.error = e; + ++stats_.pipeline_failures; + if (stats_.pipeline_failures <= 5) std::fprintf(stderr, "R360_WGPU pipeline %u: %s\n", id, e.c_str()); + pipelines_[id] = entry; + }; + const Shader* ps = nullptr; + if (d.pixel_shader) { + auto it = shaders_.find(d.pixel_shader); + ps = it == shaders_.end() ? nullptr : &it->second; + } + const Shader* vs = nullptr; + if (d.vertex_shader & kPassthroughVertexShader) { + vs = PassthroughVertexShader(d.vertex_shader & 0xFF, ps); + } else { + auto vs_it = shaders_.find(d.vertex_shader); + vs = vs_it == shaders_.end() ? nullptr : &vs_it->second; + } + if (!vs || !vs->module) return fail("vertex shader " + std::to_string(d.vertex_shader) + ": " + (vs ? vs->error : "missing")); + if (d.pixel_shader && (!ps || !ps->module)) return fail("pixel shader " + std::to_string(d.pixel_shader) + ": " + (ps ? ps->error : "missing")); + std::vector both{vs}; + if (ps) both.push_back(ps); + std::string err; + WGPUBindGroupLayout bgl[4]; + for (uint32_t g = 0; g < 4; ++g) { + entry.layouts[g] = Layout(g, both, &err); + if (!entry.layouts[g]) return fail(err); + bgl[g] = entry.layouts[g]->layout; + } + WGPUPipelineLayoutDescriptor pld = WGPU_PIPELINE_LAYOUT_DESCRIPTOR_INIT; + pld.bindGroupLayoutCount = 4; + pld.bindGroupLayouts = bgl; + WGPUPipelineLayout layout = wgpuDeviceCreatePipelineLayout(device_, &pld); + + WGPUColorTargetState targets[4]; + WGPUBlendState blends[4]; + size_t target_count = 0; + for (uint32_t i = 0; i < 4; ++i) { + if (!d.color_formats[i]) continue; + while (target_count < i) { + targets[target_count] = WGPU_COLOR_TARGET_STATE_INIT; + targets[target_count].format = WGPUTextureFormat_Undefined; + ++target_count; + } + WGPUColorTargetState t = WGPU_COLOR_TARGET_STATE_INIT; + t.format = ColorFormat(d.color_formats[i] - 1); + t.writeMask = (d.color_write_masks >> (i * 4)) & 0xF; + if (BlendState(d.blend_control[i], &blends[i]) && Blendable(t.format)) t.blend = &blends[i]; + targets[target_count++] = t; + } + static const WGPUPrimitiveTopology kTopology[] = {WGPUPrimitiveTopology_PointList, WGPUPrimitiveTopology_LineList, + WGPUPrimitiveTopology_LineStrip, WGPUPrimitiveTopology_TriangleList, + WGPUPrimitiveTopology_TriangleStrip}; + static const WGPUCullMode kCull[] = {WGPUCullMode_None, WGPUCullMode_Front, WGPUCullMode_Back}; + WGPURenderPipelineDescriptor rd = WGPU_RENDER_PIPELINE_DESCRIPTOR_INIT; + rd.layout = layout; + rd.vertex.module = vs->module; + rd.vertex.entryPoint = S("main"); + rd.primitive.topology = kTopology[std::min(d.topology, 4)]; + rd.primitive.cullMode = kCull[std::min(d.cull_mode, 2)]; + rd.primitive.frontFace = d.front_face_cw ? WGPUFrontFace_CW : WGPUFrontFace_CCW; + rd.multisample.count = 1; + WGPUFragmentState fs = WGPU_FRAGMENT_STATE_INIT; + if (ps) { + fs.module = ps->module; + fs.entryPoint = S("main"); + fs.targetCount = target_count; + fs.targets = targets; + rd.fragment = &fs; + } + WGPUDepthStencilState ds = WGPU_DEPTH_STENCIL_STATE_INIT; + if (d.depth_format) { + const uint32_t st = d.stencil; + const bool on = (st & 1) != 0; + auto face = [](uint32_t func, uint32_t fail, uint32_t zpass, uint32_t zfail) { + WGPUStencilFaceState f = WGPU_STENCIL_FACE_STATE_INIT; + f.compare = COMPARE[func & 7]; + f.failOp = STENCIL_OP[fail & 7]; + f.depthFailOp = STENCIL_OP[zfail & 7]; + f.passOp = STENCIL_OP[zpass & 7]; + return f; + }; + WGPUStencilFaceState front = WGPU_STENCIL_FACE_STATE_INIT; + front.compare = WGPUCompareFunction_Always; + WGPUStencilFaceState back = front; + if (on) { + front = face((st >> 8) & 7, (st >> 11) & 7, (st >> 14) & 7, (st >> 17) & 7); + back = ((st >> 7) & 1) ? face((st >> 20) & 7, (st >> 23) & 7, (st >> 26) & 7, (st >> 29) & 7) : front; + } + ds.format = DepthFormat(d.depth_format - 1); + ds.depthWriteEnabled = d.depth_write ? WGPUOptionalBool_True : WGPUOptionalBool_False; + ds.depthCompare = COMPARE[d.depth_compare & 7]; + ds.stencilFront = front; + ds.stencilBack = back; + ds.stencilReadMask = on ? (d.stencil_masks >> 8) & 0xFF : 0xFF; + ds.stencilWriteMask = on ? (d.stencil_masks >> 16) & 0xFF : 0; + rd.depthStencil = &ds; + } + PushScope(); + entry.pipeline = wgpuDeviceCreateRenderPipeline(device_, &rd); + const std::string e = PopScope(); + wgpuPipelineLayoutRelease(layout); + if (!e.empty()) { + entry.pipeline = nullptr; + return fail(e); + } + ++stats_.pipelines; + pipelines_[id] = entry; + } + + // Vertex shader for CPU-shaded vertices (rectangle lists): reads host + // clip-space position and `count` interpolators per vertex from group 2 and + // matches the pixel shader's interpolation qualifiers. + std::map> passthrough_; + const Shader* PassthroughVertexShader(uint32_t count, const Shader* ps) { + std::string quals; + for (uint32_t i = 0; i < count; ++i) { + auto it = ps ? ps->input_interpolation.find(i) : std::map::const_iterator(); + quals += (ps && it != ps->input_interpolation.end()) ? it->second : std::string("@interpolate(perspective, center)"); + quals += ";"; + } + const std::string key = std::to_string(count) + ":" + quals; + auto found = passthrough_.find(key); + if (found != passthrough_.end()) return found->second.get(); + std::string wgsl = "@group(2) @binding(0) var xe_vertices: array>;\nstruct Out {\n @builtin(position) position: vec4,\n"; + size_t start = 0; + for (uint32_t i = 0; i < count; ++i) { + const size_t end = quals.find(';', start); + wgsl += " @location(" + std::to_string(i) + ") " + quals.substr(start, end - start) + " i" + std::to_string(i) + ": vec4,\n"; + start = end + 1; + } + wgsl += "}\n@vertex fn main(@builtin(vertex_index) v: u32) -> Out {\n let b = v * " + std::to_string(1 + count) + "u;\n var o: Out;\n o.position = xe_vertices[b];\n"; + for (uint32_t i = 0; i < count; ++i) wgsl += " o.i" + std::to_string(i) + " = xe_vertices[b + " + std::to_string(1 + i) + "u];\n"; + wgsl += " return o;\n}\n"; + auto shader = std::make_unique(); + shader->id = kPassthroughVertexShader | count; + shader->stage = 0; + Binding b; + b.group = 2; + b.binding = 0; + b.kind = Binding::kStorage; + b.write = false; + shader->bindings.push_back(b); + PushScope(); + shader->module = WgslModule(wgsl, "Render360 pass-through vertex shader"); + shader->error = PopScope(); + if (!shader->error.empty()) { + std::fprintf(stderr, "R360_WGPU pass-through VS: %s\n%s\n", shader->error.c_str(), wgsl.c_str()); + shader->module = nullptr; + } + const Shader* raw = shader.get(); + passthrough_[key] = std::move(shader); + return raw; + } + + // Storage ring for CPU-shaded vertices of pass-through draws. + WGPUBuffer pre_shaded_ = nullptr; + uint64_t pre_shaded_offset_ = 0; + static constexpr uint64_t kPreShadedBytes = 8ull * 1024 * 1024; + + void ParseRenderTargets(const uint32_t* w) { + bound_.surface_pitch = w[0]; + bound_.msaa = w[1]; + bound_.height = w[2]; + for (int i = 0; i < 4; ++i) { bound_.color_base[i] = w[3 + i]; bound_.color_format[i] = w[7 + i]; } + bound_.depth_base = w[11]; + bound_.depth_format = w[12]; + have_bound_ = true; + } + + // target(): host render target for an EDRAM base / format / pitch. + Target* GetTarget(uint32_t base, uint32_t guest_format, bool depth, uint32_t pitch, uint32_t height, uint32_t msaa) { + char kbuf[96]; + std::snprintf(kbuf, sizeof(kbuf), "%c:%u:%u:%u:%u", depth ? 'd' : 'c', base, guest_format, pitch, msaa); + const std::string key = kbuf; + auto it = targets_.find(key); + Target* old = it == targets_.end() ? nullptr : it->second.get(); + if (old && old->height >= height) return old; + auto t = std::make_unique(); + t->key = key; + t->base = base; + t->guest_format = guest_format; + t->depth = depth; + t->msaa = msaa; + t->format = depth ? DepthFormat(guest_format) : ColorFormat(guest_format); + t->width = pitch; + t->height = std::max({height, old ? old->height : 0u, 720u}); + WGPUTextureDescriptor td = WGPU_TEXTURE_DESCRIPTOR_INIT; + td.format = t->format; + td.size = {t->width, t->height, 1}; + td.usage = WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopySrc | + WGPUTextureUsage_CopyDst; + t->texture = wgpuDeviceCreateTexture(device_, &td); + t->view = wgpuTextureCreateView(t->texture, nullptr); + // tileGeometry + const uint32_t sx = msaa >= 2 ? 2 : 1, sy = msaa >= 1 ? 2 : 1; + t->is64bpp = !depth && Is64bpp(guest_format); + t->tile_width = (t->is64bpp ? 40 : 80) / sx; + t->tile_height = 16 / sy; + t->pitch_tiles = (pitch + t->tile_width - 1) / t->tile_width; + if (old) { + EndPass(); + WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT, dst = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT; + src.texture = old->texture; + dst.texture = t->texture; + WGPUExtent3D size{old->width, old->height, 1}; + wgpuCommandEncoderCopyTextureToTexture(Encoder(), &src, &dst, &size); + t->initialized = old->initialized; + for (auto& owner : tile_owner_) if (owner == old) owner = t.get(); + if (front_ == nullptr) {} + // The old texture is referenced by the recorded copy; release after submit. + wgpuTextureRelease(old->texture); + } + Target* raw = t.get(); + targets_[key] = std::move(t); + ++stats_.targets_created; + return raw; + } + + void Own(Target* t, uint32_t height) { + const uint32_t rows = (std::min(height, t->height) + t->tile_height - 1) / t->tile_height; + for (uint32_t r = 0; r < rows; ++r) + for (uint32_t c = 0; c < t->pitch_tiles; ++c) tile_owner_[(t->base + r * t->pitch_tiles + c) % EDRAM_TILES] = t; + } + + WGPURenderPassEncoder BeginPass() { + if (pass_) return pass_; + if (!have_bound_ || !bound_.surface_pitch) return nullptr; + const RenderTargetsKey& k = bound_; + WGPURenderPassColorAttachment colors[4]; + size_t color_count = 0; + std::vector used; + for (int i = 0; i < 4; ++i) { + if (k.color_base[i] == 0xFFFFFFFFu) continue; + Target* t = GetTarget(k.color_base[i], k.color_format[i], false, k.surface_pitch, k.height, k.msaa); + while (color_count < size_t(i)) { + colors[color_count] = WGPU_RENDER_PASS_COLOR_ATTACHMENT_INIT; + ++color_count; + } + WGPURenderPassColorAttachment a = WGPU_RENDER_PASS_COLOR_ATTACHMENT_INIT; + a.view = t->view; + a.loadOp = t->initialized ? WGPULoadOp_Load : WGPULoadOp_Clear; + a.clearValue = {0, 0, 0, 0}; + a.storeOp = WGPUStoreOp_Store; + colors[color_count++] = a; + used.push_back(t); + } + WGPURenderPassDescriptor pd = WGPU_RENDER_PASS_DESCRIPTOR_INIT; + pd.colorAttachmentCount = color_count; + pd.colorAttachments = colors; + WGPURenderPassDepthStencilAttachment ds = WGPU_RENDER_PASS_DEPTH_STENCIL_ATTACHMENT_INIT; + if (k.depth_base != 0xFFFFFFFFu) { + Target* d = GetTarget(k.depth_base, k.depth_format, true, k.surface_pitch, k.height, k.msaa); + ds.view = d->view; + ds.depthLoadOp = d->initialized ? WGPULoadOp_Load : WGPULoadOp_Clear; + ds.depthClearValue = 1; + ds.depthStoreOp = WGPUStoreOp_Store; + ds.stencilLoadOp = d->initialized ? WGPULoadOp_Load : WGPULoadOp_Clear; + ds.stencilClearValue = 0; + ds.stencilStoreOp = WGPUStoreOp_Store; + pd.depthStencilAttachment = &ds; + used.push_back(d); + } + if (used.empty()) return nullptr; + pass_w_ = used[0]->width; + pass_h_ = UINT32_MAX; + for (Target* t : used) { + t->initialized = true; + Own(t, k.height); + pass_h_ = std::min(pass_h_, t->height); + } + pass_ = wgpuCommandEncoderBeginRenderPass(Encoder(), &pd); + pass_state_ = {}; + ++stats_.render_passes; + return pass_; + } + + void Draw(const uint32_t* p, uint32_t n) { + if (n < DRAW_HEADER_WORDS) { ++stats_.skipped_draws; return; } + auto it = pipelines_.find(p[0]); + if (it == pipelines_.end() || !it->second.pipeline) { ++stats_.skipped_draws; return; } + Pipeline& entry = it->second; + const uint32_t counts[5] = {p[16], p[17], p[18], p[19], p[20]}; + const uint32_t index_format = p[21], vertex_count = p[22], binding_words = p[25]; + uint32_t o = DRAW_HEADER_WORDS; + const uint32_t* constants[5]; + uint64_t total = 0; + for (int i = 0; i < 5; ++i) { + constants[i] = p + o; + o += counts[i]; + total += ((counts[i] * 4ull) + uniforms_.align - 1) & ~uint64_t(uniforms_.align - 1); + } + const uint32_t* binding = p + o; + o += binding_words; + const uint32_t index_words = index_format == 2 ? vertex_count : index_format == 1 ? (vertex_count + 1) / 2 : 0; + const uint32_t* index_data = p + o; + const uint64_t index_bytes = index_format == 2 ? vertex_count * 4ull : vertex_count * 2ull; + if (o + index_words > n) { ++stats_.skipped_draws; return; } + const bool passthrough = (entry.d.vertex_shader & kPassthroughVertexShader) != 0; + const uint64_t pre_shaded_words = passthrough ? uint64_t(vertex_count) * (4 + 4 * (entry.d.vertex_shader & 0xFF)) : 0; + const uint32_t* pre_shaded = p + o + index_words; + if (o + index_words + pre_shaded_words > n) { ++stats_.skipped_draws; return; } + // Queue writes land before the whole submission runs, so every ring is + // reused only after a submit. + if (uniforms_.offset + total > uniforms_.limit || !indices_.Fits(index_bytes) || + (passthrough && pre_shaded_offset_ + pre_shaded_words * 4 > kPreShadedBytes)) { + Submit(); + } + WGPURenderPassEncoder pass = BeginPass(); + if (!pass) { ++stats_.skipped_draws; return; } + uint32_t offsets[5]; + for (int i = 0; i < 5; ++i) offsets[i] = uniforms_.Push(constants[i], counts[i] * 4ull); + const int64_t W = pass_w_, H = pass_h_; + const int64_t vx = std::clamp(p[1], 0, W), vy = std::clamp(p[2], 0, H); + const int64_t vw = std::min(p[3], W - vx), vh = std::min(p[4], H - vy); + const int64_t sx = std::min(p[7], W), sy = std::min(p[8], H); + const int64_t sw = std::min(p[9], W - sx), sh = std::min(p[10], H - sy); + if (vw <= 0 || vh <= 0 || sw <= 0 || sh <= 0) { ++stats_.skipped_draws; return; } + if (pass_state_.pipeline != entry.pipeline) { + wgpuRenderPassEncoderSetPipeline(pass, entry.pipeline); + pass_state_.pipeline = entry.pipeline; + } + WGPUBindGroup tg[2]; + TextureBindGroups(entry, binding, binding_words, tg); + WGPUBindGroup pre_shaded_group = nullptr; + if (passthrough) { + const uint64_t bytes = pre_shaded_words * 4; + if (!pre_shaded_) pre_shaded_ = MakeBuffer("Render360 CPU-shaded vertices", kPreShadedBytes, + WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst); + if (bytes > kPreShadedBytes) { ++stats_.skipped_draws; return; } + + wgpuQueueWriteBuffer(queue_, pre_shaded_, pre_shaded_offset_, pre_shaded, bytes); + pre_shaded_group = BufferGroup(entry.layouts[2]->layout, pre_shaded_, pre_shaded_offset_, bytes); + pre_shaded_offset_ = (pre_shaded_offset_ + bytes + 255) & ~255ull; + tg[0] = pre_shaded_group; + pass_state_.groups[2] = nullptr; + } + for (uint32_t g = 0; g < 4; ++g) { + WGPUBindGroup group = g >= 2 ? tg[g - 2] : entry.layouts[g]->group; + if (g == 1) { + wgpuRenderPassEncoderSetBindGroup(pass, 1, group, 5, offsets); + } else if (pass_state_.groups[g] != group) { + wgpuRenderPassEncoderSetBindGroup(pass, g, group, 0, nullptr); + pass_state_.groups[g] = group; + } + } + float z0 = std::clamp(F(p[5]), 0.f, 1.f), z1 = std::clamp(F(p[6]), 0.f, 1.f); + if (z0 > z1) std::swap(z0, z1); + wgpuRenderPassEncoderSetViewport(pass, float(vx), float(vy), float(vw), float(vh), z0, z1); + wgpuRenderPassEncoderSetScissorRect(pass, uint32_t(sx), uint32_t(sy), uint32_t(sw), uint32_t(sh)); + wgpuRenderPassEncoderSetStencilReference(pass, p[11]); + WGPUColor blend{F(p[12]), F(p[13]), F(p[14]), F(p[15])}; + wgpuRenderPassEncoderSetBlendConstant(pass, &blend); + if (pre_shaded_group) wgpuBindGroupRelease(pre_shaded_group); // the pass keeps it alive + if (index_format) { + const uint32_t offset = indices_.Push(index_data, index_bytes); + wgpuRenderPassEncoderSetIndexBuffer(pass, indices_.buffer, + index_format == 2 ? WGPUIndexFormat_Uint32 : WGPUIndexFormat_Uint16, offset, + index_bytes); + wgpuRenderPassEncoderDrawIndexed(pass, vertex_count, 1, 0, 0, 0); + } else { + wgpuRenderPassEncoderDraw(pass, vertex_count, 1, 0, 0); + } + ++stats_.draws; + } + + // textureBindGroups: groups 2 (vertex) and 3 (pixel) of a draw. + void TextureBindGroups(Pipeline& entry, const uint32_t* words, uint32_t word_count, WGPUBindGroup out[2]) { + uint32_t o = 0; + for (uint32_t g = 2; g < 4; ++g) { + const uint32_t sid = g == 2 ? entry.d.vertex_shader : entry.d.pixel_shader; + if (g == 2 && (sid & kPassthroughVertexShader)) { out[0] = entry.layouts[2]->group; continue; } + auto sit = shaders_.find(sid); + const Shader* shader = (sid || g == 2) && sit != shaders_.end() ? &sit->second : nullptr; + GroupLayout* layout = entry.layouts[g]; + if (!shader || layout->entries.empty()) { + out[g - 2] = layout->group; + if (shader) o += uint32_t(shader->textures.size() + shader->samplers.size()); + continue; + } + const uint32_t nt = uint32_t(shader->textures.size()), ns = uint32_t(shader->samplers.size()); + if (o + nt + ns > word_count) { out[g - 2] = layout->group; continue; } + const uint32_t* ids = words + o; + o += nt + ns; + std::string key = layout->key + "|"; + for (uint32_t i = 0; i < nt + ns; ++i) key += std::to_string(ids[i]) + ","; + auto found = texture_groups_.find(key); + if (found != texture_groups_.end()) { out[g - 2] = found->second; continue; } + if (texture_groups_.size() > 4096) { + for (auto& [k, bg] : texture_groups_) wgpuBindGroupRelease(bg); + texture_groups_.clear(); + } + std::vector ge; + for (const auto& e : layout->entries) { + WGPUBindGroupEntry b = WGPU_BIND_GROUP_ENTRY_INIT; + b.binding = e.binding; + const bool is_texture = e.texture.sampleType != WGPUTextureSampleType_BindingNotUsed && + e.texture.sampleType != WGPUTextureSampleType_Undefined; + const bool is_sampler = e.sampler.type != WGPUSamplerBindingType_BindingNotUsed && + e.sampler.type != WGPUSamplerBindingType_Undefined; + if (is_texture) { + WGPUTextureView view = nullptr; + if (e.binding < nt) { + auto t = textures_.find(ids[e.binding]); + if (t != textures_.end() && !(Unfilterable(t->second.format) && !float32_filterable_)) { + auto v = t->second.views.find(e.texture.viewDimension); + if (v != t->second.views.end()) view = v->second; + } + if (!view && ids[e.binding]) { + ++stats_.unbindable_textures; + if (stats_.unbindable_textures <= 5) { + auto tt = textures_.find(ids[e.binding]); + std::fprintf(stderr, "R360_WGPU unbindable texture id=%u found=%d format=%d want_view=%d views=%zu\n", + ids[e.binding], tt != textures_.end(), tt != textures_.end() ? int(tt->second.format) : -1, + int(e.texture.viewDimension), tt != textures_.end() ? tt->second.views.size() : 0); + } + } + } + if (view) b.textureView = view; else Placeholder(e, &b); + } else if (is_sampler && e.binding >= nt && e.binding < nt + ns && e.sampler.type == WGPUSamplerBindingType_Filtering) { + b.sampler = Sampler(ids[e.binding]); + } else { + Placeholder(e, &b); + } + ge.push_back(b); + } + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = layout->layout; + gd.entryCount = ge.size(); + gd.entries = ge.data(); + WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &gd); + texture_groups_[key] = group; + out[g - 2] = group; + } + } + + WGPUSampler Sampler(uint32_t parameters) { + auto it = samplers_.find(parameters); + if (it != samplers_.end()) return it->second; + auto address = [](uint32_t m) { + return m == 0 ? WGPUAddressMode_Repeat : m == 1 ? WGPUAddressMode_MirrorRepeat : WGPUAddressMode_ClampToEdge; + }; + const uint32_t mag = (parameters >> 11) & 1, min = (parameters >> 12) & 1, mip = (parameters >> 13) & 1; + const uint32_t aniso = (parameters >> 14) & 7, base_map = (parameters >> 17) & 1, min_level = (parameters >> 18) & 15; + WGPUSamplerDescriptor d = WGPU_SAMPLER_DESCRIPTOR_INIT; + d.addressModeU = address(parameters & 7); + d.addressModeV = address((parameters >> 3) & 7); + d.addressModeW = address((parameters >> 6) & 7); + d.magFilter = mag ? WGPUFilterMode_Linear : WGPUFilterMode_Nearest; + d.minFilter = min ? WGPUFilterMode_Linear : WGPUFilterMode_Nearest; + d.mipmapFilter = mip ? WGPUMipmapFilterMode_Linear : WGPUMipmapFilterMode_Nearest; + d.lodMinClamp = float(min_level); + d.lodMaxClamp = base_map ? min_level + 0.25f : 32.f; + // Anisotropy needs every filter linear. The owner's iPhone setting (GTA + // port): 16x anisotropic where the guest asks for it. + if (aniso >= 2 && mag && min && mip) d.maxAnisotropy = uint16_t(std::min(16u, 1u << (aniso - 1))); + WGPUSampler s = wgpuDeviceCreateSampler(device_, &d); + samplers_[parameters] = s; + return s; + } + + // defineLoadShader: one of Xenia's texture_load_* / resolve compute + // shaders, with its push constants kept (wgpu immediates). + void DefineLoadShader(const uint32_t* p, uint32_t n) { + const uint32_t index = p[0], words = p[1]; + LoadShader entry; + if (2 + words > n) { load_shaders_[index] = entry; return; } + std::vector spirv = StripNonReadable(p + 2, words); + const bool resolve = index >= 64; + PushScope(); + WGPUShaderModule module = SpirvModule(spirv.data(), spirv.size(), "Xenia texture load"); + WGPUBindGroupLayout layouts[2]; + for (int i = 0; i < 2; ++i) { + WGPUBindGroupLayoutEntry e = WGPU_BIND_GROUP_LAYOUT_ENTRY_INIT; + e.binding = 0; + e.visibility = WGPUShaderStage_Compute; + // Texture loads: group 0 destination, 1 source. Resolves: 0 EDRAM, 1 shared memory. + const bool writes = resolve ? i == 1 : i == 0; + e.buffer.type = writes ? WGPUBufferBindingType_Storage : WGPUBufferBindingType_ReadOnlyStorage; + WGPUBindGroupLayoutDescriptor ld = WGPU_BIND_GROUP_LAYOUT_DESCRIPTOR_INIT; + ld.entryCount = 1; + ld.entries = &e; + layouts[i] = wgpuDeviceCreateBindGroupLayout(device_, &ld); + entry.layouts[i] = layouts[i]; + } + entry.immediate_size = resolve ? 20 : 40; + WGPUPipelineLayoutDescriptor pld = WGPU_PIPELINE_LAYOUT_DESCRIPTOR_INIT; + pld.bindGroupLayoutCount = 2; + pld.bindGroupLayouts = layouts; + pld.immediateSize = 128; + WGPUComputePipelineDescriptor cd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT; + cd.layout = wgpuDeviceCreatePipelineLayout(device_, &pld); + cd.compute.module = module; + cd.compute.entryPoint = S("main"); + entry.pipeline = wgpuDeviceCreateComputePipeline(device_, &cd); + entry.error = PopScope(); + if (!entry.error.empty()) { + ++stats_.load_shader_failures; + if (stats_.load_shader_failures <= 5) std::fprintf(stderr, "R360_WGPU load shader %u: %s\n", index, entry.error.c_str()); + entry.pipeline = nullptr; + } + load_shaders_[index] = entry; + } + + void DefineTexture(const uint32_t* p) { + const uint32_t id = p[0], format_index = p[1], dimension = p[2], width = p[3], height = p[4], depth = p[5], + mips = p[6]; + auto old = textures_.find(id); + if (old != textures_.end()) { + if (front_ == &old->second) front_ = nullptr; + wgpuTextureDestroy(old->second.texture); + textures_.erase(old); + } + const WGPUTextureFormat format = TextureFormat(format_index); + if (getenv("R360_WGPU_LOG")) std::fprintf(stderr, "R360_WGPU texture id=%u format_index=%u dim=%u %ux%ux%u mips=%u\n", id, format_index, dimension, width, height, depth, mips); + if (format == WGPUTextureFormat_Undefined || !width || !height) { ++stats_.texture_failures; return; } + Texture t; + t.id = id; + t.format = format; + t.dimension = dimension; + t.width = width; + t.height = height; + const bool is3d = dimension == 1; + WGPUTextureDescriptor td = WGPU_TEXTURE_DESCRIPTOR_INIT; + td.format = format; + td.dimension = is3d ? WGPUTextureDimension_3D : WGPUTextureDimension_2D; + td.size = {width, height, std::max(depth, 1u)}; + td.mipLevelCount = std::max(mips, 1u); + td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst | WGPUTextureUsage_CopySrc; + t.texture = wgpuDeviceCreateTexture(device_, &td); + auto view = [&](WGPUTextureViewDimension d) { + WGPUTextureViewDescriptor vd = WGPU_TEXTURE_VIEW_DESCRIPTOR_INIT; + vd.dimension = d; + t.views[d] = wgpuTextureCreateView(t.texture, &vd); + }; + if (is3d) view(WGPUTextureViewDimension_3D); + else if (dimension == 2) view(WGPUTextureViewDimension_Cube); + else view(WGPUTextureViewDimension_2DArray); + textures_[id] = std::move(t); + for (auto& [k, bg] : texture_groups_) wgpuBindGroupRelease(bg); + texture_groups_.clear(); + ++stats_.textures; + } + + WGPUBindGroup BufferGroup(WGPUBindGroupLayout layout, WGPUBuffer buffer, uint64_t offset, uint64_t size) { + WGPUBindGroupEntry e = WGPU_BIND_GROUP_ENTRY_INIT; + e.binding = 0; + e.buffer = buffer; + e.offset = offset; + e.size = size; + WGPUBindGroupDescriptor d = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + d.layout = layout; + d.entryCount = 1; + d.entries = &e; + return wgpuDeviceCreateBindGroup(device_, &d); + } + + void LoadTexture(const uint32_t* p, uint32_t n) { + const uint32_t id = p[0], shader_index = p[1], expand = p[2], buffer_size = p[3], base_offset = p[4], + base_size = p[5], mips_offset = p[6], mips_size = p[7], dispatch_count = p[8], copy_count = p[9]; + auto t = textures_.find(id); + auto sh = load_shaders_.find(shader_index); + if (t == textures_.end() || sh == load_shaders_.end() || !sh->second.pipeline || + 10 + dispatch_count * 14 + copy_count * 8 > n) { + ++stats_.texture_load_failures; + return; + } + EndPass(); + const bool expanded = expand >= 1 && expand <= 4; + const uint64_t scratch_bytes = uint64_t(buffer_size) * (expanded ? 3 : 1) + 256; + if (!scratch_ || scratch_size_ < scratch_bytes) { + if (scratch_) scratch_retired_.push_back(scratch_); + uint64_t size = 1 << 20; + while (size < scratch_bytes) size *= 2; + scratch_ = MakeBuffer("Render360 texture load scratch", size, WGPUBufferUsage_Storage | WGPUBufferUsage_CopySrc); + scratch_size_ = size; + } + WGPUBindGroup dest = BufferGroup(sh->second.layouts[0], scratch_, 0, buffer_size); + WGPUBindGroup sources[2] = { + base_size ? BufferGroup(sh->second.layouts[1], shared_memory_, base_offset, base_size) : nullptr, + mips_size ? BufferGroup(sh->second.layouts[1], shared_memory_, mips_offset, mips_size) : nullptr}; + WGPUComputePassDescriptor cpd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT; + WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(Encoder(), &cpd); + wgpuComputePassEncoderSetPipeline(pass, sh->second.pipeline); + wgpuComputePassEncoderSetBindGroup(pass, 0, dest, 0, nullptr); + uint32_t o = 10; + for (uint32_t d = 0; d < dispatch_count; ++d, o += 14) { + WGPUBindGroup src = p[o] < 2 ? sources[p[o]] : nullptr; + if (!src) continue; + wgpuComputePassEncoderSetBindGroup(pass, 1, src, 0, nullptr); + wgpuComputePassEncoderSetImmediates(pass, 0, p + o + 1, 40); + wgpuComputePassEncoderDispatchWorkgroups(pass, p[o + 11], p[o + 12], p[o + 13]); + } + wgpuComputePassEncoderEnd(pass); + wgpuComputePassEncoderRelease(pass); + WGPUBuffer copy_source = scratch_; + uint64_t scale = 1, copy_base = 0; + if (expand) ExpandTexels(expand, buffer_size, ©_source, &scale, ©_base); + for (uint32_t c = 0; c < copy_count; ++c, o += 8) { + const uint32_t offset = p[o], bytes_per_row = p[o + 1], rows_per_image = p[o + 2], mip = p[o + 3], + layers = p[o + 4], width = p[o + 5], height = p[o + 6], depth = p[o + 7]; + WGPUTexelCopyBufferInfo src = WGPU_TEXEL_COPY_BUFFER_INFO_INIT; + src.buffer = copy_source; + src.layout.offset = copy_base + offset * scale; + src.layout.bytesPerRow = uint32_t(bytes_per_row * scale); + src.layout.rowsPerImage = rows_per_image; + WGPUTexelCopyTextureInfo dst = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT; + dst.texture = t->second.texture; + dst.mipLevel = mip; + WGPUExtent3D size{width, height, t->second.dimension == 1 ? depth : layers}; + wgpuCommandEncoderCopyBufferToTexture(Encoder(), &src, &dst, &size); + } + wgpuBindGroupRelease(dest); + for (WGPUBindGroup s : sources) if (s) wgpuBindGroupRelease(s); + ++stats_.texture_loads; + } + + void ExpandTexels(uint32_t mode, uint32_t buffer_size, WGPUBuffer* buffer, uint64_t* scale, uint64_t* base) { + WGPUComputePipeline& pipeline = expand_pipelines_[mode]; + if (!pipeline) { + WGPUShaderModule module = WgslModule(ExpandShader(mode), "Render360 texel expand"); + WGPUComputePipelineDescriptor cd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT; + cd.compute.module = module; + cd.compute.entryPoint = S("main"); + pipeline = wgpuDeviceCreateComputePipeline(device_, &cd); + } + const bool in_place = mode >= 5; + const uint64_t out = in_place ? 0 : ((buffer_size + 255ull) / 256) * 256; + WGPUBindGroupEntry e[2] = {WGPU_BIND_GROUP_ENTRY_INIT, WGPU_BIND_GROUP_ENTRY_INIT}; + e[0].binding = 0; e[0].buffer = scratch_; e[0].offset = 0; e[0].size = buffer_size; + e[1].binding = 1; e[1].buffer = scratch_; e[1].offset = out; e[1].size = buffer_size * 2ull; + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = wgpuComputePipelineGetBindGroupLayout(pipeline, 0); + gd.entryCount = in_place ? 1 : 2; + gd.entries = e; + WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &gd); + WGPUComputePassDescriptor cpd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT; + WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(Encoder(), &cpd); + wgpuComputePassEncoderSetPipeline(pass, pipeline); + wgpuComputePassEncoderSetBindGroup(pass, 0, group, 0, nullptr); + const uint32_t groups = (buffer_size / 4 + 63) / 64; + wgpuComputePassEncoderDispatchWorkgroups(pass, std::min(groups, 65535u), (groups + 65534) / 65535, 1); + wgpuComputePassEncoderEnd(pass); + wgpuComputePassEncoderRelease(pass); + wgpuBindGroupRelease(group); + *buffer = scratch_; + *scale = in_place ? 1 : 2; + *base = out; + } + + WGPUComputePipeline DumpPipeline(bool depth) { + WGPUComputePipeline& p = dump_pipelines_[depth ? 1 : 0]; + if (!p) { + WGPUShaderModule module = WgslModule(EdramDumpShader(depth), "Render360 EDRAM dump"); + WGPUComputePipelineDescriptor cd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT; + cd.compute.module = module; + cd.compute.entryPoint = S("main"); + p = wgpuDeviceCreateComputePipeline(device_, &cd); + } + return p; + } + + void DumpEdram(const uint32_t* p) { + const uint32_t base = p[0], row_length = p[1], rows = p[2], pitch = p[3]; + std::vector owners; + for (uint32_t r = 0; r < rows; ++r) + for (uint32_t c = 0; c < row_length; ++c) { + Target* o = tile_owner_[(base + r * pitch + c) % EDRAM_TILES]; + if (o && std::find(owners.begin(), owners.end(), o) == owners.end()) owners.push_back(o); + } + if (owners.empty()) return; + EndPass(); + for (Target* t : owners) { + const uint32_t delta = (base - t->base + EDRAM_TILES) % EDRAM_TILES; + const uint32_t row0 = delta / t->pitch_tiles, col0 = delta % t->pitch_tiles; + const uint32_t x0 = col0 * t->tile_width, y0 = row0 * t->tile_height; + const int64_t width = std::min(int64_t(t->width) - x0, int64_t(std::max(row_length, 1u)) * t->tile_width); + const int64_t height = std::min(int64_t(t->height) - y0, int64_t(rows) * t->tile_height); + if (width <= 0 || height <= 0) continue; + WGPUComputePipeline pipeline = DumpPipeline(t->depth); + const uint32_t constants[12] = {t->base, t->pitch_tiles, t->msaa, t->guest_format, x0, y0, uint32_t(width), + uint32_t(height), t->is64bpp ? 1u : 0u, + DepthFormat(t->guest_format) == WGPUTextureFormat_Depth32FloatStencil8 ? 1u : 0u, + 0, 0}; + if (!uniforms_.Fits(sizeof(constants))) Submit(); + const uint32_t offset = uniforms_.Push(constants, sizeof(constants)); + std::vector e(2, WGPU_BIND_GROUP_ENTRY_INIT); + e[0].binding = 0; e[0].buffer = edram_; e[0].size = WGPU_WHOLE_SIZE; + e[1].binding = 1; e[1].buffer = uniforms_.buffer; e[1].offset = offset; e[1].size = 48; + std::vector views; + if (t->depth) { + WGPUTextureViewDescriptor vd = WGPU_TEXTURE_VIEW_DESCRIPTOR_INIT; + vd.aspect = WGPUTextureAspect_DepthOnly; + views.push_back(wgpuTextureCreateView(t->texture, &vd)); + vd.aspect = WGPUTextureAspect_StencilOnly; + views.push_back(wgpuTextureCreateView(t->texture, &vd)); + WGPUBindGroupEntry d2 = WGPU_BIND_GROUP_ENTRY_INIT, d3 = WGPU_BIND_GROUP_ENTRY_INIT; + d2.binding = 2; d2.textureView = views[0]; + d3.binding = 3; d3.textureView = views[1]; + e.push_back(d2); + e.push_back(d3); + } else { + WGPUBindGroupEntry d2 = WGPU_BIND_GROUP_ENTRY_INIT; + d2.binding = 2; d2.textureView = t->view; + e.push_back(d2); + } + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = wgpuComputePipelineGetBindGroupLayout(pipeline, 0); + gd.entryCount = e.size(); + gd.entries = e.data(); + WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &gd); + WGPUComputePassDescriptor cpd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT; + WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(Encoder(), &cpd); + wgpuComputePassEncoderSetPipeline(pass, pipeline); + wgpuComputePassEncoderSetBindGroup(pass, 0, group, 0, nullptr); + wgpuComputePassEncoderDispatchWorkgroups(pass, uint32_t((width + 7) / 8), uint32_t((height + 7) / 8), 1); + wgpuComputePassEncoderEnd(pass); + wgpuComputePassEncoderRelease(pass); + wgpuBindGroupRelease(group); + for (auto v : views) wgpuTextureViewRelease(v); + ++stats_.dumps; + } + } + + void Resolve(const uint32_t* p) { + auto sh = load_shaders_.find(64 + p[0]); + if (sh == load_shaders_.end() || !sh->second.pipeline) { ++stats_.resolve_failures; return; } + const uint32_t groups_x = p[6], groups_y = p[7], offset = p[8], size = p[9]; + if (uint64_t(offset) + size > shared_memory_bytes_ || !size) { ++stats_.resolve_failures; return; } + EndPass(); + WGPUBindGroup src = BufferGroup(sh->second.layouts[0], edram_, 0, uint64_t(EDRAM_TILES) * EDRAM_TILE_DWORDS * 4); + WGPUBindGroup dst = BufferGroup(sh->second.layouts[1], shared_memory_, offset, size); + WGPUComputePassDescriptor cpd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT; + WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(Encoder(), &cpd); + wgpuComputePassEncoderSetPipeline(pass, sh->second.pipeline); + wgpuComputePassEncoderSetBindGroup(pass, 0, src, 0, nullptr); + wgpuComputePassEncoderSetBindGroup(pass, 1, dst, 0, nullptr); + wgpuComputePassEncoderSetImmediates(pass, 0, p + 1, 20); + wgpuComputePassEncoderDispatchWorkgroups(pass, groups_x, groups_y, 1); + wgpuComputePassEncoderEnd(pass); + wgpuComputePassEncoderRelease(pass); + wgpuBindGroupRelease(src); + wgpuBindGroupRelease(dst); + ++stats_.resolves; + } + + WGPUBindGroupLayout ClearLayout() { + if (!clear_layout_) { + WGPUBindGroupLayoutEntry e = WGPU_BIND_GROUP_LAYOUT_ENTRY_INIT; + e.binding = 0; + e.visibility = WGPUShaderStage_Fragment; + e.buffer.type = WGPUBufferBindingType_Uniform; + e.buffer.hasDynamicOffset = true; + WGPUBindGroupLayoutDescriptor ld = WGPU_BIND_GROUP_LAYOUT_DESCRIPTOR_INIT; + ld.entryCount = 1; + ld.entries = &e; + clear_layout_ = wgpuDeviceCreateBindGroupLayout(device_, &ld); + WGPUBindGroupEntry g = WGPU_BIND_GROUP_ENTRY_INIT; + g.binding = 0; g.buffer = uniforms_.buffer; g.size = 16; + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = clear_layout_; + gd.entryCount = 1; + gd.entries = &g; + clear_group_ = wgpuDeviceCreateBindGroup(device_, &gd); + } + return clear_layout_; + } + + WGPURenderPipeline ClearPipeline(const Target* t) { + auto& p = clear_pipelines_[{t->format, t->depth}]; + if (p) return p; + WGPUShaderModule module = WgslModule(CLEAR_SHADER, "Render360 clear"); + WGPUBindGroupLayout bgl = ClearLayout(); + WGPUPipelineLayoutDescriptor pld = WGPU_PIPELINE_LAYOUT_DESCRIPTOR_INIT; + pld.bindGroupLayoutCount = 1; + pld.bindGroupLayouts = &bgl; + WGPURenderPipelineDescriptor rd = WGPU_RENDER_PIPELINE_DESCRIPTOR_INIT; + rd.layout = wgpuDeviceCreatePipelineLayout(device_, &pld); + rd.vertex.module = module; + rd.vertex.entryPoint = S("vs"); + rd.primitive.topology = WGPUPrimitiveTopology_TriangleList; + rd.multisample.count = 1; + WGPUFragmentState fs = WGPU_FRAGMENT_STATE_INIT; + fs.module = module; + WGPUColorTargetState ct = WGPU_COLOR_TARGET_STATE_INIT; + WGPUDepthStencilState ds = WGPU_DEPTH_STENCIL_STATE_INIT; + if (t->depth) { + fs.entryPoint = S("fs_depth"); + WGPUStencilFaceState face = WGPU_STENCIL_FACE_STATE_INIT; + face.compare = WGPUCompareFunction_Always; + face.passOp = face.failOp = face.depthFailOp = WGPUStencilOperation_Replace; + ds.format = t->format; + ds.depthWriteEnabled = WGPUOptionalBool_True; + ds.depthCompare = WGPUCompareFunction_Always; + ds.stencilFront = ds.stencilBack = face; + ds.stencilWriteMask = 0xFF; + rd.depthStencil = &ds; + } else { + fs.entryPoint = S("fs_color"); + ct.format = t->format; + fs.targetCount = 1; + fs.targets = &ct; + } + rd.fragment = &fs; + p = wgpuDeviceCreateRenderPipeline(device_, &rd); + return p; + } + + void Clear(const uint32_t* p) { + const uint32_t is_depth = p[0], base = p[1], pitch_tiles = p[2], msaa = p[3], format = p[4], x = p[5], y = p[6], + width = p[7], height = p[8], lo = p[9], hi = p[10]; + EndPass(); + for (auto& [key, tp] : targets_) { + Target* t = tp.get(); + if (t->depth != !!is_depth || t->pitch_tiles != pitch_tiles || t->msaa != msaa || t->guest_format != format) continue; + const uint32_t delta = (base - t->base + EDRAM_TILES) % EDRAM_TILES; + const uint32_t x0 = (delta % pitch_tiles) * t->tile_width + x, y0 = (delta / pitch_tiles) * t->tile_height + y; + if (x0 >= t->width || y0 >= t->height) continue; + const uint32_t w = std::min(width, t->width - x0), h = std::min(height, t->height - y0); + const bool whole = x0 == 0 && y0 == 0 && w >= t->width && h >= t->height; + float depth_value = 0; + uint32_t stencil_value = 0; + WGPUColor color{0, 0, 0, 0}; + if (is_depth) { + const uint32_t d24 = (lo >> 8) & 0xFFFFFF; + depth_value = std::clamp(format == 1 ? Float20e4To32(d24) * 0.5f : d24 / float(0xFFFFFF), 0.f, 1.f); + stencil_value = lo & 0xFF; + } else { + color = ColorClearValue(format, lo, hi); + } + WGPURenderPassDescriptor pd = WGPU_RENDER_PASS_DESCRIPTOR_INIT; + WGPURenderPassColorAttachment ca = WGPU_RENDER_PASS_COLOR_ATTACHMENT_INIT; + WGPURenderPassDepthStencilAttachment da = WGPU_RENDER_PASS_DEPTH_STENCIL_ATTACHMENT_INIT; + if (is_depth) { + da.view = t->view; + da.depthLoadOp = whole ? WGPULoadOp_Clear : WGPULoadOp_Load; + da.depthClearValue = depth_value; + da.depthStoreOp = WGPUStoreOp_Store; + da.stencilLoadOp = whole ? WGPULoadOp_Clear : WGPULoadOp_Load; + da.stencilClearValue = stencil_value; + da.stencilStoreOp = WGPUStoreOp_Store; + pd.depthStencilAttachment = &da; + } else { + ca.view = t->view; + ca.loadOp = whole ? WGPULoadOp_Clear : WGPULoadOp_Load; + ca.clearValue = color; + ca.storeOp = WGPUStoreOp_Store; + pd.colorAttachmentCount = 1; + pd.colorAttachments = &ca; + } + if (!whole) { + const float words[4] = {is_depth ? depth_value : float(color.r), is_depth ? 0 : float(color.g), + is_depth ? 0 : float(color.b), is_depth ? 0 : float(color.a)}; + if (!uniforms_.Fits(sizeof(words))) Submit(); + const uint32_t at = uniforms_.Push(words, sizeof(words)); + WGPURenderPipeline pipeline = ClearPipeline(t); + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(Encoder(), &pd); + wgpuRenderPassEncoderSetPipeline(pass, pipeline); + wgpuRenderPassEncoderSetBindGroup(pass, 0, clear_group_, 1, &at); + wgpuRenderPassEncoderSetScissorRect(pass, x0, y0, w, h); + if (is_depth) wgpuRenderPassEncoderSetStencilReference(pass, stencil_value); + wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0); + wgpuRenderPassEncoderEnd(pass); + wgpuRenderPassEncoderRelease(pass); + } else { + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(Encoder(), &pd); + wgpuRenderPassEncoderEnd(pass); + wgpuRenderPassEncoderRelease(pass); + } + t->initialized = true; + ++stats_.clears; + } + } + + void Upload(uint32_t dest, uint32_t length, const uint8_t* bytes) { + if (uint64_t(dest) + length > shared_memory_bytes_) { ++stats_.dropped_uploads; return; } + if (staging_offset_ + length > STAGING_BYTES) Submit(); + const uint32_t padded = (length + 3) & ~3u; + EndPass(); + if (padded > STAGING_BYTES) { + wgpuQueueWriteBuffer(queue_, shared_memory_, dest, bytes, padded); + } else { + wgpuQueueWriteBuffer(queue_, staging_, staging_offset_, bytes, padded); + wgpuCommandEncoderCopyBufferToBuffer(Encoder(), staging_, staging_offset_, shared_memory_, dest, padded); + staging_offset_ += padded; + } + ++stats_.uploads; + stats_.uploaded_bytes += padded; + } + + bool Present(uint32_t dw, uint32_t dh) override { + if (!front_ || !surface_ || !dw || !dh) return false; + if (dw != surface_w_ || dh != surface_h_) { + WGPUSurfaceCapabilities caps = WGPU_SURFACE_CAPABILITIES_INIT; + wgpuSurfaceGetCapabilities(surface_, adapter_, &caps); + surface_format_ = caps.formatCount ? caps.formats[0] : WGPUTextureFormat_BGRA8Unorm; + wgpuSurfaceCapabilitiesFreeMembers(caps); + WGPUSurfaceConfiguration c = WGPU_SURFACE_CONFIGURATION_INIT; + c.device = device_; + c.format = surface_format_; + c.usage = WGPUTextureUsage_RenderAttachment; + c.width = dw; + c.height = dh; + c.presentMode = WGPUPresentMode_Fifo; + c.alphaMode = WGPUCompositeAlphaMode_Opaque; + wgpuSurfaceConfigure(surface_, &c); + surface_w_ = dw; + surface_h_ = dh; + if (present_pipeline_) { wgpuRenderPipelineRelease(present_pipeline_); present_pipeline_ = nullptr; } + } + if (!present_pipeline_) { + WGPUShaderModule module = WgslModule(PRESENT_SHADER, "Render360 present"); + WGPURenderPipelineDescriptor rd = WGPU_RENDER_PIPELINE_DESCRIPTOR_INIT; + rd.vertex.module = module; + rd.vertex.entryPoint = S("vs"); + rd.primitive.topology = WGPUPrimitiveTopology_TriangleList; + rd.multisample.count = 1; + WGPUColorTargetState ct = WGPU_COLOR_TARGET_STATE_INIT; + ct.format = surface_format_; + WGPUFragmentState fs = WGPU_FRAGMENT_STATE_INIT; + fs.module = module; + fs.entryPoint = S("fs"); + fs.targetCount = 1; + fs.targets = &ct; + rd.fragment = &fs; + present_pipeline_ = wgpuDeviceCreateRenderPipeline(device_, &rd); + WGPUSamplerDescriptor sd = WGPU_SAMPLER_DESCRIPTOR_INIT; + sd.magFilter = sd.minFilter = WGPUFilterMode_Linear; + if (!present_sampler_) present_sampler_ = wgpuDeviceCreateSampler(device_, &sd); + if (!present_swizzle_) present_swizzle_ = MakeBuffer("present swizzle", 16, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst); + } + const uint32_t swz[4] = {front_swizzle_, 0, 0, 0}; + wgpuQueueWriteBuffer(queue_, present_swizzle_, 0, swz, sizeof(swz)); + auto view_it = front_->views.find(WGPUTextureViewDimension_2DArray); + if (view_it == front_->views.end()) return false; + WGPUBindGroupEntry e[3] = {WGPU_BIND_GROUP_ENTRY_INIT, WGPU_BIND_GROUP_ENTRY_INIT, WGPU_BIND_GROUP_ENTRY_INIT}; + e[0].binding = 0; e[0].textureView = view_it->second; + e[1].binding = 1; e[1].sampler = present_sampler_; + e[2].binding = 2; e[2].buffer = present_swizzle_; e[2].size = 16; + WGPUBindGroupDescriptor gd = WGPU_BIND_GROUP_DESCRIPTOR_INIT; + gd.layout = wgpuRenderPipelineGetBindGroupLayout(present_pipeline_, 0); + gd.entryCount = 3; + gd.entries = e; + WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &gd); + WGPUSurfaceTexture st = WGPU_SURFACE_TEXTURE_INIT; + wgpuSurfaceGetCurrentTexture(surface_, &st); + if (!st.texture) { wgpuBindGroupRelease(group); return false; } + WGPUTextureView target = wgpuTextureCreateView(st.texture, nullptr); + WGPURenderPassColorAttachment ca = WGPU_RENDER_PASS_COLOR_ATTACHMENT_INIT; + ca.view = target; + ca.loadOp = WGPULoadOp_Clear; + ca.clearValue = {0, 0, 0, 1}; + ca.storeOp = WGPUStoreOp_Store; + WGPURenderPassDescriptor pd = WGPU_RENDER_PASS_DESCRIPTOR_INIT; + pd.colorAttachmentCount = 1; + pd.colorAttachments = &ca; + EndPass(); + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(Encoder(), &pd); + // Aspect fit. + const float fa = float(front_->width) / float(front_->height), va = float(dw) / float(dh); + float w = float(dw), h = float(dh); + if (fa > va) h = w / fa; else w = h * fa; + wgpuRenderPassEncoderSetViewport(pass, (dw - w) / 2, (dh - h) / 2, w, h, 0, 1); + wgpuRenderPassEncoderSetPipeline(pass, present_pipeline_); + wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr); + wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0); + wgpuRenderPassEncoderEnd(pass); + wgpuRenderPassEncoderRelease(pass); + Submit(); + wgpuSurfacePresent(surface_); + wgpuTextureViewRelease(target); + wgpuTextureRelease(st.texture); + wgpuBindGroupRelease(group); + ++stats_.presents; + return true; + } + + bool ReadShared(uint32_t offset, uint32_t length, std::vector* out) override { + length = (length + 3) & ~3u; + if (uint64_t(offset) + length > shared_memory_bytes_ || !length) return false; + Submit(); + WGPUBuffer read = MakeBuffer("readback", length, WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst); + wgpuCommandEncoderCopyBufferToBuffer(Encoder(), shared_memory_, offset, read, 0, length); + Submit(); + bool done = false, ok = false; + WGPUBufferMapCallbackInfo mi = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT; + mi.mode = WGPUCallbackMode_AllowProcessEvents; + mi.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void* d, void* o) { + *static_cast(o) = status == WGPUMapAsyncStatus_Success; + *static_cast(d) = true; + }; + mi.userdata1 = &done; + mi.userdata2 = &ok; + wgpuBufferMapAsync(read, WGPUMapMode_Read, 0, length, mi); + while (!done) { wgpuDevicePoll(device_, true, nullptr); wgpuInstanceProcessEvents(instance_); } + if (ok) { + const auto* m = static_cast(wgpuBufferGetConstMappedRange(read, 0, length)); + out->assign(m, m + length); + wgpuBufferUnmap(read); + } + wgpuBufferDestroy(read); + wgpuBufferRelease(read); + return ok; + } + + bool ReadFront(std::vector* rgba, uint32_t* width, uint32_t* height) override { + if (!front_ || front_->format != WGPUTextureFormat_RGBA8Unorm) return false; + Submit(); + const uint32_t w = front_->width, h = front_->height, bpr = (w * 4 + 255) / 256 * 256; + WGPUBuffer read = MakeBuffer("readback", uint64_t(bpr) * h, WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst); + WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT; + src.texture = front_->texture; + WGPUTexelCopyBufferInfo dst = WGPU_TEXEL_COPY_BUFFER_INFO_INIT; + dst.buffer = read; + dst.layout.bytesPerRow = bpr; + dst.layout.rowsPerImage = h; + WGPUExtent3D size{w, h, 1}; + wgpuCommandEncoderCopyTextureToBuffer(Encoder(), &src, &dst, &size); + Submit(); + bool done = false, ok = false; + WGPUBufferMapCallbackInfo mi = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT; + mi.mode = WGPUCallbackMode_AllowProcessEvents; + mi.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void* d, void* o) { + *static_cast(o) = status == WGPUMapAsyncStatus_Success; + *static_cast(d) = true; + }; + mi.userdata1 = &done; + mi.userdata2 = &ok; + wgpuBufferMapAsync(read, WGPUMapMode_Read, 0, uint64_t(bpr) * h, mi); + while (!done) { wgpuDevicePoll(device_, true, nullptr); wgpuInstanceProcessEvents(instance_); } + if (ok) { + const auto* m = static_cast(wgpuBufferGetConstMappedRange(read, 0, uint64_t(bpr) * h)); + rgba->resize(size_t(w) * h * 4); + for (uint32_t y = 0; y < h; ++y) std::memcpy(rgba->data() + size_t(y) * w * 4, m + size_t(y) * bpr, w * 4); + // Apply the swap swizzle as the present shader does (3 bits per + // component: 0-3 RGBA, 4 zero, 5 one). + const uint32_t sw = front_swizzle_; + for (size_t i = 0; i < rgba->size(); i += 4) { + uint8_t t[4] = {(*rgba)[i], (*rgba)[i + 1], (*rgba)[i + 2], (*rgba)[i + 3]}; + for (int c = 0; c < 3; ++c) { + const uint32_t sel = (sw >> (3 * c)) & 7; + (*rgba)[i + c] = sel >= 5 ? 255 : sel == 4 ? 0 : t[sel]; + } + (*rgba)[i + 3] = 255; + } + wgpuBufferUnmap(read); + *width = w; + *height = h; + } + wgpuBufferDestroy(read); + wgpuBufferRelease(read); + return ok; + } +}; + +} // namespace + +std::unique_ptr Backend::Create(void* metal_layer, std::string* error) { + auto b = std::make_unique(); + std::string e; + if (!b->Init(metal_layer, &e)) { + if (error) *error = e; + return nullptr; + } + return b; +} + +void EnableCoreRecording(bool on) { + // R360_GPU_DEBUG: recorder debug logging (mode bit 2), as the web runner. + r360_gpu_set_mode(on ? (getenv("R360_GPU_DEBUG") ? 3 : 1) : 0); + r360_xenos_soft_set_rasterize(on ? 0 : 1); +} + +} // namespace r360gpu diff --git a/native/gpu/xenos_wgpu.h b/native/gpu/xenos_wgpu.h new file mode 100644 index 00000000..c67f9b5c --- /dev/null +++ b/native/gpu/xenos_wgpu.h @@ -0,0 +1,55 @@ +// Render360 native Xenos GPU backend: replays the command stream the core +// records (src/xenia_web_bootstrap/webgpu_backend.cpp) into wgpu-native +// (WebGPU on Metal), as render360-webgpu-backend.mjs does in the browser and +// as Xenia's VulkanCommandProcessor replays its DeferredCommandBuffer. +// The core's Xenia SPIR-V shaders go to wgpu directly (Naga inside wgpu). +#pragma once + +#include +#include +#include +#include + +struct WGPUInstanceImpl; +struct WGPUSurfaceImpl; + +namespace r360gpu { + +struct Stats { + uint64_t uploads = 0, uploaded_bytes = 0, dropped_uploads = 0, submits = 0, shaders = 0, shader_failures = 0, + pipelines = 0, pipeline_failures = 0, draws = 0, skipped_draws = 0, render_passes = 0, swaps = 0, + targets_created = 0, textures = 0, texture_loads = 0, texture_failures = 0, texture_load_failures = 0, + load_shader_failures = 0, unbindable_textures = 0, dumps = 0, resolves = 0, resolve_failures = 0, + clears = 0, presents = 0, errors = 0; +}; + +class Backend { + public: + // Creates a device. `metal_layer` (CAMetalLayer*) is optional: without it + // the backend renders off-screen (headless runner) and frames can be read + // back with ReadFront. + static std::unique_ptr Create(void* metal_layer, std::string* error); + virtual ~Backend() = default; + + // Replays and clears the core's recorded commands (r360_gpu_stream_*). + virtual void ReplayCore() = 0; + // Replays stream words (a capture file). + virtual void ReplayWords(const uint32_t* words, size_t count) = 0; + // Draws the last swapped front buffer to the layer (aspect fit). Returns + // false when there is no front buffer yet. + virtual bool Present(uint32_t drawable_width, uint32_t drawable_height) = 0; + // RGBA8 pixels of the last swapped front buffer (blocking readback). + virtual bool ReadFront(std::vector* rgba, uint32_t* width, uint32_t* height) = 0; + // Bytes of the GPU shared memory (guest physical memory copy), blocking. + virtual bool ReadShared(uint32_t offset, uint32_t length, std::vector* out) = 0; + virtual uint32_t swaps() const = 0; + virtual const Stats& stats() const = 0; + virtual std::string last_error() const = 0; + virtual std::string adapter_name() const = 0; +}; + +// Puts the core into GPU record mode (and the software renderer off), as +// render360-webgpu-play.mjs createXenosWebGpuPlayPath does. +void EnableCoreRecording(bool on); + +} // namespace r360gpu diff --git a/native/gpu/xenos_wgpu_c.cpp b/native/gpu/xenos_wgpu_c.cpp new file mode 100644 index 00000000..12ed6814 --- /dev/null +++ b/native/gpu/xenos_wgpu_c.cpp @@ -0,0 +1,30 @@ +// C entry points for the Swift app (ios/Render360) around r360gpu::Backend. +#include +#include + +#include "xenos_wgpu.h" + +namespace { +std::unique_ptr g_backend; +std::string g_error; +} // namespace + +extern "C" { +// Creates the GPU backend on a CAMetalLayer and puts the core into GPU +// record mode. Returns 1 on success; on failure the software path stays on. +int r360_gpu_backend_start(void* metal_layer) { + g_backend = r360gpu::Backend::Create(metal_layer, &g_error); + if (!g_backend) return 0; + r360gpu::EnableCoreRecording(true); + return 1; +} +// Replays the recorded commands; presents the newest front buffer when +// `present` is set. Call on the running guest thread (host slice). +int r360_gpu_backend_frame(int present, unsigned width, unsigned height) { + if (!g_backend) return 0; + g_backend->ReplayCore(); + return present ? (g_backend->Present(width, height) ? 1 : 0) : 1; +} +const char* r360_gpu_backend_error(void) { return g_error.c_str(); } +unsigned r360_gpu_backend_errors(void) { return g_backend ? unsigned(g_backend->stats().errors) : 0u; } +} diff --git a/native/include/r360_native_compat.h b/native/include/r360_native_compat.h new file mode 100644 index 00000000..0e8cf13f --- /dev/null +++ b/native/include/r360_native_compat.h @@ -0,0 +1,19 @@ +// Force-included by native/build-native.sh. Darwin's off_t is always 64-bit, +// so Xenia's glibc *64 POSIX names map directly onto the plain ones. +#pragma once +#if defined(__APPLE__) +#define off64_t off_t +#define ftello64 ftello +#define fseeko64 fseeko +#define ftruncate64 ftruncate +#define mmap64 mmap +#define lseek64 lseek +#define pread64 pread +#define pwrite64 pwrite +#include +#if TARGET_OS_IPHONE +// The iOS SDK has no stat64; off_t/stat are 64-bit already. +#define stat64 stat +#define fstat64 fstat +#endif +#endif diff --git a/native/include/render360_core.h b/native/include/render360_core.h new file mode 100644 index 00000000..d4472c14 --- /dev/null +++ b/native/include/render360_core.h @@ -0,0 +1,115 @@ +// Render360 native core: the C API the iOS app (ios/) and the native headless +// runner (native/tools/run_title.cpp) use. +// +// The browser build drives the same core from JavaScript +// (render360-title-controller.mjs handoffDefaultXex, render360-guest-fibers.mjs, +// render360-guest-vfs.mjs, wasm-core.js). native/src/native_title.cpp is a +// line-for-line C++ port of that boot path, so both builds boot a title the +// same way and their deterministic runs can be compared. +// +// Every individual core entry point is also declared in +// render360_core_exports.h (generated by native/tools/gen_core_api.py). +#pragma once + +#include +#include + +#include "render360_core_exports.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// What a title is booted from. Game files never leave the device: the core +// reads them in place (pread on disc images and folders, STFS extraction into +// memory for packages). +typedef enum R360SourceKind { + R360_SOURCE_UNKNOWN = 0, + R360_SOURCE_FOLDER = 1, // extracted game folder with default.xex + R360_SOURCE_XEX = 2, // bare default.xex (its folder is the game root) + R360_SOURCE_STFS = 3, // LIVE / PIRS / CON package (XBLA titles) + R360_SOURCE_DISC = 4, // XISO / XGD1-3 disc image +} R360SourceKind; + +typedef struct R360BootOptions { + // Disc 1 (or the only file). For multi-disc titles the other discs are + // listed in `discs`; r360_native_select_disc() switches between them. + const char* path; + const char* const* discs; + uint32_t disc_count; + uint32_t license_full; // XAM license mask: 0 trial (Xenia default), 1 full + uint32_t deterministic_ps; // >0: guest clock from instructions (replayable runs) + uint32_t max_minstr; // >0: stop after this many million guest instructions + uint32_t function_budget; // per-function HIR fuel (run-title --budget), 0 = default 1<<30 + int32_t dialog_button; // >=0: answer every XamShowMessageBoxUI with this button + // Host slices: on_slice(user) runs on the guest thread about every slice_ms + // of host time (present frames, poll input, telemetry). Return nonzero to + // stop the run. slice_ms = 0 runs without slices. + uint32_t slice_ms; + uint32_t (*on_slice)(void* user); + void* user; +} R360BootOptions; + +typedef struct R360BootResult { + uint32_t ok; // 1: the title ran (see runtime_boundary for why it stopped) + R360SourceKind kind; + char title[128]; // STFS display name when known + uint32_t vfs_files, vfs_directories; + uint32_t entry, pe_entry; + uint32_t hir; // root result of the run + uint32_t stopped_by_host; // on_slice asked to stop + char runtime_boundary[48]; // same strings as handoffDefaultXex + uint32_t execution_status, execution_instructions; + uint32_t blocker_kind, blocker_opcode, blocker_address; + uint32_t memory_fault_code, memory_fault_address; + uint32_t kernel_calls, kernel_last_status, kernel_last_module, kernel_last_ordinal; + char kernel_boundary[192]; // readKernelBoundaryTelemetry, as text + uint32_t kernel_imports, kernel_registered, kernel_variables_relocated; + double elapsed_ms; + char error[256]; // set when ok == 0 +} R360BootResult; + +// Boots `options->path` and runs the title until it stops (exit, blocker, +// instruction limit, or on_slice returning nonzero). Blocking; call it from +// a background thread. Returns 1 on a completed run (ok), 0 on a boot error. +// A run that was stopped mid-call leaves its guest threads parked: start a +// new process (the iOS app relaunches) before booting another title. +uint32_t r360_native_boot(const R360BootOptions* options, R360BootResult* result); + +// Writes the run-title JSON report (tools/run-title.mjs fields that apply to +// the native build) for the last boot. Returns the length written. +size_t r360_native_report_json(const R360BootResult* result, char* out, size_t capacity); + +// Name of a kernel export (Xenia xboxkrnl_table.inc / xam_table.inc); module +// 1 = xboxkrnl.exe, 2 = xam.xex. Falls back to "module!0xORDINAL". +const char* r360_native_kernel_export_name(uint32_t module, uint32_t ordinal, char* buf, size_t size); + +// Library metadata of a game file without booting it (the web UI's +// inspectFile): display name, title / media id, container kind. +typedef struct R360GameInfo { + char name[128]; + char display_type[48]; // "STFS CON", "Xbox 360 Disc / XDVDFS", "XEX2"... + char source_type[8]; // "con", "live", "pirs", "iso", "xex" + uint32_t title_id, media_id; + uint64_t size; + char error[160]; +} R360GameInfo; +uint32_t r360_native_inspect(const char* path, R360GameInfo* info); + +// Multi-disc titles: re-registers \Device\Cdrom0 with disc `index` of the +// last boot's disc list (the title's next file open sees the new disc). +uint32_t r360_native_select_disc(uint32_t index); +uint32_t r360_native_current_disc(void); + +// 1 when this process can map and run executable memory (JIT-capable: on iOS +// a sideloaded build with StikDebug). The core is interpreter-only today. +uint32_t r360_native_jit_available(void); + +// Native guest-thread scheduler (src/xenia_web_bootstrap/guest_fibers.cpp). +uint32_t r360_native_run_with_fibers(uint32_t (*primary)(void*), void* user, uint32_t slice_ms, + uint32_t (*on_slice)(void*), void* slice_user, + uint32_t* stopped); + +#ifdef __cplusplus +} +#endif diff --git a/native/include/render360_core_exports.h b/native/include/render360_core_exports.h new file mode 100644 index 00000000..3e16de2e --- /dev/null +++ b/native/include/render360_core_exports.h @@ -0,0 +1,534 @@ +// Generated by native/tools/gen_core_api.py - do not edit. +// Every r360_* entry point of the Render360 core (browser: wasm exports). +#pragma once +#include +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +uint32_t r360_audio_client_callback(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_callback_arg(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_frames(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_last_samples(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_cfg_export_continuation_ptr(uint32_t slot); // ppc_context_abi_probe.cpp +void r360_cfg_export_continuation_reset(uint32_t slot); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_slot_count(void); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_state_size(void); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_status(uint32_t slot); // ppc_context_abi_probe.cpp +uint32_t r360_content_package_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_debug_watch(uint32_t address); // hir_correctness_executor_vmx.cpp +uint32_t r360_debug_watch_address(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_fiber_asyncify_data(void); // guest_fibers.cpp +uint32_t r360_fiber_count(void); // guest_fibers.cpp +uint32_t r360_fiber_current(void); // guest_fibers.cpp +uint32_t r360_fiber_entry(void); // guest_fibers.cpp +uint32_t r360_fiber_host_yields(void); // guest_fibers.cpp +double r360_fiber_idle_ms(void); // guest_fibers.cpp +uint32_t r360_fiber_instructions_millions(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_leave(uint32_t index, uint32_t field); // guest_fibers.cpp +uint32_t r360_fiber_preemptions(void); // guest_fibers.cpp +uint32_t r360_fiber_prepare(void); // guest_fibers.cpp +uint32_t r360_fiber_reset(uint32_t enable); // guest_fibers.cpp +uint32_t r360_fiber_resumes(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_set_host_slice(uint32_t milliseconds); // guest_fibers.cpp +uint32_t r360_fiber_stack_pointer(void); // guest_fibers.cpp +uint32_t r360_fiber_state(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_switch_pending(void); // guest_fibers.cpp +uint32_t r360_fiber_switches(void); // guest_fibers.cpp +uint32_t r360_fiber_take_host_yield(void); // guest_fibers.cpp +uint32_t r360_fiber_thread(uint32_t index); // guest_fibers.cpp +uint64_t r360_generated_guest_load_scalar(uint32_t virtual_address, uint32_t size, uint32_t flags); // sparse_guest_memory.cpp +uint32_t r360_generated_guest_load_status(void); // sparse_guest_memory.cpp +uint32_t r360_gpu_draw_stat(uint32_t index); // webgpu_draws.cpp +uint32_t r360_gpu_set_mode(uint32_t mode); // webgpu_draws.cpp +void r360_gpu_shared_memory_clear(void); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_request(uint32_t start, uint32_t length); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_upload_ranges(void); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_uploaded_kb(void); // webgpu_backend.cpp +void r360_gpu_shared_memory_written_by_gpu(uint32_t start, uint32_t length); // webgpu_backend.cpp +uintptr_t r360_gpu_stream_data(void); // webgpu_backend.cpp +void r360_gpu_stream_reset(void); // webgpu_backend.cpp +uint32_t r360_gpu_stream_words(void); // webgpu_backend.cpp +uint32_t r360_gpu_texture_stat(uint32_t index); // webgpu_textures.cpp +uint32_t r360_guest_clock_deterministic(void); // hir_correctness_executor_vmx.cpp +uint64_t r360_guest_clock_ns(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_guest_runtime_status(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_arg1(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_context(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_create(uint32_t entry, uint32_t context, uint32_t stack_size, uint32_t flags); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_current(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_entry(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_exit_code(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_external(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_find_by_kthread(uint32_t kthread); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_flags(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_id(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_kthread(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_next_runnable(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_pcr(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_register_external(uint32_t entry, uint32_t stack_base, uint32_t stack_limit, uint32_t pcr, uint32_t kthread, uint32_t thread_id); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_resume(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_runnable_list(uint32_t* out, uint32_t capacity); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_set_current(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_set_guest_objects(uint32_t handle, uint32_t pcr, uint32_t kthread, uint32_t arg1, uint32_t thread_id); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_base(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_mapped(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_size(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_top(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_state(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_suspend(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_terminate(uint32_t handle, uint32_t exit_code); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_alloc(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_free(uint32_t slot); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_get(uint32_t handle, uint32_t slot); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_set(uint32_t handle, uint32_t slot, uint32_t value); // kernel_runtime_foundation.cpp +uint32_t r360_hir_cache_compiled_only_entries(void); // probe_backend.cpp +uint32_t r360_hir_cache_compiled_only_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_entries(void); // probe_backend.cpp +uint32_t r360_hir_cache_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_kilobytes(void); // probe_backend.cpp +uint32_t r360_hir_cache_memo_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_miss_dump(void); // probe_backend.cpp +uint32_t r360_hir_cache_misses(void); // probe_backend.cpp +uint32_t r360_hir_cache_set_budget_mb(uint32_t megabytes); // probe_backend.cpp +uint32_t r360_hir_correctness_supported_opcode_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_correctness_supports_opcode(uint32_t opcode); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_instruction_budget(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_last_source(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_opcode_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_opcode_histogram_k(uint32_t op); // hir_correctness_executor_vmx.cpp +const char* r360_hir_opcode_name(uint32_t opcode); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_set_instruction_budget(uint32_t budget); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_set_total_instruction_budget(uint32_t millions); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_total_instructions_millions(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_input_set_gamepad(uint32_t user_index, uint32_t connected, uint32_t buttons, uint32_t triggers, uint32_t left_stick, uint32_t right_stick); // kernel_xboxkrnl_services.cpp +uint32_t r360_jit_diag(uint32_t on); // hir_correctness_executor_vmx.cpp +uint32_t r360_jit_h_spill_alloc(uint32_t bytes); // guest_fibers.cpp +uint32_t r360_jit_h_spill_pop(uint32_t bytes); // guest_fibers.cpp +uint32_t r360_jit_osr_entries(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_jit_profile(uint32_t command); // hir_correctness_executor_vmx.cpp +uint32_t r360_kernel_audio_callbacks(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_cp_interrupts(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_read(uint32_t index, uintptr_t out, uint32_t capacity); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_total(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_determinism_every(uint32_t n); // kernel_import_probe.cpp +uint32_t r360_kernel_export_calls(uint32_t module, uint32_t ordinal); // kernel_import_probe.cpp +uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_graphics_interrupt_callback(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_import_calls(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_count(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_dispatch_context(uint32_t thunk_address, uintptr_t context_ptr); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_module(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_ordinal(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_status(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_thunk(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_register(uint32_t a, uint32_t m, uint32_t o, uint32_t i, uint32_t r); // kernel_import_probe.cpp +void r360_kernel_import_reset(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_arg(uint32_t index, uint32_t arg_index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_count(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_handled(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_module(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_ordinal(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_result(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_sequence(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_status(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_thunk(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_total(void); // kernel_import_probe.cpp +uint32_t r360_kernel_object_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_pool_alloc(uint32_t size, uint32_t alignment); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_prepare_thread_objects(uint32_t native_handle, uint32_t start_address, uint32_t creation_flags); // kernel_xboxkrnl_services.cpp +void r360_kernel_runtime_reset(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_call(uint32_t module, uint32_t ordinal, uint32_t r3, uint32_t r4, uint32_t r5, uint32_t r6, uint32_t r7, uint32_t r8, uint32_t r9, uint32_t r10); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_calls(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_last_module(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_last_ordinal(void); // kernel_runtime_foundation.cpp +void r360_kernel_service_reset(void); // kernel_runtime_foundation.cpp +void r360_kernel_service_set_caller(uint32_t r13, uint32_t lr, uint32_t r1); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_service_status(void); // kernel_runtime_foundation.cpp +void r360_kernel_services_reset(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_set_executable_module(uint32_t hmodule, uint32_t xex_header, uint32_t process_info_block); // kernel_xboxkrnl_services.cpp +void r360_kernel_set_timestamp_bundle(uint32_t address); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_arg(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_code(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_kind(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_lr(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_module(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_ordinal(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_thread_poll(uint32_t thread, uint32_t field); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_thread_wait(uint32_t thread, uint32_t field); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_vblank_interrupts(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_handle(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_module(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_object(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_object_type(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_ordinal(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_reason(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_watch_arg(uint32_t slot, uint32_t value); // kernel_import_probe.cpp +uint32_t r360_lzx_decompress(uint32_t input_size, uint32_t output_size, uint32_t window_size); // xex_lzx_probe.cpp +uint8_t* r360_lzx_input_buffer(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_input_capacity(void); // xex_lzx_probe.cpp +uint8_t* r360_lzx_output_buffer(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_output_capacity(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_output_size(void); // xex_lzx_probe.cpp +void r360_lzx_reset(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_status(void); // xex_lzx_probe.cpp +uint32_t r360_native_fiber_finish(void); // guest_fibers.cpp +uint32_t r360_pe_guest_entry_address(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_pe_entry_address(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_raw_bytes(void); // xex_pe_guest_loader.cpp +void r360_pe_guest_reset(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_begin(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_end(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_prolog_bytes(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_section_count(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_set_xex_pages(uintptr_t words_ptr, uint32_t count, uint32_t page_size); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_status(void); // xex_pe_guest_loader.cpp +double r360_perf_counter(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_context_offset_ctr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_fpr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_gpr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_lr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_reserved_val(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_vr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_size(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_probe_assembled_functions(void); // probe_backend.cpp +uint32_t r360_ppc_probe_compare_register(const char* name, const char* value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_correctness_blocker_address(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_blocker_kind(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_blocker_opcode(void); // probe_backend.cpp +uint64_t r360_ppc_probe_correctness_gpr(uint32_t index); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_correctness_instructions(void); // probe_backend.cpp +uint64_t r360_ppc_probe_correctness_r3(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_status(void); // probe_backend.cpp +uint32_t r360_ppc_probe_execute_on_translate(void); // probe_backend.cpp +uint32_t r360_ppc_probe_guest_base(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_hir_block_count(void); // probe_backend.cpp +uint32_t r360_ppc_probe_hir_instruction_count(void); // probe_backend.cpp +uint64_t r360_ppc_probe_initial_lr(void); // ppc_translation_probe.cpp +uintptr_t r360_ppc_probe_input_buffer(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_input_capacity(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_last_guest_address(void); // probe_backend.cpp +uint32_t r360_ppc_probe_load(const uint8_t* bytes, uint32_t length); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_load_at(uint32_t address, const uint8_t* bytes, uint32_t length); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_loaded_size(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_page_sparse_code(uint32_t target_address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_read_guest_u32_be(uint32_t address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_register_actual(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_register_save_rest(uint32_t start, uint32_t end); // ppc_translation_probe.cpp +void r360_ppc_probe_reset(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_address(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_diagnostic(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_function_end(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_hir_instructions(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_window_end(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_execute_on_translate(uint32_t enabled); // probe_backend.cpp +uint32_t r360_ppc_probe_set_initial_gpr(uint32_t index, uint64_t value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_initial_lr(uint64_t value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_initial_register(const char* name, const char* value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_stack_blocker_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_depth(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_flags(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_sequence(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_source(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_target(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_initial_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_depth(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_source(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_target(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_new_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_old_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_write_address(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_write_depth(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_address(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_depth(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_new_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_old_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_sequence(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_status(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_translate(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_translate_scanned_at(uint32_t address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_write_guest_u32_be(uint32_t address, uint32_t value); // ppc_translation_probe.cpp +const uint8_t* r360_prepare_staged_bytes(uint32_t staged_header_length); // xex_image_preparer_exports.cpp +uint32_t r360_set_deterministic_clock(uint32_t ps_per_instruction); // hir_correctness_executor_vmx.cpp +uint32_t r360_sparse_guest_memory_alloc(uint32_t page_count); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_backing_pages(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_last_fault_address(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_last_fault_code(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_map(uint32_t virtual_address, uint32_t page_count, uint32_t backing_id, uint32_t backing_page_offset, uint32_t protection); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_mapped_pages(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_protect(uint32_t virtual_address, uint32_t page_count, uint32_t protection); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_read_u32_be(uint32_t virtual_address, uint32_t* out_value); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_read_u8(uint32_t virtual_address); // sparse_guest_memory.cpp +void r360_sparse_guest_memory_reset(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_unmap(uint32_t virtual_address, uint32_t page_count); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_write_u32_be(uint32_t virtual_address, uint32_t value); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_write_u8(uint32_t virtual_address, uint32_t value); // sparse_guest_memory.cpp +uint32_t r360_title_gpu_last_vd_swap_buffer(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_frontbuffer(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_height(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_width(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_read(uint32_t address, uint32_t* out_value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_write(uint32_t address, uint32_t value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_writes(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_pumps(void); // title_gpu_runtime.cpp +void r360_title_gpu_reset(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_base(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_bytes(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_size_log2(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_word(uint32_t index, uint32_t* out_value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_word_capacity(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_rptr_block_size_log2(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_rptr_writeback(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_stalled(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_status(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_vd_swap_calls(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_vd_swap_failures(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_write_pointer(void); // title_gpu_runtime.cpp +uint32_t r360_title_handoff_bytes(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_entry_address(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_hir_instructions(void); // xex_title_handoff.cpp +void r360_title_handoff_reset(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_status(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_translate_entry(uint32_t byte_count); // xex_title_handoff.cpp +uint32_t r360_title_handoff_translate_scanned_entry(void); // xex_title_handoff.cpp +uint32_t r360_trace_set_verbose(uint32_t enabled); // hir_correctness_executor_vmx.cpp +uint32_t r360_trace_verbose(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_trace_verbose_from(uint32_t millions); // guest_fibers.cpp +uint32_t r360_trap_address(void); // probe_backend.cpp +uint32_t r360_trap_depth(void); // probe_backend.cpp +uint32_t r360_trap_phase(void); // probe_backend.cpp +uintptr_t r360_trap_reason(void); // probe_backend.cpp +uint32_t r360_trap_reason_length(void); // probe_backend.cpp +void r360_trap_reset(void); // probe_backend.cpp +uint32_t r360_trap_stack_exhausted(void); // probe_backend.cpp +uint32_t r360_trap_stack_headroom(void); // probe_backend.cpp +uintptr_t r360_vfs_data_buffer(uint32_t id); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_entry_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_entry_path(uint32_t id); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_entry(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_errno(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_length(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_offset(void); // kernel_xboxkrnl_services.cpp +uintptr_t r360_vfs_path_buffer(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_reads(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_register(uint32_t path_length, uint32_t size_lo, uint32_t size_hi, uint32_t attributes, uint32_t host_fd, uint32_t host_offset_lo, uint32_t host_offset_hi); // kernel_xboxkrnl_services.cpp +void r360_vfs_reset(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_wasm_backend_call_cache_hits(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_cache_misses(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_cache_rebuilds(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_context_ptr(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_address(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_count(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_generation(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_invalidations(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_lowered_instructions(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_module_ptr(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_module_size(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_status(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_cfg_context_ptr(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_ptr(uint32_t slot); // wasm_backend_cfg_probe.cpp +void r360_wasm_backend_cfg_continuation_reset(uint32_t slot); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_slot_count(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_state_size(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_status(uint32_t slot); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_lowered_instructions(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_module_ptr(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_module_size(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_status(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_context_ptr(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_executable_content_generation(uint32_t address); // sparse_guest_memory.cpp +uint32_t r360_wasm_backend_executable_page_generation(uint32_t address); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_fpu_context_ptr(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_lowered_instructions(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_module_ptr(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_module_size(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_status(void); // wasm_backend_fpu_probe_v2.cpp +void r360_wasm_backend_invalidate_executable_range(uint32_t address, uint32_t size); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_lowered_instructions(void); // wasm_backend_probe.cpp +void r360_wasm_backend_mark_executable_content_changed_range(uint32_t address, uint32_t size); // sparse_guest_memory.cpp +uint32_t r360_wasm_backend_memory_context_ptr(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_lowered_instructions(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_module_ptr(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_module_size(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_status(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_module_ptr(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_module_size(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_status(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_supported_opcode_count(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_supports_hir_opcode(uint32_t opcode); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_vmx_context_ptr(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_lowered_instructions(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_module_ptr(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_module_size(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_native_simd_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_scalarized_lane_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_status(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_vector_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_xam_dialog_active_button(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_answer(uint32_t button); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_button_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_pending(void); // kernel_xboxkrnl_services.cpp +int32_t r360_xam_dialog_set_auto_answer(int32_t button); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_set_host_answers(uint32_t on); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_string_len(uint32_t which); // kernel_xboxkrnl_services.cpp +uintptr_t r360_xam_dialog_string_ptr(uint32_t which); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_license_mask(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_set_license_mask(uint32_t mask); // kernel_xboxkrnl_services.cpp +uint32_t r360_xenos_arm_resume(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_debug_draws(uint32_t n); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_draws(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_edram_tile_address(uint32_t b,uint32_t p,uint32_t x,uint32_t y); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_fetch_constant_word(uint32_t g,uint32_t w); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_frame_buffer(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_generation(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_hash(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_height(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_provenance(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_size(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_width(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frontbuffer_height(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frontbuffer_ptr(void); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_frontbuffer_snapshot_buffer(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_capture(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_format(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_generation(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_hash(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_height(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_pitch(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_size(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_source_address(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_source_bytes(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_status(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_tiled(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_width(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_width(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_indirect_buffers(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_interrupts(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_fault_depth(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_fault_word(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_interrupt_mask(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_invalidate_mask(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_opcode(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_memory_writes(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_packets(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_presents(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_real_title_frame_ready(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_register(uint32_t i); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_register_writes(void); // xenos_gpu_foundation.cpp +void r360_xenos_reset(void); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_ring_buffer(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_ring_capacity(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_set_register(uint32_t i,uint32_t v); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_shader_buffer(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_dwords(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_guest_address(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_hash(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_interpreter_alloc_exports(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_analyze(uint32_t shader_type); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_cf_pair_bound(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_execute(uint32_t shader_type); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_execution_count(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_component_bits(uint32_t component); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_mask(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_register(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_register_bound(void); // xenos_shader_interpreter_probe.cpp +void r360_xenos_shader_interpreter_reset(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_shader_type(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_status(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_temp_component_bits(uint32_t reg, uint32_t component); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_texture_bindings(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_texture_fetches(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_ucode_dwords(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_uses_texture_fetch(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_value_exports(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_vertex_bindings(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_writes_color_targets(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_writes_interpolators(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_loads(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_source(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_soft_clear_ksamples(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_draws(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_resolve_info(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_skip(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_texture_format(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_pixels(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_render_us(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_resolve_kpixels(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_resolves(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_set_rasterize(uint32_t on); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_skipped(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_texture_failures(void); // xenos_soft_renderer.cpp +uintptr_t r360_xenos_spirv_buffer(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_error_count(void); // xenos_spirv_translation_probe.cpp +void r360_xenos_spirv_reset(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_shader_type(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_size(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_status(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_translate(uint32_t shader_type); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_translation_count(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_ucode_dwords(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_word(uint32_t index); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_stall_ready(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_stall_ring_offset(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_stall_wait(uint32_t i); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_status(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_submit(uint32_t n); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_swap_fetch_word(uint32_t w); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_swaps(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_trace_ibs(uint32_t on); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_waits(void); // xenos_gpu_foundation.cpp +uint32_t r360_xex_crypto_begin_session(uint32_t use_devkit_key); // xex_crypto_probe.cpp +uint8_t* r360_xex_crypto_buffer(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_bytes_done(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_capacity(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_decrypt_chunk(uint32_t chunk_length); // xex_crypto_probe.cpp +void r360_xex_crypto_reset(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_status(void); // xex_crypto_probe.cpp +uint32_t r360_xex_decode(uint32_t length); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_address(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_bytes(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_count(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_type(uint32_t index); // xex_image_decoder_exports.cpp +void r360_xex_decode_reset(void); // xex_image_decoder_exports.cpp +uint32_t r360_xex_guest_mapper_entry_address(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_finalize(void); // xex_guest_mapper.cpp +uintptr_t r360_xex_guest_mapper_input_buffer(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_input_capacity(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_input_max_capacity(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, uintptr_t source_ptr, uint32_t size); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, uint32_t virtual_size, uint32_t final_protection); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_mapped_bytes(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_patch_u32_be(uint32_t address, uint32_t value); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_reserve_input(uint32_t required_capacity); // xex_guest_mapper.cpp +void r360_xex_guest_mapper_reset(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_section_count(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_set_entry(uint32_t entry_address); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_status(void); // xex_guest_mapper.cpp +uint32_t r360_xex_pe_decode(uint32_t length); // xex_pe_image_exports.cpp +void r360_xex_pe_reset(void); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_characteristics(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_raw_address(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_raw_size(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_virtual_address(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_virtual_size(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_prepare_basic_accept_data(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_consume_zero(uint32_t max_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_data_remaining(void); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_zero_remaining(void); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_none_accept(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_none_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_normal_frame_accept(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_normal_frame_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +void r360_xex_prepare_reset(void); // xex_image_preparer_exports.cpp +#ifdef __cplusplus +} +#endif diff --git a/native/include/xenia/base/platform.h b/native/include/xenia/base/platform.h new file mode 100644 index 00000000..1c778754 --- /dev/null +++ b/native/include/xenia/base/platform.h @@ -0,0 +1,34 @@ +/** + * Render360 native (macOS / iOS) host shim for Xenia's platform switch. + * + * The native build deliberately takes the same portable code paths as the + * browser build (sparse guest memory, no host page mapping tricks, no x64 + * backend) so that native and wasm runs stay deterministic and comparable. + * XE_ARCH_WASM32 therefore means "Render360 portable host" here; + * R360_NATIVE marks the places where 64-bit host pointers differ. + */ +#ifndef XENIA_BASE_PLATFORM_H_ +#define XENIA_BASE_PLATFORM_H_ + +#if !defined(R360_NATIVE) +#error native/include must only be used by native/build-native.sh +#endif + +#define XE_PLATFORM_WEB 1 +#define XE_COMPILER_CLANG 1 +#define XE_ARCH_WASM32 1 + +#define _XEPACKEDSCOPE(body) \ + _Pragma("pack(push, 1)") body; \ + _Pragma("pack(pop)"); + +#define XEPACKEDSTRUCT(name, value) _XEPACKEDSCOPE(struct name value) +#define XEPACKEDSTRUCTANONYMOUS(value) _XEPACKEDSCOPE(struct value) +#define XEPACKEDUNION(name, value) _XEPACKEDSCOPE(union name value) + +namespace xe { +const char kPathSeparator = '/'; +const char kGuestPathSeparator = '\\'; +} // namespace xe + +#endif // XENIA_BASE_PLATFORM_H_ diff --git a/native/src/native_jit.cpp b/native/src/native_jit.cpp new file mode 100644 index 00000000..015f4d63 --- /dev/null +++ b/native/src/native_jit.cpp @@ -0,0 +1,78 @@ +// Native build: the HIR -> WebAssembly guest JIT (hir_wasm_jit.cpp) does not +// apply, and no arm64/x64 backend exists yet (Xenia only ships x64), so every +// guest function runs on the HIR interpreter. These definitions keep the +// translation cache's JIT hooks inert ("JIT off", JitLastDecision() == 5). +// +// r360_native_jit_available() reports whether this process could run a JIT +// at all: on iOS that needs the debugger-attached / JIT-enabled state that a +// sideloaded build gets from StikDebug. It maps a MAP_JIT page, writes a tiny +// "return 42" stub and calls it. +#include +#include +#include +#if defined(__APPLE__) +#include +#include +#include +#endif + +#include "hir_wasm_jit.h" + +namespace render360::xenia_web { +bool JitEnabled() { return false; } +void JitSetCandidate(xe::cpu::hir::HIRBuilder*, JitSlot*) {} +uint32_t JitTakeFunction(xe::cpu::hir::HIRBuilder*) { return 0; } +uint32_t JitLastDecision() { return 5; } +uint32_t JitRejectOpcode(xe::cpu::hir::HIRBuilder*) { return 0; } +JitSlot* JitTakeOsrSlot(xe::cpu::hir::HIRBuilder*) { return nullptr; } +uint32_t JitOsrFunction(xe::cpu::hir::HIRBuilder*, JitSlot*, bool) { return 0; } +uint32_t JitSegmentOfBlock(xe::cpu::hir::HIRBuilder*, const xe::cpu::hir::Block*) { return 0; } +void JitReleaseSlot(JitSlot*) {} +} // namespace render360::xenia_web + +namespace { +// 0 not probed, 1 available, 2 unavailable. +uint32_t g_jit_probe = 0; + +uint32_t ProbeExecutableMemory() { +#if defined(__aarch64__) || defined(__x86_64__) + const size_t size = 16384; +#if defined(__APPLE__) + void* page = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_JIT, -1, 0); +#else + void* page = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); +#endif + if (page == MAP_FAILED) return 2; +#if defined(__aarch64__) + static const uint32_t kStub[] = {0x52800540u /* mov w0, #42 */, 0xD65F03C0u /* ret */}; +#else + static const uint8_t kStub[] = {0xB8, 42, 0, 0, 0 /* mov eax, 42 */, 0xC3 /* ret */}; +#endif +#if defined(__APPLE__) && defined(__aarch64__) && TARGET_OS_OSX + pthread_jit_write_protect_np(0); +#endif + std::memcpy(page, kStub, sizeof(kStub)); +#if defined(__APPLE__) && defined(__aarch64__) && TARGET_OS_OSX + pthread_jit_write_protect_np(1); + sys_icache_invalidate(page, sizeof(kStub)); +#endif + // Without the JIT entitlement / debugger state the kernel kills the + // process on the call instead of failing the mmap on some iOS versions; + // the app only probes when the user enables JIT mode, and records a + // breadcrumb first so a crash here is attributed correctly. + using Fn = int (*)(); + const int value = reinterpret_cast(page)(); + munmap(page, size); + return value == 42 ? 1 : 2; +#else + return 2; +#endif +} +} // namespace + +extern "C" uint32_t r360_native_jit_available() { + if (!g_jit_probe) g_jit_probe = ProbeExecutableMemory(); + return g_jit_probe == 1 ? 1u : 0u; +} diff --git a/native/src/native_title.cpp b/native/src/native_title.cpp new file mode 100644 index 00000000..7d964f95 --- /dev/null +++ b/native/src/native_title.cpp @@ -0,0 +1,1497 @@ +// Native title boot: a C++ port of the browser's JavaScript boot path, so the +// iOS app and the native runner start titles exactly like the web player. +// +// render360-title-controller.mjs handoffDefaultXex and its helpers +// retail-xex-image-pipeline.mjs prepareRetailXexImage (AES + NONE/BASIC/NORMAL) +// render360-xex-imports.mjs decodeXexImportLibraries +// render360-kernel-imports.mjs buildKernelImportPlan +// render360-guest-vfs.mjs registerGuestVfs, listStfsVfsFiles +// render360-xdvdfs.mjs mountXdvdfs +// render360-iso-title-controller extractXex2EncryptedImageKey +// wasm-core.js mountStfs / extractStfsEntry +// tools/run-title.mjs openTitle, the JSON report +// +// Function names below match the JavaScript ones; keep them in step. +#include "render360_core.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Package core (render360_xenia_core.wasm in the browser), linked as one +// object whose exports are renamed r360_* -> r360pkg_* (native/build-native.sh). +extern "C" { +uintptr_t r360pkg_io_ptr(); +uint32_t r360pkg_io_capacity(); +uint32_t r360pkg_stfs_mount_begin(uint32_t size_lo, uint32_t size_hi); +uint32_t r360pkg_stfs_submit_read(uint32_t length); +uint32_t r360pkg_stfs_request_pending(); +uint32_t r360pkg_stfs_request_offset_lo(); +uint32_t r360pkg_stfs_request_offset_hi(); +uint32_t r360pkg_stfs_request_size(); +uint32_t r360pkg_stfs_mount_status(); +uint32_t r360pkg_stfs_entry_count(); +uintptr_t r360pkg_stfs_entry_name_ptr(uint32_t index); +uint32_t r360pkg_stfs_entry_name_length(uint32_t index); +uint32_t r360pkg_stfs_entry_is_directory(uint32_t index); +uint32_t r360pkg_stfs_entry_parent_index(uint32_t index); +uint32_t r360pkg_stfs_entry_length(uint32_t index); +uintptr_t r360pkg_stfs_display_name_ptr(); +uint32_t r360pkg_stfs_display_name_length(); +uint32_t r360pkg_stfs_extract_begin(uint32_t entry_index); +uint32_t r360pkg_stfs_extract_status(); +uint32_t r360pkg_stfs_extract_bytes_done(); +uint32_t r360pkg_stfs_extract_bytes_total(); +void r360pkg_stfs_extract_reset(); +uint32_t r360pkg_xex_decode(uint32_t length); +uint32_t r360pkg_inspect_xex(uint32_t length); +uint32_t r360pkg_xex_title_id(); +uint32_t r360pkg_xex_media_id(); +uint32_t r360pkg_stfs_title_id(); +uint32_t r360pkg_stfs_media_id(); +uint32_t r360pkg_stfs_package_kind(); +uint32_t r360pkg_xex_decode_encryption_type(); +uint32_t r360pkg_xex_decode_compression_type(); +uint32_t r360pkg_xex_decode_image_size(); +uint32_t r360pkg_xex_prepare_none_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_none_accept(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_basic_accept_data(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_consume_zero(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_data_remaining(); +uint32_t r360pkg_xex_prepare_basic_zero_remaining(); +uint32_t r360pkg_xex_prepare_status(); +uint32_t r360pkg_xex_prepare_last_output_kind(); +uint32_t r360pkg_xex_prepare_last_output_bytes(); +uint32_t r360pkg_xex_prepare_normal_frame_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_normal_frame_accept(uint32_t length); +uint32_t r360pkg_xex_prepare_normal_window_size(); +} + +namespace { + +using Bytes = std::vector; + +[[noreturn]] void Fail(const char* format, ...) { + char text[256]; + va_list args; + va_start(args, format); + std::vsnprintf(text, sizeof(text), format, args); + va_end(args); + throw std::runtime_error(text); +} + +uint32_t be32(const uint8_t* b, size_t o) { + return (uint32_t(b[o]) << 24) | (uint32_t(b[o + 1]) << 16) | (uint32_t(b[o + 2]) << 8) | b[o + 3]; +} +uint32_t be16(const uint8_t* b, size_t o) { return (uint32_t(b[o]) << 8) | b[o + 1]; } +uint32_t le16(const uint8_t* b, size_t o) { return b[o] | (uint32_t(b[o + 1]) << 8); } +uint32_t le32(const uint8_t* b, size_t o) { + return b[o] | (uint32_t(b[o + 1]) << 8) | (uint32_t(b[o + 2]) << 16) | (uint32_t(b[o + 3]) << 24); +} + +// --- Host files ------------------------------------------------------------- + +struct HostFile { + int fd = -1; + uint64_t size = 0; + bool Open(const std::string& path) { + fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) return false; + struct stat st {}; + if (fstat(fd, &st) != 0) return false; + size = uint64_t(st.st_size); + return true; + } + void Read(uint64_t offset, void* out, size_t length) const { + size_t done = 0; + while (done < length) { + const ssize_t n = ::pread(fd, static_cast(out) + done, length - done, off_t(offset + done)); + if (n <= 0) Fail("short read at 0x%llx (%zu/%zu)", (unsigned long long)(offset + done), done, length); + done += size_t(n); + } + } + Bytes ReadBytes(uint64_t offset, size_t length) const { + Bytes out(length); + Read(offset, out.data(), length); + return out; + } +}; +// Descriptors stay open for the process lifetime: the kernel VFS reads them. +std::vector> g_host_files; +HostFile* OpenHostFile(const std::string& path) { + auto file = std::make_unique(); + if (!file->Open(path)) Fail("cannot open %s", path.c_str()); + g_host_files.push_back(std::move(file)); + return g_host_files.back().get(); +} + +// --- Guest VFS (render360-guest-vfs.mjs) ---------------------------------------- + +struct VfsFile { + std::string path; // relative to \Device\Cdrom0, '\' separated + bool directory = false; + uint64_t size = 0; + int host_fd = 0; + uint64_t host_offset = 0; + Bytes data; // attached up front (STFS extraction) + bool has_data = false; +}; + +constexpr uint32_t FILE_ATTRIBUTE_READONLY = 0x01; +constexpr uint32_t FILE_ATTRIBUTE_DIRECTORY = 0x10; +constexpr uint32_t FILE_ATTRIBUTE_NORMAL = 0x80; + +uint32_t registerGuestVfs(const std::vector& files) { + r360_vfs_reset(); + auto* path_buffer = reinterpret_cast(r360_vfs_path_buffer()); + uint32_t registered = 0; + for (const auto& file : files) { + std::string path = file.path; + std::replace(path.begin(), path.end(), '/', '\\'); + while (!path.empty() && path[0] == '\\') path.erase(0, 1); + if (path.empty()) continue; + if (path.size() >= 1024) Fail("guest path too long for VFS: %s", path.c_str()); + std::memcpy(path_buffer, path.data(), path.size()); + const uint64_t size = file.directory ? 0 : file.size; + const uint32_t attributes = file.directory ? (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY) + : (FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_READONLY); + const uint32_t id = r360_vfs_register(uint32_t(path.size()), uint32_t(size), uint32_t(size >> 32), attributes, + uint32_t(file.host_fd), uint32_t(file.host_offset), + uint32_t(file.host_offset >> 32)); + if (!id) Fail("native VFS rejected %s", path.c_str()); + ++registered; + if (file.has_data && !file.directory) { + auto* ptr = reinterpret_cast(r360_vfs_data_buffer(id)); + if (!ptr) Fail("native VFS could not allocate %zu bytes for %s", file.data.size(), path.c_str()); + if (!file.data.empty()) std::memcpy(ptr, file.data.data(), file.data.size()); + } + } + return registered; +} + +// --- XDVDFS (render360-xdvdfs.mjs) ------------------------------------------------ + +constexpr uint32_t kSector = 2048; +const char kXdvdfsMagic[] = "MICROSOFT*XBOX*MEDIA"; + +struct XdvdfsEntry { + std::string name; + uint32_t left = 0, right = 0, start_sector = 0, size = 0, attributes = 0; + bool directory = false; +}; + +struct XdvdfsVolume { + const HostFile* file = nullptr; + std::string layout; + uint64_t partition_offset = 0; + uint32_t root_sector = 0, root_size = 0; + + Bytes Table(uint32_t sector, uint32_t size) const { + if (!size) return {}; + if (size > 16u * 1024u * 1024u) Fail("XDVDFS directory table too large %u", size); + return file->ReadBytes(partition_offset + uint64_t(sector) * kSector, size); + } + static std::vector WalkTree(const Bytes& table) { + std::vector out; + if (table.empty()) return out; + std::vector stack{0}; + std::vector seen(table.size() / 4 + 1, false); + size_t visited = 0; + while (!stack.empty()) { + const uint32_t off = stack.back(); + stack.pop_back(); + if (seen[off / 4]) Fail("XDVDFS directory tree cycle at 0x%x", off); + seen[off / 4] = true; + if (++visited > 65536) Fail("XDVDFS directory entry guard exceeded"); + if (off + 14 > table.size()) Fail("XDVDFS directory entry out of bounds 0x%x", off); + const uint32_t name_len = table[off + 13]; + if (!name_len || off + 14 + name_len > table.size()) Fail("XDVDFS directory filename out of bounds 0x%x", off); + XdvdfsEntry e; + e.left = le16(table.data(), off); + e.right = le16(table.data(), off + 2); + e.start_sector = le32(table.data(), off + 4); + e.size = le32(table.data(), off + 8); + e.attributes = table[off + 12]; + e.directory = (e.attributes & 0x10) != 0; + e.name.assign(reinterpret_cast(table.data() + off + 14), name_len); + if (e.name.find_first_of(std::string("\0/\\", 3)) != std::string::npos) Fail("invalid XDVDFS filename"); + out.push_back(e); + for (uint32_t d : {e.right, e.left}) { + if (!d) continue; + if (d * 4 >= table.size()) Fail("XDVDFS child pointer out of bounds 0x%x", d * 4); + stack.push_back(d * 4); + } + } + return out; + } +}; + +XdvdfsVolume mountXdvdfs(const HostFile* file) { + static const std::pair kPartitions[] = { + {"XISO", 0x00000000ull}, {"XGD3", 0x02080000ull}, {"XGD2", 0x0FD90000ull}, {"XGD1", 0x18300000ull}}; + for (const auto& [layout, partition_offset] : kPartitions) { + const uint64_t descriptor = partition_offset + 32ull * kSector; + if (descriptor + kSector > file->size) continue; + Bytes d = file->ReadBytes(descriptor, kSector); + if (std::memcmp(d.data(), kXdvdfsMagic, 20) || std::memcmp(d.data() + 0x7EC, kXdvdfsMagic, 20)) continue; + XdvdfsVolume volume; + volume.file = file; + volume.layout = layout; + volume.partition_offset = partition_offset; + volume.root_sector = le32(d.data(), 0x14); + volume.root_size = le32(d.data(), 0x18); + if (!volume.root_sector || !volume.root_size) Fail("XDVDFS root directory is empty"); + if (volume.root_size > 16u * 1024u * 1024u) Fail("XDVDFS root directory size unreasonable"); + if (partition_offset + uint64_t(volume.root_sector) * kSector + volume.root_size > file->size) + Fail("XDVDFS root directory outside image"); + return volume; + } + Fail("XDVDFS volume not found (XISO/XGD1/XGD2/XGD3)"); +} + +// listXdvdfsVfsFiles: every file is a contiguous extent of the image. +void listXdvdfsVfsFiles(const XdvdfsVolume& volume, uint32_t sector, uint32_t size, const std::string& prefix, + std::vector& files, int depth = 0) { + if (depth > 64) Fail("XDVDFS directory nesting too deep"); + for (const auto& entry : XdvdfsVolume::WalkTree(volume.Table(sector, size))) { + const std::string path = prefix.empty() ? entry.name : prefix + "\\" + entry.name; + VfsFile f; + f.path = path; + if (entry.directory) { + f.directory = true; + files.push_back(f); + listXdvdfsVfsFiles(volume, entry.start_sector, entry.size, path, files, depth + 1); + } else { + f.size = entry.size; + f.host_fd = volume.file->fd; + f.host_offset = volume.partition_offset + uint64_t(entry.start_sector) * kSector; + files.push_back(f); + } + } +} + +// --- STFS packages (wasm-core.js mountStfs / extractStfsEntry) -------------------- + +void StageSlice(const HostFile* file, uint64_t offset, uint32_t size) { + if (!size || size > r360pkg_io_capacity()) Fail("invalid native STFS read size %u", size); + file->Read(offset, reinterpret_cast(r360pkg_io_ptr()), size); +} +uint64_t RequestOffset() { + return (uint64_t(r360pkg_stfs_request_offset_hi()) << 32) | r360pkg_stfs_request_offset_lo(); +} + +std::string mountStfs(const HostFile* file) { + r360pkg_stfs_mount_begin(uint32_t(file->size), uint32_t(file->size >> 32)); + uint32_t requests = 0; + while (r360pkg_stfs_request_pending()) { + if (++requests > 4096) Fail("STFS mount exceeded 4096 native read requests"); + const uint32_t size = r360pkg_stfs_request_size(); + StageSlice(file, RequestOffset(), size); + r360pkg_stfs_submit_read(size); + } + const uint32_t status = r360pkg_stfs_mount_status(); + if (status != 2 && status != 3) Fail("STFS package did not mount (status %u)", status); + return std::string(reinterpret_cast(r360pkg_stfs_display_name_ptr()), + r360pkg_stfs_display_name_length()); +} + +Bytes extractStfsEntry(const HostFile* file, uint32_t index) { + r360pkg_stfs_extract_begin(index); + Bytes out(r360pkg_stfs_extract_bytes_total()); + uint32_t requests = 0; + while (r360pkg_stfs_request_pending()) { + if (++requests > (1u << 20)) { + r360pkg_stfs_extract_reset(); + Fail("STFS extraction exceeded native read request limit"); + } + const uint32_t size = r360pkg_stfs_request_size(); + const uint32_t dest = r360pkg_stfs_extract_bytes_done(); + StageSlice(file, RequestOffset(), size); + if (dest < out.size()) { + std::memcpy(out.data() + dest, reinterpret_cast(r360pkg_io_ptr()), + std::min(size, out.size() - dest)); + } + r360pkg_stfs_submit_read(size); + } + if (r360pkg_stfs_extract_status() != 2) Fail("STFS extraction of entry %u failed (status %u)", index, + r360pkg_stfs_extract_status()); + return out; +} + +// listStfsVfsFiles + run-title's eager extraction of every file. +std::vector listStfsVfsFiles(const HostFile* file, Bytes* default_xex) { + const uint32_t count = r360pkg_stfs_entry_count(); + std::vector names(count); + std::vector parents(count); + for (uint32_t i = 0; i < count; ++i) { + names[i].assign(reinterpret_cast(r360pkg_stfs_entry_name_ptr(i)), r360pkg_stfs_entry_name_length(i)); + parents[i] = r360pkg_stfs_entry_parent_index(i); + } + auto path_of = [&](uint32_t i) { + std::string path = names[i]; + for (uint32_t p = parents[i], depth = 0; p < count && p != i; p = parents[p]) { + if (++depth > 64) Fail("STFS directory chain too deep"); + path = names[p] + "\\" + path; + if (parents[p] == p) break; + } + return path; + }; + std::vector files; + for (uint32_t i = 0; i < count; ++i) { + VfsFile f; + f.path = path_of(i); + f.directory = r360pkg_stfs_entry_is_directory(i) != 0; + if (!f.directory) { + f.size = r360pkg_stfs_entry_length(i); + f.data = extractStfsEntry(file, i); + f.has_data = true; + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "default.xex") *default_xex = f.data; + } + files.push_back(std::move(f)); + } + return files; +} + +// --- Folders --------------------------------------------------------------------- + +void walkFolder(const std::string& root, const std::string& prefix, std::vector& files) { + DIR* dir = opendir(root.c_str()); + if (!dir) Fail("cannot list %s", root.c_str()); + std::vector names; + while (dirent* e = readdir(dir)) { + if (!std::strcmp(e->d_name, ".") || !std::strcmp(e->d_name, "..")) continue; + names.push_back(e->d_name); + } + closedir(dir); + std::sort(names.begin(), names.end()); // fs.readdirSync order on APFS/HFS+ + for (const auto& name : names) { + const std::string full = root + "/" + name; + const std::string guest = prefix.empty() ? name : prefix + "\\" + name; + struct stat st {}; + if (stat(full.c_str(), &st) != 0) continue; + VfsFile f; + f.path = guest; + if (S_ISDIR(st.st_mode)) { + f.directory = true; + files.push_back(f); + walkFolder(full, guest, files); + } else if (S_ISREG(st.st_mode)) { + f.size = uint64_t(st.st_size); + f.host_fd = OpenHostFile(full)->fd; + files.push_back(f); + } + } +} + +// --- openTitle (tools/run-title.mjs) ------------------------------------------------ + +struct OpenedTitle { + R360SourceKind kind = R360_SOURCE_UNKNOWN; + Bytes default_xex; + std::vector files; + std::string title; +}; + +OpenedTitle openTitle(const std::string& input) { + OpenedTitle title; + struct stat st {}; + if (stat(input.c_str(), &st) != 0) Fail("cannot stat %s", input.c_str()); + if (S_ISDIR(st.st_mode)) { + const std::string xex = input + "/default.xex"; + title.kind = R360_SOURCE_FOLDER; + walkFolder(input, "", title.files); + const HostFile* file = OpenHostFile(xex); + title.default_xex = file->ReadBytes(0, size_t(file->size)); + return title; + } + const HostFile* file = OpenHostFile(input); + uint8_t magic[4] = {}; + if (file->size >= 4) file->Read(0, magic, 4); + if (!std::memcmp(magic, "XEX2", 4)) { + // A bare XEX: its folder is the game root, as when launched from a HDD. + title.kind = R360_SOURCE_XEX; + std::string root = input.substr(0, input.find_last_of('/')); + if (root == input) root = "."; + walkFolder(root, "", title.files); + bool has_default = false; + for (const auto& f : title.files) { + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + has_default |= lower == "default.xex"; + } + if (!has_default) { + VfsFile f; + f.path = "default.xex"; + f.size = file->size; + f.host_fd = file->fd; + title.files.push_back(f); + } + title.default_xex = file->ReadBytes(0, size_t(file->size)); + return title; + } + if (!std::memcmp(magic, "LIVE", 4) || !std::memcmp(magic, "PIRS", 4) || !std::memcmp(magic, "CON ", 4)) { + title.kind = R360_SOURCE_STFS; + title.title = mountStfs(file); + title.files = listStfsVfsFiles(file, &title.default_xex); + if (title.default_xex.empty()) Fail("package has no default.xex"); + return title; + } + // Otherwise try an Xbox game disc image (XISO / XGD1-3). + title.kind = R360_SOURCE_DISC; + const XdvdfsVolume volume = mountXdvdfs(file); + listXdvdfsVfsFiles(volume, volume.root_sector, volume.root_size, "", title.files); + for (const auto& f : title.files) { + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "default.xex" && !f.directory) title.default_xex = file->ReadBytes(f.host_offset, size_t(f.size)); + } + if (title.default_xex.empty()) Fail("disc has no default.xex"); + return title; +} + +// --- XEX helpers (render360-title-controller.mjs) ------------------------------------ + +constexpr uint32_t XEX_HEADER_ENTRY_POINT = 0x00010100; +constexpr uint32_t XENIA_KERNEL_DATA_BASE = 0x50010000; +constexpr uint32_t XENIA_EXECUTABLE_MODULE_VAR = XENIA_KERNEL_DATA_BASE; +constexpr uint32_t XENIA_KE_DEBUG_MONITOR_DATA = XENIA_KERNEL_DATA_BASE + 0x004; +constexpr uint32_t XENIA_KE_CERT_MONITOR_DATA = XENIA_KERNEL_DATA_BASE + 0x008; +constexpr uint32_t XENIA_EXECUTABLE_HMODULE = XENIA_KERNEL_DATA_BASE + 0x100; +constexpr uint32_t XENIA_XEX_HEADER_BASE = XENIA_KERNEL_DATA_BASE + 0x1000; +constexpr uint32_t XENIA_PROCESS_INFO_BLOCK = XENIA_KERNEL_DATA_BASE + 0x200; + +struct KernelVariableSpec { + uint32_t ordinal; + const char* name; + uint32_t address; + std::vector words; + const char* text = nullptr; + uint32_t bytes = 0; +}; +// Every xboxkrnl variable export Xenia backs with real guest storage +// (XboxkrnlModule constructor + RegisterVideoExports), in the kernel data page. +const std::vector& KernelVariableLayout() { + static const std::vector kLayout = { + {0x0C, "ExConsoleGameRegion", XENIA_KERNEL_DATA_BASE + 0x00C, {0xFFFFFFFFu}}, + {0x59, "KeDebugMonitorData", XENIA_KE_DEBUG_MONITOR_DATA, {0}}, + {0xAD, "KeTimeStampBundle", XENIA_KERNEL_DATA_BASE + 0x040, {0, 0, 0, 0, 0, 0}}, + {0x156, "XboxHardwareInfo", XENIA_KERNEL_DATA_BASE + 0x010, {0x20, 0x06000000, 0, 0}}, + {0x158, "XboxKrnlVersion", XENIA_KERNEL_DATA_BASE + 0x020, {0x0002FFFF, 0xFFFF8000}}, + {0x193, "XexExecutableModuleHandle", XENIA_EXECUTABLE_MODULE_VAR, {}}, + {0x1AE, "ExLoadedCommandLine", XENIA_KERNEL_DATA_BASE + 0x800, {}, "\"default.xex\"", 0x400}, + {0x1AF, "ExLoadedImageName", XENIA_KERNEL_DATA_BASE + 0x400, {}, "\\Device\\Cdrom0\\default.xex", 0x100}, + {0x1BE, "VdGlobalDevice", XENIA_KERNEL_DATA_BASE + 0x028, {0}}, + {0x1BF, "VdGlobalXamDevice", XENIA_KERNEL_DATA_BASE + 0x02C, {0}}, + {0x1C0, "VdGpuClockInMHz", XENIA_KERNEL_DATA_BASE + 0x030, {500}}, + // X_RTL_CRITICAL_SECTION initialized with spin count 10000 (Xenia). + {0x1C1, "VdHSIOCalibrationLock", XENIA_KERNEL_DATA_BASE + 0x060, {0x01280000, 0, 0, 0, 0xFFFFFFFFu, 0, 0}}, + {0x266, "KeCertMonitorData", XENIA_KE_CERT_MONITOR_DATA, {0}}, + }; + return kLayout; +} +const KernelVariableSpec* FindKernelVariable(uint32_t ordinal) { + for (const auto& spec : KernelVariableLayout()) { + if (spec.ordinal == ordinal) return &spec; + } + return nullptr; +} +// Xenia XexModule::SetupLibraryImports placeholder for unbacked variables. +uint32_t xeniaUnmappedVariableValue(uint32_t ordinal) { return 0xD000BEEFu | ((ordinal & 0xFFFu) << 16); } + +uint32_t readXexEntryPoint(const Bytes& xex, uint32_t header_size) { + const uint32_t count = be32(xex.data(), 0x14); + if (header_size < 0x18 || count > ((header_size - 0x18) >> 3)) Fail("XEX optional-header table out of bounds"); + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (be32(xex.data(), p) != XEX_HEADER_ENTRY_POINT) continue; + const uint32_t entry = be32(xex.data(), p + 4); + if (!entry) Fail("XEX entry point is zero"); + return entry; + } + Fail("XEX entry point optional header missing"); +} + +// {inline value} for key&0xff == 0, {offset p+4} for 1, else {offset value}. +bool readXexOptionalHeader(const Bytes& xex, uint32_t header_size, uint32_t key, uint32_t* inline_value, + uint32_t* offset) { + const uint32_t count = be32(xex.data(), 0x14); + if (header_size < 0x18 || count > ((header_size - 0x18) >> 3)) return false; + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (be32(xex.data(), p) != key) continue; + const uint32_t value = be32(xex.data(), p + 4); + *inline_value = (key & 0xFF) == 0 ? value : 0; + *offset = (key & 0xFF) == 0 ? 0 : (key & 0xFF) == 1 ? p + 4 : value; + return true; + } + return false; +} + +struct XexTlsInfo { + uint32_t slot_count = 0, raw_data_address = 0, data_size = 0, raw_data_size = 0; +}; +bool readXexTlsInfo(const Bytes& xex, uint32_t header_size, XexTlsInfo* info) { + uint32_t value = 0, o = 0; + if (!readXexOptionalHeader(xex, header_size, 0x00020104, &value, &o) || !o || o + 16 > header_size) return false; + info->slot_count = be32(xex.data(), o); + info->raw_data_address = be32(xex.data(), o + 4); + info->data_size = be32(xex.data(), o + 8); + info->raw_data_size = be32(xex.data(), o + 12); + return true; +} +uint32_t readXexDefaultStackSize(const Bytes& xex, uint32_t header_size) { + uint32_t value = 0, o = 0; + return readXexOptionalHeader(xex, header_size, 0x00020200, &value, &o) ? value : 0; +} + +struct XexPages { + std::vector words; + uint32_t page_size = 0, load_address = 0; +}; +bool readXexPageDescriptors(const Bytes& xex, XexPages* pages) { + if (xex.size() < 0x18) return false; + const uint32_t sec = be32(xex.data(), 0x10); + if (uint64_t(sec) + 0x184 > xex.size()) return false; + pages->load_address = be32(xex.data(), sec + 0x110); + const uint32_t count = be32(xex.data(), sec + 0x180); + if (!count || count > 4096 || uint64_t(sec) + 0x184 + uint64_t(count) * 0x18 > xex.size()) return false; + pages->words.resize(count); + for (uint32_t i = 0; i < count; ++i) pages->words[i] = be32(xex.data(), sec + 0x184 + i * 0x18); + pages->page_size = pages->load_address <= 0x90000000u ? 0x10000 : 0x1000; + return true; +} + +Bytes extractXex2EncryptedImageKey(const Bytes& xex) { + if (xex.size() < 0x18 || std::memcmp(xex.data(), "XEX2", 4)) Fail("default.xex is not XEX2"); + const uint32_t header_size = be32(xex.data(), 8), security = be32(xex.data(), 0x10); + if (header_size < 0x18 || header_size > xex.size()) Fail("XEX header size out of bounds"); + if (!security || security > header_size - 0x160) Fail("XEX2 security info is too small for AES key"); + return Bytes(xex.begin() + security + 0x150, xex.begin() + security + 0x160); +} + +// --- prepareRetailXexImage (retail-xex-image-pipeline.mjs) ---------------------------- + +void coreStage(const uint8_t* bytes, size_t length) { + if (length > r360pkg_io_capacity()) Fail("XEX core staging overflow"); + std::memcpy(reinterpret_cast(r360pkg_io_ptr()), bytes, length); +} + +Bytes normalizeDecryptedHeader(const Bytes& header) { + Bytes out = header; + const uint32_t count = be32(out.data(), 0x14); + uint32_t ffi = 0; + bool found = false; + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (p + 8 > out.size()) Fail("XEX optional-header table truncated"); + if (be32(out.data(), p) == 0x3FF) { + ffi = be32(out.data(), p + 4); + found = true; + break; + } + } + if (!found) Fail("XEX file-format info missing"); + if (ffi + 8 > out.size()) Fail("XEX file-format info out of range"); + out[ffi + 4] = 0; + out[ffi + 5] = 0; + return out; +} + +Bytes decryptBody(const Bytes& key, const uint8_t* body, size_t length) { + auto* ptr = r360_xex_crypto_buffer(); + const uint32_t cap = r360_xex_crypto_capacity(); + if (key.size() != 16) Fail("encrypted XEX security key must be 16 bytes"); + if (!length || (length & 15)) Fail("encrypted XEX body must be non-empty and AES-block aligned"); + r360_xex_crypto_reset(); + std::memcpy(ptr, key.data(), 16); + if (r360_xex_crypto_begin_session(0) != 1) Fail("XEX session derivation failed %u", r360_xex_crypto_status()); + Bytes out(length); + size_t off = 0; + while (off < length) { + const uint32_t n = uint32_t(std::min(cap, length - off)) & ~15u; + if (!n) Fail("XEX AES chunk accounting failed"); + std::memcpy(ptr, body + off, n); + if (r360_xex_crypto_decrypt_chunk(n) != 1) Fail("XEX AES decrypt failed %u", r360_xex_crypto_status()); + std::memcpy(out.data() + off, ptr, n); + off += n; + } + if (r360_xex_crypto_bytes_done() != length) Fail("XEX AES byte accounting mismatch"); + return out; +} + +Bytes prepareNone(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_none_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st != 1) Fail("NONE begin failed %u", st); + Bytes out; + size_t off = 0; + while (off < body.size()) { + const size_t n = std::min(body.size() - off, 0x7000); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_none_accept(uint32_t(n)); + out.insert(out.end(), body.begin() + off, body.begin() + off + n); + off += n; + } + if (st != 2) Fail("NONE preparation failed %u", st); + return out; +} + +Bytes prepareBasic(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_basic_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st != 1) Fail("BASIC begin failed %u", st); + Bytes out; + size_t off = 0, guard = 0; + while (r360pkg_xex_prepare_status() == 1) { + if (++guard > 100000) Fail("BASIC preparation loop runaway"); + const uint32_t zero = r360pkg_xex_prepare_basic_zero_remaining(); + if (zero) { + st = r360pkg_xex_prepare_basic_consume_zero(std::min(zero, 0x4000)); + const uint32_t outn = r360pkg_xex_prepare_last_output_bytes(); + if (!outn || r360pkg_xex_prepare_last_output_kind() != 2) Fail("BASIC zero event mismatch"); + out.insert(out.end(), outn, 0); + continue; + } + const uint32_t data = r360pkg_xex_prepare_basic_data_remaining(); + if (!data) Fail("BASIC state has no work"); + const size_t n = std::min({size_t(data), body.size() - off, size_t(0x7000)}); + if (!n) Fail("BASIC encrypted source truncated"); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_basic_accept_data(uint32_t(n)); + if (r360pkg_xex_prepare_last_output_bytes() != n || r360pkg_xex_prepare_last_output_kind() != 1) + Fail("BASIC data event mismatch"); + out.insert(out.end(), body.begin() + off, body.begin() + off + n); + off += n; + } + if (st != 2 || off != body.size()) Fail("BASIC preparation failed status=%u source=%zu/%zu", st, off, body.size()); + return out; +} + +Bytes prepareNormal(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_normal_frame_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st >= 100) Fail("NORMAL begin failed %u", st); + Bytes stream; + size_t off = 0, pi = 0; + static const size_t kPattern[] = {17, 31, 67, 127, 251, 509}; + while (off < body.size() && st != 2 && st < 100) { + const size_t n = std::min(body.size() - off, kPattern[pi++ % 6]); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_normal_frame_accept(uint32_t(n)); + const uint32_t outn = r360pkg_xex_prepare_last_output_bytes(); + if (outn) { + const auto* io = reinterpret_cast(r360pkg_io_ptr()); + stream.insert(stream.end(), io, io + outn); + } + off += n; + } + if (st != 2) Fail("NORMAL framing failed %u", st); + const uint32_t expected = r360pkg_xex_decode_image_size(); + if (stream.empty() || stream.size() > r360_lzx_input_capacity() || !expected || expected > r360_lzx_output_capacity()) + Fail("NORMAL LZX bounds"); + r360_lzx_reset(); + std::memcpy(r360_lzx_input_buffer(), stream.data(), stream.size()); + const uint32_t ls = r360_lzx_decompress(uint32_t(stream.size()), expected, r360pkg_xex_prepare_normal_window_size()); + if (ls != 0 || r360_lzx_output_size() != expected) Fail("NORMAL LZX failed %u", ls); + return Bytes(r360_lzx_output_buffer(), r360_lzx_output_buffer() + expected); +} + +Bytes prepareRetailXexImage(const Bytes& header, const Bytes& body, const Bytes& key) { + coreStage(header.data(), header.size()); + const uint32_t decode = r360pkg_xex_decode(uint32_t(header.size())); + if (decode != 1) Fail("XEX metadata decode failed status=%u", decode); + const uint32_t enc = r360pkg_xex_decode_encryption_type(); + const uint32_t comp = r360pkg_xex_decode_compression_type(); + if (comp > 2) Fail("unsupported XEX patch/delta compression %u", comp); + Bytes plain = body, effective = header; + if (enc == 1) { + plain = decryptBody(key, body.data(), body.size()); + effective = normalizeDecryptedHeader(header); + } else if (enc != 0) { + Fail("unsupported XEX encryption %u", enc); + } + if (comp == 0) return prepareNone(effective, plain); + if (comp == 1) return prepareBasic(effective, plain); + return prepareNormal(effective, plain); +} + +// --- Kernel import plan (render360-xex-imports.mjs, render360-kernel-imports.mjs) --- + +struct ImportLibrary { + std::string name; + std::vector imports; +}; + +std::vector decodeXexImportLibraries(const Bytes& x) { + const uint32_t header_size = be32(x.data(), 8), header_count = be32(x.data(), 0x14); + if (header_size < 0x18 || header_size > x.size() || header_count > ((header_size - 0x18) >> 3)) + Fail("XEX optional header table out of bounds"); + uint32_t offset = 0; + for (uint32_t i = 0; i < header_count; ++i) { + if (be32(x.data(), 0x18 + i * 8) == 0x000103FF) { + offset = be32(x.data(), 0x18 + i * 8 + 4); + break; + } + } + std::vector libraries; + if (!offset) return libraries; + if (offset > header_size - 12) Fail("XEX import header out of bounds"); + const uint32_t total = be32(x.data(), offset), string_bytes = be32(x.data(), offset + 4), + string_count = be32(x.data(), offset + 8); + if (total < 12 || offset + total > header_size || 12 + string_bytes > total || string_count > 256) + Fail("XEX import header size invalid"); + std::vector strings; + for (uint32_t s = 0; s < string_bytes && strings.size() < string_count;) { + const uint32_t start = offset + 12 + s, limit = offset + 12 + string_bytes; + uint32_t end = start; + while (end < limit && x[end]) ++end; + if (end == limit) Fail("unterminated XEX import string"); + strings.emplace_back(reinterpret_cast(x.data() + start), end - start); + s += (end - start) + 1; + if (s & 3) s += 4 - (s & 3); + } + if (strings.size() != string_count) Fail("XEX import string count mismatch"); + uint32_t p = offset + 12 + string_bytes; + const uint32_t end = offset + total; + while (p < end) { + if (end - p < 0x28) Fail("truncated XEX import library"); + const uint32_t size = be32(x.data(), p); + if (!size) break; + if (size < 0x28 || size > end - p) Fail("XEX import library size invalid"); + const uint32_t name_index = be16(x.data(), p + 0x24) & 0xFF, count = be16(x.data(), p + 0x26); + if (name_index >= strings.size()) Fail("XEX import library name index invalid"); + if (0x28 + count * 4 > size) Fail("XEX import table exceeds library record"); + ImportLibrary lib; + lib.name = strings[name_index]; + for (uint32_t i = 0; i < count; ++i) lib.imports.push_back(be32(x.data(), p + 0x28 + i * 4)); + libraries.push_back(std::move(lib)); + p += size; + } + return libraries; +} + +uint32_t imageBaseFromXex(const Bytes& x) { + const uint32_t header_count = be32(x.data(), 0x14); + for (uint32_t i = 0; i < header_count; ++i) { + if (be32(x.data(), 0x18 + i * 8) == 0x00010201) return be32(x.data(), 0x18 + i * 8 + 4); + } + Fail("XEX image base optional header missing"); +} + +struct PeSection { + uint32_t virtual_size, virtual_address, raw_size, raw_pointer, virtual_span; +}; +struct PreparedPe { + const Bytes* bytes; + uint32_t size_of_image = 0, size_of_headers = 0; + std::vector sections; +}; + +PreparedPe parsePreparedPe(const Bytes& p) { + if (p.size() < 0x40 || p[0] != 0x4D || p[1] != 0x5A) Fail("kernel import prepared image is not PE"); + const uint32_t nt = le32(p.data(), 0x3C); + if (nt > p.size() - 24 || le32(p.data(), nt) != 0x00004550) Fail("kernel import PE NT header invalid"); + const uint32_t section_count = le16(p.data(), nt + 6), optional_size = le16(p.data(), nt + 20), optional = nt + 24; + if (optional > p.size() || optional_size > p.size() - optional) Fail("kernel import PE optional header out of bounds"); + if (optional_size < 64) Fail("kernel import PE optional header too small"); + PreparedPe pe; + pe.bytes = &p; + pe.size_of_image = le32(p.data(), optional + 56); + pe.size_of_headers = le32(p.data(), optional + 60); + if (!pe.size_of_image || pe.size_of_headers > p.size()) Fail("kernel import PE image/header size invalid"); + const uint32_t table = optional + optional_size; + if (section_count > (p.size() - table) / 40) Fail("kernel import PE section table out of bounds"); + for (uint32_t i = 0; i < section_count; ++i) { + const uint32_t s = table + i * 40; + PeSection sec{le32(p.data(), s + 8), le32(p.data(), s + 12), le32(p.data(), s + 16), le32(p.data(), s + 20), 0}; + sec.virtual_span = std::max(sec.virtual_size, sec.raw_size); + const uint64_t vend = uint64_t(sec.virtual_address) + sec.virtual_span; + if (vend > 0x100000000ull || vend > pe.size_of_image) Fail("kernel import PE section RVA wraps/exceeds image"); + pe.sections.push_back(sec); + } + return pe; +} + +bool rvaInsideMappedPe(const PreparedPe& pe, uint64_t rva, uint64_t size) { + const uint64_t len = pe.bytes->size(); + if (rva < pe.size_of_headers) return rva + size <= pe.size_of_headers && rva + size <= len; + for (const auto& s : pe.sections) { + if (rva < s.virtual_address) continue; + const uint64_t delta = rva - s.virtual_address; + if (delta >= s.virtual_span) continue; + return rva + size <= len && delta + size <= s.virtual_span; + } + return false; +} + +bool rawOffsetForRva(const PreparedPe& pe, uint64_t rva, uint64_t size, uint64_t* out) { + const uint64_t len = pe.bytes->size(); + if (rva < pe.size_of_headers) { + if (rva + size <= pe.size_of_headers && rva + size <= len) { + *out = rva; + return true; + } + return false; + } + for (const auto& s : pe.sections) { + if (rva < s.virtual_address) continue; + const uint64_t delta = rva - s.virtual_address; + if (delta >= s.virtual_span) continue; + if (int64_t(delta) > int64_t(s.raw_size) - int64_t(size)) return false; + const uint64_t raw = s.raw_pointer + delta; + if (raw + size > len) return false; + *out = raw; + return true; + } + return false; +} + +bool isMappedImageLayout(const PreparedPe& pe) { + const uint64_t len = pe.bytes->size(); + if (len >= pe.size_of_image) return true; + uint64_t disk_end = pe.size_of_headers; + for (const auto& s : pe.sections) disk_end = std::max(disk_end, uint64_t(s.raw_pointer) + s.raw_size); + if (len > disk_end) return true; + if (pe.sections.empty()) return false; + for (const auto& s : pe.sections) { + if (uint64_t(s.virtual_address) + std::min(s.raw_size, s.virtual_span) > len) return false; + } + return true; +} + +struct ResolvedDescriptor { + bool mapped; + uint64_t offset; + uint32_t descriptor, type, ordinal; +}; +ResolvedDescriptor resolveImportDescriptor(const PreparedPe& pe, uint64_t rva) { + std::vector candidates; + if (rvaInsideMappedPe(pe, rva, 4)) candidates.push_back({true, rva, 0, 0, 0}); + uint64_t raw = 0; + if (rawOffsetForRva(pe, rva, 4, &raw)) { + bool dup = false; + for (const auto& c : candidates) dup |= c.offset == raw; + if (!dup) candidates.push_back({false, raw, 0, 0, 0}); + } + if (candidates.empty()) Fail("XEX import descriptor RVA is outside PE mappings"); + for (auto& c : candidates) { + c.descriptor = be32(pe.bytes->data(), size_t(c.offset)); + c.type = (c.descriptor >> 24) & 0xFF; + c.ordinal = c.descriptor & 0xFFFF; + } + std::vector valid; + for (const auto& c : candidates) { + if (c.type == 0 || c.type == 1) valid.push_back(c); + } + if (valid.size() == 1) return valid[0]; + if (valid.size() > 1) { + const bool want_mapped = isMappedImageLayout(pe); + for (const auto& c : valid) { + if (c.mapped == want_mapped) return c; + } + return valid[0]; + } + Fail("unsupported XEX import descriptor type %u", candidates[0].type); +} + +struct KernelImport { + std::string module; + uint32_t ordinal = 0; + bool function = false; + bool kernel_module = false; + uint32_t value_address = 0, thunk_address = 0; +}; +struct KernelImportPlan { + uint32_t image_base = 0; + std::vector plan; +}; + +KernelImportPlan buildKernelImportPlan(const Bytes& xex, const Bytes& prepared) { + KernelImportPlan out; + const auto libraries = decodeXexImportLibraries(xex); + const PreparedPe pe = parsePreparedPe(prepared); + out.image_base = imageBaseFromXex(xex); + for (const auto& lib : libraries) { + std::string lower = lib.name; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + const bool kernel = lower == "xboxkrnl.exe" || lower == "xam.xex"; + std::vector imports; + for (uint32_t record : lib.imports) { + if (record < out.image_base) Fail("XEX import descriptor below image base: %s@0x%x", lib.name.c_str(), record); + const ResolvedDescriptor d = resolveImportDescriptor(pe, uint64_t(record) - out.image_base); + if (d.type == 0) { + KernelImport item; + item.module = lib.name; + item.ordinal = d.ordinal; + item.kernel_module = kernel; + item.value_address = record; + imports.push_back(item); + continue; + } + if (imports.empty() || imports.back().ordinal != d.ordinal || imports.back().thunk_address) + Fail("XEX import thunk has no matching descriptor: %s ordinal 0x%x", lib.name.c_str(), d.ordinal); + imports.back().function = true; + imports.back().thunk_address = record; + } + out.plan.insert(out.plan.end(), imports.begin(), imports.end()); + } + return out; +} + +uint32_t moduleId(const std::string& name) { + std::string lower = name; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + return lower == "xboxkrnl.exe" ? 1 : lower == "xam.xex" ? 2 : 0; +} + +// registerKernelImportPlan: no browser HLE in the native build (the native +// title-GPU runtime is always present), so no function import is +// "implemented" by a relocated shim. +uint32_t registerKernelImportPlan(const KernelImportPlan& imports) { + r360_kernel_import_reset(); + uint32_t registered = 0; + for (const auto& item : imports.plan) { + if (!item.kernel_module || !item.function || !item.thunk_address) continue; + const uint32_t id = moduleId(item.module); + if (!id) continue; + if (r360_kernel_import_register(item.thunk_address, id, item.ordinal, 0, 0) != 1) + Fail("failed to register kernel import %s ordinal 0x%x", item.module.c_str(), item.ordinal); + ++registered; + } + return registered; +} + +void put8(uint32_t address, uint32_t value) { + if (r360_sparse_guest_memory_write_u8(address, value & 0xFF) != 1) + Fail("unable to initialize guest memory @ 0x%x", address); +} +void put32(uint32_t address, uint32_t value) { + for (int i = 0; i < 4; ++i) put8(address + i, (value >> (24 - i * 8)) & 0xFF); +} + +uint32_t installKernelVariableImports(const KernelImportPlan& imports, const Bytes& xex, uint32_t entry, + uint32_t header_size) { + bool any = false; + for (const auto& item : imports.plan) any |= item.kernel_module && !item.function; + if (!any) return 0; + const uint32_t page = 4096, read_write = 3; + const uint32_t pages = 1 + (header_size + page - 1) / page; + const uint32_t backing = r360_sparse_guest_memory_alloc(pages); + if (!backing || r360_sparse_guest_memory_map(XENIA_KERNEL_DATA_BASE, pages, backing, 0, read_write) != 1) + Fail("unable to map Xenia kernel variable/module state"); + for (uint32_t i = 0; i < header_size; ++i) put8(XENIA_XEX_HEADER_BASE + i, xex[i]); + const uint32_t security = be32(xex.data(), 0x10); + if (security > header_size - 8) Fail("XEX security header is outside copied guest header"); + const uint32_t image_size = be32(xex.data(), security + 4); + // X_LDR_DATA_TABLE_ENTRY fields used by Xenia UserModule::LoadXexContinue. + put32(XENIA_EXECUTABLE_HMODULE + 0x18, 0); + put32(XENIA_EXECUTABLE_HMODULE + 0x1C, imports.image_base); + put32(XENIA_EXECUTABLE_HMODULE + 0x38, image_size); + put32(XENIA_EXECUTABLE_HMODULE + 0x3C, entry); + put32(XENIA_EXECUTABLE_HMODULE + 0x58, XENIA_XEX_HEADER_BASE); + put32(XENIA_EXECUTABLE_MODULE_VAR, XENIA_EXECUTABLE_HMODULE); + for (const auto& spec : KernelVariableLayout()) { + for (size_t i = 0; i < spec.words.size(); ++i) put32(spec.address + uint32_t(i) * 4, spec.words[i]); + if (spec.text) { + const size_t n = std::strlen(spec.text); + for (uint32_t i = 0; i < spec.bytes; ++i) put8(spec.address + i, i < n ? uint8_t(spec.text[i]) : 0); + } + } + // ProcessInfoBlock (KernelState::SetExecutableModule). + XexTlsInfo tls; + const bool has_tls = readXexTlsInfo(xex, header_size, &tls); + for (uint32_t i = 0; i < 0x60; i += 4) put32(XENIA_PROCESS_INFO_BLOCK + i, 0); + put32(XENIA_PROCESS_INFO_BLOCK + 0x0C, 0x0000007F); + put32(XENIA_PROCESS_INFO_BLOCK + 0x10, 0x001F0000); + put8(XENIA_PROCESS_INFO_BLOCK + 0x1B, 0x06); + put32(XENIA_PROCESS_INFO_BLOCK + 0x1C, 16 * 1024); + if (has_tls) { + put32(XENIA_PROCESS_INFO_BLOCK + 0x24, tls.data_size); + put32(XENIA_PROCESS_INFO_BLOCK + 0x28, tls.raw_data_size); + put8(XENIA_PROCESS_INFO_BLOCK + 0x2C, ((tls.slot_count * 4) >> 8) & 0xFF); + put8(XENIA_PROCESS_INFO_BLOCK + 0x2D, (tls.slot_count * 4) & 0xFF); + } + put8(XENIA_PROCESS_INFO_BLOCK + 0x2F, 1); // X_PROCTYPE_USER + if (r360_kernel_set_executable_module(XENIA_EXECUTABLE_HMODULE, XENIA_XEX_HEADER_BASE, XENIA_PROCESS_INFO_BLOCK) != 1) + Fail("native kernel rejected the guest XEX header"); + r360_kernel_set_timestamp_bundle(XENIA_KERNEL_DATA_BASE + 0x040); + uint32_t relocated = 0; + for (const auto& item : imports.plan) { + if (!item.kernel_module || item.function) continue; + std::string lower = item.module; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + const KernelVariableSpec* spec = lower == "xboxkrnl.exe" ? FindKernelVariable(item.ordinal) : nullptr; + const uint32_t target = spec ? spec->address : xeniaUnmappedVariableValue(item.ordinal); + if (r360_xex_guest_mapper_patch_u32_be(item.value_address, target) != 1) + Fail("failed to relocate %s ordinal 0x%x at 0x%x (mapper 0x%x)", item.module.c_str(), item.ordinal, + item.value_address, r360_xex_guest_mapper_status()); + if (spec) ++relocated; + } + return relocated; +} + +struct MainThreadContext { + uint32_t stack_top = 0, pcr = 0; +}; + +MainThreadContext prepareBrowserMainThreadContext(uint32_t entry, const Bytes& xex, uint32_t header_size) { + const uint32_t page = 4096, stack_slot_base = 0x70000000, stack_limit = stack_slot_base + page; + const uint32_t xex_stack = readXexDefaultStackSize(xex, header_size); + const uint32_t stack_pages = std::max(128, std::min(0x0F00, (xex_stack + 4095) / 4096)); + const uint32_t stack_base = stack_limit + stack_pages * page; + MainThreadContext ctx; + ctx.stack_top = (stack_base - (64 + 112)) & ~0xFu; + ctx.pcr = 0x50000000; + const uint32_t tls_address = 0x50001000, thread = 0x50002000, context_pages = 3, read_write = 3; + const uint32_t stack_backing = r360_sparse_guest_memory_alloc(stack_pages); + if (!stack_backing || r360_sparse_guest_memory_map(stack_limit, stack_pages, stack_backing, 0, read_write) != 1) + Fail("unable to map Xbox main-thread stack"); + const uint32_t context_backing = r360_sparse_guest_memory_alloc(context_pages); + if (!context_backing || r360_sparse_guest_memory_map(ctx.pcr, context_pages, context_backing, 0, read_write) != 1) + Fail("unable to map Xbox main-thread PCR/TLS"); + put32(ctx.pcr + 0x000, tls_address); + put32(ctx.pcr + 0x030, ctx.pcr); + put32(ctx.pcr + 0x070, stack_base); + put32(ctx.pcr + 0x074, stack_limit); + put32(ctx.pcr + 0x100, thread); + put32(ctx.pcr + 0x150, 0); + put32(thread + 0x05C, stack_base); + put32(thread + 0x060, stack_limit); + put32(thread + 0x068, tls_address); + put32(thread + 0x0D0, stack_base); + put32(thread + 0x14C, 1); + put32(thread + 0x150, entry); + // XThread::InitializeGuestObject: dispatcher header type 6, self-linked + // list heads, process info block, creation time, flags. + put8(thread + 0x000, 6); + static const uint32_t kLinks[][2] = {{0x008, 0x008}, {0x00C, 0x008}, {0x010, 0x010}, {0x014, 0x010}, + {0x040, 0x020}, {0x044, 0x020}, {0x048, 0x000}, {0x04C, 0x018}, + {0x074, 0x074}, {0x078, 0x074}, {0x07C, 0x07C}, {0x080, 0x07C}, + {0x144, 0x144}, {0x148, 0x144}, {0x154, 0x154}, {0x158, 0x154}}; + for (const auto& link : kLinks) put32(thread + link[0], thread + link[1]); + put32(thread + 0x054, 0x01020001); + put32(thread + 0x084, XENIA_PROCESS_INFO_BLOCK); + put8(thread + 0x08B, 1); + put32(thread + 0x09C, 0xFDFFD7FF); + put32(thread + 0x17C, 1); + // TLS: slots*4 + extended data, with the XEX TLS template copied in. + XexTlsInfo tls; + if (readXexTlsInfo(xex, header_size, &tls)) { + const uint32_t slots = tls.slot_count ? tls.slot_count : 1024; + const uint32_t total = slots * 4 + tls.data_size; + uint32_t block = tls_address; + if (total > page) { + block = r360_kernel_pool_alloc(total, 16); + if (!block) Fail("unable to allocate %u-byte Xbox TLS block", total); + } + const uint32_t copy = std::min(tls.raw_data_size, tls.data_size); + for (uint32_t i = 0; copy && tls.raw_data_address && i < copy; ++i) + put8(block + i, r360_sparse_guest_memory_read_u8(tls.raw_data_address + i)); + put32(ctx.pcr + 0x000, block); + put32(thread + 0x068, block); + } + r360_guest_thread_register_external(entry, stack_base, stack_limit, ctx.pcr, thread, 1); + return ctx; +} + +void stagePreparedPeImage(const Bytes& prepared, uint32_t xex_entry, const Bytes& xex) { + uintptr_t input = r360_xex_guest_mapper_input_buffer(); + uint32_t cap = r360_xex_guest_mapper_input_capacity(); + if (prepared.size() > cap) { + const uint32_t max = r360_xex_guest_mapper_input_max_capacity(); + if (max && prepared.size() > max) Fail("prepared image exceeds bounded PE staging ceiling %zu/%u", prepared.size(), max); + if (r360_xex_guest_mapper_reserve_input(uint32_t(prepared.size())) != 1) + Fail("unable to reserve PE staging for prepared image %zu bytes (status 0x%x)", prepared.size(), + r360_xex_guest_mapper_status()); + input = r360_xex_guest_mapper_input_buffer(); + cap = r360_xex_guest_mapper_input_capacity(); + } + if (!input || prepared.size() > cap) Fail("prepared image exceeds current PE staging capacity %zu/%u", prepared.size(), cap); + XexPages pages; + if (readXexPageDescriptors(xex, &pages) && pages.words.size() * 4 <= cap) { + std::memcpy(reinterpret_cast(input), pages.words.data(), pages.words.size() * 4); + r360_pe_guest_set_xex_pages(input, uint32_t(pages.words.size()), pages.page_size); + } + std::memcpy(reinterpret_cast(input), prepared.data(), prepared.size()); + if (r360_pe_guest_load_at_entry(input, uint32_t(prepared.size()), xex_entry) != 1) + Fail("prepared PE guest load failed 0x%x", r360_pe_guest_status()); +} + +uint32_t RunScannedEntry(void*) { return r360_title_handoff_translate_scanned_entry(); } + +// Mirrors the runtimeBoundary expression in handoffDefaultXex. +const char* RuntimeBoundary(bool stopped, uint32_t exec_status, uint32_t kernel_status, uint32_t blocker_kind) { + if (stopped) return "stopped-by-user"; + if (exec_status == 3) return "guest-return"; + if (kernel_status == 2) return "kernel-import-unimplemented"; + if (kernel_status == 3) return "kernel-import-abi-failed"; + if (kernel_status == 4) return "title-requested-exit"; + if (kernel_status == 5) return "guest-wait-blocked"; + if (exec_status == 2) return "no-return-boundary"; + if (exec_status == 1) { + return blocker_kind == 2 ? "unresolved-guest-call" + : blocker_kind == 3 ? "instruction-limit" + : blocker_kind == 5 ? "guest-memory-dependency" + : "unsupported-hir"; + } + return "execution-not-observed"; +} + +const char* const kTerminalKinds[] = {"none", "HalReturnToFirmware", "KeBugCheck", "ExTerminateThread", + "XamLoaderTerminateTitle", "XamLoaderLaunchTitle", "title process exit"}; +const char* const kWaitReasons[] = {"none", + "infinite wait on an unsignalled object", + "bounded wait spinning without progress", + "lock held by another guest thread", + "game file bytes not yet available to the synchronous kernel", + "XMA audio buffers waiting for a decoder (not implemented yet)"}; + +// Disc list of the last boot (multi-disc titles). +std::vector g_discs; +uint32_t g_current_disc = 0; + +void handoffDefaultXex(const Bytes& xex, const Bytes& key, const R360BootOptions& options, R360BootResult* r) { + if (xex.size() < 0x18 || std::memcmp(xex.data(), "XEX2", 4)) Fail("default.xex is not XEX2"); + const uint32_t header_size = be32(xex.data(), 8); + if (header_size < 0x18 || header_size > xex.size()) Fail("default.xex header size out of bounds"); + const uint32_t xex_entry = readXexEntryPoint(xex, header_size); + const Bytes header(xex.begin(), xex.begin() + header_size), body(xex.begin() + header_size, xex.end()); + const Bytes prepared = prepareRetailXexImage(header, body, key); + + // Each handoff is a fresh title boot (the registered guest VFS is kept). + r360_kernel_runtime_reset(); + r360_kernel_services_reset(); + r360_xam_set_license_mask(options.license_full ? 1 : 0); + r360_kernel_service_reset(); + stagePreparedPeImage(prepared, xex_entry, xex); + // XexModule::FindSaveRest. + XexPages pages; + if (readXexPageDescriptors(xex, &pages)) { + uint32_t address = pages.load_address; + for (uint32_t word : pages.words) { + const uint32_t size = (word >> 4) * pages.page_size; + if ((word & 0xF) == 1 && r360_ppc_probe_register_save_rest(address, address + size) == 3) break; + address += size; + } + } + const uint32_t entry = r360_pe_guest_entry_address(); + r->pe_entry = r360_pe_guest_pe_entry_address(); + if (entry != xex_entry) Fail("XEX entry selection mismatch 0x%x/0x%x", entry, xex_entry); + r->entry = entry; + + const KernelImportPlan imports = buildKernelImportPlan(xex, prepared); + r->kernel_imports = uint32_t(imports.plan.size()); + r->kernel_registered = registerKernelImportPlan(imports); + r->kernel_variables_relocated = installKernelVariableImports(imports, xex, entry, header_size); + + r360_title_handoff_reset(); + if (r360_ppc_probe_page_sparse_code(entry) == 0) Fail("unable to initialize Xenia title decoder before main-thread context"); + r360_title_handoff_reset(); + const MainThreadContext ctx = prepareBrowserMainThreadContext(entry, xex, header_size); + // R360_XENIA_ENTRY_ABI_V51: upstream Processor::Execute special state. + if (r360_ppc_probe_set_initial_lr(0xBCBCBCBCull) != 1) Fail("unable to initialize Xenia title-entry LR"); + if (uint32_t(r360_ppc_probe_initial_lr()) != 0xBCBCBCBCu) Fail("Xenia title-entry LR verification failed"); + if (r360_ppc_probe_set_initial_gpr(1, ctx.stack_top) != 1 || r360_ppc_probe_set_initial_gpr(13, ctx.pcr) != 1) + Fail("failed to set startup GPRs"); + // A sliced run lifts the per-function HIR instruction guard (as the browser). + if (options.slice_ms) r360_hir_set_instruction_budget(0xFFFFFFFFu); + + uint32_t stopped = 0; + const uint32_t hir = r360_native_run_with_fibers(RunScannedEntry, nullptr, options.slice_ms, options.on_slice, + options.user, &stopped); + r->stopped_by_host = stopped == 1; + r->hir = r->stopped_by_host ? 1 : hir; + if (!r->hir) { + Fail("title entry handoff failed 0x%x probe=0x%x entry=0x%x", r360_title_handoff_status(), r360_ppc_probe_status(), + entry); + } + r->execution_status = r360_ppc_probe_correctness_status(); + r->execution_instructions = r360_ppc_probe_correctness_instructions(); + r->blocker_kind = r360_ppc_probe_correctness_blocker_kind(); + r->blocker_opcode = r360_ppc_probe_correctness_blocker_opcode(); + r->blocker_address = r360_ppc_probe_correctness_blocker_address(); + r->memory_fault_address = r360_sparse_guest_memory_last_fault_address(); + r->memory_fault_code = r360_sparse_guest_memory_last_fault_code(); + r->kernel_calls = r360_kernel_import_calls(); + r->kernel_last_status = r360_kernel_import_last_status(); + r->kernel_last_module = r360_kernel_import_last_module(); + r->kernel_last_ordinal = r360_kernel_import_last_ordinal(); + std::snprintf(r->runtime_boundary, sizeof(r->runtime_boundary), "%s", + RuntimeBoundary(r->stopped_by_host, r->execution_status, r->kernel_last_status, r->blocker_kind)); + char name[96]; + if (r->kernel_last_status == 4) { + const uint32_t kind = r360_kernel_terminal_kind(); + std::snprintf(r->kernel_boundary, sizeof(r->kernel_boundary), "title-requested-exit: %s via %s code 0x%X lr 0x%08X", + kind < 7 ? kTerminalKinds[kind] : "terminal", + r360_native_kernel_export_name(r360_kernel_terminal_module(), r360_kernel_terminal_ordinal(), name, + sizeof(name)), + r360_kernel_terminal_code(), r360_kernel_terminal_lr()); + } else if (r->kernel_last_status == 5) { + const uint32_t reason = r360_kernel_wait_reason(); + std::snprintf(r->kernel_boundary, sizeof(r->kernel_boundary), "guest-wait-blocked: %s via %s object 0x%08X", + reason < 6 ? kWaitReasons[reason] : "wait", + r360_native_kernel_export_name(r360_kernel_wait_module(), r360_kernel_wait_ordinal(), name, + sizeof(name)), + r360_kernel_wait_object()); + } +} + +struct ExportName { + uint32_t ordinal; + const char* name; +}; +const ExportName kXboxkrnl[] = { +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name} +#include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc" +#undef XE_EXPORT +}; +const ExportName kXam[] = { +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name} +#include "xenia/kernel/xam/xam_table.inc" +#undef XE_EXPORT +}; + +void JsonString(std::string& out, const char* s) { + out += '"'; + for (; *s; ++s) { + const unsigned char c = static_cast(*s); + if (c == '"' || c == '\\') { + out += '\\'; + out += char(c); + } else if (c < 0x20) { + char esc[8]; + std::snprintf(esc, sizeof(esc), "\\u%04x", c); + out += esc; + } else { + out += char(c); + } + } + out += '"'; +} + +std::chrono::steady_clock::time_point g_boot_started; + +} // namespace + +extern "C" const char* r360_native_kernel_export_name(uint32_t module, uint32_t ordinal, char* buf, size_t size) { + const ExportName* table = module == 1 ? kXboxkrnl : module == 2 ? kXam : nullptr; + const size_t count = module == 1 ? sizeof(kXboxkrnl) / sizeof(kXboxkrnl[0]) : sizeof(kXam) / sizeof(kXam[0]); + for (size_t i = 0; table && i < count; ++i) { + if (table[i].ordinal == ordinal) { + std::snprintf(buf, size, "%s", table[i].name); + return buf; + } + } + std::snprintf(buf, size, "%s!0x%X", module == 1 ? "xboxkrnl.exe" : module == 2 ? "xam.xex" : "module", ordinal); + return buf; +} + +extern "C" uint32_t r360_native_boot(const R360BootOptions* options, R360BootResult* result) { + *result = R360BootResult{}; + g_boot_started = std::chrono::steady_clock::now(); + try { + if (!options || !options->path) Fail("no title path"); + g_discs.clear(); + g_discs.push_back(options->path); + for (uint32_t i = 0; options->discs && i < options->disc_count; ++i) { + if (options->discs[i] && g_discs[0] != options->discs[i]) g_discs.push_back(options->discs[i]); + } + g_current_disc = 0; + OpenedTitle title = openTitle(options->path); + result->kind = title.kind; + std::snprintf(result->title, sizeof(result->title), "%s", title.title.c_str()); + for (const auto& f : title.files) (f.directory ? result->vfs_directories : result->vfs_files)++; + registerGuestVfs(title.files); + title.files.clear(); // attached STFS data now lives in the kernel VFS + const Bytes key = extractXex2EncryptedImageKey(title.default_xex); + r360_hir_set_instruction_budget(options->function_budget ? options->function_budget : (1u << 30)); + r360_trace_set_verbose(0); + if (options->deterministic_ps) r360_set_deterministic_clock(options->deterministic_ps); + r360_hir_set_total_instruction_budget(options->max_minstr); + if (options->dialog_button >= 0) r360_xam_dialog_set_auto_answer(options->dialog_button); + r360_ppc_probe_set_execute_on_translate(1); + handoffDefaultXex(title.default_xex, key, *options, result); + result->ok = 1; + } catch (const std::exception& e) { + std::snprintf(result->error, sizeof(result->error), "%s", e.what()); + result->ok = 0; + } + result->elapsed_ms = + std::chrono::duration(std::chrono::steady_clock::now() - g_boot_started).count(); + return result->ok; +} + +extern "C" uint32_t r360_native_current_disc() { return g_current_disc; } + +extern "C" uint32_t r360_native_select_disc(uint32_t index) { + if (index >= g_discs.size()) return 0; + try { + OpenedTitle disc = openTitle(g_discs[index]); + registerGuestVfs(disc.files); + g_current_disc = index; + return 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "R360_DISC select %u failed: %s\n", index, e.what()); + return 0; + } +} + +extern "C" size_t r360_native_report_json(const R360BootResult* r, char* out, size_t capacity) { + static const char* const kKinds[] = {"unknown", "folder", "xex", "stfs", "iso"}; + std::string j = "{"; + char buf[512]; + auto field = [&](const char* name, const char* format, auto... values) { + std::snprintf(buf, sizeof(buf), format, values...); + if (j.size() > 1) j += ','; + j += '"'; + j += name; + j += "\":"; + j += buf; + }; + auto text = [&](const char* name, const char* value) { + if (j.size() > 1) j += ','; + j += '"'; + j += name; + j += "\":"; + JsonString(j, value); + }; + text("build", "native"); + text("kind", kKinds[r->kind < 5 ? r->kind : 0]); + if (r->title[0]) text("title", r->title); + field("elapsedMs", "%.0f", r->elapsed_ms); + field("vfs", "{\"files\":%u,\"directories\":%u,\"reads\":%u}", r->vfs_files, r->vfs_directories, r360_vfs_reads()); + if (!r->ok) { + if (j.size() > 1) j += ','; + j += "\"error\":{\"message\":"; + JsonString(j, r->error); + j += '}'; + } else { + field("error", "null"); + field("entry", "\"0x%08X\"", r->entry); + text("runtimeBoundary", r->runtime_boundary); + field("executionStatus", "%u", r->execution_status); + field("instructions", "%u", r->execution_instructions); + field("kernelCalls", "%u", r->kernel_calls); + if (r->kernel_boundary[0]) text("kernelBoundary", r->kernel_boundary); + if (r->blocker_kind) + field("hirBlocker", "{\"kind\":%u,\"opcode\":%u,\"address\":\"0x%08X\"}", r->blocker_kind, r->blocker_opcode, + r->blocker_address); + if (r->memory_fault_code) + field("memoryFault", "{\"code\":%u,\"address\":\"0x%08X\"}", r->memory_fault_code, r->memory_fault_address); + if (r->kernel_last_status == 2) { + char name[96]; + if (j.size() > 1) j += ','; + j += "\"unsupportedKernelCall\":"; + JsonString(j, r360_native_kernel_export_name(r->kernel_last_module, r->kernel_last_ordinal, name, sizeof(name))); + } + field("guestFibers", "{\"threads\":%u,\"switches\":%u,\"preemptions\":%u,\"endedOn\":%u}", + r360_fiber_count() ? r360_fiber_count() - 1 : 0, r360_fiber_switches(), r360_fiber_preemptions(), + r360_fiber_current()); + // The 30 FPS bar inputs (same definitions as run-title.mjs perf). + const double wall = r->elapsed_ms / 1000.0; + const double instr = r360_perf_counter(0), interp = r360_perf_counter(1); + const uint32_t frames = r360_title_gpu_vd_swap_calls(); + field("perf", + "{\"wallSeconds\":%.1f,\"guestFrames\":%u,\"gameFpsWall\":%.2f,\"mips\":%.1f,\"interpretedPercent\":%.3f," + "\"guestIdleMs\":%.0f}", + wall, frames, frames / std::max(wall, 0.001), instr / std::max(wall, 0.001) / 1e6, + instr ? 100.0 * interp / instr : 0.0, r360_fiber_idle_ms()); + field("framesPresented", + "{\"vdSwapCalls\":%u,\"vblankInterrupts\":%u,\"cpInterrupts\":%u,\"gpuPackets\":%u,\"gpuDraws\":%u," + "\"softDraws\":%u,\"cacheHits\":%u,\"cacheMisses\":%u,\"cacheEntries\":%u,\"cacheKB\":%u," + "\"vdSwapFailures\":%u,\"width\":%u,\"height\":%u}", + frames, r360_kernel_vblank_interrupts(), r360_kernel_cp_interrupts(), r360_xenos_packets(), + r360_xenos_draws(), r360_xenos_soft_draws(), r360_hir_cache_hits(), r360_hir_cache_misses(), + r360_hir_cache_entries(), r360_hir_cache_kilobytes(), r360_title_gpu_vd_swap_failures(), + r360_title_gpu_last_vd_swap_width(), r360_title_gpu_last_vd_swap_height()); + // Last kernel calls (readKernelServiceTrace). + j += ",\"kernelTrace\":["; + const uint32_t n = r360_kernel_import_trace_count(); + for (uint32_t i = n > 48 ? n - 48 : 0, first = 1; i < n; ++i, first = 0) { + char name[96]; + if (!first) j += ','; + std::snprintf(buf, sizeof(buf), + "{\"sequence\":%u,\"name\":\"%s\",\"args\":[%u,%u,%u,%u],\"result\":%u,\"status\":%u}", + r360_kernel_import_trace_sequence(i), + r360_native_kernel_export_name(r360_kernel_import_trace_module(i), + r360_kernel_import_trace_ordinal(i), name, sizeof(name)), + r360_kernel_import_trace_arg(i, 0), r360_kernel_import_trace_arg(i, 1), + r360_kernel_import_trace_arg(i, 2), r360_kernel_import_trace_arg(i, 3), + r360_kernel_import_trace_result(i), r360_kernel_import_trace_status(i)); + j += buf; + } + j += ']'; + field("totalInstructionsMillions", "%u", r360_hir_total_instructions_millions()); + field("hostStackHeadroom", "%u", r360_trap_stack_headroom()); + } + j += '}'; + if (capacity) { + const size_t n = std::min(j.size(), capacity - 1); + std::memcpy(out, j.data(), n); + out[n] = 0; + } + return j.size(); +} + +extern "C" uint32_t r360_native_inspect(const char* path, R360GameInfo* info) { + *info = R360GameInfo{}; + try { + const HostFile* file = OpenHostFile(path); + info->size = file->size; + std::string base = path; + base = base.substr(base.find_last_of('/') + 1); + std::snprintf(info->name, sizeof(info->name), "%s", base.c_str()); + uint8_t magic[4] = {}; + if (file->size >= 4) file->Read(0, magic, 4); + auto inspect_xex = [&](const Bytes& xex) { + const size_t n = std::min(xex.size(), r360pkg_io_capacity()); + coreStage(xex.data(), n); + if (r360pkg_inspect_xex(uint32_t(n)) >= 1) { + info->title_id = r360pkg_xex_title_id(); + info->media_id = r360pkg_xex_media_id(); + } + }; + if (!std::memcmp(magic, "XEX2", 4)) { + std::snprintf(info->display_type, sizeof(info->display_type), "XEX2"); + std::snprintf(info->source_type, sizeof(info->source_type), "xex"); + inspect_xex(file->ReadBytes(0, size_t(std::min(file->size, r360pkg_io_capacity())))); + } else if (!std::memcmp(magic, "LIVE", 4) || !std::memcmp(magic, "PIRS", 4) || !std::memcmp(magic, "CON ", 4)) { + const char* kind = magic[0] == 'L' ? "live" : magic[0] == 'P' ? "pirs" : "con"; + std::snprintf(info->source_type, sizeof(info->source_type), "%s", kind); + std::snprintf(info->display_type, sizeof(info->display_type), "STFS %s", magic[0] == 'L' ? "LIVE" : magic[0] == 'P' ? "PIRS" : "CON"); + const std::string name = mountStfs(file); + if (!name.empty()) std::snprintf(info->name, sizeof(info->name), "%s", name.c_str()); + info->title_id = r360pkg_stfs_title_id(); + info->media_id = r360pkg_stfs_media_id(); + } else { + std::snprintf(info->source_type, sizeof(info->source_type), "iso"); + std::snprintf(info->display_type, sizeof(info->display_type), "Xbox 360 Disc / XDVDFS"); + const XdvdfsVolume volume = mountXdvdfs(file); + std::vector files; + listXdvdfsVfsFiles(volume, volume.root_sector, volume.root_size, "", files); + for (const auto& f : files) { + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "default.xex" && !f.directory) { + inspect_xex(file->ReadBytes(f.host_offset, size_t(std::min(f.size, r360pkg_io_capacity())))); + } + } + } + return 1; + } catch (const std::exception& e) { + std::snprintf(info->error, sizeof(info->error), "%s", e.what()); + return 0; + } +} diff --git a/native/tools/gen_core_api.py b/native/tools/gen_core_api.py new file mode 100644 index 00000000..d2a1040a --- /dev/null +++ b/native/tools/gen_core_api.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Generates native/include/render360_core_exports.h: C declarations of every +extern "C" r360_* function the Render360 bootstrap core defines (the same +surface the browser build exports to JavaScript). Run after changing exports: + python3 native/tools/gen_core_api.py +""" +import pathlib, re, sys +ROOT = pathlib.Path(__file__).resolve().parents[2] +SRC = ROOT / "src" / "xenia_web_bootstrap" +TYPES = r"(?:const\s+)?(?:void|bool|double|float|int|int32_t|uint8_t|uint16_t|uint32_t|uint64_t|int64_t|size_t|uintptr_t|char)\s*\**" +DEF = re.compile(r"^(?:extern\s+\"C\"\s+)?(?:__attribute__\(\([^;{]*?\)\)\s*)?(?:R360_WASM_EXPORT\([^)]*\)\s*)?(?:static\s+)?(?P" + TYPES + r")\s*(?Pr360_[A-Za-z0-9_]+)\s*\((?P[^)]*)\)\s*(?:noexcept\s*)?\{", re.M) +SKIP_FILES = {"hir_wasm_jit.cpp"} +found = {} +# Overlay-generated units (prepare-*.py) replace some sources at build time. +OVERLAY = ROOT / "build" / "xenia-web-overlay" / "render360" +paths = sorted(SRC.glob("*.cpp")) + sorted(SRC.glob("*.inc")) +if OVERLAY.is_dir(): + paths = sorted(OVERLAY.glob("*.cpp")) + paths +for path in paths: + if path.name in SKIP_FILES: + continue + text = path.read_text(errors="replace") + # Join attribute lines with the definition that follows them. + text = re.sub(r"(extern\s+\"C\"\s*)\n", r"\1 ", text) + text = re.sub(r"(__attribute__\(\([^\n]*\)\)|R360_WASM_EXPORT\([^)]*\))\s*\n", r"\1 ", text) + for m in DEF.finditer(text): + name = m.group("name") + args = " ".join(m.group("args").split()) + ret = " ".join(m.group("ret").split()) + found.setdefault(name, (ret, args, path.name)) +out = ["// Generated by native/tools/gen_core_api.py - do not edit.", + "// Every r360_* entry point of the Render360 core (browser: wasm exports).", + "#pragma once", "#include ", "#include ", "#include ", + "#ifdef __cplusplus", 'extern "C" {', "#endif"] +for name in sorted(found): + ret, args, src = found[name] + out.append(f"{ret} {name}({args or 'void'}); // {src}") +out += ["#ifdef __cplusplus", "}", "#endif", ""] +dest = ROOT / "native" / "include" / "render360_core_exports.h" +dest.write_text("\n".join(out)) +print(f"{len(found)} r360_* functions -> {dest.relative_to(ROOT)}", file=sys.stderr) diff --git a/native/tools/run_title.cpp b/native/tools/run_title.cpp new file mode 100644 index 00000000..8e000021 --- /dev/null +++ b/native/tools/run_title.cpp @@ -0,0 +1,272 @@ +// Native headless title runner (macOS): the native counterpart of +// tools/run-title.mjs, built by native/build-native.sh as build/native-/run-title. +// +// run-title [--json out.json] +// [--max-minstr N] [--deterministic PS] [--budget N] [--license trial|full] +// [--dialog-button N] [--progress] [--slice-ms N] [--disc FILE]... +// +// Interpreter only (no guest JIT natively). Game files are read in place. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render360_core.h" +#if defined(R360_WITH_WGPU) +#include +#include "../gpu/xenos_wgpu.h" +#endif + +namespace { +struct Progress { + std::chrono::steady_clock::time_point started, last; + bool enabled = false; +#if defined(R360_WITH_WGPU) + r360gpu::Backend* gpu = nullptr; + uint32_t replayed_swaps = 0; +#endif +}; + +#if defined(R360_WITH_WGPU) +// Minimal PNG writer (RGBA8) for --gpu. +bool WritePng(const char* file, const std::vector& rgba, uint32_t w, uint32_t h) { + std::vector raw; + raw.reserve(size_t(w * 4 + 1) * h); + for (uint32_t y = 0; y < h; ++y) { + raw.push_back(0); + raw.insert(raw.end(), rgba.begin() + size_t(y) * w * 4, rgba.begin() + size_t(y + 1) * w * 4); + } + uLongf zlen = compressBound(uLong(raw.size())); + std::vector z(zlen); + if (compress2(z.data(), &zlen, raw.data(), uLong(raw.size()), 6) != Z_OK) return false; + z.resize(zlen); + FILE* f = std::fopen(file, "wb"); + if (!f) return false; + auto be = [](uint32_t v, uint8_t* o) { o[0] = v >> 24; o[1] = v >> 16; o[2] = v >> 8; o[3] = v; }; + auto chunk = [&](const char* type, const std::vector& data) { + uint8_t len[4], crcb[4]; + be(uint32_t(data.size()), len); + std::fwrite(len, 1, 4, f); + std::fwrite(type, 1, 4, f); + std::fwrite(data.data(), 1, data.size(), f); + uLong crc = crc32(0, reinterpret_cast(type), 4); + crc = crc32(crc, data.data(), uInt(data.size())); + be(uint32_t(crc), crcb); + std::fwrite(crcb, 1, 4, f); + }; + static const uint8_t sig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + std::fwrite(sig, 1, 8, f); + std::vector ihdr(13, 0); + be(w, ihdr.data()); + be(h, ihdr.data() + 4); + ihdr[8] = 8; + ihdr[9] = 6; + chunk("IHDR", ihdr); + chunk("IDAT", z); + chunk("IEND", {}); + std::fclose(f); + return true; +} +#endif + +uint32_t OnSlice(void* user) { + auto* p = static_cast(user); + const auto now = std::chrono::steady_clock::now(); +#if defined(R360_WITH_WGPU) + // As render360-webgpu-play.mjs: replay on every new guest frame, and at + // least when the stream grows large. + if (p->gpu && (r360_title_gpu_vd_swap_calls() != p->replayed_swaps || r360_gpu_stream_words() > 4u * 1024 * 1024)) { + p->replayed_swaps = r360_title_gpu_vd_swap_calls(); + p->gpu->ReplayCore(); + } +#endif + if (p->enabled && now - p->last >= std::chrono::seconds(5)) { + p->last = now; + const double wall = std::chrono::duration(now - p->started).count(); + std::printf("progress %uM instr · %u kernel calls · %u frames · %u fibers · %u switches · %.1f MIPS · %.0fs\n", + r360_hir_total_instructions_millions(), r360_kernel_import_calls(), r360_title_gpu_vd_swap_calls(), + r360_fiber_count(), r360_fiber_switches(), r360_perf_counter(0) / wall / 1e6, wall); + std::fflush(stdout); + } + return 0; +} +} // namespace + +int main(int argc, char** argv) { + R360BootOptions options{}; + options.dialog_button = -1; + const char* json = nullptr; + const char* gpu_png = nullptr; + const char* frame_png = nullptr; + std::vector discs; + Progress progress; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--json") json = next(); + else if (a == "--max-minstr") options.max_minstr = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--deterministic") options.deterministic_ps = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--budget") options.function_budget = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--license") options.license_full = std::strcmp(next(), "full") == 0; + else if (a == "--dialog-button") options.dialog_button = int32_t(std::strtol(next(), nullptr, 0)); + else if (a == "--slice-ms") options.slice_ms = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--progress") progress.enabled = true; + else if (a == "--disc") discs.push_back(next()); + else if (a == "--gpu") gpu_png = next(); + else if (a == "--frame") frame_png = next(); + else if (a == "--help" || a == "-h") { + std::printf("usage: run-title [--json out.json] [--max-minstr N] " + "[--deterministic PS] [--budget N] [--license trial|full] [--dialog-button N] [--progress] " + "[--slice-ms N] [--disc FILE]...\n"); + return 0; + } else if (!options.path) options.path = argv[i]; + else { + std::fprintf(stderr, "unexpected argument %s\n", argv[i]); + return 2; + } + } + if (!options.path) { + std::fprintf(stderr, "usage: run-title [--json out.json] ... (--help)\n"); + return 2; + } + // Same rule as run-title.mjs: progress (and frame/press work) runs in 200 ms slices. + if (progress.enabled && !options.slice_ms) options.slice_ms = 200; +#if defined(R360_WITH_WGPU) + std::unique_ptr gpu; + if (gpu_png) { + std::string error; + gpu = r360gpu::Backend::Create(nullptr, &error); + if (!gpu) { + std::fprintf(stderr, "GPU backend: %s\n", error.c_str()); + return 1; + } + std::printf("GPU: wgpu-native on %s (Xenos command stream replay)\n", gpu->adapter_name().c_str()); + r360gpu::EnableCoreRecording(true); + progress.gpu = gpu.get(); + if (!options.slice_ms) options.slice_ms = 200; + } +#else + if (gpu_png) { + std::fprintf(stderr, "--gpu needs a build with wgpu-native (R360_WGPU_DIR)\n"); + return 2; + } +#endif + progress.started = progress.last = std::chrono::steady_clock::now(); + if (options.slice_ms) { + options.on_slice = OnSlice; + options.user = &progress; + } + options.discs = discs.data(); + options.disc_count = uint32_t(discs.size()); + std::printf("Render360 native title runner · JIT-capable process: %s (interpreter only)\n", + r360_native_jit_available() ? "yes" : "no"); + + R360BootResult result{}; + r360_native_boot(&options, &result); + + if (!result.ok) { + std::printf("FAILED BEFORE EXECUTION: %s\n", result.error); + } else { + std::printf("entry 0x%08X · %u PPC instructions (native HIR) · %u kernel calls\n", result.entry, + result.execution_instructions, result.kernel_calls); + std::printf("stopped at: %s\n", result.runtime_boundary); + if (result.kernel_boundary[0]) std::printf(" %s\n", result.kernel_boundary); + const double wall = result.elapsed_ms / 1000.0; + const double instr = r360_perf_counter(0), interp = r360_perf_counter(1); + std::printf(" frames (VdSwap): %u at %ux%u · %.2f fps wall · %.1f MIPS · interpreted %.1f%% · %.1fs\n", + r360_title_gpu_vd_swap_calls(), r360_title_gpu_last_vd_swap_width(), + r360_title_gpu_last_vd_swap_height(), r360_title_gpu_vd_swap_calls() / wall, + instr / wall / 1e6, instr ? 100.0 * interp / instr : 0.0, wall); + std::printf(" guest threads: %u title-created, %u switches\n", r360_fiber_count() ? r360_fiber_count() - 1 : 0, + r360_fiber_switches()); + } +#if defined(R360_WITH_WGPU) + if (gpu) { + gpu->ReplayCore(); + const auto& st = gpu->stats(); + std::printf(" GPU: %llu swaps, %llu draws (%llu skipped), %llu pipelines (%llu failed), %llu shaders (%llu failed), " + "%llu textures, %llu texture loads (%llu failed), %llu resolves (%llu failed), %llu clears, %llu errors\n", + (unsigned long long)st.swaps, (unsigned long long)st.draws, (unsigned long long)st.skipped_draws, + (unsigned long long)st.pipelines, (unsigned long long)st.pipeline_failures, + (unsigned long long)st.shaders, (unsigned long long)st.shader_failures, + (unsigned long long)st.textures, (unsigned long long)st.texture_loads, + (unsigned long long)st.texture_load_failures, (unsigned long long)st.resolves, + (unsigned long long)st.resolve_failures, (unsigned long long)st.clears, (unsigned long long)st.errors); + // Diagnostic: the guest frontbuffer bytes in CPU memory vs the GPU copy. + if (getenv("R360_GPU_COMPARE")) { + r360_xenos_frontbuffer_snapshot_capture(); + const uint32_t src = r360_xenos_frontbuffer_snapshot_source_address(), bytes = r360_xenos_frontbuffer_snapshot_source_bytes(); + std::vector shared; + uint32_t diff = 0, cpu_nonwhite = 0, gpu_nonwhite = 0; + if (src && bytes && gpu->ReadShared(src & 0x1FFFFFFFu, bytes, &shared)) { + for (uint32_t i = 0; i + 4 <= bytes; i += 4) { + uint32_t cpu = 0; + r360_sparse_guest_memory_read_u32_be(src + i, &cpu); + uint32_t g = (uint32_t(shared[i]) << 24) | (uint32_t(shared[i + 1]) << 16) | (uint32_t(shared[i + 2]) << 8) | shared[i + 3]; + diff += cpu != g; + cpu_nonwhite += (cpu & 0xFFFFFF00u) != 0xFFFFFF00u && (cpu & 0x00FFFFFFu) != 0x00FFFFFFu; + gpu_nonwhite += (g & 0xFFFFFF00u) != 0xFFFFFF00u && (g & 0x00FFFFFFu) != 0x00FFFFFFu; + } + } + std::printf(" compare frontbuffer 0x%08X +%u: %u words differ, non-white cpu %u gpu %u\n", src, bytes, diff, cpu_nonwhite, gpu_nonwhite); + // Decode the GPU-resolved bytes with the software frontbuffer decoder. + if (shared.size() >= bytes) { + for (uint32_t i = 0; i < bytes; ++i) r360_sparse_guest_memory_write_u8(src + i, shared[i]); + if (r360_xenos_frontbuffer_snapshot_capture() == 1) { + const uint32_t w = r360_xenos_frontbuffer_snapshot_width(), h = r360_xenos_frontbuffer_snapshot_height(); + const auto* px = reinterpret_cast(r360_xenos_frontbuffer_snapshot_buffer()); + std::vector rgba(px, px + size_t(w) * h * 4); + WritePng("/tmp/gpu-mem-decoded.png", rgba, w, h); + std::printf(" GPU memory decoded by the software path -> /tmp/gpu-mem-decoded.png\n"); + } + } + } + std::printf(" core GPU recorder: draws %u skips noVS %u translation %u primitive %u indices %u vfetch %u · " + "textures %u created %u loads %u load failures %u · resolves %u (%u failed)\n", + r360_gpu_draw_stat(0), r360_gpu_draw_stat(1), r360_gpu_draw_stat(2), r360_gpu_draw_stat(3), + r360_gpu_draw_stat(4), r360_gpu_draw_stat(5), r360_gpu_texture_stat(0), r360_gpu_texture_stat(1), + r360_gpu_texture_stat(2), r360_gpu_texture_stat(3), r360_gpu_draw_stat(7), r360_gpu_draw_stat(8)); + std::vector rgba; + uint32_t w = 0, h = 0; + if (gpu->ReadFront(&rgba, &w, &h) && WritePng(gpu_png, rgba, w, h)) std::printf(" GPU front buffer %ux%u -> %s\n", w, h, gpu_png); + else std::printf(" GPU front buffer: none yet\n"); + } +#endif +#if defined(R360_WITH_WGPU) + // --frame: the software path's last VdSwap frontbuffer (render360-title-frontbuffer.mjs). + if (frame_png && !gpu_png) { + if (r360_xenos_frontbuffer_snapshot_capture() == 1) { + const uint32_t w = r360_xenos_frontbuffer_snapshot_width(), h = r360_xenos_frontbuffer_snapshot_height(); + const auto* px = reinterpret_cast(r360_xenos_frontbuffer_snapshot_buffer()); + std::vector rgba(px, px + size_t(w) * h * 4); + if (WritePng(frame_png, rgba, w, h)) std::printf(" frame %ux%u -> %s\n", w, h, frame_png); + } else { + std::printf(" frame: no frontbuffer (status 0x%x)\n", r360_xenos_frontbuffer_snapshot_status()); + } + } +#endif + if (json) { + std::vector report(1 << 20); + const size_t n = r360_native_report_json(&result, report.data(), report.size()); + FILE* f = std::fopen(json, "w"); + if (f) { + std::fwrite(report.data(), 1, std::min(n, report.size() - 1), f); + std::fclose(f); + std::printf("report written to %s\n", json); + } + } + std::fflush(stdout); + // Guest threads of the run may still be parked; exit without unwinding them. + std::_Exit(result.ok ? 0 : 1); +} diff --git a/prepare-hir-hot-path-overlay.py b/prepare-hir-hot-path-overlay.py new file mode 100644 index 00000000..31e79c76 --- /dev/null +++ b/prepare-hir-hot-path-overlay.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Hot-path fixes for the HIR executor overlay (applied after the JIT overlay). + +ExecuteHIRCorrectnessProbe runs for every guest call, compiled or not. It +declared `PPCContext local_context{}` unconditionally, zero-filling a whole +PPC register file (GPRs, FPRs, 128 vector registers) per call although only +the outermost call of a thread uses it. The storage stays on the stack (each +fiber's outermost call needs its own), but it is only initialised there. +""" +from pathlib import Path + +path = Path(__file__).resolve().parent / 'build/xenia-web-overlay/render360/hir_correctness_executor_vmx.cpp' +s = path.read_text() +marker = 'R360_HOT_PATH_OVERLAY' +if marker not in s: + old = ' xe::cpu::ppc::PPCContext local_context{};\n if (outermost) {\n' + new = (' // ' + marker + ': initialised only by the outermost call (see\n' + ' // prepare-hir-hot-path-overlay.py).\n' + ' alignas(xe::cpu::ppc::PPCContext) unsigned char\n' + ' local_context_storage[sizeof(xe::cpu::ppc::PPCContext)];\n' + ' xe::cpu::ppc::PPCContext& local_context =\n' + ' *reinterpret_cast(local_context_storage);\n' + ' if (outermost) {\n' + ' new (&local_context) xe::cpu::ppc::PPCContext{};\n') + if s.count(old) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: PPCContext anchor not found exactly once') + s = s.replace(old, new, 1) + if '#include ' not in s: + s = '#include \n' + s + path.write_text(s) + +# The interpreter (ExecuteBuilder) runs well under 1% of guest instructions +# once the JIT is warm, but it was inlined into ExecuteHIRCorrectnessProbe, +# the per-call entry, which made every call pay for its frame. +s = path.read_text() +noinline_marker = 'R360_HOT_PATH_NOINLINE' +if noinline_marker not in s: + old = 'HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n' + if s.count(old) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: ExecuteBuilder anchor not found exactly once') + s = s.replace(old, '// ' + noinline_marker + ': kept out of the per-call entry.\n' + '__attribute__((noinline)) ' + old, 1) + path.write_text(s) + +# On-stack replacement (hir_wasm_jit.h JitOsrFunction): a run that has +# interpreted many instructions, or an interior entry, continues in compiled +# code at the next block head. Without it a function entered once that loops +# (a thread's main loop, a wait loop) was interpreted for its whole life. +s = path.read_text() +osr_marker = 'R360_HOT_PATH_OSR' +if osr_marker not in s: + builder_at = s.index('HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n') + decl_at = s.rindex('\n', 0, s.rindex('// R360_HOT_PATH_NOINLINE', 0, builder_at)) + 1 + s = (s[:decl_at] + + '// ' + osr_marker + ' (prepare-hir-hot-path-overlay.py; defined in hir_jit_glue.inc).\n' + '} // namespace\n' + 'bool JitTryOsr(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot,\n' + ' const xe::cpu::hir::Block* block, bool hot, xe::Memory* memory,\n' + ' xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result);\n' + 'namespace {\n' + '// Interpreted instructions in one run before it moves to compiled code.\n' + 'constexpr uint32_t kOsrInstructions = 1000;\n\n' + s[decl_at:]) + builder_at = s.index('HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n') + values = ' RuntimeValues values;\n' + at = s.index(values, builder_at) + len(values) + s = s[:at] + ' JitSlot* const osr_slot = JitTakeOsrSlot(builder);\n bool osr_tried = false;\n' + s[at:] + loop = ' while (block && supported && !reached_return) {\n auto* next_block = block->next;\n' + at = s.index(loop, builder_at) + if s.count(loop) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: interpreter loop anchor not found exactly once') + hook = (' while (block && supported && !reached_return) {\n' + ' if (osr_slot) {\n' + ' // An interior entry starts at a block head: run it compiled once\n' + ' // the owner is hot; a long run moves over at its next block.\n' + ' const bool interior = first_execution_block && entry_instr;\n' + ' const bool hot = !osr_tried && result.instructions_executed >= kOsrInstructions;\n' + ' if (interior || hot) {\n' + ' if (hot) osr_tried = true;\n' + ' HIRCorrectnessResult compiled;\n' + ' if (JitTryOsr(builder, osr_slot, block, hot, memory, context, &compiled)) {\n' + ' compiled.instructions_executed = result.instructions_executed;\n' + ' return compiled;\n' + ' }\n' + ' }\n' + ' }\n' + ' auto* next_block = block->next;\n') + s = s[:at] + hook + s[at + len(loop):] + path.write_text(s) +print('R360_HOT_PATH_OVERLAY applied') diff --git a/prepare-hir-stack-history-overlay.py b/prepare-hir-stack-history-overlay.py index 381b7c0f..477e90e4 100644 --- a/prepare-hir-stack-history-overlay.py +++ b/prepare-hir-stack-history-overlay.py @@ -40,19 +40,26 @@ def replace_once(old: str, new: str, label: str) -> None: g_r360_stack_call_history{}; thread_local uint32_t g_r360_stack_write_history_count = 0; thread_local uint32_t g_r360_stack_call_history_count = 0; +// Ring buffers (every guest call records one event): index of the oldest. +thread_local uint32_t g_r360_stack_write_history_head = 0; +thread_local uint32_t g_r360_stack_call_history_head = 0; thread_local uint32_t g_r360_stack_event_sequence = 0; template void PushBoundedHistory(std::array& history, uint32_t* count, - const T& event) { - if (!count) return; + uint32_t* head, const T& event) { + if (!count || !head) return; if (*count < N) { - history[*count] = event; + history[(*head + *count) % N] = event; ++(*count); return; } - for (size_t i = 1; i < N; ++i) history[i - 1] = history[i]; - history[N - 1] = event; + history[*head] = event; + *head = uint32_t((*head + 1) % N); +} +// Oldest-first index into a ring history. +inline size_t HistorySlot(uint32_t head, uint32_t index) { + return size_t((head + index) % kR360StackHistoryCapacity); } void RecordStackWriteHistory(uint32_t source, uint64_t old_r1, @@ -64,7 +71,8 @@ def replace_once(old: str, new: str, label: str) -> None: event.old_r1 = old_r1; event.new_r1 = new_r1; PushBoundedHistory(g_r360_stack_write_history, - &g_r360_stack_write_history_count, event); + &g_r360_stack_write_history_count, + &g_r360_stack_write_history_head, event); } void RecordStackCallHistory(uint32_t target, uint32_t flags) { @@ -77,7 +85,8 @@ def replace_once(old: str, new: str, label: str) -> None: event.flags = flags; event.r1 = g_active_context->r[1]; PushBoundedHistory(g_r360_stack_call_history, - &g_r360_stack_call_history_count, event); + &g_r360_stack_call_history_count, + &g_r360_stack_call_history_head, event); } ''' replace_once(state_anchor, state_replacement, 'history state') @@ -141,6 +150,8 @@ def replace_once(old: str, new: str, label: str) -> None: g_r360_stack_call_history = {}; g_r360_stack_write_history_count = 0; g_r360_stack_call_history_count = 0; + g_r360_stack_write_history_head = 0; + g_r360_stack_call_history_head = 0; g_r360_stack_event_sequence = 0; ''' replace_once(reset_anchor, reset_replacement, 'outer history reset') @@ -157,40 +168,40 @@ def replace_once(old: str, new: str, label: str) -> None: return g_r360_stack_write_history_count; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_sequence(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].sequence : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].sequence : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_address(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].source : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].source : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_old_r1(uint32_t index) { - return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[index].old_r1) : 0; + return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].old_r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_new_r1(uint32_t index) { - return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[index].new_r1) : 0; + return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].new_r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_depth(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].depth : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].depth : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_count() { return g_r360_stack_call_history_count; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_sequence(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].sequence : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].sequence : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_source(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].source : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].source : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_target(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].target : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].target : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_r1(uint32_t index) { - return index < g_r360_stack_call_history_count ? static_cast(g_r360_stack_call_history[index].r1) : 0; + return index < g_r360_stack_call_history_count ? static_cast(g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_depth(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].depth : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].depth : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_flags(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].flags : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].flags : 0; } } // extern "C" ''' diff --git a/prepare-xenia-arena-overlay.py b/prepare-xenia-arena-overlay.py index ff272639..f3d80efd 100644 --- a/prepare-xenia-arena-overlay.py +++ b/prepare-xenia-arena-overlay.py @@ -51,11 +51,13 @@ assert_not_null(buffer); assert_true((reinterpret_cast(buffer) & size_t(15)) == 0, "16 byte alignment required"); + g_r360_arena_live_bytes += capacity; } Arena::Chunk::~Chunk() { if (buffer) { free(buffer); + g_r360_arena_live_bytes -= capacity; } } ''' @@ -98,6 +100,13 @@ raise SystemExit(f"Upstream Arena {name} drifted") text = text.replace(a, b, 1) +# Live bytes held by all arena chunks. Retained HIR builders are most of it, +# so the translation cache budgets against this (probe_backend.cpp). +ns_anchor = "namespace xe {\n" +if text.count(ns_anchor) != 1: + raise SystemExit("Upstream Arena namespace drifted") +text = text.replace(ns_anchor, ns_anchor + "\nsize_t g_r360_arena_live_bytes = 0;\n", 1) + DEST.parent.mkdir(parents=True, exist_ok=True) DEST.write_text(text) print(f"Generated web Arena overlay: {DEST}") diff --git a/prepare-xenia-web-overlay.py b/prepare-xenia-web-overlay.py index 77499315..b0aa6cf1 100644 --- a/prepare-xenia-web-overlay.py +++ b/prepare-xenia-web-overlay.py @@ -44,7 +44,7 @@ if needle not in text: raise SystemExit("Upstream PPCContext layout drifted: reserved_val anchor not found") replacement = needle + ( - "\n#if defined(__EMSCRIPTEN__) || defined(XE_ARCH_WASM32)\n" + "\n#if (defined(__EMSCRIPTEN__) || defined(XE_ARCH_WASM32)) && !defined(R360_NATIVE)\n" " // Render360 web ABI: compensate for 32-bit host pointers without\n" " // moving any existing PPCContext field. Keep this as tail padding.\n" " uint8_t render360_wasm32_tail_padding[16];\n" @@ -274,6 +274,18 @@ def write_narrow_utf8_overlay(source: Path, dest: Path, label: str) -> int: wasm_init += desktop_body_without_close + "#endif\n}\n\n" memory_cc = memory_cc[:init_start] + wasm_init + memory_cc[map_info_start:] MEMORY_DEST.parent.mkdir(parents=True, exist_ok=True) +# The portable host never installs an MMIOHandler (no host page faults), but +# the HIR constant-propagation pass still asks for MMIO ranges. Upstream +# dereferences the null handler; wasm32 happened to read zeros at address 0x20, +# a 64-bit native host faults. Report "no range" instead. +lookup_anchor = " return mmio_handler_->LookupRange(virtual_address);\n" +if lookup_anchor not in memory_cc: + raise SystemExit("Upstream Memory::LookupVirtualMappedRange drifted") +memory_cc = memory_cc.replace( + lookup_anchor, + " if (!mmio_handler_) return nullptr; // Render360 portable host\n" + lookup_anchor, + 1, +) MEMORY_DEST.write_text(memory_cc) # processor.cc: the debugger exception-resume path knows how to restore a diff --git a/render360-browser-modern-content-bridge.mjs b/render360-browser-modern-content-bridge.mjs index 347daa43..4852a3e0 100644 --- a/render360-browser-modern-content-bridge.mjs +++ b/render360-browser-modern-content-bridge.mjs @@ -9,6 +9,7 @@ import {inspectCapturedXenosShaders} from './render360-xenos-shader-runtime.mjs' import {validateCapturedXenosShadersWebGPU} from './render360-webgpu-title-shaders.mjs'; import {captureTitleFrontbuffer,ensureTitleWebGPUCanvas,hideTitleFrontbuffer,presentTitleFrontbuffer,showTitleWebGPUCanvas} from './render360-title-frontbuffer.mjs'; import {createRgbaFramePresenter} from './render360-webgpu-runtime.mjs'; +import {createXenosWebGpuPlayPath,webGpuPlayPathRequested} from './render360-webgpu-play.mjs'; import {browserPerformanceDefaults,createAdaptivePerformancePolicy} from './render360-performance-policy.mjs'; import {prepareStfsGuestVfs,prepareXexGuestVfs,runWithGuestVfsRetries} from './render360-guest-vfs.mjs'; @@ -22,7 +23,27 @@ let activePresenter=null; function stage(onStage,stage,message,extra={}){onStage?.({stage,message,...extra});} function guestRunOptions(bootstrap,onStage){ - return browserGuestRunOptions({bootstrap,onProgress:(message,extra)=>stage(onStage,'execute',message,extra),onFrame:()=>{const frame=captureTitleFrontbuffer({bootstrap});if(frame?.captured)presentTitleFrontbuffer(frame);}}); + // WebGPU play path (render360-webgpu-play.mjs) when requested; frames + // come from the software renderer until it is ready or if it fails. + const play={path:null,pending:false,failed:false}; + if(webGpuPlayPathRequested(null)&&globalThis.navigator?.gpu){ + play.pending=true; + createXenosWebGpuPlayPath(bootstrap,ensureTitleWebGPUCanvas()).then(path=>{ + play.path=path;activePresenter=path; + stage(onStage,'renderer','WebGPU Xenos renderer active (port of Xenia’s Vulkan backend)'); + },error=>{ + play.failed=true; + console.warn('[Render360] WebGPU Xenos renderer unavailable:',error); + stage(onStage,'renderer',`WebGPU Xenos renderer unavailable: ${error?.message||error}`); + }).finally(()=>{play.pending=false;}); + } + return browserGuestRunOptions({bootstrap,onProgress:(message,extra)=>stage(onStage,'execute',message,extra), + onSlice:()=>play.path?.slice(), + gpuFrameMs:()=>play.path?.takeGpuMs?.()??null, + onFrame:()=>{ + if(play.path&&!play.path.lost){play.path.frame();return;} + const frame=captureTitleFrontbuffer({bootstrap});if(frame?.captured)presentTitleFrontbuffer(frame); + }}); } async function getBootstrap(onStage=null){ const wasCached=Boolean(globalThis.render360PpcRuntimeIdentity?.verified); diff --git a/render360-guest-fibers.mjs b/render360-guest-fibers.mjs index 0508b899..9a274d29 100644 --- a/render360-guest-fibers.mjs +++ b/render360-guest-fibers.mjs @@ -4,6 +4,8 @@ // blocks in the kernel, the core snapshots it and unwinds the wasm stack back // here (Binaryen Asyncify); this loop then starts or rewinds the next guest // thread on its own C stack until the title's primary thread returns. + +import {PerfStats,createPerfOverlay} from './render360-perf-overlay.mjs'; const pick=(bootstrap,name)=>bootstrap?.exports?.[name]??bootstrap?.exports?.[`_${name}`]; export function hasGuestFibers(bootstrap){ @@ -76,7 +78,7 @@ export async function runWithGuestFibers(bootstrap,callPrimary,{maxSwitches=1e9, // Browser options for a continuous title run: ~25 ms host slices, Stop through // globalThis.render360GuestRun.stop() (aborts at the next slice), and a // progress line about twice a second. -export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,sliceMs=25}={}){ +export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,onSlice=null,gpuFrameMs=null,sliceMs=25}={}){ let lastFrames=-1; globalThis.render360GuestRun?.stop?.(); const controller=new AbortController(); @@ -85,19 +87,74 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,s let lastReport=0; globalThis.render360GuestRun={stop:()=>controller.abort(),signal:controller.signal}; const read=name=>{const f=bootstrap?.exports?.[name];return typeof f==='function'?(f()>>>0):0;}; + // System message boxes (XamShowMessageBoxUI) are answered by the player. + if(globalThis.document)bootstrap?.exports?.r360_xam_dialog_set_host_answers?.(1); + // FPS / frame-time overlay: time inside the emulator per slice, the GPU + // renderer's share of it, page-side present time, submitted vs presented. + const perf=new PerfStats(); + const overlay=globalThis.document?createPerfOverlay():null; + let sliceExit=now(),lastRenderUs=read('r360_xenos_soft_render_us'),lastOverlay=0; return {guestSliceMs:sliceMs,signal:controller.signal,onGuestSlice:s=>{ - pushGuestControllerState(bootstrap); const t=now(); + const renderUs=read('r360_xenos_soft_render_us'); + const gpuMs=((renderUs-lastRenderUs)>>>0)/1000;lastRenderUs=renderUs; + pushGuestControllerState(bootstrap); + showGuestDialog(bootstrap); + try{onSlice?.();}catch{} + const frames=read('r360_title_gpu_vd_swap_calls'); + perf.submitted(t,frames); + // Present every new guest frame (software Xenos backend output). + let presentMs=0; + if(onFrame&&frames!==lastFrames){lastFrames=frames;const p0=now();try{onFrame();}catch{}presentMs=now()-p0;perf.framePresented(now());} + perf.slice(t,t-sliceExit,gpuMs,presentMs); + const counter=bootstrap?.exports?.r360_perf_counter,idle=bootstrap?.exports?.r360_fiber_idle_ms; + if(typeof counter==='function')perf.counters(t,counter(0),counter(1),typeof idle==='function'?idle():0); + const gpuFrame=gpuFrameMs?.(); + if(gpuFrame!==null&&gpuFrame!==undefined)perf.gpuFrame(t,gpuFrame); + perf.record(t); + if(overlay&&t-lastOverlay>=1000){lastOverlay=t;overlay.update(perf.snapshot(t));} + globalThis.render360Perf=perf; + sliceExit=now(); if(t-lastReport<500)return; lastReport=t; - const frames=read('r360_title_gpu_vd_swap_calls'),draws=read('r360_xenos_draws'); - // Show the newest swapped frontbuffer (software Xenos backend output). - if(onFrame&&frames!==lastFrames){lastFrames=frames;try{onFrame();}catch{}} + const draws=read('r360_xenos_draws'); const seconds=Math.max(0.001,(t-started)/1000); onProgress?.(`Running · ${frames.toLocaleString()} frames presented (${(frames/seconds).toFixed(1)}/s) · ${draws.toLocaleString()} GPU draws · ${s.threads} guest threads`,{frames,draws,slices:s.slices}); }}; } + +// Shows a pending XamShowMessageBoxUI as a page dialog (the console's system +// UI); the chosen button goes back to the title through r360_xam_dialog_answer. +let shownDialog=null; +export function showGuestDialog(bootstrap,doc=globalThis.document){ + const e=bootstrap?.exports; + if(!doc||typeof e?.r360_xam_dialog_pending!=='function')return false; + if(!(e.r360_xam_dialog_pending()>>>0)){if(shownDialog){shownDialog.remove();shownDialog=null;}return false;} + if(shownDialog)return true; + const str=w=>new TextDecoder().decode(new Uint8Array(e.memory.buffer,e.r360_xam_dialog_string_ptr(w)>>>0,e.r360_xam_dialog_string_len(w)>>>0).slice()); + const count=e.r360_xam_dialog_button_count()>>>0,focused=e.r360_xam_dialog_active_button()>>>0; + const box=doc.createElement('div'); + box.setAttribute('role','dialog');box.setAttribute('aria-modal','true'); + box.style.cssText='position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.55);z-index:9999;padding:16px'; + const panel=doc.createElement('div'); + panel.style.cssText='max-width:520px;width:100%;background:#1d1f24;color:#f2f2f2;border-radius:10px;padding:20px;font:15px/1.45 system-ui,sans-serif;box-shadow:0 10px 40px rgba(0,0,0,.5)'; + const title=doc.createElement('h2');title.textContent=str(0)||'Message';title.style.cssText='margin:0 0 8px;font-size:18px'; + const text=doc.createElement('p');text.textContent=str(1);text.style.cssText='margin:0 0 16px;white-space:pre-wrap'; + const row=doc.createElement('div');row.style.cssText='display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end'; + let focus=null; + for(let i=0;i{e.r360_xam_dialog_answer(i);box.remove();shownDialog=null;}); + if(i===focused)focus=b; + row.append(b); + } + panel.append(title,text,row);box.append(panel);doc.body.append(box); + shownDialog=box;focus?.focus(); + return true; +} + // XInput gamepad bits (XINPUT_GAMEPAD_*) for the Render360 controller keys. const XINPUT_BUTTONS={UP:0x1,DOWN:0x2,LEFT:0x4,RIGHT:0x8,START:0x10,BACK:0x20,LS:0x40,RS:0x80,LB:0x100,RB:0x200,A:0x1000,B:0x2000,X:0x4000,Y:0x8000}; diff --git a/render360-perf-overlay.mjs b/render360-perf-overlay.mjs new file mode 100644 index 00000000..97ff5ec8 --- /dev/null +++ b/render360-perf-overlay.mjs @@ -0,0 +1,266 @@ +// Render360 FPS / frame-time overlay. +// +// PerfStats is pure (testable in Node); createPerfOverlay draws it on the page. +// The player feeds it once per guest slice (see browserGuestRunOptions): +// - presented frames: frames actually drawn to the page canvas; +// - submitted frames: the guest's VdSwap count (frames the game handed to +// the GPU); +// - host time spent inside the emulator, the part of it spent in the GPU +// renderer, and the time spent presenting frames on the page. +// +// Shown: current FPS (last second), average FPS (last 60 s), frame time, 1% +// low FPS, CPU emulation vs GPU rendering time, submitted vs presented. +// +// The 30 FPS bar (PROGRESS.md "30 FPS bar"), judged on guest frames (VdSwap +// presents per second, "game FPS"): average >= 30 and 1% low >= 25 over the +// last 60 s, emulation speed >= 100%, at most one frame over 50 ms per minute. +// Emulation speed is 100% plus the headroom when the guest had idle time +// (nothing runnable: the emulator is ahead of real time); without idle time +// it is game FPS / 30. Counters (counters()) come from the core: guest and +// interpreted instructions, guest idle ms. + +const WINDOW_MS = 60000; + +export class PerfStats { + constructor({windowMs = WINDOW_MS} = {}) { + this.windowMs = windowMs; + this.presentTimes = []; // performance.now() of each presented frame + this.submitEvents = []; // [time, count] of guest submissions + this.slices = []; // [time, emulationMs, gpuMs, presentMs] + this.lastSubmitted = null; + this.totalPresented = 0; + this.totalSubmitted = 0; + this.guestFrameTimes = []; // time of each guest frame (VdSwap) + this.counterSamples = []; // [time, instructions, interpreted, idleMs] + this.gpuFrames = []; // [time, gpuMs] per presented frame (WebGPU path) + this.log = []; // one record per second (exportLog) + this.lastLogAt = 0; + } + + // Core counters at time t (cumulative): guest instructions, interpreted + // instructions, guest idle milliseconds. + counters(t, instructions, interpreted, idleMs) { + this.counterSamples.push([t, instructions, interpreted, idleMs]); + this.trim(t); + } + + // GPU time of one frame on the WebGPU path (submit to completion, ms). + gpuFrame(t, ms) { + this.gpuFrames.push([t, ms]); + this.trim(t); + } + + // One presented frame at time t (ms). + framePresented(t) { + this.presentTimes.push(t); + ++this.totalPresented; + this.trim(t); + } + + // Guest swap counter (cumulative) seen at time t. + submitted(t, cumulative) { + if (this.lastSubmitted !== null && cumulative > this.lastSubmitted) { + const n = cumulative - this.lastSubmitted; + this.submitEvents.push([t, n]); + this.totalSubmitted += n; + for (let i = 0; i < n; ++i) this.guestFrameTimes.push(t); + } + this.lastSubmitted = cumulative; + this.trim(t); + } + + // Host time of one slice: total time inside the emulator, the part of it + // spent in the GPU renderer, and the page-side present time (all ms). + slice(t, emulationMs, gpuMs, presentMs) { + this.slices.push([t, Math.max(0, emulationMs - gpuMs), gpuMs + presentMs]); + this.trim(t); + } + + trim(t) { + const old = t - this.windowMs; + while (this.presentTimes.length && this.presentTimes[0] < old) this.presentTimes.shift(); + while (this.submitEvents.length && this.submitEvents[0][0] < old) this.submitEvents.shift(); + while (this.slices.length && this.slices[0][0] < old) this.slices.shift(); + while (this.guestFrameTimes.length && this.guestFrameTimes[0] < old) this.guestFrameTimes.shift(); + while (this.counterSamples.length > 2 && this.counterSamples[1][0] < old) this.counterSamples.shift(); + while (this.gpuFrames.length && this.gpuFrames[0][0] < old) this.gpuFrames.shift(); + } + + snapshot(t) { + const inLast = (times, ms) => times.filter(x => x >= t - ms).length; + const current = inLast(this.presentTimes, 1000); + const span = this.presentTimes.length > 1 + ? Math.max(1, t - this.presentTimes[0]) : 0; + const average = span ? (this.presentTimes.length - 1) * 1000 / span : current; + const deltas = []; + for (let i = 1; i < this.presentTimes.length; ++i) { + deltas.push(this.presentTimes[i] - this.presentTimes[i - 1]); + } + const frameMs = deltas.length ? deltas.slice(-Math.max(1, current)).reduce((a, b) => a + b, 0) / Math.min(deltas.length, Math.max(1, current)) : 0; + // 1% low: the FPS of the slowest 1% of frames in the window. + let low1 = 0; + if (deltas.length) { + const sorted = [...deltas].sort((a, b) => b - a); + const worst = sorted.slice(0, Math.max(1, Math.ceil(sorted.length / 100))); + low1 = 1000 / (worst.reduce((a, b) => a + b, 0) / worst.length); + } + const submittedLastSecond = this.submitEvents + .filter(([time]) => time >= t - 1000).reduce((a, [, n]) => a + n, 0); + const recent = this.slices.filter(([time]) => time >= t - 1000); + const cpuMs = recent.reduce((a, s) => a + s[1], 0); + const gpuMs = recent.reduce((a, s) => a + s[2], 0); + // Game FPS from guest frames: last second, 60 s average, 1% low, + // frames over 50 ms in the last minute. + const g = this.guestFrameTimes; + const gameFps = g.filter(x => x > t - 1000).length; + const gSpan = g.length > 1 ? Math.max(1, t - g[0]) : 0; + const gameAverageFps = gSpan ? (g.length - 1) * 1000 / gSpan : gameFps; + const gDeltas = []; + for (let i = 1; i < g.length; ++i) if (g[i] > g[i - 1]) gDeltas.push(g[i] - g[i - 1]); + let gameLow1Fps = 0; + if (gDeltas.length) { + const sorted = [...gDeltas].sort((a, b) => b - a); + const worst = sorted.slice(0, Math.max(1, Math.ceil(sorted.length / 100))); + gameLow1Fps = 1000 / (worst.reduce((a, b) => a + b, 0) / worst.length); + } + const stutters = gDeltas.filter(d => d > 50).length; + const minutes = Math.max(1 / 60, Math.min(this.windowMs, gSpan || 1000) / 60000); + // Counter rates over the last second (or the oldest sample in it). + const cs = this.counterSamples; + let mips = 0, interpretedPercent = 0, idlePercent = 0; + if (cs.length > 1) { + const last = cs[cs.length - 1]; + let first = cs[0]; + for (const c of cs) { if (c[0] >= t - 1000) { first = c; break; } } + if (first === last) first = cs[cs.length - 2]; + const dt = Math.max(1, last[0] - first[0]); + const di = last[1] - first[1]; + mips = di / dt / 1000; + interpretedPercent = di > 0 ? 100 * (last[2] - first[2]) / di : 0; + idlePercent = Math.min(100, 100 * (last[3] - first[3]) / dt); + } + const emulationSpeedPercent = idlePercent > 0 ? 100 / Math.max(0.01, 1 - idlePercent / 100) + : Math.min(100, 100 * gameFps / 30); + const gpuRecent = this.gpuFrames.filter(([time]) => time >= t - 1000); + const gpuMsPerFrame = gpuRecent.length ? gpuRecent.reduce((a, [, ms]) => a + ms, 0) / gpuRecent.length : null; + const cpuMsPerGuestFrame = gameFps ? cpuMs / gameFps : null; + const stuttersPerMinute = stutters / minutes; + const bar = { + average: gameAverageFps >= 30, low1: gameLow1Fps >= 25, speed: emulationSpeedPercent >= 100, + stutter: stuttersPerMinute <= 1, + }; + bar.pass = bar.average && bar.low1 && bar.speed && bar.stutter && gSpan >= 10000; + return { + gameFps, gameAverageFps, gameLow1Fps, stuttersPerMinute, emulationSpeedPercent, idlePercent, + mips, interpretedPercent, cpuMsPerGuestFrame, gpuMsPerFrame, bar, + frameTimes: gDeltas.slice(-120), + fps: current, + averageFps: average, + frameMs, + low1Fps: low1, + cpuMsPerSecond: cpuMs, + gpuMsPerSecond: gpuMs, + bottleneck: cpuMs === 0 && gpuMs === 0 ? '—' : cpuMs >= gpuMs ? 'CPU emulation' : 'GPU rendering', + submittedPerSecond: submittedLastSecond, + presentedPerSecond: current, + totalSubmitted: this.totalSubmitted, + totalPresented: this.totalPresented, + }; + } + + // Appends a once-a-second record to the log (exportLog). + record(t, extra = {}) { + if (t - this.lastLogAt < 1000) return; + this.lastLogAt = t; + const s = this.snapshot(t); + const {frameTimes, ...rest} = s; + this.log.push({t: Math.round(t), ...rest, ...extra}); + if (this.log.length > 7200) this.log.shift(); + } + + // The run log with device details, as one JSON-serializable object. + exportLog(device = {}) { + return {format: 'render360-perf-log-1', device, bar: '30 FPS: avg >= 30, 1% low >= 25, speed >= 100%, <= 1 stutter (>50 ms) per minute', + records: this.log}; + } +} + +export function formatPerf(s) { + const f = (x, d = 1) => Number.isFinite(x) ? x.toFixed(d) : '—'; + const mark = ok => ok ? '✓' : '✗'; + const game = s.gameFps === undefined ? [] : [ + `Game FPS ${f(s.gameFps, 0)} avg ${f(s.gameAverageFps)} 1% low ${f(s.gameLow1Fps)} stutters ${f(s.stuttersPerMinute, 1)}/min`, + `Emulation speed ${f(s.emulationSpeedPercent, 0)}% idle ${f(s.idlePercent, 0)}% ${f(s.mips, 0)} MIPS interpreted ${f(s.interpretedPercent, 2)}%`, + `CPU ${f(s.cpuMsPerGuestFrame)} ms/frame GPU ${s.gpuMsPerFrame === null ? '—' : f(s.gpuMsPerFrame) + ' ms/frame'}`, + `30 FPS bar: ${s.bar.pass ? 'PASS' : 'not met'} avg${mark(s.bar.average)} low${mark(s.bar.low1)} speed${mark(s.bar.speed)} stutter${mark(s.bar.stutter)}`, + ]; + return [ + ...game, + `FPS ${f(s.fps, 0)} avg ${f(s.averageFps)} 1% low ${f(s.low1Fps)}`, + `Frame time ${f(s.frameMs)} ms`, + `CPU emulation ${f(s.cpuMsPerSecond, 0)} ms/s GPU rendering ${f(s.gpuMsPerSecond, 0)} ms/s`, + `Bottleneck: ${s.bottleneck}`, + `Frames submitted ${f(s.submittedPerSecond, 0)}/s presented ${f(s.presentedPerSecond, 0)}/s`, + 'Audio: not implemented (no XMA yet)', + ].join('\n'); +} + +// Overlay element, toggled with the ` key (or globalThis.render360PerfOverlay.toggle()). +export function createPerfOverlay(doc = globalThis.document) { + if (!doc) return null; + const el = doc.createElement('pre'); + el.setAttribute('aria-live', 'off'); + el.style.cssText = 'position:fixed;top:8px;left:8px;z-index:9998;margin:0;padding:8px 10px;' + + 'background:rgba(0,0,0,.66);color:#e8f5e9;font:12px/1.4 ui-monospace,Menlo,Consolas,monospace;' + + 'border-radius:6px;pointer-events:none;white-space:pre;max-width:calc(100vw - 16px);overflow:hidden'; + el.textContent = 'FPS —'; + doc.body.append(el); + // Frame-time graph: guest frame times, 33.3 ms (30 FPS) and 50 ms lines. + const graph = doc.createElement('canvas'); + graph.width = 240; graph.height = 60; + graph.style.cssText = 'display:block;margin-top:6px;width:240px;height:60px'; + el.after(graph); + const box = doc.createElement('div'); + box.style.cssText = 'position:fixed;top:8px;left:8px;z-index:9998;pointer-events:none'; + el.style.position = 'static'; + el.replaceWith(box); + box.append(el, graph); + const drawGraph = times => { + const ctx = graph.getContext?.('2d'); + if (!ctx) return; + ctx.clearRect(0, 0, 240, 60); + ctx.fillStyle = 'rgba(0,0,0,.66)'; ctx.fillRect(0, 0, 240, 60); + const y = ms => 60 - Math.min(60, ms * 60 / 100); + ctx.strokeStyle = 'rgba(120,255,120,.5)'; ctx.beginPath(); ctx.moveTo(0, y(1000 / 30)); ctx.lineTo(240, y(1000 / 30)); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,120,120,.5)'; ctx.beginPath(); ctx.moveTo(0, y(50)); ctx.lineTo(240, y(50)); ctx.stroke(); + ctx.fillStyle = '#e8f5e9'; + times.forEach((ms, i) => { const h = 60 - y(ms); ctx.fillRect(i * 2, 60 - h, 2, h); }); + }; + let visible = true; + const toggle = () => { visible = !visible; box.style.display = visible ? '' : 'none'; }; + // L downloads the run log (globalThis.render360Perf.exportLog). + const download = () => { + const perf = globalThis.render360Perf; + if (!perf?.exportLog) return; + const nav = globalThis.navigator || {}; + const device = {userAgent: nav.userAgent, cores: nav.hardwareConcurrency, memoryGiB: nav.deviceMemory, + gpu: globalThis.render360GpuAdapterInfo || null, screen: globalThis.screen ? `${screen.width}x${screen.height}@${globalThis.devicePixelRatio}` : null}; + const blob = new Blob([JSON.stringify(perf.exportLog(device), null, 1)], {type: 'application/json'}); + const a = doc.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = `render360-perf-${new Date().toISOString().replace(/[:.]/g, '-')}.json`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 10000); + }; + const onKey = e => { if (e.key === '`') toggle(); else if (e.key === 'L' || e.key === 'l') download(); }; + doc.addEventListener('keydown', onKey); + const overlay = { + element: el, + toggle, + update(snapshot) { if (visible) { el.textContent = formatPerf(snapshot) + '\n[`] hide [L] download log'; drawGraph(snapshot.frameTimes || []); } }, + download, + remove() { doc.removeEventListener('keydown', onKey); box.remove(); }, + }; + globalThis.render360PerfOverlay = overlay; + return overlay; +} diff --git a/render360-trap-report.mjs b/render360-trap-report.mjs index f06ee027..19208c56 100644 --- a/render360-trap-report.mjs +++ b/render360-trap-report.mjs @@ -87,7 +87,7 @@ export function wrapCoreTrap(error,bootstrap,{onPoisoned=null,context=''}={}){ const wrapped=new Error(describeTrap(report,error)+' [FAIL_CLOSED_CORE_TRAP]'); wrapped.code='R360_CORE_TRAP'; wrapped.cause=error; - wrapped.render360={kind:'core-trap',context,trap:report,original:String(error?.message||error)}; + wrapped.render360={kind:'core-trap',context,trap:report,original:String(error?.message||error),stack:String(error?.stack||'').split('\n').slice(0,40).join('\n')}; return wrapped; } diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs new file mode 100644 index 00000000..0301da06 --- /dev/null +++ b/render360-webgpu-backend.mjs @@ -0,0 +1,1067 @@ +// Render360 WebGPU Xenos backend: replays the command stream the core +// records (src/xenia_web_bootstrap/webgpu_backend.cpp) into WebGPU, as +// Xenia's VulkanCommandProcessor replays its DeferredCommandBuffer. +// docs/gpu/WEBGPU_BACKEND.md describes the design. + +export const GPU_STREAM_UPLOAD=1; +export const GPU_STREAM_SHADER=2; +export const GPU_STREAM_PIPELINE=3; +export const GPU_STREAM_RENDER_TARGETS=4; +export const GPU_STREAM_DRAW=5; +export const GPU_STREAM_SWAP=6; +export const GPU_STREAM_LOAD_SHADER=7; +export const GPU_STREAM_TEXTURE=8; +export const GPU_STREAM_TEXTURE_LOAD=9; +export const GPU_STREAM_EDRAM_DUMP=10; +export const GPU_STREAM_RESOLVE=11; +export const GPU_STREAM_CLEAR=12; + +const EDRAM_TILES=2048,EDRAM_TILE_DWORDS=80*16; +// xenos::IsColorRenderTargetFormat64bpp. +const COLOR_64BPP=new Set([5,7,15]); + +// WebGpuTextureFormat (src/xenia_web_bootstrap/webgpu_textures.h). +const TEXTURE_FORMATS=[null,'r8unorm','r8snorm','rg8unorm','rg8snorm','rgba8unorm','rgba8snorm','rgb10a2unorm', + 'r16float','rg16float','rgba16float','r32float','rg32float','rgba32float']; +const UNFILTERABLE_FORMATS=new Set(['r32float','rg32float','rgba32float']); + +const BUFFER_USAGE={MAP_READ:0x1,COPY_SRC:0x4,COPY_DST:0x8,INDEX:0x10,UNIFORM:0x40,STORAGE:0x80}; +const TEXTURE_USAGE={COPY_SRC:0x1,COPY_DST:0x2,TEXTURE_BINDING:0x4,RENDER_ATTACHMENT:0x10}; +const SHADER_STAGE={VERTEX:0x1,FRAGMENT:0x2}; +const SHARED_MEMORY_BYTES=512*1024*1024; // Xenia SharedMemory::kBufferSize +const STAGING_BYTES=16*1024*1024; + +// Shared memory buffer size the adapter allows: Xenia's 512 MiB, or the +// largest power of two below the device's limits (physical addresses above +// it then cannot be used by GPU emulation, which is reported). +export function sharedMemoryBytesForLimits(limits){ + const max=Math.min(limits.maxBufferSize,limits.maxStorageBufferBindingSize); + let bytes=SHARED_MEMORY_BYTES; + while(bytes>max)bytes/=2; + return bytes; +} + +export class XenosWebGpuBackend{ + constructor(device,exports,{sharedMemoryBytes=sharedMemoryBytesForLimits(device.limits)}={}){ + this.device=device; + this.exports=exports; + this.sharedMemoryBytes=sharedMemoryBytes; + // The GPU copy of guest physical memory (Xenia's shared memory buffer). + this.sharedMemory=device.createBuffer({label:'Render360 shared memory',size:sharedMemoryBytes, + usage:BUFFER_USAGE.STORAGE|BUFFER_USAGE.COPY_DST|BUFFER_USAGE.COPY_SRC}); + // Upload staging: writeBuffer is ordered before the next submit, so the + // region is reusable once the commands copying out of it are submitted. + this.staging=device.createBuffer({label:'Render360 upload staging',size:STAGING_BYTES, + usage:BUFFER_USAGE.COPY_SRC|BUFFER_USAGE.COPY_DST}); + this.stagingOffset=0; + this.encoder=null; + this.stats={uploads:0,uploadedBytes:0,droppedUploads:0,submits:0,shaders:0,pipelines:0, + pipelineFailures:0,draws:0,skippedDraws:0,renderPasses:0,swaps:0,targetsCreated:0, + textures:0,textureLoads:0,textureFailures:0,textureLoadFailures:0,loadShaderFailures:0,unbindableTextures:0, + dumps:0,resolves:0,resolveFailures:0,clears:0}; + // r32float and wider float textures are filterable only with this feature. + this.float32Filterable=!!device.features?.has?.('float32-filterable'); + this.convert=null; + this.shaders=new Map(); // stream id -> {stage, module, bindings, outputs} + this.pipelines=new Map(); // stream id -> {pipeline, layouts, description} or {error} + this.layouts=new Map(); // layout key -> GPUBindGroupLayout + this.bindGroups=new Map(); // layout key -> GPUBindGroup (shared memory, placeholders) + this.targets=new Map(); // render target key -> {texture, view, format, width, height} + this.boundTargets=null; // WebGpuRenderTargetsKey of op 4 + this.pass=null; + this.lastSwap=null; + this.loadShaders=new Map(); // TextureCache::LoadShaderIndex -> compute pipeline + this.textures=new Map(); // stream texture id -> {texture, views, format} + this.samplers=new Map(); // packed sampler parameters -> GPUSampler + this.textureGroups=new Map();// bind groups of groups 2 / 3 by contents + this.scratch=null;this.scratchRetired=[]; + // Xenia's EDRAM buffer (render target dumps for resolves) and the host + // render target owning each tile (RenderTargetCache ownership). + this.edram=device.createBuffer({label:'Render360 EDRAM',size:EDRAM_TILES*EDRAM_TILE_DWORDS*4, + usage:BUFFER_USAGE.STORAGE|BUFFER_USAGE.COPY_SRC|BUFFER_USAGE.COPY_DST}); + this.tileOwner=new Array(EDRAM_TILES).fill(null); + this.frontTexture=null; + this.uniforms=new XenosUniformRing(device); + this.indices=new XenosRing(device,'Render360 indices',BUFFER_USAGE.INDEX,8*1024*1024); + } + + // Loads the SPIR-V to WGSL converter (Naga); needed before shaders replay. + async init(){ + const {loadSpirvToWgslConverter}=await import('./render360-spirv-wgsl-runtime.mjs'); + this.convert=(await loadSpirvToWgslConverter()).convert; + return this; + } + + encoderForCommands(){ + if(!this.encoder)this.encoder=this.device.createCommandEncoder({label:'Render360 Xenos'}); + return this.encoder; + } + + submit(){ + this.endPass(); + this.uniforms.flush();this.indices.flush(); + if(this.encoder){this.device.queue.submit([this.encoder.finish()]);this.encoder=null;this.stats.submits++;} + for(const b of this.scratchRetired)b.destroy(); + this.scratchRetired.length=0; + this.stagingOffset=0; + } + + // Replays and clears the core's recorded commands. + replay(){ + const e=this.exports,count=e.r360_gpu_stream_words()>>>0; + if(!count)return; + const base=e.r360_gpu_stream_data()>>>0; + this.replayWords(new Uint32Array(e.memory.buffer,base,count)); + e.r360_gpu_stream_reset(); + } + + // Replays stream words (from the core's memory, or a capture). + replayWords(words){ + const bytes=new Uint8Array(words.buffer,words.byteOffset,words.byteLength); + for(let i=0;i>>8,p=words.subarray(i+1,i+1+n); + if(op===GPU_STREAM_UPLOAD)this.upload(p[0],p[1],bytes.subarray((i+3)*4,(i+3)*4+p[1])); + else if(op===GPU_STREAM_SHADER)this.defineShader(p); + else if(op===GPU_STREAM_PIPELINE)this.definePipeline(p); + else if(op===GPU_STREAM_RENDER_TARGETS){this.endPass();this.boundTargets=parseRenderTargets(p);} + else if(op===GPU_STREAM_DRAW)this.draw(p); + else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.frontTexture=this.textures.get(p[6])||null;this.frontSwizzle=p[7]??0x688;this.submit();} + else if(op===GPU_STREAM_EDRAM_DUMP)this.dumpEdram(p); + else if(op===GPU_STREAM_RESOLVE)this.resolve(p); + else if(op===GPU_STREAM_CLEAR)this.clear(p); + else if(op===GPU_STREAM_LOAD_SHADER)this.defineLoadShader(p); + else if(op===GPU_STREAM_TEXTURE)this.defineTexture(p); + else if(op===GPU_STREAM_TEXTURE_LOAD)this.loadTexture(p); + else throw new Error(`Render360 GPU stream: unknown op ${op} at word ${i}`); + i+=1+n; + } + } + + // Shader op: translated SPIR-V, converted to WGSL by Naga. + defineShader(p){ + if(!this.convert)throw new Error('Render360 WebGPU backend: init() before replaying shaders'); + const [id,stage,textureCount,samplerCount,spirvWords]=p; + const spirv=new Uint8Array(p.buffer,p.byteOffset+(5+textureCount+samplerCount)*4,spirvWords*4).slice(); + const shader={id,stage,textures:Array.from(p.subarray(5,5+textureCount)), + samplers:Array.from(p.subarray(5+textureCount,5+textureCount+samplerCount))}; + try{ + shader.wgsl=this.convert(spirv); + shader.bindings=parseWgslBindings(shader.wgsl); + shader.module=this.device.createShaderModule({label:`Render360 Xenos ${stage?'pixel':'vertex'} shader ${id}`,code:shader.wgsl}); + }catch(error){shader.error=String(error?.message||error);} + this.shaders.set(id,shader); + this.stats.shaders++; + } + + // Pipeline op: the WebGpuPipelineDescription, as Xenia's + // VulkanPipelineCache::EnsurePipelineCreated turns it into a pipeline. + definePipeline(p){ + const id=p[0],d=parsePipelineDescription(p.subarray(1)); + const entry={description:d}; + try{ + const vs=this.shaders.get(d.vertexShader),ps=d.pixelShader?this.shaders.get(d.pixelShader):null; + if(!vs?.module)throw new Error(`vertex shader ${d.vertexShader}: ${vs?.error||'missing'}`); + if(d.pixelShader&&!ps?.module)throw new Error(`pixel shader ${d.pixelShader}: ${ps?.error||'missing'}`); + // Bind groups (Xenia's descriptor sets): 0 shared memory, 1 constant + // buffers, 2 vertex textures, 3 pixel textures. + entry.layouts=[0,1,2,3].map(g=>this.groupLayout(g,[vs,ps].filter(Boolean))); + const layout=this.device.createPipelineLayout({bindGroupLayouts:entry.layouts.map(l=>l.layout)}); + const targets=[]; + for(let i=0;i<4;i++){ + if(!d.colorFormats[i])continue; + const format=colorFormat(d.colorFormats[i]-1); + while(targets.length>>(i*4))&0xF}; + const blend=blendState(d.blendControl[i]); + if(blend&&blendableFormat(format))target.blend=blend; + targets.push(target); + } + const descriptor={label:`Render360 Xenos pipeline ${id}`,layout, + vertex:{module:vs.module,entryPoint:'main'}, + primitive:{topology:['point-list','line-list','line-strip','triangle-list','triangle-strip'][d.topology], + cullMode:['none','front','back'][d.cullMode],frontFace:d.frontFaceCw?'cw':'ccw'}, + multisample:{count:1}}; + if(ps||targets.length)descriptor.fragment={module:(ps||vs).module,entryPoint:'main',targets}; + if(!ps)delete descriptor.fragment; + if(d.depthFormat){ + const stencil=d.stencil,on=(stencil&1)!==0; + const face=(func,fail,zpass,zfail)=>({compare:COMPARE[func],failOp:STENCIL_OP[fail],depthFailOp:STENCIL_OP[zfail],passOp:STENCIL_OP[zpass]}); + const front=on?face((stencil>>>8)&7,(stencil>>>11)&7,(stencil>>>14)&7,(stencil>>>17)&7):{}; + const back=on?((stencil>>>7)&1?face((stencil>>>20)&7,(stencil>>>23)&7,(stencil>>>26)&7,(stencil>>>29)&7):front):{}; + descriptor.depthStencil={format:this.depthFormat(d.depthFormat-1),depthWriteEnabled:!!d.depthWrite, + depthCompare:COMPARE[d.depthCompare],stencilFront:front,stencilBack:back, + stencilReadMask:on?(d.stencilMasks>>>8)&0xFF:0xFF,stencilWriteMask:on?(d.stencilMasks>>>16)&0xFF:0}; + } + entry.pipeline=this.device.createRenderPipeline(descriptor); + this.stats.pipelines++; + }catch(error){entry.error=String(error?.message||error);this.stats.pipelineFailures++;} + this.pipelines.set(id,entry); + } + + depthFormat(guest){ + // kD24FS8 (20e4 float depth): 32-bit float depth where the device has it. + return guest===1&&this.device.features?.has?.('depth32float-stencil8')?'depth32float-stencil8':'depth24plus-stencil8'; + } + + // A bind group layout (and its constant bind group when it has one) for + // the WGSL declarations of the pipeline's shaders in `group`. + groupLayout(group,shaders){ + const entries=new Map(); + if(group===1){ + // Constant buffers at dynamic offsets in the uniform ring. + for(let b=0;b<5;b++)entries.set(b,{binding:b,visibility:SHADER_STAGE.VERTEX|SHADER_STAGE.FRAGMENT,buffer:{type:'uniform',hasDynamicOffset:true}}); + }else{ + for(const shader of shaders)for(const decl of shader.bindings){ + if(decl.group!==group)continue; + const visibility=shader.stage?SHADER_STAGE.FRAGMENT:SHADER_STAGE.VERTEX; + const prior=entries.get(decl.binding); + if(prior){prior.visibility|=visibility;continue;} + const entry={binding:decl.binding,visibility}; + if(decl.kind==='storage'){ + if(decl.write&&!shader.stage)throw new Error('vertex shader memory export is not supported yet'); + entry.buffer={type:decl.write?'storage':'read-only-storage'}; + }else if(decl.kind==='uniform')entry.buffer={type:'uniform'}; + else if(decl.kind==='sampler')entry.sampler={type:decl.comparison?'comparison':'filtering'}; + else if(decl.kind==='texture')entry.texture={sampleType:decl.sampleType,viewDimension:decl.viewDimension,multisampled:false}; + else throw new Error(`unsupported WGSL binding ${decl.type}`); + entries.set(decl.binding,entry); + } + } + const list=[...entries.values()].sort((a,b)=>a.binding-b.binding); + const key=`${group}:${JSON.stringify(list)}`; + let cached=this.layouts.get(key); + if(!cached){ + const layout=this.device.createBindGroupLayout({label:`Render360 Xenos group ${group}`,entries:list}); + cached={key,layout,entries:list,group:group===1?null:this.device.createBindGroup({layout,entries:list.map(e=>({binding:e.binding,resource:this.placeholderResource(e)}))})}; + if(group===1)cached.group=this.uniforms.bindGroup(layout); + this.layouts.set(key,cached); + } + return cached; + } + + // The shared memory buffer, or a placeholder texture / sampler until the + // texture cache is ported. + placeholderResource(entry){ + if(entry.buffer)return {buffer:this.sharedMemory}; + if(entry.sampler){ + const key=`sampler:${entry.sampler.type}`; + if(!this.bindGroups.has(key))this.bindGroups.set(key,this.device.createSampler(entry.sampler.type==='comparison'?{compare:'less'}:{magFilter:'linear',minFilter:'linear'})); + return this.bindGroups.get(key); + } + const {sampleType,viewDimension}=entry.texture,key=`texture:${sampleType}:${viewDimension}`; + if(!this.bindGroups.has(key)){ + const format=sampleType==='sint'?'rgba8sint':sampleType==='uint'?'rgba8uint':sampleType==='depth'?'depth32float':'rgba8unorm'; + const layers=viewDimension==='cube'?6:1; + const texture=this.device.createTexture({label:`Render360 placeholder ${viewDimension}`,format, + dimension:viewDimension==='3d'?'3d':'2d',size:{width:1,height:1,depthOrArrayLayers:layers},usage:TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_DST}); + if(format!=='depth32float'){ + const texel=new Uint8Array(4*layers).fill(255); + this.device.queue.writeTexture({texture},texel,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:layers}); + } + this.bindGroups.set(key,texture.createView({dimension:viewDimension})); + } + return this.bindGroups.get(key); + } + + // Host render target for an EDRAM base / format / pitch (Xenia's + // RenderTargetCache key without the resolution scale). + target(base,guestFormat,depth,pitch,height,msaa=0){ + const key=`${depth?'d':'c'}:${base}:${guestFormat}:${pitch}:${msaa}`; + let t=this.targets.get(key); + if(t&&t.height>=height)return t; + const format=depth?this.depthFormat(guestFormat):colorFormat(guestFormat); + const texture=this.device.createTexture({label:`Render360 EDRAM ${key}`,format,size:{width:pitch,height:Math.max(height,t?.height||0,720)}, + usage:TEXTURE_USAGE.RENDER_ATTACHMENT|TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_SRC|TEXTURE_USAGE.COPY_DST}); + // A taller target replaces the old one; its contents are kept by copying. + const fresh={key,base,guestFormat,depth,texture,view:texture.createView(),format,width:pitch,height:texture.height,initialized:false, + msaa,...tileGeometry(pitch,msaa,!depth&&COLOR_64BPP.has(guestFormat))}; + if(t){ + this.endPass(); + this.encoderForCommands().copyTextureToTexture({texture:t.texture},{texture},{width:t.width,height:t.height}); + fresh.initialized=t.initialized;t.texture.destroy(); + } + this.targets.set(key,fresh); + this.stats.targetsCreated++; + return fresh; + } + + // Begins a render pass on the bound render targets. + beginPass(){ + if(this.pass)return this.pass; + const k=this.boundTargets; + if(!k||!k.surfacePitch)return null; + const colorAttachments=[]; + const used=[]; + for(let i=0;i<4;i++){ + if(k.colorBase[i]===0xFFFFFFFF)continue; + const t=this.target(k.colorBase[i],k.colorFormat[i],false,k.surfacePitch,k.height,k.msaaSamples); + while(colorAttachments.lengtht.height))}; + this.pass=this.encoderForCommands().beginRenderPass(pass); + this.passState={pipeline:null,groups:[]}; + this.stats.renderPasses++; + return this.pass; + } + + endPass(){ + if(this.pass){this.pass.end();this.pass=null;} + } + + // Draw op: header, system / float / bool-loop / fetch constants, indices. + draw(p){ + const h=parseDrawHeader(p); + if(this.drawLimit!==undefined&&this.stats.draws>=this.drawLimit){this.stats.skippedDraws++;return;} + const entry=this.pipelines.get(h.pipeline); + if(!entry?.pipeline){this.stats.skippedDraws++;return;} + let o=DRAW_HEADER_WORDS; + const constants=[h.systemWords,h.floatVertexWords,h.floatPixelWords,h.boolLoopWords,h.fetchWords].map(n=>{const c=p.subarray(o,o+n);o+=n;return c;}); + const bindingWords=p.subarray(o,o+h.bindingWords);o+=h.bindingWords; + const indexWords=h.indexFormat===2?h.vertexCount:h.indexFormat===1?(h.vertexCount+1)>>>1:0; + const indexData=p.subarray(o,o+indexWords); + // Constants and indices are written before the pass using them is + // submitted (both rings flush on submit). + if(!this.uniforms.fits(constants)||!this.indices.fits(indexData.byteLength))this.submit(); + const pass=this.beginPass(); + if(!pass){this.stats.skippedDraws++;return;} + const offsets=constants.map(c=>this.uniforms.push(c)); + const W=this.passSize.width,H=this.passSize.height; + const vx=Math.max(0,Math.min(h.viewport[0],W)),vy=Math.max(0,Math.min(h.viewport[1],H)); + const vw=Math.min(h.viewport[2],W-vx),vh=Math.min(h.viewport[3],H-vy); + const sx=Math.min(h.scissor[0],W),sy=Math.min(h.scissor[1],H); + const sw=Math.min(h.scissor[2],W-sx),sh=Math.min(h.scissor[3],H-sy); + if(vw<=0||vh<=0||sw<=0||sh<=0){this.stats.skippedDraws++;return;} + const s=this.passState; + if(s.pipeline!==entry.pipeline){pass.setPipeline(entry.pipeline);s.pipeline=entry.pipeline;} + const textureGroups=this.textureBindGroups(entry,bindingWords); + for(let g=0;g<4;g++){ + const group=g>=2?textureGroups[g-2]:entry.layouts[g].group; + if(g===1)pass.setBindGroup(1,group,offsets); + else if(s.groups[g]!==group){pass.setBindGroup(g,group);s.groups[g]=group;} + } + let z0=Math.max(0,Math.min(1,h.depthRange[0])),z1=Math.max(0,Math.min(1,h.depthRange[1])); + if(z0>z1)[z0,z1]=[z1,z0]; + pass.setViewport(vx,vy,vw,vh,z0,z1); + pass.setScissorRect(sx,sy,sw,sh); + pass.setStencilReference(h.stencilReference); + pass.setBlendConstant({r:h.blendConstant[0],g:h.blendConstant[1],b:h.blendConstant[2],a:h.blendConstant[3]}); + if(h.indexFormat){ + const bytes=new Uint8Array(indexData.buffer,indexData.byteOffset,h.indexFormat===2?h.vertexCount*4:h.vertexCount*2); + const offset=this.indices.push(bytes); + pass.setIndexBuffer(this.indices.buffer,h.indexFormat===2?'uint32':'uint16',offset,bytes.byteLength); + pass.drawIndexed(h.vertexCount); + }else{ + pass.draw(h.vertexCount); + } + this.stats.draws++; + } + + // Bind groups 2 (vertex) and 3 (pixel) of a draw: its textures (by + // stream id, 0 for Xenia's null texture) and samplers. + textureBindGroups(entry,words){ + const out=[];let o=0; + for(let g=2;g<4;g++){ + const shader=this.shaders.get(g===2?entry.description.vertexShader:entry.description.pixelShader); + const layout=entry.layouts[g]; + if(!shader||!layout.entries.length){out.push(layout.group);if(shader)o+=shader.textures.length+shader.samplers.length;continue;} + const n=shader.textures.length,m=shader.samplers.length,ids=words.subarray(o,o+n+m);o+=n+m; + const key=`${layout.key}|${ids.join(',')}`; + let group=this.textureGroups.get(key); + if(!group){ + if(this.textureGroups.size>4096)this.textureGroups.clear(); + group=this.device.createBindGroup({layout:layout.layout,entries:layout.entries.map(e=>{ + if(e.texture){ + const t=e.binding=n&&e.bindingm===0?'repeat':m===1?'mirror-repeat':'clamp-to-edge'; + const mag=(parameters>>>11)&1,min=(parameters>>>12)&1,mip=(parameters>>>13)&1; + const aniso=(parameters>>>14)&7,baseMap=(parameters>>>17)&1,minLevel=(parameters>>>18)&15; + const descriptor={addressModeU:address(parameters&7),addressModeV:address((parameters>>>3)&7),addressModeW:address((parameters>>>6)&7), + magFilter:mag?'linear':'nearest',minFilter:min?'linear':'nearest',mipmapFilter:mip?'linear':'nearest', + lodMinClamp:minLevel,lodMaxClamp:baseMap?minLevel+0.25:32}; + // Anisotropy needs every filter linear in WebGPU. + if(aniso>=2&&mag&&min&&mip)descriptor.maxAnisotropy=Math.min(16,1<<(aniso-1)); + sampler=this.device.createSampler(descriptor); + this.samplers.set(parameters,sampler); + return sampler; + } + + // One of Xenia's texture_load_* compute shaders. Naga rejects write-only + // storage (NonReadable) and has no push constants in WGSL: the decoration + // is dropped and the push constant block becomes a uniform buffer. + defineLoadShader(p){ + const index=p[0],spirv=stripNonReadable(p.subarray(2,2+p[1])); + const entry={}; + try{ + const wgsl=this.convert(new Uint8Array(spirv.buffer,spirv.byteOffset,spirv.byteLength)) + .replace(/var<(?:immediate|push_constant)>\s+(\w+)\s*:/,'@group(2) @binding(0) var $1:'); + const module=this.device.createShaderModule({label:`Xenia texture load ${index}`,code:wgsl}); + const S=0x4; // COMPUTE + // Texture loads: group 0 destination, 1 source. Resolve copies (64 + + // ResolveCopyShaderIndex): group 0 EDRAM, 1 shared memory destination. + const resolve=index>=64; + const layouts=[ + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:resolve?'read-only-storage':'storage'}}]}), + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:resolve?'storage':'read-only-storage'}}]}), + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:'uniform',hasDynamicOffset:true}}]})]; + entry.layouts=layouts; + entry.pipeline=this.device.createComputePipeline({label:`Xenia texture load ${index}`, + layout:this.device.createPipelineLayout({bindGroupLayouts:layouts}),compute:{module,entryPoint:'main'}}); + entry.constants=this.device.createBindGroup({layout:layouts[2],entries:[{binding:0,resource:{buffer:this.uniforms.buffer,offset:0,size:256}}]}); + }catch(error){entry.error=String(error?.message||error);this.stats.loadShaderFailures++;} + this.loadShaders.set(index,entry); + } + + // Texture op: VulkanTextureCache::CreateTexture. + defineTexture(p){ + const [id,formatIndex,dimension,width,height,depth,mips]=p; + const format=TEXTURE_FORMATS[formatIndex]; + const old=this.textures.get(id); + if(old)old.texture.destroy(); + if(!format){this.stats.textureFailures++;return;} + const is3d=dimension===1; + const texture=this.device.createTexture({label:`Xenos texture ${id}`,format,dimension:is3d?'3d':'2d', + size:{width,height,depthOrArrayLayers:depth},mipLevelCount:mips,usage:TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_DST|TEXTURE_USAGE.COPY_SRC}); + const views={}; + if(is3d)views['3d']=texture.createView({dimension:'3d'}); + else if(dimension===2)views.cube=texture.createView({dimension:'cube'}); + else views['2d-array']=texture.createView({dimension:'2d-array'}); + this.textures.set(id,{id,texture,views,format,dimension,width,height}); + this.textureGroups.clear(); + this.stats.textures++; + } + + // Texture load op: Xenia's load shader dispatches into a scratch buffer + // (VulkanTextureCache::LoadTextureDataFromResidentMemoryImpl), an + // optional expansion pass, then copies into the texture. + loadTexture(p){ + const [id,shaderIndex,expand,bufferSize,baseOffset,baseSize,mipsOffset,mipsSize,dispatchCount,copyCount]=p; + const t=this.textures.get(id),shader=this.loadShaders.get(shaderIndex); + if(!t||!shader?.pipeline){this.stats.textureLoadFailures++;return;} + this.endPass(); + const expanded=expand>=1&&expand<=4; + const scratchBytes=bufferSize*(expanded?3:1)+256; + if(!this.scratch||this.scratch.sizesize?this.device.createBindGroup({layout:shader.layouts[1],entries:[{binding:0,resource:{buffer:this.sharedMemory,offset,size}}]}):null; + const sources=[source(baseOffset,baseSize),source(mipsOffset,mipsSize)]; + const pass=this.encoderForCommands().beginComputePass({label:'Xenia texture load'}); + pass.setPipeline(shader.pipeline); + pass.setBindGroup(0,dest); + let o=10; + for(let d=0;d=5,words=bufferSize/4; + const out=inPlace?0:Math.ceil(bufferSize/256)*256; + const group=this.device.createBindGroup({layout:entry.pipeline.getBindGroupLayout(0),entries:[ + {binding:0,resource:{buffer:this.scratch,offset:0,size:bufferSize}}, + ...(inPlace?[]:[{binding:1,resource:{buffer:this.scratch,offset:out,size:bufferSize*2}}])]}); + const pass=this.encoderForCommands().beginComputePass({label:'Render360 texel expand'}); + pass.setPipeline(entry.pipeline);pass.setBindGroup(0,group); + const groups=Math.ceil(words/64); + pass.dispatchWorkgroups(Math.min(groups,65535),Math.ceil(groups/65535)); + pass.end(); + return inPlace?{buffer:this.scratch,scale:1,base:0}:{buffer:this.scratch,scale:2,base:out}; + } + + // The render target owns the EDRAM tiles it covers up to `height` pixels. + own(t,height){ + const rows=Math.ceil(Math.min(height,t.height)/t.tileHeight); + for(let r=0;rthis.sharedMemoryBytes){this.stats.resolveFailures++;return;} + this.endPass(); + const constants=p.subarray(1,6); + if(!this.uniforms.fits([constants]))this.submit(); + const at=this.uniforms.push(constants); + const pass=this.encoderForCommands().beginComputePass({label:'Xenia resolve'}); + pass.setPipeline(shader.pipeline); + pass.setBindGroup(0,this.device.createBindGroup({layout:shader.layouts[0],entries:[{binding:0,resource:{buffer:this.edram}}]})); + pass.setBindGroup(1,this.device.createBindGroup({layout:shader.layouts[1],entries:[{binding:0,resource:{buffer:this.sharedMemory,offset,size}}]})); + pass.setBindGroup(2,shader.constants,[at]); + pass.dispatchWorkgroups(groupsX,groupsY,1); + pass.end(); + this.stats.resolves++; + } + + // Clear op: the host render targets at the cleared EDRAM region + // (VulkanRenderTargetCache::PrepareHostRenderTargetsResolveClear and + // PerformTransfersAndResolveClears). + clear(p){ + const [isDepth,base,pitchTiles,msaa,format,x,y,width,height,lo,hi]=p; + this.endPass(); + for(const t of this.targets.values()){ + if(!!t.depth!==!!isDepth||t.pitchTiles!==pitchTiles||t.msaa!==msaa||t.guestFormat!==format)continue; + const delta=(base-t.base+EDRAM_TILES)%EDRAM_TILES; + const x0=(delta%pitchTiles)*t.tileWidth+x,y0=Math.floor(delta/pitchTiles)*t.tileHeight+y; + if(x0>=t.width||y0>=t.height)continue; + const w=Math.min(width,t.width-x0),h=Math.min(height,t.height-y0); + const whole=x0===0&&y0===0&&w>=t.width&&h>=t.height; + const value=isDepth?depthClearValue(format,lo,this.depthFormat(format)):colorClearValue(format,lo,hi); + const attachment=isDepth + ?{depthStencilAttachment:{view:t.view,depthLoadOp:whole?'clear':'load',depthClearValue:value.depth,depthStoreOp:'store', + stencilLoadOp:whole?'clear':'load',stencilClearValue:value.stencil,stencilStoreOp:'store'},colorAttachments:[]} + :{colorAttachments:[{view:t.view,loadOp:whole?'clear':'load',clearValue:value,storeOp:'store'}]}; + const pass=this.encoderForCommands().beginRenderPass(attachment); + if(!whole){ + pass.setPipeline(this.clearPipeline(t)); + const words=new Float32Array(isDepth?[value.depth,0,0,0]:[value.r,value.g,value.b,value.a]); + if(!this.uniforms.fits([words])){pass.end();this.submit();this.clear(p);return;} + const at=this.uniforms.push(new Uint32Array(words.buffer)); + pass.setBindGroup(0,this.clearGroup(t),[at]); + pass.setScissorRect(x0,y0,w,h); + if(isDepth)pass.setStencilReference(value.stencil); + pass.draw(3); + } + pass.end(); + t.initialized=true; + this.stats.clears++; + } + } + + clearPipeline(t){ + this.clearPipelines??=new Map(); + let pipeline=this.clearPipelines.get(t.format); + if(!pipeline){ + const module=this.device.createShaderModule({label:'Render360 clear',code:CLEAR_SHADER}); + const layout=this.clearLayout(); + const descriptor={label:`Render360 clear ${t.format}`,layout:this.device.createPipelineLayout({bindGroupLayouts:[layout]}), + vertex:{module,entryPoint:'vs'},primitive:{topology:'triangle-list'}}; + if(t.depth){ + descriptor.fragment={module,entryPoint:'fs_depth',targets:[]}; + const face={compare:'always',passOp:'replace',failOp:'replace',depthFailOp:'replace'}; + descriptor.depthStencil={format:t.format,depthWriteEnabled:true,depthCompare:'always',stencilFront:face,stencilBack:face,stencilWriteMask:0xFF}; + }else descriptor.fragment={module,entryPoint:'fs_color',targets:[{format:t.format}]}; + pipeline=this.device.createRenderPipeline(descriptor); + this.clearPipelines.set(t.format,pipeline); + } + return pipeline; + } + clearLayout(){ + this.clearBindGroupLayout??=this.device.createBindGroupLayout({entries:[{binding:0,visibility:SHADER_STAGE.FRAGMENT,buffer:{type:'uniform',hasDynamicOffset:true}}]}); + return this.clearBindGroupLayout; + } + clearGroup(){ + this.clearBindGroup??=this.device.createBindGroup({layout:this.clearLayout(),entries:[{binding:0,resource:{buffer:this.uniforms.buffer,offset:0,size:16}}]}); + return this.clearBindGroup; + } + + // Draws the front buffer of the last swap to a canvas context configured + // on this device (the play path's present; Xenia's swap presenter). + present(context,format){ + const front=this.frontTexture; + if(!front)return false; + this.presentPipelines??=new Map(); + let pipeline=this.presentPipelines.get(format); + if(!pipeline){ + const module=this.device.createShaderModule({label:'Render360 present',code:PRESENT_SHADER}); + pipeline=this.device.createRenderPipeline({label:'Render360 present',layout:'auto', + vertex:{module,entryPoint:'vs'},fragment:{module,entryPoint:'fs',targets:[{format}]},primitive:{topology:'triangle-list'}}); + this.presentPipelines.set(format,pipeline); + } + this.presentSwizzleBuffer??=this.device.createBuffer({size:16,usage:BUFFER_USAGE.UNIFORM|BUFFER_USAGE.COPY_DST}); + this.device.queue.writeBuffer(this.presentSwizzleBuffer,0,new Uint32Array([this.frontSwizzle??0x688,0,0,0])); + if(this.presentSource!==front.texture||this.presentPipeline!==pipeline){ + this.presentSampler??=this.device.createSampler({magFilter:'linear',minFilter:'linear'}); + this.presentGroup=this.device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:[ + {binding:0,resource:front.views['2d-array']},{binding:1,resource:this.presentSampler}, + {binding:2,resource:{buffer:this.presentSwizzleBuffer}}]}); + this.presentSource=front.texture;this.presentPipeline=pipeline; + } + const encoder=this.encoderForCommands(); + this.endPass(); + const pass=encoder.beginRenderPass({colorAttachments:[{view:context.getCurrentTexture().createView(),loadOp:'clear',clearValue:{r:0,g:0,b:0,a:1},storeOp:'store'}]}); + pass.setPipeline(pipeline);pass.setBindGroup(0,this.presentGroup);pass.draw(3);pass.end(); + this.submit(); + this.stats.presents=(this.stats.presents||0)+1; + return true; + } + + // RGBA8 pixels of a color render target (tests and the frame preview). + async readTarget(t){ + this.submit(); + if(t.format!=='rgba8unorm')throw new Error(`readTarget: ${t.format} not supported`); + const bytesPerRow=Math.ceil(t.width*4/256)*256; + const read=this.device.createBuffer({size:bytesPerRow*t.height,usage:BUFFER_USAGE.MAP_READ|BUFFER_USAGE.COPY_DST}); + const encoder=this.device.createCommandEncoder(); + encoder.copyTextureToBuffer({texture:t.texture},{buffer:read,bytesPerRow},{width:t.width,height:t.height}); + this.device.queue.submit([encoder.finish()]); + await read.mapAsync(1); + const mapped=new Uint8Array(read.getMappedRange()),out=new Uint8Array(t.width*t.height*4); + for(let y=0;ythis.sharedMemoryBytes){this.stats.droppedUploads++;return;} + if(this.stagingOffset+length>STAGING_BYTES)this.submit(); + length=(length+3)&~3; + if(length>STAGING_BYTES){ + // Larger than the staging buffer: write directly (ordered before the + // next submit; nothing recorded after it reads the old contents). + this.endPass(); + this.device.queue.writeBuffer(this.sharedMemory,dest,bytes.buffer,bytes.byteOffset,length); + }else{ + // Copies happen outside render passes; draws after this one see the data. + this.endPass(); + this.device.queue.writeBuffer(this.staging,this.stagingOffset,bytes.buffer,bytes.byteOffset,length); + this.encoderForCommands().copyBufferToBuffer(this.staging,this.stagingOffset,this.sharedMemory,dest,length); + this.stagingOffset+=length; + } + this.stats.uploads++; + this.stats.uploadedBytes+=length; + } + + // Reads `length` bytes of the GPU shared memory (tests and resolve checks). + async readSharedMemory(offset,length){ + this.submit(); + const read=this.device.createBuffer({size:length,usage:BUFFER_USAGE.MAP_READ|BUFFER_USAGE.COPY_DST}); + const encoder=this.device.createCommandEncoder(); + encoder.copyBufferToBuffer(this.sharedMemory,offset,read,0,length); + this.device.queue.submit([encoder.finish()]); + await read.mapAsync(1); + const bytes=new Uint8Array(read.getMappedRange()).slice(); + read.unmap();read.destroy(); + return bytes; + } +} + +const COMPARE=['never','less','equal','less-equal','greater','not-equal','greater-equal','always']; +const STENCIL_OP=['keep','zero','replace','increment-clamp','decrement-clamp','invert','increment-wrap','decrement-wrap']; +const BLEND_FACTOR={0:'zero',1:'one',4:'src',5:'one-minus-src',6:'src-alpha',7:'one-minus-src-alpha',8:'dst',9:'one-minus-dst', + 10:'dst-alpha',11:'one-minus-dst-alpha',12:'constant',13:'one-minus-constant',14:'constant',15:'one-minus-constant',16:'src-alpha-saturated'}; +const BLEND_ALPHA_FACTOR={...BLEND_FACTOR,4:'src-alpha',5:'one-minus-src-alpha',8:'dst-alpha',9:'one-minus-dst-alpha'}; +const BLEND_OP=['add','subtract','min','max','reverse-subtract']; + +// xenos::ColorRenderTargetFormat to the host format Xenia's Vulkan render +// target cache picks (16_16(_16_16) use float here: WebGPU has no +// renderable snorm16; the system constants scale them as Xenia does). +export function colorFormat(guest){ + switch(guest){ + case 0:case 1:return 'rgba8unorm'; + case 2:case 10:return 'rgb10a2unorm'; + case 3:case 12:case 5:case 7:return 'rgba16float'; + case 4:case 6:return 'rg16float'; + case 14:return 'r32float'; + case 15:return 'rg32float'; + default:throw new Error(`unknown color render target format ${guest}`); + } +} +function blendableFormat(format){return format!=='r32float'&&format!=='rg32float';} + +// RB_BLENDCONTROL to a blend state (undefined: replace, blending off). +function blendState(control){ + const cs=control&31,cop=(control>>>5)&7,cd=(control>>>8)&31,as=(control>>>16)&31,aop=(control>>>21)&7,ad=(control>>>24)&31; + if(cs===1&&cd===0&&cop===0&&as===1&&ad===0&&aop===0)return undefined; + const component=(src,op,dst,map)=>{ + const operation=BLEND_OP[op]||'add'; + // WebGPU min / max ignore the factors and require one. + if(operation==='min'||operation==='max')return {operation,srcFactor:'one',dstFactor:'one'}; + return {operation,srcFactor:map[src]||'zero',dstFactor:map[dst]||'zero'}; + }; + return {color:component(cs,cop,cd,BLEND_FACTOR),alpha:component(as,aop,ad,BLEND_ALPHA_FACTOR)}; +} + +function parsePipelineDescription(w){ + return {vertexShader:w[0],pixelShader:w[1],topology:w[2],cullMode:w[3],frontFaceCw:w[4],depthCompare:w[5],depthWrite:w[6], + stencil:w[7],stencilMasks:w[8],colorFormats:Array.from(w.subarray(9,13)),colorWriteMasks:w[13], + blendControl:Array.from(w.subarray(14,18)),depthFormat:w[18],msaaSamples:w[19]}; +} + +function parseRenderTargets(w){ + return {surfacePitch:w[0],msaaSamples:w[1],height:w[2],colorBase:Array.from(w.subarray(3,7)), + colorFormat:Array.from(w.subarray(7,11)),depthBase:w[11],depthFormat:w[12]}; +} + +const DRAW_HEADER_WORDS=26; +function parseDrawHeader(w){ + const f=new Float32Array(w.buffer,w.byteOffset,DRAW_HEADER_WORDS); + return {pipeline:w[0],viewport:Array.from(w.subarray(1,5)),depthRange:[f[5],f[6]],scissor:Array.from(w.subarray(7,11)), + stencilReference:w[11],blendConstant:[f[12],f[13],f[14],f[15]],systemWords:w[16],floatVertexWords:w[17], + floatPixelWords:w[18],boolLoopWords:w[19],fetchWords:w[20],indexFormat:w[21],vertexCount:w[22], + vertexTextureMask:w[23],pixelTextureMask:w[24],bindingWords:w[25]}; +} + +// Resource declarations of Naga's WGSL: group, binding, kind and type. +export function parseWgslBindings(wgsl){ + const out=[]; + const re=/@group\((\d+)\)\s*@binding\((\d+)\)\s*var(?:<([^>]*)>)?\s+\w+\s*:\s*([^;]+);/g; + for(let m;(m=re.exec(wgsl));){ + const group=+m[1],binding=+m[2],space=(m[3]||'').replace(/\s/g,''),type=m[4].trim(); + const decl={group,binding,type}; + if(space.startsWith('storage')){decl.kind='storage';decl.write=space.includes('read_write');} + else if(space==='uniform')decl.kind='uniform'; + else if(type==='sampler'||type==='sampler_comparison'){decl.kind='sampler';decl.comparison=type==='sampler_comparison';} + else if(type.startsWith('texture_')){ + decl.kind='texture'; + const t=/^texture_(depth_)?(multisampled_)?(1d|2d_array|2d|3d|cube_array|cube)(?:<(\w+)>)?/.exec(type); + if(!t)throw new Error(`unsupported WGSL texture type ${type}`); + decl.viewDimension=t[3].replace('_','-'); + decl.sampleType=t[1]?'depth':t[4]==='i32'?'sint':t[4]==='u32'?'uint':'float'; + }else decl.kind='unknown'; + out.push(decl); + } + return out; +} + +// A CPU-side ring written to a GPU buffer in one writeBuffer on flush. +class XenosRing{ + constructor(device,label,usage,size,align=4){ + this.device=device;this.size=size;this.align=align; + this.buffer=device.createBuffer({label,size,usage:usage|BUFFER_USAGE.COPY_DST}); + this.cpu=new Uint8Array(size);this.offset=0; + } + fits(bytes){return this.offset+((bytes+this.align-1)&~(this.align-1))<=this.size;} + push(bytes){ + const at=this.offset; + this.cpu.set(bytes,at); + this.offset=at+((bytes.byteLength+this.align-1)&~(this.align-1)); + return at; + } + flush(){ + if(this.offset)this.device.queue.writeBuffer(this.buffer,0,this.cpu,0,this.offset); + this.offset=0; + } +} + +// The five constant buffers of a draw at dynamic offsets (Xenia's uniform +// buffer pool). Bindings are 4 KiB windows: the largest constant buffer +// (256 float4 registers) fits, and the ring keeps 4 KiB of slack at its end. +const CONSTANT_WINDOW=4096; +class XenosUniformRing extends XenosRing{ + constructor(device){ + const align=device.limits.minUniformBufferOffsetAlignment||256; + super(device,'Render360 constants',BUFFER_USAGE.UNIFORM,8*1024*1024+CONSTANT_WINDOW,align); + this.limit=8*1024*1024; + } + fits(constants){ + let total=0;for(const c of constants)total+=(c.byteLength+this.align-1)&~(this.align-1); + return this.offset+total<=this.limit; + } + push(words){return super.push(new Uint8Array(words.buffer,words.byteOffset,words.byteLength));} + bindGroup(layout){ + return this.device.createBindGroup({label:'Render360 constants',layout, + entries:[0,1,2,3,4].map(b=>({binding:b,resource:{buffer:this.buffer,offset:0,size:CONSTANT_WINDOW}}))}); + } +} + +// SPIR-V without NonReadable decorations (OpDecorate / OpMemberDecorate 25). +export function stripNonReadable(words){ + const out=Array.from(words.subarray(0,5)); + for(let i=5;i>>16,op=words[i]&0xFFFF; + if(!n)break; + const drop=(op===71&&words[i+2]===25)||(op===72&&words[i+3]===25); + if(!drop)for(let k=0;k src: array;\n`; + const index=`let i = id.x + id.y * 65535u * 64u; if (i >= arrayLength(&src)) { return; }`; + if(mode>=5){ + const conv=mode===5?'vec2(f32(v & 0xFFFFu), f32(v >> 16u)) / 65535.0' + :'max(vec2(f32((bitcast(v) << 16u) >> 16u), f32(bitcast(v) >> 16u)) / 32767.0, vec2(-1.0))'; + return `${head}@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + ${index} let v = src[i]; src[i] = pack2x16float(${conv}); }`; + } + const unpack={ + 1:'vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 63u) / 63.0, f32((t >> 11u) & 31u) / 31.0, 1.0)', + 2:'vec4(f32(t & 31u) / 31.0, f32((t >> 10u) & 63u) / 63.0, f32((t >> 5u) & 31u) / 31.0, 1.0)', + 3:'vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 31u) / 31.0, f32((t >> 10u) & 31u) / 31.0, f32(t >> 15u))', + 4:'vec4(f32(t & 15u), f32((t >> 4u) & 15u), f32((t >> 8u) & 15u), f32(t >> 12u)) / 15.0'}[mode]; + return `${head}@group(0) @binding(1) var dst: array; +fn texel(t: u32) -> u32 { return pack4x8unorm(${unpack}); } +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + ${index} let v = src[i]; dst[2u * i] = texel(v & 0xFFFFu); dst[2u * i + 1u] = texel(v >> 16u); }`; +} + +// EDRAM tile geometry of a host render target in pixels (80x16 32bpp +// samples per tile, 40x16 at 64bpp; 2x MSAA doubles Y, 4x also X). +function tileGeometry(pitch,msaa,is64bpp){ + const sx=msaa>=2?2:1,sy=msaa>=1?2:1; + const tileWidth=(is64bpp?40:80)/sx,tileHeight=16/sy; + return {is64bpp,tileWidth,tileHeight,pitchTiles:Math.ceil(pitch/tileWidth)}; +} + +function float7e3To32(f10){ + f10&=0x3FF;if(!f10)return 0; + let mantissa=f10&0x7F,exponent=f10>>>7; + if(!exponent){let lz=7-(31-Math.clz32(mantissa));exponent=1-lz;mantissa=(mantissa<>>0]).buffer)[0]; +} +function float20e4To32(f24){ + f24&=0xFFFFFF;if(!f24)return 0; + let mantissa=f24&0xFFFFF,exponent=f24>>>20; + if(!exponent){let lz=20-(31-Math.clz32(mantissa));exponent=1-lz;mantissa=(mantissa<>>0]).buffer)[0]; +} +function halfToFloat(h){ + const s=h&0x8000?-1:1,e=(h>>>10)&31,m=h&1023; + if(!e)return s*m*2**-24;if(e===31)return m?NaN:s*Infinity; + return s*(1+m/1024)*2**(e-15); +} + +// Guest clear values to host clear colors (VulkanRenderTargetCache), for the +// host formats render360 picks (16-bit fixed formats stored as float in +// Xenia's -1...1 host scale). +function colorClearValue(format,lo,hi){ + const v=BigInt(lo>>>0)|(BigInt(hi>>>0)<<32n),bits=(shift,n)=>Number((v>>BigInt(shift))&((1n<Math.max(((x<<16)>>16)/32767,-1); + switch(format){ + case 0:case 1:return {r:bits(0,8)/255,g:bits(8,8)/255,b:bits(16,8)/255,a:bits(24,8)/255}; + case 2:case 10:return {r:bits(0,10)/1023,g:bits(10,10)/1023,b:bits(20,10)/1023,a:bits(30,2)/3}; + case 3:case 12:return {r:float7e3To32(bits(0,10)),g:float7e3To32(bits(10,10)),b:float7e3To32(bits(20,10)),a:bits(30,2)/3}; + case 4:return {r:s16(bits(0,16)),g:s16(bits(16,16)),b:0,a:0}; + case 5:return {r:s16(bits(0,16)),g:s16(bits(16,16)),b:s16(bits(32,16)),a:s16(bits(48,16))}; + case 6:return {r:halfToFloat(bits(0,16)),g:halfToFloat(bits(16,16)),b:0,a:0}; + case 7:return {r:halfToFloat(bits(0,16)),g:halfToFloat(bits(16,16)),b:halfToFloat(bits(32,16)),a:halfToFloat(bits(48,16))}; + case 14:{const f=new Float32Array(new Uint32Array([lo>>>0]).buffer)[0];return {r:f,g:0,b:0,a:0};} + case 15:{const f=new Float32Array(new Uint32Array([lo>>>0,hi>>>0]).buffer);return {r:f[0],g:f[1],b:0,a:0};} + default:return {r:0,g:0,b:0,a:0}; + } +} +function depthClearValue(format,value,hostFormat){ + const d24=(value>>>8)&0xFFFFFF; + // D24FS8: Xenia's host depth takes [0, 2) to [0, 1). + const depth=format===1?float20e4To32(d24)*0.5:d24/0xFFFFFF; + return {depth:Math.min(1,Math.max(0,depth)),stencil:value&0xFF}; +} + +const CLEAR_SHADER=`@group(0) @binding(0) var value: vec4; +@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + return vec4(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0, 0.0, 1.0); +} +@fragment fn fs_color() -> @location(0) vec4 { return value; } +@fragment fn fs_depth() -> @builtin(frag_depth) f32 { return value.x; }`; + +// EDRAM dump of one host render target region (WGSL port of edram.xesli +// XeEdramOffsetBytes and the EDRAM pixel formats of pixel_formats.xesli). +function edramDumpShader(depth){ + return `struct Dump { + base_tiles: u32, pitch_tiles: u32, msaa: u32, format: u32, + x0: u32, y0: u32, width: u32, height: u32, is_64bpp: u32, depth_float32: u32, pad0: u32, pad1: u32, +} +@group(0) @binding(0) var edram: array; +@group(0) @binding(1) var dump: Dump; +${depth?`@group(0) @binding(2) var depth_texture: texture_depth_2d; +@group(0) @binding(3) var stencil_texture: texture_2d;`:`@group(0) @binding(2) var color_texture: texture_2d;`} + +fn edram_offset_dwords(pixel: vec2, sample: u32) -> u32 { + var s = pixel << vec2(select(0u, 1u, dump.msaa >= 2u), select(0u, 1u, dump.msaa >= 1u)); + s += (vec2(sample) >> vec2(1u, 0u)) & vec2(1u); + let ints_log2 = dump.is_64bpp; + let tile_size = vec2(80u >> ints_log2, 16u); + let tile = s / tile_size; + var base = dump.base_tiles + tile.y * dump.pitch_tiles + tile.x; + s -= tile * tile_size; + ${depth?`let half = tile_size.x >> 1u; + s.x = select(s.x + half, s.x - half, s.x >= half);`:''} + let address = base * 1280u + ((s.y * tile_size.x + s.x) << ints_log2); + return address % (1280u * 2048u); +} + +fn f32_to_7e3(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x41FF8000u) { return 0x3FFu; } + if (u < 0x3E800000u) { + let shift = min(125u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC2000000u; + } + u += 0x7FFFu + ((u >> 16u) & 1u); + return (u >> 16u) & 0x3FFu; +} +fn f32_to_20e4(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x3FFFFFF8u) { return 0xFFFFFFu; } + if (u < 0x38800000u) { + let shift = min(113u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC8000000u; + } + u += 3u + ((u >> 3u) & 1u); + return (u >> 3u) & 0xFFFFFFu; +} +fn s16(f: f32) -> u32 { return u32(i32(round(clamp(f, -1.0, 1.0) * 32767.0))) & 0xFFFFu; } +fn to_unorm(f: f32, bits: u32) -> u32 { let m = f32((1u << bits) - 1u); return u32(round(clamp(f, 0.0, 1.0) * m)); } + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3) { + if (id.x >= dump.width || id.y >= dump.height) { return; } + let pixel = vec2(dump.x0 + id.x, dump.y0 + id.y); + var lo = 0u; + var hi = 0u; + ${depth?`let d = textureLoad(depth_texture, vec2(pixel), 0); + let stencil = textureLoad(stencil_texture, vec2(pixel), 0).x & 0xFFu; + // D24FS8: Xenia's host depth takes [0, 2) to [0, 1). + let d24 = select(u32(round(clamp(d, 0.0, 1.0) * 16777215.0)), f32_to_20e4(d * 2.0), dump.format == 1u); + lo = (d24 << 8u) | stencil;`:`let c = textureLoad(color_texture, vec2(pixel), 0); + switch dump.format { + case 0u, 1u: { lo = pack4x8unorm(c); } + case 2u, 10u: { lo = to_unorm(c.x, 10u) | (to_unorm(c.y, 10u) << 10u) | (to_unorm(c.z, 10u) << 20u) | (to_unorm(c.w, 2u) << 30u); } + case 3u, 12u: { lo = f32_to_7e3(c.x) | (f32_to_7e3(c.y) << 10u) | (f32_to_7e3(c.z) << 20u) | (to_unorm(c.w, 2u) << 30u); } + case 4u: { lo = s16(c.x) | (s16(c.y) << 16u); } + case 5u: { lo = s16(c.x) | (s16(c.y) << 16u); hi = s16(c.z) | (s16(c.w) << 16u); } + case 6u: { lo = pack2x16float(c.xy); } + case 7u: { lo = pack2x16float(c.xy); hi = pack2x16float(c.zw); } + case 14u: { lo = bitcast(c.x); } + case 15u: { lo = bitcast(c.x); hi = bitcast(c.y); } + default: { lo = pack4x8unorm(c); } + }`} + // One host sample: every guest sample of the pixel gets its value. + let samples = select(select(1u, 2u, dump.msaa == 1u), 4u, dump.msaa >= 2u); + for (var s = 0u; s < samples; s++) { + let o = edram_offset_dwords(pixel, s); + edram[o] = lo; + if (dump.is_64bpp != 0u) { edram[o + 1u] = hi; } + } +}`; +} + +const PRESENT_SHADER=`struct Out { @builtin(position) position: vec4, @location(0) uv: vec2 } +@vertex fn vs(@builtin(vertex_index) i: u32) -> Out { + let p = vec2(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0); + return Out(vec4(p, 0.0, 1.0), vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5)); +} +@group(0) @binding(0) var front: texture_2d_array; +@group(0) @binding(1) var front_sampler: sampler; +// Host swizzle of the swap fetch constant (3 bits per component: 0-3 RGBA, +// 4 zero, 5 one), as Xenia's swap texture view applies it. +@group(0) @binding(2) var swizzle: vec4; +fn component(t: vec4, s: u32) -> f32 { + if (s >= 5u) { return 1.0; } + if (s == 4u) { return 0.0; } + return t[s]; +} +@fragment fn fs(i: Out) -> @location(0) vec4 { + let t = textureSample(front, front_sampler, i.uv, 0); + let s = swizzle.x; + return vec4(component(t, s & 7u), component(t, (s >> 3u) & 7u), component(t, (s >> 6u) & 7u), 1.0); +}`; diff --git a/render360-webgpu-play.mjs b/render360-webgpu-play.mjs new file mode 100644 index 00000000..d9504bf8 --- /dev/null +++ b/render360-webgpu-play.mjs @@ -0,0 +1,61 @@ +// Render360 WebGPU play path: the core records draws, textures and resolves +// for render360-webgpu-backend.mjs (Xenia's Vulkan backend ported to +// WebGPU) and the software renderer does no work; each frame the stream is +// replayed and the swapped front buffer is drawn to the canvas. +// +// Opt-in while it is verified against the software renderer: `?gpu=xenos` +// in the page URL, or config.renderer === 'webgpu-xenos'. +import {XenosWebGpuBackend} from './render360-webgpu-backend.mjs'; + +export function webGpuPlayPathRequested(config){ + if(config?.renderer==='webgpu-xenos')return true; + try{return new URLSearchParams(globalThis.location?.search||'').get('gpu')==='xenos';}catch{return false;} +} + +export async function createXenosWebGpuPlayPath(bootstrap,canvas){ + const e=bootstrap.exports; + if(typeof e.r360_gpu_set_mode!=='function')throw new Error('core has no WebGPU recorder'); + const adapter=await navigator.gpu?.requestAdapter({powerPreference:'high-performance'}); + if(!adapter)throw new Error('no WebGPU adapter'); + globalThis.render360GpuAdapterInfo={vendor:adapter.info?.vendor,architecture:adapter.info?.architecture,device:adapter.info?.device,description:adapter.info?.description}; + const device=await adapter.requestDevice({ + requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)), + requiredLimits:{maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); + const context=canvas.getContext('webgpu'); + const format=navigator.gpu.getPreferredCanvasFormat(); + context.configure({device,format,alphaMode:'opaque'}); + const backend=await new XenosWebGpuBackend(device,e).init(); + let lost=null,gpuMs=null,pendingGpu=false; + device.lost.then(info=>{lost=info?.message||'device lost';}); + e.r360_gpu_set_mode(1); + e.r360_xenos_soft_set_rasterize?.(0); + // Replays at least this often (loading screens can go long without swaps; + // the stream holds uploaded pages until it is replayed). + const maxPendingWords=4*1024*1024; + return { + backend, + get lost(){return lost;}, + slice(){if(!lost&&(e.r360_gpu_stream_words()>>>0)>maxPendingWords)backend.replay();}, + // Submit-to-completion time of the last frame's GPU work (ms), once. + takeGpuMs(){const ms=gpuMs;gpuMs=null;return ms;}, + frame(){ + if(lost)return false; + const t0=performance.now(); + backend.replay(); + const front=backend.frontTexture; + if(front&&(canvas.width!==front.width||canvas.height!==front.height)){canvas.width=front.width;canvas.height=front.height;} + canvas.style.display='block'; + const presented=backend.present(context,format); + if(!pendingGpu){ + pendingGpu=true; + device.queue.onSubmittedWorkDone().then(()=>{gpuMs=performance.now()-t0;pendingGpu=false;},()=>{pendingGpu=false;}); + } + return presented; + }, + destroy(){ + e.r360_gpu_set_mode(0); + e.r360_xenos_soft_set_rasterize?.(1); + try{device.destroy();}catch{} + }, + }; +} diff --git a/render360_xenia_core.cpp b/render360_xenia_core.cpp index d5070bcb..dd365f8d 100644 --- a/render360_xenia_core.cpp +++ b/render360_xenia_core.cpp @@ -642,8 +642,8 @@ __attribute__((visibility("default"))) uint32_t r360_io_capacity() { return R360_IO_CAPACITY; } __attribute__((visibility("default"))) -uint32_t r360_io_ptr() { - return static_cast(reinterpret_cast(io_buffer)); +uintptr_t r360_io_ptr() { + return reinterpret_cast(io_buffer); } __attribute__((visibility("default"))) @@ -820,8 +820,8 @@ R360_STFS_GETTER(r360_stfs_request_kind, request_kind) #undef R360_STFS_GETTER __attribute__((visibility("default"))) -uint32_t r360_stfs_display_name_ptr() { - return static_cast(reinterpret_cast(stfs_display_name)); +uintptr_t r360_stfs_display_name_ptr() { + return reinterpret_cast(stfs_display_name); } __attribute__((visibility("default"))) uint32_t r360_stfs_display_name_length() { return stfs_display_name_length; } @@ -836,9 +836,9 @@ __attribute__((visibility("default"))) uint32_t r360_stfs_request_offset_hi() { return static_cast(stfs_state.request_offset >> 32); } __attribute__((visibility("default"))) -uint32_t r360_stfs_entry_name_ptr(uint32_t index) { +uintptr_t r360_stfs_entry_name_ptr(uint32_t index) { if (index >= stfs_state.entry_count) return 0u; - return static_cast(reinterpret_cast(stfs_entries[index].name)); + return reinterpret_cast(stfs_entries[index].name); } __attribute__((visibility("default"))) uint32_t r360_stfs_entry_name_length(uint32_t index) { diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index c29e8911..ff193155 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -1,5 +1,6 @@ #include "guest_fibers.h" +#include #include #include #include @@ -20,10 +21,28 @@ extern "C" char __stack_low; // The R360_FIBER_LOCAL section bounds (wasm-ld start/stop symbols). extern "C" char __start_r360_fiber[]; extern "C" char __stop_r360_fiber[]; +#define R360_FIBER_SWITCHING 1 +#elif defined(R360_NATIVE) +// Native build (native/build-native.sh): every guest thread is a pthread, and +// a baton (one mutex + condition variable) lets exactly one of them run at a +// time, so scheduling stays cooperative and deterministic like the browser's. +// What the JS driver (render360-guest-fibers.mjs) does after an Asyncify +// unwind is done in place by the thread that leaves (NativeDriveSwitch), and +// a resumed thread re-enters the function it left from, exactly as an +// Asyncify rewind would. The R360_FIBER_LOCAL block is a Mach-O section that +// is swapped the same way as the wasm section. +#include +#include +#include +extern "C" char __start_r360_fiber[] __asm("section$start$__DATA$r360_fiber"); +extern "C" char __stop_r360_fiber[] __asm("section$end$__DATA$r360_fiber"); +#define R360_FIBER_SWITCHING 1 #endif extern "C" { uint32_t r360_guest_thread_current(); +uint32_t r360_kernel_thread_wait(uint32_t thread, uint32_t field); +uint32_t r360_guest_thread_kthread(uint32_t handle); uint32_t r360_guest_thread_set_current(uint32_t handle); uint32_t r360_guest_thread_runnable_list(uint32_t* out, uint32_t capacity); uint32_t r360_guest_thread_entry(uint32_t handle); @@ -108,19 +127,19 @@ uint64_t HostMillis() { } size_t LocalsSize() { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) return size_t(__stop_r360_fiber - __start_r360_fiber); #else return 0; #endif } void SaveLocals(Fiber& fiber) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) fiber.locals.assign(__start_r360_fiber, __stop_r360_fiber); #endif } void RestoreLocals(const Fiber& fiber) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) const auto& image = fiber.locals.empty() ? g_pristine_locals : fiber.locals; if (image.size() == LocalsSize()) { std::memcpy(__start_r360_fiber, image.data(), image.size()); @@ -198,14 +217,31 @@ bool PickTarget(uint32_t from, uint32_t* target, bool preempting = false) { from >= n ? 0 : g_fibers[from].vruntime + (from == g_current ? HIRTotalInstructions() - g_run_start : 0); + // Bounded lag (as CFS bounds it): a thread that has run far more than the + // others is passed over for at most kMaxLag instructions of theirs. On the + // console every thread runs on its own hardware thread, so a busy thread is + // never starved by an idle-looping one (Banjo-Tooie's main thread waited + // ~50B instructions for a lock while a timer thread spun Sleep(0)). + constexpr uint64_t kMaxLag = 8ull * kPreemptQuantum; + bool any = false; + uint64_t min_count = 0; + for (uint32_t index = 0; index < n; ++index) { + if (index == from) continue; + const Fiber& fiber = g_fibers[index]; + if (!Eligible(fiber) || (index != 0 && !ThreadRunnable(fiber.thread))) continue; + if (!any || fiber.vruntime < min_count) min_count = fiber.vruntime; + any = true; + } + if (any && from < n && from_count < min_count) min_count = from_count; bool found = false; uint32_t best = 0; for (uint32_t step = 1; step <= n; ++step) { const uint32_t index = (from + step) % n; if (index == from) continue; - const Fiber& fiber = g_fibers[index]; + Fiber& fiber = g_fibers[index]; if (!Eligible(fiber)) continue; if (index != 0 && !ThreadRunnable(fiber.thread)) continue; + if (fiber.vruntime > min_count + kMaxLag) fiber.vruntime = min_count + kMaxLag; if (!found || fiber.vruntime < g_fibers[best].vruntime) best = index; found = true; } @@ -221,6 +257,12 @@ bool PickTarget(uint32_t from, uint32_t* target, bool preempting = false) { } bool EnsureFiberMemory(Fiber& fiber, bool needs_stack) { +#if defined(R360_NATIVE) + // Each native fiber is a pthread with its own stack; no Asyncify buffer. + (void)fiber; + (void)needs_stack; + return true; +#endif if (!fiber.asyncify) { fiber.asyncify = static_cast(std::malloc(kFiberAsyncifyBytes)); if (!fiber.asyncify) return false; @@ -238,6 +280,153 @@ void ArmAsyncifyBuffer(Fiber& fiber) { header[1] = static_cast(reinterpret_cast(fiber.asyncify + kFiberAsyncifyBytes)); } +#if defined(R360_NATIVE) +// --- Native baton (see the comment at the top of this file) --------------- +inline void r360_asyncify_stop_rewind() {} +} // namespace +} // namespace render360::xenia_web +extern "C" uint32_t r360_fiber_prepare(); +extern "C" uint32_t r360_fiber_entry(); +namespace render360::xenia_web { +namespace { +// Guest call chains live on the host stack (the browser gives each fiber its +// own C stack); native frames are larger, so give every guest thread plenty. +// Pages are only committed when touched. +constexpr size_t kNativeFiberStackBytes = 64u * 1024u * 1024u; +std::mutex g_native_mutex; +std::condition_variable g_native_cv; +uint32_t g_native_baton = 0; // fiber index allowed to run +uint64_t g_native_generation = 0; // one per title run +bool g_native_run_done = false; +uint32_t g_native_run_result = 0; +uint32_t g_native_run_stopped = 0; +uint32_t g_native_slice_ms = 0; +uint32_t (*g_native_on_slice)(void*) = nullptr; +void* g_native_slice_user = nullptr; + +// Blocks until fiber `index` holds the baton in run `generation`. A thread +// left behind when a run ends never wakes again (its generation is over). +void NativeWaitForBaton(uint32_t index, uint64_t generation) { + std::unique_lock lock(g_native_mutex); + g_native_cv.wait(lock, [&] { + return g_native_generation == generation && g_native_baton == index && !g_native_run_done; + }); +} + +void NativeEndRun(uint32_t result, uint32_t stopped) { + std::lock_guard lock(g_native_mutex); + g_native_run_done = true; + g_native_run_result = result; + g_native_run_stopped = stopped; + g_native_baton = UINT32_MAX; + g_native_cv.notify_all(); +} + +void NativePassBaton(uint32_t index) { + std::lock_guard lock(g_native_mutex); + g_native_baton = index; + g_native_cv.notify_all(); +} + +struct NativeThreadStart { + uint32_t index; + uint64_t generation; + uint32_t (*primary)(void*); + void* user; +}; + +bool NativeSpawn(NativeThreadStart* start, void* (*body)(void*)) { + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, kNativeFiberStackBytes); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_t thread; + const bool ok = pthread_create(&thread, &attr, body, start) == 0; + pthread_attr_destroy(&attr); + return ok; +} + +void NativeDriveSwitch(); + +// Root of a title-created guest thread (the JS driver's r360_fiber_entry call). +void* NativeFiberThreadMain(void* raw) { + auto* start = static_cast(raw); + const uint32_t index = start->index; + const uint64_t generation = start->generation; + delete start; + pthread_setname_np("r360-guest"); + NativeWaitForBaton(index, generation); + const uint32_t result = r360_fiber_entry(); + // As in the JS driver: a title thread that finished queued the next fiber; + // one that stopped on a blocker ends the run. + if (g_current == 0 || !g_switch_pending) { + NativeEndRun(result, 0); + return nullptr; + } + NativeDriveSwitch(); + return nullptr; +} + +// The JS driver's step after an unwind: prepare the switch target and start +// (fresh fiber: a new thread) or resume it (pass the baton). +void NativeDriveSwitch() { + const uint32_t kind = r360_fiber_prepare(); + if (kind == 0) { + std::fprintf(stderr, "R360_FIBER_STOP native: switch without a target\n"); + NativeEndRun(0, 2); + return; + } + const uint32_t next = g_current; + if (kind == 1) { + { + std::lock_guard lock(g_native_mutex); + g_native_baton = next; + } + auto* start = new NativeThreadStart{next, g_native_generation, nullptr, nullptr}; + if (!NativeSpawn(start, NativeFiberThreadMain)) { + delete start; + std::fprintf(stderr, "R360_FIBER_STOP native: pthread_create failed\n"); + NativeEndRun(0, 2); + } + return; + } + NativePassBaton(next); +} + +// Called by the running guest thread when it leaves (SwitchTo): gives the +// host its slice callback if a host yield is due, hands over, and waits until +// it is scheduled again. Returns with this fiber's state restored. +void NativeLeave() { + const uint32_t me = g_current; + const uint64_t generation = g_native_generation; + if (g_host_yield) { + g_host_yield = false; + if (g_native_on_slice && g_native_on_slice(g_native_slice_user)) { + // The host stopped the run. This thread is abandoned mid-call. + NativeEndRun(0, 1); + NativeWaitForBaton(me, generation); + return; + } + if (g_native_slice_ms) g_host_slice_deadline_ms = HostMillis() + g_native_slice_ms; + } + NativeDriveSwitch(); + NativeWaitForBaton(me, generation); +} + +void* NativePrimaryThreadMain(void* raw) { + auto* start = static_cast(raw); + const uint64_t generation = start->generation; + uint32_t (*primary)(void*) = start->primary; + void* user = start->user; + delete start; + pthread_setname_np("r360-guest-primary"); + NativeWaitForBaton(0, generation); + const uint32_t result = primary(user); + NativeEndRun(result, 0); + return nullptr; +} +#endif + // Leaves the current fiber for `target`: snapshot its state and unwind the // wasm stack back to the JS driver, which then starts or rewinds the target. void SwitchTo(uint32_t target, FiberState leaving_state, uint32_t kind) { @@ -259,6 +448,22 @@ void SwitchTo(uint32_t target, FiberState leaving_state, uint32_t kind) { g_switch_pending = true; ++g_switches; r360_asyncify_start_unwind(current.asyncify); +#elif defined(R360_NATIVE) + Fiber& current = g_fibers[g_current]; + current.leave_kind = kind; + if (kind < 5) ++current.leave_counts[kind]; + current.leave_pc = HIRLastSourceAddress(); + current.leave_call = (r360_kernel_import_last_module() << 16) | + (r360_kernel_import_last_ordinal() & 0xFFFFu); + current.instructions += HIRTotalInstructions() - g_run_start; + current.vruntime += HIRTotalInstructions() - g_run_start; + current.state = leaving_state; + current.progress_mark = g_progress; + SaveLocals(current); + g_target = target; + g_switch_pending = true; + ++g_switches; + NativeLeave(); #else (void)target; (void)leaving_state; @@ -275,13 +480,16 @@ void GuestFiberNoteProgress() { ++g_progress; } uintptr_t GuestFiberStackLow() { #if defined(__wasm__) return g_stack_low ? g_stack_low : reinterpret_cast(&__stack_low); +#elif defined(R360_NATIVE) + pthread_t self = pthread_self(); + return reinterpret_cast(pthread_get_stackaddr_np(self)) - pthread_get_stacksize_np(self); #else return 0; #endif } bool GuestFiberYield(bool blocked) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { // Resumed: the driver restored this fiber's state and rewound into here. g_rewinding = false; @@ -301,6 +509,9 @@ bool GuestFiberYield(bool blocked) { return false; } SwitchTo(target, blocked ? kFiberBlocked : kFiberReady, blocked ? 1u : 2u); +#if defined(R360_NATIVE) + return GuestFiberYield(blocked); // resumed: re-enter as a rewind would +#endif return false; // unwinding; the value is not observed #else (void)blocked; @@ -310,12 +521,35 @@ bool GuestFiberYield(bool blocked) { bool GuestInterruptActive() { return g_in_interrupt; } +// Scheduler state for diagnostics (r360_jit_diag). +void GuestFiberDiagnostic(char* out, size_t size) { + uint32_t ready = 0, blocked = 0; + for (const auto& f : g_fibers) { + if (f.state == kFiberReady) ++ready; + if (f.state == kFiberBlocked) ++blocked; + } + int n = std::snprintf(out, size, "fibers=%u current=%u ready=%u blocked=%u clock_ms=%llu |", + uint32_t(g_fibers.size()), g_current, ready, blocked, + (unsigned long long)(GuestClockNanoseconds() / 1000000ull)); + // Per fiber: state, last kernel call (module<<16|ordinal), wake deadline, + // guest PC when it left. + for (size_t i = 0; i < g_fibers.size() && n > 0 && size_t(n) < size; ++i) { + const Fiber& f = g_fibers[i]; + // Kernel wait record: object, reason, caller. + n += std::snprintf(out + n, size - size_t(n), " %u:kt=%08x:%u/%llu/obj=%08x/r=%u/lr=%08x", uint32_t(i), + r360_guest_thread_kthread(f.thread), + uint32_t(f.state), (unsigned long long)(f.wake_ns / 1000000ull), + r360_kernel_thread_wait(f.thread, 1), r360_kernel_thread_wait(f.thread, 4), + r360_kernel_thread_wait(f.thread, 5)); + } +} + // Xenia blocks a sleeping or timed-waiting XThread on a host wait until its // deadline; here the fiber blocks with a guest-clock deadline and another // fiber runs. Returns true when resumed (the caller re-checks its condition), // false when no other fiber can run now (the caller idles: GuestFiberIdle). bool GuestFiberSleepUntil(uint64_t deadline_ns) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { g_rewinding = false; r360_asyncify_stop_rewind(); @@ -335,6 +569,9 @@ bool GuestFiberSleepUntil(uint64_t deadline_ns) { return false; } SwitchTo(target, kFiberBlocked, 1u); +#if defined(R360_NATIVE) + return GuestFiberSleepUntil(deadline_ns); // resumed +#endif return false; // unwinding; the value is not observed #else (void)deadline_ns; @@ -347,6 +584,9 @@ bool GuestFiberSleepUntil(uint64_t deadline_ns) { // steps no longer than a vblank period, delivering the interrupts that fall // in between (their handlers may wake a thread). Returns false if idling is // not possible here. +// Guest time spent idle (nothing runnable): the emulator was ahead of the +// guest's real-time needs (render360-perf-overlay.mjs headroom). +uint64_t g_idle_ns = 0; bool GuestFiberIdle(uint64_t deadline_ns) { if (!g_enabled || g_in_interrupt) return false; const uint64_t now = GuestClockNanoseconds(); @@ -359,12 +599,21 @@ bool GuestFiberIdle(uint64_t deadline_ns) { constexpr uint64_t kMaxIdleStepNs = 4000000ull; // 4 ms if (until > now + kMaxIdleStepNs) until = now + kMaxIdleStepNs; if (!GuestClockIdleUntil(until)) return false; + g_idle_ns += until - now; DeliverGuestInterruptsNow(); return true; } +// Verbose runtime tracing from an instruction count on (r360_trace_verbose_from): +// checked here because a stuck guest may never return to the host to turn it on. +uint64_t g_trace_from_instructions = 0; + void GuestFiberHostYieldIfDue() { -#if defined(__wasm__) + if (g_trace_from_instructions && HIRTotalInstructions() >= g_trace_from_instructions) { + g_trace_from_instructions = 0; + g_r360_verbose_trace = true; + } +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { // Resumed after the page got its turn. g_rewinding = false; @@ -382,9 +631,15 @@ void GuestFiberHostYieldIfDue() { EnsureFiberMemory(g_fibers[target], target != 0)) { ++g_preemptions; SwitchTo(target, kFiberReady, 3u); +#if defined(R360_NATIVE) + GuestFiberHostYieldIfDue(); // resumed +#endif return; } } + R360_VERBOSE_TRACE("R360_HOST_YIELD_CHECK fiber=%u interrupt=%u deadline=%llu now=%llu\n", + g_current, g_in_interrupt ? 1u : 0u, + (unsigned long long)g_host_slice_deadline_ms, (unsigned long long)HostMillis()); if (!g_enabled || g_in_interrupt || !g_host_slice_deadline_ms || g_current >= g_fibers.size() || HostMillis() < g_host_slice_deadline_ms) { return; @@ -393,12 +648,15 @@ void GuestFiberHostYieldIfDue() { g_host_yield = true; ++g_host_yields; SwitchTo(g_current, kFiberReady, 4u); +#if defined(R360_NATIVE) + GuestFiberHostYieldIfDue(); // resumed after the host's turn +#endif #endif } bool RunGuestInterrupt(uint32_t address, uint32_t r3, uint32_t r4, uint32_t stack_top, uint32_t pcr) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (!g_enabled || g_in_interrupt || g_pristine_locals.size() != LocalsSize() || !address || !stack_top) { return false; @@ -452,7 +710,7 @@ uint32_t r360_fiber_reset(uint32_t enable) { rx::g_preemptions = 0; rx::g_enabled = enable != 0; if (!rx::g_enabled) return 0; -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) rx::g_pristine_locals.assign(__start_r360_fiber, __stop_r360_fiber); #endif rx::Fiber primary; @@ -472,6 +730,11 @@ uint32_t r360_fiber_set_host_slice(uint32_t milliseconds) { rx::g_host_slice_deadline_ms = milliseconds ? rx::HostMillis() + milliseconds : 0; return milliseconds; } +__attribute__((used, export_name("r360_trace_verbose_from"))) +uint32_t r360_trace_verbose_from(uint32_t millions) { + rx::g_trace_from_instructions = uint64_t(millions) * 1000000ull; + return millions; +} // 1 when the last unwind was a host time-slice yield (consumed by this call). uint32_t r360_fiber_take_host_yield() { const bool yielded = rx::g_host_yield; @@ -480,6 +743,8 @@ uint32_t r360_fiber_take_host_yield() { } uint32_t r360_fiber_host_yields() { return rx::g_host_yields; } uint32_t r360_fiber_preemptions() { return rx::g_preemptions; } +__attribute__((used, export_name("r360_fiber_idle_ms"))) +double r360_fiber_idle_ms() { return double(rx::g_idle_ns) / 1e6; } // Guest JIT frames (hir_wasm_jit.cpp) save their locals in the current // fiber's Asyncify buffer like Binaryen-instrumented functions: pushed on // unwind (after their callees), popped on rewind (before them). @@ -567,6 +832,8 @@ uint32_t r360_fiber_entry() { if (rx::g_current == 0 || rx::g_current >= rx::g_fibers.size()) return 0; const uint32_t handle = rx::g_fibers[rx::g_current].thread; const uint32_t entry = r360_guest_thread_entry(handle); + std::fprintf(stderr, "R360_FIBER_START fiber=%u thread=0x%08X entry=0x%08X minstr=%llu\n", rx::g_current, + handle, entry, static_cast(rx::HIRTotalInstructions() / 1000000ull)); rx::ResetHIRCorrectnessInitialState(); rx::ClearHIRCorrectnessInitialRegisterStrings(); rx::SetHIRCorrectnessInitialGPR(1, r360_guest_thread_stack_top(handle)); @@ -583,7 +850,12 @@ uint32_t r360_fiber_entry() { const bool returned = hir && r360_ppc_probe_correctness_status() == 3u; const bool exited = rx::FinishGuestThreadFiber( handle, returned, uint32_t(rx::GetHIRCorrectnessLastGPR(3))); - if (!exited) return hir ? hir : 1u; // stopped on a blocker: end the run + if (!exited) { + // Stopped on a blocker: end the run. + std::fprintf(stderr, "R360_FIBER_STOP fiber=%u thread=0x%08X hir=%u status=%u returned=%u\n", + rx::g_current, handle, hir, r360_ppc_probe_correctness_status(), returned ? 1u : 0u); + return hir ? hir : 1u; + } fiber.state = rx::kFiberDone; rx::GuestFiberNoteProgress(); uint32_t target = 0; @@ -593,7 +865,11 @@ uint32_t r360_fiber_entry() { target = 0; rx::g_force_fail = rx::g_fibers[0].state == rx::kFiberBlocked || rx::g_fibers[0].state == rx::kFiberReady; - if (!rx::g_force_fail) return hir ? hir : 1u; + if (!rx::g_force_fail) { + std::fprintf(stderr, "R360_FIBER_STOP no-target fiber=%u primary_state=%u\n", rx::g_current, + uint32_t(rx::g_fibers[0].state)); + return hir ? hir : 1u; + } } rx::g_target = target; rx::g_switch_pending = true; @@ -601,4 +877,51 @@ uint32_t r360_fiber_entry() { return hir ? hir : 1u; } +#if defined(R360_NATIVE) +// Native equivalent of runWithGuestFibers (render360-guest-fibers.mjs): runs +// `primary` (enters the title's primary thread) with guest-thread scheduling +// and returns its result, or the root result of the title thread the run +// ended on. slice_ms > 0 calls on_slice about every slice_ms of host time on +// the running guest thread (frames, input, telemetry); a nonzero return stops +// the run (*stopped = 1). Threads of a stopped run are abandoned, so the host +// should end the process before booting another title. +uint32_t r360_native_run_with_fibers(uint32_t (*primary)(void*), void* user, uint32_t slice_ms, + uint32_t (*on_slice)(void*), void* slice_user, + uint32_t* stopped) { + r360_fiber_reset(1); + uint64_t generation; + { + std::lock_guard lock(rx::g_native_mutex); + generation = ++rx::g_native_generation; + rx::g_native_baton = 0; + rx::g_native_run_done = false; + rx::g_native_run_result = 0; + rx::g_native_run_stopped = 0; + } + rx::g_native_slice_ms = on_slice ? slice_ms : 0; + rx::g_native_on_slice = on_slice; + rx::g_native_slice_user = slice_user; + r360_fiber_set_host_slice(rx::g_native_slice_ms); + auto* start = new rx::NativeThreadStart{0, generation, primary, user}; + if (!rx::NativeSpawn(start, rx::NativePrimaryThreadMain)) { + delete start; + r360_fiber_reset(0); + if (stopped) *stopped = 2; + return 0; + } + uint32_t result; + { + std::unique_lock lock(rx::g_native_mutex); + rx::g_native_cv.wait(lock, [] { return rx::g_native_run_done; }); + result = rx::g_native_run_result; + if (stopped) *stopped = rx::g_native_run_stopped; + } + r360_fiber_set_host_slice(0); + rx::g_native_on_slice = nullptr; + // Fiber bookkeeping stays readable (r360_fiber_*) until the next reset. + return result; +} +uint32_t r360_native_fiber_finish() { return r360_fiber_reset(0); } +#endif + } // extern "C" diff --git a/src/xenia_web_bootstrap/guest_fibers.h b/src/xenia_web_bootstrap/guest_fibers.h index c7b57301..b5318351 100644 --- a/src/xenia_web_bootstrap/guest_fibers.h +++ b/src/xenia_web_bootstrap/guest_fibers.h @@ -1,5 +1,6 @@ #pragma once +#include #include // Guest threads for the native HIR compatibility executor. @@ -37,6 +38,8 @@ uintptr_t GuestFiberStackLow(); bool RunGuestInterrupt(uint32_t address, uint32_t r3, uint32_t r4, uint32_t stack_top, uint32_t pcr); bool GuestInterruptActive(); +// Scheduler state as text, for diagnostics. +void GuestFiberDiagnostic(char* out, size_t size); // Browser time slicing: when the host slice set by the driver // (r360_fiber_set_host_slice) has run out, unwinds the running guest thread diff --git a/src/xenia_web_bootstrap/hir_correctness_executor.cpp b/src/xenia_web_bootstrap/hir_correctness_executor.cpp index 8a819898..177c9cfa 100644 --- a/src/xenia_web_bootstrap/hir_correctness_executor.cpp +++ b/src/xenia_web_bootstrap/hir_correctness_executor.cpp @@ -33,6 +33,8 @@ uint32_t r360_ppc_probe_loaded_size(); namespace render360::xenia_web { +void MaybeDeliverGuestInterrupts(); // kernel_xboxkrnl_services.cpp + bool g_r360_verbose_trace = false; namespace { @@ -1048,6 +1050,8 @@ bool ExecuteIndirect(uint64_t target, uint32_t flags, bool* reached_return, uint32_t g_debug_watch_address = 0; uint64_t g_total_instruction_budget = 0; uint64_t g_total_instructions = 0; +// Instructions run by this interpreter (the rest ran in generated code). +uint64_t g_interpreted_instructions = 0; uint64_t g_opcode_histogram[256] = {}; // executed HIR opcodes (run-title R360_OPHIST) // Guest address of the last SOURCE_OFFSET executed (diagnostics). uint32_t g_last_source_address = 0; @@ -1630,6 +1634,7 @@ HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder, break; } + ++g_interpreted_instructions; if (++g_total_instructions > g_total_instruction_budget && g_total_instruction_budget) { result.blocker_kind = kHIRBlockerInstructionLimit; @@ -1637,6 +1642,11 @@ HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder, supported = false; break; } + // Interpreted code polls like the guest JIT's backward branches: a + // loop in a function that was never compiled (one call that spins + // waiting for another thread, as in Banjo-Tooie's object table) would + // otherwise never deliver interrupts, preempt or return to the host. + if ((g_total_instructions & 4095u) == 0) MaybeDeliverGuestInterrupts(); ++g_opcode_histogram[instr->opcode->num & 0xFFu]; if (ExecuteFlaggedOperation(instr, values, &supported)) { if (!supported) { @@ -2234,6 +2244,16 @@ uint32_t r360_hir_set_total_instruction_budget(uint32_t millions) { render360::xenia_web::g_total_instruction_budget = uint64_t(millions) * 1000000ull; return millions; } +// Performance overlay counters (render360-perf-overlay.mjs), as doubles: +// 0 guest instructions, 1 interpreted instructions. +extern "C" __attribute__((used, export_name("r360_perf_counter"))) +double r360_perf_counter(uint32_t index) { + switch (index) { + case 0: return double(render360::xenia_web::g_total_instructions); + case 1: return double(render360::xenia_web::g_interpreted_instructions); + default: return 0.0; + } +} extern "C" __attribute__((used, export_name("r360_hir_total_instructions_millions"))) uint32_t r360_hir_total_instructions_millions() { return uint32_t(render360::xenia_web::g_total_instructions / 1000000ull); diff --git a/src/xenia_web_bootstrap/hir_correctness_executor.h b/src/xenia_web_bootstrap/hir_correctness_executor.h index d87dc9a9..a8435e8b 100644 --- a/src/xenia_web_bootstrap/hir_correctness_executor.h +++ b/src/xenia_web_bootstrap/hir_correctness_executor.h @@ -11,6 +11,11 @@ // its own host thread and thread_local state). #if defined(__wasm__) #define R360_FIBER_LOCAL __attribute__((section("r360_fiber"))) +#elif defined(R360_NATIVE) && defined(__APPLE__) +// Native build: guest threads are pthreads that run one at a time (a baton, +// guest_fibers.cpp), and the block is swapped exactly as in the browser so +// both builds schedule identically. Mach-O section syntax. +#define R360_FIBER_LOCAL __attribute__((section("__DATA,r360_fiber"))) #else #define R360_FIBER_LOCAL thread_local #endif diff --git a/src/xenia_web_bootstrap/hir_jit_glue.inc b/src/xenia_web_bootstrap/hir_jit_glue.inc index 057082c4..c81859db 100644 --- a/src/xenia_web_bootstrap/hir_jit_glue.inc +++ b/src/xenia_web_bootstrap/hir_jit_glue.inc @@ -6,14 +6,20 @@ // PPCContext, so guest calls, returns, memory, MMIO and atomics behave exactly // as in ExecuteBuilder above. // --------------------------------------------------------------------------- +extern "C" uint32_t r360_guest_thread_current(); namespace render360::xenia_web { namespace { xe::Memory* g_jit_memory = nullptr; -uint32_t g_jit_fault = 0; +// Fault state of the running generated function, per guest thread: a guest +// interrupt (RunGuestInterrupt swaps the fiber-local section) or another +// fiber can run nested JIT code that fails, and must not leave the fault set +// for the interrupted code's next FaultCheck. Generated code reads it at a +// fixed address, which the section swap keeps valid. +R360_FIBER_LOCAL uint32_t g_jit_fault = 0; // Operand/result exchange for r360_jit_h_exec: three 16-byte operand slots // and the result slot. alignas(16) uint8_t g_jit_scratch[64] = {}; -uint32_t g_jit_fail_kind = 0, g_jit_fail_opcode = 0, g_jit_fail_address = 0; +R360_FIBER_LOCAL uint32_t g_jit_fail_kind = 0, g_jit_fail_opcode = 0, g_jit_fail_address = 0; // Blocker for a failed helper, preferring a nested callee's blocker as the // executor does after a failed call. @@ -87,6 +93,24 @@ uint32_t JitInstructionCounterAddress() { uint32_t JitDebugWatchAddress() { return g_debug_watch_address; } uint32_t JitFaultAddress() { return uint32_t(reinterpret_cast(&g_jit_fault)); } uint32_t JitScratchAddress() { return uint32_t(reinterpret_cast(g_jit_scratch)); } +uint32_t g_jit_entry_segment = 0; +uint32_t g_jit_poll_source = 0; +uint32_t JitPollSourceAddress() { return uint32_t(reinterpret_cast(&g_jit_poll_source)); } +// r360_jit_diag: a line every 2^27 guest instructions (where the guest runs +// when it never returns to the host, e.g. inside back-to-back interrupts). +bool g_jit_diag = false; +uint64_t g_jit_diag_next = 0; +void JitDiagnosticPoll() { + if (!g_jit_diag || g_total_instructions < g_jit_diag_next) return; + g_jit_diag_next = (g_total_instructions | ((uint64_t(1) << 27) - 1)) + 1; + char fibers[512]; + GuestFiberDiagnostic(fibers, sizeof(fibers)); + std::fprintf(stderr, "R360_DIAG minstr=%llu interrupt=%u active=%u thread=0x%08X source=0x%08X loop=0x%08X %s\n", + (unsigned long long)(g_total_instructions / 1000000u), GuestInterruptActive() ? 1u : 0u, + GuestFibersActive() ? 1u : 0u, r360_guest_thread_current(), g_current_source_address, + g_jit_poll_source, fibers); +} +uint32_t JitEntrySegmentAddress() { return uint32_t(reinterpret_cast(&g_jit_entry_segment)); } uint32_t JitReturnAddressSlot() { return uint32_t(reinterpret_cast(&g_next_guest_return_address)); } @@ -119,17 +143,60 @@ void JitProfileInterpreted(xe::cpu::hir::HIRBuilder* builder, uint32_t reason, u ++e.runs; } +// Runs the compiled `function` from dispatcher segment `entry` and maps its +// status to an executor result. +void JitRun(uint32_t function, uint32_t entry, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result); + // Runs `builder` as compiled code when it has some (ExecuteHIRCorrectnessProbe // calls this in place of ExecuteBuilder for plain function entries). bool JitTryExecute(xe::cpu::hir::HIRBuilder* builder, xe::Memory* memory, xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { const uint32_t function = JitTakeFunction(builder); if (!function) return false; + JitRun(function, 0, memory, context, result); + return true; +} + +uint32_t JitBlockSource(const xe::cpu::hir::Block* block) { + for (auto* i = block->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + return 0; +} + +// ExecuteBuilder hands a run over to compiled code at the head of `block` +// (JitOsrFunction); false keeps interpreting. +uint64_t g_jit_osr_entries = 0; +bool JitTryOsr(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot, + const xe::cpu::hir::Block* block, bool hot, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { + const uint32_t function = JitOsrFunction(builder, slot, hot); + if (!function) return false; + const uint32_t segment = JitSegmentOfBlock(builder, block); + if (segment == 0xFFFFFFFFu) return false; + ++g_jit_osr_entries; + JitRun(function, segment, memory, context, result); + if (!result->supported) { + std::fprintf(stderr, "R360_OSR_FAILED block_source=0x%08X segment=%u hot=%u blocker=%u@0x%08X\n", + JitBlockSource(block), segment, hot ? 1u : 0u, result->blocker_kind, + result->blocker_address); + } + return true; +} + +void JitRun(uint32_t function, uint32_t entry, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { + g_jit_entry_segment = entry; g_jit_memory = memory; + // A caller in generated code learns of this run's failure from its + // helper's return value; its own fault flag stays as it was. + const uint32_t caller_fault = g_jit_fault; g_jit_fault = 0; g_jit_fail_kind = g_jit_fail_opcode = g_jit_fail_address = 0; const uint32_t status = reinterpret_cast(uintptr_t(function))( uint32_t(reinterpret_cast(&context))); + g_jit_fault = caller_fault; *result = HIRCorrectnessResult{}; result->r3 = context.r[3]; switch (status) { @@ -149,7 +216,6 @@ bool JitTryExecute(xe::cpu::hir::HIRBuilder* builder, xe::Memory* memory, result->blocker_address = g_jit_fail_address; break; } - return true; } } // namespace render360::xenia_web @@ -209,6 +275,7 @@ R360_JIT_HELPER(st64) void r360_jit_h_st64(uint32_t a, uint64_t v, uint32_t s) { // Loops in generated code poll here: guest interrupts, preemption and host // time slices (may unwind), and the --max-minstr budget. R360_JIT_HELPER(poll) uint32_t r360_jit_h_poll() { + rxj::JitDiagnosticPoll(); rxj::DeliverGuestInterruptsNow(); if (rxj::g_total_instruction_budget && rxj::g_total_instructions > rxj::g_total_instruction_budget) { @@ -278,6 +345,10 @@ R360_JIT_HELPER(mulhi64) uint64_t r360_jit_h_mulhi64(uint64_t a, uint64_t b, uin return is_unsigned ? uint64_t((unsigned __int128)a * (unsigned __int128)b >> 64) : uint64_t(((__int128)int64_t(a) * (__int128)int64_t(b)) >> 64); } +__attribute__((used, export_name("r360_jit_diag"))) +uint32_t r360_jit_diag(uint32_t on) { rxj::g_jit_diag = on != 0; return on; } +__attribute__((used, export_name("r360_jit_osr_entries"))) +uint32_t r360_jit_osr_entries() { return uint32_t(rxj::g_jit_osr_entries); } __attribute__((used, export_name("r360_jit_profile"))) uint32_t r360_jit_profile(uint32_t command) { if (command == 1) { rxj::g_jit_profile = true; rxj::g_jit_profile_entries.clear(); return 1; } diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 58520e39..eb24f0e2 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -1,11 +1,14 @@ // Render360 guest JIT: finalized Xenia HIR -> WebAssembly (see hir_wasm_jit.h). #include "hir_wasm_jit.h" +#include #include #include +#include #include #include +#include "xenia/base/string_buffer.h" #include "xenia/cpu/function.h" #include "xenia/cpu/hir/block.h" #include "xenia/cpu/hir/hir_builder.h" @@ -20,6 +23,12 @@ namespace render360::xenia_web { uint32_t JitInstructionCounterAddress(); uint32_t JitFaultAddress(); uint32_t JitScratchAddress(); +// Dispatcher segment the next generated-function call starts at (0 = entry); +// generated code reads and clears it. +uint32_t JitEntrySegmentAddress(); +// Guest address of the loop head a generated function last polled at +// (diagnostics: r360_jit_diag). +uint32_t JitPollSourceAddress(); uint32_t SparseGuestPageDirectoryAddress(); // Nonzero while a debug store watch (r360_debug_watch) is armed. uint32_t JitDebugWatchAddress(); @@ -51,6 +60,9 @@ uint32_t g_compiler = 0; uint32_t g_next_request = 1; std::unordered_map g_pending; HIRBuilder* g_candidate_builder = nullptr; +// The run JitTakeFunction last sent to the interpreter (JitTakeOsrSlot). +HIRBuilder* g_osr_builder = nullptr; +JitSlot* g_osr_slot = nullptr; uint32_t g_last_decision = 0; JitSlot* g_candidate_slot = nullptr; // Telemetry. @@ -236,7 +248,8 @@ constexpr uint32_t kPollBudget = 20000; // backward branches between polls constexpr uint32_t kLocPc = 1, kLocBudget = 2, kLocResume = 3, kLocPending = 4, kLocSp = 5, kLocTmp = 6, kLocTmpB = 7, kLocTmp64 = 8, kLocTmp64B = 9, kLocTmpF64 = 10, kLocTmpV = 11, kLocAddr = 12, - kLocPage = 13, kLocHost = 14, kLocVal = 15, kFixedLocals = 16; + kLocPage = 13, kLocHost = 14, kLocVal = 15, + kLocResumed = 16, kFixedLocals = 17; class Emitter { public: @@ -244,6 +257,8 @@ class Emitter { bool Compile(std::vector* out); uint32_t reject_opcode() const { return reject_opcode_; } + bool uses_exec() const { return uses_exec_; } + bool osr_capable() const { return osr_capable_; } private: struct Segment { @@ -342,6 +357,16 @@ class Emitter { uint32_t real_ = 0, n_ = 0, end_ = 0, poll_ = 0, spill_ = 0, restore_ = 0; uint32_t extra_ = 0; uint32_t reject_opcode_ = 0; + bool uses_exec_ = false; + bool osr_capable_ = false; + uint32_t entry_slot_ = 0, poll_source_ = 0; + // First guest address in segment k. + uint32_t SegmentSource(uint32_t k) const { + for (Instr* i = segments_[k].first; i && i != segments_[k].end; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + return 0; + } uint32_t counter_ = 0, fault_ = 0, return_slot_ = 0, return_valid_ = 0, scratch_ = 0; uint32_t page_directory_ = 0; // Inline sparse page walk for an access of `size` bytes at kLocAddr: falls @@ -435,6 +460,7 @@ void Emitter::Jump(uint32_t k, uint32_t j) { Else(); I32(int32_t(kPollBudget)); Set(kLocBudget); I32(int32_t(j)); Set(kLocPending); + I32(int32_t(poll_source_)); I32(int32_t(SegmentSource(j))); Mem(oI32Store, 2, 0); I32(int32_t(poll_)); Set(kLocPc); End(); BrTo(DepthToLoop(k)); @@ -774,10 +800,18 @@ bool Emitter::EmitVector(Instr* instr, uint32_t source) { return SetDest(instr); case OPCODE_EXTRACT: { if (is_vec(a) && d && b && !b->IsConstant() && IsInt(b->type) && - (d->type == INT8_TYPE || d->type == INT16_TYPE)) { + (d->type == INT8_TYPE || d->type == INT16_TYPE || d->type == INT32_TYPE)) { // Dynamic index: gather the element into lane 0 with a swizzle. Push(a); - if (d->type == INT8_TYPE) { + if (d->type == INT32_TYPE) { + // Lane index & 3, as the constant case: bytes 4*lane .. 4*lane+3. + uint8_t quad[16]; + for (int k = 0; k < 16; ++k) quad[k] = uint8_t(k & 3); + PushAs(b, Cls::kI32); I32(3); Op(oI32And); I32(2); Op(oI32Shl); + Simd(0x0F); V128Const(quad); Simd(0x6E); // splat(4*lane) + {0,1,2,3,...} + Simd(0x0E); + Simd(0x1B); code_.u8(0); + } else if (d->type == INT8_TYPE) { PushAs(b, Cls::kI32); I32(3); Op(oI32Xor); I32(0xF); Op(oI32And); Simd(0x0F); Simd(0x0E); // swizzle(v, splat(idx)) Simd(0x16); code_.u8(0); @@ -803,6 +837,27 @@ bool Emitter::EmitVector(Instr* instr, uint32_t source) { } return SetDest(instr); } + case OPCODE_VECTOR_COMPARE_EQ: case OPCODE_VECTOR_COMPARE_SGT: + case OPCODE_VECTOR_COMPARE_SGE: case OPCODE_VECTOR_COMPARE_UGT: + case OPCODE_VECTOR_COMPARE_UGE: { + // Lane-wise compare, all-ones where true (executor StoreVectorCompare / + // VectorCompareFloat: ordered float compares, so NaN lanes are false, + // as wasm f32x4.eq/gt/ge; unsigned float compares are the signed ones). + if (!is_vec(d) || !is_vec(a) || !is_vec(b)) return Reject(instr); + const bool eq = op == OPCODE_VECTOR_COMPARE_EQ; + const bool gt = op == OPCODE_VECTOR_COMPARE_SGT || op == OPCODE_VECTOR_COMPARE_UGT; + const bool uns = op == OPCODE_VECTOR_COMPARE_UGT || op == OPCODE_VECTOR_COMPARE_UGE; + uint32_t simd = 0; + switch (TypeName(instr->flags & 0xFF)) { + case INT8_TYPE: simd = eq ? 0x23 : gt ? (uns ? 0x28 : 0x27) : (uns ? 0x2C : 0x2B); break; + case INT16_TYPE: simd = eq ? 0x2D : gt ? (uns ? 0x32 : 0x31) : (uns ? 0x36 : 0x35); break; + case INT32_TYPE: simd = eq ? 0x37 : gt ? (uns ? 0x3C : 0x3B) : (uns ? 0x40 : 0x3F); break; + case FLOAT32_TYPE: simd = eq ? 0x41 : gt ? 0x44 : 0x46; break; + default: return Reject(instr); + } + Push(a); Push(b); Simd(simd); + return SetDest(instr); + } case OPCODE_SWIZZLE: { if (!is_vec(d) || !is_vec(a) || (instr->flags != INT32_TYPE && instr->flags != FLOAT32_TYPE)) { return Reject(instr); @@ -890,6 +945,7 @@ bool Emitter::EmitGeneric(Instr* instr, uint32_t source) { StoreClass(c, uint32_t(16 * n)); } if (instr->dest && ClassOf(instr->dest->type) == Cls::kNone) return Reject(instr); + uses_exec_ = true; // the code now points into the builder's HIR I32(int32_t(reinterpret_cast(instr))); I32(int32_t(source)); Call(kHExec); @@ -903,6 +959,7 @@ bool Emitter::EmitGeneric(Instr* instr, uint32_t source) { return true; } +extern bool g_reject_tail_calls; bool Emitter::EmitInstr(Instr* instr, uint32_t k, uint32_t source) { const size_t mark = code_.b.size(); const uint32_t extra = extra_; @@ -1533,6 +1590,7 @@ bool Emitter::EmitNative(Instr* instr, uint32_t k, uint32_t source) { return true; case OPCODE_CALL: case OPCODE_CALL_TRUE: { + if ((instr->flags & CALL_TAIL) && g_reject_tail_calls) return Reject(instr); const bool conditional = op == OPCODE_CALL_TRUE; auto* symbol = conditional ? instr->src2.symbol : instr->src1.symbol; uint32_t direct_target = 0; @@ -1617,12 +1675,18 @@ bool Emitter::EmitSegment(uint32_t k) { if (k < real_) { const Segment& s = segments_[k]; if (s.count) { - // Total instruction counter (--max-minstr, preemption accounting). + // Total instruction counter (--max-minstr, preemption accounting, + // deterministic clock). A segment re-entered by an Asyncify rewind + // (RESTORE) was already counted when it first ran. + Get(kLocResumed); Op(oI32Eqz); + If(); I32(int32_t(counter_)); I32(int32_t(counter_)); Mem(oI64Load, 3, 0); I64(int64_t(s.count)); Op(oI64Add); Mem(oI64Store, 3, 0); + End(); } + I32(0); Set(kLocResumed); uint32_t source = 0; for (Instr* i = s.block->instr_head; i && i != s.first; i = i->next) { if (i->opcode && i->opcode->num == hir::OPCODE_SOURCE_OFFSET) source = uint32_t(i->src1.offset); @@ -1644,6 +1708,8 @@ bool Emitter::EmitSegment(uint32_t k) { UnwindCheck(k); Get(kLocTmp); Op(oI32Eqz); If(); I32(int32_t(kJitStatusFailed)); Op(oReturn); End(); + // Resumed here after a rewind: the branch target has not run yet. + I32(0); Set(kLocResumed); Get(kLocPending); Set(kLocPc); BrTo(DepthToLoop(k)); return true; @@ -1688,6 +1754,7 @@ bool Emitter::EmitSegment(uint32_t k) { } Set(i); } + I32(1); Set(kLocResumed); Get(kLocResume); Set(kLocPc); BrTo(DepthToLoop(k)); return true; @@ -1700,14 +1767,33 @@ bool Emitter::Compile(std::vector* out) { scratch_ = JitScratchAddress(); page_directory_ = SparseGuestPageDirectoryAddress(); return_valid_ = JitReturnValidSlot(); + entry_slot_ = JitEntrySegmentAddress(); + poll_source_ = JitPollSourceAddress(); if (!Plan()) return false; AllocateTemporaries(); + // Block-local values only: every block head is a valid entry. + using namespace xe::cpu::hir; + osr_capable_ = true; + for (Block* block = builder_->first_block(); block && osr_capable_; block = block->next) { + for (Instr* i = block->instr_head; i && osr_capable_; i = i->next) { + const auto sig = i->opcode->signature; + const Value* operands[3] = { + GET_OPCODE_SIG_TYPE_SRC1(sig) == OPCODE_SIG_TYPE_V ? i->src1.value : nullptr, + GET_OPCODE_SIG_TYPE_SRC2(sig) == OPCODE_SIG_TYPE_V ? i->src2.value : nullptr, + GET_OPCODE_SIG_TYPE_SRC3(sig) == OPCODE_SIG_TYPE_V ? i->src3.value : nullptr}; + for (const Value* v : operands) { + if (v && !v->IsConstant() && (!v->def || v->def->block != block)) osr_capable_ = false; + } + } + } // Function body (after the local declarations, which depend on it). - // Entry: rewinding -> RESTORE, else segment 0. + // Entry: rewinding -> RESTORE, else the requested entry segment (0 unless + // the interpreter is handing over mid-run), which is then cleared. Call(kHState); I32(2); Op(oI32Eq); - If(kI32); I32(int32_t(restore_)); Else(); I32(0); End(); + If(kI32); I32(int32_t(restore_)); Else(); I32(int32_t(entry_slot_)); Mem(oI32Load, 2, 0); End(); Set(kLocPc); + I32(int32_t(entry_slot_)); I32(0); Mem(oI32Store, 2, 0); I32(int32_t(kPollBudget)); Set(kLocBudget); code_.u8(oLoop); code_.u8(kVoid); for (uint32_t i = 0; i < n_; ++i) { code_.u8(oBlock); code_.u8(kVoid); } @@ -1771,7 +1857,7 @@ bool Emitter::Compile(std::vector* out) { }; for (uint32_t i = 1; i < kLocTmp64; ++i) add_local(kI32); add_local(kI64); add_local(kI64); add_local(kF64); add_local(kV128); - for (int i = 0; i < 4; ++i) add_local(kI32); + for (uint32_t i = kLocAddr; i < kFixedLocals; ++i) add_local(kI32); for (uint8_t t : local_types_) add_local(t); body.u32(uint32_t(runs.size())); for (const auto& r : runs) { body.u32(r.first); body.u8(r.second); } @@ -1785,7 +1871,65 @@ bool Emitter::Compile(std::vector* out) { return true; } +// Functions starting in [g_exclude_begin, g_exclude_end) stay interpreted +// (r360_jit_set_exclude; bisecting a suspected miscompile). +uint32_t g_exclude_begin = 0, g_exclude_end = 0; +bool Excluded(HIRBuilder* builder) { + if (g_exclude_begin >= g_exclude_end) return false; + for (Block* b = builder->first_block(); b; b = b->next) { + for (Instr* i = b->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) { + const uint32_t start = uint32_t(i->src1.offset); + return start >= g_exclude_begin && start < g_exclude_end; + } + } + } + return false; +} + +// Compile requests numbered in order; [g_exclude_seq_begin, end) stay +// interpreted (r360_jit_set_exclude_seq; bisecting by when code compiles, +// which keeps early, hot functions compiled). +uint32_t g_compile_seq = 0, g_exclude_seq_begin = 0, g_exclude_seq_end = 0; +// Compile requests in [g_log_seq_begin, end) print their guest function +// (r360_jit_set_log_seq; naming what a sequence bisect found). +uint32_t g_log_seq_begin = 0, g_log_seq_end = 0; +bool g_log_dump = false; // also the HIR and the wasm module +// Functions with direct tail calls stay interpreted (r360_jit_set_reject_tail; +// isolating a tail-call miscompile). +bool g_reject_tail_calls = false; + +uint32_t SourceStart(HIRBuilder* builder) { + for (Block* b = builder->first_block(); b; b = b->next) { + for (Instr* i = b->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + } + return 0; +} + uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { + const uint32_t seq = g_compile_seq++; + const bool logged = seq >= g_log_seq_begin && seq < g_log_seq_end; + if (logged) { + std::fprintf(stderr, "R360_JIT_SEQ seq=%u start=0x%08X\n", seq, SourceStart(builder)); + if (g_log_dump) { + xe::StringBuffer dump; + builder->Dump(&dump); + const std::string text = dump.to_string(); + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::fprintf(stderr, "R360_JIT_SEQ_HIR %u %.*s\n", seq, int(end - at), text.data() + at); + at = end + 1; + } + } + } + if (Excluded(builder) || (seq >= g_exclude_seq_begin && seq < g_exclude_seq_end)) { + slot->state = 2; + return 0; + } Emitter emitter(builder); std::vector bytes; if (!emitter.Compile(&bytes)) { @@ -1796,7 +1940,16 @@ uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { g_reject_by_builder[builder] = g_last_reject_opcode; return 0; } + if (logged && g_log_dump) { + for (size_t at = 0; at < bytes.size(); at += 64) { + std::fprintf(stderr, "R360_JIT_SEQ_WASM %u ", seq); + for (size_t k = at; k < std::min(bytes.size(), at + 64); ++k) std::fprintf(stderr, "%02x", bytes[k]); + std::fprintf(stderr, "\n"); + } + } const uint32_t request = g_next_request++; + slot->builder_free = !emitter.uses_exec(); + slot->osr_capable = emitter.osr_capable(); slot->state = 1; slot->request = request; g_pending[request] = slot; @@ -1824,6 +1977,11 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { JitSlot* slot = g_candidate_builder == builder ? g_candidate_slot : nullptr; g_candidate_builder = nullptr; g_candidate_slot = nullptr; + // Recorded only for a run going to the interpreter, which takes it at once + // (JitTakeOsrSlot): a stale record could match a later builder allocated at + // the same address. + g_osr_builder = nullptr; + g_osr_slot = nullptr; g_last_decision = 5; if (!g_mode || !g_compiler) return 0; g_last_decision = 1; @@ -1843,7 +2001,11 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { return 0; } g_last_decision = 2; - if (++slot->runs < (g_mode >= 2 ? 1u : g_hot_threshold)) return 0; + if (++slot->runs < (g_mode >= 2 ? 1u : g_hot_threshold)) { + g_osr_builder = builder; + g_osr_slot = slot; + return 0; + } const uint32_t index = RequestCompile(builder, slot); if (!index) g_last_decision = slot->state == 1 ? 3 : 4; if (index) ++g_jit_calls; @@ -1851,6 +2013,45 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { } uint32_t JitLastDecision() { return g_last_decision; } +bool JitEnabled() { return g_mode && g_compiler; } + +JitSlot* JitTakeOsrSlot(HIRBuilder* builder) { + JitSlot* slot = nullptr; + if (g_candidate_builder == builder) { + slot = g_candidate_slot; + } else if (g_osr_builder == builder) { + slot = g_osr_slot; + } + g_candidate_builder = g_osr_builder = nullptr; + g_candidate_slot = g_osr_slot = nullptr; + return slot; +} + +// Bit 0: long runs, bit 1: interior entries. +uint32_t g_osr_enabled = 3; +uint32_t JitOsrFunction(HIRBuilder* builder, JitSlot* slot, bool hot) { + if (!slot || !g_mode || !g_compiler || !(g_osr_enabled & (hot ? 1u : 2u))) return 0; + if (!slot->function) { + if (slot->state) return 0; // pending or not compilable + if (!hot && ++slot->runs < g_hot_threshold) return 0; + if (!RequestCompile(builder, slot)) return 0; + } + return slot->osr_capable ? slot->function : 0; +} + +uint32_t JitSegmentOfBlock(HIRBuilder* builder, const Block* target) { + // Plan()'s split: one segment per block plus one per call site after the + // block's first instruction. + uint32_t segment = 0; + for (Block* block = builder->first_block(); block; block = block->next) { + if (block == target) return segment; + ++segment; + for (Instr* instr = block->instr_head; instr; instr = instr->next) { + if (instr != block->instr_head && instr->opcode && IsCallSite(instr->opcode->num)) ++segment; + } + } + return 0xFFFFFFFFu; +} uint32_t JitRejectOpcode(HIRBuilder* builder) { auto it = g_reject_by_builder.find(builder); return it == g_reject_by_builder.end() ? 0xFFu : it->second; @@ -1865,6 +2066,33 @@ void JitReleaseSlot(JitSlot* slot) { namespace rx = render360::xenia_web; extern "C" { +__attribute__((used, export_name("r360_jit_set_exclude_seq"))) +uint32_t r360_jit_set_exclude_seq(uint32_t begin, uint32_t end) { + rx::g_exclude_seq_begin = begin; + rx::g_exclude_seq_end = end; + return rx::g_compile_seq; +} +__attribute__((used, export_name("r360_jit_set_log_seq"))) +uint32_t r360_jit_set_log_seq(uint32_t begin, uint32_t end, uint32_t dump) { + rx::g_log_dump = dump != 0; + rx::g_log_seq_begin = begin; + rx::g_log_seq_end = end; + return rx::g_compile_seq; +} +__attribute__((used, export_name("r360_jit_set_reject_tail"))) +uint32_t r360_jit_set_reject_tail(uint32_t on) { rx::g_reject_tail_calls = on != 0; return on; } +__attribute__((used, export_name("r360_jit_compile_seq"))) +uint32_t r360_jit_compile_seq() { return rx::g_compile_seq; } +__attribute__((used, export_name("r360_jit_set_exclude"))) +uint32_t r360_jit_set_exclude(uint32_t begin, uint32_t end) { + rx::g_exclude_begin = begin; + rx::g_exclude_end = end; + return end > begin ? end - begin : 0; +} +// On-stack replacement: bit 0 long runs, bit 1 interior entries (default 3; +// 0 for bisecting). +__attribute__((used, export_name("r360_jit_set_osr"))) +uint32_t r360_jit_set_osr(uint32_t mask) { rx::g_osr_enabled = mask & 3u; return rx::g_osr_enabled; } __attribute__((used, export_name("r360_jit_set_compiler"))) uint32_t r360_jit_set_compiler(uint32_t table_index) { rx::g_compiler = table_index; diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.h b/src/xenia_web_bootstrap/hir_wasm_jit.h index 92e36bc5..8698fe68 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.h +++ b/src/xenia_web_bootstrap/hir_wasm_jit.h @@ -3,6 +3,7 @@ #include namespace xe::cpu::hir { +class Block; class HIRBuilder; } @@ -32,8 +33,17 @@ struct JitSlot { uint32_t state = 0; // 0 not compiled, 1 compile pending, 2 not compilable uint32_t runs = 0; uint32_t request = 0; // pending asynchronous compile request id + // The compiled code holds no pointer into its HIR builder (no single-op + // executor fallbacks), so it can run after the builder is freed. + bool builder_free = false; + // No HIR value is used outside its defining block, so the code can be + // entered at any block head (JitOsrFunction). + bool osr_capable = false; }; +// Compiled code can run (a JIT compiler is installed and enabled). +bool JitEnabled(); + // The next HIR execution of `builder` belongs to `slot` (set by the cache just // before it runs the builder). void JitSetCandidate(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot); @@ -49,6 +59,19 @@ uint32_t JitLastDecision(); // First HIR opcode that kept `builder` from compiling (diagnostics). uint32_t JitRejectOpcode(xe::cpu::hir::HIRBuilder* builder); +// Entering compiled code from the interpreter (on-stack replacement): a +// function entered once that loops (a thread's main loop, a wait loop) never +// reaches the call-count threshold and would stay interpreted. +// The slot the interpreter's current run of `builder` belongs to (the +// candidate JitTakeFunction declined, or one an interior entry never took). +JitSlot* JitTakeOsrSlot(xe::cpu::hir::HIRBuilder* builder); +// Compiled function for entering `builder` mid-run, compiling it now when +// `hot` (else when it has run often enough); 0 when it cannot be entered. +uint32_t JitOsrFunction(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot, bool hot); +// Dispatcher segment where `block` starts in the compiled function. +uint32_t JitSegmentOfBlock(xe::cpu::hir::HIRBuilder* builder, + const xe::cpu::hir::Block* block); + // The cache entry owning `slot` is being destroyed. void JitReleaseSlot(JitSlot* slot); diff --git a/src/xenia_web_bootstrap/kernel_import_probe.cpp b/src/xenia_web_bootstrap/kernel_import_probe.cpp index d4addc84..9f392d9a 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.cpp +++ b/src/xenia_web_bootstrap/kernel_import_probe.cpp @@ -86,6 +86,7 @@ KernelServiceTraceEntry* BeginKernelServiceTrace( // are logged to stderr (r360_kernel_watch_arg; tools/run-title.mjs // --watch-kernel-arg). std::array g_kernel_arg_watch{}; +uint32_t g_determinism_every = 0; void FinishKernelServiceTrace(KernelServiceTraceEntry* trace, uint32_t result, uint32_t service_status, bool handled) { @@ -93,6 +94,13 @@ void FinishKernelServiceTrace(KernelServiceTraceEntry* trace, uint32_t result, trace->result = result; trace->service_status = service_status; trace->handled = handled ? 1u : 0u; + // Determinism checkpoints: every Nth kernel call with the guest instruction + // count, so two runs can be diffed for the first divergence. + if (g_determinism_every && trace->sequence % g_determinism_every == 0) { + std::fprintf(stderr, "R360_DET seq=%u instr=%llu thread=0x%08X ord=%u.%X r3=0x%08X\n", + trace->sequence, static_cast(HIRTotalInstructions()), + r360_guest_thread_current(), trace->module_id, trace->ordinal, result); + } if (!g_kernel_arg_watch[0]) return; for (uint32_t watched : g_kernel_arg_watch) { if (!watched) continue; @@ -249,6 +257,10 @@ bool RegisterKernelImportThunk(uint32_t thunk_address, uint32_t module_id, } return false; } +bool IsKernelImportThunk(uint32_t thunk_address) { + return FindKernelImport(thunk_address) != nullptr; +} + bool ResolveKernelImportThunk(uint32_t thunk_address) { const auto* entry = FindKernelImport(thunk_address); if (!entry) return false; @@ -350,7 +362,7 @@ uint32_t r360_kernel_import_register(uint32_t a, uint32_t m, uint32_t o, : 0u; } uint32_t r360_kernel_import_dispatch_context(uint32_t thunk_address, - uint32_t context_ptr) { + uintptr_t context_ptr) { if (!context_ptr || (context_ptr & (alignof(xe::cpu::ppc::PPCContext) - 1u)) != 0u) { return 0; @@ -385,6 +397,11 @@ uint32_t r360_kernel_export_calls(uint32_t module, uint32_t ordinal) { if (module < 1 || module > 2 || ordinal >= 0x1000u) return 0; return render360::xenia_web::g_export_calls[module - 1][ordinal]; } +__attribute__((used, export_name("r360_kernel_determinism_every"))) +uint32_t r360_kernel_determinism_every(uint32_t n) { + render360::xenia_web::g_determinism_every = n; + return n; +} __attribute__((used, export_name("r360_kernel_watch_arg"))) uint32_t r360_kernel_watch_arg(uint32_t slot, uint32_t value) { if (slot >= render360::xenia_web::g_kernel_arg_watch.size()) return 0; diff --git a/src/xenia_web_bootstrap/kernel_import_probe.h b/src/xenia_web_bootstrap/kernel_import_probe.h index c7e42136..2848b322 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.h +++ b/src/xenia_web_bootstrap/kernel_import_probe.h @@ -10,6 +10,8 @@ bool RegisterKernelImportThunk(uint32_t thunk_address, uint32_t module_id, uint32_t ordinal, bool implemented, uint32_t abi_target); bool ResolveKernelImportThunk(uint32_t thunk_address); +// A registered import thunk (no side effects, unlike ResolveKernelImportThunk). +bool IsKernelImportThunk(uint32_t thunk_address); uint32_t KernelImportProbeCount(); uint32_t KernelImportProbeCalls(); uint32_t KernelImportProbeLastThunk(); diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 2e5526cc..bfb0d6fc 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -17,6 +17,7 @@ // * Kernel pool allocations come from a sparse arena at 0x5A000000 rather than // Xenia's system heap in the 0x80000000 XEX range. +#include "xam_xdbf.h" #include "kernel_xboxkrnl_services.h" #include @@ -42,6 +43,7 @@ extern "C" __attribute__((weak)) uint32_t r360_guest_clock_deterministic() { ret #include #include "guest_fibers.h" +#include "kernel_import_probe.h" #include "kernel_export_ordinals.h" // Weak defaults for builds that link the kernel services without the HIR @@ -63,6 +65,9 @@ __attribute__((weak)) uint32_t TitleGpuTakePendingInterrupts(uint32_t* mask) { i #if defined(__wasm__) #include +#elif defined(R360_NATIVE) +#include +#include #endif #if defined(__wasm__) @@ -140,6 +145,7 @@ constexpr uint32_t X_ERROR_NOT_FOUND = 0x00000490u; constexpr uint32_t X_ERROR_NO_SUCH_USER = 0x00000525u; constexpr uint32_t X_E_SUCCESS = 0x00000000u; constexpr uint32_t X_E_INVALIDARG = 0x80070057u; +constexpr uint32_t X_STATUS_DRIVER_ENTRYPOINT_NOT_FOUND = 0xC0000263u; constexpr uint32_t X_E_NO_SUCH_USER = 0x80070525u; constexpr uint32_t X_ERROR_INSUFFICIENT_BUFFER = 0x0000007Au; constexpr uint32_t X_ERROR_IO_INCOMPLETE = 0x000003E4u; @@ -378,6 +384,22 @@ std::vector& DebugLogEntries() { } constexpr size_t kMaxDebugLog = 64; uint32_t g_debug_log_total = 0; +// XamShowMessageBoxUI waiting for the player (host dialog mode). +struct MessageBox { + enum State { kIdle, kPending, kAnswered } state = kIdle; + uint32_t thread = 0, result_ptr = 0, overlapped = 0; + uint32_t active_button = 0, choice = 0; + std::string title, text; + std::vector buttons; +}; +MessageBox& PendingMessageBox() { + static MessageBox box; + return box; +} +bool g_dialog_host_answers = false; +// Headless runs: a preset answer given inside the call, so the run does not +// depend on when the host gets to answer (-1: none). +int32_t g_dialog_auto_answer = -1; void DebugLog(std::string text) { if (text.size() > 512) text.resize(512); @@ -623,6 +645,8 @@ std::map& PhysicalByVirtual() { static std::map allocations; return allocations; } +// Bumped whenever the physical range tables change (GPU address cache). +uint32_t g_physical_ranges_generation = 1; std::map& PhysicalRanges() { // physical base -> size static std::map ranges; return ranges; @@ -727,6 +751,7 @@ uint32_t AllocatePhysical(uint32_t size, uint32_t protect_bits, return 0; } PhysicalRanges()[physical] = adjusted_size; + ++g_physical_ranges_generation; PhysicalVirtualBases()[physical] = virtual_address; PhysicalByVirtual()[virtual_address] = {virtual_address, physical, adjusted_size, page_size, @@ -998,6 +1023,7 @@ void UpdateTimerByGuest(uint32_t guest) { uint32_t g_status = kKernelServiceSuccess; bool g_handled = true; + uint32_t Terminal(uint32_t kind, uint32_t code, uint32_t module, uint32_t ordinal, const uint32_t* args) { g_terminal = {}; @@ -1306,6 +1332,27 @@ uint32_t KernelModuleHandle(uint32_t index) { return g_kernel_module_handles[index]; } +// Xenia KernelModule::GetProcAddressByOrdinal: one guest trampoline per +// xboxkrnl/XAM export, made on first request. Here it is a registered import +// thunk, so calls through it reach the same service dispatcher as static +// imports (an unimplemented export still fails closed when it is called). +std::map& ProcTrampolines() { // (module << 16 | ordinal) -> guest address + static std::map trampolines; + return trampolines; +} +uint32_t KernelExportTrampoline(uint32_t module_id, uint32_t ordinal) { + const uint32_t key = (module_id << 16) | (ordinal & 0xFFFFu); + auto it = ProcTrampolines().find(key); + if (it != ProcTrampolines().end()) return it->second; + const uint32_t address = PoolAlloc(8u, 8u); + if (!address || !Wr32(address, 0x4E800020u) || !Wr32(address + 4u, 0x4E800020u) || // blr + !RegisterKernelImportThunk(address, module_id, ordinal, false, 0)) { + return 0; + } + ProcTrampolines()[key] = address; + return address; +} + std::map& ThreadPriority() { static std::map priority; return priority; @@ -1674,6 +1721,32 @@ uint32_t ReadVfs(VfsEntry& entry, uint32_t entry_index, uint64_t offset, g_vfs_bytes_read += done; return X_STATUS_SUCCESS; } +#elif defined(R360_NATIVE) + // Native host: host_fd is a real POSIX descriptor opened by the app/runner. + if (entry.host_fd) { + std::vector chunk(std::min(count, 1u << 20)); + uint32_t done = 0; + while (done < count) { + const uint32_t want = std::min(count - done, uint32_t(chunk.size())); + const ssize_t got = ::pread(int(entry.host_fd), chunk.data(), want, + off_t(entry.host_offset + offset + done)); + if (got <= 0) { + if (done) break; + g_host_io = {entry_index, offset, count, uint32_t(got < 0 ? errno : 0)}; + g_wait = {}; + g_wait.object = entry_index; + g_wait.reason = kWaitReasonHostIo; + g_status = kKernelServiceWouldBlock; + return 0; + } + if (!Wr(guest_buffer + done, chunk.data(), uint32_t(got))) return X_STATUS_ACCESS_VIOLATION; + done += uint32_t(got); + } + *read = done; + ++g_vfs_reads; + g_vfs_bytes_read += done; + return X_STATUS_SUCCESS; + } #endif g_host_io = {entry_index, offset, count, 0}; g_wait = {}; @@ -2393,23 +2466,86 @@ uint32_t DeleteContent(uint32_t content_type, const std::string& file_name) { return X_ERROR_FILE_NOT_FOUND; } +// XEX resource (Xenia UserModule::GetSection): name -> guest address, size. +bool FindModuleSection(const std::string& name, uint32_t* address, uint32_t* size) { + uint32_t info = 0; + if (!XexOptionalHeader(kXexHeaderResourceInfo, &info) || !info) return false; + uint32_t info_size = 0; + if (!Rd32(info, &info_size) || info_size < 4u) return false; + const uint32_t count = (info_size - 4u) / 16u; + for (uint32_t i = 0; i < count; ++i) { + const uint32_t entry = info + 4u + i * 16u; + char raw[9] = {}; + if (!Rd(entry, raw, 8) || !Rd32(entry + 8u, address) || !Rd32(entry + 12u, size)) { + return false; + } + if (name == std::string(raw)) return true; + } + return false; +} + +// Xenia KernelState::title_xdbf: the XDBF resource named by the title id. +std::vector TitleXdbf() { + uint32_t info = 0, title_id = 0; + if (!XexOptionalHeader(kXexHeaderExecutionInfo, &info) || !info || + !Rd32(info + 0x0Cu, &title_id)) { + return {}; + } + char name[9]; + std::snprintf(name, sizeof(name), "%08X", title_id); + uint32_t address = 0, size = 0; + if (!FindModuleSection(name, &address, &size) || !size || size > (16u << 20)) return {}; + std::vector data(size); + if (!Rd(address, data.data(), size)) return {}; + return data; +} + // XAM enumerators (Xenia XStaticEnumerator): fixed-size items handed out // items_per_enumerate at a time by XamEnumerate. +struct XamAchievement { + uint32_t id = 0, image_id = 0, gamerscore = 0, flags = 0; + std::u16string label, description, unachieved; +}; struct XamEnumerator { uint32_t item_size = 0; uint32_t per_enumerate = 1; uint32_t current = 0; std::vector items; - uint32_t count() const { return item_size ? uint32_t(items.size() / item_size) : 0; } + // Xenia XStaticAchievementEnumerator: X_ACHIEVEMENT_DETAILS records, then + // the strings the flags ask for (label 1, description 2, unachieved 4). + bool achievements = false; + uint32_t achievement_flags = 0; + std::vector achievement_items; + uint32_t count() const { + if (achievements) return uint32_t(achievement_items.size()); + return item_size ? uint32_t(items.size() / item_size) : 0; + } }; std::map& XamEnumerators() { static std::map enumerators; return enumerators; } +// Xenia XEnumerator::Initialize: the guest-visible X_KENUMERATOR (app id, +// open/close messages, user, items per enumerate, flags), optionally followed +// by an extra block (XamGetPrivateEnumStructureFromHandle returns it). +struct XamEnumeratorInit { + uint32_t user_index = 0xFF, app_id = 0xFE, open_message = 0, close_message = 0; + uint32_t flags = 0, extra_size = 0; +}; uint32_t CreateXamEnumerator(uint32_t item_size, uint32_t per_enumerate, - std::vector items) { - const uint32_t handle = CreateObject(ObjectType::kEnumerator, 0, false); + std::vector items, const XamEnumeratorInit& init = {}, + uint32_t* guest_out = nullptr) { + const uint32_t guest = PoolAlloc(0x18u + init.extra_size, 8u); + if (!guest) return 0; + for (uint32_t i = 0; i < 0x18u + init.extra_size; i += 4) Wr32(guest + i, 0); + if (!Wr32(guest + 0x00u, init.app_id) || !Wr32(guest + 0x04u, init.open_message) || + !Wr32(guest + 0x08u, init.close_message) || !Wr32(guest + 0x0Cu, init.user_index) || + !Wr32(guest + 0x10u, per_enumerate ? per_enumerate : 1u) || !Wr32(guest + 0x14u, init.flags)) { + return 0; + } + const uint32_t handle = CreateObject(ObjectType::kEnumerator, guest, true); if (!handle) return 0; + if (guest_out) *guest_out = guest; XamEnumerator e; e.item_size = item_size; e.per_enumerate = per_enumerate ? per_enumerate : 1u; @@ -2857,31 +2993,36 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { if (r4 && !Wr32(r4, hmodule)) return Invalid(); return hmodule ? X_ERROR_SUCCESS : X_ERROR_NOT_FOUND; } + case kx::XexGetProcedureAddress: { + // (hmodule, ordinal or name, function_ptr*): Xenia + // xboxkrnl_modules.cc. Kernel modules hand out export trampolines. + if (!r5) return Invalid(); + const bool by_name = (r4 & 0xFFFF0000u) != 0; + uint32_t module_id = 0; + if (r3 && r3 == KernelModuleHandle(0)) module_id = kModuleXboxkrnl; + if (r3 && r3 == KernelModuleHandle(1)) module_id = kModuleXam; + if (!module_id && r3 && r3 != g_exe.hmodule) return X_STATUS_INVALID_HANDLE; + uint32_t address = 0; + if (module_id && !by_name) address = KernelExportTrampoline(module_id, r4); + if (!address) { + std::string name; + if (by_name) ReadCString(r4, &name, 128); + DebugLog("XexGetProcedureAddress not found: module " + std::to_string(module_id) + + (by_name ? " name " + name : " ordinal " + std::to_string(r4))); + if (!Wr32(r5, 0)) return Invalid(); + return X_STATUS_DRIVER_ENTRYPOINT_NOT_FOUND; + } + if (!Wr32(r5, address)) return Invalid(); + return X_STATUS_SUCCESS; + } case kx::XexGetModuleSection: { if (!r3 || r3 != g_exe.hmodule) return X_STATUS_INVALID_HANDLE; std::string name; if (!ReadCString(r4, &name, 64)) return Invalid(); - uint32_t info = 0; - if (!XexOptionalHeader(kXexHeaderResourceInfo, &info) || !info) { - return X_STATUS_NOT_FOUND; - } - uint32_t info_size = 0; - if (!Rd32(info, &info_size) || info_size < 4u) return X_STATUS_NOT_FOUND; - const uint32_t count = (info_size - 4u) / 16u; - for (uint32_t i = 0; i < count; ++i) { - const uint32_t entry = info + 4u + i * 16u; - char raw[9] = {}; - uint32_t address = 0, size = 0; - if (!Rd(entry, raw, 8) || !Rd32(entry + 8u, &address) || - !Rd32(entry + 12u, &size)) { - return Invalid(); - } - if (name == std::string(raw)) { - if (!Wr32(r5, address) || !Wr32(r6, size)) return Invalid(); - return X_STATUS_SUCCESS; - } - } - return X_STATUS_NOT_FOUND; + uint32_t address = 0, size = 0; + if (!FindModuleSection(name, &address, &size)) return X_STATUS_NOT_FOUND; + if (!Wr32(r5, address) || !Wr32(r6, size)) return Invalid(); + return X_STATUS_SUCCESS; } // --- Time -------------------------------------------------------------- @@ -3327,11 +3468,24 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { const uint32_t kthread = CurrentKThread(); const uint32_t native = NativeThreadForKThread(kthread); if (native && !r360_guest_thread_external(native)) { + std::fprintf(stderr, "R360_THREAD_EXIT thread=0x%08X kthread=0x%08X code=0x%08X lr=0x%08X\n", + native, kthread, r3, g_caller_lr); MarkThreadExited(kthread, r3); r360_guest_thread_terminate(native, r3); return Terminal(kTerminalThreadExit, r3, kModuleXboxkrnl, ordinal, a); } // The primary thread leaving ends the title, as on the console. + { + uint32_t thread_id = 0, back = 0, lr = 0; + Rd32(kthread + 0x14Cu, &thread_id); + std::fprintf(stderr, "R360_PRIMARY_EXIT code=0x%08X kthread=0x%08X id=%u native=%u lr=0x%08X stack=", + r3, kthread, thread_id, native, g_caller_lr); + uint32_t fp = g_caller_r1; + for (uint32_t n = 0; n < 16 && fp && Rd32(fp, &back) && back > fp; ++n, fp = back) { + if (Rd32(back - 8u, &lr)) std::fprintf(stderr, "0x%08X ", lr); + } + std::fprintf(stderr, "\n"); + } MarkThreadExited(kthread, r3); return Terminal(kTerminalProcessExit, r3, kModuleXboxkrnl, ordinal, a); } @@ -3859,6 +4013,7 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { auto it = PhysicalByVirtual().find(r4); if (it != PhysicalByVirtual().end()) { PhysicalRanges().erase(it->second.physical_address); + ++g_physical_ranges_generation; PhysicalVirtualBases().erase(it->second.physical_address); PhysicalByVirtual().erase(it); } @@ -5085,6 +5240,74 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { if (!Wr32(a[4], handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamContentAggregateCreateEnumerator: { + // (xuid (qword), device_id, content_type, unknown, handle*): Xenia + // xam_content_aggregate.cc. XCONTENT_AGGREGATE_DATA items (0x148: the + // content data, a zero qword, the title id) for the HDD packages of + // the running title. Xenia's ODD test adds packages under + // game:\Content\0000000000000000, which title packages do not have. + const uint32_t device_id = r4, content_type = r5, handle_out = a[4]; + if ((device_id && !FindDummyDevice(device_id)) || !handle_out) return X_E_INVALIDARG; + uint32_t info = 0, title_id = 0; + if (XexOptionalHeader(kXexHeaderExecutionInfo, &info) && info) Rd32(info + 0x0Cu, &title_id); + std::vector items; + if (!device_id || device_id == 1u) { + for (const auto& package : ContentPackages()) { + if (package.content_type != content_type) continue; + std::array item{}; + std::copy(package.data.begin(), package.data.end(), item.begin()); + item[0] = 0; item[1] = 0; item[2] = 0; item[3] = 1; // device_id = HDD + item[0x13C] = uint8_t(title_id >> 24); item[0x13D] = uint8_t(title_id >> 16); + item[0x13E] = uint8_t(title_id >> 8); item[0x13F] = uint8_t(title_id); + items.insert(items.end(), item.begin(), item.end()); + } + } + // Initialize(0xFF, 0xFE, 0x2000E, 0x20010, 0) with an + // X_KENUMERATOR_CONTENT_AGGREGATE (kXObjSignature 'XEN\0', handle). + XamEnumeratorInit init; + init.open_message = 0x2000Eu; + init.close_message = 0x20010u; + init.extra_size = 8u; + uint32_t guest = 0; + const uint32_t handle = CreateXamEnumerator(0x148u, 1u, std::move(items), init, &guest); + if (!handle) return X_STATUS_NO_MEMORY; + if (!Wr32(guest + 0x18u, 0x58454E00u) || !Wr32(guest + 0x1Cu, handle)) return Invalid(); + if (!Wr32(handle_out, handle)) return Invalid(); + return X_ERROR_SUCCESS; + } + case xam::XamTaskSchedule: { + // (callback, message, unknown, handle*): Xenia xam_task.cc runs the + // callback with the message on a new guest thread (the executable's + // stack size, 16 KiB minimum, 4 KiB aligned) and reports handle 12345. + if (!r3 || !a[3]) return X_STATUS_INVALID_PARAMETER; + if (!Wr32(a[3], 12345u)) return Invalid(); + uint32_t stack_size = ExecutableStackSize(); + stack_size = std::max(0x4000u, (stack_size + 0xFFFu) & 0xFFFFF000u); + const uint32_t native = r360_guest_thread_create(r3, r4, stack_size, 0); + if (!native) return X_STATUS_NO_MEMORY; + const uint32_t kthread = PrepareThreadObjects(native, r3, 0, 0); + if (!kthread) { + r360_guest_thread_terminate(native, 0); + return X_STATUS_NO_MEMORY; + } + const uint32_t handle = CreateObject(ObjectType::kThread, kthread, false); + if (!handle) return X_STATUS_NO_MEMORY; + uint32_t slot = 0; + SlotForHandle(handle, &slot); + Objects()[slot].thread = native; + return X_STATUS_SUCCESS; + } + case xam::XamGetPrivateEnumStructureFromHandle: { + // (handle, object_ptr*): Xenia xam_enum.cc. The caller takes a + // reference (released by ObDereferenceObject). + KernelObject* object = ResolveHandle(r3); + if (!object || object->type != ObjectType::kEnumerator || !object->guest) { + return X_STATUS_INVALID_HANDLE; + } + ++object->handle_count; + if (r4 && !Wr32(r4, object->guest)) return Invalid(); + return X_STATUS_SUCCESS; + } case xam::XamContentCreateEnumerator: { // (user, device_id, content_type, content_flags, items_per_enumerate, // buffer_size*, handle*) @@ -5104,11 +5327,47 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { items.insert(items.end(), item.begin(), item.end()); } } - const uint32_t handle = CreateXamEnumerator(0x134u, per, std::move(items)); + XamEnumeratorInit init; // Xenia xam_content.cc: Initialize(0xFF, 0xFE, 0x20005, 0x20007, 0) + init.open_message = 0x20005u; + init.close_message = 0x20007u; + const uint32_t handle = CreateXamEnumerator(0x134u, per, std::move(items), init); if (!handle) return X_STATUS_NO_MEMORY; if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamUserCreateAchievementEnumerator: { + // (title_id, user_index, xuid, flags, offset, count, buffer_size*, + // handle*): Xenia's static enumerator over the title's XDBF + // achievement table, strings in the default user language (English). + const uint32_t flags = a[3], count = a[5], size_ptr = a[6], handle_out = a[7]; + if (!count || !size_ptr || !handle_out || r4 >= 4u) return X_ERROR_INVALID_PARAMETER; + const uint32_t entry_size = 36u + ((flags & 7u) ? 464u : 0u); + if (!Wr32(size_ptr, entry_size * count)) return Invalid(); + XamEnumeratorInit init; // Xenia: Initialize(user_index, 0xFB, 0xB000A, 0xB000B, 0) + init.user_index = r4; + init.app_id = 0xFBu; + init.open_message = 0xB000Au; + init.close_message = 0xB000Bu; + const uint32_t handle = CreateXamEnumerator(entry_size, count, {}, init); + if (!handle) return X_STATUS_NO_MEMORY; + XamEnumerator& e = XamEnumerators()[handle]; + e.achievements = true; + e.achievement_flags = flags; + const std::vector xdbf = TitleXdbf(); + for (auto& entry : ParseXdbfAchievements(xdbf.data(), xdbf.size())) { + XamAchievement item; + item.id = entry.id; + item.label = std::move(entry.label); + item.description = std::move(entry.description); + item.unachieved = std::move(entry.unachieved); + item.image_id = entry.image_id; + item.gamerscore = entry.gamerscore; + item.flags = entry.flags; + e.achievement_items.push_back(std::move(item)); + } + if (!Wr32(handle_out, handle)) return Invalid(); + return X_ERROR_SUCCESS; + } case xam::XamEnumerate: { // (handle, flags, buffer, buffer_length, items_returned*, overlapped) const uint32_t items_returned = a[4], overlapped = a[5]; @@ -5125,6 +5384,34 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { count = std::min(e.count() - e.current, e.per_enumerate); if (!count) { result = X_ERROR_NO_MORE_FILES; + } else if (e.achievements) { + constexpr uint32_t kDetailsSize = 36, kStringBufferSize = 464; + uint32_t string_ptr = r5 + e.per_enumerate * kDetailsSize; + uint32_t string_left = count * kStringBufferSize; + auto append = [&](const std::u16string& text) -> uint32_t { + const uint32_t bytes = uint32_t(text.size() + 1) * 2u; + if (bytes > string_left) return 0; + const uint32_t ptr = string_ptr; + for (size_t c = 0; c <= text.size(); ++c) { + if (!Wr16(ptr + uint32_t(c) * 2u, c < text.size() ? uint16_t(text[c]) : 0u)) return 0; + } + string_ptr += bytes; + string_left -= bytes; + return ptr; + }; + for (uint32_t i = 0; i < count; ++i, ++e.current) { + const XamAchievement& item = e.achievement_items[e.current]; + const uint32_t d = r5 + i * kDetailsSize; + const uint32_t f = e.achievement_flags; + if (!Wr32(d + 0, item.id) || + !Wr32(d + 4, (f & 1u) ? append(item.label) : 0u) || + !Wr32(d + 8, (f & 2u) ? append(item.description) : 0u) || + !Wr32(d + 12, (f & 4u) ? append(item.unachieved) : 0u) || + !Wr32(d + 16, item.image_id) || !Wr32(d + 20, item.gamerscore) || + !Wr32(d + 24, 0) || !Wr32(d + 28, 0) || !Wr32(d + 32, item.flags)) { + return Invalid(); + } + } } else { if (!Wr(r5, e.items.data() + size_t(e.current) * e.item_size, count * e.item_size)) { return Invalid(); @@ -5145,6 +5432,73 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { BroadcastNotification(0x0Au, 1); BroadcastNotification(0x09u, 0); return X_ERROR_SUCCESS; + case xam::XamShowMessageBoxUI: { + // (user, title, text, button_count, button_ptrs, active_button, flags, + // result_ptr, overlapped), bracketed by XN_SYS_UI. Without a host + // dialog this is Xenia's headless path (the focused button). With one + // (r360_xam_dialog_set_host_answers), the player chooses, as with + // Xenia's MessageBoxDialog: an overlapped call returns + // ERROR_IO_PENDING and completes on r360_xam_dialog_answer; a + // synchronous call blocks its thread until then. + uint32_t overlapped = 0; + if (!StackArg(8, &overlapped)) return Invalid(); + const uint32_t result_ptr = a[7]; + if (!result_ptr) return Invalid(); + MessageBox& box = PendingMessageBox(); + if (box.state == MessageBox::kAnswered && box.thread == r360_guest_thread_current() && + !box.overlapped) { + // Retry of a blocked synchronous call: the player has answered. + const uint32_t choice = box.choice; + box = {}; + if (!Wr32(result_ptr, choice)) return Invalid(); + BroadcastNotification(0x09u, 0); + return X_ERROR_SUCCESS; + } + if (box.state != MessageBox::kIdle) { + // Another dialog is up (or this thread's is unanswered): wait. + return WouldBlock(kModuleXam, xam::XamShowMessageBoxUI, 0, 0, 1); + } + std::u16string title, text; + ReadU16String(r4, &title); + ReadU16String(r5, &text); + box.title = Utf16ToUtf8(title); + box.text = Utf16ToUtf8(text); + box.buttons.clear(); + for (uint32_t i = 0; i < a[3] && i < 8u; ++i) { + uint32_t button = 0; + std::u16string label; + if (Rd32(a[4] + i * 4u, &button)) ReadU16String(button, &label); + box.buttons.push_back(Utf16ToUtf8(label)); + } + box.active_button = a[5]; + std::string log = "XamShowMessageBoxUI \"" + box.title + "\": " + box.text + " ["; + for (size_t i = 0; i < box.buttons.size(); ++i) log += (i ? " | " : "") + box.buttons[i]; + log += "] focused " + std::to_string(a[5]); + DebugLog(log); + std::fprintf(stderr, "R360_MESSAGE_BOX %s\n", log.c_str()); + BroadcastNotification(0x09u, 1); + if (!g_dialog_host_answers || g_dialog_auto_answer >= 0) { + uint32_t choice = a[5]; + if (g_dialog_auto_answer >= 0) { + choice = std::min(uint32_t(g_dialog_auto_answer), + box.buttons.empty() ? 0u : uint32_t(box.buttons.size() - 1)); + std::fprintf(stderr, "R360_MESSAGE_BOX answered %u (preset)\n", choice); + } + box = {}; + if (!Wr32(result_ptr, choice)) return Invalid(); + BroadcastNotification(0x09u, 0); + return FinishXamOverlapped(overlapped, X_ERROR_SUCCESS, 0); + } + box.state = MessageBox::kPending; + box.thread = r360_guest_thread_current(); + box.result_ptr = result_ptr; + box.overlapped = overlapped; + if (overlapped) { + if (!Wr32(overlapped, X_ERROR_IO_PENDING)) return Invalid(); + return X_ERROR_IO_PENDING; + } + return WouldBlock(kModuleXam, xam::XamShowMessageBoxUI, 0, 0, 1); + } case xam::XamShowDeviceSelectorUI: { // (user, content_type, content_flags, total_requested(qword), // device_id*, overlapped): the dummy HDD, bracketed by XN_SYS_UI. @@ -5345,6 +5699,7 @@ uint32_t DispatchExtendedKernelService(uint32_t module, uint32_t ordinal, // make kernel calls) while this one is suspended in a wait. const uint32_t caller_r13 = g_caller_r13, caller_lr = g_caller_lr, caller_r1 = g_caller_r1; + uint64_t idle_started_ns = 0; for (;;) { g_status = kKernelServiceSuccess; g_handled = true; @@ -5374,6 +5729,26 @@ uint32_t DispatchExtendedKernelService(uint32_t module, uint32_t ordinal, g_caller_r1 = caller_r1; continue; } + // Every guest thread is waiting (some may sleep until a deadline). On the + // console the CPU idles while vblank, audio and timers keep firing and + // eventually wake a thread: idle the guest clock, delivering interrupts, + // and retry. Ten seconds of guest time with no thread able to run is a + // real deadlock and is reported. + constexpr uint64_t kIdleStepNs = 4000000ull, kMaxIdleNs = 10000000000ull; + if (g_status == kKernelServiceWouldBlock && g_wait.reason >= 1 && + g_wait.reason <= 3 && GuestFibersActive() && !GuestInterruptActive()) { + const uint64_t now = r360_guest_clock_ns(); + if (!idle_started_ns) idle_started_ns = now; + // A thread waiting for the player's answer to a dialog is not + // deadlocked, however long it waits. + const bool player_wait = PendingMessageBox().state != MessageBox::kIdle; + if ((player_wait || now - idle_started_ns < kMaxIdleNs) && GuestFiberIdle(now + kIdleStepNs)) { + g_caller_r13 = caller_r13; + g_caller_lr = caller_lr; + g_caller_r1 = caller_r1; + continue; + } + } if (g_status == kKernelServiceSuccess) { GuestFiberNoteProgress(); if (!g_thread_waits.empty()) g_thread_waits.erase(r360_guest_thread_current()); @@ -5546,8 +5921,13 @@ void DeliverGuestInterruptsNow() { bool FinishGuestThreadFiber(uint32_t native, bool returned, uint32_t exit_code) { if (g_terminal.kind == kTerminalThreadExit) { + // ExTerminateThread already marked and terminated it. The service state + // it left (terminal) is not the next fiber's: a thread resuming in the + // middle of its own call (a sleep or timed wait) must not inherit it. g_terminal = {}; - return true; // ExTerminateThread already marked and terminated it + g_status = kKernelServiceSuccess; + g_handled = true; + return true; } if (!returned) return false; MarkThreadExited(r360_guest_thread_kthread(native), exit_code); @@ -5574,6 +5954,8 @@ void ResetExtendedKernelServices() { g_wait = {}; g_timeout_spin = {}; DebugLogEntries().clear(); + PendingMessageBox() = {}; + ProcTrampolines().clear(); g_debug_log_total = 0; Input() = {}; Input()[0].connected = true; @@ -5582,6 +5964,7 @@ void ResetExtendedKernelServices() { g_pool_top = kPoolBase; PhysicalByVirtual().clear(); PhysicalRanges().clear(); + ++g_physical_ranges_generation; PhysicalVirtualBases().clear(); Objects().clear(); ThreadPriority().clear(); @@ -5723,7 +6106,7 @@ uint32_t r360_kernel_debug_log_count() { } // Copies debug log entry |index| into wasm memory at |out| (capacity bytes). R360_WASM_EXPORT("r360_kernel_debug_log_read") -uint32_t r360_kernel_debug_log_read(uint32_t index, uint32_t out, +uint32_t r360_kernel_debug_log_read(uint32_t index, uintptr_t out, uint32_t capacity) { if (index >= r360k::DebugLogEntries().size() || !out || !capacity) return 0; const std::string& text = r360k::DebugLogEntries()[index]; @@ -5733,6 +6116,65 @@ uint32_t r360_kernel_debug_log_read(uint32_t index, uint32_t out, } // Render360 controller -> XInput gamepad state for user_index. +// Host dialog for XamShowMessageBoxUI: the page shows the pending message +// box and passes back the chosen button. +R360_WASM_EXPORT("r360_xam_dialog_set_host_answers") +uint32_t r360_xam_dialog_set_host_answers(uint32_t on) { + r360k::g_dialog_host_answers = on != 0; + return r360k::g_dialog_host_answers ? 1u : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_set_auto_answer") +int32_t r360_xam_dialog_set_auto_answer(int32_t button) { + r360k::g_dialog_auto_answer = button < 0 ? -1 : button; + return r360k::g_dialog_auto_answer; +} +R360_WASM_EXPORT("r360_xam_dialog_pending") +uint32_t r360_xam_dialog_pending() { + return r360k::PendingMessageBox().state == r360k::MessageBox::kPending ? 1u : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_button_count") +uint32_t r360_xam_dialog_button_count() { return uint32_t(r360k::PendingMessageBox().buttons.size()); } +R360_WASM_EXPORT("r360_xam_dialog_active_button") +uint32_t r360_xam_dialog_active_button() { return r360k::PendingMessageBox().active_button; } +// which: 0 title, 1 text, 2 + n button n. UTF-8, not terminated. +static const std::string* DialogString(uint32_t which) { + const auto& box = r360k::PendingMessageBox(); + if (which == 0) return &box.title; + if (which == 1) return &box.text; + if (which - 2u < box.buttons.size()) return &box.buttons[which - 2u]; + return nullptr; +} +R360_WASM_EXPORT("r360_xam_dialog_string_ptr") +uintptr_t r360_xam_dialog_string_ptr(uint32_t which) { + const std::string* s = DialogString(which); + return s ? (reinterpret_cast(s->data())) : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_string_len") +uint32_t r360_xam_dialog_string_len(uint32_t which) { + const std::string* s = DialogString(which); + return s ? uint32_t(s->size()) : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_answer") +uint32_t r360_xam_dialog_answer(uint32_t button) { + auto& box = r360k::PendingMessageBox(); + if (box.state != r360k::MessageBox::kPending || button >= box.buttons.size()) return 0; + box.choice = button; + if (box.overlapped) { + // Xenia CompleteOverlappedDeferred: result, then XN_SYS_UI off. + const uint32_t result_ptr = box.result_ptr, overlapped = box.overlapped; + box = {}; + if (!r360k::Wr32(result_ptr, button) || + !r360k::CompleteOverlappedEx(overlapped, r360k::X_ERROR_SUCCESS, 0, 0)) { + return 0; + } + r360k::BroadcastNotification(0x09u, 0); + } else { + box.state = r360k::MessageBox::kAnswered; // the blocked call's retry completes it + } + r360k::GuestFiberNoteProgress(); + return 1; +} + R360_WASM_EXPORT("r360_input_set_gamepad") uint32_t r360_input_set_gamepad(uint32_t user_index, uint32_t connected, uint32_t buttons, uint32_t triggers, @@ -5772,8 +6214,8 @@ void r360_vfs_reset() { } // 1 KiB scratch buffer in wasm memory for passing a UTF-8 guest path. R360_WASM_EXPORT("r360_vfs_path_buffer") -uint32_t r360_vfs_path_buffer() { - return uint32_t(uintptr_t(r360k::g_vfs_path_buffer)); +uintptr_t r360_vfs_path_buffer() { + return (uintptr_t(r360k::g_vfs_path_buffer)); } // Registers a file or directory relative to \Device\Cdrom0 (the game disc). // Returns the 1-based entry id. host_fd/host_offset let WASI fd_pread supply @@ -5795,12 +6237,12 @@ uint32_t r360_vfs_register(uint32_t path_length, uint32_t size_lo, // Allocates an in-memory buffer holding the whole file for entry |id| and // returns its wasm address for the loader to fill (0 on failure). R360_WASM_EXPORT("r360_vfs_data_buffer") -uint32_t r360_vfs_data_buffer(uint32_t id) { +uintptr_t r360_vfs_data_buffer(uint32_t id) { auto* entry = r360k::VfsEntryAt(id); if (!entry || entry->size > 0x7FFFFFFFull) return 0; entry->data.assign(size_t(entry->size), 0); entry->has_data = true; - return entry->size ? uint32_t(uintptr_t(entry->data.data())) : 1u; + return entry->size ? (uintptr_t(entry->data.data())) : 1u; } R360_WASM_EXPORT("r360_vfs_entry_count") uint32_t r360_vfs_entry_count() { return uint32_t(r360k::VfsEntries().size()); } @@ -5867,6 +6309,13 @@ uint32_t r360_audio_client_last_samples(uint32_t index) { R360_WASM_EXPORT("r360_kernel_gpu_address_to_virtual") uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address) { if (address >= 0x20000000u) return address; + // The GPU command processor translates every word it reads; nearly all hit + // the same range as the previous call, so remember it (two map lookups + // were ~14% of a native Banjo-Tooie run). + static uint32_t cached_generation = 0, cached_base = 0, cached_size = 0, cached_virtual = 0; + if (cached_generation == r360k::g_physical_ranges_generation && address - cached_base < cached_size) { + return cached_virtual + (address - cached_base); + } auto& ranges = r360k::PhysicalRanges(); auto it = ranges.upper_bound(address); if (it == ranges.begin()) return address; @@ -5874,6 +6323,10 @@ uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address) { if (address - it->first >= it->second) return address; auto base = r360k::PhysicalVirtualBases().find(it->first); if (base == r360k::PhysicalVirtualBases().end()) return address; + cached_generation = r360k::g_physical_ranges_generation; + cached_base = it->first; + cached_size = it->second; + cached_virtual = base->second; return base->second + (address - it->first); } R360_WASM_EXPORT("r360_kernel_vblank_interrupts") diff --git a/src/xenia_web_bootstrap/ppc_translation_probe.cpp b/src/xenia_web_bootstrap/ppc_translation_probe.cpp index 558a4d9f..ea566426 100644 --- a/src/xenia_web_bootstrap/ppc_translation_probe.cpp +++ b/src/xenia_web_bootstrap/ppc_translation_probe.cpp @@ -320,8 +320,8 @@ uint32_t r360_ppc_probe_read_guest_u32_be(uint32_t address) { (uint32_t(bytes[2]) << 8) | uint32_t(bytes[3]); } -uint32_t r360_ppc_probe_input_buffer() { - return static_cast( +uintptr_t r360_ppc_probe_input_buffer() { + return ( reinterpret_cast(render360::xenia_web::g_input_buffer)); } diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index d7fa247d..ab20523f 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -58,6 +59,9 @@ extern "C" char __stack_high; extern "C" uintptr_t emscripten_stack_get_current(void); #endif +// Defined by the Arena overlay (prepare-xenia-arena-overlay.py). +namespace xe { extern size_t g_r360_arena_live_bytes; } + namespace render360::xenia_web { namespace { enum TrapPhase : uint32_t { @@ -81,7 +85,18 @@ uint32_t CurrentStackPointer() { } uint32_t StackHeadroom() { -#if defined(__wasm__) +#if defined(R360_NATIVE) + // Native guest threads run on their own pthread stacks; measure the + // distance to the current thread's stack limit (64-bit addresses, so keep + // the low-water mark relative to the stack base). + const uintptr_t low = GuestFiberStackLow(); + const uintptr_t sp = reinterpret_cast(__builtin_frame_address(0)); + if (!low || sp <= low) return low ? 0 : UINT32_MAX; + const uint64_t room = sp - low; + const uint32_t headroom = room > UINT32_MAX ? UINT32_MAX : uint32_t(room); + if (!g_trap_stack_low_water || headroom < g_trap_stack_low_water) g_trap_stack_low_water = headroom; + return headroom; +#elif defined(__wasm__) const uint32_t sp = CurrentStackPointer(); const uint32_t low = static_cast(GuestFiberStackLow()); if (!g_trap_stack_low_water || sp < g_trap_stack_low_water) g_trap_stack_low_water = sp; @@ -254,6 +269,23 @@ bool ExecuteSharedEpilogReturn(uint32_t address) { } const uint32_t r1 = static_cast(context->r[1]); + // rN..r31 are saved contiguously below the LR word at -8(r1): read the + // whole save area at once (the per-register loop below reports faults). + { + const uint32_t base = r1 - 16u - (31u - first_gpr) * 8u; + const uint32_t size = (32u - first_gpr) * 8u + 4u; + uint8_t area[18 * 8 + 4]; + if (ReadSparseGuestMemory(base, area, size)) { + for (uint32_t reg = first_gpr; reg <= 31u; ++reg) { + context->r[reg] = ReadBigEndian64(area + (reg - first_gpr) * 8u); + } + context->lr = ReadBigEndian32(area + (32u - first_gpr) * 8u); + R360_VERBOSE_TRACE( + "R360_EPILOG_HELPER executed target=0x%08X first_gpr=%u r1=0x%08X lr=0x%08X\n", + address, first_gpr, r1, static_cast(context->lr)); + return true; + } + } for (uint32_t reg = first_gpr; reg <= 31u; ++reg) { const int32_t disp = -16 - int32_t(31u - reg) * 8; const uint32_t ea = r1 + static_cast(disp); @@ -304,7 +336,33 @@ struct CachedTranslation { JitSlot jit; // compiled code for this translation (hir_wasm_jit.h) uint32_t hir_blocks = 0, hir_instructions = 0; }; -std::unordered_map g_translation_cache; +// libc++ hashes a 64-bit key with a byte-wise murmur on wasm32 (size_t is +// 32 bits); translation keys are looked up on every guest call. +struct TranslationKeyHash { + size_t operator()(uint64_t key) const { + return size_t(((key >> 32) ^ key) * 0x9E3779B97F4A7C15ull >> 32); + } +}; +std::unordered_map g_translation_cache; +// Second tier: evicted translations whose compiled code needs no HIR +// (JitSlot::builder_free) keep only that code here, so a function that +// falls out of the HIR budget runs compiled again without retranslating or +// recompiling. Entries have no builder; interior entries (which run HIR) and +// interpreter-only runs still translate afresh. +std::unordered_map g_compiled_only_cache; +constexpr size_t kCompiledOnlyCacheLimit = 65536; +uint64_t g_compiled_only_hits = 0; +// Any insert into or erase from either cache map. +uint32_t g_cache_epoch = 1; +// Stands in for the freed builder: ExecuteHIRCorrectnessProbe only matches it +// against the JIT candidate (JitSetCandidate) and runs the compiled code. +xe::cpu::hir::HIRBuilder* CompiledOnlyBuilder() { + static auto* stub = new xe::cpu::hir::HIRBuilder(); + return stub; +} +xe::cpu::hir::HIRBuilder* ExecutionBuilder(CachedTranslation& entry) { + return entry.builder ? entry.builder.get() : CompiledOnlyBuilder(); +} size_t g_translation_cache_bytes = 0; size_t g_translation_cache_budget = size_t(192) * 1024 * 1024; uint64_t g_translation_cache_clock = 0; @@ -324,8 +382,12 @@ uint64_t TranslationKey(uint32_t begin, uint32_t end, bool fragment) { return (uint64_t(begin) << 32) | (uint64_t(end) & ~3ull) | (fragment ? 1u : 0u); } +// Bytes held by every Xenia arena chunk (prepare-xenia-arena-overlay.py); +// retained translations are nearly all of it. +size_t TranslationCacheLiveBytes() { return xe::g_r360_arena_live_bytes; } + void EvictTranslations() { - while (g_translation_cache_bytes > g_translation_cache_budget) { + while (TranslationCacheLiveBytes() > g_translation_cache_budget) { auto victim = g_translation_cache.end(); for (auto it = g_translation_cache.begin(); it != g_translation_cache.end(); ++it) { if (it->second.pins) continue; @@ -336,8 +398,23 @@ void EvictTranslations() { } if (victim == g_translation_cache.end()) return; g_translation_cache_bytes -= victim->second.bytes; + CachedTranslation& evicted = victim->second; + auto twin = g_compiled_only_cache.find(victim->first); + if (evicted.jit.function && evicted.jit.builder_free && + g_compiled_only_cache.size() < kCompiledOnlyCacheLimit && + (twin == g_compiled_only_cache.end() || !twin->second.pins)) { + CachedTranslation code; + code.begin = evicted.begin; + code.end = evicted.end; + code.generation_begin = evicted.generation_begin; + code.generation_end = evicted.generation_end; + code.jit = evicted.jit; + code.hir_blocks = evicted.hir_blocks; + code.hir_instructions = evicted.hir_instructions; + g_compiled_only_cache.insert_or_assign(victim->first, std::move(code)); ++g_cache_epoch; + } JitReleaseSlot(&victim->second.jit); - g_translation_cache.erase(victim); + g_translation_cache.erase(victim); ++g_cache_epoch; } } @@ -347,9 +424,73 @@ std::unordered_map g_cache_miss_debug; void NoteCacheMiss(uint64_t key, uint32_t reason) { ++g_cache_miss_debug[(uint64_t(reason) << 32) | (key >> 32)]; } -CachedTranslation* LookupTranslation(uint64_t key) { +// Compiled-only entry for `key`, or nullptr (stale ones are dropped). +CachedTranslation* LookupCompiledOnly(uint64_t key) { + auto it = g_compiled_only_cache.find(key); + if (it == g_compiled_only_cache.end()) return nullptr; + CachedTranslation& entry = it->second; + if (entry.generation_begin != GetWasmBackendExecutableContentGeneration(entry.begin) || + entry.generation_end != GetWasmBackendExecutableContentGeneration(entry.end)) { + if (entry.pins) return nullptr; + ++g_cache_epoch; + g_compiled_only_cache.erase(it); + return nullptr; + } + if (!JitEnabled()) return nullptr; + ++g_compiled_only_hits; + return &entry; +} + +CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder); + +// Direct-mapped memo of LookupTranslation results. A slot holds while +// neither cache map has changed and no executable page has been rewritten +// (both epochs unchanged), so a hit needs no hashing or generation checks. +struct LookupMemo { + uint64_t key = 0; + CachedTranslation* entry = nullptr; + uint32_t cache_epoch = 0, content_epoch = 0; + bool compiled_only = false; +}; +std::array g_lookup_memo; +uint64_t g_lookup_memo_hits = 0; + +// `need_builder`: the caller runs the HIR itself (an interior entry), so a +// compiled-only entry does not count. +CachedTranslation* LookupTranslation(uint64_t key, bool need_builder = false) { + if (need_builder) return LookupTranslationSlow(key, true); + LookupMemo& memo = g_lookup_memo[TranslationKeyHash{}(key) & 4095u]; + const uint32_t content_epoch = GetWasmBackendExecutableContentEpoch(); + if (memo.entry && memo.key == key && memo.cache_epoch == g_cache_epoch && + memo.content_epoch == content_epoch && (!memo.compiled_only || JitEnabled())) { + ++g_lookup_memo_hits; + if (memo.compiled_only) { + ++g_compiled_only_hits; + } else { + memo.entry->last_use = ++g_translation_cache_clock; + } + return memo.entry; + } + CachedTranslation* entry = LookupTranslationSlow(key, false); + // The slow lookup may have erased a stale entry (epoch bumped): record the + // epochs after it. + memo.key = key; + memo.entry = entry; + memo.cache_epoch = g_cache_epoch; + memo.content_epoch = GetWasmBackendExecutableContentEpoch(); + memo.compiled_only = entry && !entry->builder; + return entry; +} + +CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder) { auto it = g_translation_cache.find(key); - if (it == g_translation_cache.end()) { NoteCacheMiss(key, 0); return nullptr; } + if (it == g_translation_cache.end()) { + if (!need_builder) { + if (CachedTranslation* code = LookupCompiledOnly(key)) return code; + } + NoteCacheMiss(key, 0); + return nullptr; + } CachedTranslation& entry = it->second; if (entry.generation_begin != GetWasmBackendExecutableContentGeneration(entry.begin) || entry.generation_end != GetWasmBackendExecutableContentGeneration(entry.end)) { @@ -357,6 +498,7 @@ CachedTranslation* LookupTranslation(uint64_t key) { NoteCacheMiss(key, 1); g_translation_cache_bytes -= entry.bytes; JitReleaseSlot(&entry.jit); + ++g_cache_epoch; g_translation_cache.erase(it); return nullptr; } @@ -364,27 +506,48 @@ CachedTranslation* LookupTranslation(uint64_t key) { return &entry; } +// A nested call's first run after a translation miss: ProbeAssembler::Assemble +// skips executing a builder about to be retained, and DefineOrRunCached runs +// it from its new cache entry instead, so that run already has a JIT slot +// (compilation by call count, on-stack replacement of a long first run). +// Per guest thread: a fiber can switch while a translation that was not +// deferred runs guest code inside Assemble. +R360_FIBER_LOCAL bool g_defer_first_run = false; // DefineOrRunCached is translating +R360_FIBER_LOCAL bool g_deferred_first_run = false; // Assemble skipped the run +bool CanRetainTranslatedBuilder() { + if (!g_retain_pending) return false; + auto it = g_translation_cache.find(g_retain_key); + return it == g_translation_cache.end() || !it->second.pins; +} + // Runs a cached translation as ProbeAssembler::Assemble runs a nested one. -bool ExecuteCachedTranslation(CachedTranslation& entry) { +bool ExecuteCachedTranslation(CachedTranslation& entry, bool count_hit = true) { auto* memory = g_probe_backend && g_probe_backend->processor() ? g_probe_backend->processor()->memory() : nullptr; if (!memory) return false; - ++g_translation_cache_hits; + if (count_hit) ++g_translation_cache_hits; ++entry.pins; NoteTrapPhase(kTrapPhaseExecute, entry.begin); - JitSetCandidate(entry.builder.get(), &entry.jit); - const HIRCorrectnessResult result = - ExecuteHIRCorrectnessProbe(entry.builder.get(), memory); + xe::cpu::hir::HIRBuilder* const builder = ExecutionBuilder(entry); + JitSetCandidate(builder, &entry.jit); + const HIRCorrectnessResult result = ExecuteHIRCorrectnessProbe(builder, memory); --entry.pins; + if (!(result.supported && result.reached_return_boundary)) { + R360_VERBOSE_TRACE("R360_CACHED_RUN_FAILED begin=0x%08X compiled_only=%u jit=%u supported=%u returned=%u blocker=%u@0x%08X instr=%u\n", + entry.begin, entry.builder ? 0u : 1u, entry.jit.function, + result.supported ? 1u : 0u, result.reached_return_boundary ? 1u : 0u, + result.blocker_kind, result.blocker_address, result.instructions_executed); + } return result.supported && result.reached_return_boundary; } // DefineFunction (translate + execute), or the cached translation of the same // function. The interior entry and provenance mode are applied by the caller. bool DefineOrRunCached(xe::cpu::ppc::PPCFrontend* frontend, - xe::cpu::GuestFunction* function, uint64_t key) { - if (CachedTranslation* cached = LookupTranslation(key)) { + xe::cpu::GuestFunction* function, uint64_t key, + bool need_builder = false) { + if (CachedTranslation* cached = LookupTranslation(key, need_builder)) { return ExecuteCachedTranslation(*cached); } ++g_translation_cache_misses; @@ -395,7 +558,22 @@ bool DefineOrRunCached(xe::cpu::ppc::PPCFrontend* frontend, g_retain_key = key; g_retain_begin = function->address(); g_retain_end = function->end_address(); - const bool ok = frontend->DefineFunction(function, 0); + const bool saved_defer = g_defer_first_run; + g_defer_first_run = true; + g_deferred_first_run = false; + bool ok = frontend->DefineFunction(function, 0); + g_defer_first_run = saved_defer; + if (g_deferred_first_run) { + g_deferred_first_run = false; + // RetainTranslatedBuilder pinned the entry so nothing evicted it. + auto it = g_translation_cache.find(key); + if (!ok || it == g_translation_cache.end()) { + ok = false; + } else { + --it->second.pins; + ok = ExecuteCachedTranslation(it->second, false); + } + } if (g_retain_pending) NoteCacheMiss(key, ok ? 4u : 5u); // not retained g_retain_pending = saved_pending; g_retain_key = saved_key; @@ -448,8 +626,31 @@ bool TranslateNestedGuestAddress(uint32_t address, xe::cpu::Module* module) { return ok; } +bool TranslateNestedGuestAddressFull(uint32_t address, xe::cpu::Module* module, + uint32_t call_flags); + +// The common case of TranslateNestedGuestAddressFull, kept small: a plain +// (non-tail) call to a function with a cached translation. Tail calls (owner +// and epilogue handling), import thunks and misses take the full path. bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, uint32_t call_flags) { + if (!(call_flags & xe::cpu::hir::CALL_TAIL) && !IsKernelImportThunk(address) && + StackHeadroom() >= kMinNestedStackHeadroom) { + if (CachedTranslation* cached = LookupTranslation(TranslationKey(address, 0u, false))) { + SetHIRCorrectnessExecutionEntry(0u); + NoteTrapPhase(kTrapPhaseTranslate, address); + ++g_trap_depth; + const bool translated = ExecuteCachedTranslation(*cached); + --g_trap_depth; + SetHIRCorrectnessExecutionEntry(0u); + return translated; + } + } + return TranslateNestedGuestAddressFull(address, module, call_flags); +} + +__attribute__((noinline)) bool TranslateNestedGuestAddressFull( + uint32_t address, xe::cpu::Module* module, uint32_t call_flags) { // Registered kernel/XAM import thunks are resolved before the bounded probe // memory check. Real XEX thunks may live outside the entry's 64 KiB staging // window, but a known HLE import is an external call boundary, not guest code @@ -502,6 +703,10 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, struct CallTargetClass { uint32_t address = 0, fn_begin = 0, fn_end = 0, prolog = 0; bool valid = false, pdata = false, epilog_meta = false; + // MatchSharedEpilogReturnSignature reads the code at `address`; cached + // per content generation of the (at most two) pages it reads. + bool signature_checked = false, signature_match = false; + uint32_t signature_first_gpr = 0, signature_generation[2] = {}; }; static std::array call_classes; if (g_call_class_generation != g_call_class_seen_generation) { @@ -520,8 +725,21 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, } const bool epilog_by_metadata = cls.epilog_meta; uint32_t signature_first_gpr = 0; - const bool epilog_by_signature = - is_tail && MatchSharedEpilogReturnSignature(address, &signature_first_gpr); + bool epilog_by_signature = false; + if (is_tail) { + // The signature spans at most 21 words from `address` (r14..r31 + 3). + const uint32_t g0 = GetWasmBackendExecutableContentGeneration(address); + const uint32_t g1 = GetWasmBackendExecutableContentGeneration(address + 20u * 4u); + if (!cls.signature_checked || cls.signature_generation[0] != g0 || + cls.signature_generation[1] != g1) { + cls.signature_match = MatchSharedEpilogReturnSignature(address, &cls.signature_first_gpr); + cls.signature_generation[0] = g0; + cls.signature_generation[1] = g1; + cls.signature_checked = true; + } + epilog_by_signature = cls.signature_match; + signature_first_gpr = cls.signature_first_gpr; + } const bool is_epilog_return = epilog_by_metadata || epilog_by_signature; if (is_tail && is_epilog_return) { @@ -593,7 +811,13 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, "depth=%u\n", address, g_trap_depth); return false; } - ProbeGuestFunction nested_function(module, fn_begin); + // Only a translation miss scans or defines the function: a cached + // translation runs without constructing the guest function object. + std::optional nested_storage; + auto nested = [&]() -> ProbeGuestFunction& { + if (!nested_storage) nested_storage.emplace(module, fn_begin); + return *nested_storage; + }; uint32_t scan_end = use_owner ? fn_end - 4 : 0u; // Decoder-window-relative scan bound, valid once the code is paged. auto set_scan_end = [&]() -> bool { @@ -601,7 +825,7 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, const uint32_t loaded_size = r360_ppc_probe_loaded_size(); if (loaded_size < 4) return false; scan_end = use_owner ? fn_end - 4 : loaded_base + loaded_size - 4; - nested_function.set_end_address(scan_end); + nested().set_end_address(scan_end); return true; }; @@ -615,19 +839,20 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, g_missing_interior_entries.count((owner_key << 0) ^ (uint64_t(interior_entry) * 0x9E3779B97F4A7C15ull)); // The PPC scan only feeds a new translation: a cached one runs as is (its // key does not depend on the scan). - CachedTranslation* const cached_owner = known_missing ? nullptr : LookupTranslation(owner_key); + CachedTranslation* const cached_owner = + known_missing ? nullptr : LookupTranslation(owner_key, interior_entry != 0); if (!cached_owner && !known_missing) { if (!page_code() || !set_scan_end()) return false; xe::cpu::ppc::PPCScanner scanner(frontend); - if (!scanner.Scan(&nested_function, nullptr)) { + if (!scanner.Scan(&nested(), nullptr)) { std::fprintf(stderr, "R360_CALL_RESOLVE scan failed target=0x%08X function=0x%08X " "owner=%u\n", address, fn_begin, use_owner ? 1u : 0u); return false; } - if (use_owner && nested_function.end_address() < address) { - nested_function.set_end_address(scan_end); + if (use_owner && nested().end_address() < address) { + nested().set_end_address(scan_end); } } if (interior_entry) { @@ -643,7 +868,8 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, NoteTrapPhase(kTrapPhaseTranslate, address); ++g_trap_depth; translated = cached_owner ? ExecuteCachedTranslation(*cached_owner) - : DefineOrRunCached(frontend, &nested_function, owner_key); + : DefineOrRunCached(frontend, &nested(), owner_key, + interior_entry != 0); --g_trap_depth; SetHIRCorrectnessExecutionEntry(0u); missing_entry = interior_entry ? ConsumeHIRCorrectnessInteriorEntryMissing() : 0u; @@ -654,7 +880,7 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, R360_VERBOSE_TRACE( "R360_CALL_RESOLVE translated target=0x%08X function=0x%08X " "end=0x%08X flags=0x%X owner=%u interior=0x%08X result=%u\n", - address, fn_begin, nested_function.end_address(), call_flags, + address, fn_begin, nested().end_address(), call_flags, use_owner ? 1u : 0u, interior_entry, translated ? 1u : 0u); // A compiler tail target may be a valid PPC instruction without surviving as @@ -730,35 +956,47 @@ void RetainTranslatedBuilder(std::unique_ptr builder) g_translation_cache_bytes -= it->second.bytes; JitReleaseSlot(&it->second.jit); g_translation_cache.erase(it); + ++g_cache_epoch; + } + if (auto code = g_compiled_only_cache.find(g_retain_key); + code != g_compiled_only_cache.end() && !code->second.pins) { + g_compiled_only_cache.erase(code); ++g_cache_epoch; } CachedTranslation entry; entry.begin = g_retain_begin; entry.end = g_retain_end ? g_retain_end : g_retain_begin; entry.generation_begin = GetWasmBackendExecutableContentGeneration(entry.begin); entry.generation_end = GetWasmBackendExecutableContentGeneration(entry.end); - // Arena use is private to Xenia; an HIR instruction plus its result value - // and operand uses is about 192 bytes, plus the 64 KiB first arena chunk. + // Per-entry estimate (an HIR instruction with its value and uses is about + // 192 bytes, plus a part-used 64 KiB arena chunk); the budget itself is + // checked against the real arena bytes (EvictTranslations). size_t instructions = 0; for (auto* block = builder->first_block(); block; block = block->next) { for (auto* instr = block->instr_head; instr; instr = instr->next) ++instructions; } - entry.bytes = instructions * 192 + 64 * 1024; + entry.bytes = instructions * 192 + 32 * 1024; entry.hir_instructions = uint32_t(instructions); for (auto* block = builder->first_block(); block; block = block->next) ++entry.hir_blocks; entry.last_use = ++g_translation_cache_clock; + if (g_deferred_first_run) entry.pins = 1; // until DefineOrRunCached runs it entry.builder = std::move(builder); g_translation_cache_bytes += entry.bytes; - g_translation_cache.emplace(g_retain_key, std::move(entry)); + g_translation_cache.emplace(g_retain_key, std::move(entry)); ++g_cache_epoch; EvictTranslations(); } void ResetTranslationCache() { + ++g_cache_epoch; for (auto it = g_translation_cache.begin(); it != g_translation_cache.end();) { if (it->second.pins) { ++it; continue; } g_translation_cache_bytes -= it->second.bytes; JitReleaseSlot(&it->second.jit); it = g_translation_cache.erase(it); } + for (auto it = g_compiled_only_cache.begin(); it != g_compiled_only_cache.end();) { + it = it->second.pins ? std::next(it) : g_compiled_only_cache.erase(it); + } g_translation_cache_hits = g_translation_cache_misses = 0; + g_compiled_only_hits = 0; g_missing_interior_entries.clear(); ++g_call_class_generation; g_retain_pending = false; @@ -787,7 +1025,7 @@ bool DefineTopLevelCached(xe::cpu::ppc::PPCFrontend* frontend, ? g_probe_backend->processor()->memory() : nullptr; if (memory && GetProbeExecuteCorrectnessOnAssemble() && !IsHIRCorrectnessExecutionActive()) { - if (CachedTranslation* cached = LookupTranslation(key)) { + if (CachedTranslation* cached = LookupTranslation(key, true)) { ++g_translation_cache_hits; ++cached->pins; NoteTrapPhase(kTrapPhaseExecute, cached->begin); @@ -887,7 +1125,13 @@ bool ProbeAssembler::Assemble(xe::cpu::GuestFunction* function, xe::cpu::hir::HI } HIRCorrectnessResult correctness; - if (execute_correctness) { + if (nested_execution && g_defer_first_run && !g_deferred_first_run && + CanRetainTranslatedBuilder()) { + // DefineOrRunCached runs it once it is retained (see g_defer_first_run). + g_deferred_first_run = true; + correctness.supported = true; + correctness.reached_return_boundary = true; + } else if (execute_correctness) { NoteTrapPhase(kTrapPhaseExecute, function ? function->address() : 0u); correctness = ExecuteHIRCorrectnessProbe(builder, memory); } else { @@ -987,8 +1231,8 @@ void render360_wasi_initialize() { #endif R360_WASM_EXPORT("r360_trap_reason") -uint32_t r360_trap_reason() { - return static_cast(reinterpret_cast(render360::xenia_web::g_trap_reason)); +uintptr_t r360_trap_reason() { + return reinterpret_cast(render360::xenia_web::g_trap_reason); } R360_WASM_EXPORT("r360_trap_reason_length") uint32_t r360_trap_reason_length() { @@ -1021,7 +1265,10 @@ extern "C" { uint32_t r360_hir_cache_hits() { return uint32_t(render360::xenia_web::g_translation_cache_hits); } uint32_t r360_hir_cache_misses() { return uint32_t(render360::xenia_web::g_translation_cache_misses); } uint32_t r360_hir_cache_entries() { return uint32_t(render360::xenia_web::g_translation_cache.size()); } -uint32_t r360_hir_cache_kilobytes() { return uint32_t(render360::xenia_web::g_translation_cache_bytes / 1024); } +uint32_t r360_hir_cache_compiled_only_entries() { return uint32_t(render360::xenia_web::g_compiled_only_cache.size()); } +uint32_t r360_hir_cache_memo_hits() { return uint32_t(render360::xenia_web::g_lookup_memo_hits); } +uint32_t r360_hir_cache_compiled_only_hits() { return uint32_t(render360::xenia_web::g_compiled_only_hits); } +uint32_t r360_hir_cache_kilobytes() { return uint32_t(render360::xenia_web::TranslationCacheLiveBytes() / 1024); } uint32_t r360_hir_cache_set_budget_mb(uint32_t megabytes) { if (megabytes) render360::xenia_web::g_translation_cache_budget = size_t(megabytes) * 1024 * 1024; render360::xenia_web::EvictTranslations(); diff --git a/src/xenia_web_bootstrap/sparse_guest_memory.cpp b/src/xenia_web_bootstrap/sparse_guest_memory.cpp index c2aca660..3ce634ce 100644 --- a/src/xenia_web_bootstrap/sparse_guest_memory.cpp +++ b/src/xenia_web_bootstrap/sparse_guest_memory.cpp @@ -16,6 +16,12 @@ extern "C" __attribute__((weak)) uint32_t r360_debug_watch_address() { return 0; extern "C" __attribute__((weak)) uint32_t r360_guest_thread_current() { return 0; } extern "C" __attribute__((weak)) uint32_t r360_hir_last_source() { return 0; } +#if defined(R360_NATIVE) && defined(__APPLE__) +#include +#include +#define R360_FLAT_GUEST_MEMORY 1 +#endif + namespace render360::xenia_web { namespace { @@ -33,8 +39,74 @@ enum FaultCode : uint32_t { kFaultAlreadyMapped = 5, }; +#if defined(R360_FLAT_GUEST_MEMORY) +// Native flat guest memory (Xenia's Memory layout, as XeniOS on 16 KiB-page +// Apple hosts): the 4 GiB guest space plus 0x1000 is one reservation at +// g_flat_base; 0x00000000-0x9FFFFFFF is plain host memory and the three +// physical views 0xA0000000 / 0xC0000000 / 0xE0000000 map one 512 MiB +// physical object. The E0 view's 4 KiB physical offset is applied on the CPU +// side (Xenia's host_address_offset): guest E0000000+x lives at host +// base + E0000000 + x + 0x1000. Every guest page then has a fixed host +// address (base + address [+ 0x1000]), which statically recompiled code +// (XenonRecomp: base + address) needs. Page table, protection and watches +// are unchanged. +uint8_t* g_flat_base = nullptr; +constexpr uint64_t kFlatReserve = 0x100000000ull + 0x10000ull; +constexpr uint64_t kPhysicalSize = 0x20000000ull; + +inline uint8_t* FlatHost(uint32_t address) { + return g_flat_base + address + (address >= 0xE0000000u ? 0x1000u : 0u); +} + +bool MapPhysicalView(mach_port_t entry, uint64_t guest) { + // vm_map (mach_vm_map is not in the iOS SDK; addresses are 64-bit on arm64). + vm_address_t at = vm_address_t(g_flat_base + guest); + const kern_return_t kr = vm_map(mach_task_self(), &at, vm_size_t(kPhysicalSize), 0, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, + entry, 0, FALSE, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE, + VM_INHERIT_NONE); + if (kr != KERN_SUCCESS) std::fprintf(stderr, "R360_FLAT_MEMORY view 0x%llX: mach_vm_map %d\n", (unsigned long long)guest, kr); + return kr == KERN_SUCCESS; +} + +// (Re)creates the layout: fresh zeroed memory everywhere. +bool CreateFlatGuestMemory() { + if (g_flat_base) munmap(g_flat_base, kFlatReserve); + g_flat_base = nullptr; + void* base = mmap(nullptr, kFlatReserve, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (base == MAP_FAILED) { + std::fprintf(stderr, "R360_FLAT_MEMORY reserve failed\n"); + return false; + } + g_flat_base = static_cast(base); + // One named (shareable) memory object for the 512 MiB of physical memory. + memory_object_size_t size = kPhysicalSize; + mach_port_t entry = MACH_PORT_NULL; + const kern_return_t kr = mach_make_memory_entry_64(mach_task_self(), &size, 0, + MAP_MEM_NAMED_CREATE | VM_PROT_READ | VM_PROT_WRITE, &entry, + MACH_PORT_NULL); + if (kr != KERN_SUCCESS) { + std::fprintf(stderr, "R360_FLAT_MEMORY physical object: %d\n", kr); + return false; + } + const bool ok = MapPhysicalView(entry, 0xA0000000ull) && MapPhysicalView(entry, 0xC0000000ull) && + MapPhysicalView(entry, 0xE0000000ull); + mach_port_deallocate(mach_task_self(), entry); // the views keep the object + if (!ok) std::fprintf(stderr, "R360_FLAT_MEMORY failed to map the physical views\n"); + return ok; +} + +// Zeroes guest pages that are no longer mapped (fresh backings start zeroed). +void ZeroFlatPages(uint32_t address, uint32_t page_count) { + if (!g_flat_base) return; + std::memset(FlatHost(address), 0, size_t(page_count) * kPageSize); +} +#endif + struct Backing { + // Browser build: the backing's own pages. Native flat build: unused (every + // guest page has its fixed host address), only page_count matters. std::vector> pages; + uint32_t page_count = 0; // Number of executable virtual aliases of each backing page. Sized once at // allocation so page-table entries can hold stable pointers into it. std::vector executable_aliases; @@ -70,11 +142,14 @@ constexpr uint32_t kDirectoryEntries = 1u << (32u - kDirectoryShift); std::vector g_backings; std::array g_page_directory{}; -// Generated guest code (hir_wasm_jit.cpp) walks this table inline. +// Generated guest code (hir_wasm_jit.cpp) walks this table inline. The +// native build has no wasm JIT and 64-bit host pointers. +#if !defined(R360_NATIVE) static_assert(sizeof(PageEntry) == 20 && offsetof(PageEntry, host) == 0 && offsetof(PageEntry, executable_aliases) == 4 && offsetof(PageEntry, protection) == 16, "guest JIT inline page walk layout"); +#endif uint32_t g_mapped_pages = 0; // Executable virtual pages aliasing each physical sparse backing page. Guest // RAM writes are extremely hot; they check the per-page alias count and only @@ -83,7 +158,10 @@ std::map, std::set> g_executable_aliases // This is the authoritative executable-byte content generation. It is sparse // across the full 32-bit Xbox virtual address space and is intentionally // independent of permission/mapping invalidation and the legacy backend epoch. -std::map g_executable_content_generations; +// Two-level table (same split as g_page_directory): translation-cache lookups +// read two generations per guest call, so this must be a couple of loads. +// A zero entry means the default generation 1. +std::array g_executable_content_generations{}; uint32_t g_last_fault_address = 0; uint32_t g_last_fault_code = kFaultNone; @@ -108,14 +186,23 @@ bool PageRangeValid(uint32_t address, uint32_t page_count) { uint32_t ContentGeneration(uint32_t address) { const uint32_t page = address >> kPageShift; - auto it = g_executable_content_generations.find(page); - return it == g_executable_content_generations.end() ? 1u : it->second; + const uint32_t* table = g_executable_content_generations[page >> kTableBits]; + if (!table) return 1u; + const uint32_t generation = table[page & (kTableEntries - 1u)]; + return generation ? generation : 1u; } +// Bumped with every content generation change (and on reset), so a cache of +// generation checks can tell nothing has been rewritten. +uint32_t g_executable_content_epoch = 1; + void BumpContentGeneration(uint32_t page) { - auto [it, inserted] = g_executable_content_generations.emplace(page, 1u); - ++it->second; - if (it->second == 0) it->second = 1u; + ++g_executable_content_epoch; + uint32_t*& table = g_executable_content_generations[page >> kTableBits]; + if (!table) table = new uint32_t[kTableEntries](); + uint32_t& generation = table[page & (kTableEntries - 1u)]; + generation = (generation ? generation : 1u) + 1u; + if (generation == 0) generation = 1u; } Backing* GetBacking(uint32_t backing_id) { @@ -230,19 +317,27 @@ void MarkWasmBackendExecutableContentChangedRange(uint32_t address, InvalidateWasmBackendExecutableRange(address, size); } +uint32_t GetWasmBackendExecutableContentEpoch() { return g_executable_content_epoch; } uint32_t GetWasmBackendExecutableContentGeneration(uint32_t address) { return ContentGeneration(address); } void ResetSparseGuestMemory() { + ++g_executable_content_epoch; for (PageEntry*& table : g_page_directory) { delete[] table; table = nullptr; } g_mapped_pages = 0; g_backings.clear(); +#if defined(R360_FLAT_GUEST_MEMORY) + if (g_flat_base) CreateFlatGuestMemory(); +#endif g_executable_aliases.clear(); - g_executable_content_generations.clear(); + for (uint32_t*& table : g_executable_content_generations) { + delete[] table; + table = nullptr; + } ClearFault(); } @@ -253,8 +348,16 @@ uint32_t AllocateSparseGuestBacking(uint32_t page_count) { return 0; } Backing backing; + backing.page_count = page_count; +#if defined(R360_FLAT_GUEST_MEMORY) + if (!g_flat_base && !CreateFlatGuestMemory()) { + Fault(0, kFaultInvalidArgument); + return 0; + } +#else // resize() value-initializes: every page starts zero-filled. backing.pages.resize(page_count); +#endif backing.executable_aliases.resize(page_count); backing.gpu_generation.assign(page_count, 1u); g_backings.push_back(std::move(backing)); @@ -271,7 +374,7 @@ bool MapSparseGuestMemory(uint32_t virtual_address, uint32_t page_count, } Backing* backing = GetBacking(backing_id); if (!backing || uint64_t(backing_page_offset) + page_count > - backing->pages.size()) { + backing->page_count) { return Fault(virtual_address, kFaultInvalidArgument); } const uint32_t first_page = virtual_address >> kPageShift; @@ -283,7 +386,14 @@ bool MapSparseGuestMemory(uint32_t virtual_address, uint32_t page_count, for (uint32_t i = 0; i < page_count; ++i) { const uint32_t backing_page = backing_page_offset + i; PageEntry* entry = EnsurePageSlot(first_page + i); +#if defined(R360_FLAT_GUEST_MEMORY) + entry->host = FlatHost((first_page + i) << kPageShift); + // A fresh backing reads zeros: clear plain memory and the first (A0) + // physical view; the C0 / E0 views of the same pages alias it. + if (((first_page + i) << kPageShift) < 0xC0000000u) std::memset(entry->host, 0, kPageSize); +#else entry->host = backing->pages[backing_page].data(); +#endif entry->executable_aliases = &backing->executable_aliases[backing_page]; entry->backing_id = backing_id; entry->backing_page = backing_page; @@ -354,6 +464,11 @@ bool UnmapSparseGuestMemory(uint32_t virtual_address, uint32_t page_count) { InvalidateWasmBackendExecutableRange((first_page + i) << kPageShift, kPageSize); } +#if defined(R360_FLAT_GUEST_MEMORY) + // Physical views alias: only plain virtual memory is cleared on unmap + // (the next allocation there must read zeros). + if (((first_page + i) << kPageShift) < 0xA0000000u) ZeroFlatPages((first_page + i) << kPageShift, 1); +#endif entry = PageEntry{}; --g_mapped_pages; } @@ -494,7 +609,7 @@ uint32_t SparseGuestMappedPageCount() { return g_mapped_pages; } uint32_t SparseGuestBackingPageCount() { uint64_t total = 0; - for (const auto& backing : g_backings) total += backing.pages.size(); + for (const auto& backing : g_backings) total += backing.page_count; return total > UINT32_MAX ? UINT32_MAX : static_cast(total); } @@ -633,7 +748,16 @@ namespace render360::xenia_web { // Address of the two-level guest page directory (1024 PageEntry* slots, each // table 1024 x 20-byte entries: host, executable_aliases, backing id/page, // protection), for the guest JIT's inline loads and stores. +#if defined(R360_FLAT_GUEST_MEMORY) +uint8_t* SparseGuestFlatBase() { return g_flat_base; } +#else +uint8_t* SparseGuestFlatBase() { return nullptr; } +#endif uint32_t SparseGuestPageDirectoryAddress() { return uint32_t(reinterpret_cast(g_page_directory.data())); } } // namespace render360::xenia_web + +extern "C" uintptr_t r360_flat_guest_base() { + return reinterpret_cast(render360::xenia_web::SparseGuestFlatBase()); +} diff --git a/src/xenia_web_bootstrap/sparse_guest_memory.h b/src/xenia_web_bootstrap/sparse_guest_memory.h index a042fd1a..ff61591f 100644 --- a/src/xenia_web_bootstrap/sparse_guest_memory.h +++ b/src/xenia_web_bootstrap/sparse_guest_memory.h @@ -46,6 +46,10 @@ uint32_t SparseGuestBackingPageCount(); uint32_t SparseGuestLastFaultAddress(); uint32_t SparseGuestLastFaultCode(); +// Native build: host address of guest address 0 in the flat guest memory +// layout (statically recompiled code accesses base + address; addresses at +// or above 0xE0000000 add 0x1000). Null in the browser build. +uint8_t* SparseGuestFlatBase(); } // namespace render360::xenia_web extern "C" { diff --git a/src/xenia_web_bootstrap/title_gpu_runtime.cpp b/src/xenia_web_bootstrap/title_gpu_runtime.cpp index 1fc689b1..daede5db 100644 --- a/src/xenia_web_bootstrap/title_gpu_runtime.cpp +++ b/src/xenia_web_bootstrap/title_gpu_runtime.cpp @@ -6,9 +6,11 @@ #include "sparse_guest_memory.h" extern "C" __attribute__((weak)) uint32_t r360_guest_thread_current() { return 0; } +extern "C" __attribute__((weak)) uint64_t r360_guest_clock_ns() { return 0; } +extern "C" __attribute__((weak)) uint32_t r360_kernel_vblank_interrupts() { return 0; } extern "C" { void r360_xenos_reset(); -uint32_t r360_xenos_ring_buffer(); +uintptr_t r360_xenos_ring_buffer(); uint32_t r360_xenos_ring_capacity(); uint32_t r360_xenos_submit(uint32_t words); uint32_t r360_xenos_status(); @@ -227,7 +229,7 @@ bool DrainPendingRingToXenos() { ? g_write_pointer - g_read_pointer : (capacity - g_read_pointer) + g_write_pointer; const uint32_t decoder_capacity = r360_xenos_ring_capacity(); - const uint32_t decoder_ptr = r360_xenos_ring_buffer(); + const uintptr_t decoder_ptr = r360_xenos_ring_buffer(); if (!pending || !decoder_ptr || pending > decoder_capacity) { ++g_xenos_rejections; g_last_xenos_status = r360_xenos_status(); @@ -417,8 +419,18 @@ bool WriteTitleGpuMmio(uint32_t address, uint32_t value) { switch (RegisterIndex(address)) { case kRegisterCpRbWptr: if (r360_xenos_trace_ibs(2) & 1u) { - std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X\n", - g_write_pointer, value, g_read_pointer, r360_guest_thread_current()); + std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X us=%llu vblank=%u words=", + g_write_pointer, value, g_read_pointer, r360_guest_thread_current(), + static_cast(r360_guest_clock_ns() / 1000u), + r360_kernel_vblank_interrupts()); + const uint32_t capacity = RingCapacityInternal(); + for (uint32_t i = g_write_pointer, n = 0; capacity && i != value && n < 16u; + i = (i + 1u) % capacity, ++n) { + uint32_t word = 0; + ReadRingWordInternal(i, &word); + std::fprintf(stderr, "%08X ", word); + } + std::fprintf(stderr, "\n"); } g_write_pointer = value; if (g_ring_base) g_status = g_status < 2u ? 2u : g_status; diff --git a/src/xenia_web_bootstrap/wasm_backend_call_probe.h b/src/xenia_web_bootstrap/wasm_backend_call_probe.h index 5a50c956..dba63fd9 100644 --- a/src/xenia_web_bootstrap/wasm_backend_call_probe.h +++ b/src/xenia_web_bootstrap/wasm_backend_call_probe.h @@ -22,6 +22,8 @@ void MarkWasmBackendExecutableContentChangedRange(uint32_t address, uint32_t size); uint32_t GetWasmBackendExecutablePageGeneration(uint32_t address); uint32_t GetWasmBackendExecutableContentGeneration(uint32_t address); +// Changes whenever any executable content generation changes. +uint32_t GetWasmBackendExecutableContentEpoch(); uint32_t GetWasmBackendCallStatus(); uint32_t GetWasmBackendCallFunctionCount(); uint32_t GetWasmBackendCallFunctionAddress(uint32_t index); diff --git a/src/xenia_web_bootstrap/webgpu_backend.cpp b/src/xenia_web_bootstrap/webgpu_backend.cpp new file mode 100644 index 00000000..87535cb6 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_backend.cpp @@ -0,0 +1,136 @@ +// WebGPU Xenos backend (see webgpu_backend.h, docs/gpu/WEBGPU_BACKEND.md). +#include "webgpu_backend.h" + +#include +#include + +#include "sparse_guest_memory.h" + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace render360::xenia_web { + +uint32_t* GpuCommandStream::Begin(GpuStreamOp op, uint32_t words) { + const size_t at = words_.size(); + words_.resize(at + 1 + words); + words_[at] = uint32_t(op) | (words << 8); + return words_.data() + at + 1; +} + +GpuCommandStream& GpuStream() { + static GpuCommandStream stream; + return stream; +} + +namespace { +// Guest virtual address through which the core maps physical `page`. +uint32_t PageVirtual(uint32_t page) { + return r360_kernel_gpu_address_to_virtual(page << WebGpuSharedMemory::kPageSizeLog2); +} +} // namespace + +void WebGpuSharedMemory::ClearCache() { + valid_generation_.assign(kPageCount, 0u); +} + +bool WebGpuSharedMemory::PageValid(uint32_t page) const { + const uint32_t generation = valid_generation_[page]; + return generation && generation == SparseGuestGpuGeneration(PageVirtual(page)); +} + +void WebGpuSharedMemory::MarkValid(uint32_t page) { + // Arming returns the generation the next CPU write will change. + valid_generation_[page] = SparseGuestGpuWatch(PageVirtual(page)); +} + +void WebGpuSharedMemory::Upload(uint32_t page_first, uint32_t page_count) { + constexpr uint32_t kPageBytes = 1u << kPageSizeLog2; + const uint32_t length = page_count * kPageBytes; + uint32_t* payload = GpuStream().Begin(kGpuStreamUpload, 2 + length / 4); + payload[0] = page_first * kPageBytes; + payload[1] = length; + uint8_t* bytes = reinterpret_cast(payload + 2); + for (uint32_t i = 0; i < page_count; ++i) { + // Unmapped physical pages read as zeros, as never-written GPU memory. + const uint8_t* host = SparseGuestPageHost(PageVirtual(page_first + i)); + if (host) { + std::memcpy(bytes + i * kPageBytes, host, kPageBytes); + } else { + std::memset(bytes + i * kPageBytes, 0, kPageBytes); + } + MarkValid(page_first + i); + } + uploaded_bytes_ += length; + ++upload_ranges_; +} + +bool WebGpuSharedMemory::RequestRange(uint32_t start, uint32_t length) { + // Some texture or buffer is empty: nothing to upload. + if (!length) return true; + if (start > kBufferSize || kBufferSize - start < length) return false; + if (valid_generation_.empty()) ClearCache(); + const uint32_t page_first = start >> kPageSizeLog2; + const uint32_t page_last = (start + length - 1) >> kPageSizeLog2; + // Contiguous runs of pages not valid on the GPU, as Xenia's + // SharedMemory::RequestRange builds its upload_ranges_. + uint32_t run_start = UINT32_MAX; + for (uint32_t page = page_first; page <= page_last; ++page) { + if (!PageValid(page)) { + if (run_start == UINT32_MAX) run_start = page; + continue; + } + if (run_start != UINT32_MAX) { + Upload(run_start, page - run_start); + run_start = UINT32_MAX; + } + } + if (run_start != UINT32_MAX) Upload(run_start, page_last + 1 - run_start); + return true; +} + +void WebGpuSharedMemory::RangeWrittenByGpu(uint32_t start, uint32_t length) { + if (!length || start >= kBufferSize) return; + if (valid_generation_.empty()) ClearCache(); + length = std::min(length, kBufferSize - start); + const uint32_t page_first = start >> kPageSizeLog2; + const uint32_t page_last = (start + length - 1) >> kPageSizeLog2; + for (uint32_t page = page_first; page <= page_last; ++page) MarkValid(page); +} + +WebGpuSharedMemory& GpuSharedMemory() { + static WebGpuSharedMemory shared_memory; + return shared_memory; +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// The recorded command stream (words) for render360-webgpu-xenos.mjs. +__attribute__((used, export_name("r360_gpu_stream_data"))) +uintptr_t r360_gpu_stream_data() { + return (reinterpret_cast(rx::GpuStream().words().data())); +} +__attribute__((used, export_name("r360_gpu_stream_words"))) +uint32_t r360_gpu_stream_words() { return uint32_t(rx::GpuStream().words().size()); } +__attribute__((used, export_name("r360_gpu_stream_reset"))) +void r360_gpu_stream_reset() { rx::GpuStream().Reset(); } + +__attribute__((used, export_name("r360_gpu_shared_memory_request"))) +uint32_t r360_gpu_shared_memory_request(uint32_t start, uint32_t length) { + return rx::GpuSharedMemory().RequestRange(start, length) ? 1u : 0u; +} +__attribute__((used, export_name("r360_gpu_shared_memory_written_by_gpu"))) +void r360_gpu_shared_memory_written_by_gpu(uint32_t start, uint32_t length) { + rx::GpuSharedMemory().RangeWrittenByGpu(start, length); +} +__attribute__((used, export_name("r360_gpu_shared_memory_clear"))) +void r360_gpu_shared_memory_clear() { rx::GpuSharedMemory().ClearCache(); } +__attribute__((used, export_name("r360_gpu_shared_memory_uploaded_kb"))) +uint32_t r360_gpu_shared_memory_uploaded_kb() { + return uint32_t(rx::GpuSharedMemory().uploaded_bytes() / 1024u); +} +__attribute__((used, export_name("r360_gpu_shared_memory_upload_ranges"))) +uint32_t r360_gpu_shared_memory_upload_ranges() { return rx::GpuSharedMemory().upload_ranges(); } +} // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h new file mode 100644 index 00000000..305b14e6 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -0,0 +1,175 @@ +#pragma once + +#include +#include + +// WebGPU Xenos backend (docs/gpu/WEBGPU_BACKEND.md): a port of Xenia's Vulkan +// backend that records a command stream which render360-webgpu-xenos.mjs +// replays into WebGPU, as Xenia's VulkanCommandProcessor records into a +// DeferredCommandBuffer. +namespace render360::xenia_web { + +// Command stream words: [op | (payload words << 8)] then the payload. +enum GpuStreamOp : uint32_t { + // dest offset in the shared memory buffer, byte length, then the bytes + // (padded to 4). Copied at record time: the guest may rewrite the source + // before the stream is replayed. + kGpuStreamUpload = 1, + // A translated shader, once per (ucode, modification): id, stage (0 vertex, + // 1 pixel), texture binding count, sampler binding count, SPIR-V word + // count, then the texture bindings (fetch constant | dimension << 5 | + // signed << 7), the sampler bindings (fetch constant | mag << 5 | min << 7 + // | mip << 9 | aniso << 11) and the SPIR-V words. + kGpuStreamShader = 2, + // A render pipeline, once per description: id, then the + // WebGpuPipelineDescription words. + kGpuStreamPipeline = 3, + // The render targets subsequent draws write: WebGpuRenderTargetsKey words. + kGpuStreamRenderTargets = 4, + // A draw: WebGpuDrawHeader, the system constants, vertex and pixel float + // constants, bool/loop constants, fetch constants, then the indices. + kGpuStreamDraw = 5, + // A swap: the front buffer's texture fetch constant (6 words), its + // texture id (0: none) and the host swizzle to present it with. + kGpuStreamSwap = 6, + // One of Xenia's texture_load_* compute shaders, once: load shader index + // (TextureCache::LoadShaderIndex), SPIR-V word count, SPIR-V. + kGpuStreamLoadShader = 7, + // A texture: id, format (WebGpuTextureFormat), dimension (0 2D array, + // 1 3D, 2 cube), width, height, depth or layers, mip levels. + kGpuStreamTexture = 8, + // Texture data load (webgpu_textures.cpp LoadTextureData): id, load + // shader, expand, scratch size, base offset / size and mips offset / size + // in shared memory, dispatch count, copy count, then the dispatches + // (source, LoadConstants, 3 group counts) and copies (buffer offset, + // bytes per row, rows per image, mip level, layers, width, height, depth). + kGpuStreamTextureLoad = 9, + // Before a resolve copy (VulkanRenderTargetCache::DumpRenderTargets): the + // EDRAM tile span to write from the host render targets owning it into + // the EDRAM buffer: base tiles, row length used, rows, pitch (tiles). + kGpuStreamEdramDump = 10, + // Resolve copy (VulkanRenderTargetCache::Resolve): copy shader + // (draw_util::ResolveCopyShaderIndex, SPIR-V sent as load shader 64 + + // index), the 5 ResolveCopyShaderConstants words (dest_base relative to + // the binding), group counts x / y, shared memory binding offset / size. + kGpuStreamResolve = 11, + // Resolve clear of host render targets: is_depth, EDRAM base tiles, pitch + // tiles, MSAA samples, format, x / y / width / height (pixels from the + // base tile), clear value low / high (guest encoding). + kGpuStreamClear = 12, +}; + +// Pipeline state, following Xenia's VulkanPipelineCache::PipelineDescription. +struct WebGpuPipelineDescription { + uint32_t vertex_shader; // stream shader id + uint32_t pixel_shader; // 0: none (depth only) + uint32_t topology; // 0 points, 1 lines, 2 line strip, 3 triangles, 4 triangle strip + uint32_t cull_mode; // 0 none, 1 front, 2 back + uint32_t front_face_cw; + uint32_t depth_compare; // xenos::CompareFunction, kAlways when the test is off + uint32_t depth_write; + uint32_t stencil; // RB_DEPTHCONTROL bits 0 and 7..31 when stencil is on, else 0 + uint32_t stencil_masks; // RB_STENCILREFMASK (front) read/write masks + uint32_t color_formats[4]; // xenos::ColorRenderTargetFormat + 1, 0: unused + uint32_t color_write_masks; // 4 bits per render target + uint32_t blend_control[4]; // RB_BLENDCONTROL & 0x1FFF1FFF per render target + uint32_t depth_format; // xenos::DepthRenderTargetFormat + 1, 0: no depth + uint32_t msaa_samples; // xenos::MsaaSamples +}; + +// Bound render targets, keyed like Xenia's RenderTargetCache: EDRAM base +// (tiles), pitch (pixels), format; 0xFFFFFFFF base when unused. +struct WebGpuRenderTargetsKey { + uint32_t surface_pitch; + uint32_t msaa_samples; + uint32_t height; // pixels the draws can reach (viewport / scissor bound) + uint32_t color_base[4]; + uint32_t color_format[4]; + uint32_t depth_base; + uint32_t depth_format; +}; + +// Pipeline vertex shader id of a pass-through vertex shader (low bits: the +// interpolator count): the draw carries host clip-space vertices shaded on +// the CPU after its index data (rectangle lists, webgpu_draws.cpp). +constexpr uint32_t kPassthroughVertexShader = 0x80000000u; + +struct WebGpuDrawHeader { + uint32_t pipeline; + uint32_t viewport[4]; // x, y, width, height (pixels) + float depth_range[2]; + uint32_t scissor[4]; + uint32_t stencil_reference; + float blend_constant[4]; + uint32_t system_constant_words; + uint32_t float_vertex_words; + uint32_t float_pixel_words; + uint32_t bool_loop_words; + uint32_t fetch_words; + uint32_t index_format; // 0 none (vertex_count vertices), 1 uint16, 2 uint32 + uint32_t vertex_count; // indices, or vertices without an index buffer + uint32_t vertex_texture_mask; // fetch constants the shaders sample + uint32_t pixel_texture_mask; + // After the fetch constants: for the vertex then the pixel shader, a + // texture id per texture binding then packed sampler parameters per + // sampler binding (webgpu_textures.h). + uint32_t binding_words; +}; + +// Records draws for the WebGPU backend when enabled (r360_gpu_set_mode); +// false when the draw uses something not implemented yet (counted). +struct XenosSoftDraw; +bool WebGpuIssueDraw(const XenosSoftDraw& draw); +bool WebGpuBackendEnabled(); +// PM4 XE_SWAP: the front buffer texture fetch constant (6 words). +void WebGpuSwap(const uint32_t* fetch_constant); + +class GpuCommandStream { + public: + void Reset() { words_.clear(); } + // Payload of `words` words for `op`; valid until the next Begin. + uint32_t* Begin(GpuStreamOp op, uint32_t words); + const std::vector& words() const { return words_; } + + private: + std::vector words_; +}; +GpuCommandStream& GpuStream(); + +// Port of Xenia's SharedMemory (src/xenia/gpu/shared_memory.cc): the 512 MiB +// GPU copy of guest physical memory. RequestRange uploads the pages of a +// range that are not valid on the GPU; CPU writes invalidate pages. Xenia +// learns of CPU writes through physical memory access watches; here every +// uploaded page arms the sparse guest memory GPU watch +// (SparseGuestGpuWatch) and stays valid while its write generation is +// unchanged. +class WebGpuSharedMemory { + public: + static constexpr uint32_t kBufferSizeLog2 = 29; + static constexpr uint32_t kBufferSize = 1u << kBufferSizeLog2; + static constexpr uint32_t kPageSizeLog2 = 12; + static constexpr uint32_t kPageCount = kBufferSize >> kPageSizeLog2; + + void ClearCache(); + // False if the range is outside physical memory. + bool RequestRange(uint32_t start, uint32_t length); + // A resolve wrote the range on the GPU: valid there, no upload needed + // until the CPU writes it. + void RangeWrittenByGpu(uint32_t start, uint32_t length); + + uint64_t uploaded_bytes() const { return uploaded_bytes_; } + uint32_t upload_ranges() const { return upload_ranges_; } + + private: + bool PageValid(uint32_t page) const; + void MarkValid(uint32_t page); + void Upload(uint32_t page_first, uint32_t page_count); + + // Write generation each page had when it was made valid (0: not valid). + std::vector valid_generation_; + uint64_t uploaded_bytes_ = 0; + uint32_t upload_ranges_ = 0; +}; +WebGpuSharedMemory& GpuSharedMemory(); + +} // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp new file mode 100644 index 00000000..5edd2ba2 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -0,0 +1,880 @@ +// WebGPU backend draws: the per-draw part of Xenia's VulkanCommandProcessor +// (IssueDraw, UpdateSystemConstantValues, UpdateBindings) and +// VulkanPipelineCache (shader modifications, translation, pipeline state), +// recording into the command stream (webgpu_backend.h) instead of a Vulkan +// command buffer. Render targets follow Xenia's host render target path. +#include +#include +#include +#include +#include +#include +#include + +#include "webgpu_backend.h" +#include "webgpu_textures.h" +#include "xenos_soft_draw.h" +#include "xenos_soft_renderer.h" +#include "sparse_guest_memory.h" +#include "xenia/base/math.h" +#include "xenia/base/string_buffer.h" +#include "xenia/gpu/draw_util.h" +#include "xenia/gpu/register_file.h" +#include "xenia/gpu/registers.h" +#include "xenia/gpu/spirv_shader.h" +#include "xenia/gpu/spirv_shader_translator.h" +#include "xenia/gpu/trace_writer.h" +#include "xenia/gpu/xenos.h" +#include "ppc_translation_probe_runtime.h" + +namespace xe::gpu::shaders { +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_32bpp_1x2xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_32bpp_4xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_64bpp_1x2xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_64bpp_4xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_128bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_16bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_32bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_64bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_8bpp_cs.h" +} // namespace xe::gpu::shaders + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace render360::xenia_web { +namespace { + +using xe::gpu::RegisterFile; +using xe::gpu::Shader; +using xe::gpu::SpirvShader; +using xe::gpu::SpirvShaderTranslator; +namespace reg = xe::gpu::reg; +namespace xenos = xe::gpu::xenos; +namespace draw_util = xe::gpu::draw_util; +using namespace xe::gpu; // XE_GPU_REG_* register indices + +uint32_t g_mode = 0; // 0 off, 1 record draws + +// Why draws were not recorded (r360_gpu_draw_stat). +enum DrawSkip : uint32_t { + kSkipNoVertexShader = 1, + kSkipTranslation, + kSkipPrimitive, + kSkipIndices, + kSkipVertexFetch, + kSkipCount, +}; +uint32_t g_draws = 0, g_skips[kSkipCount] = {}, g_last_skip = 0; +bool Skip(DrawSkip reason) { + ++g_skips[reason]; + g_last_skip = reason; + return false; +} + +RegisterFile& Regs() { + static RegisterFile registers; + return registers; +} + +SpirvShaderTranslator& Translator() { + static SpirvShaderTranslator* translator = [] { + SpirvShaderTranslator::Features features(false); + // One logical 512 MiB shared memory binding (see + // xenos_spirv_translation_probe.cpp: WGSL has no arrays of unsized + // storage structs). + features.max_storage_buffer_range = 512u * 1024u * 1024u; + // WebGPU texture views do not swizzle: the shaders apply the swizzle + // from the system constants, as Xenia does without + // imageViewFormatSwizzle. + features.image_view_format_swizzle = false; + return new SpirvShaderTranslator(features, false, false, false); + }(); + return *translator; +} + +// Analyzed shaders by type and ucode (Xenia's shader storage). +SpirvShader* GetShader(xenos::ShaderType type, const uint32_t* words, uint32_t dwords, + uint32_t hash) { + static std::unordered_map> shaders; + if (!words || !dwords) return nullptr; + const uint64_t key = (uint64_t(hash) << 32) ^ (uint64_t(dwords) << 1) ^ uint64_t(type); + auto it = shaders.find(key); + if (it != shaders.end()) return it->second.get(); + auto shader = std::make_unique(type, key, words, dwords, std::endian::native); + xe::StringBuffer disassembly; + shader->AnalyzeUcode(disassembly); + SpirvShader* result = shader.get(); + shaders.emplace(key, std::move(shader)); + return result; +} + +// Port of VulkanPipelineCache::GetCurrentVertexShaderModification (host +// vertex shader type kVertex). +SpirvShaderTranslator::Modification VertexShaderModification(const Shader& shader, + uint32_t interpolator_mask) { + const RegisterFile& regs = Regs(); + SpirvShaderTranslator::Modification modification( + Translator().GetDefaultVertexShaderModification( + shader.GetDynamicAddressableRegisterCount(regs.Get().vs_num_reg), + Shader::HostVertexShaderType::kVertex)); + modification.vertex.interpolator_mask = interpolator_mask; + modification.vertex.output_point_parameters = + uint32_t((shader.writes_point_size_edge_flag_kill_vertex() & 0b001) && + regs.Get().prim_type == xenos::PrimitiveType::kPointList); + return modification; +} + +// Port of VulkanPipelineCache::GetCurrentPixelShaderModification (host +// render targets path). +SpirvShaderTranslator::Modification PixelShaderModification(const Shader& shader, + uint32_t interpolator_mask, + uint32_t param_gen_pos) { + const RegisterFile& regs = Regs(); + SpirvShaderTranslator::Modification modification( + Translator().GetDefaultPixelShaderModification( + shader.GetDynamicAddressableRegisterCount(regs.Get().ps_num_reg))); + modification.pixel.interpolator_mask = interpolator_mask; + modification.pixel.interpolators_centroid = + interpolator_mask & + ~xenos::GetInterpolatorSamplingPattern(regs.Get().msaa_samples, + regs.Get().sc_sample_cntl, + regs.Get().sampling_pattern); + if (param_gen_pos < xenos::kMaxInterpolators) { + modification.pixel.param_gen_enable = 1; + modification.pixel.param_gen_interpolator = param_gen_pos; + modification.pixel.param_gen_point = + uint32_t(regs.Get().prim_type == xenos::PrimitiveType::kPointList); + } else { + modification.pixel.param_gen_enable = 0; + modification.pixel.param_gen_interpolator = 0; + modification.pixel.param_gen_point = 0; + } + using DepthStencilMode = SpirvShaderTranslator::Modification::DepthStencilMode; + if (shader.implicit_early_z_write_allowed() && + (!shader.writes_color_target(0) || + !draw_util::DoesCoverageDependOnAlpha(regs.Get()))) { + modification.pixel.depth_stencil_mode = DepthStencilMode::kEarlyHint; + } else { + modification.pixel.depth_stencil_mode = DepthStencilMode::kNoModifiers; + } + return modification; +} + +// Stream ids of translations already sent (0: none yet). +std::unordered_map& ShaderIds() { + static std::unordered_map ids; + return ids; +} +uint32_t g_next_shader_id = 1; + +// Translates (once) and returns the stream id, sending the shader the first +// time; 0 on failure. +uint32_t ShaderId(SpirvShader& shader, uint64_t modification) { + Shader::Translation* translation = shader.GetOrCreateTranslation(modification); + if (!translation) return 0; + auto& ids = ShaderIds(); + if (auto it = ids.find(translation); it != ids.end()) return it->second; + if (!translation->is_translated() && !Translator().TranslateAnalyzedShader(*translation)) { + ids.emplace(translation, 0u); + return 0; + } + const auto& binary = translation->translated_binary(); + if (!translation->is_valid() || binary.size() < 20 || (binary.size() & 3)) { + ids.emplace(translation, 0u); + return 0; + } + const auto& textures = shader.GetTextureBindingsAfterTranslation(); + const auto& samplers = shader.GetSamplerBindingsAfterTranslation(); + const uint32_t spirv_words = uint32_t(binary.size() / 4); + const uint32_t id = g_next_shader_id++; + uint32_t* w = GpuStream().Begin(kGpuStreamShader, + 5 + uint32_t(textures.size() + samplers.size()) + spirv_words); + *w++ = id; + *w++ = shader.type() == xenos::ShaderType::kVertex ? 0u : 1u; + *w++ = uint32_t(textures.size()); + *w++ = uint32_t(samplers.size()); + *w++ = spirv_words; + for (const auto& t : textures) { + *w++ = t.fetch_constant | (uint32_t(t.dimension) << 5) | (uint32_t(t.is_signed) << 7); + } + for (const auto& s : samplers) { + *w++ = s.fetch_constant | (uint32_t(s.mag_filter) << 5) | (uint32_t(s.min_filter) << 7) | + (uint32_t(s.mip_filter) << 9) | (uint32_t(s.aniso_filter) << 11); + } + std::memcpy(w, binary.data(), binary.size()); + ids.emplace(translation, id); + return id; +} + +// Pipelines already sent, by description. +struct PipelineKeyHash { + size_t operator()(const std::vector& v) const { + uint64_t h = 1469598103934665603ull; + for (uint32_t x : v) h = (h ^ x) * 1099511628211ull; + return size_t(h ^ (h >> 32)); + } +}; +std::unordered_map, uint32_t, PipelineKeyHash> g_pipelines; +uint32_t PipelineId(const WebGpuPipelineDescription& description) { + auto& pipelines = g_pipelines; + static uint32_t next_id = 1; + constexpr uint32_t kWords = sizeof(description) / 4; + std::vector key(kWords); + std::memcpy(key.data(), &description, sizeof(description)); + if (auto it = pipelines.find(key); it != pipelines.end()) return it->second; + const uint32_t id = next_id++; + uint32_t* w = GpuStream().Begin(kGpuStreamPipeline, 1 + kWords); + w[0] = id; + std::memcpy(w + 1, &description, sizeof(description)); + pipelines.emplace(std::move(key), id); + return id; +} + +// Guest indices converted to host little-endian indices of the host +// primitive type (Xenia's PrimitiveProcessor converts fans, quads and +// endianness in the same way when the host cannot use them directly). +struct Indices { + uint32_t host_topology = 3; // see WebGpuPipelineDescription::topology + std::vector values; // empty: non-indexed with vertex_count + uint32_t vertex_count = 0; + bool use_32bit = false; +}; + +bool ReadGuestIndex(const XenosSoftDraw& draw, const reg::VGT_DRAW_INITIATOR& init, uint32_t i, + xenos::Endian endian, uint32_t* out) { + if (i >= draw.index_size) return false; + if (init.index_size == xenos::IndexFormat::kInt16) { + // The GPU swaps whole 32-bit words, then takes the 16-bit half (as the + // software renderer's ReadIndex does). + const uint32_t address = draw.index_base + i * 2u; + uint32_t word = 0; + if (!ReadSparseGuestMemory(r360_kernel_gpu_address_to_virtual(address & ~3u), &word, 4)) return false; + *out = (xenos::GpuSwap(word, endian) >> ((address & 2u) * 8u)) & 0xFFFFu; + return true; + } + uint32_t v = 0; + if (!ReadSparseGuestMemory(r360_kernel_gpu_address_to_virtual(draw.index_base + i * 4u), &v, 4)) return false; + *out = xenos::GpuSwap(v, endian) & 0xFFFFFFu; + return true; +} + +bool BuildIndices(const XenosSoftDraw& draw, Indices& out) { + const RegisterFile& regs = Regs(); + reg::VGT_DRAW_INITIATOR init; + init.value = draw.draw_initiator; + const uint32_t count = init.num_indices; + const bool indexed = init.source_select == xenos::SourceSelect::kDMA; + if (!indexed && init.source_select != xenos::SourceSelect::kAutoIndex) return false; + const auto endian = xenos::Endian(regs[XE_GPU_REG_VGT_DMA_SIZE] >> 30); + const uint32_t offset = regs[XE_GPU_REG_VGT_INDX_OFFSET]; + std::vector guest; + if (indexed) { + guest.resize(count); + for (uint32_t i = 0; i < count; ++i) { + if (!ReadGuestIndex(draw, init, i, endian, &guest[i])) return false; + guest[i] = (guest[i] + offset) & 0xFFFFFFu; + } + } + auto index_at = [&](uint32_t i) { return indexed ? guest[i] : (i + offset) & 0xFFFFFFu; }; + auto& v = out.values; + switch (init.prim_type) { + case xenos::PrimitiveType::kPointList: out.host_topology = 0; break; + case xenos::PrimitiveType::kLineList: out.host_topology = 1; break; + case xenos::PrimitiveType::kLineStrip: out.host_topology = 2; break; + case xenos::PrimitiveType::kTriangleList: out.host_topology = 3; break; + case xenos::PrimitiveType::kTriangleStrip: out.host_topology = 4; break; + case xenos::PrimitiveType::kTriangleFan: + out.host_topology = 3; + for (uint32_t i = 2; i < count; ++i) { + v.push_back(index_at(0)); v.push_back(index_at(i - 1)); v.push_back(index_at(i)); + } + break; + case xenos::PrimitiveType::kQuadList: + out.host_topology = 3; + for (uint32_t i = 0; i + 3 < count; i += 4) { + v.push_back(index_at(i)); v.push_back(index_at(i + 1)); v.push_back(index_at(i + 2)); + v.push_back(index_at(i)); v.push_back(index_at(i + 2)); v.push_back(index_at(i + 3)); + } + break; + case xenos::PrimitiveType::kLineLoop: + out.host_topology = 2; + for (uint32_t i = 0; i < count; ++i) v.push_back(index_at(i)); + if (count) v.push_back(index_at(0)); + break; + default: + return false; // rectangle lists, polygons, patches: not yet + } + const bool converted = !v.empty() || init.prim_type == xenos::PrimitiveType::kTriangleFan || + init.prim_type == xenos::PrimitiveType::kQuadList; + if (!converted) { + if (indexed || offset) { + for (uint32_t i = 0; i < count; ++i) v.push_back(index_at(i)); + } else { + out.vertex_count = count; + } + } + for (uint32_t x : v) out.use_32bit |= x > 0xFFFFu; + return true; +} + +// Port of VulkanCommandProcessor::UpdateSystemConstantValues for the host +// render targets path (no fragment shader interlock, no resolution scale). +void FillSystemConstants(SpirvShaderTranslator::SystemConstants& c, bool primitive_polygonal, + const draw_util::ViewportInfo& viewport_info, uint32_t used_texture_mask) { + const RegisterFile& regs = Regs(); + std::memset(&c, 0, sizeof(c)); + auto pa_cl_vte_cntl = regs.Get(); + auto rb_colorcontrol = regs.Get(); + auto rb_depth_info = regs.Get(); + auto rb_surface_info = regs.Get(); + uint32_t flags = 0; + if (pa_cl_vte_cntl.vtx_xy_fmt) flags |= SpirvShaderTranslator::kSysFlag_XYDividedByW; + if (pa_cl_vte_cntl.vtx_z_fmt) flags |= SpirvShaderTranslator::kSysFlag_ZDividedByW; + if (pa_cl_vte_cntl.vtx_w0_fmt) flags |= SpirvShaderTranslator::kSysFlag_WNotReciprocal; + if (primitive_polygonal) flags |= SpirvShaderTranslator::kSysFlag_PrimitivePolygonal; + if (draw_util::IsPrimitiveLine(regs)) flags |= SpirvShaderTranslator::kSysFlag_PrimitiveLine; + flags |= uint32_t(rb_surface_info.msaa_samples) << SpirvShaderTranslator::kSysFlag_MsaaSamples_Shift; + if (rb_depth_info.depth_format == xenos::DepthRenderTargetFormat::kD24FS8) { + flags |= SpirvShaderTranslator::kSysFlag_DepthFloat24; + } + const xenos::CompareFunction alpha_test_function = + rb_colorcontrol.alpha_test_enable ? rb_colorcontrol.alpha_func : xenos::CompareFunction::kAlways; + flags |= uint32_t(alpha_test_function) << SpirvShaderTranslator::kSysFlag_AlphaPassIfLess_Shift; + for (uint32_t i = 0; i < xenos::kMaxColorRenderTargets; ++i) { + auto color_info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + if (color_info.color_format == xenos::ColorRenderTargetFormat::k_8_8_8_8_GAMMA) { + flags |= SpirvShaderTranslator::kSysFlag_ConvertColor0ToGamma << i; + } + int32_t color_exp_bias = color_info.color_exp_bias; + // Host k_16_16 / k_16_16_16_16 render targets are normalized to -1..1 in + // 32-unit range (Xenia's non-truncated fixed-point RG(BA)16). + if (color_info.color_format == xenos::ColorRenderTargetFormat::k_16_16 || + color_info.color_format == xenos::ColorRenderTargetFormat::k_16_16_16_16) { + color_exp_bias -= 5; + } + uint32_t bits = uint32_t(0x3F800000 + (color_exp_bias << 23)); + std::memcpy(&c.color_exp_bias[i], &bits, 4); + } + c.flags = flags; + c.vertex_index_endian = xenos::Endian::kNone; + c.vertex_base_index = 0; // applied while building the host indices + for (uint32_t i = 0; i < 3; ++i) { + c.ndc_scale[i] = viewport_info.ndc_scale[i]; + c.ndc_offset[i] = viewport_info.ndc_offset[i]; + } + if (regs.Get().prim_type == xenos::PrimitiveType::kPointList) { + auto minmax = regs.Get(); + auto size = regs.Get(); + c.point_vertex_diameter_min = float(minmax.min_size) * (2.0f / 16.0f); + c.point_vertex_diameter_max = float(minmax.max_size) * (2.0f / 16.0f); + c.point_constant_diameter[0] = float(size.width) * (2.0f / 16.0f); + c.point_constant_diameter[1] = float(size.height) * (2.0f / 16.0f); + c.point_screen_diameter_to_ndc_radius[0] = 1.0f / std::max(viewport_info.xy_extent[0], 1u); + c.point_screen_diameter_to_ndc_radius[1] = 1.0f / std::max(viewport_info.xy_extent[1], 1u); + } + // Texture signedness / gamma and host swizzles (applied in the shader: + // WebGPU views do not swizzle) from the texture cache. + uint32_t textures_remaining = used_texture_mask, texture_index; + while (xe::bit_scan_forward(textures_remaining, &texture_index)) { + textures_remaining &= ~(1u << texture_index); + c.texture_swizzled_signs[texture_index >> 2] |= uint32_t(WebGpuTextureSwizzledSigns(texture_index)) + << (8 * (texture_index & 3)); + c.texture_swizzles[texture_index >> 1] |= WebGpuTextureHostSwizzle(texture_index) + << (12 * (texture_index & 1)); + } + c.alpha_test_reference = regs.Get(XE_GPU_REG_RB_ALPHA_REF); +} + +// Float constants used by the shader, packed in register order (Xenia's +// UpdateBindings tight packing). +void PackFloatConstants(const Shader& shader, bool pixel, std::vector& out) { + const RegisterFile& regs = Regs(); + const auto& map = shader.constant_register_map(); + const uint32_t base = XE_GPU_REG_SHADER_CONSTANT_000_X + (pixel ? 256u * 4u : 0u); + for (uint32_t i = 0; i < 4; ++i) { + uint64_t bits = map.float_bitmap[i]; + uint32_t index; + while (xe::bit_scan_forward(bits, &index)) { + bits &= ~(uint64_t(1) << index); + const uint32_t reg_index = base + (((i << 6) + index) << 2); + for (uint32_t c = 0; c < 4; ++c) out.push_back(regs[reg_index + c]); + } + } + if (out.empty()) out.assign(4, 0u); +} + +// The render targets the draw writes (host render targets path), as Xenia's +// RenderTargetCache::Update selects them. +WebGpuRenderTargetsKey RenderTargets(uint32_t normalized_color_mask, bool depth_enabled, + uint32_t height) { + const RegisterFile& regs = Regs(); + WebGpuRenderTargetsKey key{}; + auto surface = regs.Get(); + key.surface_pitch = surface.surface_pitch; + key.msaa_samples = uint32_t(surface.msaa_samples); + key.height = height; + for (uint32_t i = 0; i < 4; ++i) { + auto info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + const bool used = (normalized_color_mask >> (i * 4)) & 0xF; + key.color_base[i] = used ? info.color_base : 0xFFFFFFFFu; + key.color_format[i] = used ? uint32_t(info.color_format) : 0u; + } + auto depth = regs.Get(); + key.depth_base = depth_enabled ? depth.depth_base : 0xFFFFFFFFu; + key.depth_format = depth_enabled ? uint32_t(depth.depth_format) : 0u; + return key; +} + +// Xenia's resolve copy shaders, sent once as load shaders 64 + index. +bool g_resolve_shader_sent[size_t(draw_util::ResolveCopyShaderIndex::kCount)] = {}; +void SendResolveShader(draw_util::ResolveCopyShaderIndex index) { + if (g_resolve_shader_sent[size_t(index)]) return; + g_resolve_shader_sent[size_t(index)] = true; + static const std::pair kShaders[] = { + {shaders::resolve_fast_32bpp_1x2xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_1x2xmsaa_cs)}, + {shaders::resolve_fast_32bpp_4xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_4xmsaa_cs)}, + {shaders::resolve_fast_64bpp_1x2xmsaa_cs, sizeof(shaders::resolve_fast_64bpp_1x2xmsaa_cs)}, + {shaders::resolve_fast_64bpp_4xmsaa_cs, sizeof(shaders::resolve_fast_64bpp_4xmsaa_cs)}, + {shaders::resolve_full_8bpp_cs, sizeof(shaders::resolve_full_8bpp_cs)}, + {shaders::resolve_full_16bpp_cs, sizeof(shaders::resolve_full_16bpp_cs)}, + {shaders::resolve_full_32bpp_cs, sizeof(shaders::resolve_full_32bpp_cs)}, + {shaders::resolve_full_64bpp_cs, sizeof(shaders::resolve_full_64bpp_cs)}, + {shaders::resolve_full_128bpp_cs, sizeof(shaders::resolve_full_128bpp_cs)}, + }; + const auto& shader = kShaders[size_t(index)]; + uint32_t* w = GpuStream().Begin(kGpuStreamLoadShader, 2 + uint32_t(shader.second / 4)); + w[0] = 64u + uint32_t(index); + w[1] = uint32_t(shader.second / 4); + std::memcpy(w + 2, shader.first, shader.second); +} + +// VulkanRenderTargetCache::Resolve for the host render targets path: dump +// the render targets owning the source span into the EDRAM buffer, run +// Xenia's resolve copy shader into shared memory, then clear. +uint32_t g_resolves = 0, g_resolve_failures = 0; +void Resolve() { + const RegisterFile& regs = Regs(); + xe::Memory* memory = ActiveProbeMemory(); + if (!memory) { + ++g_resolve_failures; + return; + } + // GetResolveInfo reads guest memory only through the sparse memory + // overlay; its trace writer is never used (as in xenos_soft_renderer.cpp). + alignas(TraceWriter) static uint8_t trace_storage[sizeof(TraceWriter)] = {}; + auto& trace_writer = *reinterpret_cast(trace_storage); + draw_util::ResolveInfo info; + if (!draw_util::GetResolveInfo(regs, *memory, trace_writer, 1, 1, false, false, info)) { + ++g_resolve_failures; + return; + } + if (getenv("R360_RESOLVE_LOG")) { + static uint32_t logged = 0; + if (logged++ < 3) + std::fprintf(stderr, "R360_RESOLVE_WGPU dest_base_reg=0x%08X adjusted=0x%08X extent=0x%08X+%u dest_off=%u,%u edram_off=%u,%u size=%ux%u\n", + regs[XE_GPU_REG_RB_COPY_DEST_BASE], info.copy_dest_base, info.copy_dest_extent_start, + info.copy_dest_extent_length, info.copy_dest_coordinate_info.offset_x_div_8 * 8u, + info.copy_dest_coordinate_info.offset_y_div_8 * 8u, info.coordinate_info.edram_offset_x_div_8 * 8u, + info.coordinate_info.edram_offset_y_div_8 * 8u, info.coordinate_info.width_div_8 * 8u, + info.height_div_8 * 8u); + } + if (!info.coordinate_info.width_div_8 || !info.height_div_8) return; + ++g_resolves; + if (g_mode & 2) { + const auto window = regs.Get(); + const draw_util::ResolveEdramInfo& e = info.IsCopyingDepth() ? info.depth_edram_info : info.color_edram_info; + std::fprintf(stderr, + "R360_XENOS_WGPU_RESOLVE base=%u pitch=%u msaa=%u fmt=%u off=%u,%u size=%ux%u " + "dest=0x%08X dest_off=%u,%u dest_pitch=%u window=%d,%d window_enable=%u\n", + e.base_tiles, e.pitch_tiles, uint32_t(e.msaa_samples), e.format, + info.coordinate_info.edram_offset_x_div_8 * 8u, info.coordinate_info.edram_offset_y_div_8 * 8u, + info.coordinate_info.width_div_8 * 8u, info.height_div_8 * 8u, info.copy_dest_base, + info.copy_dest_coordinate_info.offset_x_div_8 * 8u, info.copy_dest_coordinate_info.offset_y_div_8 * 8u, + info.copy_dest_coordinate_info.pitch_aligned_div_32 * 32u, int(window.window_x_offset), + int(window.window_y_offset), uint32_t(regs.Get().vtx_window_offset_enable)); + } + if (info.copy_dest_extent_length) { + uint32_t dump_base, dump_row_length_used, dump_rows, dump_pitch; + info.GetCopyEdramTileSpan(dump_base, dump_row_length_used, dump_rows, dump_pitch); + uint32_t* w = GpuStream().Begin(kGpuStreamEdramDump, 4); + w[0] = dump_base; + w[1] = dump_row_length_used; + w[2] = dump_rows; + w[3] = dump_pitch; + draw_util::ResolveCopyShaderConstants constants; + uint32_t group_count_x, group_count_y; + const draw_util::ResolveCopyShaderIndex copy_shader = + info.GetCopyShader(1, 1, constants, group_count_x, group_count_y); + if (copy_shader != draw_util::ResolveCopyShaderIndex::kUnknown && + GpuSharedMemory().RequestRange(info.copy_dest_extent_start, info.copy_dest_extent_length)) { + SendResolveShader(copy_shader); + // Storage bindings start at 256-byte multiples in WebGPU. + const uint32_t binding_offset = info.copy_dest_base & ~255u; + const uint32_t binding_size = + xe::align(info.copy_dest_extent_start - binding_offset + info.copy_dest_extent_length, 16u); + constants.dest_base -= binding_offset; + static_assert(sizeof(constants) == 20, "ResolveCopyShaderConstants layout"); + w = GpuStream().Begin(kGpuStreamResolve, 10); + w[0] = uint32_t(copy_shader); + std::memcpy(w + 1, &constants, sizeof(constants)); + w[6] = group_count_x; + w[7] = group_count_y; + w[8] = binding_offset; + w[9] = binding_size; + GpuSharedMemory().RangeWrittenByGpu(info.copy_dest_extent_start, info.copy_dest_extent_length); + WebGpuTexturesMarkRangeResolved(info.copy_dest_extent_start, info.copy_dest_extent_length); + } + } + auto clear = [&](bool depth, const draw_util::ResolveEdramInfo& edram, uint32_t lo, uint32_t hi) { + uint32_t* w = GpuStream().Begin(kGpuStreamClear, 11); + w[0] = depth; + w[1] = edram.base_tiles; + w[2] = edram.pitch_tiles; + w[3] = uint32_t(edram.msaa_samples); + w[4] = edram.format; + w[5] = info.coordinate_info.edram_offset_x_div_8 * 8u; + w[6] = info.coordinate_info.edram_offset_y_div_8 * 8u; + w[7] = info.coordinate_info.width_div_8 * 8u; + w[8] = info.height_div_8 * 8u; + w[9] = lo; + w[10] = hi; + }; + if (info.IsClearingDepth()) clear(true, info.depth_edram_info, info.rb_depth_clear, 0); + if (info.IsClearingColor()) { + clear(false, info.color_edram_info, info.rb_color_clear, info.rb_color_clear_lo); + } +} + +WebGpuRenderTargetsKey g_bound_targets{}; +bool g_targets_bound = false; + +} // namespace + +bool WebGpuBackendEnabled() { return g_mode != 0; } + +void WebGpuSwap(const uint32_t* fetch_constant) { + if (!g_mode) return; + uint32_t swizzle; + const uint32_t texture = WebGpuSwapTexture(fetch_constant, &swizzle); + uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 8); + std::memcpy(w, fetch_constant, 6 * sizeof(uint32_t)); + w[6] = texture; + w[7] = swizzle; +} + +bool WebGpuIssueDraw(const XenosSoftDraw& draw) { + if (!g_mode) return false; + RegisterFile& regs = Regs(); + const uint32_t count = std::min(draw.register_count, RegisterFile::kRegisterCount); + std::memcpy(regs.values, draw.registers, count * sizeof(uint32_t)); + const auto edram_mode = regs.Get().edram_mode; + if (edram_mode == xenos::EdramMode::kCopy) { + Resolve(); + return true; + } + if (edram_mode != xenos::EdramMode::kColorDepth && edram_mode != xenos::EdramMode::kDepthOnly) { + return true; + } + + SpirvShader* vertex_shader = + GetShader(xenos::ShaderType::kVertex, draw.vertex_shader, draw.vertex_shader_dwords, + draw.vertex_shader_hash); + if (!vertex_shader || !vertex_shader->is_ucode_analyzed()) return Skip(kSkipNoVertexShader); + SpirvShader* pixel_shader = nullptr; + if (edram_mode == xenos::EdramMode::kColorDepth && draw.pixel_shader) { + pixel_shader = GetShader(xenos::ShaderType::kPixel, draw.pixel_shader, draw.pixel_shader_dwords, + draw.pixel_shader_hash); + if (pixel_shader && !pixel_shader->is_ucode_analyzed()) return Skip(kSkipTranslation); + } + const bool primitive_polygonal = draw_util::IsPrimitivePolygonal(regs); + if (!draw_util::IsRasterizationPotentiallyDone(regs, primitive_polygonal)) return true; + + uint32_t param_gen_pos = UINT32_MAX; + const uint32_t interpolator_mask = + pixel_shader ? vertex_shader->writes_interpolators() & + pixel_shader->GetInterpolatorInputMask(regs.Get(), + regs.Get(), + param_gen_pos) + : 0u; + const uint32_t vs_id = + ShaderId(*vertex_shader, VertexShaderModification(*vertex_shader, interpolator_mask).value); + if (!vs_id) return Skip(kSkipTranslation); + uint32_t ps_id = 0; + if (pixel_shader) { + ps_id = ShaderId(*pixel_shader, + PixelShaderModification(*pixel_shader, interpolator_mask, param_gen_pos).value); + if (!ps_id) return Skip(kSkipTranslation); + } + + // Rectangle lists: WebGPU has no geometry shaders (Xenia's Vulkan backend + // expands them in one), so the guest vertex shader runs on the CPU and the + // host draws the shaded vertices with a pass-through vertex shader + // (pipeline vertex shader id kPassthroughVertexShader | interpolator count). + reg::VGT_DRAW_INITIATOR draw_init; + draw_init.value = draw.draw_initiator; + const bool rectangle_list = draw_init.prim_type == xenos::PrimitiveType::kRectangleList; + const uint32_t interpolator_count = uint32_t(xe::bit_count(interpolator_mask)); + std::vector shaded; + uint32_t shaded_count = 0; + Indices indices; + if (rectangle_list) { + if (!ShadeXenosVertices(draw, shaded, &shaded_count)) return Skip(kSkipPrimitive); + if (shaded_count < 3) return true; + indices.host_topology = 3; + } else if (!BuildIndices(draw, indices)) { + return Skip(kSkipPrimitive); + } + + // Pipeline state (VulkanPipelineCache::GetCurrentStateDescription). + const reg::RB_DEPTHCONTROL depth_control = draw_util::GetNormalizedDepthControl(regs); + const uint32_t color_mask = + pixel_shader ? draw_util::GetNormalizedColorMask(regs, pixel_shader->writes_color_targets()) : 0u; + WebGpuPipelineDescription description{}; + description.vertex_shader = rectangle_list ? (kPassthroughVertexShader | interpolator_count) : vs_id; + description.pixel_shader = ps_id; + description.topology = indices.host_topology; + auto pa_su_sc_mode_cntl = regs.Get(); + if (primitive_polygonal) { + description.cull_mode = pa_su_sc_mode_cntl.cull_front ? 1u : (pa_su_sc_mode_cntl.cull_back ? 2u : 0u); + if (pa_su_sc_mode_cntl.cull_front && pa_su_sc_mode_cntl.cull_back) return true; // nothing drawn + } + description.front_face_cw = pa_su_sc_mode_cntl.face ? 1u : 0u; + const bool depth_used = depth_control.z_enable || depth_control.stencil_enable; + description.depth_compare = + depth_control.z_enable ? uint32_t(depth_control.zfunc) : uint32_t(xenos::CompareFunction::kAlways); + description.depth_write = depth_control.z_enable && depth_control.z_write_enable; + if (depth_control.stencil_enable) { + description.stencil = depth_control.value & 0xFFFFFF81u; + description.stencil_masks = regs[XE_GPU_REG_RB_STENCILREFMASK] & 0xFFFF00u; + } + for (uint32_t i = 0; i < 4; ++i) { + const uint32_t mask = (color_mask >> (i * 4)) & 0xF; + if (!mask) continue; + auto info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + description.color_formats[i] = uint32_t(info.color_format) + 1u; + description.color_write_masks |= mask << (i * 4); + description.blend_control[i] = regs[reg::RB_BLENDCONTROL::rt_register_indices[i]] & 0x1FFF1FFFu; + } + if (depth_used) { + description.depth_format = uint32_t(regs.Get().depth_format) + 1u; + } + description.msaa_samples = uint32_t(regs.Get().msaa_samples); + + // Viewport and scissor in render target pixels (origin top-left, no + // resolution scale). WebGPU clip space has Y up like Direct3D 12, so the + // NDC transform is D3D12CommandProcessor's (origin_bottom_left). + auto surface = regs.Get(); + const uint32_t pitch = std::max(surface.surface_pitch, 1u); + constexpr uint32_t kMaxHeight = 2560; + draw_util::ViewportInfo viewport_info; + draw_util::GetHostViewportInfo(regs, 1, 1, true, pitch, kMaxHeight, false, depth_control, + false, false, pixel_shader && pixel_shader->writes_depth(), + viewport_info); + draw_util::Scissor scissor; + draw_util::GetScissor(regs, scissor); + const uint32_t height = std::min( + kMaxHeight, std::max(scissor.offset[1] + scissor.extent[1], + viewport_info.xy_offset[1] + viewport_info.xy_extent[1])); + + // Render targets: a new set ends the current render pass. + const WebGpuRenderTargetsKey targets = RenderTargets(color_mask, depth_used, height); + if (!g_targets_bound || std::memcmp(&targets, &g_bound_targets, sizeof(targets)) != 0) { + uint32_t* w = GpuStream().Begin(kGpuStreamRenderTargets, sizeof(targets) / 4); + std::memcpy(w, &targets, sizeof(targets)); + g_bound_targets = targets; + g_targets_bound = true; + } + + // Vertex data the shader fetches from shared memory. + for (const auto& binding : vertex_shader->vertex_bindings()) { + if (rectangle_list) break; // fetched by the CPU vertex shader + const xenos::xe_gpu_vertex_fetch_t fetch = regs.GetVertexFetch(binding.fetch_constant); + if (fetch.type != xenos::FetchConstantType::kVertex) return Skip(kSkipVertexFetch); + if (!GpuSharedMemory().RequestRange(fetch.address << 2, fetch.size << 2)) { + return Skip(kSkipVertexFetch); + } + } + + // Textures (VulkanCommandProcessor::IssueDraw requests them before + // updating the constants and bindings). + const uint32_t used_texture_mask = + (rectangle_list ? 0u : vertex_shader->GetUsedTextureMaskAfterTranslation()) | + (pixel_shader ? pixel_shader->GetUsedTextureMaskAfterTranslation() : 0u); + WebGpuRequestTextures(regs, used_texture_mask); + std::vector binding_words; + for (const SpirvShader* shader : {vertex_shader, pixel_shader}) { + if (!shader || (rectangle_list && shader == vertex_shader)) continue; + for (const auto& t : shader->GetTextureBindingsAfterTranslation()) { + binding_words.push_back(WebGpuTextureForBinding(t)); + } + for (const auto& s : shader->GetSamplerBindingsAfterTranslation()) { + binding_words.push_back(WebGpuSamplerParameters(regs, s)); + } + } + + // Constants. + SpirvShaderTranslator::SystemConstants system{}; + FillSystemConstants(system, primitive_polygonal, viewport_info, used_texture_mask); + std::vector float_vertex, float_pixel; + PackFloatConstants(*vertex_shader, false, float_vertex); + if (pixel_shader) PackFloatConstants(*pixel_shader, true, float_pixel); + else float_pixel.assign(4, 0u); + // Bool (8 dwords) and loop (32 dwords) constants, then the 32 texture / + // vertex fetch constants (6 dwords each), as Xenia uploads them. + constexpr uint32_t kBoolLoopWords = 8 + 32, kFetchWords = 32 * 6; + + // Rectangle list: host clip-space vertices (CompleteVertexOrTessEvalShaderInMain's + // W / XY / Z conventions and NDC transform), then per rectangle the fourth + // corner v1 + v2 - v0 of the right-angle corner v0 (Xenia's primitive + // processor), as two triangles. Per host vertex: position, interpolators. + std::vector host_vertices; + if (rectangle_list) { + const uint32_t floats_per_vertex = 4 + 4 * interpolator_count; + auto to_host = [&](uint32_t v, float* o) { + const float* g = &shaded[size_t(v) * 68]; + float w = (system.flags & SpirvShaderTranslator::kSysFlag_WNotReciprocal) ? g[3] : 1.0f / g[3]; + float xyz[3] = {g[0], g[1], g[2]}; + if (system.flags & SpirvShaderTranslator::kSysFlag_XYDividedByW) { xyz[0] *= w; xyz[1] *= w; } + if (system.flags & SpirvShaderTranslator::kSysFlag_ZDividedByW) xyz[2] *= w; + for (int k = 0; k < 3; ++k) o[k] = xyz[k] * system.ndc_scale[k] + system.ndc_offset[k] * w; + o[3] = w; + uint32_t slot = 0, remaining = interpolator_mask, index; + while (xe::bit_scan_forward(remaining, &index)) { + remaining &= ~(1u << index); + std::memcpy(o + 4 + 4 * slot++, g + 4 + 4 * index, 16); + } + }; + std::vector corner(size_t(floats_per_vertex) * 4); + for (uint32_t i = 0; i + 2 < shaded_count; i += 3) { + float* c[4] = {&corner[0], &corner[floats_per_vertex], &corner[2 * floats_per_vertex], + &corner[3 * floats_per_vertex]}; + for (uint32_t k = 0; k < 3; ++k) to_host(i + k, c[k]); + auto sx = [&](const float* v) { return v[0] / v[3]; }; + auto sy = [&](const float* v) { return v[1] / v[3]; }; + auto len2 = [&](const float* a, const float* b) { + const float dx = sx(a) - sx(b), dy = sy(a) - sy(b); + return dx * dx + dy * dy; + }; + // v0 is the right-angle corner: opposite the longest edge. + const float ab = len2(c[0], c[1]), bc = len2(c[1], c[2]), ca = len2(c[2], c[0]); + const float *p0 = c[0], *p1 = c[1], *p2 = c[2]; + if (bc >= ab && bc >= ca) { p0 = c[0]; p1 = c[1]; p2 = c[2]; } + else if (ca >= ab && ca >= bc) { p0 = c[1]; p1 = c[2]; p2 = c[0]; } + else { p0 = c[2]; p1 = c[0]; p2 = c[1]; } + const float* p3 = c[3]; + for (uint32_t k = 0; k < floats_per_vertex; ++k) c[3][k] = p1[k] + p2[k] - p0[k]; + for (const float* v : {p0, p1, p2, p1, p3, p2}) host_vertices.insert(host_vertices.end(), v, v + floats_per_vertex); + } + indices.vertex_count = uint32_t(host_vertices.size() / floats_per_vertex); + if (!indices.vertex_count) return true; + } + + const uint32_t index_words = + indices.values.empty() ? 0u + : (indices.use_32bit ? uint32_t(indices.values.size()) + : uint32_t((indices.values.size() + 1) / 2)); + const uint32_t system_words = sizeof(system) / 4; + const uint32_t payload = sizeof(WebGpuDrawHeader) / 4 + system_words + + uint32_t(float_vertex.size() + float_pixel.size()) + kBoolLoopWords + + kFetchWords + uint32_t(binding_words.size()) + index_words + + uint32_t(host_vertices.size()); + const uint32_t pipeline_id = PipelineId(description); + if ((g_mode & 2) && g_draws < 4000 && (g_draws % 50) == 0) { + const auto window = regs.Get(); + std::fprintf(stderr, "R360_XENOS_WGPU_DRAW n=%u viewport=%u,%u %ux%u scissor=%u,%u %ux%u window=%d,%d enable=%u\n", + g_draws, viewport_info.xy_offset[0], viewport_info.xy_offset[1], viewport_info.xy_extent[0], + viewport_info.xy_extent[1], scissor.offset[0], scissor.offset[1], scissor.extent[0], scissor.extent[1], + int(window.window_x_offset), int(window.window_y_offset), + uint32_t(pa_su_sc_mode_cntl.vtx_window_offset_enable)); + } + uint32_t* w = GpuStream().Begin(kGpuStreamDraw, payload); + WebGpuDrawHeader header{}; + header.pipeline = pipeline_id; + header.viewport[0] = viewport_info.xy_offset[0]; + header.viewport[1] = viewport_info.xy_offset[1]; + header.viewport[2] = viewport_info.xy_extent[0]; + header.viewport[3] = viewport_info.xy_extent[1]; + header.depth_range[0] = viewport_info.z_min; + header.depth_range[1] = viewport_info.z_max; + header.scissor[0] = scissor.offset[0]; + header.scissor[1] = scissor.offset[1]; + header.scissor[2] = scissor.extent[0]; + header.scissor[3] = scissor.extent[1]; + header.stencil_reference = regs.Get().stencilref; + header.blend_constant[0] = regs.Get(XE_GPU_REG_RB_BLEND_RED); + header.blend_constant[1] = regs.Get(XE_GPU_REG_RB_BLEND_GREEN); + header.blend_constant[2] = regs.Get(XE_GPU_REG_RB_BLEND_BLUE); + header.blend_constant[3] = regs.Get(XE_GPU_REG_RB_BLEND_ALPHA); + header.system_constant_words = system_words; + header.float_vertex_words = uint32_t(float_vertex.size()); + header.float_pixel_words = uint32_t(float_pixel.size()); + header.bool_loop_words = kBoolLoopWords; + header.fetch_words = kFetchWords; + header.index_format = indices.values.empty() ? 0u : (indices.use_32bit ? 2u : 1u); + header.vertex_count = indices.values.empty() ? indices.vertex_count : uint32_t(indices.values.size()); + header.vertex_texture_mask = rectangle_list ? 0u : vertex_shader->GetUsedTextureMaskAfterTranslation(); + header.pixel_texture_mask = pixel_shader ? pixel_shader->GetUsedTextureMaskAfterTranslation() : 0u; + header.binding_words = uint32_t(binding_words.size()); + std::memcpy(w, &header, sizeof(header)); + w += sizeof(header) / 4; + std::memcpy(w, &system, sizeof(system)); + w += system_words; + std::memcpy(w, float_vertex.data(), float_vertex.size() * 4); + w += float_vertex.size(); + std::memcpy(w, float_pixel.data(), float_pixel.size() * 4); + w += float_pixel.size(); + std::memcpy(w, ®s[XE_GPU_REG_SHADER_CONSTANT_BOOL_000_031], kBoolLoopWords * 4); + w += kBoolLoopWords; + std::memcpy(w, ®s[XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0], kFetchWords * 4); + w += kFetchWords; + std::memcpy(w, binding_words.data(), binding_words.size() * 4); + w += binding_words.size(); + if (index_words) { + if (indices.use_32bit) { + std::memcpy(w, indices.values.data(), indices.values.size() * 4); + } else { + auto* h = reinterpret_cast(w); + for (size_t i = 0; i < indices.values.size(); ++i) h[i] = uint16_t(indices.values[i]); + if (indices.values.size() & 1) h[indices.values.size()] = 0; + } + w += index_words; + } + // Pass-through draws: the host vertices follow (vertex_count x (4 + 4 x + // interpolator count) floats). + if (!host_vertices.empty()) std::memcpy(w, host_vertices.data(), host_vertices.size() * 4); + ++g_draws; + return true; +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// 0 off, 1 record draws for the WebGPU backend. +__attribute__((used, export_name("r360_gpu_set_mode"))) +uint32_t r360_gpu_set_mode(uint32_t mode) { + // A new mode starts a new stream consumer: everything sent once (shaders, + // pipelines, textures, load and resolve shaders, shared memory) is sent + // again. + rx::g_mode = mode; + rx::g_targets_bound = false; + rx::ShaderIds().clear(); + rx::g_pipelines.clear(); + for (bool& sent : rx::g_resolve_shader_sent) sent = false; + rx::WebGpuTexturesReset(); + rx::GpuSharedMemory().ClearCache(); + rx::GpuStream().Reset(); + return mode; +} +// 0 draws recorded, 1..5 skips by reason (see DrawSkip), 6 last skip reason, +// 7 resolves, 8 resolve failures. +__attribute__((used, export_name("r360_gpu_draw_stat"))) +uint32_t r360_gpu_draw_stat(uint32_t index) { + if (index == 0) return rx::g_draws; + if (index < rx::kSkipCount) return rx::g_skips[index]; + if (index == 7) return rx::g_resolves; + if (index == 8) return rx::g_resolve_failures; + return rx::g_last_skip; +} +} // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_textures.cpp b/src/xenia_web_bootstrap/webgpu_textures.cpp new file mode 100644 index 00000000..4c247b3c --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_textures.cpp @@ -0,0 +1,892 @@ +// WebGPU texture cache (see webgpu_textures.h): Xenia's TextureCache binding +// and texture key logic (src/xenia/gpu/texture_cache.cc) and +// VulkanTextureCache's host formats and LoadTextureDataFromResidentMemoryImpl +// (src/xenia/gpu/vulkan/vulkan_texture_cache.cc), recording WebGPU stream +// ops instead of Vulkan commands. +#include "webgpu_textures.h" + +#include +#include +#include +#include +#include + +#include "sparse_guest_memory.h" +#include "webgpu_backend.h" +#include "xenia/base/math.h" +#include "xenia/gpu/texture_cache.h" +#include "xenia/gpu/texture_info.h" +#include "xenia/gpu/texture_util.h" + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace xe::gpu::shaders { +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_128bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_16bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_32bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_64bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_8bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_bgrg8_rgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_bgrg8_rgbg8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_ctx1_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_depth_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_depth_unorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxn_rg8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt1_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3a_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3aas1111_argb4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3aas1111_bgra4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt5_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt5a_r8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_gbgr8_grgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_gbgr8_rgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r10g11b11_rgba16_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r10g11b11_rgba16_snorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r11g11b10_rgba16_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r11g11b10_rgba16_snorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r16_unorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r4g4b4a4_a4r4g4b4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r4g4b4a4_b4g4r4a4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g5b5a1_b5g5r5a1_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g6b5_b5g6r5_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rg16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rg16_unorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rgba16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rgba16_unorm_float_cs.h" +} // namespace xe::gpu::shaders + +namespace render360::xenia_web { + +using namespace xe::gpu; + +namespace { + +// Xenia's TextureCache types (protected there; this class is never +// instantiated). +class Types : public TextureCache { + public: + using TextureCache::kLoadGuestXThreadsPerGroupLog2; + using TextureCache::kLoadGuestYBlocksPerGroupLog2; + using TextureCache::LoadConstants; + using TextureCache::LoadShaderIndex; + using TextureCache::LoadShaderInfo; + using TextureCache::TextureKey; + using TextureCache::kLoadShaderCount; + using TextureCache::kLoadShaderIndex128bpb; + using TextureCache::kLoadShaderIndex16bpb; + using TextureCache::kLoadShaderIndex32bpb; + using TextureCache::kLoadShaderIndex64bpb; + using TextureCache::kLoadShaderIndex8bpb; + using TextureCache::kLoadShaderIndexBGRG8ToRGB8; + using TextureCache::kLoadShaderIndexCTX1; + using TextureCache::kLoadShaderIndexDXNToRG8; + using TextureCache::kLoadShaderIndexDXT1ToRGBA8; + using TextureCache::kLoadShaderIndexDXT3A; + using TextureCache::kLoadShaderIndexDXT3ToRGBA8; + using TextureCache::kLoadShaderIndexDXT5AToR8; + using TextureCache::kLoadShaderIndexDXT5ToRGBA8; + using TextureCache::kLoadShaderIndexDepthFloat; + using TextureCache::kLoadShaderIndexDepthUnorm; + using TextureCache::kLoadShaderIndexGBGR8ToRGB8; + using TextureCache::kLoadShaderIndexR10G11B11ToRGBA16; + using TextureCache::kLoadShaderIndexR10G11B11ToRGBA16SNorm; + using TextureCache::kLoadShaderIndexR11G11B10ToRGBA16; + using TextureCache::kLoadShaderIndexR11G11B10ToRGBA16SNorm; + using TextureCache::kLoadShaderIndexR16SNormToFloat; + using TextureCache::kLoadShaderIndexR16UNormToFloat; + using TextureCache::kLoadShaderIndexRG16SNormToFloat; + using TextureCache::kLoadShaderIndexRG16UNormToFloat; + using TextureCache::kLoadShaderIndexRGBA16SNormToFloat; + using TextureCache::kLoadShaderIndexRGBA16UNormToFloat; + using TextureCache::kLoadShaderIndexUnknown; + + // TextureCache::GuestToHostSwizzle (texture_cache.cc is not linked). + static uint32_t GuestToHostSwizzle(uint32_t guest_swizzle, uint32_t host_format_swizzle) { + uint32_t host_swizzle = 0; + for (uint32_t i = 0; i < 4; ++i) { + const uint32_t guest_component = (guest_swizzle >> (3 * i)) & 0b111; + const uint32_t host_component = guest_component >= xenos::XE_GPU_TEXTURE_SWIZZLE_0 + ? guest_component & 0b101 + : (host_format_swizzle >> (3 * guest_component)) & 0b111; + host_swizzle |= host_component << (3 * i); + } + return host_swizzle; + } + // VulkanTextureCache::AreDimensionsCompatible. + static constexpr bool AreDimensionsCompatible(xenos::FetchOpDimension binding_dimension, + xenos::DataDimension resource_dimension) { + switch (binding_dimension) { + case xenos::FetchOpDimension::k1D: + case xenos::FetchOpDimension::k2D: + return resource_dimension == xenos::DataDimension::k1D || + resource_dimension == xenos::DataDimension::k2DOrStacked; + case xenos::FetchOpDimension::k3DOrStacked: + return resource_dimension == xenos::DataDimension::k3D; + case xenos::FetchOpDimension::kCube: + return resource_dimension == xenos::DataDimension::kCube; + default: + return false; + } + } +}; +using TextureKey = Types::TextureKey; +using LoadShaderIndex = Types::LoadShaderIndex; +constexpr LoadShaderIndex kUnknown = Types::kLoadShaderIndexUnknown; + +// TextureCache::load_shader_info_ and the Vulkan SPIR-V of each load shader. +struct LoadShader { + Types::LoadShaderInfo info; + const uint32_t* spirv; + uint32_t spirv_bytes; +}; +#define R360_LOAD_SHADER(bytes, log2, name) \ + {{bytes, log2}, shaders::name, uint32_t(sizeof(shaders::name))} +const LoadShader kLoadShaders[Types::kLoadShaderCount] = { + R360_LOAD_SHADER(1, 4, texture_load_8bpb_cs), + R360_LOAD_SHADER(2, 4, texture_load_16bpb_cs), + R360_LOAD_SHADER(4, 3, texture_load_32bpb_cs), + R360_LOAD_SHADER(8, 2, texture_load_64bpb_cs), + R360_LOAD_SHADER(16, 1, texture_load_128bpb_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g5b5a1_b5g5r5a1_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g6b5_b5g6r5_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs), + R360_LOAD_SHADER(2, 4, texture_load_r4g4b4a4_b4g4r4a4_cs), + R360_LOAD_SHADER(2, 4, texture_load_r4g4b4a4_a4r4g4b4_cs), + R360_LOAD_SHADER(4, 3, texture_load_gbgr8_grgb8_cs), + R360_LOAD_SHADER(8, 3, texture_load_gbgr8_rgb8_cs), + R360_LOAD_SHADER(4, 3, texture_load_bgrg8_rgbg8_cs), + R360_LOAD_SHADER(8, 3, texture_load_bgrg8_rgb8_cs), + R360_LOAD_SHADER(8, 3, texture_load_r10g11b11_rgba16_cs), + R360_LOAD_SHADER(8, 3, texture_load_r10g11b11_rgba16_snorm_cs), + R360_LOAD_SHADER(8, 3, texture_load_r11g11b10_rgba16_cs), + R360_LOAD_SHADER(8, 3, texture_load_r11g11b10_rgba16_snorm_cs), + R360_LOAD_SHADER(2, 4, texture_load_r16_unorm_float_cs), + R360_LOAD_SHADER(2, 4, texture_load_r16_snorm_float_cs), + R360_LOAD_SHADER(4, 3, texture_load_rg16_unorm_float_cs), + R360_LOAD_SHADER(4, 3, texture_load_rg16_snorm_float_cs), + R360_LOAD_SHADER(8, 2, texture_load_rgba16_unorm_float_cs), + R360_LOAD_SHADER(8, 2, texture_load_rgba16_snorm_float_cs), + R360_LOAD_SHADER(4, 2, texture_load_dxt1_rgba8_cs), + R360_LOAD_SHADER(4, 1, texture_load_dxt3_rgba8_cs), + R360_LOAD_SHADER(4, 1, texture_load_dxt5_rgba8_cs), + R360_LOAD_SHADER(2, 1, texture_load_dxn_rg8_cs), + R360_LOAD_SHADER(1, 2, texture_load_dxt3a_cs), + R360_LOAD_SHADER(2, 2, texture_load_dxt3aas1111_bgra4_cs), + R360_LOAD_SHADER(2, 2, texture_load_dxt3aas1111_argb4_cs), + R360_LOAD_SHADER(1, 2, texture_load_dxt5a_r8_cs), + R360_LOAD_SHADER(2, 2, texture_load_ctx1_cs), + R360_LOAD_SHADER(4, 3, texture_load_depth_unorm_cs), + R360_LOAD_SHADER(4, 3, texture_load_depth_float_cs), +}; +#undef R360_LOAD_SHADER + +// VulkanTextureCache::HostFormat for WebGPU. +struct HostFormat { + LoadShaderIndex load_shader = kUnknown; + WebGpuTextureFormat format = kWebGpuFormatNone; + WebGpuTextureExpand expand = kWebGpuExpandNone; + bool linear_filterable = true; +}; +struct HostFormatPair { + HostFormat format_unsigned; + HostFormat format_signed; + uint32_t swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; +}; + +// VulkanTextureCache::kBestHostFormats with its fallbacks for formats +// WebGPU lacks: S3TC, DXN and DXT5A decompressed (BC is optional in +// WebGPU and absent on iOS), 4:2:2 to RGBA8, 16-bit normalized through the +// *ToFloat load shaders, and 16-bit packed formats expanded to RGBA8. +const HostFormatPair* HostFormats() { + static HostFormatPair formats[64]; + static bool initialized = false; + if (initialized) return formats; + initialized = true; + using F = xenos::TextureFormat; + auto set = [](F f, HostFormat u, HostFormat s, uint32_t swizzle) { + formats[uint32_t(f)] = {u, s, swizzle}; + }; + constexpr uint32_t RRRR = xenos::XE_GPU_TEXTURE_SWIZZLE_RRRR; + constexpr uint32_t RGGG = xenos::XE_GPU_TEXTURE_SWIZZLE_RGGG; + constexpr uint32_t RGBA = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; + constexpr uint32_t RGBB = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBB; + const HostFormat none; + auto h = [](LoadShaderIndex shader, WebGpuTextureFormat format, + WebGpuTextureExpand expand = kWebGpuExpandNone, bool filterable = true) { + return HostFormat{shader, format, expand, filterable}; + }; + set(F::k_1_REVERSE, none, none, RRRR); + set(F::k_1, none, none, RRRR); + set(F::k_8, h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Unorm), + h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Snorm), RRRR); + set(F::k_1_5_5_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand1555), + none, RGBA); + set(F::k_5_6_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand565), + none, RGBB); + // On the host, green bits in blue, blue bits in green (as Xenia's + // R5G5B6ToB5G6R5WithRBGASwizzle). + set(F::k_6_5_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand655), + none, XE_GPU_MAKE_TEXTURE_SWIZZLE(R, B, G, G)); + set(F::k_8_8_8_8, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Snorm), RGBA); + // No snorm 10:10:10:2 in WebGPU. + set(F::k_2_10_10_10, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGB10A2Unorm), none, RGBA); + set(F::k_8_A, h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Unorm), + h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Snorm), RRRR); + set(F::k_8_B, none, none, RRRR); + set(F::k_8_8, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRG8Unorm), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRG8Snorm), RGGG); + set(F::k_Cr_Y1_Cb_Y0_REP, h(Types::kLoadShaderIndexGBGR8ToRGB8, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndexGBGR8ToRGB8, kWebGpuFormatRGBA8Snorm), RGBB); + set(F::k_Y1_Cr_Y0_Cb_REP, h(Types::kLoadShaderIndexBGRG8ToRGB8, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndexBGRG8ToRGB8, kWebGpuFormatRGBA8Snorm), RGBB); + set(F::k_16_16_EDRAM, none, none, RGGG); + set(F::k_8_8_8_8_A, none, none, RGBA); + set(F::k_4_4_4_4, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand4444), + none, RGBA); + set(F::k_10_11_11, + h(Types::kLoadShaderIndexR11G11B10ToRGBA16, kWebGpuFormatRGBA16Float, kWebGpuExpandUnorm16ToFloat), + h(Types::kLoadShaderIndexR11G11B10ToRGBA16SNorm, kWebGpuFormatRGBA16Float, + kWebGpuExpandSnorm16ToFloat), + RGBB); + set(F::k_11_11_10, + h(Types::kLoadShaderIndexR10G11B11ToRGBA16, kWebGpuFormatRGBA16Float, kWebGpuExpandUnorm16ToFloat), + h(Types::kLoadShaderIndexR10G11B11ToRGBA16SNorm, kWebGpuFormatRGBA16Float, + kWebGpuExpandSnorm16ToFloat), + RGBB); + set(F::k_DXT1, h(Types::kLoadShaderIndexDXT1ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_DXT2_3, h(Types::kLoadShaderIndexDXT3ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_DXT4_5, h(Types::kLoadShaderIndexDXT5ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_16_16_16_16_EDRAM, none, none, RGBA); + // Depth as R32_SFLOAT; filterable only with float32-filterable, which is + // optional (sampled with point filtering, as Xenia does for formats + // without linear filtering). + set(F::k_24_8, h(Types::kLoadShaderIndexDepthUnorm, kWebGpuFormatR32Float, kWebGpuExpandNone, false), + none, RRRR); + set(F::k_24_8_FLOAT, + h(Types::kLoadShaderIndexDepthFloat, kWebGpuFormatR32Float, kWebGpuExpandNone, false), none, + RRRR); + set(F::k_16, h(Types::kLoadShaderIndexR16UNormToFloat, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndexR16SNormToFloat, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16, h(Types::kLoadShaderIndexRG16UNormToFloat, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndexRG16SNormToFloat, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16, h(Types::kLoadShaderIndexRGBA16UNormToFloat, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndexRGBA16SNormToFloat, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_16_EXPAND, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16_EXPAND, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16_EXPAND, h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_16_FLOAT, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16_FLOAT, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16_FLOAT, h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_32, none, none, RRRR); + set(F::k_32_32, none, none, RGGG); + set(F::k_32_32_32_32, none, none, RGBA); + const HostFormat r32f = h(Types::kLoadShaderIndex32bpb, kWebGpuFormatR32Float, kWebGpuExpandNone, false); + set(F::k_32_FLOAT, r32f, r32f, RRRR); + const HostFormat rg32f = h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRG32Float, kWebGpuExpandNone, false); + set(F::k_32_32_FLOAT, rg32f, rg32f, RGGG); + const HostFormat rgba32f = + h(Types::kLoadShaderIndex128bpb, kWebGpuFormatRGBA32Float, kWebGpuExpandNone, false); + set(F::k_32_32_32_32_FLOAT, rgba32f, rgba32f, RGBA); + set(F::k_32_AS_8, none, none, RRRR); + set(F::k_32_AS_8_8, none, none, RGGG); + set(F::k_16_MPEG, none, none, RRRR); + set(F::k_16_16_MPEG, none, none, RGGG); + set(F::k_8_INTERLACED, none, none, RRRR); + set(F::k_32_AS_8_INTERLACED, none, none, RRRR); + set(F::k_32_AS_8_8_INTERLACED, none, none, RGGG); + set(F::k_16_INTERLACED, none, none, RRRR); + set(F::k_16_MPEG_INTERLACED, none, none, RRRR); + set(F::k_16_16_MPEG_INTERLACED, none, none, RGGG); + set(F::k_DXN, h(Types::kLoadShaderIndexDXNToRG8, kWebGpuFormatRG8Unorm), none, RGGG); + set(F::k_8_8_8_8_AS_16_16_16_16, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Snorm), RGBA); + formats[uint32_t(F::k_DXT1_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT1)]; + formats[uint32_t(F::k_DXT2_3_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT2_3)]; + formats[uint32_t(F::k_DXT4_5_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT4_5)]; + formats[uint32_t(F::k_2_10_10_10_AS_16_16_16_16)] = formats[uint32_t(F::k_2_10_10_10)]; + formats[uint32_t(F::k_10_11_11_AS_16_16_16_16)] = formats[uint32_t(F::k_10_11_11)]; + formats[uint32_t(F::k_11_11_10_AS_16_16_16_16)] = formats[uint32_t(F::k_11_11_10)]; + set(F::k_32_32_32_FLOAT, none, none, RGBB); + set(F::k_DXT3A, h(Types::kLoadShaderIndexDXT3A, kWebGpuFormatR8Unorm), none, RRRR); + set(F::k_DXT5A, h(Types::kLoadShaderIndexDXT5AToR8, kWebGpuFormatR8Unorm), none, RRRR); + set(F::k_CTX1, h(Types::kLoadShaderIndexCTX1, kWebGpuFormatRG8Unorm), none, RGGG); + // Xenia loads DXT3A_AS_1_1_1_1 into 4:4:4:4, which WebGPU lacks (not yet). + set(F::k_DXT3A_AS_1_1_1_1, none, none, RGBA); + set(F::k_8_8_8_8_GAMMA_EDRAM, none, none, RGBA); + set(F::k_2_10_10_10_FLOAT_EDRAM, none, none, RGBA); + return formats; +} + +const HostFormatPair& GetHostFormatPair(const TextureKey& key) { + return HostFormats()[uint32_t(key.format)]; +} + +// Unsigned and signed versions are separate textures whenever both exist +// with different formats: WebGPU views cannot reinterpret unorm as snorm +// (Vulkan's mutable-format images can, for Xenia's +// unsigned_signed_compatible formats). +bool IsSignedVersionSeparateForFormat(const TextureKey& key) { + const HostFormatPair& pair = GetHostFormatPair(key); + return pair.format_unsigned.format && pair.format_signed.format && + pair.format_unsigned.format != pair.format_signed.format; +} + +const HostFormat& GetHostFormat(const TextureKey& key) { + const HostFormatPair& pair = GetHostFormatPair(key); + bool is_signed = IsSignedVersionSeparateForFormat(key) + ? bool(key.signed_separate) + : pair.format_unsigned.load_shader == kUnknown; + return is_signed ? pair.format_signed : pair.format_unsigned; +} + +// Guest physical pages backing a texture, with the GPU write-watch +// generation each had when loaded (Xenia watches them with memory access +// watches; here the sparse guest memory GPU watch). +struct PageRange { + std::vector generations; + uint32_t first_page = 0; + void Watch(uint32_t start, uint32_t length) { + generations.clear(); + if (!length) return; + first_page = start >> 12; + const uint32_t last_page = (start + length - 1) >> 12; + for (uint32_t page = first_page; page <= last_page; ++page) { + generations.push_back(SparseGuestGpuWatch(r360_kernel_gpu_address_to_virtual(page << 12))); + } + } + bool Outdated() const { + for (size_t i = 0; i < generations.size(); ++i) { + const uint32_t page = first_page + uint32_t(i); + if (generations[i] != SparseGuestGpuGeneration(r360_kernel_gpu_address_to_virtual(page << 12))) { + return true; + } + } + return false; + } +}; + +struct Texture { + TextureKey key; + uint32_t id = 0; + texture_util::TextureGuestLayout guest_layout; + bool loaded_base = false, loaded_mips = false; + PageRange base_pages, mip_pages; + uint32_t GetGuestBaseSize() const { return guest_layout.base.level_data_extent_bytes; } + uint32_t GetGuestMipsSize() const { return guest_layout.mips_total_extent_bytes; } +}; + +struct TextureKeyHasher { + size_t operator()(const TextureKey& key) const { + uint64_t words[2] = {}; + std::memcpy(words, &key, std::min(sizeof(key), sizeof(words))); + uint64_t h = words[0] * 0x9E3779B97F4A7C15ull ^ words[1]; + return size_t(h ^ (h >> 29)); + } +}; + +// TextureCache::TextureBinding. +struct TextureBinding { + TextureKey key; + uint32_t host_swizzle = 0; + uint8_t swizzled_signs = 0; + Texture* texture = nullptr; + Texture* texture_signed = nullptr; + void Reset() { + key.MakeInvalid(); + host_swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_0000; + swizzled_signs = uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); + texture = nullptr; + texture_signed = nullptr; + } +}; + +struct Cache { + std::unordered_map, TextureKeyHasher> textures; + TextureBinding bindings[32]; + uint32_t next_id = 1; + bool load_shader_sent[Types::kLoadShaderCount] = {}; + uint32_t loads = 0, load_failures = 0, created = 0; +}; +Cache& cache() { + static Cache c; + return c; +} + +// TextureCache::BindingInfoFromFetchConstant. +void BindingInfoFromFetchConstant(const xenos::xe_gpu_texture_fetch_t& fetch, TextureKey& key_out, + uint8_t* swizzled_signs_out) { + key_out.MakeInvalid(); + if (swizzled_signs_out) { + *swizzled_signs_out = uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); + } + // gpu_allow_invalid_fetch_constants is off by default in Xenia. + if (fetch.type != xenos::FetchConstantType::kTexture) return; + uint32_t width_minus_1, height_minus_1, depth_or_array_size_minus_1; + uint32_t base_page, mip_page, mip_max_level; + texture_util::GetSubresourcesFromFetchConstant(fetch, &width_minus_1, &height_minus_1, + &depth_or_array_size_minus_1, &base_page, + &mip_page, nullptr, &mip_max_level); + if (base_page == 0 && mip_page == 0) return; + if (fetch.dimension == xenos::DataDimension::k1D) { + if (width_minus_1 >= xenos::kTexture2DCubeMaxWidthHeight || fetch.tiled || fetch.packed_mips) { + return; + } + } + key_out.base_page = base_page; + key_out.mip_page = mip_page; + key_out.dimension = fetch.dimension; + key_out.width_minus_1 = width_minus_1; + key_out.height_minus_1 = height_minus_1; + key_out.depth_or_array_size_minus_1 = depth_or_array_size_minus_1; + key_out.pitch = fetch.pitch; + key_out.mip_max_level = mip_max_level; + key_out.tiled = fetch.tiled; + key_out.packed_mips = fetch.packed_mips; + key_out.format = GetBaseFormat(fetch.format); + key_out.endianness = fetch.endianness; + key_out.is_valid = 1; + if (swizzled_signs_out) *swizzled_signs_out = texture_util::SwizzleSigns(fetch); +} + +// The stream's texture dimensions: 0 2D array (1D and 2D), 1 3D, 2 cube. +uint32_t StreamDimension(xenos::DataDimension dimension) { + switch (dimension) { + case xenos::DataDimension::k3D: return 1; + case xenos::DataDimension::kCube: return 2; + default: return 0; + } +} + +// TextureCache::FindOrCreateTexture and VulkanTextureCache::CreateTexture. +Texture* FindOrCreateTexture(const TextureKey& key) { + Cache& c = cache(); + // WebGPU guaranteed limits (maxTextureDimension2D / 3D, array layers). + constexpr uint32_t kMax2D = 8192, kMax3D = 2048, kMaxLayers = 256; + const uint32_t max_width_height = key.dimension == xenos::DataDimension::k3D ? kMax3D : kMax2D; + const uint32_t max_depth = key.dimension == xenos::DataDimension::k3D ? kMax3D + : key.dimension == xenos::DataDimension::kCube ? 6u + : kMaxLayers; + if (key.GetWidth() > max_width_height || key.GetHeight() > max_width_height || + key.GetDepthOrArraySize() > max_depth) { + return nullptr; + } + if (auto it = c.textures.find(key); it != c.textures.end()) return it->second.get(); + const HostFormat& host_format = GetHostFormat(key); + if (!host_format.format || host_format.load_shader == kUnknown) return nullptr; + auto texture = std::make_unique(); + texture->key = key; + texture->id = c.next_id++; + texture->guest_layout = key.GetGuestLayout(); + uint32_t* w = GpuStream().Begin(kGpuStreamTexture, 7); + w[0] = texture->id; + w[1] = host_format.format; + w[2] = StreamDimension(key.dimension); + w[3] = key.GetWidth(); + w[4] = key.GetHeight(); + w[5] = key.GetDepthOrArraySize(); + w[6] = key.mip_max_level + 1; + ++c.created; + Texture* result = texture.get(); + c.textures.emplace(key, std::move(texture)); + return result; +} + +void SendLoadShader(LoadShaderIndex index) { + Cache& c = cache(); + if (c.load_shader_sent[index]) return; + c.load_shader_sent[index] = true; + const LoadShader& shader = kLoadShaders[index]; + uint32_t* w = GpuStream().Begin(kGpuStreamLoadShader, 2 + shader.spirv_bytes / 4); + w[0] = index; + w[1] = shader.spirv_bytes / 4; + std::memcpy(w + 2, shader.spirv, shader.spirv_bytes); +} + +// VulkanTextureCache::LoadTextureDataFromResidentMemoryImpl: the load +// shader dispatches into a scratch buffer and the copies from it into the +// texture, as one stream op. Host rows are padded to WebGPU's 256-byte +// bytesPerRow alignment for buffer to texture copies. +bool LoadTextureData(Texture& texture, bool load_base, bool load_mips) { + const TextureKey& key = texture.key; + const HostFormat& host_format = GetHostFormat(key); + const LoadShaderIndex load_shader = host_format.load_shader; + if (load_shader == kUnknown) return false; + const Types::LoadShaderInfo& load_shader_info = kLoadShaders[load_shader].info; + + const texture_util::TextureGuestLayout& guest_layout = texture.guest_layout; + const xenos::DataDimension dimension = key.dimension; + const bool is_3d = dimension == xenos::DataDimension::k3D; + const uint32_t width = key.GetWidth(), height = key.GetHeight(); + const uint32_t depth_or_array_size = key.GetDepthOrArraySize(); + const uint32_t depth = is_3d ? depth_or_array_size : 1; + const uint32_t array_size = is_3d ? 1 : depth_or_array_size; + const xenos::TextureFormat guest_format = key.format; + const FormatInfo* guest_format_info = FormatInfo::Get(guest_format); + const uint32_t block_width = guest_format_info->block_width; + const uint32_t block_height = guest_format_info->block_height; + const uint32_t bytes_per_block = guest_format_info->bytes_per_block(); + const uint32_t level_first = load_base ? 0 : 1; + const uint32_t level_last = load_mips ? key.mip_max_level : 0; + if (level_first > level_last) return true; + const uint32_t level_packed = guest_layout.packed_level; + const uint32_t level_stored_first = std::min(level_first, level_packed); + const uint32_t level_stored_last = std::min(level_last, level_packed); + uint32_t loop_level_first, loop_level_last; + if (level_packed == 0) { + loop_level_first = uint32_t(level_first != 0); + loop_level_last = uint32_t(level_last != 0); + } else { + loop_level_first = level_stored_first; + loop_level_last = level_stored_last; + } + + // Host layout (no resolution scale, host formats never block-compressed). + uint32_t host_x_blocks_per_thread = (1u << load_shader_info.guest_x_blocks_per_thread_log2) * block_width; + // bytesPerRow multiple of 256 (of 128 when expanded to twice the size). + const uint32_t row_alignment_bytes = + (host_format.expand >= kWebGpuExpand565 && host_format.expand <= kWebGpuExpand4444) ? 128u : 256u; + const uint32_t row_alignment_blocks = std::max(row_alignment_bytes / load_shader_info.bytes_per_host_block, 1u); + const uint32_t x_pitch_alignment = std::max(host_x_blocks_per_thread, row_alignment_blocks); + struct HostLayout { + uint32_t offset_bytes, slice_size_bytes, x_pitch_blocks, y_pitch_blocks; + }; + HostLayout host_layout_base{}, host_layout_mips[xenos::kTextureMaxMips]{}; + uint32_t host_buffer_size = 0; + for (uint32_t loop_level = loop_level_first; loop_level <= loop_level_last; ++loop_level) { + const bool is_base = loop_level == 0; + const uint32_t level = level_packed == 0 ? 0 : loop_level; + HostLayout& l = is_base ? host_layout_base : host_layout_mips[level]; + l.offset_bytes = host_buffer_size; + uint32_t x_texels, y_texels, z_texels; + if (level == level_packed) { + const auto& packed = is_base ? guest_layout.base : guest_layout.mips[level]; + x_texels = packed.x_extent_blocks * block_width; + y_texels = packed.y_extent_blocks * block_height; + z_texels = packed.z_extent; + } else { + x_texels = std::max(width >> level, 1u); + y_texels = std::max(height >> level, 1u); + z_texels = std::max(depth >> level, 1u); + } + l.x_pitch_blocks = xe::round_up(x_texels, x_pitch_alignment); + l.y_pitch_blocks = y_texels; + l.slice_size_bytes = load_shader_info.bytes_per_host_block * l.x_pitch_blocks * l.y_pitch_blocks * z_texels; + host_buffer_size += l.slice_size_bytes * array_size; + } + host_buffer_size = xe::align(host_buffer_size, 16u); + + // Guest data in the shared memory buffer. + const uint32_t base_offset = key.base_page << 12, mips_offset = key.mip_page << 12; + const uint32_t base_size = xe::align(texture.GetGuestBaseSize(), 16u); + const uint32_t mips_size = xe::align(texture.GetGuestMipsSize(), 16u); + if (level_first == 0 && !GpuSharedMemory().RequestRange(base_offset, base_size)) return false; + if (level_last != 0 && !GpuSharedMemory().RequestRange(mips_offset, mips_size)) return false; + SendLoadShader(load_shader); + + // Dispatches: source (0 base, 1 mips), LoadConstants (10 words), groups. + struct Dispatch { + uint32_t source; + Types::LoadConstants constants; + uint32_t groups[3]; + }; + static_assert(sizeof(Types::LoadConstants) == 40, "LoadConstants layout"); + std::vector dispatches; + Types::LoadConstants load_constants{}; + load_constants.is_tiled_3d_endian_scale = uint32_t(key.tiled) | (uint32_t(is_3d) << 1) | + (uint32_t(key.endianness) << 2) | (1u << 4) | (1u << 7); + const uint32_t guest_x_blocks_per_group_log2 = + Types::kLoadGuestXThreadsPerGroupLog2 + load_shader_info.guest_x_blocks_per_thread_log2; + for (uint32_t loop_level = loop_level_first; loop_level <= loop_level_last; ++loop_level) { + const bool is_base = loop_level == 0; + const uint32_t level = level_packed == 0 ? 0 : loop_level; + load_constants.guest_offset = is_base ? 0 : guest_layout.mip_offsets_bytes[level]; + const auto& level_guest_layout = is_base ? guest_layout.base : guest_layout.mips[level]; + load_constants.guest_pitch_aligned = level_guest_layout.row_pitch_bytes / bytes_per_block; + load_constants.guest_z_stride_block_rows_aligned = level_guest_layout.z_slice_stride_block_rows; + uint32_t level_width, level_height, level_depth; + if (level == level_packed) { + level_width = level_guest_layout.x_extent_blocks * block_width; + level_height = level_guest_layout.y_extent_blocks * block_height; + level_depth = level_guest_layout.z_extent; + } else { + level_width = std::max(width >> level, 1u); + level_height = std::max(height >> level, 1u); + level_depth = std::max(depth >> level, 1u); + } + load_constants.size_blocks[0] = (level_width + (block_width - 1)) / block_width; + load_constants.size_blocks[1] = (level_height + (block_height - 1)) / block_height; + load_constants.size_blocks[2] = level_depth; + load_constants.height_texels = level_height; + const uint32_t group_count_x = + (load_constants.size_blocks[0] + ((1u << guest_x_blocks_per_group_log2) - 1)) >> + guest_x_blocks_per_group_log2; + const uint32_t group_count_y = + (load_constants.size_blocks[1] + ((1u << Types::kLoadGuestYBlocksPerGroupLog2) - 1)) >> + Types::kLoadGuestYBlocksPerGroupLog2; + const HostLayout& l = is_base ? host_layout_base : host_layout_mips[level]; + load_constants.host_offset = l.offset_bytes; + load_constants.host_pitch = load_shader_info.bytes_per_host_block * l.x_pitch_blocks; + for (uint32_t slice = 0; slice < array_size; ++slice) { + dispatches.push_back({is_base ? 0u : 1u, load_constants, {group_count_x, group_count_y, load_constants.size_blocks[2]}}); + load_constants.guest_offset += level_guest_layout.array_slice_stride_bytes; + load_constants.host_offset += l.slice_size_bytes; + } + } + + // Copies: buffer offset, bytes per row, rows per image, mip level, + // layers, width, height, depth. + struct Copy { + uint32_t words[8]; + }; + std::vector copies; + for (uint32_t level = level_first; level <= level_last; ++level) { + const HostLayout& l = level != 0 ? host_layout_mips[std::min(level, level_packed)] : host_layout_base; + uint32_t buffer_offset = l.offset_bytes; + if (level >= level_packed) { + uint32_t offset_x, offset_y, offset_z; + texture_util::GetPackedMipOffset(width, height, depth, guest_format, level, offset_x, offset_y, + offset_z); + offset_x *= block_width; + offset_y *= block_height; + buffer_offset += load_shader_info.bytes_per_host_block * + (offset_x + l.x_pitch_blocks * (offset_y + l.y_pitch_blocks * offset_z)); + } + copies.push_back({{buffer_offset, l.x_pitch_blocks * load_shader_info.bytes_per_host_block, l.y_pitch_blocks, + level, array_size, std::max(width >> level, 1u), std::max(height >> level, 1u), + std::max(depth >> level, 1u)}}); + } + + // id, load shader, expand, host buffer size, base offset / size, mips + // offset / size, dispatch count, copy count, dispatches (14 words), copies + // (8 words). + const uint32_t words = 10 + uint32_t(dispatches.size()) * 14 + uint32_t(copies.size()) * 8; + uint32_t* w = GpuStream().Begin(kGpuStreamTextureLoad, words); + w[0] = texture.id; + w[1] = load_shader; + w[2] = host_format.expand; + w[3] = host_buffer_size; + w[4] = base_offset; + w[5] = base_size; + w[6] = mips_offset; + w[7] = mips_size; + w[8] = uint32_t(dispatches.size()); + w[9] = uint32_t(copies.size()); + w += 10; + for (const Dispatch& d : dispatches) { + *w++ = d.source; + std::memcpy(w, &d.constants, sizeof(d.constants)); + w += 10; + *w++ = d.groups[0]; + *w++ = d.groups[1]; + *w++ = d.groups[2]; + } + for (const Copy& copy : copies) { + std::memcpy(w, copy.words, sizeof(copy.words)); + w += 8; + } + return true; +} + +// TextureCache::LoadTextureData: loads what CPU writes have outdated. +void MakeUpToDate(Texture& texture) { + const bool has_base = texture.key.base_page != 0; + const bool has_mips = texture.key.mip_max_level != 0 && texture.key.mip_page != 0; + const bool base_outdated = has_base && (!texture.loaded_base || texture.base_pages.Outdated()); + const bool mips_outdated = has_mips && (!texture.loaded_mips || texture.mip_pages.Outdated()); + if (!base_outdated && !mips_outdated) return; + Cache& c = cache(); + if (!LoadTextureData(texture, base_outdated, mips_outdated)) { + ++c.load_failures; + return; + } + ++c.loads; + if (base_outdated) { + texture.loaded_base = true; + texture.base_pages.Watch(texture.key.base_page << 12, texture.GetGuestBaseSize()); + } + if (mips_outdated) { + texture.loaded_mips = true; + texture.mip_pages.Watch(texture.key.mip_page << 12, texture.GetGuestMipsSize()); + } +} + +} // namespace + +// TextureCache::RequestTextures, rechecking every used binding each draw +// (the bindings stay as Xenia keeps them; pages are checked against their +// write generations instead of watch callbacks). +void WebGpuRequestTextures(const RegisterFile& regs, uint32_t used_texture_mask) { + Cache& c = cache(); + uint32_t remaining = used_texture_mask, index; + while (xe::bit_scan_forward(remaining, &index)) { + remaining &= ~(1u << index); + TextureBinding& binding = c.bindings[index]; + const xenos::xe_gpu_texture_fetch_t fetch = regs.GetTextureFetch(index); + TextureKey key; + uint8_t swizzled_signs; + BindingInfoFromFetchConstant(fetch, key, &swizzled_signs); + if (!key.is_valid) { + binding.Reset(); + continue; + } + binding.key = key; + binding.swizzled_signs = swizzled_signs; + binding.host_swizzle = Types::GuestToHostSwizzle(fetch.swizzle, GetHostFormatPair(key).swizzle); + binding.texture = nullptr; + binding.texture_signed = nullptr; + if (IsSignedVersionSeparateForFormat(key)) { + if (texture_util::IsAnySignNotSigned(swizzled_signs)) binding.texture = FindOrCreateTexture(key); + if (texture_util::IsAnySignSigned(swizzled_signs)) { + TextureKey signed_key = key; + signed_key.signed_separate = 1; + binding.texture_signed = FindOrCreateTexture(signed_key); + } + } else { + binding.texture = FindOrCreateTexture(key); + } + if (binding.texture) MakeUpToDate(*binding.texture); + if (binding.texture_signed) MakeUpToDate(*binding.texture_signed); + } +} + +// VulkanTextureCache::GetActiveBindingOrNullImageView. +uint32_t WebGpuTextureForBinding(const SpirvShader::TextureBinding& shader_binding) { + const TextureBinding& binding = cache().bindings[shader_binding.fetch_constant]; + if (!binding.key.is_valid || + !Types::AreDimensionsCompatible(shader_binding.dimension, binding.key.dimension)) { + return 0; + } + const Texture* texture = binding.texture; + if (shader_binding.is_signed && IsSignedVersionSeparateForFormat(binding.key)) { + texture = binding.texture_signed; + } + return texture && (texture->loaded_base || texture->loaded_mips) ? texture->id : 0; +} + +void WebGpuTexturesReset() { + Cache& c = cache(); + c.textures.clear(); + for (TextureBinding& binding : c.bindings) binding.Reset(); + for (bool& sent : c.load_shader_sent) sent = false; +} + +// VulkanTextureCache::RequestSwapTexture. +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant, uint32_t* host_swizzle) { + xenos::xe_gpu_texture_fetch_t fetch; + std::memcpy(&fetch, fetch_constant, sizeof(fetch)); + TextureKey key; + BindingInfoFromFetchConstant(fetch, key, nullptr); + *host_swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; + if (!key.is_valid || !key.base_page || key.dimension != xenos::DataDimension::k2DOrStacked) return 0; + *host_swizzle = Types::GuestToHostSwizzle(fetch.swizzle, GetHostFormatPair(key).swizzle); + Texture* texture = FindOrCreateTexture(key); + if (!texture) return 0; + MakeUpToDate(*texture); + return texture->loaded_base ? texture->id : 0; +} + +void WebGpuTexturesMarkRangeResolved(uint32_t start, uint32_t length) { + if (!length) return; + const uint32_t end = start + length; + for (auto& [key, texture] : cache().textures) { + const uint32_t base = key.base_page << 12, mips = key.mip_page << 12; + if (texture->loaded_base && base < end && start < base + texture->GetGuestBaseSize()) { + texture->loaded_base = false; + } + if (texture->loaded_mips && mips < end && start < mips + texture->GetGuestMipsSize()) { + texture->loaded_mips = false; + } + } +} + +uint32_t WebGpuTextureHostSwizzle(uint32_t fetch_constant) { + const TextureBinding& binding = cache().bindings[fetch_constant & 31]; + return binding.key.is_valid ? binding.host_swizzle : xenos::XE_GPU_TEXTURE_SWIZZLE_0000; +} + +uint8_t WebGpuTextureSwizzledSigns(uint32_t fetch_constant) { + const TextureBinding& binding = cache().bindings[fetch_constant & 31]; + return binding.key.is_valid ? binding.swizzled_signs + : uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); +} + +// VulkanTextureCache::GetSamplerParameters, packed: clamp x / y / z (3 bits +// each), border color (2), mag / min / mip linear, aniso filter (3), mip +// base map, mip min level (4). +uint32_t WebGpuSamplerParameters(const RegisterFile& regs, const SpirvShader::SamplerBinding& binding) { + const xenos::xe_gpu_texture_fetch_t fetch = regs.GetTextureFetch(binding.fetch_constant); + xenos::ClampMode clamp[3]; + texture_util::GetClampModesForDimension(fetch, clamp[0], clamp[1], clamp[2]); + // NormalizeClampMode: no clamp to halfway; mirror clamp falls back to + // mirrored repeat (WebGPU has neither mirror clamp nor border colors). + for (auto& mode : clamp) { + if (mode == xenos::ClampMode::kClampToHalfway) mode = xenos::ClampMode::kClampToEdge; + if (mode == xenos::ClampMode::kMirrorClampToEdge || mode == xenos::ClampMode::kMirrorClampToHalfway || + mode == xenos::ClampMode::kMirrorClampToBorder) { + mode = xenos::ClampMode::kMirroredRepeat; + } + } + const bool border = xenos::ClampModeUsesBorder(clamp[0]) || xenos::ClampModeUsesBorder(clamp[1]) || + xenos::ClampModeUsesBorder(clamp[2]); + const uint32_t border_color = border ? uint32_t(fetch.border_color) : 0u; + auto filter = [](xenos::TextureFilter binding_filter, xenos::TextureFilter fetch_filter) { + return binding_filter == xenos::TextureFilter::kUseFetchConst ? fetch_filter : binding_filter; + }; + const xenos::TextureFilter mip_filter = filter(binding.mip_filter, fetch.mip_filter); + bool mag_linear = filter(binding.mag_filter, fetch.mag_filter) == xenos::TextureFilter::kLinear; + bool min_linear = filter(binding.min_filter, fetch.min_filter) == xenos::TextureFilter::kLinear; + bool mip_linear = mip_filter == xenos::TextureFilter::kLinear; + if (mag_linear || min_linear || mip_linear) { + TextureKey key; + uint8_t signs; + BindingInfoFromFetchConstant(fetch, key, &signs); + bool linear_filterable = key.is_valid; + if (key.is_valid) { + const HostFormatPair& pair = GetHostFormatPair(key); + if ((texture_util::IsAnySignNotSigned(signs) && !pair.format_unsigned.linear_filterable) || + (texture_util::IsAnySignSigned(signs) && !pair.format_signed.linear_filterable)) { + linear_filterable = false; + } + } + if (!linear_filterable) mag_linear = min_linear = mip_linear = false; + } + const xenos::AnisoFilter aniso_filter = std::min( + binding.aniso_filter == xenos::AnisoFilter::kUseFetchConst ? fetch.aniso_filter : binding.aniso_filter, + xenos::AnisoFilter::kMax_16_1); + uint32_t mip_min_level; + texture_util::GetSubresourcesFromFetchConstant(fetch, nullptr, nullptr, nullptr, nullptr, nullptr, + &mip_min_level, nullptr); + return uint32_t(clamp[0]) | (uint32_t(clamp[1]) << 3) | (uint32_t(clamp[2]) << 6) | (border_color << 9) | + (uint32_t(mag_linear) << 11) | (uint32_t(min_linear) << 12) | (uint32_t(mip_linear) << 13) | + (uint32_t(aniso_filter) << 14) | (uint32_t(mip_filter == xenos::TextureFilter::kBaseMap) << 17) | + (std::min(mip_min_level, 15u) << 18); +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// 0 textures, 1 created, 2 loads, 3 load failures. +__attribute__((used, export_name("r360_gpu_texture_stat"))) +uint32_t r360_gpu_texture_stat(uint32_t index) { + auto& c = rx::cache(); + switch (index) { + case 0: return uint32_t(c.textures.size()); + case 1: return c.created; + case 2: return c.loads; + case 3: return c.load_failures; + default: return 0; + } +} +} // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_textures.h b/src/xenia_web_bootstrap/webgpu_textures.h new file mode 100644 index 00000000..284eb9b6 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_textures.h @@ -0,0 +1,76 @@ +#pragma once + +// WebGPU texture cache (webgpu_textures.cpp): a port of Xenia's TextureCache +// (src/xenia/gpu/texture_cache.cc) with VulkanTextureCache's host formats and +// texture loading. Textures are untiled and converted on the GPU by Xenia's +// texture_load_* compute shaders reading the shared memory buffer, as Xenia +// does, then copied into WebGPU textures. + +#include + +#include "xenia/gpu/register_file.h" +#include "xenia/gpu/spirv_shader.h" + +namespace render360::xenia_web { + +// WebGPU texture formats (render360-webgpu-backend.mjs TEXTURE_FORMATS). +enum WebGpuTextureFormat : uint32_t { + kWebGpuFormatNone = 0, + kWebGpuFormatR8Unorm, + kWebGpuFormatR8Snorm, + kWebGpuFormatRG8Unorm, + kWebGpuFormatRG8Snorm, + kWebGpuFormatRGBA8Unorm, + kWebGpuFormatRGBA8Snorm, + kWebGpuFormatRGB10A2Unorm, + kWebGpuFormatR16Float, + kWebGpuFormatRG16Float, + kWebGpuFormatRGBA16Float, + kWebGpuFormatR32Float, + kWebGpuFormatRG32Float, + kWebGpuFormatRGBA32Float, +}; + +// Second pass over the load shader output where WebGPU has no format for +// what Xenia's Vulkan backend loads into (render360-webgpu-backend.mjs). +enum WebGpuTextureExpand : uint32_t { + kWebGpuExpandNone = 0, + // Guest 16-bit packed texels (16bpb load: untiled, endian-swapped) to + // RGBA8 with the host component order of Xenia's Vulkan formats. + kWebGpuExpand565, + kWebGpuExpand655, + kWebGpuExpand1555, + kWebGpuExpand4444, + // 16-bit normalized components (Xenia's R16G16B16A16_UNORM / SNORM + // outputs) to float16 in place. + kWebGpuExpandUnorm16ToFloat, + kWebGpuExpandSnorm16ToFloat, +}; + +// Makes the textures of the fetch constants in `used_texture_mask` resident +// and up to date (Xenia's TextureCache::RequestTextures), recording texture +// creation and load ops. +void WebGpuRequestTextures(const xe::gpu::RegisterFile& regs, uint32_t used_texture_mask); + +// For the bindings of the last WebGpuRequestTextures: stream texture id for +// a shader texture binding (0: null texture), host swizzle and swizzled +// signs for the system constants, and the packed sampler parameters +// (render360-webgpu-backend.mjs sampler()). +uint32_t WebGpuTextureForBinding(const xe::gpu::SpirvShader::TextureBinding& binding); +uint32_t WebGpuTextureHostSwizzle(uint32_t fetch_constant); +uint8_t WebGpuTextureSwizzledSigns(uint32_t fetch_constant); +uint32_t WebGpuSamplerParameters(const xe::gpu::RegisterFile& regs, + const xe::gpu::SpirvShader::SamplerBinding& binding); + +// The front buffer texture of a swap (6 fetch constant words), loaded; 0 +// if there is none. `host_swizzle` gets the swizzle to present it with. +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant, uint32_t* host_swizzle); + +// Forgets every texture (a new stream consumer, r360_gpu_set_mode). +void WebGpuTexturesReset(); + +// A resolve wrote the range on the GPU (TextureCache::MarkRangeAsResolved): +// textures in it are reloaded on their next use. +void WebGpuTexturesMarkRangeResolved(uint32_t start, uint32_t length); + +} // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/xam_xdbf.cpp b/src/xenia_web_bootstrap/xam_xdbf.cpp new file mode 100644 index 00000000..061f6fc3 --- /dev/null +++ b/src/xenia_web_bootstrap/xam_xdbf.cpp @@ -0,0 +1,33 @@ +// Title XDBF achievement table for XamUserCreateAchievementEnumerator, +// parsed by Xenia's own xdbf_utils (kept out of kernel_xboxkrnl_services.cpp, +// whose status constants collide with xenia/xbox.h macros). +#include "xam_xdbf.h" + +#include "xenia/base/string.h" +#include "xenia/kernel/util/xdbf_utils.h" + +namespace render360::xenia_web { + +std::vector ParseXdbfAchievements(const uint8_t* data, size_t size) { + std::vector out; + const xe::kernel::util::XdbfGameData db(data, size); + if (!db.is_valid()) return out; + // Xenia xam_user.cc: cvars::user_language (default 1, English), or the + // title's default language when it has no English strings. + const auto language = db.GetExistingLanguage(xe::XLanguage::kEnglish); + auto text = [&](uint16_t id) { return xe::to_utf16(db.GetStringTableEntry(language, id)); }; + for (const auto& entry : db.GetAchievements()) { + XdbfAchievement item; + item.id = entry.id; + item.label = text(entry.label_id); + item.description = text(entry.description_id); + item.unachieved = text(entry.unachieved_id); + item.image_id = entry.image_id; + item.gamerscore = entry.gamerscore; + item.flags = entry.flags; + out.push_back(std::move(item)); + } + return out; +} + +} // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/xam_xdbf.h b/src/xenia_web_bootstrap/xam_xdbf.h new file mode 100644 index 00000000..eb947d0c --- /dev/null +++ b/src/xenia_web_bootstrap/xam_xdbf.h @@ -0,0 +1,21 @@ +#ifndef RENDER360_XAM_XDBF_H_ +#define RENDER360_XAM_XDBF_H_ + +#include +#include +#include +#include + +namespace render360::xenia_web { + +// One XDBF achievement table entry with its strings resolved. +struct XdbfAchievement { + uint32_t id = 0, image_id = 0, gamerscore = 0, flags = 0; + std::u16string label, description, unachieved; +}; + +std::vector ParseXdbfAchievements(const uint8_t* data, size_t size); + +} // namespace render360::xenia_web + +#endif // RENDER360_XAM_XDBF_H_ diff --git a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp index f543d9e7..a6a9f2de 100644 --- a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp +++ b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp @@ -16,6 +16,8 @@ extern "C" __attribute__((weak)) uint32_t r360_debug_watch_address() { return 0; // standalone Xenos foundation keeps its bounded bring-up raster. namespace render360::xenia_web { __attribute__((weak)) bool RenderXenosDraw(const XenosSoftDraw&) { return false; } +// The WebGPU backend (webgpu_draws.cpp) records the swap's front buffer. +__attribute__((weak)) void WebGpuSwap(const uint32_t*) {} } namespace render360::xenia_web { @@ -439,12 +441,20 @@ bool ExecuteBuffer(const uint32_t* words, uint32_t word_count, uint32_t depth) { if (type != 3) { SetFault(header_index, depth, kStatusUnsupported); return false; } const uint32_t count = ((header >> 16) & 0x3FFFu) + 1u, opcode = (header >> 8) & 0x7Fu; if (count > word_count - i) { SetFault(header_index, depth, kStatusInvalid); return false; } + // CommandProcessor::ExecutePacketType3: bit 0 predicates the packet on the + // tiling bin (SET_BIN_MASK/SELECT); predicated swaps are always skipped. + // Predicated tiling replays one IB per bin, so a packet meant for a single + // bin must not run in every pass. + if ((header & 1u) && (!(g_bin_select & g_bin_mask) || opcode == kPm4XeSwap)) { + i += count; continue; + } const uint32_t* p = words + i; g_last_opcode = opcode; bool handled = true; switch (opcode) { case kPm4Nop: case kPm4MeInit: case kPm4WaitForIdle: break; case kPm4DrawIndx: case kPm4DrawIndx2: handled = ExecuteDraw(opcode, p, count); break; case kPm4XeSwap: for (uint32_t w = 0; w < 6u; ++w) g_swap_fetch[w] = g_regs[0x4800u + w]; + WebGpuSwap(g_swap_fetch.data()); handled = ExecuteSwap(p, count); break; case kPm4RegRmw: { if (count != 3u) { handled = false; g_status = kStatusInvalid; break; } @@ -682,7 +692,7 @@ const ShaderCapture* ShaderForExport(uint32_t type) { extern "C" { void r360_xenos_reset(){render360::xenia_web::Reset();} -uint32_t r360_xenos_ring_buffer(){return uint32_t(reinterpret_cast(render360::xenia_web::g_ring.data()));} +uintptr_t r360_xenos_ring_buffer(){return (reinterpret_cast(render360::xenia_web::g_ring.data()));} uint32_t r360_xenos_ring_capacity(){return render360::xenia_web::kRingCapacity;} uint32_t r360_xenos_submit(uint32_t n){if(n>render360::xenia_web::kRingCapacity){render360::xenia_web::g_status=render360::xenia_web::kStatusInvalid;return 0;}render360::xenia_web::g_ring_words=n;return render360::xenia_web::Execute()?1u:0u;} uint32_t r360_xenos_status(){return render360::xenia_web::g_status;} @@ -719,7 +729,7 @@ uint32_t r360_xenos_frame_provenance(){return render360::xenia_web::FrameProvena uint32_t r360_xenos_real_title_frame_ready(){const uint32_t need=render360::xenia_web::kFrameProvSwap|render360::xenia_web::kFrameProvVertexShader|render360::xenia_web::kFrameProvPixelShader|render360::xenia_web::kFrameProvFetchResources;const uint32_t p=render360::xenia_web::FrameProvenance();return((p&need)==need&&!(p&render360::xenia_web::kFrameProvBoundedRaster))?1u:0u;} uint32_t r360_xenos_register(uint32_t i){return i=render360::xenia_web::g_regs.size())return 0;render360::xenia_web::g_regs[i]=v;return 1;} -uint32_t r360_xenos_shader_buffer(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?uint32_t(reinterpret_cast(s->words.data())):0u;} +uintptr_t r360_xenos_shader_buffer(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?(reinterpret_cast(s->words.data())):0u;} uint32_t r360_xenos_shader_dwords(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->dword_count:0u;} uint32_t r360_xenos_shader_hash(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->hash:0u;} uint32_t r360_xenos_shader_guest_address(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->guest_address:0u;} @@ -728,7 +738,7 @@ uint32_t r360_xenos_debug_draws(uint32_t n){render360::xenia_web::g_draw_log_rem uint32_t r360_xenos_swap_fetch_word(uint32_t w){return w<6u?render360::xenia_web::g_swap_fetch[w]:0u;} uint32_t r360_xenos_fetch_constant_word(uint32_t g,uint32_t w){if(w>=6u)return 0u;const uint64_t i=0x4800ull+uint64_t(g)*6u+w;return i(render360::xenia_web::g_frame.data()));} +uintptr_t r360_xenos_frame_buffer(){return (reinterpret_cast(render360::xenia_web::g_frame.data()));} uint32_t r360_xenos_frame_size(){return render360::xenia_web::kFrameBytes;} uint32_t r360_xenos_frame_width(){return render360::xenia_web::kFrameWidth;} uint32_t r360_xenos_frame_height(){return render360::xenia_web::kFrameHeight;} diff --git a/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp b/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp index 7c167968..baf0ff41 100644 --- a/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp +++ b/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp @@ -14,7 +14,7 @@ extern "C" { uint32_t r360_xenos_register(uint32_t index); -uint32_t r360_xenos_shader_buffer(uint32_t shader_type); +uintptr_t r360_xenos_shader_buffer(uint32_t shader_type); uint32_t r360_xenos_shader_dwords(uint32_t shader_type); uint32_t r360_xenos_shader_hash(uint32_t shader_type); } @@ -98,7 +98,7 @@ std::unique_ptr AnalyzeCurrentShader(uint32_t type) { return nullptr; } const uint32_t count = r360_xenos_shader_dwords(type); - const uint32_t ptr = r360_xenos_shader_buffer(type); + const uintptr_t ptr = r360_xenos_shader_buffer(type); if (!count || !ptr) { g_status = kStatusNoShader; return nullptr; diff --git a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp index bd3f529c..1acc573c 100644 --- a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp +++ b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp @@ -7,12 +7,15 @@ // assembly, triangle rasterization, the output merger and resolve copies. #include "xenos_soft_renderer.h" +#include "webgpu_backend.h" #include #include #include #include +#include #include +#include #include #include #include @@ -813,6 +816,16 @@ bool Resolve() { if (!xe::gpu::draw_util::GetResolveInfo(regs, *memory, trace_writer, 1, 1, false, false, info)) { return Skip(kSkipResolveInfo); } + if (getenv("R360_RESOLVE_LOG")) { + static uint32_t logged = 0; + if (logged++ < 3) + std::fprintf(stderr, "R360_RESOLVE_SOFT dest_base_reg=0x%08X adjusted=0x%08X extent=0x%08X+%u dest_off=%u,%u edram_off=%u,%u size=%ux%u\n", + regs[XE_GPU_REG_RB_COPY_DEST_BASE], info.copy_dest_base, info.copy_dest_extent_start, + info.copy_dest_extent_length, info.copy_dest_coordinate_info.offset_x_div_8 * 8u, + info.copy_dest_coordinate_info.offset_y_div_8 * 8u, info.coordinate_info.edram_offset_x_div_8 * 8u, + info.coordinate_info.edram_offset_y_div_8 * 8u, info.coordinate_info.width_div_8 * 8u, + info.height_div_8 * 8u); + } const bool copying_depth = info.IsCopyingDepth(); const auto& edram_info = copying_depth ? info.depth_edram_info : info.color_edram_info; const uint32_t width = info.coordinate_info.width_div_8 * 8u; @@ -1208,7 +1221,30 @@ bool SampleXenosTexture(const xenos::xe_gpu_texture_fetch_t& fetch, return true; } +// Host time spent rendering (draws, clears, resolves), for the frame-time +// overlay's CPU-emulation vs GPU-rendering split (r360_xenos_soft_render_us). +uint64_t g_render_ns = 0; +uint64_t MonotonicNs() { + timespec ts{}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return uint64_t(ts.tv_sec) * 1000000000ull + uint64_t(ts.tv_nsec); +} +bool RenderXenosDrawUntimed(const XenosSoftDraw& draw); bool RenderXenosDraw(const XenosSoftDraw& draw) { + if (!g_rasterize) { + // WebGPU play path: the software renderer does no work at all. + if (WebGpuBackendEnabled()) WebGpuIssueDraw(draw); + return true; + } + const uint64_t start = MonotonicNs(); + const bool ok = RenderXenosDrawUntimed(draw); + g_render_ns += MonotonicNs() - start; + return ok; +} +bool RenderXenosDrawUntimed(const XenosSoftDraw& draw) { + // The WebGPU backend records the draw for the browser; the software + // renderer still runs (for comparison) unless rasterization is off. + if (WebGpuBackendEnabled()) WebGpuIssueDraw(draw); // Headless fast-forward (r360_xenos_soft_set_rasterize(0)): no EDRAM // work at all; the command processor still executes every packet. if (!g_rasterize) return true; @@ -1236,11 +1272,52 @@ void ResetXenosSoftRenderer() { g_last_skip_reason = g_texture_fetch_failures = g_last_texture_format = 0; } +// Rectangle lists for the GPU backend (webgpu_draws.cpp): WebGPU has no +// geometry shaders, so the guest vertex shader runs here on Xenia's +// ShaderInterpreter (as for the software renderer) and the host draws the +// shaded vertices. Fills 4 + 64 floats per guest vertex: position, then the +// 16 interpolators. +bool ShadeXenosVertices(const XenosSoftDraw& draw, std::vector& out, uint32_t* vertex_count) { + RegisterFile& regs = Registers(); + const uint32_t count_regs = std::min(draw.register_count, RegisterFile::kRegisterCount); + std::memcpy(regs.values, draw.registers, count_regs * sizeof(uint32_t)); + reg::VGT_DRAW_INITIATOR init; + init.value = draw.draw_initiator; + const uint32_t count = init.num_indices; + *vertex_count = 0; + auto* vs = GetShader(xenos::ShaderType::kVertex, draw.vertex_shader, draw.vertex_shader_dwords, + draw.vertex_shader_hash); + if (!vs || !xe::gpu::ShaderInterpreter::CanInterpretShader(*vs)) return false; + xe::Memory* memory = ActiveProbeMemory(); + if (!memory) return false; + out.assign(size_t(count) * 68, 0.0f); + xe::gpu::ShaderInterpreter interpreter(regs, *memory); + VertexExportSink sink; + interpreter.SetExportSink(&sink); + interpreter.SetShader(*vs); + for (uint32_t i = 0; i < count; ++i) { + uint32_t index = 0; + if (!ReadIndex(draw, init, i, &index)) return false; + std::fill(interpreter.temp_registers(), + interpreter.temp_registers() + xenos::kMaxShaderTempRegisters * 4, 0.0f); + interpreter.temp_registers()[0] = float(index); + VertexOut v; + sink.out = &v; + interpreter.Execute(); + std::memcpy(&out[size_t(i) * 68], v.position, sizeof(v.position)); + std::memcpy(&out[size_t(i) * 68 + 4], v.interpolators, sizeof(v.interpolators)); + } + *vertex_count = count; + return true; +} + } // namespace render360::xenia_web namespace rx = render360::xenia_web; extern "C" { uint32_t r360_xenos_soft_draws() { return rx::g_draws_rendered; } +// Cumulative host microseconds inside the GPU renderer (wraps; take deltas). +uint32_t r360_xenos_soft_render_us() { return uint32_t(rx::g_render_ns / 1000u); } uint32_t r360_xenos_soft_set_rasterize(uint32_t on) { rx::g_rasterize = on ? 1u : 0u; return rx::g_rasterize; } uint32_t r360_xenos_soft_skipped() { return rx::g_draws_skipped; } uint32_t r360_xenos_soft_resolves() { return rx::g_resolves; } diff --git a/src/xenia_web_bootstrap/xenos_soft_renderer.h b/src/xenia_web_bootstrap/xenos_soft_renderer.h index 470ec868..dbbbec79 100644 --- a/src/xenia_web_bootstrap/xenos_soft_renderer.h +++ b/src/xenia_web_bootstrap/xenos_soft_renderer.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include "xenia/gpu/ucode.h" #include "xenia/gpu/xenos.h" @@ -15,5 +16,10 @@ bool SampleXenosTexture(const xe::gpu::xenos::xe_gpu_texture_fetch_t& fetch, const xe::gpu::ucode::TextureFetchInstruction& instr, const float coords[3], float result[4]); +// Runs the guest vertex shader of `draw` on the CPU (Xenia ShaderInterpreter): +// 68 floats per guest vertex (position, 16 interpolators). Used by the GPU +// backend for primitives the host cannot expand (rectangle lists). +bool ShadeXenosVertices(const XenosSoftDraw& draw, std::vector& out, uint32_t* vertex_count); + } // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp b/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp index a52fed92..e89aa282 100644 --- a/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp +++ b/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp @@ -36,7 +36,7 @@ #include "third_party/glslang/SPIRV/InReadableOrder.cpp" extern "C" { -uint32_t r360_xenos_shader_buffer(uint32_t shader_type); +uintptr_t r360_xenos_shader_buffer(uint32_t shader_type); uint32_t r360_xenos_shader_dwords(uint32_t shader_type); uint32_t r360_xenos_shader_hash(uint32_t shader_type); uint32_t r360_xenos_fetch_constant_word(uint32_t group, uint32_t word); @@ -115,7 +115,7 @@ uint32_t Translate(uint32_t type) { } const uint32_t count = r360_xenos_shader_dwords(type); - const uint32_t ptr = r360_xenos_shader_buffer(type); + const uintptr_t ptr = r360_xenos_shader_buffer(type); if (!count || !ptr) { g_status = kStatusNoShader; return 0; @@ -414,10 +414,10 @@ uint32_t r360_xenos_spirv_translation_count() { uint32_t r360_xenos_spirv_error_count() { return render360::xenia_web::g_error_count; } -uint32_t r360_xenos_spirv_buffer() { +uintptr_t r360_xenos_spirv_buffer() { return render360::xenia_web::g_spirv.empty() ? 0u - : static_cast(reinterpret_cast( + : (reinterpret_cast( render360::xenia_web::g_spirv.data())); } uint32_t r360_xenos_spirv_size() { @@ -443,10 +443,10 @@ uint32_t r360_xenos_frontbuffer_snapshot_status() { return render360::xenia_web::g_frontbuffer_snapshot_status; } R360_WASM_EXPORT("r360_xenos_frontbuffer_snapshot_buffer") -uint32_t r360_xenos_frontbuffer_snapshot_buffer() { +uintptr_t r360_xenos_frontbuffer_snapshot_buffer() { return render360::xenia_web::g_frontbuffer_snapshot.empty() ? 0u - : static_cast(reinterpret_cast( + : (reinterpret_cast( render360::xenia_web::g_frontbuffer_snapshot.data())); } R360_WASM_EXPORT("r360_xenos_frontbuffer_snapshot_size") diff --git a/src/xenia_web_bootstrap/xex_guest_mapper.cpp b/src/xenia_web_bootstrap/xex_guest_mapper.cpp index 0e438931..81d470a8 100644 --- a/src/xenia_web_bootstrap/xex_guest_mapper.cpp +++ b/src/xenia_web_bootstrap/xex_guest_mapper.cpp @@ -276,7 +276,7 @@ uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, : 0u; } uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, - uint32_t source_ptr, uint32_t size) { + uintptr_t source_ptr, uint32_t size) { const void* source = reinterpret_cast(uintptr_t(source_ptr)); return render360::xenia_web::LoadXexGuestSectionData(virtual_address, source, size) @@ -310,8 +310,8 @@ uint32_t r360_xex_guest_mapper_section_count() { uint32_t r360_xex_guest_mapper_mapped_bytes() { return render360::xenia_web::XexGuestMappedBytes(); } -uint32_t r360_xex_guest_mapper_input_buffer() { - return static_cast( +uintptr_t r360_xex_guest_mapper_input_buffer() { + return ( reinterpret_cast(render360::xenia_web::XexGuestInputBuffer())); } uint32_t r360_xex_guest_mapper_input_capacity() { diff --git a/src/xenia_web_bootstrap/xex_guest_mapper.h b/src/xenia_web_bootstrap/xex_guest_mapper.h index 5fd6ec8c..93b133a6 100644 --- a/src/xenia_web_bootstrap/xex_guest_mapper.h +++ b/src/xenia_web_bootstrap/xex_guest_mapper.h @@ -42,7 +42,7 @@ uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, uint32_t virtual_size, uint32_t final_protection); uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, - uint32_t source_ptr, uint32_t size); + uintptr_t source_ptr, uint32_t size); uint32_t r360_xex_guest_mapper_set_entry(uint32_t entry_address); uint32_t r360_xex_guest_mapper_finalize(); uint32_t r360_xex_guest_mapper_patch_u32_be(uint32_t address, uint32_t value); @@ -51,7 +51,7 @@ uint32_t r360_xex_guest_mapper_status(); uint32_t r360_xex_guest_mapper_entry_address(); uint32_t r360_xex_guest_mapper_section_count(); uint32_t r360_xex_guest_mapper_mapped_bytes(); -uint32_t r360_xex_guest_mapper_input_buffer(); +uintptr_t r360_xex_guest_mapper_input_buffer(); uint32_t r360_xex_guest_mapper_input_capacity(); uint32_t r360_xex_guest_mapper_input_max_capacity(); } diff --git a/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp b/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp index 6f25452b..98c7a37b 100644 --- a/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp +++ b/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp @@ -2,7 +2,7 @@ #include #include "xex_image_decoder.h" -extern "C" uint32_t r360_io_ptr(); +extern "C" uintptr_t r360_io_ptr(); extern "C" uint32_t r360_io_capacity(); namespace { diff --git a/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp b/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp index 4c9b1a93..5927dc48 100644 --- a/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp +++ b/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp @@ -2,7 +2,7 @@ #include #include "xex_image_preparer.h" -extern "C" uint32_t r360_io_ptr(); +extern "C" uintptr_t r360_io_ptr(); extern "C" uint32_t r360_io_capacity(); namespace { diff --git a/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp b/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp index e30e78fb..91770589 100644 --- a/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp +++ b/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp @@ -295,7 +295,7 @@ void r360_pe_guest_reset() { } // Supplies the XEX page descriptors for the next r360_pe_guest_load*: count // big-endian-decoded words at words_ptr and the image page size. -uint32_t r360_pe_guest_set_xex_pages(uint32_t words_ptr, uint32_t count, +uint32_t r360_pe_guest_set_xex_pages(uintptr_t words_ptr, uint32_t count, uint32_t page_size) { auto& words = render360::xenia_web::g_xex_page_words; words.clear(); @@ -310,13 +310,13 @@ uint32_t r360_pe_guest_set_xex_pages(uint32_t words_ptr, uint32_t count, render360::xenia_web::g_xex_page_size = page_size; return 1; } -uint32_t r360_pe_guest_load(uint32_t source_ptr, uint32_t length) { +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length) { const auto* source = reinterpret_cast(static_cast(source_ptr)); return render360::xenia_web::LoadPreparedPeImageToGuest(source, length) ? 1u : 0u; } -uint32_t r360_pe_guest_load_at_entry(uint32_t source_ptr, uint32_t length, +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address) { const auto* source = reinterpret_cast(static_cast(source_ptr)); diff --git a/src/xenia_web_bootstrap/xex_pe_guest_loader.h b/src/xenia_web_bootstrap/xex_pe_guest_loader.h index af29ab83..0863331b 100644 --- a/src/xenia_web_bootstrap/xex_pe_guest_loader.h +++ b/src/xenia_web_bootstrap/xex_pe_guest_loader.h @@ -35,8 +35,8 @@ bool PreparedPeGuestFindRuntimeFunction(uint32_t address, uint32_t* begin, extern "C" { void r360_pe_guest_reset(); -uint32_t r360_pe_guest_load(uint32_t source_ptr, uint32_t length); -uint32_t r360_pe_guest_load_at_entry(uint32_t source_ptr, uint32_t length, +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length); +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address); uint32_t r360_pe_guest_status(); uint32_t r360_pe_guest_entry_address(); diff --git a/src/xenia_web_bootstrap/xex_title_handoff.cpp b/src/xenia_web_bootstrap/xex_title_handoff.cpp index ee3ff180..9e0c8850 100644 --- a/src/xenia_web_bootstrap/xex_title_handoff.cpp +++ b/src/xenia_web_bootstrap/xex_title_handoff.cpp @@ -7,7 +7,7 @@ extern "C" { void r360_ppc_probe_reset(); -uint32_t r360_ppc_probe_input_buffer(); +uintptr_t r360_ppc_probe_input_buffer(); uint32_t r360_ppc_probe_input_capacity(); uint32_t r360_ppc_probe_load_at(uint32_t address, const uint8_t* bytes, uint32_t length); @@ -53,7 +53,7 @@ uint32_t TranslatePreparedPeEntry(uint32_t byte_count) { } const uint32_t entry = PreparedPeGuestEntryAddress(); - const uint32_t input_ptr = r360_ppc_probe_input_buffer(); + const uintptr_t input_ptr = r360_ppc_probe_input_buffer(); auto* input = reinterpret_cast(static_cast(input_ptr)); if (!input || !ReadSparseGuestMemory(entry, input, byte_count)) { g_status = kPreparedEntryHandoffReadFailed; diff --git a/test-guest-jit-differential.mjs b/test-guest-jit-differential.mjs index d231ee22..1cd6c209 100644 --- a/test-guest-jit-differential.mjs +++ b/test-guest-jit-differential.mjs @@ -6,6 +6,7 @@ // // Usage: node test-guest-jit-differential.mjs [bootstrap.wasm] [iterations] // Requires powerpc64-linux-gnu-{as,ld} (apt: binutils-powerpc64-linux-gnu). +import './test-node-wasi-safe.mjs'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/test-guest-jit-osr.mjs b/test-guest-jit-osr.mjs new file mode 100644 index 00000000..3e60a212 --- /dev/null +++ b/test-guest-jit-osr.mjs @@ -0,0 +1,98 @@ +// On-stack replacement test for the guest JIT (hir_wasm_jit.h JitOsrFunction): +// a guest function called once that runs a long loop starts interpreted (it +// has not reached the call-count threshold) and must continue in compiled +// code at a block head with exactly the interpreter's results. +// +// Usage: node test-guest-jit-osr.mjs [bootstrap.wasm] +// Requires powerpc64-linux-gnu-{as,ld} (apt: binutils-powerpc64-linux-gnu). +import './test-node-wasi-safe.mjs'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {execFileSync} from 'node:child_process'; +import {WASI} from 'node:wasi'; +import {installGuestJit} from './render360-guest-jit.mjs'; + + +const wasmPath=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const BASE=0x82010000; + +// t0 calls loop once through the translation cache (a nested call, so its run +// has a JIT slot). loop mixes add, rotate, xor and a data-dependent branch +// for r5 iterations (several thousand HIR instructions per call). +const asm=` +t0: + mflr 12 + bl loop + mtlr 12 + blr +loop: + li 3, 0 + mtctr 5 +1: + add 3, 3, 4 + rotlwi 3, 3, 3 + xor 3, 3, 5 + andi. 6, 4, 1 + beq 2f + addi 3, 3, 7 +2: + addi 4, 4, 1 + bdnz 1b + blr +`; +const work=fs.mkdtempSync(path.join(os.tmpdir(),'r360-jit-osr-')); +const source=path.join(work,'osr.s'),obj=path.join(work,'osr.o'),bin=path.join(work,'osr.bin'); +fs.writeFileSync(source,asm); +execFileSync('powerpc64-linux-gnu-as',['-a32','-be','-mregnames','-R','-o',obj,source]); +execFileSync('powerpc64-linux-gnu-ld',['-melf32ppc','-EB','-nostdlib','--oformat=binary',`-Ttext=0x${BASE.toString(16)}`,`-e0x${BASE.toString(16)}`,'-o',bin,obj]); +const code=fs.readFileSync(bin); +fs.rmSync(work,{recursive:true,force:true}); + +const module=await WebAssembly.compile(fs.readFileSync(wasmPath)); +async function instantiate(jit){ + const wasi=new WASI({version:'preview1',args:[],env:{},preopens:{},returnOnExit:true}); + const imports=wasi.getImportObject(module); + imports.env||={};imports.env.emscripten_notify_memory_growth=()=>{}; + const instance=await WebAssembly.instantiate(module,imports); + wasi.initialize(instance); + // Mode 1: compile by call count, as in titles (mode 2 compiles every run). + if(jit&&!installGuestJit({exports:instance.exports},{mode:1}))throw new Error('guest JIT unavailable'); + return instance.exports; +} + +function run(e,r4,r5){ + const cstr=(off,text)=>{const b=new TextEncoder().encode(`${text}\0`);const p=e.r360_ppc_probe_input_buffer()+off;new Uint8Array(e.memory.buffer,p,b.length).set(b);return p;}; + e.r360_ppc_probe_reset(); + const buffer=e.r360_ppc_probe_input_buffer(); + new Uint8Array(e.memory.buffer,buffer,code.length).set(code); + if((e.r360_ppc_probe_load_at(BASE,buffer,code.length)>>>0)!==code.length)throw new Error('code load failed'); + e.r360_ppc_probe_set_execute_on_translate(1); + e.r360_ppc_probe_set_initial_lr(0xBCBCBCBCn); + e.r360_ppc_probe_set_initial_register(cstr(0,'r4'),cstr(64,String(r4))); + e.r360_ppc_probe_set_initial_register(cstr(0,'r5'),cstr(64,String(r5))); + const hir=e.r360_ppc_probe_translate_scanned_at(BASE)>>>0; + if(!hir||(e.r360_ppc_probe_correctness_status()>>>0)!==3)return 'did-not-return'; + const out=[]; + for(const reg of ['r3','r4','r6']){ + e.r360_ppc_probe_compare_register(cstr(0,reg),cstr(64,'0')); + const p=e.r360_ppc_probe_register_actual()>>>0,m=new Uint8Array(e.memory.buffer);let s=''; + for(let i=p;m[i];i++)s+=String.fromCharCode(m[i]); + out.push(`${reg}=${s}`); + } + return out.join(' '); +} + +const interp=await instantiate(false),jit=await instantiate(true); +const failures=[]; +let cases=0; +for(const [r4,r5] of [[1,600],[12345,1000],[0x7FFFFFF0,2500],[3,4000]]){ + const a=run(interp,r4,r5),b=run(jit,r4,r5); + cases++; + if(a!==b||a==='did-not-return')failures.push(`r4=${r4} r5=${r5}\n executor: ${a}\n jit: ${b}`); +} +const osr=jit.r360_jit_osr_entries?jit.r360_jit_osr_entries()>>>0:0; +console.log(`guest JIT OSR: ${cases} cases, ${failures.length} mismatching, ${osr} OSR entries`); +for(const f of failures)console.log(`FAIL ${f}`); +if(failures.length||!osr)process.exit(1); +console.log('GUEST_JIT_OSR_PASS'); diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index 616c8e1c..de6029ed 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -318,6 +318,87 @@ expect(k('NtWaitForSingleObjectEx',sys,1,0,P+0x8F0)===0x102,'drained listener sh const second=x('XamNotifyCreateListener',0x1,10);expect(x('XNotifyGetNext',second,0,P+0x900,P+0x904)===0&&r32(P+0x900)===0,'startup notifications must only go to the first system listener'); console.log('XAM_NOTIFY_LISTENER_XENIA=PASS'); +// --- XamShowMessageBoxUI (Xenia xam_ui.cc headless: focused button) -------------- +utf16(P+0xA00,'Title');utf16(P+0xA40,'Continue?');utf16(P+0xA80,'Yes');utf16(P+0xA90,'No'); +w32(P+0xAA0,P+0xA80);w32(P+0xAA4,P+0xA90);w32(P+0xAB0,0xFFFFFFFF); +w32(P+0xF000+0x54,0); // ninth argument (overlapped) on the caller's stack +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,1,0,P+0xAB0)===0&&status()===1,'synchronous XamShowMessageBoxUI should succeed'); +expect(r32(P+0xAB0)===1,`message box should report the focused button, got ${r32(P+0xAB0)}`); +const uiSeen=[];while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1)uiSeen.push(`${r32(P+0x900).toString(16)}:${r32(P+0x904)}`); +expect(JSON.stringify(uiSeen)===JSON.stringify(['9:1','9:0']),`message box should bracket XN_SYS_UI, got ${uiSeen}`); +w32(P+0xAB0,0xFFFFFFFF);for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0);w32(P+0xAC0,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===997&&status()===1,'overlapped XamShowMessageBoxUI should return ERROR_IO_PENDING'); +expect(r32(P+0xAB0)===0&&r32(P+0xAC0)===0,'overlapped message box should complete with the focused button and success'); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +w32(P+0xF000+0x54,0); +console.log('XAM_MESSAGE_BOX_XENIA=PASS'); + +// Host dialog mode: the player answers (Xenia MessageBoxDialog). +expect((need('r360_xam_dialog_set_host_answers')(1)>>>0)===1,'host dialog mode not enabled'); +const dlgStr=w=>Buffer.from(new Uint8Array(e.memory.buffer,need('r360_xam_dialog_string_ptr')(w)>>>0,need('r360_xam_dialog_string_len')(w)>>>0)).toString('utf8'); +for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0);w32(P+0xAB0,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===997&&r32(P+0xAC0)===997,'overlapped host dialog should stay pending'); +expect((need('r360_xam_dialog_pending')()>>>0)===1&&dlgStr(0)==='Title'&&dlgStr(1)==='Continue?'&&dlgStr(3)==='No'&&(need('r360_xam_dialog_button_count')()>>>0)===2,'pending dialog not exposed to the host'); +expect(r32(P+0xAB0)===0xFFFFFFFF,'unanswered dialog must not write a result'); +expect((need('r360_xam_dialog_answer')(5)>>>0)===0,'out-of-range answer must be rejected'); +expect((need('r360_xam_dialog_answer')(1)>>>0)===1&&r32(P+0xAB0)===1&&r32(P+0xAC0)===0&&(need('r360_xam_dialog_pending')()>>>0)===0,'answer should complete the overlapped dialog with the chosen button'); +w32(P+0xF000+0x54,0);w32(P+0xAB0,0xFFFFFFFF); +x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0); +expect(status()===5&&r32(P+0xAB0)===0xFFFFFFFF,'synchronous host dialog should block until answered'); +x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0); +expect(status()===5,'retry before the answer should still block'); +expect((need('r360_xam_dialog_answer')(1)>>>0)===1,'answer to synchronous dialog rejected'); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===0&&status()===1&&r32(P+0xAB0)===1,'retry after the answer should return the chosen button'); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +need('r360_xam_dialog_set_host_answers')(0); +console.log('XAM_MESSAGE_BOX_HOST_DIALOG=PASS'); +expect((need('r360_xam_dialog_set_auto_answer')(1)|0)===1,'preset answer not set'); +w32(P+0xAB0,0xFFFFFFFF);w32(P+0xF000+0x54,0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===0&&status()===1&&r32(P+0xAB0)===1,'preset answer should complete the dialog inside the call'); +need('r360_xam_dialog_set_auto_answer')(-1); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +console.log('XAM_MESSAGE_BOX_PRESET_ANSWER=PASS'); + +// --- XamUserCreateAchievementEnumerator (Xenia XStaticAchievementEnumerator) ------ +expect(x('XamUserCreateAchievementEnumerator',0,0,0,7,0,4,P+0xB00,P+0xB04)===0&&status()===1,'achievement enumerator not created'); +expect(r32(P+0xB00)===(36+464)*4,`achievement buffer size ${r32(P+0xB00)}`); +expect(x('XamUserCreateAchievementEnumerator',0,4,0,7,0,4,P+0xB00,P+0xB04)===0x57,'bad user index must be rejected'); +w32(P+0xB08,0xFFFFFFFF); +expect(x('XamEnumerate',r32(P+0xB04),0,P+0xC000,(36+464)*4,P+0xB08,0)===0x12&&r32(P+0xB08)===0,'title without an XDBF achievement table should enumerate nothing'); +console.log('XAM_ACHIEVEMENT_ENUMERATOR_XENIA=PASS'); + +// --- XexGetProcedureAddress (Xenia KernelModule::GetProcAddressByOrdinal) ------- +ascii(P+0xB40,'xam.xex'); +expect(k('XexGetModuleHandle',P+0xB40,P+0xB60)===0&&r32(P+0xB60)!==0,'xam.xex module handle missing'); +const xamModule=r32(P+0xB60); +expect(k('XexGetProcedureAddress',xamModule,0x279,P+0xB64)===0&&status()===1&&r32(P+0xB64)!==0,'XAM export trampoline not created'); +const trampoline=r32(P+0xB64); +expect(k('XexGetProcedureAddress',xamModule,0x279,P+0xB68)===0&&r32(P+0xB68)===trampoline,'repeated lookup should return the same trampoline'); +expect(k('XexGetProcedureAddress',xamModule,0x2CA,P+0xB68)===0&&r32(P+0xB68)!==trampoline,'another ordinal should get its own trampoline'); +expect(k('XexGetProcedureAddress',0x12345678,0x279,P+0xB68)===0xC0000008,'bad module handle must be rejected'); +ascii(P+0xB80,'XamSomething'); +expect(k('XexGetProcedureAddress',xamModule,P+0xB80,P+0xB68)===0xC0000263&&r32(P+0xB68)===0,'lookup by name should report the entry point as not found'); +console.log('XEX_GET_PROCEDURE_ADDRESS_XENIA=PASS'); + +// --- XamContentAggregateCreateEnumerator (Xenia xam_content_aggregate.cc) --------- +expect(x('XamContentAggregateCreateEnumerator',0,0,1,0,P+0xBA0)===0&&status()===1,'aggregate content enumerator not created'); +expect(x('XamContentAggregateCreateEnumerator',0,99,1,0,P+0xBA4)===0x80070057,'unknown device must be rejected'); +w32(P+0xBA8,0xFFFFFFFF); +expect(x('XamEnumerate',r32(P+0xBA0),0,P+0xC000,0x148,P+0xBA8,0)===0x12&&r32(P+0xBA8)===0,'no saved content should enumerate nothing'); +expect(x('XamGetPrivateEnumStructureFromHandle',r32(P+0xBA0),P+0xBAC)===0&&status()===1,'private enum structure lookup failed'); +const enumObject=r32(P+0xBAC); +expect(r32(enumObject)===0xFE&&r32(enumObject+4)===0x2000E&&r32(enumObject+8)===0x20010&&r32(enumObject+0xC)===0xFF&&r32(enumObject+0x10)===1,'X_KENUMERATOR header mismatch'); +expect(r32(enumObject+0x18)===0x58454E00&&r32(enumObject+0x1C)===r32(P+0xBA0),'aggregate extra block should hold the XEN signature and handle'); +expect(x('XamGetPrivateEnumStructureFromHandle',0x12345678,P+0xBAC)===0xC0000008,'bad enumerator handle must be rejected'); +console.log('XAM_CONTENT_AGGREGATE_XENIA=PASS'); + +// --- XamTaskSchedule (Xenia xam_task.cc: the callback runs on a new thread) ------- +w32(P+0xC14,0); +expect(x('XamTaskSchedule',0x82400000,P+0xC00,0,P+0xC14)===0&&status()===1&&r32(P+0xC14)===12345,'XamTaskSchedule should start the task thread and report handle 12345'); +expect(x('XamTaskSchedule',0,P+0xC00,0,P+0xC14)===0xC000000D,'a task without a callback must be rejected'); +expect(x('XamTaskShouldExit',0)===0,'XamTaskShouldExit mismatch'); +console.log('XAM_TASK_SCHEDULE_XENIA=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; diff --git a/test-node-wasi-safe.mjs b/test-node-wasi-safe.mjs new file mode 100644 index 00000000..2456aa3f --- /dev/null +++ b/test-node-wasi-safe.mjs @@ -0,0 +1,10 @@ +// Import first in tests that run the bootstrap under node:wasi. +// +// Node 22's WASI fd_write fast-API callback allocates (uvwasi) and reports +// external memory to V8, which can start a garbage collection inside the fast +// call; V8 then crashes walking an optimized frame (SIGSEGV in +// InnerPointerToCodeCache::GetCacheEntry). Guest stderr output under heap +// pressure triggers it. Fast API calls off keeps WASI calls on the regular +// path, where GC is allowed. +import v8 from 'node:v8'; +v8.setFlagsFromString('--no-turbo-fast-api-calls'); diff --git a/test-perf-overlay.mjs b/test-perf-overlay.mjs new file mode 100644 index 00000000..5a957d32 --- /dev/null +++ b/test-perf-overlay.mjs @@ -0,0 +1,82 @@ +// Unit test for the FPS / frame-time overlay statistics (render360-perf-overlay.mjs). +import {PerfStats, formatPerf} from './render360-perf-overlay.mjs'; + +const expect = (cond, message) => { if (!cond) throw new Error(message); }; +const near = (a, b, tol) => Math.abs(a - b) <= tol; + +const stats = new PerfStats(); +let t = 0, submitted = 0; +stats.submitted(t, submitted); +// 10 s at 30 FPS presented, 60 frames/s submitted; one 200 ms hitch at 5 s. +for (let frame = 0; frame < 300; ++frame) { + t += frame === 150 ? 200 : 1000 / 30; + submitted += 2; + stats.submitted(t, submitted); + stats.framePresented(t); + // Each 33 ms frame: 20 ms inside the emulator, 5 of them in the GPU + // renderer, plus 3 ms presenting -> CPU 15 ms, GPU 8 ms. + stats.slice(t, 20, 5, 3); +} +const s = stats.snapshot(t); +expect(near(s.fps, 30, 1), `current FPS ${s.fps}`); +expect(near(s.averageFps, 30, 2), `average FPS ${s.averageFps}`); +expect(near(s.frameMs, 1000 / 30, 1), `frame time ${s.frameMs}`); +// Slowest 1% of 299 intervals = 3 frames: the 200 ms hitch and two 33 ms ones. +expect(near(s.low1Fps, 3000 / (200 + 2000 / 30), 0.2), `1% low should reveal the 200 ms hitch, got ${s.low1Fps}`); +expect(near(s.cpuMsPerSecond, 15 * 30, 20) && near(s.gpuMsPerSecond, 8 * 30, 20), + `CPU/GPU split ${s.cpuMsPerSecond}/${s.gpuMsPerSecond}`); +expect(s.bottleneck === 'CPU emulation', `bottleneck ${s.bottleneck}`); +expect(near(s.submittedPerSecond, 60, 2) && near(s.presentedPerSecond, 30, 1), + `submitted/presented ${s.submittedPerSecond}/${s.presentedPerSecond}`); +expect(s.totalSubmitted === 600 && s.totalPresented === 300, 'totals'); +const text = formatPerf(s); +for (const label of ['FPS', 'avg', '1% low', 'Frame time', 'CPU emulation', 'GPU rendering', 'submitted', 'presented']) { + expect(text.includes(label), `overlay text missing ${label}`); +} + +// Window: older than 60 s drops out of the average. +const w = new PerfStats({windowMs: 60000}); +for (let i = 0; i <= 600; ++i) w.framePresented(i * 100); // 10 FPS for 60 s +for (let i = 1; i <= 600; ++i) w.framePresented(60000 + i * 50); // then 20 FPS for 30 s +expect(near(w.snapshot(90000).averageFps, 15, 1.5), `windowed average ${w.snapshot(90000).averageFps}`); + +console.log(text); +// 30 FPS bar on guest frames. 60 s at 30 guest FPS with 20% idle, 2% of +// instructions interpreted: passes. One 80 ms hitch per 10 s: fails stutter. +{ + const run = (hitchEvery) => { + const b = new PerfStats(); + let t = 0, swaps = 0, instr = 0, interp = 0, idle = 0; + b.submitted(t, swaps); + b.counters(t, instr, interp, idle); + for (let frame = 1; frame <= 1800; ++frame) { + t += hitchEvery && frame % hitchEvery === 0 ? 80 : 1000 / 30; + b.submitted(t, ++swaps); + instr += 20e6; interp += 0.4e6; idle += (1000 / 30) * 0.2; + b.counters(t, instr, interp, idle); + b.slice(t, 20, 4, 1); + b.gpuFrame(t, 6); + b.record(t); + } + return b; + }; + const good = run(0), gs = good.snapshot(1800 * 1000 / 30); + expect(near(gs.gameFps, 30, 1) && near(gs.gameAverageFps, 30, 0.5), `game FPS ${gs.gameFps}/${gs.gameAverageFps}`); + expect(near(gs.interpretedPercent, 2, 0.01), `interpreted ${gs.interpretedPercent}`); + expect(near(gs.idlePercent, 20, 0.5) && near(gs.emulationSpeedPercent, 125, 1), `speed ${gs.emulationSpeedPercent} idle ${gs.idlePercent}`); + expect(near(gs.mips, 600, 5), `MIPS ${gs.mips}`); + expect(near(gs.gpuMsPerFrame, 6, 0.01) && near(gs.cpuMsPerGuestFrame, 16, 1), `ms/frame ${gs.cpuMsPerGuestFrame}/${gs.gpuMsPerFrame}`); + expect(gs.bar.pass && gs.stuttersPerMinute === 0, `bar should pass: ${JSON.stringify(gs.bar)}`); + expect(good.log.length >= 59 && good.exportLog({cores: 8}).records.length === good.log.length, 'log records'); + expect(formatPerf(gs).includes('30 FPS bar: PASS'), 'overlay verdict'); + const hitchy = run(300).snapshot(1800 * 1000 / 30); + expect(!hitchy.bar.pass && !hitchy.bar.stutter && near(hitchy.stuttersPerMinute, 6, 0.6), `stutters ${hitchy.stuttersPerMinute}`); + // No idle time and 20 guest FPS: speed is 20/30, bar not met. + const slow = new PerfStats(); + let t = 0; + slow.submitted(0, 0); slow.counters(0, 0, 0, 0); + for (let f = 1; f <= 600; ++f) { t += 50; slow.submitted(t, f); slow.counters(t, f * 1e7, 0, 0); } + const ss = slow.snapshot(t); + expect(near(ss.emulationSpeedPercent, 66.7, 1) && !ss.bar.pass && !ss.bar.average, `slow ${ss.emulationSpeedPercent}`); +} +console.log('PERF_OVERLAY_STATS=PASS'); diff --git a/test-webgpu-replay-capture-browser.mjs b/test-webgpu-replay-capture-browser.mjs new file mode 100644 index 00000000..20896eb0 --- /dev/null +++ b/test-webgpu-replay-capture-browser.mjs @@ -0,0 +1,19 @@ +// Replays a local GPU capture (run-title.mjs --gpu-capture M:SWAPS:FILE) in +// headless Chromium WebGPU (tests/browser/webgpu-replay-capture.mjs). +// Captures hold game data: they stay outside the repository and the test +// skips without one. +// node test-webgpu-replay-capture-browser.mjs /path/to/capture.bin [out.png] +import fs from 'node:fs'; +import path from 'node:path'; +import {runBrowserTest} from './tools/browser-test.mjs'; + +const capture=process.argv[2]||process.env.R360_GPU_CAPTURE; +if(!capture||!fs.existsSync(capture)){console.log('WEBGPU_REPLAY_CAPTURE_SKIP (no local capture)');process.exit(0);} +const dir=path.dirname(path.resolve(capture)),name=path.basename(capture); +const reference=fs.existsSync(`${capture}.png`)?`/__data__/${name}.png`:null; +const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference,process.env.R360_DRAW_LIMIT?Number(process.env.R360_DRAW_LIMIT):null,!!process.env.R360_DEBUG_EDRAM],dataRoot:dir, + onConsole:t=>process.env.VERBOSE&&console.log(t)}); +if(result.png){if(process.argv[3])fs.writeFileSync(process.argv[3],Buffer.from(result.png,'base64'));delete result.png;} +console.log(JSON.stringify(result,null,1)); +if(!result.ok)process.exit(1); +console.log('WEBGPU_REPLAY_CAPTURE_PASS'); diff --git a/test-webgpu-shared-memory-browser.mjs b/test-webgpu-shared-memory-browser.mjs new file mode 100644 index 00000000..8aa9b8a3 --- /dev/null +++ b/test-webgpu-shared-memory-browser.mjs @@ -0,0 +1,11 @@ +// WebGPU shared memory end to end in headless Chromium (SwiftShader): uploads +// the core records are replayed into the GPU buffer, which then matches guest +// memory (tests/browser/webgpu-shared-memory.mjs). +import {runBrowserTest} from './tools/browser-test.mjs'; + +const wasm=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const result=await runBrowserTest('tests/browser/webgpu-shared-memory.mjs',{args:[`/${wasm}`],onConsole:t=>process.env.VERBOSE&&console.log(t)}); +console.log(JSON.stringify(result)); +if(!result.ok)process.exit(1); +if(result.secondUploads!==1){console.log('expected exactly one page re-uploaded after the CPU write');process.exit(1);} +console.log('WEBGPU_SHARED_MEMORY_BROWSER_PASS'); diff --git a/test-webgpu-shared-memory.mjs b/test-webgpu-shared-memory.mjs new file mode 100644 index 00000000..66460dae --- /dev/null +++ b/test-webgpu-shared-memory.mjs @@ -0,0 +1,71 @@ +// WebGPU backend shared memory (src/xenia_web_bootstrap/webgpu_backend.cpp, a +// port of Xenia's SharedMemory): a requested range uploads exactly the pages +// that are not valid on the GPU, CPU writes invalidate pages through the +// sparse memory GPU watch, and GPU-written ranges need no upload. +import './test-node-wasi-safe.mjs'; +import fs from 'node:fs'; +import {WASI} from 'node:wasi'; + +const wasmPath=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const wasi=new WASI({version:'preview1',args:[],env:{},preopens:{},returnOnExit:true}); +const module=await WebAssembly.compile(fs.readFileSync(wasmPath)); +const imports=wasi.getImportObject(module); +imports.env||={};imports.env.emscripten_notify_memory_growth=()=>{}; +const instance=await WebAssembly.instantiate(module,imports); +wasi.initialize(instance); +const e=instance.exports; + +const expect=(cond,message)=>{if(!cond)throw new Error(message);}; +const PAGE=4096,BASE=0x00100000; // physical == virtual outside kernel physical ranges +e.r360_sparse_guest_memory_reset(); +const backing=e.r360_sparse_guest_memory_alloc(4); +expect(backing&&e.r360_sparse_guest_memory_map(BASE,4,backing,0,3),'map 4 pages'); +for(let p=0;p<4;p++)expect(e.r360_sparse_guest_memory_write_u32_be(BASE+p*PAGE,0x11110000+p),'write'); +e.r360_gpu_shared_memory_clear(); + +// Stream: [op | words << 8] payload; upload payload = dest, length, bytes. +function uploads(){ + const words=e.r360_gpu_stream_words()>>>0,ptr=e.r360_gpu_stream_data()>>>0; + const w=new Uint32Array(e.memory.buffer,ptr,words),out=[]; + for(let i=0;i>>8; + if(op===1){ + const dest=w[i+1],length=w[i+2]; + const bytes=new Uint8Array(e.memory.buffer,ptr+(i+3)*4,length); + const firstWords=[];for(let p=0;p>>0); + out.push({dest,length,firstWords}); + } + i+=1+n; + } + e.r360_gpu_stream_reset(); + return out; +} + +expect(e.r360_gpu_shared_memory_request(BASE,4*PAGE)===1,'request'); +let u=uploads(); +expect(u.length===1&&u[0].dest===BASE&&u[0].length===4*PAGE,`first request uploads the range once: ${JSON.stringify(u)}`); +expect(u[0].firstWords.join()===[0x11110000,0x11110001,0x11110002,0x11110003].join(),'uploaded bytes'); + +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +expect(uploads().length===0,'valid pages are not uploaded again'); + +e.r360_sparse_guest_memory_write_u32_be(BASE+2*PAGE+8,0xABCDEF01); +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +u=uploads(); +expect(u.length===1&&u[0].dest===BASE+2*PAGE&&u[0].length===PAGE,`a CPU write reuploads only its page: ${JSON.stringify(u)}`); + +e.r360_sparse_guest_memory_write_u32_be(BASE+3*PAGE,0x22222222); +e.r360_gpu_shared_memory_written_by_gpu(BASE+3*PAGE,PAGE); +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +expect(uploads().length===0,'a GPU-written range needs no upload'); + +e.r360_sparse_guest_memory_write_u32_be(BASE,0x33333333); +e.r360_sparse_guest_memory_write_u32_be(BASE+PAGE,0x44444444); +e.r360_gpu_shared_memory_request(BASE+16,PAGE); // spans pages 0 and 1 +u=uploads(); +expect(u.length===1&&u[0].dest===BASE&&u[0].length===2*PAGE&&u[0].firstWords.join()===[0x33333333,0x44444444].join(), + `dirty neighbours upload as one range: ${JSON.stringify(u)}`); + +expect(e.r360_gpu_shared_memory_request(0x1FFFF000,0x2000)===0,'ranges past 512 MiB are refused'); +console.log(`uploaded ${e.r360_gpu_shared_memory_uploaded_kb()} KiB in ${e.r360_gpu_shared_memory_upload_ranges()} ranges`); +console.log('WEBGPU_SHARED_MEMORY_PASS'); diff --git a/test-xenia-ppc-instruction-suite.mjs b/test-xenia-ppc-instruction-suite.mjs index 342a70de..8f0f90d9 100644 --- a/test-xenia-ppc-instruction-suite.mjs +++ b/test-xenia-ppc-instruction-suite.mjs @@ -10,6 +10,7 @@ // // Not covered here: VMX128 files stock binutils cannot assemble (Xenia uses a // patched binutils for those) and the MEMORY_IN/OUT store tests. +import './test-node-wasi-safe.mjs'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/test-xenos-predication.mjs b/test-xenos-predication.mjs new file mode 100644 index 00000000..3550e95c --- /dev/null +++ b/test-xenos-predication.mjs @@ -0,0 +1,58 @@ +// Regression: PM4 type-3 predication (Xenia CommandProcessor::ExecutePacketType3). +// A type-3 packet with header bit 0 set runs only when (bin_select & bin_mask) +// is non-zero, and a predicated XE_SWAP never runs. D3D predicated tiling +// replays one IB per screen bin; without this check every bin-specific packet +// (including D3D's GPU-to-CPU callback requests) ran once per bin. +// +// Usage: node test-xenos-predication.mjs [bootstrap.wasm] +import fs from 'node:fs'; +import { WASI } from 'node:wasi'; + +const wasmPath = process.argv[2] || 'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const module = await WebAssembly.compile(fs.readFileSync(wasmPath)); +const wasi = new WASI({ version: 'preview1', args: [], env: {}, preopens: {}, returnOnExit: true }); +const imports = wasi.getImportObject(module); +imports.env ||= {}; +imports.env.emscripten_notify_memory_growth = () => {}; +const instance = await WebAssembly.instantiate(module, imports); +wasi.initialize(instance); +const e = instance.exports; +const f = (name) => { + const fn = e[name] ?? e[`_${name}`]; + if (typeof fn !== 'function') throw new Error(`missing export ${name}`); + return fn; +}; + +const type3 = (opcode, count, predicated = false) => + ((3 << 30) | ((count - 1) << 16) | (opcode << 8) | (predicated ? 1 : 0)) >>> 0; +const kSetConstant = 0x2D, kSetBinMaskLo = 0x60, kSetBinSelectLo = 0x62, kXeSwap = 0x64; +const setConstant = (register, value, predicated) => + [type3(kSetConstant, 2, predicated), (4 << 16) | (register - 0x2000), value]; + +f('r360_xenos_reset')(); +const words = [ + type3(kSetBinMaskLo, 1), 0x1, + type3(kSetBinSelectLo, 1), 0x2, // selected bin not in mask + ...setConstant(0x2010, 0xAAAA, true), // skipped + ...setConstant(0x2011, 0xBBBB, false), // not predicated: runs + type3(kSetBinSelectLo, 1), 0x1, // selected bin in mask + ...setConstant(0x2012, 0xCCCC, true), // runs + type3(kXeSwap, 4, true), 0x50415753, 0x00123000, 1280, 720, // predicated swap: skipped +]; +const ring = new Uint32Array(e.memory.buffer, f('r360_xenos_ring_buffer')() >>> 0, words.length); +ring.set(words); +if (!(f('r360_xenos_submit')(words.length) >>> 0)) { + throw new Error(`submit failed status=${f('r360_xenos_status')() >>> 0}`); +} +const reg = (r) => f('r360_xenos_register')(r) >>> 0; +const checks = { + 'predicated packet with no matching bin is skipped': reg(0x2010) === 0, + 'unpredicated packet runs': reg(0x2011) === 0xBBBB, + 'predicated packet with a matching bin runs': reg(0x2012) === 0xCCCC, + 'predicated XE_SWAP is skipped': (f('r360_xenos_swaps')() >>> 0) === 0, +}; +for (const [name, ok] of Object.entries(checks)) { + if (!ok) throw new Error(`${name}: failed (0x2010=0x${reg(0x2010).toString(16)} 0x2011=0x${reg(0x2011).toString(16)} 0x2012=0x${reg(0x2012).toString(16)} swaps=${f('r360_xenos_swaps')() >>> 0})`); + console.log(`ok: ${name}`); +} +console.log('XENOS_PREDICATION_PASS'); diff --git a/tests/browser/webgpu-replay-capture.mjs b/tests/browser/webgpu-replay-capture.mjs new file mode 100644 index 00000000..17e3e724 --- /dev/null +++ b/tests/browser/webgpu-replay-capture.mjs @@ -0,0 +1,95 @@ +// Browser side of test-webgpu-replay-capture-browser.mjs: replays a GPU +// command stream captured by run-title.mjs --gpu-capture (served from the +// local data root, never the repository) and compares the color render +// target at EDRAM base 0 with the software renderer's frame. +import {XenosWebGpuBackend} from '../../render360-webgpu-backend.mjs'; + +async function decodePng(url){ + const bitmap=await createImageBitmap(await (await fetch(url)).blob()); + const canvas=new OffscreenCanvas(bitmap.width,bitmap.height),ctx=canvas.getContext('2d'); + ctx.drawImage(bitmap,0,0); + return {width:bitmap.width,height:bitmap.height,pixels:ctx.getImageData(0,0,bitmap.width,bitmap.height).data}; +} + +async function readBuffer(device,buffer,offset,size){ + const read=device.createBuffer({size,usage:0x1|0x8}); + const e=device.createCommandEncoder();e.copyBufferToBuffer(buffer,offset,read,0,size);device.queue.submit([e.finish()]); + await read.mapAsync(1);const out=new Uint8Array(read.getMappedRange()).slice();read.unmap();read.destroy();return out; +} + +export default async function run(captureUrl,referenceUrl,drawLimit,debugEdram){ + const adapter=await navigator.gpu?.requestAdapter(); + if(!adapter)return {ok:false,error:'no WebGPU adapter'}; + const device=await adapter.requestDevice({requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)),requiredLimits:{ + maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); + const errors=[]; + device.onuncapturederror=e=>{if(errors.length<20)errors.push(e.error.message.slice(0,400));}; + const backend=await new XenosWebGpuBackend(device,null).init(); + if(drawLimit!==undefined&&drawLimit!==null)backend.drawLimit=drawLimit; + backend.debugEdram=!!debugEdram; + const words=new Uint32Array(await (await fetch(captureUrl)).arrayBuffer()); + const started=performance.now(); + backend.replayWords(words); + backend.submit(); + await device.queue.onSubmittedWorkDone(); + const replayMs=performance.now()-started; + const shaderErrors=[...backend.shaders.values()].filter(s=>s.error).map(s=>`${s.id}: ${s.error.slice(0,300)}`).slice(0,5); + const pipelineErrors=[...backend.pipelines.entries()].filter(([,p])=>p.error).map(([id,p])=>`${id}: ${p.error.slice(0,300)}`).slice(0,5); + const loadShaderErrors=[...backend.loadShaders.entries()].filter(([,l])=>l.error).map(([i,l])=>`${i}: ${l.error.slice(0,300)}`).slice(0,5); + const result={ok:true,stats:backend.stats,loadShaderErrors,replayMs:Math.round(replayMs),shaderErrors,pipelineErrors,errors, + targets:[...backend.targets.values()].map(t=>`${t.key} ${t.format} ${t.width}x${t.height}`)}; + // The swapped front buffer (resolved into shared memory, loaded by the + // texture cache), else the color render target at EDRAM base 0. + // Debug: the EDRAM buffer against the color render target at base 0 + // (Xenia's layout, 32bpp), at X shifts, to locate resolve offsets. + if(globalThis.location?.search?.includes('edram')||backend.debugEdram){ + const rt=[...backend.targets.values()].find(t=>!t.depth&&t.base===0); + const img=await backend.readTarget(rt); + const ed=new Uint32Array((await readBuffer(device,backend.edram,0,backend.edram.size)).buffer); + const sx=rt.msaa>=2?2:1,sy=rt.msaa>=1?2:1,scores={}; + for(const shift of [-64,-32,0,32,64]){ + let same=0,n=0; + for(let y=0;y>>0)===(v>>>0))same++; + } + scores[shift]=+(same/n).toFixed(3); + } + result.edramMatchByShift=scores; + } + const front=(backend.frontTexture?.format==='rgba8unorm'?backend.frontTexture:null)|| + [...backend.targets.values()].find(t=>!t.depth&&t.base===0&&t.format==='rgba8unorm'); + result.front=front===backend.frontTexture?'front buffer':'render target'; + if(front&&referenceUrl){ + const got=await backend.readTarget(front),want=await decodePng(referenceUrl); + // The front buffer as presented: the swap's host swizzle. + if(front===backend.frontTexture){ + const sw=backend.frontSwizzle??0x688,px=got.pixels; + for(let i=0;i{const v=(sw>>>(3*k))&7;return v>=5?255:v===4?0:t[v];}; + px[i]=c(0);px[i+1]=c(1);px[i+2]=c(2);px[i+3]=c(3); + } + } + const w=Math.min(got.width,want.width),h=Math.min(got.height,want.height); + let diff=0,close=0,lit=0; + for(let y=0;y>>0); + e.r360_gpu_shared_memory_clear(); + + // Expected bytes: the words written above, big-endian, zero elsewhere. + const expected=()=>{ + const out=new Uint8Array(4*PAGE); + for(let p=0;p<4;p++)for(let w=0;w>>0,o=p*PAGE+w*4;out[o]=v>>>24;out[o+1]=v>>>16&255;out[o+2]=v>>>8&255;out[o+3]=v&255;} + return out; + }; + const want=expected(); + const same=(a,b)=>a.length===b.length&&a.every((x,i)=>x===b[i]); + + e.r360_gpu_shared_memory_request(BASE,4*PAGE); + backend.replay(); + const first=await backend.readSharedMemory(BASE,4*PAGE); + if(!same(first,want))return {ok:false,error:'shared memory differs from guest memory after the first upload'}; + + e.r360_sparse_guest_memory_write_u32_be(BASE+PAGE+8,0xCAFEF00D); + want.set([0xCA,0xFE,0xF0,0x0D],PAGE+8); + const uploadsBefore=backend.stats.uploads; + e.r360_gpu_shared_memory_request(BASE,4*PAGE); + backend.replay(); + const second=await backend.readSharedMemory(BASE,4*PAGE); + if(!same(second,want))return {ok:false,error:'shared memory differs after the CPU write'}; + return {ok:true,uploads:backend.stats.uploads,secondUploads:backend.stats.uploads-uploadsBefore, + uploadedBytes:backend.stats.uploadedBytes,sharedMemoryMiB:backend.sharedMemoryBytes/1048576, + adapter:adapter.info?.architecture||''}; +} diff --git a/tools/browser-test.mjs b/tools/browser-test.mjs new file mode 100644 index 00000000..75646f05 --- /dev/null +++ b/tools/browser-test.mjs @@ -0,0 +1,64 @@ +// Runs a browser-side test module in headless Chromium with WebGPU +// (SwiftShader) and returns what it reports. +// +// import {runBrowserTest} from './tools/browser-test.mjs'; +// const result = await runBrowserTest('tests/browser/foo.mjs'); +// +// The repository root is served on localhost (WebGPU needs a secure +// context). The module's default export is awaited in the page; its return +// value comes back as JSON. Uses the globally installed Playwright. +import http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; +import {execSync} from 'node:child_process'; +import {createRequire} from 'node:module'; + +const ROOT=path.resolve(path.dirname(new URL(import.meta.url).pathname),'..'); +const TYPES={'.mjs':'text/javascript','.js':'text/javascript','.html':'text/html','.wasm':'application/wasm','.json':'application/json'}; + +function loadPlaywright(){ + const globalRoot=execSync('npm root -g').toString().trim(); + return createRequire(path.join(globalRoot,'noop.js'))(path.join(globalRoot,'playwright')); +} + +function serve(dataRoot){ + const server=http.createServer((req,res)=>{ + const url=new URL(req.url,'http://localhost'); + if(url.pathname==='/__test__.html'){ + res.writeHead(200,{'content-type':'text/html'}); + res.end(''); + return; + } + // /__data__/ serves dataRoot: local inputs (game captures) kept outside + // the repository. + const data=dataRoot&&url.pathname.startsWith('/__data__/'); + const root=data?path.resolve(dataRoot):ROOT; + const file=path.join(root,decodeURIComponent(data?url.pathname.slice(9):url.pathname)); + if(!file.startsWith(root)||!fs.existsSync(file)||fs.statSync(file).isDirectory()){res.writeHead(404);res.end();return;} + res.writeHead(200,{'content-type':TYPES[path.extname(file)]||'application/octet-stream'}); + fs.createReadStream(file).pipe(res); + }); + return new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(server))); +} + +export async function runBrowserTest(modulePath,{args=[],timeoutMs=300000,onConsole=null,dataRoot=null}={}){ + const {chromium}=loadPlaywright(); + const server=await serve(dataRoot); + const port=server.address().port; + const browser=await chromium.launch({args:['--enable-unsafe-webgpu','--enable-features=Vulkan', + '--use-vulkan=swiftshader','--use-webgpu-adapter=swiftshader','--disable-vulkan-surface']}); + try{ + const page=await browser.newPage(); + page.on('console',m=>onConsole?.(m.text())); + page.on('pageerror',e=>onConsole?.(`pageerror: ${e.message}`)); + await page.goto(`http://127.0.0.1:${port}/__test__.html`); + page.setDefaultTimeout(timeoutMs); + return await page.evaluate(async([m,a])=>{ + const mod=await import(m); + return JSON.stringify(await mod.default(...a)); + },[`/${modulePath}`,args]).then(JSON.parse); + }finally{ + await browser.close(); + server.close(); + } +} diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 81eb5e0a..5b424227 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -41,12 +41,15 @@ function parseArgs(argv){ else if(a==='--max-minstr')args.maxMillions=Number(argv[++i]); else if(a==='--json')args.json=argv[++i]; else if(a==='--verbose'||a==='-v')args.verbose=true; + // --trace-from-minstr N: verbose runtime tracing (R360_VERBOSE_TRACE) from N million instructions on. + else if(a==='--trace-from-minstr')args.traceFrom=Number(argv[++i])>>>0; else if(a==='--trace-calls')args.traceCalls=true; else if(a==='--license')args.license=String(argv[++i]||'trial'); else if(a==='--log-draws')args.logDraws=Number(argv[++i])>>>0; else if(a==='--progress')args.progress=true; else if(a==='--no-jit')args.jit=0; else if(a==='--list-files'){} + else if(a==='--det-every')args.detEvery=Number(argv[++i])>>>0; else if(a==='--xenos-trace-from')args.xenosTraceFrom=Number(argv[++i])>>>0; else if(a==='--dump-shaders')args.dumpShaders=argv[++i]; else if(a==='--deterministic')args.deterministicPs=Number(argv[++i])>>>0; @@ -54,6 +57,15 @@ function parseArgs(argv){ else if(a==='--watch-kernel-arg')(args.kernelWatch||=[]).push(Number(argv[++i])>>>0); else if(a==='--render-from-minstr')args.renderFrom=Number(argv[++i])>>>0; else if(a==='--frame')args.frame=argv[++i]; + // --frame-at M1,M2,...:PREFIX saves PREFIX-M.png when the run passes M million instructions. + else if(a==='--gpu-capture'){const [from,swaps,...file]=String(argv[++i]).split(':');args.gpuCapture={from:Number(from),swaps:Number(swaps),file:file.join(':')};} + else if(a==='--frame-at'){const v=String(argv[++i]),c=v.lastIndexOf(':');args.frameAt={at:v.slice(0,c).split(',').map(Number).sort((x,y)=>x-y),prefix:v.slice(c+1)};} + // --press FROM:TO:BUTTONS holds gamepad 0 buttons (XINPUT bits, e.g. 0x10 = START, 0x1000 = A) between FROM and TO million instructions. + // --dialog-button N answers every XamShowMessageBoxUI with button N (the player's choice); without it the focused button is taken (Xenia headless). + else if(a==='--dialog-button')args.dialogButton=Number(argv[++i])>>>0; + // --stick FROM:TO:X:Y holds gamepad 0's left stick at X,Y (-1..1) between FROM and TO million instructions. + else if(a==='--stick'){const [from,to,x,y]=String(argv[++i]).split(':');(args.stick??=[]).push({from:Number(from),to:Number(to),x:Number(x),y:Number(y)});} + else if(a==='--press'){const [from,to,buttons]=String(argv[++i]).split(':');(args.press??=[]).push({from:Number(from),to:Number(to),buttons:Number(buttons)&0xFFFF});} else if(a==='--slice-ms')args.sliceMs=Number(argv[++i])>>>0; else if(a==='--watch')args.watch=Number(argv[++i])>>>0; else if(a==='--dump-guest'){const [addr,len,file]=String(argv[++i]).split(':');(args.dumps??=[]).push({address:Number(addr)>>>0,length:Number(len)>>>0,file});} @@ -64,6 +76,76 @@ function parseArgs(argv){ return args; } + +// PNG of the last swapped frontbuffer (Xenos decode of the VdSwap fetch +// constant from guest memory), for --frame and --frame-at. +let frontbufferModule=null,runArgs={}; +const savedFrames=[]; +function saveFramePng(file){ + let frame=null; + try{frame=frontbufferModule.captureTitleFrontbuffer({bootstrap:globalThis.__r360Bootstrap});}catch(e){frame={captured:false,reason:e.message};} + if(!frame?.captured)return {file,captured:false,reason:frame?.reason}; + const {width,height,rgba}=frame; + const raw=Buffer.alloc((width*4+1)*height); + for(let y=0;y{let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;return c>>>0;}); + const crc=b=>{let c=0xFFFFFFFF;for(const x of b)c=crcTable[(c^x)&255]^(c>>>8);return (c^0xFFFFFFFF)>>>0;}; + const chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length);const td=Buffer.concat([Buffer.from(type),data]);const c=Buffer.alloc(4);c.writeUInt32BE(crc(td));return Buffer.concat([len,td,c]);}; + const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0);ihdr.writeUInt32BE(height,4);ihdr[8]=8;ihdr[9]=6; + fs.writeFileSync(file,Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',ihdr),chunk('IDAT',zlibModule.deflateSync(raw)),chunk('IEND',Buffer.alloc(0))])); + let nonBlack=0;for(let i=0;i>>0;return; + } + const words=x.r360_gpu_stream_words()>>>0; + if(words)gpuCapture.chunks.push(Buffer.from(new Uint8Array(x.memory.buffer,x.r360_gpu_stream_data()>>>0,words*4))); + x.r360_gpu_stream_reset(); + // Count swap ops recorded so far. + let swaps=0;for(const b of gpuCapture.chunks){const w=new Uint32Array(b.buffer,b.byteOffset,b.byteLength/4);for(let i=0;i>>8))if((w[i]&0xFF)===6)swaps++;} + if(swaps>=c.swaps){ + x.r360_gpu_set_mode(0);gpuCapture.done=true; + fs.writeFileSync(c.file,Buffer.concat(gpuCapture.chunks)); + const info={swaps,minstr:m,draws:x.r360_gpu_draw_stat(0)>>>0,skips:[1,2,3,4,5].map(i=>x.r360_gpu_draw_stat(i)>>>0), + uploadedKiB:x.r360_gpu_shared_memory_uploaded_kb()>>>0}; + process.stderr.write(`gpu capture ${c.file}: ${JSON.stringify(info)}\n`); + if(frontbufferModule)info.frame=saveFramePng(c.file+'.png'); + fs.writeFileSync(c.file+'.json',JSON.stringify(info)); + } +} +function slicePressAndFrames(x){ + if(runArgs.dialogButton!==undefined&&x.r360_xam_dialog_pending?.()){ + const str=w=>Buffer.from(new Uint8Array(x.memory.buffer,x.r360_xam_dialog_string_ptr(w)>>>0,x.r360_xam_dialog_string_len(w)>>>0)).toString('utf8'); + const n=x.r360_xam_dialog_button_count()>>>0,choice=Math.min(runArgs.dialogButton,n-1); + process.stderr.write(`dialog "${str(0)}" -> ${choice} (${str(2+choice)})\n`);x.r360_xam_dialog_answer(choice); + } + const m=x.r360_hir_total_instructions_millions?.()>>>0; + sliceGpuCapture(x,m); + if(runArgs.press||runArgs.stick){ + let buttons=0,lx=0,ly=0; + for(const p of runArgs.press||[])if(m>=p.from&&m=p.from&&mMath.max(-32768,Math.min(32767,Math.round(v*32767)))&0xFFFF; + const left=(axis(lx)|(axis(ly)<<16))>>>0,key=`${buttons}:${left}`; + if(key!==globalThis.__r360PressKey){globalThis.__r360PressKey=key;x.r360_input_set_gamepad?.(0,1,buttons,0,left,0);process.stderr.write(`press ${m}M buttons=0x${buttons.toString(16)} stick=${lx},${ly}\n`);} + } + if(runArgs.frameAt){ + const pending=runArgs.frameAt.at.filter(at=>at<=m&&!savedFrames.some(f=>f.at===at)); + if(pending.length){const at=pending[pending.length-1];const info=saveFramePng(`${runArgs.frameAt.prefix}-${at}.png`);for(const p of pending)savedFrames.push({at:p,actual:m,vdSwap:x.r360_title_gpu_vd_swap_calls?.()>>>0,...(p===at?info:{skipped:true})});process.stderr.write(`frame ${m}M -> ${JSON.stringify(info)}\n`);} + } +} + const hex=v=>`0x${(Number(v)>>>0).toString(16).toUpperCase().padStart(8,'0')}`; // --dump-shaders DIR: each distinct current Xenos shader as ucode and as @@ -88,7 +170,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR')||line.startsWith('R360_DIAG')||line.startsWith('R360_JIT_SEQ'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; @@ -179,6 +261,10 @@ async function main(){ } const bootstrapFile=args.bootstrap||(fs.existsSync(rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'))?rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'):rel('xenia_ppc_bootstrap.wasm')); const {instance:bootstrap,host,stderr}=await loadBootstrap(bootstrapFile,args.verbose); + runArgs=args;globalThis.__r360Bootstrap=bootstrap; + // A preset answer inside the call keeps the run deterministic. + if(args.dialogButton!==undefined)bootstrap.exports.r360_xam_dialog_set_auto_answer?.(args.dialogButton); + if(args.frame||args.frameAt||args.gpuCapture){frontbufferModule=await import(rel('render360-title-frontbuffer.mjs'));zlibModule=await import('node:zlib');} const core=await loadCore(); const started=Date.now(); const title=await openTitle(args.input,{core,host}); @@ -189,15 +275,23 @@ async function main(){ // Per-call/per-function stderr tracing is off by default for speed. bootstrap.exports.r360_trace_set_verbose?.(args.traceCalls?1:0); if(args.watch)bootstrap.exports.r360_debug_watch?.(args.watch); + if(args.detEvery)bootstrap.exports.r360_kernel_determinism_every?.(args.detEvery); // Guest time from executed instructions (ps per HIR instruction): replayable runs. if(args.deterministicPs)bootstrap.exports.r360_set_deterministic_clock?.(args.deterministicPs); if(args.logDraws)bootstrap.exports.r360_xenos_debug_draws?.(args.logDraws); // Guest JIT (render360-guest-jit.mjs): hot guest functions run as // generated WebAssembly. --no-jit keeps everything on the HIR executor. const {installGuestJit}=await import(rel('render360-guest-jit.mjs')); - const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); + const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,hotThreshold:Number(process.env.R360_JIT_HOT||2),onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); globalThis.__r360Jit=jit; if(process.env.R360_JITPROF)bootstrap.exports.r360_jit_profile?.(1); + if(process.env.R360_DIAG){bootstrap.exports.r360_jit_diag?.(1);} + if(process.env.R360_JIT_REJECT_TAIL)bootstrap.exports.r360_jit_set_reject_tail?.(1); + if(process.env.R360_JIT_LOG_SEQ){const [b,e]=process.env.R360_JIT_LOG_SEQ.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_log_seq?.(b,e,process.env.R360_JIT_LOG_DUMP?1:0);} + if(process.env.R360_JIT_EXCLUDE_SEQ){const [b,e]=process.env.R360_JIT_EXCLUDE_SEQ.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude_seq?.(b,e);} + if(process.env.R360_JIT_EXCLUDE){const [b,e]=process.env.R360_JIT_EXCLUDE.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude?.(b,e);} + if(args.traceFrom!==undefined){globalThis.__r360TraceOn=1;bootstrap.exports.r360_trace_verbose_from?.(args.traceFrom);} + if(process.env.R360_OSR!==undefined)bootstrap.exports.r360_jit_set_osr?.(Number(process.env.R360_OSR)); (args.kernelWatch||[]).slice(0,4).forEach((v,k)=>bootstrap.exports.r360_kernel_watch_arg?.(k,v)); if(args.renderFrom!==undefined)bootstrap.exports.r360_xenos_soft_set_rasterize?.(args.renderFrom===0?1:0); // --max-minstr N: stop after N million guest instructions in total. @@ -209,7 +303,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined)?(s=>{const x=bootstrap.exports;if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.gpuCapture||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.gpuCapture||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} @@ -219,7 +313,7 @@ async function main(){ const elapsedMs=Date.now()-started; const report={ - input:path.resolve(args.input),kind:title.kind,bootstrap:bootstrapFile,elapsedMs,instructionBudget:budget||null, + input:path.resolve(args.input),kind:title.kind,bootstrap:bootstrapFile,elapsedMs,wasmMemoryMiB:Math.round(bootstrap.exports.memory.buffer.byteLength/1048576),instructionBudget:budget||null, vfs:{files:title.files.filter(f=>!f.directory).length,directories:title.files.filter(f=>f.directory).length,registered:vfs.registered,reads:bootstrap.exports.r360_vfs_reads?.()>>>0,pending:pendingGuestVfsRead(bootstrap)}, error:error?{message:error.message,details:error.render360??null}:null, }; @@ -233,7 +327,11 @@ async function main(){ memoryFault:result.memoryFaultCode?{code:result.memoryFaultCode,address:hex(result.memoryFaultAddress)}:null, guestFibers:result.guestFibers??null, guestThreadWaits:globalThis.__r360Threads??null, - framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), + // 30 FPS bar inputs for a headless run (render360-perf-overlay.mjs): + // guest frames per wall second, instruction rate, interpreted share, + // guest idle time. + perf:(()=>{const x=bootstrap.exports;if(typeof x.r360_perf_counter!=='function')return null;const wall=(Date.now()-started)/1000,instr=x.r360_perf_counter(0),interp=x.r360_perf_counter(1),frames=(x.r360_title_gpu_vd_swap_calls?.()>>>0)||0;return {wallSeconds:+wall.toFixed(1),guestFrames:frames,gameFpsWall:+(frames/Math.max(wall,0.001)).toFixed(2),mips:+(instr/Math.max(wall,0.001)/1e6).toFixed(1),interpretedPercent:+(instr?100*interp/instr:0).toFixed(3),guestIdleMs:+(x.r360_fiber_idle_ms?.()??0).toFixed(0)};})(), + framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),cacheMemoHits:f('r360_hir_cache_memo_hits'),jitOsrEntries:f('r360_jit_osr_entries'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), mainThread:result.mainThreadContext?{stackBytes:result.mainThreadContext.stackBytes,tlsBytes:result.mainThreadContext.tlsBytes,tlsTemplate:result.mainThreadContext.tlsTemplate}:null, kernelVariables:{relocated:result.kernelVariableRegistration?.relocated?.map(v=>v.name),placeholders:result.kernelVariableRegistration?.placeholders?.map(v=>kernelExportName(v.module,v.ordinal))}, importedKernelFunctions:result.kernelImports?.plan?.filter(i=>i.isKernelModule&&i.kind==='function').length, @@ -244,6 +342,7 @@ async function main(){ titleGpu:result.titleGpuTelemetry, debugLog:readDebugLog(bootstrap), guestVfsFetched:result.guestVfsFetched, + threads:globalThis.__r360Threads??null, }); } // --frame FILE.png saves the last swapped frontbuffer (Xenos decode of the @@ -251,24 +350,8 @@ async function main(){ // R360_DUMP=address,bytes,file: guest bytes (sparse memory) after the run. for(const spec of (process.env.R360_DUMP||'').split(';').filter(Boolean)){const [a0,n0,file]=spec.split(',');const a=Number(a0)>>>0,n=Number(n0)>>>0,x=bootstrap.exports,out=Buffer.alloc(n); const tmp=x.r360_ppc_probe_input_buffer()>>>0;for(let i=0;i{let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;return c>>>0;}); - const crc=b=>{let c=0xFFFFFFFF;for(const x of b)c=crcTable[(c^x)&255]^(c>>>8);return (c^0xFFFFFFFF)>>>0;}; - const chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length);const td=Buffer.concat([Buffer.from(type),data]);const c=Buffer.alloc(4);c.writeUInt32BE(crc(td));return Buffer.concat([len,td,c]);}; - const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0);ihdr.writeUInt32BE(height,4);ihdr[8]=8;ihdr[9]=6; - fs.writeFileSync(args.frame,Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',ihdr),chunk('IDAT',zlib.deflateSync(raw)),chunk('IEND',Buffer.alloc(0))])); - let nonBlack=0;for(let i=0;i "From my Mac" lists /games.json and downloads files with +HTTP Range requests, so an interrupted download resumes where it stopped. + +* Read-only: GET/HEAD only, nothing outside the served folder (no symlink or + ".." escapes), no directory listings except the JSON catalogue. +* Optional --token: the app must send it as ?token= or the X-Render360-Token + header (prints a URL with the token to paste into the app). +* Game files never go into git: serve them from a folder outside the repo. + +Catalogue format (/games.json): {"games":[{"id","title","discs":[{"name","path","size"}]}]} +A game is a sub-folder (its files are its discs, sorted by name: Watch Dogs +Disc 1, Disc 2) or a single file at the top level. +""" +import argparse +import hashlib +import http.server +import json +import os +import socket +import socketserver +import sys +import urllib.parse + +GAME_EXTENSIONS = {".iso", ".xex", ".god", ".stfs", ".con", ".live", ""} +CHUNK = 1 << 20 + + +def is_game_file(name): + if name.startswith("."): + return False + ext = os.path.splitext(name)[1].lower() + # STFS packages are usually extension-less 42-hex-digit names (Banjo). + return ext in GAME_EXTENSIONS or ext in {".bin", ".img"} + + +def catalogue(root): + games = [] + for name in sorted(os.listdir(root)): + full = os.path.join(root, name) + if name.startswith("."): + continue + if os.path.isdir(full): + discs = [] + for disc in sorted(os.listdir(full)): + path = os.path.join(full, disc) + if os.path.isfile(path) and is_game_file(disc): + discs.append({"name": disc, "path": f"{name}/{disc}", "size": os.path.getsize(path)}) + if discs: + games.append({"id": hashlib.sha1(name.encode()).hexdigest()[:12], "title": name, "discs": discs}) + elif os.path.isfile(full) and is_game_file(name): + games.append({"id": hashlib.sha1(name.encode()).hexdigest()[:12], "title": name, + "discs": [{"name": name, "path": name, "size": os.path.getsize(full)}]}) + return {"games": games} + + +class Handler(http.server.BaseHTTPRequestHandler): + root = "." + token = None + server_version = "Render360GameServer/1" + + def log_message(self, fmt, *args): + sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args)) + + def authorized(self, query): + if not self.token: + return True + supplied = self.headers.get("X-Render360-Token") or query.get("token", [None])[0] + return supplied == self.token + + def resolve(self, rel): + rel = urllib.parse.unquote(rel).lstrip("/") + path = os.path.realpath(os.path.join(self.root, rel)) + if path != self.root and not path.startswith(self.root + os.sep): + return None + return path if os.path.isfile(path) else None + + def do_HEAD(self): + self.handle_request(head=True) + + def do_GET(self): + self.handle_request(head=False) + + def handle_request(self, head): + url = urllib.parse.urlsplit(self.path) + query = urllib.parse.parse_qs(url.query) + if not self.authorized(query): + self.send_error(403, "token required") + return + if url.path == "/games.json": + body = json.dumps(catalogue(self.root)).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + if not head: + self.wfile.write(body) + return + if not url.path.startswith("/files/"): + self.send_error(404) + return + path = self.resolve(url.path[len("/files/"):]) + if not path: + self.send_error(404) + return + size = os.path.getsize(path) + start, end = 0, size - 1 + status = 200 + rng = self.headers.get("Range") + if rng: + try: + unit, spec = rng.split("=", 1) + first, last = spec.split(",")[0].split("-") + if unit.strip() != "bytes": + raise ValueError + if first: + start = int(first) + end = int(last) if last else size - 1 + else: # suffix range: last N bytes + start = max(0, size - int(last)) + if start > end or start >= size: + raise ValueError + end = min(end, size - 1) + status = 206 + except ValueError: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{size}") + self.end_headers() + return + length = end - start + 1 + self.send_response(status) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Length", str(length)) + stat = os.stat(path) + self.send_header("ETag", '"%x-%x"' % (stat.st_size, int(stat.st_mtime))) + if status == 206: + self.send_header("Content-Range", f"bytes {start}-{end}/{size}") + self.end_headers() + if head: + return + with open(path, "rb") as f: + f.seek(start) + remaining = length + try: + while remaining: + data = f.read(min(CHUNK, remaining)) + if not data: + break + self.wfile.write(data) + remaining -= len(data) + except (BrokenPipeError, ConnectionResetError): + pass # the app paused/cancelled; it resumes with a Range request + + +class Server(socketserver.ThreadingMixIn, http.server.HTTPServer): + daemon_threads = True + allow_reuse_address = True + + +def lan_address(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + s.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("folder", help="folder with your game files (outside any git repository)") + parser.add_argument("--port", type=int, default=8360) + parser.add_argument("--bind", default="0.0.0.0") + parser.add_argument("--token", default=None, help="require this token from the app") + args = parser.parse_args() + root = os.path.realpath(args.folder) + if not os.path.isdir(root): + parser.error(f"{root} is not a folder") + probe = root + while probe != os.path.dirname(probe): + if os.path.isdir(os.path.join(probe, ".git")): + print(f"warning: {root} is inside a git repository ({probe}); keep game files out of git", file=sys.stderr) + break + probe = os.path.dirname(probe) + Handler.root = root + Handler.token = args.token + games = catalogue(root)["games"] + url = f"http://{lan_address()}:{args.port}" + print(f"Serving {len(games)} game(s) from {root}") + print(f"In the app: Import > From my Mac > {url}" + (f" (token {args.token})" if args.token else "")) + Server((args.bind, args.port), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/tools/telemetry-server.py b/tools/telemetry-server.py new file mode 100644 index 00000000..fb122f0d --- /dev/null +++ b/tools/telemetry-server.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Receive Render360 iOS telemetry on the Mac and show it at /status. + + python3 tools/telemetry-server.py [--port 8361] [--logs logs/phone] + +In the app: Settings > Telemetry to the Mac > http://:8361 +The phone POSTs one JSON object per second to /telemetry?s= and, +after a crash, its last breadcrumbs to /crash?s=. This server keeps: + logs/phone/telemetry_.jsonl every line (game FPS, speed, MIPS, + interpreted %, memory, thermal...) + logs/phone/crash__