Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Windows/GPU/D3D11Context.cpp
3185 views
1
#include "ppsspp_config.h"
2
3
#include "Common/CommonWindows.h"
4
#ifndef __LIBRETRO__ // their build server uses an old SDK
5
#include <dxgi1_5.h>
6
#endif
7
#include <d3d11.h>
8
#include <WinError.h>
9
#include <wrl/client.h>
10
11
#include "Common/Log.h"
12
#include "Common/System/Display.h"
13
#include "Common/Data/Encoding/Utf8.h"
14
#include "Common/Data/Text/I18n.h"
15
16
#include "Core/Config.h"
17
#include "Core/ConfigValues.h"
18
#include "Core/System.h"
19
#include "Windows/GPU/D3D11Context.h"
20
#include "Windows/W32Util/Misc.h"
21
#include "Common/GPU/thin3d.h"
22
#include "Common/GPU/thin3d_create.h"
23
#include "Common/GPU/D3D11/D3D11Loader.h"
24
25
#ifndef DXGI_ERROR_NOT_FOUND
26
#define _FACDXGI 0x87a
27
#define MAKE_DXGI_HRESULT(code) MAKE_HRESULT(1, _FACDXGI, code)
28
#define DXGI_ERROR_NOT_FOUND MAKE_DXGI_HRESULT(2)
29
#endif
30
31
#if PPSSPP_PLATFORM(UWP)
32
#error This file should not be compiled for UWP.
33
#endif
34
35
using Microsoft::WRL::ComPtr;
36
37
HRESULT D3D11Context::CreateTheDevice(IDXGIAdapter *adapter) {
38
bool windowed = true;
39
// D3D11 has no need for display rotation.
40
g_display.rotation = DisplayRotation::ROTATE_0;
41
g_display.rot_matrix.setIdentity();
42
#if defined(_DEBUG) && !PPSSPP_ARCH(ARM) && !PPSSPP_ARCH(ARM64)
43
UINT createDeviceFlags = D3D11_CREATE_DEVICE_DEBUG;
44
#else
45
UINT createDeviceFlags = 0;
46
#endif
47
48
static const D3D_FEATURE_LEVEL featureLevels[] = {
49
D3D_FEATURE_LEVEL_12_1,
50
D3D_FEATURE_LEVEL_12_0,
51
D3D_FEATURE_LEVEL_11_1,
52
D3D_FEATURE_LEVEL_11_0,
53
D3D_FEATURE_LEVEL_10_1,
54
D3D_FEATURE_LEVEL_10_0,
55
};
56
const UINT numFeatureLevels = ARRAYSIZE(featureLevels);
57
58
HRESULT hr = S_OK;
59
D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_UNKNOWN;
60
hr = ptr_D3D11CreateDevice(adapter, driverType, nullptr, createDeviceFlags, (D3D_FEATURE_LEVEL *)featureLevels, numFeatureLevels,
61
D3D11_SDK_VERSION, &device_, &featureLevel_, &context_);
62
if (hr == E_INVALIDARG) {
63
// DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
64
hr = ptr_D3D11CreateDevice(adapter, driverType, nullptr, createDeviceFlags, (D3D_FEATURE_LEVEL *)&featureLevels[3], numFeatureLevels - 3,
65
D3D11_SDK_VERSION, &device_, &featureLevel_, &context_);
66
} else if ((hr == DXGI_ERROR_SDK_COMPONENT_MISSING) && (createDeviceFlags & D3D11_CREATE_DEVICE_DEBUG)) {
67
// Likely no debug device available.
68
// This happens in debug builds if you don't install the Graphics Tools optional feature in Windows 10+.
69
// So, we just retry without the debug flag.
70
WARN_LOG(Log::G3D, "D3D11CreateDevice failed with DXGI_ERROR_SDK_COMPONENT_MISSING, retrying without debug flag.");
71
createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
72
hr = ptr_D3D11CreateDevice(adapter, driverType, nullptr, createDeviceFlags, (D3D_FEATURE_LEVEL *)featureLevels, numFeatureLevels,
73
D3D11_SDK_VERSION, &device_, &featureLevel_, &context_);
74
}
75
return hr;
76
}
77
78
bool D3D11Context::Init(HINSTANCE hInst, HWND wnd, std::string *error_message) {
79
hWnd_ = wnd;
80
LoadD3D11Error result = LoadD3D11();
81
82
HRESULT hr = E_FAIL;
83
std::vector<std::string> adapterNames;
84
std::string chosenAdapterName;
85
if (result == LoadD3D11Error::SUCCESS) {
86
std::vector<ComPtr<IDXGIAdapter>> adapters;
87
int chosenAdapter = 0;
88
ComPtr<IDXGIFactory> pFactory;
89
90
hr = ptr_CreateDXGIFactory(IID_PPV_ARGS(&pFactory));
91
if (SUCCEEDED(hr)) {
92
ComPtr<IDXGIAdapter> pAdapter;
93
for (UINT i = 0; pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; i++) {
94
adapters.push_back(pAdapter);
95
DXGI_ADAPTER_DESC desc;
96
pAdapter->GetDesc(&desc);
97
std::string str = ConvertWStringToUTF8(desc.Description);
98
adapterNames.push_back(str);
99
if (str == g_Config.sD3D11Device) {
100
chosenAdapter = i;
101
}
102
}
103
if (!adapters.empty()) {
104
chosenAdapterName = adapterNames[chosenAdapter];
105
hr = CreateTheDevice(adapters[chosenAdapter].Get());
106
adapters.clear();
107
} else {
108
// No adapters found. Trip the error path below.
109
hr = E_FAIL;
110
}
111
}
112
}
113
114
if (FAILED(hr)) {
115
const char *defaultError = "Your GPU does not appear to support Direct3D 11.\n\nWould you like to try again using OpenGL instead?";
116
auto err = GetI18NCategory(I18NCat::ERRORS);
117
118
std::wstring error;
119
120
if (result == LoadD3D11Error::FAIL_NO_COMPILER) {
121
error = ConvertUTF8ToWString(err->T("D3D11CompilerMissing", "D3DCompiler_47.dll not found. Please install. Or press Yes to try again using OpenGL instead."));
122
} else if (result == LoadD3D11Error::FAIL_NO_D3D11) {
123
error = ConvertUTF8ToWString(err->T("D3D11Missing", "Your operating system version does not include D3D11. Please run Windows Update.\n\nPress Yes to try again using Direct3D9 instead."));
124
}
125
126
error = ConvertUTF8ToWString(err->T("D3D11NotSupported", defaultError));
127
std::wstring title = ConvertUTF8ToWString(err->T("D3D11InitializationError", "Direct3D 11 initialization error"));
128
bool yes = IDYES == MessageBox(hWnd_, error.c_str(), title.c_str(), MB_ICONERROR | MB_YESNO);
129
if (yes) {
130
// Change the config to OpenGL and restart.
131
g_Config.iGPUBackend = (int)GPUBackend::OPENGL;
132
g_Config.sFailedGPUBackends.clear();
133
g_Config.Save("save_d3d9_fallback");
134
135
W32Util::ExitAndRestart();
136
}
137
return false;
138
}
139
140
if (FAILED(device_.As(&device1_))) {
141
device1_ = nullptr;
142
}
143
144
if (FAILED(context_.As(&context1_))) {
145
context1_ = nullptr;
146
}
147
148
#ifdef _DEBUG
149
if (SUCCEEDED(device_.As(&d3dDebug_))) {
150
if (SUCCEEDED(d3dDebug_.As(&d3dInfoQueue_))) {
151
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
152
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
153
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true);
154
}
155
}
156
#endif
157
158
159
int width;
160
int height;
161
W32Util::GetWindowRes(hWnd_, &width, &height);
162
163
// Obtain DXGI factory from device (since we used nullptr for pAdapter above)
164
ComPtr<IDXGIFactory1> dxgiFactory;
165
ComPtr<IDXGIDevice> dxgiDevice;
166
hr = device_.As(&dxgiDevice);
167
if (SUCCEEDED(hr)) {
168
ComPtr<IDXGIAdapter> adapter;
169
hr = dxgiDevice->GetAdapter(&adapter);
170
if (SUCCEEDED(hr)) {
171
hr = adapter->GetParent(IID_PPV_ARGS(&dxgiFactory));
172
}
173
}
174
175
// Create the swap chain. Modern features (flip model, tearing) require Windows 10 (DXGI 1.5) or newer.
176
swapChainDesc_.BufferCount = 1;
177
swapChainDesc_.BufferDesc.Width = width;
178
swapChainDesc_.BufferDesc.Height = height;
179
swapChainDesc_.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
180
swapChainDesc_.BufferDesc.RefreshRate.Numerator = 60;
181
swapChainDesc_.BufferDesc.RefreshRate.Denominator = 1;
182
swapChainDesc_.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
183
swapChainDesc_.OutputWindow = hWnd_;
184
swapChainDesc_.SampleDesc.Count = 1;
185
swapChainDesc_.SampleDesc.Quality = 0;
186
swapChainDesc_.Windowed = TRUE;
187
swapChainDesc_.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
188
189
#ifndef __LIBRETRO__ // their build server uses an old SDK
190
ComPtr<IDXGIFactory5> dxgiFactory5;
191
hr = dxgiFactory.As(&dxgiFactory5);
192
if (SUCCEEDED(hr)) {
193
swapChainDesc_.BufferCount = 2;
194
swapChainDesc_.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
195
196
BOOL allowTearing = FALSE;
197
hr = dxgiFactory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing));
198
if (SUCCEEDED(hr) && allowTearing) {
199
swapChainDesc_.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
200
}
201
}
202
#endif
203
204
hr = dxgiFactory->CreateSwapChain(device_.Get(), &swapChainDesc_, &swapChain_);
205
dxgiFactory->MakeWindowAssociation(hWnd_, DXGI_MWA_NO_ALT_ENTER);
206
207
draw_ = Draw::T3DCreateD3D11Context(device_, context_, device1_, context1_, swapChain_, featureLevel_, hWnd_, adapterNames, g_Config.iInflightFrames);
208
SetGPUBackend(GPUBackend::DIRECT3D11, chosenAdapterName);
209
bool success = draw_->CreatePresets(); // If we can run D3D11, there's a compiler installed. I think.
210
_assert_msg_(success, "Failed to compile preset shaders");
211
212
GotBackbuffer();
213
return true;
214
}
215
216
void D3D11Context::LostBackbuffer() {
217
draw_->HandleEvent(Draw::Event::LOST_BACKBUFFER, width, height, nullptr);
218
bbRenderTargetTex_.Reset();
219
bbRenderTargetView_.Reset();
220
}
221
222
void D3D11Context::GotBackbuffer() {
223
// Create a render target view
224
HRESULT hr = swapChain_->GetBuffer(0, IID_PPV_ARGS(&bbRenderTargetTex_));
225
if (FAILED(hr))
226
return;
227
228
D3D11_TEXTURE2D_DESC bbDesc{};
229
bbRenderTargetTex_->GetDesc(&bbDesc);
230
width = bbDesc.Width;
231
height = bbDesc.Height;
232
233
hr = device_->CreateRenderTargetView(bbRenderTargetTex_.Get(), nullptr, &bbRenderTargetView_);
234
if (FAILED(hr))
235
return;
236
draw_->HandleEvent(Draw::Event::GOT_BACKBUFFER, width, height, bbRenderTargetView_.Get(), bbRenderTargetTex_.Get());
237
}
238
239
void D3D11Context::Resize() {
240
LostBackbuffer();
241
int width;
242
int height;
243
W32Util::GetWindowRes(hWnd_, &width, &height);
244
swapChain_->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, swapChainDesc_.Flags);
245
GotBackbuffer();
246
}
247
248
void D3D11Context::Shutdown() {
249
LostBackbuffer();
250
251
delete draw_;
252
draw_ = nullptr;
253
254
context_->ClearState();
255
context_->Flush();
256
#ifdef _DEBUG
257
if (d3dInfoQueue_) {
258
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false);
259
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false);
260
d3dInfoQueue_->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, false);
261
}
262
if (d3dDebug_) {
263
d3dDebug_->ReportLiveDeviceObjects(D3D11_RLDO_FLAGS(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL));
264
}
265
#endif
266
267
#ifdef _DEBUG
268
d3dDebug_ = nullptr;
269
d3dInfoQueue_ = nullptr;
270
#endif
271
272
// Important that we release before we unload the DLL, otherwise we may crash on shutdown.
273
bbRenderTargetTex_ = nullptr;
274
bbRenderTargetView_ = nullptr;
275
swapChain_ = nullptr;
276
context1_ = nullptr;
277
context_ = nullptr;
278
device1_ = nullptr;
279
device_ = nullptr;
280
hWnd_ = nullptr;
281
282
UnloadD3D11();
283
}
284
285