-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathzt_renderer_directx.h
2643 lines (2134 loc) · 93.4 KB
/
zt_renderer_directx.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
/**************************************************************************************************
** file: zt_directx.h v 0.00 (active initial development)
**
** This software is dual-licensed to the public domain and under the following
** license: you are granted a perpetual, irrevocable license to copy, modify,
** publish, and distribute this file as you see fit.
**
** No warranty is offered or implied. Use this at your own risk.
**
**************************************************************************************************
Zero Tolerance DirectX Library
In exactly one c/cpp source file of your project, you must:
#define ZT_DIRECTX_IMPLEMENTATION
#include "zt_directx.h"
**************************************************************************************************
Options:
**************************************************************************************************
Implimentation Options: (only used with ZT_DIRECTX_IMPLEMENTATION #include)
**************************************************************************************************/
#ifndef __zt_directx_h_included__
#define __zt_directx_h_included__
// ------------------------------------------------------------------------------------------------
#define ZT_DIRECTX
// ------------------------------------------------------------------------------------------------
#include "zt_tools.h"
#if !defined(ZT_WINDOWS)
# error DirectX is only supported on Windows
// maybe Xbox support later?
#endif
#include <windows.h>
#include <d3d11.h>
#include <d3dcompiler.h>
// ------------------------------------------------------------------------------------------------
struct ztContextDX;
ztContextDX *ztdx_contextMake(void *window, i32 client_w, i32 client_h, i32 pixels_per_unit, i32 flags); // ztRendererFlags
ztContextDX *ztdx_contextMake(ztMemoryArena *arena, void *window, i32 client_w, i32 client_h, i32 pixels_per_unit, i32 flags); // ztRendererFlags
void ztdx_contextFree(ztContextDX *context);
void ztdx_contextDisplay(ztContextDX *context);
ztVec2i ztdx_contextGetSize(ztContextDX *context);
bool ztdx_contextSetSize(ztContextDX *context, i32 w, i32 h);
bool ztdx_contextIsFullscreen(ztContextDX *context);
bool ztdx_contextToggleFullscreen(ztContextDX *context, bool fullscreen);
void ztdx_clipRegionSet(ztContextDX *context, int left, int top, int right, int bottom);
void ztdx_clipRegionRemove(ztContextDX *context);
// ------------------------------------------------------------------------------------------------
bool ztdx_setViewport(i32 width, i32 height);
bool ztdx_setViewport(ztContextDX *context);
void ztdx_cullFront(ztContextDX *context);
void ztdx_cullBack(ztContextDX *context);
void ztdx_cullNone(ztContextDX *context);
void ztdx_depthTestOff(ztContextDX *context);
void ztdx_depthTestNever(ztContextDX *context);
void ztdx_depthTestLess(ztContextDX *context);
void ztdx_depthTestLessEqual(ztContextDX *context);
void ztdx_depthTestEqual(ztContextDX *context);
void ztdx_depthTestGreater(ztContextDX *context);
void ztdx_depthTestNotEqual(ztContextDX *context);
void ztdx_depthTestGreaterEqual(ztContextDX *context);
void ztdx_depthTestAlways(ztContextDX *context);
void ztdx_clearColor(ztContextDX *context, ztVec4& color);
void ztdx_clearColor(ztContextDX *context, r32 color[4]);
void ztdx_clearColor(ztContextDX *context, r32 r, r32 g, r32 b, r32 a = 1);
void ztdx_clearDepth(ztContextDX *context);
void ztdx_clear(ztContextDX *context, ztVec4& color);
void ztdx_clear(ztContextDX *context, r32 color[4]);
void ztdx_clear(ztContextDX *context, r32 r, r32 g, r32 b, r32 a = 1);
enum ztBlendModeDX_Enum
{
ztBlendModeDX_Zero,
ztBlendModeDX_One,
ztBlendModeDX_SourceColor,
ztBlendModeDX_OneMinusSourceColor,
ztBlendModeDX_DestColor,
ztBlendModeDX_OneMinusDestColor,
ztBlendModeDX_SourceAlpha,
ztBlendModeDX_OneMinusSourceAlpha,
ztBlendModeDX_DestAlpha,
ztBlendModeDX_OneMinusDestAlpha,
ztBlendModeDX_MAX,
};
void ztdx_blendMode(ztContextDX *context, ztBlendModeDX_Enum source, ztBlendModeDX_Enum dest);
// ------------------------------------------------------------------------------------------------
bool ztdx_checkAndReportError(const char *function, i32 hr);
int ztdx_clearErrors();
#define ztdx_callAndReturnOnError(function) if (ztdx_checkAndReportError(#function, (function))) return;
#define ztdx_callAndReturnValOnError(function, retval) if (ztdx_checkAndReportError(#function, (function))) return retval;
#define ztdx_callAndReportOnError(function) ztdx_checkAndReportError(#function, (function));
#if defined(ZT_DIRECTX_DEBUGGING)
# define ztdx_callAndReportOnErrorFast(function) ztdx_checkAndReportError(#function, (function));
#else
# define ztdx_callAndReportOnErrorFast(function) function;
#endif
// ------------------------------------------------------------------------------------------------
enum ztTextureDXFlags_Enum
{
ztTextureDXFlags_MipMaps = (1 << 0),
ztTextureDXFlags_DepthMap = (1 << 1),
ztTextureDXFlags_PixelPerfect = (1 << 2),
ztTextureDXFlags_CubeMap = (1 << 3),
};
// ------------------------------------------------------------------------------------------------
enum ztTextureDXCubeMapFiles_Enum
{
ztTextureDXCubeMapFiles_Right,
ztTextureDXCubeMapFiles_Left,
ztTextureDXCubeMapFiles_Top,
ztTextureDXCubeMapFiles_Bottom,
ztTextureDXCubeMapFiles_Back,
ztTextureDXCubeMapFiles_Front,
ztTextureDXCubeMapFiles_MAX,
};
// ------------------------------------------------------------------------------------------------
struct ztTextureDX
{
ID3D11Texture2D *tex;
ID3D11ShaderResourceView *shader_resource_view;
ID3D11SamplerState *sampler_state;
ID3D11Texture2D *depth_stencil_buffer;
ID3D11DepthStencilView *depth_stencil_view;
ID3D11RenderTargetView *render_target_view;
ztVec2i size;
i32 flags;
ztMemoryArena *arena;
};
// ------------------------------------------------------------------------------------------------
ztTextureDX *ztdx_textureMakeFromPixelData(ztContextDX *context, byte *pixels, int w, int h, int d, i32 flags);
ztTextureDX *ztdx_textureMakeFromPixelData(ztMemoryArena *arena, ztContextDX *context, byte *pixels, int w, int h, int d, i32 flags);
ztTextureDX *ztdx_textureMakeCubeMapFromPixelData(ztContextDX *context, byte **pixels, int w, int h, int d);
ztTextureDX *ztdx_textureMakeCubeMapFromPixelData(ztMemoryArena *arena, ztContextDX *context, byte **pixels, int w, int h, int d);
ztTextureDX *ztdx_textureMakeRenderTarget(ztContextDX *context, int w, int h, i32 flags);
ztTextureDX *ztdx_textureMakeRenderTarget(ztMemoryArena *arena, ztContextDX *context, int w, int h, i32 flags);
ztTextureDX *ztdx_textureMakeDepthRenderTarget(ztContextDX *context, int w, int h);
ztTextureDX *ztdx_textureMakeDepthRenderTarget(ztMemoryArena *arena, ztContextDX *context, int w, int h);
void ztdx_textureFree(ztTextureDX *texture);
void ztdx_textureRenderTargetPrepare(ztContextDX *context, ztTextureDX *texture);
void ztdx_textureRenderTargetCommit(ztContextDX *context, ztTextureDX *texture);
bool ztdx_textureIsRenderTarget(ztTextureDX *texture);
// ------------------------------------------------------------------------------------------------
enum ztShaderDXVariableType_Enum
{
ztShaderDXVariableType_Invalid,
ztShaderDXVariableType_Float,
ztShaderDXVariableType_Vec2,
ztShaderDXVariableType_Vec3,
ztShaderDXVariableType_Vec4,
ztShaderDXVariableType_Int,
ztShaderDXVariableType_Mat3,
ztShaderDXVariableType_Mat4,
ztShaderDXVariableType_Tex,
ztShaderDXVariableType_TexCube,
ztShaderDXVariableType_MAX,
};
// ------------------------------------------------------------------------------------------------
struct ztShaderDX
{
ID3D11VertexShader *vert;
ID3D11PixelShader *frag;
ID3D11InputLayout *layout;
struct ConstantBuffer
{
ID3D11Buffer *buffer;
int shader; // 0 - vert, 1 - frag
};
ConstantBuffer *cbuffers;
i32 cbuffers_count;
struct Variable
{
char name[64];
u32 name_hash;
int cbuffer;
int size;
int offset;
int shader; // 0 - vert, 1 - frag
ztShaderDXVariableType_Enum type;
byte *data;
};
Variable *variables;
int variables_count;
bool has_cubemap;
ztMemoryArena *arena;
};
// ------------------------------------------------------------------------------------------------
ztShaderDX *ztdx_shaderMake(ztContextDX *context, const char *vert_src, const char *vert_func, const char *frag_src, const char *frag_func);
ztShaderDX *ztdx_shaderMake(ztMemoryArena *arena, ztContextDX *context, const char *vert_src, const char *vert_func, const char *frag_src, const char *frag_func);
void ztdx_shaderFree(ztContextDX *context, ztShaderDX *shader);
void ztdx_shaderBegin(ztContextDX *context, ztShaderDX *shader);
void ztdx_shaderEnd(ztContextDX *context, ztShaderDX *shader);
bool ztdx_shaderHasVariable(ztShaderDX *shader, u32 name_hash);
void ztdx_shaderVariableFloat(ztShaderDX *shader, u32 name_hash, r32 value);
void ztdx_shaderVariableInt(ztShaderDX *shader, u32 name_hash, i32 value);
void ztdx_shaderVariableVec2(ztShaderDX *shader, u32 name_hash, r32 value[2]);
void ztdx_shaderVariableVec3(ztShaderDX *shader, u32 name_hash, r32 value[3]);
void ztdx_shaderVariableVec4(ztShaderDX *shader, u32 name_hash, r32 value[4]);
void ztdx_shaderVariableMat4(ztShaderDX *shader, u32 name_hash, r32 value[16]);
void ztdx_shaderVariableMat3(ztShaderDX *shader, u32 name_hash, r32 value[9]);
void ztdx_shaderVariableTex(ztShaderDX *shader, u32 name_hash, ztTextureDX *tex);
void ztdx_shaderPopulateConstantBuffers(ztContextDX *context, ztShaderDX *shader);
// ------------------------------------------------------------------------------------------------
struct ztVertexEntryDX
{
int size;
};
// ------------------------------------------------------------------------------------------------
struct ztVertexArrayDX
{
ID3D11Buffer *buff_vert;
i32 stride;
ztVertexEntryDX *entries;
int entries_count;
int vert_count;
ztMemoryArena *arena;
};
// ------------------------------------------------------------------------------------------------
ztVertexArrayDX *ztdx_vertexArrayMake (ztContextDX *context, ztVertexEntryDX *entries, int entries_count, void *vert_data, int vert_count);
ztVertexArrayDX *ztdx_vertexArrayMake (ztMemoryArena *arena, ztContextDX *context, ztVertexEntryDX *entries, int entries_count, void *vert_data, int vert_count);
void ztdx_vertexArrayFree (ztVertexArrayDX *vertex_array);
bool ztdx_vertexArrayUpdate(ztContextDX *context, ztVertexArrayDX *vertex_array, void *vert_data, int vert_count);
void ztdx_vertexArrayDraw (ztContextDX *context, ztVertexArrayDX *vertex_array, D3D11_PRIMITIVE_TOPOLOGY topology = D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
#endif // include guard
#if defined(ZT_DIRECTX_IMPLEMENTATION) || defined(ZT_DIRECTX_INTERNAL_DECLARATIONS)
#ifndef __zt_directx_h_internal_included__
#define __zt_directx_h_internal_included__
struct ztContextDX
{
HWND handle;
IDXGISwapChain *swapchain;
ID3D11Device *device;
ID3D11DeviceContext *context;
ID3D11RenderTargetView *backbuffer;
ID3D11BlendState *transparency;
ID3D11BlendState *blend_states[16];
ID3D11RasterizerState *cull_mode_ccw;
ID3D11RasterizerState *cull_mode_cw;
ID3D11RasterizerState *cull_mode_none;
ID3D11DepthStencilView *depth_stencil_view;
ID3D11Texture2D *depth_stencil_buffer;
ID3D11DepthStencilState *stencil_state_enabled;
ID3D11DepthStencilState *stencil_state_disabled;
ID3D11DepthStencilState *stencil_state_enabled_leq;
ID3D11RenderTargetView *active_render_target;
ID3D11DepthStencilView *active_render_target_depth_stencil_view;
int texture_count;
ztVec2i size;
i32 pixels_per_unit;
i32 flags;
ztMemoryArena *arena;
};
#endif // include guard
#endif // internal declarations
#if defined(ZT_DIRECTX_IMPLEMENTATION)
enum ztRendererFlagsDX_Enum
{
ztRendererFlagsDX_Windowed = (1 << 0),
ztRendererFlagsDX_Fullscreen = (1 << 1),
ztRendererFlagsDX_Vsync = (1 << 2),
ztRendererFlagsDX_LockAspect = (1 << 5),
ztRendererFlagsDX_HideCursor = (1 << 6),
};
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dxguid.lib")
// ------------------------------------------------------------------------------------------------
ztContextDX *ztdx_contextMake(void *window, i32 client_w, i32 client_h, i32 pixels_per_unit, i32 flags) // ztRendererFlags
{
return ztdx_contextMake(zt_memGetGlobalArena(), window, client_w, client_h, pixels_per_unit, flags);
}
// ------------------------------------------------------------------------------------------------
ztContextDX *ztdx_contextMake(ztMemoryArena *arena, void *window, i32 client_w, i32 client_h, i32 pixels_per_unit, i32 renderer_flags) // ztRendererFlags
{
ztContextDX *context = zt_mallocStructArena(ztContextDX, arena);
context->size.x = client_w;
context->size.y = client_h;
context->pixels_per_unit = pixels_per_unit;
context->flags = renderer_flags;
context->handle = (HWND)window;
context->arena = arena;
DXGI_MODE_DESC buffer_desc;
ZeroMemory(&buffer_desc, sizeof(DXGI_MODE_DESC));
buffer_desc.Width = client_w;
buffer_desc.Height = client_h;
buffer_desc.RefreshRate.Numerator = 60;
buffer_desc.RefreshRate.Denominator = 1;
buffer_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
buffer_desc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
buffer_desc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
DXGI_SWAP_CHAIN_DESC scd;
ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
scd.BufferCount = 1; // one back buffer
scd.BufferDesc = buffer_desc;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
scd.OutputWindow = context->handle; // the window to be used
scd.SampleDesc.Count = 1; // how many multisamples
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.Windowed = zt_bitIsSet(renderer_flags, ztRendererFlags_Windowed) ? TRUE : FALSE;
zt_logInfo("DirectX: Creating swap chain");
// create a device, device context and swap chain using the information in the scd struct
i32 flags = 0;
#if defined(_DEBUG) && defined(ZT_DIRECTX_DEBUGGING)
flags = D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL feature_level;
ztdx_callAndReturnValOnError(D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
flags,
NULL,
0,
D3D11_SDK_VERSION,
&scd,
&context->swapchain,
&context->device,
&feature_level,
&context->context), false);
// get the address of the back buffer
zt_logInfo("DirectX: Finding back buffer address");
ID3D11Texture2D *backbuffer;
ztdx_callAndReturnValOnError(context->swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backbuffer), nullptr);
// use the back buffer address to create the render target
zt_logInfo("DirectX: Creating back buffer render target");
ztdx_callAndReturnValOnError(context->device->CreateRenderTargetView(backbuffer, NULL, &context->backbuffer), nullptr);
backbuffer->Release();
D3D11_TEXTURE2D_DESC dsdesc;
dsdesc.Width = client_w;
dsdesc.Height = client_h;
dsdesc.MipLevels = 1;
dsdesc.ArraySize = 1;
dsdesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsdesc.SampleDesc.Count = 1;
dsdesc.SampleDesc.Quality = 0;
dsdesc.Usage = D3D11_USAGE_DEFAULT;
dsdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
dsdesc.CPUAccessFlags = 0;
dsdesc.MiscFlags = 0;
//Create the Depth/Stencil View
ztdx_callAndReturnValOnError(context->device->CreateTexture2D(&dsdesc, NULL, &context->depth_stencil_buffer), nullptr);
ztdx_callAndReturnValOnError(context->device->CreateDepthStencilView(context->depth_stencil_buffer, NULL, &context->depth_stencil_view), nullptr);
// set the render target as the back buffer
zt_logInfo("DirectX: Setting context back buffer");
context->context->OMSetRenderTargets(1, &context->backbuffer, context->depth_stencil_view);
context->active_render_target = context->backbuffer;
context->active_render_target_depth_stencil_view = context->depth_stencil_view;
context->texture_count = 0;
D3D11_DEPTH_STENCIL_DESC dssdesc;
dssdesc.DepthEnable = true;
dssdesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dssdesc.DepthFunc = D3D11_COMPARISON_LESS;
dssdesc.StencilEnable = true;
dssdesc.StencilReadMask = 0xFF;
dssdesc.StencilWriteMask = 0xFF;
dssdesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dssdesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
dssdesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dssdesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
dssdesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dssdesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
dssdesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dssdesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
ztdx_callAndReturnValOnError(context->device->CreateDepthStencilState(&dssdesc, &context->stencil_state_enabled), nullptr);
dssdesc.DepthEnable = true;
dssdesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
ztdx_callAndReturnValOnError(context->device->CreateDepthStencilState(&dssdesc, &context->stencil_state_enabled_leq), nullptr);
dssdesc.DepthEnable = true;
dssdesc.DepthFunc = D3D11_COMPARISON_ALWAYS;
ztdx_callAndReturnValOnError(context->device->CreateDepthStencilState(&dssdesc, &context->stencil_state_disabled), nullptr);
if (!ztdx_setViewport(context)) {
return false;
}
// alpha blending
D3D11_BLEND_DESC blend_desc;
ZeroMemory(&blend_desc, sizeof(blend_desc));
D3D11_RENDER_TARGET_BLEND_DESC rtbd;
ZeroMemory(&rtbd, sizeof(rtbd));
rtbd.BlendEnable = true;
rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA; //D3D11_BLEND_SRC_COLOR;
rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;// D3D11_BLEND_BLEND_FACTOR;
rtbd.BlendOp = D3D11_BLEND_OP_ADD;
rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
rtbd.DestBlendAlpha = D3D11_BLEND_ONE;
rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
blend_desc.AlphaToCoverageEnable = false;
blend_desc.RenderTarget[0] = rtbd;
context->device->CreateBlendState(&blend_desc, &context->transparency);
zt_fize(context->blend_states) {
context->blend_states[i] = nullptr;
}
//Create the Counter Clockwise and Clockwise Culling States
D3D11_RASTERIZER_DESC cmdesc;
ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));
cmdesc.FillMode = D3D11_FILL_SOLID;
cmdesc.CullMode = D3D11_CULL_BACK;
cmdesc.ScissorEnable = TRUE;
cmdesc.FrontCounterClockwise = true;
ztdx_callAndReturnValOnError(context->device->CreateRasterizerState(&cmdesc, &context->cull_mode_ccw), nullptr);
cmdesc.FrontCounterClockwise = false;
ztdx_callAndReturnValOnError(context->device->CreateRasterizerState(&cmdesc, &context->cull_mode_cw), nullptr);
cmdesc.CullMode = D3D11_CULL_NONE;
cmdesc.FrontCounterClockwise = true;
ztdx_callAndReturnValOnError(context->device->CreateRasterizerState(&cmdesc, &context->cull_mode_none), nullptr);
return context;
}
// ------------------------------------------------------------------------------------------------
void ztdx_contextFree(ztContextDX *context)
{
if (context->swapchain != nullptr) {
context->swapchain->Release();
context->backbuffer->Release();
context->device->Release();
context->context->Release();
context->cull_mode_ccw->Release();
context->cull_mode_cw->Release();
context->cull_mode_none->Release();
context->transparency->Release();
zt_fize(context->blend_states) {
if(context->blend_states[i]) {
context->blend_states[i]->Release();
}
}
context->depth_stencil_view->Release();
context->depth_stencil_buffer->Release();
context->stencil_state_enabled->Release();
context->stencil_state_enabled_leq->Release();
context->stencil_state_disabled->Release();
}
zt_freeArena(context, context->arena);
}
// ------------------------------------------------------------------------------------------------
void ztdx_contextDisplay(ztContextDX *context)
{
context->swapchain->Present(0, 0);
}
// ------------------------------------------------------------------------------------------------
ztVec2i ztdx_contextGetSize(ztContextDX *context)
{
return context->size;
}
// ------------------------------------------------------------------------------------------------
bool ztdx_contextSetSize(ztContextDX *context, i32 w, i32 h)
{
context->size.x = w;
context->size.y = h;
return ztdx_setViewport(context);
}
// ------------------------------------------------------------------------------------------------
bool ztdx_contextIsFullscreen(ztContextDX *context)
{
return zt_bitIsSet(context->flags, ztRendererFlagsDX_Fullscreen);
}
// ------------------------------------------------------------------------------------------------
bool ztdx_contextToggleFullscreen(ztContextDX *context, bool fullscreen)
{
#if 0
ztdx_callAndReturnValOnError(context->swapchain->SetFullscreenState(fullscreen ? TRUE : FALSE, NULL), false);
ztdx_setViewport(context);
return true;
#else
return false;
#endif
}
// ------------------------------------------------------------------------------------------------
void ztdx_clipRegionSet(ztContextDX *context, int left, int top, int right, int bottom)
{
D3D11_RECT rect; rect.left = left; rect.top = top; rect.right = right; rect.bottom = bottom;
context->context->RSSetScissorRects(1, &rect);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clipRegionRemove(ztContextDX *context)
{
D3D11_RECT rect; rect.left = 0; rect.top = 0; rect.right = context->size.x; rect.bottom = context->size.y;
context->context->RSSetScissorRects(1, &rect);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
bool ztdx_checkAndReportError(const char *function, i32 hr)
{
switch (hr)
{
case S_OK: return false;
case D3D11_ERROR_FILE_NOT_FOUND : zt_logCritical("DirectX: Error: D3D11_ERROR_FILE_NOT_FOUND"); return true;
case D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS : zt_logCritical("DirectX: Error: D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS"); return true;
case D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS : zt_logCritical("DirectX: Error: D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS"); return true;
case D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD: zt_logCritical("DirectX: Error: D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD"); return true;
case DXGI_ERROR_INVALID_CALL : zt_logCritical("DirectX: Error: DXGI_ERROR_INVALID_CALL"); return true;
case DXGI_ERROR_WAS_STILL_DRAWING : zt_logCritical("DirectX: Error: DXGI_ERROR_WAS_STILL_DRAWING"); return true;
case E_FAIL : zt_logCritical("DirectX: Error: E_FAIL"); return true;
case E_INVALIDARG : zt_logCritical("DirectX: Error: E_INVALIDARG"); return true;
case E_OUTOFMEMORY : zt_logCritical("DirectX: Error: E_OUTOFMEMORY"); return true;
case E_NOTIMPL : zt_logCritical("DirectX: Error: E_NOTIMPL"); return true;
case S_FALSE : zt_logCritical("DirectX: Error: S_FALSE"); return true;
default : zt_logCritical("DirectX: Unknown error code: 0x%x (%d)", hr, hr); return true;
}
}
// ------------------------------------------------------------------------------------------------
i32 ztdx_clearErrors()
{
return 0;
}
// ------------------------------------------------------------------------------------------------
bool ztdx_setViewport(ztContextDX *context, i32 width, i32 height)
{
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
viewport.Width = (r32)width;
viewport.Height = (r32)height;
context->context->RSSetViewports(1, &viewport);
D3D11_RECT rect; rect.left = 0; rect.top = 0; rect.right = width; rect.bottom = height;
context->context->RSSetScissorRects(1, &rect);
return true;
}
// ------------------------------------------------------------------------------------------------
bool ztdx_setViewport(ztContextDX *context)
{
return ztdx_setViewport(context, context->size.x, context->size.y);
}
// ------------------------------------------------------------------------------------------------
void ztdx_cullFront(ztContextDX *context)
{
context->context->RSSetState(context->cull_mode_cw);
}
// ------------------------------------------------------------------------------------------------
void ztdx_cullBack(ztContextDX *context)
{
context->context->RSSetState(context->cull_mode_ccw);
}
// ------------------------------------------------------------------------------------------------
void ztdx_cullNone(ztContextDX *context)
{
context->context->RSSetState(context->cull_mode_none);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestOff(ztContextDX *context)
{
context->context->OMSetDepthStencilState(context->stencil_state_disabled, 1);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestNever(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestLess(ztContextDX *context)
{
context->context->OMSetDepthStencilState(context->stencil_state_enabled, 1);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestLessEqual(ztContextDX *context)
{
context->context->OMSetDepthStencilState(context->stencil_state_enabled_leq, 1);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestEqual(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestGreater(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestNotEqual(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestGreaterEqual(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_depthTestAlways(ztContextDX *context)
{
zt_assert(false);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clearColor(ztContextDX *context, ztVec4& color)
{
ztdx_clearColor(context, color.values);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clearColor(ztContextDX *context, r32 color[4])
{
context->context->ClearRenderTargetView(context->active_render_target, color);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clearColor(ztContextDX *context, r32 r, r32 g, r32 b, r32 a)
{
r32 color[] = { r, g, b, a };
ztdx_clearColor(context, color);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clearDepth(ztContextDX *context)
{
context->context->ClearDepthStencilView(context->active_render_target_depth_stencil_view, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.f, 0);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clear(ztContextDX *context, ztVec4& color)
{
ztdx_clear(context, color.values);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clear(ztContextDX *context, r32 color[4])
{
context->context->ClearRenderTargetView(context->active_render_target, color);
context->context->ClearDepthStencilView(context->active_render_target_depth_stencil_view, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.f, 0);
}
// ------------------------------------------------------------------------------------------------
void ztdx_clear(ztContextDX *context, r32 r, r32 g, r32 b, r32 a)
{
r32 color[] = { r, g, b, a };
ztdx_clear(context, color);
}
// ------------------------------------------------------------------------------------------------
void ztdx_blendMode(ztContextDX *context, ztBlendModeDX_Enum source, ztBlendModeDX_Enum dest)
{
D3D11_BLEND factors[2] = { D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA };
ztBlendModeDX_Enum params[2] = { source, dest };
zt_fize(params) {
switch(params[i])
{
case ztBlendModeDX_Zero : factors[i] = D3D11_BLEND_ZERO; break;
case ztBlendModeDX_One : factors[i] = D3D11_BLEND_ONE; break;
case ztBlendModeDX_SourceColor : factors[i] = D3D11_BLEND_SRC_COLOR; break;
case ztBlendModeDX_OneMinusSourceColor : factors[i] = D3D11_BLEND_INV_SRC_COLOR; break;
case ztBlendModeDX_DestColor : factors[i] = D3D11_BLEND_DEST_COLOR; break;
case ztBlendModeDX_OneMinusDestColor : factors[i] = D3D11_BLEND_INV_DEST_COLOR; break;
case ztBlendModeDX_SourceAlpha : factors[i] = D3D11_BLEND_SRC_ALPHA; break;
case ztBlendModeDX_OneMinusSourceAlpha : factors[i] = D3D11_BLEND_INV_SRC_ALPHA; break;
case ztBlendModeDX_DestAlpha : factors[i] = D3D11_BLEND_DEST_ALPHA; break;
case ztBlendModeDX_OneMinusDestAlpha : factors[i] = D3D11_BLEND_INV_DEST_ALPHA; break;
}
}
D3D11_BLEND_DESC desc;
context->transparency->GetDesc(&desc);
if (desc.RenderTarget[0].SrcBlend == factors[0] && desc.RenderTarget[0].DestBlend == factors[1]) {
float blend_factor[] = { 1.f, 1.f, 1.f, 1.f };
context->context->OMSetBlendState(context->transparency, blend_factor, 0xffffffff);
return;
}
int last_idx = 0;
zt_fize(context->blend_states) {
if(context->blend_states[i]) {
context->transparency->GetDesc(&desc);
if (desc.RenderTarget[0].SrcBlend == factors[0] && desc.RenderTarget[0].DestBlend == factors[1]) {
float blend_factor[] = { 1.f, 1.f, 1.f, 1.f };
context->context->OMSetBlendState(context->blend_states[i], blend_factor, 0xffffffff);
return;
}
}
else break;
last_idx += 1;
}
zt_assert(last_idx < zt_elementsOf(context->blend_states));
ZeroMemory(&desc, sizeof(desc));
desc.AlphaToCoverageEnable = false;
desc.RenderTarget[0].BlendEnable = true;
desc.RenderTarget[0].SrcBlend = factors[0];
desc.RenderTarget[0].DestBlend = factors[1];
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = factors[0];
desc.RenderTarget[0].DestBlendAlpha = factors[1];
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
context->device->CreateBlendState(&desc, &context->blend_states[last_idx]);
float blend_factor[] = { 1.f, 1.f, 1.f, 1.f };
context->context->OMSetBlendState(context->blend_states[last_idx], blend_factor, 0xffffffff);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
ztShaderDX *ztdx_shaderMake(ztContextDX *context, const char *vert_src, const char *vert_func, const char *frag_src, const char *frag_func)
{
return ztdx_shaderMake(zt_memGetGlobalArena(), context, vert_src, vert_func, frag_src, frag_func);
}
// ------------------------------------------------------------------------------------------------
ztShaderDX *ztdx_shaderMake(ztMemoryArena *arena, ztContextDX *context, const char *vert_src, const char *vert_func, const char *frag_src, const char *frag_func)
{
struct local
{
static bool load_shader(const char *src, const char *entry, const char *target, ID3DBlob **shader)
{
ID3DBlob *blob_error = nullptr;
i32 hr = D3DCompile(src, zt_strLen(src), NULL, NULL, NULL, entry, target, 0, 0, shader, &blob_error);
if (blob_error != nullptr) {
char *b_error = (char*)blob_error->GetBufferPointer();
SIZE_T b_error_len = blob_error->GetBufferSize();
char error_buffer[1024 * 16];
zt_strCpy(error_buffer, sizeof(error_buffer), b_error, (int)b_error_len);
if( hr != 0) {
zt_logCritical("DirectX compile failure: %s", error_buffer);
return false;
}
else {
zt_logCritical("DirectX compile warnings: %s", error_buffer);
}
}
return true;
}
};
ID3D10Blob *vert = nullptr, *frag = nullptr;
if (!local::load_shader(vert_src, vert_func, "vs_4_0", &vert)) {
zt_logCritical("Unable to compile DirectX vertex shader.");
return nullptr;
}
if (!local::load_shader(frag_src, frag_func, "ps_4_0", &frag)) {
zt_logCritical("Unable to compile DirectX pixel shader.");
return nullptr;
}
ztShaderDX *shader = zt_mallocStructArena(ztShaderDX, arena);
shader->arena = arena;
shader->has_cubemap = false;
ztdx_callAndReturnValOnError(context->device->CreateVertexShader(vert->GetBufferPointer(), vert->GetBufferSize(), NULL, &shader->vert), nullptr);
ztdx_callAndReturnValOnError(context->device->CreatePixelShader(frag->GetBufferPointer(), frag->GetBufferSize(), NULL, &shader->frag), nullptr);
context->context->VSSetShader(shader->vert, NULL, NULL);
context->context->PSSetShader(shader->frag, NULL, NULL);
shader->cbuffers_count = 0;
int cbuffers_count = 0;
int variables_count = 0;
zt_fkz(2) {
ID3D11ShaderReflection *reflection = nullptr;
ID3D10Blob *shad = k == 0 ? vert : frag;
ztdx_callAndReportOnError(D3DReflect(shad->GetBufferPointer(), shad->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflection));
if (reflection) {
D3D11_SHADER_DESC shader_desc;
if (SUCCEEDED(reflection->GetDesc(&shader_desc))) {
cbuffers_count += shader_desc.ConstantBuffers;
zt_fiz(shader_desc.BoundResources) {
variables_count += 1;
}
zt_fiz(shader_desc.ConstantBuffers) {
ID3D11ShaderReflectionConstantBuffer *buffer = reflection->GetConstantBufferByIndex(i);
if (!buffer) {
zt_logCritical("DirectX: Unable to get constant buffer index %d", i);
return nullptr;
}
D3D11_SHADER_BUFFER_DESC bdesc;
buffer->GetDesc(&bdesc);
variables_count += bdesc.Variables;
zt_fjz(bdesc.Variables) {
ID3D11ShaderReflectionVariable* variable = buffer->GetVariableByIndex(j);
if (!variable) {
zt_logCritical("DirectX: Unable to get variables for constant buffer index %d", i);