mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
Ocarina of Time runs at full resolution, and its dynamic resolution no longer sits at its floor: 128-bit raw global loads are one vector load (GPU 16.3 -> 12.6 ms on an M4 Pro), occlusion conditions are read once landed (-0.6 ms), a frame-start timestamp from a slot its encoder never wrote is dropped, and a wait on a queued WRITE event signal is released at encode (chain 89f44f9b6bb0)
- Translator: LDG.64/.128 through the pool table load a uvecN once (GlobalMemoryVector) instead of one word at a time; the mesh shaders' 128-bit raw loads were about 3.1 ms of Ocarina's frame - nvn_mtl.m: a samples-passed condition is evaluated from its landed result (Ocarina: 1.48 million conditions on its route, 42% false, all drawn before) - nvn_mtl.m rep_ticks: a heap time from before its submission began encoding is a slot no encoder wrote (an empty encoder writes no relaxed timestamp); Ocarina's frame-start TIMESTAMP_TOP read 1.7 s early and its controller kept 683x384 - nvn_queue.inc: an event wait the last in-flight WRITE signal satisfies is released when encoded (the one Metal queue orders it after the writer); waiting for completion idled the GPU about 2 ms a frame, counted as GPU time. ADD signals still wait. t_wait_event checks both - Ocarina's dynamic resolution: a frame step rule may name other functions by fingerprint (MATCH_FRAME_STEP others, ctx.others, ctx.capabilities); Ocarina's stub makes its level function return 0 (1536x864) unless the launcher's Dynamic resolution (DM_DYNAMIC_RESOLUTION, state page +0x40) is on. M4 Pro: 48.1 fps at full size (GPU p50 15.0 ms); 60 fps with the game's own choice - GPU clock ruled out (mactop: about 1,562 MHz at 94% active either way); a separate display queue was tried and dropped (worse pacing) Regression: not run (the user chose to push after the Ocarina A/B); Ocarina kokiri-deck bench only
This commit is contained in:
1 parent
651369bc7e
commit
04419bc255
36 files changed
+497
-52
No files matched your search
@@ -11,6 +11,7 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se
|
||||
| `sys_resource 0x3000000` | `game.tsv` | 48 MB, as the NPDM declares |
|
||||
| `render_cond on` | `game.tsv` | agl clears a copy of the prepass depth again under a render condition the console skips. Run unconditionally, the opaque pass's `EQUAL` test fails everywhere ([PR 1299](https://github.com/seedds/nxnative/pull/1299)'s finding) |
|
||||
| `gpu_timestamps segment` | `game.tsv` | the game's dynamic resolution decides from GPU timestamps, and with one time per submission it never lowers its resolution ([why](../../../docs/reference/frame-rate.md#dynamic-resolution-that-never-moves-and-draw-passes-that-wait-for-each-other)) |
|
||||
| Dynamic-resolution stub | [`patches.py`](patches.py) (frame step rule, `others`) | full resolution unless the launcher's Dynamic resolution is on ([Dynamic resolution](#dynamic-resolution)) |
|
||||
| `draw_barriers game` | `game.tsv` | about 180 full barriers a frame NVN does not ask for: GPU 25 → 18 ms at full resolution |
|
||||
| `tex_flush_upload on`, `tex_dirty_upload on` | `game.tsv` | as Tears of the Kingdom: the CPU writes the terrain tiles' height (R32F), blend and hole (RGBA8) maps into textures after creating them. Without the keys those textures stay zero: flat blue holes in the ground around the path with grass floating in them, and grey stone where the console shows dirt |
|
||||
| `shader_groups`, `shader_note` | `game.tsv` | shaders grouped as `/Shader/`, `/Effect/`, `/Lib/`, `/UI/` |
|
||||
@@ -48,6 +49,13 @@ Measured on an M6 Mac with 16 GB, headless, on one walk with camera turns (`walk
|
||||
- With a window, the first start on a new chain runs the pipeline prebuild first: 33,190 shader pairs, 691 s on this Mac. A run with no window skips it.
|
||||
- The opening movie runs at the movie's own 24 fps pace during the story section and cannot be skipped: about 8 minutes on a new file.
|
||||
|
||||
## Dynamic resolution
|
||||
|
||||
- The controller (v131072; found by fingerprint, so the addresses are only for reading): the parameters are `game__gfx__DynamicResolutionParam` (`LoadThreshold`, `ReduceCounterMax`, `IncreaseCounterMax`, and a list of levels, each a `ResolutionReduceScale` and a `Priority`). Once a frame the update (`main+0x805aa0`) reads the frame's GPU time, subtracts what its cost model predicts at the current size and keeps the trend of that residual. The level function (`main+0x8065e0`) adds the residual to the model's cost at each level and returns the best level under the threshold: 0, the full 1536x864, when the current size fits. The update moves down after `ReduceCounterMax` frames that ask for it and back up after `IncreaseCounterMax`. Scripted `GPULoad` hints from event data (`main+0x31c3de0`) and `OneshotSetDynamicResolutionLoadThreshold` adjust it in cutscenes.
|
||||
- Resolved on the host: after a loading screen it sat at its floor, 683x384, for minutes while the frame held 60 fps with GPU time to spare. A stale frame-start timestamp and event waits that idled the GPU made its timer read more than the frame took: [Dynamic resolution at its floor while the GPU has time to spare](../../../docs/reference/frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare).
|
||||
- Current: the launcher's **Dynamic resolution** (`DM_DYNAMIC_RESOLUTION`, off by default) holds full resolution. A stub of the frame step rule in [`patches.py`](patches.py), placed by the level function's fingerprint, makes that function return level 0 while state page `+0x40` is 0, so the update climbs to full size and stays there; 1 runs the game's own choice. The rewriter declares the `DYNAMIC_RESOLUTION` capability when it places the stub.
|
||||
- Measured on the M4 Pro (20-core GPU, 2026-11-08, `kokiri-deck`, one run each): at full resolution (the main passes 1536x864 in pass dumps at 75, 100 and 125 s) 48.1 fps, frame p50 16.74 / p95 33.41 ms, GPU p50 15.0 / p95 16.9 ms: the GPU needs about one vsync a frame, so the frame step holds 2 vsyncs much of the time. With the game's own dynamic resolution and the host fixes above: 60 fps, GPU p50 12.6 ms, at a lower resolution. A second dynamic-resolution run wandered off the route into Saria's dialogue and is not counted.
|
||||
|
||||
## Memory
|
||||
|
||||
- Current: on the walk, run from an external drive with a 3.5 GB pipeline archive: resident 10.9-11.4 GB, wired about 9.4 GB, on a 16 GB Mac. `vmmap` and `footprint`: 6.4 GB of guest memory and 3.8 GB of Metal textures and targets, 1 GB of IOAccelerator memory. [Reading the archive into memory](../../../docs/reference/memory.md#a-pipeline-archive-on-an-external-drive-is-read-into-memory) used to add 3.5 GB (footprint 15.0, peak 16.7). `mem_map_limit on`: a map past the application pool fails as on Horizon, and the SDK's allocator then gives back the pages it keeps. Other apps' memory adds to the swap: other games running beside it can push the Mac over.
|
||||
@@ -73,7 +81,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
|
||||
- Diagnostic caveat: earlier shader probes used fragment buffer 30, which conflicts with alpha-test state, then buffer 28 with added atomics that can move depth testing late. Visual conclusions from those instrumented runs are inconclusive. The event trace, offline producer comparison and combined validation above use the original uninstrumented fragment libraries. The scene flash predates those probes.
|
||||
- Regression reach is uncertain because every NVN submission now passes through logical queue scheduling. The five selected checks are Ocarina (the original dependency), Three Houses (multiple queues), Octopath Traveler 0 (command-buffer fences and Unreal RHI), Octopath Traveler II (an available boot route), and Okami HD (an older NVN path). The run is in progress; its unfinished rebuild is not a passing result. The focused tests pass with Metal validation: event/receipt 80, descriptor lifetime 38, continuation 38, native mesh first use 42 and storage-writer state 34 checks per encoding mode; capture 91, suspend 22, NVN 245, alias residency 28, completion ordering 36 in each of three configurations, and counter-overlap 42 per mode. The older CPU-post report/GPU-byte ordering limitation remains open as described in the rendering reference.
|
||||
|
||||
- Open on M4 Pro: low internal resolution and frame-rate instability are separate ongoing work. The visual-fix delivery retains main's timestamp policy and unavailable-query behavior; it does not claim a performance or resolution fix. Measurements here share the Mac with a separate shader build, per the testing constraint.
|
||||
- Current on M4 Pro (20-core GPU, 2026-11-08, the `kokiri-deck` route in [`bench.tsv`](bench.tsv), the partial shader set): GPU p50 12.6 / p95 13.6 ms, 51.8 fps, frame p50 16.69 ms (60 fps most of the time; two runs). Before, the main pass sat at the game's floor, 683x384, and the frame step held 30 fps at 16.3 / 18.6 ms (a hold of one vsync needs a cost under 1.1 vsyncs, a probe back to it 0.85). The time was geometry: per frame about 9 ms in the vertex and mesh stages, 5 ms compute, 4 ms fragment (Metal System Trace); the foliage task/mesh pass 4.6 ms of vertex-stage time against 0.2 ms of fragment. Two causes, both general: the mesh shaders read their 128-bit raw loads a word at a time ([128-bit raw global loads read one word at a time](../../../docs/reference/shaders.md#128-bit-raw-global-loads-read-one-word-at-a-time), about 3.1 ms), and occlusion conditions were never read ([Occlusion conditions read once landed](../../../docs/reference/rendering.md#occlusion-conditions-read-once-landed), 0.6 ms). Ruled out by A/B: the mesh shaders' threadgroup memory (folding it 50-77% smaller did not help), its zero fill, the pool table reads, their primitive output (0.3 ms) and missing `c1_full.tsv` / `cb_extent.tsv`. Open: compute is still about 5 ms of the frame (the NDSR upscaler `d99fbeeb53d38847` writing 2048x1152, a fixed cost at any internal resolution, and a culling group), not looked into.
|
||||
|
||||
- Resolved: the build left 9 shaders out. Six foliage compute shaders used `ATOMG.CAS` ([Global memory: descriptors, ATOMG.CAS, INC / DEC](../../../docs/reference/shaders.md#global-memory-descriptors-atomgcas-inc--dec)); `1f78730053feb036` and `e172bd7ec218ab8e` nest 259 brackets ([Bracket nesting past the front end's 256](../../../docs/reference/shaders.md#bracket-nesting-past-the-front-ends-256)); `68bbe98b3bfd9876` (`Ampere instruction 481 at 0x0`) and five more map rows were no shaders at all ([A control section's words read as a BAHS entry](../../../docs/reference/shaders.md#a-control-sections-words-read-as-a-bahs-entry)), now gone from the map. None of the eight real ones was used on the walk to Kokiri Forest.
|
||||
- Open: [the movie network](https://github.com/seedds/nxnative/issues/1375) took 35 ms a frame on an M1 Max, so movies and the title ran at about 28 fps there; on this M6 it takes 11.4 ms since [HMMA chains keep their matrices in the SIMD-group](../../../docs/reference/shaders.md#hmma-chains-keep-their-matrices-in-the-simd-group) (from 14.8), not measured on an M1 Max since.
|
||||
@@ -96,6 +104,8 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
|
||||
|
||||
- [Position invariance across shaders](../../../docs/reference/shaders.md#position-invariance-across-shaders): white shapes on plants and bushes for single frames in Kokiri Forest, from the foliage's mesh pre-pass and mesh colour pass rounding the position apart.
|
||||
- [GPU event waits order work across queues](../../../docs/reference/nvn-objects.md#gpu-event-waits-order-work-across-queues): the lighting producer-to-consumer dependency is proven in native SDK code and 297 live traced frames; the halo disappears when it is honored.
|
||||
- [128-bit raw global loads read one word at a time](../../../docs/reference/shaders.md#128-bit-raw-global-loads-read-one-word-at-a-time): the foliage mesh shaders read 464 of their 506 raw words as pieces of 116 `LDG.128`s, one lookup and one load each; GPU p50 16.3 → 12.6 ms with the occlusion fix below.
|
||||
- [Occlusion conditions read once landed](../../../docs/reference/rendering.md#occlusion-conditions-read-once-landed): 213 conditions on its occlusion queries in a dumped frame, all landed at replay and 42% false over the route, were drawn anyway; GPU p50 17.06 → 16.44 ms on an M4 Pro.
|
||||
- [Conditional rendering survives queue continuations](../../../docs/reference/rendering.md#conditional-rendering-survives-queue-continuations): event/fence splits lost disabled draws and pending counter values, causing the remaining patchy scene flashes.
|
||||
- [Native mesh draws omitted while their pipeline compiles](../../../docs/reference/shaders.md#native-mesh-draws-omitted-while-their-pipeline-compiles): compile the first demanded native mesh pipeline before its draw; the prior background path omitted geometry and depth while loading.
|
||||
|
||||
@@ -138,6 +148,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
|
||||
- [A texture shared by its packaged texture's serials left the residency set with one of them](../../../docs/reference/nvn-objects.md#a-texture-shared-by-its-packaged-textures-serials-left-the-residency-set-with-one-of-them): GPU page faults 15-45 minutes into play (issue #1326), on 260x260 terrain tiles made GPU textures at the GPU's first write.
|
||||
- [Finalizing a copy of a texture object](../../../docs/reference/nvn-objects.md#finalizing-a-copy-of-a-texture-object)
|
||||
- [Dynamic resolution that never moves, and draw passes that wait for each other](../../../docs/reference/frame-rate.md#dynamic-resolution-that-never-moves-and-draw-passes-that-wait-for-each-other)
|
||||
- [Dynamic resolution at its floor while the GPU has time to spare](../../../docs/reference/frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare): a stale frame-start timestamp, and event waits that idled the GPU
|
||||
- [A full table of running GPU writes ends passes for nothing](../../../docs/reference/frame-rate.md#a-full-table-of-running-gpu-writes-ends-passes-for-nothing)
|
||||
- [Float atomics in storage memory](../../../docs/reference/shaders.md#float-atomics-in-storage-memory)
|
||||
- [textureGatherOffsets and a loop over its offsets](../../../docs/reference/shaders.md#texturegatheroffsets-and-a-loop-over-its-offsets)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Benchmark routes for scripts/bench.py
|
||||
kokiri-deck 35:A~0.2,40:A~0.2,43:A~0.2,105:RRight~4,111:LUp~3,116:RLeft~4,122:LUp~3 85 45 the Kokiri Forest deck save: standing 20 s, then the camera turns right, Link walks, the camera turns left, he walks again
|
||||
|
@@ -31,13 +31,42 @@ def frame_step(ctx):
|
||||
emit(B(here(), site + 4))
|
||||
emit(0x1e201828); emit(B(here(), site + 4)) # orig: fdiv s8,s1,s0; back
|
||||
fs_put(site, [B(site, start)], 'frame ratio: the host\'s step × base rate / 60 instead of base rate / the game\'s frame rate (state page target fps; 0 = the game\'s ratio)')
|
||||
dynamic_resolution(ctx)
|
||||
|
||||
# The game's dynamic resolution (game__gfx__DynamicResolutionParam: LoadThreshold, ReduceCounterMax, IncreaseCounterMax and a list of levels, each a ResolutionReduceScale and a
|
||||
# Priority). Its controller's update (main+0x805aa0, v131072) reads the frame's GPU time, subtracts what its cost model predicts at the current size and keeps the residual's trend;
|
||||
# the level function (main+0x8065e0) adds that residual to the model's cost at each level and returns the best level that stays under the threshold, 0 (the full size, 1536x864)
|
||||
# when the current size does; the update moves to a lower level after ReduceCounterMax frames that ask for it and back up after IncreaseCounterMax. Its scale divides the 3D views.
|
||||
# On the Mac the GPU holds 1536x864 within a 60 fps frame, yet the controller sat at 683x384 for minutes after a loading screen (game note, Dynamic resolution). With
|
||||
# DM_DYNAMIC_RESOLUTION 0 (the default; state +0x40 0) the stub makes the level function return 0, so the update climbs to full resolution and stays; 1 runs the game's function.
|
||||
# The function is a leaf: x16 / x17 are free at its entry, and w0 is its only result (the original also stores the predicted cost at +0x18, which only this function and the update's
|
||||
# own decision read)
|
||||
def dynamic_resolution(ctx):
|
||||
here, emit, fs_site, fs_put, FS_STATE_OFF = ctx.here, ctx.emit, ctx.site, ctx.put, ctx.state
|
||||
site = ctx.others.get('dynamic resolution')
|
||||
if site is None: return # not found in this build (a red line from the locator): the game's own dynamic resolution
|
||||
fs_site(site, '017c40bd') # ldr s1,[x0,#0x7c]
|
||||
start = here(); emit(ADRP(16, here(), FS_STATE_OFF))
|
||||
for w in (0xb9404210, # ldr w16,[x16,#0x40] dynamic resolution on
|
||||
0x35000070, # cbnz w16,orig (+3)
|
||||
0x2a1f03e0, # mov w0,wzr level 0: full resolution
|
||||
0xd65f03c0, # ret
|
||||
0xbd407c01): # orig: ldr s1,[x0,#0x7c]
|
||||
emit(w)
|
||||
emit(B(here(), site + 4))
|
||||
fs_put(site, [B(site, start)], 'dynamic resolution level: 0 (full resolution) unless state +0x40 (DM_DYNAMIC_RESOLUTION) runs the game\'s choice')
|
||||
ctx.capabilities.add('DYNAMIC_RESOLUTION')
|
||||
|
||||
MATCH_FRAME_STEP = {'main': [
|
||||
{'name': 'frame ratio from the host\'s step', 'size': 0x9b4, 'fingerprints': ['6ae2aff5344d14568e4dbaf93455e2d8278384bf892ed6c6eca87fef98fbcd1d'], 'stub': frame_step}, # v131072 main+0x6e6be0
|
||||
{'name': 'frame ratio from the host\'s step', 'size': 0x9b4, 'fingerprints': ['6ae2aff5344d14568e4dbaf93455e2d8278384bf892ed6c6eca87fef98fbcd1d'], 'stub': frame_step, # v131072 main+0x6e6be0
|
||||
'others': {'dynamic resolution': {'size': 0x294, 'fingerprints': ['7af6ceb0aedf8e0c17dc08ce17fcd6a7cba6d394a0d09e3b504c6d668dc418e7']}}}, # v131072 main+0x8065e0
|
||||
]}
|
||||
|
||||
BINDING = [
|
||||
{'what': 'frame ratio from the host\'s step', 'now': 'game', 'goal': 'game', 'purpose': 'frame rate',
|
||||
'why': "the game's own frame-ratio division, found by its function's fingerprint on any build that keeps the function",
|
||||
'checked': 'v131072 main: one function with this fingerprint, the site and its free registers read by disassembly (2026-11-08)'},
|
||||
{'what': 'dynamic resolution held at full size', 'now': 'game', 'goal': 'game', 'purpose': 'rendering',
|
||||
'why': "the game's own dynamic-resolution level function, found by its function's fingerprint on any build that keeps the function; switchable (DM_DYNAMIC_RESOLUTION)",
|
||||
'checked': 'v131072 main: one function with this fingerprint (a leaf, x16 / x17 free), its callers and the controller read by disassembly (2026-11-08)'},
|
||||
]
|
||||
@@ -15,7 +15,7 @@
|
||||
# meta optional, key=value pairs separated by ; (settings.py META lists the keys; docs/frontends.md, The settings list, describes them):
|
||||
# level=basic a setting a front end shows first; needs=<VAR>=<value> a sub-setting, drawn only while the row that sets <VAR> has that value
|
||||
DM_FPS_TARGET choice 30=30 fps,60=60 fps,120=120 fps?DM_GAME_FPS_MAX==120&platform:mac DM_GAME_FPS_TARGET DM_GAME_FPS_TARGET!=0 Game Frame rate level=basic
|
||||
DM_DYNAMIC_RESOLUTION toggle - 0 fixups:DYNAMIC_RESOLUTION Game Dynamic resolution Adjusts resolution between 70% and 100% under load. Turn off to keep full resolution for the selected console mode.
|
||||
DM_DYNAMIC_RESOLUTION toggle - 0 fixups:DYNAMIC_RESOLUTION Game Dynamic resolution Lets the game lower its resolution under load. Turn off to keep full resolution for the selected console mode.
|
||||
DM_RENDER_SCALE range 0.5:1.0:0.05 1.0 fixups:RENDER_SCALE Game Render scale level=basic
|
||||
DM_OPMODE choice 1=Docked,0=Handheld DM_GAME_OPMODE always Game Console mode level=basic
|
||||
DM_PRESENT_UPSCALE choice off=Standard,metalfx=MetalFX off always Game Upscaling Uses more GPU time and can increase heat.
|
||||
|
||||
|
@@ -1,3 +1,3 @@
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
|
||||
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
|
||||
#define DMSH_CHAIN "579d06bf3932"
|
||||
#define DMSH_CHAIN "89f44f9b6bb0"
|
||||
+11
-5
@@ -873,7 +873,9 @@ typedef struct seg_clk seg_clk; static seg_clk *g_sclk; static void seg_clk_put(
|
||||
// before the composite read them, and the 3D scene came out black.
|
||||
// Metal has no predication, so the condition is evaluated here at replay, on the CPU, from the records in memory. A report in an earlier unfinished GPU prefix is not written yet
|
||||
// (that happens when the GPU completes): a timestamp one counts with its known counter 0; a samples-passed result (an occlusion query, written from the visibility buffers) is
|
||||
// unknown, and a condition on it keeps drawing, as before (occlusion culling only saves work). Inside a block evaluated false, draws and clears are dropped
|
||||
// unknown until its submission completes, and a condition on it keeps drawing (occlusion culling only saves work). Once it has landed the condition is evaluated from it, as the
|
||||
// GPU would at that point in the queue: Ocarina of Time reports its queries a submission ahead of the conditional draws, so every one has landed by then (1.48 million
|
||||
// conditions on its Kokiri Forest route, 42% false; the host drew them all, GPU p50 17.06 → 16.44 ms a frame on an M4 Pro). Inside a block evaluated false, draws and clears are dropped
|
||||
static int g_rc_skip; // logical queue state: a render-enable block evaluated false is active
|
||||
// Latest command-ordered writer of each report counter. Completed reports are read
|
||||
// from memory, so CPU rewrites remain visible. Unfinished queries stay unknown;
|
||||
@@ -948,7 +950,7 @@ static void rc_query_operand(rc_report *r) {
|
||||
}
|
||||
static void rc_note(uint64_t addr, int kind) {
|
||||
rc_report *r=rc_ensure(addr);
|
||||
if (kind!=1) r->conservative=1; // retain main's unavailable-query fallback; completed-query culling is a separate change
|
||||
r->conservative=kind==3; // counter kinds the host does not implement; a samples-passed result is read once it has landed (rc_value)
|
||||
// A condition compares adjacent 16-byte records. Either operand can be the
|
||||
// query; track its unreported neighbor before later explicit buffer writers.
|
||||
// Existing entries keep their own report type, pending fence and known bytes.
|
||||
@@ -1905,7 +1907,7 @@ static uint64_t gpu_ticks(void) { uint64_t g = guest_ns(); if (!g) { struct time
|
||||
// In segment mode a report takes the GPU time of the segment it was encoded in (sub_cut): TIMESTAMP_TOP (0x10) that segment's GPU start, other types its GPU end. The writes stay in the last segment's handler, before the fence,
|
||||
// so a game that waits for the fence reads one submission's reports together; a segment whose feedback has not arrived by then takes the last segment's times
|
||||
#define SEG_CLK_N 1024
|
||||
struct seg_clk { _Atomic int refs; _Atomic uint64_t t[SEG_CLK_N][2]; uint32_t nb; uint16_t b[SEG_CLK_N + 1]; }; // per submission (g_sclk, allocated at its first cut): guest ns of each cut segment's GPU start / end (0 = no feedback yet); b: with ts_on, the heap slots of the segment boundaries, segment k from b[k] to b[k + 1]
|
||||
struct seg_clk { _Atomic int refs; _Atomic uint64_t t[SEG_CLK_N][2]; uint32_t nb; uint16_t b[SEG_CLK_N + 1]; uint64_t begin; }; // per submission (g_sclk, allocated at its first cut): guest ns of each cut segment's GPU start / end (0 = no feedback yet); b: with ts_on, the heap slots of the segment boundaries, segment k from b[k] to b[k + 1]
|
||||
static int seg_ts(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_GPU_TS"); v = e && *e ? !strcmp(e, "segment") : DM_GAME_GPU_TS_SEGMENT; MLOG("counter timestamps: %s (profile key gpu_timestamps; DM_NVN_GPU_TS=segment / submission)", v ? "GPU start / end time of their segment" : "one time for the whole submission"); } return v; }
|
||||
static void seg_clk_put(seg_clk *c) { if (c && atomic_fetch_sub(&c->refs, 1) == 1) free(c); }
|
||||
static uint64_t gpu_s_guest_ns(double s) { // a feedback GPU time (seconds on the mach absolute time base) on the guest clock; 0 when unknown
|
||||
@@ -1922,6 +1924,9 @@ static uint64_t rep_ticks(const post_op *o, seg_clk *sc, uint32_t last, uint64_t
|
||||
static double scale; if (!scale) { uint64_t hz = [g_dev queryTimestampFrequency]; scale = hz ? 1e9 / (double)hz : 1; }
|
||||
uint64_t g = cpu ? guest_ns_at_host_time(cpu) : 0;
|
||||
if (e && d.length >= sizeof *e && e->timestamp && g) { double at = (double)e->timestamp * scale, ago = (double)gpu - at; if (ago >= 0 && ago < 2e9 && ago < (double)g) ns = g - (uint64_t)ago; } // an entry counts at queryTimestampFrequency (24 MHz here), a sample in ns
|
||||
// A stamp from before the submission began is a slot it did not write, the ring's last value there: an encoder with no work writes no relaxed timestamp (Ocarina of Time's
|
||||
// frame-start TIMESTAMP_TOP, alone in its submission, read 1.7 s early and its dynamic resolution kept its floor). Its segment's feedback time stands instead
|
||||
if (ns && sc->begin && ns + 500000 < sc->begin) ns = 0;
|
||||
if (ns) return nvn_timestamp_from_ns(ns);
|
||||
}
|
||||
if (sc && o->seg < last && o->seg < SEG_CLK_N) ns = atomic_load(&sc->t[o->seg][!top]);
|
||||
@@ -4399,10 +4404,11 @@ static int ts_stamp(void) { // no render encoder open. Written at the start of
|
||||
if (g_blit) [g_blit writeTimestampWithGranularity:MTL4TimestampGranularityRelaxed intoHeap:g_ts_heap atIndex:(NSUInteger)slot]; else g_ts_pend = slot;
|
||||
return slot;
|
||||
}
|
||||
static void ts_sub_begin(void) { if (ts_on()) g_ts_s0 = ts_stamp(); }
|
||||
static uint64_t g_ts_begin; // guest ns when this submission began encoding: no GPU timestamp of it is earlier (rep_ticks)
|
||||
static void ts_sub_begin(void) { if (ts_on()) { g_ts_s0 = ts_stamp(); g_ts_begin = guest_ns(); } }
|
||||
static void ts_clk(void) { // the submission's first report or boundary
|
||||
if (!ts_on() || g_sclk) return;
|
||||
g_sclk = calloc(1, sizeof *g_sclk); if (!g_sclk) MDIE("segment clock allocation failed"); atomic_store(&g_sclk->refs, 1); g_sclk->b[0] = (uint16_t)g_ts_s0; g_sclk->nb = 1;
|
||||
g_sclk = calloc(1, sizeof *g_sclk); if (!g_sclk) MDIE("segment clock allocation failed"); atomic_store(&g_sclk->refs, 1); g_sclk->b[0] = (uint16_t)g_ts_s0; g_sclk->nb = 1; g_sclk->begin = g_ts_begin;
|
||||
}
|
||||
static void ts_boundary(void) { // the end of a segment and the start of the next
|
||||
if (!ts_on()) return;
|
||||
|
||||
@@ -42,13 +42,17 @@ static pthread_mutex_t nq_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t nq_cv = PTHREAD_COND_INITIALIZER;
|
||||
static pthread_once_t nq_once = PTHREAD_ONCE_INIT;
|
||||
static nq_queue *nq_queues;
|
||||
typedef struct nq_event_write { struct nq_event_write *next; volatile uint32_t *word; uint64_t fence; } nq_event_write;
|
||||
// The last GPU write of each event word not yet landed: its submission's fence, and for a WRITE signal the value it leaves (exact). A wait the queued value satisfies needs no
|
||||
// completion: its continuation is encoded after the writer's on the one ordered Metal queue, as the next submission of one NVN queue is, and memory the writer's completion lands
|
||||
// on the CPU (reports, render-target readbacks) is that same in-flight case. An ADD's result depends on the writes landing before it, so such a wait still waits for them
|
||||
typedef struct nq_event_write { struct nq_event_write *next; volatile uint32_t *word; uint64_t fence; uint32_t value; int exact; } nq_event_write;
|
||||
static nq_event_write *nq_event_writes;
|
||||
static uint64_t nq_event_pending(volatile uint32_t *word) { for(nq_event_write *w=nq_event_writes;w;w=w->next) if(w->word==word) return w->fence; return 0; }
|
||||
static void nq_event_issued(volatile uint32_t *word,uint64_t fence) {
|
||||
nq_event_write *w=nq_event_writes; while(w && w->word!=word) w=w->next;
|
||||
static nq_event_write *nq_event_write_of(volatile uint32_t *word) { nq_event_write *w=nq_event_writes; while(w && w->word!=word) w=w->next; return w; }
|
||||
static void nq_event_issued(volatile uint32_t *word,uint64_t fence,unsigned mode,uint32_t value) {
|
||||
nq_event_write *w=nq_event_write_of(word);
|
||||
if(!w) { w=calloc(1,sizeof *w); if(!w) die("event ordering allocation failed"); w->word=word; w->next=nq_event_writes; nq_event_writes=w; }
|
||||
w->fence=fence;
|
||||
w->fence=fence; w->value=value; w->exact=mode==0;
|
||||
}
|
||||
|
||||
enum { NQ_COMMANDS, NQ_EVENT, NQ_SYNC, NQ_FENCE, NQ_PRESENT };
|
||||
@@ -118,6 +122,10 @@ static void *nq_worker(void *unused) {
|
||||
if(n->kind==NQ_EVENT && n->event) {
|
||||
uint64_t predecessor=nq_event_pending(n->event);
|
||||
if(!n->waiting) n->event_predecessor=predecessor;
|
||||
// The queued GPU write satisfies the wait: the GPU runs this continuation after it (nq_event_write). Ocarina of Time waits on about 25 events a frame; each wait
|
||||
// for the writer's completion left the GPU idle while the host encoded the next submission, 2 ms of its 14.5 ms frame, which its dynamic resolution read as work
|
||||
nq_event_write *queued=predecessor>mtl_completed_fence() ? nq_event_write_of(n->event) : NULL;
|
||||
if(queued && queued->exact && nq_predicate(queued->value,n->mode,n->value)) break;
|
||||
if(predecessor>mtl_completed_fence() || !nq_predicate(atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode,n->value)) { n->waiting=1; mapped_event_wait=1; continue; }
|
||||
}
|
||||
if(n->kind==NQ_SYNC) {
|
||||
@@ -156,7 +164,7 @@ static void *nq_worker(void *unused) {
|
||||
}
|
||||
nq_cost_end(cost); gfx_leave(); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu);
|
||||
}
|
||||
pthread_mutex_lock(&nq_mu); if(n->kind==NQ_PRESENT) { q->present=present; j->receipt->present=present; } if(fence) { q->physical=fence; if(n->event) nq_event_issued(n->event,fence); } if(n->receipt) nq_put(n->receipt); free(n->bytes); free(n); pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu);
|
||||
pthread_mutex_lock(&nq_mu); if(n->kind==NQ_PRESENT) { q->present=present; j->receipt->present=present; } if(fence) { q->physical=fence; if(n->event) nq_event_issued(n->event,fence,n->mode,n->value); } if(n->receipt) nq_put(n->receipt); free(n->bytes); free(n); pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -179,7 +187,7 @@ static void nq_flatten(nq_job *j,const uint8_t *p,unsigned depth) {
|
||||
nq_node *n=j->last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
|
||||
size_t offset=n->length; nq_bytes(n,p,h.size);
|
||||
if(!cap_rec_fields(h.op,n->bytes+offset+8,h.size,&nq_snapshot_ops,j)) die("queue snapshot: unknown command %u",h.op);
|
||||
if(h.op==OP_SIGNAL_EVENT) { memcpy(&n->event,a,8); nq_end(j); nq_append(j,NQ_FENCE)->receipt=nq_new(); }
|
||||
if(h.op==OP_SIGNAL_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); nq_end(j); nq_append(j,NQ_FENCE)->receipt=nq_new(); }
|
||||
}
|
||||
p+=h.size;
|
||||
}
|
||||
|
||||
@@ -174,6 +174,45 @@ int main(void) { @autoreleasepool {
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(pixels(0,255,0,0),"CPU counter write after completed report replaces pending zero");
|
||||
|
||||
// Occlusion conditions: a samples-passed report that has landed decides the
|
||||
// block as the GPU would; one still in flight keeps the block drawing.
|
||||
uint64_t *empty=(uint64_t *)(memory+EVENT+256),*seen=(uint64_t *)(memory+EVENT+320);
|
||||
empty[0]=seen[0]=7;empty[2]=seen[2]=0; // +16 stays 0: RENDER_IF_NOT_EQUAL draws when samples passed
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderTargets)(&command,1,colors,NULL,NULL,NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command,0,1,viewport); P(nvnCommandBufferSetScissor)(&command,0,0,W,H);
|
||||
P(nvnCommandBufferResetCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED);
|
||||
P(nvnCommandBufferReportCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED,(NVNbufferAddress)(uintptr_t)empty); // no draw counted
|
||||
P(nvnCommandBufferResetCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED);
|
||||
P(nvnCommandBufferBindProgram)(&command,&stable_red,3);
|
||||
P(nvnCommandBufferDrawArrays)(&command,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3); // covers the target
|
||||
P(nvnCommandBufferReportCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED,(NVNbufferAddress)(uintptr_t)seen);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(empty[0]==0 && seen[0]==W*H,"samples-passed reports land with 0 and the drawn samples");
|
||||
const char *occ[]={"landed zero query culls its block","landed nonzero query draws its block"};
|
||||
for (int k=0;k<2;k++) {
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferBindProgram)(&command,&stable_green,3);
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)1,(NVNbufferAddress)(uintptr_t)(k ? seen : empty));
|
||||
P(nvnCommandBufferDrawArrays)(&command,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(k ? pixels(0,0,255,0) : pixels(0,0,0,255),occ[k]);
|
||||
}
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferResetCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED);
|
||||
P(nvnCommandBufferReportCounter)(&command,NVN_COUNTER_TYPE_SAMPLES_PASSED,(NVNbufferAddress)(uintptr_t)empty);
|
||||
P(nvnCommandBufferBindProgram)(&command,&stable_green,3);
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)1,(NVNbufferAddress)(uintptr_t)empty);
|
||||
P(nvnCommandBufferDrawArrays)(&command,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(pixels(0,0,255,0),"query in flight keeps its block drawing");
|
||||
P(nvnSyncFinalize)(&dependency);P(nvnSyncFinalize)(&split_sync);
|
||||
P(nvnQueueFinish)(&queues[0]); P(nvnQueueFinish)(&queues[1]);
|
||||
P(nvnProgramFinalize)(&stable_red); P(nvnProgramFinalize)(&stable_green);
|
||||
|
||||
@@ -235,6 +235,31 @@ static void event_stale_gpu_reset(void) {
|
||||
if(!done) _Exit(2);
|
||||
P(nvnSyncFinalize)(&reset); P(nvnSyncFinalize)(&consumed);
|
||||
}
|
||||
// A wait whose event a still-running WRITE signal satisfies is encoded without that writer's completion (the one Metal queue runs it after the writer, nq_event_write), and its GPU work
|
||||
// still sees the writer's payload; an ADD signal's result is not known before it lands, so a wait on it parks until then
|
||||
static void event_queued_write(int mode) {
|
||||
printf("CASE wait on an in-flight %s signal\n",mode==NVN_EVENT_SIGNAL_MODE_WRITE?"WRITE":"ADD");
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,0);
|
||||
id<MTLSharedEvent> gate=[g_dev newSharedEvent];
|
||||
pthread_mutex_lock(&g_sub_mu); pthread_mutex_lock(&g_res_mu); [g_q4 waitForEvent:gate value:1]; pthread_mutex_unlock(&g_res_mu); pthread_mutex_unlock(&g_sub_mu);
|
||||
NVNsync produced,consumed; P(nvnSyncInitialize)(&produced,&device); P(nvnSyncInitialize)(&consumed,&device);
|
||||
begin_cmd(1); uint32_t payload=after;
|
||||
P(nvnCommandBufferUpdateUniformBuffer)(&commands[1],source_addr,4,0,4,&payload);
|
||||
P(nvnCommandBufferSignalEvent)(&commands[1],&event,(NVNeventSignalMode)mode,NVN_EVENT_SIGNAL_LOCATION_BOTTOM,0,1);
|
||||
P(nvnCommandBufferFenceSync)(&commands[1],&produced,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
job pj,cj; enqueue(&pj,&queues[1],P(nvnCommandBufferEndRecording)(&commands[1])); int pr=returned(&pj,250000000ull);
|
||||
CHECK(pr && receipt_encoded(&produced,1000000000ull),"producer encodes while its GPU work is held by a shared-event gate");
|
||||
enqueue(&cj,&queues[0],consumer(NVN_EVENT_WAIT_MODE_EQUAL,1,&consumed,1)); int cr=returned(&cj,250000000ull);
|
||||
int early=receipt_encoded(&consumed,mode==NVN_EVENT_SIGNAL_MODE_WRITE?1000000000ull:100000000ull);
|
||||
CHECK(early==(mode==NVN_EVENT_SIGNAL_MODE_WRITE),mode==NVN_EVENT_SIGNAL_MODE_WRITE?"the consumer is encoded behind the in-flight WRITE before it completes"
|
||||
:"the consumer waits for an in-flight ADD to land");
|
||||
CHECK(!landed(&produced,0) && !landed(&consumed,0) && *result==sentinel,"nothing has run while the gate holds the GPU");
|
||||
gate.signaledValue=1; // always release the GPU before cleanup, including assertion failures
|
||||
require_returned(&pj,pr); require_returned(&cj,cr);
|
||||
int done=landed(&produced,5000000000ull) && landed(&consumed,5000000000ull);
|
||||
CHECK(done && *result==after,"the consumer's copy reads the producer's payload"); if(!done) { P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1); _Exit(2); }
|
||||
P(nvnSyncFinalize)(&produced); P(nvnSyncFinalize)(&consumed);
|
||||
}
|
||||
static void receipt_tests(void) {
|
||||
receipt_unrelated_completion(); receipt_snapshot(0); receipt_snapshot(1); receipt_wait_only(0); receipt_wait_only(1);
|
||||
}
|
||||
@@ -286,6 +311,8 @@ int main(void) { @autoreleasepool {
|
||||
case_wait("wrap rejects exactly half-range",1,0x80000000,0,0);
|
||||
case_cross_queue();
|
||||
event_stale_gpu_reset();
|
||||
event_queued_write(NVN_EVENT_SIGNAL_MODE_WRITE);
|
||||
event_queued_write(NVN_EVENT_SIGNAL_MODE_ADD);
|
||||
receipt_tests();
|
||||
event_mirror_publication();
|
||||
pthread_mutex_lock(&jobs_mu); jobs_stop=1; pthread_cond_signal(&jobs_cv); pthread_mutex_unlock(&jobs_mu); pthread_join(worker,NULL);
|
||||
|
||||
@@ -107,5 +107,53 @@ class RawLast(Translated):
|
||||
self.assertIn('bad 0 of 1024', out.stdout, out.stdout + out.stderr)
|
||||
|
||||
|
||||
LDG128 = ((LDG[0] & ~(7 << 9)) | 6 << 9, (LDG[1] & ~(0xff << 16)) | 12 << 16) # LDG.E.128 R12, [R5.64 + UR4]: size bits 73..75 = 6 (B128), R12..R15
|
||||
def sts(rb, off): return (STORE[0], (STORE[1] & ~(0xffffffff << 32)) | rb << 32 | off << 40) # STS.U32 [R9 * 16 + off], Rb
|
||||
VEC_HELPER = re.compile(r'(?m)^int (_\d+)\(thread const int& _\d+, thread const int& _\d+, const device (_\d+)& \w+, thread uint& (_\d+), thread spvUnsafeArray<uint, 3>& (_\d+)\)\n\{\n')
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_XLATE'), 'set DMSH_TEST_XLATE to the offline translator')
|
||||
class RawVector(Translated):
|
||||
"""An LDG.128 through an address the translator ties to no storage buffer: one pool table lookup and one 128-bit load (Operation.GlobalVectorCount, GlobalToStorage
|
||||
GenerateRawVectorLoad), not four, the other words passed back in gmem_vec; on the GPU each of the four words is the pool's"""
|
||||
def msl(self):
|
||||
code = (s2r_tid(9), s2r_tid(5), LDG128, sts(12, 0), sts(13, 4), sts(14, 8), sts(15, 12))
|
||||
return self.translate(b''.join(inst(*waiting(i)) for i in code) + inst(*EXIT), shared=0x1000)
|
||||
|
||||
def test_one_vector_load_for_the_four_words(self):
|
||||
msl = self.msl()
|
||||
m = VEC_HELPER.search(msl)
|
||||
self.assertTrue(m, msl[:3000])
|
||||
helper = msl[m.end():msl.index('\n}\n', m.end())]
|
||||
self.assertEqual(len(re.findall(r'uint4 _\d+ = \*\(reinterpret_cast<const device uint4\*>', helper)), 1, helper[-1500:])
|
||||
self.assertNotRegex(helper, r'reinterpret_cast<const device uint\*>') # no word loads besides it
|
||||
main = msl[msl.index('kernel void main0'):]
|
||||
self.assertEqual(len(re.findall(m.group(1) + r'\(', main)), 1)
|
||||
scalar = HELPER.search(msl)
|
||||
self.assertFalse(scalar and re.search(scalar.group(1) + r'\(', main), 'a word of the 128-bit load went through the scalar helper')
|
||||
for k in range(3): self.assertRegex(main, re.escape(m.group(4)) + rf'\[{k}\]')
|
||||
|
||||
@unittest.skipUnless(shutil.which('xcrun') and sys.platform == 'darwin', 'needs Metal')
|
||||
def test_reads_on_gpu(self):
|
||||
msl = self.msl()
|
||||
m = VEC_HELPER.search(msl)
|
||||
# each step's word 0 when words 1..3 are the next three of its pool (value() counts words), 0 where it reads no pool; the runner's addresses keep all four in one pool
|
||||
kernel = (msl[:msl.index('kernel void main0')] +
|
||||
f'kernel void k(const device {m.group(2)}& map [[buffer(0)]], const device uint2* addr [[buffer(1)]], device int* out [[buffer(2)]], uint id [[thread_position_in_grid]])\n'
|
||||
'{\n uint last = 0u;\n spvUnsafeArray<uint, 3> vec;\n for (int s = 0; s < 16; s++)\n {\n int lo = int(addr[id * 16 + s].x), hi = int(addr[id * 16 + s].y);\n'
|
||||
f' int w = {m.group(1)}(lo, hi, map, last, vec);\n'
|
||||
' out[id * 16 + s] = w == 0 || (vec[0] == uint(w) + 1u && vec[1] == uint(w) + 2u && vec[2] == uint(w) + 3u) ? w : int(0xdead);\n }\n}\n')
|
||||
with tempfile.TemporaryDirectory() as w:
|
||||
w = Path(w)
|
||||
(w / 'k.metal').write_text(kernel)
|
||||
r = subprocess.run(MAC_METAL + [str(w / 'k.metal'), '-o', str(w / 'k.air')], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr[-3000:])
|
||||
subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', str(w / 'k.air'), '-o', str(w / 'k.metallib')], check=True)
|
||||
(w / 'r.m').write_text(RUNNER)
|
||||
subprocess.run(['clang', '-fobjc-arc', '-framework', 'Metal', '-framework', 'Foundation', str(w / 'r.m'), '-o', str(w / 'r')], check=True, capture_output=True)
|
||||
out = subprocess.run([str(w / 'r'), str(w / 'k.metallib')], capture_output=True, text=True)
|
||||
self.assertIn('bad 0 of 1024', out.stdout, out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,7 +1,7 @@
|
||||
# Translation chain tool fingerprints (written by tool_lock.py --update-lock; regenerate after changing tools and commit it)
|
||||
dmsh_xlate.dll 0c4a312520b5aa7f
|
||||
Ryujinx.Graphics.Shader.dll 63adda80b4b3bd6e
|
||||
Ryujinx.Common.dll eea41bd3312d4f2a
|
||||
dmsh_xlate.dll 2d36ca9c8bb6ee4f
|
||||
Ryujinx.Graphics.Shader.dll 4963ff329995dcdc
|
||||
Ryujinx.Common.dll 6c522e5c70acc883
|
||||
xlate_source 0bd66426675438a9
|
||||
spirv-cross e37945d8e441d34d
|
||||
metal_macosx Apple metal version 32023.922 (metalfe-32023.922.4)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -321,6 +321,11 @@ void dm_fps_state_apply(void) {
|
||||
const char *rs = getenv("DM_RENDER_SCALE"); float sc = 1.0f;
|
||||
if (rs) { char *end; sc = strtof(rs, &end); if (end == rs || *end || !(sc >= 0.5f && sc <= 1.0f)) { LOG("[RED] DM_RENDER_SCALE=%s: must be 0.5 to 1.0; keeping the game's size", rs); sc = 1.0f; } else LOG("%s: 3D views rendered at %.2f of the game's size (DM_RENDER_SCALE)", g_fps_mod, sc); }
|
||||
memcpy(dm_fps_state + 0x10, &sc, sizeof sc);
|
||||
// The game's own dynamic resolution, for builds whose stubs read it (the DYNAMIC_RESOLUTION capability of a frame step stub: Ocarina of Time's level function): 1 lets it
|
||||
// run, 0 (the default) holds full resolution. Builds without such a stub ignore the field
|
||||
const char *dr = getenv("DM_DYNAMIC_RESOLUTION"); uint32_t dyn = dr && !strcmp(dr, "1");
|
||||
if (dr && strcmp(dr, "0") && strcmp(dr, "1")) LOG("[RED] DM_DYNAMIC_RESOLUTION=%s: must be 0 or 1; keeping full resolution", dr);
|
||||
memcpy(dm_fps_state + 0x40, &dyn, sizeof dyn);
|
||||
// Screen shape: DM_SCREEN_ASPECT, the screen's width / height between 1.3 and 1.77, makes the builds with screen-shape stubs
|
||||
// (Breath of the Wild 1.9.0's patches.py) render that shape: the output keeps its width (1920) and takes the height that gives the ratio, a multiple of 48 so the
|
||||
// 2/3-size layout space (1280 wide) stays whole: 1.43 → 1920x1344 and 1280x896. State +0x48 u32 output height, +0x4c u32 layout height, +0x50 its float; 0 = 16:9
|
||||
|
||||
+39
@@ -1792,6 +1792,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
|
||||
private static OperationResult GenerateLoadOrStore(CodeGenContext context, AstOperation operation, bool isStore)
|
||||
{
|
||||
if (!isStore && operation.StorageKind == StorageKind.GlobalMemoryVector)
|
||||
{
|
||||
return GenerateRawVectorLoad(context, operation);
|
||||
}
|
||||
|
||||
SpvInstruction pointer = GetStoragePointer(context, operation, out AggregateType varType);
|
||||
|
||||
// nxnative: a load or store through a physical storage buffer pointer must state its alignment (a 32-bit word)
|
||||
@@ -1821,6 +1826,40 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
}
|
||||
}
|
||||
|
||||
// nxnative: a raw vector load (GlobalToStorage.TryGenerateRawStorageOp): low and high words of the host GPU address, the word count, the local memory for words 1 and up.
|
||||
// One load of a vector of 32-bit words through a physical storage buffer pointer (aligned as a word, as the scalar loads), word 0 returned, the others stored
|
||||
private static OperationResult GenerateRawVectorLoad(CodeGenContext context, AstOperation operation)
|
||||
{
|
||||
if (operation.GetSource(2) is not AstOperand { Type: OperandType.Constant } countOperand ||
|
||||
operation.GetSource(3) is not AstOperand { Type: OperandType.Constant } memoryOperand)
|
||||
{
|
||||
throw new InvalidOperationException($"The word count and local memory of a {operation.StorageKind} load must be constants.");
|
||||
}
|
||||
|
||||
int count = countOperand.Value;
|
||||
SpvInstruction vectorType = context.TypeVector(context.TypeU32(), count);
|
||||
SpvInstruction addressWords = context.CompositeConstruct(
|
||||
context.TypeVector(context.TypeU32(), 2),
|
||||
context.Get(AggregateType.U32, operation.GetSource(0)),
|
||||
context.Get(AggregateType.U32, operation.GetSource(1)));
|
||||
SpvInstruction pointer = context.ConvertUToPtr(
|
||||
context.TypePointer(StorageClass.PhysicalStorageBuffer, vectorType),
|
||||
context.Bitcast(context.TypeInt(64, 0), addressWords));
|
||||
|
||||
SpvInstruction value = context.Load(vectorType, pointer, MemoryAccessMask.Aligned);
|
||||
value.AddOperand((SpvLiteralInteger)4);
|
||||
|
||||
SpvInstruction wordPointerType = context.TypePointer(StorageClass.Private, context.TypeU32());
|
||||
|
||||
for (int word = 1; word < count; word++)
|
||||
{
|
||||
SpvInstruction element = context.AccessChain(wordPointerType, context.LocalMemories[memoryOperand.Value], context.Constant(context.TypeS32(), word - 1));
|
||||
context.Store(element, context.CompositeExtract(context.TypeU32(), value, (SpvLiteralInteger)word));
|
||||
}
|
||||
|
||||
return new OperationResult(AggregateType.U32, context.CompositeExtract(context.TypeU32(), value, (SpvLiteralInteger)0));
|
||||
}
|
||||
|
||||
private static SpvInstruction GetStoragePointer(CodeGenContext context, AstOperation operation, out AggregateType varType)
|
||||
{
|
||||
StorageKind storageKind = operation.StorageKind;
|
||||
|
||||
+13
-1
@@ -311,6 +311,10 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
context.BranchIfFalse(lblSkip, pred);
|
||||
}
|
||||
|
||||
// The words of one LDG.64 / LDG.128 are marked as one access (Operation.GlobalVectorCount): an address the translator ties to no storage buffer then takes one pool
|
||||
// table lookup and one vector load for all of them, where each word took its own (Ocarina of Time's foliage mesh shaders: 4.6 ms of a 683x384 frame, 464 of 506 loads)
|
||||
bool vector = count > 1 && storageKind == StorageKind.GlobalMemory && x.Rd + count <= RegisterConsts.RegisterZeroIndex;
|
||||
|
||||
for (int index = 0; index < count; index++)
|
||||
{
|
||||
if (x.Rd + index >= RegisterConsts.RegisterZeroIndex)
|
||||
@@ -318,7 +322,15 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
break;
|
||||
}
|
||||
|
||||
context.Copy(Register(x.Rd + index, RegisterType.Gpr), context.Load(storageKind, los[index], his[index]));
|
||||
Operand value = context.Load(storageKind, los[index], his[index]);
|
||||
|
||||
if (vector && value.AsgOp is Operation load)
|
||||
{
|
||||
load.GlobalVectorCount = count;
|
||||
load.GlobalVectorWord = index;
|
||||
}
|
||||
|
||||
context.Copy(Register(x.Rd + index, RegisterType.Gpr), value);
|
||||
}
|
||||
|
||||
if (lblSkip != null)
|
||||
|
||||
+9
@@ -393,6 +393,9 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
Operand srcA = context.Copy(new Operand(new Register(ra, RegisterType.Gpr)));
|
||||
|
||||
// nxnative: the words of one LDG.64 / LDG.128 are marked as one access (Operation.GlobalVectorCount, as in InstEmitAmpereMem.ALdg)
|
||||
bool vector = count > 1 && storageKind == StorageKind.GlobalMemory && rd + count <= RegisterConsts.RegisterZeroIndex;
|
||||
|
||||
for (int index = 0; index < count; index++)
|
||||
{
|
||||
Register dest = new(rd + index, RegisterType.Gpr);
|
||||
@@ -404,6 +407,12 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
Operand value = context.Load(storageKind, context.IAdd(srcA, Const(offset + index * 4)), addrHigh);
|
||||
|
||||
if (vector && value.AsgOp is Operation load)
|
||||
{
|
||||
load.GlobalVectorCount = count;
|
||||
load.GlobalVectorWord = index;
|
||||
}
|
||||
|
||||
context.Copy(Register(dest), value);
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -10,6 +10,11 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
|
||||
|
||||
public bool ForcePrecise { get; set; }
|
||||
|
||||
// nxnative: the words of one 64- or 128-bit global load (LDG.64 / LDG.128), which the emitters split into 32-bit loads: the access's word count (2 or 4) on each of
|
||||
// them and the word's index, 0 on none other. GlobalToStorage reads such an access through the pool table as one vector load (TryGenerateRawStorageOp)
|
||||
public int GlobalVectorCount { get; set; }
|
||||
public int GlobalVectorWord { get; set; }
|
||||
|
||||
private Operand[] _dests;
|
||||
|
||||
public Operand Dest
|
||||
|
||||
Vendored
+1
@@ -18,6 +18,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
|
||||
GlobalMemoryS16, // TODO: Remove this and store type as a field on the Operation class itself.
|
||||
GlobalMemoryU8, // TODO: Remove this and store type as a field on the Operation class itself.
|
||||
GlobalMemoryU16, // TODO: Remove this and store type as a field on the Operation class itself.
|
||||
GlobalMemoryVector, // nxnative: a raw vector load at a host GPU address (GlobalToStorage.TryGenerateRawStorageOp): low, high, word count, the local memory taking words 1 and up
|
||||
}
|
||||
|
||||
static class StorageKindExtensions
|
||||
|
||||
Vendored
+120
-6
@@ -82,6 +82,18 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
_hfm = hfm;
|
||||
}
|
||||
|
||||
// nxnative: the raw vector load helpers by word count (TryGenerateRawStorageOp), kept apart from _entries, where a scalar load would find them
|
||||
public readonly Dictionary<int, int> RawVectorFunctions = [];
|
||||
|
||||
public int AddRawVectorFunction(int count, Function function)
|
||||
{
|
||||
int functionId = _hfm.AddFunction(function);
|
||||
|
||||
RawVectorFunctions[count] = functionId;
|
||||
|
||||
return functionId;
|
||||
}
|
||||
|
||||
public int AddFunction(Operation baseOp, bool isMultiTarget, IReadOnlyList<uint> targetCbs, Function function)
|
||||
{
|
||||
int functionId = _hfm.AddFunction(function);
|
||||
@@ -381,15 +393,101 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
targetLanguage,
|
||||
block,
|
||||
operation,
|
||||
out int functionId))
|
||||
out int functionId,
|
||||
out bool raw))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (raw &&
|
||||
operation.Inst == Instruction.Load &&
|
||||
operation.StorageKind == StorageKind.GlobalMemory &&
|
||||
operation.GlobalVectorCount > 1 &&
|
||||
operation.GlobalVectorWord == 0 &&
|
||||
TryGetRawVectorFunction(gtsContext, resourceManager, gpuAccessor, operation, out int vectorFunctionId))
|
||||
{
|
||||
return GenerateRawVectorLoad(resourceManager, node, operation, vectorFunctionId);
|
||||
}
|
||||
|
||||
return GenerateCallStorageOp(node, operation, null, functionId);
|
||||
}
|
||||
}
|
||||
|
||||
// nxnative: the first word of a 64- or 128-bit global load whose address goes through the pool table (Operation.GlobalVectorCount) calls the vector helper, which leaves
|
||||
// the other words in the shader's gmem_vec local memory; the loads of those words, which follow in the block, read them from there right after the call. A word whose
|
||||
// load is gone (unused) is not read. The scan stops at any other memory access or call, so nothing writes gmem_vec in between
|
||||
private static LinkedListNode<INode> GenerateRawVectorLoad(ResourceManager resourceManager, LinkedListNode<INode> node, Operation operation, int functionId)
|
||||
{
|
||||
int count = operation.GlobalVectorCount;
|
||||
int vectorMemoryId = resourceManager.GetRawVectorMemory();
|
||||
|
||||
node = GenerateCallStorageOp(node, operation, null, functionId); // the first word's load, now a copy of the call's result
|
||||
|
||||
LinkedListNode<INode> insertAfter = node;
|
||||
|
||||
for (LinkedListNode<INode> next = node.Next; next != null; next = next.Next)
|
||||
{
|
||||
if (next.Value is not Operation follower)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (follower.Inst == Instruction.Load &&
|
||||
follower.StorageKind == StorageKind.GlobalMemory &&
|
||||
follower.GlobalVectorCount == count &&
|
||||
follower.GlobalVectorWord > 0)
|
||||
{
|
||||
Operand word = Local();
|
||||
Operation load = new(Instruction.Load, StorageKind.LocalMemory, word, Const(vectorMemoryId), Const(follower.GlobalVectorWord - 1));
|
||||
|
||||
insertAfter = insertAfter.List.AddAfter(insertAfter, load);
|
||||
|
||||
// A plain copy in its place: TurnIntoCopy keeps the storage kind, and this pass, which reaches the node later, would take it for a global access again
|
||||
Operand dest = follower.Dest;
|
||||
follower.TurnIntoCopy(word);
|
||||
word.UseOps.Remove(follower);
|
||||
follower.Dest = null;
|
||||
next.Value = new Operation(Instruction.Copy, dest, word);
|
||||
|
||||
if (follower.GlobalVectorWord == count - 1)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (follower.GlobalVectorCount != 0 ||
|
||||
follower.StorageKind != StorageKind.None ||
|
||||
follower.Inst == Instruction.Call ||
|
||||
follower.Inst == Instruction.Barrier ||
|
||||
follower.Inst == Instruction.MemoryBarrier ||
|
||||
follower.Inst.IsAtomic())
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static bool TryGetRawVectorFunction(
|
||||
GtsContext gtsContext,
|
||||
ResourceManager resourceManager,
|
||||
IGpuAccessor gpuAccessor,
|
||||
Operation operation,
|
||||
out int functionId)
|
||||
{
|
||||
int count = operation.GlobalVectorCount;
|
||||
|
||||
if (gtsContext.RawVectorFunctions.TryGetValue(count, out functionId))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return TryGenerateRawStorageOp(gtsContext, resourceManager, gpuAccessor, operation, out functionId, count);
|
||||
}
|
||||
|
||||
private static bool CanUseInlineStorageOp(Operation operation, TargetLanguage targetLanguage)
|
||||
{
|
||||
if (operation.StorageKind != StorageKind.GlobalMemory)
|
||||
@@ -589,11 +687,13 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
TargetLanguage targetLanguage,
|
||||
BasicBlock block,
|
||||
Operation operation,
|
||||
out int functionId)
|
||||
out int functionId,
|
||||
out bool raw)
|
||||
{
|
||||
Queue<PhiNode> phis = new();
|
||||
HashSet<PhiNode> visited = [];
|
||||
List<uint> targetCbs = [];
|
||||
raw = false;
|
||||
|
||||
Operand globalAddress = operation.GetSource(0);
|
||||
|
||||
@@ -658,6 +758,8 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
gpuAccessor.Log($"Global memory operation \"{operation.Inst}\" traced to no storage buffer: it goes through the memory pool table.");
|
||||
}
|
||||
|
||||
raw = targetCbs.Count == 0;
|
||||
|
||||
if (gtsContext.TryGetFunctionId(operation, isMultiTarget: true, targetCbs, out functionId))
|
||||
{
|
||||
return true;
|
||||
@@ -801,7 +903,8 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
ResourceManager resourceManager,
|
||||
IGpuAccessor gpuAccessor,
|
||||
Operation operation,
|
||||
out int functionId)
|
||||
out int functionId,
|
||||
int vectorCount = 1)
|
||||
{
|
||||
functionId = 0;
|
||||
|
||||
@@ -928,7 +1031,16 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
Operand resultValue = null;
|
||||
|
||||
if (operation.Inst == Instruction.Load)
|
||||
if (operation.Inst == Instruction.Load && vectorCount > 1)
|
||||
{
|
||||
// All the words of a 64- or 128-bit load in one vector load (ReplaceGlobalMemoryWithStorage, GenerateRawVectorLoad): word 0 returned, the others left in gmem_vec.
|
||||
// The first word's entry holds them all: such a load is aligned to its size on the GPU, and every entry starts and ends on a pool's 4 KiB boundary
|
||||
// (nvn_mtl.m gmem_map). Ocarina of Time's foliage mesh shaders read 464 of their 506 raw words as 116 such loads, which Metal's compiler kept as four word
|
||||
// loads each, every one through a pointer of its own: one vector load each (first as an overlay of those shaders) took the frame's GPU time from 17.0 to
|
||||
// 13.9 ms on an M4 Pro (docs/reference/shaders.md, 128-bit raw global loads read one word at a time)
|
||||
resultValue = context.Add(Instruction.Load, StorageKind.GlobalMemoryVector, Local(), hostLow, hostHigh, Const(vectorCount), Const(resourceManager.GetRawVectorMemory()));
|
||||
}
|
||||
else if (operation.Inst == Instruction.Load)
|
||||
{
|
||||
resultValue = context.Load(StorageKind.GlobalMemory, hostLow, hostHigh);
|
||||
|
||||
@@ -1001,12 +1113,14 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
Function function = new(
|
||||
ControlFlowGraph.Create(context.GetOperations()).Blocks,
|
||||
GetFunctionName(operation, isMultiTarget: true, []) + "Raw",
|
||||
GetFunctionName(operation, isMultiTarget: true, []) + (vectorCount > 1 ? $"RawV{vectorCount}" : "Raw"),
|
||||
returnsValue,
|
||||
inArgumentsCount,
|
||||
0);
|
||||
|
||||
functionId = gtsContext.AddFunction(operation, isMultiTarget: true, [], function);
|
||||
functionId = vectorCount > 1
|
||||
? gtsContext.AddRawVectorFunction(vectorCount, function)
|
||||
: gtsContext.AddFunction(operation, isMultiTarget: true, [], function);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
+14
@@ -165,6 +165,20 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
return Properties.AddLocalMemory(new MemoryDefinition($"gmem_last_{Properties.LocalMemories.Count}", AggregateType.U32, 1, zeroInit: true));
|
||||
}
|
||||
|
||||
// nxnative: words 1 to 3 of a raw vector load (GlobalToStorage.TryGenerateRawStorageOp), one for the shader: the helper writes them and the loads of those words read them
|
||||
// right after its call, before any other access
|
||||
private int _rawVectorMemoryId = -1;
|
||||
|
||||
public int GetRawVectorMemory()
|
||||
{
|
||||
if (_rawVectorMemoryId < 0)
|
||||
{
|
||||
_rawVectorMemoryId = Properties.AddLocalMemory(new MemoryDefinition("gmem_vec", AggregateType.Array | AggregateType.U32, 3));
|
||||
}
|
||||
|
||||
return _rawVectorMemoryId;
|
||||
}
|
||||
|
||||
private int AddMemoryDefinition(string name, AggregateType type, int arrayLength = 1)
|
||||
{
|
||||
return Properties.AddLocalMemory(new MemoryDefinition(name, type, arrayLength));
|
||||
|
||||
@@ -172,12 +172,18 @@ def build_rows(gs): # {build ID: [(game, display version, module)]}
|
||||
return out
|
||||
|
||||
|
||||
def frame_step_sites(fn, base=0): # (offset, reason) of each site a FRAME_STEP function (or a MATCH_FRAME_STEP stub, its function at base) writes, and whether it marks a render-scale stub
|
||||
pos, puts = [0x8000000], []
|
||||
OTHER_BASE = 0x10000000 # where the dry run puts a MATCH_FRAME_STEP rule's other functions, 16 MB apart, so their sites read as offsets in them
|
||||
|
||||
|
||||
def frame_step_sites(fn, base=0, others=()): # (offset, reason) of each site a FRAME_STEP function (or a MATCH_FRAME_STEP stub, its function at base) writes, whether it marks a
|
||||
pos, puts = [0x8000000], [] # render-scale stub, the sites in each of the rule's other functions ({label: [(offset, reason)]}) and the capabilities it declares
|
||||
def emit(w): pos[0] += 4
|
||||
ctx = types.SimpleNamespace(here=lambda: pos[0], emit=emit, site=lambda off, orig: None, put=lambda off, words, why: puts.append((off, why)), state=0x9000000, render_scale=0, base=base)
|
||||
at = {label: OTHER_BASE + i * 0x1000000 for i, label in enumerate(others)}
|
||||
ctx = types.SimpleNamespace(here=lambda: pos[0], emit=emit, site=lambda off, orig: None, put=lambda off, words, why: puts.append((off, why)), state=0x9000000, render_scale=0, base=base,
|
||||
others=at, capabilities=set())
|
||||
fn(ctx)
|
||||
return sorted(puts), ctx.render_scale
|
||||
in_others = {label: sorted((off - a, why) for off, why in puts if a <= off < a + 0x1000000) for label, a in at.items()}
|
||||
return sorted((off, why) for off, why in puts if off < OTHER_BASE), ctx.render_scale, in_others, sorted(ctx.capabilities)
|
||||
|
||||
|
||||
def host_files(): # the host's tracked sources without its tests: what the build-ID scan below and the title-ID check (test_architecture.py) read
|
||||
@@ -292,13 +298,13 @@ def page():
|
||||
for off, ob, nb, why in cuts.get(bid, []): lines.append(f' - cut `+{off:#x}`: {why}')
|
||||
for off, gate, word, why in obs.get(bid, []): lines.append(f' - gate {gate} at `+{off:#x}`: {why}')
|
||||
if bid in fs:
|
||||
sites, scale = frame_step_sites(fs[bid]); n_fs += len(sites)
|
||||
sites, scale, _, fs_caps = frame_step_sites(fs[bid]); n_fs += len(sites)
|
||||
fold = len(sites) > 12 # a long list (ASTRAL CHAIN's) folds
|
||||
if fold: lines += [f' <details><summary>{len(sites)} frame-step sites</summary>', '']
|
||||
for off, why in sites: lines.append(f' - frame step `+{off:#x}`: {why}')
|
||||
if fold: lines += ['', ' </details>', '']
|
||||
if scale: lines.append(' - render scale stub (the launcher offers DM_RENDER_SCALE)')
|
||||
if caps.get(bid): lines.append(f' - launcher capabilities: {", ".join(caps[bid])}')
|
||||
if caps.get(bid) or (bid in fs and fs_caps): lines.append(f' - launcher capabilities: {", ".join(sorted(set(caps.get(bid, ())) | set(fs_caps if bid in fs else ())))}')
|
||||
for p, n, what, _ in host.get(bid, []): lines.append(f' - host {link(p, n)}: {what}')
|
||||
for module, rules in mc.items():
|
||||
for r in rules:
|
||||
@@ -306,9 +312,12 @@ def page():
|
||||
lines.append(f'- **function-matched** (`{module}` of builds without CUTS): {r["name"]}: {len(fns)} function{"s" * (len(fns) > 1)}, {ncut} cut{"s" * (ncut > 1)}')
|
||||
for module, rules in mfs.items():
|
||||
for i, r in enumerate(rules):
|
||||
sites, _ = frame_step_sites(r['stub']); n_fs += len(sites) * (i == 0)
|
||||
sites, _, in_others, fs_caps = frame_step_sites(r['stub'], others=r.get('others', {})); n_fs += (len(sites) + sum(map(len, in_others.values()))) * (i == 0)
|
||||
lines.append(f'- **function-matched frame step** (`{module}` of builds without FRAME_STEP): {r["name"]}: a function of {r["size"]:#x} bytes, '
|
||||
+ ', '.join(f'`+{off:#x}`' for off, _ in sites) + ' in it')
|
||||
+ ', '.join(f'`+{off:#x}`' for off, _ in sites) + ' in it'
|
||||
+ ''.join(f'; {label}, a function of {r["others"][label]["size"]:#x} bytes, ' + ', '.join(f'`+{off:#x}`' for off, _ in got) + ' in it'
|
||||
for label, got in in_others.items())
|
||||
+ (f'; launcher capabilities: {", ".join(fs_caps)}' if fs_caps else ''))
|
||||
sections += lines + ['']
|
||||
n_host = sum(len(host.get(b, [])) for b in bids)
|
||||
kinds = {}
|
||||
|
||||
+17
-4
@@ -219,14 +219,21 @@ def validate_function(rule):
|
||||
|
||||
|
||||
def validate_stub(rule):
|
||||
"""A frame-step rule (patch_nso.py MATCH_FRAME_STEP): {name, size, fingerprints, stub}, stub(ctx) writing its sites at ctx.base + offsets inside the function"""
|
||||
if set(rule) != {'name', 'size', 'fingerprints', 'stub'}: raise ValueError('a frame-step rule needs name, size, fingerprints and stub')
|
||||
"""A frame-step rule (patch_nso.py MATCH_FRAME_STEP): {name, size, fingerprints, stub[, others]}, stub(ctx) writing its sites at ctx.base + offsets inside the function;
|
||||
others = {label: {size, fingerprints}} names more functions the stub patches, each found the same way (ctx.others[label], None when not exactly one matches)"""
|
||||
if not {'name', 'size', 'fingerprints', 'stub'} <= set(rule) <= {'name', 'size', 'fingerprints', 'stub', 'others'}:
|
||||
raise ValueError('a frame-step rule needs name, size, fingerprints and stub (and may name others)')
|
||||
validate_function(rule)
|
||||
if not callable(rule['stub']): raise ValueError('a frame-step rule\'s stub must be a function of the context')
|
||||
if not isinstance(rule.get('others', {}), dict): raise ValueError('a frame-step rule\'s others are {label: {size, fingerprints}}')
|
||||
for label, fn in rule.get('others', {}).items():
|
||||
if not isinstance(fn, dict) or set(fn) != {'size', 'fingerprints'}: raise ValueError(f'another function of a frame-step rule ({label}) needs size and fingerprints')
|
||||
validate_function(dict(fn, name=label))
|
||||
|
||||
|
||||
def locate_stub(image, text_end, rules, report=print):
|
||||
"""(rule, function start) of the one frame-step rule that matches, or None with a red line. Rules are one patch's reviewed implementations (one name): exactly one must match"""
|
||||
"""(rule, function start, others) of the one frame-step rule that matches, or None with a red line. Rules are one patch's reviewed implementations (one name): exactly one must
|
||||
match. others maps each of the rule's other functions to its start, or to None with a red line when not exactly one matches: the stub leaves that part out, the rest still goes in"""
|
||||
if not rules: return None
|
||||
for rule in rules: validate_stub(rule)
|
||||
names = {rule['name'] for rule in rules}
|
||||
@@ -244,7 +251,13 @@ def locate_stub(image, text_end, rules, report=print):
|
||||
return None
|
||||
(i, rule, start), = found
|
||||
report(f'frame step {name!r}: matched the function at {start:#x}' + (f' (implementation {i} of {len(rules)})' if len(rules) > 1 else ''))
|
||||
return rule, start
|
||||
others = {}
|
||||
for label, fn in rule.get('others', {}).items():
|
||||
try:
|
||||
others[label] = module.locate(fn['size'], fn['fingerprints']); report(f'frame step {name!r}: {label} at {others[label]:#x}')
|
||||
except MatchError as e:
|
||||
others[label] = None; report(f'[RED] frame step {name!r}: {label} left out: {e}')
|
||||
return rule, start, others
|
||||
|
||||
|
||||
def validate(rule):
|
||||
|
||||
+11
-6
@@ -84,7 +84,8 @@ else:
|
||||
# FRAME_STEP = {build ID: function(ctx)}: the frame step stubs of a main ("Frame step in whole vsyncs" below)
|
||||
# MATCH_FRAME_STEP = {'main': [{name, size, fingerprints, stub}, ...]}: the frame step stubs of any main without FRAME_STEP, placed by the function they patch (nso_match.locate_stub:
|
||||
# one complete unwind function of that size and fingerprint, or no stubs and a red line); stub(ctx) writes its sites at ctx.base + offsets inside that function. Rules are
|
||||
# one patch's reviewed implementations (one name). Only the profile selected by DM_GAME participates, as for MATCH_CUTS
|
||||
# one patch's reviewed implementations (one name). Only the profile selected by DM_GAME participates, as for MATCH_CUTS. A rule's others = {label: {size, fingerprints}}
|
||||
# are more functions its stub patches, found the same way: ctx.others[label] is the start of each, or None (a red line) when it does not match, and the stub leaves that part out
|
||||
# MATCH_CUTS = {module name: [nso_match rule, ...]}: fallback for modules without registered CUTS. Only the profile selected by DM_GAME participates; a derived profile uses
|
||||
# the repository's rules, an external-only provisional profile its own. Missing or ambiguous matches are reported and skipped; known builds retain their exact CUTS.
|
||||
# A rule of several functions applies whole or not at all. For such a module <name>.match.tsv lists the cuts of the profile's registered builds of it and each patch's result,
|
||||
@@ -1539,12 +1540,15 @@ obs += region_obs
|
||||
# State page = the page after the key page (zero in the file, read-write in both loaders): +0 float target fps written by the loader (fps_target, DM_FPS_TARGET; 0 = every stub
|
||||
# runs the original instructions), +4 30 fps movie/cinematic flag, +8 double lead (TOTK), +0x10 float render scale (TOTK, BotW), +0x18 double game seconds (TOTK),
|
||||
# +0x20 u32 step in vsyncs (host; 0 = not decided yet), +0x24 u32 a step the game fixes itself (BotW's VFR override; 0 = none), +0x28 u32 AoC's vsyncs per update, marked by
|
||||
# its first stub (0 = off), +0x30 u64 vsyncs stepped (the stubs; logged by the host to check the game's speed). Stub bodies assembled with clang
|
||||
# its first stub (0 = off), +0x30 u64 vsyncs stepped (the stubs; logged by the host to check the game's speed), +0x40 u32 1 = the game's own dynamic resolution runs, 0 = its
|
||||
# stub holds full resolution (DM_DYNAMIC_RESOLUTION, written by the loader; the stub declares the DYNAMIC_RESOLUTION capability). Stub bodies assembled with clang
|
||||
# A build's stubs are FRAME_STEP[build ID](ctx) in its patches.py: ctx.here() / ctx.emit(word) assemble into the patch area, ctx.site(offset, original bytes) asserts a site and that it is
|
||||
# no rewrite site, ctx.put(offset, words, reason) writes it (listed with the cuts), ctx.state is the state page's offset, and ctx.render_scale = 1 marks a render-scale stub
|
||||
# no rewrite site, ctx.put(offset, words, reason) writes it (listed with the cuts), ctx.state is the state page's offset, ctx.render_scale = 1 marks a render-scale stub,
|
||||
# ctx.others the other functions a MATCH_FRAME_STEP rule names, and ctx.capabilities.add(name) declares a launcher capability the stubs provide (written as CAPABILITIES are)
|
||||
FRAME_STEP = PATCHES['FRAME_STEP']
|
||||
FS_STATE_OFF = 0
|
||||
RENDER_SCALE = 0 # 1 = the build has a render-scale stub (state +0x10): the fixups table says so (RENDER_SCALE), and the iOS launcher offers the setting (dm/games/settings.tsv)
|
||||
FS_CAPABILITIES = set() # capabilities the frame step stubs declare (ctx.capabilities)
|
||||
if (BUILD_ID in FRAME_STEP or FS_MATCH) and NAME == 'main':
|
||||
FS_STATE_OFF = KEY_PAGE_OFF + 0x4000
|
||||
if FAR:
|
||||
@@ -1562,8 +1566,9 @@ if (BUILD_ID in FRAME_STEP or FS_MATCH) and NAME == 'main':
|
||||
for i, w in enumerate(words): struct.pack_into('<I', IMG, off + 4 * i, w)
|
||||
cuts.append((off, old.hex(), bytes(IMG[off:off + 4 * len(words)]).hex(), why + (' [function match]' if FS_MATCH else ''))); stat('frame_step')
|
||||
if FS_STATE_OFF: # the build's stubs (FRAME_STEP of its patches.py), or those placed by their function (MATCH_FRAME_STEP: ctx.base is its start)
|
||||
use_area(0); fs = types.SimpleNamespace(here=here, emit=emit, site=fs_site, put=fs_put, state=FS_STATE_OFF, render_scale=0, base=FS_MATCH[1] if FS_MATCH else 0)
|
||||
(FS_MATCH[0]['stub'] if FS_MATCH else FRAME_STEP[BUILD_ID])(fs); RENDER_SCALE = fs.render_scale
|
||||
use_area(0); fs = types.SimpleNamespace(here=here, emit=emit, site=fs_site, put=fs_put, state=FS_STATE_OFF, render_scale=0, base=FS_MATCH[1] if FS_MATCH else 0,
|
||||
others=FS_MATCH[2] if FS_MATCH else {}, capabilities=set())
|
||||
(FS_MATCH[0]['stub'] if FS_MATCH else FRAME_STEP[BUILD_ID])(fs); RENDER_SCALE = fs.render_scale; FS_CAPABILITIES = fs.capabilities
|
||||
|
||||
# ---- Spin waits (every module) ----
|
||||
# A guest loop that polls memory until another thread changes it fills only its own core on the Switch, where any higher-priority thread pinned there preempts it, so the
|
||||
@@ -1901,7 +1906,7 @@ with open(P('fixups.tsv'), 'w') as f:
|
||||
for n, o in UE_CVARS.items(): f.write(f'# UE_CVAR:{n}\t{o:#x}\n') # Unreal console variables (ue_cvar.py): the TAutoConsoleVariable registered under each name
|
||||
if RENDER_SCALE: f.write('# RENDER_SCALE\t1\n') # a render-scale stub reads state +0x10 (the loader ignores the key; dm/games/settings.py offers the setting by it)
|
||||
if NAME == 'main':
|
||||
for capability in PATCHES['CAPABILITIES'].get(BUILD_ID, ()):
|
||||
for capability in sorted(set(PATCHES['CAPABILITIES'].get(BUILD_ID, ())) | FS_CAPABILITIES):
|
||||
assert re.fullmatch(r'[A-Z][A-Z0-9_]*', capability), f'invalid capability {capability}'
|
||||
f.write(f'# {capability}\t1\n')
|
||||
f.write(f'# BUILD_ID\t{BUILD_ID}\n') # the host identifies the build by it: features with hard-coded addresses only run on the build they belong to
|
||||
|
||||
@@ -169,8 +169,15 @@ class Matching(unittest.TestCase):
|
||||
stub = dict(name='step', size=self.rule['size'], fingerprints=self.rule['fingerprints'], stub=lambda ctx: None)
|
||||
moved = image({0x800: caller(0x800, 0x1200, 0x2980), 0x1200: [0xd2800020, RET]})
|
||||
messages = []
|
||||
self.assertEqual(locate_stub(moved, 0x2000, [stub], messages.append), (stub, 0x800))
|
||||
self.assertEqual(locate_stub(moved, 0x2000, [stub], messages.append), (stub, 0x800, {}))
|
||||
self.assertFalse([m for m in messages if m.startswith('[RED]')], messages)
|
||||
# others: more functions the stub patches, found the same way; one that does not match is left out with a red line, the frame step itself still goes in
|
||||
leaf = Image(moved, 0x2000).fingerprint(0x1200)
|
||||
found = dict(stub, others={'leaf': dict(size=8, fingerprints=[leaf]), 'gone': dict(size=12, fingerprints=[leaf])})
|
||||
messages = []
|
||||
self.assertEqual(locate_stub(moved, 0x2000, [found], messages.append), (found, 0x800, {'leaf': 0x1200, 'gone': None}))
|
||||
self.assertEqual([m for m in messages if m.startswith('[RED]')], ["[RED] frame step 'step': gone left out: 0 matching functions (need exactly one)"])
|
||||
with self.assertRaisesRegex(ValueError, 'needs size and fingerprints'): locate_stub(moved, 0x2000, [dict(stub, others={'leaf': dict(size=8)})], messages.append)
|
||||
duplicate = image({0x100: caller(0x100, 0x500), 0x800: caller(0x800, 0x500), 0x500: [0xd2800020, RET]})
|
||||
for img in (duplicate, image({0x100: [RET]})):
|
||||
messages = []
|
||||
|
||||
@@ -94,7 +94,8 @@ class Registry(unittest.TestCase):
|
||||
for rule in rules: validate(rule)
|
||||
|
||||
def test_function_matched_frame_steps(self):
|
||||
# one frame step per main, in a game's own patches.py; its stub writes only inside the function it was matched by (docs_patches.frame_step_sites with that base)
|
||||
# one frame step per main, in a game's own patches.py; its stub writes only inside the function it was matched by and the other functions it names (docs_patches.frame_step_sites
|
||||
# with that base), and writes no site in another function it could not find (ctx.others[label] None)
|
||||
from nso_match import validate_stub
|
||||
for p, m in MODS.items():
|
||||
for module, rules in getattr(m, 'MATCH_FRAME_STEP', {}).items():
|
||||
@@ -102,9 +103,18 @@ class Registry(unittest.TestCase):
|
||||
self.assertTrue(rules); self.assertEqual(len({r['name'] for r in rules}), 1, f'{p}: a main has one frame step')
|
||||
for rule in rules:
|
||||
validate_stub(rule)
|
||||
sites, _ = docs_patches.frame_step_sites(rule['stub'], base=0x100000)
|
||||
sites, _, in_others, _ = docs_patches.frame_step_sites(rule['stub'], base=0x100000, others=rule.get('others', {}))
|
||||
self.assertTrue(sites, f'{p}: {rule["name"]} writes no site')
|
||||
for off, why in sites: self.assertTrue(0x100000 <= off < 0x100000 + rule['size'], f'{p}: {rule["name"]} site {off:#x} outside its function')
|
||||
for label, got in in_others.items():
|
||||
self.assertTrue(got, f'{p}: {rule["name"]} names {label} but writes no site in it')
|
||||
for off, why in got: self.assertTrue(0 <= off < rule['others'][label]['size'], f'{p}: {label} site {off:#x} outside its function')
|
||||
if rule.get('others'): # none found: the stub leaves those parts out
|
||||
rest = []
|
||||
ctx = docs_patches.types.SimpleNamespace(here=lambda: 0x8000000, emit=lambda w: None, site=lambda off, orig: None, put=lambda off, words, why: rest.append(off),
|
||||
state=0x9000000, render_scale=0, base=0x100000, others={label: None for label in rule['others']}, capabilities=set())
|
||||
rule['stub'](ctx)
|
||||
self.assertTrue(all(0x100000 <= off < 0x100000 + rule['size'] for off in rest), f'{p}: {rule["name"]} writes outside its function without its others')
|
||||
|
||||
def test_sdk_wide_rules_change_what_their_names_say(self):
|
||||
# the rules were taken from registered SDK cuts, and the builds they reproduce exactly have no row any more: each cut replaces the constant its rule names (0x3fe00000, the node
|
||||
|
||||
@@ -89,7 +89,7 @@ Every patch bound tighter than it could be: the open gaps, then the blocked, kep
|
||||
| [Taiko Risshiden V DX](#taiko-risshiden-v-dx) | 1 | 0 | 0 | 2 | 0 | `game` |
|
||||
| [The Legend of Zelda: Breath of the Wild](#the-legend-of-zelda-breath-of-the-wild) | 7 | 0 | 43 | 0 | 0 | `build` → `game` ×2 |
|
||||
| [The Legend of Zelda: Link's Awakening](#the-legend-of-zelda-links-awakening) | 1 | 0 | 0 | 0 | 0 | `build` → `game` |
|
||||
| [The Legend of Zelda: Ocarina of Time](#the-legend-of-zelda-ocarina-of-time) | 0 | 0 | 1 | 0 | 0 | `game` |
|
||||
| [The Legend of Zelda: Ocarina of Time](#the-legend-of-zelda-ocarina-of-time) | 0 | 0 | 2 | 0 | 0 | `game` ×2 |
|
||||
| [The Legend of Zelda: Tears of the Kingdom](#the-legend-of-zelda-tears-of-the-kingdom) | 0 | 0 | 9 | 0 | 0 | `build` → `game` |
|
||||
| [Xenoblade Chronicles 3](#xenoblade-chronicles-3) | 6 | 0 | 0 | 0 | 0 | `build` → `game` |
|
||||
|
||||
@@ -606,8 +606,9 @@ Every patch bound tighter than it could be: the open gaps, then the blocked, kep
|
||||
[The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md), `0400486024DEC000`, [patches.py](../../dm/games/0400486024DEC000/patches.py).
|
||||
|
||||
- **`game`**, frame rate, at goal, checked: v131072 main: one function with this fingerprint, the site and its free registers read by disassembly (2026-11-08): frame ratio from the host's step. The game's own frame-ratio division, found by its function's fingerprint on any build that keeps the function
|
||||
- **`game`**, rendering, at goal, checked: v131072 main: one function with this fingerprint (a leaf, x16 / x17 free), its callers and the controller read by disassembly (2026-11-08): dynamic resolution held at full size. The game's own dynamic-resolution level function, found by its function's fingerprint on any build that keeps the function; switchable (DM_DYNAMIC_RESOLUTION)
|
||||
|
||||
- **function-matched frame step** (`main` of builds without FRAME_STEP): frame ratio from the host's step: a function of 0x9b4 bytes, `+0xe4` in it
|
||||
- **function-matched frame step** (`main` of builds without FRAME_STEP): frame ratio from the host's step: a function of 0x9b4 bytes, `+0xe4` in it; dynamic resolution, a function of 0x294 bytes, `+0x0` in it; launcher capabilities: DYNAMIC_RESOLUTION
|
||||
|
||||
### The Legend of Zelda: Tears of the Kingdom
|
||||
|
||||
|
||||
@@ -496,6 +496,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- stalls of 30–60 ms about once a second, at 30 fps and at 60 (99th percentile 63–127 ms); the main thread waits 20–34 ms for the render thread once a second. → [Time-constraint computation declared below the thread's peaks](../reference/frame-rate.md#time-constraint-computation-declared-below-the-threads-peaks)
|
||||
- a movie or full-screen compute pass far slower than the same work should be, nearly all of it GPU time: `GPU p50` near the frame time with `submit+present` under 1 ms. `[RED] raw global memory: a write log ran out of slots` on older chains. With `DM_NVN_GPUPROF` a relaxed timestamp can put the time before the compute encoder's reported start, so the encoder itself looks short and the gap before it is what is long. → [A shader that writes a whole frame through raw global memory](../reference/frame-rate.md#a-shader-that-writes-a-whole-frame-through-raw-global-memory)
|
||||
- a game with dynamic resolution stays at its full size while the GPU runs far over budget: `GPU p50` above the frame time target, frame times locked to 2 vsyncs, and the same pass sizes frame after frame in `DM_NVN_GPUPROF`. → [Dynamic resolution that never moves, and draw passes that wait for each other](../reference/frame-rate.md#dynamic-resolution-that-never-moves-and-draw-passes-that-wait-for-each-other)
|
||||
- after a loading screen the game's resolution stays at its lowest (Ocarina of Time: 683x384) for minutes while it holds 60 fps with GPU time well under the frame, and climbs back only slowly or not at all. → [Dynamic resolution at its floor while the GPU has time to spare](../reference/frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare)
|
||||
- many passes a frame on the same attachments, with the residency set line showing `passes ended to land them for a read` in the thousands and `refused …: earlier submission running` matching it. Ocarina of Time: 10,463 per 300 frames, each ending the pass over a uniform block no GPU write touched. → [A full table of running GPU writes ends passes for nothing](../reference/frame-rate.md#a-full-table-of-running-gpu-writes-ends-passes-for-nothing)
|
||||
- a game that reads textures through a pool (Shaders report which textures they read through a pool) renders far below its maximum dynamic resolution: Ocarina of Time's main pass at 763x429 with the GPU at 17 ms a frame. → [A host's own store in a fragment shader moves its depth test](../reference/frame-rate.md#a-hosts-own-store-in-a-fragment-shader-moves-its-depth-test)
|
||||
|
||||
@@ -749,6 +750,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `DM_NVN_GPUPROF=every:1` prints no per-frame reports and fills its timestamp heap across frames. → [Periodic GPU profiles close at frame boundaries](../reference/rendering.md#periodic-gpu-profiles-close-at-frame-boundaries)
|
||||
- with `DM_NVN_GPUPROF`, the host aborts minutes in on `-[AGXG16XFamilyComputeContext_mtlnext writeTimestampWithGranularity:afterStage:intoHeap:atIndex:]: unrecognized selector`, `up_flush` on the stack; or a profiled render pass with a wrong GPU time. → [GPU profiles stamp only the encoder they began](../reference/rendering.md#gpu-profiles-stamp-only-the-encoder-they-began)
|
||||
- the 3D scene black (targets cleared again before they are read); `[RED] SetRenderEnableConditional: the host draws anyway`; with a game that skips clears under render conditions, scenes black behind the HUD (Mario vs. Donkey Kong's levels, 1.0.1). → [Conditional rendering evaluated at replay](../reference/rendering.md#conditional-rendering-evaluated-at-replay)
|
||||
- with `render_cond`, GPU time spent on objects the game's occlusion queries culled: a pass dump shows `conditional render … (unknown, drawn)` on query records whose submission completed long before. → [Occlusion conditions read once landed](../reference/rendering.md#occlusion-conditions-read-once-landed)
|
||||
- with `render_cond`, a 3D scene black or missing behind the HUD, only in scenes with many occlusion queries; a pass dump shows conditions reading `values 1 / 0` on a record a report of the same submission has just written, and clear-only passes on targets just drawn to. Scenes with fewer queries are fine. → [Report tables that dropped entries](../reference/rendering.md#report-tables-that-dropped-entries)
|
||||
- `[RED] visibility slots exhausted`. → [Query slots running out inside a pass](../reference/rendering.md#query-slots-running-out-inside-a-pass)
|
||||
- no SPIR-V file in the RomFS; SPIRV-Cross refuses a module with "Struct member does not have ArrayStride set". → [Vulkan shaders generated at run time](../reference/rendering.md#vulkan-shaders-generated-at-run-time)
|
||||
@@ -954,6 +956,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a storage buffer reported with `cb_slot` 3, which had no NVN slot. → [Storage buffer addresses in the game's own uniform buffer](../reference/shaders.md#storage-buffer-addresses-in-the-games-own-uniform-buffer)
|
||||
- whatever a shader writes through a pointer it read from memory never happens. The build summary counted `Failed to find storage buffer for global memory operation "Store"`, and the shader's MSL had a store function with an empty body. In Donkey Kong Bananza the tunnel's walls and floor were black and only the loose rocks drew. → [Global memory at an address loaded from memory](../reference/shaders.md#global-memory-at-an-address-loaded-from-memory)
|
||||
- a pass whose shaders read memory through loaded addresses takes several milliseconds on the GPU for little work. `[gpuprof]` names the pass, and its shaders' build notes say `Global memory operation "Load" traced to no storage buffer`. Ocarina of Time's foliage mesh shader `73dc0b90c4082e43` (`Foliage.Product.110`, 135 such reads) took 10.9 ms of a 683x384 frame; 2,241 of the game's shaders (vertex, compute, fragment and mesh) have such a lookup, some hundreds of them. → [Raw global memory lookups that start from their last entry](../reference/shaders.md#raw-global-memory-lookups-that-start-from-their-last-entry)
|
||||
- a pass of mesh, vertex or compute shaders whose build notes say `Global memory operation "Load" traced to no storage buffer` takes milliseconds of its stage's time for little drawing, at any resolution. Metal System Trace's Shader Timeline shows no samples for task and mesh shaders, so such a pass looks idle there; the encoder's vertex-stage time and an overlay A/B tell. Ocarina of Time's foliage mesh pass took 4.6 ms of vertex-stage time a frame at 683x384, 0.2 ms of fragment. → [128-bit raw global loads read one word at a time](../reference/shaders.md#128-bit-raw-global-loads-read-one-word-at-a-time)
|
||||
- `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct). → [Bindless handles through a loop phi](../reference/shaders.md#bindless-handles-through-a-loop-phi)
|
||||
- none in the log: texture reads come back 0. Particle meshes collapse to a point (their scale reads 0), so effects are missing or show as dark patches. The translator's own message (`Failed to find handle source for bindless access of type "textureBuffer"`) used to be dropped, because `dmsh_xlate`'s accessor had no `Log`; its messages now go into the shader's notes, marked `translator: `, and the build summary counts them apart from unanswered queries. → [Bindless reads whose handle phi also carries other values](../reference/shaders.md#bindless-reads-whose-handle-phi-also-carries-other-values)
|
||||
- the shaders' bindless arrays have no slot and used not to load; the translator falls back to a 32-entry array such as `array<texture_buffer<float>, 32> vp_tb_cb0_40000000`. → [Texture slots picked at run time](../reference/shaders.md#texture-slots-picked-at-run-time)
|
||||
|
||||
@@ -28,7 +28,7 @@ DM_DBG_AU_FRAMES diagnostic `=<frames>` asks the Mac's Core Audio output for tha
|
||||
DM_DETCLOCK switch `=<step ns>`: from the first present on, the guest clock advances a fixed step per present instead of following the wall clock, and the random source becomes a fixed-seed stream (replay and test runs)
|
||||
DM_DETCLOCK_PACE switch `=1` with `DM_DETCLOCK`: each frame takes at least one clock step of wall time, so background loading keeps up with the fixed clock (used by the screenshot gate)
|
||||
DM_DISPLAY_NAME switch Overrides the iOS app's name in `build_ipa.sh` (default the game name in the base NSP's control data)
|
||||
DM_DYNAMIC_RESOLUTION player `1` lets NieR:Automata 1.0.3's own dynamic resolution scale between 70 and 100 %, `0` (default) keeps full resolution; only on the builds whose patches.py names the DYNAMIC_RESOLUTION capability (`hle_fpslock.c` `k_nier_dr`). The launcher's Dynamic resolution
|
||||
DM_DYNAMIC_RESOLUTION player `1` lets the game's own dynamic resolution run, `0` (default) keeps full resolution; only on the builds that declare the DYNAMIC_RESOLUTION capability: NieR:Automata 1.0.3 (its patches.py; scales between 70 and 100 %, `hle_fpslock.c` `k_nier_dr`) and Ocarina of Time (its frame step stub of the level function, state page +0x40). The launcher's Dynamic resolution
|
||||
DM_EMBED_TAG path Set by the iOS app of a game of several programs: the tag of the running program's embedded sections (`p<N>`, `gen_embed.py --tag`)
|
||||
DM_ENTITLEMENTS path `=<plist>` gives a prepared Xcode project another entitlements file instead of the Increased Memory Limit one, and the ad-hoc signature of the unsigned IPA's executable carries them; empty means no entitlements
|
||||
DM_ENV_FILE path `=<file>` makes `build_ipa.sh` bake its `KEY=VALUE` lines into the app as `dm/env.txt`, applied at boot; `Documents/env.txt` overrides them
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 19 and column 104.
|
@@ -502,6 +502,14 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
|
||||
- **Open:** the main pass at about 763x429 is a low resolution, and the GPU at about 17 ms is still a little over budget, so the frame rate is not locked.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md).
|
||||
|
||||
### Dynamic resolution at its floor while the GPU has time to spare
|
||||
|
||||
- **Symptom:** after a loading screen the game's resolution stays at its lowest (Ocarina of Time: 683x384) for minutes while it holds 60 fps with GPU time well under the frame, and climbs back only slowly or not at all.
|
||||
- **Cause:** two host errors made the game's frame timer read more GPU time than its frame took. (1) A segment report reads its time from the timestamp heap slot of its boundary. An encoder with no work writes no relaxed timestamp, so the slot kept the ring's value from a frame long ago: Ocarina's frame-start `TIMESTAMP_TOP`, alone in its submission, read 1.7 s early, and its controller saw a frame of 1.7 s. (2) A queue continuation that waited on an event parked until the signalling submission completed on the GPU. About 25 waits a frame each left the GPU idle while the host encoded the next submission, about 2 ms of a 14.5 ms frame, which the frame-start-to-end timestamps count as GPU work.
|
||||
- **Fix:** (1) `rep_ticks` (`nvn_mtl.m`) drops a heap time from before its submission began encoding (`g_ts_begin`, kept in the segment clock) and takes the segment's feedback time instead. (2) [A wait on a queued WRITE signal is released at encode](nvn-objects.md#gpu-event-waits-order-work-across-queues). The game then read a 13.8 ms span instead of 14.5 and climbed to full resolution in about 25 s instead of staying at its floor.
|
||||
- **Ruled out:** the GPU clock. With macOS's `mactop` sampling during play, the GPU held about 1,562 MHz at 94% active on the M4 Pro with and without moving presentation to its own Metal queue, which removed 6 ms of idle per frame but did not change GPU time.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#dynamic-resolution), M4 Pro. Its controller and the switch that holds it at full size are in the game note.
|
||||
|
||||
### A full table of running GPU writes ends passes for nothing
|
||||
|
||||
- **Symptom:** many passes a frame on the same attachments, with the residency set line showing `passes ended to land them for a read` in the thousands and `refused …: earlier submission running` matching it. Ocarina of Time: 10,463 per 300 frames, each ending the pass over a uniform block no GPU write touched.
|
||||
|
||||
@@ -294,7 +294,8 @@ Games read this count as a position in their own command memory and size their h
|
||||
- **Symptom:** intermittent scene-wide lighting flashes and a persistent pale outline around a character. Extra GPU readbacks or synchronous screenshots can make the flashes disappear temporarily.
|
||||
- **Cause:** `nvnCommandBufferWaitEvent` was registered as a no-op. Serializing NVN submissions onto one Metal queue only orders them by CPU arrival; a consumer can be submitted before its producer on another NVN queue. Its acquire must park that queue until the producer releases the event. The native SDK implements exact equality and wrapping greater-or-equal (`(uint32_t)(current - target) < 0x80000000`), and its CPU event signal publishes earlier writes with a store barrier. Ignoring either dependency lets a consumer read cleared or stale shared data.
|
||||
- **Fix:** `nvn_queue.inc` retains submitted command streams and replays ready continuations. An unresolved event or sync wait parks only its NVN queue; another queue can submit and execute its producer. GPU event signals end physical submission prefixes and publish after their completion writes, including render-target readback. CPU signals publish with release ordering. Logical queue receipts remain separate from physical Metal fences: a fence on parked work cannot accidentally inherit another queue's completion, and a queued sync wait retains its original target through later refencing. Presents remain in queue order. Descriptor snapshots and retained renderer objects survive deferred replay; the caller still owns backing-memory lifetime.
|
||||
- **Check:** `t_wait_event` exercises public NVN calls, CPU and GPU producers, wrapping predicates, a consumer submitted before its producer, and logical sync lifetime. `t_queue_lifetime` checks submitted program/texture descriptor reuse and inherited queue bindings. The focused event, receipt, descriptor and lifecycle checks pass; combined gameplay and performance validation are still pending.
|
||||
- **Waits on a queued signal:** a wait the last GPU `WRITE` signal of its event satisfies, still in flight, is released when the host encodes it: its continuation runs after the writer on the one ordered Metal queue, as a later submission of the same NVN queue would, and the reports and readbacks the writer's completion lands are handled as for any in-flight submission. Waiting for the writer's completion instead left the GPU idle while the host encoded the next submission (Ocarina of Time: about 25 waits a frame, 2 ms of a 14.5 ms frame, which its dynamic resolution counted as GPU time: [Dynamic resolution at its floor](frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare)). An `ADD` signal's result depends on the writes landing before it, so a wait on it still waits for its completion.
|
||||
- **Check:** `t_wait_event` exercises public NVN calls, CPU and GPU producers, wrapping predicates, a consumer submitted before its producer, a wait on an in-flight `WRITE` (encoded before it completes) and `ADD` (parked until it lands), and logical sync lifetime. `t_queue_lifetime` checks submitted program/texture descriptor reuse and inherited queue bindings. The focused event, receipt, descriptor and lifecycle checks pass; combined gameplay and performance validation are still pending.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#open), M4 Pro. Its traced lighting producer and ambient-cache consumer have an explicit event dependency; this is a general queue contract, with no shader-key or game check in the fix.
|
||||
|
||||
### Bindings belong to each queue
|
||||
|
||||
@@ -1262,13 +1262,20 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
|
||||
|
||||
- **Symptom:** the 3D scene black (targets cleared again before they are read); `[RED] SetRenderEnableConditional: the host draws anyway`; with a game that skips clears under render conditions, scenes black behind the HUD (Mario vs. Donkey Kong's levels, 1.0.1).
|
||||
- **Cause:** by default the host draws everything a `SetRenderEnableConditional` would skip. A game that wraps clears in `SetRenderEnableConditional(RENDER_IF_NOT_EQUAL, rec)` … `SetRenderEnable(true)`: the condition compares the 64-bit counters at `rec` and `rec + 16`. A timestamp report puts 0 in the counter field (the time goes in the second field). The host ignored the condition and wrote the time into both fields, so every clear ran.
|
||||
- **Fix:** profile key `render_cond`: `OP_RENDER_COND` is evaluated at replay from the records in memory. A timestamp report replayed earlier in the same submission counts as 0, and a condition on a samples-passed result (an occlusion query, known only when the GPU completes) keeps drawing. A pass dump shows the switches as `E` lines (`conditional render … → not drawn`) and a skipped clear as `c … skipped by conditional rendering`.
|
||||
- **Fix:** profile key `render_cond`: `OP_RENDER_COND` is evaluated at replay from the records in memory. A timestamp report replayed earlier in the same submission counts as 0. A condition on a samples-passed result (an occlusion query, written when its submission completes) keeps drawing while that report is in flight, and once it has landed is evaluated from it, as the GPU would at that point in the queue ([Occlusion conditions read once landed](#occlusion-conditions-read-once-landed)). A pass dump shows the switches as `E` lines (`conditional render … → not drawn`) and a skipped clear as `c … skipped by conditional rendering`.
|
||||
- **Found on:**
|
||||
- [The Legend of Zelda: Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md): TOTK wraps nearly every `ClearColor` / `ClearDepthStencil` this way; each clear is followed by `ReportCounter(TIMESTAMP_TOP, rec)`, the CPU sets `rec` to 1 when a target needs a clear, and `rec + 16` is never written, so after one clear the two are equal and later conditional clears of that target are skipped. The first tile-lighting round, the half-resolution scene depth the light volumes test against (back faces `GREATER` against a buffer just cleared to 1.0 can never pass) and the light accumulation were all cleared before the composite read them.
|
||||
- [Mario vs. Donkey Kong](../../dm/games/0100B99019412000/README.md) (it skips clears under render conditions, as Tears of the Kingdom and Animal Crossing: New Horizons do).
|
||||
- Drawn unconditionally with no `render_cond`, nothing looked wrong in [Big Brain Academy: Brain vs. Brain](../../dm/games/0100620012D6E000/README.md) (no screen played looked wrong) or [DARK SOULS: REMASTERED](../../dm/games/01004AB00A260000/README.md) (nothing seen).
|
||||
- [Portal 2](../../dm/games/0100ABD01785C000/README.md) needs no `render_cond` and must not get it: NVIDIA's occlusion culling in its D3D9 layer (`IDirect3DDevice9::SetOcclusionShape`, `materialsystem.nro+0xc1130`) puts a mesh under `SetRenderEnableConditional(RENDER_IF_NOT_EQUAL, pair)` when its shape has a query, else `SetRenderEnable(true)`, so drawing everything only costs GPU time. With the key on, those conditions read 0 / 0 at replay (no report in the submission writes the pairs; memory later held `0xffff` / 0) and visible furniture vanished. **Open:** who writes those pairs and when.
|
||||
|
||||
### Occlusion conditions read once landed
|
||||
|
||||
- **Symptom:** with `render_cond`, GPU time spent on objects the game's occlusion queries culled: a pass dump shows `conditional render … (unknown, drawn)` on query records whose submission completed long before.
|
||||
- **Cause:** every address a samples-passed report ever wrote counted as unknown at replay, landed or not (`rc_occ_has`, later the report's `conservative` mark), so every draw under an occlusion condition was made. The report table already knows when a report has landed: its submission's fence against `g_rc_complete`, with later buffer writes and GPU writes tracked.
|
||||
- **Fix:** only counter kinds the host does not implement stay conservative (`rc_note`); a landed samples-passed result is read like a landed timestamp one (`rc_value`), and a report still in flight keeps the block drawing.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md): it reports its queries a submission ahead of the conditional draws, so all of them had landed at replay (1.48 million conditions on the Kokiri Forest route, 0 in flight, 42% false). GPU p50 17.06 → 16.44 ms and p95 18.74 → 18.01 ms a frame on a 20-core M4 Pro (two runs each), picture unchanged. Skipping every unknown block instead (the visible ones too) whitened the scene for good: only the evaluated condition is a valid skip.
|
||||
|
||||
### Report tables that dropped entries
|
||||
|
||||
- **Symptom:** with `render_cond`, a 3D scene black or missing behind the HUD, only in scenes with many occlusion queries; a pass dump shows conditions reading `values 1 / 0` on a record a report of the same submission has just written, and clear-only passes on targets just drawn to. Scenes with fewer queries are fine.
|
||||
|
||||
@@ -1582,9 +1582,17 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Cause:** each 32-bit word found its pool on its own ([Global memory at an address loaded from memory](#global-memory-at-an-address-loaded-from-memory)): the hint of its 2 MiB chunk, and on a miss the 13-step search of the pool table. A shader reads a structure word after word from one pool, so all but the first lookup of a run chose the entry the first one chose.
|
||||
- **Fix:** general, in the translator (`GlobalToStorage.TryGenerateRawStorageOp`). Each helper keeps the entry it chose last in a private word of the invocation (`ResourceManager.AddRawLastEntryMemory`, zero at the start through a SPIR-V null initializer, `MemoryDefinition.ZeroInit`; spirv-cross declares it `uint _N = 0u;` in `main0` and passes it to the helper). An address inside that entry's range takes it without the hint or the search; a hint or a search records its choice. Loads, stores and atomics all do it, and a store's write log bit is the chosen entry's. It holds because the table's ranges are disjoint (`nvn_mtl.m` `gmem_map`) and the host binds one table for a whole draw or dispatch; entry 0 is empty, so an invocation's first lookup searches. `dmsh_meshstage.py` keeps thread variables declared ahead of the stage memory in `dm_stage_body`: until then Ocarina of Time's 98 mesh and 11 task shaders with such a lookup failed the mesh stage (`no kernel main0 starting with its stage memory`).
|
||||
- **Check:** `dm/gfx/tests/test_dmsh_raw_last.py`: the translated helper's shape, and on the GPU its reads over runs of addresses that stay in, leave and come back to pools (adjacent pools, a gap, a hinted chunk above 4 GiB); without the cached entry's end check 768 of its 1,024 reads go wrong. `test_dmsh_meshstage.py` for the thread variables. Ocarina of Time on an M6 Mac (macOS 27.2), main's host, the 2,241 shaders of the new chain laid over main's libraries (the other 2,592 shaders built with them came out with the same MSL), the same scripted walk from `save_ref` with warmed pipeline archives, two runs a side: at the spawn point right after loading (the same view, about 2,500 draws a frame) the GPU span p50 went 16.53 / 16.41 → 14.11 / 14.57 ms, and over the walk 15.7 → 14.0 ms. Screenshots at the spawn point match, and so do the red lines.
|
||||
- **Open:** over the walk the frame time p95 went 19 → 26 ms. The runs ended in different places (the route is timed and the game moves at its frame rate), the new side's render target loads were higher (the game's dynamic resolution taking the headroom), and the Mac had 8 GB of swap in use, so this is not settled. Keeping the range itself in registers (PR #1464's form, no table reads on a hit) has not been compared on the same Mac.
|
||||
- **Open:** over the walk the frame time p95 went 19 → 26 ms. The runs ended in different places (the route is timed and the game moves at its frame rate), the new side's render target loads were higher (the game's dynamic resolution taking the headroom), and the Mac had 8 GB of swap in use, so this is not settled. Keeping the range itself in registers (PR #1464's form, no table reads on a hit), tried on an M4 Pro (2026-11-08) as an overlay of Ocarina's eleven hot task and mesh shaders, changed nothing (GPU p50 16.45 → 16.61 ms, two runs each): the table reads hit the cache. The time went to the words of each 128-bit load being read one by one ([128-bit raw global loads read one word at a time](#128-bit-raw-global-loads-read-one-word-at-a-time)).
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md); the diagnosis, the cache and the first measurements in [PR 1464](https://github.com/seedds/nxnative/pull/1464) and [PR 1405](https://github.com/seedds/nxnative/pull/1405#issuecomment-6678379920).
|
||||
|
||||
### 128-bit raw global loads read one word at a time
|
||||
|
||||
- **Symptom:** a pass of mesh, vertex or compute shaders whose build notes say `Global memory operation "Load" traced to no storage buffer` takes milliseconds of its stage's time for little drawing, at any resolution. Metal System Trace's Shader Timeline shows no samples for task and mesh shaders, so such a pass looks idle there; the encoder's vertex-stage time and an overlay A/B tell. Ocarina of Time's foliage mesh pass took 4.6 ms of vertex-stage time a frame at 683x384, 0.2 ms of fragment.
|
||||
- **Cause:** the emitters split an `LDG.64` / `LDG.128` into 32-bit loads (`InstEmitAmpereMem.ALdg`, Maxwell's `InstEmitMemory.EmitLdg`), each with its own 64-bit address. Traced to no storage buffer, each word then went through the pool table on its own ([Raw global memory lookups that start from their last entry](#raw-global-memory-lookups-that-start-from-their-last-entry)) and was read through a pointer of its own, built from two 32-bit halves. Metal's compiler cannot see that four such pointers are consecutive, so one 128-bit read became four word loads, each waiting on its own address. Ocarina's foliage mesh shader `eed1add7c89f5d34` read 464 of its 506 raw words as pieces of 116 such loads. Measured on an M4 Pro: the lookups' table reads cost nothing (kept in registers, no change), and the reads were the time (replaced by a value made from the address, the frame's GPU time fell 16.8 → 13.0 ms).
|
||||
- **Fix:** general, in the translator. The emitters mark the words of one access (`Operation.GlobalVectorCount`, `GlobalVectorWord`). For such an access whose address goes through the pool table, `GlobalToStorage` (`ReplaceGlobalMemoryWithStorage`, `GenerateRawVectorLoad`) calls a vector helper once (`…RawV2` / `…RawV4`, `TryGenerateRawStorageOp`): the first word's lookup, then one 64- or 128-bit load through a physical pointer (`StorageKind.GlobalMemoryVector`, the SPIR-V backend's `GenerateRawVectorLoad`, aligned as a word like the scalar loads). Word 0 is returned and the others go to the shader's `gmem_vec` local memory, which the loads of those words read right after the call (they become copies, so the pass does not take them for global accesses again). The first word's entry holds the whole access: an `LDG.64` / `LDG.128` is aligned to its size on the GPU, and every pool table entry starts and ends on a pool's 4 KiB boundary (`nvn_mtl.m gmem_map`). Ocarina's `eed1add7c89f5d34` makes 122 vector calls and 22 word calls instead of 506 word calls, and its MSL shrinks from 7,949 to 5,656 lines.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md): the Kokiri Forest route (`bench.tsv` `kokiri-deck`, its partial shader set rebuilt, with [occlusion conditions read once landed](rendering.md#occlusion-conditions-read-once-landed)) on a 20-core M4 Pro went from GPU p50 16.3 / p95 18.6 ms at 34.7 fps (a 30 fps frame step) to 12.6 / 13.6 ms at 51.8 fps, frame p50 16.69 ms (60 fps most of the time), two runs each, picture unchanged.
|
||||
- **Check:** `dm/gfx/tests/test_dmsh_raw_last.py` `RawVector` (with `DMSH_TEST_XLATE`): an `LDG.E.128` through an untraced address translates to one call of a helper with one `uint4` load and no word call, and on this Mac's GPU each of its four words is the pool's.
|
||||
|
||||
### Bindless handles through a loop phi
|
||||
|
||||
- **Symptom:** `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct).
|
||||
|
||||
@@ -27,6 +27,10 @@ Games whose speed the app controls (Breath of the Wild, Tears of the Kingdom and
|
||||
|
||||
On a Mac, a game checked at that speed (Fire Emblem Fortune's Weave, Mario & Luigi: Brothership) also offers **120 fps**. It needs a screen that shows 120 Hz, and uses more GPU and power. When frames do not fit, during movies, or on a slower screen, the game drops to 60 for a while, so it keeps its real speed. If you see the frame rate move between 60 and 120 and would rather it stayed still, choose 60.
|
||||
|
||||
### Dynamic resolution
|
||||
|
||||
Off, the default, keeps the 3D picture at full size. On lets the game lower its resolution when frames run heavy, as on the Switch: steadier frame rate, softer picture. Only games whose resolution control the app can hold offer it (NieR:Automata, Ocarina of Time).
|
||||
|
||||
### Render scale
|
||||
|
||||
The size of the 3D picture, from 50 to 100 %. Below 100 % the size is fixed there and the game's own dynamic resolution is off; 100 % keeps the game's own. Lower can be lighter on the GPU but is blurrier; the HUD and text keep their sharpness. Only games the app can scale offer it.
|
||||
|
||||
Reference in new issue
Block a user