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++

test: reject unchanged-output duplicate reuse using 4500 real graph frames

Veyra Goal Agent275ca1ad001a
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 53afc764..708ed2e6 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -708,3 +708,6 @@ compiled HIP modules and runtime DLLs stay outside source Git; their use in this
runtime MIT notice accompany the local asset directory. No AMD driver DLL is
copied from that package; an RX 9000 driver must provide `amdhip64_7.dll`.
Hardware inference, image quality and stability remain unverified on RX 9000.
+# Performance experiments (2026-10-04)
+
+`tests/perf/DuplicateFrameCS.hlsl` adapts `src/Magpie.Core/shaders/DuplicateFrameCS.hlsl` from [SAOG0721/Magpie](https://github.com/SAOG0721/Magpie/tree/27c5df91177a29b33be612e98274169f3d2fca49), fixed commit `27c5df91177a29b33be612e98274169f3d2fca49` / `v0.6.9-experimental`, GPL-3.0. Original shader SHA256 `39fe0acfcf499083c1380aa4a5dc0ad8e0b6632537efda61342e068d9eac2275` matches the local research copy byte-for-byte. Adaptations retain group reduction and atomic publication, replace sampler Gather with four bounded texture loads for D3D12/odd extents, add typed textures and provenance. This is an isolated measurement fixture; no production duplicate-skip behavior is implied.
diff --git a/docs/PERF_1A_DUPLICATE_REUSE_2026-10-04.md b/docs/PERF_1A_DUPLICATE_REUSE_2026-10-04.md
new file mode 100644
index 00000000..b87a5a14
--- /dev/null
+++ b/docs/PERF_1A_DUPLICATE_REUSE_2026-10-04.md
@@ -0,0 +1,25 @@
+# 1a 精确重复输入与整链复用:画面不变前提未成立
+
+## 实际产品链反例
+
+使用 M1 真实解码出的第一张自然画面,固定像素和颜色语义,连续输入300次,每次PTS/序号真实递增;处理一轮后继续保留SDK/光流/时域历史。Graph不注入2a缓存,没有生产重复跳过改动。仅在测试中读回完整RGBA、逐字节比较和SHA256;处理计时不含读回。不是CPU模型替身,也不是主机实卡30-in-60素材。
+
+RTX5070 / 616.56 / Lecram F95FEB原字节,native EXE `082bb45fc1f3567e6312d0b947c77d098d023f5b260f016b09948478ed8ffb33`,构建3e28be0。五组各独立三轮,共4500次源帧处理:15/15 native测量有效、debug0、设备正常、实际NR/SR Evaluate数符合请求。
+
+| 配置 | 三轮A-A不同帧 | 复用首帧对A的不同帧(每轮300) | 后100帧与上一帧不同 | MAE对首帧中位数(0–255) |
+|---|---|---|---:|---:|
+| NR1层,外部抗闪烁关 | 0/0/0 | 299/299/299 | 100 | 0.560520 |
+| NR1层,外部抗闪烁开 | 0/0/0 | 299/299/299 | 100 | 0.555252 |
+| NR1层 + DLSS SR4K | 0/0/0 | 299/299/299 | 100 | 0.609764 |
+| 仅DLSS SR4K | 0/0/0 | 299/299/299 | 100 | 0.166118 |
+| 所有效果关 | 0/0/0 | 0/0/0 | 0 | 0 |
+
+原始数据 `E:/项目/Veyra/logs/perf-nr-20261004/static-M1-v1-{nr,nr-temporal,srnr,sr,off}-r{1,2,3}/`:300行frames.csv、完整11张关键帧、console/engine日志、result.json。三轮输出序列逐帧SHA相同,噪声底线0;`static-M1-v1-summary.json` / `static-M1-v1-comparison.json`。`nr-static.py B2a static-M1-v1`及report均exit0,测量成功不等于优化通过。
+
+## 决定
+
+方案第9.4要求1a“不应改画面”,第9.5要求画面不一致回退或关默认。当前链中完全相同的源像素并不保证下一次完整处理输出相同,首个后续帧就有736,284个RGBA字节变化;持续预热后仍有变化。不能归咎于随机噪声,因为独立A-A重复相同;也不能仅以“外部抗闪烁关”推断整个SDK链无状态。
+
+因此拒绝把“精确重复输入→不推进NR/SR/光流→复用旧完整输出”作为不改画面的默认优化。未加入生产候选,没有生产代码需revert,原行为保留。不能用大幅省计算量替代画面合同,不能宣称所有NR运行库或其它GPU均有同样差异。
+
+GPU精确比较、奇数边界/Alpha及真实WGC比例仍作为E3独立测量继续,不代表产品开启整链跳过。1b不能在增强仍处理每个transport帧时,仅凭内容30fps把60fps工作预算翻倍;需等实际去重处理合同成立。暂停后显式reset与残差-only重合成属于5c,须单独测,不能由本反例直接否定或通过。
diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.md
index bdcc19b1..d10224d5 100644
--- a/docs/PERF_EXECUTION_NR_2026-10-04.md
+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md
@@ -28,7 +28,7 @@
| E1 | Feature18动态输入尺寸 | completed-conditional | 两运行库8组合API/区域/恢复正常,但缩小后与独立小实例不同;PERF_E1_DYNAMIC_SIZE,3b优先实际尺寸实例 |
| E2 | 并行Evaluate/CreateFeature | completed-conditional | 单Core/adapter,三次240s累计12min及150次创建安全通过;间隔110–116ms,不能据此宣称2b无缝 |
| E3 | 真实来源精确重复比例 | pending | 屏幕/实卡可用性与合成节奏分开 |
-| 1a | 精确重复帧整链复用 | pending | 先验证时域模型重复Evaluate结果是否相同 |
+| 1a | 精确重复帧整链复用 | rejected-unchanged-output | 自然同像素300帧×五组×三轮,A-A噪声0;NR/SR复用299帧不同;PERF_1A_DUPLICATE_REUSE;无生产改动 |
| 5a | 黑边检测与有效区域处理 | pending | 防暗场误裁,先测准确性与重建收益 |
| 3a | 进程GPU调度优先级 | pending | 只改本进程,有竞争负载的实际A/B |
| 2a | 跨重建保留NGX核心 | in-progress | 四组20次×三轮A基线,240次重建/重复像素0差异;PERF_2A_CORE_REUSE;尚未产品候选 |
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4b53e43d..f0dc5c53 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,12 @@
# Veyra 工作记录
+## 2026-10-04 NR优化1a:真实链4500帧反例,拒绝默认整链复用
+
+- 1a-before标签3e28be0后,`nr-static.py B2a static-M1-v1` 五组各300帧×三轮15/15测量exit0,NR/SR实际Evaluate计数符合配置,debug0/设备正常。固定M1真实解码自然画面、PTS/序号增加,没有生产跳过,也没有注入Core缓存。EXE082bb45…ffb33,NR F95FEB/616.56。
+- `nr-static-report.py static-M1-v1`:每组A-A输出序列0差异;NR(抗闪烁关/开)/NR+DLSSSR/仅DLSSSR复用首帧对A每轮299/300帧不同,预热后最后100帧全部继续变化;只有效果全关0不同。MAE中位0.560520/0.555252/0.609764/0.166118(byte0–255)。全部原始300行/11张全RGBA/日志/JSON在logs/perf-nr-20261004/static-M1-v1-*。
+- 拒绝方案“不改画面”的默认整链重复跳过,不以NN非确定性豁免,因为三轮A-A噪声0;未写生产候选,无生产revert。PERF_1A_DUPLICATE_REUSE记录边界,1b预算不能在仍处理60transport帧时假定工作量30;5c显式暂停reset另测。
+- CoreUI修正后v3六组各20请求全部exit0,无FG的NR/SR/层数/尺寸仅Init1/Shutdown1;FG开关和NR模块变化Init21/Shutdown21,按完整流程。层数20请求实际26次重建,逐setter有中间状态,诚实保留。v2脚本设置倍率自动打开FG,作为带DLSS2X额外组合,不冒充无FG对照。Core64参数表边界/活动借用拒绝/初始化早期失败真实SDK检查exit0;预期拒绝日志不是设备故障。
+
## 2026-10-04 NR优化2a:三组实测有收益,补生命周期拒绝检查
- fbaffeb候选全新build-B2a-v1 479步exit0。A/B/B-off四组各20×三轮,720次重建36/36 native有效;对A三轮暖创建中位:NR开1569.510→386.758ms(-75.36%),SR1409.580→415.158(-70.55%),层数1456.600→544.314(-62.63%),尺寸1348.730→403.039(-70.12%)。B-off分别1563.090/1580.430/1701.260/1596.630,后几组时钟未采不能解释慢于A,不用差额虚增收益。
diff --git a/scripts/perf/nr-core-ui.py b/scripts/perf/nr-core-ui.py
index 03d31647..3a15d6c0 100644
--- a/scripts/perf/nr-core-ui.py
+++ b/scripts/perf/nr-core-ui.py
@@ -43,6 +43,7 @@ for group in groups:
settled=[json.loads(line.split('CORE_UI_SETTLED ',1)[1]) for line in text.splitlines() if 'CORE_UI_SETTLED ' in line]
resets=[{k:float(v) for k,v in re.findall(r'(\w+)=(-?\d+(?:\.\d+)?)',line)} for line in text.splitlines() if '[reset-lifecycle]' in line]
result={'variant':variant,'group':group,'exeSha256':matrix.digest(app/'veyra_qml_ui.exe'),
+ 'testQmlSha256':matrix.digest(app/'qml/Veyra/NrCoreUiProbe.qml'),
'nrSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'command':command,'exitCode':rc,
'wallSeconds':time.monotonic()-start,'gpuBefore':before,'gpuAfter':matrix.gpu_query(),
'settledRequests':settled,'actualResetEvents':resets,'coreInitCalls':text.count('core-host: Init_with_ProjectID result='),
diff --git a/scripts/perf/nr-core-ui.qml b/scripts/perf/nr-core-ui.qml
index edeb5b19..149ed40b 100644
--- a/scripts/perf/nr-core-ui.qml
+++ b/scripts/perf/nr-core-ui.qml
@@ -60,6 +60,9 @@ Item {
veyra.nrEnabled = true; veyra.srEnabled = false; veyra.fgEnabled = false
veyra.videoHdr = false; veyra.colorEnabled = false; veyra.videoSrQuality = 0
veyra.srTargetIndex = 2; veyra.fgBackendName = "dlss"; veyra.fgMultiplier = 2
+ // Selecting a multiplier intentionally enables FG in the
+ // product bridge; reset it after configuring the saved level.
+ veyra.fgEnabled = false
while (veyra.nrLayers.length < (probe.group === "layers" ? 3 : 1))
require(veyra.duplicateNrLayer(veyra.nrLayers[0].index)>=0,"duplicate NR")
for (let i=0;i<veyra.nrLayers.length;++i) {
@@ -68,6 +71,8 @@ Item {
require(veyra.setEffectEnabled(veyra.nrLayers[i].index,i===0),"initial enable")
}
veyra.openPath(probe.media)
+ console.log("CORE_UI_INITIAL",JSON.stringify({group:probe.group,fg:veyra.fgEnabled,
+ multiplier:veyra.fgMultiplier,sr:veyra.srEnabled,layers:veyra.nrLayers}))
return
}
if (!veyra.running || veyra.applying || veyra.position <= 0) return
diff --git a/scripts/perf/nr-rebuild-series.py b/scripts/perf/nr-rebuild-series.py
new file mode 100644
index 00000000..1c362335
--- /dev/null
+++ b/scripts/perf/nr-rebuild-series.py
@@ -0,0 +1,9 @@
+"""Serial B / same-executable B-off suites; each native case is bounded."""
+from pathlib import Path
+import subprocess
+import sys
+root=Path(__file__).resolve().parents[2]
+variant,label=sys.argv[1:3]
+for v,name in ((variant,label),(variant+'-off',label+'-off')):
+ rc=subprocess.run([sys.executable,'-B',str(root/'scripts/perf/nr-rebuild.py'),v,name],cwd=root).returncode
+ if rc:raise SystemExit(rc)
diff --git a/scripts/perf/nr-rebuild.py b/scripts/perf/nr-rebuild.py
index d96572e6..d4ac9518 100644
--- a/scripts/perf/nr-rebuild.py
+++ b/scripts/perf/nr-rebuild.py
@@ -30,19 +30,26 @@ for group in groups:
name=f'{label}-{group}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
out.mkdir(parents=True,exist_ok=False);tmp.mkdir(parents=True,exist_ok=False)
env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_VERBOSE_FRAME_LOGS='1')
+ for key in tuple(env):
+ if key.upper().startswith('VEYRA_') and key!='VEYRA_VERBOSE_FRAME_LOGS':env.pop(key)
if variant.endswith('off'):env['VEYRA_TEST_DISABLE_NGX_CORE_REUSE']='1'
cmd=[str(exe),str(matrix.SOURCES['M1']),str(out),group]
- print('START',name,flush=True);start=time.monotonic()
+ print('START',name,flush=True);gpu_before=matrix.gpu_query();start=time.monotonic();meters=[]
with (out/'console.log').open('xb') as log:
- try:rc=subprocess.run(cmd,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280).returncode
- except subprocess.TimeoutExpired:rc=124
+ proc=subprocess.Popen(cmd,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT)
+ while proc.poll() is None and time.monotonic()-start<280:
+ meters.append({'elapsed':time.monotonic()-start,'gpu':matrix.gpu_query()});time.sleep(.7)
+ if proc.poll() is None:proc.kill();proc.wait(timeout=8);rc=124
+ else:rc=proc.returncode
+ (out/'meters.json').write_text(json.dumps(meters,ensure_ascii=False,indent=2),encoding='utf-8')
text=(out/'console.log').read_text(encoding='utf-8',errors='replace')
rows=list(csv.DictReader((out/'rebuild.csv').open())) if (out/'rebuild.csv').exists() else []
metrics={k:{'p50':statistics.median(float(r[k]) for r in rows),'p95':percentile([float(r[k]) for r in rows],95),
'min':min(float(r[k]) for r in rows),'max':max(float(r[k]) for r in rows)}
for k in ('createMs','destroyMs','totalMs','vramLive','vramAfter')} if rows else {}
r={'variant':variant,'group':group,'repeat':repeat,'command':cmd,'exitCode':rc,'wallSeconds':time.monotonic()-start,
- 'exeSha256':matrix.digest(exe),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'exeSha256':matrix.digest(exe),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'gpuBefore':gpu_before,'gpuAfter':matrix.gpu_query(),
'nrSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'rowCount':len(rows),'metrics':metrics,
'frameHashes':{p.name:matrix.digest(p) for p in sorted(out.glob('frame-*.rgba'))},
'passed':rc==0 and len(rows)==20 and 'RESULT pass=1 debugErrors=0 deviceRemoved=0' in text,
diff --git a/scripts/perf/nr-static-report.py b/scripts/perf/nr-static-report.py
new file mode 100644
index 00000000..097b0c18
--- /dev/null
+++ b/scripts/perf/nr-static-report.py
@@ -0,0 +1,23 @@
+"""Verify A-A noise before judging a frozen-output duplicate reuse candidate."""
+from pathlib import Path
+import csv
+import json
+import statistics
+import sys
+base=Path('E:/项目/Veyra/logs/perf-nr-20261004');label=sys.argv[1]
+runs=json.loads((base/(label+'-summary.json')).read_text(encoding='utf-8'))
+report={'label':label,'modes':{},'candidate':'Reuse first accepted complete output on exact identical inputs; no product change'}
+for mode in sorted(set(r['mode'] for r in runs)):
+ rr=[r for r in runs if r['mode']==mode];assert len(rr)==3 and all(r['safetyPassed'] for r in rr)
+ noise=[sum(a!=b for a,b in zip(rr[0]['sha256Sequence'],r['sha256Sequence'])) for r in rr]
+ rows=list(csv.DictReader((base/f'{label}-{mode}-r1'/'frames.csv').open()))
+ report['modes'][mode]={'framesPerRun':300,'repeatCount':3,'differentFramesAcrossIdenticalARepeats':noise,
+ 'candidateDifferentFramesToA':[r['differentOutputFramesToFirst'] for r in rr],
+ 'last100ChangedFromPrevious':sum(r['equalPrevious']=='0' for r in rows[-100:]),
+ 'maeToFirstMedianByteScale':statistics.median(float(r['maeToFirst']) for r in rows),
+ 'exeSha256':rr[0]['exeSha256'],'nrSha256':rr[0]['nrSha256'],'sourceSha256':rr[0]['sourceSha256']}
+assert all(not any(x['differentFramesAcrossIdenticalARepeats']) for x in report['modes'].values())
+report['unchangedOutputContractPassed']=all(not any(x['candidateDifferentFramesToA']) for x in report['modes'].values())
+with (base/(label+'-comparison.json')).open('x',encoding='utf-8') as f:json.dump(report,f,ensure_ascii=False,indent=2)
+print(json.dumps(report,ensure_ascii=False,indent=2))
+# A valid counterexample is a successfully measured experiment.
diff --git a/tests/perf/DuplicateFrameCS.hlsl b/tests/perf/DuplicateFrameCS.hlsl
new file mode 100644
index 00000000..f3b58bce
--- /dev/null
+++ b/tests/perf/DuplicateFrameCS.hlsl
@@ -0,0 +1,28 @@
+// Adapted from SAOG0721/Magpie, src/Magpie.Core/shaders/DuplicateFrameCS.hlsl
+// commit 27c5df91177a29b33be612e98274169f3d2fca49 (v0.6.9-experimental), GPL-3.0.
+// Retain 8x8 group reduction/one global atomic and 2x2 pixels per thread.
+// D3D12 test adaptation: four bounded Load operations replace sampler Gather,
+// so odd extents are exact and the existing sampler-free root signature works.
+RWBuffer<uint> result : register(u0);
+cbuffer CompareOptions : register(b0) {uint compareAlpha;};
+groupshared uint groupDifferent;
+Texture2D<float4> tex1 : register(t0);
+Texture2D<float4> tex2 : register(t1);
+[numthreads(8,8,1)]
+void main(uint3 tid:SV_GroupThreadID,uint3 gid:SV_GroupID){
+ if(all(tid==0))groupDifferent=0;
+ GroupMemoryBarrierWithGroupSync();
+ const uint2 gxy=(gid.xy<<4)+(tid.xy<<1);
+ uint width,height;tex1.GetDimensions(width,height);
+ bool different=false;
+ [unroll]for(uint y=0;y<2;++y)[unroll]for(uint x=0;x<2;++x){
+ const uint2 at=gxy+uint2(x,y);
+ if(at.x<width&&at.y<height){
+ const float4 a=tex1.Load(int3(at,0)),b=tex2.Load(int3(at,0));
+ different=different||(compareAlpha!=0?any(a!=b):any(a.rgb!=b.rgb));
+ }
+ }
+ if(different)InterlockedOr(groupDifferent,1u);
+ GroupMemoryBarrierWithGroupSync();
+ if(all(tid==0)&&groupDifferent!=0)InterlockedOr(result[0],1u);
+}
diff --git a/tests/perf/DuplicateGpuFixture.h b/tests/perf/DuplicateGpuFixture.h
new file mode 100644
index 00000000..2a36dda3
--- /dev/null
+++ b/tests/perf/DuplicateGpuFixture.h
@@ -0,0 +1,77 @@
+#pragma once
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+#include <d3dcompiler.h>
+#include <chrono>
+#include <cstring>
+#include <filesystem>
+#include <iostream>
+
+namespace dupperf {
+using namespace veyra;
+inline double nowUs(){return std::chrono::duration<double,std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count();}
+class ExactChecker {
+ gfx::D3D12DeviceContext& ctx_;gfx::CommandSlotRing& ring_;
+ pipeline::ComputePass pass_;pipeline::DescriptorStager stager_;pipeline::StateTracker states_;
+ pipeline::ComPtr<ID3D12Resource> flag_,readback_,zero_,history_;
+ pipeline::ComPtr<ID3D12QueryHeap> queries_;bool valid_=false;
+ bool copyHistory(ID3D12Resource* current,D3D12_RESOURCE_STATES initial){
+ Status status;uint32_t slot;auto* list=ring_.acquireNext(slot,status);if(!list)return false;
+ states_.set(current,initial);states_.transition(list,current,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ states_.transition(list,history_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(history_.Get(),current);
+ states_.transition(list,current,initial);states_.transition(list,history_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ if(!ring_.submitAndSignal(slot)||!ring_.waitIdle())return false;valid_=true;return true;
+ }
+public:
+ struct Result {bool first=false,duplicate=false;double gpuCompareMs=0,cpuFenceWaitUs=0,totalCpuUs=0,historyCopyCpuUs=0;};
+ ExactChecker(gfx::D3D12DeviceContext& c,gfx::CommandSlotRing& r):ctx_(c),ring_(r){}
+ void invalidate(){valid_=false;}
+ bool initialize(const std::filesystem::path& shader){
+ pipeline::ComPtr<ID3DBlob> code,errors;
+ const auto hr=D3DCompileFromFile(shader.c_str(),nullptr,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","cs_5_1",D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&code,&errors);
+ if(FAILED(hr)){std::cerr<<"compile HRESULT="<<unsigned(hr)<<' '<<(errors?static_cast<const char*>(errors->GetBufferPointer()):"")<<std::endl;return false;}
+ std::vector<uint8_t> bytes(static_cast<const uint8_t*>(code->GetBufferPointer()),static_cast<const uint8_t*>(code->GetBufferPointer())+code->GetBufferSize());
+ if(!pass_.create(ctx_.device(),bytes,3,2,1,1)||!stager_.initialize(ctx_.device(),2))return false;
+ D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;d.Width=4;d.Height=1;d.DepthOrArraySize=1;d.MipLevels=1;d.SampleDesc.Count=1;d.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ D3D12_HEAP_PROPERTIES h{};h.Type=D3D12_HEAP_TYPE_DEFAULT;d.Flags=D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ if(FAILED(ctx_.device()->CreateCommittedResource(&h,D3D12_HEAP_FLAG_NONE,&d,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&flag_))))return false;
+ d.Width=24;d.Flags=D3D12_RESOURCE_FLAG_NONE;h.Type=D3D12_HEAP_TYPE_READBACK;
+ if(FAILED(ctx_.device()->CreateCommittedResource(&h,D3D12_HEAP_FLAG_NONE,&d,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback_))))return false;
+ zero_=pipeline::makeUploadBuffer(ctx_.device(),4);if(!zero_)return false;
+ void* p=nullptr;D3D12_RANGE empty{};if(FAILED(zero_->Map(0,&empty,&p)))return false;std::memset(p,0,4);zero_->Unmap(0,nullptr);
+ D3D12_QUERY_HEAP_DESC q{};q.Type=D3D12_QUERY_HEAP_TYPE_TIMESTAMP;q.Count=2;
+ if(FAILED(ctx_.device()->CreateQueryHeap(&q,IID_PPV_ARGS(&queries_))))return false;
+ D3D12_UNORDERED_ACCESS_VIEW_DESC u{};u.Format=DXGI_FORMAT_R32_UINT;u.ViewDimension=D3D12_UAV_DIMENSION_BUFFER;u.Buffer.NumElements=1;
+ auto handle=pass_.heap->GetCPUDescriptorHandleForHeapStart();handle.ptr+=2*pass_.increment;
+ ctx_.device()->CreateUnorderedAccessView(flag_.Get(),nullptr,&u,handle);return true;
+ }
+ bool check(ID3D12Resource* current,D3D12_RESOURCE_STATES initial,bool alpha,Result& result){
+ result={};const auto start=nowUs();if(!current)return false;const auto d=current->GetDesc();
+ if(d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D||d.MipLevels!=1||d.SampleDesc.Count!=1)return false;
+ if(!history_||history_->GetDesc().Width!=d.Width||history_->GetDesc().Height!=d.Height||history_->GetDesc().Format!=d.Format){
+ history_=pipeline::makeTexture(ctx_.device(),uint32_t(d.Width),d.Height,d.Format,false);valid_=false;states_={};if(!history_)return false;
+ }
+ if(!valid_){result.first=true;const auto at=nowUs();const bool ok=copyHistory(current,initial);result.historyCopyCpuUs=nowUs()-at;result.totalCpuUs=nowUs()-start;return ok;}
+ D3D12_SHADER_RESOURCE_VIEW_DESC srv{};srv.Format=d.Format;srv.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2D;srv.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;srv.Texture2D.MipLevels=1;
+ stager_.stageSrv(current,&srv,pass_.heap.Get(),0);stager_.stageSrv(history_.Get(),&srv,pass_.heap.Get(),1);
+ Status status;uint32_t slot;auto* list=ring_.acquireNext(slot,status);if(!list)return false;
+ states_.set(current,initial);states_.transition(list,current,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ states_.transition(list,flag_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);list->CopyBufferRegion(flag_.Get(),0,zero_.Get(),0,4);
+ states_.transition(list,flag_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const uint32_t compareAlpha=alpha?1:0;auto gpu=pass_.heap->GetGPUDescriptorHandleForHeapStart();
+ pass_.bind(list,reinterpret_cast<const float*>(&compareAlpha),gpu.ptr,gpu.ptr+2*pass_.increment);
+ list->EndQuery(queries_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0);list->Dispatch((uint32_t(d.Width)+15)/16,(d.Height+15)/16,1);
+ list->EndQuery(queries_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,1);states_.uavBarrier(list,flag_.Get());
+ states_.transition(list,flag_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);list->CopyBufferRegion(readback_.Get(),0,flag_.Get(),0,4);
+ list->ResolveQueryData(queries_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0,2,readback_.Get(),8);states_.transition(list,current,initial);
+ if(!ring_.submitAndSignal(slot))return false;const auto waitAt=nowUs();if(!ring_.waitIdle())return false;result.cpuFenceWaitUs=nowUs()-waitAt;
+ D3D12_RANGE range{0,24};void* p=nullptr;if(FAILED(readback_->Map(0,&range,&p)))return false;
+ uint32_t flag=0;uint64_t time[2]{};std::memcpy(&flag,p,4);std::memcpy(time,static_cast<uint8_t*>(p)+8,16);D3D12_RANGE empty{};readback_->Unmap(0,&empty);
+ UINT64 frequency=0;if(FAILED(ctx_.directQueue()->GetTimestampFrequency(&frequency))||!frequency||time[1]<time[0])return false;
+ result.duplicate=flag==0;result.gpuCompareMs=double(time[1]-time[0])*1000/frequency;
+ if(!result.duplicate){const auto at=nowUs();if(!copyHistory(current,initial))return false;result.historyCopyCpuUs=nowUs()-at;}
+ result.totalCpuUs=nowUs()-start;return true;
+ }
+};
+}