Repository navigation
Conversation
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]>
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]>
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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(default1), this PR compiles vertex/fragment libraries and normal-pass pipelines in the background:TOTK_SHADER_STALL_MS(default 4 ms), so anything already in the system Metal cache is never skipped.These stay synchronous: translation, compute, merged-pass/specialised-fragment pipelines, and iOS.
TOTK_ASYNC_SHADERS=0restores the previous behaviour completely.Results (cold cache, same save and route, Apple M4, 4 runs per mode; details below):
Relation to open PRs
Builds on Prevent synchronous shader compilation during TOTK pipeline lookahead #29 and includes its commit. Please merge Prevent synchronous shader compilation during TOTK pipeline lookahead #29 first; this PR's own changes are
5607131and the merge of upstreammain,40ebc33. Prevent synchronous shader compilation during TOTK pipeline lookahead #29 makes the pipeline prediction stop translating and reclaim stale guesses. It explicitly leaves actual draws synchronous, which is what this PR changes. Prevent synchronous shader compilation during TOTK pipeline lookahead #29's stale-guess reclaim is adapted so that pipelines a real draw is waiting for ("demand" slots) are not reclaimed.Overlaps Add optional asynchronous shader compilation with render skipping #4 (optional async compilation with render skipping, off by default, currently conflicting with
main). The differences:Happy to fold this into Add optional asynchronous shader compilation with render skipping #4, or the other way round, if the maintainers prefer one PR.
Changes (
nvn_mtl.m,hle_nvn.c,totk_shader_rt.*)prog_get/prog_fitcallshader_get_async. It queuesshader_loadon 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 asshader-loading.mtl_sub_beginpublishes finished loads (shload_drain). Programs pick them up throughprog_retry/prog_fit(-2), with the binding signature the variant was translated for. A failed load is stillMDIEwhen a program needs it, as before.pso_pend_poll). If it isn't ready, the draw is skipped aspipeline-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.present_nownow callsres_commit()after taking its source texture.tex_mtlcreates and uploads it insidepresent_now. It was not resident when the present command buffer ran.上屏命令缓冲错误 … PageFault) in 4 of 14 empty-cache async boots. With the fix: 0 of 12. Sync mode had none in 12 boots either way.totk_precise_opts()published itsMTLCompileOptionsbefore 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.[长帧]splits library and pipeline time and adds translations made in the frame (totk_rt_xlate_stats), appended after the existing text.pipeline-pending/shader-loading.[nvn] 后台载着色器库line reports background loads queued / finished / failed, with their average and longest time.docs/async-shader-loading.md(design, trade-offs, method, all numbers) and a README line in English and Chinese.Measurements
Method.
TOTK_ASYNC_SHADERS. Runs went in the order A/B/B/A/B/A/A/B.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 onmain.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.
Where the time in frames over 100 ms went, averaged per run:
Notes:
pipeline-pendingand 1,800–3,100shader-loading, out of about 4,000 frames. No background load failed.After merging the latest upstream
mainUpstream's title-first startup and multi-threaded warm-up are now merged into this branch.
probe-gfxpasses, and 2 empty-cache async boots each showed the first frame after about 290 ms, with no GPU fault.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
python -m unittest discover -s tests: 68 tests pass, after the merge with upstreammain.git diff --check: clean.make runtime-v143builds with 58 renderer warnings, the same count as Prevent synchronous shader compilation during TOTK pipeline lookahead #29, so none are new.probe-gfx: passes on the final binary, including its three prediction checks.async_libs()returns 0 there) and 1.0.0 / 1.1.2 builds.🤖 Generated with Claude Code