Skip to content

Load in-game shader libraries and pipelines in the background - #30

Closed
tvc97 wants to merge 6 commits into
ly05010419:mainfrom
tvc97:perf/async-shader-loading
Closed

tvc97 wants to merge 6 commits into
ly05010419:mainfrom
tvc97:perf/async-shader-loading

Conversation

@tvc97

@tvc97 tvc97 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When play reaches a shader variant or render pipeline it hasn't used before, the Metal library (newLibraryWithSource) and the pipeline are compiled on the submit thread, inside the frame. On a cold cache, that is the in-game stutter: frames of 0.5–17 s, mostly while entering new areas and loading a save.

With TOTK_ASYNC_SHADERS (default 1), this PR compiles vertex/fragment libraries and normal-pass pipelines in the background:

  • The submit thread waits at most TOTK_SHADER_STALL_MS (default 4 ms), so anything already in the system Metal cache is never skipped.
  • Otherwise, the draws that need the shader or pipeline are skipped until it is ready, usually a few frames.

These stay synchronous: translation, compute, merged-pass/specialised-fragment pipelines, and iOS. TOTK_ASYNC_SHADERS=0 restores the previous behaviour completely.

Results (cold cache, same save and route, Apple M4, 4 runs per mode; details below):

Sync This PR
Average FPS on the route 26.6 59.3
p99 frame 579 ms 71 ms
Worst frame 13.1 s 1.7 s
Frames > 500 ms 22.2 3.5
Time lost to frames > 50 ms 42.0 s 10.1 s
Save load → gameplay 60.0 s 22.5 s

Relation to open PRs

Changes (nvn_mtl.m, hle_nvn.c, totk_shader_rt.*)

  • Libraries. prog_get / prog_fit call shader_get_async. It queues shader_load on a background queue, once per variant, and waits up to the budget. If the library is still loading, it marks the stage pending (NvProg.pend*) and the draw is skipped as shader-loading. mtl_sub_begin publishes finished loads (shload_drain). Programs pick them up through prog_retry / prog_fit (-2), with the binding signature the variant was translated for. A failed load is still MDIE when a program needs it, as before.
  • Pipelines. A normal-pass miss is kicked into the pending table as a demand slot and polled with the same budget (pso_pend_poll). If it isn't ready, the draw is skipped as pipeline-pending, not reported as a failed pipeline. If the table is full, the pipeline compiles synchronously as before. Prediction skips programs with a stage still loading.
  • Fix: present residency. present_now now calls res_commit() after taking its source texture.
    • With every frame-1 draw skipped, nothing has rendered into the presented texture, so tex_mtl creates and uploads it inside present_now. It was not resident when the present command buffer ran.
    • This showed up as a GPU page fault (上屏命令缓冲错误 … PageFault) in 4 of 14 empty-cache async boots. With the fix: 0 of 12. Sync mode had none in 12 boots either way.
  • Compile-options race. totk_precise_opts() published its MTLCompileOptions before setting safe math, so a concurrent first compile could use fast math. Upstream has since fixed this the same way, and this branch now uses upstream's version.
  • Logging.
    • [长帧] splits library and pipeline time and adds translations made in the frame (totk_rt_xlate_stats), appended after the existing text.
    • The draw-skip summary gains pipeline-pending / shader-loading.
    • A new 300-frame [nvn] 后台载着色器库 line reports background loads queued / finished / failed, with their average and longest time.
  • Docs. docs/async-shader-loading.md (design, trade-offs, method, all numbers) and a README line in English and Chinese.

Measurements

Method.

  • Same build for both modes, differing only in TOTK_ASYNC_SHADERS. Runs went in the order A/B/B/A/B/A/A/B.
  • Each run starts cold:
    • a fresh copy of one profile, with the newest save autoloaded;
    • an empty translation cache;
    • the system Metal cache bypassed (MTL_SHADER_CACHE_SIZE=0), so every library and pipeline compiled cold, as on a first visit to an area;
    • TOTK_WARM_PARALLEL=0, the warm-up behaviour on main.
  • Route. Once gameplay frames were flowing (more than 1,000 draws per frame for 6 s), plus 10 s to settle, a scripted 69 s route ran: camera turns, two sprints, then a look around.
  • Data. Frame times come from DM_NVN_TSV, and the cost breakdown from [长帧].

