1#include "../Rendering/Device11.h"
2#include "../Rendering/FrameProfiler11.h"
3#include <filesystem>
4#include <fstream>
5#include <sstream>
6#include <iostream>
7#include <stdexcept>
8#include <vector>
9#include <map>
10#include <thread>
11#include <atomic>
12#include <limits>
13
15namespace
16{
17 void Check(bool value,const char* text){if(!value)throw std::runtime_error(text);}
18 std::vector<std::string> Split(const std::string& line)
19 {
20 std::vector<std::string> fields;std::string field;bool quoted=false;
21 for(size_t i=0;i<line.size();++i)
22 {
23 const char c=line[i];
24 if(c=='"'){if(quoted && i+1<line.size() && line[i+1]=='"'){field+='"';++i;}else quoted=!quoted;}
25 else if(c==',' && !quoted){fields.push_back(field);field.clear();}
26 else field+=c;
27 }
28 fields.push_back(field);return fields;
29 }
30 void FlightTests(
Device11& device,
const std::filesystem::path& root,
bool abruptExit)
31 {
33 Check(!std::filesystem::exists("render-profile.capture"),"flight capture needs no trigger");
34 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
35 Check(profiler.Capturing(),"flight flag captures first frame");
36 profiler.Scene(3,22.6,true,false,0,0);
37 profiler.FlightMotion(125,true);
38 profiler.RecordChat(L"hiccup, \"entering\" clouds \u00e9\U0001f680",7);
40 profiler.RecordChat(L"after the frame\r\nsecond line",2);
41 const auto statusPath=
root/
"outputs"/(
"render-profile-"+std::to_string(GetCurrentProcessId())+
".status.json");
42 for(unsigned attempt=0;attempt<200 && !std::filesystem::exists(statusPath);++attempt)Sleep(10);
43 std::ifstream initialStatus(statusPath);std::stringstream initialJson;initialJson<<initialStatus.rdbuf();initialStatus.close();
44 Check(initialJson.str().find("\"writer_stopped\":false")!=std::string::npos,"metadata is available before any shutdown or device reset");
45 Check(initialJson.str().find("\"client_version\":\"7.8.9.10\"")!=std::string::npos,"initial checkpoint contains executable identity");
46 Check(initialJson.str().find("\"writer_queue_frames\":32")!=std::string::npos &&
47 initialJson.str().find("\"stdio_buffer_bytes\":1048576")!=std::string::npos,"status documents capture buffer bounds");
48 if(abruptExit)
49 {
50 std::cout<<"Abrupt termination after initial metadata checkpoint: "<<statusPath<<std::endl;
51
52
53 TerminateProcess(GetCurrentProcess(),0);
54 }
55 profiler.Reset();
56 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
57 Check(profiler.Capturing(),"flight capture resumes on device reset");
58 profiler.RecordChat(L"after reset",1);
60 for(unsigned i=0;i<4;++i)
61 {
62 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,i==3 ? 0 : .1);
63 profiler.Scene(8,50,true,true,0,0);
64 const double speed=i==0 ? -8750. : i==1 ? 0. : std::numeric_limits<double>::quiet_NaN();
65 profiler.FlightMotion(speed,i!=3);
67 }
68 profiler.Reset();
69 const auto csv=
root/
"outputs"/(
"render-profile-"+std::to_string(GetCurrentProcessId())+
".csv");
70 std::ifstream input(csv);Check(bool(input),"flight capture CSV exists");
71 std::string line;std::getline(input,line);Check(Split(line).size()==63,"flight context columns in CSV header");
72 unsigned notes=0,frames=0;double previous=-1;
73 while(std::getline(input,line))
74 {
75 const auto fields=Split(line);Check(fields.size()==63,"quoted marker has complete CSV row");
76 if(fields[28]!="marker")
77 {
78 ++frames;Check(fields[57].empty(),"frame rows have no chat");
79 const auto number=std::stoul(fields[0]);
80 Check(fields[62]==(number==1 ? "1" : "2"),"frames retain their device epoch across recovery");
81 Check(fields[61]==(number==1 ? "cockpit" : number==2 ? "unknown" : "exterior"),"view mode changes and missing scene is unknown");
82 Check(fields[8]==(number==1 ? "3" : number==2 ? "-1" : "8"),"vehicle changes stay with their samples");
83 if(number<6)Check(std::stod(fields[58])==(number<=2 ? 62.5 : 10.),"FPS comes from actual frame interval");
84 else Check(fields[58].empty(),"zero interval does not invent FPS");
85 if(number==1)Check(fields[60]=="ascending" && std::stod(fields[59])==125,"positive VSI is ascending");
86 else if(number==3)Check(fields[60]=="descending" && std::stod(fields[59])==-8750,"high speed descent is retained without atmospheric cutoff");
87 else if(number==4)Check(fields[60]=="level" && std::stod(fields[59])==0,"zero vertical speed is level");
88 else Check(fields[59].empty() && fields[60]=="unknown","missing or invalid flight motion cannot reuse earlier samples");
89 continue;
90 }
91 for(size_t column=58;column<63;++column)Check(fields[column].empty(),"chat markers do not claim sampled flight context");
92 Check(std::stod(fields[1])>=previous,"chat timestamp order");previous=std::stod(fields[1]);
93 Check(std::stod(fields[9])==22.6,"marker altitude at submission");
94 Check(fields[15]=="-1" && fields[19]=="0","marker is not a timed scope");
95 if(notes==0)Check(fields[56]=="7" && fields[57]=="hiccup, \"entering\" clouds \xc3\xa9\xf0\x9f\x9a\x80","UTF-8, commas and quotes round trip");
96 if(notes==1)Check(fields[57]=="after the frame second line","line breaks remain one CSV record");
97 if(notes==2)Check(fields[57]=="after reset","markers survive reset without duplicates");
98 ++notes;
99 }
100 Check(notes==3 && frames==6,"startup frames and queued notes drained exactly once");
101 std::ifstream status(root/"outputs"/("render-profile-"+std::to_string(GetCurrentProcessId())+".status.json"));
102 std::stringstream json;json<<status.rdbuf();const auto metadata=json.str();
103 Check(metadata.find("\"client_version\":\"7.8.9.10\"")!=std::string::npos,"version read from running executable resource");
104 Check(metadata.find("\"process_bits\":"+std::to_string(sizeof(void*)*8))!=std::string::npos,"capture identifies process architecture");
105 Check(metadata.find("\"device_epoch\":1")!=std::string::npos && metadata.find("\"device_epoch\":2")!=std::string::npos,
106 "status retains earlier GPU identities after recovery");
107 Check(metadata.find("\"gpu_valid\":true,\"gpu\":\"")!=std::string::npos,"status contains rendering adapter description");
108 Check(metadata.find("\"output_failed\":false")!=std::string::npos,"metadata preserves terminal capture status");
109 Check(metadata.find("\"writer_stopped\":true")!=std::string::npos,"normal reset marks writer shutdown complete");
110 std::cout<<"One-flag flight capture and UTF-8 chat markers: passed\n";
111 }
112 void QueueTests()
113 {
116 const auto* blockedSink=queue.
Front();
118 Check(!queue.
Reserve(),
"slow writer rejects work without waiting");
119 Check(*blockedSink==41,"slow writer retains its snapshot while producer fills queue");
122 for(
unsigned i=0;i<3;++i){Check(*queue.
Front()==i,
"FIFO after wrap");queue.
Release();}
123 Check(*queue.
Front()==99,
"wrapped publication");queue.
Release();
124 Check(!queue.
Front(),
"queue drained");
125 std::atomic<bool> ordered{true};
126 std::thread consumer([&]{
for(
unsigned i=0;i<100000;++i){
const unsigned* value;
while(!(value=queue.
Front()))std::this_thread::yield();
if(*value!=i)ordered=
false;queue.
Release();}});
127 for(
unsigned i=0;i<100000;++i){
unsigned* value;
while(!(value=queue.
Reserve()))std::this_thread::yield();*value=i;queue.
Publish();}
128 consumer.join();Check(ordered,"concurrent publication keeps payloads ordered and intact");
129 }
130}
131int main(
int argc,
char** argv)
132{
133 try
134 {
135 QueueTests();
136 bool warp=false,enabled=false,flight=false,abruptExit=false;
137 for(int i=1;i<argc;++i){warp|=std::string(argv[i])=="--warp";enabled|=std::string(argv[i])=="--profile-render";flight|=std::string(argv[i])=="--profile-flight";abruptExit|=std::string(argv[i])=="--abrupt-exit";}
138 const auto root=std::filesystem::absolute(std::filesystem::path(
"outputs/frame-profiler-tests")/std::to_string(GetCurrentProcessId()));
139 std::filesystem::create_directories(root);std::filesystem::current_path(root);
140 Device11 device;Check(SUCCEEDED(device.
Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,true})),
"create validation device");
141 D3D11_TEXTURE2D_DESC desc{};desc.Width=desc.Height=64;desc.MipLevels=desc.ArraySize=desc.SampleDesc.Count=1;
142 desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
143 Microsoft::WRL::ComPtr<ID3D11Texture2D> texture;Microsoft::WRL::ComPtr<ID3D11RenderTargetView>
target;
144 Check(SUCCEEDED(device.
Device()->CreateTexture2D(&desc,
nullptr,&texture)),
"create texture");
145 Check(SUCCEEDED(device.
Device()->CreateRenderTargetView(texture.Get(),
nullptr,&target)),
"create target");
147
148 if(flight){FlightTests(device,root,abruptExit);return 0;}
149 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
150 profiler.RecordChat(L"inactive chat must not be recorded",1);
152 Check(!std::filesystem::exists(root/"outputs"),"no capture without trigger");
153 std::ofstream("render-profile.capture").close();
154 Sleep(150);
155 for(unsigned f=0;f<80;++f)
156 {
157 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
159 profiler.BeginGpu();profiler.Scene(3,14,true,false,0,0);
160 if(f%2==0){profiler.CloudScene(true,2.5f,8.5f,.75f);profiler.BillboardDecode(5);profiler.BillboardDecode(2);}
161 if(f%3==0)profiler.CloudClearance(.125f);
162 else if(f%3==1)profiler.CloudClearance(0);
163 {
165 {
167 if(f%2==0)
168 {
170 profiler.GeometryDraw(3);profiler.ConstantUpload(32);
171 profiler.BufferUpload(64);profiler.TextureUpload(128);
172 }
173 const float color[]={.1f,.2f,.3f,1};device.
Context()->ClearRenderTargetView(
target.Get(),color);
174 }
175 if(f%2==0)profiler.GeometryDraw(10);
176 }
177
178
179 for(unsigned call=0;call<120;++call)
180 {
182 profiler.GeometryDraw(1);profiler.ConstantUpload(4);
183 profiler.BufferUpload(16);profiler.TextureUpload(32);
184 }
185 if(f==40)
for(
int i=0;i<230;++i){
ProfileScope11 overflow(
"Overflow");}
186 if(f==50)
for(
int i=0;i<1100;++i){
ProfileScope11 overflow(
"CPU overflow",
false);}
187 profiler.EndGpu();{
ProfileScope11 present(
"Present wait",
false);}profiler.EndFrame();
188
189
190 device.
Context()->Flush();Sleep(2);
191 }
192 std::filesystem::remove("render-profile.capture");
193 Sleep(150);
194 for(
int i=0;i<20;++i){profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);Sleep(2);}
195 profiler.Reset();
196 const auto csv=
root/
"outputs"/(
"render-profile-"+std::to_string(GetCurrentProcessId())+
".csv");
197 if(!enabled){Check(!std::filesystem::exists(csv),"disabled process never captures");std::cout<<"Disabled profiler: passed\n";return 0;}
198
199 const auto savedBytes=std::filesystem::file_size(csv);
200 std::ofstream("render-profile.capture").close();
201 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
202 profiler.EndFrame();
203 std::filesystem::remove("render-profile.capture");
204 profiler.BeginFrame(device.
Device(),device.
Context(),64,64,1,
false,.016);
205 profiler.Reset();
206 Check(std::filesystem::file_size(csv)==savedBytes,"reset preserves prior capture and writes header only once");
207 std::ifstream input(csv);Check(bool(input),"open timing CSV");std::string line;std::getline(input,line);
208 unsigned gpu=0,cpu=0,nested=0,overflow=0,memorySamples=0;
209 std::map<unsigned long long,unsigned> accumulatedRows;
210 while(std::getline(input,line))
211 {
212 const auto fields=Split(line);Check(fields.size()==63,"complete CSV row with collection timings, markers and flight context");
213 Check(fields[59].empty() && fields[60]=="unknown","unprovided flight motion stays unknown across ring reuse");
214 const float clearance=std::stof(fields[22]);
215 const auto remainder=(std::stoull(fields[0])-1)%3;
216 Check(clearance==(remainder==0 ? .125f : remainder==1 ? 0.f : -1.f),"clearance metadata/reset");
217 const bool hasWork=(std::stoull(fields[0])-1)%2==0;
218 Check(fields[45]==(hasWork ? "1" : "-1") && std::stod(fields[46])==(hasWork ? 2.5 : 0) &&
219 std::stod(fields[47])==(hasWork ? 8.5 : 0) && std::stod(fields[48])==(hasWork ? .75 : 0),"cloud flight metadata/reset");
220 Check(std::stod(fields[49])==(hasWork ? 7 : 0) && std::stoul(fields[50])==(hasWork ? 2u : 0u),"asynchronous billboard work/reset");
221 const bool inner=fields[16]=="Clear",inclusive=inner || fields[16]=="Clear group" || fields[16]=="GPU frame";
222 const bool accumulated=fields[16]=="Repeated CPU work";
223 const unsigned repeated=accumulated || fields[16]=="GPU frame" ? 120u : 0u;
224 Check(std::stoull(fields[23])==(hasWork && inclusive ? (inner ? 1u : 2u) : 0u)+repeated,"inclusive draw counts/reset");
225 Check(std::stoull(fields[24])==(hasWork && inclusive ? (inner ? 3u : 13u) : 0u)+repeated,"inclusive primitive counts/reset");
226 Check(std::stoull(fields[25])==(hasWork && inclusive ? 1u : 0u)+repeated,"inclusive upload counts/reset");
227 Check(std::stoull(fields[26])==(hasWork && inclusive ? 32u : 0u)+repeated*4,"inclusive upload bytes/reset");
228 Check(std::stod(fields[27])>=0,"nonnegative shader binding duration");
229 Check(fields[28]==(accumulated ? "aggregate" : "scope"),"cross-pass aggregate kind");
230 Check(std::stoul(fields[29])==(accumulated ? 120u : 1u),"calls reset each frame");
231 Check(std::stoull(fields[30])==(hasWork && inclusive ? 64u : 0u)+repeated*16,"inclusive buffer payload/reset");
232 Check(std::stoull(fields[31])==(hasWork && inclusive ? 128u : 0u)+repeated*32,"inclusive texture payload/reset");
233 if(fields[41]=="1"){Check(std::stoull(fields[32])>0 && std::stoull(fields[33])>0,"valid process memory");++memorySamples;}
234 if(fields[42]=="1")Check(std::stoull(fields[36])>0,"valid system memory");
235 Check(std::stod(fields[51])>=0 && std::stod(fields[52])>=0 && std::stod(fields[53])>=0,"explicit collection timings");
236 Check(std::stod(fields[55])>=-1,"explicit memory sample age or unavailable");
237 Check(fields[43]=="0" || fields[43]=="1","explicit GPU memory availability");
238 if(!hasWork || !inclusive)Check(std::stod(fields[27])==0,"shader binding duration reset");
239 Check(fields[8]=="3" && fields[10]=="1","scene metadata");
240 Check(std::stod(fields[17])>=0,"nonnegative CPU duration");
241 if(fields[19]=="1"){Check(!fields[18].empty() && std::stod(fields[18])>=0,"valid GPU duration");++gpu;}
242 if(fields[16]=="CPU update" || fields[16]=="Present wait"){Check(fields[18].empty() && fields[19]=="0","CPU-only scopes have no GPU duration");++cpu;}
243 if(fields[16]=="Clear"){Check(fields[15]=="2","nested pass parent");++nested;}
244 if(accumulated)
245 {
246 Check(fields[15]=="-1" && fields[18].empty() && fields[19]=="0","accumulated CPU row has no GPU query or single parent");
247 Check(std::stod(fields[17])>0,"repeated CPU calls accumulated duration");
248 Check(++accumulatedRows[std::stoull(fields[0])]==1,"one accumulated row per captured frame");
249 if(std::stoull(fields[0])!=41 && std::stoull(fields[0])!=51)Check(fields[20]=="0","repeated calls do not exhaust event budget");
250 }
251 if(std::stoi(fields[20])>0)++overflow;
252 }
253 Check(gpu>10 && cpu>10 && nested>10,"delayed queries delivered");Check(overflow>0,"bounded event overflow recorded");
254 Check(accumulatedRows.size()==nested,"accumulated counters reset on every frame");
255 Check(memorySamples>0,"background memory samples delivered");
256 Check(std::filesystem::exists(root/"outputs"/("render-profile-"+std::to_string(GetCurrentProcessId())+".status.json")),"terminal drop counters persisted");
257 std::cout<<(warp ? "WARP" : "Hardware")<<" profiler: passed ("<<gpu<<" GPU rows, "<<cpu<<" CPU rows, "<<nested<<" nested rows)\n";
258 return 0;
259 }
260 catch(const std::exception& error){std::cerr<<error.what()<<'\n';return 1;}
261}
ID3D11DeviceContext * Context() const
ID3D11Device * Device() const
HRESULT Create(const DeviceOptions11 &options={})
static FrameProfiler11 & Get()