Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ MetaHook's `metahook/configs/plugins.lst`. Don't forget to launch game from Meta
- [Build instruction](docs/en/build-instruction.md)
- [Installation](docs/en/installation.md)
- [Features](docs/en/features.md)
- [Parallel shader compilation](docs/en/parallel-shader-compile.md) — driver ARB/KHR prewarming with synchronous fallback; acceleration depends on the driver and workload.
- [F5 debugging (optional)](docs/en/debugging.md)

## License
Expand Down
1 change: 1 addition & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ MetaRenderer 是 MetaHookSv 的图形渲染插件,用现代 OpenGL 渲染管
- [构建说明](docs/zh-CN/build-instruction.md)
- [安装说明](docs/zh-CN/installation.md)
- [功能说明](docs/zh-CN/features.md)
- [Shader 并行编译](docs/zh-CN/parallel-shader-compile.md):ARB/KHR 驱动预热与同步回退,实际收益取决于驱动和负载。
- [F5 调试(可选)](docs/zh-CN/debugging.md)

## 许可证
Expand Down
1 change: 1 addition & 0 deletions cmake/Sources.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ set(RENDERER_SOURCES
"${PROJECT_SOURCE_DIR}/src/gl_rmisc.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_rsurf.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_shader.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_shader_parallel.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_shadow.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_sprite.cpp"
"${PROJECT_SOURCE_DIR}/src/gl_studio.cpp"
Expand Down
8 changes: 7 additions & 1 deletion docs/en/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@

# Features

## Parallel shader compilation

Saved shader variants are prewarmed with driver ARB/KHR support and synchronous fallback.
Fixed HUD shaders use a startup batch barrier. Thread settings are hints, not promised worker
counts or speedups. See [controls, algorithm and verification](parallel-shader-compile.md).

## HDR

HDR (High Dynamic Range) rendering simulates brightness above that which a computer monitor is actually capable of displaying. This mainly involves "blooming" colours above 100% brightness into neighbouring areas, and adjusting a virtual camera aperture to compensate for any over-exposure that results.
Expand Down Expand Up @@ -1171,4 +1177,4 @@ Example:
"specularpow" "10.0"
"shadow" "1"
}
```
```
128 changes: 128 additions & 0 deletions docs/en/parallel-shader-compile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
[Back to README](../../README.md) | [中文](../zh-CN/parallel-shader-compile.md)

# Parallel shader compilation

Renderer submits compilation and linking in batches on its current OpenGL rendering thread.
It prefers `GL_ARB_parallel_shader_compile`, then the usable desktop KHR entry point.
Missing extensions/entry points or an explicit disable select synchronous demand compilation.
No application worker thread calls GL. GLSL, the `IMetaRenderer` ABI and public synchronous
compilation return semantics are preserved.

## Scheduling and ownership

```text
cache loader / draw -> shared define factory -> owned paths, defines, sources -> Queued
GL_BeginRendering -> batch compile + link -> Linking
later game frame -> completion status -> link status -> locations -> Ready
first draw -> Require the same ticket -> explicit link wait -> use
failure -> program and VS/GS/FS diagnostics -> delete objects -> Failed
shutdown / context -> cleanup or discard handles, advance generation -> Cancelled
```

`Linking` combines stage submission and program linking: Submit sends every stage and then
links immediately, without intermediate compile-status queries. Poll uses completion token
`0x91B1`; only completion permits link-status and Uniform/Attrib queries. Diagnostics retain
stage paths, defines and logs. Ready variant tables publish linked programs with initialized
locations; dynamic uniform values are still uploaded at draw time.

Tickets contain stable IDs and context generations. Deduplication compares category, state,
all stage paths, complete sources and defines; hash collisions still compare the full data.
Jobs own sources and callbacks, which capture values or static HUD fields. The scheduler owns
internal variants and fixed HUD programs; `g_ShaderTable` owns programs returned by the public
synchronous path, preventing double deletion. Map reload retains shaders in the same context.
Client shutdown cancels/releases internal jobs. GL shutdown deletes objects while the context
is valid; a lost context only discards application handles.

