Rise
The Vieneo Province
Loading...
Searching...
No Matches
FrameProfiler11.h
Go to the documentation of this file.
1#pragma once
2// Opt-in, immediate-context diagnostics. Queries are read on later frames with
3// DONOTFLUSH; a full ring drops samples instead of stalling the game.
4#include <d3d11.h>
5#include <dxgi1_4.h>
6#include <psapi.h>
7#include <wrl/client.h>
8#include <array>
9#include <cstdio>
10#include <cwchar>
11#include <cwctype>
12#include <cstring>
13#include <share.h>
14#include <memory>
15#include <atomic>
16#include <mutex>
17#include <thread>
18#include <algorithm>
19#include <cmath>
20#include <vector>
21#include <winver.h>
22#include "BoundedSpscQueue.h"
23#pragma comment(lib,"version.lib")
24
25namespace Rendering
26{
27 // Private-device preparation must never append events to the UI thread's
28 // profiler or issue queries on its immediate context.
29 inline thread_local bool isolatedFrameProfiler11=false;
38 {
39 static constexpr unsigned RingSize=8, MaxEvents=1024, MaxGpuEvents=192;
40 static constexpr unsigned WriterQueueSize=32, OutputBufferBytes=1024*1024;
41 using Query=Microsoft::WRL::ComPtr<ID3D11Query>;
43 struct Work
44 {
46 LONGLONG bindTicks=0;
48 };
52 struct Memory
53 {
54 LONGLONG sampled=0;
57 bool processValid=false,systemValid=false,localValid=false,sharedValid=false;
58 };
59 struct Event
60 {
61 char name[128]{};
62 int gpuIndex=-1;
63 int parent=-1;
64 LONGLONG cpuStart=0;
65 double cpuMs=0;
66 UINT64 first=0,last=0;
68 bool gpu=false,closed=false,accumulated=false;
69 unsigned calls=0;
70 };
71 struct FrameData
72 {
73 std::array<Event,MaxEvents> events;
74 unsigned count=0,gpuCount=0,width=0,height=0,samples=0,overflow=0;
75 UINT64 number=0;
79 unsigned deviceEpoch=0;
86 int vehicle=-1,above=-1,outside=-1,dock=-1,rain=-1;
87 bool vsync=false,pending=false,gpuStarted=false,gpuEnded=false;
88 LONGLONG cpuStart=0;
90 double beginMs=0,pollMs=0,enqueueMs=0;
91 };
93 {
95 std::array<GpuQueries,MaxGpuEvents> queries;
96 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timing{};
97 unsigned readEvent=0;
98 bool timingRead=false,valid=false;
99 };
101 {
103 bool valid=false;
104 };
106 {
107 wchar_t text[256]{};
108 double seconds=0,altitude=0;
109 UINT64 frame=0;
110 unsigned channel=0;
111 };
112 // Detailed CPU trees need more rows, not more GPU queries. Allocate
113 // both bounded pools only when an opted-in capture actually starts.
114 std::unique_ptr<std::array<Frame,RingSize>> ring;
115 Frame* current=nullptr;
116 ID3D11Device* device=nullptr;
117 ID3D11DeviceContext* context=nullptr;
118 Microsoft::WRL::ComPtr<IDXGIAdapter3> adapter;
120 {
121 DXGI_ADAPTER_DESC gpu{};
122 bool valid=false;
123 };
124 // Appended only before starting a writer, after the previous writer has
125 // joined. Epochs keep earlier frames identifiable across device recovery.
126 std::vector<DeviceMetadata> devices;
127 char clientVersion[64]{};
128 bool versionRead=false;
130 LONGLONG lastMemory=0;
131 // The worker owns the file and sampling calls. Only plain snapshots
132 // cross threads; D3D11 immediate-context queries stay on the frame thread.
134 std::unique_ptr<OutputQueue> outputQueue;
135 // GUI submission is the single producer; markers survive a full frame
136 // queue and need no GPU result or active frame to reach the writer.
138 std::atomic<UINT64> markersDropped{0};
139 double lastAltitude=0;
140 std::thread writer;
141 HANDLE wake=nullptr;
142 std::atomic<bool> stopping{false},captureRequested{false},ioFailed{false};
143 std::mutex memoryMutex;
145 FILE* output=nullptr;
146 std::atomic<UINT64> writerDropped{0};
147 unsigned pollNext=0;
148 double pollMs=0,enqueueMs=0;
149 unsigned next=0;
150 int parent=-1,gpuFrame=-1;
151 UINT64 sequence=0;
152 std::atomic<UINT64> dropped{0};
154 bool optedIn=false,autoCapture=false,failed=false,fileStarted=false;
155 unsigned displayDepth=0;
156
157 static void CopyName(Event& event,const char* name)
158 {
159 // Frames are written asynchronously: never retain pointers into a
160 // cockpit/page that may be destroyed before the GPU query drains.
161 strncpy_s(event.name,name ? name : "",_TRUNCATE);
162 for(char* c=event.name;*c;++c)if(*c==',' || *c=='\r' || *c=='\n')*c=' ';
163 }
164
165 static LONGLONG Now() {LARGE_INTEGER value{};QueryPerformanceCounter(&value);return value.QuadPart;}
166 static bool HasFlag(const wchar_t* flag)
167 {
168 const wchar_t* command=GetCommandLineW();const size_t length=wcslen(flag);
169 for(const wchar_t* at=command;(at=wcsstr(at,flag))!=nullptr;++at)
170 if((at==command || iswspace(at[-1]) || at[-1]==L'\"') &&
171 (!at[length] || iswspace(at[length]) || at[length]==L'\"'))return true;
172 return false;
173 }
174 double Ms(LONGLONG ticks) const {return 1000.*double(ticks)/double(frequency);}
176 {
177 if(versionRead)return;
178 versionRead=true;
179 wchar_t path[32768]{};
180 const DWORD length=GetModuleFileNameW(nullptr,path,32768);
181 if(!length || length>=32768)return;
182 const DWORD size=GetFileVersionInfoSizeW(path,nullptr);
183 if(!size)return;
184 std::vector<BYTE> data(size);
185 if(!GetFileVersionInfoW(path,0,size,data.data()))return;
186 VS_FIXEDFILEINFO* info=nullptr;UINT bytes=0;
187 if(!VerQueryValueW(data.data(),L"\\",reinterpret_cast<void**>(&info),&bytes) ||
188 bytes<sizeof(*info) || info->dwSignature!=0xfeef04bd)return;
189 sprintf_s(clientVersion,"%u.%u.%u.%u",unsigned(HIWORD(info->dwFileVersionMS)),unsigned(LOWORD(info->dwFileVersionMS)),
190 unsigned(HIWORD(info->dwFileVersionLS)),unsigned(LOWORD(info->dwFileVersionLS)));
191 }
192 static void WriteJsonString(FILE* file,const wchar_t* value)
193 {
194 char utf8[1024]{};
195 WideCharToMultiByte(CP_UTF8,0,value,-1,utf8,sizeof(utf8),nullptr,nullptr);
196 fputc('"',file);
197 for(const unsigned char* p=reinterpret_cast<const unsigned char*>(utf8);*p;++p)
198 if(*p=='"' || *p=='\\'){fputc('\\',file);fputc(*p,file);}
199 else if(*p<32)fprintf(file,"\\u%04x",unsigned(*p));
200 else fputc(*p,file);
201 fputc('"',file);
202 }
203 void WriteStatus(FILE* file,bool writerStopped)
204 {
205 fprintf(file,"{\"schema_version\":2,\"client_version\":");
206 if(*clientVersion)fprintf(file,"\"%s\"",clientVersion);else fputs("null",file);
207 fprintf(file,",\"process_bits\":%u,\"devices\":[",unsigned(sizeof(void*)*8));
208 for(size_t i=0;i<devices.size();++i)
209 {
210 if(i)fputc(',',file);
211 const auto& gpu=devices[i];
212 fprintf(file,"{\"device_epoch\":%u,\"gpu_valid\":%s,\"gpu\":",unsigned(i+1),gpu.valid ? "true" : "false");
213 if(gpu.valid)WriteJsonString(file,gpu.gpu.Description);else fputs("null",file);
214 fprintf(file,",\"vendor_id\":%u,\"device_id\":%u,\"dedicated_video_memory_bytes\":%llu}",
215 gpu.gpu.VendorId,gpu.gpu.DeviceId,UINT64(gpu.gpu.DedicatedVideoMemory));
216 }
217 fprintf(file,"],\"dropped\":%llu,\"writer_dropped\":%llu,\"markers_dropped\":%llu,\"output_failed\":%s,"
218 "\"writer_stopped\":%s,\"checkpoint_seconds\":%.6f,\"buffering\":{\"gpu_ring_frames\":%u,"
219 "\"writer_queue_frames\":%u,\"stdio_buffer_bytes\":%u,\"flush_interval_ms\":1000}}\n",
220 dropped.load(),writerDropped.load(),markersDropped.load(),ioFailed.load() ? "true" : "false",
221 writerStopped ? "true" : "false",double(Now()-started)/double(frequency),RingSize,WriterQueueSize,OutputBufferBytes);
222 }
223 void PersistStatus(bool writerStopped)
224 {
225 // Replace a complete snapshot so termination during a checkpoint
226 // leaves the previous valid JSON. Never perform this on the UI thread.
227 wchar_t path[128]{},temporary[128]{};
228 swprintf_s(path,L"outputs/render-profile-%lu.status.json",GetCurrentProcessId());
229 swprintf_s(temporary,L"outputs/render-profile-%lu.status.json.tmp",GetCurrentProcessId());
230 if(FILE* file=_wfsopen(temporary,L"w",_SH_DENYNO))
231 {
232 WriteStatus(file,writerStopped);
233 const bool written=ferror(file)==0;
234 const bool closed=fclose(file)==0;
235 if(written && closed && MoveFileExW(temporary,path,MOVEFILE_REPLACE_EXISTING))return;
236 }
237 OutputDebugStringW(L"Rise frame profiler: status checkpoint failed; continuing CSV capture.\n");
238 }
240 {
241 const auto now=Now();if(lastMemory && now-lastMemory<frequency)return;
242 lastMemory=now;Memory sample;
243 PROCESS_MEMORY_COUNTERS_EX process{};process.cb=sizeof(process);
244 sample.processValid=K32GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&process),sizeof(process))!=FALSE;
245 if(sample.processValid){sample.workingSet=process.WorkingSetSize;sample.privateBytes=process.PrivateUsage;}
246 MEMORYSTATUSEX system{};system.dwLength=sizeof(system);
247 sample.systemValid=GlobalMemoryStatusEx(&system)!=FALSE;
248 if(sample.systemValid)sample.available=system.ullAvailPhys;
249 PERFORMANCE_INFORMATION performance{};performance.cb=sizeof(performance);
250 sample.systemValid=sample.systemValid && K32GetPerformanceInfo(&performance,sizeof(performance))!=FALSE;
251 if(sample.systemValid){sample.commit=UINT64(performance.CommitTotal)*performance.PageSize;sample.commitLimit=UINT64(performance.CommitLimit)*performance.PageSize;}
252 DXGI_QUERY_VIDEO_MEMORY_INFO info{};
253 sample.localValid=adapter && SUCCEEDED(adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP_LOCAL,&info));
254 if(sample.localValid){sample.localUsage=info.CurrentUsage;sample.localBudget=info.Budget;}
255 sample.sharedValid=adapter && SUCCEEDED(adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL,&info));
256 if(sample.sharedValid){sample.sharedUsage=info.CurrentUsage;sample.sharedBudget=info.Budget;}
257 sample.sampled=Now();
258 std::lock_guard<std::mutex> lock(memoryMutex);sampledMemory=sample;
259 }
260 bool Initialize(ID3D11Device* native,ID3D11DeviceContext* immediate)
261 {
262 device=native;context=immediate;
263 ring=std::make_unique<std::array<Frame,RingSize>>();
264 for(auto& frame:*ring)
265 {
266 D3D11_QUERY_DESC desc{D3D11_QUERY_TIMESTAMP_DISJOINT,0};
267 if(FAILED(device->CreateQuery(&desc,&frame.disjoint)))return false;
268 desc.Query=D3D11_QUERY_TIMESTAMP;
269 for(auto& queries:frame.queries)
270 if(FAILED(device->CreateQuery(&desc,&queries.begin)) || FAILED(device->CreateQuery(&desc,&queries.end)))return false;
271 }
272 return true;
273 }
275 {
276 CreateDirectoryW(L"outputs",nullptr);
277 wchar_t path[128]{};swprintf_s(path,L"outputs/render-profile-%lu.csv",GetCurrentProcessId());
278 output=_wfsopen(path,fileStarted ? L"a" : L"w",_SH_DENYNO);
279 if(!output)return false;
280 fileStarted=true;setvbuf(output,nullptr,_IOFBF,OutputBufferBytes);
281 _fseeki64(output,0,SEEK_END);
282 if(_ftelli64(output)==0)fprintf(output,"frame,seconds,interval_ms,frame_cpu_ms,width,height,msaa,vsync,vehicle,altitude_km,above_clouds,outside,dock_texture,rain,event_index,parent_index,pass,cpu_ms,gpu_ms,gpu_valid,overflow,dropped,cloud_clearance_km,geometry_draws,geometry_primitives,constant_uploads,constant_bytes,shader_bind_cpu_ms,event_kind,calls,buffer_upload_bytes,texture_upload_bytes,working_set_bytes,private_bytes,system_available_bytes,system_commit_bytes,system_commit_limit_bytes,gpu_local_usage_bytes,gpu_local_budget_bytes,gpu_shared_usage_bytes,gpu_shared_budget_bytes,process_memory_valid,system_memory_valid,gpu_local_memory_valid,gpu_shared_memory_valid,volume_clouds,cloud_base_km,cloud_top_km,cloud_density,billboard_decode_ms,billboard_decode_jobs,profiler_begin_ms,profiler_poll_ms,profiler_enqueue_ms,writer_dropped,memory_sample_age_ms,marker_channel,marker_text,fps,vertical_speed_mps,flight_direction,view_mode,device_epoch\n");
283 PersistStatus(false);
284 return true;
285 }
286 void WriteFrame(const OutputFrame& frame)
287 {
288 for(unsigned i=0;i<frame.count;++i)
289 {
290 const auto& event=frame.events[i];
291 fprintf(output,"%llu,%.6f,%.6f,%.6f,%u,%u,%u,%d,%d,%.6f,%d,%d,%d,%d,%u,%d,%s,%.6f,",
292 frame.number,frame.seconds,frame.interval,frame.cpuMs,frame.width,frame.height,frame.samples,
293 int(frame.vsync),frame.vehicle,frame.altitude,frame.above,frame.outside,frame.dock,frame.rain,
294 i,event.parent,event.name,event.cpuMs);
295 if(frame.valid && event.gpu)fprintf(output,"%.6f",1000.*double(event.last-event.first)/double(frame.gpuFrequency));
296 fprintf(output,",%d,%u,%llu,%.6f,%llu,%llu,%llu,%llu,%.6f",int(frame.valid && event.gpu),frame.overflow,frame.droppedTotal,frame.cloudClearance,
297 event.work.draws,event.work.primitives,event.work.uploads,event.work.uploadBytes,Ms(event.work.bindTicks));
298 const auto& m=frame.memory;
299 fprintf(output,",%s,%u,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%d,%d,%d,%d",
300 event.accumulated ? "aggregate" : "scope",event.calls,event.work.bufferBytes,event.work.textureBytes,
301 m.workingSet,m.privateBytes,m.available,m.commit,m.commitLimit,m.localUsage,m.localBudget,m.sharedUsage,m.sharedBudget,
302 int(m.processValid),int(m.systemValid),int(m.localValid),int(m.sharedValid));
303 fprintf(output,",%d,%.6f,%.6f,%.6f,%.6f,%u,%.6f,%.6f,%.6f,%llu,%.6f,,\"\",",frame.volumeClouds,frame.cloudBase,frame.cloudTop,
305 frame.memory.sampled ? Ms(frame.cpuStart-frame.memory.sampled) : -1.);
306 if(frame.interval>0 && std::isfinite(frame.interval))fprintf(output,"%.6f",1000./frame.interval);
307 fputc(',',output);
308 if(frame.verticalSpeedValid)fprintf(output,"%.6f",frame.verticalSpeedMps);
309 const char* direction=!frame.verticalSpeedValid ? "unknown" : frame.verticalSpeedMps>0 ? "ascending" :
310 frame.verticalSpeedMps<0 ? "descending" : "level";
311 fprintf(output,",%s,%s,%u\n",direction,frame.outside<0 ? "unknown" : frame.outside ? "exterior" : "cockpit",frame.deviceEpoch);
312 }
313 }
314 void WriteMarker(const ChatMarker& marker)
315 {
316 // Keep one physical UTF-8 CSV line, quoting commas and quotes. No
317 // spreadsheet formulas are interpreted by the diagnostic readers.
318 char utf8[1024]{};
319 WideCharToMultiByte(CP_UTF8,0,marker.text,-1,utf8,sizeof(utf8),nullptr,nullptr);
320 for(unsigned column=0;column<58;++column)
321 {
322 if(column)fputc(',',output);
323 switch(column)
324 {
325 case 0:fprintf(output,"%llu",marker.frame);break;
326 case 1:fprintf(output,"%.6f",marker.seconds);break;
327 case 9:fprintf(output,"%.6f",marker.altitude);break;
328 case 14:case 15:fputs("-1",output);break;
329 case 16:fputs("Tester chat",output);break;
330 case 18:break;
331 case 21:fprintf(output,"%llu",dropped.load());break;
332 case 28:fputs("marker",output);break;
333 case 54:fprintf(output,"%llu",writerDropped.load());break;
334 case 56:fprintf(output,"%u",marker.channel);break;
335 case 57:
336 fputc('"',output);
337 for(const char* p=utf8;*p;++p){if(*p=='"')fputc('"',output);fputc(*p=='\r' || *p=='\n' ? ' ' : *p,output);}
338 fputc('"',output);break;
339 default:fputc('0',output);break;
340 }
341 }
342 // Markers are annotations, not sampled flight or timing state.
343 fputs(",,,,,\n",output);
344 }
346 {
347 try
348 {
350 LONGLONG lastTrigger=0;
351 while(true)
352 {
353 const auto now=Now();
354 if(!lastTrigger || now-lastTrigger>=frequency/10)
355 {
356 captureRequested.store(autoCapture || GetFileAttributesW(L"render-profile.capture")!=INVALID_FILE_ATTRIBUTES,std::memory_order_release);
357 lastTrigger=now;
358 }
359 if(captureRequested.load(std::memory_order_acquire) && !stopping.load(std::memory_order_acquire))SampleMemory();
360 const auto* frame=outputQueue->Front();
361 if(frame)
362 {
363 if(!ioFailed.load(std::memory_order_relaxed))
364 {
365 if(!output && !OpenOutput())ioFailed.store(true,std::memory_order_release);
366 if(output)
367 {
368 WriteFrame(*frame);
369 if(ferror(output))ioFailed.store(true,std::memory_order_release);
370 }
371 }
372 outputQueue->Release();
373 }
374 const auto* marker=chatQueue.Front();
375 if(marker)
376 {
377 if(!ioFailed.load(std::memory_order_relaxed))
378 {
379 if(!output && !OpenOutput())ioFailed.store(true,std::memory_order_release);
380 if(output){WriteMarker(*marker);if(ferror(output))ioFailed.store(true,std::memory_order_release);}
381 }
383 }
384 if(output && (now-lastFlush>=frequency || stopping.load(std::memory_order_acquire)))
385 {
386 if(fflush(output)!=0)ioFailed.store(true,std::memory_order_release);
387 if(!stopping.load(std::memory_order_acquire))PersistStatus(false);
388 lastFlush=now;
389 }
390 if(!frame && !marker)
391 {
392 if(stopping.load(std::memory_order_acquire))break;
393 WaitForSingleObject(wake,25);
394 }
395 }
396 }
397 catch(...) {ioFailed.store(true,std::memory_order_release);}
398 if(output)
399 {
400 if(fclose(output)!=0)ioFailed.store(true,std::memory_order_release);
401 output=nullptr;
402 }
403 // Persist terminal losses too: a full queue at shutdown may have
404 // no later CSV frame on which to report its updated counters.
405 if(fileStarted)PersistStatus(true);
406 if(ioFailed.load(std::memory_order_acquire))OutputDebugStringW(L"Rise frame profiler: CSV output failed; capture disabled.\n");
407 }
408 bool StartWorker(ID3D11Device* native)
409 {
410 // The initial check preserves capture from the very first frame.
411 // Later trigger checks, memory sampling and all file I/O are off-thread.
412 captureRequested.store(autoCapture || GetFileAttributesW(L"render-profile.capture")!=INVALID_FILE_ATTRIBUTES,std::memory_order_release);
413 device=native;
414 Microsoft::WRL::ComPtr<IDXGIDevice> dxgi;
415 Microsoft::WRL::ComPtr<IDXGIAdapter> base;
416 DeviceMetadata metadata;
417 if(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&dxgi))) && SUCCEEDED(dxgi->GetAdapter(&base)))
418 {
419 base.As(&adapter);metadata.valid=SUCCEEDED(base->GetDesc(&metadata.gpu));
420 }
421 devices.push_back(metadata);
422 outputQueue=std::make_unique<OutputQueue>();
423 wake=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!wake)return false;
424 stopping.store(false,std::memory_order_release);ioFailed.store(false,std::memory_order_release);
425 try {writer=std::thread([this]{WriterLoop();});}
426 catch(...) {CloseHandle(wake);wake=nullptr;return false;}
427 return true;
428 }
429 void Enqueue(Frame& frame)
430 {
431 const auto start=Now();
432 if(auto* snapshot=outputQueue->Reserve())
433 {
434 static_cast<FrameData&>(*snapshot)=static_cast<const FrameData&>(frame);
435 snapshot->gpuFrequency=frame.timing.Frequency;snapshot->valid=frame.valid;
436 snapshot->droppedTotal=dropped;snapshot->writerDropped=writerDropped;
437 outputQueue->Publish();SetEvent(wake);
438 }
439 else {++dropped;++writerDropped;}
440 frame.pending=false;enqueueMs+=Ms(Now()-start);
441 }
442 void Poll()
443 {
444 pollMs=enqueueMs=0;if(!context || !ring)return;
445 const auto start=Now();const auto budget=(std::max)(LONGLONG(1),frequency/1000);
446 // Bound total collection work to approximately 1 ms. A driver call
447 // itself cannot be preempted; its elapsed time remains visible.
448 for(unsigned scanned=0;scanned<RingSize && Now()-start<budget;++scanned)
449 {
450 auto& frame=(*ring)[pollNext++%RingSize];if(!frame.pending)continue;
451 if(!frame.timingRead)
452 {
453 frame.valid=frame.gpuStarted && frame.gpuEnded;
454 if(frame.valid)
455 {
456 const HRESULT hr=context->GetData(frame.disjoint.Get(),&frame.timing,sizeof(frame.timing),D3D11_ASYNC_GETDATA_DONOTFLUSH);
457 if(hr==S_FALSE)continue;
458 frame.valid=hr==S_OK && !frame.timing.Disjoint && frame.timing.Frequency!=0;
459 }
460 frame.timingRead=true;
461 }
462 bool ready=true;
463 while(frame.valid && frame.readEvent<frame.count)
464 {
465 auto& event=frame.events[frame.readEvent];
466 if(!event.gpu){++frame.readEvent;continue;}
467 if(!event.closed){frame.valid=false;break;}
468 if(Now()-start>=budget){ready=false;break;}
469 const auto& queries=frame.queries[event.gpuIndex];
470 const HRESULT a=context->GetData(queries.begin.Get(),&event.first,sizeof(event.first),D3D11_ASYNC_GETDATA_DONOTFLUSH);
471 const HRESULT b=context->GetData(queries.end.Get(),&event.last,sizeof(event.last),D3D11_ASYNC_GETDATA_DONOTFLUSH);
472 if(a==S_FALSE || b==S_FALSE){ready=false;break;}
473 if(FAILED(a) || FAILED(b) || event.last<event.first){frame.valid=false;break;}
474 ++frame.readEvent;
475 }
476 if(ready)Enqueue(frame);
477 }
478 pollMs=Ms(Now()-start);
479 }
480 public:
482 {
483 int index=-1;
484 UINT64 frame=0;
485 LONGLONG start=0;
487 };
489 {
490 LARGE_INTEGER value{};QueryPerformanceFrequency(&value);frequency=value.QuadPart;
492 // Merely shipping this instrumentation does not enable it.
493 autoCapture=HasFlag(L"--profile-flight");
494 optedIn=autoCapture || HasFlag(L"--profile-render");
495 }
500 {
501 if(isolatedFrameProfiler11){static thread_local FrameProfiler11 isolated;return isolated;}
502 static FrameProfiler11 profiler;return profiler;
503 }
504 void Reset()
505 {
506 current=nullptr;parent=gpuFrame=-1;displayDepth=0;
507 // Shutdown/device recovery may join the writer; active gameplay never
508 // waits for it. Preserve unresolved CPU samples with invalid GPU data.
509 if(ring && outputQueue)for(auto& frame:*ring)if(frame.pending){frame.valid=false;Enqueue(frame);}
510 stopping.store(true,std::memory_order_release);if(wake)SetEvent(wake);
511 if(writer.joinable())writer.join();
512 if(wake){CloseHandle(wake);wake=nullptr;}
513 outputQueue.reset();ring.reset();
514 adapter.Reset();memory={};sampledMemory={};lastMemory=0;
515 device=nullptr;context=nullptr;next=pollNext=0;
516 }
517 void BeginFrame(ID3D11Device* native,ID3D11DeviceContext* immediate,UINT width,UINT height,UINT samples,bool vsync,double interval)
518 {
519 if(!optedIn || failed)return;
520 const auto begin=Now();
521 if(device && device!=native)Reset();
522 if(!writer.joinable() && !StartWorker(native)){Reset();failed=true;return;}
523 if(ioFailed.load(std::memory_order_acquire)){failed=true;return;}
524 Poll();
525 if(!captureRequested.load(std::memory_order_acquire))return;
526 if(!ring && !Initialize(native,immediate)){Reset();failed=true;return;}
527 {std::unique_lock<std::mutex> lock(memoryMutex,std::try_to_lock);if(lock.owns_lock())memory=sampledMemory;}
528 auto& frame=(*ring)[next];++sequence;
529 if(frame.pending){++dropped;return;}
530 next=(next+1)%RingSize;
531 frame.count=frame.gpuCount=frame.overflow=frame.readEvent=0;frame.gpuStarted=frame.gpuEnded=frame.timingRead=frame.valid=false;frame.timing={};
532 frame.number=sequence;frame.width=width;frame.height=height;frame.samples=samples;frame.vsync=vsync;
533 frame.vehicle=frame.above=frame.outside=frame.dock=frame.rain=-1;frame.altitude=0;
534 frame.verticalSpeedMps=0;frame.verticalSpeedValid=false;frame.deviceEpoch=unsigned(devices.size());
535 frame.cloudClearance=-1;
536 frame.volumeClouds=-1;frame.cloudBase=frame.cloudTop=frame.cloudDensity=0;
537 frame.billboardDecodeMs=0;frame.billboardDecodeJobs=0;
538 frame.work={};
539 frame.memory=memory;
540 frame.interval=interval*1000;frame.cpuStart=Now();frame.seconds=double(frame.cpuStart-started)/double(frequency);
541 frame.beginMs=Ms(frame.cpuStart-begin);frame.pollMs=pollMs;frame.enqueueMs=enqueueMs;
542 current=&frame;parent=gpuFrame=-1;
543 }
544 void Scene(int vehicle,double altitude,bool above,bool outside,int dock,int rain)
545 {
546 lastAltitude=altitude;
547 if(!current)return;
548 current->vehicle=vehicle;current->altitude=altitude;current->above=above;current->outside=outside;
549 current->dock=dock;current->rain=rain;
550 }
551 // Existing VSI bus estimate, in metres/second. No Earth-specific flight
552 // envelope or altitude cutoff: record ground, ascent, orbit and re-entry.
553 void FlightMotion(double verticalSpeedMps,bool valid)
554 {
555 if(!current)return;
556 current->verticalSpeedValid=valid && std::isfinite(verticalSpeedMps);
557 current->verticalSpeedMps=current->verticalSpeedValid ? verticalSpeedMps : 0;
558 }
559 // Call on the frame/UI thread for the tester's own submitted text,
560 // before radio garbling. This does not capture received chat/commands.
561 void RecordChat(const wchar_t* message,unsigned channel)
562 {
563 if(!optedIn || failed || !writer.joinable() || !captureRequested.load(std::memory_order_acquire) ||
564 ioFailed.load(std::memory_order_acquire) || !message || !*message)return;
565 if(auto* marker=chatQueue.Reserve())
566 {
567 wcsncpy_s(marker->text,message,_TRUNCATE);
568 const size_t size=wcslen(marker->text);
569 if(size && marker->text[size-1]>=0xd800 && marker->text[size-1]<=0xdbff)marker->text[size-1]=0;
570 marker->seconds=double(Now()-started)/double(frequency);
571 marker->frame=sequence;marker->altitude=lastAltitude;marker->channel=channel;
572 chatQueue.Publish();SetEvent(wake);
573 }
574 else ++markersDropped;
575 }
576 void CloudClearance(float radiusKm) {if(current)current->cloudClearance=radiusKm;}
577 void CloudScene(bool volume,float base,float top,float density)
579 // Worker elapsed time is reported on the frame that consumes its result;
580 // it overlaps frame-thread work and must never be added to the CPU tree.
581 void BillboardDecode(double milliseconds)
583 // Accumulate hot-path diagnostics without allocating a query/event per
584 // draw. Each scope records an inclusive delta, like its timing fields.
585 void GeometryDraw(UINT primitives) {if(current){++current->work.draws;current->work.primitives+=primitives;}}
586 void ConstantUpload(UINT bytes) {if(current){++current->work.uploads;current->work.uploadBytes+=bytes;}}
587 void BufferUpload(UINT64 bytes) {if(current)current->work.bufferBytes+=bytes;}
588 void TextureUpload(UINT64 bytes) {if(current)current->work.textureBytes+=bytes;}
589 LONGLONG BeginShaderBind() const {return current ? Now() : 0;}
590 void EndShaderBind(LONGLONG start) {if(current && start)current->work.bindTicks+=Now()-start;}
591 // Repeated CPU preparation calls share one row per frame, with no GPU
592 // timestamps or stack changes. Parent=-1 prevents a misleading single
593 // parent when calls originate in several different render passes.
595 {
596 if(!current)return {};
597 int index=-1;
598 for(unsigned i=0;i<current->count;++i)
599 if(current->events[i].accumulated && std::strcmp(current->events[i].name,name)==0)
600 {index=int(i);break;}
601 if(index<0)
602 {
603 if(current->count==MaxEvents){++current->overflow;return {};}
604 index=int(current->count++);auto& event=current->events[index];
605 CopyName(event,name);event.parent=-1;event.cpuMs=0;event.work={};event.calls=0;
606 event.gpu=false;event.closed=event.accumulated=true;
607 }
608 return {index,current->number,Now(),current->work};
609 }
610 void EndAccumulatedCpu(const CpuSample& sample)
611 {
612 if(!current || sample.index<0 || sample.frame!=current->number || unsigned(sample.index)>=current->count)return;
613 auto& event=current->events[sample.index];event.cpuMs+=Ms(Now()-sample.start);
614 ++event.calls;
615 const auto& work=current->work;const auto& start=sample.startWork;
616 event.work.draws+=work.draws-start.draws;event.work.primitives+=work.primitives-start.primitives;
617 event.work.uploads+=work.uploads-start.uploads;event.work.uploadBytes+=work.uploadBytes-start.uploadBytes;
618 event.work.bindTicks+=work.bindTicks-start.bindTicks;
619 event.work.bufferBytes+=work.bufferBytes-start.bufferBytes;event.work.textureBytes+=work.textureBytes-start.textureBytes;
620 }
621 bool Capturing() const {return current!=nullptr;}
622 bool DisplayDetailActive() const {return current && displayDepth!=0;}
625 int BeginCpu(const char* name,const char* detail=nullptr,bool displayOnly=false)
626 {
627 if(!current || (displayOnly && !displayDepth))return -1;
628 char label[128];
629 if(detail)snprintf(label,sizeof(label),"%s: %s",name,detail);
630 else strncpy_s(label,name,_TRUNCATE);
631 for(char* c=label;*c;++c)if(*c==',' || *c=='\r' || *c=='\n')*c=' ';
632 return Begin(label,false,true);
633 }
634 int Begin(const char* name,bool gpu=true,bool mergeCpu=false)
635 {
636 if(!current)return -1;
637 // Repeated text/queue/flush calls retain their actual parent and
638 // nested children, but use one row per name and parent per frame.
639 if(mergeCpu)for(int i=int(current->count)-1;i>parent;--i)
640 {
641 auto& event=current->events[i];
642 if(event.closed && !event.gpu && !event.accumulated && event.parent==parent && !strcmp(event.name,name))
643 {
644 event.closed=false;event.cpuStart=Now();event.startWork=current->work;
645 ++event.calls;parent=i;return i;
646 }
647 }
648 if(current->count==MaxEvents){++current->overflow;return -1;}
649 const int index=int(current->count++);auto& event=current->events[index];
650 CopyName(event,name);event.parent=parent;event.closed=event.accumulated=false;event.cpuStart=Now();event.cpuMs=0;
651 event.startWork=current->work;event.work={};
652 event.calls=1;
653 event.gpu=gpu && current->gpuStarted && !current->gpuEnded;
654 if(event.gpu && current->gpuCount==MaxGpuEvents){event.gpu=false;++current->overflow;}
655 event.gpuIndex=event.gpu ? int(current->gpuCount++) : -1;
656 if(event.gpu)context->End(current->queries[event.gpuIndex].begin.Get());
657 parent=index;return index;
658 }
659 void End(int index)
660 {
661 if(!current || index<0 || unsigned(index)>=current->count)return;
662 auto& event=current->events[index];if(event.closed)return;
663 if(event.gpu)context->End(current->queries[event.gpuIndex].end.Get());
664 event.cpuMs+=Ms(Now()-event.cpuStart);event.closed=true;parent=event.parent;
665 const auto& work=current->work;const auto& start=event.startWork;
666 const auto delta=Delta(work,start);
667 event.work.draws+=delta.draws;event.work.primitives+=delta.primitives;
668 event.work.uploads+=delta.uploads;event.work.uploadBytes+=delta.uploadBytes;
669 event.work.bindTicks+=delta.bindTicks;event.work.bufferBytes+=delta.bufferBytes;event.work.textureBytes+=delta.textureBytes;
670 }
671 void BeginGpu()
672 {
673 if(!current)return;
674 context->Begin(current->disjoint.Get());current->gpuStarted=true;
675 gpuFrame=Begin("GPU frame");
676 }
677 void EndGpu()
678 {
679 if(!current || !current->gpuStarted || current->gpuEnded)return;
680 End(gpuFrame);context->End(current->disjoint.Get());current->gpuEnded=true;
681 }
682 void EndFrame()
683 {
684 if(!current)return;
686 }
687 };
697 {
698 int index;
699 public:
700 explicit ProfileCpuScope11(const char* name,const char* detail=nullptr,bool displayOnly=false)
701 :index(FrameProfiler11::Get().BeginCpu(name,detail,displayOnly)){}
706 };
708 {
709 public:
710 explicit ProfileDisplayCpu11(const char* name):ProfileCpuScope11(name,nullptr,true){}
711 };
731 {
732 int index;
733 public:
734 explicit ProfileScope11(const char* name,bool gpu=true):index(FrameProfiler11::Get().Begin(name,gpu)){}
739 };
740}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
static constexpr unsigned MaxEvents
std::atomic< UINT64 > writerDropped
void EndAccumulatedCpu(const CpuSample &sample)
static bool HasFlag(const wchar_t *flag)
Microsoft::WRL::ComPtr< IDXGIAdapter3 > adapter
Microsoft::WRL::ComPtr< ID3D11Query > Query
static void WriteJsonString(FILE *file, const wchar_t *value)
void GeometryDraw(UINT primitives)
void Scene(int vehicle, double altitude, bool above, bool outside, int dock, int rain)
std::atomic< bool > captureRequested
void WriteStatus(FILE *file, bool writerStopped)
void EndShaderBind(LONGLONG start)
std::atomic< bool > stopping
void PersistStatus(bool writerStopped)
static Work Delta(const Work &a, const Work &b)
CpuSample BeginAccumulatedCpu(const char *name)
static constexpr unsigned RingSize
void TextureUpload(UINT64 bytes)
FrameProfiler11(const FrameProfiler11 &)=delete
static constexpr unsigned WriterQueueSize
static constexpr unsigned MaxGpuEvents
std::unique_ptr< std::array< Frame, RingSize > > ring
BoundedSpscQueue< OutputFrame, WriterQueueSize > OutputQueue
int Begin(const char *name, bool gpu=true, bool mergeCpu=false)
double Ms(LONGLONG ticks) const
BoundedSpscQueue< ChatMarker, 64 > chatQueue
FrameProfiler11 & operator=(const FrameProfiler11 &)=delete
std::atomic< UINT64 > dropped
static constexpr unsigned OutputBufferBytes
void CloudScene(bool volume, float base, float top, float density)
std::vector< DeviceMetadata > devices
void BillboardDecode(double milliseconds)
void CloudClearance(float radiusKm)
void FlightMotion(double verticalSpeedMps, bool valid)
void WriteMarker(const ChatMarker &marker)
int BeginCpu(const char *name, const char *detail=nullptr, bool displayOnly=false)
bool StartWorker(ID3D11Device *native)
ID3D11DeviceContext * context
bool Initialize(ID3D11Device *native, ID3D11DeviceContext *immediate)
LONGLONG BeginShaderBind() const
void RecordChat(const wchar_t *message, unsigned channel)
std::atomic< UINT64 > markersDropped
void ConstantUpload(UINT bytes)
static void CopyName(Event &event, const char *name)
void WriteFrame(const OutputFrame &frame)
static FrameProfiler11 & Get()
std::unique_ptr< OutputQueue > outputQueue
void BufferUpload(UINT64 bytes)
void BeginFrame(ID3D11Device *native, ID3D11DeviceContext *immediate, UINT width, UINT height, UINT samples, bool vsync, double interval)
std::atomic< bool > ioFailed
ProfileAccumulatedCpu11 & operator=(const ProfileAccumulatedCpu11 &)=delete
ProfileAccumulatedCpu11(const ProfileAccumulatedCpu11 &)=delete
FrameProfiler11::CpuSample sample
ProfileCpuScope11(const char *name, const char *detail=nullptr, bool displayOnly=false)
ProfileCpuScope11 & operator=(const ProfileCpuScope11 &)=delete
ProfileCpuScope11(const ProfileCpuScope11 &)=delete
ProfileDisplayCpu11(const char *name)
ProfileDisplayDetail11 & operator=(const ProfileDisplayDetail11 &)=delete
ProfileDisplayDetail11(const ProfileDisplayDetail11 &)=delete
ProfileScope11(const ProfileScope11 &)=delete
ProfileScope11 & operator=(const ProfileScope11 &)=delete
ProfileScope11(const char *name, bool gpu=true)
ProfileShaderBind11 & operator=(const ProfileShaderBind11 &)=delete
ProfileShaderBind11(const ProfileShaderBind11 &)=delete
bool isolatedFrameProfiler11
std::array< Event, MaxEvents > events
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timing
std::array< GpuQueries, MaxGpuEvents > queries