The 8-run comparison above used a local build with the same async code plus some other open PRs. This branch was then checked with two more pairs: one before the two fixes, one with them.

This branch Sync Async Sync (final) Async (final)
Average FPS on the route 31.4 60.5 39.1 59.3
p99 frame 166 ms 65 ms 429 ms 81 ms
Worst frame 16,281 ms 1,138 ms 2,677 ms 892 ms
Frames > 500 ms 15 5 21 3
Time lost to frames > 50 ms 38.0 s 9.3 s 27.5 s 9.9 s
Save load → gameplay 59.6 s 23.7 s 62.2 s 23.6 s

Where the time in frames over 100 ms went, averaged per run:

Library creation Pipeline creation Translation
Sync 33.2 s (79%) 5.3 s (13%) 3.0 s (7%)
Async 2.1 s 1.1 s 5.5 s

Notes:

  • Async covered more ground. A stall also stops game time, so the async runs travelled further and met more new shaders (280–347 background library loads per run).
  • What's left is mostly translation. It is still synchronous; making it async (copying the guest shader bytes first) is the natural next step.
  • The 50–100 ms band is slightly larger with async. Async presents 2.3 times as many frames, and those frames are mostly translation.
  • Skipped draws per async run: about 900–1,350 pipeline-pending and 1,800–3,100 shader-loading, out of about 4,000 frames. No background load failed.
  • No visible damage. End-of-route screenshots show nothing missing. The red log lines are identical between the modes, apart from the fixed fault.

After merging the latest upstream main

Upstream's title-first startup and multi-threaded warm-up are now merged into this branch.

  • Checks: the build has 58 warnings, all 68 source tests pass, probe-gfx passes, and 2 empty-cache async boots each showed the first frame after about 290 ms, with no GPU fault.
  • One more cold-cache gameplay pair, same method:
Sync Async
Average FPS on the route 36.6 62.1
p99 frame 490 ms 48 ms
Worst frame 2,525 ms 1,441 ms
Frames > 500 ms 21 4
Time lost to frames > 50 ms 27.9 s 7.9 s
Save load → gameplay 61.5 s 20.5 s

Trade-off

Objects or effects whose library or pipeline is still compiling are missing for those frames, so things can appear a moment late. A pass drawn only once while its work is pending (a capture or a baked texture) stays wrong until the game draws it again. Occlusion queries around a skipped draw read 0. Compute dispatches are never skipped.

Tests

🤖 Generated with Claude Code

A shader variant or render pipeline met for the first time in play was
compiled on the submit thread, inside the frame. With TOTK_ASYNC_SHADERS
(default 1), vertex/fragment libraries and normal-pass pipelines now
compile in the background. The submit thread waits up to
TOTK_SHADER_STALL_MS (default 4 ms), then skips the draws that need them
until they are ready. Translation, compute and merged-pass pipelines stay
synchronous. TOTK_ASYNC_SHADERS=0 restores the old behaviour.

- shader_get_async / shload_drain / prog_retry, plus prog_fit's
  pend_alt: background library loads and how programs pick them up.
- Pipeline misses become demand slots in the pending table, polled by
  pso_pend_poll. ly05010419#29's stale-guess reclaim skips demand slots.
  Prediction skips programs that have a stage still loading.
- present_now commits the residency set after taking its source. With
  every frame-1 draw skipped, tex_mtl creates the presented texture
  there, and it was not resident: a GPU page fault in 4 of 14
  empty-cache async boots, 0 of 12 after this.
- totk_precise_opts() is set up with dispatch_once. It published the
  options before setting safe math, which a concurrent first compile
  could pick up.
- Logging: draw skips "pipeline-pending" / "shader-loading"; [长帧]
  splits library / pipeline time and adds translation time; a 300-frame
  summary of background library loads.

Cold-cache A/B on an Apple M4 (TOTK 1.4.3, empty translation cache,
system Metal cache bypassed, same save and 69 s scripted route, 4 runs
per mode): average FPS 26.6 -> 59.3, p99 frame 579 -> 71 ms, worst
frame 13.1 s -> 1.7 s, time lost to frames over 50 ms 42.0 -> 10.1 s,
save load to play 60 -> 22.5 s. See docs/async-shader-loading.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tvc97 added a commit to tvc97/MacNativeGames that referenced this pull request Oct 19, 2026
…05010419#30)

