forked from gboisse/gfx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgfx.h
8796 lines (8244 loc) · 478 KB
/
gfx.h
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) 2023 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.
****************************************************************************/
#ifndef GFX_INCLUDE_GFX_H
#define GFX_INCLUDE_GFX_H
#include "d3d12.h"
#include "dxgi1_4.h"
#include "gfx_core.h"
//!
//! Context creation/destruction.
//!
class GfxContext { friend class GfxInternal; uint64_t handle; char name[kGfxConstant_MaxNameLength + 1]; uint32_t vendor_id; public:
inline bool operator ==(GfxContext const &other) const { return handle == other.handle; }
inline bool operator !=(GfxContext const &other) const { return handle != other.handle; }
inline GfxContext() { memset(this, 0, sizeof(*this)); }
inline uint32_t getVendorId() const { return vendor_id; }
inline char const *getName() const { return name; }
inline operator bool() const { return !!handle; } };
enum GfxCreateContextFlag
{
kGfxCreateContextFlag_EnableDebugLayer = 1 << 0,
kGfxCreateContextFlag_EnableShaderDebugging = 1 << 1,
kGfxCreateContextFlag_EnableStablePowerState = 1 << 2
};
typedef uint32_t GfxCreateContextFlags;
GfxContext gfxCreateContext(HWND window, GfxCreateContextFlags flags = 0, IDXGIAdapter *adapter = nullptr);
GfxResult gfxDestroyContext(GfxContext context);
uint32_t gfxGetBackBufferWidth(GfxContext context);
uint32_t gfxGetBackBufferHeight(GfxContext context);
uint32_t gfxGetBackBufferIndex(GfxContext context);
uint32_t gfxGetBackBufferCount(GfxContext context);
bool gfxIsRaytracingSupported(GfxContext context);
bool gfxIsInteropContext(GfxContext context);
//!
//! Buffer resources.
//!
enum GfxCpuAccess
{
kGfxCpuAccess_None = 0, // No CPU access, fastest path for GPU read & write memory.
kGfxCpuAccess_Read, // CPU can read but not write, GPU can copy to; ideal for CPU readbacks.
kGfxCpuAccess_Write, // CPU can write but not read, GPU can only read (ideally not too often); ideal for constants & uploads.
kGfxCpuAccess_Count
};
class GfxBuffer { GFX_INTERNAL_NAMED_HANDLE(GfxBuffer); uint64_t size; uint32_t stride; GfxCpuAccess cpu_access; public:
inline uint32_t getCount() const { return (uint32_t)(!stride ? 0 : size / stride); }
inline GfxCpuAccess getCpuAccess() const { return cpu_access; }
inline void setStride(uint32_t stride_) { stride = stride_; }
inline uint32_t getStride() const { return stride; }
inline uint64_t getSize() const { return size; } };
GfxBuffer gfxCreateBuffer(GfxContext context, uint64_t size, void const *data = nullptr, GfxCpuAccess cpu_access = kGfxCpuAccess_None);
GfxBuffer gfxCreateBufferRange(GfxContext context, GfxBuffer buffer, uint64_t byte_offset, uint64_t size = 0); // fast path for (sub-)allocating during a frame
GfxResult gfxDestroyBuffer(GfxContext context, GfxBuffer buffer);
void *gfxBufferGetData(GfxContext context, GfxBuffer buffer);
//!
//! Template helpers.
//!
template<typename TYPE>
GfxBuffer gfxCreateBuffer(GfxContext context, uint32_t element_count, void const *data = nullptr, GfxCpuAccess cpu_access = kGfxCpuAccess_None)
{
GfxBuffer buffer = gfxCreateBuffer(context, element_count * sizeof(TYPE), data, cpu_access);
if(buffer) buffer.setStride((uint32_t)sizeof(TYPE));
return buffer;
}
template<typename TYPE>
GfxBuffer gfxCreateBufferRange(GfxContext context, GfxBuffer buffer, uint32_t element_offset, uint32_t element_count = 0)
{
GfxBuffer buffer_range = gfxCreateBufferRange(context, buffer, element_offset * sizeof(TYPE), element_count * sizeof(TYPE));
if(buffer_range) buffer_range.setStride((uint32_t)sizeof(TYPE));
return buffer_range;
}
template<typename TYPE>
TYPE *gfxBufferGetData(GfxContext context, GfxBuffer buffer)
{
return (TYPE *)gfxBufferGetData(context, buffer);
}
//!
//! Texture resources.
//!
class GfxTexture { GFX_INTERNAL_NAMED_HANDLE(GfxTexture); uint32_t width; uint32_t height; uint32_t depth; DXGI_FORMAT format; uint32_t mip_levels; enum { kType_2D, kType_2DArray, kType_3D, kType_Cube } type; public:
inline bool is2DArray() const { return type == kType_2DArray; }
inline bool isCube() const { return type == kType_Cube; }
inline bool is3D() const { return type == kType_3D; }
inline bool is2D() const { return type == kType_2D; }
inline uint32_t getWidth() const { return width; }
inline uint32_t getHeight() const { return height; }
inline uint32_t getDepth() const { return depth; }
inline DXGI_FORMAT getFormat() const { return format; }
inline uint32_t getMipLevels() const { return mip_levels; } };
GfxTexture gfxCreateTexture2D(GfxContext context, DXGI_FORMAT format); // creates auto-resize window-sized texture
GfxTexture gfxCreateTexture2D(GfxContext context, uint32_t width, uint32_t height, DXGI_FORMAT format, uint32_t mip_levels = 1);
GfxTexture gfxCreateTexture2DArray(GfxContext context, uint32_t width, uint32_t height, uint32_t slice_count, DXGI_FORMAT format, uint32_t mip_levels = 1);
GfxTexture gfxCreateTexture3D(GfxContext context, uint32_t width, uint32_t height, uint32_t depth, DXGI_FORMAT format, uint32_t mip_levels = 1);
GfxTexture gfxCreateTextureCube(GfxContext context, uint32_t size, DXGI_FORMAT format, uint32_t mip_levels = 1);
GfxResult gfxDestroyTexture(GfxContext context, GfxTexture texture);
//!
//! Helper functions.
//!
inline uint32_t gfxCalculateMipCount(uint32_t width, uint32_t height = 0, uint32_t depth = 0)
{
uint32_t mip_count = 0;
uint32_t mip_size = GFX_MAX(width, GFX_MAX(height, depth));
while(mip_size >= 1) { mip_size >>= 1; ++mip_count; }
return mip_count;
}
//!
//! Sampler states.
//!
class GfxSamplerState { GFX_INTERNAL_HANDLE(GfxSamplerState); D3D12_FILTER filter; D3D12_TEXTURE_ADDRESS_MODE address_u; D3D12_TEXTURE_ADDRESS_MODE address_v; D3D12_TEXTURE_ADDRESS_MODE address_w; float mip_lod_bias; uint32_t max_anisotropy; D3D12_COMPARISON_FUNC comparison_func; float min_lod; float max_lod; public:
inline D3D12_FILTER getFilter() const { return filter; }
inline D3D12_TEXTURE_ADDRESS_MODE getAddressU() const { return address_u; }
inline D3D12_TEXTURE_ADDRESS_MODE getAddressV() const { return address_v; }
inline D3D12_TEXTURE_ADDRESS_MODE getAddressW() const { return address_w; }
inline float getMipLodBias() const { return mip_lod_bias; }
inline uint32_t getMaxAnisotropy() const { return max_anisotropy; }
inline D3D12_COMPARISON_FUNC getComparisonFunc() const { return comparison_func; }
inline float getMinLod() const { return min_lod; }
inline float getMaxLod() const { return max_lod; } };
GfxSamplerState gfxCreateSamplerState(GfxContext context, D3D12_FILTER filter, D3D12_TEXTURE_ADDRESS_MODE address_u = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE address_v = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE address_w = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
float mip_lod_bias = 0.0f, float min_lod = 0.0f, float max_lod = (float)D3D12_REQ_MIP_LEVELS);
GfxSamplerState gfxCreateSamplerState(GfxContext context, D3D12_FILTER filter, D3D12_COMPARISON_FUNC comparison_func, // for comparison samplers
D3D12_TEXTURE_ADDRESS_MODE address_u = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE address_v = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE address_w = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
float mip_lod_bias = 0.0f, float min_lod = 0.0f, float max_lod = (float)D3D12_REQ_MIP_LEVELS);
GfxResult gfxDestroySamplerState(GfxContext context, GfxSamplerState sampler_state);
//!
//! Acceleration structures.
//!
class GfxRaytracingPrimitive; // forward declaration
class GfxAccelerationStructure { GFX_INTERNAL_NAMED_HANDLE(GfxAccelerationStructure); public: };
GfxAccelerationStructure gfxCreateAccelerationStructure(GfxContext context);
GfxResult gfxDestroyAccelerationStructure(GfxContext context, GfxAccelerationStructure acceleration_structure); // automatically releases all raytracing primitives
GfxResult gfxAccelerationStructureUpdate(GfxContext context, GfxAccelerationStructure acceleration_structure);
uint32_t gfxAccelerationStructureGetRaytracingPrimitiveCount(GfxContext context, GfxAccelerationStructure acceleration_structure);
GfxRaytracingPrimitive const *gfxAccelerationStructureGetRaytracingPrimitives(GfxContext context, GfxAccelerationStructure acceleration_structure);
//!
//! Raytracing primitives.
//!
enum GfxBuildRaytracingPrimitiveFlag
{
kGfxBuildRaytracingPrimitiveFlag_Opaque = 1 << 0
};
typedef uint32_t GfxBuildRaytracingPrimitiveFlags;
class GfxRaytracingPrimitive { GFX_INTERNAL_NAMED_HANDLE(GfxRaytracingPrimitive); public: };
GfxRaytracingPrimitive gfxCreateRaytracingPrimitive(GfxContext context, GfxAccelerationStructure acceleration_structure);
GfxResult gfxDestroyRaytracingPrimitive(GfxContext context, GfxRaytracingPrimitive raytracing_primitive);
GfxResult gfxRaytracingPrimitiveBuild(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, GfxBuffer vertex_buffer, uint32_t vertex_stride = 0, GfxBuildRaytracingPrimitiveFlags build_flags = 0);
GfxResult gfxRaytracingPrimitiveBuild(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, GfxBuffer index_buffer, GfxBuffer vertex_buffer, uint32_t vertex_stride = 0, GfxBuildRaytracingPrimitiveFlags build_flags = 0);
GfxResult gfxRaytracingPrimitiveSetTransform(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, float const *row_major_4x4_transform);
GfxResult gfxRaytracingPrimitiveSetInstanceID(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, uint32_t instance_id); // retrieved through `ray_query.CommittedInstanceID()`
GfxResult gfxRaytracingPrimitiveSetInstanceMask(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, uint8_t instance_mask);
GfxResult gfxRaytracingPrimitiveSetInstanceContributionToHitGroupIndex(GfxContext context, GfxRaytracingPrimitive raytracing_primitive, uint32_t instance_contribution_to_hit_group_index);
GfxResult gfxRaytracingPrimitiveUpdate(GfxContext context, GfxRaytracingPrimitive raytracing_primitive);
//!
//! Draw state manipulation.
//!
class GfxDrawState { friend class GfxInternal; uint64_t handle; public: GfxDrawState(); GfxDrawState(GfxDrawState const &); GfxDrawState &operator =(GfxDrawState const &); ~GfxDrawState(); };
GfxResult gfxDrawStateSetColorTarget(GfxDrawState draw_state, uint32_t target_index, GfxTexture texture, uint32_t mip_level = 0, uint32_t slice = 0);
GfxResult gfxDrawStateSetDepthStencilTarget(GfxDrawState draw_state, GfxTexture texture, uint32_t mip_level = 0, uint32_t slice = 0);
GfxResult gfxDrawStateSetCullMode(GfxDrawState draw_state, D3D12_CULL_MODE cull_mode);
GfxResult gfxDrawStateSetFillMode(GfxDrawState draw_state, D3D12_FILL_MODE fill_mode);
GfxResult gfxDrawStateSetBlendMode(GfxDrawState draw_state, 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 mode helpers.
//!
inline GfxResult gfxDrawStateEnableAlphaBlending(GfxDrawState draw_state)
{
return gfxDrawStateSetBlendMode(draw_state, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD);
}
//!
//! Program creation/destruction.
//!
class GfxProgram { GFX_INTERNAL_HANDLE(GfxProgram); char name[kGfxConstant_MaxNameLength + 1]; public:
inline char const *getName() const { return name; } };
class GfxProgramDesc { public: inline GfxProgramDesc() : cs(nullptr), vs(nullptr), gs(nullptr), ps(nullptr) {}
char const *cs;
char const *vs;
char const *gs;
char const *ps; };
GfxProgram gfxCreateProgram(GfxContext context, char const *file_name, char const *file_path = nullptr, char const *shader_model = nullptr);
GfxProgram gfxCreateProgram(GfxContext context, GfxProgramDesc program_desc, char const *name = nullptr, char const *shader_model = nullptr);
GfxResult gfxDestroyProgram(GfxContext context, GfxProgram program);
GfxResult gfxProgramSetBuffer(GfxContext context, GfxProgram program, char const *parameter_name, GfxBuffer buffer);
GfxResult gfxProgramSetBuffers(GfxContext context, GfxProgram program, char const *parameter_name, GfxBuffer const *buffers, uint32_t buffer_count);
GfxResult gfxProgramSetTexture(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture texture, uint32_t mip_level = 0);
GfxResult gfxProgramSetTextures(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const *textures, uint32_t texture_count);
GfxResult gfxProgramSetTextures(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const *textures, uint32_t const *mip_levels, uint32_t texture_count);
GfxResult gfxProgramSetSamplerState(GfxContext context, GfxProgram program, char const *parameter_name, GfxSamplerState sampler_state);
GfxResult gfxProgramSetAccelerationStructure(GfxContext context, GfxProgram program, char const *parameter_name, GfxAccelerationStructure acceleration_structure);
GfxResult gfxProgramSetConstants(GfxContext context, GfxProgram program, char const *parameter_name, void const *data, uint32_t data_size);
enum GfxShaderGroupType
{
kGfxShaderGroupType_Raygen,
kGfxShaderGroupType_Miss,
kGfxShaderGroupType_Hit,
kGfxShaderGroupType_Callable,
kGfxShaderGroupType_Count
};
GfxResult gfxProgramSetShaderGroup(GfxContext context, GfxProgram program, GfxShaderGroupType shader_group_type, uint32_t index, char const *group_name);
GfxResult gfxProgramSetConstants(GfxContext context, GfxProgram program, GfxShaderGroupType shader_group_type, uint32_t index, char const *parameter_name, void const *data, uint32_t data_size);
//!
//! Template helpers.
//!
template<typename TYPE>
inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, TYPE const &value);
inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, GfxBuffer const *buffers, uint32_t buffer_count) { return gfxProgramSetBuffers(context, program, parameter_name, buffers, buffer_count); }
inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const &texture, uint32_t mip_level) { return gfxProgramSetTexture(context, program, parameter_name, texture, mip_level); }
inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const *textures, uint32_t texture_count) { return gfxProgramSetTextures(context, program, parameter_name, textures, texture_count); }
inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const *textures, uint32_t const *mip_levels, uint32_t texture_count) { return gfxProgramSetTextures(context, program, parameter_name, textures, mip_levels, texture_count); }
template<> inline GfxResult gfxProgramSetParameter<GfxBuffer>(GfxContext context, GfxProgram program, char const *parameter_name, GfxBuffer const &value) { return gfxProgramSetBuffer(context, program, parameter_name, value); }
template<> inline GfxResult gfxProgramSetParameter<GfxTexture>(GfxContext context, GfxProgram program, char const *parameter_name, GfxTexture const &value) { return gfxProgramSetTexture(context, program, parameter_name, value); }
template<> inline GfxResult gfxProgramSetParameter<GfxSamplerState>(GfxContext context, GfxProgram program, char const *parameter_name, GfxSamplerState const &value) { return gfxProgramSetSamplerState(context, program, parameter_name, value); }
template<> inline GfxResult gfxProgramSetParameter<GfxAccelerationStructure>(GfxContext context, GfxProgram program, char const *parameter_name, GfxAccelerationStructure const &value) { return gfxProgramSetAccelerationStructure(context, program, parameter_name, value); }
template<typename TYPE> inline GfxResult gfxProgramSetParameter(GfxContext context, GfxProgram program, char const *parameter_name, TYPE const &value)
{
static_assert(!std::is_pointer<TYPE>::value, "Program parameters must be passed by value, not by pointer");
return gfxProgramSetConstants(context, program, parameter_name, &value, sizeof(value));
}
//!
//! Kernel compilation.
//!
class GfxKernel { GFX_INTERNAL_HANDLE(GfxKernel); char name[kGfxConstant_MaxNameLength + 1]; enum { kType_Compute, kType_Graphics, kType_Raytracing } type; public:
inline bool isGraphics() const { return type == kType_Graphics; }
inline bool isCompute() const { return type == kType_Compute; }
inline bool isRaytracing() const { return type == kType_Raytracing; }
inline char const *getName() const { return name; } };
struct GfxLocalRootSignatureAssociation
{
uint32_t local_root_signature_space;
GfxShaderGroupType shader_group_type;
char const *shader_group_name;
};
GfxKernel gfxCreateComputeKernel(GfxContext context, GfxProgram program, char const *entry_point = nullptr, char const **defines = nullptr, uint32_t define_count = 0);
GfxKernel gfxCreateGraphicsKernel(GfxContext context, GfxProgram program, char const *entry_point = nullptr, char const **defines = nullptr, uint32_t define_count = 0); // draws to back buffer
GfxKernel gfxCreateGraphicsKernel(GfxContext context, GfxProgram program, GfxDrawState draw_state, char const *entry_point = nullptr, char const **defines = nullptr, uint32_t define_count = 0);
GfxKernel gfxCreateRaytracingKernel(GfxContext context, GfxProgram program, GfxLocalRootSignatureAssociation *local_root_signature_associations = nullptr, uint32_t local_root_signature_association_count = 0, char const **defines = nullptr, uint32_t define_count = 0);
GfxResult gfxDestroyKernel(GfxContext context, GfxKernel kernel);
uint32_t const *gfxKernelGetNumThreads(GfxContext context, GfxKernel kernel);
GfxResult gfxKernelReloadAll(GfxContext context); // hot-reloads all kernel objects
//!
//! Command encoding.
//!
GfxResult gfxCommandCopyBuffer(GfxContext context, GfxBuffer dst, GfxBuffer src);
GfxResult gfxCommandCopyBuffer(GfxContext context, GfxBuffer dst, uint64_t dst_offset, GfxBuffer src, uint64_t src_offset, uint64_t size);
GfxResult gfxCommandClearBuffer(GfxContext context, GfxBuffer buffer, uint32_t clear_value = 0);
GfxResult gfxCommandClearBackBuffer(GfxContext context); // clears to (0.0, 0.0, 0.0, 1.0)
GfxResult gfxCommandClearTexture(GfxContext context, GfxTexture texture);
GfxResult gfxCommandCopyTexture(GfxContext context, GfxTexture dst, GfxTexture src);
GfxResult gfxCommandClearImage(GfxContext context, GfxTexture texture, uint32_t mip_level = 0, uint32_t slice = 0);
GfxResult gfxCommandCopyTextureToBackBuffer(GfxContext context, GfxTexture texture);
GfxResult gfxCommandCopyBufferToTexture(GfxContext context, GfxTexture dst, GfxBuffer src);
GfxResult gfxCommandGenerateMips(GfxContext context, GfxTexture texture); // expects mip level 0 to be populated, generates the others
GfxResult gfxCommandBindKernel(GfxContext context, GfxKernel kernel);
GfxResult gfxCommandBindIndexBuffer(GfxContext context, GfxBuffer index_buffer);
GfxResult gfxCommandBindVertexBuffer(GfxContext context, GfxBuffer vertex_buffer);
GfxResult gfxCommandSetViewport(GfxContext context, float x = 0.0f, float y = 0.0f, float width = 0.0f, float height = 0.0f); // leave at 0 to draw to render target/back buffer size
GfxResult gfxCommandSetScissorRect(GfxContext context, int32_t x = 0, int32_t y = 0, int32_t width = 0, int32_t height = 0); // leave at 0 to draw to render target/back buffer size
GfxResult gfxCommandDraw(GfxContext context, uint32_t vertex_count, uint32_t instance_count = 1, uint32_t base_vertex = 0, uint32_t base_instance = 0);
GfxResult gfxCommandDrawIndexed(GfxContext context, uint32_t index_count, uint32_t instance_count = 1, uint32_t first_index = 0, uint32_t base_vertex = 0, uint32_t base_instance = 0);
GfxResult gfxCommandMultiDrawIndirect(GfxContext context, GfxBuffer args_buffer, uint32_t args_count); // expects a buffer of D3D12_DRAW_ARGUMENTS elements
GfxResult gfxCommandMultiDrawIndexedIndirect(GfxContext context, GfxBuffer args_buffer, uint32_t args_count); // expects a buffer of D3D12_DRAW_INDEXED_ARGUMENTS elements
GfxResult gfxCommandDispatch(GfxContext context, uint32_t num_groups_x, uint32_t num_groups_y, uint32_t num_groups_z);
GfxResult gfxCommandDispatchIndirect(GfxContext context, GfxBuffer args_buffer); // expects a buffer of D3D12_DISPATCH_ARGUMENTS elements
GfxResult gfxCommandMultiDispatchIndirect(GfxContext context, GfxBuffer args_buffer, uint32_t args_count); // expects a buffer of D3D12_DISPATCH_ARGUMENTS elements
GfxResult gfxCommandDispatchRays(GfxContext context, uint32_t width, uint32_t height, uint32_t depth);
//!
//! Debug/profile API.
//!
class GfxTimestampQuery { GFX_INTERNAL_HANDLE(GfxTimestampQuery); public: };
GfxTimestampQuery gfxCreateTimestampQuery(GfxContext context);
GfxResult gfxDestroyTimestampQuery(GfxContext context, GfxTimestampQuery timestamp_query);
float gfxTimestampQueryGetDuration(GfxContext context, GfxTimestampQuery timestamp_query); // in milliseconds
GfxResult gfxCommandBeginTimestampQuery(GfxContext context, GfxTimestampQuery timestamp_query);
GfxResult gfxCommandEndTimestampQuery(GfxContext context, GfxTimestampQuery timestamp_query);
GfxResult gfxCommandBeginEvent(GfxContext context, char const *format, ...);
GfxResult gfxCommandBeginEvent(GfxContext context, uint64_t color, char const *format, ...);
GfxResult gfxCommandEndEvent(GfxContext context);
//!
//! RAII helpers.
//!
class GfxTimedSection { GFX_NON_COPYABLE(GfxTimedSection); GfxContext context; GfxTimestampQuery timestamp_query; char const *section_name; public:
inline GfxTimedSection(GfxContext context, GfxTimestampQuery timestamp_query, char const *section_name = nullptr) : context(context), timestamp_query(timestamp_query), section_name(section_name) { gfxCommandBeginTimestampQuery(context, timestamp_query); }
inline ~GfxTimedSection() { gfxCommandEndTimestampQuery(context, timestamp_query); if(section_name != nullptr) GFX_PRINTLN("Completed `%s' in %.3fms", section_name, gfxTimestampQueryGetDuration(context, timestamp_query)); } };
class GfxCommandEvent { GFX_NON_COPYABLE(GfxCommandEvent); GfxContext context; public:
inline GfxCommandEvent(GfxContext context, char const *format, ...) : context(context) { va_list args; va_start(args, format); char buffer[4096]; vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); gfxCommandBeginEvent(context, buffer); }
inline GfxCommandEvent(GfxContext context, uint64_t color, char const *format, ...) : context(context) { va_list args; va_start(args, format); char buffer[4096]; vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); gfxCommandBeginEvent(context, color, buffer); }
inline ~GfxCommandEvent() { gfxCommandEndEvent(context); } };
//!
//! Parallel primitives.
//!
enum GfxDataType
{
kGfxDataType_Int = 0,
kGfxDataType_Uint,
kGfxDataType_Float,
kGfxDataType_Count
};
GfxResult gfxCommandScanMin(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr); // dst can be the same than src for all parallel primitives
GfxResult gfxCommandScanMax(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr);
GfxResult gfxCommandScanSum(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr);
GfxResult gfxCommandReduceMin(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr);
GfxResult gfxCommandReduceMax(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr);
GfxResult gfxCommandReduceSum(GfxContext context, GfxDataType data_type, GfxBuffer dst, GfxBuffer src, GfxBuffer const *count = nullptr);
GfxResult gfxCommandSortRadix(GfxContext context, GfxBuffer keys_dst, GfxBuffer keys_src, GfxBuffer const *values_dst = nullptr, GfxBuffer const *values_src = nullptr, GfxBuffer const *count = nullptr);
//!
//! Frame processing.
//!
GfxResult gfxFrame(GfxContext context, bool vsync = true);
GfxResult gfxFinish(GfxContext context);
//!
//! Interop interface.
//!
GfxContext gfxCreateContext(ID3D12Device *device, uint32_t max_frames_in_flight = kGfxConstant_BackBufferCount);
ID3D12Device *gfxGetDevice(GfxContext context);
ID3D12GraphicsCommandList *gfxGetCommandList(GfxContext context);
GfxResult gfxSetCommandList(GfxContext context, ID3D12GraphicsCommandList *command_list);
GfxResult gfxResetCommandListState(GfxContext context); // call this function before returning to gfx after externally modifying the state on the command list
GfxBuffer gfxCreateBuffer(GfxContext context, ID3D12Resource *resource, D3D12_RESOURCE_STATES resource_state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
GfxTexture gfxCreateTexture(GfxContext context, ID3D12Resource *resource, D3D12_RESOURCE_STATES resource_state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
GfxAccelerationStructure gfxCreateAccelerationStructure(GfxContext context, ID3D12Resource *resource, uint64_t byte_offset = 0); // resource must be in D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE state
ID3D12Resource *gfxBufferGetResource(GfxContext context, GfxBuffer buffer);
ID3D12Resource *gfxTextureGetResource(GfxContext context, GfxTexture texture);
ID3D12Resource *gfxAccelerationStructureGetResource(GfxContext context, GfxAccelerationStructure acceleration_structure);
D3D12_RESOURCE_STATES gfxBufferGetResourceState(GfxContext context, GfxBuffer buffer);
D3D12_RESOURCE_STATES gfxTextureGetResourceState(GfxContext context, GfxTexture texture);
//!
//! Template helpers.
//!
template<typename TYPE>
GfxBuffer gfxCreateBuffer(GfxContext context, ID3D12Resource *resource, D3D12_RESOURCE_STATES resource_state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)
{
GfxBuffer buffer = gfxCreateBuffer(context, resource, resource_state);
if(buffer) buffer.setStride((uint32_t)sizeof(TYPE));
return buffer;
}
#endif //! GFX_INCLUDE_GFX_H
//!
//! Implementation details.
//!
#ifdef GFX_IMPLEMENTATION_DEFINE
#pragma once
#include <map> // std::map
#include <deque> // std::deque
#include "direct.h" // _mkdir()
#include "inc/dxcapi.h" // shader compiler
#include "inc/d3d12shader.h" // shader reflection
#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
#include "D3D12MemAlloc.cpp" // D3D12MemoryAllocator
#include "WinPixEventRuntime/pix3.h"
#pragma warning(pop)
#pragma warning(push)
#pragma warning(disable:4996) // this function or variable may be unsafe
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;
ID3D12CommandQueue *command_queue_ = nullptr;
ID3D12GraphicsCommandList *command_list_ = nullptr;
ID3D12GraphicsCommandList4 *dxr_command_list_ = nullptr;
ID3D12CommandAllocator **command_allocators_ = nullptr;
HANDLE fence_event_ = {};
uint32_t fence_index_ = 0;
ID3D12Fence **fences_ = nullptr;
uint64_t *fence_values_ = nullptr;
bool debug_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;
std::vector<D3D12_RESOURCE_BARRIER> resource_barriers_;
ID3D12Resource **back_buffers_ = nullptr;
uint32_t *back_buffer_rtvs_ = nullptr;
GfxKernel bound_kernel_ = {};
GfxBuffer draw_id_buffer_ = {};
GfxBuffer sbt_buffers_[kGfxShaderGroupType_Count] = {};
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 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) { free(data_); data_ = other.data_; other.data_ = nullptr; } return *this; }
inline String &operator =(char const *data) { free(data_); if(!data) data_ = nullptr; else
{ data_ = (char *)malloc(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() { free(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 RenderTarget
{
GfxTexture texture_ = {};
uint32_t mip_level = 0;
uint32_t slice = 0;
};
struct Data
{
RenderTarget color_targets_[kGfxConstant_MaxRenderTarget] = {};
RenderTarget depth_stencil_target_ = {};
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_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;
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_ = {};
std::vector<GfxRaytracingPrimitive> raytracing_primitives_;
};
GfxArray<AccelerationStructure> acceleration_structures_;
GfxHandles acceleration_structure_handles_;
struct RaytracingPrimitive
{
uint32_t index_ = 0;
float transform_[16] = {};
uint32_t build_flags_ = 0;
uint32_t instance_id_ = 0;
uint32_t instance_contribution_to_hit_group_index_ = 0;
uint8_t instance_mask_ = 0xFFu;
GfxBuffer bvh_buffer_ = {};
uint32_t index_stride_ = 0;
GfxBuffer index_buffer_ = {};
uint32_t vertex_stride_ = 0;
GfxBuffer vertex_buffer_ = {};
GfxAccelerationStructure acceleration_structure_ = {};
};
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 ? malloc(buffer_count * sizeof(GfxBuffer)) : nullptr);
if(buffer_count > 0 && data_.buffer_.buffers_ == nullptr)
{
GFX_ASSERT(0); // out of memory
unset(); return;
}
}
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 ? malloc(texture_count * sizeof(GfxTexture)) : nullptr);
data_.image_.mip_levels_ = (uint32_t *)(texture_count > 0 && mip_levels != nullptr ? malloc(texture_count * sizeof(uint32_t)) : nullptr);
if(texture_count > 0 && (data_.image_.textures_ == nullptr || (mip_levels != nullptr && data_.image_.mip_levels_ == nullptr)))
{
GFX_ASSERT(0); // out of memory
unset(); return;
}
}
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 ? malloc(data_size) : nullptr);
}
memcpy(data_.constants_, data, data_size);
data_size_ = data_size;
}
void unset()
{
switch(type_)
{
case kType_Image:
free(data_.image_.textures_);
free(data_.image_.mip_levels_);
break;
case kType_Constants:
free(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;
struct ShaderRecord
{
std::wstring shader_identifier_;