Debian Codegraph @

Source/Core/VideoCommon/ShaderCache.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/ShaderCache.h"
5
6 #include <utility>
7
8 #include <fmt/format.h>
9
10 #include "Common/Assert.h"
11 #include "Common/FileUtil.h"
12 #include "Common/MsgHandler.h"
13 #include "Core/ConfigManager.h"
14
15 #include "VideoCommon/AbstractGfx.h"
16 #include "VideoCommon/ConstantManager.h"
17 #include "VideoCommon/DriverDetails.h"
18 #include "VideoCommon/FramebufferManager.h"
19 #include "VideoCommon/FramebufferShaderGen.h"
20 #include "VideoCommon/PipelineUtils.h"
21 #include "VideoCommon/Present.h"
22 #include "VideoCommon/Statistics.h"
23 #include "VideoCommon/VertexLoaderManager.h"
24 #include "VideoCommon/VertexManagerBase.h"
25 #include "VideoCommon/VideoCommon.h"
26 #include "VideoCommon/VideoConfig.h"
27
28 #include <imgui.h>
29
30 std::unique_ptr<VideoCommon::ShaderCache> g_shader_cache;
31
32 namespace VideoCommon
33 {
34 ShaderCache::ShaderCache() : m_api_type{APIType::Nothing}
35 {
36 }
37
38 ShaderCache::~ShaderCache()
39 {
40 ClearCaches();
41 }
42
43 bool ShaderCache::Initialize()
44 {
45 m_api_type = g_backend_info.api_type;
46 m_host_config.bits = ShaderHostConfig::GetCurrent().bits;
47
48 if (!CompileSharedPipelines())
49 return false;
50
51 m_async_shader_compiler = g_gfx->CreateAsyncShaderCompiler();
52 m_frame_end_handler = GetVideoEvents().after_frame_event.Register(
53 [this](Core::System&) { RetrieveAsyncShaders(); });
54 return true;
55 }
56
57 void ShaderCache::InitializeShaderCache()
58 {
59 m_async_shader_compiler->ResizeWorkerThreads(g_ActiveConfig.GetShaderPrecompilerThreads());
60
61 // Load shader and UID caches.
62 if (g_ActiveConfig.bShaderCache && m_api_type != APIType::Nothing)
63 {
64 LoadCaches();
65 LoadPipelineUIDCache();
66 }
67
68 // Queue ubershader precompiling if required.
69 if (g_ActiveConfig.UsingUberShaders())
70 QueueUberShaderPipelines();
71
72 // Compile all known UIDs.
73 CompileMissingPipelines();
74 if (g_ActiveConfig.bWaitForShadersBeforeStarting)
75 WaitForAsyncCompiler();
76
77 // Switch to the runtime shader compiler thread configuration.
78 m_async_shader_compiler->ResizeWorkerThreads(g_ActiveConfig.GetShaderCompilerThreads());
79 }
80
81 void ShaderCache::Reload()
82 {
83 WaitForAsyncCompiler();
84 ClosePipelineUIDCache();
85 ClearCaches();
86
87 if (!CompileSharedPipelines())
88 PanicAlertFmt("Failed to compile shared pipelines after reload.");
89
90 if (g_ActiveConfig.bShaderCache)
91 LoadCaches();
92
93 // Switch to the precompiling shader configuration while we rebuild.
94 m_async_shader_compiler->ResizeWorkerThreads(g_ActiveConfig.GetShaderPrecompilerThreads());
95
96 // We don't need to explicitly recompile the individual ubershaders here, as the pipelines
97 // UIDs are still be in the map. Therefore, when these are rebuilt, the shaders will also
98 // be recompiled.
99 CompileMissingPipelines();
100 if (g_ActiveConfig.bWaitForShadersBeforeStarting)
101 WaitForAsyncCompiler();
102 m_async_shader_compiler->ResizeWorkerThreads(g_ActiveConfig.GetShaderCompilerThreads());
103 }
104
105 void ShaderCache::RetrieveAsyncShaders()
106 {
107 m_async_shader_compiler->RetrieveWorkItems();
108 }
109
110 void ShaderCache::Shutdown()
111 {
112 // This may leave shaders uncommitted to the cache, but it's better than blocking shutdown
113 // until everything has finished compiling.
114 if (m_async_shader_compiler)
115 {
116 m_async_shader_compiler->StopWorkerThreads();
117 m_async_shader_compiler->ClearAllWork();
118 }
119
120 ClosePipelineUIDCache();
121 }
122
123 const AbstractPipeline* ShaderCache::GetPipelineForUid(const GXPipelineUid& uid)
124 {
125 auto it = m_gx_pipeline_cache.find(uid);
126 if (it != m_gx_pipeline_cache.end() && !it->second.second)
127 return it->second.first.get();
128
129 const bool exists_in_cache = it != m_gx_pipeline_cache.end();
130 std::unique_ptr<AbstractPipeline> pipeline;
131 std::optional<AbstractPipelineConfig> pipeline_config = GetGXPipelineConfig(uid);
132 if (pipeline_config)
133 pipeline = g_gfx->CreatePipeline(*pipeline_config);
134 if (g_ActiveConfig.bShaderCache && !exists_in_cache)
135 AppendGXPipelineUID(uid);
136 return InsertGXPipeline(uid, std::move(pipeline));
137 }
138
139 std::optional<const AbstractPipeline*> ShaderCache::GetPipelineForUidAsync(const GXPipelineUid& uid)
140 {
141 auto it = m_gx_pipeline_cache.find(uid);
142 if (it != m_gx_pipeline_cache.end())
143 {
144 // .second is the pending flag, i.e. compiling in the background.
145 if (!it->second.second)
146 return it->second.first.get();
147 else
148 return {};
149 }
150
151 AppendGXPipelineUID(uid);
152 QueuePipelineCompile(uid, COMPILE_PRIORITY_ONDEMAND_PIPELINE);
153 return {};
154 }
155
156 const AbstractPipeline* ShaderCache::GetUberPipelineForUid(const GXUberPipelineUid& uid)
157 {
158 auto it = m_gx_uber_pipeline_cache.find(uid);
159 if (it != m_gx_uber_pipeline_cache.end() && !it->second.second)
160 return it->second.first.get();
161
162 std::unique_ptr<AbstractPipeline> pipeline;
163 std::optional<AbstractPipelineConfig> pipeline_config = GetGXPipelineConfig(uid);
164 if (pipeline_config)
165 pipeline = g_gfx->CreatePipeline(*pipeline_config);
166 return InsertGXUberPipeline(uid, std::move(pipeline));
167 }
168
169 void ShaderCache::WaitForAsyncCompiler()
170 {
171 bool running = true;
172
173 constexpr auto update_ui_progress = [](size_t completed, size_t total) {
174 const float center_x = ImGui::GetIO().DisplaySize.x * 0.5f;
175 const float center_y = ImGui::GetIO().DisplaySize.y * 0.5f;
176 const float scale = ImGui::GetIO().DisplayFramebufferScale.x;
177
178 ImGui::SetNextWindowSize(ImVec2(400.0f * scale, 50.0f * scale), ImGuiCond_Always);
179 ImGui::SetNextWindowPos(ImVec2(center_x, center_y), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
180 if (ImGui::Begin(Common::GetStringT("Compiling Shaders").c_str(), nullptr,
181 ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs |
182 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
183 ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoNav |
184 ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing))
185 {
186 ImGui::Text("Compiling shaders: %zu/%zu", completed, total);
187 ImGui::ProgressBar(static_cast<float>(completed) /
188 static_cast<float>(std::max(total, static_cast<size_t>(1))),
189 ImVec2(-1.0f, 0.0f), "");
190 }
191 ImGui::End();
192
193 g_presenter->Present();
194 };
195
196 while (running &&
197 (m_async_shader_compiler->HasPendingWork() || m_async_shader_compiler->HasCompletedWork()))
198 {
199 running = m_async_shader_compiler->WaitUntilCompletion(update_ui_progress);
200
201 m_async_shader_compiler->RetrieveWorkItems();
202 }
203
204 // An extra Present to clear the screen
205 g_presenter->Present();
206 }
207
208 template <typename SerializedUidType, typename UidType>
209 static void SerializePipelineUid(const UidType& uid, SerializedUidType& serialized_uid)
210 {
211 // Convert to disk format. Ensure all padding bytes are zero.
212 std::memset(reinterpret_cast<u8*>(&serialized_uid), 0, sizeof(serialized_uid));
213 serialized_uid.vertex_decl = uid.vertex_format->GetVertexDeclaration();
214 serialized_uid.vs_uid = uid.vs_uid;
215 serialized_uid.gs_uid = uid.gs_uid;
216 serialized_uid.ps_uid = uid.ps_uid;
217 serialized_uid.rasterization_state_bits = uid.rasterization_state.hex;
218 serialized_uid.depth_state_bits = uid.depth_state.hex;
219 serialized_uid.blending_state_bits = uid.blending_state.hex;
220 }
221
222 template <typename UidType, typename SerializedUidType>
223 static void UnserializePipelineUid(const SerializedUidType& uid, UidType& real_uid)
224 {
225 real_uid.vertex_format = VertexLoaderManager::GetOrCreateMatchingFormat(uid.vertex_decl);
226 real_uid.vs_uid = uid.vs_uid;
227 real_uid.gs_uid = uid.gs_uid;
228 real_uid.ps_uid = uid.ps_uid;
229 real_uid.rasterization_state.hex = uid.rasterization_state_bits;
230 real_uid.depth_state.hex = uid.depth_state_bits;
231 real_uid.blending_state.hex = uid.blending_state_bits;
232 }
233
234 template <ShaderStage stage, typename K, typename T>
235 void ShaderCache::LoadShaderCache(T& cache, APIType api_type, const char* type, bool include_gameid)
236 {
237 class CacheReader : public Common::LinearDiskCacheReader<K, u8>
238 {
239 public:
240 CacheReader(T& cache_) : cache(cache_) {}
241 void Read(const K& key, const u8* value, u32 value_size) override
242 {
243 auto shader = g_gfx->CreateShaderFromBinary(stage, value, value_size);
244 if (shader)
245 {
246 auto& entry = cache.shader_map[key];
247 entry.shader = std::move(shader);
248 entry.pending = false;
249
250 switch (stage)
251 {
252 case ShaderStage::Vertex:
253 INCSTAT(g_stats.num_vertex_shaders_created);
254 INCSTAT(g_stats.num_vertex_shaders_alive);
255 break;
256 case ShaderStage::Pixel:
257 INCSTAT(g_stats.num_pixel_shaders_created);
258 INCSTAT(g_stats.num_pixel_shaders_alive);
259 break;
260 default:
261 break;
262 }
263 }
264 }
265
266 private:
267 T& cache;
268 };
269
270 std::string filename = GetDiskShaderCacheFileName(api_type, type, include_gameid, true);
271 CacheReader reader(cache);
272 u32 count = cache.disk_cache.OpenAndRead(filename, reader);
273 INFO_LOG_FMT(VIDEO, "Loaded {} cached shaders from {}", count, filename);
274 }
275
276 template <typename T>
277 void ShaderCache::ClearShaderCache(T& cache)
278 {
279 cache.disk_cache.Sync();
280 cache.disk_cache.Close();
281 cache.shader_map.clear();
282 }
283
284 template <typename KeyType, typename DiskKeyType, typename T>
285 void ShaderCache::LoadPipelineCache(T& cache, Common::LinearDiskCache<DiskKeyType, u8>& disk_cache,
286 APIType api_type, const char* type, bool include_gameid)
287 {
288 class CacheReader : public Common::LinearDiskCacheReader<DiskKeyType, u8>
289 {
290 public:
291 CacheReader(ShaderCache* this_ptr_, T& cache_) : this_ptr(this_ptr_), cache(cache_) {}
292 bool AnyFailed() const { return failed; }
293 void Read(const DiskKeyType& key, const u8* value, u32 value_size) override
294 {
295 KeyType real_uid;
296 UnserializePipelineUid(key, real_uid);
297
298 // Skip those which are already compiled.
299 if (failed || cache.contains(real_uid))
300 return;
301
302 auto config = this_ptr->GetGXPipelineConfig(real_uid);
303 if (!config)
304 return;
305
306 auto pipeline = g_gfx->CreatePipeline(*config, value, value_size);
307 if (!pipeline)
308 {
309 // If any of the pipelines fail to create, consider the cache stale.
310 failed = true;
311 return;
312 }
313
314 auto& entry = cache[real_uid];
315 entry.first = std::move(pipeline);
316 entry.second = false;
317 }
318
319 private:
320 ShaderCache* this_ptr;
321 T& cache;
322 bool failed = false;
323 };
324
325 std::string filename = GetDiskShaderCacheFileName(api_type, type, include_gameid, true);
326 CacheReader reader(this, cache);
327 const u32 count = disk_cache.OpenAndRead(filename, reader);
328 INFO_LOG_FMT(VIDEO, "Loaded {} cached pipelines from {}", count, filename);
329
330 // If any of the pipelines in the cache failed to create, it's likely because of a change of
331 // driver version, or system configuration. In this case, when the UID cache picks up the pipeline
332 // later on, we'll write a duplicate entry to the pipeline cache. There's also no point in keeping
333 // the old cache data around, so discard and recreate the disk cache.
334 if (reader.AnyFailed())
335 {
336 WARN_LOG_FMT(VIDEO, "Failed to load one or more pipelines from cache '{}'. Discarding.",
337 filename);
338 disk_cache.Close();
339 File::Delete(filename);
340 disk_cache.OpenAndRead(filename, reader);
341 }
342 }
343
344 template <typename T, typename Y>
345 void ShaderCache::ClearPipelineCache(T& cache, Y& disk_cache)
346 {
347 disk_cache.Sync();
348 disk_cache.Close();
349
350 // Set the pending flag to false, and destroy the pipeline.
351 for (auto& it : cache)
352 {
353 it.second.first.reset();
354 it.second.second = false;
355 }
356 }
357
358 void ShaderCache::LoadCaches()
359 {
360 // Ubershader caches, if present.
361 if (g_backend_info.bSupportsShaderBinaries)
362 {
363 LoadShaderCache<ShaderStage::Vertex, UberShader::VertexShaderUid>(m_uber_vs_cache, m_api_type,
364 "uber-vs", false);
365 LoadShaderCache<ShaderStage::Pixel, UberShader::PixelShaderUid>(m_uber_ps_cache, m_api_type,
366 "uber-ps", false);
367
368 // We also share geometry shaders, as there aren't many variants.
369 if (m_host_config.backend_geometry_shaders)
370 LoadShaderCache<ShaderStage::Geometry, GeometryShaderUid>(m_gs_cache, m_api_type, "gs",
371 false);
372
373 // Specialized shaders, gameid-specific.
374 LoadShaderCache<ShaderStage::Vertex, VertexShaderUid>(m_vs_cache, m_api_type, "specialized-vs",
375 true);
376 LoadShaderCache<ShaderStage::Pixel, PixelShaderUid>(m_ps_cache, m_api_type, "specialized-ps",
377 true);
378 }
379
380 if (g_backend_info.bSupportsPipelineCacheData)
381 {
382 LoadPipelineCache<GXPipelineUid, SerializedGXPipelineUid>(
383 m_gx_pipeline_cache, m_gx_pipeline_disk_cache, m_api_type, "specialized-pipeline", true);
384 LoadPipelineCache<GXUberPipelineUid, SerializedGXUberPipelineUid>(
385 m_gx_uber_pipeline_cache, m_gx_uber_pipeline_disk_cache, m_api_type, "uber-pipeline",
386 false);
387 }
388 }
389
390 void ShaderCache::ClearCaches()
391 {
392 ClearPipelineCache(m_gx_pipeline_cache, m_gx_pipeline_disk_cache);
393 ClearShaderCache(m_vs_cache);
394 ClearShaderCache(m_gs_cache);
395 ClearShaderCache(m_ps_cache);
396
397 ClearPipelineCache(m_gx_uber_pipeline_cache, m_gx_uber_pipeline_disk_cache);
398 ClearShaderCache(m_uber_vs_cache);
399 ClearShaderCache(m_uber_ps_cache);
400
401 m_screen_quad_vertex_shader.reset();
402 m_texture_copy_vertex_shader.reset();
403 m_efb_copy_vertex_shader.reset();
404 m_texcoord_geometry_shader.reset();
405 m_color_geometry_shader.reset();
406 m_texture_copy_pixel_shader.reset();
407 m_color_pixel_shader.reset();
408
409 m_efb_copy_to_vram_pipelines.clear();
410 m_efb_copy_to_ram_pipelines.clear();
411 m_copy_rgba8_pipeline.reset();
412 m_rgba8_stereo_copy_pipeline.reset();
413 for (auto& pipeline : m_palette_conversion_pipelines)
414 pipeline.reset();
415 m_texture_reinterpret_pipelines.clear();
416 m_texture_decoding_shaders.clear();
417
418 SETSTAT(g_stats.num_pixel_shaders_created, 0);
419 SETSTAT(g_stats.num_pixel_shaders_alive, 0);
420 SETSTAT(g_stats.num_vertex_shaders_created, 0);
421 SETSTAT(g_stats.num_vertex_shaders_alive, 0);
422 }
423
424 void ShaderCache::CompileMissingPipelines()
425 {
426 // Queue all uids with a null pipeline for compilation.
427 for (auto& it : m_gx_pipeline_cache)
428 {
429 if (!it.second.first)
430 QueuePipelineCompile(it.first, COMPILE_PRIORITY_SHADERCACHE_PIPELINE);
431 }
432 for (auto& it : m_gx_uber_pipeline_cache)
433 {
434 if (!it.second.first)
435 QueueUberPipelineCompile(it.first, COMPILE_PRIORITY_UBERSHADER_PIPELINE);
436 }
437 }
438
439 std::unique_ptr<AbstractShader> ShaderCache::CompileVertexShader(const VertexShaderUid& uid) const
440 {
441 const ShaderCode source_code =
442 GenerateVertexShaderCode(m_api_type, m_host_config, uid.GetUidData(), {});
443 return g_gfx->CreateShaderFromSource(ShaderStage::Vertex, source_code.GetBuffer());
444 }
445
446 std::unique_ptr<AbstractShader>
447 ShaderCache::CompileVertexUberShader(const UberShader::VertexShaderUid& uid) const
448 {
449 const ShaderCode source_code =
450 UberShader::GenVertexShader(m_api_type, m_host_config, uid.GetUidData());
451 return g_gfx->CreateShaderFromSource(ShaderStage::Vertex, source_code.GetBuffer(), nullptr,
452 fmt::to_string(*uid.GetUidData()));
453 }
454
455 std::unique_ptr<AbstractShader> ShaderCache::CompilePixelShader(const PixelShaderUid& uid) const
456 {
457 const ShaderCode source_code =
458 GeneratePixelShaderCode(m_api_type, m_host_config, uid.GetUidData(), {});
459 return g_gfx->CreateShaderFromSource(ShaderStage::Pixel, source_code.GetBuffer());
460 }
461
462 std::unique_ptr<AbstractShader>
463 ShaderCache::CompilePixelUberShader(const UberShader::PixelShaderUid& uid) const
464 {
465 const ShaderCode source_code =
466 UberShader::GenPixelShader(m_api_type, m_host_config, uid.GetUidData());
467 return g_gfx->CreateShaderFromSource(ShaderStage::Pixel, source_code.GetBuffer(), nullptr,
468 fmt::to_string(*uid.GetUidData()));
469 }
470
471 const AbstractShader* ShaderCache::InsertVertexShader(const VertexShaderUid& uid,
472 std::unique_ptr<AbstractShader> shader)
473 {
474 auto& entry = m_vs_cache.shader_map[uid];
475 entry.pending = false;
476
477 if (shader && !entry.shader)
478 {
479 if (g_ActiveConfig.bShaderCache && g_backend_info.bSupportsShaderBinaries)
480 {
481 auto binary = shader->GetBinary();
482 if (!binary.empty())
483 m_vs_cache.disk_cache.Append(uid, binary.data(), static_cast<u32>(binary.size()));
484 }
485 INCSTAT(g_stats.num_vertex_shaders_created);
486 INCSTAT(g_stats.num_vertex_shaders_alive);
487 entry.shader = std::move(shader);
488 }
489
490 return entry.shader.get();
491 }
492
493 const AbstractShader* ShaderCache::InsertVertexUberShader(const UberShader::VertexShaderUid& uid,
494 std::unique_ptr<AbstractShader> shader)
495 {
496 auto& entry = m_uber_vs_cache.shader_map[uid];
497 entry.pending = false;
498
499 if (shader && !entry.shader)
500 {
501 if (g_ActiveConfig.bShaderCache && g_backend_info.bSupportsShaderBinaries)
502 {
503 auto binary = shader->GetBinary();
504 if (!binary.empty())
505 m_uber_vs_cache.disk_cache.Append(uid, binary.data(), static_cast<u32>(binary.size()));
506 }
507 INCSTAT(g_stats.num_vertex_shaders_created);
508 INCSTAT(g_stats.num_vertex_shaders_alive);
509 entry.shader = std::move(shader);
510 }
511
512 return entry.shader.get();
513 }
514
515 const AbstractShader* ShaderCache::InsertPixelShader(const PixelShaderUid& uid,
516 std::unique_ptr<AbstractShader> shader)
517 {
518 auto& entry = m_ps_cache.shader_map[uid];
519 entry.pending = false;
520
521 if (shader && !entry.shader)
522 {
523 if (g_ActiveConfig.bShaderCache && g_backend_info.bSupportsShaderBinaries)
524 {
525 auto binary = shader->GetBinary();
526 if (!binary.empty())
527 m_ps_cache.disk_cache.Append(uid, binary.data(), static_cast<u32>(binary.size()));
528 }
529 INCSTAT(g_stats.num_pixel_shaders_created);
530 INCSTAT(g_stats.num_pixel_shaders_alive);
531 entry.shader = std::move(shader);
532 }
533
534 return entry.shader.get();
535 }
536
537 const AbstractShader* ShaderCache::InsertPixelUberShader(const UberShader::PixelShaderUid& uid,
538 std::unique_ptr<AbstractShader> shader)
539 {
540 auto& entry = m_uber_ps_cache.shader_map[uid];
541 entry.pending = false;
542
543 if (shader && !entry.shader)
544 {
545 if (g_ActiveConfig.bShaderCache && g_backend_info.bSupportsShaderBinaries)
546 {
547 auto binary = shader->GetBinary();
548 if (!binary.empty())
549 m_uber_ps_cache.disk_cache.Append(uid, binary.data(), static_cast<u32>(binary.size()));
550 }
551 INCSTAT(g_stats.num_pixel_shaders_created);
552 INCSTAT(g_stats.num_pixel_shaders_alive);
553 entry.shader = std::move(shader);
554 }
555
556 return entry.shader.get();
557 }
558
559 const AbstractShader* ShaderCache::CreateGeometryShader(const GeometryShaderUid& uid)
560 {
561 const ShaderCode source_code =
562 GenerateGeometryShaderCode(m_api_type, m_host_config, uid.GetUidData());
563 std::unique_ptr<AbstractShader> shader =
564 g_gfx->CreateShaderFromSource(ShaderStage::Geometry, source_code.GetBuffer(), nullptr,
565 fmt::format("Geometry shader: {}", *uid.GetUidData()));
566
567 auto& entry = m_gs_cache.shader_map[uid];
568 entry.pending = false;
569
570 if (shader && !entry.shader)
571 {
572 if (g_ActiveConfig.bShaderCache && g_backend_info.bSupportsShaderBinaries)
573 {
574 auto binary = shader->GetBinary();
575 if (!binary.empty())
576 m_gs_cache.disk_cache.Append(uid, binary.data(), static_cast<u32>(binary.size()));
577 }
578 entry.shader = std::move(shader);
579 }
580
581 return entry.shader.get();
582 }
583
584 bool ShaderCache::NeedsGeometryShader(const GeometryShaderUid& uid) const
585 {
586 return m_host_config.backend_geometry_shaders && !uid.GetUidData()->IsPassthrough();
587 }
588
589 bool ShaderCache::UseGeometryShaderForEFBCopies() const
590 {
591 return m_host_config.backend_geometry_shaders && m_host_config.stereo;
592 }
593
594 AbstractPipelineConfig ShaderCache::GetGXPipelineConfig(
595 const NativeVertexFormat* vertex_format, const AbstractShader* vertex_shader,
596 const AbstractShader* geometry_shader, const AbstractShader* pixel_shader,
597 const RasterizationState& rasterization_state, const DepthState& depth_state,
598 const BlendingState& blending_state, AbstractPipelineUsage usage)
599 {
600 AbstractPipelineConfig config = {};
601 config.usage = usage;
602 config.vertex_format = vertex_format;
603 config.vertex_shader = vertex_shader;
604 config.geometry_shader = geometry_shader;
605 config.pixel_shader = pixel_shader;
606 config.rasterization_state = rasterization_state;
607 config.depth_state = depth_state;
608 config.blending_state = blending_state;
609 config.framebuffer_state = g_framebuffer_manager->GetEFBFramebufferState();
610 return config;
611 }
612
613 std::optional<AbstractPipelineConfig>
614 ShaderCache::GetGXPipelineConfig(const GXPipelineUid& config_in)
615 {
616 GXPipelineUid config = VideoCommon::ApplyDriverBugs(config_in);
617 const AbstractShader* vs;
618 auto vs_iter = m_vs_cache.shader_map.find(config.vs_uid);
619 if (vs_iter != m_vs_cache.shader_map.end() && !vs_iter->second.pending)
620 vs = vs_iter->second.shader.get();
621 else
622 vs = InsertVertexShader(config.vs_uid, CompileVertexShader(config.vs_uid));
623
624 PixelShaderUid ps_uid = config.ps_uid;
625 ClearUnusedPixelShaderUidBits(m_api_type, m_host_config, &ps_uid);
626
627 const AbstractShader* ps;
628 auto ps_iter = m_ps_cache.shader_map.find(ps_uid);
629 if (ps_iter != m_ps_cache.shader_map.end() && !ps_iter->second.pending)
630 ps = ps_iter->second.shader.get();
631 else
632 ps = InsertPixelShader(ps_uid, CompilePixelShader(ps_uid));
633
634 if (!vs || !ps)
635 return {};
636
637 const AbstractShader* gs = nullptr;
638 if (NeedsGeometryShader(config.gs_uid))
639 {
640 auto gs_iter = m_gs_cache.shader_map.find(config.gs_uid);
641 if (gs_iter != m_gs_cache.shader_map.end() && !gs_iter->second.pending)
642 gs = gs_iter->second.shader.get();
643 else
644 gs = CreateGeometryShader(config.gs_uid);
645 if (!gs)
646 return {};
647 }
648
649 return GetGXPipelineConfig(config.vertex_format, vs, gs, ps, config.rasterization_state,
650 config.depth_state, config.blending_state, AbstractPipelineUsage::GX);
651 }
652
653 /// Edits the UID based on driver bugs and other special configurations
654 static GXUberPipelineUid ApplyDriverBugs(const GXUberPipelineUid& in)
655 {
656 GXUberPipelineUid out;
657 // TODO: static_assert(std::is_trivially_copyable_v<GXUberPipelineUid>);
658 // GXUberPipelineUid is not trivially copyable because RasterizationState and BlendingState aren't
659 // either, but we can pretend it is for now. This will be improved after PR #10848 is finished.
660 memcpy(static_cast<void*>(&out), static_cast<const void*>(&in), sizeof(out)); // Copy padding
661 if (g_backend_info.bSupportsDynamicVertexLoader)
662 out.vertex_format = nullptr;
663
664 // If framebuffer fetch is available, we can emulate logic ops in the fragment shader
665 // and don't need the below blend approximation
666 if (out.blending_state.logic_op_enable && !g_backend_info.bSupportsLogicOp &&
667 !g_backend_info.bSupportsFramebufferFetch)
668 {
669 if (!out.blending_state.LogicOpApproximationIsExact())
670 WARN_LOG_FMT(VIDEO,
671 "Approximating logic op with blending, this will produce incorrect rendering.");
672 out.blending_state.ApproximateLogicOpWithBlending();
673 }
674
675 if (g_backend_info.bSupportsFramebufferFetch)
676 {
677 // Always blend in shader
678 out.blending_state.hex = 0;
679 out.blending_state.color_update = in.blending_state.color_update.Value();
680 out.blending_state.alpha_update = in.blending_state.alpha_update.Value();
681 out.ps_uid.GetUidData()->no_dual_src = true;
682 }
683 else if (!g_backend_info.bSupportsDualSourceBlend ||
684 (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_DUAL_SOURCE_BLENDING) &&
685 !out.blending_state.RequiresDualSrc()))
686 {
687 out.blending_state.use_dual_src = false;
688 out.ps_uid.GetUidData()->no_dual_src = true;
689 }
690
691 if (g_ActiveConfig.UseVSForLinePointExpand())
692 {
693 // All primitives are expanded to triangles in the vertex shader
694 PrimitiveType prim = g_backend_info.bSupportsPrimitiveRestart ? PrimitiveType::TriangleStrip :
695 PrimitiveType::Triangles;
696 out.rasterization_state.primitive = prim;
697 out.gs_uid.GetUidData()->primitive_type = static_cast<u32>(prim);
698 }
699
700 return out;
701 }
702
703 std::optional<AbstractPipelineConfig>
704 ShaderCache::GetGXPipelineConfig(const GXUberPipelineUid& config_in)
705 {
706 GXUberPipelineUid config = ApplyDriverBugs(config_in);
707 const AbstractShader* vs;
708 auto vs_iter = m_uber_vs_cache.shader_map.find(config.vs_uid);
709 if (vs_iter != m_uber_vs_cache.shader_map.end() && !vs_iter->second.pending)
710 vs = vs_iter->second.shader.get();
711 else
712 vs = InsertVertexUberShader(config.vs_uid, CompileVertexUberShader(config.vs_uid));
713
714 UberShader::PixelShaderUid ps_uid = config.ps_uid;
715 UberShader::ClearUnusedPixelShaderUidBits(m_api_type, m_host_config, &ps_uid);
716
717 const AbstractShader* ps;
718 auto ps_iter = m_uber_ps_cache.shader_map.find(ps_uid);
719 if (ps_iter != m_uber_ps_cache.shader_map.end() && !ps_iter->second.pending)
720 ps = ps_iter->second.shader.get();
721 else
722 ps = InsertPixelUberShader(ps_uid, CompilePixelUberShader(ps_uid));
723
724 if (!vs || !ps)
725 return {};
726
727 const AbstractShader* gs = nullptr;
728 if (NeedsGeometryShader(config.gs_uid))
729 {
730 auto gs_iter = m_gs_cache.shader_map.find(config.gs_uid);
731 if (gs_iter != m_gs_cache.shader_map.end() && !gs_iter->second.pending)
732 gs = gs_iter->second.shader.get();
733 else
734 gs = CreateGeometryShader(config.gs_uid);
735 if (!gs)
736 return {};
737 }
738
739 return GetGXPipelineConfig(config.vertex_format, vs, gs, ps, config.rasterization_state,
740 config.depth_state, config.blending_state,
741 AbstractPipelineUsage::GXUber);
742 }
743
744 const AbstractPipeline* ShaderCache::InsertGXPipeline(const GXPipelineUid& config,
745 std::unique_ptr<AbstractPipeline> pipeline)
746 {
747 auto& entry = m_gx_pipeline_cache[config];
748 entry.second = false;
749 if (!entry.first && pipeline)
750 {
751 entry.first = std::move(pipeline);
752
753 if (g_ActiveConfig.bShaderCache)
754 {
755 auto cache_data = entry.first->GetCacheData();
756 if (!cache_data.empty())
757 {
758 SerializedGXPipelineUid disk_uid;
759 SerializePipelineUid(config, disk_uid);
760 m_gx_pipeline_disk_cache.Append(disk_uid, cache_data.data(),
761 static_cast<u32>(cache_data.size()));
762 }
763 }
764 }
765
766 return entry.first.get();
767 }
768
769 const AbstractPipeline*
770 ShaderCache::InsertGXUberPipeline(const GXUberPipelineUid& config,
771 std::unique_ptr<AbstractPipeline> pipeline)
772 {
773 auto& entry = m_gx_uber_pipeline_cache[config];
774 entry.second = false;
775 if (!entry.first && pipeline)
776 {
777 entry.first = std::move(pipeline);
778
779 if (g_ActiveConfig.bShaderCache)
780 {
781 auto cache_data = entry.first->GetCacheData();
782 if (!cache_data.empty())
783 {
784 SerializedGXUberPipelineUid disk_uid;
785 SerializePipelineUid(config, disk_uid);
786 m_gx_uber_pipeline_disk_cache.Append(disk_uid, cache_data.data(),
787 static_cast<u32>(cache_data.size()));
788 }
789 }
790 }
791
792 return entry.first.get();
793 }
794
795 void ShaderCache::LoadPipelineUIDCache()
796 {
797 constexpr u32 CACHE_FILE_MAGIC = 0x44495550; // PUID
798 constexpr size_t CACHE_HEADER_SIZE = sizeof(u32) + sizeof(u32);
799 std::string filename =
800 File::GetUserPath(D_CACHE_IDX) + SConfig::GetInstance().GetGameID() + ".uidcache";
801 if (m_gx_pipeline_uid_cache_file.Open(filename, "rb+"))
802 {
803 // If an existing case exists, validate the version before reading entries.
804 u32 existing_magic;
805 u32 existing_version;
806 bool uid_file_valid = false;
807 if (m_gx_pipeline_uid_cache_file.ReadBytes(&existing_magic, sizeof(existing_magic)) &&
808 m_gx_pipeline_uid_cache_file.ReadBytes(&existing_version, sizeof(existing_version)) &&
809 existing_magic == CACHE_FILE_MAGIC && existing_version == GX_PIPELINE_UID_VERSION)
810 {
811 // Ensure the expected size matches the actual size of the file. If it doesn't, it means
812 // the cache file may be corrupted, and we should not proceed with loading potentially
813 // garbage or invalid UIDs.
814 const u64 file_size = m_gx_pipeline_uid_cache_file.GetSize();
815 const size_t uid_count =
816 static_cast<size_t>(file_size - CACHE_HEADER_SIZE) / sizeof(SerializedGXPipelineUid);
817 const size_t expected_size = uid_count * sizeof(SerializedGXPipelineUid) + CACHE_HEADER_SIZE;
818 uid_file_valid = file_size == expected_size;
819 if (uid_file_valid)
820 {
821 for (size_t i = 0; i < uid_count; i++)
822 {
823 SerializedGXPipelineUid serialized_uid;
824 if (m_gx_pipeline_uid_cache_file.ReadBytes(&serialized_uid, sizeof(serialized_uid)))
825 {
826 // This just adds the pipeline to the map, it is compiled later.
827 AddSerializedGXPipelineUID(serialized_uid);
828 }
829 else
830 {
831 uid_file_valid = false;
832 break;
833 }
834 }
835 }
836
837 // We open the file for reading and writing, so we must seek to the end before writing.
838 if (uid_file_valid)
839 uid_file_valid = m_gx_pipeline_uid_cache_file.Seek(expected_size, File::SeekOrigin::Begin);
840 }
841
842 // If the file is invalid, close it. We re-open and truncate it below.
843 if (!uid_file_valid)
844 m_gx_pipeline_uid_cache_file.Close();
845 }
846
847 // If the file is not open, it means it was either corrupted or didn't exist.
848 if (!m_gx_pipeline_uid_cache_file.IsOpen())
849 {
850 if (m_gx_pipeline_uid_cache_file.Open(filename, "wb"))
851 {
852 // Write the version identifier.
853 m_gx_pipeline_uid_cache_file.WriteBytes(&CACHE_FILE_MAGIC, sizeof(GX_PIPELINE_UID_VERSION));
854 m_gx_pipeline_uid_cache_file.WriteBytes(&GX_PIPELINE_UID_VERSION,
855 sizeof(GX_PIPELINE_UID_VERSION));
856
857 // Write any current UIDs out to the file.
858 // This way, if we load a UID cache where the data was incomplete (e.g. Dolphin crashed),
859 // we don't lose the existing UIDs which were previously at the beginning.
860 for (const auto& it : m_gx_pipeline_cache)
861 AppendGXPipelineUID(it.first);
862 }
863 }
864
865 INFO_LOG_FMT(VIDEO, "Read {} pipeline UIDs from {}", m_gx_pipeline_cache.size(), filename);
866 }
867
868 void ShaderCache::ClosePipelineUIDCache()
869 {
870 // This is left as a method in case we need to append extra data to the file in the future.
871 m_gx_pipeline_uid_cache_file.Close();
872 }
873
874 void ShaderCache::AddSerializedGXPipelineUID(const SerializedGXPipelineUid& uid)
875 {
876 GXPipelineUid real_uid;
877 UnserializePipelineUid(uid, real_uid);
878
879 auto iter = m_gx_pipeline_cache.find(real_uid);
880 if (iter != m_gx_pipeline_cache.end())
881 return;
882
883 // Flag it as empty with a null pipeline object, for later compilation.
884 auto& entry = m_gx_pipeline_cache[real_uid];
885 entry.second = false;
886 }
887
888 void ShaderCache::AppendGXPipelineUID(const GXPipelineUid& config)
889 {
890 if (!m_gx_pipeline_uid_cache_file.IsOpen())
891 return;
892
893 SerializedGXPipelineUid disk_uid;
894 SerializePipelineUid(config, disk_uid);
895 if (!m_gx_pipeline_uid_cache_file.WriteBytes(&disk_uid, sizeof(disk_uid)))
896 {
897 WARN_LOG_FMT(VIDEO, "Writing pipeline UID to cache failed, closing file.");
898 m_gx_pipeline_uid_cache_file.Close();
899 }
900 }
901
902 void ShaderCache::QueueVertexShaderCompile(const VertexShaderUid& uid, u32 priority)
903 {
904 class VertexShaderWorkItem final : public AsyncShaderCompiler::WorkItem
905 {
906 public:
907 VertexShaderWorkItem(ShaderCache* shader_cache_, const VertexShaderUid& uid_)
908 : shader_cache(shader_cache_), uid(uid_)
909 {
910 }
911
912 bool Compile() override
913 {
914 shader = shader_cache->CompileVertexShader(uid);
915 return true;
916 }
917
918 void Retrieve() override { shader_cache->InsertVertexShader(uid, std::move(shader)); }
919
920 private:
921 ShaderCache* shader_cache;
922 std::unique_ptr<AbstractShader> shader;
923 VertexShaderUid uid;
924 };
925
926 m_vs_cache.shader_map[uid].pending = true;
927 auto wi = m_async_shader_compiler->CreateWorkItem<VertexShaderWorkItem>(this, uid);
928 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
929 }
930
931 void ShaderCache::QueueVertexUberShaderCompile(const UberShader::VertexShaderUid& uid, u32 priority)
932 {
933 class VertexUberShaderWorkItem final : public AsyncShaderCompiler::WorkItem
934 {
935 public:
936 VertexUberShaderWorkItem(ShaderCache* shader_cache_, const UberShader::VertexShaderUid& uid_)
937 : shader_cache(shader_cache_), uid(uid_)
938 {
939 }
940
941 bool Compile() override
942 {
943 shader = shader_cache->CompileVertexUberShader(uid);
944 return true;
945 }
946
947 void Retrieve() override { shader_cache->InsertVertexUberShader(uid, std::move(shader)); }
948
949 private:
950 ShaderCache* shader_cache;
951 std::unique_ptr<AbstractShader> shader;
952 UberShader::VertexShaderUid uid;
953 };
954
955 m_uber_vs_cache.shader_map[uid].pending = true;
956 auto wi = m_async_shader_compiler->CreateWorkItem<VertexUberShaderWorkItem>(this, uid);
957 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
958 }
959
960 void ShaderCache::QueuePixelShaderCompile(const PixelShaderUid& uid, u32 priority)
961 {
962 class PixelShaderWorkItem final : public AsyncShaderCompiler::WorkItem
963 {
964 public:
965 PixelShaderWorkItem(ShaderCache* shader_cache_, const PixelShaderUid& uid_)
966 : shader_cache(shader_cache_), uid(uid_)
967 {
968 }
969
970 bool Compile() override
971 {
972 shader = shader_cache->CompilePixelShader(uid);
973 return true;
974 }
975
976 void Retrieve() override { shader_cache->InsertPixelShader(uid, std::move(shader)); }
977
978 private:
979 ShaderCache* shader_cache;
980 std::unique_ptr<AbstractShader> shader;
981 PixelShaderUid uid;
982 };
983
984 m_ps_cache.shader_map[uid].pending = true;
985 auto wi = m_async_shader_compiler->CreateWorkItem<PixelShaderWorkItem>(this, uid);
986 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
987 }
988
989 void ShaderCache::QueuePixelUberShaderCompile(const UberShader::PixelShaderUid& uid, u32 priority)
990 {
991 class PixelUberShaderWorkItem final : public AsyncShaderCompiler::WorkItem
992 {
993 public:
994 PixelUberShaderWorkItem(ShaderCache* shader_cache_, const UberShader::PixelShaderUid& uid_)
995 : shader_cache(shader_cache_), uid(uid_)
996 {
997 }
998
999 bool Compile() override
1000 {
1001 shader = shader_cache->CompilePixelUberShader(uid);
1002 return true;
1003 }
1004
1005 void Retrieve() override { shader_cache->InsertPixelUberShader(uid, std::move(shader)); }
1006
1007 private:
1008 ShaderCache* shader_cache;
1009 std::unique_ptr<AbstractShader> shader;
1010 UberShader::PixelShaderUid uid;
1011 };
1012
1013 m_uber_ps_cache.shader_map[uid].pending = true;
1014 auto wi = m_async_shader_compiler->CreateWorkItem<PixelUberShaderWorkItem>(this, uid);
1015 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
1016 }
1017
1018 void ShaderCache::QueuePipelineCompile(const GXPipelineUid& uid, u32 priority)
1019 {
1020 class PipelineWorkItem final : public AsyncShaderCompiler::WorkItem
1021 {
1022 public:
1023 PipelineWorkItem(ShaderCache* shader_cache_, GXPipelineUid uid_, u32 priority_)
1024 : shader_cache(shader_cache_), uid(std::move(uid_)), priority(priority_)
1025 {
1026 // Check if all the stages required for this pipeline have been compiled.
1027 // If not, this work item becomes a no-op, and re-queues the pipeline for the next frame.
1028 if (SetStagesReady())
1029 config = shader_cache->GetGXPipelineConfig(uid);
1030 }
1031
1032 bool SetStagesReady()
1033 {
1034 stages_ready = true;
1035
1036 GXPipelineUid actual_uid = ApplyDriverBugs(uid);
1037
1038 auto vs_it = shader_cache->m_vs_cache.shader_map.find(actual_uid.vs_uid);
1039 stages_ready &= vs_it != shader_cache->m_vs_cache.shader_map.end() && !vs_it->second.pending;
1040 if (vs_it == shader_cache->m_vs_cache.shader_map.end())
1041 shader_cache->QueueVertexShaderCompile(actual_uid.vs_uid, priority);
1042
1043 PixelShaderUid ps_uid = actual_uid.ps_uid;
1044 ClearUnusedPixelShaderUidBits(shader_cache->m_api_type, shader_cache->m_host_config, &ps_uid);
1045
1046 auto ps_it = shader_cache->m_ps_cache.shader_map.find(ps_uid);
1047 stages_ready &= ps_it != shader_cache->m_ps_cache.shader_map.end() && !ps_it->second.pending;
1048 if (ps_it == shader_cache->m_ps_cache.shader_map.end())
1049 shader_cache->QueuePixelShaderCompile(ps_uid, priority);
1050
1051 return stages_ready;
1052 }
1053
1054 bool Compile() override
1055 {
1056 if (config)
1057 pipeline = g_gfx->CreatePipeline(*config);
1058 return true;
1059 }
1060
1061 void Retrieve() override
1062 {
1063 if (stages_ready)
1064 {
1065 shader_cache->InsertGXPipeline(uid, std::move(pipeline));
1066 }
1067 else
1068 {
1069 // Re-queue for next frame.
1070 auto wi = shader_cache->m_async_shader_compiler->CreateWorkItem<PipelineWorkItem>(
1071 shader_cache, uid, priority);
1072 shader_cache->m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
1073 }
1074 }
1075
1076 private:
1077 ShaderCache* shader_cache;
1078 std::unique_ptr<AbstractPipeline> pipeline;
1079 GXPipelineUid uid;
1080 u32 priority;
1081 std::optional<AbstractPipelineConfig> config;
1082 bool stages_ready;
1083 };
1084
1085 auto wi = m_async_shader_compiler->CreateWorkItem<PipelineWorkItem>(this, uid, priority);
1086 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
1087 m_gx_pipeline_cache[uid].second = true;
1088 }
1089
1090 void ShaderCache::QueueUberPipelineCompile(const GXUberPipelineUid& uid, u32 priority)
1091 {
1092 class UberPipelineWorkItem final : public AsyncShaderCompiler::WorkItem
1093 {
1094 public:
1095 UberPipelineWorkItem(ShaderCache* shader_cache_, GXUberPipelineUid uid_, u32 priority_)
1096 : shader_cache(shader_cache_), uid(std::move(uid_)), priority(priority_)
1097 {
1098 // Check if all the stages required for this UberPipeline have been compiled.
1099 // If not, this work item becomes a no-op, and re-queues the UberPipeline for the next frame.
1100 if (SetStagesReady())
1101 config = shader_cache->GetGXPipelineConfig(uid);
1102 }
1103
1104 bool SetStagesReady()
1105 {
1106 stages_ready = true;
1107
1108 GXUberPipelineUid actual_uid = ApplyDriverBugs(uid);
1109
1110 auto vs_it = shader_cache->m_uber_vs_cache.shader_map.find(actual_uid.vs_uid);
1111 stages_ready &=
1112 vs_it != shader_cache->m_uber_vs_cache.shader_map.end() && !vs_it->second.pending;
1113 if (vs_it == shader_cache->m_uber_vs_cache.shader_map.end())
1114 shader_cache->QueueVertexUberShaderCompile(actual_uid.vs_uid, priority);
1115
1116 UberShader::PixelShaderUid ps_uid = actual_uid.ps_uid;
1117 UberShader::ClearUnusedPixelShaderUidBits(shader_cache->m_api_type,
1118 shader_cache->m_host_config, &ps_uid);
1119
1120 auto ps_it = shader_cache->m_uber_ps_cache.shader_map.find(ps_uid);
1121 stages_ready &=
1122 ps_it != shader_cache->m_uber_ps_cache.shader_map.end() && !ps_it->second.pending;
1123 if (ps_it == shader_cache->m_uber_ps_cache.shader_map.end())
1124 shader_cache->QueuePixelUberShaderCompile(ps_uid, priority);
1125
1126 return stages_ready;
1127 }
1128
1129 bool Compile() override
1130 {
1131 if (config)
1132 UberPipeline = g_gfx->CreatePipeline(*config);
1133 return true;
1134 }
1135
1136 void Retrieve() override
1137 {
1138 if (stages_ready)
1139 {
1140 shader_cache->InsertGXUberPipeline(uid, std::move(UberPipeline));
1141 }
1142 else
1143 {
1144 // Re-queue for next frame.
1145 auto wi = shader_cache->m_async_shader_compiler->CreateWorkItem<UberPipelineWorkItem>(
1146 shader_cache, uid, priority);
1147 shader_cache->m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
1148 }
1149 }
1150
1151 private:
1152 ShaderCache* shader_cache;
1153 std::unique_ptr<AbstractPipeline> UberPipeline;
1154 GXUberPipelineUid uid;
1155 u32 priority;
1156 std::optional<AbstractPipelineConfig> config;
1157 bool stages_ready;
1158 };
1159
1160 auto wi = m_async_shader_compiler->CreateWorkItem<UberPipelineWorkItem>(this, uid, priority);
1161 m_async_shader_compiler->QueueWorkItem(std::move(wi), priority);
1162 m_gx_uber_pipeline_cache[uid].second = true;
1163 }
1164
1165 void ShaderCache::QueueUberShaderPipelines()
1166 {
1167 // Create a dummy vertex format with no attributes.
1168 // All attributes will be enabled in GetUberVertexFormat.
1169 PortableVertexDeclaration dummy_vertex_decl = {};
1170 dummy_vertex_decl.position.components = 4;
1171 dummy_vertex_decl.position.type = ComponentFormat::Float;
1172 dummy_vertex_decl.position.enable = true;
1173 dummy_vertex_decl.stride = sizeof(float) * 4;
1174 NativeVertexFormat* dummy_vertex_format =
1175 VertexLoaderManager::GetUberVertexFormat(dummy_vertex_decl);
1176 auto QueueDummyPipeline =
1177 [&](const UberShader::VertexShaderUid& vs_uid, const GeometryShaderUid& gs_uid,
1178 const UberShader::PixelShaderUid& ps_uid, const BlendingState& blend) {
1179 GXUberPipelineUid config;
1180 config.vertex_format = dummy_vertex_format;
1181 config.vs_uid = vs_uid;
1182 config.gs_uid = gs_uid;
1183 config.ps_uid = ps_uid;
1184 config.rasterization_state = RenderState::GetCullBackFaceRasterizationState(
1185 static_cast<PrimitiveType>(gs_uid.GetUidData()->primitive_type));
1186 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1187 config.blending_state = blend;
1188 if (ps_uid.GetUidData()->uint_output)
1189 {
1190 // uint_output is only ever enabled when logic ops are enabled.
1191 config.blending_state.logic_op_enable = true;
1192 config.blending_state.logic_mode = LogicOp::And;
1193 }
1194
1195 auto iter = m_gx_uber_pipeline_cache.find(config);
1196 if (iter != m_gx_uber_pipeline_cache.end())
1197 return;
1198
1199 auto& entry = m_gx_uber_pipeline_cache[config];
1200 entry.second = false;
1201 };
1202
1203 // Populate the pipeline configs with empty entries, these will be compiled afterwards.
1204 UberShader::EnumerateVertexShaderUids([&](const UberShader::VertexShaderUid& vuid) {
1205 UberShader::EnumeratePixelShaderUids([&](const UberShader::PixelShaderUid& puid) {
1206 // UIDs must have compatible texgens, a mismatching combination will never be queried.
1207 if (vuid.GetUidData()->num_texgens != puid.GetUidData()->num_texgens)
1208 return;
1209
1210 UberShader::PixelShaderUid cleared_puid = puid;
1211 UberShader::ClearUnusedPixelShaderUidBits(m_api_type, m_host_config, &cleared_puid);
1212 EnumerateGeometryShaderUids([&](const GeometryShaderUid& guid) {
1213 if (guid.GetUidData()->numTexGens != vuid.GetUidData()->num_texgens ||
1214 (!guid.GetUidData()->IsPassthrough() && !m_host_config.backend_geometry_shaders))
1215 {
1216 return;
1217 }
1218 BlendingState blend = RenderState::GetNoBlendingBlendState();
1219 QueueDummyPipeline(vuid, guid, cleared_puid, blend);
1220 if (g_backend_info.bSupportsDynamicVertexLoader)
1221 {
1222 // Not all GPUs need all the pipeline state compiled into shaders, so they tend to key
1223 // compiled shaders based on some subset of the pipeline state.
1224 // Some test results:
1225 // (GPUs tested: AMD Radeon Pro 5600M, Nvidia GT 750M, Intel UHD 630,
1226 // Intel Iris Pro 5200, Apple M1)
1227 // MacOS Metal:
1228 // - AMD, Nvidia, Intel GPUs: Shaders are keyed on vertex layout and whether or not
1229 // dual source blend is enabled. That's it.
1230 // - Apple GPUs: Shaders are keyed on vertex layout and all blending settings. We use
1231 // framebuffer fetch here, so the only blending settings used by ubershaders are the
1232 // alpha_update and color_update ones. Also keyed on primitive type, but Metal
1233 // supports setting it to "unknown" and we do for ubershaders (but MoltenVK won't).
1234 // Windows Vulkan:
1235 // - AMD, Nvidia: Definitely keyed on dual source blend, but the others seem more random
1236 // Changing a setting on one shader will require a recompile, but changing the same
1237 // setting on another won't. Compiling a copy with alpha_update off, color_update off,
1238 // and one with DSB on seems to get pretty good coverage though.
1239 // Windows D3D12:
1240 // - AMD: Keyed on dual source blend and vertex layout
1241 // - Nvidia Kepler: No recompiles for changes to vertex layout or blend
1242 blend.alpha_update = false;
1243 QueueDummyPipeline(vuid, guid, cleared_puid, blend);
1244 blend.alpha_update = true;
1245 blend.color_update = false;
1246 QueueDummyPipeline(vuid, guid, cleared_puid, blend);
1247 blend.color_update = true;
1248 if (!cleared_puid.GetUidData()->no_dual_src && !cleared_puid.GetUidData()->uint_output)
1249 {
1250 blend.blend_enable = true;
1251 blend.use_dual_src = true;
1252 blend.src_factor = SrcBlendFactor::SrcAlpha;
1253 blend.dst_factor = DstBlendFactor::InvSrcAlpha;
1254 QueueDummyPipeline(vuid, guid, cleared_puid, blend);
1255 }
1256 }
1257 });
1258 });
1259 });
1260 }
1261
1262 const AbstractPipeline*
1263 ShaderCache::GetEFBCopyToVRAMPipeline(const TextureConversionShaderGen::TCShaderUid& uid)
1264 {
1265 auto iter = m_efb_copy_to_vram_pipelines.find(uid);
1266 if (iter != m_efb_copy_to_vram_pipelines.end())
1267 return iter->second.get();
1268
1269 auto shader_code = TextureConversionShaderGen::GeneratePixelShader(m_api_type, uid.GetUidData());
1270 auto shader = g_gfx->CreateShaderFromSource(
1271 ShaderStage::Pixel, shader_code.GetBuffer(), nullptr,
1272 fmt::format("EFB copy to VRAM pixel shader: {}", *uid.GetUidData()));
1273 if (!shader)
1274 {
1275 m_efb_copy_to_vram_pipelines.emplace(uid, nullptr);
1276 return nullptr;
1277 }
1278
1279 AbstractPipelineConfig config = {};
1280 config.vertex_format = nullptr;
1281 config.vertex_shader = m_efb_copy_vertex_shader.get();
1282 config.geometry_shader =
1283 UseGeometryShaderForEFBCopies() ? m_texcoord_geometry_shader.get() : nullptr;
1284 config.pixel_shader = shader.get();
1285 config.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
1286 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1287 config.blending_state = RenderState::GetNoBlendingBlendState();
1288 config.framebuffer_state = RenderState::GetRGBA8FramebufferState();
1289 config.usage = AbstractPipelineUsage::Utility;
1290 auto iiter = m_efb_copy_to_vram_pipelines.emplace(uid, g_gfx->CreatePipeline(config));
1291 return iiter.first->second.get();
1292 }
1293
1294 const AbstractPipeline* ShaderCache::GetEFBCopyToRAMPipeline(const EFBCopyParams& uid)
1295 {
1296 auto iter = m_efb_copy_to_ram_pipelines.find(uid);
1297 if (iter != m_efb_copy_to_ram_pipelines.end())
1298 return iter->second.get();
1299
1300 const std::string shader_code =
1301 TextureConversionShaderTiled::GenerateEncodingShader(uid, m_api_type);
1302 const auto shader =
1303 g_gfx->CreateShaderFromSource(ShaderStage::Pixel, shader_code, nullptr,
1304 fmt::format("EFB copy to RAM pixel shader: {}", uid));
1305 if (!shader)
1306 {
1307 m_efb_copy_to_ram_pipelines.emplace(uid, nullptr);
1308 return nullptr;
1309 }
1310
1311 AbstractPipelineConfig config = {};
1312 config.vertex_shader = m_screen_quad_vertex_shader.get();
1313 config.pixel_shader = shader.get();
1314 config.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
1315 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1316 config.blending_state = RenderState::GetNoBlendingBlendState();
1317 config.framebuffer_state = RenderState::GetColorFramebufferState(AbstractTextureFormat::BGRA8);
1318 config.usage = AbstractPipelineUsage::Utility;
1319 auto iiter = m_efb_copy_to_ram_pipelines.emplace(uid, g_gfx->CreatePipeline(config));
1320 return iiter.first->second.get();
1321 }
1322
1323 bool ShaderCache::CompileSharedPipelines()
1324 {
1325 m_screen_quad_vertex_shader = g_gfx->CreateShaderFromSource(
1326 ShaderStage::Vertex, FramebufferShaderGen::GenerateScreenQuadVertexShader(), nullptr,
1327 "Screen quad vertex shader");
1328 m_texture_copy_vertex_shader = g_gfx->CreateShaderFromSource(
1329 ShaderStage::Vertex, FramebufferShaderGen::GenerateTextureCopyVertexShader(), nullptr,
1330 "Texture copy vertex shader");
1331 m_efb_copy_vertex_shader = g_gfx->CreateShaderFromSource(
1332 ShaderStage::Vertex, TextureConversionShaderGen::GenerateVertexShader(m_api_type).GetBuffer(),
1333 nullptr, "EFB copy vertex shader");
1334 if (!m_screen_quad_vertex_shader || !m_texture_copy_vertex_shader || !m_efb_copy_vertex_shader)
1335 return false;
1336
1337 if (UseGeometryShaderForEFBCopies())
1338 {
1339 m_texcoord_geometry_shader = g_gfx->CreateShaderFromSource(
1340 ShaderStage::Geometry, FramebufferShaderGen::GeneratePassthroughGeometryShader(1, 0),
1341 nullptr, "Texcoord passthrough geometry shader");
1342 m_color_geometry_shader = g_gfx->CreateShaderFromSource(
1343 ShaderStage::Geometry, FramebufferShaderGen::GeneratePassthroughGeometryShader(0, 1),
1344 nullptr, "Color passthrough geometry shader");
1345 if (!m_texcoord_geometry_shader || !m_color_geometry_shader)
1346 return false;
1347 }
1348
1349 m_texture_copy_pixel_shader = g_gfx->CreateShaderFromSource(
1350 ShaderStage::Pixel, FramebufferShaderGen::GenerateTextureCopyPixelShader(), nullptr,
1351 "Texture copy pixel shader");
1352 m_color_pixel_shader = g_gfx->CreateShaderFromSource(
1353 ShaderStage::Pixel, FramebufferShaderGen::GenerateColorPixelShader(), nullptr,
1354 "Color pixel shader");
1355 if (!m_texture_copy_pixel_shader || !m_color_pixel_shader)
1356 return false;
1357
1358 AbstractPipelineConfig config;
1359 config.vertex_format = nullptr;
1360 config.vertex_shader = m_texture_copy_vertex_shader.get();
1361 config.geometry_shader = nullptr;
1362 config.pixel_shader = m_texture_copy_pixel_shader.get();
1363 config.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
1364 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1365 config.blending_state = RenderState::GetNoBlendingBlendState();
1366 config.framebuffer_state = RenderState::GetRGBA8FramebufferState();
1367 config.usage = AbstractPipelineUsage::Utility;
1368 m_copy_rgba8_pipeline = g_gfx->CreatePipeline(config);
1369 if (!m_copy_rgba8_pipeline)
1370 return false;
1371
1372 if (UseGeometryShaderForEFBCopies())
1373 {
1374 config.geometry_shader = m_texcoord_geometry_shader.get();
1375 m_rgba8_stereo_copy_pipeline = g_gfx->CreatePipeline(config);
1376 if (!m_rgba8_stereo_copy_pipeline)
1377 return false;
1378 }
1379
1380 if (m_host_config.backend_palette_conversion)
1381 {
1382 config.vertex_shader = m_screen_quad_vertex_shader.get();
1383 config.geometry_shader = nullptr;
1384
1385 for (size_t i = 0; i < NUM_PALETTE_CONVERSION_SHADERS; i++)
1386 {
1387 TLUTFormat format = static_cast<TLUTFormat>(i);
1388 auto shader = g_gfx->CreateShaderFromSource(
1389 ShaderStage::Pixel,
1390 TextureConversionShaderTiled::GeneratePaletteConversionShader(format, m_api_type),
1391 nullptr, fmt::format("Palette conversion pixel shader: {}", format));
1392 if (!shader)
1393 return false;
1394
1395 config.pixel_shader = shader.get();
1396 m_palette_conversion_pipelines[i] = g_gfx->CreatePipeline(config);
1397 if (!m_palette_conversion_pipelines[i])
1398 return false;
1399 }
1400 }
1401
1402 return true;
1403 }
1404
1405 const AbstractPipeline* ShaderCache::GetPaletteConversionPipeline(TLUTFormat format)
1406 {
1407 ASSERT(static_cast<size_t>(format) < NUM_PALETTE_CONVERSION_SHADERS);
1408 return m_palette_conversion_pipelines[static_cast<size_t>(format)].get();
1409 }
1410
1411 const AbstractPipeline* ShaderCache::GetTextureReinterpretPipeline(TextureFormat from_format,
1412 TextureFormat to_format)
1413 {
1414 const auto key = std::make_pair(from_format, to_format);
1415 const auto [iter, inserted] = m_texture_reinterpret_pipelines.emplace(key, nullptr);
1416
1417 if (!inserted)
1418 return iter->second.get();
1419
1420 std::string shader_source =
1421 FramebufferShaderGen::GenerateTextureReinterpretShader(from_format, to_format);
1422 if (shader_source.empty())
1423 return nullptr;
1424
1425 std::unique_ptr<AbstractShader> shader = g_gfx->CreateShaderFromSource(
1426 ShaderStage::Pixel, shader_source, nullptr,
1427 fmt::format("Texture reinterpret pixel shader: {} to {}", from_format, to_format));
1428 if (!shader)
1429 return nullptr;
1430
1431 AbstractPipelineConfig config;
1432 config.vertex_format = nullptr;
1433 config.vertex_shader = m_screen_quad_vertex_shader.get();
1434 config.geometry_shader = nullptr;
1435 config.pixel_shader = shader.get();
1436 config.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
1437 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1438 config.blending_state = RenderState::GetNoBlendingBlendState();
1439 config.framebuffer_state = RenderState::GetRGBA8FramebufferState();
1440 config.usage = AbstractPipelineUsage::Utility;
1441 iter->second = g_gfx->CreatePipeline(config);
1442 return iter->second.get();
1443 }
1444
1445 const AbstractShader*
1446 ShaderCache::GetTextureDecodingShader(TextureFormat format,
1447 std::optional<TLUTFormat> palette_format)
1448 {
1449 const auto key = std::make_pair(static_cast<u32>(format),
1450 static_cast<u32>(palette_format.value_or(TLUTFormat::IA8)));
1451 const auto [iter, inserted] = m_texture_decoding_shaders.emplace(key, nullptr);
1452 if (!inserted)
1453 return iter->second.get();
1454
1455 const std::string shader_source =
1456 TextureConversionShaderTiled::GenerateDecodingShader(format, palette_format, APIType::OpenGL);
1457 if (shader_source.empty())
1458 return nullptr;
1459
1460 const std::string name =
1461 palette_format.has_value() ?
1462 fmt::format("Texture decoding compute shader: {}, {}", format, *palette_format) :
1463 fmt::format("Texture decoding compute shader: {}", format);
1464
1465 std::unique_ptr<AbstractShader> shader =
1466 g_gfx->CreateShaderFromSource(ShaderStage::Compute, shader_source, nullptr, name);
1467 if (!shader)
1468 return nullptr;
1469
1470 iter->second = std::move(shader);
1471 return iter->second.get();
1472 }
1473 } // namespace VideoCommon