-
Notifications
You must be signed in to change notification settings - Fork 1
/
CNSDKGettingStartedD3D12.cpp
1967 lines (1653 loc) · 74.8 KB
/
CNSDKGettingStartedD3D12.cpp
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <assert.h>
#include "framework.h"
// CNSDK includes
#include "leia/core/cxx/core.hpp"
#include "leia/core/cxx/interlacer.d3d12.hpp"
// CNSDKGettingStartedD3D11 includes
#include "CNSDKGettingStartedD3D12.h"
#include "CNSDKGettingStartedMath.h"
// D3D11 includes.
#include <d3d12.h>
#include <d3d12sdklayers.h>
#include <d3dcompiler.h>
#include <dxgi1_6.h>
#include "d3dx12.h"
// CNSDK single library
#pragma comment(lib, "CNSDK/lib/leiaCore-faceTrackingInApp.lib")
// D3D12 libraries
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dxguid.lib")
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(x) if(x != nullptr) { x->Release(); x = nullptr; }
#endif
enum class eDemoMode { Spinning3DCube, StereoImage };
void InitializeOffscreenFrameBuffer();
// Global Variables.
const wchar_t* g_windowTitle = L"CNSDK Getting Started D3D12 Sample";
const wchar_t* g_windowClass = L"CNSDKGettingStartedD3D12WindowClass";
int g_windowWidth = 1280;
int g_windowHeight = 720;
bool g_fullscreen = true;
std::unique_ptr<leia::Core> g_sdk;
std::unique_ptr<leia::InterlacerD3D12> g_interlacer = nullptr;
eDemoMode g_demoMode = eDemoMode::Spinning3DCube;
float g_geometryDist = 500;
bool g_perspective = true;
float g_perspectiveCameraFiledOfView = 90.0f * 3.14159f / 180.0f;
float g_orthographicCameraHeight = 500.0f;
bool g_showGUI = true;
int g_viewWidth = -1;
int g_viewHeight = -1;
bool g_sRGB = true;
// Global D3D12 Variables.
const int g_frameCount = 2;
ID3D12Device* g_device = nullptr;
ID3D12CommandQueue* g_commandQueue = nullptr;
ID3D12CommandAllocator* g_commandAllocator[g_frameCount] = {};
IDXGISwapChain3* g_swapChain = nullptr;
int g_frameIndex = 0;
DXGI_FORMAT g_swapChainFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
DXGI_FORMAT g_swapChainViewFormat = g_sRGB ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
ID3D12DescriptorHeap* g_srvHeap = nullptr;
D3D12_CPU_DESCRIPTOR_HANDLE g_srvFontCpuDescHandle = {};
D3D12_GPU_DESCRIPTOR_HANDLE g_srvFontGpuDescHandle = {};
UINT g_srvDescriptorSize = 0;
UINT g_srvHeapUsed = 0;
ID3D12CommandAllocator* g_guiCommandAllocator[g_frameCount] = {};
ID3D12GraphicsCommandList* g_guiCommandList = nullptr;
ID3D12GraphicsCommandList* g_textureUploadCommandList = nullptr;
ID3D12Resource* g_renderTargets[g_frameCount] = {};
ID3D12DescriptorHeap* g_rtvHeap = nullptr;
UINT g_rtvDescriptorSize = 0;
UINT g_rtvHeapUsed = 0;
CD3DX12_CPU_DESCRIPTOR_HANDLE g_renderTargetViews[g_frameCount] = {};
ID3D12Resource* g_depthStencil[g_frameCount] = {};
ID3D12DescriptorHeap* g_dsvHeap = nullptr;
UINT g_dsvDescriptorSize = 0;
UINT g_dsvHeapUsed = 0;
CD3DX12_CPU_DESCRIPTOR_HANDLE g_depthStencilViews[g_frameCount] = {};
ID3D12Fence* g_fence = nullptr;
UINT64 g_fenceValues[g_frameCount] = {};
HANDLE g_fenceEvent = NULL;
ID3D12Resource* g_offscreenTexture = nullptr;
CD3DX12_CPU_DESCRIPTOR_HANDLE g_offscreenShaderResourceView = {};
CD3DX12_CPU_DESCRIPTOR_HANDLE g_offscreenRenderTargetView = {};
ID3D12Resource* g_offscreenDepthTexture = nullptr;
CD3DX12_CPU_DESCRIPTOR_HANDLE g_offscreenDepthStencilView = {};
const FLOAT g_offscreenColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };
const FLOAT g_backbufferColor[4] = { 0.0f, 0.25f, 0.0f, 1.0f };
ID3D12Resource* g_vertexBuffer = nullptr;
ID3D12Resource* g_indexBuffer = nullptr;
D3D12_VERTEX_BUFFER_VIEW g_vertexBufferView = {};
D3D12_INDEX_BUFFER_VIEW g_indexBufferView = {};
D3D12_INPUT_LAYOUT_DESC g_inputLayoutDesc = {};
ID3D12Resource* g_constantBuffer[2] = {};
void* g_constantBufferDataBegin[2] = {};
ID3D12GraphicsCommandList* g_commandList = nullptr;
ID3D12GraphicsCommandList* g_commandList2 = nullptr;
ID3D12RootSignature* g_rootSignature = nullptr;
ID3D12PipelineState* g_pipelineState = nullptr;
ID3DBlob* g_compiledVertexShaderBlob = nullptr;
ID3DBlob* g_compiledPixelShaderBlob = nullptr;
ID3D12Resource* g_imageTexture = nullptr;
#pragma pack(push, 1)
struct CONSTANTBUFFER
{
mat4f transform;
};
struct VERTEX
{
float pos[3];
float color[3];
VERTEX() = default;
VERTEX(const float* p, const float* c)
{
pos[0] = p[0];
pos[1] = p[1];
pos[2] = p[2];
color[0] = c[0];
color[1] = c[1];
color[2] = c[2];
}
VERTEX(float p0, float p1, float p2, float c0, float c1, float c2)
{
pos[0] = p0;
pos[1] = p1;
pos[2] = p2;
color[0] = c0;
color[1] = c1;
color[2] = c2;
}
};
#pragma pack(pop)
void OnError(const wchar_t* msg)
{
MessageBox(NULL, msg, L"CNSDKGettingStartedD3D12", MB_ICONERROR | MB_OK);
exit(-1);
}
bool ReadEntireFile(const char* filename, bool binary, char*& data, size_t& dataSize)
{
const int BUFFERSIZE = 4096;
char buffer[BUFFERSIZE];
// Open file.
FILE* f = fopen(filename, binary ? "rb" : "rt");
if (f == NULL)
return false;
data = nullptr;
dataSize = 0;
while (true)
{
// Read chunk into buffer.
const size_t bytes = (int)fread(buffer, sizeof(char), BUFFERSIZE, f);
if (bytes <= 0)
break;
// Extend allocated memory and copy chunk into it.
char* newData = new char[dataSize + bytes];
if (dataSize > 0)
{
memcpy(newData, data, dataSize);
delete [] data;
data = nullptr;
}
memcpy(newData + dataSize, buffer, bytes);
dataSize += bytes;
data = newData;
}
// Done and close.
fclose(f);
return dataSize > 0;
}
bool ReadTGA(const char* filename, int& width, int& height, char*& data, int& dataSize)
{
char* ptr = nullptr;
size_t fileSize = 0;
if (!ReadEntireFile(filename, true, ptr, fileSize))
{
OnError(L"Failed to read TGA file.");
return false;
}
static std::uint8_t DeCompressed[12] = { 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
static std::uint8_t IsCompressed[12] = { 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
typedef union PixelInfo
{
std::uint32_t Colour;
struct
{
std::uint8_t R, G, B, A;
};
} *PPixelInfo;
// Read header.
std::uint8_t Header[18] = { 0 };
memcpy(&Header, ptr, sizeof(Header));
ptr += sizeof(Header);
int bitsPerPixel = 0;
if (!std::memcmp(DeCompressed, &Header, sizeof(DeCompressed)))
{
bitsPerPixel = Header[16];
width = Header[13] * 256 + Header[12];
height = Header[15] * 256 + Header[14];
dataSize = ((width * bitsPerPixel + 31) / 32) * 4 * height;
if ((bitsPerPixel != 24) && (bitsPerPixel != 32))
{
OnError(L"Invalid TGA file isn't 24/32-bit.");
return false;
}
data = new char[dataSize];
memcpy(data, ptr, dataSize);
}
else if (!std::memcmp(IsCompressed, &Header, sizeof(IsCompressed)))
{
bitsPerPixel = Header[16];
width = Header[13] * 256 + Header[12];
height = Header[15] * 256 + Header[14];
dataSize = width * height * sizeof(PixelInfo);
if ((bitsPerPixel != 24) && (bitsPerPixel != 32))
{
OnError(L"Invalid TGA file isn't 24/32-bit.");
return false;
}
PixelInfo Pixel = { 0 };
int CurrentByte = 0;
std::size_t CurrentPixel = 0;
std::uint8_t ChunkHeader = { 0 };
int BytesPerPixel = (bitsPerPixel / 8);
data = new char[dataSize];
do
{
memcpy(&ChunkHeader, ptr, sizeof(ChunkHeader));
ptr += sizeof(ChunkHeader);
if (ChunkHeader < 128)
{
++ChunkHeader;
for (int I = 0; I < ChunkHeader; ++I, ++CurrentPixel)
{
memcpy(&Pixel, ptr, BytesPerPixel);
ptr += BytesPerPixel;
data[CurrentByte++] = Pixel.B;
data[CurrentByte++] = Pixel.G;
data[CurrentByte++] = Pixel.R;
if (bitsPerPixel > 24)
data[CurrentByte++] = Pixel.A;
}
}
else
{
ChunkHeader -= 127;
memcpy(&Pixel, ptr, BytesPerPixel);
ptr += BytesPerPixel;
for (int I = 0; I < ChunkHeader; ++I, ++CurrentPixel)
{
data[CurrentByte++] = Pixel.B;
data[CurrentByte++] = Pixel.G;
data[CurrentByte++] = Pixel.R;
if (bitsPerPixel > 24)
data[CurrentByte++] = Pixel.A;
}
}
} while (CurrentPixel < (width * height));
}
else
{
OnError(L"Invalid TGA file isn't 24/32-bit.");
return false;
}
return true;
}
float GetSRGB(float value)
{
// If already in sRGB, no change.
if (g_sRGB)
return value;
// Convert linear->sRGB.
if (value <= 0.0f)
return 0.0f;
else if (value >= 1.0f)
return 1.0f;
else if (value <= 0.0031308f)
return value * 12.92f;
else
return 1.055f * pow(value, 1.0f / 2.4f) - 0.055f;
}
BOOL CALLBACK GetDefaultWindowStartPos_MonitorEnumProc(__in HMONITOR hMonitor, __in HDC hdcMonitor, __in LPRECT lprcMonitor, __in LPARAM dwData)
{
std::vector<MONITORINFOEX>& infoArray = *reinterpret_cast<std::vector<MONITORINFOEX>*>(dwData);
MONITORINFOEX info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info);
GetMonitorInfo(hMonitor, &info);
infoArray.push_back(info);
return TRUE;
}
bool GetNonPrimaryDisplayTopLeftCoordinate(int& x, int& y)
{
// Get connected monitor info.
std::vector<MONITORINFOEX> mInfo;
mInfo.reserve(::GetSystemMetrics(SM_CMONITORS));
EnumDisplayMonitors(NULL, NULL, GetDefaultWindowStartPos_MonitorEnumProc, reinterpret_cast<LPARAM>(&mInfo));
// If we have multiple monitors, select the first non-primary one.
if (mInfo.size() > 1)
{
for (int i = 0; i < mInfo.size(); i++)
{
const MONITORINFOEX& mi = mInfo[i];
if (0 == (mi.dwFlags & MONITORINFOF_PRIMARY))
{
x = mi.rcMonitor.left;
y = mi.rcMonitor.top;
return true;
}
}
}
// Didn't find a non-primary, there is only one display connected.
x = 0;
y = 0;
return false;
}
HWND CreateGraphicsWindow(HINSTANCE hInstance)
{
// Create window.
HWND hWnd = NULL;
{
int defaultX = 0;
int defaultY = 0;
GetNonPrimaryDisplayTopLeftCoordinate(defaultX, defaultY);
DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
DWORD dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
RECT WindowRect;
WindowRect.left = (long)defaultX;
WindowRect.right = (long)(defaultX + g_windowWidth);
WindowRect.top = (long)defaultY;
WindowRect.bottom = (long)(defaultY + g_windowHeight);
//AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
hWnd = CreateWindowEx
(
dwExStyle,
g_windowClass, // Class Name
g_windowTitle, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
WindowRect.left, // Window left
WindowRect.top, // Window top
WindowRect.right - WindowRect.left, // Calculate Window Width
WindowRect.bottom - WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL // Dont Pass Anything To WM_CREATE
);
if (!hWnd)
OnError(L"Failed to create window.");
}
return hWnd;
}
void SetFullscreen(HWND hWnd, bool fullscreen)
{
static int windowPrevX = 0;
static int windowPrevY = 0;
static int windowPrevWidth = 0;
static int windowPrevHeight = 0;
DWORD style = GetWindowLong(hWnd, GWL_STYLE);
if (fullscreen)
{
RECT rect;
MONITORINFO mi = { sizeof(mi) };
GetWindowRect(hWnd, &rect);
windowPrevX = rect.left;
windowPrevY = rect.top;
windowPrevWidth = rect.right - rect.left;
windowPrevHeight = rect.bottom - rect.top;
GetMonitorInfo(MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY), &mi);
SetWindowLong(hWnd, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(hWnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
}
else
{
MONITORINFO mi = { sizeof(mi) };
UINT flags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW;
GetMonitorInfo(MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY), &mi);
SetWindowLong(hWnd, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
SetWindowPos(hWnd, HWND_NOTOPMOST, windowPrevX, windowPrevY, windowPrevWidth, windowPrevHeight, flags);
}
}
void TransitionResourceState(ID3D12GraphicsCommandList* commandList, ID3D12Resource* resource, D3D12_RESOURCE_STATES fromState, D3D12_RESOURCE_STATES toState)
{
assert(resource != nullptr);
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(resource, fromState, toState);
commandList->ResourceBarrier(1, &barrier);
}
HRESULT ResizeBuffers(int width, int height)
{
if (g_device == nullptr)
return S_OK;
for (int i = 0; i < g_frameCount; i++)
{
if (g_renderTargets[i] != nullptr)
{
g_renderTargets[i]->Release();
g_renderTargets[i] = nullptr;
}
if (g_depthStencil[i] != nullptr)
{
g_depthStencil[i]->Release();
g_depthStencil[i] = nullptr;
}
}
g_rtvHeapUsed = 0;
g_dsvHeapUsed = 0;
g_srvHeapUsed = 0;
memset(g_renderTargetViews, 0, sizeof(g_renderTargetViews));
memset(g_depthStencilViews, 0, sizeof(g_depthStencilViews));
// Resize swapchain.
HRESULT hr = g_swapChain->ResizeBuffers(g_frameCount, width, height, g_swapChainFormat, 0);
if (FAILED(hr))
OnError(L"Failed to resize swapchain.");
// Create frame resources.
{
// Create a RTV for each frame.
for (int n = 0; n < g_frameCount; n++)
{
g_renderTargetViews[n] = CD3DX12_CPU_DESCRIPTOR_HANDLE(g_rtvHeap->GetCPUDescriptorHandleForHeapStart());
g_renderTargetViews[n].Offset(g_rtvHeapUsed);
// Create view for single slice.
D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Format = g_swapChainViewFormat;
rtvDesc.Texture2D.MipSlice = 0;
rtvDesc.Texture2D.PlaneSlice = 0;
hr = g_swapChain->GetBuffer(n, _uuidof(ID3D12Resource), (void**) &g_renderTargets[n]);
g_device->CreateRenderTargetView(g_renderTargets[n], &rtvDesc, g_renderTargetViews[n]);
g_rtvHeapUsed += g_rtvDescriptorSize;
}
// Create a depth stencil buffer and a DSV for each frame.
{
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = DXGI_FORMAT_D32_FLOAT;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
for (int n = 0; n < g_frameCount; n++)
{
CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_DEFAULT);
CD3DX12_RESOURCE_DESC resourceDesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, width, height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
hr = g_device->CreateCommittedResource(
&heapProps,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&depthOptimizedClearValue,
_uuidof(ID3D12Resource),
(void**)&g_depthStencil[n]);
g_depthStencilViews[n] = CD3DX12_CPU_DESCRIPTOR_HANDLE(g_dsvHeap->GetCPUDescriptorHandleForHeapStart());
g_depthStencilViews[n].Offset(g_dsvHeapUsed);//1, g_dsvHeapUsed);
g_device->CreateDepthStencilView(g_depthStencil[n], &depthStencilDesc, g_depthStencilViews[n]);
g_dsvHeapUsed += g_dsvDescriptorSize;
}
}
}
//
if (g_demoMode == eDemoMode::Spinning3DCube)
InitializeOffscreenFrameBuffer();
return S_OK;
}
// Helper function for acquiring the first available hardware adapter that supports Direct3D 12.
// If no such adapter can be found, *ppAdapter will be set to nullptr.
void GetHardwareAdapter(IDXGIFactory1* pFactory, IDXGIAdapter1** ppAdapter, bool requestHighPerformanceAdapter = false)
{
*ppAdapter = nullptr;
IDXGIAdapter1* adapter = nullptr;
IDXGIFactory6* factory6 = nullptr;
if (SUCCEEDED(pFactory->QueryInterface(_uuidof(IDXGIAdapter1), (void**) &adapter)))
{
for (
UINT adapterIndex = 0;
SUCCEEDED(factory6->EnumAdapterByGpuPreference(
adapterIndex,
requestHighPerformanceAdapter == true ? DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE : DXGI_GPU_PREFERENCE_UNSPECIFIED,
IID_PPV_ARGS(&adapter)));
++adapterIndex)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
{
// Don't select the Basic Render Driver adapter.
// If you want a software adapter, pass in "/warp" on the command line.
continue;
}
// Check to see whether the adapter supports Direct3D 12, but don't create the
// actual device yet.
if (SUCCEEDED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
{
break;
}
}
}
if (adapter == nullptr)
{
for (UINT adapterIndex = 0; SUCCEEDED(pFactory->EnumAdapters1(adapterIndex, &adapter)); ++adapterIndex)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
{
// Don't select the Basic Render Driver adapter.
// If you want a software adapter, pass in "/warp" on the command line.
continue;
}
// Check to see whether the adapter supports Direct3D 12, but don't create the
// actual device yet.
if (SUCCEEDED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
{
break;
}
}
}
*ppAdapter = adapter;
}
// Prepare to render the next frame.
void MoveToNextFrame()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = g_fenceValues[g_frameIndex];
g_commandQueue->Signal(g_fence, currentFenceValue);
// Update the frame index.
g_frameIndex = g_swapChain->GetCurrentBackBufferIndex();
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (g_fence->GetCompletedValue() < g_fenceValues[g_frameIndex])
{
g_fence->SetEventOnCompletion(g_fenceValues[g_frameIndex], g_fenceEvent);
WaitForSingleObjectEx(g_fenceEvent, INFINITE, FALSE);
}
// Set the fence value for the next frame.
g_fenceValues[g_frameIndex] = currentFenceValue + 1;
}
// Wait for pending GPU work to complete.
void WaitForGpu()
{
// Schedule a Signal command in the queue.
g_commandQueue->Signal(g_fence, g_fenceValues[g_frameIndex]);
// Wait until the fence has been processed.
g_fence->SetEventOnCompletion(g_fenceValues[g_frameIndex], g_fenceEvent);
WaitForSingleObjectEx(g_fenceEvent, INFINITE, FALSE);
// Increment the fence value for the current frame.
g_fenceValues[g_frameIndex]++;
}
HRESULT InitializeD3D12(HWND hWnd)
{
HRESULT hr = S_OK;
UINT dxgiFactoryFlags = 0;
#if defined(_DEBUG)
// Enable the debug layer (requires the Graphics Tools "optional feature").
// NOTE: Enabling the debug layer after device creation will invalidate the active device.
{
ID3D12Debug* debugController = nullptr;
if (SUCCEEDED(D3D12GetDebugInterface(_uuidof(ID3D12Debug), (void**) &debugController)))
{
debugController->EnableDebugLayer();
// Enable additional debug layers.
dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
}
}
#endif
IDXGIFactory4* factory = nullptr;
hr = CreateDXGIFactory2(dxgiFactoryFlags, _uuidof(IDXGIFactory4), (void**) &factory);
if(FAILED(hr))
return hr;
IDXGIAdapter1* hardwareAdapter = nullptr;
GetHardwareAdapter(factory, &hardwareAdapter);
hr = D3D12CreateDevice(hardwareAdapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), (void**) &g_device);
if (FAILED(hr))
return hr;
// Get window size.
RECT rc;
GetClientRect(hWnd, &rc);
const UINT width = rc.right - rc.left;
const UINT height = rc.bottom - rc.top;
// Create the command queue.
{
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
hr = g_device->CreateCommandQueue(&queueDesc, _uuidof(ID3D12CommandQueue), (void**)&g_commandQueue);
if (FAILED(hr))
return hr;
}
// Create the swap chain.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.BufferCount = g_frameCount;
swapChainDesc.Width = width;
swapChainDesc.Height = height;
swapChainDesc.Format = g_swapChainFormat;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.SampleDesc.Count = 1;
IDXGISwapChain1* swapChain = nullptr;
hr = factory->CreateSwapChainForHwnd(g_commandQueue, hWnd, &swapChainDesc, nullptr, nullptr, &swapChain);
if (FAILED(hr))
return hr;
swapChain->QueryInterface(_uuidof(IDXGISwapChain3), (void**) &g_swapChain);// g_swapChain = dynamic_cast<IDXGISwapChain3*>(swapChain);
if (g_swapChain == nullptr)
return hr;
//
hr = factory->MakeWindowAssociation(hWnd, 0);//DXGI_MWA_NO_ALT_ENTER
if (FAILED(hr))
return hr;
g_frameIndex = g_swapChain->GetCurrentBackBufferIndex();
// Create descriptor heaps.
{
// Describe and create a render target view (RTV) descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
rtvHeapDesc.NumDescriptors = 64;//g_frameCount;
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
hr = g_device->CreateDescriptorHeap(&rtvHeapDesc, _uuidof(ID3D12DescriptorHeap), (void**) &g_rtvHeap);
g_rtvDescriptorSize = g_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
// Describe and create a depth stencil view (DSV) descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
dsvHeapDesc.NumDescriptors = 64;//g_frameCount;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
hr = g_device->CreateDescriptorHeap(&dsvHeapDesc, _uuidof(ID3D12DescriptorHeap), (void**)&g_dsvHeap);
g_dsvDescriptorSize = g_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
// Describe and create a shader resource view (SRV) descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = 64;//g_frameCount;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
hr = g_device->CreateDescriptorHeap(&srvHeapDesc, _uuidof(ID3D12DescriptorHeap), (void**)&g_srvHeap);
g_srvDescriptorSize = g_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
for (int i=0; i<g_frameCount; i++)
{
hr = g_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, _uuidof(ID3D12CommandAllocator), (void**)&g_commandAllocator[i]);
if (FAILED(hr))
OnError(L"Failed to create command allocator.");
hr = g_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, _uuidof(ID3D12CommandAllocator), (void**)&g_guiCommandAllocator[i]);
if (FAILED(hr))
OnError(L"Failed to create command allocator.");
}
{
hr = g_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_commandAllocator[g_frameIndex], NULL, _uuidof(ID3D12GraphicsCommandList), (void**)&g_commandList);
if (FAILED(hr))
OnError(L"Failed to create command list.");
hr = g_commandList->Close();
if (FAILED(hr))
OnError(L"Failed to close command list.");
hr = g_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_commandAllocator[g_frameIndex], NULL, _uuidof(ID3D12GraphicsCommandList), (void**)&g_commandList2);
if (FAILED(hr))
OnError(L"Failed to create command list.");
hr = g_commandList2->Close();
if (FAILED(hr))
OnError(L"Failed to close command list.");
}
{
// Create SRV for GUI font.
g_srvFontCpuDescHandle = g_srvHeap->GetCPUDescriptorHandleForHeapStart();
g_srvFontGpuDescHandle = g_srvHeap->GetGPUDescriptorHandleForHeapStart();
// Create command list.
hr = g_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_guiCommandAllocator[g_frameIndex], nullptr, _uuidof(ID3D12GraphicsCommandList), (void**) &g_guiCommandList);
if (FAILED(hr))
{
assert(false);
}
hr = g_guiCommandList->Close();
if (FAILED(hr))
{
assert(false);
}
}
{
// Create command list.
hr = g_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_commandAllocator[g_frameIndex], nullptr, _uuidof(ID3D12GraphicsCommandList), (void**)&g_textureUploadCommandList);
if (FAILED(hr))
{
assert(false);
}
hr = g_textureUploadCommandList->Close();
if (FAILED(hr))
{
assert(false);
}
}
// Create frame resources.
{
// Create a RTV for each frame.
for (int n = 0; n < g_frameCount; n++)
{
g_renderTargetViews[n] = CD3DX12_CPU_DESCRIPTOR_HANDLE(g_rtvHeap->GetCPUDescriptorHandleForHeapStart());
g_renderTargetViews[n].Offset(g_rtvHeapUsed);//1, g_rtvHeapUsed);
// Create view for single slice.
D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Format = g_swapChainViewFormat;
rtvDesc.Texture2D.MipSlice = 0;
rtvDesc.Texture2D.PlaneSlice = 0;
hr = g_swapChain->GetBuffer(n, _uuidof(ID3D12Resource), (void**) &g_renderTargets[n]);
g_device->CreateRenderTargetView(g_renderTargets[n], &rtvDesc, g_renderTargetViews[n]);
g_rtvHeapUsed += g_rtvDescriptorSize;
}
// Create a depth stencil buffer and a DSV for each frame.
{
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = DXGI_FORMAT_D32_FLOAT;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
for (int n = 0; n < g_frameCount; n++)
{
CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_DEFAULT);
CD3DX12_RESOURCE_DESC resourceDesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, width, height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
hr = g_device->CreateCommittedResource(
&heapProps,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&depthOptimizedClearValue,
_uuidof(ID3D12Resource),
(void**)&g_depthStencil[n]);
g_depthStencilViews[n] = CD3DX12_CPU_DESCRIPTOR_HANDLE(g_dsvHeap->GetCPUDescriptorHandleForHeapStart());
g_depthStencilViews[n].Offset(g_dsvHeapUsed);//1, g_dsvHeapUsed);
g_device->CreateDepthStencilView(g_depthStencil[n], &depthStencilDesc, g_depthStencilViews[n]);
g_dsvHeapUsed += g_dsvDescriptorSize;
}
}
}
// Create synchronization objects and wait until assets have been uploaded to the GPU.
{
hr = g_device->CreateFence(g_fenceValues[g_frameIndex], D3D12_FENCE_FLAG_NONE, _uuidof(ID3D12Fence), (void**)&g_fence);
if (FAILED(hr))
return hr;
g_fenceValues[g_frameIndex]++;
// Create an event handle to use for frame synchronization.
g_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (g_fenceEvent == nullptr)
{
hr = HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr))
return hr;
}
// Wait for the command list to execute; we are reusing the same command
// list in our main loop but for now, we just want to wait for setup to
// complete before continuing.
WaitForGpu();
}
return S_OK;
}
void InitializeCNSDK(HWND hWnd)
{
// Initialize SDK.
leia::CoreInitConfiguration coreConfig(nullptr);
coreConfig.SetFaceTrackingServerLogLevel(kLeiaLogLevelTrace);
coreConfig.SetFaceTrackingEnable(true);
g_sdk = std::make_unique<leia::Core>(coreConfig);
// Initialize interlacer.
leia::InterlacerInitConfiguration interlacerConfig;
interlacerConfig.SetUseAtlasForViews(true);
g_interlacer = std::make_unique<leia::InterlacerD3D12>(*g_sdk, interlacerConfig, g_device, g_commandQueue);
g_interlacer->SetSourceViewsSRGB(g_sRGB);
// Initialize interlacer GUI.
if (g_showGUI)
{
leia::InterlacerDebugMenuConfiguration debugMenuInitArgs = {};
debugMenuInitArgs.gui.surface = hWnd;
debugMenuInitArgs.gui.d3d12.device = g_device;
debugMenuInitArgs.gui.d3d12.deviceCbvSrvHeap = g_srvHeap;
debugMenuInitArgs.gui.d3d12.fontSrvCpuDescHandle = *((uint64_t*)&g_srvFontCpuDescHandle);
debugMenuInitArgs.gui.d3d12.fontSrvGpuDescHandle = *((uint64_t*)&g_srvFontGpuDescHandle);
debugMenuInitArgs.gui.d3d12.numFramesInFlight = g_frameCount;
debugMenuInitArgs.gui.d3d12.rtvFormat = g_swapChainViewFormat;
debugMenuInitArgs.gui.d3d12.commandList = g_guiCommandList;
debugMenuInitArgs.gui.graphicsAPI = LEIA_GRAPHICS_API_D3D12;
g_interlacer->InitializeGui(&debugMenuInitArgs, g_sRGB);
}
// Set stereo sliding mode.
const int numViews = g_interlacer->GetNumViews();
if (numViews != 2)
OnError(L"Unexpected number of views");
leia::device::Config* config = g_sdk->GetDeviceConfig();
g_viewWidth = config->viewResolution[0];
g_viewHeight = config->viewResolution[1];
g_sdk->ReleaseDeviceConfig(config);
/*
// Initialize SDK.
g_sdk = leia::sdk::CreateLeiaSDK();
leia::PlatformInitArgs pia;
g_sdk->InitializePlatform(pia);
g_sdk->Initialize(nullptr);
// Initialize interlacer.
leia::sdk::ThreadedInterlacerInitArgs interlacerInitArgs = {};
interlacerInitArgs.useMegaTextureForViews = true;
interlacerInitArgs.graphicsAPI = leia::sdk::GraphicsAPI::D3D12;
g_interlacer = g_sdk->CreateNewThreadedInterlacer(interlacerInitArgs);
g_interlacer->InitializeD3D12(g_device, g_commandQueue, leia::sdk::eLeiaTaskResponsibility::SDK, leia::sdk::eLeiaTaskResponsibility::SDK, leia::sdk::eLeiaTaskResponsibility::SDK);
// Initialize interlacer GUI.
if (g_showGUI)
{
leia::sdk::DebugMenuInitArgs debugMenuInitArgs;
debugMenuInitArgs.gui.surface = hWnd;
debugMenuInitArgs.gui.d3d12Device = g_device;
debugMenuInitArgs.gui.d3d12DeviceCbvSrvHeap = g_srvHeap;
debugMenuInitArgs.gui.d3d12FontSrvCpuDescHandle = *((uint64_t*)&g_srvFontCpuDescHandle);
debugMenuInitArgs.gui.d3d12FontSrvGpuDescHandle = *((uint64_t*)&g_srvFontGpuDescHandle);
debugMenuInitArgs.gui.d3d12NumFramesInFlight = g_frameCount;
debugMenuInitArgs.gui.d3d12RtvFormat = g_swapChainFormat;
debugMenuInitArgs.gui.d3d12CommandList = g_guiCommandList;
debugMenuInitArgs.gui.graphicsAPI = leia::sdk::GuiGraphicsAPI::D3D12;
g_interlacer->InitializeGui(debugMenuInitArgs);
}
// Set stereo sliding mode.
g_interlacer->SetInterlaceMode(leia::sdk::eLeiaInterlaceMode::StereoSliding);
const int numViews = g_interlacer->GetNumViews();
if (numViews != 2)
OnError(L"Unexpected number of views");*/
}
void LoadScene()
{
if (g_demoMode == eDemoMode::Spinning3DCube)
{
const float cubeWidth = 200.0f;
const float cubeHeight = 200.0f;
const float cubeDepth = 200.0f;
const float l = -cubeWidth / 2.0f;
const float r = l + cubeWidth;
const float b = -cubeHeight / 2.0f;
const float t = b + cubeHeight;
const float n = -cubeDepth / 2.0f;
const float f = n + cubeDepth;
const int vertexCount = 8;
const int indexCount = 36;
const float cubeVerts[vertexCount][3] =
{
{l, n, b}, // Left Near Bottom
{l, f, b}, // Left Far Bottom
{r, f, b}, // Right Far Bottom
{r, n, b}, // Right Near Bottom
{l, n, t}, // Left Near Top
{l, f, t}, // Left Far Top
{r, f, t}, // Right Far Top
{r, n, t} // Right Near Top
};
static const int faces[6][4] =
{
{0,1,2,3}, // bottom
{1,0,4,5}, // left
{0,3,7,4}, // front
{3,2,6,7}, // right
{2,1,5,6}, // back
{4,7,6,5} // top
};
float c = GetSRGB(0.5f);