diff --git a/.gitignore b/.gitignore index c3563c064..03bf66fb4 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ games/totk/tools/totk_xlate/bin/ games/totk/scripts/shader_inventory/obj/ games/totk/scripts/shader_inventory/bin/ ultracode.md +games/oot/tools/totk_xlate/obj/ diff --git a/README.md b/README.md index 082f56dd5..f99996ff2 100644 --- a/README.md +++ b/README.md @@ -359,6 +359,7 @@ MNG Launcher 和每个游戏**每天最多上报一次**到 [mac-native-games.co ## 更新说明 +- **2026-11-25:时之笛设置面板新增“动态分辨率”行(默认关,下次启动生效),并附一份 M2 上的实测性能分析**([games/oot/docs/m2-performance.md](games/oot/docs/m2-performance.md))。 - **2026-11-23:大金刚 Bananza 可以用 `.nup` 或导出目录打包,带追加内容(Mac)。** Emerald Rush 能从你自己的文件加载,还没有玩通。 - **2026-11-23:修复宝可梦 Pokopia 画面偏暗(Mac)。** - **2026-11-23:女神异闻录 5 皇家版 1.0.2 和巫师 3 4.04b 登陆 Mac,早期。** 女神异闻录 5 皇家版有 Mac App,能玩到开场赌场([games/p5r](games/p5r/README.md));巫师 3 能读档在凯尔莫罕游玩,还没有 App([games/w3](games/w3/README.md))。 diff --git a/games/oot/Makefile b/games/oot/Makefile index 38e918593..8d381ce23 100644 --- a/games/oot/Makefile +++ b/games/oot/Makefile @@ -77,6 +77,19 @@ $(OUT)/timeline-trigger: tests/timeline_trigger.c third_party/d2r_gfx/gfx/nvn/to probe-timeline-trigger: $(OUT)/timeline-trigger "$(OUT)/timeline-trigger" "$(OUT)/timeline-trigger.tsv" +# PoC microbenchmark: Ocarina of Time mesh-stage structure at fed302d7 scale (1117 threadgroups, +# 128 vertices x 10 float4 per group, ~13 KB device scratch slot with atomics, 80 raw reads per +# logical lane through an 8-word range cache). Variants t32/t64/t128 (threads per threadgroup) +# and s64/s128 (reads staged per SIMD group through threadgroup memory). Measured on an Apple M2 +# (2026-11-26): t32 49.9 ms, t64 26.8, t128 14.6 (-71 %), s64 26.1, s128 16.7 - the win is the +# thread count per threadgroup, not the read split. +$(OUT)/mesh-simd-split-bench: tests/mesh_simd_split_bench.m tests/mesh_simd_split_bench.metal + @mkdir -p "$(dir $@)" + xcrun clang -O2 -framework Metal -framework Foundation tests/mesh_simd_split_bench.m -o "$@" +.PHONY: mesh-simd-split-bench +mesh-simd-split-bench: $(OUT)/mesh-simd-split-bench + "$(OUT)/mesh-simd-split-bench" "$(CURDIR)/tests/mesh_simd_split_bench.metal" + $(OUT)/pool-sources: tests/pool_sources.m third_party/d2r_gfx/gfx/nvn/nvn_pool_sources.m third_party/d2r_gfx/gfx/nvn/nvn_pool_sources.h third_party/d2r_gfx/gfx/nvn/nvn_refl.h @mkdir -p "$(OUT)" xcrun clang -std=gnu11 -O2 -Wall -Wextra -Werror -fobjc-arc tests/pool_sources.m third_party/d2r_gfx/gfx/nvn/nvn_pool_sources.m -framework Foundation -o "$@" diff --git a/games/oot/README.md b/games/oot/README.md index b365593f9..1b60fb778 100644 --- a/games/oot/README.md +++ b/games/oot/README.md @@ -34,9 +34,15 @@ Key **1** opens the settings panel. The first page: - **Upscaler**: MetalFX (the default) or the game's own network, for that one upscale. The title and opening movies always use MetalFX, whatever this setting: the game runs its own network on each movie picture (about 28 ms a frame on an M4, so the movies played slowed down and out of sync with their sound); with MetalFX a movie frame takes about 1.5 ms on the GPU. - **End-of-frame network at native resolution**: skipped (the default) or running. At a native resolution the game still runs its upscaling network 1:1, about 2 ms a frame; skipped, the picture is copied to the canvas instead and has no anti-aliasing from the network. - **Quality profile**, changed while the game runs: handheld (the default) or docked. The game's own handheld profile draws less vegetation; the resolution stays the one chosen above. +- **Dynamic resolution** (from the next start): off (the default — the Mac pins the render scale, the picture never changes under load) or on, as on the console: the game lowers the 3D scale itself when the GPU is the limit. Measured on an Apple M2 at a 720p canvas in Kokiri Forest: 34 fps fixed against 39–40 fps dynamic; in lighter scenes the game keeps the full scale. `OOT_FIXED_RES=0` in the environment does the same. See [docs/m2-performance.md](docs/m2-performance.md). - **Frame lock**: 30 (the default), off, 40, 60, 72, 90, 120. - **Frame interpolation (MetalFX)**: 30+30, 40+40, 50+50, 60+60 or uncapped. On a 100 Hz display, 50+50 adds one frame between every two game frames. Choosing it turns the frame lock off. +On a weaker Mac (an M2, say), a steady 60 Hz on screen comes from the dynamic resolution row on plus frame +interpolation (uncapped if the game rate is well above 30): measured on an M2 at 720p native and at 1080p native +the display then shows a steady 60.0 images/s while the game's own rate adapts (about 40 fps real at 1080p native +with dynamic resolution + uncapped interpolation; see [docs/m2-performance.md](docs/m2-performance.md)). + `defaults write org.macnativegames.oot TOTK_OPERATION_MODE handheld` starts the game in handheld mode with the handheld controller, whatever the quality profile row saved; `defaults delete org.macnativegames.oot TOTK_OPERATION_MODE` removes it. The environment variable of the same name wins. ## Shaders diff --git a/games/oot/docs/m2-performance.md b/games/oot/docs/m2-performance.md new file mode 100644 index 000000000..91c317896 --- /dev/null +++ b/games/oot/docs/m2-performance.md @@ -0,0 +1,169 @@ +# Ocarina of Time on an Apple M2: measured performance and where the time goes + +Measurements of 2026-11-25 on a MacBook Air M2 (10-core GPU, fanless), macOS 27.2.1, internal 2560×1664 @ 60 Hz, +app built from `3b0eae42`. Scene: the newest save, Kokiri Forest, standing still; private copy of the player's +profile and shader cache; frame lock off (`flag fps_lock 0`); 40 s windows after a 35–60 s warm-up, two runs each, +host not idle. Frame times come from `TOTK_BENCH_FRAMES`; GPU/CPU from `metalperftrace` and the in-game 300-frame +windows; pass/dispatch costs from `TOTK_PASS_GPU_FILE` / `OOT_DISPATCH_GPU_FILE` (`flag pass_gpu 30`). + +## The headline numbers + +| Setting (canvas row) | FPS (median frame) | GPU busy per frame | +|---|---|---| +| 720p native (default) | 34.1 fps (29.2 ms) | ~27.9 ms — the Metal layer is active ~100 % of the time | +| 720p from 480p (handheld 3D) | 39.0 fps (25.6 ms) | — | +| 720p native + the game's own dynamic resolution (`OOT_FIXED_RES=0`, now the panel's 动态分辨率 row) | 39.0–40.1 fps (25.3 ms) | the game lowers the 3D scale itself (to ~683×384 at the heaviest here) | +| 1080p native | ~30 fps (33–34 ms) | — | + +**The game is GPU-bound, not CPU-bound, in this scene.** `metalperftrace`: on-GPU time 27.6–28.2 ms per frame +(stddev 1.5 ms) against a 29 ms frame; CPU begin-to-present 21.5 ms, i.e. the CPU mostly waits for the GPU. +Total CPU is only ~1.5 cores of the 10, and the Time Profiler puts ~15 % of samples in the guest's own code, +the rest spread over the encode stage (~8 %) and ~80 guest worker threads. + +## Where the GPU time goes (per frame, 720p canvas) + +From the pass/dispatch dumps (encoder spans overlap, so the buckets are indicative, not additive): + +- ~63 render passes at the 3D size + ~100 smaller ones, ~160 passes and ~1,215 draws per frame in total. + Main-target passes ≈ 16 ms, half-res (640×360) post ≈ 2.6 ms, shadow cascades (depth-only 1000×1000, 3/frame) + ≈ 3.3 ms, small 128×128 passes ≈ 2.1 ms. +- ~31 compute passes ≈ 9.8 ms/frame; the five heaviest (mesh / culling shaders) ≈ 5.6 ms of that. +- The keep-alive spinner ≈ 0.7 ms/frame (measured `TOTK_GPU_KEEPALIVE=0`: no change at this load, the GPU never idles). + +The cost barely drops when the 3D resolution is halved (720p → 480p: render passes 16.4 → 13.0 ms): the frame is +**draw-call and pass-count bound, not pixel bound** — ~1,200 draws and ~160 passes of fixed per-draw/per-pass cost +plus attachment traffic. That is the Switch 2 mesh-shader pipeline's shape, and it is the main thing to attack for +60 fps on a weaker Mac. + +## What was measured and ruled out (2026-11-25, M2, 720p canvas, 40 s A/B windows) + +| Candidate | Result | +|---|---| +| GPU keep-alive off (`TOTK_GPU_KEEPALIVE=0`) | neutral (34.5 vs 34.2 fps) — GPU already ~96 % busy | +| Cheaper scheduler yields (`flag yield_fast 2`) | neutral (34.1 vs 34.2) | +| Async replay (`TOTK_ASYNC_REPLAY=1`) | neutral / slightly worse (38.7 vs 39.4 at 480p) | +| Drawable at the game picture's size (`TOTK_DRAWABLE_SCALE=0.5`) | neutral — the present pass is a cheap blit | +| Present link off (`DM_PRESENT_LINK=0`) | neutral at 720p; only matters when the window is occluded | +| Shading-rate images (NVN2 VRS) | **unused by the game in this scene**: ~6,984 binds / 300 frames, every palette entry 1×1. The full-rate shading is not waste here | +| The game's own dynamic resolution | **+14 %** (34.1 → 39.0–40.1 fps), the single biggest lever measured; exposed as the 动态分辨率 settings row (default off) | +| 720p-from-480p canvas | +14 % (34.1 → 39.0 fps), the game's own handheld mode | + +## Why frames drop during play (measured while playing, 2026-11-25) + +The long-frame log (整帧 > 80 ms) shows the drops are **first-visit texture streaming**, not steady-state cost: +one frame uploaded 383 textures / 280 MB (146 ms of upload, 582 ms frame with a 343 ms GPU burst), others +84-145 textures / 25-135 MB (100-400 ms frames) right after the save loads and when new areas enter view. +Rarer: one arena heap migration (~90 ms) and a one-off pipeline compile (~17 ms). Steady state is p50 ~24 ms +at 720p on the M2 — the drops are area loads, which the shader cache / pipeline archive already cover for +shaders; textures stream on demand by design. + +## 1080p native on the M2 (2026-11-26): 60 FPS displayed, ~40-52 real + +Measured at canvas 1920x1080 (the "1080p (native)" row), same scene/method on the rebased tree: + +| Config | game fps | displayed FPS | +|---|---|---| +| 1080p native, fixed scale | 34.9 (p50 28.6 ms) | 34.9 | +| 1080p native + dynamic resolution | **51.5 (p50 19.3 ms)** | 51.5 | +| 1080p native + DRS + interpolation 30+30 | 30 (held) | **59.5-60.0** | +| 1080p native + DRS + interpolation **uncapped** (`interp-4`) | **~40 real** | **60.0 steady** (present interval p50/p95 16.67 ms, 373-399 of 600 presents interpolated, 0.2-0.7 % over one refresh) | + +So at 1080p native the M2 shows a steady **60 FPS** with the uncapped interpolation while the game logic +runs at ~40 fps (DRS adapts the internal 3D scale, ~683x384-768x432 here). A real 60 fps *game* rate at +1080p native is not reachable on the M2 in this scene: the GPU wall needs <= 16.7 ms/frame and DRS already +sits at ~19.3 ms; 51.5 fps is the measured ceiling without interpolation. + +## 60 FPS displayed on the M2: the applied recipe (2026-11-25) + +With the settings files alone, measured on the rebased tree: present interval **p50 / p95 / max 16.67 ms, +~0 % over one refresh, ~300-400 of 600 presents interpolated — a steady 60.0 FPS on the 60 Hz display**. +- 720p native (`graphics-canvas.txt=1`) + `graphics-drs.txt=1` + `graphics-frame.txt=interp-1` (30+30): 60.0 displayed, game held at 30. +- 1080p native (`graphics-canvas.txt=3`) + `graphics-drs.txt=1` + `graphics-frame.txt=interp-4` (uncapped): **60.0 displayed, game ~40 fps real** — the current applied setting. +Without interpolation the same scene runs at 41 fps (720p native) / 35 fps (1080p native), 51 fps with DRS. + +## Real 60 fps in Kokiri Forest on the M2: measured ceiling and what it would take (2026-11-26) + +Goal: 60 fps *game* rate (no interpolation) in this scene on the M2. Measured (rebased tree, 720p canvas): + +- 720p native fixed scale: 41 fps (frame 24.2 ms). With the game's dynamic resolution (internal ~683x384 at + load): **50.6-51.5 fps (frame 19.6 ms)** — the measured ceiling. metalperftrace: on-GPU 19.3-20.8 ms, layer + active ~100 %, CPU begin-to-present 18-20.6 ms: the GPU is the wall. +- The frame cost is **not pixel-bound**: fixed scales 1.0 / 0.75 / 0.6 all measure ~41 fps (24.5 ms) while the + game's own DRS at 683x384 reaches 51 — the game's DRS also drops draw/LOD work, a fixed scale does not. +- Per frame at DRS (pass spans, overlapping): ~31 compute passes 10.2 ms (the biggest bucket, resolution + independent), ~63 main render passes 13.0 ms, 1000x1000 shadow passes 3.2 ms, 128x128 passes 2.1 ms + (~112 draws), post chain ~3 ms. ~1,210 draws/frame total. +- Ruled out by A/B at DRS: `skip_invisible` (no draw ever has all-zero queries — nothing skipped), keep-alive + **off hurts** (43.9 vs 50.6 — on the fanless M2 the spinner keeps the GPU clock up; leave it on), + `yield_fast`, `TOTK_ASYNC_PREEMPT=0` — all neutral. +- Kernel-level split (OOT_DISPATCH_GPU_FILE Precise timestamps, 30 frames): compute kernels ~4.5 ms/frame, + render kernels ~15 ms/frame — the wall is the render (geometry/mesh/fragment) side, not the per-encoder + overhead: `TOTK_BARRIER_START=0` (racy, measurement only) changes nothing (50.7 vs 50.6 fps), the + queue-wide barrier at each compute encoder start is not the cost while the GPU is saturated. +- To reach 16.7 ms/frame needs ~15 % less GPU work. The realistic paths, in order: (a) merge adjacent compute + encoders when no barrier separates them (~10.2 ms of compute spans, much of it per-pass fixed cost); + (b) translator-level mesh/compute work (SIMD split of one thread's reads: up to -42 % on the mesh stage, + needs a new chain + seed); (c) an opt-in shadow-resolution row (1000x1000 + 128x128 passes ~5.3 ms/frame; + needs a verified size site in OoT's main, like BotW's botw_shadow_res.h); (d) more render-pass merging + (114 passes/frame after #2324). None of these is safe to land without the corresponding GPU probes. + +## Update after rebasing on 786ddc00 (PR #2324, 2026-11-25): pass splits on M1/M2 + +`origin/main` then landed "on M1 / M2 an Ocarina of Time render pass ends only where mesh and ordinary draws meet" +(PR #2324): render passes per frame in this scene went **159.7 -> 114.2** (-28 %) and the frame rate on the M2 +at 720p native went **34.1 -> 41 fps** (p50 29.2 -> 24.2 ms). New numbers on the rebased tree, same scene/method: + +| Config | game fps (p50) | +|---|---| +| 720p native | 40.9-41.2 (24.2 ms) | +| 720p native + dynamic resolution | **51.0 (19.5 ms)** | +| 480p canvas | 41.7-49.7 (20-24 ms) | +| 480p canvas + dynamic resolution | **50.8 (19.6 ms, p99 22.3 ms — the most stable)** | + +So on the M2 the game now runs at ~41 fps at 720p native and ~51 fps with the dynamic-resolution row on — +"aux alentours de 60" on the game rate in the heavy village scene, with the display filled to a steady 60 Hz +by MetalFX interpolation 30+30 whenever the game rate is >= 30 (measured displayed 54-60 FPS with FI on; +note FI itself costs ~2-4 ms of GPU per generated frame, so it trades a little game rate for the steady 60 Hz). + +## Reaching a steady 60 Hz on screen on the M2 (display rate, with frame interpolation) + +The game runs its logic at ~30-40 fps in this scene on the M2 (GPU wall above); MetalFX frame interpolation +fills the display to a steady 60 Hz. Measured with metalperftrace (output FPS = drawables shown per second): + +| Config (720p canvas unless said) | game fps | **displayed FPS** | on-GPU avg | +|---|---|---|---| +| 720p native, no interpolation | 34 | 34 | 27.9 ms | +| 720p native + interpolation 30+30 | ~30 | **55.5-57** | 17.5 ms | +| 720p native + dynamic resolution + interpolation 30+30 | ~30 (internal 683x384-1152x648 adapting) | **60.0 steady** (present interval p50 16.67 ms, ~50 % interpolated, 0.3 % over one refresh) | ~16 ms | +| 480p canvas (720p from 480p) + interpolation 30+30 | 29.9 | **60.0 steady** | 15.9 ms | + +So on an M2 the practical "60 FPS" setup is: Resolution 720p native (or 720p from 480p), the new 动态分辨率 row on, +and 补帧 (MetalFX) 30+30 — the display then shows a steady 60 images/s. The interpolation costs GPU time per +generated frame (~2-4 ms), which is why the game rate itself drops a little; the DRS row is what keeps the game +rate (and latency) up while it adapts. + +## Update 2026-11-25 (later the same day) + +- The pending-write overlay scan now skips out-of-span queries (perf commit in this PR): the copy routine's + scans went 15.6 -> 0.0 entries per call (~29k iterations/frame removed), applied entries identical; + `probe-gpu-ubo-snapshot` passes (16,409 checks). Frame rate unchanged — the frame is GPU-bound, this removes CPU work. +- 480p canvas + the game's dynamic resolution together: 39.5-39.9 fps (DRS adds nothing on top of 480p there, + the game is already at its lowest scale). + +## Where the remaining work is + +1. **Per-draw / per-pass cost** (~1,200 draws, ~160 passes/frame): more pass merging (only 8 layered passes merge + today), fewer encoder splits, less attachment load/store traffic. The mesh-batch and write-domain work of + 2026-11-08 already landed; the next step is batching more of the indirect-argument preparation and looking at + the ~31 compute passes (mesh + culling) — the offline meshbench showed splitting one thread's reads across + SIMD groups is worth up to −42 % on the mesh stage, that is a translator (`tools/totk_xlate`) change and needs + a new chain and seed. +2. **Shadow passes** (3 depth-only 1000×1000 passes/frame, ~3.3 ms): resolution-independent; only reducible by + rendering them less often, which is the game's decision, not ours. +3. **CPU headroom** for when the GPU is not the wall (lighter scenes): the HLE scheduler still shows in samples + (`runtime_gate` / `svc_thread_` / `block`); the `yield_backoff` / `yield_fast` flags of 2026-11-24 are off by + default and stay off — on the M4 they saved ~2.5 % CPU but dropped frames at 100 fps. + +Rule reminder for any change here: on the Mac the picture must not change — no resolution, effect or rate changes +by default; anything that lowers quality goes behind a switch that is off by default (the dynamic-resolution row +is exactly that: the game's own console behavior, opt-in). diff --git a/games/oot/docs/mesh-threads-poc.md b/games/oot/docs/mesh-threads-poc.md new file mode 100644 index 000000000..a28c70d8d --- /dev/null +++ b/games/oot/docs/mesh-threads-poc.md @@ -0,0 +1,101 @@ +# PoC: mesh stage at 64/128 threads per threadgroup on Apple silicon (2026-11-26) + +Branch `oot-mesh-simd-poc`. Question: the offline meshbench measured that running a mesh stage +at more threads per threadgroup (same output allocation) is the win — on an M4: 32 -> 128 threads +was −42 % (docs/fps-60-90.md); we re-measured on an M2 with the real fed302d7 structure — and the +real shader crashes above 32 threads. Details and numbers below. + +## 1. Microbenchmark, reproduced and committed (`make -C games/oot WORK=… mesh-simd-split-bench`) + +`games/oot/tests/mesh_simd_split_bench.{m,metal}`: 1117 threadgroups (fed302d7's grid), 128 vertices +x 10 float4 exported per group, a ~13 KB device scratch slot taken/released with atomics, and 80 raw +word reads per logical lane through an 8-word range cache (the port's raw-read path; the real shader +has 61 4-wide + 19 1-wide). Variants t32/t64/t128 (threads per group) and s64/s128 (reads staged per +SIMD group through threadgroup memory). Median of 16 submits, Apple M2: + +| variant | threads | median ms | vs t32 | +|---|---|---|---| +| t32 (as shipped) | 32 | 49.9-51.9 | — | +| t64 | 64 | 26.8-27.3 | −46 % | +| t128 | 128 | 14.4-16.6 | **−69..−71 %** | +| g32 / g64 / g128 (sgid-only body, the real guest shape) | 32/64/128 | 41.7 / 36.4 / 42.3 | ~none (g128 worse) | +| s64 / s128 (read split) | 64 / 128 | 26.1-27.6 / 16.7-16.9 | no better than t64/t128 | + +So on the M2 the win is the **thread count per threadgroup**, not splitting one thread's read chain +across SIMD groups (the split adds nothing once the group is bigger). + +## 2. Translator PoC: `TOTK_MESH_THREADS_SCALE` in `tools/totk_xlate/MeshStage.cs` + +Off unless the env is set. It scales the mesh stage's local size (`job["local"]`, every wrapper +stride, and the reflection's `threads`/`threadgroup_size`) by the factor. Verified faithful: with +scale unset, a JIT build of the translator reproduces the packaged seed's MSL for fed302d7 +byte-for-byte (148,784 bytes identical); with scale 4 the MSL compiles and declares 128 threads. + +## 3. Runtime PoC: `OOT_MESH_TRANSLATION=3` (kind `mesh_threads`) + +`nvn_mesh_translation.inc` / `nvn_mesh_tasks.inc`: mode 3 loads an external candidate whose +reflection may differ only in `threadgroup_size` / `mesh_stage.threads`, and uses the candidate's +thread count for the mesh pipeline and the draw. `probe-gpu-mesh` passes with the patch in default +mode (7,920 checks); full `unittest` 2398 OK; oot and totk runtimes build. + +## 4. In-game result on the M2: the real shader crashes above 32 threads + +fed302d7 (foliage) re-translated at 64 and at 128 threads, loaded via mode 3, run in Kokiri Forest +(720p + dynamic resolution): both crash with SIGSEGV at the same frame (660), i.e. when the scaled +mesh pipeline first draws. Crash data (mode-3 variant, 64 threads): `signal=0xb fault=0x1 +esr=0x92000006`, faulting PC in libsystem called from guest `main+0x1c4280` — a guest-side bad +pointer deref, i.e. the 64-lane run computes a wrong index (the code assumes a 32-lane workgroup). +The local size cannot simply be raised — the benchmark's model does not transfer as-is. + +## Root cause of the crash (found 2026-11-26) and the real W1 design + +The guest mesh body uses **only** `gl_SubgroupInvocationID` (0..31 per SIMD group) as its lane id and +computes its per-lane raw address as `_77 = (instance << 5) + sgid` (the `<<5` is the hardcoded +32-lane stride). At 64/128 physical threads there are 2/4 SIMD groups with the *same* sgid values, so +they run the identical body concurrently and race on the stage memory — that is the SIGSEGV. The +body has no `thread_position_in_threadgroup`-strided loops to widen (the bench body did, which is why +its t64/t128 variants won there). + +Metal limits on the M2 (measured with the bench): a mesh threadgroup may export at most **256 +vertices** and **32 KB of total mesh size** — with 10 float4/vertex that is one 128-vertex instance +per threadgroup. So multi-instance-per-threadgroup (the other way to use extra threads) is impossible +here; the only route to 64/128 threads is **flattening the lane id inside one instance**, which means +patching the body's lane-stride constant (`<<5` -> `<<6`/`<<7`) and keeping subgroup masks per-32-lane +in the translator's IR — a per-shader change that needs `probe-gpu-mesh` + screenshot equality against +the 32-thread build as acceptance. The crash repro above (variant at 64/128, SIGSEGV at frame 660) is +the acceptance test: any candidate must render fed302d7's foliage identically to the 32-thread build +*and* not crash. + +Bench limits are now printed by failing compiles on any Mac: 512 verts/group is refused (max 256), +and 256 verts x 10 float4 exceeds the 32 KB mesh-size cap on the M2. The `g*` variants (body lane id += `thread_index_in_simdgroup` only, like the real guest body) show the real shape gains nothing from +more threads without the IR lane flattening: g32 41.7 / g64 36.4 / g128 42.3 ms vs t128 16.6 ms. + +## Update (2026-11-26, later): lane-flattening pass implemented in the translator, variant loads but still faults at 64 threads + +`MeshStage.cs` gained a flattening pass (behind the existing `TOTK_MESH_THREADS_SCALE`): when the scaled +thread count is a power of two > 32, the body's subgroup lane id used for addressing is replaced by the +global thread id (`dm_lid`, passed in as a new `dm_flat` parameter; subgroup *mask* lines keep the +per-32-lane subgroup id), and the wrapper's stage header `mem[0]` is scaled by `threads/32` so one +threadgroup covers that many 32-vertex blocks (the guest grid stays sized for 32, out-of-range groups +no-op via the body's bounds check). All 32-lane strides/decompositions in the body stay at 32, so the +stage layout and export loops are unchanged. + +Validated on fed302d7: the variant generates, compiles standalone (`xcrun metal`), its reflection +equals the seed's except `threadgroup_size`/`mesh_stage.threads`, and mode 3 **loads** it +("loaded mode=3"). But running at 64 threads still SIGSEGVs the guest at `main+0x1c4280` (fault=0x1) +at world entry — the raw-pool address path in the body (not just the `_77` vertex id) still assumes 32 +lanes. Next step: trace that faulting access (watch/`mscan` on the pool table read) and flatten it too; +the acceptance stays probe-gpu-mesh + pixel-identical foliage vs the 32-thread build. + +## Isolation (2026-11-26, later still): the world-entry SIGSEGV is NOT the lane duplication +Ran the loaded 64-thread variant three ways on the PoC build (Kokiri, DRS): mode 3 with no variant dir +(32-thread fallback) = fine, 3 900 frames, no signal; mode 3 with the dir but the variant REJECTED +(hash mismatch fallback) = fine, 3 900 frames; mode 3 with the variant LOADED (both the original +unflattened `_b` and the new flattened one) = SIGSEGV (fault=0x1) right at the first fed302d7 mesh +draw at world entry, guest frame chain innermost main+0x5703c0 (a vtable callee, blr at main+0x5703b8). +So running this mesh stage at 64 threads per threadgroup crashes regardless of the body transform — +the blocker is in the 64-thread dispatch path itself (object-block launch / grid sizing / stage slot +bookkeeping at 64 threads), not in the lane flattening. Next step: map the faulting JIT pc to the exact +guest instruction (runtime translation log) or watch the slot header words during the first 64-thread +draw, and fix the dispatch; then re-run the flattened variant and check pixel-identical output. diff --git a/games/oot/runtime/game_patches_ns2.c b/games/oot/runtime/game_patches_ns2.c index ec0cced31..8551abcef 100644 --- a/games/oot/runtime/game_patches_ns2.c +++ b/games/oot/runtime/game_patches_ns2.c @@ -523,7 +523,11 @@ static void patch_oot_scale_live(Module *m, uint64_t page) { static void patch_oot_fixed_res(Module *m) { if (getenv("TOTK_EXPORT_IOS")) return; const char *e = getenv("OOT_FIXED_RES"); - if (e && !strcmp(e, "0")) { fprintf(stderr, "[oot] dynamic resolution left to the game (OOT_FIXED_RES=0)\n"); return; } + if (!e || !*e) { /* the settings panel's dynamic-resolution row (graphics-drs.txt, 1 = the game's own DRS); the environment wins */ + char word[32]; + if (runtime_setting_word("graphics-drs.txt", word, sizeof word) && !strcmp(strtok(word, " \t\r\n"), "1")) e = "0"; + } + if (e && !strcmp(e, "0")) { fprintf(stderr, "[oot] dynamic resolution left to the game (OOT_FIXED_RES=0 / graphics-drs.txt)\n"); return; } float s = runtime_handheld_mode() ? 2.0f / 3.0f : 0.75f; if (e && *e) { char *end = NULL; s = strtof(e, &end); if (!end || *end || !(s > 0 && s <= 1)) runtime_fail("OOT_FIXED_RES must be 0 or a scale in (0, 1]"); } uint32_t bits; memcpy(&bits, &s, sizeof bits); diff --git a/games/oot/runtime/settings_game.h b/games/oot/runtime/settings_game.h index 43da43393..e947ab64b 100644 --- a/games/oot/runtime/settings_game.h +++ b/games/oot/runtime/settings_game.h @@ -358,6 +358,20 @@ static TOTKSettingRow *settings_oot_profile_row(void) { } #endif #if defined(GAME_OOT) && !TARGET_OS_IPHONE +/* The game's own dynamic resolution, as on the console: with OOT_FIXED_RES=0 patch_oot_fixed_res is left unpatched and + the game lowers the 3D scale itself under load (the canvas of the resolution row stays). Off by default: the Mac pins + the scale, so the picture never changes under load. Takes effect from the next start (the patch is applied when the + guest starts). Measured on an Apple M2, 720p canvas, Kokiri Forest standing still, frame lock off, 40 s windows: + fixed 34.1 fps (p50 29.2 ms), dynamic 39.0 fps (p50 25.6 ms, the game dropped the 3D to about 683x384 at the + heaviest); in lighter scenes the game keeps the full scale, so those hold their frame rate. */ +static TOTKSettingRow *settings_oot_drs_row(void) { + return settings_row(settings_text("动态分辨率(下次启动生效)","Dynamic resolution (from the next start)"), + @[settings_text("关(固定渲染比例,默认)","Off (fixed render scale, default)"),settings_text("开(主机原样,游戏自己调)","On (as on the console, the game adjusts itself)")],@[@0,@1], + ^int{int v;return settings_read_int("graphics-drs.txt",&v)&&v==1;}, + ^(int v){settings_save_int("graphics-drs.txt",v?1:0,"dynamic resolution");}); /* read by patch_oot_fixed_res when the guest starts; OOT_FIXED_RES in the environment wins over the file */ +} +#endif +#if defined(GAME_OOT) && !TARGET_OS_IPHONE /* The resolution row: the canvas and the 3D picture together, in force at once. */ static TOTKSettingRow *settings_oot_output_row(void) { return settings_row(settings_text("分辨率","Resolution"), @@ -449,7 +463,7 @@ static NSArray *settings_rows(void) { NSString *resolution=settings_text("分辨率","Resolution"); #if defined(GAME_OOT) && !TARGET_OS_IPHONE (void)resolution; /* every resolution setting of this game is on this page (user 2026-11-09) */ - [rows addObject:settings_oot_output_row()];[rows addObject:settings_oot_upscaler_row()];[rows addObject:settings_oot_net_copy_row()];[rows addObject:settings_oot_profile_row()]; + [rows addObject:settings_oot_output_row()];[rows addObject:settings_oot_drs_row()];[rows addObject:settings_oot_upscaler_row()];[rows addObject:settings_oot_net_copy_row()];[rows addObject:settings_oot_profile_row()]; #else if(res.count<2)[rows addObject:settings_fixed(resolution,@"1080p")]; else [rows addObject:settings_row(resolution,res,resModes, diff --git a/games/oot/tests/mesh_simd_split_bench.m b/games/oot/tests/mesh_simd_split_bench.m new file mode 100644 index 000000000..edbf3c5ca --- /dev/null +++ b/games/oot/tests/mesh_simd_split_bench.m @@ -0,0 +1,83 @@ +/* PoC host for the OoT mesh-stage microbenchmark (fed302d7 scale) — measures mesh kernel GPU time + for 32/64/128 threads per threadgroup and the SIMD-split read staging, on the local Apple GPU. + Build: clang -O2 -framework Metal -framework Foundation bench.m -o bench + Run: ./bench bench.metal */ +#import +#import +#include +#include +#include +#include + +#define GROUPS 1117u /* fed302d7's real grid: 1117 x 1 x 1 */ +#define RUNS 16 /* median of 16 submits, as the 2026-11-07 meshbench */ + +static int cmp_d(const void*a,const void*b){double x=*(const double*)a,y=*(const double*)b;return xy?1:0;} + +int main(int argc,const char**argv){@autoreleasepool{ + if(argc<2){fprintf(stderr,"usage: bench \n");return 2;} + id dev=MTLCreateSystemDefaultDevice(); if(!dev){fprintf(stderr,"no Metal device\n");return 1;} + NSError*err=nil; + NSString*src=[NSString stringWithContentsOfFile:@(argv[1]) encoding:NSUTF8StringEncoding error:&err]; + if(!src){fprintf(stderr,"read: %s\n",err.description.UTF8String);return 1;} + id lib=[dev newLibraryWithSource:src options:nil error:&err]; + if(!lib){fprintf(stderr,"compile: %s\n",err.description.UTF8String);return 1;} + id queue=[dev newCommandQueue]; + /* buffers: address table (GROUPS*32*80 word addresses), raw src memory, scratch slots, hdr, tgstage */ + const size_t nt=(size_t)GROUPS*32*80; + id addr=[dev newBufferWithLength:nt*8 options:MTLResourceStorageModeShared]; + uint64_t*a=addr.contents; uint64_t seed=0xfeed302d791a4ba4ULL; + for(size_t i=0;i>7;seed^=seed<<17;a[i]=(seed%(1u<<20))*4;} + const size_t srcwords=(size_t)1<<22; /* 16 MB raw memory */ + id srcb=[dev newBufferWithLength:srcwords*4 options:MTLResourceStorageModeShared]; + memset(srcb.contents,0x5a,srcwords*4); + const uint slots=64, slotwords=4096; + id slot=[dev newBufferWithLength:(8192u+slots*slotwords)*4 options:MTLResourceStorageModeShared]; + uint32_t*hdr=(uint32_t*)slot.contents; hdr[0]=0; hdr[1]=slots-1; hdr[2]=slotwords; memset(hdr+4,0,(slots)*4); + id tgstage=[dev newBufferWithLength:(size_t)128*80*4 options:MTLResourceStorageModeShared]; + /* dummy color target for the mesh pass */ + MTLTextureDescriptor* td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:64 height:64 mipmapped:NO]; + td.usage=MTLTextureUsageRenderTarget; id target=[dev newTextureWithDescriptor:td]; + struct Var{const char*fn;int threads;int split;}; + struct Var vars[]={{"mesh_t",32,0},{"mesh_t",64,0},{"mesh_t",128,0},{"mesh_s",64,2},{"mesh_s",128,4}}; + /* instantiate templates: Metal needs explicit symbols; compile source with -DTHREADS? No: templates + instantiated below via C++-style names are not addressable from ObjC. Instead the .metal defines + fixed entry points. We expect: t32,t64,t128,s64,s128. */ + const char*names[]={"t32","t64","t128","s64","s128","g32","g64","g128"}; + int threads[]={32,64,128,64,128,32,64,128}; + printf("device: %s\nGROUPS=%u runs=%u\n",dev.name.UTF8String,GROUPS,RUNS); + printf("%-6s %8s %8s\n","variant","threads","median ms"); + for(unsigned v=0;v fn=[lib newFunctionWithName:@(names[v])]; + id fragfn=[lib newFunctionWithName:@"frag_main"]; + if(!fn){fprintf(stderr,"missing kernel %s\n",names[v]);return 1;} + MTLMeshRenderPipelineDescriptor* md=[MTLMeshRenderPipelineDescriptor new]; + md.label=@(names[v]); + md.meshFunction=fn; md.fragmentFunction=fragfn; + md.maxTotalThreadsPerMeshThreadgroup=threads[v]; + md.colorAttachments[0].pixelFormat=MTLPixelFormatBGRA8Unorm; + id ps=[dev newRenderPipelineStateWithMeshDescriptor:md options:MTLPipelineOptionNone reflection:nil error:&err]; + if(!ps){fprintf(stderr,"pipeline %s: %s\n",names[v],err.description.UTF8String);return 1;} + double ts[RUNS]; + for(unsigned r=0;r cb=[queue commandBuffer]; + id enc=[cb renderCommandEncoderWithDescriptor:rp]; + [enc setRenderPipelineState:ps]; + [enc setVertexBuffer:addr offset:0 atIndex:0]; /* buffers bound by index in kernel signature order */ + [enc setVertexBuffer:srcb offset:0 atIndex:1]; + [enc setVertexBuffer:slot offset:0 atIndex:2]; + [enc setVertexBuffer:slot offset:0 atIndex:3]; + [enc setVertexBuffer:tgstage offset:0 atIndex:4]; + [enc drawMeshThreadgroups:MTLSizeMake(GROUPS,1,1) threadsPerObjectThreadgroup:MTLSizeMake(1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(threads[v],1,1)]; + [enc endEncoding]; + [cb commit]; [cb waitUntilCompleted]; + if(cb.status!=MTLCommandBufferStatusCompleted){fprintf(stderr,"gpu err %s\n",cb.error.description.UTF8String);return 1;} + ts[r]=(cb.GPUEndTime-cb.GPUStartTime)*1000.0; + } + qsort(ts,RUNS,sizeof(double),cmp_d); + printf("%-6s %8d %8.3f\n",names[v],threads[v],ts[RUNS/2]); + } + return 0; +}} diff --git a/games/oot/tests/mesh_simd_split_bench.metal b/games/oot/tests/mesh_simd_split_bench.metal new file mode 100644 index 000000000..3d3f314b1 --- /dev/null +++ b/games/oot/tests/mesh_simd_split_bench.metal @@ -0,0 +1,120 @@ +// PoC microbenchmark: Ocarina of Time mesh-stage structure at fed302d7 scale, Apple silicon. +// GROUPS=1117 threadgroups, 128 vertices x 10 float4 exported per group, ~13 KB device scratch +// slot taken/released with atomics, and 80 raw word reads per logical lane through an 8-word +// range cache (the port's raw-read path; 61 4-wide + 19 1-wide in the real shader). +// Entries: t32/t64/t128 = THREADS threads per group, reads issued per thread (as shipped at 32); +// s64/s128 = reads of each logical lane staged once per SIMD group in threadgroup +// memory, then broadcast (split over 2 / 4 SIMD groups). +#include +#include +using namespace metal; + +struct V { float4 pos [[position]]; float4 a0 [[user(locn0)]]; float4 a1 [[user(locn1)]]; float4 a2 [[user(locn2)]]; float4 a3 [[user(locn3)]]; float4 a4 [[user(locn4)]]; float4 a5 [[user(locn5)]]; float4 a6 [[user(locn6)]]; float4 a7 [[user(locn7)]]; float4 a8 [[user(locn8)]]; }; + +struct RangeCache { // the port's raw read range cache (one 8-word block) + ulong c_lo; uint c[8]; bool hit; + uint read(device const uint* src, ulong a) { + ulong base = a & ~7ul; + if (!hit || base != c_lo) { for (int k = 0; k < 8; k++) c[k] = src[base + k]; c_lo = base; hit = true; } + return c[a & 7u]; + } +}; + +#define VMAX 128 +#define MESH_BODY(THREADS) \ + threadgroup uint my_slot; \ + if (lid == 0) { uint s; for (;;) { s = atomic_fetch_add_explicit((device atomic_uint*)hdr, 1u, memory_order_relaxed) & hdr[1]; \ + if (atomic_exchange_explicit((device atomic_uint*)(hdr + 4 + s), 1u, memory_order_relaxed) == 0) break; } my_slot = s; } \ + threadgroup_barrier(mem_flags::mem_threadgroup); \ + device uint* st = slot + 8192 + my_slot * hdr[2]; \ + for (uint i = lid; i < 3285u; i += (THREADS)) st[i] = 0u; \ + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); \ + if (lid == 0) st[0] = tg; \ + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); + +#define EXPORT_ALL(THREADS) \ + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); \ + for (uint n = lid; n < VMAX; n += (THREADS)) { \ + uint b = 36u + (n / 32u) * 800u + n % 32u; \ + V v; \ + v.pos = float4(as_type(st[b+0u]), as_type(st[b+32u]), as_type(st[b+64u]), as_type(st[b+96u])); \ + v.a0=float4(as_type(st[b+128u]),0,0,1);v.a1=float4(as_type(st[b+160u]),0,0,1);v.a2=float4(as_type(st[b+192u]),0,0,1);v.a3=float4(as_type(st[b+224u]),0,0,1);v.a4=float4(as_type(st[b+256u]),0,0,1);v.a5=float4(as_type(st[b+288u]),0,0,1);v.a6=float4(as_type(st[b+320u]),0,0,1);v.a7=float4(as_type(st[b+352u]),0,0,1);v.a8=float4(as_type(st[b+384u]),0,0,1); \ + out.set_vertex(n, v); } \ + out.set_primitive_count(64u); \ + if (lid == 0) atomic_store_explicit((device atomic_uint*)(hdr + 4 + my_slot), 0u, memory_order_relaxed); + +#define KERNEL_T(NAME, THREADS) \ +[[mesh]] void NAME(device const uint* addr_table [[buffer(0)]], device const uint* src [[buffer(1)]], \ + device uint* slot [[buffer(2)]], device uint* hdr [[buffer(3)]], \ + uint tg [[threadgroup_position_in_grid]], uint lid [[thread_position_in_threadgroup]], \ + mesh out [[stage_out]]) { \ + MESH_BODY(THREADS) \ + constexpr int READS = 80 * 32 / (THREADS); \ + RangeCache rc; rc.hit = false; \ + float acc = 0; \ + uint logical = lid * 32 / (THREADS); \ + for (int k = 0; k < READS; k++) \ + acc += as_type(rc.read(src, addr_table[(tg * 32 + logical) * 80 + k])); \ + st[100 + lid] = as_type(acc); \ + EXPORT_ALL(THREADS) \ +} + +// split variant: THREADS = 2/4 SIMD groups; the 80 reads of the logical lanes a SIMD group owns are +// issued once and staged in threadgroup memory; every lane then reads the staged words. +#define KERNEL_S(NAME, THREADS) \ +[[mesh]] void NAME(device const uint* addr_table [[buffer(0)]], device const uint* src [[buffer(1)]], \ + device uint* slot [[buffer(2)]], device uint* hdr [[buffer(3)]], \ + uint tg [[threadgroup_position_in_grid]], uint lid [[thread_position_in_threadgroup]], \ + mesh out [[stage_out]]) { \ + constexpr int SIMD = (THREADS) / 32; \ + constexpr int READS = 80 * 32 / (THREADS); \ + constexpr int LANES_PER_GROUP = 32 / SIMD; \ + threadgroup uint tgstage[2560]; /* SIMD groups x LANES_PER_GROUP x 80 words <= 10 KB */ \ + MESH_BODY(THREADS) \ + uint group = lid / 32, in_group = lid % 32; \ + uint lane0 = group * LANES_PER_GROUP; \ + RangeCache rc; rc.hit = false; \ + float acc = 0; \ + for (int k = 0; k < READS; k++) { \ + uint ll = lane0 + (in_group % LANES_PER_GROUP); \ + uint w = rc.read(src, addr_table[(tg * 32 + ll) * 80 + k]); \ + tgstage[group * LANES_PER_GROUP * 80 + (in_group % LANES_PER_GROUP) * 80 + k] = w; \ + acc += as_type(w); } \ + threadgroup_barrier(mem_flags::mem_threadgroup); \ + float acc2 = 0; \ + for (int k = 0; k < READS; k++) acc2 += as_type(tgstage[group * LANES_PER_GROUP * 80 + (in_group % LANES_PER_GROUP) * 80 + k]); \ + st[100 + lid] = as_type(acc + acc2); \ + EXPORT_ALL(THREADS) \ +} + +KERNEL_T(t32, 32) +KERNEL_T(t64, 64) +KERNEL_T(t128, 128) +KERNEL_S(s64, 64) +KERNEL_S(s128, 128) + +struct FOut { float4 c [[color(0)]]; }; +[[fragment]] FOut frag_main(V v [[stage_in]]) { return FOut{ float4(1.0) }; } + +// sgid-only variant: the body's lane id is thread_index_in_simdgroup only (as in the real guest +// mesh body, which also hardcodes a 32-lane stride), so extra threads per threadgroup duplicate +// the work instead of splitting it. Measured on the M2: g32 41.7, g64 36.4, g128 42.3 ms — +// the real shader shape gains almost nothing from more threads without an IR-level lane flattening, +// while the lid-strided bench body wins big (t128 16.6 ms, -69 %). +#define KERNEL_G(NAME, THREADS) \ +[[mesh]] void NAME(device const uint* addr_table [[buffer(0)]], device const uint* src [[buffer(1)]], \ + device uint* slot [[buffer(2)]], device uint* hdr [[buffer(3)]], \ + uint tg [[threadgroup_position_in_grid]], uint lid [[thread_position_in_threadgroup]], \ + uint sgid [[thread_index_in_simdgroup]], \ + mesh out [[stage_out]]) { \ + MESH_BODY(THREADS) \ + RangeCache rc; rc.hit = false; \ + float acc = 0; \ + for (int k = 0; k < 80; k++) \ + acc += as_type(rc.read(src, addr_table[(tg * 32 + sgid) * 80 + k])); \ + st[100 + sgid] = as_type(acc); \ + EXPORT_ALL(THREADS) \ +} +KERNEL_G(g32, 32) +KERNEL_G(g64, 64) +KERNEL_G(g128, 128) diff --git a/games/oot/tools/totk_xlate/MeshStage.cs b/games/oot/tools/totk_xlate/MeshStage.cs index fbcecf187..e06b8c36e 100644 --- a/games/oot/tools/totk_xlate/MeshStage.cs +++ b/games/oot/tools/totk_xlate/MeshStage.cs @@ -9,7 +9,8 @@ sealed class MeshStage { readonly string kind; - readonly int threads, payload, maxV, maxP; + int threads; readonly int payload, maxV, maxP; // threads is scaled by TOTK_MESH_THREADS_SCALE (PoC, 2026-11-26) + int flatShift; // W1 flattening (PoC): when threads>32, the body's 32-lane stride becomes 2^(5+flatShift) and the lane id becomes the global thread id (dm_lid); subgroup masks stay per-32-lane readonly bool task, deviceAllowed; // deviceAllowed: the request may say stage_device=false (tests reading the stage memory from a compute wrapper) readonly List<(int n,int c)> vertex = new(), primitive = new(); readonly int[] layout; @@ -54,6 +55,16 @@ public MeshStage(JsonObject rq,JsonObject job,string outDir) { kind=(string)rq["stage"]; threads=BitConverter.ToUInt16(ctl,0x58);payload=BitConverter.ToUInt16(ctl,0x5a); deviceAllowed=!(rq["stage_device"] is JsonValue sd && sd.TryGetValue(out bool allowed) && !allowed); if(threads<1||threads>1024||code.Length<0x80)throw new Exception("invalid task/mesh control"); + { // PoC (2026-11-26, off unless set): run the mesh stage with more threads per threadgroup. The meshbench + // (games/oot/tests/mesh_simd_split_bench) measured on an M2 at fed302d7 scale: 32 -> 128 threads per + // threadgroup is 49.9 -> 14.4 ms (-71 %) for the same output. job["local"] and every wrapper stride + // follow, so the generated body stays consistent; the reflection reports the scaled count. + var e = Environment.GetEnvironmentVariable("TOTK_MESH_THREADS_SCALE"); + if (!string.IsNullOrEmpty(e)) { int k = int.Parse(e.Trim()); if (k > 1) { threads = Math.Min(threads * k, 1024); rq["local"] = new JsonArray(threads, 1, 1); } } + if (threads > 32 && (threads & (threads - 1)) == 0 && threads % 32 == 0 && threads <= 512) { + flatShift = 0; while ((32 << flatShift) < threads) flatShift++; // stride shift 5 -> 5+flatShift + } + } int output=16+Align(payload,16), prim; if(kind=="ts") {prim=output+payload;shared=output+Align(payload,4);} else { @@ -88,7 +99,7 @@ public MeshStage(JsonObject rq,JsonObject job,string outDir) { string path=Path.Combine(outDir,(string)rq["variant"]+".mesh.code");File.WriteAllBytes(path,code[0x80..]);job["code"]=path; job["local"]=new JsonArray(threads,1,1);job["shared"]=shared;job["stage_memory"]=new JsonArray(layout.Select(x=>(JsonNode)JsonValue.Create(x)).ToArray()); } - public JsonObject Reflection()=>new(){["kind"]=kind,["threads"]=threads,["payload"]=payload,["task"]=task,["device"]=Device,["byte_stores"]=ByteStores}; + public JsonObject Reflection()=>new(){["kind"]=kind,["threads"]=threads,["payload"]=payload,["task"]=task,["device"]=Device,["byte_stores"]=ByteStores}; // flat_shift stays internal: the mode-3 loader requires the candidate reflection to equal the original except threadgroup_size / mesh_stage.threads static List Params(string t) { var r=new List();int depth=0,at=0; for(int i=0;i".Contains(c))depth--;} @@ -118,6 +129,25 @@ public string Wrap(string msl) { } Device=device; src=ByteStores_(src); + int flatLane=0, flatStride=0; + if (flatShift > 0) { + // W1 lane flattening (PoC): the guest body addresses the stage with (instance << 5) + subgroup-lane. + // With threads = 2^(5+flatShift) per group, use the global thread id (dm_lid) as the lane and scale the + // instance stride << 5 -> << (5+flatShift), so every thread owns a distinct vertex and no two threads race. + // Subgroup masks (lines containing "Mask") keep the per-32-lane subgroup id: their semantics are per SIMD group. + string sgid = pars.Select(p => Regex.Match(p, @"(uint3?)\s+(\w+)\s*\[\[thread_index_in_simdgroup\]\]$")) + .Where(x => x.Success).Select(x => x.Groups[2].Value).FirstOrDefault(); + if (sgid != null) { + src = Regex.Replace(src, @"dm_stage_body\(([^)]*)\)", m => $"dm_stage_body({m.Groups[1].Value}, uint dm_flat)"); // the flat lane comes in as a parameter + var lines = src.Split('\n').ToList(); + for (int i = 0; i < lines.Count; i++) { + if (lines[i].Contains("Mask") || lines[i].Contains("dm_stage_body(")) continue; + if (lines[i].Contains(sgid)) { lines[i] = lines[i].Replace(sgid, "dm_flat"); flatLane++; } + } + src = string.Join("\n", lines); + flatStride = 0; // strides stay x32: each thread owns vertex (mem[0]<<5)+lid, and the wrapper lets one group cover threads/32 blocks + } + } string lid="dm_lid",tg="dm_tg";var extras=new List(); foreach(string attr in new[]{"thread_position_in_threadgroup","threadgroup_position_in_grid"}){ var t=pars.Select(p=>Regex.Match(p,@"(uint3?)\s+(\w+)\s*\[\[("+attr+@")\]\]$")).FirstOrDefault(x=>x.Success); @@ -125,7 +155,7 @@ public string Wrap(string msl) { if(t==null)extras.Add($"uint {name} [[{attr}]]");if(attr=="thread_position_in_threadgroup")lid=name;else tg=name; } int pay=(payload+3)/4,output=layout[2]/4,prim=layout[3],input=4; - string call=$"dm_stage_body({string.Join(", ",names.Append(mem))});"; + string call=$"dm_stage_body({string.Join(", ",names.Append(mem))}{(flatShift>0?", "+lid:"")});"; string bar=device?"threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device);":"threadgroup_barrier(mem_flags::mem_threadgroup);"; string start=device ?$" threadgroup uint dm_slot_tg;\n if({lid}==0u){{ uint s, tries=0u; for(;;){{ s=atomic_fetch_add_explicit((device atomic_uint*)dm_scratch,1u,memory_order_relaxed)&dm_scratch[1]; if(atomic_exchange_explicit((device atomic_uint*)(dm_scratch+{ScratchFlagsWord}u+s),1u,memory_order_relaxed)==0u)break; if(++tries=={ScratchSpinLimit}u){{atomic_fetch_add_explicit((device atomic_uint*)(dm_scratch+{ScratchForcedWord}u),1u,memory_order_relaxed);break;}} }} dm_slot_tg=s; }}\n threadgroup_barrier(mem_flags::mem_threadgroup);\n device spvUnsafeArray& {mem}=*reinterpret_cast*>(dm_scratch+{ScratchSlotsWord}u+dm_slot_tg*dm_scratch[2]);\n for(uint i={lid}; i<{words}u;i+={threads}u) {mem}[i]=0u;\n {bar}\n" @@ -154,7 +184,8 @@ public string Wrap(string msl) { string sets=string.Concat(vn.Select(n=>$"v.{(n<0?"position":"a"+n)}={Vec(vertex,n)};\n")); string psets=string.Concat(pn.Select(n=>$"p.p{n}={Vec(primitive,n)};\n")); string Entry(string name,bool gl){ - string fill=task?$"for(uint i={lid};i<{pay}u;i+={threads}u){mem}[{input}u+i]=dm_payload.w[i];\n{bar}\nif({lid}==0u){{{mem}[0]={tg};{mem}[{input}]={tg};}}\n":$"if({lid}==0u){mem}[0]=dm_first[0]+{tg};\n"; + string blockscale=flatShift>0?"*"+(threads/32).ToString():""; + string fill=task?$"for(uint i={lid};i<{pay}u;i+={threads}u){mem}[{input}u+i]=dm_payload.w[i];\n{bar}\nif({lid}==0u){{{mem}[0]={tg};{mem}[{input}]={tg};}}\n":$"if({lid}==0u){mem}[0]=dm_first[0]+{tg}{blockscale};\n"; return $"[[mesh]] void {name}({sig}, dm_mesh_t dm_out, "+(task?"const object_data dm_payload_t& dm_payload [[payload]]":first)+scratch+$")\n{{\n{start}{fill}{bar}\n{call}\n{bar}\nuint np=min({mem}[{prim/4}]>>24,{maxP}u);\nif({lid}==0u)dm_out.set_primitive_count(np);\nfor(uint n={lid};n<{maxV}u;n+={threads}u){{uint b={output}u+(n/32u)*{vstride}u+n%32u; dm_vertex_t v;\n{sets}"+(gl?"v.position.z=fma(v.position.z,0.5,v.position.w*0.5);\n":"")+"dm_out.set_vertex(n,v);}\n"+(pn.Count>0?$"for(uint n={lid};n>2]>>((at&3u)*8u))&255u);}}\n{release}}}\n"; } return src+"\n"+head+Entry("main0",true)+"\n"+Entry("main0_z",false); diff --git a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_tasks.inc b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_tasks.inc index 0b31a27d9..e133918f2 100644 --- a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_tasks.inc +++ b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_tasks.inc @@ -1,7 +1,7 @@ /* NVN2 task/mesh: original control metadata -> native Metal object/mesh stages. * API/layout reference: ChiefSZ13/nxnative ee9b7765, MIT. Pipeline creation is * synchronous here: every requested draw must execute with its complete stages. */ -static struct { int on,profile_grid; NvShader *ts,*ms,*fs; uint32_t first,count; uint64_t first_gpu,indirect_gpu; } g_mtk; +static struct { int on,profile_grid,tr_selected; NvShader *ts,*ms,*fs; uint32_t first,count; uint64_t first_gpu,indirect_gpu; } g_mtk; /* A mesh shader with no task shader launches its workgroups through its own object function, MTK_OBJECT_BLOCK at a time (MeshStage.cs ObjectEntry / ObjectBlock / ObjectCountBuffer, the same constants; after nxnative 09dcb627, MIT): Metal holds a mesh grid to 1024 threadgroups, and Ocarina of Time's foliage drew up to 1,238 in one indirect draw here (1,771 at @@ -161,7 +161,11 @@ static NSString *mtk_archive_key(NvShader *ts,NvShader *ms,NvShader *fs,const mt /* The mesh pipeline for a filled key, on any thread (the first draw, the warm-up, or the packaging fill); nil and *error when Metal refuses it. Taken from the pipeline archive when its file holds it (*from_archive = 1); otherwise compiled, and a warm-up or fill thread writes it to the archive (par_add), as pso_new does for render pipelines. */ -static id mtk_build(NvShader *ts,NvShader *ms,NvShader *fs,const mtk_pso_key *key,id base,int pack,NSError **error,int *from_archive) { +static int mtk_eff_mesh_threads(NvShader *ms,int selected){ // PoC mode 3: the selected variant's thread count + int t=(selected?g_mtk.tr_selected:selected)==3?mtk_translation_threads():0; + return t>0?t:ms->mesh_threads; +} +static id mtk_build(NvShader *ts,NvShader *ms,NvShader *fs,const mtk_pso_key *key,id base,int pack,NSError **error,int *from_archive,int selected) { if(from_archive)*from_archive=0; id mesh=mtk_mesh_fn_base(ms,fs,base),packedFs=nil; if(pack)mesh=mtk_pack_varyings(ms,fs,mesh,key->p.dfmt==0,&packedFs); // nvn_mesh_pack.inc: fewer declared vec4 slots, same values @@ -169,7 +173,7 @@ static id mtk_build(NvShader *ts,NvShader *ms,NvShader * MTLMeshRenderPipelineDescriptor *m=[MTLMeshRenderPipelineDescriptor new]; m.label=[NSString stringWithFormat:@"task=%s mesh=%s fs=%s",ts?ts->key:"none",ms->key,fs?fs->key:"none"]; if(g_mtk_geometry)mesh=mtk_geo_function(ms,fs,mesh); - m.meshFunction=mtk_empty_export_fn(mesh,ms);m.fragmentFunction=d.fragmentFunction;m.maxTotalThreadsPerMeshThreadgroup=ms->mesh_threads; + m.meshFunction=mtk_empty_export_fn(mesh,ms);m.fragmentFunction=d.fragmentFunction;m.maxTotalThreadsPerMeshThreadgroup=mtk_eff_mesh_threads(ms,selected); if(!m.meshFunction.label.length)m.meshFunction.label=@(ms->key); if(ts){m.objectFunction=ts->fn;m.payloadMemoryLength=(ts->mesh_payload+15u)&~15u;m.maxTotalThreadsPerObjectThreadgroup=ts->mesh_threads;} else if(mtk_blocks_on(ms)){m.objectFunction=ms->ofn;m.payloadMemoryLength=16;m.maxTotalThreadsPerObjectThreadgroup=1;} // its workgroups in blocks of MTK_OBJECT_BLOCK (mtk_encode) @@ -210,7 +214,7 @@ static id mtk_build(NvShader *ts,NvShader *ms,NvShader * } static id mtk_pso(NvProg *raster) { NvShader *ts=g_mtk.ts,*ms=g_mtk.ms,*fs=raster->sh[1]; - int selected=0;id base=mtk_translation_function(ms,&selected);g_mesh_translation_hits[selected]++; + int selected=0;id base=mtk_translation_function(ms,&selected);g_mesh_translation_hits[selected]++;g_mtk.tr_selected=selected; static int stats=-1;if(stats<0){const char*s=getenv("OOT_MESH_TRANSLATION_STATS");stats=s&&atoi(s);} if(stats&&g_mesh_translation_hits[selected]%600==1)MLOG("[mesh-translation] selected mode=%d draws=%llu loaded=%llu",selected,g_mesh_translation_hits[selected],g_mesh_translation_loaded[selected]); mtk_pso_key key; memset(&key,0,sizeof key); @@ -221,7 +225,7 @@ static id mtk_pso(NvProg *raster) { key.variant=mtk_empty_export_on()|(g_mtk_geometry?2u:0u)|(pack?4u:0u)|((uint64_t)selected<<3); id ps=hm_get_id(&g_mtk_cache,&key);if(ps)return ps; if(nvn_hm_get(&g_mtk_failed,&key))return nil; // refused earlier this run: skipped again without compiling (the patch above) - uint64_t build_t0=bp_now();NSError *error=nil;int archived=0;ps=mtk_build(ts,ms,fs,&key,base,pack,&error,&archived); + uint64_t build_t0=bp_now();NSError *error=nil;int archived=0;ps=mtk_build(ts,ms,fs,&key,base,pack,&error,&archived,selected); /* Counted with the render pipelines made at a draw, as pso_get counts them (archive hits included): until 2026-11-15 a mesh pipeline built here was missing from the long-frame line's and the per-frame record's pipeline count and time (an OOT world entry: 32 mesh pipelines, 75 s, none of it counted). */ @@ -265,7 +269,7 @@ static id mtk_row_build(mtk_row *r,NSError **error,int * int selected=0;id base=mtk_translation_function(r->ms,&selected); int pack=mtk_pack_on()&&!((r->key.p.a2c&PSO_HDR)&&r->fs&&r->fs->hdr_fn); r->key.variant=(pack?4u:0u)|((uint64_t)selected<<3); - return mtk_build(r->ts,r->ms,r->fs,&r->key,base,pack,error,from_archive); + return mtk_build(r->ts,r->ms,r->fs,&r->key,base,pack,error,from_archive,selected); } static void mtk_warm_row(NSArray *c,NSMutableDictionary *dict) { if(!mtk_device_compiles()){ // the phone's fallback: its M rows are not compiled there @@ -339,7 +343,7 @@ static void mtk_encode(id en) { g_args_dirty[4]=1;encode_args((id)en,ms,4,1);enc_r_vbuf(en,29,first); enc_r_vbuf(en,MTK_SCRATCH_BUFFER,mtk_scratch_gpu());mtk_scratch_report(); // device stage memory of the mesh shaders the translator put there (MeshStage.cs) if(mtk_geo_selected(g_mtk.fs))enc_r_vbuf(en,30,g_mtk_geometry?g_mtk_geometry.gpuAddress:zero_bank_gpu()); - int timing=ms_time_begin(en,ms->key,ts?ts->key:NULL,g_mtk.fs?g_mtk.fs->key:NULL,g_mtk.indirect_gpu,g_mtk.first,g_mtk.count,ms->mesh_threads,g_mtk.profile_grid); + int mt=mtk_eff_mesh_threads(ms,g_mtk.tr_selected);int timing=ms_time_begin(en,ms->key,ts?ts->key:NULL,g_mtk.fs?g_mtk.fs->key:NULL,g_mtk.indirect_gpu,g_mtk.first,g_mtk.count,mt,g_mtk.profile_grid); if(blocks){ /* The object stage reads the workgroup count from word 0 of the grid record (an indirect draw's converted record, a direct draw's copy) and each object threadgroup launches its block. An indirect draw's count is known only on the @@ -349,16 +353,16 @@ static void mtk_encode(id en) { if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_OBJECT_ADDRESS,.u={MTK_OBJECT_COUNT_BUFFER,count}},0);else[g_ot setAddress:count atIndex:MTK_OBJECT_COUNT_BUFFER]; atomic_fetch_add(&g_mtk_block_draws,1); if(groups){ - if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH,.u={groups,1,ms->mesh_threads}},1); - else [en drawMeshThreadgroups:MTLSizeMake(groups,1,1) threadsPerObjectThreadgroup:MTLSizeMake(1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(ms->mesh_threads,1,1)]; + if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH,.u={groups,1,mt}},1); + else [en drawMeshThreadgroups:MTLSizeMake(groups,1,1) threadsPerObjectThreadgroup:MTLSizeMake(1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(mt,1,1)]; } } else if(g_mtk.indirect_gpu){ - if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH_INDIRECT,.u={g_mtk.indirect_gpu,ts?ts->mesh_threads:1,ms->mesh_threads}},1); - else [en drawMeshThreadgroupsWithIndirectBuffer:g_mtk.indirect_gpu threadsPerObjectThreadgroup:MTLSizeMake(ts?ts->mesh_threads:1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(ms->mesh_threads,1,1)]; + if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH_INDIRECT,.u={g_mtk.indirect_gpu,ts?ts->mesh_threads:1,mt}},1); + else [en drawMeshThreadgroupsWithIndirectBuffer:g_mtk.indirect_gpu threadsPerObjectThreadgroup:MTLSizeMake(ts?ts->mesh_threads:1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(mt,1,1)]; } - else if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH,.u={g_mtk.count,ts?ts->mesh_threads:1,ms->mesh_threads}},1); - else [en drawMeshThreadgroups:MTLSizeMake(g_mtk.count,1,1) threadsPerObjectThreadgroup:MTLSizeMake(ts?ts->mesh_threads:1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(ms->mesh_threads,1,1)]; + else if(rs_using(en))rs_put((nvn_encode_packet){.op=RS_DRAW_MESH,.u={g_mtk.count,ts?ts->mesh_threads:1,mt}},1); + else [en drawMeshThreadgroups:MTLSizeMake(g_mtk.count,1,1) threadsPerObjectThreadgroup:MTLSizeMake(ts?ts->mesh_threads:1,1,1) threadsPerMeshThreadgroup:MTLSizeMake(mt,1,1)]; ms_time_stamp(en,timing,1); } /* Mesh draws in render passes of their own on Apple GPUs before the Apple9 family (M1 / M2), 2026-11-16. On an M1 Pro the diff --git a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_translation.inc b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_translation.inc index ab6e11475..0d13fd888 100644 --- a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_translation.inc +++ b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mesh_translation.inc @@ -4,11 +4,13 @@ * External generated game shaders remain outside the source checkout. */ static NSMutableDictionary *g_mesh_translation_info; static uint64_t g_mesh_translation_hits[3],g_mesh_translation_loaded[3]; +static _Atomic int g_mesh_translation_threads; // PoC mode 3 (2026-11-26): candidate threadgroup_size[0] when a mesh_threads variant is selected static int mtk_translation_mode(void) { int v=atomic_load(&g_mesh_translation); if(v<0){const char*s=getenv("OOT_MESH_TRANSLATION");v=s?atoi(s):0;atomic_store(&g_mesh_translation,v);} - return !TARGET_OS_IPHONE&&v>=1&&v<=2?v:0; + return !TARGET_OS_IPHONE&&v>=1&&v<=3?v:0; } +int mtk_translation_threads(void) { return atomic_load(&g_mesh_translation_threads); } // 0 = not a threads variant static NSString *mtk_translation_sha(NSData*d) { if(!d)return nil;unsigned char h[32];char hex[65]={0};CC_SHA256(d.bytes,(CC_LONG)d.length,h); for(int i=0;i<32;i++)snprintf(hex+2*i,3,"%02x",h[i]);return @(hex); @@ -26,7 +28,7 @@ static id mtk_translation_function(NvShader*ms,int *selected) { NSData*proof=[NSData dataWithContentsOfFile:[stem stringByAppendingString:@".variant.json"]]; NSDictionary*j=proof&&proof.length<32768?[NSJSONSerialization JSONObjectWithData:proof options:0 error:nil]:nil; if(![j isKindOfClass:NSDictionary.class]||[j[@"abi"]intValue]!=1||![j[@"key"]isEqual:@(ms->key)]|| - ![j[@"kind"]isEqual:mode==1?@"mesh_bounds":@"raw_span"])return ms->fn; + ![j[@"kind"]isEqual:mode==1?@"mesh_bounds":mode==2?@"raw_span":@"mesh_threads"])return ms->fn; NSData*src=[NSData dataWithContentsOfFile:[stem stringByAppendingString:@".metal"]]; NSData*ref=[NSData dataWithContentsOfFile:[stem stringByAppendingString:@".json"]]; NSData*original=[sh_src(ms)dataUsingEncoding:NSUTF8StringEncoding]; @@ -41,6 +43,13 @@ static id mtk_translation_function(NvShader*ms,int *selected) { NSDictionary*o=oref?[NSJSONSerialization JSONObjectWithData:oref options:0 error:nil]:nil; if(![r isKindOfClass:NSMutableDictionary.class]||![o isKindOfClass:NSDictionary.class])return ms->fn; if(mode==2){if([r[@"raw_read_span_abi"]intValue]!=1)return ms->fn;[r removeObjectForKey:@"raw_read_span_abi"];} + if(mode==3){ // PoC: the candidate runs the mesh stage at another thread count; threadgroup_size may differ + if(![r[@"threadgroup_size"]isKindOfClass:NSArray.class]||[r[@"threadgroup_size"]count]<1)return ms->fn; + atomic_store(&g_mesh_translation_threads,[r[@"threadgroup_size"][0]intValue]); + [r removeObjectForKey:@"threadgroup_size"]; + NSMutableDictionary *o2=[o mutableCopy];[o2 removeObjectForKey:@"threadgroup_size"];o=(NSDictionary *)o2; + if([r[@"mesh_stage"]isKindOfClass:NSDictionary.class]){[(NSMutableDictionary *)r[@"mesh_stage"] removeObjectForKey:@"threads"];id mo=o[@"mesh_stage"];if([mo isKindOfClass:NSDictionary.class]){NSMutableDictionary *mo2=[mo mutableCopy];[mo2 removeObjectForKey:@"threads"];[o2 setObject:mo2 forKey:@"mesh_stage"];}} + } if(![r isEqual:o]){MLOG("[mesh-translation] binding fallback mode=%d %.16s",mode,ms->key);return ms->fn;} NSString*source=[[NSString alloc]initWithData:src encoding:NSUTF8StringEncoding];NSError*error=nil; idlib=source?variant_library(source,&error):nil;idfn=lib?[lib newFunctionWithName:ms->fn.name]:nil; diff --git a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mtl.m b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mtl.m index 286af5aef..08d2d078a 100644 --- a/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mtl.m +++ b/games/totk/third_party/d2r_gfx/gfx/nvn/nvn_mtl.m @@ -1595,16 +1595,38 @@ static void pool_input_invalidate(uint64_t a,uint64_t n) { static uint64_t g_pend_lo[PEND_MAX], g_pend_hi[PEND_MAX]; static int g_npend; static const void *g_pend_src[PEND_MAX]; static uint8_t g_pend_kind[PEND_MAX]; // TOTK: 0 = inline update (host copy of the data), 1 = GPU copy (guest source address) static uint64_t g_pend_fence[PEND_MAX], g_pend_over_fence; +/* Union bounds of g_pend[0..g_npend) (lo min / hi max), maintained on append (pend_note) and recomputed at the + submission-start compaction (pend_begin): a query range outside [span_lo, span_hi) overlaps no entry, completed + ones included, so pend_overlay_x / pend_hits can skip the whole scan. TOTK_PEND_SPAN=0 disables (A/B). */ +static uint64_t g_pend_span_lo = UINT64_MAX, g_pend_span_hi; +static _Atomic int g_pend_span = -1; +static int pend_span_on(void) { + int v = atomic_load(&g_pend_span); + if (v < 0) { const char *e = getenv("TOTK_PEND_SPAN"); v = !(e && !atoi(e)); atomic_store(&g_pend_span, v); } + return v; +} static int g_usnap_pend_n; // pend entries present when this submission's uniform snapshot was dispatched: all a snapshot copy may look at (the replay appends entries concurrently with the helper threads) static _Atomic uint64_t g_usnap_faults; // snapshot copies that hit an inaccessible address (guarded, the entry is dropped) // TOTK: a write stays pending until the GPU completed its submission; over_fence: a submission whose writes did not fit the table static uint64_t g_pend_reuse_done; static _Atomic int g_pend_arena_pin = 1; static uint64_t g_pend_arena_hazards; static int pend_over(void) { return g_pend_over_fence > g_done; } -static int pend_hits(uint64_t a, uint64_t n) { if (pend_over()) return 1; for (int i = 0; i < g_npend; i++) if (a < g_pend_hi[i] && a + n > g_pend_lo[i]) return 1; return 0; } +static int pend_hits(uint64_t a, uint64_t n) { + if (pend_over()) return 1; + if (pend_span_on() && g_npend && (a + n <= __atomic_load_n(&g_pend_span_lo, __ATOMIC_ACQUIRE) || a >= __atomic_load_n(&g_pend_span_hi, __ATOMIC_ACQUIRE))) return 0; + for (int i = 0; i < g_npend; i++) if (a < g_pend_hi[i] && a + n > g_pend_lo[i]) return 1; + return 0; +} static void pend_note(uint64_t dst, uint64_t n, const void *src, int kind) { g_pool_write_epoch++;pool_input_invalidate(dst,n); - if (g_npend < PEND_MAX) { g_pend_lo[g_npend] = dst; g_pend_hi[g_npend] = dst + n; g_pend_src[g_npend] = src; g_pend_kind[g_npend] = (uint8_t)kind; g_pend_fence[g_npend] = g_fence + 1; g_npend++; } + if (g_npend < PEND_MAX) { + g_pend_lo[g_npend] = dst; g_pend_hi[g_npend] = dst + n; g_pend_src[g_npend] = src; g_pend_kind[g_npend] = (uint8_t)kind; g_pend_fence[g_npend] = g_fence + 1; + if (pend_span_on()) { + if (dst < __atomic_load_n(&g_pend_span_lo, __ATOMIC_RELAXED)) __atomic_store_n(&g_pend_span_lo, dst, __ATOMIC_RELEASE); + if (dst + n > __atomic_load_n(&g_pend_span_hi, __ATOMIC_RELAXED)) __atomic_store_n(&g_pend_span_hi, dst + n, __ATOMIC_RELEASE); + } + g_npend++; + } else g_pend_over_fence = g_fence + 1; } /* Submission start: writes of earlier submissions the GPU has not completed yet stay in the table. The game updates @@ -1619,6 +1641,11 @@ static void pend_begin(void) { n++; } g_npend = n; + if (pend_span_on()) { // the entries left after the compaction + uint64_t lo = UINT64_MAX, hi = 0; + for (int i = 0; i < n; i++) { if (g_pend_lo[i] < lo) lo = g_pend_lo[i]; if (g_pend_hi[i] > hi) hi = g_pend_hi[i]; } + __atomic_store_n(&g_pend_span_lo, lo, __ATOMIC_RELEASE); __atomic_store_n(&g_pend_span_hi, hi, __ATOMIC_RELEASE); + } } /* TOTK (2026-10-15): uniform contents as of the submit call. A submission is replayed inside nvnQueueSubmitCommands for several milliseconds; on the console the call returns at once and the GPU reads the constants soon after. Meanwhile the @@ -3116,6 +3143,11 @@ static void pend_overlay_x(uint64_t a, uint8_t *out, size_t n, int depth, int wa int first = pend_skip_on() ? pend_first_live(npend, done) : 0; if (pend_skip_check_on()) for (int i = 1; i < npend; i++) if (g_pend_fence[i] < g_pend_fence[i - 1]) MDIE("pending writes out of fence order at %d: %llu after %llu", i, (unsigned long long)g_pend_fence[i], (unsigned long long)g_pend_fence[i - 1]); + if (pend_span_on() && npend && (a + n <= __atomic_load_n(&g_pend_span_lo, __ATOMIC_ACQUIRE) || a >= __atomic_load_n(&g_pend_span_hi, __ATOMIC_ACQUIRE))) { + _Atomic uint64_t *c = g_pov + (wait ? 0 : 4); // outside the table's union bounds: nothing to scan or apply + atomic_fetch_add_explicit(&c[0], 1, memory_order_relaxed); + return; + } uint64_t c_hit = 0; for (int i = first; i < npend; i++) { uint64_t lo = g_pend_lo[i], hi = g_pend_hi[i];