-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathgfx.cpp
10557 lines (9981 loc) · 573 KB
/
gfx.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
/****************************************************************************
MIT License
Copyright (c) 2024 Guillaume Boissé
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 "gfx.h"
#include <map> // std::map
#include <deque> // std::deque
#include <memory> // std::unique_ptr
#include <direct.h> // _mkdir()
#include <aclapi.h> // SetEntriesInAcl()
#include <accctrl.h> // EXPLICIT_ACCESS
#include <dxcapi.h> // shader compiler
#include <d3d12shader.h> // shader reflection
#include <D3D12MemAlloc.h> // D3D12 memory allocator
#include <dxgi1_6.h> // IDXGIFactory6 + IDXGIOutput6
#include <filesystem>
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wmissing-field-initializers"
# pragma clang diagnostic ignored "-Wmisleading-indentation"
# pragma clang diagnostic ignored "-Wswitch"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wtautological-undefined-compare"
# pragma clang diagnostic ignored "-Wunused-but-set-variable"
# pragma clang diagnostic ignored "-Wunused-function"
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
# pragma GCC diagnostic ignored "-Wmisleading-indentation"
# pragma GCC diagnostic ignored "-Wswitch"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wtautological-undefined-compare"
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
# pragma GCC diagnostic ignored "-Wunused-function"
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4100) // unreferenced formal parameter
# pragma warning(disable:4127) // conditional expression is constant
# pragma warning(disable:4189) // local variable is initialized but not referenced
# pragma warning(disable:4211) // nonstandard extension used: redefined extern to static
#endif
#include <WinPixEventRuntime/pix3.h>
#ifdef __clang__
# pragma clang diagnostic pop
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#elif defined(_MSC_VER)
# pragma warning(pop)
#endif
extern "C"
{
__declspec(dllexport) extern const UINT D3D12SDKVersion = 614;
__declspec(dllexport) extern char8_t const *D3D12SDKPath = u8".\\";
__declspec(dllexport) UINT GetD3D12SDKVersion()
{
return D3D12SDKVersion;
}
}
class GfxInternal
{
GFX_NON_COPYABLE(GfxInternal);
HWND window_ = {};
uint32_t window_width_ = 0;
uint32_t window_height_ = 0;
uint32_t max_frames_in_flight_ = 0;
ID3D12Device *device_ = nullptr;
IDXGIAdapter1 *adapter_ = nullptr;
ID3D12Device5 *dxr_device_ = nullptr;
ID3D12Device2 *mesh_device_ = nullptr;
ID3D12CommandQueue *command_queue_ = nullptr;
ID3D12GraphicsCommandList *command_list_ = nullptr;
ID3D12GraphicsCommandList4 *dxr_command_list_ = nullptr;
ID3D12GraphicsCommandList6 *mesh_command_list_ = nullptr;
ID3D12CommandAllocator **command_allocators_ = nullptr;
std::vector<IAmdExtD3DDevice1 *> amd_ext_devices_;
HANDLE fence_event_ = {};
uint32_t fence_index_ = 0;
ID3D12Fence **fences_ = nullptr;
uint64_t *fence_values_ = nullptr;
bool debug_shaders_ = false;
bool cache_shaders_ = false;
bool experimental_shaders_ = false;
IDxcUtils *dxc_utils_ = nullptr;
IDxcCompiler3 *dxc_compiler_ = nullptr;
IDxcIncludeHandler *dxc_include_handler_ = nullptr;
IDXGISwapChain3 *swap_chain_ = nullptr;
D3D12MA::Allocator *mem_allocator_ = nullptr;
ID3D12CommandSignature *dispatch_signature_ = nullptr;
ID3D12CommandSignature *multi_draw_signature_ = nullptr;
ID3D12CommandSignature *multi_draw_indexed_signature_ = nullptr;
ID3D12CommandSignature *dispatch_rays_signature_ = nullptr;
ID3D12CommandSignature *draw_mesh_signature_ = nullptr;
std::vector<D3D12_RESOURCE_BARRIER> resource_barriers_;
ID3D12Resource **back_buffers_ = nullptr;
D3D12MA::Allocation **back_buffer_allocations_ = nullptr;
DXGI_FORMAT back_buffer_format_ = DXGI_FORMAT_R8G8B8A8_UNORM;
DXGI_COLOR_SPACE_TYPE color_space_ = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
uint32_t *back_buffer_rtvs_ = nullptr;
bool is_interop_ = false;
GfxKernel bound_kernel_ = {};
GfxBuffer draw_id_buffer_ = {};
uint64_t descriptor_heap_id_ = 0;
GfxBuffer bound_index_buffer_ = {};
GfxBuffer bound_vertex_buffer_ = {};
GfxBuffer texture_upload_buffer_ = {};
GfxBuffer installed_index_buffer_ = {};
GfxBuffer installed_vertex_buffer_ = {};
bool force_install_index_buffer_ = false;
bool force_install_vertex_buffer_ = false;
bool force_install_draw_id_buffer_ = false;
GfxBuffer raytracing_scratch_buffer_ = {};
GfxBuffer *constant_buffer_pool_ = nullptr;
uint64_t *constant_buffer_pool_cursors_ = nullptr;
std::vector<GfxRaytracingPrimitive> active_raytracing_primitives_;
struct RenderTarget
{
GfxTexture texture_ = {};
uint32_t mip_level_ = 0;
uint32_t slice_ = 0;
};
RenderTarget bound_color_targets_[kGfxConstant_MaxRenderTarget] = {};
RenderTarget bound_depth_stencil_target_ = {};
struct Viewport
{
inline Viewport &operator =(D3D12_VIEWPORT const &other)
{
x_ = other.TopLeftX;
y_ = other.TopLeftY;
width_ = other.Width;
height_ = other.Height;
return *this;
}
inline bool operator !=(D3D12_VIEWPORT const &other) const
{
return (x_ != other.TopLeftX || y_ != other.TopLeftY || width_ != other.Width || height_ != other.Height);
}
inline void invalidate()
{
width_ = NAN;
height_ = NAN;
}
float x_ = 0.0f;
float y_ = 0.0f;
float width_ = 0.0f;
float height_ = 0.0f;
};
Viewport viewport_;
Viewport bound_viewport_;
struct ScissorRect
{
inline ScissorRect &operator =(D3D12_RECT const &other)
{
x_ = (int32_t)other.left;
y_ = (int32_t)other.top;
width_ = (int32_t)(other.right - other.left);
height_ = (int32_t)(other.bottom - other.top);
return *this;
}
inline bool operator !=(D3D12_RECT const &other) const
{
return (x_ != other.left || y_ != other.top || x_ + width_ != other.right || y_ + height_ != other.bottom);
}
inline void invalidate()
{
width_ = -1;
height_ = -1;
}
int32_t x_ = 0;
int32_t y_ = 0;
int32_t width_ = 0;
int32_t height_ = 0;
};
ScissorRect scissor_rect_;
ScissorRect bound_scissor_rect_;
GfxKernel clear_buffer_kernel_ = {};
GfxProgram clear_buffer_program_ = {};
bool issued_clear_buffer_warning_ = false;
GfxKernel copy_to_backbuffer_kernel_ = {};
GfxProgram copy_to_backbuffer_program_ = {};
struct MipKernels
{
GfxProgram mip_program_ = {};
GfxKernel mip_kernel_ = {};
};
std::map<uint32_t, MipKernels> mip_kernels_;
struct ScanKernels
{
GfxProgram scan_program_ = {};
GfxKernel reduce_kernel_ = {};
GfxKernel scan_add_kernel_ = {};
GfxKernel scan_kernel_ = {};
GfxKernel args_kernel_ = {};
};
std::map<uint32_t, ScanKernels> scan_kernels_;
struct SortKernels
{
GfxProgram sort_program_ = {};
GfxKernel histogram_kernel_ = {};
GfxKernel scatter_kernel_ = {};
GfxKernel args_kernel_ = {};
};
GfxBuffer sort_scratch_buffer_;
std::map<uint32_t, SortKernels> sort_kernels_;
struct String
{
char *data_;
GFX_NON_COPYABLE(String);
inline String() : data_(nullptr) {}
inline String(char const *data) : data_(nullptr) { *this = data; }
inline String(String &&other) : data_(other.data_) { other.data_ = nullptr; }
inline String &operator =(String &&other) { if(this != &other) { gfxFree(data_); data_ = other.data_; other.data_ = nullptr; } return *this; }
inline String &operator =(char const *data) { gfxFree(data_); if(!data) data_ = nullptr; else
{ data_ = (char *)gfxMalloc(strlen(data) + 1); strcpy(data_, data); }
return *this; }
inline operator char const *() const { return data_ ? data_ : ""; }
inline size_t size() const { return data_ ? strlen(data_) : 0; }
inline char const *c_str() const { return data_ ? data_ : ""; }
inline operator bool() const { return data_ != nullptr; }
inline ~String() { gfxFree(data_); }
};
struct Garbage
{
GFX_NON_COPYABLE(Garbage);
typedef void (*Collector)(Garbage const &garbage);
inline Garbage() : deletion_counter_(0), garbage_collector_(nullptr) { memset(garbage_, 0, sizeof(garbage_)); }
inline Garbage(Garbage &&other) : deletion_counter_(other.deletion_counter_), garbage_collector_(other.garbage_collector_) { memcpy(garbage_, other.garbage_, sizeof(garbage_)); other.garbage_collector_ = nullptr; }
inline Garbage &operator =(Garbage &&other) { if(this != &other) { GFX_ASSERT(!garbage_collector_); if(garbage_collector_) garbage_collector_(*this); memcpy(garbage_, other.garbage_, sizeof(garbage_)); deletion_counter_ = other.deletion_counter_; garbage_collector_ = other.garbage_collector_; other.garbage_collector_ = nullptr; } return *this; }
inline ~Garbage() { GFX_ASSERT(!!deletion_counter_ || !garbage_collector_); if(garbage_collector_) garbage_collector_(*this); }
template<typename TYPE>
static void ResourceCollector(Garbage const &garbage)
{
TYPE *resource = (TYPE *)garbage.garbage_[0];
GFX_ASSERT(resource != nullptr); if(resource == nullptr) return;
resource->Release(); // release resource
}
static void DescriptorCollector(Garbage const &garbage)
{
uint32_t const descriptor_slot = (uint32_t)garbage.garbage_[0];
GfxFreelist *descriptor_freelist = (GfxFreelist *)garbage.garbage_[1];
GFX_ASSERT(descriptor_freelist != nullptr); if(descriptor_freelist == nullptr) return;
descriptor_freelist->free_slot(descriptor_slot); // release descriptor slot
}
uintptr_t garbage_[2];
uint32_t deletion_counter_;
Collector garbage_collector_;
};
std::deque<Garbage> garbage_collection_;
struct DescriptorHeap
{
inline D3D12_CPU_DESCRIPTOR_HANDLE getCPUHandle(uint32_t descriptor_slot) const
{
GFX_ASSERT(descriptor_slot < (descriptor_heap_ != nullptr ? descriptor_heap_->GetDesc().NumDescriptors : 0));
D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle = descriptor_heap_->GetCPUDescriptorHandleForHeapStart();
cpu_handle.ptr += descriptor_slot * descriptor_handle_size_;
return cpu_handle;
}
inline D3D12_GPU_DESCRIPTOR_HANDLE getGPUHandle(uint32_t descriptor_slot) const
{
GFX_ASSERT(descriptor_slot < (descriptor_heap_ != nullptr ? descriptor_heap_->GetDesc().NumDescriptors : 0));
D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle = descriptor_heap_->GetGPUDescriptorHandleForHeapStart();
gpu_handle.ptr += descriptor_slot * descriptor_handle_size_;
return gpu_handle;
}
uint32_t descriptor_handle_size_ = 0;
ID3D12DescriptorHeap *descriptor_heap_ = nullptr;
};
DescriptorHeap descriptors_;
DescriptorHeap dsv_descriptors_;
DescriptorHeap rtv_descriptors_;
DescriptorHeap sampler_descriptors_;
GfxFreelist freelist_descriptors_;
GfxFreelist freelist_dsv_descriptors_;
GfxFreelist freelist_rtv_descriptors_;
GfxFreelist freelist_sampler_descriptors_;
struct DrawState
{
struct Data
{
DXGI_FORMAT color_formats_[kGfxConstant_MaxRenderTarget] = {};
DXGI_FORMAT depth_stencil_format_ = {};
D3D12_PRIMITIVE_TOPOLOGY_TYPE primitive_topology_type_ = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
struct
{
inline operator bool() const
{
return (src_blend_ != 0 && dst_blend_ != 0 && blend_op_ != 0 && src_blend_alpha_ != 0 && dst_blend_alpha_ != 0 && blend_op_alpha_ != 0);
}
D3D12_BLEND src_blend_ = {};
D3D12_BLEND dst_blend_ = {};
D3D12_BLEND_OP blend_op_ = {};
D3D12_BLEND src_blend_alpha_ = {};
D3D12_BLEND dst_blend_alpha_ = {};
D3D12_BLEND_OP blend_op_alpha_ = {};
} blend_state_;
struct
{
D3D12_COMPARISON_FUNC depth_func_ = D3D12_COMPARISON_FUNC_LESS;
D3D12_DEPTH_WRITE_MASK depth_write_mask_ = D3D12_DEPTH_WRITE_MASK_ALL;
} depth_stencil_state_;
struct
{
D3D12_CULL_MODE cull_mode_ = D3D12_CULL_MODE_BACK;
D3D12_FILL_MODE fill_mode_ = D3D12_FILL_MODE_SOLID;
} raster_state_;
};
DrawState() : reference_count_(0) {}
DrawState(DrawState &&other) : draw_state_(other.draw_state_), reference_count_(other.reference_count_) { other.reference_count_ = 0; }
~DrawState() { GFX_ASSERT(reference_count_ == 0); }
inline DrawState &operator =(DrawState &&other)
{
if(this != &other)
{
GFX_ASSERT(reference_count_ == 0);
draw_state_ = other.draw_state_;
reference_count_ = other.reference_count_;
other.reference_count_ = 0;
}
return *this;
}
Data draw_state_;
uint32_t reference_count_;
};
static GfxArray<DrawState> draw_states_;
static GfxHandles draw_state_handles_;
struct Object
{
enum Flag
{
kFlag_Named = 1 << 0
};
uint32_t flags_ = 0;
};
struct Buffer : public Object
{
inline bool isInterop() const { return (allocation_ == nullptr ? true : false); }
void *data_ = nullptr;
uint64_t data_offset_ = 0;
ID3D12Resource *resource_ = nullptr;
uint32_t *reference_count_ = nullptr;
D3D12MA::Allocation *allocation_ = nullptr;
D3D12_RESOURCE_STATES *resource_state_ = nullptr;
D3D12_RESOURCE_STATES initial_resource_state_ = D3D12_RESOURCE_STATE_COMMON;
};
GfxArray<Buffer> buffers_;
GfxHandles buffer_handles_;
struct Texture : public Object
{
enum Flag
{
kFlag_AutoResize = 1 << 0
};
inline bool isInterop() const { return (allocation_ == nullptr ? true : false); }
uint32_t flags_ = 0;
float clear_value_[4] = {};
ID3D12Resource *resource_ = nullptr;
D3D12MA::Allocation *allocation_ = nullptr;
std::vector<uint32_t> dsv_descriptor_slots_[D3D12_REQ_MIP_LEVELS];
std::vector<uint32_t> rtv_descriptor_slots_[D3D12_REQ_MIP_LEVELS];
D3D12_RESOURCE_STATES resource_state_ = D3D12_RESOURCE_STATE_COMMON;
D3D12_RESOURCE_STATES initial_resource_state_ = D3D12_RESOURCE_STATE_COMMON;
};
GfxArray<Texture> textures_;
GfxHandles texture_handles_;
struct SamplerState
{
D3D12_SAMPLER_DESC sampler_desc_ = {};
uint32_t descriptor_slot_ = 0xFFFFFFFFu;
};
GfxArray<SamplerState> sampler_states_;
GfxHandles sampler_state_handles_;
struct AccelerationStructure
{
bool needs_update_ = false;
bool needs_rebuild_ = false;
GfxBuffer bvh_buffer_ = {};
uint64_t bvh_data_size_ = 0;
std::vector<GfxRaytracingPrimitive> raytracing_primitives_;
};
GfxArray<AccelerationStructure> acceleration_structures_;
GfxHandles acceleration_structure_handles_;
struct RaytracingPrimitive
{
uint32_t index_ = 0;
float transform_[16] = {};
uint32_t instance_id_ = 0;
uint8_t instance_mask_ = 0xFFu;
uint32_t instance_contribution_to_hit_group_index_ = 0;
enum
{
kType_Triangles = 0,
kType_Instance,
kType_Procedural,
kType_Count
}
type_;
struct
{
uint32_t build_flags_ = 0;
GfxBuffer bvh_buffer_ = {};
uint64_t bvh_data_size_ = 0;
uint32_t index_stride_ = 0;
GfxBuffer index_buffer_ = {};
uint32_t vertex_stride_ = 0;
GfxBuffer vertex_buffer_ = {};
GfxAccelerationStructure acceleration_structure_ = {};
}
triangles_;
struct
{
GfxRaytracingPrimitive parent_ = {};
}
instance_;
struct
{
uint32_t build_flags_ = 0;
GfxBuffer bvh_buffer_ = {};
uint64_t bvh_data_size_ = 0;
uint32_t procedural_stride_ = 0;
GfxBuffer procedural_buffer_ = {};
GfxAccelerationStructure acceleration_structure_ = {};
}
procedural_;
};
GfxArray<RaytracingPrimitive> raytracing_primitives_;
GfxHandles raytracing_primitive_handles_;
struct Program
{
struct Parameter
{
enum Type
{
kType_Buffer = 0,
kType_Image,
kType_SamplerState,
kType_AccelerationStructure,
kType_Constants,
kType_Count
};
String name_;
uint32_t id_ = 0;
Type type_ = kType_Count;
union
{
struct { GfxBuffer *buffers_; uint32_t buffer_count; } buffer_;
struct { GfxTexture *textures_; uint32_t *mip_levels_; uint32_t texture_count; } image_;
GfxSamplerState sampler_state_;
struct { GfxAccelerationStructure bvh_; GfxBuffer bvh_buffer_; } acceleration_structure_;
void *constants_;
}
data_ = {};
uint32_t data_size_ = 0;
void set(GfxBuffer const *buffers, uint32_t buffer_count)
{
GFX_ASSERT(buffers != nullptr || buffer_count == 0);
if(type_ == kType_Buffer && data_.buffer_.buffer_count == buffer_count)
for(uint32_t i = 0; i < buffer_count; ++i) { if(buffers[i].handle != data_.buffer_.buffers_[i].handle) { ++id_; break; } }
else
{
unset();
type_ = kType_Buffer;
data_.buffer_.buffer_count = buffer_count;
data_size_ = buffer_count * sizeof(GfxBuffer);
data_.buffer_.buffers_ = (GfxBuffer *)(buffer_count > 0 ? gfxMalloc(buffer_count * sizeof(GfxBuffer)) : nullptr);
}
for(uint32_t i = 0; i < buffer_count; ++i)
data_.buffer_.buffers_[i] = buffers[i];
}
void set(GfxTexture const *textures, uint32_t const *mip_levels, uint32_t texture_count)
{
GFX_ASSERT(textures != nullptr || texture_count == 0);
if(type_ == kType_Image && data_.image_.texture_count == texture_count)
for(uint32_t i = 0; i < texture_count; ++i) { if(textures[i].handle != data_.image_.textures_[i].handle ||
(data_.image_.mip_levels_ != nullptr ? data_.image_.mip_levels_[i] : 0) != (mip_levels != nullptr ? mip_levels[i] : 0)) { ++id_; break; } }
else
{
unset();
type_ = kType_Image;
data_.image_.texture_count = texture_count;
data_size_ = texture_count * sizeof(GfxTexture);
data_.image_.textures_ = (GfxTexture *)(texture_count > 0 ? gfxMalloc(texture_count * sizeof(GfxTexture)) : nullptr);
data_.image_.mip_levels_ = (uint32_t *)(texture_count > 0 && mip_levels != nullptr ? gfxMalloc(texture_count * sizeof(uint32_t)) : nullptr);
}
for(uint32_t i = 0; i < texture_count; ++i)
{
data_.image_.textures_[i] = textures[i];
if(mip_levels != nullptr)
data_.image_.mip_levels_[i] = mip_levels[i];
}
}
void set(GfxSamplerState const &sampler_state)
{
if(type_ == kType_SamplerState)
id_ += (sampler_state.handle != data_.sampler_state_.handle);
else
{
unset();
type_ = kType_SamplerState;
data_size_ = sizeof(sampler_state);
}
data_.sampler_state_ = sampler_state;
}
void set(GfxAccelerationStructure const &acceleration_structure)
{
if(type_ == kType_AccelerationStructure)
id_ += (acceleration_structure.handle != data_.acceleration_structure_.bvh_.handle);
else
{
unset();
type_ = kType_AccelerationStructure;
data_size_ = sizeof(acceleration_structure);
}
data_.acceleration_structure_.bvh_ = acceleration_structure;
}
void set(void const *data, uint32_t data_size)
{
if(type_ == kType_Constants && data_size_ == data_size)
id_ += (memcmp(data, data_.constants_, data_size) != 0);
else
{
unset();
type_ = kType_Constants;
data_.constants_ = (data_size > 0 ? gfxMalloc(data_size) : nullptr);
}
memcpy(data_.constants_, data, data_size);
data_size_ = data_size;
}
void unset()
{
switch(type_)
{
case kType_Image:
gfxFree(data_.image_.textures_);
gfxFree(data_.image_.mip_levels_);
break;
case kType_Constants:
gfxFree(data_.constants_);
break;
default:
break;
}
memset(&data_, 0, sizeof(data_));
type_ = kType_Count;
data_size_ = 0;
++id_;
}
char const *getTypeName() const
{
switch(type_)
{
case kType_Buffer:
return "Buffer";
case kType_Image:
return "Texture";
case kType_SamplerState:
return "Sampler state";
case kType_AccelerationStructure:
return "Acceleration structure";
case kType_Constants:
return "Constants";
default:
break; // undefined type
}
return "undefined";
}
};
typedef std::map<uint64_t, Parameter> Parameters;
Parameter &insertParameter(char const *parameter_name)
{
uint64_t const parameter_id = Hash(parameter_name);
Parameters::iterator const it = parameters_.find(parameter_id);
GFX_ASSERT(parameter_name != nullptr && *parameter_name != '\0');
if(it == parameters_.end())
{
Parameter ¶meter = parameters_[parameter_id];
parameter.name_ = parameter_name;
return parameter;
}
GFX_ASSERT(strcmp((*it).second.name_.c_str(), parameter_name) == 0);
return (*it).second; // ^ assert on hashing conflicts
}
String cs_;
String as_;
String ms_;
String vs_;
String gs_;
String ps_;
String lib_;
String file_name_;
String file_path_;
String shader_model_;
Parameters parameters_;
std::vector<String> include_paths_;
};
GfxArray<Program> programs_;
GfxHandles program_handles_;
struct Kernel
{
enum Type
{
kType_Mesh = 0,
kType_Compute,
kType_Graphics,
kType_Raytracing,
kType_Count
};
inline bool isMesh() const { return type_ == kType_Mesh; }
inline bool isCompute() const { return type_ == kType_Compute; }
inline bool isGraphics() const { return type_ == kType_Graphics; }
inline bool isRaytracing() const { return type_ == kType_Raytracing; }
struct Parameter
{
enum Type
{
kType_Buffer = 0,
kType_RWBuffer,
kType_Texture2D,
kType_RWTexture2D,
kType_Texture2DArray,
kType_RWTexture2DArray,
kType_Texture3D,
kType_RWTexture3D,
kType_TextureCube,
kType_AccelerationStructure,
kType_Constants,
kType_ConstantBuffer,
kType_Sampler,
kType_Count
};
Type type_ = kType_Count;
uint32_t id_ = 0xFFFFFFFFu;
uint64_t parameter_id_ = 0;
uint32_t descriptor_count_ = 0;
uint32_t descriptor_slot_ = 0xFFFFFFFFu;
std::vector<ID3D12Resource *> bound_textures_;
Program::Parameter const *parameter_ = nullptr;
struct Variable
{
uint32_t id_ = 0;
uint32_t data_size_ = 0;
uint32_t data_start_ = 0;
uint64_t parameter_id_ = 0;
Program::Parameter const *parameter_ = nullptr;
};
Variable *variables_ = nullptr;
uint32_t variable_count_ = 0;
uint32_t variable_size_ = 0;
};
struct LocalParameter
{
ID3D12RootSignature *local_root_signature_ = nullptr;
std::vector<Parameter> parameters_;
};
struct LocalRootSignatureAssociation
{
uint32_t local_root_signature_space = 0;
GfxShaderGroupType shader_group_type = kGfxShaderGroupType_Count;
};
String entry_point_;
GfxProgram program_ = {};
Type type_ = kType_Count;
DrawState::Data draw_state_;
std::vector<String> defines_;
std::vector<String> exports_;
std::vector<String> subobjects_;
std::map<std::wstring, LocalRootSignatureAssociation> local_root_signature_associations_;
uint64_t descriptor_heap_id_ = 0;
uint32_t *num_threads_ = nullptr;
IDxcBlob *cs_bytecode_ = nullptr;
IDxcBlob *as_bytecode_ = nullptr;
IDxcBlob *ms_bytecode_ = nullptr;
IDxcBlob *vs_bytecode_ = nullptr;
IDxcBlob *gs_bytecode_ = nullptr;
IDxcBlob *ps_bytecode_ = nullptr;
IDxcBlob *lib_bytecode_ = nullptr;
ID3D12ShaderReflection *cs_reflection_ = nullptr;
ID3D12ShaderReflection *as_reflection_ = nullptr;
ID3D12ShaderReflection *ms_reflection_ = nullptr;
ID3D12ShaderReflection *vs_reflection_ = nullptr;
ID3D12ShaderReflection *gs_reflection_ = nullptr;
ID3D12ShaderReflection *ps_reflection_ = nullptr;
ID3D12LibraryReflection *lib_reflection_ = nullptr;
ID3D12RootSignature *root_signature_ = nullptr;
std::map<uint32_t, LocalParameter> local_parameters_;
size_t sbt_record_stride_[kGfxShaderGroupType_Count] = {};
ID3D12PipelineState *pipeline_state_ = nullptr;
ID3D12StateObject *state_object_ = nullptr;
Parameter *parameters_ = nullptr;
uint32_t parameter_count_ = 0;
uint32_t vertex_stride_ = 0;
};
GfxArray<Kernel> kernels_;
GfxHandles kernel_handles_;
enum ShaderType
{
kShaderType_CS = 0,
kShaderType_AS,
kShaderType_MS,
kShaderType_VS,
kShaderType_GS,
kShaderType_PS,
kShaderType_LIB,
kShaderType_Count
};
static char const *shader_extensions_[kShaderType_Count];
uint32_t dummy_descriptors_[Kernel::Parameter::kType_Count] = {};
uint32_t dummy_rtv_descriptor_ = 0xFFFFFFFFu;
struct TimestampQuery
{
float duration_ = 0.0f;
bool was_begun_ = false;
};
GfxArray<TimestampQuery> timestamp_queries_;
GfxHandles timestamp_query_handles_;
struct TimestampQueryHeap
{
GfxBuffer query_buffer_ = {};
ID3D12QueryHeap *query_heap_ = nullptr;
std::map<uint64_t, std::pair<uint32_t, GfxTimestampQuery>> timestamp_queries_;
};
uint64_t timestamp_query_ticks_per_second_ = 0;
TimestampQueryHeap *timestamp_query_heaps_ = nullptr;
struct Sbt
{
struct ShaderRecord
{
uint32_t id_ = 0;
uint32_t commited_id_ = 0xFFFFFFFFu;
std::wstring shader_identifier_;
std::vector<Kernel::Parameter> bound_parameters_;
std::unique_ptr<Program::Parameters> parameters_;
};
ShaderRecord &insertSbtRecord(GfxShaderGroupType shader_group_type, uint32_t index)
{
auto const it = shader_records_[shader_group_type].find(index);
if(it == shader_records_[shader_group_type].end())
{
ShaderRecord &record = shader_records_[shader_group_type][index];
record.parameters_ = std::make_unique<Program::Parameters>();
return record;
}
return (*it).second;
}
void insertSbtRecordShaderIdentifier(GfxShaderGroupType shader_group_type, uint32_t index, WCHAR *shader_identifier)
{
ShaderRecord &record = insertSbtRecord(shader_group_type, index);
record.id_ += record.shader_identifier_ != shader_identifier;
record.shader_identifier_ = shader_identifier;
}
std::pair<ShaderRecord &, Program::Parameter &> insertSbtRecordParameter(GfxShaderGroupType shader_group_type, uint32_t index, char const *parameter_name)
{
uint64_t const parameter_id = Hash(parameter_name);
ShaderRecord &record = insertSbtRecord(shader_group_type, index);
Program::Parameters::iterator const it = record.parameters_->find(parameter_id);
GFX_ASSERT(parameter_name != nullptr && *parameter_name != '\0');
if(it == record.parameters_->end())
{
Program::Parameter ¶meter = (*record.parameters_)[parameter_id];
parameter.name_ = parameter_name;
return {record, parameter};
}
GFX_ASSERT(strcmp((*it).second.name_.c_str(), parameter_name) == 0);
return {record, (*it).second}; // ^ assert on hashing conflicts
}
std::map<uint32_t, ShaderRecord> shader_records_[kGfxShaderGroupType_Count];
uint64_t descriptor_heap_id_ = 0;
GfxBuffer sbt_buffers_[kGfxShaderGroupType_Count] = {};
size_t sbt_max_record_stride_[kGfxShaderGroupType_Count];
D3D12_GPU_VIRTUAL_ADDRESS_RANGE ray_generation_shader_record_;
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE miss_shader_table_;
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE hit_group_table_;
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE callable_shader_table_;
GfxKernel kernel_ = {};
};
GfxArray<Sbt> sbts_;
GfxHandles sbt_handles_;
struct WindowsSecurityAttributes
{
SECURITY_ATTRIBUTES security_attributes_ = {};
PSECURITY_DESCRIPTOR security_descriptor_ = {};
inline SECURITY_ATTRIBUTES *operator &()
{
return &security_attributes_;
}
inline WindowsSecurityAttributes()
{
security_descriptor_ = (PSECURITY_DESCRIPTOR)gfxMalloc(SECURITY_DESCRIPTOR_MIN_LENGTH + 2 * sizeof(void**));
GFX_ASSERT(security_descriptor_ != nullptr);
PSID *ppSID = (PSID *)((PBYTE)security_descriptor_ + SECURITY_DESCRIPTOR_MIN_LENGTH);
PACL *ppACL = (PACL *)((PBYTE)ppSID + sizeof(PSID *));
InitializeSecurityDescriptor(security_descriptor_, SECURITY_DESCRIPTOR_REVISION);
SID_IDENTIFIER_AUTHORITY identifier_authority = SECURITY_WORLD_SID_AUTHORITY;
AllocateAndInitializeSid(&identifier_authority, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, ppSID);
EXPLICIT_ACCESS
explicit_access = {};
explicit_access.grfAccessPermissions = STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL;
explicit_access.grfAccessMode = SET_ACCESS;
explicit_access.grfInheritance = INHERIT_ONLY;
explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
explicit_access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
explicit_access.Trustee.ptstrName = (LPTSTR)*ppSID;
SetEntriesInAcl(1, &explicit_access, nullptr, ppACL);
SetSecurityDescriptorDacl(security_descriptor_, TRUE, *ppACL, FALSE);
security_attributes_.nLength = sizeof(security_attributes_);
security_attributes_.lpSecurityDescriptor = security_descriptor_;
security_attributes_.bInheritHandle = TRUE;
}
inline ~WindowsSecurityAttributes()
{
PSID *ppSID = (PSID *)((PBYTE)security_descriptor_ + SECURITY_DESCRIPTOR_MIN_LENGTH);
PACL *ppACL = (PACL *)((PBYTE)ppSID + sizeof(PSID *));
FreeSid(*ppSID);
LocalFree(*ppACL);
gfxFree(security_descriptor_);
}
};
public:
GfxInternal(GfxContext &gfx) : buffer_handles_("buffer"), texture_handles_("texture"), sampler_state_handles_("sampler state")
, acceleration_structure_handles_("acceleration structure"), raytracing_primitive_handles_("raytracing primitive")
, program_handles_("program"), kernel_handles_("kernel"), timestamp_query_handles_("timestamp query"), sbt_handles_("shader binding table")
{ gfx.handle = reinterpret_cast<uint64_t>(this); }
~GfxInternal() { terminate(); }
GfxResult initialize(HWND window, GfxCreateContextFlags flags, IDXGIAdapter *adapter, GfxContext &context)
{
if(!window)
return GFX_SET_ERROR(kGfxResult_InvalidParameter, "An invalid window handle was supplied");
IDXGIFactory4 *factory = nullptr;
if(!SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))
return GFX_SET_ERROR(kGfxResult_InternalError, "Unable to create DXGI factory");
if((flags & kGfxCreateContextFlag_EnableExperimentalShaders) != 0)
{
IID const features[] = { D3D12ExperimentalShaderModels };
if(!IsDeveloperModeEnabled())
return GFX_SET_ERROR(kGfxResult_InternalError, "Unable to enable experimental shaders without Windows developer mode");
if(!SUCCEEDED(D3D12EnableExperimentalFeatures(ARRAYSIZE(features), features, nullptr, nullptr)))
return GFX_SET_ERROR(kGfxResult_InternalError, "Unable to enable experimental shaders");
experimental_shaders_ = true;
}
struct DXGIFactoryReleaser
{
IDXGIFactory4 *factory;
GFX_NON_COPYABLE(DXGIFactoryReleaser);
DXGIFactoryReleaser(IDXGIFactory4 *factory) : factory(factory) {}
~DXGIFactoryReleaser() { factory->Release(); }
};
DXGIFactoryReleaser const factory_releaser(factory);
GFX_TRY(initializeDevice(flags, adapter, factory));
window_ = window;
RECT window_rect = {};
GetClientRect(window_, &window_rect);
window_width_ = window_rect.right - window_rect.left;
window_height_ = window_rect.bottom - window_rect.top;
IDXGIOutput *output = nullptr;
color_space_ = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
UINT output_i = 0;
LONG best_area = -1;
IDXGIOutput *current_output;
while(adapter_->EnumOutputs(output_i, ¤t_output) != DXGI_ERROR_NOT_FOUND)
{
DXGI_OUTPUT_DESC output_desc;
if(SUCCEEDED(current_output->GetDesc(&output_desc))) {
RECT rect = output_desc.DesktopCoordinates;
int intersect_area =
GFX_MAX(0L, GFX_MIN(window_rect.right, rect.right) - GFX_MAX(window_rect.left, rect.left)) *
GFX_MAX(0l, GFX_MIN(window_rect.bottom, rect.bottom) - GFX_MAX(window_rect.top, rect.top));
if(intersect_area > best_area)
{
output = current_output;
best_area = intersect_area;
}
}
if(current_output != output) current_output->Release();
output_i++;
}
if(output != nullptr)
{
IDXGIOutput6 *output6 = nullptr;
output->QueryInterface(&output6);
if(output6 != nullptr)
{
DXGI_OUTPUT_DESC1 output_desc = {};