Skip to content

Add optional asynchronous shader compilation with render skipping - #4

Closed
NicolasV15 wants to merge 2 commits into
ly05010419:mainfrom
NicolasV15:codex/async-shader-option
Closed

NicolasV15 wants to merge 2 commits into
ly05010419:mainfrom
NicolasV15:codex/async-shader-option

Conversation

@NicolasV15

@NicolasV15 NicolasV15 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

解决的问题

首次启动当前会在显示第一帧前等待整批着色器预热;即使后台已经开始编译,渲染遇到尚未就绪的库或管线时仍会等待。本 PR 增加一个默认关闭、由玩家选择的异步着色器模式:允许先进入游戏,并在后台继续准备着色器;暂时无法执行的绘制跳过,后续帧再次检查,准备好后恢复。

这是以短暂画面缺失换取较少编译等待的选项。界面直接提示可能缺少物体或特效,不承诺开启后画面始终完整或彻底消除卡顿。

使用方式与行为

  • 启动界面新增“异步着色器”复选框,在预热期间也可操作。
  • macOS 菜单栏新增 图形 → 异步着色器(可能暂时缺少画面内容),游玩中可以切换。
  • 两个入口状态同步,默认关闭;选择按档案保存在 TOTK_PROFILE_DIR/graphics-settings.json,原文件其他字段会保留。
  • TOTK_ASYNC_SHADERS=0|1 可以覆盖本次启动,便于独立复测。
情况 行为
关闭(默认) 保留首批预热等待;当前需要的着色器、管线等待就绪后使用。
开启 首批全量预热继续在后台进行;首帧出现后解除启动遮罩。
绘制所需的 Metal 库或渲染管线尚未完成 提交后台任务,暂时跳过该次绘制,后续帧重试。
编译完成 后续使用时领用结果,加入现有缓存及收集流程。
后台任务排队已满 立即返回未就绪,后续帧重试,不等待队列空位。
关闭异步选项时仍有任务在途 当前需要该结果时等待已有任务,不为同一异步请求另起一份编译。
计算着色器 / 计算管线 保持等待,不因本开关丢弃计算派发。
编译失败 与“尚未完成”区分;记录失败,不无限重复提交失败任务。

关闭选项不会补做此前已经跳过的绘制,也不会清除玩家已有缓存。

实现说明

编译任务与状态

新增 nvn_async_compile.h/.m:

  • 用不可变 key 合并同一编译任务,明确区分 pending / ready / failed。
  • 非等待调用只查询或提交任务;实际编译不持有状态锁。
  • 即时库、管线队列各限制 64 个未完成任务,使用 utility 优先级的串行后台工作队列。
  • 等待调用加入已有任务;结果和失败状态可复用。
  • 着色器库的预热和即时请求共享结果,避免它们重复加载同一个库。

渲染流程

nvn_mtl.m 将尚未完成的库视为可重试状态,不把它永久记成缺失。初始程序未完整准备时不向后续绘制流程暴露半成品;绑定状态变化后的 shader 变体仍按原有匹配规则选择。

渲染管线任务捕获本次管线 key、着色器和特化函数,后台完成描述符及管线创建,绘制线程在后续请求时发布结果。异步模式下停止额外的提交内预测编译,让当前实际请求优先。编译配置初始化、统计及派生函数缓存访问补充了并发保护。

某一 shader stage 已切换、另一 stage 仍在编译时,立即使旧 PSO / 资源摘要失效,避免恢复绘制后错误沿用此前的管线。

界面、文档与复测工具

  • frontend.m:启动复选框、图形菜单、设置保存和异步模式下的遮罩行为。
  • 中英文 README 与 docs/first-launch-shaders.md:用法、代价、实现范围及验证记录。
  • verify_first_launch_shaders.py:显式关闭异步模式,继续检查原有首启全量预热要求。
  • verify_async_shaders.py:使用独立空档案/缓存和共享 game-slot 检查真实 App;真实用户输入或用户启动抢占后停止控制。截图需要另行视觉检查。

本 PR 基于上游 41e1e0c,保留其新增的启动阶段提示。提交只包含异步着色器选项的 15 个源码、测试和文档文件;其他本地游戏适配、地址布局修复、游戏数据、缓存、App 和存档不在提交中。

验证结果