`HUD_Frame` marks a game tick without issuing GL calls. After the engine's `GL_BeginRendering`
returns, at most one pump runs per tick, avoiding repeated budgets across SvEngine views.
Every operation verifies the captured WGL context and thread. A single driver call or finalizer
cannot be preempted by the CPU budget and may still stall. A real demand can temporarily borrow
one inflight slot instead of waiting for unrelated prewarming.

## Coverage

Request-only loaders cover WSurf, Water, DLight, DFinal, Studio, Sprite, TriAPI, Portal,
DrawTexturedRect and DrawFilledRect. They do not bind programs or upload dynamic uniforms.
Existing factories retain Studio/WSurf multiview geometry stages and OIT/fog/blending defines.
OIT capability is established at GL initialization and remains constant within that context.

`R_InitHUD` also batches its 23 fixed programs (21 without OIT), with a controlled startup
completion barrier: FXAA, HDR, HBAO, OIT, gamma/copy/underwater processing. HBAO locations are
initialized in completion callbacks; all fixed programs are usable before initialization
returns. SSR is covered by the DFinal variant factory. `GL_CompileShaderFile[Ex]`,
`IMetaRenderer::CompileShaderFile[Ex]` and startup-video `GL_TryCompileShaderObject` still return
usable objects synchronously, including calls before `R_Init`.

State caches contain flags text, not program binaries. The reader uses the supplied filename,
deduplicates lines, ignores empty/missing files, and rejects a whole line containing unknown
or cross-category tokens. `NONE` means zero state. Autosave precedes table cleanup and merges
valid historical states so unfinished prewarming does not erase them.

## Console controls

| Control | Default | Meaning and bounds |
| --- | ---: | --- |
| `r_shader_parallel_compile` | 1 | Auto ARB/KHR; 0 selects synchronous new demand compilation |
| `r_shader_parallel_threads` | -1 | -1/invalid negative/non-finite/out-of-range maps to `0xFFFFFFFF`; 0 requests no parallel work; positive values truncate to an integer hint |
| `r_shader_parallel_max_inflight` | 16 | Simultaneous prewarm links, clamped to 1–256 |
| `r_shader_parallel_submit_per_frame` | 8 | Submissions per game frame, clamped to 1–256; fixed startup batches have their own inflight bound |
| `r_shader_parallel_poll_budget_ms` | 1.0 | Pump CPU budget, clamped to 0–10 ms; non-finite uses 1; zero pauses background progress |
| `r_shader_parallel_autosave` | 1 | Save valid states at safe client/GL shutdown points |

`shader_compile_stats` reports backend, GPU/GL/GLEW, requested/reported hint, request/dedup
counts, queued/inflight/ready/failed/cancelled, synchronous fallbacks, peaks, polls, submission
and polling times, demand stalls, and separate startup-barrier counts/times. Counts accumulate
within one scheduler until GL recreation. `requests/cacheHits` count scheduler requests,
excluding draws that directly hit an existing variant table. `saveprogstate` and `loadprogstate`
remain available. In synchronous mode ordinary prewarm requests stay queued until a real demand;
the frame pump does not perform blocking synchronous compilation. Fixed startup shaders always
complete at their barrier.

Command-line `+r_shader_parallel_*` controls are applied before fixed HUD compilation. The
engine subsequently executes configuration files and commands in its normal order. For A/B
runs, check archived values and `shader_compile_stats`; a change after startup does not change
the mode used for startup compilation. Statistics also count shader/program creation, deletion
and objects discarded after context loss. Prewarm wall time accumulates completed waves.

Disabling preserves already submitted jobs, which still complete through the completion query;
new submissions use Sync. Thread hints update on the valid GL thread. `0xFFFFFFFF` requests an
implementation-specific maximum. The query returns hint state, never the actual worker count
or a guarantee of acceleration.

## Verification and performance reproduction

