summaryrefslogtreecommitdiff
path: root/Source/Core/VideoCommon/Resources/ShaderResource.cpp
blob: 7b77886e2efcd8e97c0f0d42eb011efef91ed01e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Copyright 2025 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "VideoCommon/Resources/ShaderResource.h"

#include <string_view>
#include <utility>

#include <fmt/format.h>

#include "VideoCommon/AbstractGfx.h"
#include "VideoCommon/Assets/CustomAssetCache.h"
#include "VideoCommon/AsyncShaderCompiler.h"
#include "VideoCommon/FramebufferShaderGen.h"
#include "VideoCommon/GeometryShaderGen.h"
#include "VideoCommon/PipelineUtils.h"
#include "VideoCommon/PixelShaderGen.h"
#include "VideoCommon/VertexShaderGen.h"
#include "VideoCommon/VideoConfig.h"

namespace VideoCommon
{
namespace
{
// TODO: the uniform buffer is combined due to the utility path only having a single
// set of constants, this isn't ideal (both for the end user, where it's more readable
// to see 'custom_uniforms' before variables and from Dolphin because the
// standard uniforms have to be packed with the custom ones
void GeneratePostProcessUniformOutput(ShaderCode& shader_source, std::string_view block_name,
                                      std::string_view uniforms)
{
  shader_source.Write("UBO_BINDING(std140, 1) uniform {} {{\n", block_name);
  shader_source.Write("\tvec4 source_resolution;\n");
  shader_source.Write("\tvec4 target_resolution;\n");
  shader_source.Write("\tvec4 window_resolution;\n");
  shader_source.Write("\tvec4 source_region;\n");
  shader_source.Write("\tint source_layer;\n");
  shader_source.Write("\tint source_layer_pad1;\n");
  shader_source.Write("\tint source_layer_pad2;\n");
  shader_source.Write("\tint source_layer_pad3;\n");
  shader_source.Write("\tuint time;\n");
  shader_source.Write("\tuint time_pad1;\n");
  shader_source.Write("\tuint time_pad2;\n");
  shader_source.Write("\tuint time_pad3;\n");
  shader_source.Write("\tint graphics_api;\n");
  shader_source.Write("\tint graphics_api_pad1;\n");
  shader_source.Write("\tint graphics_api_pad2;\n");
  shader_source.Write("\tint graphics_api_pad3;\n");
  shader_source.Write("\tuint efb_scale;\n");
  shader_source.Write("\tuint efb_scale_pad1;\n");
  shader_source.Write("\tuint efb_scale_pad2;\n");
  shader_source.Write("\tuint efb_scale_pad3;\n");
  if (!uniforms.empty())
  {
    shader_source.Write("{}", uniforms);
  }
  shader_source.Write("}};\n");
}

// TODO: move this to a more standard post processing file
// once post processing has been cleaned up
void GeneratePostProcessingVertexShader(ShaderCode& shader_source,
                                        const CustomVertexContents& custom_contents)
{
  // Note: if blocks are the same, they need to match for the OpenGL backend
  GeneratePostProcessUniformOutput(shader_source, "PSBlock", custom_contents.uniforms);

  // Define some defines that are shared with custom draw shaders,
  // so that a common shader code could possibly be used in both
  shader_source.Write("#define HAS_COLOR_0 0\n");
  shader_source.Write("#define HAS_COLOR_1 0\n");
  shader_source.Write("#define HAS_NORMAL 0\n");
  shader_source.Write("#define HAS_BINORMAL 0\n");
  shader_source.Write("#define HAS_TANGENT 0\n");
  shader_source.Write("#define HAS_TEXTURE_COORD_0 1\n");
  for (u32 i = 1; i < 8; i++)
  {
    shader_source.Write("#define HAS_TEXTURE_COORD_{} 0\n", i);
  }

  // Write the common structs, might want to consider
  // moving these to another location?
  shader_source.Write("struct DolphinVertexInput\n");
  shader_source.Write("{{\n");
  shader_source.Write("\tvec4 position;\n");
  shader_source.Write("\tvec3 texture_coord_0;\n");
  shader_source.Write("}};\n\n");

  shader_source.Write("struct DolphinVertexOutput\n");
  shader_source.Write("{{\n");
  shader_source.Write("\tvec4 position;\n");
  shader_source.Write("\tvec3 texture_coord_0;\n");
  shader_source.Write("}};\n\n");

  constexpr std::string_view emulated_vertex_definition =
      "void dolphin_process_emulated_vertex(in DolphinVertexInput vertex_input, out "
      "DolphinVertexOutput vertex_output)";
  shader_source.Write("{}\n", emulated_vertex_definition);
  shader_source.Write("{{\n");
  shader_source.Write("\tvertex_output.position = vertex_input.position;\n");
  shader_source.Write("\tvertex_output.texture_coord_0 = vertex_input.texture_coord_0;\n");
  shader_source.Write("}}\n");

  if (custom_contents.shader.empty())
  {
    shader_source.Write(
        "void process_vertex(in DolphinVertexInput vertex_input, out DolphinVertexOutput "
        "vertex_output)\n");
    shader_source.Write("{{\n");

    shader_source.Write("\tdolphin_process_emulated_vertex(vertex_input, vertex_output);\n");

    shader_source.Write("}}\n");
  }
  else
  {
    shader_source.Write("{}\n", custom_contents.shader);
  }

  if (g_backend_info.bSupportsGeometryShaders)
  {
    shader_source.Write("VARYING_LOCATION(0) out VertexData {{\n");
    shader_source.Write("\tvec3 v_tex0;\n");
    shader_source.Write("}};\n");
  }
  else
  {
    shader_source.Write("VARYING_LOCATION(0) out vec3 v_tex0;\n");
  }

  shader_source.Write("void main()\n");
  shader_source.Write("{{\n");
  shader_source.Write("\tDolphinVertexInput vertex_input;\n");
  shader_source.Write("\tvec3 vert = vec3(float((gl_VertexID << 1) & 2), "
                      "float(gl_VertexID & 2), 0.0f);\n");
  shader_source.Write("\tvertex_input.position = vec4(vert.xy * "
                      "float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);\n");
  shader_source.Write("\tvertex_input.texture_coord_0 = vec3(source_region.xy + "
                      "(source_region.zw * vert.xy), 0.0f);\n");
  shader_source.Write("\tDolphinVertexOutput vertex_output;\n");
  shader_source.Write("\tprocess_vertex(vertex_input, vertex_output);\n");
  shader_source.Write("\tgl_Position = vertex_output.position;\n");
  shader_source.Write("\tv_tex0 = vertex_output.texture_coord_0;\n");

  // NDC space is flipped in Vulkan
  if (g_backend_info.api_type == APIType::Vulkan)
  {
    shader_source.Write("\tgl_Position.y = -gl_Position.y;\n");
  }

  shader_source.Write("}}\n");
}

void GeneratePostProcessingPixelShader(ShaderCode& shader_source,
                                       const CustomPixelContents& custom_contents)
{
  GeneratePostProcessUniformOutput(shader_source, "PSBlock", custom_contents.uniforms);

  shader_source.Write("SAMPLER_BINDING(0) uniform sampler2DArray samp0;\n");

  if (g_backend_info.bSupportsGeometryShaders)
  {
    shader_source.Write("VARYING_LOCATION(0) in VertexData {{\n");
    shader_source.Write("\tvec3 v_tex0;\n");
    shader_source.Write("}};\n");
  }
  else
  {
    shader_source.Write("VARYING_LOCATION(0) in float3 v_tex0;\n");
  }

  shader_source.Write("FRAGMENT_OUTPUT_LOCATION(0) out vec4 ocol0;\n");

  shader_source.Write("struct DolphinFragmentInput\n");
  shader_source.Write("{{\n");
  for (u32 i = 0; i < 1; i++)
  {
    shader_source.Write("\tvec3 tex{};\n", i);
  }
  shader_source.Write("\n");

  shader_source.Write("}};\n\n");

  shader_source.Write("struct DolphinFragmentOutput\n");
  shader_source.Write("{{\n");
  shader_source.Write("\tvec4 main;\n");
  shader_source.Write("}};\n\n");

  constexpr std::string_view emulated_fragment_definition =
      "void dolphin_process_emulated_fragment(in DolphinFragmentInput frag_input, out "
      "DolphinFragmentOutput frag_output)";
  shader_source.Write("{}\n", emulated_fragment_definition);
  shader_source.Write("{{\n");
  shader_source.Write("\tfrag_output.main = texture(samp0, frag_input.tex0);\n");
  shader_source.Write("}}\n");

  if (custom_contents.shader.empty())
  {
    shader_source.Write(
        "void process_fragment(in DolphinFragmentInput frag_input, out DolphinFragmentOutput "
        "frag_output)\n");
    shader_source.Write("{{\n");

    shader_source.Write("\tdolphin_process_emulated_fragment(frag_input, frag_output);\n");

    shader_source.Write("}}\n");
  }
  else
  {
    shader_source.Write("{}\n", custom_contents.shader);
  }

  shader_source.Write("void main()\n");
  shader_source.Write("{{\n");
  shader_source.Write("\tDolphinFragmentInput frag_input;\n");
  shader_source.Write("\tfrag_input.tex0 = v_tex0;\n");
  shader_source.Write("\tDolphinFragmentOutput frag_output;\n");
  shader_source.Write("\tprocess_fragment(frag_input, frag_output);\n");
  shader_source.Write("\tocol0 = frag_output.main;\n");
  shader_source.Write("}}\n");
}

std::unique_ptr<AbstractShader> CompileGeometryShader(GeometryShaderUid* uid, APIType api_type,
                                                      ShaderHostConfig host_config)
{
  if (!uid)
  {
    return g_gfx->CreateShaderFromSource(
        ShaderStage::Geometry, FramebufferShaderGen::GeneratePassthroughGeometryShader(1, 0),
        nullptr, "Custom Post Processing Geometry Shader");
  }

  const ShaderCode source_code =
      GenerateGeometryShaderCode(api_type, host_config, uid->GetUidData());
  return g_gfx->CreateShaderFromSource(ShaderStage::Geometry, source_code.GetBuffer(), nullptr,
                                       fmt::format("Geometry shader: {}", *uid->GetUidData()));
}

std::unique_ptr<AbstractShader>
CompilePixelShader(PixelShaderUid* uid, std::string_view preprocessor_settings, APIType api_type,
                   const ShaderHostConfig& host_config, RasterSurfaceShaderData* shader_data)
{
  ShaderCode shader_code;

  // Write any preprocessor values that were passed in
  shader_code.Write("{}", preprocessor_settings);

  // TODO: in the future we could dynamically determine the amount of samplers
  // available, for now just hardcode to start at 8 (the first non game
  // sampler index available)
  const std::size_t custom_sampler_index_offset = 8;
  for (std::size_t i = 0; i < shader_data->samplers.size(); i++)
  {
    const auto& sampler = shader_data->samplers[i];
    std::string_view sampler_type;
    switch (sampler.type)
    {
    case AbstractTextureType::Texture_2D:
      sampler_type = "sampler2D";
      break;
    case AbstractTextureType::Texture_2DArray:
      sampler_type = "sampler2DArray";
      break;
    case AbstractTextureType::Texture_CubeMap:
      sampler_type = "samplerCube";
      break;
    };
    shader_code.Write("SAMPLER_BINDING({}) uniform {} samp_{};\n", custom_sampler_index_offset + i,
                      sampler_type, sampler.name);

    // Sampler usage is passed in from the material
    // Write a new preprocessor value with the sampler name
    // for easier code in the shader
    shader_code.Write("#if HAS_SAMPLER_{} == 1\n", i);
    shader_code.Write("#define HAS_{} 1\n", sampler.name);
    shader_code.Write("#endif\n");

    shader_code.Write("\n");
  }
  shader_code.Write("\n");

  // Now write the custom shader
  shader_code.Write("{}", ReplaceAll(shader_data->pixel_source, "\r\n", "\n"));

  // Write out the uniform data
  ShaderCode uniform_code;
  for (const auto& property : shader_data->uniform_properties)
  {
    VideoCommon::ShaderProperty::WriteAsShaderCode(uniform_code, property);
  }
  if (!shader_data->uniform_properties.empty())
    uniform_code.Write("\n\n");

  // Compile the shader
  CustomPixelContents contents{.shader = shader_code.GetBuffer(),
                               .uniforms = uniform_code.GetBuffer()};

  ShaderCode source_code;
  if (uid)
  {
    source_code = GeneratePixelShaderCode(api_type, host_config, uid->GetUidData(), contents);
  }
  else
  {
    GeneratePostProcessingPixelShader(source_code, contents);
  }
  ShaderIncluder* shader_includer =
      shader_data->shader_includer ? &*shader_data->shader_includer : nullptr;
  return g_gfx->CreateShaderFromSource(ShaderStage::Pixel, source_code.GetBuffer(), shader_includer,
                                       "Custom Pixel Shader");
}

std::unique_ptr<AbstractShader>
CompileVertexShader(VertexShaderUid* uid, std::string_view preprocessor_settings, APIType api_type,
                    const ShaderHostConfig& host_config, const RasterSurfaceShaderData& shader_data)
{
  ShaderCode shader_code;

  // Write any preprocessor values that were passed in
  shader_code.Write("{}", preprocessor_settings);

  // TODO: in the future we could dynamically determine the amount of samplers
  // available, for now just hardcode to start at 8 (the first non game
  // sampler index available)
  const std::size_t custom_sampler_index_offset = 8;
  for (std::size_t i = 0; i < shader_data.samplers.size(); i++)
  {
    const auto& sampler = shader_data.samplers[i];
    std::string_view sampler_type = "";
    switch (sampler.type)
    {
    case AbstractTextureType::Texture_2D:
      sampler_type = "sampler2D";
      break;
    case AbstractTextureType::Texture_2DArray:
      sampler_type = "sampler2DArray";
      break;
    case AbstractTextureType::Texture_CubeMap:
      sampler_type = "samplerCube";
      break;
    };
    shader_code.Write("SAMPLER_BINDING({}) uniform {} samp_{};\n", custom_sampler_index_offset + i,
                      sampler_type, sampler.name);

    // Sampler usage is passed in from the material
    // Write a new preprocessor value with the sampler name
    // for easier code in the shader
    shader_code.Write("#if HAS_SAMPLER_{} == 1\n", i);
    shader_code.Write("#define HAS_{} 1\n", sampler.name);
    shader_code.Write("#endif\n");

    shader_code.Write("\n");
  }
  shader_code.Write("\n");

  // Now write the custom shader
  shader_code.Write("{}", ReplaceAll(shader_data.vertex_source, "\r\n", "\n"));

  // Write out the uniform data
  ShaderCode uniform_code;
  for (const auto& property : shader_data.uniform_properties)
  {
    VideoCommon::ShaderProperty::WriteAsShaderCode(uniform_code, property);
  }
  if (!shader_data.uniform_properties.empty())
    uniform_code.Write("\n\n");

  // Compile the shader
  CustomVertexContents contents{.shader = shader_code.GetBuffer(),
                                .uniforms = uniform_code.GetBuffer()};

  ShaderCode source_code;
  if (uid)
  {
    source_code = GenerateVertexShaderCode(api_type, host_config, uid->GetUidData(), contents);
  }
  else
  {
    GeneratePostProcessingVertexShader(source_code, contents);
  }
  return g_gfx->CreateShaderFromSource(ShaderStage::Vertex, source_code.GetBuffer(), nullptr,
                                       "Custom Vertex Shader");
}
}  // namespace
ShaderResource::ShaderResource(Resource::ResourceContext resource_context,
                               std::optional<GXPipelineUid> pipeline_uid,
                               std::string preprocessor_setting,
                               const ShaderHostConfig& shader_host_config)
    : Resource(std::move(resource_context)), m_shader_host_config{.bits = shader_host_config.bits},
      m_uid(std::move(pipeline_uid)), m_preprocessor_settings(std::move(preprocessor_setting))
{
  m_shader_asset = m_resource_context.asset_cache->CreateAsset<RasterSurfaceShaderAsset>(
      m_resource_context.primary_asset_id, m_resource_context.asset_library, this);
}

void ShaderResource::SetHostConfig(const ShaderHostConfig& host_config)
{
  m_shader_host_config.bits = host_config.bits;
}

void ShaderResource::MarkAsPending()
{
  m_resource_context.asset_cache->MarkAssetPending(m_shader_asset);
}

void ShaderResource::MarkAsActive()
{
  m_resource_context.asset_cache->MarkAssetActive(m_shader_asset);
}

AbstractShader* ShaderResource::Data::GetVertexShader() const
{
  if (!m_vertex_shader)
    return nullptr;
  return m_vertex_shader.get();
}

AbstractShader* ShaderResource::Data::GetPixelShader() const
{
  if (!m_pixel_shader)
    return nullptr;
  return m_pixel_shader.get();
}

AbstractShader* ShaderResource::Data::GetGeometryShader() const
{
  if (!m_geometry_shader)
    return nullptr;
  return m_geometry_shader.get();
}

bool ShaderResource::Data::IsCompiled() const
{
  return m_vertex_shader && m_pixel_shader && (!m_needs_geometry_shader || m_geometry_shader);
}

AbstractTextureType ShaderResource::Data::GetTextureType(std::size_t index)
{
  // If the data doesn't exist, just pick one...
  if (!m_shader_data || index >= m_shader_data->samplers.size()) [[unlikely]]
    return AbstractTextureType::Texture_2D;

  return m_shader_data->samplers[index].type;
}

void ShaderResource::ResetData()
{
  m_load_data = std::make_shared<Data>();
  m_processing_load_data = false;
}

Resource::TaskComplete ShaderResource::CollectPrimaryData()
{
  const auto shader_data = m_shader_asset->GetData();
  if (!shader_data) [[unlikely]]
  {
    return Resource::TaskComplete::No;
  }
  m_load_data->m_shader_data = shader_data;

  return Resource::TaskComplete::Yes;
}

Resource::TaskComplete ShaderResource::ProcessData()
{
  class WorkItem final : public VideoCommon::AsyncShaderCompiler::WorkItem
  {
  public:
    WorkItem(std::shared_ptr<ShaderResource::Data> resource_data, VideoCommon::GXPipelineUid* uid,
             u32 shader_bits, std::string_view preprocessor_settings)
        : m_resource_data(std::move(resource_data)), m_uid(uid), m_shader_bits(shader_bits),
          m_preprocessor_settings(preprocessor_settings)
    {
    }

    bool Compile() override
    {
      const ShaderHostConfig shader_host_config{.bits = m_shader_bits};
      if (m_uid)
      {
        // Draw based shader
        auto actual_uid = ApplyDriverBugs(*m_uid);

        ClearUnusedPixelShaderUidBits(g_backend_info.api_type, shader_host_config,
                                      &actual_uid.ps_uid);
        m_resource_data->m_needs_geometry_shader = shader_host_config.backend_geometry_shaders &&
                                                   !actual_uid.gs_uid.GetUidData()->IsPassthrough();

        if (m_resource_data->m_needs_geometry_shader)
        {
          m_resource_data->m_geometry_shader = CompileGeometryShader(
              &actual_uid.gs_uid, g_backend_info.api_type, shader_host_config);
        }
        m_resource_data->m_pixel_shader =
            CompilePixelShader(&actual_uid.ps_uid, m_preprocessor_settings, g_backend_info.api_type,
                               shader_host_config, m_resource_data->m_shader_data.get());
        m_resource_data->m_vertex_shader = CompileVertexShader(
            &actual_uid.vs_uid, m_preprocessor_settings, g_backend_info.api_type,
            shader_host_config, *m_resource_data->m_shader_data);
      }
      else
      {
        // Post processing based shader

        m_resource_data->m_needs_geometry_shader =
            shader_host_config.backend_geometry_shaders && shader_host_config.stereo;
        if (m_resource_data->m_needs_geometry_shader)
        {
          m_resource_data->m_geometry_shader =
              CompileGeometryShader(nullptr, g_backend_info.api_type, shader_host_config);
        }
        m_resource_data->m_pixel_shader =
            CompilePixelShader(nullptr, m_preprocessor_settings, g_backend_info.api_type,
                               shader_host_config, m_resource_data->m_shader_data.get());
        m_resource_data->m_vertex_shader =
            CompileVertexShader(nullptr, m_preprocessor_settings, g_backend_info.api_type,
                                shader_host_config, *m_resource_data->m_shader_data);
      }
      m_resource_data->m_processing_finished = true;
      return true;
    }
    void Retrieve() override {}

  private:
    std::shared_ptr<ShaderResource::Data> m_resource_data;
    VideoCommon::GXPipelineUid* m_uid;
    u32 m_shader_bits;
    std::string_view m_preprocessor_settings;
  };

  if (!m_processing_load_data)
  {
    std::string_view preprocessor_settings = m_preprocessor_settings;
    auto wi = m_resource_context.shader_compiler->CreateWorkItem<WorkItem>(
        m_load_data, m_uid ? &*m_uid : nullptr, m_shader_host_config.bits, preprocessor_settings);

    // We don't need priority, that is already handled by the resource system
    m_resource_context.shader_compiler->QueueWorkItem(std::move(wi), 0);
    m_processing_load_data = true;
  }

  if (!m_load_data->m_processing_finished)
    return Resource::TaskComplete::No;

  if (!m_load_data->IsCompiled())
    return Resource::TaskComplete::Error;

  std::swap(m_current_data, m_load_data);
  return Resource::TaskComplete::Yes;
}
}  // namespace VideoCommon