-
Notifications
You must be signed in to change notification settings - Fork 52
/
blah_renderer_d3d11.cpp
1659 lines (1412 loc) · 43.3 KB
/
blah_renderer_d3d11.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
#ifdef BLAH_RENDERER_D3D11
// TODO:
// Note the D3D11 Implementation is still a work-in-progress
#include "blah_renderer.h"
#include "blah_internal.h"
#include "blah_platform.h"
#include <blah_common.h>
#include <cstdio>
#include <cstring>
#include <cstddef>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d11.h>
#include <d3dcompiler.h>
// shorthand to our internal state
#define RENDERER ((Renderer_D3D11*)Internal::app_renderer())
namespace Blah
{
const char* d3d11_batch_shader = ""
"cbuffer constants : register(b0)\n"
"{\n"
" row_major float4x4 u_matrix;\n"
"}\n"
"struct vs_in\n"
"{\n"
" float2 position : POS;\n"
" float2 texcoord : TEX;\n"
" float4 color : COL;\n"
" float4 mask : MASK;\n"
"};\n"
"struct vs_out\n"
"{\n"
" float4 position : SV_POSITION;\n"
" float2 texcoord : TEX;\n"
" float4 color : COL;\n"
" float4 mask : MASK;\n"
"};\n"
"Texture2D u_texture : register(t0);\n"
"SamplerState u_texture_sampler : register(s0);\n"
"vs_out vs_main(vs_in input)\n"
"{\n"
" vs_out output;\n"
" output.position = mul(float4(input.position, 0.0f, 1.0f), u_matrix);\n"
" output.texcoord = input.texcoord;\n"
" output.color = input.color;\n"
" output.mask = input.mask;\n"
" return output;\n"
"}\n"
"float4 ps_main(vs_out input) : SV_TARGET\n"
"{\n"
" float4 color = u_texture.Sample(u_texture_sampler, input.texcoord);\n"
" return\n"
" input.mask.x * color * input.color + \n"
" input.mask.y * color.a * input.color + \n"
" input.mask.z * input.color;\n"
"}\n";
const ShaderData d3d11_batch_shader_data = {
d3d11_batch_shader,
d3d11_batch_shader,
{
{ "POS", 0 },
{ "TEX", 0 },
{ "COL", 0 },
{ "MASK", 0 },
}
};
class D3D11_Shader;
class Renderer_D3D11 : public Renderer
{
public:
// main resources
ID3D11Device* device = nullptr;
ID3D11DeviceContext* context = nullptr;
IDXGISwapChain* swap_chain = nullptr;
ID3D11RenderTargetView* backbuffer_view = nullptr;
ID3D11DepthStencilView* backbuffer_depth_view = nullptr;
// last backbuffer size
Point drawable_size;
Point last_window_size;
struct StoredInputLayout
{
u32 shader_hash;
VertexFormat format;
ID3D11InputLayout* layout;
};
struct StoredBlendState
{
BlendMode blend;
ID3D11BlendState* state;
};
struct StoredRasterizer
{
Cull cull;
bool has_scissor;
ID3D11RasterizerState* state;
};
struct StoredSampler
{
TextureSampler sampler;
ID3D11SamplerState* state;
};
struct StoredDepthStencil
{
Compare depth;
ID3D11DepthStencilState* state;
};
Vector<StoredInputLayout> layout_cache;
Vector<StoredBlendState> blend_cache;
Vector<StoredRasterizer> rasterizer_cache;
Vector<StoredSampler> sampler_cache;
Vector<StoredDepthStencil> depthstencil_cache;
bool init() override;
void shutdown() override;
void update() override;
void before_render() override;
void after_render() override;
bool get_draw_size(int* w, int* h) override;
void render(const DrawCall& pass) override;
void clear_backbuffer(Color color, float depth, u8 stencil, ClearMask mask) override;
TextureRef create_texture(int width, int height, TextureFormat format) override;
TargetRef create_target(int width, int height, const TextureFormat* attachments, int attachment_count) override;
ShaderRef create_shader(const ShaderData* data) override;
MeshRef create_mesh() override;
ID3D11InputLayout* get_layout(D3D11_Shader* shader, const VertexFormat& format);
ID3D11BlendState* get_blend(const BlendMode& blend);
ID3D11RasterizerState* get_rasterizer(const DrawCall& pass);
ID3D11SamplerState* get_sampler(const TextureSampler& sampler);
ID3D11DepthStencilState* get_depthstencil(const DrawCall& pass);
};
// Utility Methods
D3D11_BLEND_OP blend_op(BlendOp op);
D3D11_BLEND blend_factor(BlendFactor factor);
bool reflect_uniforms(Vector<UniformInfo>& append_uniforms_to, Vector<ID3D11Buffer*>& append_buffers_to, ID3DBlob* shader, ShaderType shader_type);
void apply_uniforms(D3D11_Shader* shader, const MaterialRef& material, ShaderType type);
class D3D11_Texture : public Texture
{
private:
int m_width;
int m_height;
TextureFormat m_format;
DXGI_FORMAT m_dxgi_format;
bool m_is_framebuffer;
int m_size;
public:
ID3D11Texture2D* texture = nullptr;
ID3D11Texture2D* staging = nullptr;
ID3D11ShaderResourceView* view = nullptr;
D3D11_Texture(int width, int height, TextureFormat format, bool is_framebuffer)
{
m_width = width;
m_height = height;
m_format = format;
m_is_framebuffer = is_framebuffer;
m_size = 0;
D3D11_TEXTURE2D_DESC desc = { 0 };
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
bool is_depth_stencil = false;
switch (format)
{
case TextureFormat::R:
desc.Format = DXGI_FORMAT_R8_UNORM;
m_size = width * height;
break;
case TextureFormat::RG:
desc.Format = DXGI_FORMAT_R8G8_UNORM;
m_size = width * height * 2;
break;
case TextureFormat::RGBA:
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
m_size = width * height * 4;
break;
case TextureFormat::DepthStencil:
desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
m_size = width * height * 4;
is_depth_stencil = true;
break;
case TextureFormat::None:
case TextureFormat::Count:
break;
}
if (!is_depth_stencil)
desc.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
else
desc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
if (is_framebuffer && !is_depth_stencil)
desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
m_dxgi_format = desc.Format;
auto hr = RENDERER->device->CreateTexture2D(&desc, NULL, &texture);
if (!SUCCEEDED(hr))
{
if (texture)
texture->Release();
texture = nullptr;
return;
}
if (!is_depth_stencil)
{
hr = RENDERER->device->CreateShaderResourceView(texture, NULL, &view);
if (!SUCCEEDED(hr))
{
texture->Release();
texture = nullptr;
}
}
}
~D3D11_Texture()
{
if (texture)
texture->Release();
texture = nullptr;
if (staging)
staging->Release();
staging = nullptr;
if (view)
view->Release();
view = nullptr;
}
int width() const override
{
return m_width;
}
int height() const override
{
return m_height;
}
TextureFormat format() const override
{
return m_format;
}
void set_data(const u8* data) override
{
// bounds
D3D11_BOX box;
box.left = 0;
box.right = m_width;
box.top = 0;
box.bottom = m_height;
box.front = 0;
box.back = 1;
// set data
RENDERER->context->UpdateSubresource(
texture,
0,
&box,
data,
m_size / m_height,
0);
}
void get_data(u8* data) override
{
HRESULT hr;
// create staging texture
if (!staging)
{
D3D11_TEXTURE2D_DESC desc;
desc.Width = m_width;
desc.Height = m_height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = m_dxgi_format;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;
hr = RENDERER->device->CreateTexture2D(&desc, NULL, &staging);
if (!SUCCEEDED(hr))
{
BLAH_ASSERT(false, "Failed to create staging texture to get data");
return;
}
}
D3D11_BOX box;
box.left = 0;
box.right = m_width;
box.bottom = m_height;
box.top = 0;
box.front = 0;
box.back = 1;
// copy data to staging texture
RENDERER->context->CopySubresourceRegion(
staging, 0,
0, 0, 0,
texture, 0,
&box);
// get data
D3D11_MAPPED_SUBRESOURCE map;
hr = RENDERER->context->Map(staging, 0, D3D11_MAP_READ, 0, &map);
if (!SUCCEEDED(hr))
{
BLAH_ASSERT(false, "Failed to get texture data");
return;
}
int bytes_per_pixel = m_size / (m_width * m_height);
int bytes_per_row = m_width * bytes_per_pixel;
for (int y = 0; y < m_height; y++)
memcpy(data + y * bytes_per_row, (unsigned char*)map.pData + map.RowPitch * y, bytes_per_row);
RENDERER->context->Unmap(staging, 0);
}
bool is_framebuffer() const override
{
return m_is_framebuffer;
}
};
class D3D11_Target : public Target
{
private:
Attachments m_attachments;
public:
StackVector<ID3D11RenderTargetView*, Attachments::capacity - 1> color_views;
ID3D11DepthStencilView* depth_view = nullptr;
D3D11_Target(int width, int height, const TextureFormat* attachments, int attachment_count)
{
for (int i = 0; i < attachment_count; i++)
{
auto tex = new D3D11_Texture(width, height, attachments[i], true);
m_attachments.push_back(TextureRef(tex));
if (attachments[i] == TextureFormat::DepthStencil)
{
RENDERER->device->CreateDepthStencilView(tex->texture, nullptr, &depth_view);
}
else
{
ID3D11RenderTargetView* view = nullptr;
RENDERER->device->CreateRenderTargetView(tex->texture, nullptr, &view);
color_views.push_back(view);
}
}
}
~D3D11_Target()
{
for (auto& it : color_views)
it->Release();
color_views.clear();
if (depth_view)
depth_view->Release();
depth_view = nullptr;
}
Attachments& textures() override
{
return m_attachments;
}
const Attachments& textures() const override
{
return m_attachments;
}
void clear(Color color, float depth, u8 stencil, ClearMask mask) override
{
float col[4] = { color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f };
if (((int)mask & (int)ClearMask::Color) == (int)ClearMask::Color)
{
for (int i = 0; i < color_views.size(); i++)
RENDERER->context->ClearRenderTargetView(color_views[i], col);
}
if (depth_view)
{
UINT flags = 0;
if (((int)mask & (int)ClearMask::Depth) == (int)ClearMask::Depth)
flags |= D3D11_CLEAR_DEPTH;
if (((int)mask & (int)ClearMask::Stencil) == (int)ClearMask::Stencil)
flags |= D3D11_CLEAR_STENCIL;
if (flags != 0)
RENDERER->context->ClearDepthStencilView(depth_view, flags, depth, stencil);
}
}
};
class D3D11_Shader : public Shader
{
public:
ID3D11VertexShader* vertex = nullptr;
ID3D11PixelShader* fragment = nullptr;
ID3DBlob* vertex_blob = nullptr;
ID3DBlob* fragment_blob = nullptr;
Vector<ID3D11Buffer*> vertex_uniform_buffers;
Vector<ID3D11Buffer*> fragment_uniform_buffers;
Vector<Vector<float>> vertex_uniform_values;
Vector<Vector<float>> fragment_uniform_values;
StackVector<ShaderData::HLSL_Attribute, 16> attributes;
Vector<UniformInfo> uniform_list;
u32 hash = 0;
bool valid = false;
D3D11_Shader(const ShaderData* data)
{
UINT flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_DEBUG;
ID3DBlob* error_blob = nullptr;
HRESULT hr;
// compile vertex shader
{
hr = D3DCompile(
data->vertex.cstr(),
data->vertex.length(),
nullptr,
nullptr,
nullptr,
"vs_main",
"vs_5_0",
flags,
0,
&vertex_blob,
&error_blob);
if (FAILED(hr))
{
Log::error("%s", (char*)error_blob->GetBufferPointer());
error_blob->Release();
return;
}
}
// compile fragment shader
{
hr = D3DCompile(
data->fragment.cstr(),
data->fragment.length(),
nullptr,
nullptr,
nullptr,
"ps_main",
"ps_5_0",
flags,
0,
&fragment_blob,
&error_blob);
if (FAILED(hr))
{
Log::error("%s", (char*)error_blob->GetBufferPointer());
error_blob->Release();
return;
}
}
// create vertex shader
{
hr = RENDERER->device->CreateVertexShader(
vertex_blob->GetBufferPointer(),
vertex_blob->GetBufferSize(),
NULL,
&vertex);
if (!SUCCEEDED(hr))
return;
}
// create fragment shader
{
hr = RENDERER->device->CreatePixelShader(
fragment_blob->GetBufferPointer(),
fragment_blob->GetBufferSize(),
NULL,
&fragment);
if (!SUCCEEDED(hr))
return;
}
// get uniforms
reflect_uniforms(uniform_list, vertex_uniform_buffers, vertex_blob, ShaderType::Vertex);
reflect_uniforms(uniform_list, fragment_uniform_buffers, fragment_blob, ShaderType::Fragment);
// combine uniforms that were in both
for (int i = 0; i < uniform_list.size(); i++)
{
for (int j = i + 1; j < uniform_list.size(); j++)
{
if (strcmp(uniform_list[i].name, uniform_list[j].name) == 0)
{
if (uniform_list[i].type == uniform_list[j].type)
{
uniform_list[i].shader = (ShaderType)((int)uniform_list[i].shader | (int)uniform_list[j].shader);
uniform_list.erase(j);
j--;
}
}
}
}
// create CPU uniform buffers, so we don't need to create them during rendering
vertex_uniform_values.expand(vertex_uniform_buffers.size());
fragment_uniform_values.expand(fragment_uniform_buffers.size());
// copy HLSL attributes
attributes = data->hlsl_attributes;
// store hash
hash = 5381;
for (auto& it : attributes)
{
for (size_t i = 0, n = strlen(it.semantic_name); i < n; i++)
hash = ((hash << 5) + hash) + it.semantic_name[i];
hash = (it.semantic_index << 5) + hash;
}
// Shader is ready for use!
valid = true;
}
~D3D11_Shader() override
{
if (vertex)
vertex->Release();
vertex = nullptr;
if (vertex_blob)
vertex_blob->Release();
vertex_blob = nullptr;
if (fragment)
fragment->Release();
fragment = nullptr;
if (fragment_blob)
fragment_blob->Release();
fragment_blob = nullptr;
for (auto& it : vertex_uniform_buffers)
it->Release();
vertex_uniform_buffers.clear();
for (auto& it : fragment_uniform_buffers)
it->Release();
fragment_uniform_buffers.clear();
}
Vector<UniformInfo>& uniforms() override
{
return uniform_list;
}
const Vector<UniformInfo>& uniforms() const override
{
return uniform_list;
}
};
class D3D11_Mesh : public Mesh
{
private:
i64 m_vertex_count = 0;
i64 m_vertex_capacity = 0;
i64 m_index_count = 0;
i64 m_index_capacity = 0;
public:
ID3D11Buffer* vertex_buffer = nullptr;
VertexFormat vertex_format;
ID3D11Buffer* index_buffer = nullptr;
IndexFormat index_format = IndexFormat::UInt16;
int index_stride = 0;
D3D11_Mesh()
{
}
~D3D11_Mesh()
{
if (vertex_buffer)
vertex_buffer->Release();
vertex_buffer = nullptr;
if (index_buffer)
index_buffer->Release();
index_buffer = nullptr;
}
void index_data(IndexFormat format, const void* indices, i64 count) override
{
m_index_count = count;
if (index_format != format || !index_buffer || m_index_count > m_index_capacity)
{
index_stride = 0;
index_format = format;
m_index_capacity = max(m_index_capacity, m_index_count);
switch (format)
{
case IndexFormat::UInt16: index_stride = sizeof(i16); break;
case IndexFormat::UInt32: index_stride = sizeof(i32); break;
}
if (m_index_capacity > 0 && indices)
{
// release existing buffer
if (index_buffer)
index_buffer->Release();
index_buffer = nullptr;
// buffer description
D3D11_BUFFER_DESC desc = { 0 };
desc.ByteWidth = (UINT)(index_stride * m_index_capacity);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
// buffer data
D3D11_SUBRESOURCE_DATA data = { 0 };
data.pSysMem = indices;
// create
auto hr = RENDERER->device->CreateBuffer(&desc, &data, &index_buffer);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Index Data");
}
}
else if (indices)
{
D3D11_MAPPED_SUBRESOURCE map;
auto hr = RENDERER->context->Map(index_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Index Data");
if (SUCCEEDED(hr))
{
memcpy(map.pData, indices, index_stride * count);
RENDERER->context->Unmap(index_buffer, 0);
}
}
}
void vertex_data(const VertexFormat& format, const void* vertices, i64 count) override
{
m_vertex_count = count;
// recreate buffer if we've changed
if (vertex_format.stride != format.stride || !vertex_buffer || m_vertex_count > m_vertex_capacity)
{
m_vertex_capacity = max(m_vertex_capacity, m_vertex_count);
vertex_format = format;
// discard old buffer
if (vertex_buffer)
vertex_buffer->Release();
vertex_buffer = nullptr;
if (m_vertex_capacity > 0 && vertices)
{
// buffer description
D3D11_BUFFER_DESC desc = { 0 };
desc.ByteWidth = (UINT)(format.stride * m_vertex_capacity);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
// buffer data
D3D11_SUBRESOURCE_DATA data = { 0 };
data.pSysMem = vertices;
// create
auto hr = RENDERER->device->CreateBuffer(&desc, &data, &vertex_buffer);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Vertex Data");
}
}
// otherwise just update it
else if (vertices)
{
D3D11_MAPPED_SUBRESOURCE map;
auto hr = RENDERER->context->Map(vertex_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Vertex Data");
if (SUCCEEDED(hr))
{
memcpy(map.pData, vertices, vertex_format.stride * count);
RENDERER->context->Unmap(vertex_buffer, 0);
}
}
}
void instance_data(const VertexFormat& format, const void* instances, i64 count) override
{
}
i64 index_count() const override
{
return m_index_count;
}
i64 vertex_count() const override
{
return m_vertex_count;
}
i64 instance_count() const override
{
return 0;
}
};
bool Renderer_D3D11::init()
{
last_window_size = App::get_size();
// Define Swap Chain
DXGI_SWAP_CHAIN_DESC desc = {};
desc.BufferDesc.RefreshRate.Numerator = 0;
desc.BufferDesc.RefreshRate.Denominator = 1;
desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 1;
desc.OutputWindow = (HWND)Platform::d3d11_get_hwnd();
desc.Windowed = true;
// Creation Flags
UINT flags = D3D11_CREATE_DEVICE_SINGLETHREADED;
#if defined(DEBUG) || defined(_DEBUG)
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// Create D3D device & context & swap chain
D3D_FEATURE_LEVEL feature_level;
HRESULT hr = D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
flags,
NULL,
0,
D3D11_SDK_VERSION,
&desc,
&swap_chain,
&device,
&feature_level,
&context);
// Exit out if it's not OK
if (!SUCCEEDED(hr) || !swap_chain || !device || !context)
return false;
// Get the backbuffer
ID3D11Texture2D* frame_buffer = nullptr;
swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&frame_buffer);
if (frame_buffer)
{
D3D11_TEXTURE2D_DESC desc;
frame_buffer->GetDesc(&desc);
drawable_size = Point(desc.Width, desc.Height);
device->CreateRenderTargetView(frame_buffer, nullptr, &backbuffer_view);
frame_buffer->Release();
}
// TODO:
// create a depth backbuffer
// Store Features
info.type = RendererType::D3D11;
info.instancing = true;
info.max_texture_size = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
info.origin_bottom_left = false;
// Print Driver Info
{
IDXGIDevice* dxgi_device;
IDXGIAdapter* dxgi_adapter;
DXGI_ADAPTER_DESC adapter_desc;
hr = device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgi_device);
if (SUCCEEDED(hr))
{
dxgi_device->GetAdapter(&dxgi_adapter);
dxgi_adapter->GetDesc(&adapter_desc);
Log::info("D3D11 %ls", adapter_desc.Description);
dxgi_device->Release();
dxgi_adapter->Release();
}
else
{
Log::info("D3D11");
}
}
// create default sprite batch shader
default_batcher_shader = Shader::create(d3d11_batch_shader_data);
return true;
}
void Renderer_D3D11::shutdown()
{
// release cached objects
for (auto& it : blend_cache)
it.state->Release();
for (auto& it : depthstencil_cache)
it.state->Release();
for (auto& it : layout_cache)
it.layout->Release();
for (auto& it : rasterizer_cache)
it.state->Release();
for (auto& it : sampler_cache)
it.state->Release();
// release main devices
if (backbuffer_view)
backbuffer_view->Release();
if (backbuffer_depth_view)
backbuffer_depth_view->Release();
swap_chain->Release();
context->ClearState();
context->Flush();
context->Release();
device->Release();
}
void Renderer_D3D11::update()
{
}
void Renderer_D3D11::before_render()
{
HRESULT hr;
auto next_window_size = App::get_size();
if (last_window_size != next_window_size)
{
last_window_size = next_window_size;
// release old buffer
if (backbuffer_view)
backbuffer_view->Release();
// perform resize
hr = swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Backbuffer on Resize");
// get the new buffer
ID3D11Texture2D* frame_buffer = nullptr;
hr = swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&frame_buffer);
if (SUCCEEDED(hr) && frame_buffer)
{
// get backbuffer drawable size
D3D11_TEXTURE2D_DESC desc;
frame_buffer->GetDesc(&desc);
drawable_size = Point(desc.Width, desc.Height);
// create view
hr = device->CreateRenderTargetView(frame_buffer, nullptr, &backbuffer_view);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to update Backbuffer on Resize");
frame_buffer->Release();
}
}
}
bool Renderer_D3D11::get_draw_size(int* w, int* h)
{
*w = drawable_size.x;
*h = drawable_size.y;
return true;
}
void Renderer_D3D11::after_render()
{
auto vsync = App::get_flag(Flags::VSync);
auto hr = swap_chain->Present(vsync ? 1 : 0, 0);
BLAH_ASSERT(SUCCEEDED(hr), "Failed to Present swap chain");
}
TextureRef Renderer_D3D11::create_texture(int width, int height, TextureFormat format)
{
auto result = new D3D11_Texture(width, height, format, false);
if (result->texture)
return TextureRef(result);
delete result;
return TextureRef();
}
TargetRef Renderer_D3D11::create_target(int width, int height, const TextureFormat* attachments, int attachment_count)
{
return TargetRef(new D3D11_Target(width, height, attachments, attachment_count));
}
ShaderRef Renderer_D3D11::create_shader(const ShaderData* data)
{
auto result = new D3D11_Shader(data);
if (result->valid)
return ShaderRef(result);
delete result;
return ShaderRef();
}
MeshRef Renderer_D3D11::create_mesh()
{
return MeshRef(new D3D11_Mesh());
}
void Renderer_D3D11::render(const DrawCall& pass)
{
auto ctx = context;
auto mesh = (D3D11_Mesh*)pass.mesh.get();
auto shader = (D3D11_Shader*)(pass.material->shader().get());
// OM
{
// Set the Target
if (pass.target == App::backbuffer() || !pass.target)
{
ctx->OMSetRenderTargets(1, &backbuffer_view, backbuffer_depth_view);
}
else
{
auto target = (D3D11_Target*)(pass.target.get());
ctx->OMSetRenderTargets(target->color_views.size(), target->color_views.begin(), target->depth_view);
}
// Depth
{
auto depthstencil = get_depthstencil(pass);
if (depthstencil)
ctx->OMSetDepthStencilState(depthstencil, 0);
}
// Blend Mode
{
auto blend = get_blend(pass.blend);
if (blend)