```powershell
cmake --build build/x86/Debug --config Debug --target Renderer gl_shader_parallel_scheduler_tests gl_shader_cache_tests gl_shader_parallel_integration_tests
ctest --test-dir build/x86/Debug -C Debug --output-on-failure
ctest --test-dir build/x86/Release -C Release --output-on-failure
ctest --test-dir build/x86/Debug -C Debug -R gl_shader_parallel_integration_tests -V
cmake -S . -B build/format -DFORMAT_VALIDATION_ONLY=ON
cmake --build build/format --target format-check
git diff --check
```

Standalone builds first enable `RENDERER_BUILD_TESTS=ON` with actual dependencies as described
in the [build instructions](build-instruction.md). Aggregator CTest can be scoped to
`build/x86/<config>/Plugins/Renderer`. CPU tests run the production scheduler and cache parser.
GL tests create three independent contexts for automatic ARB, KHR-only and simulated missing
extension fallback; unsupported flavors still execute synchronous drawing. Only inability to
create a context returns 2 / SKIP. GLEW initialization, shader or pixel failures fail the test.
Release retains assertions.

The integration test emits `PERF` CSV for the same 32 simple programs, covering sequential
first demand without history and batch prewarming from a known state list. Each case has five
rounds with alternating sync/parallel order, producing 20 rows: mean/peak submission CPU,
total poll time, prewarm wall time,
demand stalls, pump/require sample p50/p95/p99 and peak inflight. It does not clear driver binary
caches or simulate a game's first frame. Tiny shaders with warm caches may show no throughput
benefit. These measurements demonstrate actual branch behavior, not game performance.

Game A/B requires identical GPU, driver, resolution, map, camera and variant sets, with separate
first-run/no-state-cache and subsequent/cached runs. Record stats, loading/first-frame
p50/p95/p99, private bytes/VRAM, at least ten map transitions and five reinitialization cycles.
Check models/water/particles/TriAPI/portals/lights/post-processing, runtime disable, thread hint
zero and context recreation. Report cache conditions and sample counts. Current evidence and
unverified items are tracked in [ParallelShaderCompile](../../memory/ParallelShaderCompile.md).

