返回提交历史
Modified
docs/API.md
+2
-1
Modified
docs/RAYTRACING.md
+15
-6
Added
docs/evidence/path-tracing-menu-2026-11-17.json
+366
-0
Added
docs/path-tracing-menu-2026-11-17.md
+54
-0
Modified
src/XFE.SeAgent.Plugin/AgentPlugin.cs
+1
-1
Modified
src/XFE.SeAgent.Plugin/Game/GameDebugApi.cs
+1
-0
Added
src/XFE.SeAgent.Plugin/Graphics/RayTracing.Menu.cs
+153
-0
Modified
src/XFE.SeAgent.Plugin/Graphics/RayTracing.cs
+24
-16
Modified
src/XFE.SeRayTracing.Native/Interop.hlsl
+9
-5
Modified
src/XFE.SeRayTracing.Native/Native.cpp
+9
-4
Modified
src/XFE.SeRayTracing.Native/Native.h
+1
-0
Modified
src/XFE.SeRayTracing.Native/Rays.hlsl
+54
-6
Modified
tests/XFE.SeRayTracing.Tests/GpuTest.cpp
+43
-2
SpaceEngineersModDev/XFE.SpaceEngineers.AgentBridge
Add near-field path tracing and native graphics settings menu
3e36f89
代码差异
13 个文件
+732
-41
@@ -96,7 +96,8 @@ JSON 字段名区分大小写。请求最大深度 32,不接受重复属性名
96
96
| `performance.status` | `{}` | 无需世界,返回渲染窗口状态、原生性能计数、线程池、GC、调优开关等;没有世界时模拟速度为 `null`。 |
97
97
| `graphics.status` | `{}` | 只读检查进程/窗口 DPI 感知、窗口物理尺寸、实际渲染/视口/后缓冲尺寸、动态分辨率开关及画质;无需世界。DRS 未启用时,fraction 不代表正在缩放。 |
98
98
| `graphics.rayTracing.status` | `{}` | 启用状态、实际 DXR 硬件层级、几何/玻璃/体素/灯具数量、快照年龄、分辨率、CPU 提交耗时及错误。`render.gpuTraceDenoiseMs` 是上一帧 D3D12 射线、历史复制和去噪的 GPU timestamp 时长,不含完整游戏渲染。 |
99
| `graphics.rayTracing.configure` | 可选 `enabled`、`radius`、`strength`、`shadowStrength`、`reflections`、`indirect`、`glass`、`voxels`、`bounces`、`voxelLod`、`diagnostic`、`persist` | 主菜单或离线世界可用。只改变客户端渲染及显式保存的本机设置,不修改存档;参数范围见 [光追说明](RAYTRACING.md)。 |
99
| `graphics.rayTracing.configure` | 可选 `enabled`、`pathTracing`、`fullResolution`、`samples`、`denoise`、`radius`、`strength`、`shadowStrength`、`reflections`、`indirect`、`glass`、`voxels`、`bounces`、`voxelLod`、`diagnostic`、`persist` | 主菜单或离线世界可用。只改变客户端渲染及显式保存的本机设置,不修改存档;参数范围见 [光追说明](RAYTRACING.md)。 |
100
| `graphics.rayTracing.menu` | `action`: `status`/`openGraphics`/`open`/`set`/`apply`/`cancel`/`closeGraphics` | 打开原版画质菜单或新增子面板,通过同一批原生控件与回调进行有界自动验证。`set` 需 `values` 对象,组合框使用从 0 开始的索引:mode=关闭/混合/路径,fullResolution=半/原生,samples/bounces=实际值减1,voxelLod=0/1/2;其余复选框和滑块与 configure 相同。`set` 只改草稿,`apply` 才保存;返回草稿、控件位置和启用状态。 |
100
101
| `graphics.rayTracing.inspect` | 可选 `model`:最多 128 字符的模型名子串 | 读接口;相机位置、最多 32 个匹配玻璃对象的模型/姿态/三角形表面中心和法线,以及最近 64 个体素根实体的范围。ID 是字符串,捕获未完成时对象列表可能为空。 |
101
102
| `debug.camera` | `{}` 读取;`position:{x,y,z},target:{x,y,z},up:{x,y,z}` 设置;`restore:true` 恢复,不能与位置同时传入 | 设置/恢复需要授权离线副本。固定观察镜头,不移动角色或受控舰船;第一次覆盖前的控制器会保留,同世界可恢复。向量必须有限,观察方向和 up 不能平行。省略 up 时采用世界 Y 轴。返回的 pose 是当前渲染帧,设置在下一帧生效。 |
102
103
| `performance.capture` | `seconds`:5–180,默认 60;`label`:最多 128 字;`engineStages`:默认 false | 主菜单或授权副本可用。异步采样,单次运行;返回 `started,label,seconds,pollMethod`。阶段探针有额外开销,仅用于定位热点。 |
@@ -1,10 +1,12 @@
1
# 实验性硬件光追
1
# 硬件光追与实验性近场路径追踪
2
2
3
插件在游戏显卡上创建 D3D12 设备,构建真实三角形 BLAS/TLAS,运行 DXR 1.1 inline ray query,再把结果合成到 DX11 的原生 HDR。它能命中屏幕外几何,不依赖屏幕空间反射替代硬件射线。原版主渲染、远景、HUD 和曝光链保留;这仍是局部混合渲染,并非完整 DX12 引擎迁移或全场景路径追踪。
3
插件在游戏显卡上创建 D3D12 设备,构建真实三角形 BLAS/TLAS,运行 DXR 1.1 inline ray query,再把结果合成到 DX11 的原生 HDR。可选择混合光追或近场路径追踪:后者对覆盖的不透明表面重新积分自发光、直接光和 BSDF 多次反弹,替换该表面的原版光照。真实几何首命中受光栅深度校验,未覆盖对象、天空和远景保留原版。玻璃继续使用现有混合透明模型。这不是完整 DX12 引擎迁移或全场景路径追踪。
4
5
游戏内进入 **选项 → 图形选项(画质)→ 光追 / 路径追踪**。使用原版 GUI 控件,选择关闭、混合光追、路径追踪(近场实验),再按“应用并保存”。“取消”或关闭面板不修改配置;保存后重启恢复。菜单支持射线分辨率、每帧采样、反弹次数、去噪、玻璃、体素精度及混合光照参数。路径模式下不适用的混合 AO/接触阴影/GI 强度会禁用。
4
6
5
7
## 本版支持
6
8
7
- 刚性舰体、功能方块及子部件的局部反射、环境遮蔽、太阳接触阴影;GGX 金属/粗糙度反射,最多四次路径反弹。
9
- 刚性舰体、功能方块及子部件的局部反射、环境遮蔽、太阳接触阴影;GGX 金属/粗糙度反射,最多八次路径反弹。近场路径模式每帧 1–8 个样本,首表面使用 G-buffer 法线/光滑度和真实几何材质,采用直接光采样、BSDF 采样和俄罗斯轮盘终止;覆盖校验失败保留原版,不用黑色填补未知几何。
8
10
- `MESH` 材质的自发光贴图参与次级光路;扩展贴图按线性数据读取,缺失时使用无发光回退。第一人称驾驶舱采集实际内部模型,LCD 从引擎当前纹理直接在 GPU 上复制到共享纹理,屏幕内容、颜色、发光强度及可见性用于玻璃和其他表面的反射。最多 32 块屏幕、64 米范围、10 Hz 更新;当前驾驶舱优先。单块纹理不超过 2048×2048,总共享纹理预算 128 MiB。屏幕空间 HUD 不进入几何反射。
9
11
- 实际 `GLASS` 材质进入加速结构,窗框仍按不透明材质处理,不再根据模型文件名把整扇窗跳过。按顺序追踪玻璃层,计算菲涅耳反射、透射颜色和斜入射吸收;阴影能穿过玻璃。次级路径使用薄平行板折射,主视图通过折射后的真实命中位置、深度校验及原生 HDR 取样实现近场折射偏移。原有玻璃污渍和背景着色保留,不重复乘透射颜色。
10
12
- 相机周围 320 米内的小行星/星球体素等值面参与射线。使用本机引擎的线程独立等值面生成器和 storage pin,默认 LOD 0(1 米体素采样),后台最多四个生成任务,按距离顺序发布结果。材质取实际体素索引,以三个方向投影贴图并混合顶点材质。分块有边界采样及唯一三角形归属;体素内容/材质事件会作废旧快照并重新生成,未改写任何体素。主射线最远 256 米;不再用光栅深度加 10 厘米截断体素查询。接近光栅表面的体素命中提供次级射线起点和几何法线,避免独立 LOD 深度失配;前景遮挡的玻璃仍被拒绝。
@@ -31,12 +33,16 @@ $cli='./src/XFE.SeAgent.Cli/bin/Release/net10.0/xfe-se.exe'
31
33
| 参数 | 范围/默认 | 含义 |
32
34
| --- | --- | --- |
33
35
| `enabled` | bool/false | 开关 |
36
| `pathTracing` | bool/false | 近场不透明表面路径积分;false 为原有混合光追 |
37
| `fullResolution` | bool/false | 射线使用原生分辨率,关闭时使用半分辨率;不修改游戏主画面分辨率 |
38
| `samples` | 整数 1–8/1 | 路径模式每帧每像素样本数;混合模式不使用此项 |
39
| `denoise` | bool/true | 时域积累与空间去噪;关闭可查看原始采样噪声 |
34
40
| `radius` | 0.25–12/3 | AO 距离,米 |
35
41
| `strength` | 0–1/0.3 | AO 混合强度 |
36
42
| `shadowStrength` | 0–0.5/0.15 | 接触阴影混合强度 |
37
43
| `reflections` | 0–1/0.8 | 反射混合强度 |
38
44
| `indirect` | 0–1/0.6 | 间接光强度 |
39
| `bounces` | 整数 1–4/3 | 次级路径的不透明表面反弹上限;玻璃穿越另有步数上限 |
45
| `bounces` | 整数 1–8/3 | 不透明表面路径长度上限;路径模式包含首表面,混合模式从次级命中开始计数;玻璃穿越另有步数上限 |
40
46
| `glass` | bool/true | 玻璃反射/透射/薄板折射;关闭时射线忽略玻璃,保留原版透明显示 |
41
47
| `voxels` | bool/true | 收集附近体素 |
42
48
| `voxelLod` | 整数 0–2/0 | 体素采样间隔 1/2/4 米;不改变原版体素显示质量 |
@@ -53,7 +59,7 @@ $cli='./src/XFE.SeAgent.Cli/bin/Release/net10.0/xfe-se.exe'
53
59
54
60
约 10 Hz 的不可变快照使用三个可复用缓冲和读取租约。模型和 BLAS 缓存复用,变化时增量上传并回收过期几何;仅累计空洞过大时压缩。相机移动超过 64 米立即重建收集范围,通常拓扑周期 15 秒。方块/体素变更通过世代号拒绝过期结果;卸载世界释放缓存和本机图形资源。
55
61
56
DX11/DX12 同适配器共享纹理,以 GPU fence 同步,临时隔离并恢复 DX11 context state。射线和去噪以半分辨率运行:原生 4K 对应 1920×1080 射线缓冲,合成在曝光、Bloom、色调映射和 HUD 之前。主画面与 HUD 不降分辨率。
62
DX11/DX12 同适配器共享纹理,以 GPU fence 同步,临时隔离并恢复 DX11 context state。射线和去噪支持半分辨率或原生分辨率:原生 4K 分别对应 1920×1080 或 3840×2160 射线缓冲,合成在曝光、Bloom、色调映射和 HUD 之前。切换模式/尺寸/参数会重置历史。主画面与 HUD 不降分辨率。
57
63
58
64
`graphics.rayTracing.status` 返回实际 DXR 层级、几何/纹理/玻璃/体素/灯具数量、缓存年龄和错误。`render.gpuTraceDenoiseMs` 由 D3D12 timestamp query 测量上一帧的射线、历史复制和去噪,**不包含**几何构建、DX11 pack/合成及整个游戏 GPU 开销;`cpuSubmitMs` 还可能包含同步等待,不能冒充 GPU 时间。
59
65
@@ -73,9 +79,10 @@ VRAGE3 不能作为本插件的可替换 DLL 后端直接装入 SE1。[官方架
73
79
74
80
- 只处理近场刚性模型和有限范围体素。未处理蒙皮装甲、alpha cutout、完整行星远景几何、运动矢量及次级法线贴图。体素采样 LOD 和原版地形 LOD 可能有差别,默认优先精度。
75
81
- 玻璃是薄板模型;IOR 1.52、厚度 10 mm 是明确的默认假设,不是引擎提供的物理参数。没有封闭介质体积、焦散或完整双面材质模型。主视图折射需要有效的屏幕内背景命中,失配时保留原版背景;次级路径使用几何折射。原版透明着色仍保留,不能称为完整替换。
76
- 接触阴影是对已有光照的近似混合;环境反射在未命中时保留原版。次级光照保留小幅近似环境项,不是物理校准的全场景参考积分器。灯具候选上限 64,尚未覆盖所有粒子、武器、自发光面光源及完整反射器纹理。
82
- 混合模式的接触阴影是对已有光照的近似混合,环境反射在未命中时保留原版;该模式的次级光照保留小幅近似环境项。路径模式移除此环境项,但没有完整环境贴图采样,两种模式都不是物理校准的全场景参考积分器。灯具候选上限 64,尚未覆盖所有粒子、武器、自发光面光源及完整反射器纹理。
77
83
- LCD 与静态发光网格能被射线命中,但没有对自发光表面做专门的重要性采样;小文字的间接照明仍可能噪声较大。非 LCD 材质的所有运行时颜色/开关变化、alpha cutout 发光贴花尚未完整覆盖。半分辨率射线及去噪会使玻璃反射中的细小文字偏软,主画面和原屏幕仍为原生分辨率。
78
84
- 半精度近场数据、有限样本、短历史和较少反弹仍可能产生噪声、闪烁、细边误差或运动拖影。次级高亮有限幅,不是生产级重建。
85
- 路径模式没有完整环境贴图采样、发光面重要性采样或完整材质模型。没有局部灯的舱内可能比原版环境照明更暗,小面积屏幕的间接照明仍会有噪声。不能将这个有界近场积分器称为 Cyberpunk Overdrive 或 RTXPT 的完整集成。
79
86
- 光追增加 CPU/GPU 工作,不解决原有大型舰船模拟瓶颈,不保证 FPS 提升。关闭开关可恢复原版渲染。
80
87
81
88
## 验证
@@ -87,3 +94,5 @@ GPU 回读测试覆盖不透明遮挡、天空/远景保留、纹理和 GGX
87
94
方差去噪、体素覆盖与 CPU 线程对照见 [后续实测](performance-raytracing-2026-11-17-v3.md)。
88
95
89
96
驾驶舱内部屏幕、自发光文字和玻璃反射见 [LCD 修复实测](raytracing-emissive-lcd-2026-11-17.md)。
97
98
路径积分、原生画质菜单及保存重启验证见 [路径追踪与设置实测](path-tracing-menu-2026-11-17.md)。
@@ -0,0 +1,366 @@
1
{
2
"date": "2026-11-17",
3
"gameVersion": "1.211.017",
4
"gpu": "RTX 5090",
5
"pid": 154184,
6
"world": "C:\\Users\\XFEstudio\\AppData\\Roaming\\SpaceEngineers\\Saves\\76561198835257426\\XFE Performance Huanyu 20261116",
7
"backup": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\backups\\20261116T232604819-c178e6a809f74f56975f463b023192e8",
8
"plugin": {
9
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\src\\XFE.SeAgent.Plugin\\bin\\Release\\net48\\XFE.SeAgent.Plugin.dll",
10
"sha256": "73348f065aa08ef2af796eddc8f4b81b026139b2c8ed9b6f3773d2ba895c85c4"
11
},
12
"installedPlugin": {
13
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFEToolBox\\CrossVersion\\ToolData\\xfestudio.space-engineers-plugin-manager\\plugins\\agent-e53c387695384438b381131548b24cec\\XFE.SeAgent.Plugin.dll",
14
"sha256": "73348f065aa08ef2af796eddc8f4b81b026139b2c8ed9b6f3773d2ba895c85c4"
15
},
16
"native": {
17
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\raytracing-native\\XFE.SeRayTracing.Native.dll",
18
"sha256": "135233e5e8693bb76f887efe926d66ed46e2a3ddb6759d91e54a54c35769957f"
19
},
20
"camera": {
21
"pose": {
22
"position": {
23
"x": 15231.714304701727,
24
"y": 314366.4732227367,
25
"z": -83987.78667612362
26
},
27
"forward": {
28
"x": 0.5169432759284975,
29
"y": 0.16967767477035534,
30
"z": -0.8390346765518191
31
},
32
"up": {
33
"x": -0.6653606891632081,
34
"y": -0.5370353460311892,
35
"z": -0.5185442566871644
36
},
37
"right": {
38
"x": -0.5385766029357911,
39
"y": 0.826318681240082,
40
"z": -0.1647199988365174
41
}
42
},
43
"controller": "Sandbox.Game.Entities.MyCockpit",
44
"overridden": false,
45
"note": "Only the rendering camera changes; the player, controlled ship and world entities are not moved. Pose updates on the next rendered frame."
46
},
47
"settings": {
48
"enabled": true,
49
"radius": 3.0,
50
"strength": 0.3,
51
"shadowStrength": 0.15,
52
"reflections": 0.8,
53
"indirect": 0.6,
54
"glass": true,
55
"voxels": true,
56
"bounces": 4,
57
"voxelLod": 0,
58
"pathTracing": true,
59
"fullResolution": true,
60
"samples": 2,
61
"denoise": true
62
},
63
"graphics": {
64
"processDpiAwareness": 2,
65
"windowDpi": 144,
66
"windowDpiAwareness": 2,
67
"windowClient": {
68
"width": 3840,
69
"height": 2160
70
},
71
"physicalWindow": {
72
"width": 3840,
73
"height": 2160
74
},
75
"renderResolution": {
76
"width": 3840,
77
"height": 2160
78
},
79
"viewportResolution": {
80
"width": 3840,
81
"height": 2160
82
},
83
"backBufferResolution": {
84
"width": 3840,
85
"height": 2160
86
},
87
"dynamicResolutionSetting": false,
88
"dynamicResolutionOverride": false,
89
"dynamicResolutionFraction": 0.5,
90
"quality": {
91
"AntialiasingMode": "FXAA",
92
"TextureQuality": "HIGH",
93
"VoxelTextureQuality": "HIGH",
94
"ModelQuality": "HIGH",
95
"VoxelShaderQuality": "HIGH",
96
"AlphaMaskedShaderQuality": "HIGH",
97
"AtmosphereShaderQuality": "HIGH",
98
"ShadowQuality": "HIGH"
99
},
100
"configuredWidth": 3840,
101
"configuredHeight": 2160,
102
"note": "Renderer and window snapshots; DRS fraction is not an applied scale when DRS is disabled. DPI awareness 0 allows Windows bitmap scaling."
103
},
104
"rayTracing": {
105
"enabled": true,
106
"radius": 3.0,
107
"strength": 0.3,
108
"shadowStrength": 0.15,
109
"pathTracing": true,
110
"fullResolution": true,
111
"samples": 2,
112
"denoise": true,
113
"mode": "path-traced-near-field",
114
"diagnostic": 0,
115
"failure": null,
116
"render": {
117
"state": "active",
118
"hardwareTier": 12,
119
"meshes": 86,
120
"instances": 525,
121
"triangles": 284897,
122
"frames": 3536,
123
"cpuSubmitMs": 13.3192,
124
"gpuTraceDenoiseMs": 11.852736,
125
"hresult": 0,
126
"message": "Hardware DXR local paths, thin dielectric transmission, voxel materials, temporal and atrous denoising",
127
"nativeResolution": "3840x2160",
128
"traceResolution": "3840x2160",
129
"textures": 38
130
},
131
"collecting": false,
132
"reflections": 0.8,
133
"indirect": 0.6,
134
"textureFallbacks": 0,
135
"glass": true,
136
"voxels": true,
137
"bounces": 4,
138
"voxelLod": 0,
139
"glassMaterials": 1,
140
"glassTriangles": 158,
141
"voxelChunks": 0,
142
"voxelTriangles": 0,
143
"voxelRevision": 0,
144
"voxelCaptureRadiusMeters": 320,
145
"voxelWorkers": 4,
146
"localLights": 21,
147
"scannedBlocks": 1572,
148
"skippedModels": 0,
149
"snapshotInstances": 525,
150
"snapshotAgeMs": 49.9166,
151
"implementation": "DXR 1.1 hardware geometry rays. Hybrid effects or near-field opaque surface path integration, 1..8 samples/bounces; full/half resolution; native HDR before HUD.",
152
"limits": "Near-field path tracing replaces covered opaque lighting with emission, direct-light sampling and BSDF paths; raster depth validates primary visibility. Uncovered geometry, sky and distant scenes keep native shading. Glass retains hybrid primary transparency and thin-slab secondary transport. Up to 64 fixtures, 32 live LCDs within 64 m at 10 Hz; voxel capture 320 m, primary range 256 m. No environment-map sampling, emissive-area importance sampling, ReSTIR, NRD, DLSS RR, full-scene path tracing, solid dielectric volumes, cutouts, deformation or secondary normal maps."
153
},
154
"tests": {
155
"managed": "PASS 93 checks",
156
"engine": "PASS engine executable",
157
"gpuLog": {
158
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\native-tests-final.txt",
159
"sha256": "9ed0bd7b9fb91fa803294445e0f5c8fa456b67071f13e4a8ef9c7c44d38bbd4c"
160
},
161
"restart": {
162
"mode": "path-traced-near-field",
163
"pathTracing": true,
164
"fullResolution": true,
165
"samples": 2,
166
"bounces": 4
167
},
168
"cancel": {
169
"passed": true,
170
"hash": "6B41E1BD37A2EE3C3299AEAB330AE93BCF5EDBFFED86F874A2B90B785EA37439"
171
},
172
"allThreeModesAppliedThroughMenu": true,
173
"interaction": "Native control selection and Apply/Cancel callbacks through bounded API; no simulated mouse"
174
},
175
"screenshots": {
176
"entry": {
177
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\Screenshots\\se-20261116T2328000345686.png",
178
"sha256": "ff980dfeeee541ba947b2eebdafe41486b782425d1607725333e3bb0fdfb7b52"
179
},
180
"panel": {
181
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\Screenshots\\se-20261116T2328013353452.png",
182
"sha256": "7e6f41cba6cfa3803835f98a40a0df6b35daaa1c1f427f035057d3c3aae94c05"
183
},
184
"off": {
185
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\Screenshots\\se-20261116T2328044854516.png",
186
"sha256": "7d67955fad1ef22d453c0d9ff8ceb50a81e58d2f7b0930dd29e329a80c289536"
187
},
188
"hybrid": {
189
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\Screenshots\\se-20261116T2328101494637.png",
190
"sha256": "d7590a7e02c3be3c9f3eda782998f6431747e6ea2c5d35cc54bc2727663379b8"
191
},
192
"path": {
193
"path": "C:\\Users\\XFEstudio\\AppData\\Local\\XFE\\SpaceEngineersAgent\\Screenshots\\se-20261116T2328159495442.png",
194
"sha256": "298a9cc73371a1b0ab533e951b14e734d499530f5bfc10834523d66d7696da5b"
195
}
196
},
197
"visualReview": {
198
"frozenRequirements": {
199
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\requirements.json",
200
"sha256": "2e60b1135ba40b1ada1689a00d8db9984aa79ed7b11c3f3873988e660e864814"
201
},
202
"gates": {
203
"entry": {
204
"status": "pass",
205
"created_at": "2026-11-16T23:33:31.503190+00:00",
206
"requirements": {
207
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\entry\\requirements.json",
208
"sha256": "03808d250df22d8b52576c9f9f141be73d04eec9bdff3e07a31dac79734b8eb2"
209
},
210
"review": {
211
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\entry\\review.json",
212
"sha256": "29ca0948deb88b5f2303160a34b67370af0f049d8bc36ae8cf45fdf22552e30e"
213
},
214
"reasons": [],
215
"checks": [
216
{
217
"id": "entry",
218
"status": "pass",
219
"observation": "原生 4K 原图中入口位于图形选项标题右侧;没有覆盖标题、预设或其他原版选项,底部好/取消完整可见。",
220
"problems": []
221
}
222
],
223
"notice": "Evidence integrity/coverage gate; observations are not independently recognized or authenticated."
224
},
225
"panel": {
226
"status": "pass",
227
"created_at": "2026-11-16T23:33:31.845989+00:00",
228
"requirements": {
229
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\panel\\requirements.json",
230
"sha256": "4459a7882cd471dc7da51ecbdf41a8b895acbf020737d3039a1165639ef32b29"
231
},
232
"review": {
233
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\panel\\review.json",
234
"sha256": "05582ee64e248fe73a5e757bd402f8a6bdc9a94907a946f3a031a09b4432c9d7"
235
},
236
"reasons": [],
237
"checks": [
238
{
239
"id": "panel",
240
"status": "pass",
241
"observation": "原图与原比例分块显示 13 项控件、两行说明、应用并保存和取消均完整;原生分辨率、2 个样本、4 次可读,滑块数值为 3.00/0.30/0.15/0.80/0.60;不适用项变灰。原生控件布局与显示文字交叉核验一致。",
242
"problems": []
243
},
244
{
245
"id": "settings",
246
"status": "pass",
247
"observation": "通过实际原生控件及同一 Apply/Cancel 回调验证三种模式;取消保持配置文件哈希不变,应用后配置落盘;最终进程启动后已恢复路径模式、原生射线、2 样本、4 反弹。自动化调用菜单回调,未模拟鼠标。",
248
"problems": []
249
}
250
],
251
"notice": "Evidence integrity/coverage gate; observations are not independently recognized or authenticated."
252
},
253
"path": {
254
"status": "pass",
255
"created_at": "2026-11-16T23:33:32.258315+00:00",
256
"requirements": {
257
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\path\\requirements.json",
258
"sha256": "6d6c0d56a95d86cf5e30474a5889c2e2228684a8c28b5d795d5020e10eb4c3fe"
259
},
260
"review": {
261
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\work\\visual\\20261117-path\\final\\path\\review.json",
262
"sha256": "2adbcd4597e16c390704c63a6412406663d42a1aad1a31831359d0a7e0bc3dfe"
263
},
264
"reasons": [],
265
"checks": [
266
{
267
"id": "path",
268
"status": "pass",
269
"observation": "固定视角对比显示近场舱框光照替换、玻璃仍反射蓝色仪表,天空和 HUD 保留;GPU 回读验证一次反弹无绿色贡献、三次出现 0.128637 绿色间接光,未覆盖像素仍为原版 0.2。舱框过暗与噪点仍存在;本项只验证有界路径积分及回退。",
270
"problems": []
271
},
272
{
273
"id": "native4k",
274
"status": "pass",
275
"observation": "整张截图 3840×2160,HUD 文字与菜单按原生尺寸显示;graphics.status 的渲染/视口/后缓冲均为 3840×2160,DRS 关闭;DXR 状态的主画面和射线尺寸均为 3840×2160。",
276
"problems": []
277
}
278
],
279
"notice": "Evidence integrity/coverage gate; observations are not independently recognized or authenticated."
280
}
281
},
282
"scope": "Three gates partition the original five frozen requirements unchanged; functional UI/native-4K coverage only",
283
"knownVisualLimitations": [
284
"Near-field opaque cockpit is much darker without complete environment lighting",
285
"Visible grain and soft reflected instrument details remain",
286
"No long-duration motion/other cockpit/all resolution validation"
287
]
288
},
289
"performance": {
290
"label": "Native 4K near-field PT 2 spp 4 bounces",
291
"completedUtc": "2026-11-16T23:29:17.9968870Z",
292
"elapsedSeconds": 60.030176500022414,
293
"renderIntervals": {
294
"Count": 3903,
295
"Dropped": 0,
296
"Fps": 65.0391705445245,
297
"MeanMs": 15.375349833457982,
298
"P50Ms": 14.206000000238419,
299
"P95Ms": 24.841600000858307,
300
"P99Ms": 29.508599996566772,
301
"OnePercentLowFps": 27.277372487879415,
302
"MaxMs": 71.20359998941422,
303
"LongFrameThresholdMs": 50.0,
304
"LongFrameCount": 2,
305
"LongFrames": [
306
{
307
"Index": 234,
308
"EndMs": 3817.422399997711,
309
"DurationMs": 55.18510001897812
310
},
311
{
312
"Index": 3009,
313
"EndMs": 47176.78639999032,
314
"DurationMs": 71.20359998941422
315
}
316
]
317
},
318
"updateIntervals": {
319
"Count": 1656,
320
"Dropped": 0,
321
"Fps": 27.60880076539844,
322
"MeanMs": 36.22033454105258,
323
"P50Ms": 35.10900002717972,
324
"P95Ms": 44.6797000169754,
325
"P99Ms": 51.698500007390976,
326
"OnePercentLowFps": 17.99276521543177,
327
"MaxMs": 64.24789997935295,
328
"LongFrameThresholdMs": 70.21800005435944,
329
"LongFrameCount": 0,
330
"LongFrames": []
331
}
332
},
333
"performanceScope": "Single active-world cockpit observation after paused menu tests; not an A/B comparison and not a new Huanyu large-ship performance result",
334
"rawEvidence": [
335
{
336
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\final\\performance.json",
337
"sha256": "b0b841afc6b34d0d6dde06b8d33abc115e1f1c3dbf64fd402c6e7b0cad1ef917"
338
},
339
{
340
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\final\\reloaded.json",
341
"sha256": "7a35be5ff547862b29bce0db66fe95cf3dd0968a6569635c8a82ff57a1ae4d55"
342
},
343
{
344
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\final\\panel-state.json",
345
"sha256": "2c9192ffe7c01a6936839f98765cc38cd04e22ec24a78e5ea63cece0608725dc"
346
},
347
{
348
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\final\\end-world.status.json",
349
"sha256": "6cd8d52f3c781f6ebda5e0f468811ad3d64aea29a164bdc60e0170f35125badc"
350
},
351
{
352
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\final\\end-graphics.rayTracing.status.json",
353
"sha256": "326bf552acdf0e2aef87bce155da2158a3e8acf58f50d3504ad5fee14483e896"
354
},
355
{
356
"path": "C:\\Users\\XFEstudio\\Desktop\\work\\CSharp\\GitHub\\XFEstudio\\XFE.SpaceEngineers.AgentBridge\\artifacts\\graphics\\20261117-path\\Verify-Final.ps1",
357
"sha256": "eba71f20d4ab0963ede6f7ca13cd8d268183e7d1e9f2c51858559bd5fc60082d"
358
}
359
],
360
"endWorldPaused": false,
361
"limits": [
362
"Near-field opaque surfaces only; primary rays 256 m and existing scene capture limits",
363
"Sky and uncovered/distant surfaces use native lighting; primary glass retains hybrid behavior",
364
"No full environment or emissive-area importance sampling; no ReSTIR/NRD/DLSS RR integration"
365
]
366
}
@@ -0,0 +1,54 @@
1
# 路径追踪与原生画质菜单实测(2026-11-17)
2
3
本版增加可选的近场不透明表面路径积分,并把光追和路径追踪设置放入原版 **选项 → 图形选项 → 光追 / 路径追踪**。它仍是有界实验功能:天空、远景及未采集几何保留原版,主视图玻璃沿用现有混合透射/折射。不能称为全场景路径追踪。
4
5
## 设置与实现
6
7
菜单提供关闭、混合光追、路径追踪三种模式;射线半分辨率/原生分辨率;每帧 1–8 个样本;1–8 次反弹;时域积累与空间去噪;玻璃、体素及体素精度;混合 AO、接触阴影、反射与间接光强度。路径模式中不适用的混合参数禁用。主画面分辨率不随射线选项改变。
8
9
面板使用游戏原生 GUI 控件,保留独立草稿。“应用并保存”先成功写入配置再修改运行状态;“取消”或关闭面板不改变配置。重启从原有 `raytracing.json` 恢复,旧配置兼容,默认不开启新模式。新增 `graphics.rayTracing.menu` 是对这些实际控件和相同回调的有界自动化接口,详见 [API](API.md)。
10
11
路径模式以硬件射线确定首个不透明表面,并与原版深度交叉验证覆盖。有效表面的光照由自发光、太阳/局部灯直接采样和 BSDF 多次反弹计算,替换近场原生 HDR 光照;失配保留原版。使用 G-buffer 法线与光滑度、真实几何的颜色及发光材质,保留俄罗斯轮盘终止、几何校验历史和方差引导过滤。全分辨率模式同时调整打包、射线、重投影及合成坐标。
12
13
实现参考 [PBRT 路径积分与采样说明](https://pbr-book.org/4ed/Light_Transport_I_Surface_Reflection/A_Better_Path_Tracer)中的直接光/BSDF 采样和俄罗斯轮盘思路,以及 [NVIDIA RTXPT 设计说明](https://github.com/NVIDIA-RTX/RTXPT/blob/main/Docs/Design.md)的集成边界。没有引入其完整渲染器,也未集成 ReSTIR、NRD 或 DLSS Ray Reconstruction。
14
15
## 最终构建与验证
16
17
- Space Engineers 1.211.017,RTX 5090;最终进程 PID 154184。
18
- 只在已授权副本 `XFE Performance Huanyu 20261116` 验证;重启前离线备份为 `20261116T232604819-c178e6a809f74f56975f463b023192e8`,完整路径与文件证据见 [JSON 记录](evidence/path-tracing-menu-2026-11-17.json)。
19
- 测试镜头是当时玩家实际驾驶的战斗机驾驶舱 `107436408077512738`,没有用 spectator 替换第一人称内部模型,也没有移动舰船。本轮不作为新的寰宇号 CPU 优化对照。
20
- 最终托管插件 SHA-256:`73348F065AA08EF2AF796EDDC8F4B81B026139B2C8ED9B6F3773D2BA895C85C4`;安装文件与构建一致。嵌入原生模块:`135233E5E8693BB76F887EFE926D66ED46E2A3DDB6759D91E54A54C35769957F`。
21
- Release 构建零警告/零错误;通用测试 93 项通过,引擎测试程序通过,硬件 DXR GPU 回读与状态恢复测试通过。
22
23
新增 GPU 回读用例的结果:
24
25
| 场景 | 结果 |
26
| --- | --- |
27
| 发光首表面,半分辨率 | RGB `0, 0.497803, 0`,替换原生灰色光照 |
28
| 同一场景,全分辨率 | RGB `0, 0.497803, 0` |
29
| 首表面几何与光栅覆盖失配 | 保留原生 RGB `0.2, 0.2, 0.2` |
30
| 未照亮表面与屏幕外发光墙,一次反弹 | 绿色贡献 `0` |
31
| 同一场景,三次反弹、8 样本、去噪 | 绿色贡献 `0.128637` |
32
33
最终进程通过菜单依次应用关闭、混合光追、路径追踪;取消测试中文件哈希不变,运行状态不变。重启后的首次查询已恢复路径模式、原生射线、2 样本和 4 次反弹。自动化调用真实控件及其 Apply/Cancel 回调,没有模拟鼠标点击。
34
35
最终后台截图已查看原生尺寸图、局部分块及同视角局部并排/差异图。原版入口没有遮挡既有选项;新面板 13 项控件、滑块数值、说明和两个按钮完整。三份证据门禁按原冻结需求分组通过,只覆盖本轮功能和布局;不代表下述画质缺陷已解决。截图、哈希和检查结果保存在 JSON 记录中,原始大图及原生二进制不提交到 Git。
36
37
## 实际画面与性能边界
38
39
最终设置为原生 **3840×2160 主画面及射线**、DRS 关闭、2 样本/4 次反弹、去噪/玻璃/体素开启。已保留这一设置供用户从游戏菜单调整。
40
41
同镜头对照中,玻璃仍可见蓝色仪表反射,天空和 HUD 保留;近场舱框明显变暗,暗部仍有噪点。这不是已经解决的画质问题:目前缺少完整环境贴图采样及小面积发光面的重要性采样,不能保证舱内照明和噪声达到可发布质量。玻璃细小反射仍偏软,移动视角、其他驾驶舱、其他窗口尺寸和长时间运行尚未完成专项验收。本轮镜头没有近场体素,不能据此声称完成路径模式的实景地表覆盖验收。
42
43
截图为暂停世界的固定视角对照;性能另在恢复运行后采样 60.03 秒,菜单关闭,无方法计时探针:
44
45
| 指标 | 实测 |
46
| --- | --- |
47
| 渲染间隔平均 FPS | 65.04 |
48
| 渲染间隔 P95 / P99 | 24.84 / 29.51 ms |
49
| 1% low | 27.28 FPS |
50
| 超过 50 ms 的帧 / 最长帧 | 2 / 71.20 ms |
51
| 模拟更新频率 | 27.61 Hz |
52
| 采样末尾模拟速度 | 0.50 |
53
54
这是单次驾驶舱观察,没有同条件关闭模式的运行性能基线,不能据此声称帧率提升;模拟速度与卡顿仍有问题。DXR 状态为 active、HRESULT 为 0、failure 为空。结束时世界已恢复运行,原生设置面板关闭,镜头仍由实际驾驶舱控制。
@@ -74,7 +74,7 @@ namespace XFE.SeAgent.Plugin
74
74
["mutationPolicy"] = "Only explicitly authorized offline test worlds; all game access runs on the game thread.",
75
75
["methods"] = new JArray("agent.ping", "agent.capabilities", "agent.events", "graphics.status", "graphics.rayTracing.status", "graphics.rayTracing.configure", "performance.status", "performance.capture", "performance.report", "performance.configure", "debug.closePauseMenu", "world.status", "world.load", "world.save", "world.pause", "world.exit", "world.unload", "game.exit",
76
76
"grids.list", "grids.get", "grid.stop", "blocks.list", "blocks.get", "blocks.actions", "blocks.action", "blocks.properties", "blocks.setProperty",
77
"pb.read", "pb.inspect", "pb.deploy", "pb.run", "cameras.scan", "telemetry.snapshot", "inventory.route", "sorters.setFilters", "debug.screenshot", "debug.dismissInfo", "debug.camera", "graphics.rayTracing.inspect")
77
"pb.read", "pb.inspect", "pb.deploy", "pb.run", "cameras.scan", "telemetry.snapshot", "inventory.route", "sorters.setFilters", "debug.screenshot", "debug.dismissInfo", "debug.camera", "graphics.rayTracing.inspect", "graphics.rayTracing.menu")
78
78
};
79
79
if (method == "agent.events")
80
80
{
@@ -48,6 +48,7 @@ namespace XFE.SeAgent.Plugin.Game
48
48
case "performance.status": return PerformanceStatus();
49
49
case "graphics.status": return Performance.GraphicsDiagnostics.Snapshot();
50
50
case "graphics.rayTracing.status": return rayTracing?.Status() ?? new JObject { ["unavailable"] = true };
51
case "graphics.rayTracing.menu": return rayTracing?.SettingsMenu(args) ?? new JObject { ["unavailable"] = true };
51
52
case "graphics.rayTracing.inspect": RequireWorld(); return rayTracing?.Inspect((string)args["model"]) ?? new JObject { ["unavailable"]=true };
52
53
case "debug.camera": RequireWorld(); return CameraView(args);
53
54
case "graphics.rayTracing.configure":
@@ -0,0 +1,153 @@
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using HarmonyLib;
6
using Newtonsoft.Json.Linq;
7
using Sandbox.Game.World;
8
using Sandbox.Graphics.GUI;
9
using SpaceEngineers.Game.GUI;
10
using VRage.Game;
11
using VRage.Utils;
12
using VRageMath;
13
14
namespace XFE.SeAgent.Plugin.Graphics
15
{
16
internal sealed partial class RayTracing
17
{
18
private SettingsScreen settingsScreen;
19
private void InstallSettingsMenu() => harmony.Patch(
20
AccessTools.DeclaredMethod(typeof(MyGuiScreenOptionsGraphics),"RecreateControls"),
21
postfix:new HarmonyMethod(typeof(RayTracing),nameof(AfterGraphicsControls)));
22
private static void AfterGraphicsControls(MyGuiScreenOptionsGraphics __instance,bool constructor)
23
{
24
if(!constructor || active==null)return;
25
var button=new MyGuiControlButton(position:new Vector2(.172f,-.437f),text:new StringBuilder("光追 / 路径追踪"),textScale:.65f,
26
onButtonClick: _=>active?.OpenSettings()) {Name="XFE_RayTracingSettings",Size=new Vector2(.25f,.042f)};
27
__instance.Controls.Add(button);
28
}
29
private void OpenSettings()
30
{
31
if(settingsScreen!=null)return;
32
settingsScreen=new SettingsScreen(this);
33
settingsScreen.Closed+=(screen,unloading)=>settingsScreen=null;
34
MyGuiSandbox.AddScreen(settingsScreen);
35
}
36
// Bounded automation of these exact native controls for integration tests.
37
// It uses the same draft/apply/cancel callbacks as the in-game menu.
38
public JObject SettingsMenu(JObject args)
39
{
40
string action=(string)args["action"]??"status";
41
if(action=="openGraphics")MyGuiSandbox.AddScreen(new MyGuiScreenOptionsGraphics());
42
else if(action=="open")OpenSettings();
43
else if(action=="set") {
44
if(settingsScreen==null)throw new InvalidOperationException("Settings menu is not open.");
45
settingsScreen.SetValues(args["values"] as JObject??throw new ArgumentException("values object required"));
46
} else if(action=="apply") {
47
if(settingsScreen==null)throw new InvalidOperationException("Settings menu is not open.");
48
settingsScreen.Apply();
49
} else if(action=="cancel")settingsScreen?.CloseScreenNow();
50
else if(action=="closeGraphics") {
51
foreach(var s in MyScreenManager.Screens.ToArray())if(s is MyGuiScreenOptionsGraphics)s.CloseScreenNow();
52
} else if(action!="status")throw new ArgumentException("Unknown graphics menu action.");
53
return new JObject { ["open"]=settingsScreen!=null,["draft"]=settingsScreen?.Values(),["controls"]=settingsScreen?.Layout(),["error"]=settingsScreen?.Error,
54
["graphicsEntryPresent"]=MyScreenManager.Screens.OfType<MyGuiScreenOptionsGraphics>().Any(s=>s.Controls.Any(c=>c.Name=="XFE_RayTracingSettings")) };
55
}
56
private sealed class SettingsScreen:MyGuiScreenBase
57
{
58
private readonly RayTracing owner;
59
private readonly Dictionary<string,MyGuiControlBase> fields=new Dictionary<string,MyGuiControlBase>();
60
private readonly MyGuiControlLabel error;
61
private int row;
62
public string Error {get;private set;}
63
public override string GetFriendlyName()=>"XFE Ray Tracing Graphics Settings";
64
public SettingsScreen(RayTracing owner):base(new Vector2(.5f,.5f),MyGuiConstants.SCREEN_BACKGROUND_COLOR,new Vector2(.8f,.94f),false)
65
{
66
this.owner=owner;EnabledBackgroundFade=true;
67
AddCaption("光追与路径追踪",null,new Vector2(0,.006f));
68
var o=owner.options;
69
Combo("mode","渲染模式",o.Enabled?(o.PathTracing?2:1):0,new[]{"关闭","混合光线追踪","路径追踪(近场实验)"});
70
Combo("fullResolution","射线分辨率",o.FullResolution?1:0,new[]{"半分辨率","原生分辨率"});
71
Combo("samples","路径追踪每帧采样",o.Samples-1,Enumerable.Range(1,8).Select(i=>i+" 个样本").ToArray());
72
Combo("bounces","最大反弹次数",o.Bounces-1,Enumerable.Range(1,8).Select(i=>i+" 次").ToArray());
73
Check("denoise","时域积累与空间去噪",o.Denoise);
74
Check("glass","玻璃反射与折射",o.Glass);
75
Check("voxels","小行星与地表体素",o.Voxels);
76
Combo("voxelLod","体素精度",o.VoxelLod,new[]{"精细(1 米)","均衡(2 米)","快速(4 米)"});
77
Slider("radius","环境遮蔽范围(米)",o.Radius,.25f,12);
78
Slider("strength","环境遮蔽强度",o.Strength,0,1);
79
Slider("shadowStrength","接触阴影强度",o.ShadowStrength,0,.5f);
80
Slider("reflections","混合 / 玻璃反射强度",o.Reflections,0,1);
81
Slider("indirect","间接光强度",o.Indirect,0,1);
82
Controls.Add(new MyGuiControlLabel(position:new Vector2(-.35f,.285f),text:"路径追踪替换近场不透明表面的光照;远景与天空保留原版。",textScale:.62f));
83
Controls.Add(new MyGuiControlLabel(position:new Vector2(-.35f,.315f),text:"主画面分辨率不变。原生射线、多采样与多反弹会增加显卡负载。",textScale:.62f));
84
error=new MyGuiControlLabel(position:new Vector2(-.35f,.345f),text:"",textScale:.6f);Controls.Add(error);
85
Controls.Add(new MyGuiControlButton(position:new Vector2(-.14f,.402f),text:new StringBuilder("应用并保存"),onButtonClick:_=>Apply()){Name="XFE_Apply"});
86
Controls.Add(new MyGuiControlButton(position:new Vector2(.14f,.402f),text:new StringBuilder("取消"),onButtonClick:_=>CloseScreen()){Name="XFE_Cancel"});
87
((MyGuiControlCombobox)fields["mode"]).ItemSelected+=RefreshEnabled;
88
((MyGuiControlCheckbox)fields["voxels"]).IsCheckedChanged=_=>RefreshEnabled();RefreshEnabled();
89
}
90
private Vector2 PositionFor(string key,string caption,MyGuiControlBase control)
91
{
92
float y=-.345f+row++*.046f;
93
Controls.Add(new MyGuiControlLabel(position:new Vector2(-.35f,y),text:caption,textScale:.72f,originAlign:MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));
94
control.Name=key;fields.Add(key,control);Controls.Add(control);return new Vector2(.15f,y);
95
}
96
private void Combo(string key,string caption,int selected,string[] items)
97
{
98
var c=new MyGuiControlCombobox();c.Position=PositionFor(key,caption,c);c.Size=new Vector2(.34f,.04f);
99
for(int i=0;i<items.Length;i++)c.AddItem(i,items[i]);c.SelectItemByKey(selected);
100
}
101
private void Check(string key,string caption,bool value)
102
{
103
var c=new MyGuiControlCheckbox(isChecked:value);c.Position=PositionFor(key,caption,c);
104
}
105
private void Slider(string key,string caption,float value,float min,float max)
106
{
107
var c=new MyGuiControlSlider(minValue:min,maxValue:max,width:.30f,labelText:"{0}",labelSpaceWidth:.05f,labelDecimalPlaces:2,showLabel:true,labelScale:.65f);
108
c.Position=PositionFor(key,caption,c);c.Value=value;
109
}
110
private long Selected(string key)=>((MyGuiControlCombobox)fields[key]).GetSelectedKey();
111
private void RefreshEnabled()
112
{
113
bool enabled=Selected("mode")!=0,path=Selected("mode")==2;
114
foreach(var f in fields)if(f.Key!="mode")f.Value.Enabled=enabled;
115
fields["samples"].Enabled=enabled && path;
116
fields["voxelLod"].Enabled=enabled && ((MyGuiControlCheckbox)fields["voxels"]).IsChecked;
117
foreach(var key in new[]{"radius","strength","shadowStrength","indirect"})fields[key].Enabled=enabled && !path;
118
}
119
public JObject Values()
120
{
121
var v=new JObject();foreach(var field in fields) {
122
if(field.Value is MyGuiControlCombobox c)v[field.Key]=c.GetSelectedKey();
123
else if(field.Value is MyGuiControlCheckbox b)v[field.Key]=b.IsChecked;
124
else if(field.Value is MyGuiControlSlider s)v[field.Key]=s.Value;
125
}
126
return v;
127
}
128
public JArray Layout()=>new JArray(Controls.Select(c=>new JObject { ["name"]=c.Name,["enabled"]=c.Enabled,
129
["x"]=c.Position.X,["y"]=c.Position.Y,["width"]=c.Size.X,["height"]=c.Size.Y,
130
["text"]=(c as MyGuiControlLabel)?.Text }));
131
public void SetValues(JObject values)
132
{
133
foreach(var p in values.Properties()) {
134
if(!fields.TryGetValue(p.Name,out var field))throw new ArgumentException("Unknown control: "+p.Name);
135
if(field is MyGuiControlCombobox c) {if(p.Value.Type!=JTokenType.Integer)throw new ArgumentException("Integer selection required");c.SelectItemByKey((long)p.Value);}
136
else if(field is MyGuiControlCheckbox b)b.IsChecked=(bool)p.Value;
137
else if(field is MyGuiControlSlider s)s.Value=(float)p.Value;
138
}
139
RefreshEnabled();
140
}
141
public void Apply()
142
{
143
try {
144
if(MySession.Static!=null && MySession.Static.OnlineMode!=MyOnlineModeEnum.OFFLINE)throw new InvalidOperationException("此实验功能目前仅支持离线世界。");
145
var v=Values();long mode=(long)v["mode"];v.Remove("mode");
146
v["enabled"]=mode!=0;v["pathTracing"]=mode==2;v["fullResolution"]=(long)v["fullResolution"]==1;
147
v["samples"]=(long)v["samples"]+1;v["bounces"]=(long)v["bounces"]+1;v["persist"]=true;v["diagnostic"]=0;
148
owner.Configure(v);CloseScreen();
149
}catch(Exception ex){Error=ex.Message;error.Text="无法应用:"+ex.Message;}
150
}
151
}
152
}
153
}
@@ -46,6 +46,7 @@ namespace XFE.SeAgent.Plugin.Graphics
46
46
public Matrix PreviousViewProjection;
47
47
public Vector4 PreviousCamera, OriginChange, History, Transport;
48
48
public Matrix ViewProjection;
49
public Vector4 PathSettings;
49
50
}
50
51
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] private struct NativeStatus
51
52
{
@@ -65,7 +66,7 @@ namespace XFE.SeAgent.Plugin.Graphics
65
66
[DllImport(Library, CallingConvention=CallingConvention.Cdecl)] private static extern void RtDestroy(IntPtr context);
66
67
[DllImport("kernel32", CharSet=CharSet.Unicode, SetLastError=true)] private static extern IntPtr LoadLibraryEx(string path, IntPtr file, uint flags);
67
68
68
private sealed class Options { public bool Enabled; public float Radius=3, Strength=.3f, ShadowStrength=.15f, Reflections=.8f, Indirect=.6f; public int Diagnostic, Bounces=3, VoxelLod=0; public bool Glass=true, Voxels=true; }
69
private sealed class Options { public bool Enabled, PathTracing, FullResolution; public float Radius=3, Strength=.3f, ShadowStrength=.15f, Reflections=.8f, Indirect=.6f; public int Diagnostic, Bounces=3, VoxelLod=0, Samples=1; public bool Glass=true, Voxels=true, Denoise=true; }
69
70
private sealed class Mesh { public uint Id; public float[] Vertices; public uint[] Indices, Materials; public MeshPart[] Parts; }
70
71
private sealed class MeshPart { public string Name; public int Start,Count; }
71
72
private sealed class Material { public uint Id; public string Path; public bool Linear; public Task<byte[]> Bytes; }
@@ -125,6 +126,7 @@ namespace XFE.SeAgent.Plugin.Graphics
125
126
// tone mapping and HUD. The engine's cached state is restored by native.
126
127
harmony.Patch(done, postfix:new HarmonyMethod(typeof(RayTracing),nameof(AfterScene)));
127
128
InstallScreenCapture();
129
InstallSettingsMenu();
128
130
active=this;
129
131
MyCubeGrid.OnBlockAddedGlobally+=GeometryChanged;
130
132
MyCubeGrid.OnBlockRemovedGlobally+=GeometryChanged;
@@ -137,34 +139,37 @@ namespace XFE.SeAgent.Plugin.Graphics
137
139
{
138
140
foreach (var property in args.Properties())
139
141
{
140
if (!new[]{"enabled","radius","strength","shadowStrength","reflections","indirect","diagnostic","persist","glass","voxels","bounces","voxelLod"}.Contains(property.Name)) throw new ArgumentException("Unknown ray tracing option: "+property.Name);
141
bool boolean=property.Name=="enabled" || property.Name=="persist" || property.Name=="glass" || property.Name=="voxels";
142
if (!new[]{"enabled","radius","strength","shadowStrength","reflections","indirect","diagnostic","persist","glass","voxels","bounces","voxelLod","pathTracing","fullResolution","samples","denoise"}.Contains(property.Name)) throw new ArgumentException("Unknown ray tracing option: "+property.Name);
143
bool boolean=new[]{"enabled","persist","glass","voxels","pathTracing","fullResolution","denoise"}.Contains(property.Name);
142
144
if(boolean ? property.Value.Type!=JTokenType.Boolean : property.Value.Type!=JTokenType.Integer && property.Value.Type!=JTokenType.Float)
143
145
throw new ArgumentException("Invalid ray tracing option type: "+property.Name);
144
if((property.Name=="diagnostic" || property.Name=="bounces" || property.Name=="voxelLod") && property.Value.Type!=JTokenType.Integer) throw new ArgumentException(property.Name+" must be an integer.");
146
if((property.Name=="diagnostic" || property.Name=="bounces" || property.Name=="voxelLod" || property.Name=="samples") && property.Value.Type!=JTokenType.Integer) throw new ArgumentException(property.Name+" must be an integer.");
145
147
}
146
148
var old=options;
147
149
var next=new Options { Enabled=(bool?)args["enabled"]??old.Enabled, Radius=(float?)args["radius"]??old.Radius,
148
150
Strength=(float?)args["strength"]??old.Strength, ShadowStrength=(float?)args["shadowStrength"]??old.ShadowStrength,
149
151
Reflections=(float?)args["reflections"]??old.Reflections, Indirect=(float?)args["indirect"]??old.Indirect,
150
152
Diagnostic=(int?)args["diagnostic"]??old.Diagnostic, Bounces=(int?)args["bounces"]??old.Bounces,
151
VoxelLod=(int?)args["voxelLod"]??old.VoxelLod, Glass=(bool?)args["glass"]??old.Glass, Voxels=(bool?)args["voxels"]??old.Voxels };
153
VoxelLod=(int?)args["voxelLod"]??old.VoxelLod, Glass=(bool?)args["glass"]??old.Glass, Voxels=(bool?)args["voxels"]??old.Voxels,
154
PathTracing=(bool?)args["pathTracing"]??old.PathTracing, FullResolution=(bool?)args["fullResolution"]??old.FullResolution,
155
Samples=(int?)args["samples"]??old.Samples,Denoise=(bool?)args["denoise"]??old.Denoise };
152
156
if (!Finite(next.Radius) || next.Radius<.25f || next.Radius>12 || !Finite(next.Strength) || next.Strength<0 || next.Strength>1 ||
153
157
!Finite(next.ShadowStrength) || next.ShadowStrength<0 || next.ShadowStrength>.5f || !Finite(next.Reflections) || next.Reflections<0 || next.Reflections>1 ||
154
!Finite(next.Indirect) || next.Indirect<0 || next.Indirect>1 || next.Diagnostic<0 || next.Diagnostic>6 || next.Bounces<1 || next.Bounces>4 || next.VoxelLod<0 || next.VoxelLod>2)
155
throw new ArgumentException("radius .25..12 m; strength/reflections/indirect 0..1; shadowStrength 0...5; diagnostic 0..6; bounces 1..4; voxelLod 0..2.");
158
!Finite(next.Indirect) || next.Indirect<0 || next.Indirect>1 || next.Diagnostic<0 || next.Diagnostic>6 || next.Bounces<1 || next.Bounces>8 || next.VoxelLod<0 || next.VoxelLod>2 || next.Samples<1 || next.Samples>8)
159
throw new ArgumentException("radius .25..12 m; strength/reflections/indirect 0..1; shadowStrength 0...5; diagnostic 0..6; bounces/samples 1..8; voxelLod 0..2.");
156
160
if (next.Enabled && failure!=null) throw new InvalidOperationException("Ray tracing failed closed: "+failure+". Restart after correcting the cause.");
157
options=next;
158
if(next.Voxels!=old.Voxels || next.VoxelLod!=old.VoxelLod) Interlocked.Increment(ref sceneGeneration);
159
Interlocked.Exchange(ref resetHistory,1);
160
161
if(mayPersist && (bool?)args["persist"]==true) {
161
162
var settings=new JObject { ["enabled"]=next.Enabled,["radius"]=next.Radius,["strength"]=next.Strength,
162
163
["shadowStrength"]=next.ShadowStrength,["reflections"]=next.Reflections,["indirect"]=next.Indirect,
163
["glass"]=next.Glass,["voxels"]=next.Voxels,["bounces"]=next.Bounces,["voxelLod"]=next.VoxelLod };
164
["glass"]=next.Glass,["voxels"]=next.Voxels,["bounces"]=next.Bounces,["voxelLod"]=next.VoxelLod,
165
["pathTracing"]=next.PathTracing,["fullResolution"]=next.FullResolution,["samples"]=next.Samples,["denoise"]=next.Denoise };
164
166
Directory.CreateDirectory(Path.GetDirectoryName(settingsPath));
165
167
File.WriteAllText(settingsPath+".tmp",settings.ToString());
166
168
if(File.Exists(settingsPath)) File.Replace(settingsPath+".tmp",settingsPath,settingsPath+".bak"); else File.Move(settingsPath+".tmp",settingsPath);
167
169
}
170
options=next;
171
if(next.Voxels!=old.Voxels || next.VoxelLod!=old.VoxelLod) Interlocked.Increment(ref sceneGeneration);
172
Interlocked.Exchange(ref resetHistory,1);
168
173
return Status();
169
174
}
170
175
private static bool Finite(float value) => !float.IsNaN(value) && !float.IsInfinity(value);
@@ -173,6 +178,7 @@ namespace XFE.SeAgent.Plugin.Graphics
173
178
var o=options; var s=snapshots.Current;
174
179
var rendered=(JObject)renderStatus.DeepClone(); if(!o.Enabled) rendered["state"]="disabled"; else if(!worldReady) rendered["state"]="no-world";
175
180
return new JObject { ["enabled"]=o.Enabled, ["radius"]=o.Radius, ["strength"]=o.Strength, ["shadowStrength"]=o.ShadowStrength,
181
["pathTracing"]=o.PathTracing,["fullResolution"]=o.FullResolution,["samples"]=o.Samples,["denoise"]=o.Denoise,["mode"]=!o.Enabled?"disabled":o.PathTracing?"path-traced-near-field":"hybrid-ray-tracing",
176
182
["diagnostic"]=o.Diagnostic, ["failure"]=failure, ["render"]=rendered, ["collecting"]=collector!=null,
177
183
["reflections"]=o.Reflections,["indirect"]=o.Indirect,["textureFallbacks"]=textureFallbacks,
178
184
["glass"]=o.Glass,["voxels"]=o.Voxels,["bounces"]=o.Bounces,["voxelLod"]=o.VoxelLod,
@@ -181,8 +187,8 @@ namespace XFE.SeAgent.Plugin.Graphics
181
187
["localLights"]=s?.Lights?.Length??0,["screens"]=screenStatus,
182
188
["scannedBlocks"]=scannedBlocks, ["skippedModels"]=skippedModels, ["snapshotInstances"]=s?.Count??0,
183
189
["snapshotAgeMs"]=s==null ? (JToken)null : (Stopwatch.GetTimestamp()-s.Created)*1000.0/Stopwatch.Frequency,
184
["implementation"]="DXR 1.1 inline hardware rays over cached triangle models. Half-resolution rays, bilateral composite into native HDR before HUD.",
185
["limits"]="Local hybrid DXR: 1..4 bounces, up to 64 point/spot fixtures via RIS, emissive mesh materials and up to 32 live LCD textures within 64 m at 10 Hz (current cockpit first), thin dielectric glass, editable voxel capture within 320 m / primary rays 256 m. Variance-guided GI and reflection filtering. Glass defaults IOR 1.52 / 10 mm; primary refraction reuses depth-validated native HDR, secondary paths refract through slabs. Native transparency and approximate ambient remain. No ReSTIR reuse, NRD, DLSS RR, full-frame path tracing, solid dielectric volumes, cutouts, deformation or secondary normal maps." };
190
["implementation"]="DXR 1.1 hardware geometry rays. Hybrid effects or near-field opaque surface path integration, 1..8 samples/bounces; full/half resolution; native HDR before HUD.",
191
["limits"]="Near-field path tracing replaces covered opaque lighting with emission, direct-light sampling and BSDF paths; raster depth validates primary visibility. Uncovered geometry, sky and distant scenes keep native shading. Glass retains hybrid primary transparency and thin-slab secondary transport. Up to 64 fixtures, 32 live LCDs within 64 m at 10 Hz; voxel capture 320 m, primary range 256 m. No environment-map sampling, emissive-area importance sampling, ReSTIR, NRD, DLSS RR, full-scene path tracing, solid dielectric volumes, cutouts, deformation or secondary normal maps." };
186
192
}
187
193
public void Update(bool allowed)
188
194
{
@@ -502,11 +508,12 @@ namespace XFE.SeAgent.Plugin.Graphics
502
508
var sunColor=(Vector3)Member(lighting,"SunColorRaw")*(float)Member(lighting,"SunDiffuseFactor");
503
509
var p=new Parameters { InverseViewProjection=(Matrix)Member(matrices,"InvViewProjectionAt0"), InverseView=(Matrix)Member(matrices,"InvViewAt0"),
504
510
OriginDelta=new Vector4((Vector3)(camera-s.Origin),0), SunDirection=new Vector4(sunVector,0), Settings=new Vector4(o.Radius,o.Strength,o.ShadowStrength,o.Diagnostic),
505
Width=(uint)resolution.X,Height=(uint)resolution.Y,TraceWidth=(uint)(resolution.X+1)/2,TraceHeight=(uint)(resolution.Y+1)/2,
511
Width=(uint)resolution.X,Height=(uint)resolution.Y,TraceWidth=(uint)(o.FullResolution?resolution.X:(resolution.X+1)/2),TraceHeight=(uint)(o.FullResolution?resolution.Y:(resolution.Y+1)/2),
506
512
SunColor=new Vector4(sunColor,0),Effects=new Vector4(o.Reflections,o.Indirect,o.Voxels?2.5f*(1<<o.VoxelLod):0,0), PreviousViewProjection=previousViewProjection,
507
513
PreviousCamera=new Vector4((Vector3)(previousCamera-s.Origin),0),OriginChange=new Vector4((Vector3)(s.Origin-previousOrigin),0),
508
History=new Vector4(previousFrameAt!=0 && Stopwatch.GetTimestamp()-previousFrameAt<Stopwatch.Frequency/4?1:0,0,0,0),
509
Transport=new Vector4(o.Bounces,64,o.Glass?1:0,s.Lights.Length),ViewProjection=(Matrix)Member(matrices,"ViewProjectionAt0") };
514
History=new Vector4(o.Denoise && previousFrameAt!=0 && Stopwatch.GetTimestamp()-previousFrameAt<Stopwatch.Frequency/4?1:0,0,0,0),
515
Transport=new Vector4(o.Bounces,64,o.Glass?1:0,s.Lights.Length),ViewProjection=(Matrix)Member(matrices,"ViewProjectionAt0"),
516
PathSettings=new Vector4(o.PathTracing?1:0,o.Samples,0,o.Denoise?1:0) };
510
517
var g=Member(GBuffer,"Main");
511
518
UpdateScreens(s.Screens);
512
519
int code=RtFrame(native,Pointer(Member(Member(Member(g,"ResolvedDepthStencil"),"SrvDepth"),"Srv")),
@@ -543,6 +550,7 @@ namespace XFE.SeAgent.Plugin.Graphics
543
550
private void Fail(string reason) { failure=reason; log("Ray tracing disabled: "+reason); }
544
551
public void Dispose()
545
552
{
553
settingsScreen?.CloseScreenNow();
546
554
harmony.UnpatchAll(harmony.Id); active=null; worldReady=false;
547
555
MyCubeGrid.OnBlockAddedGlobally-=GeometryChanged; MyCubeGrid.OnBlockRemovedGlobally-=GeometryChanged;
548
556
ResetCapture();
@@ -12,6 +12,7 @@ cbuffer Parameters : register(b0) {
12
12
row_major float4x4 previousViewProjection;
13
13
float4 previousCamera, originChange, history, transport;
14
14
row_major float4x4 viewProjection;
15
float4 pathSettings;
15
16
};
16
17
Texture2D<float> depthInput : register(t0);
17
18
Texture2D<float4> normalInput : register(t1);
@@ -37,7 +38,7 @@ float3 DecodeNormal(float2 packed) {
37
38
[numthreads(8, 8, 1)]
38
39
void Pack(uint3 id : SV_DispatchThreadID) {
39
40
if (any(id.xy >= sizes.zw)) return;
40
uint2 p = min(id.xy * 2 + 1, sizes.xy - 1);
41
uint2 p = min(uint2((float2(id.xy)+.5)*float2(sizes.xy)/sizes.zw),sizes.xy-1);
41
42
float depth = depthInput[p];
42
43
float2 uv = (float2(p) + .5) / sizes.xy;
43
44
float4 world = mul(float4(uv.x * 2 - 1, 1 - uv.y * 2, depth, 1), inverseViewProjection);
@@ -52,7 +53,7 @@ float4 Fullscreen(uint id : SV_VertexID) : SV_Position {
52
53
return float4(id == 2 ? 3 : -1, id == 1 ? 3 : -1, 0, 1);
53
54
}
54
55
float4 GlassComposite(uint2 pixel,float4 color) {
55
int2 center=int2(pixel/2);float4 data=glassDataResult[center];
56
int2 center=int2(min(pixel*sizes.zw/sizes.xy,sizes.zw-1));float4 data=glassDataResult[center];
56
57
if(data.w<=0) return color;
57
58
float4 refraction=glassRefractionResult[center];
58
59
if(refraction.w>0) {
@@ -81,9 +82,9 @@ float4 Composite(float4 screen : SV_Position) : SV_Target {
81
82
uint2 pixel = uint2(screen.xy);
82
83
float4 color = lightInput[pixel];
83
84
if(settings.w==5) {
84
float4 g=glassDataResult[pixel/2];return g.w>0?float4(g.rgb,1):float4(0,0,0,1);
85
float4 g=glassDataResult[min(pixel*sizes.zw/sizes.xy,sizes.zw-1)];return g.w>0?float4(g.rgb,1):float4(0,0,0,1);
85
86
}
86
if(settings.w==6) return float4(traceResult[pixel/2].zzz,1);
87
if(settings.w==6) return float4(traceResult[min(pixel*sizes.zw/sizes.xy,sizes.zw-1)].zzz,1);
87
88
float depth = depthInput[pixel];
88
89
if (depth <= 0) return GlassComposite(pixel,color);
89
90
float2 uv = (float2(pixel) + .5) / sizes.xy;
@@ -93,12 +94,14 @@ float4 Composite(float4 screen : SV_Position) : SV_Target {
93
94
float3 pos = local + originDelta.xyz;
94
95
float3 n = normalize(mul(float4(DecodeNormal(normalInput[pixel].xy), 0), inverseView).xyz);
95
96
float2 sum = 0; float4 reflected = 0; float3 indirect = 0; float weight = 0;
96
int2 center = int2(pixel / 2);
97
int2 center = int2(min(pixel*sizes.zw/sizes.xy,sizes.zw-1));
98
if(pathSettings.x>0 && traceResult[center].w<=0)return GlassComposite(pixel,color);
97
99
// Joint bilateral upsample: respect geometry edges, do not darken sky/HUD.
98
100
[unroll] for (int y = -2; y <= 2; ++y) [unroll] for (int x = -2; x <= 2; ++x) {
99
101
int2 q = clamp(center + int2(x, y), 0, int2(sizes.zw) - 1);
100
102
float4 p = positions[q];
101
103
if (p.w == 0) continue;
104
if(pathSettings.x>0 && traceResult[q].w==0)continue;
102
105
float3 nn = normals[q].xyz;
103
106
float w = p.w * exp(-abs(dot(p.xyz - pos, n))*12 - (x*x+y*y)*.25)
104
107
* pow(saturate(dot(n,nn)), 24);
@@ -106,6 +109,7 @@ float4 Composite(float4 screen : SV_Position) : SV_Target {
106
109
}
107
110
float2 visibility = weight > 1e-5 ? sum / weight : 1;
108
111
reflected /= max(weight,1e-5); indirect /= max(weight,1e-5);
112
if(pathSettings.x>0 && settings.w==0) return GlassComposite(pixel,float4(weight>1e-5?indirect:color.rgb,color.a));
109
113
float4 mat = materialInput[pixel];
110
114
float diffuse = (1 - mat.x) * (1 - mat.z);
111
115
float ao = lerp(1, visibility.x, settings.y * (1 - mat.z));
@@ -34,7 +34,7 @@ struct Vertex { float position[3],uv[2],tint[3]; };
34
34
struct Triangle { uint32_t v[3],material; };
35
35
struct InstanceMaterial { uint32_t triangleOffset; float tint[3]; };
36
36
static_assert(sizeof(RtSurfaceMaterial)==32,"Surface material shader layout");
37
static_assert(sizeof(RtParameters)==416 && sizeof(RtInstance)==64 && sizeof(Vertex)==32 && sizeof(RtGlassMaterial)==32,"Managed/native/shader ABI mismatch");
37
static_assert(sizeof(RtParameters)==432 && sizeof(RtInstance)==64 && sizeof(Vertex)==32 && sizeof(RtGlassMaterial)==32,"Managed/native/shader ABI mismatch");
38
38
struct SharedTexture {
39
39
ComPtr<ID3D12Resource> resource;
40
40
ComPtr<ID3D11Texture2D> texture;
@@ -384,8 +384,10 @@ public:
384
384
params.transport[3]=(float)lights.size();
385
385
if (!ready) return -1;
386
386
if (!depth || !normal || !light || !material || !albedo || !target || !scene) throw Failure(E_INVALIDARG, "Missing frame resources");
387
if(!params.sizes[0] || !params.sizes[1] || params.sizes[2]!=(params.sizes[0]+1)/2 || params.sizes[3]!=(params.sizes[1]+1)/2)
388
throw Failure(E_INVALIDARG,"Frame dimensions must match half-resolution ray buffers");
387
bool half=params.sizes[2]==(params.sizes[0]+1)/2 && params.sizes[3]==(params.sizes[1]+1)/2;
388
bool full=params.sizes[2]==params.sizes[0] && params.sizes[3]==params.sizes[1];
389
if(!params.sizes[0] || !params.sizes[1] || (!half && !full))
390
throw Failure(E_INVALIDARG,"Frame dimensions must match half or full resolution ray buffers");
389
391
WaitPrevious(); transient.clear(); Resize(params.sizes[2], params.sizes[3]);
390
392
if(timerReady) {
391
393
void* data=nullptr;D3D12_RANGE read{0,16};Check(timerReadback->Map(0,&read,&data),"Read GPU timestamps");
@@ -480,7 +482,8 @@ public:
480
482
// Keep temporal history unfiltered: feeding a spatial blur back into
481
483
// accumulation progressively destroys detail. Three expanding passes
482
484
// operate on this frame only, with geometry and radiance edge weights.
483
if(params.effects[0]>0 || params.effects[1]>0) {
485
if(params.pathSettings[3]>0 && (params.pathSettings[0]>0 || params.effects[0]>0 || params.effects[1]>0)) {
486
Barrier(result.resource.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
484
487
list->SetPipelineState(denoisePipeline.Get());
485
488
Barrier(positions.resource.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
486
489
Barrier(normals.resource.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -507,6 +510,8 @@ public:
507
510
Barrier(normals.resource.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON);
508
511
Barrier(moments.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COMMON);
509
512
}
513
if(params.pathSettings[3]>0 && (params.pathSettings[0]>0 || params.effects[0]>0 || params.effects[1]>0))
514
Barrier(result.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COMMON);
510
515
list->EndQuery(timer.Get(),D3D12_QUERY_TYPE_TIMESTAMP,1);
511
516
for(auto& d:dynamicTextures) if(d.second.source && d.second.shared.resource)
512
517
Barrier(d.second.shared.resource.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON);
@@ -8,6 +8,7 @@ struct RtParameters {
8
8
float sunColor[4], effects[4]; // reflected/indirect strength, reserved
9
9
float previousViewProjection[16], previousCamera[4], originChange[4], history[4], transport[4];
10
10
float viewProjection[16];
11
float pathSettings[4]; // path mode, samples per pixel, reserved, denoise
11
12
};
12
13
struct RtGlassMaterial { float transmission[4],optics[4]; };
13
14
struct RtLight { float positionRange[4],colorIntensity[4],directionCone[4],settings[4]; };
@@ -40,6 +40,7 @@ cbuffer Parameters : register(b0) {
40
40
row_major float4x4 previousViewProjection;
41
41
float4 previousCamera, originChange, history, transport;
42
42
row_major float4x4 viewProjection;
43
float4 pathSettings;
43
44
};
44
45
cbuffer FilterParameters : register(b1) { uint filterStep; };
45
46
static const float PI=3.14159265359;
@@ -177,10 +178,10 @@ float3 LocalLighting(Hit h,float3 view,inout uint rng) {
177
178
}
178
179
return selectedWeight>0?selected*(sum/selectedWeight)*Visibility(h.p+h.n*.04,selectedDirection,max(.004,selectedDistance-.06)):0;
179
180
}
180
float4 PathRadiance(float3 origin,float3 direction,float range,inout uint rng) {
181
float4 PathRadiance(float3 origin,float3 direction,float range,inout uint rng,uint depthLimit=0) {
181
182
float3 radiance=0,throughput=1;float found=0;uint bounce=0;
182
uint maxBounces=(uint)clamp(transport.x,1,4);
183
[loop] for(uint step=0;step<16;step++) {
183
uint maxBounces=depthLimit>0?depthLimit:(uint)clamp(transport.x,1,8);
184
[loop] for(uint step=0;step<32;step++) {
184
185
Hit h;if(!Closest(origin,direction,range,h)) break;
185
186
if(h.flags&GLASS) {
186
187
GlassMaterial g=glassMaterials[h.glass];
@@ -200,7 +201,7 @@ float4 PathRadiance(float3 origin,float3 direction,float range,inout uint rng) {
200
201
found=1;
201
202
float3 l=normalize(sunDirection.xyz);float cosine=saturate(dot(h.n,l));
202
203
float3 lit=cosine>0?Visibility(h.p+h.n*.04,l,192):0;
203
radiance+=throughput*(h.emission+Bsdf(h,-direction,l)*sunColor.rgb*cosine*lit+LocalLighting(h,-direction,rng)+h.albedo*.018);
204
radiance+=throughput*(h.emission+Bsdf(h,-direction,l)*sunColor.rgb*cosine*lit+LocalLighting(h,-direction,rng)+(pathSettings.x>0?0:h.albedo*.018));
204
205
if(++bounce>=maxBounces) break;
205
206
float3 weight;direction=SampleBsdf(h,-direction,rng,weight);throughput*=weight;
206
207
if(max(throughput.x,max(throughput.y,throughput.z))<.001) break;
@@ -212,6 +213,50 @@ float4 PathRadiance(float3 origin,float3 direction,float range,inout uint rng) {
212
213
}
213
214
return float4(min(radiance,32),found);
214
215
}
216
// Replace near-field opaque lighting with a complete BSDF path estimate, rather
217
// than adding a GI/reflection overlay to already lit raster pixels. Raster depth
218
// validates coverage; missing/deformed/distant geometry keeps native lighting.
219
void TraceSurfacePaths(uint2 pixel,float4 p,inout uint rng) {
220
result[pixel]=0;
221
if(p.w<=0)return;
222
float3 viewRay=normalize(p.xyz-originDelta.xyz),origin=originDelta.xyz;
223
Hit primary;bool found=false;
224
[loop] for(uint layer=0;layer<12;layer++) {
225
if(!Closest(origin,viewRay,256,primary))break;
226
if(!(primary.flags&GLASS)){found=true;break;}
227
origin=primary.p+viewRay*.012;
228
}
229
if(!found || length(primary.p-p.xyz)>((primary.flags&VOXEL)?max(effects.z,.25):.25))return;
230
primary.n=normalize(normals[pixel].xyz);
231
if(dot(primary.n,viewRay)>0)primary.n=-primary.n;
232
primary.rough=max(.04,pow(1-normals[pixel].w,2));
233
float3 radiance=0;uint samples=(uint)clamp(pathSettings.y,1,8);
234
[loop] for(uint sample=0;sample<samples;sample++) {
235
float3 sun=normalize(sunDirection.xyz);float cosine=saturate(dot(primary.n,sun));
236
float3 direct=primary.emission+LocalLighting(primary,-viewRay,rng);
237
if(cosine>0) direct+=Bsdf(primary,-viewRay,sun)*sunColor.rgb*cosine*Visibility(primary.p+primary.n*.04,sun,192);
238
if(transport.x>1) {
239
float3 weight;float3 outgoing=SampleBsdf(primary,-viewRay,rng,weight);
240
direct+=weight*PathRadiance(primary.p+primary.n*.04,outgoing,max(transport.y,12),rng,(uint)clamp(transport.x-1,1,7)).rgb;
241
}
242
radiance+=min(direct,32)/samples;
243
}
244
float count=1,luma=Luma(radiance);float2 stats=float2(luma,luma*luma);
245
if(history.x>0) {
246
float4 clip=mul(float4(p.xyz-previousCamera.xyz,1),previousViewProjection);
247
float2 uv=float2(clip.x/clip.w*.5+.5,.5-clip.y/clip.w*.5);
248
if(clip.w>0 && all(uv>=0) && all(uv<1)) {
249
uint2 q=min(uint2(uv*sizes.zw),sizes.zw-1);
250
if(previousReflections[q].a>.5 && previousPositions[q].w>0 && length(previousPositions[q].xyz-(p.xyz+originChange.xyz))<.12 && dot(normals[pixel].xyz,previousNormals[q].xyz)>.98 && abs(normals[pixel].w-previousNormals[q].w)<.05) {
251
count=min(previousIndirect[q].a+1,64);
252
radiance=lerp(radiance,previousIndirect[q].rgb,1-1/count);
253
stats=lerp(stats,previousMoments[q].xy,1-1/count);
254
}
255
}
256
}
257
result[pixel]=float4(1,1,(primary.flags&VOXEL)?1:0,1);
258
reflected[pixel]=float4(0,0,0,1);indirect[pixel]=float4(radiance,count);moments[pixel]=float4(stats,0,0);
259
}
215
260
[numthreads(8,8,1)]
216
261
void Trace(uint3 id:SV_DispatchThreadID) {
217
262
if(any(id.xy>=sizes.zw)) return;
@@ -222,7 +267,8 @@ void Trace(uint3 id:SV_DispatchThreadID) {
222
267
// Transparent surfaces have no opaque G-buffer entry. Trace camera rays
223
268
// independently, including windows backed by sky or distant terrain.
224
269
if(transport.z>0 || settings.w==6 || effects.z>0) {
225
float2 uv=(float2(id.xy*2+1)+.5)/sizes.xy;
270
uint2 nativePixel=min(uint2((float2(id.xy)+.5)*float2(sizes.xy)/sizes.zw),sizes.xy-1);
271
float2 uv=(float2(nativePixel)+.5)/sizes.xy;
226
272
float4 nearPoint=mul(float4(uv.x*2-1,1-uv.y*2,1,1),inverseViewProjection);
227
273
float3 viewRay=p.w>0?normalize(p.xyz-originDelta.xyz):normalize(nearPoint.xyz/nearPoint.w);
228
274
// Raster voxels and the independently meshed RT surface need not have
@@ -283,6 +329,7 @@ void Trace(uint3 id:SV_DispatchThreadID) {
283
329
}
284
330
} else result[id.xy].z=0;
285
331
}
332
if(pathSettings.x>0) {TraceSurfacePaths(id.xy,p,rng);return;}
286
333
if(p.w==0) return;
287
334
float3 n=surfaceNormal,t,b;Basis(n,t,b);
288
335
uint stable=id.x*1973+id.y*9277+89173;float ao=0;
@@ -325,7 +372,7 @@ void Denoise(uint3 id:SV_DispatchThreadID) {
325
372
if(any(id.xy>=sizes.zw)) return;
326
373
float4 center=indirect[id.xy],p=positions[id.xy];
327
374
float4 spec=reflected[id.xy];
328
if(p.w==0) {filtered[id.xy]=center;filteredReflection[id.xy]=spec;return;}
375
if(p.w==0 || (pathSettings.x>0 && result[id.xy].w==0)) {filtered[id.xy]=center;filteredReflection[id.xy]=spec;return;}
329
376
float3 n=normals[id.xy].xyz;float3 sum=0;float total=0;float4 specSum=0;float specTotal=0;
330
377
float4 m=moments[id.xy];
331
378
float2 variance=max(float2(m.y-m.x*m.x,m.w-m.z*m.z),0);
@@ -344,6 +391,7 @@ void Denoise(uint3 id:SV_DispatchThreadID) {
344
391
[unroll] for(int y=-1;y<=1;y++) [unroll] for(int x=-1;x<=1;x++) {
345
392
int2 q=clamp(int2(id.xy)+int2(x,y)*(int)filterStep,0,int2(sizes.zw)-1);
346
393
float4 other=positions[q],value=indirect[q];
394
if(pathSettings.x>0 && result[q].w==0)continue;
347
395
float distance=abs(dot(other.xyz-p.xyz,n));
348
396
float geometry=other.w*exp(-distance*20)*pow(saturate(dot(n,normals[q].xyz)),32);
349
397
float kernel=(x==0?2:1)*(y==0?2:1);