Brings in upstream ly05010419#29 (bounded pipeline prediction without translation,
stale guesses reclaimed) and ly05010419#30 (in-game libraries and pipelines in the
background, plus the present residency and compile-options fixes).

Conflict resolution in nvn_mtl.m / hle_nvn.c: took the branch side,
re-applied what main has since ly05010419#29's base (ly05010419#13 warm_precompile, ly05010419#17
compact HUD), and kept main's prebuilt-library hit/miss diagnostic.
Our earlier prediction-table drain (pso_pend_drain into g_pso,
prog_get_cached, mtl_pp_stats and its log line) is replaced by ly05010419#29's
version. It no longer skips pso_user.tsv for drained pipelines.

Checked: make runtime-v143 (58 warnings, none new), 38 source tests,
probe-gfx pass, 3 empty-cache async boots without a GPU fault.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tvc97 and others added 2 commits October 19, 2026 15:48
Conflicts:
- totk_precise_opts(): upstream fixed the same race with dispatch_once,
  for its multi-threaded warm-up. Took upstream's version.
- g_rt_prebuilt / g_rt_compiled: upstream made them atomic too. Took
  upstream's comment.
- README: kept the async-loading line and took upstream's test-count
  lines.

Upstream's other shader writers (warm_claim) still run on the submit
thread, so the async design is unchanged.

Checked: make runtime-v143 (58 warnings), 68 source tests, probe-gfx
pass, 2 empty-cache async boots with the title-first startup (first
frame after about 290 ms, no GPU fault). One cold-cache gameplay pair:
average FPS 36.6 -> 62.1, p99 490 -> 48 ms, time lost to frames over
50 ms 27.9 -> 7.9 s, save load to play 61.5 -> 20.5 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tvc97 and others added 2 commits October 19, 2026 17:18
Upstream merged ly05010419#29 with follow-ups (c5b3ae7): prediction limits and
statistics, and probe-gfx negative controls 24-27. Conflicts in nvn_mtl.m:
- prog_prediction_stages: upstream's missing-stage skip with negative 26;
  pr->missing also covers stages still loading in the background.
- pso_pend_reclaim: keeps demand slots (a draw waits for them), and takes
  upstream's negative 25 and reclaim count.
- pso_pend_kick: keeps the demand flag and upstream's table-full count.
- pso_predict_rest: upstream's max_keys bound, guesses kicked with demand 0.

pso_pend_poll, the async path's wait, now adds to upstream's waited-for
statistics as pso_pend_take does.

Checked: nvn_mtl.m and hle_nvn.c compile, nvn_mtl.m with 58 warnings, the
same as upstream main; 79 source tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tvc97 added a commit to tvc97/MacNativeGames that referenced this pull request Oct 19, 2026
…y05010419#38)

