Debian Codegraph @

Source/Core/VideoBackends/Metal/MTLUtil.mm

raw
1 // Copyright 2022 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoBackends/Metal/MTLUtil.h"
5
6 #include <fstream>
7 #include <string>
8
9 #include <TargetConditionals.h>
10 #include <spirv_msl.hpp>
11
12 #include "Common/MsgHandler.h"
13
14 #include "VideoCommon/Constants.h"
15 #include "VideoCommon/DriverDetails.h"
16 #include "VideoCommon/ShaderCompileUtils.h"
17 #include "VideoCommon/Spirv.h"
18
19 Metal::DeviceFeatures Metal::g_features;
20
21 std::vector<MRCOwned<id<MTLDevice>>> Metal::Util::GetAdapterList()
22 {
23 std::vector<MRCOwned<id<MTLDevice>>> list;
24 id<MTLDevice> default_dev = MTLCreateSystemDefaultDevice();
25 if (default_dev)
26 list.push_back(MRCTransfer(default_dev));
27
28 #if TARGET_OS_OSX
29 auto devices = MRCTransfer(MTLCopyAllDevices());
30 for (id<MTLDevice> device in devices.Get())
31 {
32 if (device != default_dev)
33 list.push_back(MRCRetain(device));
34 }
35 #endif
36
37 return list;
38 }
39
40 void Metal::Util::PopulateBackendInfo(BackendInfo* backend_info)
41 {
42 backend_info->api_type = APIType::Metal;
43 backend_info->bUsesLowerLeftOrigin = false;
44 backend_info->bSupportsExclusiveFullscreen = false;
45 backend_info->bSupportsDualSourceBlend = true;
46 backend_info->bSupportsPrimitiveRestart = true;
47 backend_info->bSupportsGeometryShaders = false;
48 backend_info->bSupportsComputeShaders = true;
49 backend_info->bSupports3DVision = false;
50 backend_info->bSupportsEarlyZ = true;
51 backend_info->bSupportsBindingLayout = true;
52 backend_info->bSupportsBBox = true;
53 backend_info->bSupportsGSInstancing = false;
54 backend_info->bSupportsPostProcessing = true;
55 backend_info->bSupportsPaletteConversion = true;
56 backend_info->bSupportsClipControl = true;
57 backend_info->bSupportsSSAA = true;
58 backend_info->bSupportsFragmentStoresAndAtomics = true;
59 backend_info->bSupportsReversedDepthRange = false;
60 backend_info->bSupportsLogicOp = false;
61 backend_info->bSupportsMultithreading = false;
62 backend_info->bSupportsGPUTextureDecoding = true;
63 backend_info->bSupportsCopyToVram = true;
64 backend_info->bSupportsBitfield = true;
65 backend_info->bSupportsDynamicSamplerIndexing = true;
66 backend_info->bSupportsFramebufferFetch = false;
67 backend_info->bSupportsBackgroundCompiling = true;
68 backend_info->bSupportsLargePoints = true;
69 backend_info->bSupportsPartialDepthCopies = true;
70 backend_info->bSupportsDepthReadback = true;
71 backend_info->bSupportsShaderBinaries = false;
72 backend_info->bSupportsPipelineCacheData = false;
73 backend_info->bSupportsCoarseDerivatives = false;
74 backend_info->bSupportsTextureQueryLevels = true;
75 backend_info->bSupportsLodBiasInSampler = false;
76 backend_info->bSupportsSettingObjectNames = true;
77 // Metal requires multisample resolve to be done on a render pass
78 backend_info->bSupportsPartialMultisampleResolve = false;
79 backend_info->bSupportsDynamicVertexLoader = true;
80 backend_info->bSupportsVSLinePointExpand = true;
81 backend_info->bSupportsHDROutput =
82 1.0 < [[NSScreen deepestScreen] maximumPotentialExtendedDynamicRangeColorComponentValue];
83 }
84
85 void Metal::Util::PopulateBackendInfoAdapters(BackendInfo* backend_info,
86 const std::vector<MRCOwned<id<MTLDevice>>>& adapters)
87 {
88 backend_info->Adapters.clear();
89 for (id<MTLDevice> adapter : adapters)
90 {
91 backend_info->Adapters.push_back([[adapter name] UTF8String]);
92 }
93 }
94
95 /// For testing driver brokenness
96 static bool RenderSinglePixel(id<MTLDevice> dev, id<MTLFunction> vs, id<MTLFunction> fs, //
97 u32 px_in, u32* px_out)
98 {
99 auto pdesc = MRCTransfer([MTLRenderPipelineDescriptor new]);
100 [pdesc setVertexFunction:vs];
101 [pdesc setFragmentFunction:fs];
102 [[pdesc colorAttachments][0] setPixelFormat:MTLPixelFormatRGBA8Unorm];
103 auto pipe = MRCTransfer([dev newRenderPipelineStateWithDescriptor:pdesc error:nil]);
104 if (!pipe)
105 return false;
106 auto buf = MRCTransfer([dev newBufferWithLength:4 options:MTLResourceStorageModeShared]);
107 memcpy([buf contents], &px_in, sizeof(px_in));
108 auto tdesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
109 width:1
110 height:1
111 mipmapped:false];
112 [tdesc setUsage:MTLTextureUsageRenderTarget];
113 auto tex = MRCTransfer([dev newTextureWithDescriptor:tdesc]);
114 auto q = MRCTransfer([dev newCommandQueue]);
115 id<MTLCommandBuffer> cmdbuf = [q commandBuffer];
116
117 id<MTLBlitCommandEncoder> upload_encoder = [cmdbuf blitCommandEncoder];
118 [upload_encoder copyFromBuffer:buf
119 sourceOffset:0
120 sourceBytesPerRow:4
121 sourceBytesPerImage:4
122 sourceSize:MTLSizeMake(1, 1, 1)
123 toTexture:tex
124 destinationSlice:0
125 destinationLevel:0
126 destinationOrigin:MTLOriginMake(0, 0, 0)];
127 [upload_encoder endEncoding];
128
129 auto rpdesc = MRCTransfer([MTLRenderPassDescriptor new]);
130 [[rpdesc colorAttachments][0] setTexture:tex];
131 [[rpdesc colorAttachments][0] setLoadAction:MTLLoadActionLoad];
132 [[rpdesc colorAttachments][0] setStoreAction:MTLStoreActionStore];
133 id<MTLRenderCommandEncoder> renc = [cmdbuf renderCommandEncoderWithDescriptor:rpdesc];
134 [renc setRenderPipelineState:pipe];
135 [renc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
136 [renc endEncoding];
137
138 id<MTLBlitCommandEncoder> download_encoder = [cmdbuf blitCommandEncoder];
139 [download_encoder copyFromTexture:tex
140 sourceSlice:0
141 sourceLevel:0
142 sourceOrigin:MTLOriginMake(0, 0, 0)
143 sourceSize:MTLSizeMake(1, 1, 1)
144 toBuffer:buf
145 destinationOffset:0
146 destinationBytesPerRow:4
147 destinationBytesPerImage:4];
148 [download_encoder endEncoding];
149
150 [cmdbuf commit];
151 [cmdbuf waitUntilCompleted];
152
153 memcpy(px_out, [buf contents], sizeof(*px_out));
154 return [cmdbuf status] == MTLCommandBufferStatusCompleted;
155 }
156
157 static bool DetectIntelGPUFBFetch(id<MTLDevice> dev)
158 {
159 // Even though it's nowhere in the feature set tables, some Intel GPUs support fbfetch!
160 // Annoyingly, the Haswell compiler successfully makes a pipeline but actually miscompiles it and
161 // doesn't insert any fbfetch instructions.
162 // The Broadwell compiler inserts the Skylake fbfetch instruction,
163 // but Broadwell doesn't support that. It seems to make the shader not do anything.
164 // So we actually have to test the thing
165
166 static constexpr const char* shader = R"(
167 vertex float4 fs_triangle(uint vid [[vertex_id]]) {
168 return float4(vid & 1 ? 3 : -1, vid & 2 ? 3 : -1, 0, 1);
169 }
170 fragment float4 fbfetch_test(float4 in [[color(0), raster_order_group(0)]]) {
171 return in * 2;
172 }
173 )";
174 auto lib = MRCTransfer([dev newLibraryWithSource:[NSString stringWithUTF8String:shader]
175 options:nil
176 error:nil]);
177 if (!lib)
178 return false;
179 u32 outpx;
180 bool ok = RenderSinglePixel(dev, //
181 MRCTransfer([lib newFunctionWithName:@"fs_triangle"]), //
182 MRCTransfer([lib newFunctionWithName:@"fbfetch_test"]), //
183 0x11223344, &outpx);
184 if (!ok)
185 return false;
186
187 // Proper fbfetch will double contents, Haswell will return black, and Broadwell will do nothing
188 if (outpx == 0x22446688)
189 return true; // Skylake+
190 else if (outpx == 0x11223344)
191 return false; // Broadwell
192 else
193 return false; // Haswell
194 }
195
196 enum class DetectionResult
197 {
198 Yes,
199 No,
200 Unsure
201 };
202
203 static DetectionResult DetectInvertedIsHelper(id<MTLDevice> dev)
204 {
205 static constexpr const char* shader = R"(
206 vertex float4 fs_triangle(uint vid [[vertex_id]]) {
207 return float4(vid & 1 ? 3 : -1, vid & 2 ? 3 : -1, 0, 1);
208 }
209 fragment float4 is_helper_test() {
210 float val = metal::simd_is_helper_thread() ? 1 : 0.5;
211 return float4(val, metal::dfdx(val) + 0.5, metal::dfdy(val) + 0.5, 0);
212 }
213 )";
214
215 auto lib = MRCTransfer([dev newLibraryWithSource:[NSString stringWithUTF8String:shader]
216 options:nil
217 error:nil]);
218 if (!lib)
219 return DetectionResult::Unsure;
220
221 u32 outpx;
222 bool ok = RenderSinglePixel(dev, //
223 MRCTransfer([lib newFunctionWithName:@"fs_triangle"]), //
224 MRCTransfer([lib newFunctionWithName:@"is_helper_test"]), //
225 0, &outpx);
226
227 // The pixel itself should not be a helper thread (0.5)
228 // The pixels to its right and below should be helper threads (1.0)
229 // Correctly working would therefore be 0.5 for the pixel and (0.5 + 0.5) for the derivatives
230 // Inverted would be 1.0 for the pixel and (-0.5 + 0.5) for the derivatives
231 if (!ok)
232 return DetectionResult::Unsure;
233 if (outpx == 0xffff80)
234 return DetectionResult::No; // Working correctly
235 if (outpx == 0x0000ff)
236 return DetectionResult::Yes; // Inverted
237 WARN_LOG_FMT(VIDEO, "metal::simd_is_helper_thread might be broken! Test shader returned {:06x}!",
238 outpx);
239 return DetectionResult::Unsure;
240 }
241
242 void Metal::Util::PopulateBackendInfoFeatures(const VideoConfig& config, BackendInfo* backend_info,
243 id<MTLDevice> device)
244 {
245 // Initialize DriverDetails first so we can use it later
246 DriverDetails::Vendor vendor = DriverDetails::VENDOR_UNKNOWN;
247 std::string name = [[device name] UTF8String];
248 if (name.contains("NVIDIA"))
249 vendor = DriverDetails::VENDOR_NVIDIA;
250 else if (name.contains("AMD"))
251 vendor = DriverDetails::VENDOR_ATI;
252 else if (name.contains("Intel"))
253 vendor = DriverDetails::VENDOR_INTEL;
254 else if (name.contains("Apple"))
255 vendor = DriverDetails::VENDOR_APPLE;
256 DriverDetails::Init(DriverDetails::API_METAL, vendor, DriverDetails::DRIVER_APPLE, 0.0,
257 DriverDetails::Family::UNKNOWN, std::move(name));
258
259 #if TARGET_OS_OSX
260 backend_info->bSupportsDepthClamp = true;
261 backend_info->bSupportsST3CTextures = true;
262 backend_info->bSupportsBPTCTextures = true;
263 #else
264 backend_info->bSupportsDepthClamp = [device supportsFamily:MTLGPUFamilyApple4];
265
266 bool supports_bcn = false;
267 if (@available(iOS 16.4, *))
268 supports_bcn = [device supportsBCTextureCompression];
269 backend_info->bSupportsST3CTextures = supports_bcn;
270 backend_info->bSupportsBPTCTextures = supports_bcn;
271
272 backend_info->bSupportsFramebufferFetch = true;
273 #endif
274
275 backend_info->AAModes.clear();
276 for (u32 i = 1; i <= 64; i <<= 1)
277 {
278 if ([device supportsTextureSampleCount:i])
279 backend_info->AAModes.push_back(i);
280 }
281
282 switch (config.iManuallyUploadBuffers)
283 {
284 case TriState::Off:
285 g_features.manual_buffer_upload = false;
286 break;
287 case TriState::On:
288 g_features.manual_buffer_upload = true;
289 break;
290 case TriState::Auto:
291 #if TARGET_OS_OSX
292 g_features.manual_buffer_upload = false;
293 if (![device hasUnifiedMemory])
294 g_features.manual_buffer_upload = true;
295 #else
296 // All iOS devices have unified memory
297 g_features.manual_buffer_upload = false;
298 #endif
299 break;
300 }
301
302 g_features.subgroup_ops =
303 [device supportsFamily:MTLGPUFamilyMac2] || [device supportsFamily:MTLGPUFamilyApple7];
304 if (g_features.subgroup_ops)
305 {
306 DetectionResult result = DetectInvertedIsHelper(device);
307 if (result != DetectionResult::Unsure)
308 {
309 bool is_helper_inverted = result == DetectionResult::Yes;
310 if (is_helper_inverted != DriverDetails::HasBug(DriverDetails::BUG_INVERTED_IS_HELPER))
311 DriverDetails::OverrideBug(DriverDetails::BUG_INVERTED_IS_HELPER, is_helper_inverted);
312 }
313 }
314
315 backend_info->bSupportsFramebufferFetch = [device supportsFamily:MTLGPUFamilyApple1];
316 #if TARGET_OS_OSX
317 if (vendor == DriverDetails::VENDOR_INTEL)
318 backend_info->bSupportsFramebufferFetch |= DetectIntelGPUFBFetch(device);
319 #endif
320
321 if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_DYNAMIC_SAMPLER_INDEXING))
322 backend_info->bSupportsDynamicSamplerIndexing = false;
323 }
324
325 // clang-format off
326
327 AbstractTextureFormat Metal::Util::ToAbstract(MTLPixelFormat format)
328 {
329 switch (format)
330 {
331 case MTLPixelFormatRGBA8Unorm: return AbstractTextureFormat::RGBA8;
332 case MTLPixelFormatBGRA8Unorm: return AbstractTextureFormat::BGRA8;
333 case MTLPixelFormatRGB10A2Unorm: return AbstractTextureFormat::RGB10_A2;
334 case MTLPixelFormatRGBA16Float: return AbstractTextureFormat::RGBA16F;
335 case MTLPixelFormatBC1_RGBA: return AbstractTextureFormat::DXT1;
336 case MTLPixelFormatBC2_RGBA: return AbstractTextureFormat::DXT3;
337 case MTLPixelFormatBC3_RGBA: return AbstractTextureFormat::DXT5;
338 case MTLPixelFormatBC7_RGBAUnorm: return AbstractTextureFormat::BPTC;
339 case MTLPixelFormatR16Unorm: return AbstractTextureFormat::R16;
340 case MTLPixelFormatDepth16Unorm: return AbstractTextureFormat::D16;
341 #if TARGET_OS_OSX
342 case MTLPixelFormatDepth24Unorm_Stencil8: return AbstractTextureFormat::D24_S8;
343 #endif
344 case MTLPixelFormatR32Float: return AbstractTextureFormat::R32F;
345 case MTLPixelFormatDepth32Float: return AbstractTextureFormat::D32F;
346 case MTLPixelFormatDepth32Float_Stencil8: return AbstractTextureFormat::D32F_S8;
347 default: return AbstractTextureFormat::Undefined;
348 }
349 }
350
351 // Don't complain about BCn formats requiring iOS 16.4, these are just enum conversions
352 #pragma clang diagnostic push
353 #pragma clang diagnostic ignored "-Wunguarded-availability"
354
355 MTLPixelFormat Metal::Util::FromAbstract(AbstractTextureFormat format)
356 {
357 switch (format)
358 {
359 case AbstractTextureFormat::RGBA8: return MTLPixelFormatRGBA8Unorm;
360 case AbstractTextureFormat::BGRA8: return MTLPixelFormatBGRA8Unorm;
361 case AbstractTextureFormat::RGB10_A2: return MTLPixelFormatRGB10A2Unorm;
362 case AbstractTextureFormat::RGBA16F: return MTLPixelFormatRGBA16Float;
363 case AbstractTextureFormat::DXT1: return MTLPixelFormatBC1_RGBA;
364 case AbstractTextureFormat::DXT3: return MTLPixelFormatBC2_RGBA;
365 case AbstractTextureFormat::DXT5: return MTLPixelFormatBC3_RGBA;
366 case AbstractTextureFormat::BPTC: return MTLPixelFormatBC7_RGBAUnorm;
367 case AbstractTextureFormat::R16: return MTLPixelFormatR16Unorm;
368 case AbstractTextureFormat::D16: return MTLPixelFormatDepth16Unorm;
369 #if TARGET_OS_OSX
370 case AbstractTextureFormat::D24_S8: return MTLPixelFormatDepth24Unorm_Stencil8;
371 #endif
372 case AbstractTextureFormat::R32F: return MTLPixelFormatR32Float;
373 case AbstractTextureFormat::D32F: return MTLPixelFormatDepth32Float;
374 case AbstractTextureFormat::D32F_S8: return MTLPixelFormatDepth32Float_Stencil8;
375 default: return MTLPixelFormatInvalid;
376 }
377 }
378
379 #pragma clang diagnostic pop
380
381 // clang-format on
382
383 // MARK: Shader Translation
384
385 static const std::string_view SHADER_HEADER = R"(
386 // Target GLSL 4.5.
387 #version 450 core
388 // Always available on Metal
389 #extension GL_EXT_shader_8bit_storage : require
390 #extension GL_EXT_shader_16bit_storage : require
391 #extension GL_EXT_shader_explicit_arithmetic_types_int8 : require
392 #extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
393
394 #define ATTRIBUTE_LOCATION(x) layout(location = x)
395 #define FRAGMENT_OUTPUT_LOCATION(x) layout(location = x)
396 #define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y) layout(location = x, index = y)
397 #define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (x - 1))
398 #define SAMPLER_BINDING(x) layout(set = 1, binding = x)
399 #define TEXEL_BUFFER_BINDING(x) layout(set = 1, binding = (x + 8))
400 #define SSBO_BINDING(x) layout(std430, set = 2, binding = x)
401 #define INPUT_ATTACHMENT_BINDING(x, y, z) layout(set = x, binding = y, input_attachment_index = z)
402 #define VARYING_LOCATION(x) layout(location = x)
403 #define FORCE_EARLY_Z layout(early_fragment_tests) in
404
405 // Metal framebuffer fetch helpers.
406 #define FB_FETCH_VALUE subpassLoad(in_ocol0)
407
408 // hlsl to glsl function translation
409 #define API_METAL 1
410 #define float2 vec2
411 #define float3 vec3
412 #define float4 vec4
413 #define uint2 uvec2
414 #define uint3 uvec3
415 #define uint4 uvec4
416 #define int2 ivec2
417 #define int3 ivec3
418 #define int4 ivec4
419 #define frac fract
420 #define lerp mix
421
422 // These were changed in Vulkan
423 #define gl_VertexID gl_VertexIndex
424 #define gl_InstanceID gl_InstanceIndex
425 )";
426 static const std::string_view COMPUTE_SHADER_HEADER = R"(
427 // Target GLSL 4.5.
428 #version 450 core
429 // Always available on Metal
430 #extension GL_EXT_shader_8bit_storage : require
431 #extension GL_EXT_shader_16bit_storage : require
432 #extension GL_EXT_shader_explicit_arithmetic_types_int8 : require
433 #extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
434
435 #define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (x - 1))
436 #define SAMPLER_BINDING(x) layout(set = 1, binding = x)
437 #define SSBO_BINDING(x) layout(std430, set = 2, binding = x)
438 #define IMAGE_BINDING(format, x) layout(format, set = 3, binding = x)
439
440 // hlsl to glsl function translation
441 #define API_METAL 1
442 #define float2 vec2
443 #define float3 vec3
444 #define float4 vec4
445 #define uint2 uvec2
446 #define uint3 uvec3
447 #define uint4 uvec4
448 #define int2 ivec2
449 #define int3 ivec3
450 #define int4 ivec4
451 #define frac fract
452 #define lerp mix
453 )";
454 static const std::string_view SUBGROUP_HELPER_HEADER = R"(
455 #extension GL_KHR_shader_subgroup_basic : enable
456 #extension GL_KHR_shader_subgroup_arithmetic : enable
457 #extension GL_KHR_shader_subgroup_ballot : enable
458
459 #define SUPPORTS_SUBGROUP_REDUCTION 1
460 #define IS_HELPER_INVOCATION gl_HelperInvocation
461 #define IS_FIRST_ACTIVE_INVOCATION (subgroupElect())
462 #define SUBGROUP_MIN(value) value = subgroupMin(value)
463 #define SUBGROUP_MAX(value) value = subgroupMax(value)
464 )";
465
466 static const std::string_view MSL_HEADER =
467 // We know our shader generator leaves unused variables.
468 "#pragma clang diagnostic ignored \"-Wunused-variable\"\n"
469 // These are usually when the compiler doesn't think a switch is exhaustive
470 "#pragma clang diagnostic ignored \"-Wreturn-type\"\n";
471
472 static constexpr std::pair<std::string_view, std::string_view> MSL_FIXUPS[] = {
473 // Force-unroll the lighting loop in ubershaders, which greatly reduces register pressure on AMD
474 {"for (uint chan = 0u; chan < 2u; chan++)",
475 "_Pragma(\"unroll\") for (uint chan = 0u; chan < 2u; chan++)"},
476 };
477
478 static constexpr spirv_cross::MSLResourceBinding
479 MakeResourceBinding(spv::ExecutionModel stage, u32 set, u32 binding, //
480 u32 msl_buffer, u32 msl_texture, u32 msl_sampler)
481 {
482 spirv_cross::MSLResourceBinding resource;
483 resource.stage = stage;
484 resource.desc_set = set;
485 resource.binding = binding;
486 resource.msl_buffer = msl_buffer;
487 resource.msl_texture = msl_texture;
488 resource.msl_sampler = msl_sampler;
489 return resource;
490 }
491
492 std::optional<std::string>
493 Metal::Util::TranslateShaderToMSL(ShaderStage stage, std::string_view source,
494 VideoCommon::ShaderIncluder* shader_includer)
495 {
496 std::string full_source;
497
498 std::string_view header = stage == ShaderStage::Compute ? COMPUTE_SHADER_HEADER : SHADER_HEADER;
499 full_source.reserve(header.size() + SUBGROUP_HELPER_HEADER.size() + source.size());
500
501 full_source.append(header);
502 if (Metal::g_features.subgroup_ops)
503 full_source.append(SUBGROUP_HELPER_HEADER);
504 if (DriverDetails::HasBug(DriverDetails::BUG_INVERTED_IS_HELPER))
505 {
506 full_source.append("#define gl_HelperInvocation !gl_HelperInvocation "
507 "// Work around broken AMD Metal driver\n");
508 }
509 if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_SUBGROUP_OPS_WITH_DISCARD))
510 full_source.append("#define BROKEN_SUBGROUP_WITH_DISCARD 1\n");
511 full_source.append(source);
512
513 std::optional<SPIRV::CodeVector> code;
514 switch (stage)
515 {
516 case ShaderStage::Vertex:
517 code = SPIRV::CompileVertexShader(full_source, APIType::Metal, glslang::EShTargetSpv_1_5,
518 shader_includer);
519 break;
520 case ShaderStage::Geometry:
521 PanicAlertFmt("Tried to compile geometry shader for Metal, but Metal doesn't support them!");
522 break;
523 case ShaderStage::Pixel:
524 code = SPIRV::CompileFragmentShader(full_source, APIType::Metal, glslang::EShTargetSpv_1_5,
525 shader_includer);
526 break;
527 case ShaderStage::Compute:
528 code = SPIRV::CompileComputeShader(full_source, APIType::Metal, glslang::EShTargetSpv_1_5,
529 shader_includer);
530 break;
531 }
532 if (!code.has_value())
533 return std::nullopt;
534
535 // clang-format off
536 static const spirv_cross::MSLResourceBinding resource_bindings[] = {
537 MakeResourceBinding(spv::ExecutionModelVertex, 0, 0, 1, 0, 0), // vs/ubo
538 MakeResourceBinding(spv::ExecutionModelVertex, 0, 1, 1, 0, 0), // vs/ubo
539 MakeResourceBinding(spv::ExecutionModelVertex, 0, 3, 2, 0, 0), // vs/ubo
540 MakeResourceBinding(spv::ExecutionModelVertex, 2, 1, 0, 0, 0), // vs/ssbo
541 MakeResourceBinding(spv::ExecutionModelFragment, 0, 0, 0, 0, 0), // vs/ubo
542 MakeResourceBinding(spv::ExecutionModelFragment, 0, 1, 1, 0, 0), // vs/ubo
543 // Dynamic list initialized below Fragment, 1, N, 0, N, N // ps/samp0-N
544 MakeResourceBinding(spv::ExecutionModelFragment, 2, 0, 2, 0, 0), // ps/ssbo
545 MakeResourceBinding(spv::ExecutionModelGLCompute, 0, 1, 0, 0, 0), // cs/ubo
546 // Dynamic list initialized below GLCompute, 1, N, 0, N, N, // cs/samp0-N
547 MakeResourceBinding(spv::ExecutionModelGLCompute, 2, 0, 2, 0, 0), // cs/ssbo
548 MakeResourceBinding(spv::ExecutionModelGLCompute, 2, 1, 3, 0, 0), // cs/ssbo
549 // Dynamic list initialized below GLCompute, 3, N, 0, N, 0, // cs/img0-N
550 };
551
552 spirv_cross::CompilerMSL::Options options;
553 #if TARGET_OS_OSX
554 options.platform = spirv_cross::CompilerMSL::Options::macOS;
555 #elif TARGET_OS_IOS
556 options.platform = spirv_cross::CompilerMSL::Options::iOS;
557 // Otherwise SPIRV-Cross will try to compile subgroup ops to quad ops instead
558 // (And crash because there's no quad_min or quad_max)
559 options.ios_use_simdgroup_functions = Metal::g_features.subgroup_ops;
560 #else
561 #error What platform is this?
562 #endif
563 // clang-format on
564
565 spirv_cross::CompilerMSL compiler(std::move(*code));
566
567 options.set_msl_version(2, 3);
568 options.use_framebuffer_fetch_subpasses = true;
569 compiler.set_msl_options(options);
570
571 for (auto& binding : resource_bindings)
572 compiler.add_msl_resource_binding(binding);
573 if (stage == ShaderStage::Pixel)
574 {
575 for (u32 i = 0; i < VideoCommon::MAX_PIXEL_SHADER_SAMPLERS; i++) // ps/samp0-N
576 {
577 compiler.add_msl_resource_binding(
578 MakeResourceBinding(spv::ExecutionModelFragment, 1, i, 0, i, i));
579 }
580 }
581 else if (stage == ShaderStage::Compute)
582 {
583 u32 img = 0;
584 u32 smp = 0;
585 for (u32 i = 0; i < VideoCommon::MAX_COMPUTE_SHADER_SAMPLERS; i++) // cs/samp0-N
586 {
587 compiler.add_msl_resource_binding(
588 MakeResourceBinding(spv::ExecutionModelGLCompute, 1, i, 0, img++, smp++));
589 }
590 for (u32 i = 0; i < VideoCommon::MAX_COMPUTE_SHADER_SAMPLERS; i++) // cs/img0-N
591 {
592 compiler.add_msl_resource_binding(
593 MakeResourceBinding(spv::ExecutionModelGLCompute, 3, i, 0, img++, 0));
594 }
595 }
596
597 std::string output(MSL_HEADER);
598 std::string compiled = compiler.compile();
599 std::string_view remaining = compiled;
600 while (!remaining.empty())
601 {
602 // Apply fixups
603 std::string_view piece = remaining;
604 std::string_view fixup_piece = {};
605 size_t next = piece.size();
606 for (const auto& fixup : MSL_FIXUPS)
607 {
608 size_t found = piece.find(fixup.first);
609 if (found == std::string_view::npos)
610 continue;
611 piece = piece.substr(0, found);
612 fixup_piece = fixup.second;
613 next = found + fixup.first.size();
614 }
615 output += piece;
616 output += fixup_piece;
617 remaining = remaining.substr(next);
618 }
619 return output;
620 }