检查 结果与范围
独立 PR 分支:python -m unittest discover -s tests -v 49 项通过(包含本轮新增的审查回归)。
新增编译队列测试 验证非阻塞查询、同 key 合并、队列满后的重试、等待已有任务、结果复用、失败终态、设置持久化和其他设置字段保留;不执行 GPU 工作。
修改的 Objective-C 文件编译检查 通过;渲染文件仍有编译器警告,未将其描述为零警告构建。
PR 分支 AppKit 界面探针 通过;验证复选框、菜单、两处切换、保存/恢复及异步遮罩释放,并视觉检查启动控件截图。没有执行游戏或 GPU 命令。
此前本机开发运行时 完整构建、安装和 App 签名检查通过;该开发工作区还含其他本机兼容性改动,不能当作独立 PR 分支的完整游戏构建验证。
此前实际 App 的独立空档案观察 日志确认绕过全量预热等待,遇到 pending 库和管线,随后记录到 133 次管线就绪领用;首帧记录为 11.905 秒。系统 Metal 缓存未清除,这不是全新 GPU 的冷编译基准,也不是性能提升比例。
自动游戏测试完整性 中断:检测到真实用户输入后停止控制并保留测试窗口,未完成自动截图和关闭模式的后续游戏对照。未声称完成长时间游玩、稳定帧率或全场景验收。

本地原始日志保留在项目外,未把资源或个人数据加入 PR。文档记录了复测入口和本地证据位置。

Copilot 审查意见处理(提交 7092afc)

审查意见 修复 回归验证
退出时用户接管检查过期 抽取 SessionMonitor;在证据写入及命令文件打开之后、发送 close 之前重新读取本次日志并检查抢占。发现接管即改记为中断并保留窗口;日志缺失或仍属于前次运行时不关闭。 构造用户输入/抢占恰好发生在证据写入期间的情况,并覆盖日志缺失、旧日志、正常关闭及超时。
仅供预热的结果长期驻留 iOS 预热使用临时结果请求;同键在途任务仍然合并,最后一个调用者返回后释放仅供预热的缓存记录。渲染请求途中加入则保留结果,已有常驻结果不被淘汰。 检查 300 个临时对象实际释放,以及预热与渲染途中共享任务、常驻结果/失败状态保留。使用 Foundation 对象验证所有权,没有声称完成 iOS 真机内存测量。
切换模式导致重复预测编译 预测任务先检查异步缓存;反向切换也先非阻塞查询已有预测任务,就绪后领用并释放槽位。协调代码提取到渲染器与测试共用的 nvn_pso_pending.h。 用模拟编译器执行生产槽位逻辑,验证两个切换方向、编译次数及槽位回收;不创建 GPU 设备。

修复后 49 项本地测试通过,修改的 Objective-C 文件编译检查通过。另在项目外临时副本中分别恢复三种旧错误,相应测试均按预期失败。本次仅更新 PR 源码及测试,没有重新安装本机 App,也未追加完整游戏或 iOS 真机测试。审查线程保留供复核。

复测建议

  1. 正常构建 App,首次不勾选开关,确认原有预热进度和启动行为。
  2. 在启动界面开启异步选项,确认可以继续进入游戏;在新内容尚未编好时,允许出现暂时的画面缺失。
  3. 观察同一内容在后台编译完成后恢复;检查日志中的 pending / ready 记录和编译错误。
  4. 从图形菜单关闭,再次遇到未准备内容时确认恢复等待;重启确认档案设置被保存。
  5. 对需要可重复记录的检查,使用新的外部测试目录:
python3 games/totk/scripts/verify_async_shaders.py \
  --app '/Applications/Tears of the Kingdom.app' \
  --output "$HOME/Library/Application Support/MacNativeGames/TOTK/tests/async-review-on" \
  --async-mode 1 --timeout 360

关闭模式使用另一个全新的输出目录和 --async-mode 0;首次 GPU 编译较慢的机器需要增加观察时限。

已知限制

  • 缺失的绘制可能涉及物体、阴影、特效或全屏合成,可能暂时出现空白、闪烁或内容突然出现。
  • 涉及历史缓冲或写入副作用的绘制被跳过后,影响可能持续多帧,不能保证只影响当前帧。
  • Switch 到 MSL 的新变体翻译和部分特殊函数构建仍走同步路径;后台编译也会占用 CPU,因此不是“零卡顿”保证。
  • 本次验证范围为 macOS;未验证 iOS、长时间内存行为或全场景视觉一致性。

Copilot AI balanced review requested due to automatic review settings October 18, 2026 12:43

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Shader retention, duplicate pipeline compilation after toggling, and takeover-unsafe verifier cleanup remain unresolved.

3 open issues
What changed in this PR

Adds optional asynchronous shader compilation to TOTK’s Metal renderer, trading temporary missing visuals for reduced compilation waits.

Changes:

  • Adds bounded compilation queues and skips draws until shaders or pipelines are ready.
  • Adds synchronized startup and menu controls with per-profile persistence.
  • Documents limitations and adds queue, UI, and packaged-app verification tools.