Specifications: [ARB](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_parallel_shader_compile.txt),
[KHR](https://registry.khronos.org/OpenGL/extensions/KHR/KHR_parallel_shader_compile.txt).
6 changes: 6 additions & 0 deletions docs/zh-CN/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@

# 功能

## Shader 并行编译

保存的 Shader 变体使用驱动 ARB/KHR 能力预热,不支持时同步回退;固定 HUD Shader 使用
启动批量完成屏障。线程设置只是 hint,不保证 worker 数量或加速。
详见[参数、算法与验证说明](parallel-shader-compile.md)。

## HDR

HDR (高动态范围) 模拟了超出显示器所能显示的亮度范围,将大于0-255的色彩范围映射到0-255的范围内,并且在超出100%亮度的地方施加Bloom(辉光)特效。
Expand Down
112 changes: 112 additions & 0 deletions docs/zh-CN/parallel-shader-compile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
[返回 README](../../README.zh-CN.md) | [English](../en/parallel-shader-compile.md)

# Shader 并行编译

Renderer 在当前 OpenGL 渲染线程批量提交编译与链接,使用驱动提供的
`GL_ARB_parallel_shader_compile`,其次使用可用的桌面 KHR 入口。没有扩展、入口点
缺失或强制关闭时走同步需求路径。不会创建调用 GL 的后台线程,也不改变 GLSL、
`IMetaRenderer` ABI 或公开同步编译接口的返回语义。

## 调度与所有权

```text
缓存 loader / 实际绘制 -> 共用 define 工厂 -> 复制路径、宏、预处理源码 -> Queued
GL_BeginRendering -> 批量 compile + link -> Linking
后续游戏帧 -> completion status -> link status -> Uniform -> Ready
首次实际绘制 -> Require 同一个 ticket -> 一次链接等待 -> 使用
失败 -> VS/GS/FS 和 program 诊断 -> 删除对象 -> Failed
退出 / Context 重建 -> 清理或丢弃旧句柄,更新 generation -> Cancelled
```

`Linking` 合并了 stage 提交与 program 链接;一次 Submit 立即提交所有阶段后链接,
不在中间查询编译状态。非阻塞轮询只查 completion token `0x91B1`,完成后才查询
链接状态、Uniform/Attrib location。失败时保留每个阶段的路径、宏与日志。
`Ready` 变体表只发布已链接并初始化 location 的程序;动态 Uniform 值仍在绘制时更新。

任务 ID 与 Context generation 共同标识任务;去重比较类型、state、VS/GS/FS 路径、
完整源码和宏,哈希碰撞仍比较原文。队列拥有源码和回调,回调只捕获值或静态 HUD 字段。
内部调度器独占内部变体和固定 HUD 程序;`g_ShaderTable` 只管理公开同步编译路径的程序,
两者不会重复删除。Map 重载保留同一 Context 的 shader,客户端关闭取消并释放内部任务;
GL 关闭时,在 Context 仍有效时释放 GL 对象,Context 已失效则仅丢弃句柄。

`HUD_Frame` 仅标记游戏帧。`GL_BeginRendering` 在引擎入口返回后最多 pump 一次,
所以多个 SvEngine view 不重复消耗预算;每次 GL 调用前都核对创建调度器的 WGL Context
和线程。一个 GL 调用、一次最终化自身的耗时无法被毫秒预算抢占,单次驱动调用仍可能卡顿。
需求点可临时借用一个 inflight 槽,避免等待与当前绘制无关的预热任务。

## 覆盖范围

十类状态缓存均使用 request-only loader:WSurf、Water、DLight、DFinal、Studio、
Sprite、TriAPI、Portal、DrawTexturedRect、DrawFilledRect。loader 不绑定程序或上传
动态 Uniform。Studio/WSurf 的 multiview geometry stage、各类 OIT/fog/混合宏沿用原工厂。
OIT 能力由 GL 初始化确定,在同一 Context 内保持不变。

`R_InitHUD` 的 23 个固定程序(OIT 关闭时 21 个)也使用批量提交和受控启动屏障,
覆盖 FXAA、HDR、HBAO、OIT、gamma/copy/水下后处理。HBAO location 在完成回调中初始化;
函数返回前所有固定程序均已就绪。SSR 属于 DFinal 状态变体。
`GL_CompileShaderFile[Ex]`、`IMetaRenderer::CompileShaderFile[Ex]` 和启动视频使用的
`GL_TryCompileShaderObject` 继续同步返回可用对象,包括 `R_Init` 前的调用。

缓存是 flags 文本,不是 program binary cache。读取使用真实传入的 filename;重复行
去重,空行/缺失文件不产生请求,含未知或其他类型 token 的行整行跳过,`NONE` 表示零状态。
自动保存发生在清表之前,并合并有效历史缓存,防止尚未完成的预热状态丢失。

## 控制台参数

| 参数 | 默认 | 语义与边界 |
| --- | ---: | --- |
| `r_shader_parallel_compile` | 1 | 自动选 ARB/KHR;0 使新编译走同步需求路径 |
| `r_shader_parallel_threads` | -1 | -1/非法负值/非有限值/超范围值映射 `0xFFFFFFFF`;0 请求不并行;正数截断为整数 hint |
| `r_shader_parallel_max_inflight` | 16 | 预热同时链接数,限制为 1–256 |
| `r_shader_parallel_submit_per_frame` | 8 | 每游戏帧最多提交数,限制为 1–256;固定启动批次另受 inflight 限制 |
| `r_shader_parallel_poll_budget_ms` | 1.0 | pump CPU 预算限制为 0–10 ms;非有限值用 1;0 暂停后台推进 |
| `r_shader_parallel_autosave` | 1 | 客户端或 GL 安全关闭点保存有效状态 |

`shader_compile_stats` 输出 backend、GPU/GL/GLEW、请求/读回 hint、请求与去重数、
queued/inflight/ready/failed/cancelled、同步回退、峰值、poll、提交/轮询耗时、
实际需求等待及独立的启动屏障次数/耗时。计数在同一调度器中累计,直到 GL 重建。
`requests/cacheHits` 是调度器请求统计,不包含变体表直接命中的每次绘制。
`saveprogstate`、`loadprogstate` 保持可用。同步模式的普通预热请求留在队列直到真实需求,
不在每帧预算里执行阻塞同步编译;固定启动程序始终在启动屏障完成。

启动命令行中的 `+r_shader_parallel_*` 会在固定 HUD 编译前提前应用;之后引擎仍按正常
顺序执行配置文件和命令。做 A/B 时应核对配置文件中的存档值和 `shader_compile_stats`,
避免启动后改配置而误认为启动编译也使用了该模式。统计同时记录 shader/program 创建、
删除及 Context 丢失后丢弃的数量;prewarm wall 为已完成预热批次的累计 wall time。

切换关闭不会丢弃已提交任务;它们仍按 completion 状态结束。后续提交使用同步路径。
thread hint 在有效 GL 线程更新。hint 只是请求,`0xFFFFFFFF` 请求实现自选最大值;
`glGetIntegerv` 返回 hint 状态,不能解释成真实线程数或加速保证。

## 验证和性能复现

```powershell
cmake --build build/x86/Debug --config Debug --target Renderer gl_shader_parallel_scheduler_tests gl_shader_cache_tests gl_shader_parallel_integration_tests
ctest --test-dir build/x86/Debug -C Debug --output-on-failure
ctest --test-dir build/x86/Release -C Release --output-on-failure
ctest --test-dir build/x86/Debug -C Debug -R gl_shader_parallel_integration_tests -V
cmake -S . -B build/format -DFORMAT_VALIDATION_ONLY=ON
cmake --build build/format --target format-check
git diff --check
```

独立工程先按[构建说明](build-instruction.md)启用 `RENDERER_BUILD_TESTS=ON` 并指定实际依赖。
聚合工程可把 CTest 目录缩小到 `build/x86/<config>/Plugins/Renderer`。CPU 测试执行生产
调度器和缓存解析器;GL 测试创建三个独立 Context,分别走自动 ARB、仅 KHR 和模拟无扩展
回退(驱动缺少对应扩展时仍测试同步绘制)。只有无法创建 Context 使用退出码 2 / SKIP;
GLEW 初始化失败、编译/像素错误必须失败,Release 保留断言。

集成测试输出 `PERF` CSV:相同 32 个简易程序,分别覆盖无历史的逐项首次需求和已有状态
列表的批量预热;每组五轮交替 sync/parallel 次序,共 20 行。记录提交
平均/峰值、poll 总时长、预热 wall time、需求等待、pump/require 样本 p50/p95/p99
和峰值 inflight。它不清除驱动 binary cache,也不模拟游戏第一帧。小程序在热缓存下可能
没有吞吐收益;这些数据只能证明提交/轮询/需求等待的实际分支,不能替代游戏性能结论。

游戏 A/B 需使用相同 GPU、驱动、分辨率、地图、视角和变体集合,分开记录首次无状态缓存
与再次有状态缓存。保存 `shader_compile_stats`、加载/首帧 p50/p95/p99、private bytes/VRAM,
至少 10 次地图切换和 5 次重新初始化循环。检查模型/水面/粒子/TriAPI/Portal/灯光/后处理,
并测试运行时关闭、thread hint 0 和 Context 重建。驱动缓存冷热与采样次数必须写入报告。
本次实际执行证据及未验证项见 [ParallelShaderCompile](../../memory/ParallelShaderCompile.md)。

规范:[ARB](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_parallel_shader_compile.txt)、
[KHR](https://registry.khronos.org/OpenGL/extensions/KHR/KHR_parallel_shader_compile.txt)。
Loading
Loading