forked from vpinball/vpinball
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RenderDevice.cpp
2254 lines (1954 loc) · 82.7 KB
/
RenderDevice.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
#include "stdafx.h"
#include <DxErr.h>
//#include "Dwmapi.h" // use when we get rid of XP at some point, get rid of the manual dll loads in here then
#ifndef DISABLE_FORCE_NVIDIA_OPTIMUS
#include "nvapi.h"
#endif
#include "RenderDevice.h"
#include "Shader.h"
#ifndef ENABLE_SDL
#include "Material.h"
#include "BasicShader.h"
#include "DMDShader.h"
#include "FBShader.h"
#include "FlasherShader.h"
#include "LightShader.h"
#ifdef SEPARATE_CLASSICLIGHTSHADER
#include "ClassicLightShader.h"
#endif
#endif
// SMAA:
#include "shader/AreaTex.h"
#include "shader/SearchTex.h"
#ifndef ENABLE_SDL
#pragma comment(lib, "d3d9.lib") // TODO: put into build system
#pragma comment(lib, "d3dx9.lib") // TODO: put into build system
#if _MSC_VER >= 1900
#pragma comment(lib, "legacy_stdio_definitions.lib") //dxerr.lib needs this
#endif
#pragma comment(lib, "dxerr.lib") // TODO: put into build system
static RenderTarget *srcr_cache = nullptr; //!! meh, for nvidia depth read only
static D3DTexture *srct_cache = nullptr;
static D3DTexture* dest_cache = nullptr;
static bool IsWindowsVistaOr7()
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0,{ 0 }, 0, 0 };
const DWORDLONG dwlConditionMask = //VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0, VER_MAJORVERSION, VER_EQUAL),
VER_MINORVERSION, VER_EQUAL)/*,
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL)*/;
osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA);
osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA);
//osvi.wServicePackMajor = 0;
const bool vista = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION /*| VER_SERVICEPACKMAJOR*/, dwlConditionMask) != FALSE;
OSVERSIONINFOEXW osvi2 = { sizeof(osvi), 0, 0, 0, 0,{ 0 }, 0, 0 };
osvi2.dwMajorVersion = HIBYTE(_WIN32_WINNT_WIN7);
osvi2.dwMinorVersion = LOBYTE(_WIN32_WINNT_WIN7);
//osvi2.wServicePackMajor = 0;
const bool win7 = VerifyVersionInfoW(&osvi2, VER_MAJORVERSION | VER_MINORVERSION /*| VER_SERVICEPACKMAJOR*/, dwlConditionMask) != FALSE;
return vista || win7;
}
#endif
typedef HRESULT(STDAPICALLTYPE *pRGV)(LPOSVERSIONINFOEXW osi);
static pRGV mRtlGetVersion = nullptr;
bool IsWindows10_1803orAbove()
{
if (mRtlGetVersion == nullptr)
mRtlGetVersion = (pRGV)GetProcAddress(GetModuleHandle(TEXT("ntdll")), "RtlGetVersion"); // apparently the only really reliable solution to get the OS version (as of Win10 1803)
if (mRtlGetVersion != nullptr)
{
OSVERSIONINFOEXW osInfo;
osInfo.dwOSVersionInfoSize = sizeof(osInfo);
mRtlGetVersion(&osInfo);
if (osInfo.dwMajorVersion > 10)
return true;
if (osInfo.dwMajorVersion == 10 && osInfo.dwMinorVersion > 0)
return true;
if (osInfo.dwMajorVersion == 10 && osInfo.dwMinorVersion == 0 && osInfo.dwBuildNumber >= 17134) // which is the more 'common' 1803
return true;
}
return false;
}
#ifdef ENABLE_SDL
//my definition for SDL GLint size; GLenum type; GLboolean normalized; GLsizei stride;
//D3D definition WORD Stream; WORD Offset; BYTE Type; BYTE Method; BYTE Usage; BYTE UsageIndex;
constexpr VertexElement VertexTexelElement[] =
{
{ 3, GL_FLOAT, GL_FALSE, 0, "POSITION0" },
{ 2, GL_FLOAT, GL_FALSE, 0, "TEXCOORD0" },
{ 0, 0, 0, 0, nullptr}
/* { 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()*/
};
VertexDeclaration* RenderDevice::m_pVertexTexelDeclaration = (VertexDeclaration*)&VertexTexelElement;
constexpr VertexElement VertexNormalTexelElement[] =
{
{ 3, GL_FLOAT, GL_FALSE, 0, "POSITION0" },
{ 3, GL_FLOAT, GL_FALSE, 0, "NORMAL0" },
{ 2, GL_FLOAT, GL_FALSE, 0, "TEXCOORD0" },
{ 0, 0, 0, 0, nullptr}
/*
{ 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal
{ 0, 6 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()*/
};
VertexDeclaration* RenderDevice::m_pVertexNormalTexelDeclaration = (VertexDeclaration*)&VertexNormalTexelElement;
/*constexpr VertexElement VertexNormalTexelTexelElement[] =
{
{ 0, 0 * sizeof(float),D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float),D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal
{ 0, 6 * sizeof(float),D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
{ 0, 8 * sizeof(float),D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // tex1
D3DDECL_END()
};
VertexDeclaration* RenderDevice::m_pVertexNormalTexelTexelDeclaration = nullptr;*/
constexpr VertexElement VertexTrafoTexelElement[] =
{
{ 4, GL_FLOAT, GL_FALSE, 0, "POSITION0" },
{ 2, GL_FLOAT, GL_FALSE, 0, nullptr },//legacy?
{ 2, GL_FLOAT, GL_FALSE, 0, "TEXCOORD0" },
{ 0, 0, 0, 0, nullptr }
/* { 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, // transformed pos
{ 0, 4 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // (mostly, except for classic lights) unused, there to be able to share same code as VertexNormalTexelElement
{ 0, 6 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()*/
};
VertexDeclaration* RenderDevice::m_pVertexTrafoTexelDeclaration = (VertexDeclaration*)&VertexTrafoTexelElement;
#else
constexpr VertexElement VertexTexelElement[] =
{
{ 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()
};
VertexDeclaration* RenderDevice::m_pVertexTexelDeclaration = nullptr;
constexpr VertexElement VertexNormalTexelElement[] =
{
{ 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal
{ 0, 6 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()
};
VertexDeclaration* RenderDevice::m_pVertexNormalTexelDeclaration = nullptr;
/*constexpr VertexElement VertexNormalTexelTexelElement[] =
{
{ 0, 0 * sizeof(float),D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos
{ 0, 3 * sizeof(float),D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal
{ 0, 6 * sizeof(float),D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
{ 0, 8 * sizeof(float),D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // tex1
D3DDECL_END()
};
VertexDeclaration* RenderDevice::m_pVertexNormalTexelTexelDeclaration = nullptr;*/
// pre-transformed, take care that this is a float4 and needs proper w component setup (also see https://docs.microsoft.com/en-us/windows/desktop/direct3d9/mapping-fvf-codes-to-a-directx-9-declaration)
constexpr VertexElement VertexTrafoTexelElement[] =
{
{ 0, 0 * sizeof(float), D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, // transformed pos
{ 0, 4 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // (mostly, except for classic lights) unused, there to be able to share same code as VertexNormalTexelElement
{ 0, 6 * sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // tex0
D3DDECL_END()
};
VertexDeclaration* RenderDevice::m_pVertexTrafoTexelDeclaration = nullptr;
static unsigned int fvfToSize(const DWORD fvf)
{
switch (fvf)
{
case MY_D3DFVF_NOTEX2_VERTEX:
case MY_D3DTRANSFORMED_NOTEX2_VERTEX:
return sizeof(Vertex3D_NoTex2);
case MY_D3DFVF_TEX:
return sizeof(Vertex3D_TexelOnly);
default:
assert(!"Unknown FVF type in fvfToSize");
return 0;
}
}
static VertexDeclaration* fvfToDecl(const DWORD fvf)
{
switch (fvf)
{
case MY_D3DFVF_NOTEX2_VERTEX:
return RenderDevice::m_pVertexNormalTexelDeclaration;
case MY_D3DTRANSFORMED_NOTEX2_VERTEX:
return RenderDevice::m_pVertexTrafoTexelDeclaration;
case MY_D3DFVF_TEX:
return RenderDevice::m_pVertexTexelDeclaration;
default:
assert(!"Unknown FVF type in fvfToDecl");
return nullptr;
}
}
#endif
static UINT ComputePrimitiveCount(const RenderDevice::PrimitiveTypes type, const int vertexCount)
{
switch (type)
{
case RenderDevice::POINTLIST:
return vertexCount;
case RenderDevice::LINELIST:
return vertexCount / 2;
case RenderDevice::LINESTRIP:
return std::max(0, vertexCount - 1);
case RenderDevice::TRIANGLELIST:
return vertexCount / 3;
case RenderDevice::TRIANGLESTRIP:
case RenderDevice::TRIANGLEFAN:
return std::max(0, vertexCount - 2);
default:
return 0;
}
}
#ifdef ENABLE_SDL
static const char* glErrorToString(const int error) {
switch (error) {
case GL_INVALID_ENUM: return "GL_INVALID_ENUM";
case GL_INVALID_VALUE: return "GL_INVALID_VALUE";
case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION";
case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW";
case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW";
case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY";
case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION";
default: return "unknown";
}
}
#endif
void ReportFatalError(const HRESULT hr, const char *file, const int line)
{
char msg[1024];
#ifdef ENABLE_SDL
sprintf_s(msg, 1024, "GL Fatal Error 0x%0002X %s in %s:%d", hr, glErrorToString(hr), file, line);
ShowError(msg);
#else
sprintf_s(msg, 1024, "Fatal error %s (0x%x: %s) at %s:%d", DXGetErrorString(hr), hr, DXGetErrorDescription(hr), file, line);
ShowError(msg);
exit(-1);
#endif
}
void ReportError(const char *errorText, const HRESULT hr, const char *file, const int line)
{
char msg[1024];
#ifdef ENABLE_SDL
sprintf_s(msg, 1024, "GL Error 0x%0002X %s in %s:%d", hr, glErrorToString(hr), file, line);
ShowError(msg);
#else
sprintf_s(msg, 1024, "%s %s (0x%x: %s) at %s:%d", errorText, DXGetErrorString(hr), hr, DXGetErrorDescription(hr), file, line);
ShowError(msg);
exit(-1);
#endif
}
unsigned m_curLockCalls, m_frameLockCalls;
unsigned int RenderDevice::Perf_GetNumLockCalls() const { return m_frameLockCalls; }
#ifdef ENABLE_SDL
void checkGLErrors(const char *file, const int line) {
GLenum err;
unsigned int count = 0;
while ((err = glGetError()) != GL_NO_ERROR) {
count++;
ReportFatalError(err, file, line);
}
/*if (count>0) {
exit(-1);
}*/
}
#endif
////////////////////////////////////////////////////////////////////
int getNumberOfDisplays()
{
#ifdef ENABLE_SDL
return SDL_GetNumVideoDisplays();
#else
return GetSystemMetrics(SM_CMONITORS);
#endif
}
void EnumerateDisplayModes(const int display, std::vector<VideoMode>& modes)
{
modes.clear();
#ifdef ENABLE_SDL
const int amount = SDL_GetNumDisplayModes(display);
for (int mode = 0; mode < amount; ++mode) {
SDL_DisplayMode myMode;
SDL_GetDisplayMode(display, mode, &myMode);
VideoMode vmode = {};
vmode.width = myMode.w;
vmode.height = myMode.h;
switch (myMode.format) {
case SDL_PIXELFORMAT_RGB24:
case SDL_PIXELFORMAT_BGR24:
case SDL_PIXELFORMAT_RGB888:
case SDL_PIXELFORMAT_RGBX8888:
case SDL_PIXELFORMAT_BGR888:
case SDL_PIXELFORMAT_BGRX8888:
case SDL_PIXELFORMAT_ARGB8888:
case SDL_PIXELFORMAT_RGBA8888:
case SDL_PIXELFORMAT_ABGR8888:
case SDL_PIXELFORMAT_BGRA8888:
vmode.depth = 32;
break;
case SDL_PIXELFORMAT_RGB565:
case SDL_PIXELFORMAT_BGR565:
case SDL_PIXELFORMAT_ABGR1555:
case SDL_PIXELFORMAT_BGRA5551:
case SDL_PIXELFORMAT_ARGB1555:
case SDL_PIXELFORMAT_RGBA5551:
vmode.depth = 16;
break;
case SDL_PIXELFORMAT_ARGB2101010:
vmode.depth = 30;
break;
default:
vmode.depth = 0;
}
vmode.refreshrate = myMode.refresh_rate;
modes.push_back(vmode);
}
#else
std::vector<DisplayConfig> displays;
getDisplayList(displays);
if (display >= (int)displays.size())
return;
const int adapter = displays[display].adapter;
IDirect3D9 *d3d = Direct3DCreate9(D3D_SDK_VERSION);
if (d3d == nullptr)
{
ShowError("Could not create D3D9 object.");
return;
}
//for (int j = 0; j < 2; ++j)
const int j = 0; // limit to 32bit only nowadays
{
const D3DFORMAT fmt = (D3DFORMAT)((j == 0) ? colorFormat::RGB8 : colorFormat::RGB5);
const unsigned numModes = d3d->GetAdapterModeCount(adapter, fmt);
for (unsigned i = 0; i < numModes; ++i)
{
D3DDISPLAYMODE d3dmode;
d3d->EnumAdapterModes(adapter, fmt, i, &d3dmode);
if (d3dmode.Width >= 640)
{
VideoMode mode;
mode.width = d3dmode.Width;
mode.height = d3dmode.Height;
mode.depth = (fmt == (D3DFORMAT)colorFormat::RGB5) ? 16 : 32;
mode.refreshrate = d3dmode.RefreshRate;
modes.push_back(mode);
}
}
}
SAFE_RELEASE(d3d);
#endif
}
BOOL CALLBACK MonitorEnumList(__in HMONITOR hMonitor, __in HDC hdcMonitor, __in LPRECT lprcMonitor, __in LPARAM dwData)
{
std::map<std::string,DisplayConfig>* data = reinterpret_cast<std::map<std::string,DisplayConfig>*>(dwData);
MONITORINFOEX info;
info.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(hMonitor, &info);
DisplayConfig config = {};
config.top = info.rcMonitor.top;
config.left = info.rcMonitor.left;
config.width = info.rcMonitor.right - info.rcMonitor.left;
config.height = info.rcMonitor.bottom - info.rcMonitor.top;
config.isPrimary = (config.top == 0) && (config.left == 0);
config.display = (int)data->size(); // This number does neither map to the number form display settings nor something else.
#ifdef ENABLE_SDL
config.adapter = config.display;
#else
config.adapter = -1;
#endif
memcpy(config.DeviceName, info.szDevice, CCHDEVICENAME); // Internal display name e.g. "\\\\.\\DISPLAY1"
data->insert(std::pair<std::string, DisplayConfig>(config.DeviceName, config));
return TRUE;
}
int getDisplayList(std::vector<DisplayConfig>& displays)
{
displays.clear();
std::map<std::string, DisplayConfig> displayMap;
// Get the resolution of all enabled displays.
EnumDisplayMonitors(nullptr, nullptr, MonitorEnumList, reinterpret_cast<LPARAM>(&displayMap));
#ifndef ENABLE_SDL
IDirect3D9* pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D == nullptr)
{
ShowError("Could not create D3D9 object.");
return -1;
}
// Map the displays to the DX9 adapter. Otherwise this leads to an performance impact on systems with multiple GPUs
const int adapterCount = pD3D->GetAdapterCount();
for (int i = 0;i < adapterCount;++i) {
D3DADAPTER_IDENTIFIER9 adapter;
pD3D->GetAdapterIdentifier(i, 0, &adapter);
std::map<std::string, DisplayConfig>::iterator display = displayMap.find(adapter.DeviceName);
if (display != displayMap.end()) {
display->second.adapter = i;
strncpy_s(display->second.GPU_Name, adapter.Description, sizeof(display->second.GPU_Name)-1);
}
}
SAFE_RELEASE(pD3D);
#endif
// Apply the same numbering as windows
int i = 0;
for (std::map<std::string, DisplayConfig>::iterator display = displayMap.begin(); display != displayMap.end(); ++display)
{
if (display->second.adapter >= 0) {
display->second.display = i;
#ifdef ENABLE_SDL
const char* name = SDL_GetDisplayName(display->second.adapter);
if(name != nullptr)
strncpy_s(display->second.GPU_Name, name, sizeof(display->second.GPU_Name) - 1);
else
display->second.GPU_Name[0] = '\0'; //!!
#endif
displays.push_back(display->second);
}
i++;
}
return i;
}
bool getDisplaySetupByID(const int display, int &x, int &y, int &width, int &height)
{
std::vector<DisplayConfig> displays;
getDisplayList(displays);
for (std::vector<DisplayConfig>::iterator displayConf = displays.begin(); displayConf != displays.end(); ++displayConf) {
if ((display == -1 && displayConf->isPrimary) || display == displayConf->display) {
x = displayConf->left;
y = displayConf->top;
width = displayConf->width;
height = displayConf->height;
return true;
}
}
x = 0;
y = 0;
width = GetSystemMetrics(SM_CXSCREEN);
height = GetSystemMetrics(SM_CYSCREEN);
return false;
}
int getPrimaryDisplay()
{
std::vector<DisplayConfig> displays;
getDisplayList(displays);
for (std::vector<DisplayConfig>::iterator displayConf = displays.begin(); displayConf != displays.end(); ++displayConf)
if (displayConf->isPrimary)
return displayConf->adapter;
return 0;
}
////////////////////////////////////////////////////////////////////
VertexBuffer* RenderDevice::m_quadVertexBuffer = nullptr;
unsigned int RenderDevice::m_stats_drawn_triangles = 0;
#ifndef ENABLE_SDL
#define CHECKNVAPI(s) { NvAPI_Status hr = (s); if (hr != NVAPI_OK) { NvAPI_ShortString ss; NvAPI_GetErrorMessage(hr,ss); g_pvp->MessageBox(ss, "NVAPI", MB_OK | MB_ICONEXCLAMATION); } }
static bool NVAPIinit = false; //!! meh
bool RenderDevice::m_INTZ_support = false;
bool RenderDevice::m_useNvidiaApi = false;
#ifdef USE_D3D9EX
typedef HRESULT(WINAPI *pD3DC9Ex)(UINT SDKVersion, IDirect3D9Ex**);
static pD3DC9Ex mDirect3DCreate9Ex = nullptr;
#endif
#define DWM_EC_DISABLECOMPOSITION 0
#define DWM_EC_ENABLECOMPOSITION 1
typedef HRESULT(STDAPICALLTYPE *pDICE)(BOOL* pfEnabled);
static pDICE mDwmIsCompositionEnabled = nullptr;
typedef HRESULT(STDAPICALLTYPE *pDF)();
static pDF mDwmFlush = nullptr;
typedef HRESULT(STDAPICALLTYPE *pDEC)(UINT uCompositionAction);
static pDEC mDwmEnableComposition = nullptr;
#endif
RenderDevice::RenderDevice(const HWND hwnd, const int width, const int height, const bool fullscreen, const int colordepth, int VSync, const bool useAA, const bool stereo3D, const unsigned int FXAA, const bool sharpen, const bool ss_refl, const bool useNvidiaApi, const bool disable_dwm, const int BWrendering)
: m_windowHwnd(hwnd), m_width(width), m_height(height), m_fullscreen(fullscreen),
m_colorDepth(colordepth), m_vsync(VSync), m_useAA(useAA), m_stereo3D(stereo3D),
m_ssRefl(ss_refl), m_disableDwm(disable_dwm), m_sharpen(sharpen), m_FXAA(FXAA), m_BWrendering(BWrendering), m_texMan(*this)
{
m_useNvidiaApi = useNvidiaApi;
m_stats_drawn_triangles = 0;
mDwmIsCompositionEnabled = (pDICE)GetProcAddress(GetModuleHandle(TEXT("dwmapi.dll")), "DwmIsCompositionEnabled"); //!! remove as soon as win xp support dropped and use static link
mDwmEnableComposition = (pDEC)GetProcAddress(GetModuleHandle(TEXT("dwmapi.dll")), "DwmEnableComposition"); //!! remove as soon as win xp support dropped and use static link
mDwmFlush = (pDF)GetProcAddress(GetModuleHandle(TEXT("dwmapi.dll")), "DwmFlush"); //!! remove as soon as win xp support dropped and use static link
if (mDwmIsCompositionEnabled && mDwmEnableComposition)
{
BOOL dwm = 0;
mDwmIsCompositionEnabled(&dwm);
m_dwm_enabled = m_dwm_was_enabled = !!dwm;
if (m_dwm_was_enabled && m_disableDwm && IsWindowsVistaOr7()) // windows 8 and above will not allow do disable it, but will still return S_OK
{
mDwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
m_dwm_enabled = false;
}
}
else
{
m_dwm_was_enabled = false;
m_dwm_enabled = false;
}
currentDeclaration = nullptr;
//m_curShader = nullptr;
// fill state caches with dummy values
memset(textureStateCache, 0xCC, sizeof(DWORD) * TEXTURE_SAMPLERS * TEXTURE_STATE_CACHE_SIZE);
memset(textureSamplerCache, 0xCC, sizeof(DWORD) * TEXTURE_SAMPLERS * TEXTURE_SAMPLER_CACHE_SIZE);
// initialize performance counters
m_curDrawCalls = m_frameDrawCalls = 0;
m_curStateChanges = m_frameStateChanges = 0;
m_curTextureChanges = m_frameTextureChanges = 0;
m_curParameterChanges = m_frameParameterChanges = 0;
m_curTechniqueChanges = m_frameTechniqueChanges = 0;
m_curTextureUpdates = m_frameTextureUpdates = 0;
m_curLockCalls = m_frameLockCalls = 0; //!! meh
}
void RenderDevice::CreateDevice(int &refreshrate, UINT adapterIndex)
{
#ifdef USE_D3D9EX
m_pD3DEx = nullptr;
m_pD3DDeviceEx = nullptr;
mDirect3DCreate9Ex = (pD3DC9Ex)GetProcAddress(GetModuleHandle(TEXT("d3d9.dll")), "Direct3DCreate9Ex"); //!! remove as soon as win xp support dropped and use static link
if (mDirect3DCreate9Ex)
{
const HRESULT hr = mDirect3DCreate9Ex(D3D_SDK_VERSION, &m_pD3DEx);
if (FAILED(hr) || (m_pD3DEx == nullptr))
{
ShowError("Could not create D3D9Ex object.");
throw 0;
}
m_pD3DEx->QueryInterface(__uuidof(IDirect3D9), reinterpret_cast<void **>(&m_pD3D));
}
else
#endif
{
m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (m_pD3D == nullptr)
{
ShowError("Could not create D3D9 object.");
throw 0;
}
}
m_adapter = m_pD3D->GetAdapterCount() > (int)adapterIndex ? adapterIndex : 0;
D3DDEVTYPE devtype = D3DDEVTYPE_HAL;
// Look for 'NVIDIA PerfHUD' adapter
// If it is present, override default settings
// This only takes effect if run under NVPerfHud, otherwise does nothing
for (UINT adapter = 0; adapter < m_pD3D->GetAdapterCount(); adapter++)
{
D3DADAPTER_IDENTIFIER9 Identifier;
m_pD3D->GetAdapterIdentifier(adapter, 0, &Identifier);
if (strstr(Identifier.Description, "PerfHUD") != 0)
{
m_adapter = adapter;
devtype = D3DDEVTYPE_REF;
break;
}
}
D3DCAPS9 caps;
m_pD3D->GetDeviceCaps(m_adapter, devtype, &caps);
// check which parameters can be used for anisotropic filter
m_mag_aniso = (caps.TextureFilterCaps & D3DPTFILTERCAPS_MAGFANISOTROPIC) != 0;
m_maxaniso = caps.MaxAnisotropy;
if (((caps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) != 0) || ((caps.TextureCaps & D3DPTEXTURECAPS_POW2) != 0))
ShowError("D3D device does only support power of 2 textures");
//if (caps.NumSimultaneousRTs < 2)
// ShowError("D3D device doesn't support multiple render targets!");
bool video10bit = LoadValueBoolWithDefault("Player", "Render10Bit", false);
if (!m_fullscreen && video10bit)
{
ShowError("10Bit-Monitor support requires 'Force exclusive Fullscreen Mode' to be also enabled!");
video10bit = false;
}
// get the current display format
D3DFORMAT format;
if (!m_fullscreen)
{
D3DDISPLAYMODE mode;
CHECKD3D(m_pD3D->GetAdapterDisplayMode(m_adapter, &mode));
format = mode.Format;
refreshrate = mode.RefreshRate;
}
else
{
format = (D3DFORMAT)(video10bit ? colorFormat::RGBA10 : ((m_colorDepth == 16) ? colorFormat::RGB5 : colorFormat::RGB8));
}
// limit vsync rate to actual refresh rate, otherwise special handling in renderloop
if (m_vsync > refreshrate)
m_vsync = 0;
D3DPRESENT_PARAMETERS params;
params.BackBufferWidth = m_width;
params.BackBufferHeight = m_height;
params.BackBufferFormat = format;
params.BackBufferCount = 1;
params.MultiSampleType = /*useAA ? D3DMULTISAMPLE_4_SAMPLES :*/ D3DMULTISAMPLE_NONE; // D3DMULTISAMPLE_NONMASKABLE? //!! useAA now uses super sampling/offscreen render
params.MultiSampleQuality = 0; // if D3DMULTISAMPLE_NONMASKABLE then set to > 0
params.SwapEffect = D3DSWAPEFFECT_DISCARD; // FLIP ?
params.hDeviceWindow = m_windowHwnd;
params.Windowed = !m_fullscreen;
params.EnableAutoDepthStencil = FALSE;
params.AutoDepthStencilFormat = D3DFMT_UNKNOWN; // ignored
params.Flags = /*fullscreen ? D3DPRESENTFLAG_LOCKABLE_BACKBUFFER :*/ /*(stereo3D ?*/ 0 /*: D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL)*/; // D3DPRESENTFLAG_LOCKABLE_BACKBUFFER only needed for SetDialogBoxMode() below, but makes rendering slower on some systems :/
params.FullScreen_RefreshRateInHz = m_fullscreen ? refreshrate : 0;
#ifdef USE_D3D9EX
params.PresentationInterval = (m_pD3DEx && (m_vsync != 1)) ? D3DPRESENT_INTERVAL_IMMEDIATE : (!!m_vsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE); //!! or have a special mode to force normal vsync?
#else
params.PresentationInterval = !!m_vsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
#endif
// check if our HDR texture format supports/does sRGB conversion on texture reads, which must NOT be the case as we always set SRGBTexture=true independent of the format!
HRESULT hr = m_pD3D->CheckDeviceFormat(m_adapter, devtype, params.BackBufferFormat, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE, (D3DFORMAT)colorFormat::RGBA32F);
if (SUCCEEDED(hr))
ShowError("D3D device does support D3DFMT_A32B32G32R32F SRGBTexture reads (which leads to wrong tex colors)");
// now the same for our LDR/8bit texture format the other way round
hr = m_pD3D->CheckDeviceFormat(m_adapter, devtype, params.BackBufferFormat, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE, (D3DFORMAT)colorFormat::RGBA8);
if (!SUCCEEDED(hr))
ShowError("D3D device does not support D3DFMT_A8R8G8B8 SRGBTexture reads (which leads to wrong tex colors)");
// check if auto generation of mipmaps can be used, otherwise will be done via d3dx
m_autogen_mipmap = (caps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) != 0;
if (m_autogen_mipmap)
m_autogen_mipmap = (m_pD3D->CheckDeviceFormat(m_adapter, devtype, params.BackBufferFormat, textureUsage::AUTOMIPMAP, D3DRTYPE_TEXTURE, (D3DFORMAT)colorFormat::RGBA8) == D3D_OK);
//m_autogen_mipmap = false; //!! could be done to support correct sRGB/gamma correct generation of mipmaps which is not possible with auto gen mipmap in DX9! at the moment disabled, as the sRGB software path is super slow for similar mipmap filter quality
#ifndef DISABLE_FORCE_NVIDIA_OPTIMUS
if (!NVAPIinit)
{
if (NvAPI_Initialize() == NVAPI_OK)
NVAPIinit = true;
}
#endif
// Determine if INTZ is supported
#ifdef ENABLE_SDL
m_INTZ_support = false;
#else
m_INTZ_support = (m_pD3D->CheckDeviceFormat( m_adapter, devtype, params.BackBufferFormat,
D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, ((D3DFORMAT)(MAKEFOURCC('I','N','T','Z'))))) == D3D_OK;
#endif
// check if requested MSAA is possible
DWORD MultiSampleQualityLevels;
if (!SUCCEEDED(m_pD3D->CheckDeviceMultiSampleType(m_adapter,
devtype, params.BackBufferFormat,
params.Windowed, params.MultiSampleType, &MultiSampleQualityLevels)))
{
ShowError("D3D device does not support this MultiSampleType");
params.MultiSampleType = D3DMULTISAMPLE_NONE;
params.MultiSampleQuality = 0;
}
else
params.MultiSampleQuality = min(params.MultiSampleQuality, MultiSampleQualityLevels);
const bool softwareVP = LoadValueBoolWithDefault("Player", "SoftwareVertexProcessing", false);
const DWORD flags = softwareVP ? D3DCREATE_SOFTWARE_VERTEXPROCESSING : D3DCREATE_HARDWARE_VERTEXPROCESSING;
// Create the D3D device. This optionally goes to the proper fullscreen mode.
// It also creates the default swap chain (front and back buffer).
#ifdef USE_D3D9EX
if (m_pD3DEx)
{
D3DDISPLAYMODEEX mode;
mode.Size = sizeof(D3DDISPLAYMODEEX);
if (m_fullscreen)
{
mode.Format = params.BackBufferFormat;
mode.Width = params.BackBufferWidth;
mode.Height = params.BackBufferHeight;
mode.RefreshRate = params.FullScreen_RefreshRateInHz;
mode.ScanLineOrdering = D3DSCANLINEORDERING_PROGRESSIVE;
}
hr = m_pD3DEx->CreateDeviceEx(
m_adapter,
devtype,
m_windowHwnd,
flags /*| D3DCREATE_PUREDEVICE*/,
¶ms,
m_fullscreen ? &mode : nullptr,
&m_pD3DDeviceEx);
if (FAILED(hr))
{
if (m_fullscreen)
{
const int result = GetSystemMetrics(SM_REMOTESESSION);
const bool isRemoteSession = (result != 0);
if (isRemoteSession)
ShowError("Try disabling exclusive Fullscreen Mode for Remote Desktop Connections");
}
ReportFatalError(hr, __FILE__, __LINE__);
}
m_pD3DDeviceEx->QueryInterface(__uuidof(IDirect3DDevice9), reinterpret_cast<void**>(&m_pD3DDevice));
// Get the display mode so that we can report back the actual refresh rate.
CHECKD3D(m_pD3DDeviceEx->GetDisplayModeEx(0, &mode, nullptr)); //!! what is the actual correct value for the swapchain here?
refreshrate = mode.RefreshRate;
}
else
#endif
{
hr = m_pD3D->CreateDevice(
m_adapter,
devtype,
m_windowHwnd,
flags /*| D3DCREATE_PUREDEVICE*/,
¶ms,
&m_pD3DDevice);
if (FAILED(hr))
ReportError("Fatal Error: unable to create D3D device!", hr, __FILE__, __LINE__);
// Get the display mode so that we can report back the actual refresh rate.
D3DDISPLAYMODE mode;
hr = m_pD3DDevice->GetDisplayMode(m_adapter, &mode);
if (FAILED(hr))
ReportError("Fatal Error: unable to get supported video mode list!", hr, __FILE__, __LINE__);
refreshrate = mode.RefreshRate;
}
/*if (m_fullscreen)
hr = m_pD3DDevice->SetDialogBoxMode(TRUE);*/ // needs D3DPRESENTFLAG_LOCKABLE_BACKBUFFER, but makes rendering slower on some systems :/
// Retrieve a reference to the back buffer.
hr = m_pD3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_pBackBuffer);
if (FAILED(hr))
ReportError("Fatal Error: unable to create back buffer!", hr, __FILE__, __LINE__);
const D3DFORMAT render_format = (D3DFORMAT)((m_BWrendering == 1) ? colorFormat::RG16F : ((m_BWrendering == 2) ? colorFormat::RED16F : colorFormat::RGBA16F));
// alloc float buffer for rendering (optionally 2x2 res for manual super sampling)
hr = m_pD3DDevice->CreateTexture(m_useAA ? 2 * m_width : m_width, m_useAA ? 2 * m_height : m_height, 1, D3DUSAGE_RENDERTARGET, render_format, (D3DPOOL)memoryPool::DEFAULT, &m_pOffscreenBackBufferTexture, nullptr); //!! D3DFMT_A32B32G32R32F?
if (FAILED(hr))
ReportError("Fatal Error: unable to create render buffer!", hr, __FILE__, __LINE__);
// alloc buffer for screen space fake reflection rendering (optionally 2x2 res for manual super sampling)
if (m_ssRefl)
{
hr = m_pD3DDevice->CreateTexture(m_useAA ? 2 * m_width : m_width, m_useAA ? 2 * m_height : m_height, 1, D3DUSAGE_RENDERTARGET, render_format, (D3DPOOL)memoryPool::DEFAULT, &m_pReflectionBufferTexture, nullptr); //!! D3DFMT_A32B32G32R32F?
if (FAILED(hr))
ReportError("Fatal Error: unable to create reflection buffer!", hr, __FILE__, __LINE__);
}
else
m_pReflectionBufferTexture = nullptr;
if (g_pplayer != nullptr)
{
const bool drawBallReflection = ((g_pplayer->m_reflectionForBalls && (g_pplayer->m_ptable->m_useReflectionForBalls == -1)) || (g_pplayer->m_ptable->m_useReflectionForBalls == 1));
if ((g_pplayer->m_ptable->m_reflectElementsOnPlayfield /*&& g_pplayer->m_pf_refl*/) || drawBallReflection)
{
hr = m_pD3DDevice->CreateTexture(m_useAA ? 2 * m_width : m_width, m_useAA ? 2 * m_height : m_height, 1, D3DUSAGE_RENDERTARGET, render_format, (D3DPOOL)memoryPool::DEFAULT, &m_pMirrorTmpBufferTexture, nullptr); //!! D3DFMT_A32B32G32R32F?
if (FAILED(hr))
ReportError("Fatal Error: unable to create reflection map!", hr, __FILE__, __LINE__);
}
}
// alloc bloom tex at 1/4 x 1/4 res (allows for simple HQ downscale of clipped input while saving memory)
hr = m_pD3DDevice->CreateTexture(m_width / 4, m_height / 4, 1, D3DUSAGE_RENDERTARGET, render_format, (D3DPOOL)memoryPool::DEFAULT, &m_pBloomBufferTexture, nullptr); //!! 8bit enough?
if (FAILED(hr))
ReportError("Fatal Error: unable to create bloom buffer!", hr, __FILE__, __LINE__);
// temporary buffer for gaussian blur
hr = m_pD3DDevice->CreateTexture(m_width / 4, m_height / 4, 1, D3DUSAGE_RENDERTARGET, render_format, (D3DPOOL)memoryPool::DEFAULT, &m_pBloomTmpBufferTexture, nullptr); //!! 8bit are enough! //!! but used also for bulb light transmission hack now!
if (FAILED(hr))
ReportError("Fatal Error: unable to create blur buffer!", hr, __FILE__, __LINE__);
// alloc temporary buffer for stereo3D/post-processing AA/sharpen
if (m_stereo3D || (m_FXAA > 0) || m_sharpen)
{
hr = m_pD3DDevice->CreateTexture(m_width, m_height, 1, D3DUSAGE_RENDERTARGET, (D3DFORMAT)(video10bit ? colorFormat::RGBA10 : colorFormat::RGBA8), (D3DPOOL)memoryPool::DEFAULT, &m_pOffscreenBackBufferTmpTexture, nullptr);
if (FAILED(hr))
ReportError("Fatal Error: unable to create stereo3D/post-processing AA/sharpen buffer!", hr, __FILE__, __LINE__);
}
else
m_pOffscreenBackBufferTmpTexture = nullptr;
// alloc one more temporary buffer for SMAA
if (m_FXAA == Quality_SMAA)
{
hr = m_pD3DDevice->CreateTexture(m_width, m_height, 1, D3DUSAGE_RENDERTARGET, (D3DFORMAT)(video10bit ? colorFormat::RGBA10 : colorFormat::RGBA8), (D3DPOOL)memoryPool::DEFAULT, &m_pOffscreenBackBufferTmpTexture2, nullptr);
if (FAILED(hr))
ReportError("Fatal Error: unable to create SMAA buffer!", hr, __FILE__, __LINE__);
}
else
m_pOffscreenBackBufferTmpTexture2 = nullptr;
if (video10bit && (m_FXAA == Quality_SMAA || m_FXAA == Standard_DLAA))
ShowError("SMAA or DLAA post-processing AA should not be combined with 10Bit-output rendering (will result in visible artifacts)!");
//
// create default vertex declarations for shaders
CreateVertexDeclaration(VertexTexelElement, &m_pVertexTexelDeclaration);
CreateVertexDeclaration(VertexNormalTexelElement, &m_pVertexNormalTexelDeclaration);
//CreateVertexDeclaration( VertexNormalTexelTexelElement, &m_pVertexNormalTexelTexelDeclaration );
CreateVertexDeclaration(VertexTrafoTexelElement, &m_pVertexTrafoTexelDeclaration);
if(m_FXAA == Quality_SMAA)
UploadAndSetSMAATextures();
else
{
m_SMAAareaTexture = 0;
m_SMAAsearchTexture = 0;
}
}
bool RenderDevice::LoadShaders()
{
bool shaderCompilationOkay = true;
basicShader = new Shader(this);
shaderCompilationOkay = basicShader->Load(g_basicShaderCode, sizeof(g_basicShaderCode)) && shaderCompilationOkay;
DMDShader = new Shader(this);
shaderCompilationOkay = DMDShader->Load(g_dmdShaderCode, sizeof(g_dmdShaderCode)) && shaderCompilationOkay;
FBShader = new Shader(this);
shaderCompilationOkay = FBShader->Load(g_FBShaderCode, sizeof(g_FBShaderCode)) && shaderCompilationOkay;
flasherShader = new Shader(this);
shaderCompilationOkay = flasherShader->Load(g_flasherShaderCode, sizeof(g_flasherShaderCode)) && shaderCompilationOkay;
lightShader = new Shader(this);
shaderCompilationOkay = lightShader->Load(g_lightShaderCode, sizeof(g_lightShaderCode)) && shaderCompilationOkay;
#ifdef SEPARATE_CLASSICLIGHTSHADER
classicLightShader = new Shader(this);
shaderCompilationOkay = classicLightShader->Load(g_classicLightShaderCode, sizeof(g_classicLightShaderCode)) && shaderCompilationOkay;
#endif
if (!shaderCompilationOkay)
{
ReportError("Fatal Error: shader compilation failed!", -1, __FILE__, __LINE__);
return false;
}
// Now that shaders are compiled, set static textures for SMAA postprocessing shader
if (m_FXAA == Quality_SMAA)
{
CHECKD3D(FBShader->Core()->SetTexture(SHADER_areaTex2D, m_SMAAareaTexture));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_searchTex2D, m_SMAAsearchTexture));
}
return true;
}
bool RenderDevice::DepthBufferReadBackAvailable()
{
if (m_INTZ_support && !m_useNvidiaApi)
return true;
// fall back to NVIDIAs NVAPI, only handle DepthBuffer ReadBack if API was initialized
return NVAPIinit;
}
#ifdef _DEBUG
static void CheckForD3DLeak(IDirect3DDevice9* d3d)
{
IDirect3DSwapChain9 *swapChain;
CHECKD3D(d3d->GetSwapChain(0, &swapChain));
D3DPRESENT_PARAMETERS pp;
CHECKD3D(swapChain->GetPresentParameters(&pp));
SAFE_RELEASE(swapChain);
// idea: device can't be reset if there are still allocated resources
HRESULT hr = d3d->Reset(&pp);
if (FAILED(hr))
{
g_pvp->MessageBox("WARNING! Direct3D resource leak detected!", "Visual Pinball", MB_ICONWARNING);
}
}
#endif
void RenderDevice::FreeShader()
{
if (basicShader)
{
CHECKD3D(basicShader->Core()->SetTexture(SHADER_Texture0, nullptr));
CHECKD3D(basicShader->Core()->SetTexture(SHADER_Texture1, nullptr));
CHECKD3D(basicShader->Core()->SetTexture(SHADER_Texture2, nullptr));
CHECKD3D(basicShader->Core()->SetTexture(SHADER_Texture3, nullptr));
CHECKD3D(basicShader->Core()->SetTexture(SHADER_Texture4, nullptr));
delete basicShader;
basicShader = 0;
}
if (DMDShader)
{
CHECKD3D(DMDShader->Core()->SetTexture(SHADER_Texture0, nullptr));
delete DMDShader;
DMDShader = 0;
}
if (FBShader)
{
CHECKD3D(FBShader->Core()->SetTexture(SHADER_Texture0, nullptr));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_Texture1, nullptr));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_Texture3, nullptr));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_Texture4, nullptr));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_areaTex2D, nullptr));
CHECKD3D(FBShader->Core()->SetTexture(SHADER_searchTex2D, nullptr));
delete FBShader;
FBShader = 0;
}
if (flasherShader)
{
CHECKD3D(flasherShader->Core()->SetTexture(SHADER_Texture0, nullptr));
CHECKD3D(flasherShader->Core()->SetTexture(SHADER_Texture1, nullptr));
delete flasherShader;
flasherShader = 0;
}
if (lightShader)
{
delete lightShader;
lightShader = 0;
}
#ifdef SEPARATE_CLASSICLIGHTSHADER
if (classicLightShader)
{
CHECKD3D(classicLightShader->Core()->SetTexture(SHADER_Texture0, nullptr));
CHECKD3D(classicLightShader->Core()->SetTexture(SHADER_Texture1, nullptr));
CHECKD3D(classicLightShader->Core()->SetTexture(SHADER_Texture2, nullptr));
delete classicLightShader;
classicLightShader=0;
}
#endif
}
RenderDevice::~RenderDevice()
{
#ifndef DISABLE_FORCE_NVIDIA_OPTIMUS
if (srcr_cache != nullptr)
CHECKNVAPI(NvAPI_D3D9_UnregisterResource(srcr_cache)); //!! meh
srcr_cache = nullptr;
if (srct_cache != nullptr)
CHECKNVAPI(NvAPI_D3D9_UnregisterResource(srct_cache)); //!! meh
srct_cache = nullptr;