23#pragma comment(lib,"version.lib")
41 using Query=Microsoft::WRL::ComPtr<ID3D11Query>;
95 std::array<GpuQueries,MaxGpuEvents>
queries;
96 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT
timing{};
114 std::unique_ptr<std::array<Frame,RingSize>>
ring;
118 Microsoft::WRL::ComPtr<IDXGIAdapter3>
adapter;
161 strncpy_s(event.
name,name ? name :
"",_TRUNCATE);
162 for(
char* c=event.
name;*c;++c)
if(*c==
',' || *c==
'\r' || *c==
'\n')*c=
' ';
165 static LONGLONG
Now() {LARGE_INTEGER value{};QueryPerformanceCounter(&value);
return value.QuadPart;}
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;
174 double Ms(LONGLONG ticks)
const {
return 1000.*double(ticks)/double(
frequency);}
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);
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)));
195 WideCharToMultiByte(CP_UTF8,0,value,-1,utf8,
sizeof(utf8),
nullptr,
nullptr);
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));
205 fprintf(file,
"{\"schema_version\":2,\"client_version\":");
207 fprintf(file,
",\"process_bits\":%u,\"devices\":[",
unsigned(
sizeof(
void*)*8));
208 for(
size_t i=0;i<
devices.size();++i)
210 if(i)fputc(
',',file);
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));
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",
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))
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;
237 OutputDebugStringW(L
"Rise frame profiler: status checkpoint failed; continuing CSV capture.\n");
243 PROCESS_MEMORY_COUNTERS_EX process{};process.cb=
sizeof(process);
244 sample.
processValid=K32GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*
>(&process),
sizeof(process))!=FALSE;
246 MEMORYSTATUSEX system{};system.dwLength=
sizeof(system);
247 sample.
systemValid=GlobalMemoryStatusEx(&system)!=FALSE;
249 PERFORMANCE_INFORMATION performance{};performance.cb=
sizeof(performance);
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{};
260 bool Initialize(ID3D11Device* native,ID3D11DeviceContext* immediate)
263 ring=std::make_unique<std::array<Frame,RingSize>>();
264 for(
auto& frame:*
ring)
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;
276 CreateDirectoryW(L
"outputs",
nullptr);
277 wchar_t path[128]{};swprintf_s(path,L
"outputs/render-profile-%lu.csv",GetCurrentProcessId());
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");
288 for(
unsigned i=0;i<frame.
count;++i)
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,",
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,
319 WideCharToMultiByte(CP_UTF8,0,marker.
text,-1,utf8,
sizeof(utf8),
nullptr,
nullptr);
320 for(
unsigned column=0;column<58;++column)
322 if(column)fputc(
',',
output);
328 case 14:
case 15:fputs(
"-1",
output);
break;
329 case 16:fputs(
"Tester chat",
output);
break;
332 case 28:fputs(
"marker",
output);
break;
337 for(
const char* p=utf8;*p;++p){
if(*p==
'"')fputc(
'"',
output);fputc(*p==
'\r' || *p==
'\n' ?
' ' : *p,
output);}
339 default:fputc(
'0',
output);
break;
350 LONGLONG lastTrigger=0;
353 const auto now=
Now();
354 if(!lastTrigger || now-lastTrigger>=
frequency/10)
356 captureRequested.store(
autoCapture || GetFileAttributesW(L
"render-profile.capture")!=INVALID_FILE_ATTRIBUTES,std::memory_order_release);
363 if(!
ioFailed.load(std::memory_order_relaxed))
377 if(!
ioFailed.load(std::memory_order_relaxed))
386 if(fflush(
output)!=0)
ioFailed.store(
true,std::memory_order_release);
390 if(!frame && !marker)
392 if(
stopping.load(std::memory_order_acquire))
break;
393 WaitForSingleObject(
wake,25);
397 catch(...) {
ioFailed.store(
true,std::memory_order_release);}
400 if(fclose(
output)!=0)
ioFailed.store(
true,std::memory_order_release);
406 if(
ioFailed.load(std::memory_order_acquire))OutputDebugStringW(L
"Rise frame profiler: CSV output failed; capture disabled.\n");
412 captureRequested.store(
autoCapture || GetFileAttributesW(L
"render-profile.capture")!=INVALID_FILE_ATTRIBUTES,std::memory_order_release);
414 Microsoft::WRL::ComPtr<IDXGIDevice> dxgi;
415 Microsoft::WRL::ComPtr<IDXGIAdapter> base;
417 if(SUCCEEDED(
device->QueryInterface(IID_PPV_ARGS(&dxgi))) && SUCCEEDED(dxgi->GetAdapter(&base)))
419 base.As(&
adapter);metadata.
valid=SUCCEEDED(base->GetDesc(&metadata.
gpu));
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);
426 catch(...) {CloseHandle(
wake);
wake=
nullptr;
return false;}
431 const auto start=
Now();
435 snapshot->gpuFrequency=frame.
timing.Frequency;snapshot->valid=frame.
valid;
445 const auto start=
Now();
const auto budget=(std::max)(LONGLONG(1),
frequency/1000);
448 for(
unsigned scanned=0;scanned<
RingSize &&
Now()-start<budget;++scanned)
451 if(!frame.timingRead)
453 frame.valid=frame.gpuStarted && frame.gpuEnded;
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;
460 frame.timingRead=
true;
463 while(frame.valid && frame.readEvent<frame.count)
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;}
490 LARGE_INTEGER value{};QueryPerformanceFrequency(&value);
frequency=value.QuadPart;
517 void BeginFrame(ID3D11Device* native,ID3D11DeviceContext* immediate,UINT width,UINT height,UINT samples,
bool vsync,
double interval)
520 const auto begin=
Now();
529 if(frame.pending){++
dropped;
return;}
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;
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;
544 void Scene(
int vehicle,
double altitude,
bool above,
bool outside,
int dock,
int rain)
564 ioFailed.load(std::memory_order_acquire) || !message || !*message)
return;
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;
577 void CloudScene(
bool volume,
float base,
float top,
float density)
600 {index=
int(i);
break;}
605 CopyName(event,name);
event.parent=-1;
event.cpuMs=0;
event.work={};
event.calls=0;
606 event.gpu=
false;
event.closed=
event.accumulated=
true;
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;
625 int BeginCpu(
const char* name,
const char* detail=
nullptr,
bool displayOnly=
false)
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);
634 int Begin(
const char* name,
bool gpu=
true,
bool mergeCpu=
false)
642 if(event.closed && !event.gpu && !event.accumulated && event.parent==
parent && !strcmp(event.name,name))
644 event.closed=
false;
event.cpuStart=
Now();
event.startWork=
current->
work;
645 ++
event.calls;
parent=i;
return i;
650 CopyName(event,name);
event.parent=
parent;
event.closed=
event.accumulated=
false;
event.cpuStart=
Now();
event.cpuMs=0;
657 parent=index;
return index;
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;
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)
void Enqueue(Frame &frame)
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
void EnterDisplayDetail()
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
void LeaveDisplayDetail()
BoundedSpscQueue< ChatMarker, 64 > chatQueue
bool DisplayDetailActive() const
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
IsolatedFrameProfiler11()
~IsolatedFrameProfiler11()
ProfileAccumulatedCpu11 & operator=(const ProfileAccumulatedCpu11 &)=delete
ProfileAccumulatedCpu11(const ProfileAccumulatedCpu11 &)=delete
ProfileAccumulatedCpu11(const char *name)
FrameProfiler11::CpuSample sample
~ProfileAccumulatedCpu11()
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()
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
unsigned billboardDecodeJobs
std::array< Event, MaxEvents > events
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timing
std::array< GpuQueries, MaxGpuEvents > queries