Debian Codegraph @

Source/Core/VideoCommon/VideoBackendBase.cpp

raw symbols SCIP
1 // Copyright 2011 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/VideoBackendBase.h"
5
6 #include <algorithm>
7 #include <cstring>
8 #include <memory>
9 #include <string>
10 #include <vector>
11
12 #include <fmt/format.h>
13
14 #include "Common/ChunkFile.h"
15 #include "Common/CommonTypes.h"
16 #include "Common/FileUtil.h"
17 #include "Common/Logging/Log.h"
18
19 #include "Core/Config/MainSettings.h"
20 #include "Core/ConfigManager.h"
21 #include "Core/Core.h"
22 #include "Core/CoreTiming.h"
23 #include "Core/DolphinAnalytics.h"
24 #include "Core/HW/SystemTimers.h"
25 #include "Core/HW/VideoInterface.h"
26 #include "Core/System.h"
27
28 // TODO: ugly
29 #ifdef _WIN32
30 #include "VideoBackends/D3D/VideoBackend.h"
31 #include "VideoBackends/D3D12/VideoBackend.h"
32 #endif
33 #include "VideoBackends/Null/VideoBackend.h"
34 #ifdef HAS_OPENGL
35 #include "VideoBackends/OGL/VideoBackend.h"
36 #include "VideoBackends/Software/VideoBackend.h"
37 #endif
38 #ifdef HAS_VULKAN
39 #include "VideoBackends/Vulkan/VideoBackend.h"
40 #endif
41 #ifdef __APPLE__
42 #include "VideoBackends/Metal/VideoBackend.h"
43 #endif
44
45 #include "VideoCommon/AbstractGfx.h"
46 #include "VideoCommon/AsyncRequests.h"
47 #include "VideoCommon/BPStructs.h"
48 #include "VideoCommon/BoundingBox.h"
49 #include "VideoCommon/CPMemory.h"
50 #include "VideoCommon/CommandProcessor.h"
51 #include "VideoCommon/EFBInterface.h"
52 #include "VideoCommon/Fifo.h"
53 #include "VideoCommon/FrameDumper.h"
54 #include "VideoCommon/FramebufferManager.h"
55 #include "VideoCommon/GeometryShaderManager.h"
56 #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModManager.h"
57 #include "VideoCommon/OnScreenDisplay.h"
58 #include "VideoCommon/PixelEngine.h"
59 #include "VideoCommon/PixelShaderManager.h"
60 #include "VideoCommon/Present.h"
61 #include "VideoCommon/Resources/CustomResourceManager.h"
62 #include "VideoCommon/TMEM.h"
63 #include "VideoCommon/TextureCacheBase.h"
64 #include "VideoCommon/VertexLoaderManager.h"
65 #include "VideoCommon/VertexManagerBase.h"
66 #include "VideoCommon/VertexShaderManager.h"
67 #include "VideoCommon/VideoConfig.h"
68 #include "VideoCommon/VideoState.h"
69 #include "VideoCommon/Widescreen.h"
70 #include "VideoCommon/XFStateManager.h"
71
72 VideoBackendBase* g_video_backend = nullptr;
73
74 #ifdef _WIN32
75 #include <windows.h>
76
77 // Nvidia drivers >= v302 will check if the application exports a global
78 // variable named NvOptimusEnablement to know if it should run the app in high
79 // performance graphics mode or using the IGP.
80 // AMD drivers >= 13.35 do the same, but for the variable
81 // named AmdPowerXpressRequestHighPerformance instead.
82 extern "C" {
83 __declspec(dllexport) DWORD NvOptimusEnablement = 1;
84 __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
85 }
86 #endif
87
88 std::string VideoBackendBase::BadShaderFilename(const char* shader_stage, int counter)
89 {
90 return fmt::format("{}bad_{}_{}_{}.txt", File::GetUserPath(D_DUMP_IDX), shader_stage,
91 g_video_backend->GetConfigName(), counter);
92 }
93
94 // Run from the CPU thread (from VideoInterface.cpp)
95 void VideoBackendBase::Video_OutputXFB(u32 xfb_addr, u32 fb_width, u32 fb_stride, u32 fb_height,
96 u64 ticks)
97 {
98 if (!m_initialized || !g_presenter)
99 return;
100
101 auto& system = Core::System::GetInstance();
102 auto& core_timing = system.GetCoreTiming();
103
104 if (!g_ActiveConfig.bImmediateXFB)
105 {
106 system.GetFifo().SyncGPU(Fifo::SyncGPUReason::Swap);
107
108 const TimePoint presentation_time = core_timing.GetTargetHostTime(ticks);
109 AsyncRequests::GetInstance()->PushEvent([=] {
110 g_presenter->ViSwap(xfb_addr, fb_width, fb_stride, fb_height, ticks, presentation_time);
111 });
112 }
113
114 // Inform the Presenter of the next estimated swap time.
115
116 auto& vi = system.GetVideoInterface();
117 const s64 refresh_rate_den = vi.GetTargetRefreshRateDenominator();
118 const s64 refresh_rate_num = vi.GetTargetRefreshRateNumerator();
119
120 const auto next_swap_estimated_ticks =
121 ticks + (system.GetSystemTimers().GetTicksPerSecond() * refresh_rate_den / refresh_rate_num);
122 const auto next_swap_estimated_time = core_timing.GetTargetHostTime(next_swap_estimated_ticks);
123
124 AsyncRequests::GetInstance()->PushEvent([=] {
125 g_presenter->SetNextSwapEstimatedTime(next_swap_estimated_ticks, next_swap_estimated_time);
126 });
127 }
128
129 u32 VideoBackendBase::Video_GetQueryResult(PerfQueryType type)
130 {
131 if (!g_perf_query->ShouldEmulate())
132 {
133 return 0;
134 }
135
136 auto& system = Core::System::GetInstance();
137 system.GetFifo().SyncGPU(Fifo::SyncGPUReason::PerfQuery);
138
139 if (!g_perf_query->IsFlushed())
140 {
141 AsyncRequests::GetInstance()->PushBlockingEvent([] { g_perf_query->FlushResults(); });
142 }
143
144 return g_perf_query->GetQueryResult(type);
145 }
146
147 u16 VideoBackendBase::Video_GetBoundingBox(int index)
148 {
149 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::ReadsBoundingBox);
150
151 if (!g_ActiveConfig.bBBoxEnable)
152 {
153 static bool warn_once = true;
154 if (warn_once)
155 {
156 ERROR_LOG_FMT(VIDEO,
157 "BBox shall be used but it is disabled. Please use a gameini to enable it "
158 "for this game.");
159 }
160 warn_once = false;
161 }
162 else if (!g_backend_info.bSupportsBBox)
163 {
164 static bool warn_once = true;
165 if (warn_once)
166 {
167 PanicAlertFmtT(
168 "This game requires bounding box emulation to run properly but your graphics "
169 "card or its drivers do not support it. As a result you will experience bugs or "
170 "freezes while running this game.");
171 }
172 warn_once = false;
173 }
174
175 auto& system = Core::System::GetInstance();
176 system.GetFifo().SyncGPU(Fifo::SyncGPUReason::BBox);
177
178 return AsyncRequests::GetInstance()->PushBlockingEvent(
179 [&] { return g_bounding_box->Get(index); });
180 }
181
182 static VideoBackendBase* GetDefaultVideoBackend()
183 {
184 const auto& backends = VideoBackendBase::GetAvailableBackends();
185 if (backends.empty())
186 return nullptr;
187 return backends.front().get();
188 }
189
190 std::string VideoBackendBase::GetDefaultBackendConfigName()
191 {
192 auto* default_backend = GetDefaultVideoBackend();
193 return default_backend ? default_backend->GetConfigName() : "";
194 }
195
196 std::string VideoBackendBase::GetDefaultBackendDisplayName()
197 {
198 auto* const default_backend = GetDefaultVideoBackend();
199 return default_backend ? default_backend->GetDisplayName() : "";
200 }
201
202 const std::vector<std::unique_ptr<VideoBackendBase>>& VideoBackendBase::GetAvailableBackends()
203 {
204 static auto s_available_backends = [] {
205 std::vector<std::unique_ptr<VideoBackendBase>> backends;
206
207 #ifdef _WIN32
208 backends.push_back(std::make_unique<DX11::VideoBackend>());
209 backends.push_back(std::make_unique<DX12::VideoBackend>());
210 #endif
211 #ifdef HAS_OPENGL
212 backends.push_back(std::make_unique<OGL::VideoBackend>());
213 #endif
214 #ifdef HAS_VULKAN
215 #ifdef __APPLE__
216 // Emplace the Vulkan backend at the beginning so it takes precedence over OpenGL.
217 // On macOS, we prefer Vulkan over OpenGL due to OpenGL support being deprecated by Apple.
218 backends.emplace(backends.begin(), std::make_unique<Vulkan::VideoBackend>());
219 #else
220 backends.push_back(std::make_unique<Vulkan::VideoBackend>());
221 #endif
222 #endif
223 #ifdef __APPLE__
224 backends.emplace(backends.begin(), std::make_unique<Metal::VideoBackend>());
225 #endif
226 #ifdef HAS_OPENGL
227 backends.push_back(std::make_unique<SW::VideoSoftware>());
228 #endif
229 backends.push_back(std::make_unique<Null::VideoBackend>());
230
231 if (!backends.empty())
232 g_video_backend = backends.front().get();
233
234 return backends;
235 }();
236 return s_available_backends;
237 }
238
239 void VideoBackendBase::ActivateBackend(const std::string& name)
240 {
241 // If empty, set it to the default backend (expected behavior)
242 if (name.empty())
243 g_video_backend = GetDefaultVideoBackend();
244
245 const auto& backends = GetAvailableBackends();
246 const auto iter = std::ranges::find(backends, name, &VideoBackendBase::GetConfigName);
247
248 if (iter == backends.end())
249 return;
250
251 g_video_backend = iter->get();
252 }
253
254 void VideoBackendBase::PopulateBackendInfo(const WindowSystemInfo& wsi)
255 {
256 // If the core has been initialized, the backend info will have been populated already. Doing it
257 // again would be unnecessary and could cause the UI thread to race with the GPU thread.
258 if (!Core::IsUninitialized(Core::System::GetInstance()))
259 return;
260
261 g_Config.Refresh();
262 // Reset backend_info so if the backend forgets to initialize something it doesn't end up using
263 // a value from the previously used renderer
264 g_backend_info = {};
265 ActivateBackend(Config::Get(Config::MAIN_GFX_BACKEND));
266 g_backend_info.DisplayName = g_video_backend->GetDisplayName();
267 g_video_backend->InitBackendInfo(wsi);
268 // We validate the config after initializing the backend info, as system-specific settings
269 // such as anti-aliasing, or the selected adapter may be invalid, and should be checked.
270 g_Config.VerifyValidity();
271 }
272
273 void VideoBackendBase::DoState(PointerWrap& p)
274 {
275 auto& system = Core::System::GetInstance();
276 if (!system.IsDualCoreMode())
277 {
278 VideoCommon_DoState(p);
279 return;
280 }
281
282 AsyncRequests::GetInstance()->PushBlockingEvent([&] { VideoCommon_DoState(p); });
283
284 // Let the GPU thread sleep after loading the state, so we're not spinning if paused after loading
285 // a state. The next GP burst will wake it up again.
286 system.GetFifo().GpuMaySleep();
287 }
288
289 bool VideoBackendBase::InitializeShared(std::unique_ptr<AbstractGfx> gfx,
290 std::unique_ptr<VertexManagerBase> vertex_manager,
291 std::unique_ptr<PerfQueryBase> perf_query,
292 std::unique_ptr<BoundingBox> bounding_box)
293 {
294 // All hardware backends use the default EFBInterface and TextureCacheBase.
295 // Only Null and Software backends override them
296
297 return InitializeShared(std::move(gfx), std::move(vertex_manager), std::move(perf_query),
298 std::move(bounding_box), std::make_unique<HardwareEFBInterface>(),
299 std::make_unique<TextureCacheBase>());
300 }
301
302 bool VideoBackendBase::InitializeShared(std::unique_ptr<AbstractGfx> gfx,
303 std::unique_ptr<VertexManagerBase> vertex_manager,
304 std::unique_ptr<PerfQueryBase> perf_query,
305 std::unique_ptr<BoundingBox> bounding_box,
306 std::unique_ptr<EFBInterfaceBase> efb_interface,
307 std::unique_ptr<TextureCacheBase> texture_cache)
308 {
309 memset(reinterpret_cast<u8*>(&g_main_cp_state), 0, sizeof(g_main_cp_state));
310 memset(reinterpret_cast<u8*>(&g_preprocess_cp_state), 0, sizeof(g_preprocess_cp_state));
311 s_tex_mem.fill(0);
312
313 // do not initialize again for the config window
314 m_initialized = true;
315
316 g_gfx = std::move(gfx);
317 g_vertex_manager = std::move(vertex_manager);
318 g_perf_query = std::move(perf_query);
319 g_bounding_box = std::move(bounding_box);
320
321 // Null and Software Backends supply their own derived EFBInterface and TextureCache
322 g_texture_cache = std::move(texture_cache);
323 g_efb_interface = std::move(efb_interface);
324
325 g_presenter = std::make_unique<VideoCommon::Presenter>();
326 g_frame_dumper = std::make_unique<FrameDumper>();
327 g_framebuffer_manager = std::make_unique<FramebufferManager>();
328 g_shader_cache = std::make_unique<VideoCommon::ShaderCache>();
329 g_graphics_mod_manager = std::make_unique<GraphicsModManager>();
330 g_widescreen = std::make_unique<WidescreenManager>();
331
332 if (!g_vertex_manager->Initialize() || !g_shader_cache->Initialize() ||
333 !g_perf_query->Initialize() || !g_presenter->Initialize() ||
334 !g_framebuffer_manager->Initialize(g_ActiveConfig.iEFBScale) ||
335 !g_texture_cache->Initialize() ||
336 (g_backend_info.bSupportsBBox && !g_bounding_box->Initialize()) ||
337 !g_graphics_mod_manager->Initialize())
338 {
339 PanicAlertFmtT("Failed to initialize renderer classes");
340 Shutdown();
341 return false;
342 }
343
344 auto& system = Core::System::GetInstance();
345 auto& command_processor = system.GetCommandProcessor();
346 command_processor.Init();
347 system.GetFifo().Init();
348 system.GetPixelEngine().Init();
349 BPInit();
350 VertexLoaderManager::Init();
351 system.GetVertexShaderManager().Init();
352 system.GetGeometryShaderManager().Init();
353 system.GetPixelShaderManager().Init();
354 system.GetXFStateManager().Init();
355 TMEM::Init();
356
357 g_Config.VerifyValidity();
358 UpdateActiveConfig();
359
360 if (g_Config.bDumpTextures)
361 {
362 OSD::AddMessage(fmt::format("Texture Dumping is enabled. This will reduce performance."),
363 OSD::Duration::NORMAL);
364 }
365
366 g_shader_cache->InitializeShaderCache();
367 system.GetCustomResourceManager().Initialize();
368
369 return true;
370 }
371
372 void VideoBackendBase::ShutdownShared()
373 {
374 auto& system = Core::System::GetInstance();
375 system.GetCustomResourceManager().Shutdown();
376
377 g_frame_dumper.reset();
378 g_presenter.reset();
379
380 if (g_shader_cache)
381 g_shader_cache->Shutdown();
382 if (g_texture_cache)
383 g_texture_cache->Shutdown();
384
385 g_bounding_box.reset();
386 g_perf_query.reset();
387 g_graphics_mod_manager.reset();
388 g_texture_cache.reset();
389 g_framebuffer_manager.reset();
390 g_shader_cache.reset();
391 g_vertex_manager.reset();
392 g_efb_interface.reset();
393 g_widescreen.reset();
394 g_gfx.reset();
395
396 m_initialized = false;
397
398 VertexLoaderManager::Clear();
399 system.GetFifo().Shutdown();
400 }