Debian Codegraph @

Source/Core/VideoBackends/OGL/ProgramShaderCache.cpp

raw symbols SCIP
1 // Copyright 2011 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoBackends/OGL/ProgramShaderCache.h"
5
6 #include <array>
7 #include <atomic>
8 #include <fstream>
9 #include <memory>
10 #include <string>
11
12 #include <fmt/format.h>
13
14 #include "Common/Align.h"
15 #include "Common/Assert.h"
16 #include "Common/CommonTypes.h"
17 #include "Common/FileUtil.h"
18 #include "Common/GL/GLContext.h"
19 #include "Common/GL/GLUtil.h"
20 #include "Common/Logging/Log.h"
21 #include "Common/MsgHandler.h"
22 #include "Common/Version.h"
23
24 #include "Core/ConfigManager.h"
25 #include "Core/System.h"
26
27 #include "VideoBackends/OGL/OGLConfig.h"
28 #include "VideoBackends/OGL/OGLGfx.h"
29 #include "VideoBackends/OGL/OGLShader.h"
30 #include "VideoBackends/OGL/OGLStreamBuffer.h"
31 #include "VideoBackends/OGL/OGLVertexManager.h"
32
33 #include "VideoCommon/GeometryShaderManager.h"
34 #include "VideoCommon/PixelShaderManager.h"
35 #include "VideoCommon/Statistics.h"
36 #include "VideoCommon/VertexShaderManager.h"
37 #include "VideoCommon/VideoBackendBase.h"
38 #include "VideoCommon/VideoConfig.h"
39
40 namespace OGL
41 {
42 u32 ProgramShaderCache::s_ubo_buffer_size;
43 s32 ProgramShaderCache::s_ubo_align = 1;
44 GLuint ProgramShaderCache::s_attributeless_VBO = 0;
45 GLuint ProgramShaderCache::s_attributeless_VAO = 0;
46 GLuint ProgramShaderCache::s_last_VAO = 0;
47
48 static std::unique_ptr<StreamBuffer> s_buffer;
49 static int num_failures = 0;
50
51 static GLuint CurrentProgram = 0;
52 ProgramShaderCache::PipelineProgramMap ProgramShaderCache::s_pipeline_programs;
53 std::mutex ProgramShaderCache::s_pipeline_program_lock;
54 static std::string s_glsl_header;
55 static std::atomic<u64> s_shader_counter{0};
56 static thread_local bool s_is_shared_context = false;
57
58 static std::string GetGLSLVersionString()
59 {
60 GlslVersion v = g_ogl_config.eSupportedGLSLVersion;
61 switch (v)
62 {
63 case GlslEs300:
64 return "#version 300 es";
65 case GlslEs310:
66 return "#version 310 es";
67 case GlslEs320:
68 return "#version 320 es";
69 case Glsl130:
70 return "#version 130";
71 case Glsl140:
72 return "#version 140";
73 case Glsl150:
74 return "#version 150";
75 case Glsl330:
76 return "#version 330";
77 case Glsl400:
78 return "#version 400";
79 case Glsl430:
80 return "#version 430";
81 case Glsl450:
82 return "#version 450";
83 default:
84 // Shouldn't ever hit this
85 return "#version ERROR";
86 }
87 }
88
89 void SHADER::SetProgramVariables()
90 {
91 if (g_backend_info.bSupportsBindingLayout)
92 return;
93
94 // To set uniform blocks/uniforms, the program must be active. We restore the
95 // current binding at the end of this method to maintain the invariant.
96 glUseProgram(glprogid);
97
98 // Bind UBO and texture samplers
99 GLint PSBlock_id = glGetUniformBlockIndex(glprogid, "PSBlock");
100 GLint VSBlock_id = glGetUniformBlockIndex(glprogid, "VSBlock");
101 GLint GSBlock_id = glGetUniformBlockIndex(glprogid, "GSBlock");
102 GLint UBERBlock_id = glGetUniformBlockIndex(glprogid, "UBERBlock");
103 if (PSBlock_id != -1)
104 glUniformBlockBinding(glprogid, PSBlock_id, 1);
105 if (VSBlock_id != -1)
106 glUniformBlockBinding(glprogid, VSBlock_id, 2);
107 if (GSBlock_id != -1)
108 glUniformBlockBinding(glprogid, GSBlock_id, 4);
109 if (UBERBlock_id != -1)
110 glUniformBlockBinding(glprogid, UBERBlock_id, 5);
111
112 // Bind Texture Samplers
113 for (int a = 0; a < 8; ++a)
114 {
115 // Still need to get sampler locations since we aren't binding them statically in the shaders
116 int loc = glGetUniformLocation(glprogid, fmt::format("samp[{}]", a).c_str());
117 if (loc < 0)
118 loc = glGetUniformLocation(glprogid, fmt::format("samp{}", a).c_str());
119 if (loc >= 0)
120 glUniform1i(loc, a);
121 }
122
123 // Restore previous program binding.
124 glUseProgram(CurrentProgram);
125 }
126
127 void SHADER::SetProgramBindings(bool is_compute)
128 {
129 if (g_ogl_config.bSupportsExplicitLayoutInShader)
130 {
131 return;
132 }
133 if (!is_compute)
134 {
135 if (g_backend_info.bSupportsDualSourceBlend)
136 {
137 // So we do support extended blending
138 // So we need to set a few more things here.
139 // Bind our out locations
140 glBindFragDataLocationIndexed(glprogid, 0, 0, "ocol0");
141 glBindFragDataLocationIndexed(glprogid, 0, 1, "ocol1");
142 }
143 // Need to set some attribute locations
144 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Position), "rawpos");
145
146 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::PositionMatrix), "posmtx");
147
148 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Color0), "rawcolor0");
149 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Color1), "rawcolor1");
150
151 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Normal), "rawnormal");
152 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Tangent), "rawtangent");
153 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::Binormal), "rawbinormal");
154 }
155
156 for (int i = 0; i < 8; i++)
157 {
158 // Per documentation: OpenGL copies the name string when glBindAttribLocation is called, so an
159 // application may free its copy of the name string immediately after the function returns.
160 glBindAttribLocation(glprogid, static_cast<GLuint>(ShaderAttrib::TexCoord0 + i),
161 fmt::format("rawtex{}", i).c_str());
162 }
163 }
164
165 void SHADER::Bind() const
166 {
167 if (CurrentProgram != glprogid)
168 {
169 INCSTAT(g_stats.this_frame.num_shader_changes);
170 glUseProgram(glprogid);
171 CurrentProgram = glprogid;
172 }
173 }
174
175 void SHADER::DestroyShaders()
176 {
177 if (vsid)
178 {
179 glDeleteShader(vsid);
180 vsid = 0;
181 }
182 if (gsid)
183 {
184 glDeleteShader(gsid);
185 gsid = 0;
186 }
187 if (psid)
188 {
189 glDeleteShader(psid);
190 psid = 0;
191 }
192 }
193
194 bool PipelineProgramKey::operator==(const PipelineProgramKey& rhs) const
195 {
196 return std::tie(vertex_shader_id, geometry_shader_id, pixel_shader_id) ==
197 std::tie(rhs.vertex_shader_id, rhs.geometry_shader_id, rhs.pixel_shader_id);
198 }
199
200 bool PipelineProgramKey::operator<(const PipelineProgramKey& rhs) const
201 {
202 return std::tie(vertex_shader_id, geometry_shader_id, pixel_shader_id) <
203 std::tie(rhs.vertex_shader_id, rhs.geometry_shader_id, rhs.pixel_shader_id);
204 }
205
206 std::size_t PipelineProgramKeyHash::operator()(const PipelineProgramKey& key) const
207 {
208 // We would really want std::hash_combine for this..
209 std::hash<u64> hasher;
210 return hasher(key.vertex_shader_id) + hasher(key.geometry_shader_id) +
211 hasher(key.pixel_shader_id);
212 }
213
214 StreamBuffer* ProgramShaderCache::GetUniformBuffer()
215 {
216 return s_buffer.get();
217 }
218
219 u32 ProgramShaderCache::GetUniformBufferAlignment()
220 {
221 return s_ubo_align;
222 }
223
224 void ProgramShaderCache::UploadConstants()
225 {
226 auto& system = Core::System::GetInstance();
227 auto& pixel_shader_manager = system.GetPixelShaderManager();
228 auto& vertex_shader_manager = system.GetVertexShaderManager();
229 auto& geometry_shader_manager = system.GetGeometryShaderManager();
230 if (pixel_shader_manager.dirty || vertex_shader_manager.dirty || geometry_shader_manager.dirty ||
231 pixel_shader_manager.custom_constants_dirty)
232 {
233 const u32 custom_constants_size = static_cast<u32>(
234 Common::AlignUp(pixel_shader_manager.custom_constants.size(), s_ubo_align));
235 auto buffer = s_buffer->Map(s_ubo_buffer_size + custom_constants_size, s_ubo_align);
236
237 memcpy(buffer.first, &pixel_shader_manager.constants, sizeof(PixelShaderConstants));
238
239 u64 size = Common::AlignUp(sizeof(PixelShaderConstants), s_ubo_align);
240
241 memcpy(buffer.first + size, &vertex_shader_manager.constants, sizeof(VertexShaderConstants));
242 size += Common::AlignUp(sizeof(VertexShaderConstants), s_ubo_align);
243
244 if (!pixel_shader_manager.custom_constants.empty())
245 {
246 memcpy(buffer.first + size, pixel_shader_manager.custom_constants.data(),
247 pixel_shader_manager.custom_constants.size());
248 size += custom_constants_size;
249 }
250
251 memcpy(buffer.first + size, &geometry_shader_manager.constants,
252 sizeof(GeometryShaderConstants));
253
254 s_buffer->Unmap(s_ubo_buffer_size + custom_constants_size);
255
256 glBindBufferRange(GL_UNIFORM_BUFFER, 1, s_buffer->m_buffer, buffer.second,
257 sizeof(PixelShaderConstants));
258 size = Common::AlignUp(sizeof(PixelShaderConstants), s_ubo_align);
259 glBindBufferRange(GL_UNIFORM_BUFFER, 2, s_buffer->m_buffer, buffer.second + size,
260 sizeof(VertexShaderConstants));
261 size += Common::AlignUp(sizeof(VertexShaderConstants), s_ubo_align);
262
263 if (!pixel_shader_manager.custom_constants.empty())
264 {
265 glBindBufferRange(GL_UNIFORM_BUFFER, 3, s_buffer->m_buffer, buffer.second + size,
266 pixel_shader_manager.custom_constants.size());
267 size += Common::AlignUp(pixel_shader_manager.custom_constants.size(), s_ubo_align);
268 }
269 glBindBufferRange(GL_UNIFORM_BUFFER, 4, s_buffer->m_buffer, buffer.second + size,
270 sizeof(GeometryShaderConstants));
271
272 pixel_shader_manager.dirty = false;
273 vertex_shader_manager.dirty = false;
274 geometry_shader_manager.dirty = false;
275 pixel_shader_manager.custom_constants_dirty = false;
276
277 ADDSTAT(g_stats.this_frame.bytes_uniform_streamed, s_ubo_buffer_size + custom_constants_size);
278 }
279 }
280
281 void ProgramShaderCache::UploadConstants(const void* data, u32 data_size)
282 {
283 // allocate and copy
284 const u32 alloc_size = Common::AlignUp(data_size, s_ubo_align);
285 auto buffer = s_buffer->Map(alloc_size, s_ubo_align);
286 std::memcpy(buffer.first, data, data_size);
287 s_buffer->Unmap(alloc_size);
288
289 // bind the same sub-buffer to all stages
290 for (u32 index = 1; index <= 4; index++)
291 glBindBufferRange(GL_UNIFORM_BUFFER, index, s_buffer->m_buffer, buffer.second, data_size);
292
293 ADDSTAT(g_stats.this_frame.bytes_uniform_streamed, data_size);
294 }
295
296 bool ProgramShaderCache::CompileComputeShader(SHADER& shader, std::string_view code)
297 {
298 // We need to enable GL_ARB_compute_shader for drivers that support the extension,
299 // but not GLSL 4.3. Mesa is one example.
300 std::string full_code;
301 if (g_backend_info.bSupportsComputeShaders && g_ogl_config.eSupportedGLSLVersion < Glsl430)
302 {
303 full_code = "#extension GL_ARB_compute_shader : enable\n";
304 }
305
306 full_code += code;
307 const GLuint shader_id = CompileSingleShader(GL_COMPUTE_SHADER, full_code);
308 if (!shader_id)
309 return false;
310
311 shader.glprogid = glCreateProgram();
312 glAttachShader(shader.glprogid, shader_id);
313 shader.SetProgramBindings(true);
314 glLinkProgram(shader.glprogid);
315
316 // original shaders aren't needed any more
317 glDeleteShader(shader_id);
318
319 if (!CheckProgramLinkResult(shader.glprogid, full_code, {}, {}))
320 {
321 shader.Destroy();
322 return false;
323 }
324
325 shader.SetProgramVariables();
326 return true;
327 }
328
329 GLuint ProgramShaderCache::CompileSingleShader(GLenum type, std::string_view code)
330 {
331 const GLuint result = glCreateShader(type);
332
333 constexpr GLsizei num_strings = 2;
334 const std::array<const char*, num_strings> src{
335 s_glsl_header.data(),
336 code.data(),
337 };
338 const std::array<GLint, num_strings> src_sizes{
339 static_cast<GLint>(s_glsl_header.size()),
340 static_cast<GLint>(code.size()),
341 };
342
343 glShaderSource(result, num_strings, src.data(), src_sizes.data());
344 glCompileShader(result);
345
346 if (!CheckShaderCompileResult(result, type, code))
347 {
348 // Don't try to use this shader
349 glDeleteShader(result);
350 return 0;
351 }
352
353 return result;
354 }
355
356 bool ProgramShaderCache::CheckShaderCompileResult(GLuint id, GLenum type, std::string_view code)
357 {
358 GLint compileStatus;
359 glGetShaderiv(id, GL_COMPILE_STATUS, &compileStatus);
360 GLsizei length = 0;
361 glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
362 if (compileStatus != GL_TRUE || length > 1)
363 {
364 std::string info_log;
365 info_log.resize(length);
366 glGetShaderInfoLog(id, length, &length, &info_log[0]);
367
368 const char* prefix = "";
369 switch (type)
370 {
371 case GL_VERTEX_SHADER:
372 prefix = "vs";
373 break;
374 case GL_GEOMETRY_SHADER:
375 prefix = "gs";
376 break;
377 case GL_FRAGMENT_SHADER:
378 prefix = "ps";
379 break;
380 case GL_COMPUTE_SHADER:
381 prefix = "cs";
382 break;
383 }
384
385 if (compileStatus != GL_TRUE)
386 {
387 ERROR_LOG_FMT(VIDEO, "{} failed compilation:\n{}", prefix, info_log);
388
389 std::string filename = VideoBackendBase::BadShaderFilename(prefix, num_failures++);
390 std::ofstream file;
391 File::OpenFStream(file, filename, std::ios_base::out);
392 file << s_glsl_header << code << info_log;
393 file << "\n";
394 file << "Dolphin Version: " + Common::GetScmRevStr() + "\n";
395 file << "Video Backend: " + g_video_backend->GetDisplayName();
396 file.close();
397
398 PanicAlertFmt("Failed to compile {} shader: {}\n"
399 "Debug info ({}, {}, {}):\n{}",
400 prefix, filename, g_ogl_config.gl_vendor, g_ogl_config.gl_renderer,
401 g_ogl_config.gl_version, info_log);
402
403 return false;
404 }
405
406 WARN_LOG_FMT(VIDEO, "{} compiled with warnings:\n{}", prefix, info_log);
407 }
408
409 return true;
410 }
411
412 bool ProgramShaderCache::CheckProgramLinkResult(GLuint id, std::string_view vcode,
413 std::string_view pcode, std::string_view gcode)
414 {
415 GLint linkStatus;
416 glGetProgramiv(id, GL_LINK_STATUS, &linkStatus);
417 GLsizei length = 0;
418 glGetProgramiv(id, GL_INFO_LOG_LENGTH, &length);
419 if (linkStatus != GL_TRUE || length > 1)
420 {
421 std::string info_log;
422 info_log.resize(length);
423 glGetProgramInfoLog(id, length, &length, &info_log[0]);
424 if (linkStatus != GL_TRUE)
425 {
426 ERROR_LOG_FMT(VIDEO, "Program failed linking:\n{}", info_log);
427 std::string filename = VideoBackendBase::BadShaderFilename("p", num_failures++);
428 std::ofstream file;
429 File::OpenFStream(file, filename, std::ios_base::out);
430 if (!vcode.empty())
431 file << s_glsl_header << vcode << '\n';
432 if (!gcode.empty())
433 file << s_glsl_header << gcode << '\n';
434 if (!pcode.empty())
435 file << s_glsl_header << pcode << '\n';
436
437 file << info_log;
438 file << "\n";
439 file << "Dolphin Version: " + Common::GetScmRevStr() + "\n";
440 file << "Video Backend: " + g_video_backend->GetDisplayName();
441 file.close();
442
443 PanicAlertFmt("Failed to link shaders: {}\n"
444 "Debug info ({}, {}, {}):\n{}",
445 filename, g_ogl_config.gl_vendor, g_ogl_config.gl_renderer,
446 g_ogl_config.gl_version, info_log);
447
448 return false;
449 }
450
451 WARN_LOG_FMT(VIDEO, "Program linked with warnings:\n{}", info_log);
452 }
453
454 return true;
455 }
456
457 void ProgramShaderCache::Init()
458 {
459 // We have to get the UBO alignment here because
460 // if we generate a buffer that isn't aligned
461 // then the UBO will fail.
462 glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &s_ubo_align);
463
464 s_ubo_buffer_size =
465 static_cast<u32>(Common::AlignUp(sizeof(PixelShaderConstants), s_ubo_align) +
466 Common::AlignUp(sizeof(VertexShaderConstants), s_ubo_align) +
467 Common::AlignUp(sizeof(GeometryShaderConstants), s_ubo_align));
468
469 // We multiply by *4*4 because we need to get down to basic machine units.
470 // So multiply by four to get how many floats we have from vec4s
471 // Then once more to get bytes
472 s_buffer = StreamBuffer::Create(GL_UNIFORM_BUFFER, VertexManagerBase::UNIFORM_STREAM_BUFFER_SIZE);
473
474 CreateHeader();
475 CreateAttributelessVAO();
476
477 CurrentProgram = 0;
478 }
479
480 void ProgramShaderCache::Shutdown()
481 {
482 s_buffer.reset();
483
484 glBindVertexArray(0);
485 glDeleteBuffers(1, &s_attributeless_VBO);
486 glDeleteVertexArrays(1, &s_attributeless_VAO);
487 s_attributeless_VBO = 0;
488 s_attributeless_VAO = 0;
489 s_last_VAO = 0;
490
491 // All pipeline programs should have been released.
492 DEBUG_ASSERT(s_pipeline_programs.empty());
493 s_pipeline_programs.clear();
494 }
495
496 void ProgramShaderCache::CreateAttributelessVAO()
497 {
498 glGenVertexArrays(1, &s_attributeless_VAO);
499
500 // In a compatibility context, we require a valid, bound array buffer.
501 glGenBuffers(1, &s_attributeless_VBO);
502
503 // Initialize the buffer with nothing. 16 floats is an arbitrary size that may work around driver
504 // issues.
505 glBindBuffer(GL_ARRAY_BUFFER, s_attributeless_VBO);
506 glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 16, nullptr, GL_STATIC_DRAW);
507
508 // We must also define vertex attribute 0.
509 glBindVertexArray(s_attributeless_VAO);
510 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
511 glEnableVertexAttribArray(0);
512 }
513
514 void ProgramShaderCache::BindVertexFormat(const GLVertexFormat* vertex_format)
515 {
516 u32 new_VAO = vertex_format ? vertex_format->VAO : s_attributeless_VAO;
517 if (s_last_VAO == new_VAO)
518 return;
519
520 glBindVertexArray(new_VAO);
521 s_last_VAO = new_VAO;
522 }
523
524 void ProgramShaderCache::ReBindVertexFormat()
525 {
526 if (s_last_VAO)
527 glBindVertexArray(s_last_VAO);
528 }
529
530 bool ProgramShaderCache::IsValidVertexFormatBound()
531 {
532 return s_last_VAO != 0 && s_last_VAO != s_attributeless_VAO;
533 }
534
535 void ProgramShaderCache::InvalidateVertexFormat()
536 {
537 s_last_VAO = 0;
538 }
539
540 void ProgramShaderCache::InvalidateVertexFormatIfBound(GLuint vao)
541 {
542 if (s_last_VAO == vao)
543 s_last_VAO = 0;
544 }
545
546 void ProgramShaderCache::InvalidateLastProgram()
547 {
548 CurrentProgram = 0;
549 }
550
551 PipelineProgram* ProgramShaderCache::GetPipelineProgram(const GLVertexFormat* vertex_format,
552 const OGLShader* vertex_shader,
553 const OGLShader* geometry_shader,
554 const OGLShader* pixel_shader,
555 const void* cache_data,
556 size_t cache_data_size)
557 {
558 PipelineProgramKey key = {vertex_shader ? vertex_shader->GetID() : 0,
559 geometry_shader ? geometry_shader->GetID() : 0,
560 pixel_shader ? pixel_shader->GetID() : 0};
561 {
562 std::lock_guard guard{s_pipeline_program_lock};
563 auto iter = s_pipeline_programs.find(key);
564 if (iter != s_pipeline_programs.end())
565 {
566 iter->second->reference_count++;
567 return iter->second.get();
568 }
569 }
570
571 std::unique_ptr<PipelineProgram> prog = std::make_unique<PipelineProgram>();
572 prog->key = key;
573 prog->shader.glprogid = glCreateProgram();
574
575 // Use the cache data, if present. If this fails, we want to return an error, so the shader cache
576 // doesn't attempt to use the same binary data in the future.
577 if (cache_data_size >= sizeof(u32))
578 {
579 u32 program_binary_type;
580 std::memcpy(&program_binary_type, cache_data, sizeof(u32));
581 glProgramBinary(prog->shader.glprogid, static_cast<GLenum>(program_binary_type),
582 static_cast<const u8*>(cache_data) + sizeof(u32),
583 static_cast<GLsizei>(cache_data_size - sizeof(u32)));
584
585 // Check the link status. If this fails, it means the binary was invalid.
586 GLint link_status;
587 glGetProgramiv(prog->shader.glprogid, GL_LINK_STATUS, &link_status);
588 if (link_status != GL_TRUE)
589 {
590 WARN_LOG_FMT(VIDEO, "Failed to create GL program from program binary.");
591 prog->shader.Destroy();
592 return nullptr;
593 }
594
595 // We don't want to retrieve this binary and duplicate entries in the cache again.
596 // See the explanation in OGLPipeline.cpp.
597 prog->binary_retrieved = true;
598 }
599 else
600 {
601 // We temporarily change the vertex array to the pipeline's vertex format.
602 // This can prevent the NVIDIA OpenGL driver from recompiling on first use.
603 GLuint vao = vertex_format ? vertex_format->VAO : s_attributeless_VAO;
604 if (s_is_shared_context || vao != s_last_VAO)
605 glBindVertexArray(vao);
606
607 // Attach shaders.
608 ASSERT(vertex_shader && vertex_shader->GetStage() == ShaderStage::Vertex);
609 ASSERT(pixel_shader && pixel_shader->GetStage() == ShaderStage::Pixel);
610 glAttachShader(prog->shader.glprogid, vertex_shader->GetGLShaderID());
611 glAttachShader(prog->shader.glprogid, pixel_shader->GetGLShaderID());
612 if (geometry_shader)
613 {
614 ASSERT(geometry_shader->GetStage() == ShaderStage::Geometry);
615 glAttachShader(prog->shader.glprogid, geometry_shader->GetGLShaderID());
616 }
617
618 if (g_backend_info.bSupportsPipelineCacheData)
619 glProgramParameteri(prog->shader.glprogid, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
620
621 // Link program.
622 prog->shader.SetProgramBindings(false);
623 glLinkProgram(prog->shader.glprogid);
624
625 // Restore VAO binding after linking.
626 if (!s_is_shared_context && vao != s_last_VAO)
627 glBindVertexArray(s_last_VAO);
628
629 if (!CheckProgramLinkResult(prog->shader.glprogid,
630 vertex_shader ? vertex_shader->GetSource() : std::string_view{},
631 geometry_shader ? geometry_shader->GetSource() : std::string_view{},
632 pixel_shader ? pixel_shader->GetSource() : std::string_view{}))
633 {
634 prog->shader.Destroy();
635 return nullptr;
636 }
637 }
638
639 // Lock to insert. A duplicate program may have been created in the meantime.
640 std::lock_guard guard{s_pipeline_program_lock};
641 auto iter = s_pipeline_programs.find(key);
642 if (iter != s_pipeline_programs.end())
643 {
644 // Destroy this program, and use the one which was created first.
645 prog->shader.Destroy();
646 iter->second->reference_count++;
647 return iter->second.get();
648 }
649
650 // Set program variables on the shader which will be returned.
651 // This is only needed for drivers which don't support binding layout.
652 prog->shader.SetProgramVariables();
653
654 // If this is a shared context, ensure we sync before we return the program to
655 // the main thread. If we don't do this, some driver can lock up (e.g. AMD).
656 if (s_is_shared_context)
657 glFinish();
658
659 auto ip = s_pipeline_programs.emplace(key, std::move(prog));
660 return ip.first->second.get();
661 }
662
663 void ProgramShaderCache::ReleasePipelineProgram(PipelineProgram* prog)
664 {
665 if (--prog->reference_count > 0)
666 return;
667
668 prog->shader.Destroy();
669
670 std::lock_guard guard{s_pipeline_program_lock};
671 const auto iter = s_pipeline_programs.find(prog->key);
672 ASSERT(iter != s_pipeline_programs.end() && prog == iter->second.get());
673 s_pipeline_programs.erase(iter);
674 }
675
676 void ProgramShaderCache::CreateHeader()
677 {
678 GlslVersion v = g_ogl_config.eSupportedGLSLVersion;
679 bool is_glsles = v >= GlslEs300;
680 std::string SupportedESPointSize;
681 std::string SupportedESTextureBuffer;
682 switch (g_ogl_config.SupportedESPointSize)
683 {
684 case EsPointSizeType::PointSizeOes:
685 SupportedESPointSize = "#extension GL_OES_geometry_point_size : enable";
686 break;
687 case EsPointSizeType::PointSizeExt:
688 SupportedESPointSize = "#extension GL_EXT_geometry_point_size : enable";
689 break;
690 case EsPointSizeType::PointSizeNone:
691 default:
692 SupportedESPointSize = "";
693 break;
694 }
695
696 switch (g_ogl_config.SupportedESTextureBuffer)
697 {
698 case EsTexbufType::TexbufExt:
699 SupportedESTextureBuffer = "#extension GL_EXT_texture_buffer : enable";
700 break;
701 case EsTexbufType::TexbufOes:
702 SupportedESTextureBuffer = "#extension GL_OES_texture_buffer : enable";
703 break;
704 case EsTexbufType::TexbufCore:
705 case EsTexbufType::TexbufNone:
706 SupportedESTextureBuffer = "";
707 break;
708 }
709
710 std::string earlyz_string;
711 if (g_backend_info.bSupportsEarlyZ)
712 {
713 if (g_ogl_config.bSupportsImageLoadStore)
714 {
715 earlyz_string = "#define FORCE_EARLY_Z layout(early_fragment_tests) in\n";
716 }
717 else if (g_ogl_config.bSupportsConservativeDepth)
718 {
719 // See PixelShaderGen for details about this fallback.
720 earlyz_string = "#define FORCE_EARLY_Z layout(depth_unchanged) out float gl_FragDepth\n";
721 earlyz_string += "#extension GL_ARB_conservative_depth : enable\n";
722 }
723 }
724
725 std::string framebuffer_fetch_string;
726 switch (g_ogl_config.SupportedFramebufferFetch)
727 {
728 case EsFbFetchType::FbFetchExt:
729 framebuffer_fetch_string = "#extension GL_EXT_shader_framebuffer_fetch: enable\n"
730 "#define FRAGMENT_INOUT inout";
731 break;
732 case EsFbFetchType::FbFetchArm:
733 framebuffer_fetch_string = "#extension GL_ARM_shader_framebuffer_fetch: enable\n"
734 "#define FB_FETCH_VALUE gl_LastFragColorARM\n"
735 "#define FRAGMENT_INOUT out";
736 break;
737 case EsFbFetchType::FbFetchNone:
738 framebuffer_fetch_string = "";
739 break;
740 }
741
742 // The sampler2DMSArray keyword is reserved in GLSL ES 3.0 and 3.1, but is available in 3.2 and
743 // with GL_OES_texture_storage_multisample_2d_array for 3.1.
744 // See https://bugs.dolphin-emu.org/issues/13198.
745 const bool use_multisample_2d_array_precision =
746 v >= GlslEs320 ||
747 g_ogl_config.SupportedMultisampleTexStorage != MultisampleTexStorageType::TexStorageNone;
748
749 std::string binding_layout;
750 if (g_backend_info.bSupportsBindingLayout)
751 {
752 if (g_ogl_config.bSupportsExplicitLayoutInShader)
753 {
754 binding_layout =
755 "#extension GL_ARB_explicit_attrib_location : enable\n"
756 "#define ATTRIBUTE_LOCATION(x) layout(location = x)\n"
757 "#define FRAGMENT_OUTPUT_LOCATION(x) layout(location = x)\n"
758 "#define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y) layout(location = x, index = y)\n"
759 "#define UBO_BINDING(packing, x) layout(packing, binding = x)\n"
760 "#define SAMPLER_BINDING(x) layout(binding = x)\n"
761 "#define TEXEL_BUFFER_BINDING(x) layout(binding = x)\n"
762 "#define SSBO_BINDING(x) layout(std430, binding = x)\n"
763 "#define IMAGE_BINDING(format, x) layout(format, binding = x)\n";
764 }
765 else
766 {
767 binding_layout = "#define ATTRIBUTE_LOCATION(x)\n"
768 "#define FRAGMENT_OUTPUT_LOCATION(x)\n"
769 "#define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y)\n"
770 "#define UBO_BINDING(packing, x) layout(packing, binding = x)\n"
771 "#define SAMPLER_BINDING(x) layout(binding = x)\n"
772 "#define TEXEL_BUFFER_BINDING(x) layout(binding = x)\n"
773 "#define SSBO_BINDING(x) layout(std430, binding = x)\n"
774 "#define IMAGE_BINDING(format, x) layout(format, binding = x)\n";
775 }
776 }
777 else
778 {
779 binding_layout = "#define ATTRIBUTE_LOCATION(x)\n"
780 "#define FRAGMENT_OUTPUT_LOCATION(x)\n"
781 "#define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y)\n"
782 "#define UBO_BINDING(packing, x) layout(packing)\n"
783 "#define SAMPLER_BINDING(x)\n"
784 "#define TEXEL_BUFFER_BINDING(x)\n"
785 "#define SSBO_BINDING(x) layout(std430)\n"
786 "#define IMAGE_BINDING(format, x) layout(format)\n";
787 }
788
789 // TODO: actually define this if using 'bSupportsExplicitLayoutInShader'
790 const std::string varying_location = "#define VARYING_LOCATION(x)\n";
791
792 std::string shader_shuffle_string;
793 if (g_ogl_config.bSupportsKHRShaderSubgroup)
794 {
795 shader_shuffle_string = R"(
796 #extension GL_KHR_shader_subgroup_basic : enable
797 #extension GL_KHR_shader_subgroup_arithmetic : enable
798 #extension GL_KHR_shader_subgroup_ballot : enable
799
800 #define SUPPORTS_SUBGROUP_REDUCTION 1
801 #define IS_HELPER_INVOCATION gl_HelperInvocation
802 #define IS_FIRST_ACTIVE_INVOCATION (subgroupElect())
803 #define SUBGROUP_MIN(value) value = subgroupMin(value)
804 #define SUBGROUP_MAX(value) value = subgroupMax(value)
805 )";
806 }
807
808 s_glsl_header = fmt::format(
809 "{}\n"
810 "{}\n" // ubo
811 "{}\n" // early-z
812 "{}\n" // 420pack
813 "{}\n" // msaa
814 "{}\n" // Input/output/sampler binding
815 "{}\n" // Varying location
816 "{}\n" // storage buffer
817 "{}\n" // shader5
818 "{}\n" // SSAA
819 "{}\n" // Geometry point size
820 "{}\n" // AEP
821 "{}\n" // texture buffer
822 "{}\n" // ES texture buffer
823 "{}\n" // ES dual source blend
824 "{}\n" // shader image load store
825 "{}\n" // shader framebuffer fetch
826 "{}\n" // shader thread shuffle
827 "{}\n" // derivative control
828 "{}\n" // query levels
829 "{}\n" // OES multisample texture storage
830
831 // Precision defines for GLSL ES
832 "{}\n"
833 "{}\n"
834 "{}\n"
835 "{}\n"
836 "{}\n"
837 "{}\n"
838
839 // Silly differences
840 "#define API_OPENGL 1\n"
841 "#define float2 vec2\n"
842 "#define float3 vec3\n"
843 "#define float4 vec4\n"
844 "#define uint2 uvec2\n"
845 "#define uint3 uvec3\n"
846 "#define uint4 uvec4\n"
847 "#define int2 ivec2\n"
848 "#define int3 ivec3\n"
849 "#define int4 ivec4\n"
850 "#define frac fract\n"
851 "#define lerp mix\n"
852
853 ,
854 GetGLSLVersionString(), v < Glsl140 ? "#extension GL_ARB_uniform_buffer_object : enable" : "",
855 earlyz_string,
856 (g_backend_info.bSupportsBindingLayout && v < GlslEs310) ?
857 "#extension GL_ARB_shading_language_420pack : enable" :
858 "",
859 (g_ogl_config.bSupportsMSAA && v < Glsl150) ?
860 "#extension GL_ARB_texture_multisample : enable" :
861 "",
862 binding_layout.c_str(), varying_location.c_str(),
863 !is_glsles && g_backend_info.bSupportsFragmentStoresAndAtomics ?
864 "#extension GL_ARB_shader_storage_buffer_object : enable" :
865 "",
866 v < Glsl400 && g_backend_info.bSupportsGSInstancing ?
867 "#extension GL_ARB_gpu_shader5 : enable" :
868 "",
869 v < Glsl400 && g_backend_info.bSupportsSSAA ? "#extension GL_ARB_sample_shading : enable" :
870 "",
871 SupportedESPointSize,
872 g_ogl_config.bSupportsAEP ? "#extension GL_ANDROID_extension_pack_es31a : enable" : "",
873 v < Glsl140 && g_backend_info.bSupportsPaletteConversion ?
874 "#extension GL_ARB_texture_buffer_object : enable" :
875 "",
876 SupportedESTextureBuffer,
877 is_glsles && g_backend_info.bSupportsDualSourceBlend ?
878 "#extension GL_EXT_blend_func_extended : enable" :
879 ""
880
881 ,
882 g_ogl_config.bSupportsImageLoadStore &&
883 ((!is_glsles && v < Glsl430) || (is_glsles && v < GlslEs310)) ?
884 "#extension GL_ARB_shader_image_load_store : enable" :
885 "",
886 framebuffer_fetch_string, shader_shuffle_string,
887 g_backend_info.bSupportsCoarseDerivatives ? "#extension GL_ARB_derivative_control : enable" :
888 "",
889 g_backend_info.bSupportsTextureQueryLevels ?
890 "#extension GL_ARB_texture_query_levels : enable" :
891 "",
892 // Note: GL_ARB_texture_storage_multisample doesn't have an #extension, as it doesn't
893 // need to change GLSL, but on GLES 3.1 sampler2DMSArray is a reserved keyword unless
894 // the extension is enabled. Thus, we don't need to check TexStorageCore/have an ARB version.
895 g_ogl_config.SupportedMultisampleTexStorage == MultisampleTexStorageType::TexStorageOes ?
896 "#extension GL_OES_texture_storage_multisample_2d_array : enable" :
897 "",
898 is_glsles ? "precision highp float;" : "", is_glsles ? "precision highp int;" : "",
899 is_glsles ? "precision highp sampler2DArray;" : "",
900 (is_glsles && g_backend_info.bSupportsPaletteConversion) ? "precision highp usamplerBuffer;" :
901 "",
902 use_multisample_2d_array_precision ? "precision highp sampler2DMSArray;" : "",
903 v >= GlslEs310 ? "precision highp image2DArray;" : "");
904 }
905
906 u64 ProgramShaderCache::GenerateShaderID()
907 {
908 return s_shader_counter++;
909 }
910
911 bool SharedContextAsyncShaderCompiler::WorkerThreadInitMainThread(void** param)
912 {
913 std::unique_ptr<GLContext> context = GetOGLGfx()->GetMainGLContext()->CreateSharedContext();
914 if (!context)
915 {
916 PanicAlertFmt("Failed to create shared context for shader compiling.");
917 return false;
918 }
919
920 *param = context.release();
921 return true;
922 }
923
924 bool SharedContextAsyncShaderCompiler::WorkerThreadInitWorkerThread(void* param)
925 {
926 GLContext* context = static_cast<GLContext*>(param);
927 if (!context->MakeCurrent())
928 return false;
929
930 s_is_shared_context = true;
931
932 // Make the state match the main context to have a better chance of avoiding recompiles.
933 if (!context->IsGLES())
934 glEnable(GL_PROGRAM_POINT_SIZE);
935 if (g_backend_info.bSupportsClipControl)
936 glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
937 if (g_backend_info.bSupportsDepthClamp)
938 {
939 glEnable(GL_CLIP_DISTANCE0);
940 glEnable(GL_CLIP_DISTANCE1);
941 glEnable(GL_DEPTH_CLAMP);
942 }
943 if (g_backend_info.bSupportsPrimitiveRestart)
944 GLUtil::EnablePrimitiveRestart(context);
945
946 return true;
947 }
948
949 void SharedContextAsyncShaderCompiler::WorkerThreadExit(void* param)
950 {
951 GLContext* context = static_cast<GLContext*>(param);
952 context->ClearCurrent();
953 delete context;
954 }
955 } // namespace OGL