-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
628 lines (508 loc) · 24.5 KB
/
main.cpp
File metadata and controls
628 lines (508 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// Main.cpp - high-precision input oscilloscope
// Requirements: C++20, DirectX 11, Dear ImGui (Docking), ImPlot, GameInput
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d11.h>
#include <tchar.h>
#include <thread>
#include <atomic>
#include <vector>
#include <array>
#include <iostream>
#include <format>
#include <numeric>
#include <map>
#include <algorithm>
// Multimedia & AVRT for high priority threads
#include <mmsystem.h>
#include <avrt.h>
// GameInput
#include <GameInput.h>
// ImGui & ImPlot
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx11.h"
#include "implot.h"
#include <cmath> // for fmod
// Link against necessary libraries
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "avrt.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "GameInput.lib")
// -----------------------------------------------------------------------------
// CONSTANTS & GLOBALS
// -----------------------------------------------------------------------------
constexpr int RING_BUFFER_SIZE = 10000;
constexpr int TARGET_POLLING_RATE_HZ = 8000;
constexpr int TARGET_SLEEP_US = 1000000 / TARGET_POLLING_RATE_HZ; // 125 us
// -----------------------------------------------------------------------------
// SHARED DATA STRUCTURES (LOCK-FREE)
// -----------------------------------------------------------------------------
struct InputSample {
uint64_t Timestamp; // QPC Timestamp
double DeltaMicroseconds; // Time since last poll/event
uint64_t SequenceNumber; // GameInput sequence number
uint64_t DeviceTimestamp; // Hardware timestamp from GameInput
uint32_t PressedScanCode; // Scancode of the first pressed key (0 if none)
HRESULT LastHResult; // Result of GetCurrentReading
uint32_t LastInputKind; // Kind of input reading
};
struct History {
uint64_t time;
uint64_t Seq;
};
struct SharedData {
std::array<InputSample, RING_BUFFER_SIZE> buffer;
std::atomic<size_t> writeIndex{0};
// Read index is managed locally by the consumer thread (Main Thread)
// We only need atomic write index to ensure we don't read garbage if we catch up (which shouldn't happen easily with 10k buffer)
};
SharedData g_SharedData;
std::atomic<bool> g_AppRunning{true};
// -----------------------------------------------------------------------------
// HELPER FUNCTIONS
// -----------------------------------------------------------------------------
struct RateEstimate {
double RateHz;
uint64_t QuantizationUs;
double ConfidencePercent;
};
// Grid search for quantization interval (e.g., 1000Hz -> 1000us, 8000Hz -> 125us)
RateEstimate EstimatePollingRate(const std::vector<History>& timestampsUs) {
if (timestampsUs.size() < 2) return { 0.0, 0, 0.0 };
const uint64_t candidates[] = { 8000, 4000, 2000, 1500, 1000, 500, 250, 125, 100 };
uint64_t bestQuant = 0;
double minRelError = 1.0e9;
for (uint64_t cand : candidates) {
double totalError = 0;
int count = 0;
for (size_t i = 1; i < timestampsUs.size(); ++i) {
uint64_t delta = timestampsUs[i].time - timestampsUs[i-1].time;
if (delta == 0) continue;
// Calculate distance to nearest multiple of candidate
// e.g., Delta 1001, Cand 1000 -> Remainder 1 -> Dist 1
// e.g., Delta 1999, Cand 1000 -> Remainder 999 -> Dist 1
uint64_t remainder = delta % cand;
uint64_t dist = (remainder > cand / 2) ? (cand - remainder) : remainder;
totalError += (double)dist;
count++;
}
if (count > 0) {
double avgError = totalError / count;
double relError = avgError / (double)cand;
if (relError < minRelError) {
minRelError = relError;
bestQuant = cand;
}
}
}
// Calculate implied Rate
double impliedRate = (bestQuant > 0) ? (1000000.0 / (double)bestQuant) : 0.0;
double confidence = (1.0 - minRelError) * 100.0;
if (confidence < 0) confidence = 0;
return { impliedRate, bestQuant, confidence };
}
// High Resolution Sleep using Waitable Timer
void MicroSleep(HANDLE timer, int us) {
if (!timer) return;
LARGE_INTEGER ft;
ft.QuadPart = -10 * us; // Convert to 100-nanosecond intervals (negative for relative time)
SetWaitableTimerEx(timer, &ft, 0, NULL, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
}
// -----------------------------------------------------------------------------
// INPUT PROBE THREAD
// -----------------------------------------------------------------------------
void InputProbeThread() {
// 1. timeBeginPeriod for global timer resolution
timeBeginPeriod(1);
// 2. Set Thread Priority to Critical / Pro Audio
DWORD taskIndex = 0;
HANDLE hRes = AvSetMmThreadCharacteristicsW(L"Pro Audio", &taskIndex);
if (hRes) {
AvSetMmThreadPriority(hRes, AVRT_PRIORITY_CRITICAL);
} else {
OutputDebugStringA("Warning: Failed to set MMCSS priority.\n");
}
// 3. Initialize Waitable Timer
HANDLE hTimer = CreateWaitableTimerEx(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
if (!hTimer) {
// Fallback to normal timer if high-res is not available (should be available on Win10+)
hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
}
// 4. Initialize GameInput
IGameInput* gameInput = nullptr;
HRESULT hr = GameInputCreate(&gameInput);
if (FAILED(hr)) {
OutputDebugStringA("Critical Error: Failed to create GameInput interface.\n");
return;
}
// QPC Frequency for conversion
LARGE_INTEGER qpcFreq;
QueryPerformanceFrequency(&qpcFreq);
double qpcPeriodUs = 1000000.0 / static_cast<double>(qpcFreq.QuadPart);
uint64_t prevTimestamp = 0;
// Initialize prevTimestamp
LARGE_INTEGER now;
// QueryPerformanceCounter(&now);
prevTimestamp = gameInput->GetCurrentTimestamp();
uint64_t lastSequence = 0;
// -------------------------------------------------------------------------
// THE LOOP (8000Hz Target)
// -------------------------------------------------------------------------
// High-Precision Timing Setup
uint64_t targetNextFrame = 0;
// Initialize target time to "now"
QueryPerformanceCounter(&now);
targetNextFrame = now.QuadPart;
// Convert target interval (125us) to QPC ticks
uint64_t intervalTicks = (uint64_t)((double)TARGET_SLEEP_US / 1000000.0 * (double)qpcFreq.QuadPart);
while (g_AppRunning) {
// LARGE_INTEGER currentQpc;
// QueryPerformanceCounter(¤tQpc);
uint64_t currentTimestamp = gameInput->GetCurrentTimestamp();
uint64_t inputTimestamp = 0;
// Poll GameInput
IGameInputReading* reading = nullptr;
// GameInputKindGamepad | GameInputKindController | GameInputKindKeyboard | GameInputKindMouse result in "Any"
hr = gameInput->GetCurrentReading(GameInputKindKeyboard, nullptr, &reading);
uint64_t currentSequence = 0;
uint64_t readingTimestamp = 0;
uint32_t pressedScanCode = 0;
GameInputKind kind = GameInputKindUnknown;
if (SUCCEEDED(hr) && reading) {
kind = reading->GetInputKind();
readingTimestamp = reading->GetTimestamp();
inputTimestamp = gameInput->GetCurrentTimestamp();
// Generate Virtual Sequence based on Timestamp change
static uint64_t lastReadingTimestamp = 0;
static uint64_t virtualSequence = 0;
if (readingTimestamp != lastReadingTimestamp) {
virtualSequence++;
lastReadingTimestamp = readingTimestamp;
}
currentSequence = virtualSequence;
// Get Key State (Proof of Input)
if ((kind & GameInputKindKeyboard) && reading->GetKeyCount() > 0) {
GameInputKeyState keyState[1]; // Just get one key for verification
if (reading->GetKeyState(1, keyState) > 0) {
pressedScanCode = keyState[0].scanCode;
}
}
// Check for missed frames (more than 1 sequence advance)
if (lastSequence != 0 && currentSequence > lastSequence) {
// Logic for missed frames would go here
}
lastSequence = currentSequence;
reading->Release();
}
// Calculate Loop Delta (Jitter)
// Note: For jitter measurement, we use the ACTUAL time diff between loop iterations
double deltaUs = (double)(currentTimestamp - prevTimestamp);
prevTimestamp = currentTimestamp;
// Write to Shared Ring Buffer
size_t idx = g_SharedData.writeIndex.load(std::memory_order_relaxed);
g_SharedData.buffer[idx].Timestamp = inputTimestamp;
g_SharedData.buffer[idx].DeltaMicroseconds = deltaUs;
g_SharedData.buffer[idx].SequenceNumber = currentSequence;
g_SharedData.buffer[idx].DeviceTimestamp = readingTimestamp;
g_SharedData.buffer[idx].PressedScanCode = pressedScanCode;
g_SharedData.buffer[idx].LastHResult = hr;
g_SharedData.buffer[idx].LastInputKind = (uint32_t)kind;
// Advance atomic index
size_t nextIdx = (idx + 1) % RING_BUFFER_SIZE;
g_SharedData.writeIndex.store(nextIdx, std::memory_order_release);
// ---------------------------------------------------------------------
// HIGH PRECISION SLEEP (SPIN WAIT)
// ---------------------------------------------------------------------
targetNextFrame += intervalTicks;
LARGE_INTEGER frameTime;
QueryPerformanceCounter(&frameTime);
// If we are significantly ahead (e.g. > 2ms), we can sleep to save CPU.
// But for 8000Hz (125us), we will almost NEVER be ahead by 2ms.
// We might be better off just spinning for ultimate consistency.
// Safety: If we fell behind more than 1 frame, reset target to avoid burst catch-up
if (frameTime.QuadPart > targetNextFrame) {
// We are late! Reset target to now + 1 interval to maintain spacing
// (or just yield and cont, but let's prevent drift accumulation)
targetNextFrame = frameTime.QuadPart + intervalTicks;
}
// SPIN LOOP
while (frameTime.QuadPart < targetNextFrame) {
// Optional: Sleep(1) if diff > 2ms (omitted for pure "Ultra Fast" simplicity)
// Just aggressive spin for <1ms tasks
// Yield CPU to Hyperthread sibling (prevents starvation of other logic on same core)
// YieldProcessor();
QueryPerformanceCounter(&frameTime);
}
}
// Cleanup
if (gameInput) gameInput->Release();
CloseHandle(hTimer);
if (hRes) AvRevertMmThreadCharacteristics(hRes);
timeEndPeriod(1);
}
// -----------------------------------------------------------------------------
// DIRECTX 11 & IMGUI BOILERPLATE
// -----------------------------------------------------------------------------
static ID3D11Device* g_pd3dDevice = nullptr;
static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Main Entry Point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
// Create Application Window
WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"InputOscilloscope", nullptr };
::RegisterClassExW(&wc);
HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"DX11 Input Oscilloscope", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd)) {
CleanupDeviceD3D();
::UnregisterClassW(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImPlot::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
ImGui::StyleColorsDark();
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// -------------------------------------------------------------------------
// SPAWN PROBE THREAD
// -------------------------------------------------------------------------
g_AppRunning = true;
std::thread probeThread(InputProbeThread);
// -------------------------------------------------------------------------
// MAIN LOOP
// -------------------------------------------------------------------------
// Visualization Data
std::vector<float> plotData;
plotData.reserve(RING_BUFFER_SIZE);
size_t localReadIndex = 0;
// Stats
double statsSum = 0;
double statsSqSum = 0;
int statsCount = 0;
double currentStdDev = 0;
double currentAvg = 0;
uint32_t lastScanCode = 0;
// Polling Rate Estimation History
std::vector<History> historyDevice;
std::vector<History> historyPoll;
// Stats for UI
RateEstimate estDevice = {0,0,0};
RateEstimate estPoll = {0,0,0};
bool done = false;
while (!done) {
MSG msg;
while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
if (msg.message == WM_QUIT)
done = true;
}
if (done) break;
// Consuming Data from Ring Buffer
size_t currentWriteIndex = g_SharedData.writeIndex.load(std::memory_order_acquire);
// Catch up read index if we fell too far behind (buffer overwrite)
// distance calculation handling wrap-around is tricky, simpler is usually:
// if head < tail ?
// For simple fixed size ring, just checking if we are drastically behind:
// This is a simplified "drain all new" strategy.
while(localReadIndex != currentWriteIndex) {
InputSample& s = g_SharedData.buffer[localReadIndex];
plotData.push_back((float)s.DeltaMicroseconds);
if (s.PressedScanCode != 0) {
lastScanCode = s.PressedScanCode;
}
// Collect data for Polling Rate Estimation
// Separate history for Device (Hardware) and Poll (Loop)
if ((historyDevice.empty() && s.SequenceNumber > 0) || !historyDevice.empty() && s.SequenceNumber > historyDevice.back().Seq) {
static LARGE_INTEGER qpcFreq = {};
if (qpcFreq.QuadPart == 0) QueryPerformanceFrequency(&qpcFreq);
double pollTimeUs = (double)s.Timestamp / (double)qpcFreq.QuadPart * 1000000.0;
historyDevice.push_back({s.DeviceTimestamp, s.SequenceNumber});
historyPoll.push_back({s.Timestamp, s.SequenceNumber});
if (historyDevice.size() > 2000) historyDevice.erase(historyDevice.begin());
if (historyPoll.size() > 2000) historyPoll.erase(historyPoll.begin());
}
// Minimal stats calc window (e.g. last 1000 samples)
if (plotData.size() > 2000) {
plotData.erase(plotData.begin(), plotData.begin() + 1000); // keep vector size manageable
}
// Rolling stats (simple iterative)
statsSum += s.DeltaMicroseconds;
statsSqSum += s.DeltaMicroseconds * s.DeltaMicroseconds;
statsCount++;
// Reset stats periodically to see "current" jitter
if (statsCount > 1000) {
double mean = statsSum / statsCount;
double variance = (statsSqSum / statsCount) - (mean * mean);
currentStdDev = std::sqrt(variance > 0 ? variance : 0);
currentAvg = mean;
statsSum = 0;
statsSqSum = 0;
statsCount = 0;
}
localReadIndex = (localReadIndex + 1) % RING_BUFFER_SIZE;
}
// Start the Dear ImGui frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// UI Definition
{
ImGui::Begin("Input Oscilloscope");
ImGui::Text("Polling Rate Target: %d Hz (%.2f us)", TARGET_POLLING_RATE_HZ, (double)TARGET_SLEEP_US);
ImGui::Text("Average Delta: %.2f us (%d Hz)", currentAvg, (int)(1000000.0 / currentAvg));
ImGui::Text("Jitter (StdDev): %.2f us", currentStdDev);
// Update Estimates (every frame or so)
auto estDevice = EstimatePollingRate(historyDevice);
auto estPoll = EstimatePollingRate(historyPoll);
if (estPoll.RateHz > 0) {
ImGui::TextColored({0,1,1,1}, "POLL RATE (Loop): %.1f Hz (%.0f us) | Conf: %.1f%%",
estPoll.RateHz, (double)estPoll.QuantizationUs, estPoll.ConfidencePercent);
} else {
ImGui::Text("POLL RATE (Loop): --");
}
if (estDevice.RateHz > 0) {
ImGui::TextColored({1,1,0,1}, "DEVICE RATE (Hw): %.1f Hz (%.0f us) | Conf: %.1f%%",
estDevice.RateHz, (double)estDevice.QuantizationUs, estDevice.ConfidencePercent);
} else {
ImGui::Text("DEVICE RATE (Hw): --");
}
// Debug: Show Min Error
// ImGui::TextDisabled("Debug: Best Rel Error %.4f%%", minRelError * 100.0);
// Get latest sample for debug
const InputSample& latest = g_SharedData.buffer[(currentWriteIndex == 0 ? RING_BUFFER_SIZE : currentWriteIndex) - 1];
ImGui::TextDisabled("Debug: HistSize %zu | LastSeq %llu | LastTime %.4f s",
historyDevice.size(),
historyDevice.empty() ? 0 : (uint64_t)historyDevice.back().Seq,
historyDevice.empty() ? 0.0 : historyDevice.back().time / 1000000.0);
ImGui::TextDisabled("Debug: HR 0x%08X | Kind %u | ScanCode %u",
latest.LastHResult, latest.LastInputKind, latest.PressedScanCode);
ImGui::TextDisabled("Debug: Seq %llu | DevTime %llu | Time %.4f s",
latest.SequenceNumber, latest.DeviceTimestamp, (double)latest.DeviceTimestamp / 1000000.0);
if (lastScanCode != 0) {
ImGui::TextColored({0,1,0,1}, "Input Detected! Last ScanCode: %u", lastScanCode);
} else {
ImGui::Text("No Input Detected Yet");
}
ImGui::Separator();
if (ImPlot::BeginPlot("Polling Interval Delta")) {
ImPlot::SetupAxes("Sample", "Delta (us)", ImPlotAxisFlags_AutoFit, ImPlotAxisFlags_AutoFit);
ImPlot::SetupAxisLimits(ImAxis_Y1, 0, 300, ImPlotCond_Once); // View around 125us
// Draw Reference Line
double tagX = 0;
double tagY = 125.0;
ImPlot::DragLineY(0, &tagY, ImVec4(1,1,0,1), 1.0f, ImPlotDragToolFlags_NoInputs);
if (!plotData.empty()) {
ImPlot::PlotLine("Delta", plotData.data(), (int)plotData.size());
}
ImPlot::EndPlot();
}
ImGui::End();
}
// Rendering
ImGui::Render();
const float clear_color_with_alpha[4] = { 0.45f, 0.55f, 0.60f, 1.00f };
g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // VSync On
}
// Cleanup
g_AppRunning = false;
if (probeThread.joinable())
probeThread.join();
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImPlot::DestroyContext();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClassW(wc.lpszClassName, wc.hInstance);
return 0;
}
// -----------------------------------------------------------------------------
// D3D Helper Functions
// -----------------------------------------------------------------------------
bool CreateDeviceD3D(HWND hWnd) {
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
D3D_FEATURE_LEVEL featureLevel;
const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext);
if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available.
res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext);
if (res != S_OK)
return false;
CreateRenderTarget();
return true;
}
void CleanupDeviceD3D() {
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; }
if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
}
void CreateRenderTarget() {
ID3D11Texture2D* pBackBuffer;
g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView);
pBackBuffer->Release();
}
void CleanupRenderTarget() {
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; }
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg) {
case WM_SIZE:
if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED) {
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProcW(hWnd, msg, wParam, lParam);
}