File Description
tests/​test_async_compile.py Runs the compilation queue probe on macOS.
tests/​async_shader_ui_probe.m Checks controls, persistence, and overlay behavior.
tests/​async_compile_probe.m Tests queue states, deduplication, and settings.
README.md Documents the optional mode in English and Chinese.
games/​totk/​third_party/​d2r_gfx/​gfx/​nvn/​nvn_mtl.m Integrates asynchronous compilation and draw skipping.
games/​totk/​third_party/​d2r_gfx/​gfx/​nvn/​nvn_async_compile.m Implements compilation queues and settings persistence.
games/​totk/​third_party/​d2r_gfx/​gfx/​nvn/​nvn_async_compile.h Defines compilation state and settings interfaces.
games/​totk/​scripts/​verify_first_launch_shaders.py Explicitly disables asynchronous mode for baseline verification.
games/​totk/​scripts/​verify_async_shaders.py Observes packaged-app behavior with isolated test data.
games/​totk/​runtime/​frontend.m Adds startup and menu controls.
docs/​first-launch-shaders.md Records behavior, limitations, and verification scope.

Review effort: Balanced

Comment on lines +92 to +96
(out/'game.log').write_text(text)
if not taken and game.poll() is None:
with commands.open('a') as f: f.write('close\n')
try: game.wait(timeout=30)
except subprocess.TimeoutExpired: report.update(status='failed', close_error='normal close timed out; left open')

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7092afc.

finish_trial() now refreshes the session log and preemption state after writing the evidence and opening the command file, immediately before enqueueing close. A detected takeover changes the report to interrupted and leaves the game open. Missing/unreadable logs or a log still belonging to the previous session prevent automatic closing.

Added deterministic tests in tests/test_async_verifier.py that inject keyboard input or preemption during the evidence write, plus missing/old logs, normal closing and timeout cases. Restoring the stale cleanup check in an isolated negative control makes both takeover tests fail. The complete local suite passes 49 tests; these tests do not launch or close a real game.

Comment on lines +4761 to +4763
dispatch_once(&once, ^{ cache = [[NVNCompileCache alloc] initWithLimit:64]; });
NSString *key = [NSString stringWithFormat:@"%d:%@", stage, pc];
return [cache resultForKey:key wait:wait build:^{ return shader_load_raw(pc, stage); } state:state];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7092afc.

The iOS warm-only shader_load() path now uses transientResultForKey:build:state:. It still shares in-flight work, but the cache removes a completed warm-only job once its active callers have returned. A persistent rendering request that joins the job promotes its ownership; warm-only callers cannot evict an already resident result. The existing macOS persistent warm-up behavior is preserved.

tests/async_compile_lifetime_probe.m verifies release of 300 transient objects, in-flight promotion without recompilation, and retention of resident results/failures. An isolated negative control that restores unconditional retention fails the lifetime test. All 49 local tests pass. This validates ARC ownership with Foundation objects; it is not an iOS device memory measurement.

// Prediction for parallel precompilation (see the note before pso_get): scan from after the current operation to the end of this submit, replaying only state; at a draw, compute the pipeline key from "the state at that time + that render pass's attachment formats" and dispatch those not yet built to the background.
// Whether a render pass actually attaches depth / stencil is only decided at replay (depth-only / stencil-only / neither attached are omitted), so one key is computed for each possible attach mode -- guessing too many only means wasted background compiles and does not affect the result.
static void pso_predict_rest(void) {
if (nvn_async_shaders_enabled()) return; /* demand jobs have priority over speculative compilation */

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7092afc.

The asynchronous PSO registry is now visible to prediction scheduling, and pso_pend_kick() excludes keys already registered there. The reverse mode transition also reuses existing predicted work: async draws poll an unfinished prediction without consuming its slot, then consume the result and free the slot when ready. Blocking draws can still wait for that same prediction.

The production coordination code is shared through nvn_pso_pending.h with tests/async_pipeline_probe.m. A fake compiler verifies both switching directions, unrelated predictions, compilation counts and slot reclamation without creating a GPU device. Removing the async-registry exclusion in an isolated negative control makes the test fail. All 49 local tests and the modified Objective-C compilation checks pass.

@ly05010419

Copy link
Copy Markdown
Owner

Thank you for this, one of the first ideas here. main now has asynchronous shader preparation, on by default on the Mac: new shaders are prepared in the background and their draws wait or skip until they are ready. So we are closing this PR. If something in your approach does better than what is on main, a new PR based on main is welcome.

@ly05010419 ly05010419 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.

3 participants