-
-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathgfxD3D11Device.cpp
More file actions
1900 lines (1569 loc) · 58.8 KB
/
gfxD3D11Device.cpp
File metadata and controls
1900 lines (1569 loc) · 58.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/console.h"
#include "core/stream/fileStream.h"
#include "core/strings/unicode.h"
#include "core/util/journal/process.h"
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11CardProfiler.h"
#include "gfx/D3D11/gfxD3D11VertexBuffer.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "gfx/D3D11/gfxD3D11QueryFence.h"
#include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
#include "gfx/D3D11/gfxD3D11Shader.h"
#include "gfx/D3D11/gfxD3D11Target.h"
#include "platformWin32/platformWin32.h"
#include "windowManager/win32/win32Window.h"
#include "windowManager/platformWindow.h"
#include "gfx/D3D11/screenshotD3D11.h"
#include "materials/shaderData.h"
#include "shaderGen/shaderGen.h"
#include <d3d9.h> //d3dperf
#include "gfxD3D11TextureArray.h"
#ifdef TORQUE_DEBUG
#include "d3d11sdklayers.h"
#endif
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d9.lib") //d3dperf
#pragma comment(lib, "d3d11.lib")
class GFXD3D11TextureArray;
class GFXPCD3D11RegisterDevice
{
public:
GFXPCD3D11RegisterDevice()
{
GFXInit::getRegisterDeviceSignal().notify(&GFXD3D11Device::enumerateAdapters);
}
};
static GFXPCD3D11RegisterDevice pPCD3D11RegisterDevice;
//-----------------------------------------------------------------------------
/// Parse command line arguments for window creation
//-----------------------------------------------------------------------------
static void sgPCD3D11DeviceHandleCommandLine(S32 argc, const char **argv)
{
// useful to pass parameters by command line for d3d (e.g. -dx9 -dx11)
for (U32 i = 1; i < argc; i++)
{
argv[i];
}
}
// Register the command line parsing hook
static ProcessRegisterCommandLine sgCommandLine(sgPCD3D11DeviceHandleCommandLine);
GFXAdapter::CreateDeviceInstanceDelegate GFXD3D11Device::mCreateDeviceInstance(GFXD3D11Device::createInstance);
GFXDevice *GFXD3D11Device::createInstance(U32 adapterIndex)
{
GFXD3D11Device* dev = new GFXD3D11Device(adapterIndex);
return dev;
}
GFXD3D11Device::GFXD3D11Device(U32 index)
{
mDeviceSwizzle32 = &Swizzles::bgra;
GFXVertexColor::setSwizzle(mDeviceSwizzle32);
mDeviceSwizzle24 = &Swizzles::bgr;
mAdapterIndex = index;
mSwapChain = NULL;
mD3DDevice = NULL;
mD3DDeviceContext = NULL;
mVolatileVB = NULL;
mCurrentPB = NULL;
mDynamicPB = NULL;
mLastVertShader = NULL;
mLastPixShader = NULL;
mLastGeoShader = NULL;
mCanCurrentlyRender = false;
mTextureManager = NULL;
mCurrentStateBlock = NULL;
mResourceListHead = NULL;
mPixVersion = 0.0;
mFeatureLevel = D3D_FEATURE_LEVEL_9_1; //lowest listed. should be overridden by init
mVertexShaderTarget = String::EmptyString;
mPixelShaderTarget = String::EmptyString;
mShaderModel = String::EmptyString;
mDrawInstancesCount = 0;
mCardProfiler = NULL;
mDeviceDepthStencil = NULL;
mDeviceBackbuffer = NULL;
mDeviceBackBufferView = NULL;
mDeviceDepthStencilView = NULL;
mCreateFenceType = -1; // Unknown, test on first allocate
mCurrentConstBuffer = NULL;
mMultisampleDesc.Count = 0;
mMultisampleDesc.Quality = 0;
mOcclusionQuerySupported = false;
mDebugLayers = false;
for (U32 i = 0; i < GS_COUNT; ++i)
mModelViewProjSC[i] = NULL;
// Set up the Enum translation tables
GFXD3D11EnumTranslate::init();
}
GFXD3D11Device::~GFXD3D11Device()
{
// Release our refcount on the current stateblock object
mCurrentStateBlock = NULL;
releaseDefaultPoolResources();
mD3DDeviceContext->ClearState();
mD3DDeviceContext->Flush();
// Free the sampler states
SamplerMap::Iterator sampIter = mSamplersMap.begin();
for (; sampIter != mSamplersMap.end(); ++sampIter)
SAFE_RELEASE(sampIter->value);
// Free device buffers
DeviceBufferMap::Iterator bufferIter = mDeviceBufferMap.begin();
for (; bufferIter != mDeviceBufferMap.end(); ++bufferIter)
SAFE_RELEASE(bufferIter->value);
// Free the vertex declarations.
VertexDeclMap::Iterator iter = mVertexDecls.begin();
for (; iter != mVertexDecls.end(); ++iter)
delete iter->value;
// Forcibly clean up the pools
mVolatileVBList.setSize(0);
mDynamicPB = NULL;
// And release our D3D resources.
SAFE_RELEASE(mDeviceDepthStencilView);
SAFE_RELEASE(mDeviceBackBufferView);
SAFE_RELEASE(mDeviceDepthStencil);
SAFE_RELEASE(mDeviceBackbuffer);
SAFE_RELEASE(mD3DDeviceContext);
SAFE_DELETE(mCardProfiler);
SAFE_DELETE(gScreenShot);
#ifdef TORQUE_DEBUG
if (mDebugLayers)
{
ID3D11Debug *pDebug = NULL;
mD3DDevice->QueryInterface(IID_PPV_ARGS(&pDebug));
AssertFatal(pDebug, "~GFXD3D11Device- Failed to get debug layer");
pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
SAFE_RELEASE(pDebug);
}
#endif
SAFE_RELEASE(mSwapChain);
SAFE_RELEASE(mD3DDevice);
}
GFXFormat GFXD3D11Device::selectSupportedFormat(GFXTextureProfile *profile, const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter)
{
U32 features = 0;
if(texture)
features |= D3D11_FORMAT_SUPPORT_TEXTURE2D;
if(mustblend)
features |= D3D11_FORMAT_SUPPORT_BLENDABLE;
if(mustfilter)
features |= D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
for(U32 i = 0; i < formats.size(); i++)
{
if(GFXD3D11TextureFormat[formats[i]] == DXGI_FORMAT_UNKNOWN)
continue;
U32 supportFlag = 0;
mD3DDevice->CheckFormatSupport(GFXD3D11TextureFormat[formats[i]],&supportFlag);
if(supportFlag & features)
return formats[i];
}
return GFXFormatR8G8B8A8;
}
DXGI_SWAP_CHAIN_DESC GFXD3D11Device::setupPresentParams(const GFXVideoMode &mode, const HWND &hwnd)
{
DXGI_SWAP_CHAIN_DESC d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
DXGI_SAMPLE_DESC sampleDesc;
sampleDesc.Count = 1;
sampleDesc.Quality = 0;
mMultisampleDesc = sampleDesc;
d3dpp.BufferCount = smEnableVSync ? 2 : 1; // triple buffering when vsync is on.
d3dpp.BufferDesc.Width = mode.resolution.x;
d3dpp.BufferDesc.Height = mode.resolution.y;
d3dpp.BufferDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
d3dpp.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
d3dpp.OutputWindow = hwnd;
d3dpp.SampleDesc = sampleDesc;
d3dpp.Windowed = !mode.fullScreen;
d3dpp.BufferDesc.RefreshRate.Numerator = mode.refreshRate;
d3dpp.BufferDesc.RefreshRate.Denominator = 1;
d3dpp.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
if (mode.fullScreen)
{
d3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
d3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
d3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
}
return d3dpp;
}
void GFXD3D11Device::enumerateAdapters(Vector<GFXAdapter*> &adapterList)
{
IDXGIAdapter1* EnumAdapter;
IDXGIFactory1* DXGIFactory;
CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
{
GFXAdapter *toAdd = new GFXAdapter;
toAdd->mType = Direct3D11;
toAdd->mIndex = adapterIndex;
toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance;
toAdd->mShaderModel = 5.0f;
DXGI_ADAPTER_DESC1 desc;
EnumAdapter->GetDesc1(&desc);
// LUID identifies adapter for oculus rift
dMemcpy(&toAdd->mLUID, &desc.AdapterLuid, sizeof(toAdd->mLUID));
size_t size=wcslen(desc.Description);
char *str = new char[size+1];
wcstombs(str, desc.Description,size);
str[size]='\0';
String Description=str;
SAFE_DELETE_ARRAY(str);
dStrncpy(toAdd->mName, Description.c_str(), GFXAdapter::MaxAdapterNameLen);
dStrncat(toAdd->mName, " (D3D11)", sizeof(toAdd->mName) - strlen(toAdd->mName) - 1);
IDXGIOutput* pOutput = NULL;
HRESULT hr;
hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
if(hr == DXGI_ERROR_NOT_FOUND)
{
SAFE_RELEASE(EnumAdapter);
break;
}
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> EnumOutputs call failure");
UINT numModes = 0;
DXGI_MODE_DESC* displayModes = NULL;
DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
// Get the number of elements
hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
displayModes = new DXGI_MODE_DESC[numModes];
// Get the list
hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
for(U32 numMode = 0; numMode < numModes; ++numMode)
{
GFXVideoMode vmAdd;
vmAdd.fullScreen = true;
vmAdd.bitDepth = 32;
vmAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
vmAdd.resolution.x = displayModes[numMode].Width;
vmAdd.resolution.y = displayModes[numMode].Height;
toAdd->mAvailableModes.push_back(vmAdd);
}
//Check adapater can handle feature level 10_!
D3D_FEATURE_LEVEL deviceFeature;
ID3D11Device *pTmpDevice = nullptr;
// Create temp Direct3D11 device.
bool suitable = true;
UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
hr = D3D11CreateDevice(EnumAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, createDeviceFlags, NULL, 0, D3D11_SDK_VERSION, &pTmpDevice, &deviceFeature, NULL);
if (FAILED(hr))
suitable = false;
if (deviceFeature < D3D_FEATURE_LEVEL_10_1)
suitable = false;
//double check we support required bgra format for LEVEL_10_1
if (deviceFeature == D3D_FEATURE_LEVEL_10_1)
{
U32 formatSupported = 0;
pTmpDevice->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &formatSupported);
U32 flagsRequired = D3D11_FORMAT_SUPPORT_RENDER_TARGET | D3D11_FORMAT_SUPPORT_DISPLAY;
if (!(formatSupported && flagsRequired))
{
Con::printf("DXGI adapter: %s does not support BGRA", Description.c_str());
suitable = false;
}
}
delete[] displayModes;
SAFE_RELEASE(pTmpDevice);
SAFE_RELEASE(pOutput);
SAFE_RELEASE(EnumAdapter);
if (suitable)
{
adapterList.push_back(toAdd);
}
else
{
Con::printf("DXGI adapter: %s does not support D3D11 feature level 10 or better", Description.c_str());
delete toAdd;
}
}
SAFE_RELEASE(DXGIFactory);
}
void GFXD3D11Device::enumerateVideoModes()
{
mVideoModes.clear();
IDXGIAdapter1* EnumAdapter;
IDXGIFactory1* DXGIFactory;
HRESULT hr;
hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
if (FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> CreateDXGIFactory1 call failure");
for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
{
IDXGIOutput* pOutput = NULL;
hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
if(hr == DXGI_ERROR_NOT_FOUND)
{
SAFE_RELEASE(EnumAdapter);
break;
}
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> EnumOutputs call failure");
UINT numModes = 0;
DXGI_MODE_DESC* displayModes = NULL;
DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
// Get the number of elements
hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
displayModes = new DXGI_MODE_DESC[numModes];
// Get the list
hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
for(U32 numMode = 0; numMode < numModes; ++numMode)
{
GFXVideoMode toAdd;
toAdd.fullScreen = false;
toAdd.bitDepth = 32;
toAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
toAdd.resolution.x = displayModes[numMode].Width;
toAdd.resolution.y = displayModes[numMode].Height;
mVideoModes.push_back(toAdd);
}
delete[] displayModes;
SAFE_RELEASE(pOutput);
SAFE_RELEASE(EnumAdapter);
}
SAFE_RELEASE(DXGIFactory);
}
void GFXD3D11Device::init(const GFXVideoMode &mode, PlatformWindow *window)
{
AssertFatal(window, "GFXD3D11Device::init - must specify a window!");
//HWND winHwnd = (HWND)window->getSystemWindow( PlatformWindow::WindowSystem_Windows );
//SetFocus(winHwnd);
UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef TORQUE_DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
mDebugLayers = true;
#endif
// TODO support at least feature level 10 to match GL
D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 };
U32 nFeatureCount = ARRAYSIZE(pFeatureLevels);
D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_HARDWARE;// use D3D_DRIVER_TYPE_REFERENCE for reference device
// create a device, device context and swap chain using the information in the d3dpp struct
HRESULT hres = D3D11CreateDevice(NULL,
driverType,
NULL,
createDeviceFlags,
pFeatureLevels,
nFeatureCount,
D3D11_SDK_VERSION,
&mD3DDevice,
&mFeatureLevel,
&mD3DDeviceContext);
if(FAILED(hres))
{
#ifdef TORQUE_DEBUG
//try again without debug device layer enabled
createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
hres = D3D11CreateDevice(NULL,
driverType,
NULL,
createDeviceFlags,
pFeatureLevels,
nFeatureCount,
D3D11_SDK_VERSION,
&mD3DDevice,
&mFeatureLevel,
&mD3DDeviceContext);
//if we failed again than we definitely have a problem
if (FAILED(hres))
AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
Con::warnf("GFXD3D11Device::init - Debug layers not detected!");
mDebugLayers = false;
#else
AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
#endif
}
//set the fullscreen state here if we need to
if(mode.fullScreen)
{
hres = mSwapChain->SetFullscreenState(TRUE, NULL);
if(FAILED(hres))
{
AssertFatal(false, "GFXD3D11Device::init- Failed to set fullscreen state!");
}
}
#ifdef TORQUE_DEBUG
_suppressDebugMessages();
#endif
mTextureManager = new GFXD3D11TextureManager();
// Now reacquire all the resources we trashed earlier
reacquireDefaultPoolResources();
//set vert/pixel shader targets
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_1:
case D3D_FEATURE_LEVEL_11_0:
mVertexShaderTarget = "vs_5_0";
mPixelShaderTarget = "ps_5_0";
mGeometryShaderTarget = "gs_5_0";
mPixVersion = 5.0f;
mShaderModel = "50";
break;
case D3D_FEATURE_LEVEL_10_1:
mVertexShaderTarget = "vs_4_1";
mPixelShaderTarget = "ps_4_1";
mGeometryShaderTarget = "gs_4_1";
mPixVersion = 4.1f;
mShaderModel = "41";
break;
default:
AssertFatal(false, "GFXD3D11Device::init - We don't support this feature level");
}
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
ID3D11Query *testQuery = NULL;
// detect occlusion query support
if (SUCCEEDED(mD3DDevice->CreateQuery(&queryDesc, &testQuery))) mOcclusionQuerySupported = true;
SAFE_RELEASE(testQuery);
Con::printf("Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No");
mCardProfiler = new GFXD3D11CardProfiler();
mCardProfiler->init();
gScreenShot = new ScreenShotD3D11;
mInitialized = true;
deviceInited();
}
// Supress any debug layer messages we don't want to see
void GFXD3D11Device::_suppressDebugMessages()
{
if (mDebugLayers)
{
ID3D11Debug *pDebug = NULL;
if (SUCCEEDED(mD3DDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDebug)))
{
ID3D11InfoQueue *pInfoQueue = NULL;
if (SUCCEEDED(pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue)))
{
//Disable breaking on error or corruption, this can be handy when using VS graphics debugging
pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false);
pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false);
D3D11_MESSAGE_ID hide[] =
{
//this is harmless and no need to spam the console
D3D11_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS
};
D3D11_INFO_QUEUE_FILTER filter;
memset(&filter, 0, sizeof(filter));
filter.DenyList.NumIDs = _countof(hide);
filter.DenyList.pIDList = hide;
pInfoQueue->AddStorageFilterEntries(&filter);
SAFE_RELEASE(pInfoQueue);
}
SAFE_RELEASE(pDebug);
}
}
}
bool GFXD3D11Device::beginSceneInternal()
{
mCanCurrentlyRender = true;
return mCanCurrentlyRender;
}
GFXWindowTarget * GFXD3D11Device::allocWindowTarget(PlatformWindow *window)
{
AssertFatal(window,"GFXD3D11Device::allocWindowTarget - no window provided!");
// Set up a new window target...
GFXD3D11WindowTarget *gdwt = new GFXD3D11WindowTarget();
gdwt->mWindow = window;
gdwt->mSize = window->getClientExtent();
gdwt->initPresentationParams();
if (!mInitialized)
{
gdwt->mSecondaryWindow = false;
// Allocate the device.
init(window->getVideoMode(), window);
gdwt->initPresentationParams();
gdwt->createSwapChain();
gdwt->createBuffersAndViews();
mSwapChain = gdwt->getSwapChain();
mDeviceBackbuffer = gdwt->getBackBuffer();
mDeviceDepthStencil = gdwt->getDepthStencil();
mDeviceBackBufferView = gdwt->getBackBufferView();
mDeviceDepthStencilView = gdwt->getDepthStencilView();
}
else //additional window/s
{
gdwt->mSecondaryWindow = true;
gdwt->initPresentationParams();
gdwt->createSwapChain();
gdwt->createBuffersAndViews();
}
return gdwt;
}
GFXTextureTarget* GFXD3D11Device::allocRenderToTextureTarget(bool genMips)
{
GFXD3D11TextureTarget *targ = new GFXD3D11TextureTarget(genMips);
targ->registerResourceWithDevice(this);
return targ;
}
void GFXD3D11Device::beginReset()
{
if (!mD3DDevice)
return;
mInitialized = false;
releaseDefaultPoolResources();
// Clean up some commonly dangling state. This helps prevents issues with
// items that are destroyed by the texture manager callbacks and recreated
// later, but still left bound.
setVertexBuffer(NULL);
setPrimitiveBuffer(NULL);
for (S32 i = 0; i<getNumSamplers(); i++)
setTexture(i, NULL);
mD3DDeviceContext->ClearState();
//release old buffers and views
SAFE_RELEASE(mDeviceDepthStencilView);
SAFE_RELEASE(mDeviceBackBufferView);
SAFE_RELEASE(mDeviceDepthStencil);
SAFE_RELEASE(mDeviceBackbuffer);
}
void GFXD3D11Device::endReset(GFXD3D11WindowTarget* windowTarget)
{
//grab new references
mDeviceBackbuffer = windowTarget->getBackBuffer();
mDeviceDepthStencil = windowTarget->getDepthStencil();
mDeviceBackBufferView = windowTarget->getBackBufferView();
mDeviceDepthStencilView = windowTarget->getDepthStencilView();
mD3DDeviceContext->OMSetRenderTargets(1, &mDeviceBackBufferView, mDeviceDepthStencilView);
// Now reacquire all the resources we trashed earlier
reacquireDefaultPoolResources();
mD3DDeviceContext->PSSetShader(mLastPixShader, NULL, 0);
mD3DDeviceContext->VSSetShader(mLastVertShader, NULL, 0);
mInitialized = true;
// Mark everything dirty and flush to card, for sanity.
updateStates(true);
}
void GFXD3D11Device::setupGenericShaders(GenericShaderType type)
{
AssertFatal(type != GSTargetRestore, ""); //not used
if(mGenericShader[GSColor] == NULL)
{
ShaderData *shaderData;
//shader model 4.0 is enough for the generic shaders
const char* shaderModel = "4.0";
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorV.hlsl"));
shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorP.hlsl"));
shaderData->setField("pixVersion", shaderModel);
shaderData->registerObject();
mGenericShader[GSColor] = shaderData->getShader();
mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureV.hlsl"));
shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureP.hlsl"));
shaderData->setField("pixVersion", shaderModel);
shaderData->registerObject();
mGenericShader[GSModColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureV.hlsl"));
shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureP.hlsl"));
shaderData->setField("pixVersion", shaderModel);
shaderData->registerObject();
mGenericShader[GSAddColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureV.hlsl"));
shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureP.hlsl"));
shaderData->setField("pixVersion", shaderModel);
shaderData->registerObject();
mGenericShader[GSTexture] = shaderData->getShader();
mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
//Force an update
mViewportDirty = true;
_updateRenderTargets();
}
MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
setShader(mGenericShader[type]);
setShaderConstBuffer(mGenericShaderBuffer[type]);
}
//-----------------------------------------------------------------------------
/// Creates a state block object based on the desc passed in. This object
/// represents an immutable state.
GFXStateBlockRef GFXD3D11Device::createStateBlockInternal(const GFXStateBlockDesc& desc)
{
return GFXStateBlockRef(new GFXD3D11StateBlock(desc));
}
/// Activates a stateblock
void GFXD3D11Device::setStateBlockInternal(GFXStateBlock* block, bool force)
{
AssertFatal(static_cast<GFXD3D11StateBlock*>(block), "Incorrect stateblock type for this device!");
GFXD3D11StateBlock* d3dBlock = static_cast<GFXD3D11StateBlock*>(block);
GFXD3D11StateBlock* d3dCurrent = static_cast<GFXD3D11StateBlock*>(mCurrentStateBlock.getPointer());
if (force)
d3dCurrent = NULL;
d3dBlock->activate(d3dCurrent);
}
/// Called by base GFXDevice to actually set a const buffer
void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
{
if (buffer)
{
PROFILE_SCOPE(GFXD3D11Device_setShaderConstBufferInternal);
AssertFatal(static_cast<GFXD3D11ShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
GFXD3D11ShaderConstBuffer* d3dBuffer = static_cast<GFXD3D11ShaderConstBuffer*>(buffer);
d3dBuffer->activate(mCurrentConstBuffer);
mCurrentConstBuffer = d3dBuffer;
}
else
{
mCurrentConstBuffer = NULL;
}
}
//-----------------------------------------------------------------------------
void GFXD3D11Device::copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face)
{
AssertFatal(pDst, "GFXD3D11Device::copyResource: Destination texture is null");
AssertFatal(pSrc, "GFXD3D11Device::copyResource: Source cubemap is null");
GFXD3D11TextureObject *pD3DDst = static_cast<GFXD3D11TextureObject*>(pDst);
GFXD3D11Cubemap *pD3DSrc = static_cast<GFXD3D11Cubemap*>(pSrc);
const U32 mipLevels = pD3DSrc->getMipMapLevels();
for (U32 mip = 0; mip < mipLevels; mip++)
{
const U32 srcSubResource = D3D11CalcSubresource(mip, face, mipLevels);
const U32 dstSubResource = D3D11CalcSubresource(mip, 0, mipLevels);
mD3DDeviceContext->CopySubresourceRegion(pD3DDst->get2DTex(), dstSubResource, 0, 0, 0, pD3DSrc->get2DTex(), srcSubResource, NULL);
}
}
//-----------------------------------------------------------------------------
void GFXD3D11Device::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
{
// Make sure we have flushed our render target state.
_updateRenderTargets();
UINT depthstencilFlag = 0;
//TODO: current support is 5 render targets, clean this up
ID3D11RenderTargetView* rtView[5] = { NULL };
ID3D11DepthStencilView* dsView = NULL;
mD3DDeviceContext->OMGetRenderTargets(5, rtView, &dsView);
const FLOAT clearColor[4] = { color.red, color.green, color.blue, color.alpha };
if (flags & GFXClearTarget && rtView)
{
for (U32 i = 0; i < 5; i++)
{
if (rtView[i])
mD3DDeviceContext->ClearRenderTargetView(rtView[i], clearColor);
}
}
if (flags & GFXClearZBuffer)
depthstencilFlag |= D3D11_CLEAR_DEPTH;
if (flags & GFXClearStencil)
depthstencilFlag |= D3D11_CLEAR_STENCIL;
if (depthstencilFlag && dsView)
mD3DDeviceContext->ClearDepthStencilView(dsView, depthstencilFlag, z, stencil);
for (U32 i = 0; i < 5; i++)
SAFE_RELEASE(rtView[i]);
SAFE_RELEASE(dsView);
}
void GFXD3D11Device::clearColorAttachment(const U32 attachment, const LinearColorF& color)
{
GFXD3D11TextureTarget *pTarget = static_cast<GFXD3D11TextureTarget*>(mCurrentRT.getPointer());
ID3D11RenderTargetView* rtView = NULL;
if (!pTarget)
{
rtView = mDeviceBackBufferView;// we are using the default backbuffer
}
else
{
//attachment + 1 to skip past DepthStencil which is first in the list
rtView = static_cast<ID3D11RenderTargetView*>(pTarget->mTargetViews[attachment + 1]);
}
const FLOAT clearColor[4] = { color.red, color.green, color.blue, color.alpha };
mD3DDeviceContext->ClearRenderTargetView(rtView, clearColor);
}
void GFXD3D11Device::endSceneInternal()
{
mCanCurrentlyRender = false;
}
void GFXD3D11Device::_updateRenderTargets()
{
if (mRTDirty || (mCurrentRT && mCurrentRT->isPendingState()))
{
if (mRTDeactivate)
{
mRTDeactivate->deactivate();
mRTDeactivate = NULL;
}
// NOTE: The render target changes are not really accurate
// as the GFXTextureTarget supports MRT internally. So when
// we activate a GFXTarget it could result in multiple calls
// to SetRenderTarget on the actual device.
mDeviceStatistics.mRenderTargetChanges++;
mCurrentRT->activate();
mRTDirty = false;
}
if (mViewportDirty)
{
D3D11_VIEWPORT viewport;
viewport.TopLeftX = mViewport.point.x;
viewport.TopLeftY = mViewport.point.y;
viewport.Width = mViewport.extent.x;
viewport.Height = mViewport.extent.y;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
mD3DDeviceContext->RSSetViewports(1, &viewport);
mViewportDirty = false;
}
}
void GFXD3D11Device::releaseDefaultPoolResources()
{
// Release all the dynamic vertex buffer arrays
// Forcibly clean up the pools
for(U32 i=0; i<mVolatileVBList.size(); i++)
{
SAFE_RELEASE(mVolatileVBList[i]->vb);
mVolatileVBList[i] = NULL;
}
mVolatileVBList.setSize(0);
// We gotta clear the current const buffer else the next
// activate may erroneously think the device is still holding
// this state and fail to set it.
mCurrentConstBuffer = NULL;
// Set current VB to NULL and set state dirty
for (U32 i=0; i < VERTEX_STREAM_COUNT; i++)
{
mCurrentVertexBuffer[i] = NULL;
mVertexBufferDirty[i] = true;
mVertexBufferFrequency[i] = 0;
mVertexBufferFrequencyDirty[i] = true;
}
// Release dynamic index buffer
if(mDynamicPB != NULL)
{
SAFE_RELEASE(mDynamicPB->ib);
}
// Set current PB/IB to NULL and set state dirty
mCurrentPrimitiveBuffer = NULL;
mCurrentPB = NULL;
mPrimitiveBufferDirty = true;
// Zombify texture manager (for D3D this only modifies default pool textures)
if( mTextureManager )
mTextureManager->zombify();
// Set global dirty state so the IB/PB and VB get reset
mStateDirty = true;
// Walk the resource list and zombify everything.
GFXResource *walk = mResourceListHead;
while(walk)
{
walk->zombify();
walk = walk->getNextResource();
}
}
void GFXD3D11Device::reacquireDefaultPoolResources()
{
// Now do the dynamic index buffers
if( mDynamicPB == NULL )
mDynamicPB = new GFXD3D11PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic);
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(U16) * GFX_MAX_DYNAMIC_INDICES;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &mDynamicPB->ib);
if(FAILED(hr))
{
AssertFatal(false, "Failed to allocate dynamic IB");
}
// Walk the resource list and zombify everything.
GFXResource *walk = mResourceListHead;
while(walk)
{
walk->resurrect();
walk = walk->getNextResource();
}
if(mTextureManager)
mTextureManager->resurrect();
}
GFXD3D11VertexBuffer* GFXD3D11Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded )
{
PROFILE_SCOPE( GFXD3D11Device_findVBPool );