Conflicts resolved toward the refreshed PR branches: nvn_mtl.m from
perf/async-shader-loading (ly05010419#30 on current upstream) plus ly05010419#13's parallel
warm-up and the precompiled-library hit/miss log; prepare_shader_seed.py
from perf/parallel-shader-seed (ly05010419#27); runtime/cheats.c kept in every
runtime target and in loader.c. AGENTS.md stays tracked here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Upstream's sampler border colour emulation puts the border fragment function
(fs_fn_border) and PSO_VBORDER into the pipeline key. The async demand path now
builds with it as well: pso_get passes bfn to its synchronous fallbacks, and
pso_pend_kick builds the descriptor from the key's fsfn (guesses have none).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tvc97 added a commit to tvc97/MacNativeGames that referenced this pull request Oct 19, 2026
…mods, shortcut status, 1.4.3 world survey, shader list)

Conflicts:
- nvn_mtl.m pso_get: kept the async pipeline path (ly05010419#30) with upstream's sampler
  border colour emulation, as on perf/async-shader-loading (6d4cbfb); pso_pend_kick
  builds from the key's fsfn.
- game_patches_v143.c: our overlay scene-size manifest beside upstream's
  runtime_output_size_current.
- frontend.m: upstream's live shortcut status.
- README: upstream's text; key 3 keeps "native high resolution".
- prepare_shader_seed.py: upstream's follow-up to ly05010419#27 (8 services, stop on failure).
- shader_list.tsv: upstream's list, which already holds every row of ours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
0x1233333 added a commit to 0x1233333/MacNativeGames that referenced this pull request Oct 20, 2026
Cut the frame work time at 1920x1080 on a Mac mini M4 from 18.76 ms p50 to
8.45 ms, and the frame rate from below the 120 Hz cadence to a steady
108.9-113.1 fps with GPU at 5.88 ms. `@pso_new` drops to 0.

Measured progression (frame work p50 / p99, ms):

  original                18.76 / 47.64   68.93% frames over 16.67 ms
  + async shader loading  17.58 / 28.34   65.75%
  + AOT translation       12.15 / 22.45    3.35%
  + PSO warm-up           10.73 / 15.02    0.61%
  + binary archive         8.70 / 13.61    0.30%
  + parallel preload       8.45 / 12.45    -

Components:

* Asynchronous shader loading. `totk_xlate` runs as a NativeAOT service; a
  cache miss used to block the calling thread. totk_shader_rt.{h,m} add a
  request/answer path so the renderer keeps drawing and swaps in the real
  pipeline when the answer lands. Statistics via mtl_shload_stats /
  mtl_xlate_stats. Taken from PR ly05010419#30 in the tvc97 fork, then extended.

* MTLBinaryArchive pipeline archive at
  shader-archive/totk-pipelines.binaryarchive. Metal can serialize a resolved
  pipeline and reload it next run; without this every launch re-resolves the
  same pipelines. Additions are write-once -- adding to an archive that is
  also being loaded grew it from 26 MB to 2.4 GB -- and the archive is
  flushed every 2048 warm items so a crash does not lose the run's
  collection. TOTK_SHADER_ARCHIVE=off disables it. Upstream has no
  MTLBinaryArchive code; warm_metal_cache.m is a packaging-time system cache
  warmer and is complementary.

* Parallel shader-library preload via dispatch_apply, WARM_BLOCK = 512.
  Background warm-up 22.8-25.4 s -> 9.5-11.2 s. The warm dictionary is a
  plain NSMutableDictionary, so every read and write goes through an
  os_unfair_lock while the expensive part (loading the library, building the
  reflection object) stays outside it. TOTK_WARM_THREADS overrides the thread
  count (default cores - 2, capped at 8).

  Two ordering constraints, both measured: the list the first frame waits
  for must not be preloaded (368 -> 1778 ms when it was), and the preload has
  to run after g_warm_priority_done is set, for the same reason.

* Warm-list ordering. The first entry of the warm list is the one the first
  frame waits for, so the list collected from play sessions
  (build/pso_manifest.tsv, mostly R rows) has to come before any seed list
  (thousands of S rows that only load libraries). With the seed list first
  the title screen waited 21,122 ms; with the collected list first, 458 ms.
  Adds optional pso_title.tsv support and the matching seed-import whitelist
  entry for the same reason.

* Depth attachment store action. Upstream rp_begin_ex() tests
  `clear_only != 2`, which leaves a stale depth attachment in place for a
  clear-only pass in an odd state. Adds a clear_only == 3 fallback and maps
  clear_only == 2 to MTLStoreActionDontCare. Still unfixed upstream.

* TBDR deferred sub-switches behind DM_NVN_TBDR / DM_NVN_TBDR_SUB (bitmask:
  1 SDX, 2 hoist, 4 defer, 8 fuse, 16 depth-stencil, 32 unknown-depth-class).
  Off by default -- these are probes, not shipped behaviour.

* Instrumentation, off unless asked for: DM_NVN_TSV per-frame timings,
  TOTK_EXP_NOSTORE_COLOR / TOTK_EXP_NOLOAD_COLOR for bandwidth experiments.
  These answered the bandwidth question -- it is not bandwidth-bound.
  Bandwidth is about 12% of GPU time, and dropping 286 MB of colour stores
  per frame made the GPU slower (+0.28 ms). The limit is the 120 Hz display
  cadence.

Also tried and left out: a full-RomFS shader sweep (28,426 unique shaders,
13,409 variants, all compiled) gave no gain over the 9,360 startup variants
plus the accumulated translation cache -- runtime compiles stayed at 28 -> 24
-- so the extra seed size is not worth it.

See docs/totk-native-optimizations.md for the per-component write-up and the
conflict notes for rebasing onto current main.
@tvc97 tvc97 closed this Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant