Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

phase-1 work: P1.5 frame loop 5/5 evaluates, non-black output, valid PNG captures

Veyra Goal Agent62a4ff1d076f
diff --git a/CMakeLists.txt b/CMakeLists.txt
index acc36e34..2130eebd 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -20,6 +20,7 @@ option(VEYRA_ENABLE_D3D12_DEBUG "Enable D3D12 debug layer" ON)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(VeyraWarnings)
+include(VeyraShaders)
# NVIDIA's static NGX core shim (nvsdk_ngx_s*.lib) is built against the
# static CRT (MT/MTd); match it for the diagnostic tools that link it.
@@ -87,12 +88,16 @@ target_compile_definitions(veyra_runtime_probe PRIVATE
target_link_libraries(veyra_runtime_probe PRIVATE veyra_gfx)
if(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR)
+ veyra_add_compute_shader(veyra_shader_test_pattern GenerateTestPattern)
add_executable(veyra_nr_harness
tools/nr_harness/main.cpp
+ tools/nr_harness/frame_loop.cpp
)
veyra_apply_warnings(veyra_nr_harness)
target_compile_features(veyra_nr_harness PRIVATE cxx_std_20)
target_compile_definitions(veyra_nr_harness PRIVATE
- UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX
+ VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_link_libraries(veyra_nr_harness PRIVATE veyra_gfx veyra_ngx)
+ add_dependencies(veyra_nr_harness veyra_shader_test_pattern)
endif()
diff --git a/cmake/VeyraShaders.cmake b/cmake/VeyraShaders.cmake
new file mode 100644
index 00000000..2a08dc47
--- /dev/null
+++ b/cmake/VeyraShaders.cmake
@@ -0,0 +1,42 @@
+# Build-time HLSL compilation via the installed DXC (Playbook section 5.4).
+# Machine-specific DXC discovery stays here; CMakePresets stay path-free.
+
+function(veyra_find_dxc out_var)
+ set(candidates "")
+ file(GLOB kit_roots "$ENV{ProgramFiles\(x86\)}/Windows Kits/10/bin/*")
+ if(kit_roots)
+ list(SORT kit_roots ORDER DESCENDING)
+ foreach(root IN LISTS kit_roots)
+ if(EXISTS "${root}/x64/dxc.exe")
+ list(APPEND candidates "${root}/x64/dxc.exe")
+ endif()
+ endforeach()
+ endif()
+ if(NOT candidates)
+ message(FATAL_ERROR "veyra_find_dxc: dxc.exe not found under the Windows Kits")
+ endif()
+ list(GET candidates 0 chosen)
+ set(${out_var} "${chosen}" PARENT_SCOPE)
+endfunction()
+
+# Compiles one compute shader into <binary-dir>/shaders/<name>.dxil.
+# Single-config Ninja: branch on CMAKE_BUILD_TYPE instead of generator
+# expressions, whose empty expansion would quote-separate dxc arguments.
+function(veyra_add_compute_shader target_name shader_name)
+ veyra_find_dxc(DXC_EXE)
+ set(source "${CMAKE_CURRENT_SOURCE_DIR}/shaders/${shader_name}.hlsl")
+ set(output "${CMAKE_CURRENT_BINARY_DIR}/shaders/${shader_name}.dxil")
+ set(config_flags -O3 -Qstrip_debug -Qstrip_reflect)
+ if(CMAKE_BUILD_TYPE STREQUAL "Debug")
+ set(config_flags -Od -Zi -Qembed_debug)
+ endif()
+ add_custom_command(
+ OUTPUT "${output}"
+ COMMAND "${DXC_EXE}" -T cs_6_0 -E main ${config_flags}
+ -Fo "${output}" "${source}"
+ DEPENDS "${source}"
+ COMMENT "dxc ${shader_name}.hlsl (${CMAKE_BUILD_TYPE})"
+ VERBATIM)
+ add_custom_target(${target_name} DEPENDS "${output}")
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source}")
+endfunction()
diff --git a/include/veyra/FileIdentity.h b/include/veyra/FileIdentity.h
index a5030d1f..10799f09 100644
--- a/include/veyra/FileIdentity.h
+++ b/include/veyra/FileIdentity.h
@@ -33,4 +33,7 @@ const char* identityErrorString(IdentityError error);
// partial results remain in `out` for logging.
bool computeFileIdentity(const std::wstring& path, FileIdentity& out, IdentityError& error);
+// Uppercase hex SHA-256 over an in-memory buffer (diagnostics/statistics).
+std::string sha256Hex(const uint8_t* data, size_t size);
+
} // namespace veyra
diff --git a/loop/BACKLOG.md b/loop/BACKLOG.md
index 6fbe43a3..888f5c64 100644
--- a/loop/BACKLOG.md
+++ b/loop/BACKLOG.md
@@ -23,7 +23,7 @@ Phase 0 gate:以 Playbook 第 16 节 Phase 0 为准。未完成 P0.9 禁止开
- [x] P1.2 封装 NGX Core、parameter block、DLSSNR runtime 和严格逆序 RAII。(2026-09-02:Init_with_ProjectID result=0x1 真实成功;exports 5/5;逆序释放干净;harness --load-only 双配置 PASS。)
- [x] P1.3 实现受隔离、可关闭的 caller-name 兼容层;禁止 patch DLL。(2026-09-02:IAT 单 owner shim + 8 项边界测试全过;DLL 文件从未被修改。)
- [x] P1.4 严格按 Playbook 参数名与类型 Create Feature 18。(2026-09-02:CreateFeature id=18 result=0x1 handle=non-null,双配置 PASS;8.5 参数全表按名按类型设置。)
-- [ ] P1.5 实现 Proxy→Feature18→Raw 的 D3D12 资源、barrier、subrect 与异步 4-slot 执行。
+- [x] P1.5 实现 Proxy→Feature18→Raw 的 D3D12 资源、barrier、subrect 与异步 4-slot 执行。(2026-09-02:5 帧全过,输出非黑非恒定,PNG 捕获有效;零初始化用 upload-copy 实现。)
- [ ] P1.6 连续 300/300 Evaluate;验证输出非黑、非恒定、随输入/参数变化;记录 GPU timings/result/capture。
- [ ] P1.7 重建/reset/释放测试。
- [ ] P1.8 gate、只读 Reviewer、P0/P1 修复、checkpoint。
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index 8f492da0..faba485e 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -400,6 +400,33 @@ Result:
---
+## Cycle 015 — P1.5 Proxy→Feature18→Raw 执行链
+
+### Before
+
+- Phase: 1
+- 唯一任务: 实现 shaders/GenerateTestPattern.hlsl(确定性 gradient/checker/硬边/RGB bars,随 frameId 平移;cs_6_0,DXC 构建期编译进 out/);Phase 1 资源(Proxy/Neural RGBA8 UAV、ZeroMotion R16G16F、ZeroDepth R32F、Confidence R8,均 1920x1080);zero 纹理一次性 UAV clear;compute root signature + descriptor heap;8.6 全部 Evaluate 参数(4 资源 + 16 subrect + 控制项,首帧 Reset=1);4-slot 逐帧:acquire→pattern dispatch→barriers→Evaluate→UAV barrier→submit;harness 主模式接 --frames N(先小 N 验证)。
+- 可证伪假设: 若资源格式/state/subrect/参数类型错误,Evaluate 返回非 0x1(0xBAD00005 等)或 debug 输出 state error——按 Playbook 18 表排查。
+- 预计修改文件: shaders/GenerateTestPattern.hlsl、cmake/VeyraShaders.cmake、CMakeLists.txt、tools/nr_harness/main.cpp(主循环 + PNG writer + stats)。
+- 快速检查命令: `build.ps1` → 0(含 DXC 编译);`veyra_nr_harness.exe --runtime-dir <abs> --frames 5` → evaluate 成功 5/5。
+- 预期新增证据: 每帧 Evaluate result hex、GPU timestamp、帧数计数。
+
+### After
+
+- 实际修改: shaders/GenerateTestPattern.hlsl(四象限确定性图案,root constant frameId)、cmake/VeyraShaders.cmake(DXC 查找+构建期编译)、tools/nr_harness/frame_loop.{h,cpp}(完整主循环:资源/UAV heap/root signature/PSO/零初始化/逐帧 Evaluate/捕获/统计/最小 PNG writer)、main.cpp 接线、FileIdentity 增加内存 sha256Hex。
+- 实际命令与 exit code:
+ - `build.ps1 -Preset x64-debug` → 修复 3 轮(DXC genex 引号问题→按 CMAKE_BUILD_TYPE 分支;D3D12_TEXTURE_COPY_LOCATION union 不能聚合多初始化器;**ClearUnorderedAccessViewFloat 段错误**→对照实验证实与纹理格式无关后改为 upload-buffer 复制零初始化)后 exit 0。
+ - `veyra_nr_harness.exe --runtime-dir <abs> --frames 5 --capture-frame 0 --capture-dir captures/tmp` → **REAL_EXIT=0,frame-loop: PASS**。
+- 新证据/日志路径: logs/tmp/p15e.out、captures/tmp/frame0000_{proxy,raw}.png(8.3MB/张,System.Drawing 验证 1920x1080)。关键数字——**Evaluate 5/5 成功 0 失败**;输出 meanLuma=0.52437、minLuma=0.05043、maxLuma=1.0、stddev=0.34352、allZero=false、constant=false、rawSha=4C3248C8…(≠proxySha=46522DAB…,证明 Feature 18 真实处理);teardown release/snippetShutdown 双 0x1;deviceRemoved=false。
+- 失败 fingerprint: phase1|frame-loop zero-init|139|ClearUnorderedAccessViewFloat crash → 换实现路径修复(upload copy),fingerprint 关闭。
+- 本 fingerprint 第几次不同尝试: 2 次(SetDescriptorHeaps 补绑后仍崩 → 换路径成功)。
+- 是否有进展,依据: 是——Playbook 8.7 完整帧链(pattern→barriers→全部 8.6 参数→Evaluate→UAV barrier→4-slot 提交→捕获统计)真实运行成功。
+- 已知偏差记录: ClearUnorderedAccessViewFloat 在本机(无 debug layer)段错误原因未定(机制问题非格式问题),已用等效 upload-copy 路径替代;待用户装 Graphics Tools 后可复查(记入 INBOX 附注候选)。
+- STATE/BACKLOG 更新: cycle.completed=15;BACKLOG P1.5 → DONE。
+- 下一唯一动作: P1.6 300/300 连续 Evaluate + 两组 Style/Intensity 变体 hash + GPU timestamp + JSON 输出,对齐 phase1 gate 契约。
+
+---
+
复制下面模板开始每个新 cycle。必须先填 Before,再改代码;完成后填 After。
## Cycle NNN — 简短任务名
diff --git a/loop/STATE.json b/loop/STATE.json
index b0d66fe0..1c729a28 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -76,14 +76,14 @@
}
],
"cycle": {
- "completed": 14,
+ "completed": 15,
"maximum": 80,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "P1.5: implement Phase 1 GPU resources (Proxy/Neural RGBA8, ZeroMotion R16G16F, ZeroDepth R32F, Confidence R8), GenerateTestPattern.hlsl compiled at build time via DXC, the 8.6 Evaluate parameter set, and the per-frame Proxy->Feature18->Raw execution on the 4-slot ring.",
+ "currentTask": "P1.6: run the full 300/300 Evaluate matrix with two Style/Intensity variants (distinct output hashes), GPU timestamps, and the JSON summary matching the phase1 gate contract.",
"lastGate": {
"name": "phase0",
"status": "passed",
@@ -96,6 +96,6 @@
"lastGoodCommit": "1fb7afa5779a6c6a0a585d4ecf18a640260a2fcf",
"openP0P1Findings": [],
"blockers": [],
- "nextAction": "Implement P1.5 resources + test pattern shader + Evaluate loop, then P1.6 300-frame run with output statistics.",
- "updatedAt": "2026-09-02T22:40:00+08:00"
+ "nextAction": "Extend frame loop with variants + JSON + timestamps (P1.6), then P1.7 resets, then the phase1 gate (blocked on Graphics Tools for the debug-layer criterion).",
+ "updatedAt": "2026-09-02T23:05:00+08:00"
}
diff --git a/shaders/GenerateTestPattern.hlsl b/shaders/GenerateTestPattern.hlsl
new file mode 100644
index 00000000..8b993a54
--- /dev/null
+++ b/shaders/GenerateTestPattern.hlsl
@@ -0,0 +1,64 @@
+// Deterministic Phase 1 test pattern (Playbook section 16 Phase 1).
+// Pure function of pixel coordinates and frameId: quadrant layout with an
+// animated horizontal gradient, an 8-pixel checker, a hard diagonal edge and
+// vertical RGB bars. For a fixed frameId the output is fully deterministic.
+
+cbuffer FrameParams : register(b0)
+{
+ uint frameId;
+ uint patternWidth;
+ uint patternHeight;
+ uint padding0;
+};
+
+RWTexture2D<unorm float4> outputTexture : register(u0);
+
+[numthreads(16, 16, 1)]
+void main(uint3 dispatchThreadId : SV_DispatchThreadID)
+{
+ if (dispatchThreadId.x >= patternWidth || dispatchThreadId.y >= patternHeight) {
+ return;
+ }
+
+ const uint x = dispatchThreadId.x;
+ const uint y = dispatchThreadId.y;
+ const float2 uv = float2(x / float(patternWidth), y / float(patternHeight));
+ // Gradient phase shifts 1/8 of the width per frame; wraps every 8 frames.
+ const float shift = frac(frameId * 0.125);
+
+ float4 color = float4(0.0, 0.0, 0.0, 1.0);
+
+ const bool rightHalf = x >= (patternWidth / 2);
+ const bool bottomHalf = y >= (patternHeight / 2);
+
+ if (!rightHalf && !bottomHalf) {
+ // Top-left: animated gradient.
+ color.rgb = frac(uv.x + shift);
+ }
+ else if (rightHalf && !bottomHalf) {
+ // Top-right: 8-pixel checker.
+ const float checker = (((x / 8) + (y / 8)) & 1) != 0 ? 0.85 : 0.15;
+ color.rgb = checker;
+ }
+ else if (!rightHalf && bottomHalf) {
+ // Bottom-left: hard diagonal edge.
+ const float edge = (uv.x + uv.y) >= 1.0 ? 0.9 : 0.05;
+ color.rgb = edge;
+ }
+ else {
+ // Bottom-right: vertical RGB bars.
+ const uint third = patternWidth / 3;
+ const uint column = x % third;
+ if (column < (third / 3)) {
+ color.r = 1.0;
+ }
+ else if (column < (2 * (third / 3))) {
+ color.g = 1.0;
+ }
+ else {
+ color.b = 1.0;
+ }
+ }
+
+ outputTexture[dispatchThreadId.xy] = color;
+}
diff --git a/src/base/FileIdentity.cpp b/src/base/FileIdentity.cpp
index b17e7bd2..cbf38848 100644
--- a/src/base/FileIdentity.cpp
+++ b/src/base/FileIdentity.cpp
@@ -264,4 +264,29 @@ bool computeFileIdentity(const std::wstring& path, FileIdentity& out, IdentityEr
return true;
}
+std::string sha256Hex(const uint8_t* data, size_t size)
+{
+ BCRYPT_ALG_HANDLE algorithm = nullptr;
+ NTSTATUS status = BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ return {};
+ }
+ BCRYPT_HASH_HANDLE hash = nullptr;
+ status = BCryptCreateHash(algorithm, &hash, nullptr, 0, nullptr, 0, 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(algorithm, 0);
+ return {};
+ }
+ std::string hex;
+ if (BCRYPT_SUCCESS(BCryptHashData(hash, const_cast<unsigned char*>(data), static_cast<ULONG>(size), 0))) {
+ std::array<unsigned char, 32> digest{};
+ if (BCRYPT_SUCCESS(BCryptFinishHash(hash, digest.data(), static_cast<ULONG>(digest.size()), 0))) {
+ hex = bytesToHexUpper(digest);
+ }
+ }
+ BCryptDestroyHash(hash);
+ BCryptCloseAlgorithmProvider(algorithm, 0);
+ return hex;
+}
+
} // namespace veyra
diff --git a/tools/nr_harness/frame_loop.cpp b/tools/nr_harness/frame_loop.cpp
new file mode 100644
index 00000000..76115535
--- /dev/null
+++ b/tools/nr_harness/frame_loop.cpp
@@ -0,0 +1,805 @@
+#include "frame_loop.h"
+
+#include <windows.h>
+#include <d3d12.h>
+#include <dxgi1_6.h>
+#include <nvsdk_ngx.h>
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <format>
+#include <fstream>
+#include <vector>
+
+#include "veyra/FileIdentity.h"
+#include "veyra/Log.h"
+#include "veyra/NgxResult.h"
+#include "veyra/Result.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/ngx/DlssNrParameters.h"
+#include "veyra/ngx/DlssNrRuntimeAdapter.h"
+#include "veyra/ngx/NgxCoreHost.h"
+#include "veyra/ngx/NgxParameters.h"
+
+namespace veyra::harness {
+
+namespace {
+
+std::string narrowText(const std::wstring& text)
+{
+ if (text.empty()) {
+ return {};
+ }
+ const int length = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
+ if (length <= 0) {
+ return {};
+ }
+ std::string converted(static_cast<size_t>(length), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), converted.data(), length, nullptr, nullptr);
+ return converted;
+}
+
+std::string scanJsonStringField(const std::string& text, const char* key)
+{
+ const std::string needle = std::string("\"") + key + "\"";
+ size_t position = text.find(needle);
+ if (position == std::string::npos) {
+ return {};
+ }
+ position = text.find(':', position + needle.size());
+ if (position == std::string::npos) {
+ return {};
+ }
+ position = text.find('"', position);
+ if (position == std::string::npos) {
+ return {};
+ }
+ const size_t start = position + 1;
+ const size_t end = text.find('"', start);
+ if (end == std::string::npos) {
+ return {};
+ }
+ return text.substr(start, end - start);
+}
+
+struct LocalIdentity {
+ std::string projectId;
+ std::string engineVersion;
+};
+
+bool loadLocalIdentity(const std::wstring& runtimeDir, LocalIdentity& identity)
+{
+ const std::wstring configPath = runtimeDir + L"\\..\\config\\ngx-local.json";
+ std::ifstream stream(configPath, std::ios::binary);
+ if (!stream.is_open()) {
+ return false;
+ }
+ std::string text((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
+ identity.projectId = scanJsonStringField(text, "ngxProjectId");
+ identity.engineVersion = scanJsonStringField(text, "engineVersion");
+ return !identity.projectId.empty() && !identity.engineVersion.empty();
+}
+
+// ---------------------------------------------------------------------------
+// Minimal PNG writer (uncompressed deflate stored blocks): a real PNG any
+// viewer opens, without linking a compression library (harness-only).
+// ---------------------------------------------------------------------------
+uint32_t crc32Of(const uint8_t* data, size_t size)
+{
+ static uint32_t table[256];
+ static bool initialized = false;
+ if (!initialized) {
+ for (uint32_t n = 0; n < 256; ++n) {
+ uint32_t c = n;
+ for (int k = 0; k < 8; ++k) {
+ c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
+ }
+ table[n] = c;
+ }
+ initialized = true;
+ }
+ uint32_t crc = 0xFFFFFFFFu;
+ for (size_t i = 0; i < size; ++i) {
+ crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
+ }
+ return crc ^ 0xFFFFFFFFu;
+}
+
+uint32_t adler32Of(const uint8_t* data, size_t size)
+{
+ uint32_t a = 1;
+ uint32_t b = 0;
+ for (size_t i = 0; i < size; ++i) {
+ a = (a + data[i]) % 65521u;
+ b = (b + a) % 65521u;
+ }
+ return (b << 16) | a;
+}
+
+bool writeRgbaPng(const std::wstring& path, const uint8_t* pixels, uint32_t width, uint32_t height, size_t sourceRowPitch)
+{
+ const size_t rowBytes = static_cast<size_t>(width) * 4;
+ std::vector<uint8_t> raw((rowBytes + 1) * height);
+ for (uint32_t y = 0; y < height; ++y) {
+ raw[y * (rowBytes + 1)] = 0; // filter: none
+ memcpy(raw.data() + y * (rowBytes + 1) + 1, pixels + y * sourceRowPitch, rowBytes);
+ }
+
+ std::vector<uint8_t> zlibStream;
+ zlibStream.push_back(0x78);
+ zlibStream.push_back(0x01);
+ size_t offset = 0;
+ while (offset < raw.size()) {
+ const size_t chunk = std::min<size_t>(raw.size() - offset, 65535);
+ const bool finalBlock = offset + chunk >= raw.size();
+ zlibStream.push_back(finalBlock ? 1 : 0);
+ zlibStream.push_back(static_cast<uint8_t>(chunk & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>((chunk >> 8) & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>(~chunk & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>((~chunk >> 8) & 0xFF));
+ zlibStream.insert(zlibStream.end(), raw.begin() + static_cast<ptrdiff_t>(offset),
+ raw.begin() + static_cast<ptrdiff_t>(offset + chunk));
+ offset += chunk;
+ }
+ const uint32_t adler = adler32Of(raw.data(), raw.size());
+ zlibStream.push_back(static_cast<uint8_t>((adler >> 24) & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>((adler >> 16) & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>((adler >> 8) & 0xFF));
+ zlibStream.push_back(static_cast<uint8_t>(adler & 0xFF));
+
+ std::vector<uint8_t> png{ 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n' };
+ const auto appendChunk = [&png](const char type[5], const std::vector<uint8_t>& payload) {
+ const uint32_t length = static_cast<uint32_t>(payload.size());
+ png.push_back(static_cast<uint8_t>((length >> 24) & 0xFF));
+ png.push_back(static_cast<uint8_t>((length >> 16) & 0xFF));
+ png.push_back(static_cast<uint8_t>((length >> 8) & 0xFF));
+ png.push_back(static_cast<uint8_t>(length & 0xFF));
+ std::vector<uint8_t> body(type, type + 4);
+ body.insert(body.end(), payload.begin(), payload.end());
+ png.insert(png.end(), body.begin(), body.end());
+ const uint32_t crc = crc32Of(body.data(), body.size());
+ png.push_back(static_cast<uint8_t>((crc >> 24) & 0xFF));
+ png.push_back(static_cast<uint8_t>((crc >> 16) & 0xFF));
+ png.push_back(static_cast<uint8_t>((crc >> 8) & 0xFF));
+ png.push_back(static_cast<uint8_t>(crc & 0xFF));
+ };
+ std::vector<uint8_t> ihdr(13);
+ ihdr[0] = static_cast<uint8_t>((width >> 24) & 0xFF);
+ ihdr[1] = static_cast<uint8_t>((width >> 16) & 0xFF);
+ ihdr[2] = static_cast<uint8_t>((width >> 8) & 0xFF);
+ ihdr[3] = static_cast<uint8_t>(width & 0xFF);
+ ihdr[4] = static_cast<uint8_t>((height >> 24) & 0xFF);
+ ihdr[5] = static_cast<uint8_t>((height >> 16) & 0xFF);
+ ihdr[6] = static_cast<uint8_t>((height >> 8) & 0xFF);
+ ihdr[7] = static_cast<uint8_t>(height & 0xFF);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 6; // RGBA
+ appendChunk("IHDR", ihdr);
+ appendChunk("IDAT", zlibStream);
+ appendChunk("IEND", {});
+
+ HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
+ if (file == INVALID_HANDLE_VALUE) {
+ return false;
+ }
+ DWORD written = 0;
+ const BOOL ok = WriteFile(file, png.data(), static_cast<DWORD>(png.size()), &written, nullptr);
+ CloseHandle(file);
+ return ok != FALSE && written == png.size();
+}
+
+struct RgbaStats {
+ double meanLuma = 0.0;
+ double minLuma = 1.0;
+ double maxLuma = 0.0;
+ double stddev = 0.0;
+ bool allZero = true;
+ bool constant = true;
+ std::string sha256;
+};
+
+RgbaStats analyzeRgba(const uint8_t* pixels, uint32_t width, uint32_t height, size_t rowPitch)
+{
+ RgbaStats stats;
+ double sum = 0.0;
+ double sumSquares = 0.0;
+ uint64_t count = 0;
+ for (uint32_t y = 0; y < height; ++y) {
+ const uint8_t* row = pixels + y * rowPitch;
+ for (uint32_t x = 0; x < width; ++x) {
+ const double r = row[x * 4 + 0] / 255.0;
+ const double g = row[x * 4 + 1] / 255.0;
+ const double b = row[x * 4 + 2] / 255.0;
+ const double luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ sum += luma;
+ sumSquares += luma * luma;
+ stats.minLuma = std::min(stats.minLuma, luma);
+ stats.maxLuma = std::max(stats.maxLuma, luma);
+ if (row[x * 4] != 0 || row[x * 4 + 1] != 0 || row[x * 4 + 2] != 0) {
+ stats.allZero = false;
+ }
+ ++count;
+ }
+ }
+ const double mean = count > 0 ? sum / static_cast<double>(count) : 0.0;
+ const double variance = count > 0 ? std::max(0.0, sumSquares / static_cast<double>(count) - mean * mean) : 0.0;
+ stats.meanLuma = mean;
+ stats.stddev = std::sqrt(variance);
+ stats.constant = stats.maxLuma == stats.minLuma;
+ std::vector<uint8_t> packed(static_cast<size_t>(width) * height * 4);
+ for (uint32_t y = 0; y < height; ++y) {
+ memcpy(packed.data() + static_cast<size_t>(y) * width * 4, pixels + y * rowPitch, static_cast<size_t>(width) * 4);
+ }
+ stats.sha256 = sha256Hex(packed.data(), packed.size());
+ return stats;
+}
+
+} // namespace
+
+int runFrameLoop(const FrameLoopArgs& args)
+{
+ const uint32_t width = args.width;
+ const uint32_t height = args.height;
+ uint64_t evaluateAttempted = 0;
+ uint64_t evaluateSucceeded = 0;
+ uint64_t evaluateFailed = 0;
+ bool deviceRemoved = false;
+ uint32_t deviceRemovedReason = 0;
+ RgbaStats finalStats;
+
+#if defined(VEYRA_D3D12_DEBUG)
+ constexpr bool kDebugLayerByBuild = true;
+#else
+ constexpr bool kDebugLayerByBuild = false;
+#endif
+ gfx::D3D12DeviceContext context;
+ gfx::DeviceContextDesc contextDesc{};
+ contextDesc.enableDebugLayer = kDebugLayerByBuild;
+ contextDesc.commandSlotCount = 4;
+ Status status = Status::Ok;
+ if (!context.initialize(contextDesc, status)) {
+ return 6;
+ }
+ gfx::CommandSlotRing ring;
+ if (!ring.initialize(context.device(), context.directQueue(), context.fence(), context.fenceEvent(), 4, status)) {
+ context.shutdown();
+ return 7;
+ }
+
+ LocalIdentity identity{};
+ if (!loadLocalIdentity(args.runtimeDir, identity)) {
+ ring.shutdown();
+ context.shutdown();
+ return 7;
+ }
+ ngx::NgxCoreHost coreHost;
+ if (!coreHost.initialize(context.device(), args.runtimeDir, identity.projectId.c_str(), identity.engineVersion.c_str(), status)) {
+ ring.shutdown();
+ context.shutdown();
+ return 8;
+ }
+ ngx::DlssNrRuntimeAdapter adapter;
+ if (!adapter.load(args.runtimeDir, status) || !adapter.installCallerCompatibility(status)) {
+ adapter.unload();
+ coreHost.shutdown();
+ ring.shutdown();
+ context.shutdown();
+ return 9;
+ }
+ uint64_t result = 0;
+ uint32_t sehCode = 0;
+ if (!adapter.snippetInitExt(context.device(), args.runtimeDir, result, sehCode) ||
+ result != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
+ adapter.restoreCallerCompatibility();
+ adapter.unload();
+ coreHost.shutdown();
+ ring.shutdown();
+ context.shutdown();
+ return 10;
+ }
+
+ NVSDK_NGX_Parameter* params = coreHost.allocateParameters(status);
+ NVSDK_NGX_Handle* handle = nullptr;
+ if (params == nullptr) {
+ goto teardown_fail;
+ }
+ {
+ namespace p = ngx::dlssnr;
+ ngx::ParameterBlock pb(params);
+ pb.setU32(p::kWidth, width);
+ pb.setU32(p::kHeight, height);
+ pb.setU32(p::kInputWidth, width);
+ pb.setU32(p::kInputHeight, height);
+ pb.setU32(p::kOutputWidth, width);
+ pb.setU32(p::kOutputHeight, height);
+ pb.setU32(p::kOutputDotWidth, width);
+ pb.setU32(p::kOutputDotHeight, height);
+ pb.setU32(p::kUpscaling, 0);
+ pb.setF32(p::kScale, 1.0f);
+ pb.setF32(p::kScalingRatio, 1.0f);
+ pb.setVoid(p::kComputeScalingRatioCallback,
+ reinterpret_cast<void*>(&ngx::DlssNrRuntimeAdapter::scalingRatioCallback));
+ pb.setI32(p::kHintRenderPreset, 0);
+ pb.setU32(p::kStdWidth, width);
+ pb.setU32(p::kStdHeight, height);
+ pb.setI32(p::kPerfQualityValue, 1);
+ pb.setU32(p::kCreationNodeMask, 1);
+ pb.setU32(p::kVisibilityNodeMask, 1);
+
+ ID3D12GraphicsCommandList* list = ring.acquire(0, status);
+ if (list == nullptr) {
+ goto teardown_fail;
+ }
+ if (!adapter.snippetCreateFeature(list, params, &handle, result, sehCode) ||
+ result != static_cast<uint64_t>(NVSDK_NGX_Result_Success) || handle == nullptr) {
+ goto teardown_fail;
+ }
+ if (!ring.submitAndSignal(0) || !ring.waitIdle()) {
+ goto teardown_fail;
+ }
+ }
+
+ {
+ const auto makeTexture = [&](DXGI_FORMAT format, const wchar_t* name) -> gfx::ComPtr<ID3D12Resource> {
+ D3D12_HEAP_PROPERTIES heapProps{};
+ heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC desc{};
+ desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ desc.Width = width;
+ desc.Height = height;
+ desc.DepthOrArraySize = 1;
+ desc.MipLevels = 1;
+ desc.Format = format;
+ desc.SampleDesc.Count = 1;
+ desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ gfx::ComPtr<ID3D12Resource> resource;
+ const HRESULT hr = context.device()->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE,
+ &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&resource));
+ if (FAILED(hr)) {
+ log::error("harness", std::format("frame-loop: create {} failed hr={}",
+ narrowText(name), hresultString(hr)));
+ return nullptr;
+ }
+ return resource;
+ };
+
+ auto proxy = makeTexture(DXGI_FORMAT_R8G8B8A8_UNORM, L"Proxy");
+ auto neural = makeTexture(DXGI_FORMAT_R8G8B8A8_UNORM, L"Neural");
+ auto motion = makeTexture(DXGI_FORMAT_R16G16_FLOAT, L"ZeroMotion");
+ auto depth = makeTexture(DXGI_FORMAT_R32_FLOAT, L"ZeroDepth");
+ auto confidence = makeTexture(DXGI_FORMAT_R8_UNORM, L"Confidence");
+ if (proxy == nullptr || neural == nullptr || motion == nullptr || depth == nullptr || confidence == nullptr) {
+ goto teardown_fail;
+ }
+
+ D3D12_DESCRIPTOR_HEAP_DESC uavHeapDesc{};
+ uavHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ uavHeapDesc.NumDescriptors = 8;
+ uavHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ gfx::ComPtr<ID3D12DescriptorHeap> uavHeap;
+ if (FAILED(context.device()->CreateDescriptorHeap(&uavHeapDesc, IID_PPV_ARGS(&uavHeap)))) {
+ goto teardown_fail;
+ }
+ const UINT handleSize = context.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ D3D12_CPU_DESCRIPTOR_HANDLE cpuBase = uavHeap->GetCPUDescriptorHandleForHeapStart();
+ D3D12_GPU_DESCRIPTOR_HANDLE gpuBase = uavHeap->GetGPUDescriptorHandleForHeapStart();
+
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc{};
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
+ uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ context.device()->CreateUnorderedAccessView(proxy.Get(), nullptr, &uavDesc, cpuBase);
+ context.device()->CreateUnorderedAccessView(neural.Get(), nullptr, &uavDesc, { cpuBase.ptr + handleSize });
+ uavDesc.Format = DXGI_FORMAT_R16G16_FLOAT;
+ context.device()->CreateUnorderedAccessView(motion.Get(), nullptr, &uavDesc, { cpuBase.ptr + 2ull * handleSize });
+ uavDesc.Format = DXGI_FORMAT_R32_FLOAT;
+ context.device()->CreateUnorderedAccessView(depth.Get(), nullptr, &uavDesc, { cpuBase.ptr + 3ull * handleSize });
+ uavDesc.Format = DXGI_FORMAT_R8_UNORM;
+ context.device()->CreateUnorderedAccessView(confidence.Get(), nullptr, &uavDesc, { cpuBase.ptr + 4ull * handleSize });
+
+ D3D12_DESCRIPTOR_RANGE1 uavRange{};
+ uavRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
+ uavRange.NumDescriptors = 1;
+ uavRange.BaseShaderRegister = 0;
+ uavRange.RegisterSpace = 0;
+ uavRange.OffsetInDescriptorsFromTableStart = 0;
+ D3D12_ROOT_PARAMETER1 rootParameters[2]{};
+ rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
+ rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameters[0].Constants.ShaderRegister = 0;
+ rootParameters[0].Constants.RegisterSpace = 0;
+ rootParameters[0].Constants.Num32BitValues = 4;
+ rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameters[1].DescriptorTable.NumDescriptorRanges = 1;
+ rootParameters[1].DescriptorTable.pDescriptorRanges = &uavRange;
+ D3D12_VERSIONED_ROOT_SIGNATURE_DESC rootDesc{};
+ rootDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
+ rootDesc.Desc_1_1.NumParameters = 2;
+ rootDesc.Desc_1_1.pParameters = rootParameters;
+ rootDesc.Desc_1_1.NumStaticSamplers = 0;
+ rootDesc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
+ gfx::ComPtr<ID3DBlob> signatureBlob;
+ gfx::ComPtr<ID3DBlob> errorBlob;
+ if (FAILED(D3D12SerializeVersionedRootSignature(&rootDesc, &signatureBlob, &errorBlob))) {
+ log::error("harness", std::format("frame-loop: root signature serialize failed: {}",
+ errorBlob != nullptr ? std::string(static_cast<const char*>(errorBlob->GetBufferPointer())) : std::string("?")));
+ goto teardown_fail;
+ }
+ gfx::ComPtr<ID3D12RootSignature> rootSignature;
+ if (FAILED(context.device()->CreateRootSignature(0, signatureBlob->GetBufferPointer(),
+ signatureBlob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ goto teardown_fail;
+ }
+
+ const std::string shaderPath8 = VEYRA_SHADER_DIR "/GenerateTestPattern.dxil";
+ HANDLE shaderFile = CreateFileA(shaderPath8.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
+ if (shaderFile == INVALID_HANDLE_VALUE) {
+ log::error("harness", std::format("frame-loop: shader missing path={}", shaderPath8));
+ goto teardown_fail;
+ }
+ LARGE_INTEGER shaderSize{};
+ GetFileSizeEx(shaderFile, &shaderSize);
+ std::vector<uint8_t> shaderBytes(static_cast<size_t>(shaderSize.QuadPart));
+ DWORD shaderRead = 0;
+ ReadFile(shaderFile, shaderBytes.data(), static_cast<DWORD>(shaderBytes.size()), &shaderRead, nullptr);
+ CloseHandle(shaderFile);
+ if (shaderBytes.empty()) {
+ goto teardown_fail;
+ }
+
+ D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc{};
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.CS.pShaderBytecode = shaderBytes.data();
+ psoDesc.CS.BytecodeLength = shaderBytes.size();
+ gfx::ComPtr<ID3D12PipelineState> pipelineState;
+ if (FAILED(context.device()->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ log::error("harness", "frame-loop: compute pipeline state creation failed");
+ goto teardown_fail;
+ }
+ log::info("harness", "frame-loop: test-pattern compute pipeline created");
+
+ // One-time zero-init of the guidance textures via an upload buffer
+ // copy (deterministic and validation-friendly; Playbook 6.4 zero
+ // contract). Neural moves COMMON->UAV for Evaluate.
+ {
+ const auto zeroInitTexture = [&](ID3D12Resource* texture, DXGI_FORMAT format, uint32_t bytesPerPixel) -> bool {
+ const size_t uploadRow = (static_cast<size_t>(width) * bytesPerPixel + 255) & ~size_t(255);
+ const size_t uploadSize = uploadRow * height;
+ static gfx::ComPtr<ID3D12Resource> upload; // reused across the three textures
+ if (upload == nullptr) {
+ D3D12_HEAP_PROPERTIES uploadProps{};
+ uploadProps.Type = D3D12_HEAP_TYPE_UPLOAD;
+ D3D12_RESOURCE_DESC uploadDesc{};
+ uploadDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ uploadDesc.Width = uploadSize;
+ uploadDesc.Height = 1;
+ uploadDesc.DepthOrArraySize = 1;
+ uploadDesc.MipLevels = 1;
+ uploadDesc.SampleDesc.Count = 1;
+ uploadDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ if (FAILED(context.device()->CreateCommittedResource(&uploadProps, D3D12_HEAP_FLAG_NONE,
+ &uploadDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload)))) {
+ return false;
+ }
+ }
+ void* mapped = nullptr;
+ if (FAILED(upload->Map(0, nullptr, &mapped))) {
+ return false;
+ }
+ memset(mapped, 0, uploadSize);
+ upload->Unmap(0, nullptr);
+
+ ID3D12GraphicsCommandList* list = ring.acquire(1, status);
+ if (list == nullptr) {
+ return false;
+ }
+ D3D12_RESOURCE_BARRIER toDest{};
+ toDest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toDest.Transition.pResource = texture;
+ toDest.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
+ toDest.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
+ toDest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toDest);
+
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
+ footprint.Footprint.Format = format;
+ footprint.Footprint.Width = width;
+ footprint.Footprint.Height = height;
+ footprint.Footprint.Depth = 1;
+ footprint.Footprint.RowPitch = static_cast<UINT>(uploadRow);
+ D3D12_TEXTURE_COPY_LOCATION dst{};
+ dst.pResource = texture;
+ dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dst.SubresourceIndex = 0;
+ D3D12_TEXTURE_COPY_LOCATION src{};
+ src.pResource = upload.Get();
+ src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint = footprint;
+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
+
+ D3D12_RESOURCE_BARRIER toSrv{};
+ toSrv.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toSrv.Transition.pResource = texture;
+ toSrv.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
+ toSrv.Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
+ toSrv.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toSrv);
+ return ring.submitAndSignal(1) && ring.waitIdle();
+ };
+
+ if (!zeroInitTexture(motion.Get(), DXGI_FORMAT_R16G16_FLOAT, 4) ||
+ !zeroInitTexture(depth.Get(), DXGI_FORMAT_R32_FLOAT, 4) ||
+ !zeroInitTexture(confidence.Get(), DXGI_FORMAT_R8_UNORM, 1)) {
+ log::error("harness", "frame-loop: zero-init upload failed");
+ goto teardown_fail;
+ }
+ log::info("harness", "frame-loop: zero guidance textures initialized via upload copy");
+
+ // Neural moves to UAV once for the whole loop.
+ {
+ ID3D12GraphicsCommandList* list = ring.acquire(1, status);
+ if (list == nullptr) {
+ goto teardown_fail;
+ }
+ D3D12_RESOURCE_BARRIER toUav{};
+ toUav.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toUav.Transition.pResource = neural.Get();
+ toUav.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
+ toUav.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ toUav.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toUav);
+ if (!ring.submitAndSignal(1) || !ring.waitIdle()) {
+ goto teardown_fail;
+ }
+ }
+ }
+
+ const size_t rowPitch = (static_cast<size_t>(width) * 4 + 255) & ~size_t(255);
+ const size_t bufferSize = rowPitch * height;
+ D3D12_HEAP_PROPERTIES readbackProps{};
+ readbackProps.Type = D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC bufferDesc{};
+ bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufferDesc.Width = bufferSize;
+ bufferDesc.Height = 1;
+ bufferDesc.DepthOrArraySize = 1;
+ bufferDesc.MipLevels = 1;
+ bufferDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufferDesc.SampleDesc.Count = 1;
+ bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ gfx::ComPtr<ID3D12Resource> readback;
+ if (FAILED(context.device()->CreateCommittedResource(&readbackProps, D3D12_HEAP_FLAG_NONE,
+ &bufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) {
+ goto teardown_fail;
+ }
+
+ const auto readTextureStats = [&](ID3D12Resource* texture, D3D12_RESOURCE_STATES before,
+ const std::wstring& pngPath, RgbaStats& statsOut) -> bool {
+ ID3D12GraphicsCommandList* list = ring.acquire(2, status);
+ if (list == nullptr) {
+ return false;
+ }
+ D3D12_RESOURCE_BARRIER toSource{};
+ toSource.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toSource.Transition.pResource = texture;
+ toSource.Transition.StateBefore = before;
+ toSource.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
+ toSource.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toSource);
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
+ footprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ footprint.Footprint.Width = width;
+ footprint.Footprint.Height = height;
+ footprint.Footprint.Depth = 1;
+ footprint.Footprint.RowPitch = static_cast<UINT>(rowPitch);
+ D3D12_TEXTURE_COPY_LOCATION dst{};
+ dst.pResource = readback.Get();
+ dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ dst.PlacedFootprint = footprint;
+ D3D12_TEXTURE_COPY_LOCATION src{};
+ src.pResource = texture;
+ src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ src.SubresourceIndex = 0;
+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
+ D3D12_RESOURCE_BARRIER back{};
+ back.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ back.Transition.pResource = texture;
+ back.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
+ back.Transition.StateAfter = before;
+ back.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &back);
+ if (!ring.submitAndSignal(2) || !ring.waitIdle()) {
+ return false;
+ }
+ void* mapped = nullptr;
+ D3D12_RANGE readRange{ 0, bufferSize };
+ if (FAILED(readback->Map(0, &readRange, &mapped))) {
+ return false;
+ }
+ statsOut = analyzeRgba(static_cast<const uint8_t*>(mapped), width, height, rowPitch);
+ bool pngOk = true;
+ if (!pngPath.empty()) {
+ pngOk = writeRgbaPng(pngPath, static_cast<const uint8_t*>(mapped), width, height, rowPitch);
+ }
+ readback->Unmap(0, nullptr);
+ return pngOk;
+ };
+
+ log::info("harness", std::format("frame-loop: starting frames={} size={}x{} style={} intensity={}",
+ args.frames, width, height, args.styleOverride, args.intensityOverride));
+ D3D12_RESOURCE_STATES proxyState = D3D12_RESOURCE_STATE_COMMON;
+ bool loopBroken = false;
+ for (uint32_t frame = 0; frame < args.frames; ++frame) {
+ ID3D12GraphicsCommandList* list = ring.acquire(frame % 4, status);
+ if (list == nullptr) {
+ loopBroken = true;
+ break;
+ }
+
+ D3D12_RESOURCE_BARRIER toUav{};
+ toUav.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toUav.Transition.pResource = proxy.Get();
+ toUav.Transition.StateBefore = proxyState;
+ toUav.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ toUav.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toUav);
+
+ ID3D12DescriptorHeap* heaps[] = { uavHeap.Get() };
+ list->SetDescriptorHeaps(1, heaps);
+ list->SetPipelineState(pipelineState.Get());
+ list->SetComputeRootSignature(rootSignature.Get());
+ const UINT constants[4] = { frame, width, height, 0 };
+ list->SetComputeRoot32BitConstants(0, 4, constants, 0);
+ list->SetComputeRootDescriptorTable(1, { gpuBase.ptr });
+ list->Dispatch((width + 15) / 16, (height + 15) / 16, 1);
+
+ D3D12_RESOURCE_BARRIER toSrv{};
+ toSrv.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ toSrv.Transition.pResource = proxy.Get();
+ toSrv.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ toSrv.Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
+ toSrv.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &toSrv);
+ proxyState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
+
+ namespace p = ngx::dlssnr;
+ ngx::ParameterBlock pb(params);
+ pb.setD3D12Resource(p::kColor, proxy.Get());
+ pb.setD3D12Resource(p::kOutput, neural.Get());
+ pb.setD3D12Resource(p::kMVec, motion.Get());
+ pb.setD3D12Resource(p::kDepth, depth.Get());
+ pb.setU32(p::kColorSubrectBaseX, 0);
+ pb.setU32(p::kColorSubrectBaseY, 0);
+ pb.setU32(p::kColorSubrectWidth, width);
+ pb.setU32(p::kColorSubrectHeight, height);
+ pb.setU32(p::kOutputSubrectBaseX, 0);
+ pb.setU32(p::kOutputSubrectBaseY, 0);
+ pb.setU32(p::kOutputSubrectWidth, width);
+ pb.setU32(p::kOutputSubrectHeight, height);
+ pb.setU32(p::kMVecSubrectBaseX, 0);
+ pb.setU32(p::kMVecSubrectBaseY, 0);
+ pb.setU32(p::kMVecSubrectWidth, width);
+ pb.setU32(p::kMVecSubrectHeight, height);
+ pb.setU32(p::kDepthSubrectBaseX, 0);
+ pb.setU32(p::kDepthSubrectBaseY, 0);
+ pb.setU32(p::kDepthSubrectWidth, width);
+ pb.setU32(p::kDepthSubrectHeight, height);
+ pb.setF32(p::kMVecScaleX, 1.0f);
+ pb.setF32(p::kMVecScaleY, 1.0f);
+ pb.setI32(p::kDepthInverted, 1);
+ pb.setI32(p::kIndicatorInvertX, 0);
+ pb.setI32(p::kIndicatorInvertY, 0);
+ pb.setI32(p::kEnabled, 1);
+ pb.setI32(p::kReset, frame == 0 ? 1 : 0);
+ pb.setI32(p::kStyle, args.styleOverride);
+ pb.setF32(p::kIntensity, args.intensityOverride);
+ pb.setF32(p::kLocalToneStrength, 1.0f);
+ pb.setF32(p::kLocalStructureStrength, 1.0f);
+ pb.setF32(p::kSkinStructureStrength, -1.0f);
+ pb.setI32(p::kUseAutoMask, 0);
+ pb.setI32(p::kUICorrection, 0);
+
+ ++evaluateAttempted;
+ uint64_t evalResult = 0;
+ uint32_t evalSeh = 0;
+ if (!adapter.snippetEvaluateFeature(list, handle, params, evalResult, evalSeh)) {
+ ++evaluateFailed;
+ loopBroken = true;
+ break;
+ }
+ if (evalResult != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
+ ++evaluateFailed;
+ log::error("harness", std::format("frame-loop: Evaluate frame={} result={} seh={}",
+ frame, ngxResultString(evalResult), evalSeh));
+ loopBroken = true;
+ break;
+ }
+ ++evaluateSucceeded;
+
+ D3D12_RESOURCE_BARRIER uavBarrier{};
+ uavBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
+ uavBarrier.UAV.pResource = neural.Get();
+ list->ResourceBarrier(1, &uavBarrier);
+
+ if (!ring.submitAndSignal(frame % 4)) {
+ loopBroken = true;
+ break;
+ }
+
+ if (frame == args.captureFrame && !args.captureDir.empty()) {
+ if (!ring.waitIdle()) {
+ loopBroken = true;
+ break;
+ }
+ RgbaStats proxyStats{};
+ const bool proxyOk = readTextureStats(proxy.Get(), proxyState,
+ args.captureDir + L"\\frame0000_proxy.png", proxyStats);
+ const bool rawOk = readTextureStats(neural.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+ args.captureDir + L"\\frame0000_raw.png", finalStats);
+ log::info("harness", std::format("frame-loop: captures frame={} proxy={} raw={} proxySha={}",
+ frame, proxyOk, rawOk, proxyStats.sha256));
+ }
+ }
+ (void)ring.waitIdle();
+ if (loopBroken) {
+ log::error("harness", "frame-loop: stopped early after error");
+ }
+
+ if (!loopBroken || evaluateSucceeded > 0) {
+ RgbaStats endStats{};
+ const std::wstring noPng;
+ if (readTextureStats(neural.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, noPng, endStats)) {
+ finalStats = endStats;
+ }
+ }
+
+ uint32_t removedReason = 0;
+ deviceRemoved = !context.checkDeviceAlive(removedReason);
+ deviceRemovedReason = removedReason;
+
+ log::info("harness", std::format("frame-loop: done attempted={} succeeded={} failed={} deviceRemoved={}",
+ evaluateAttempted, evaluateSucceeded, evaluateFailed, deviceRemoved));
+ log::info("harness", std::format("frame-loop: output stats meanLuma={:.5} minLuma={:.5} maxLuma={:.5} stddev={:.5} allZero={} constant={} sha256={}",
+ finalStats.meanLuma, finalStats.minLuma, finalStats.maxLuma, finalStats.stddev,
+ finalStats.allZero, finalStats.constant, finalStats.sha256));
+
+ uint64_t releaseResult = 0;
+ uint32_t releaseSeh = 0;
+ (void)adapter.snippetReleaseFeature(handle, releaseResult, releaseSeh);
+ coreHost.destroyParameters(params);
+ params = nullptr;
+ uint64_t snippetShutdownResult = 0;
+ uint32_t snippetShutdownSeh = 0;
+ (void)adapter.snippetShutdown1(context.device(), snippetShutdownResult, snippetShutdownSeh);
+ adapter.restoreCallerCompatibility();
+ adapter.unload();
+ ring.shutdown();
+ coreHost.shutdown();
+ context.shutdown();
+ log::info("harness", std::format("frame-loop: teardown release={} snippetShutdown={}",
+ ngxResultString(releaseResult), ngxResultString(snippetShutdownResult)));
+
+ const bool allOk = !loopBroken && evaluateSucceeded == args.frames && !deviceRemoved &&
+ !finalStats.allZero && !finalStats.constant;
+ log::info("harness", allOk ? "frame-loop: PASS" : "frame-loop: FAIL");
+ return allOk ? 0 : 12;
+ }
+
+teardown_fail:
+ if (params != nullptr) {
+ coreHost.destroyParameters(params);
+ }
+ adapter.restoreCallerCompatibility();
+ adapter.unload();
+ ring.shutdown();
+ coreHost.shutdown();
+ context.shutdown();
+ log::error("harness", std::format("frame-loop: FAIL setup attempted={} succeeded={} failed={}",
+ evaluateAttempted, evaluateSucceeded, evaluateFailed));
+ return 11;
+}
+
+} // namespace veyra::harness
diff --git a/tools/nr_harness/frame_loop.h b/tools/nr_harness/frame_loop.h
new file mode 100644
index 00000000..9406af05
--- /dev/null
+++ b/tools/nr_harness/frame_loop.h
@@ -0,0 +1,24 @@
+#pragma once
+
+// Phase 1 frame loop: Proxy (test pattern) -> Feature 18 Evaluate -> Raw
+// output with statistics and captures (Playbook sections 8.6/8.7).
+#include <cstdint>
+#include <string>
+
+namespace veyra::harness {
+
+struct FrameLoopArgs {
+ std::wstring runtimeDir;
+ uint32_t width = 1920;
+ uint32_t height = 1080;
+ uint32_t frames = 300;
+ std::wstring runId;
+ uint32_t captureFrame = 0;
+ std::wstring captureDir;
+ int styleOverride = 0;
+ float intensityOverride = 1.0f;
+};
+
+int runFrameLoop(const FrameLoopArgs& args);
+
+} // namespace veyra::harness
diff --git a/tools/nr_harness/main.cpp b/tools/nr_harness/main.cpp
index 278ee6ec..a6ceeaab 100644
--- a/tools/nr_harness/main.cpp
+++ b/tools/nr_harness/main.cpp
@@ -22,6 +22,8 @@
#include "veyra/ngx/NgxCoreHost.h"
#include "veyra/ngx/NgxParameters.h"
+#include "frame_loop.h"
+
namespace {
constexpr uint64_t kExpectedDllSize = 165840496ull;
@@ -445,11 +447,19 @@ int wmain(int argc, wchar_t** argv)
{
std::wstring runtimeDir;
std::wstring logFile;
+ std::wstring runId;
+ std::wstring jsonFile;
+ std::wstring captureDir;
+ uint32_t width = 1920;
+ uint32_t height = 1080;
+ uint32_t frames = 300;
+ uint32_t captureFrame = 0;
+ int styleOverride = 0;
+ float intensityOverride = 1.0f;
bool loadOnly = false;
bool shimTest = false;
bool createTest = false;
- uint32_t width = 1920;
- uint32_t height = 1080;
+ bool frameLoop = false;
for (int i = 1; i < argc; ++i) {
const std::wstring arg = argv[i];
if (arg == L"--load-only") {
@@ -461,6 +471,34 @@ int wmain(int argc, wchar_t** argv)
else if (arg == L"--create-test") {
createTest = true;
}
+ else if (arg == L"--frames" && i + 1 < argc) {
+ frames = static_cast<uint32_t>(wcstoul(argv[++i], nullptr, 10));
+ frameLoop = true;
+ }
+ else if (arg == L"--guidance" && i + 1 < argc) {
+ ++i; // zero is the only Phase 1 provider; accepted for CLI parity
+ }
+ else if (arg == L"--profile" && i + 1 < argc) {
+ ++i; // baseline values are compiled in for Phase 1 (P1.6 wires profiles)
+ }
+ else if (arg == L"--capture-frame" && i + 1 < argc) {
+ captureFrame = static_cast<uint32_t>(wcstoul(argv[++i], nullptr, 10));
+ }
+ else if (arg == L"--capture-dir" && i + 1 < argc) {
+ captureDir = argv[++i];
+ }
+ else if (arg == L"--run-id" && i + 1 < argc) {
+ runId = argv[++i];
+ }
+ else if (arg == L"--json-file" && i + 1 < argc) {
+ jsonFile = argv[++i];
+ }
+ else if (arg == L"--style" && i + 1 < argc) {
+ styleOverride = static_cast<int>(wcstol(argv[++i], nullptr, 10));
+ }
+ else if (arg == L"--intensity" && i + 1 < argc) {
+ intensityOverride = wcstof(argv[++i], nullptr);
+ }
else if (arg == L"--runtime-dir" && i + 1 < argc) {
runtimeDir = argv[++i];
}
@@ -486,11 +524,24 @@ int wmain(int argc, wchar_t** argv)
else if (createTest && !runtimeDir.empty()) {
exitCode = runCreateTest(runtimeDir, width, height);
}
+ else if ((frameLoop || !jsonFile.empty()) && !runtimeDir.empty()) {
+ veyra::harness::FrameLoopArgs loopArgs{};
+ loopArgs.runtimeDir = runtimeDir;
+ loopArgs.width = width;
+ loopArgs.height = height;
+ loopArgs.frames = frames;
+ loopArgs.runId = runId;
+ loopArgs.captureFrame = captureFrame;
+ loopArgs.captureDir = captureDir;
+ loopArgs.styleOverride = styleOverride;
+ loopArgs.intensityOverride = intensityOverride;
+ exitCode = veyra::harness::runFrameLoop(loopArgs);
+ }
else if (loadOnly && !runtimeDir.empty()) {
exitCode = runLoadOnly(runtimeDir);
}
else {
- veyra::log::info("harness", "no mode selected; use --load-only/--shim-test/--create-test --runtime-dir <abs> (frame loop arrives in P1.5-P1.6)");
+ veyra::log::info("harness", "no mode selected; use --load-only/--shim-test/--create-test or --frames N --runtime-dir <abs>");
exitCode = 1;
}