forked from GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathD3D12Sample.cpp
More file actions
1825 lines (1579 loc) · 76.4 KB
/
D3D12Sample.cpp
File metadata and controls
1825 lines (1579 loc) · 76.4 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
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
//
// Copyright (c) 2019-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Common.h"
#include "D3D12MemAlloc.h"
#include "Tests.h"
#include <atomic>
#include <Shlwapi.h> // For StrStrI
namespace VS
{
#include "Shaders\VS_Compiled.h"
}
namespace PS
{
#include "Shaders\PS_Compiled.h"
}
#if D3D12MA_USE_AGILITY_SDK
#if D3D12MA_USE_AGILITY_SDK_PREVIEW
extern "C" { __declspec(dllexport) extern const UINT D3D12SDKVersion = D3D12_PREVIEW_SDK_VERSION; }
#else
extern "C" { __declspec(dllexport) extern const UINT D3D12SDKVersion = D3D12_SDK_VERSION; }
#endif
extern "C" { __declspec(dllexport) extern const char* D3D12SDKPath = ".\\D3D12\\"; }
#endif
enum class ExitCode : int
{
GPUList = 2,
Help = 1,
Success = 0,
RuntimeError = -1,
CommandLineError = -2,
};
static const wchar_t * const CLASS_NAME = L"D3D12MemAllocSample";
static const wchar_t * const WINDOW_TITLE = L"D3D12 Memory Allocator Sample";
static const int SIZE_X = 1024;
static const int SIZE_Y = 576;
static const bool FULLSCREEN = false;
static const UINT PRESENT_SYNC_INTERVAL = 1;
static const DXGI_FORMAT RENDER_TARGET_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM;
static const DXGI_FORMAT DEPTH_STENCIL_FORMAT = DXGI_FORMAT_D32_FLOAT;
static const size_t FRAME_BUFFER_COUNT = 3; // number of buffers we want, 2 for double buffering, 3 for tripple buffering
static const D3D_FEATURE_LEVEL MY_D3D_FEATURE_LEVEL = D3D_FEATURE_LEVEL_12_0;
static const bool ENABLE_DEBUG_LAYER = true;
static const bool ENABLE_CPU_ALLOCATION_CALLBACKS = true;
static const bool ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT = false;
static constexpr D3D12MA::ALLOCATOR_FLAGS g_AllocatorFlags = D3D12MA::ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED;
static D3D12MA::ALLOCATION_CALLBACKS g_AllocationCallbacks = {}; // Used only when ENABLE_CPU_ALLOCATION_CALLBACKS
static HINSTANCE g_Instance;
static HWND g_Wnd;
struct GPUSelection
{
UINT32 Index = UINT32_MAX;
std::wstring Substring;
};
class DXGIUsage
{
public:
void Init();
IDXGIFactory4* GetDXGIFactory() const { return m_DXGIFactory.Get(); }
void PrintAdapterList() const;
// If failed, returns null pointer.
ComPtr<IDXGIAdapter1> CreateAdapter(const GPUSelection& GPUSelection) const;
private:
ComPtr<IDXGIFactory4> m_DXGIFactory;
};
static UINT64 g_TimeOffset; // In ms.
static UINT64 g_TimeValue; // Time since g_TimeOffset, in ms.
static float g_Time; // g_TimeValue converted to float, in seconds.
static float g_TimeDelta;
static DXGIUsage* g_DXGIUsage;
static ComPtr<ID3D12Device> g_Device;
DXGI_ADAPTER_DESC1 g_AdapterDesc;
static ComPtr<D3D12MA::Allocator> g_Allocator;
static ComPtr<IDXGISwapChain3> g_SwapChain; // swapchain used to switch between render targets
static ComPtr<ID3D12CommandQueue> g_CommandQueue; // container for command lists
static ComPtr<ID3D12DescriptorHeap> g_RtvDescriptorHeap; // a descriptor heap to hold resources like the render targets
static ComPtr<ID3D12Resource> g_RenderTargets[FRAME_BUFFER_COUNT]; // number of render targets equal to buffer count
static ComPtr<ID3D12CommandAllocator> g_CommandAllocators[FRAME_BUFFER_COUNT]; // we want enough allocators for each buffer * number of threads (we only have one thread)
static ComPtr<ID3D12GraphicsCommandList> g_CommandList; // a command list we can record commands into, then execute them to render the frame
static ComPtr<ID3D12Fence> g_Fences[FRAME_BUFFER_COUNT]; // an object that is locked while our command list is being executed by the gpu. We need as many
//as we have allocators (more if we want to know when the gpu is finished with an asset)
static HANDLE g_FenceEvent; // a handle to an event when our g_Fences is unlocked by the gpu
static UINT64 g_FenceValues[FRAME_BUFFER_COUNT]; // this value is incremented each frame. each g_Fences will have its own value
static UINT g_FrameIndex; // current rtv we are on
static UINT g_RtvDescriptorSize; // size of the rtv descriptor on the g_Device (all front and back buffers will be the same size)
static ComPtr<ID3D12PipelineState> g_PipelineStateObject;
static ComPtr<ID3D12RootSignature> g_RootSignature;
static ComPtr<ID3D12Resource> g_VertexBuffer;
static D3D12MA::Allocation* g_VertexBufferAllocation;
static ComPtr<ID3D12Resource> g_IndexBuffer;
static D3D12MA::Allocation* g_IndexBufferAllocation;
static D3D12_VERTEX_BUFFER_VIEW g_VertexBufferView;
static D3D12_INDEX_BUFFER_VIEW g_IndexBufferView;
static ComPtr<ID3D12Resource> g_DepthStencilBuffer;
static D3D12MA::Allocation* g_DepthStencilAllocation;
static ComPtr<ID3D12DescriptorHeap> g_DepthStencilDescriptorHeap;
struct Vertex {
vec3 pos;
vec2 texCoord;
Vertex() { }
Vertex(float x, float y, float z, float tx, float ty) :
pos(x, y, z),
texCoord(tx, ty)
{
}
};
struct ConstantBuffer0_PS
{
vec4 Color;
};
struct ConstantBuffer1_VS
{
mat4 WorldViewProj;
};
static const size_t ConstantBufferPerObjectAlignedSize = AlignUp<size_t>(sizeof(ConstantBuffer1_VS), 256);
static D3D12MA::Allocation* g_CbPerObjectUploadHeapAllocations[FRAME_BUFFER_COUNT];
static ComPtr<ID3D12Resource> g_CbPerObjectUploadHeaps[FRAME_BUFFER_COUNT];
static void* g_CbPerObjectAddress[FRAME_BUFFER_COUNT];
static uint32_t g_CubeIndexCount;
static ComPtr<ID3D12DescriptorHeap> g_MainDescriptorHeap[FRAME_BUFFER_COUNT];
static ComPtr<ID3D12Resource> g_ConstantBufferUploadHeap[FRAME_BUFFER_COUNT];
static D3D12MA::Allocation* g_ConstantBufferUploadAllocation[FRAME_BUFFER_COUNT];
static void* g_ConstantBufferAddress[FRAME_BUFFER_COUNT];
static ComPtr<ID3D12Resource> g_Texture;
static D3D12MA::Allocation* g_TextureAllocation;
static void* const CUSTOM_ALLOCATION_PRIVATE_DATA = (void*)(uintptr_t)0xDEADC0DE;
static std::atomic<size_t> g_CpuAllocationCount{0};
static void* CustomAllocate(size_t Size, size_t Alignment, void* pPrivateData)
{
assert(pPrivateData == CUSTOM_ALLOCATION_PRIVATE_DATA);
void* memory = _aligned_malloc(Size, Alignment);
if(ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT)
{
wprintf(L"Allocate Size=%llu Alignment=%llu -> %p\n", Size, Alignment, memory);
}
++g_CpuAllocationCount;
return memory;
}
static void CustomFree(void* pMemory, void* pPrivateData)
{
assert(pPrivateData == CUSTOM_ALLOCATION_PRIVATE_DATA);
if(pMemory)
{
--g_CpuAllocationCount;
if(ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT)
{
wprintf(L"Free %p\n", pMemory);
}
_aligned_free(pMemory);
}
}
struct CommandLineParameters
{
bool m_Help = false;
bool m_List = false;
bool m_Test = false;
GPUSelection m_GPUSelection;
bool Parse(int argc, wchar_t** argv)
{
for(int i = 1; i < argc; ++i)
{
if(_wcsicmp(argv[i], L"-h") == 0 || _wcsicmp(argv[i], L"--Help") == 0)
{
m_Help = true;
}
else if(_wcsicmp(argv[i], L"-l") == 0 || _wcsicmp(argv[i], L"--List") == 0)
{
m_List = true;
}
else if((_wcsicmp(argv[i], L"-g") == 0 || _wcsicmp(argv[i], L"--GPU") == 0) && i + 1 < argc)
{
m_GPUSelection.Substring = argv[i + 1];
++i;
}
else if((_wcsicmp(argv[i], L"-i") == 0 || _wcsicmp(argv[i], L"--GPUIndex") == 0) && i + 1 < argc)
{
m_GPUSelection.Index = _wtoi(argv[i + 1]);
++i;
}
else if (_wcsicmp(argv[i], L"-t") == 0 || _wcsicmp(argv[i], L"--Test") == 0)
{
m_Test = true;
}
else
return false;
}
return true;
}
} g_CommandLineParameters;
static void SetDefaultRasterizerDesc(D3D12_RASTERIZER_DESC& outDesc)
{
outDesc.FillMode = D3D12_FILL_MODE_SOLID;
outDesc.CullMode = D3D12_CULL_MODE_BACK;
outDesc.FrontCounterClockwise = FALSE;
outDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
outDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
outDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
outDesc.DepthClipEnable = TRUE;
outDesc.MultisampleEnable = FALSE;
outDesc.AntialiasedLineEnable = FALSE;
outDesc.ForcedSampleCount = 0;
outDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
}
static void SetDefaultBlendDesc(D3D12_BLEND_DESC& outDesc)
{
outDesc.AlphaToCoverageEnable = FALSE;
outDesc.IndependentBlendEnable = FALSE;
const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {
FALSE,FALSE,
D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
D3D12_LOGIC_OP_NOOP,
D3D12_COLOR_WRITE_ENABLE_ALL };
for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
outDesc.RenderTarget[i] = defaultRenderTargetBlendDesc;
}
static void SetDefaultDepthStencilDesc(D3D12_DEPTH_STENCIL_DESC& outDesc)
{
outDesc.DepthEnable = TRUE;
outDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
outDesc.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
outDesc.StencilEnable = FALSE;
outDesc.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
outDesc.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = {
D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS };
outDesc.FrontFace = defaultStencilOp;
outDesc.BackFace = defaultStencilOp;
}
void WaitForFrame(size_t frameIndex) // wait until gpu is finished with command list
{
// if the current g_Fences value is still less than "g_FenceValues", then we know the GPU has not finished executing
// the command queue since it has not reached the "g_CommandQueue->Signal(g_Fences, g_FenceValues)" command
if (g_Fences[frameIndex]->GetCompletedValue() < g_FenceValues[frameIndex])
{
// we have the g_Fences create an event which is signaled once the g_Fences's current value is "g_FenceValues"
CHECK_HR( g_Fences[frameIndex]->SetEventOnCompletion(g_FenceValues[frameIndex], g_FenceEvent) );
// We will wait until the g_Fences has triggered the event that it's current value has reached "g_FenceValues". once it's value
// has reached "g_FenceValues", we know the command queue has finished executing
WaitForSingleObject(g_FenceEvent, INFINITE);
}
}
void WaitGPUIdle(size_t frameIndex)
{
g_FenceValues[frameIndex]++;
CHECK_HR( g_CommandQueue->Signal(g_Fences[frameIndex].Get(), g_FenceValues[frameIndex]) );
WaitForFrame(frameIndex);
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// Row-by-row memcpy
inline void MemcpySubresource(
_In_ const D3D12_MEMCPY_DEST* pDest,
_In_ const D3D12_SUBRESOURCE_DATA* pSrc,
SIZE_T RowSizeInBytes,
UINT NumRows,
UINT NumSlices)
{
for (UINT z = 0; z < NumSlices; ++z)
{
BYTE* pDestSlice = reinterpret_cast<BYTE*>(pDest->pData) + pDest->SlicePitch * z;
const BYTE* pSrcSlice = reinterpret_cast<const BYTE*>(pSrc->pData) + pSrc->SlicePitch * z;
for (UINT y = 0; y < NumRows; ++y)
{
memcpy(pDestSlice + pDest->RowPitch * y,
pSrcSlice + pSrc->RowPitch * y,
RowSizeInBytes);
}
}
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
inline UINT64 UpdateSubresources(
_In_ ID3D12GraphicsCommandList* pCmdList,
_In_ ID3D12Resource* pDestinationResource,
_In_ ID3D12Resource* pIntermediate,
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,
UINT64 RequiredSize,
_In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts,
_In_reads_(NumSubresources) const UINT* pNumRows,
_In_reads_(NumSubresources) const UINT64* pRowSizesInBytes,
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData)
{
// Minor validation
D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc();
D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc();
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > (SIZE_T)-1 ||
(DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER &&
(FirstSubresource != 0 || NumSubresources != 1)))
{
return 0;
}
BYTE* pData;
HRESULT hr = pIntermediate->Map(0, &EMPTY_RANGE, reinterpret_cast<void**>(&pData));
if (FAILED(hr))
{
return 0;
}
for (UINT i = 0; i < NumSubresources; ++i)
{
if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0;
D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] };
MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth);
}
pIntermediate->Unmap(0, NULL);
if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
{
D3D12_BOX SrcBox = {
UINT( pLayouts[0].Offset ), 0, 0,
UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ), 0, 0 };
pCmdList->CopyBufferRegion(
pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width);
}
else
{
for (UINT i = 0; i < NumSubresources; ++i)
{
D3D12_TEXTURE_COPY_LOCATION Dst = {};
Dst.pResource = pDestinationResource;
Dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
Dst.SubresourceIndex = i + FirstSubresource;
D3D12_TEXTURE_COPY_LOCATION Src = {};
Src.pResource = pIntermediate;
Src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
Src.PlacedFootprint = pLayouts[i];
pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr);
}
}
return RequiredSize;
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
inline UINT64 UpdateSubresources(
_In_ ID3D12GraphicsCommandList* pCmdList,
_In_ ID3D12Resource* pDestinationResource,
_In_ ID3D12Resource* pIntermediate,
UINT64 IntermediateOffset,
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,
_In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData)
{
UINT64 RequiredSize = 0;
UINT64 MemToAlloc = static_cast<UINT64>(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources;
if (MemToAlloc > SIZE_MAX)
{
return 0;
}
void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(MemToAlloc));
if (pMem == NULL)
{
return 0;
}
D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast<D3D12_PLACED_SUBRESOURCE_FOOTPRINT*>(pMem);
UINT64* pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
UINT* pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc();
// Needed because of the D3D Debug Layer error:
// D3D12 ERROR: ID3D12Device::GetCopyableFootprints: D3D12_RESOURCE_DESC::Alignment is invalid. The value is 16. When D3D12_RESOURCE_DESC::Flag bit for D3D12_RESOURCE_FLAG_USE_TIGHT_ALIGNMENT is set, Alignment must be 0. [ STATE_CREATION ERROR #721: CREATERESOURCE_INVALIDALIGNMENT]
Desc.Alignment = 0;
ID3D12Device* pDevice;
pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
pDevice->Release();
UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData);
HeapFree(GetProcessHeap(), 0, pMem);
return Result;
}
void DXGIUsage::Init()
{
g_Instance = (HINSTANCE)GetModuleHandle(NULL);
CoInitialize(NULL);
CHECK_HR( CreateDXGIFactory1(IID_PPV_ARGS(&m_DXGIFactory)) );
}
void DXGIUsage::PrintAdapterList() const
{
UINT index = 0;
ComPtr<IDXGIAdapter1> adapter;
while (m_DXGIFactory->EnumAdapters1(index, &adapter) != DXGI_ERROR_NOT_FOUND)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
const bool isSoftware = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;
const wchar_t* const suffix = isSoftware ? L" (SOFTWARE)" : L"";
wprintf(L"Adapter %u: %s%s\n", index, desc.Description, suffix);
adapter.Reset();
++index;
}
}
ComPtr<IDXGIAdapter1> DXGIUsage::CreateAdapter(const GPUSelection& GPUSelection) const
{
ComPtr<IDXGIAdapter1> adapter;
if(GPUSelection.Index != UINT32_MAX)
{
// Cannot specify both index and name.
if(!GPUSelection.Substring.empty())
{
return adapter;
}
CHECK_HR(m_DXGIFactory->EnumAdapters1(GPUSelection.Index, &adapter));
return adapter;
}
if(!GPUSelection.Substring.empty())
{
ComPtr<IDXGIAdapter1> tmpAdapter;
for(UINT i = 0; m_DXGIFactory->EnumAdapters1(i, &tmpAdapter) != DXGI_ERROR_NOT_FOUND; ++i)
{
DXGI_ADAPTER_DESC1 desc;
tmpAdapter->GetDesc1(&desc);
if(StrStrI(desc.Description, GPUSelection.Substring.c_str()))
{
// Second matching adapter found - error.
if(adapter)
{
adapter.Reset();
return adapter;
}
// First matching adapter found.
adapter = std::move(tmpAdapter);
}
else
{
tmpAdapter.Reset();
}
}
// Found or not, return it.
return adapter;
}
// Select first one.
m_DXGIFactory->EnumAdapters1(0, &adapter);
return adapter;
}
static const wchar_t* VendorIDToStr(uint32_t vendorID)
{
switch(vendorID)
{
case 0x10001: return L"VIV";
case 0x10002: return L"VSI";
case 0x10003: return L"KAZAN";
case 0x10004: return L"CODEPLAY";
case 0x10005: return L"MESA";
case 0x10006: return L"POCL";
case VENDOR_ID_AMD: return L"AMD";
case VENDOR_ID_NVIDIA: return L"NVIDIA";
case VENDOR_ID_INTEL: return L"Intel";
case 0x1010: return L"ImgTec";
case 0x13B5: return L"ARM";
case 0x5143: return L"Qualcomm";
}
return L"";
}
static std::wstring SizeToStr(size_t size)
{
if(size == 0)
return L"0";
wchar_t result[32];
double size2 = (double)size;
if (size2 >= 1024.0*1024.0*1024.0*1024.0)
{
swprintf_s(result, L"%.2f TB", size2 / (1024.0*1024.0*1024.0*1024.0));
}
else if (size2 >= 1024.0*1024.0*1024.0)
{
swprintf_s(result, L"%.2f GB", size2 / (1024.0*1024.0*1024.0));
}
else if (size2 >= 1024.0*1024.0)
{
swprintf_s(result, L"%.2f MB", size2 / (1024.0*1024.0));
}
else if (size2 >= 1024.0)
{
swprintf_s(result, L"%.2f KB", size2 / 1024.0);
}
else
swprintf_s(result, L"%llu B", size);
return result;
}
static void PrintAdapterInformation(IDXGIAdapter1* adapter)
{
assert(g_Allocator);
wprintf(L"DXGI_ADAPTER_DESC1:\n");
wprintf(L" Description = %s\n", g_AdapterDesc.Description);
wprintf(L" VendorId = 0x%X (%s)\n", g_AdapterDesc.VendorId, VendorIDToStr(g_AdapterDesc.VendorId));
wprintf(L" DeviceId = 0x%X\n", g_AdapterDesc.DeviceId);
wprintf(L" SubSysId = 0x%X\n", g_AdapterDesc.SubSysId);
wprintf(L" Revision = 0x%X\n", g_AdapterDesc.Revision);
wprintf(L" DedicatedVideoMemory = %zu B (%s)\n", g_AdapterDesc.DedicatedVideoMemory, SizeToStr(g_AdapterDesc.DedicatedVideoMemory).c_str());
wprintf(L" DedicatedSystemMemory = %zu B (%s)\n", g_AdapterDesc.DedicatedSystemMemory, SizeToStr(g_AdapterDesc.DedicatedSystemMemory).c_str());
wprintf(L" SharedSystemMemory = %zu B (%s)\n", g_AdapterDesc.SharedSystemMemory, SizeToStr(g_AdapterDesc.SharedSystemMemory).c_str());
const D3D12_FEATURE_DATA_D3D12_OPTIONS& options = g_Allocator->GetD3D12Options();
wprintf(L"D3D12_FEATURE_DATA_D3D12_OPTIONS:\n");
wprintf(L" StandardSwizzle64KBSupported = %u\n", options.StandardSwizzle64KBSupported ? 1 : 0);
wprintf(L" CrossAdapterRowMajorTextureSupported = %u\n", options.CrossAdapterRowMajorTextureSupported ? 1 : 0);
switch(options.ResourceHeapTier)
{
case D3D12_RESOURCE_HEAP_TIER_1:
wprintf(L" ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1\n");
break;
case D3D12_RESOURCE_HEAP_TIER_2:
wprintf(L" ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_2\n");
break;
default:
assert(0);
}
wprintf(L"GPUUploadHeapSupported = %u\n", g_Allocator->IsGPUUploadHeapSupported() ? 1 : 0);
wprintf(L"TightAlignmentSupported = %u\n", g_Allocator->IsTightAlignmentSupported() ? 1 : 0);
ComPtr<IDXGIAdapter3> adapter3;
if(SUCCEEDED(adapter->QueryInterface(IID_PPV_ARGS(&adapter3))))
{
wprintf(L"DXGI_QUERY_VIDEO_MEMORY_INFO:\n");
for(UINT groupIndex = 0; groupIndex < 2; ++groupIndex)
{
const DXGI_MEMORY_SEGMENT_GROUP group = groupIndex == 0 ? DXGI_MEMORY_SEGMENT_GROUP_LOCAL : DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL;
const wchar_t* const groupName = groupIndex == 0 ? L"DXGI_MEMORY_SEGMENT_GROUP_LOCAL" : L"DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL";
DXGI_QUERY_VIDEO_MEMORY_INFO info = {};
CHECK_HR(adapter3->QueryVideoMemoryInfo(0, group, &info));
wprintf(L" %s:\n", groupName);
wprintf(L" Budget = %llu B (%s)\n", info.Budget, SizeToStr(info.Budget).c_str());
wprintf(L" CurrentUsage = %llu B (%s)\n", info.CurrentUsage, SizeToStr(info.CurrentUsage).c_str());
wprintf(L" AvailableForReservation = %llu B (%s)\n", info.AvailableForReservation, SizeToStr(info.AvailableForReservation).c_str());
wprintf(L" CurrentReservation = %llu B (%s)\n", info.CurrentReservation, SizeToStr(info.CurrentReservation).c_str());
}
}
assert(g_Device);
D3D12_FEATURE_DATA_ARCHITECTURE1 architecture1 = {};
if(SUCCEEDED(g_Device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1, &architecture1, sizeof architecture1)))
{
wprintf(L"D3D12_FEATURE_DATA_ARCHITECTURE1:\n");
wprintf(L" UMA: %u\n", architecture1.UMA ? 1 : 0);
wprintf(L" CacheCoherentUMA: %u\n", architecture1.CacheCoherentUMA ? 1 : 0);
wprintf(L" IsolatedMMU: %u\n", architecture1.IsolatedMMU ? 1 : 0);
}
}
static void InitD3D() // initializes direct3d 12
{
assert(g_DXGIUsage);
ComPtr<IDXGIAdapter1> adapter = g_DXGIUsage->CreateAdapter(g_CommandLineParameters.m_GPUSelection);
CHECK_BOOL(adapter);
CHECK_HR(adapter->GetDesc1(&g_AdapterDesc));
// Must be done before D3D12 device is created.
if(ENABLE_DEBUG_LAYER)
{
ComPtr<ID3D12Debug> debug;
if(SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug))))
debug->EnableDebugLayer();
}
// Create the g_Device
ID3D12Device* device = nullptr;
CHECK_HR( D3D12CreateDevice(
adapter.Get(),
MY_D3D_FEATURE_LEVEL,
IID_PPV_ARGS(&device)) );
g_Device.Attach(device);
// Create allocator
{
D3D12MA::ALLOCATOR_DESC desc = {};
desc.Flags = g_AllocatorFlags;
desc.pDevice = device;
desc.pAdapter = adapter.Get();
if(ENABLE_CPU_ALLOCATION_CALLBACKS)
{
g_AllocationCallbacks.pAllocate = &CustomAllocate;
g_AllocationCallbacks.pFree = &CustomFree;
g_AllocationCallbacks.pPrivateData = CUSTOM_ALLOCATION_PRIVATE_DATA;
desc.pAllocationCallbacks = &g_AllocationCallbacks;
}
CHECK_HR( D3D12MA::CreateAllocator(&desc, &g_Allocator) );
}
PrintAdapterInformation(adapter.Get());
wprintf(L"\n");
// -- Create the Command Queue -- //
D3D12_COMMAND_QUEUE_DESC cqDesc = {}; // we will be using all the default values
ID3D12CommandQueue* commandQueue = nullptr;
CHECK_HR( g_Device->CreateCommandQueue(&cqDesc, IID_PPV_ARGS(&commandQueue)) ); // create the command queue
g_CommandQueue.Attach(commandQueue);
// -- Create the Swap Chain (double/tripple buffering) -- //
DXGI_MODE_DESC backBufferDesc = {}; // this is to describe our display mode
backBufferDesc.Width = SIZE_X; // buffer width
backBufferDesc.Height = SIZE_Y; // buffer height
backBufferDesc.Format = RENDER_TARGET_FORMAT; // format of the buffer (rgba 32 bits, 8 bits for each chanel)
// describe our multi-sampling. We are not multi-sampling, so we set the count to 1 (we need at least one sample of course)
DXGI_SAMPLE_DESC sampleDesc = {};
sampleDesc.Count = 1; // multisample count (no multisampling, so we just put 1, since we still need 1 sample)
// Describe and create the swap chain.
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = FRAME_BUFFER_COUNT; // number of buffers we have
swapChainDesc.BufferDesc = backBufferDesc; // our back buffer description
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // this says the pipeline will render to this swap chain
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // dxgi will discard the buffer (data) after we call present
swapChainDesc.OutputWindow = g_Wnd; // handle to our window
swapChainDesc.SampleDesc = sampleDesc; // our multi-sampling description
swapChainDesc.Windowed = !FULLSCREEN; // set to true, then if in fullscreen must call SetFullScreenState with true for full screen to get uncapped fps
IDXGISwapChain* tempSwapChain;
CHECK_HR( g_DXGIUsage->GetDXGIFactory()->CreateSwapChain(
g_CommandQueue.Get(), // the queue will be flushed once the swap chain is created
&swapChainDesc, // give it the swap chain description we created above
&tempSwapChain // store the created swap chain in a temp IDXGISwapChain interface
) );
g_SwapChain.Attach(static_cast<IDXGISwapChain3*>(tempSwapChain));
g_FrameIndex = g_SwapChain->GetCurrentBackBufferIndex();
// -- Create the Back Buffers (render target views) Descriptor Heap -- //
// describe an rtv descriptor heap and create
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
rtvHeapDesc.NumDescriptors = FRAME_BUFFER_COUNT; // number of descriptors for this heap.
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; // this heap is a render target view heap
// This heap will not be directly referenced by the shaders (not shader visible), as this will store the output from the pipeline
// otherwise we would set the heap's flag to D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
ID3D12DescriptorHeap* rtvDescriptorHeap = nullptr;
CHECK_HR( g_Device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&rtvDescriptorHeap)) );
g_RtvDescriptorHeap.Attach(rtvDescriptorHeap);
// get the size of a descriptor in this heap (this is a rtv heap, so only rtv descriptors should be stored in it.
// descriptor sizes may vary from g_Device to g_Device, which is why there is no set size and we must ask the
// g_Device to give us the size. we will use this size to increment a descriptor handle offset
g_RtvDescriptorSize = g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
// get a handle to the first descriptor in the descriptor heap. a handle is basically a pointer,
// but we cannot literally use it like a c++ pointer.
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle { g_RtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart() };
// Create a RTV for each buffer (double buffering is two buffers, tripple buffering is 3).
for (int i = 0; i < FRAME_BUFFER_COUNT; i++)
{
// first we get the n'th buffer in the swap chain and store it in the n'th
// position of our ID3D12Resource array
ID3D12Resource* res = nullptr;
CHECK_HR( g_SwapChain->GetBuffer(i, IID_PPV_ARGS(&res)) );
g_RenderTargets[i].Attach(res);
// the we "create" a render target view which binds the swap chain buffer (ID3D12Resource[n]) to the rtv handle
g_Device->CreateRenderTargetView(g_RenderTargets[i].Get(), nullptr, rtvHandle);
// we increment the rtv handle by the rtv descriptor size we got above
rtvHandle.ptr += g_RtvDescriptorSize;
}
// -- Create the Command Allocators -- //
for (int i = 0; i < FRAME_BUFFER_COUNT; i++)
{
ID3D12CommandAllocator* commandAllocator = nullptr;
CHECK_HR( g_Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&commandAllocator)) );
g_CommandAllocators[i].Attach(commandAllocator);
}
// create the command list with the first allocator
CHECK_HR( g_Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_CommandAllocators[0].Get(), NULL, IID_PPV_ARGS(&g_CommandList)) );
// command lists are created in the recording state. our main loop will set it up for recording again so close it now
g_CommandList->Close();
// create a depth stencil descriptor heap so we can get a pointer to the depth stencil buffer
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
CHECK_HR( g_Device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&g_DepthStencilDescriptorHeap)) );
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = DEPTH_STENCIL_FORMAT;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
depthOptimizedClearValue.DepthStencil.Stencil = 0;
D3D12MA::CALLOCATION_DESC depthStencilAllocDesc = D3D12MA::CALLOCATION_DESC{ D3D12_HEAP_TYPE_DEFAULT };
D3D12_RESOURCE_DESC depthStencilResourceDesc = {};
depthStencilResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
depthStencilResourceDesc.Alignment = 0;
depthStencilResourceDesc.Width = SIZE_X;
depthStencilResourceDesc.Height = SIZE_Y;
depthStencilResourceDesc.DepthOrArraySize = 1;
depthStencilResourceDesc.MipLevels = 1;
depthStencilResourceDesc.Format = DEPTH_STENCIL_FORMAT;
depthStencilResourceDesc.SampleDesc.Count = 1;
depthStencilResourceDesc.SampleDesc.Quality = 0;
depthStencilResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
depthStencilResourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
CHECK_HR( g_Allocator->CreateResource(
&depthStencilAllocDesc,
&depthStencilResourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&depthOptimizedClearValue,
&g_DepthStencilAllocation,
IID_PPV_ARGS(&g_DepthStencilBuffer)
) );
CHECK_HR( g_DepthStencilBuffer->SetName(L"Depth/Stencil Resource Heap") );
g_DepthStencilAllocation->SetName(L"Depth/Stencil Resource Heap");
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
depthStencilDesc.Format = DEPTH_STENCIL_FORMAT;
depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;
g_Device->CreateDepthStencilView(g_DepthStencilBuffer.Get(), &depthStencilDesc, g_DepthStencilDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
// -- Create a Fence & Fence Event -- //
// create the fences
for (int i = 0; i < FRAME_BUFFER_COUNT; i++)
{
ID3D12Fence* fence = nullptr;
CHECK_HR( g_Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)) );
g_Fences[i].Attach(fence);
g_FenceValues[i] = 0; // set the initial g_Fences value to 0
}
// create a handle to a g_Fences event
g_FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
assert(g_FenceEvent);
D3D12_DESCRIPTOR_RANGE cbDescriptorRange;
cbDescriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
cbDescriptorRange.NumDescriptors = 1;
cbDescriptorRange.BaseShaderRegister = 0;
cbDescriptorRange.RegisterSpace = 0;
cbDescriptorRange.OffsetInDescriptorsFromTableStart = 0;
D3D12_DESCRIPTOR_RANGE textureDescRange;
textureDescRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
textureDescRange.NumDescriptors = 1;
textureDescRange.BaseShaderRegister = 0;
textureDescRange.RegisterSpace = 0;
textureDescRange.OffsetInDescriptorsFromTableStart = 1;
D3D12_ROOT_PARAMETER rootParameters[3];
rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParameters[0].DescriptorTable = {1, &cbDescriptorRange};
rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParameters[1].Descriptor = {1, 0};
rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParameters[2].DescriptorTable = {1, &textureDescRange};
rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
// create root signature
// create a static sampler
D3D12_STATIC_SAMPLER_DESC sampler = {};
sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.MipLODBias = 0;
sampler.MaxAnisotropy = 0;
sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
sampler.MinLOD = 0.0f;
sampler.MaxLOD = D3D12_FLOAT32_MAX;
sampler.ShaderRegister = 0;
sampler.RegisterSpace = 0;
sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc = {};
rootSignatureDesc.NumParameters = _countof(rootParameters);
rootSignatureDesc.pParameters = rootParameters;
rootSignatureDesc.NumStaticSamplers = 1;
rootSignatureDesc.pStaticSamplers = &sampler;
rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
ComPtr<ID3DBlob> signatureBlob;
ID3DBlob* signatureBlobPtr;
CHECK_HR( D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signatureBlobPtr, nullptr) );
signatureBlob.Attach(signatureBlobPtr);
ID3D12RootSignature* rootSignature = nullptr;
CHECK_HR( device->CreateRootSignature(0, signatureBlob->GetBufferPointer(), signatureBlob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)) );
g_RootSignature.Attach(rootSignature);
for (int i = 0; i < FRAME_BUFFER_COUNT; ++i)
{
D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
heapDesc.NumDescriptors = 2;
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
CHECK_HR( g_Device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&g_MainDescriptorHeap[i])) );
}
// # CONSTANT BUFFER
for (int i = 0; i < FRAME_BUFFER_COUNT; ++i)
{
D3D12MA::CALLOCATION_DESC constantBufferUploadAllocDesc = D3D12MA::CALLOCATION_DESC{ D3D12_HEAP_TYPE_UPLOAD };
D3D12_RESOURCE_DESC constantBufferResourceDesc = {};
constantBufferResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
constantBufferResourceDesc.Alignment = 0;
constantBufferResourceDesc.Width = 1024 * 64;
constantBufferResourceDesc.Height = 1;
constantBufferResourceDesc.DepthOrArraySize = 1;
constantBufferResourceDesc.MipLevels = 1;
constantBufferResourceDesc.Format = DXGI_FORMAT_UNKNOWN;
constantBufferResourceDesc.SampleDesc.Count = 1;
constantBufferResourceDesc.SampleDesc.Quality = 0;
constantBufferResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
constantBufferResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
CHECK_HR( g_Allocator->CreateResource(
&constantBufferUploadAllocDesc,
&constantBufferResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
&g_ConstantBufferUploadAllocation[i],
IID_PPV_ARGS(&g_ConstantBufferUploadHeap[i])) );
g_ConstantBufferUploadHeap[i]->SetName(L"Constant Buffer Upload Resource Heap");
g_ConstantBufferUploadAllocation[i]->SetName(L"Constant Buffer Upload Resource Heap");
D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
cbvDesc.BufferLocation = g_ConstantBufferUploadHeap[i]->GetGPUVirtualAddress();
cbvDesc.SizeInBytes = AlignUp<UINT>(sizeof(ConstantBuffer0_PS), 256);
g_Device->CreateConstantBufferView(&cbvDesc, g_MainDescriptorHeap[i]->GetCPUDescriptorHandleForHeapStart());
CHECK_HR( g_ConstantBufferUploadHeap[i]->Map(0, &EMPTY_RANGE, &g_ConstantBufferAddress[i]) );
}
// create input layout
// The input layout is used by the Input Assembler so that it knows
// how to read the vertex data bound to it.
const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
// create a pipeline state object (PSO)
// In a real application, you will have many pso's. for each different shader
// or different combinations of shaders, different blend states or different rasterizer states,
// different topology types (point, line, triangle, patch), or a different number
// of render targets you will need a pso
// VS is the only required shader for a pso. You might be wondering when a case would be where
// you only set the VS. It's possible that you have a pso that only outputs data with the stream
// output, and not on a render target, which means you would not need anything after the stream
// output.
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; // a structure to define a pso
psoDesc.InputLayout.NumElements = _countof(inputLayout);
psoDesc.InputLayout.pInputElementDescs = inputLayout;
psoDesc.pRootSignature = g_RootSignature.Get(); // the root signature that describes the input data this pso needs
psoDesc.VS.BytecodeLength = sizeof(VS::g_main);
psoDesc.VS.pShaderBytecode = VS::g_main;
psoDesc.PS.BytecodeLength = sizeof(PS::g_main);
psoDesc.PS.pShaderBytecode = PS::g_main;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // type of topology we are drawing
psoDesc.RTVFormats[0] = RENDER_TARGET_FORMAT; // format of the render target
psoDesc.DSVFormat = DEPTH_STENCIL_FORMAT;
psoDesc.SampleDesc = sampleDesc; // must be the same sample description as the swapchain and depth/stencil buffer
psoDesc.SampleMask = 0xffffffff; // sample mask has to do with multi-sampling. 0xffffffff means point sampling is done
SetDefaultRasterizerDesc(psoDesc.RasterizerState);
SetDefaultBlendDesc(psoDesc.BlendState);
psoDesc.NumRenderTargets = 1; // we are only binding one render target
SetDefaultDepthStencilDesc(psoDesc.DepthStencilState);
// create the pso
ID3D12PipelineState* pipelineStateObject;
CHECK_HR( device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineStateObject)) );
g_PipelineStateObject.Attach(pipelineStateObject);
// Create vertex buffer
// a triangle
Vertex vList[] = {
// front face
{ -0.5f, 0.5f, -0.5f, 0.f, 0.f },
{ 0.5f, -0.5f, -0.5f, 1.f, 1.f },