Debian Codegraph @

drivers/metal/rendering_shader_container_metal.mm

raw
1 /**************************************************************************/
2 /* rendering_shader_container_metal.mm */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #import "rendering_shader_container_metal.h"
32
33 #import "metal_utils.h"
34
35 #import "core/io/file_access.h"
36 #import "core/io/marshalls.h"
37 #import "core/templates/fixed_vector.h"
38 #import "servers/rendering/rendering_device.h"
39
40 #include "thirdparty/spirv-reflect/spirv_reflect.h"
41
42 #import <Metal/Metal.h>
43 #import <spirv.hpp>
44 #import <spirv_msl.hpp>
45 #import <spirv_parser.hpp>
46
47 void RenderingShaderContainerMetal::_initialize_toolchain_properties() {
48 if (compiler_props.is_valid()) {
49 return;
50 }
51
52 String sdk;
53 switch (device_profile->platform) {
54 case MetalDeviceProfile::Platform::macOS:
55 sdk = "macosx";
56 break;
57 case MetalDeviceProfile::Platform::iOS:
58 sdk = "iphoneos";
59 break;
60 case MetalDeviceProfile::Platform::visionOS:
61 sdk = "xros";
62 break;
63 }
64
65 Vector<String> parts{ "echo", R"("")", "|", "/usr/bin/xcrun", "-sdk", sdk, "metal", "-E", "-dM", "-x", "metal" };
66
67 switch (device_profile->platform) {
68 case MetalDeviceProfile::Platform::macOS: {
69 parts.push_back("-mtargetos=macos" + device_profile->min_os_version.to_compiler_os_version());
70 break;
71 }
72 case MetalDeviceProfile::Platform::iOS: {
73 parts.push_back("-mtargetos=ios" + device_profile->min_os_version.to_compiler_os_version());
74 break;
75 }
76 case MetalDeviceProfile::Platform::visionOS: {
77 parts.push_back("-mtargetos=xros" + device_profile->min_os_version.to_compiler_os_version());
78 break;
79 }
80 }
81
82 parts.append_array({ "-", "|", "grep", "-E", R"(\"__METAL_VERSION__|__ENVIRONMENT_OS\")" });
83
84 List<String> args = { "-c", String(" ").join(parts) };
85
86 String r_pipe;
87 int exit_code;
88 Error err = OS::get_singleton()->execute("sh", args, &r_pipe, &exit_code, true);
89 ERR_FAIL_COND_MSG(err != OK, "Failed to determine Metal toolchain properties");
90
91 // Parse the lines, which are in the form:
92 //
93 // #define VARNAME VALUE
94 Vector<String> lines = r_pipe.split("\n", false);
95 for (String &line : lines) {
96 Vector<String> name_val = line.trim_prefix("#define ").split(" ");
97 if (name_val.size() != 2) {
98 continue;
99 }
100 if (name_val[0] == "__ENVIRONMENT_OS_VERSION_MIN_REQUIRED__") {
101 compiler_props.os_version_min_required = MinOsVersion((uint32_t)name_val[1].to_int());
102 } else if (name_val[0] == "__METAL_VERSION__") {
103 uint32_t ver = (uint32_t)name_val[1].to_int();
104 uint32_t maj = ver / 100;
105 uint32_t min = (ver % 100) / 10;
106 compiler_props.metal_version = make_msl_version(maj, min);
107 }
108
109 if (compiler_props.is_valid()) {
110 break;
111 }
112 }
113 }
114
115 Error RenderingShaderContainerMetal::compile_metal_source(const char *p_source, const StageData &p_stage_data, Vector<uint8_t> &r_binary_data) {
116 String name(shader_name.ptr());
117 if (name.contains_char(':')) {
118 name = name.replace_char(':', '_');
119 }
120 Error r_error;
121 Ref<FileAccess> source_file = FileAccess::create_temp(FileAccess::ModeFlags::READ_WRITE,
122 name + "_" + itos(p_stage_data.hash.short_sha()),
123 "metal", false, &r_error);
124 ERR_FAIL_COND_V_MSG(r_error != OK, r_error, "Unable to create temporary source file.");
125 if (!source_file->store_buffer((const uint8_t *)p_source, strlen(p_source))) {
126 ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Unable to write temporary source file");
127 }
128 source_file->flush();
129 Ref<FileAccess> result_file = FileAccess::create_temp(FileAccess::ModeFlags::READ_WRITE,
130 name + "_" + itos(p_stage_data.hash.short_sha()),
131 "metallib", false, &r_error);
132
133 ERR_FAIL_COND_V_MSG(r_error != OK, r_error, "Unable to create temporary target file");
134
135 String sdk;
136 switch (device_profile->platform) {
137 case MetalDeviceProfile::Platform::macOS:
138 sdk = "macosx";
139 break;
140 case MetalDeviceProfile::Platform::iOS:
141 sdk = "iphoneos";
142 break;
143 case MetalDeviceProfile::Platform::visionOS:
144 sdk = "xros";
145 break;
146 }
147
148 // Build the .metallib binary.
149 {
150 List<String> args{ "-sdk", sdk, "metal", "-O3" };
151
152 // Compile metal shaders for the minimum supported target instead of the host machine.
153 switch (device_profile->platform) {
154 case MetalDeviceProfile::Platform::macOS: {
155 args.push_back("-mtargetos=macos" + device_profile->min_os_version.to_compiler_os_version());
156 break;
157 }
158 case MetalDeviceProfile::Platform::iOS: {
159 args.push_back("-mtargetos=ios" + device_profile->min_os_version.to_compiler_os_version());
160 break;
161 }
162 case MetalDeviceProfile::Platform::visionOS: {
163 args.push_back("-mtargetos=xros" + device_profile->min_os_version.to_compiler_os_version());
164 break;
165 }
166 }
167
168 if (p_stage_data.is_position_invariant) {
169 args.push_back("-fpreserve-invariance");
170 }
171 args.push_back("-fmetal-math-mode=fast");
172 args.push_back(source_file->get_path_absolute());
173 args.push_back("-o");
174 args.push_back(result_file->get_path_absolute());
175 String r_pipe;
176 int exit_code;
177 Error err = OS::get_singleton()->execute("/usr/bin/xcrun", args, &r_pipe, &exit_code, true);
178 if (!r_pipe.is_empty()) {
179 print_line(r_pipe);
180 }
181 if (err != OK) {
182 ERR_PRINT(vformat("Metal compiler returned error code: %d", err));
183 }
184
185 if (exit_code != 0) {
186 ERR_PRINT(vformat("Metal compiler exited with error code: %d", exit_code));
187 }
188 int len = result_file->get_length();
189 ERR_FAIL_COND_V_MSG(len == 0, ERR_CANT_CREATE, "Metal compiler created empty library");
190 }
191
192 // Strip the source from the binary.
193 {
194 List<String> args{ "-sdk", sdk, "metal-dsymutil", "--remove-source", result_file->get_path_absolute() };
195 String r_pipe;
196 int exit_code;
197 Error err = OS::get_singleton()->execute("/usr/bin/xcrun", args, &r_pipe, &exit_code, true);
198 if (!r_pipe.is_empty()) {
199 print_line(r_pipe);
200 }
201 if (err != OK) {
202 ERR_PRINT(vformat("metal-dsymutil tool returned error code: %d", err));
203 }
204
205 if (exit_code != 0) {
206 ERR_PRINT(vformat("metal-dsymutil Compiler exited with error code: %d", exit_code));
207 }
208 int len = result_file->get_length();
209 ERR_FAIL_COND_V_MSG(len == 0, ERR_CANT_CREATE, "metal-dsymutil tool created empty library");
210 }
211
212 r_binary_data = result_file->get_buffer(result_file->get_length());
213
214 return OK;
215 }
216
217 #pragma clang diagnostic push
218 #pragma clang diagnostic ignored "-Wunguarded-availability"
219
220 static spv::ExecutionModel SHADER_STAGE_REMAP[RDD::SHADER_STAGE_MAX] = {
221 spv::ExecutionModelVertex, // RDD::SHADER_STAGE_VERTEX
222 spv::ExecutionModelFragment, // RDD::SHADER_STAGE_FRAGMENT
223 spv::ExecutionModelTessellationControl, // RDD::SHADER_STAGE_TESSELATION_CONTROL
224 spv::ExecutionModelTessellationEvaluation, // RDD::SHADER_STAGE_TESSELATION_EVALUATION
225 spv::ExecutionModelGLCompute, // RDD::SHADER_STAGE_COMPUTE
226 };
227
228 spv::ExecutionModel get_stage(uint32_t p_stages_mask, RDD::ShaderStage p_stage) {
229 if (p_stages_mask & (1 << p_stage)) {
230 return SHADER_STAGE_REMAP[p_stage];
231 }
232 return spv::ExecutionModel::ExecutionModelMax;
233 }
234
235 spv::ExecutionModel map_stage(RDD::ShaderStage p_stage) {
236 return SHADER_STAGE_REMAP[p_stage];
237 }
238
239 bool RenderingShaderContainerMetal::_set_code_from_spirv(const ReflectShader &p_shader) {
240 using namespace spirv_cross;
241 using spirv_cross::CompilerMSL;
242 using spirv_cross::Resource;
243
244 const LocalVector<ReflectShaderStage> &p_spirv = p_shader.shader_stages;
245
246 if (export_mode) {
247 _initialize_toolchain_properties();
248 }
249
250 // initialize Metal-specific reflection data
251 shaders.resize(p_spirv.size());
252 mtl_shaders.resize(p_spirv.size());
253 mtl_reflection_binding_set_uniforms_data.resize(reflection_binding_set_uniforms_data.size());
254
255 mtl_reflection_data.set_needs_view_mask_buffer(reflection_data.has_multiview);
256 mtl_reflection_data.profile = *device_profile;
257
258 CompilerMSL::Options msl_options{};
259
260 // Determine Metal language version.
261 uint32_t msl_version = 0;
262 {
263 if (export_mode && compiler_props.is_valid()) {
264 // Use the properties determined by the toolchain and minimum OS version.
265 msl_version = compiler_props.metal_version;
266 mtl_reflection_data.os_min_version = compiler_props.os_version_min_required;
267 } else {
268 msl_version = device_profile->features.msl_version;
269 mtl_reflection_data.os_min_version = MinOsVersion();
270 }
271 uint32_t msl_ver_maj = 0;
272 uint32_t msl_ver_min = 0;
273 parse_msl_version(msl_version, msl_ver_maj, msl_ver_min);
274 msl_options.set_msl_version(msl_ver_maj, msl_ver_min);
275 mtl_reflection_data.msl_version = msl_version;
276 }
277
278 msl_options.platform = device_profile->platform == MetalDeviceProfile::Platform::macOS ? CompilerMSL::Options::macOS : CompilerMSL::Options::iOS;
279
280 if (device_profile->platform == MetalDeviceProfile::Platform::iOS) {
281 msl_options.ios_use_simdgroup_functions = device_profile->features.simdPermute;
282 msl_options.ios_support_base_vertex_instance = true;
283 }
284
285 // We don't currently allow argument buffers when using dynamic buffers as
286 // the current implementation does not update the argument buffer each time
287 // the dynamic buffer changes. This is a future TODO.
288 bool argument_buffers_allowed = get_shader_reflection().has_dynamic_buffers == false;
289
290 if (device_profile->features.use_argument_buffers && argument_buffers_allowed) {
291 msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier2;
292 msl_options.argument_buffers = true;
293 mtl_reflection_data.set_uses_argument_buffers(true);
294 } else {
295 msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier1;
296 // Tier 1 argument buffers don't support writable textures, so we disable them completely.
297 msl_options.argument_buffers = false;
298 mtl_reflection_data.set_uses_argument_buffers(false);
299 }
300 msl_options.force_active_argument_buffer_resources = true;
301 msl_options.pad_argument_buffer_resources = true;
302 msl_options.texture_buffer_native = true; // Enable texture buffer support.
303 msl_options.use_framebuffer_fetch_subpasses = false;
304 msl_options.pad_fragment_output_components = true;
305 msl_options.r32ui_alignment_constant_id = R32UI_ALIGNMENT_CONSTANT_ID;
306 msl_options.agx_manual_cube_grad_fixup = true;
307 if (reflection_data.has_multiview) {
308 msl_options.multiview = true;
309 msl_options.multiview_layered_rendering = true;
310 msl_options.view_mask_buffer_index = VIEW_MASK_BUFFER_INDEX;
311 }
312 if (msl_version >= MSL_VERSION_32) {
313 // All 3.2+ versions support device coherence, so we can disable texture fences.
314 msl_options.readwrite_texture_fences = false;
315 }
316
317 CompilerGLSL::Options options{};
318 options.vertex.flip_vert_y = true;
319 #if DEV_ENABLED
320 options.emit_line_directives = true;
321 #endif
322
323 // Assign MSL bindings for all the descriptor sets.
324 typedef std::pair<MSLResourceBinding, uint32_t> MSLBindingInfo;
325 LocalVector<MSLBindingInfo> spirv_bindings;
326 MSLResourceBinding push_constant_resource_binding;
327 {
328 enum IndexType {
329 Texture,
330 Buffer,
331 Sampler,
332 Max,
333 };
334
335 uint32_t dset_count = p_shader.uniform_sets.size();
336 uint32_t size = reflection_binding_set_uniforms_data.size();
337 spirv_bindings.resize(size);
338
339 uint32_t indices[IndexType::Max] = { 0 };
340 auto next_index = [&indices](IndexType p_t, uint32_t p_stride) -> uint32_t {
341 uint32_t v = indices[p_t];
342 indices[p_t] += p_stride;
343 return v;
344 };
345
346 uint32_t idx_dset = 0;
347 MSLBindingInfo *iter = spirv_bindings.ptr();
348 UniformData *found = mtl_reflection_binding_set_uniforms_data.ptrw();
349 UniformData::IndexType shader_index_type = msl_options.argument_buffers ? UniformData::IndexType::ARG : UniformData::IndexType::SLOT;
350
351 for (const ReflectDescriptorSet &dset : p_shader.uniform_sets) {
352 // Reset the index count for each descriptor set, as this is an index in to the argument table.
353 uint32_t next_arg_buffer_index = 0;
354 auto next_arg_index = [&next_arg_buffer_index](uint32_t p_stride) -> uint32_t {
355 uint32_t v = next_arg_buffer_index;
356 next_arg_buffer_index += p_stride;
357 return v;
358 };
359
360 for (const ReflectUniform &uniform : dset) {
361 const SpvReflectDescriptorBinding &binding = uniform.get_spv_reflect();
362
363 found->active_stages = uniform.stages;
364
365 RD::UniformType type = RD::UniformType(uniform.type);
366 uint32_t binding_stride = 1; // If this is an array, stride will be the length of the array.
367 if (uniform.length > 1) {
368 switch (type) {
369 case RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC:
370 case RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC:
371 case RDC::UNIFORM_TYPE_UNIFORM_BUFFER:
372 case RDC::UNIFORM_TYPE_STORAGE_BUFFER:
373 // Buffers's length is its size, in bytes, so there is no stride.
374 break;
375 default: {
376 binding_stride = uniform.length;
377 found->array_length = uniform.length;
378 } break;
379 }
380 }
381
382 // Determine access type.
383 switch (binding.descriptor_type) {
384 case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
385 if (!(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE)) {
386 if (!(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_READABLE)) {
387 found->access = MTLBindingAccessReadWrite;
388 } else {
389 found->access = MTLBindingAccessWriteOnly;
390 }
391 }
392 } break;
393 case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
394 case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
395 if (!(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE)) {
396 if (!(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_READABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_READABLE)) {
397 found->access = MTLBindingAccessReadWrite;
398 } else {
399 found->access = MTLBindingAccessWriteOnly;
400 }
401 }
402 } break;
403 default:
404 break;
405 }
406
407 switch (found->access) {
408 case MTLBindingAccessReadOnly:
409 found->usage = MTLResourceUsageRead;
410 break;
411 case MTLBindingAccessWriteOnly:
412 found->usage = MTLResourceUsageWrite;
413 break;
414 case MTLBindingAccessReadWrite:
415 found->usage = MTLResourceUsageRead | MTLResourceUsageWrite;
416 break;
417 }
418
419 iter->second = uniform.stages;
420 MSLResourceBinding &rb = iter->first;
421 rb.desc_set = idx_dset;
422 rb.binding = uniform.binding;
423 rb.count = binding_stride;
424
425 switch (type) {
426 case RDC::UNIFORM_TYPE_SAMPLER: {
427 found->data_type = MTLDataTypeSampler;
428 found->get_indexes(UniformData::IndexType::SLOT).sampler = next_index(Sampler, binding_stride);
429 found->get_indexes(UniformData::IndexType::ARG).sampler = next_arg_index(binding_stride);
430
431 rb.basetype = SPIRType::BaseType::Sampler;
432
433 } break;
434 case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE:
435 case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
436 found->data_type = MTLDataTypeTexture;
437 found->get_indexes(UniformData::IndexType::SLOT).texture = next_index(Texture, binding_stride);
438 found->get_indexes(UniformData::IndexType::SLOT).sampler = next_index(Sampler, binding_stride);
439 found->get_indexes(UniformData::IndexType::ARG).texture = next_arg_index(binding_stride);
440 found->get_indexes(UniformData::IndexType::ARG).sampler = next_arg_index(binding_stride);
441 rb.basetype = SPIRType::BaseType::SampledImage;
442 } break;
443 case RDC::UNIFORM_TYPE_TEXTURE:
444 case RDC::UNIFORM_TYPE_IMAGE:
445 case RDC::UNIFORM_TYPE_TEXTURE_BUFFER: {
446 found->data_type = MTLDataTypeTexture;
447 found->get_indexes(UniformData::IndexType::SLOT).texture = next_index(Texture, binding_stride);
448 found->get_indexes(UniformData::IndexType::ARG).texture = next_arg_index(binding_stride);
449 rb.basetype = SPIRType::BaseType::Image;
450 } break;
451 case RDC::UNIFORM_TYPE_IMAGE_BUFFER:
452 CRASH_NOW_MSG("Unimplemented!"); // TODO.
453 break;
454 case RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC:
455 case RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC:
456 case RDC::UNIFORM_TYPE_UNIFORM_BUFFER:
457 case RDC::UNIFORM_TYPE_STORAGE_BUFFER: {
458 found->data_type = MTLDataTypePointer;
459 found->get_indexes(UniformData::IndexType::SLOT).buffer = next_index(Buffer, binding_stride);
460 found->get_indexes(UniformData::IndexType::ARG).buffer = next_arg_index(binding_stride);
461 rb.basetype = SPIRType::BaseType::Void;
462 } break;
463 case RDC::UNIFORM_TYPE_INPUT_ATTACHMENT: {
464 found->data_type = MTLDataTypeTexture;
465 found->get_indexes(UniformData::IndexType::SLOT).texture = next_index(Texture, binding_stride);
466 found->get_indexes(UniformData::IndexType::ARG).texture = next_arg_index(binding_stride);
467 rb.basetype = SPIRType::BaseType::Image;
468 } break;
469 case RDC::UNIFORM_TYPE_MAX:
470 default:
471 CRASH_NOW_MSG("Unreachable");
472 }
473
474 // Specify the MSL resource bindings based on how the binding mode used by the shader.
475 rb.msl_buffer = found->get_indexes(shader_index_type).buffer;
476 rb.msl_texture = found->get_indexes(shader_index_type).texture;
477 rb.msl_sampler = found->get_indexes(shader_index_type).sampler;
478
479 if (found->data_type == MTLDataTypeTexture) {
480 const SpvReflectImageTraits &image = uniform.get_spv_reflect().image;
481
482 switch (image.dim) {
483 case SpvDim1D: {
484 if (image.arrayed) {
485 found->texture_type = MTLTextureType1DArray;
486 } else {
487 found->texture_type = MTLTextureType1D;
488 }
489 } break;
490 case SpvDimSubpassData:
491 case SpvDim2D: {
492 if (image.arrayed && image.ms) {
493 found->texture_type = MTLTextureType2DMultisampleArray;
494 } else if (image.arrayed) {
495 found->texture_type = MTLTextureType2DArray;
496 } else if (image.ms) {
497 found->texture_type = MTLTextureType2DMultisample;
498 } else {
499 found->texture_type = MTLTextureType2D;
500 }
501 } break;
502 case SpvDim3D: {
503 found->texture_type = MTLTextureType3D;
504 } break;
505 case SpvDimCube: {
506 if (image.arrayed) {
507 found->texture_type = MTLTextureTypeCubeArray;
508 } else {
509 found->texture_type = MTLTextureTypeCube;
510 }
511 } break;
512 case SpvDimRect: {
513 // Ignored.
514 } break;
515 case SpvDimBuffer: {
516 found->texture_type = MTLTextureTypeTextureBuffer;
517 } break;
518 case SpvDimTileImageDataEXT: {
519 // Godot does not use this extension.
520 // See: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_shader_tile_image.html
521 } break;
522 case SpvDimMax: {
523 // Add all enumerations to silence the compiler warning
524 // and generate future warnings, should a new one be added.
525 } break;
526 }
527 }
528
529 iter++;
530 found++;
531 }
532 idx_dset++;
533 }
534
535 if (reflection_data.push_constant_size > 0) {
536 push_constant_resource_binding.desc_set = ResourceBindingPushConstantDescriptorSet;
537 push_constant_resource_binding.basetype = SPIRType::BaseType::Void;
538 if (msl_options.argument_buffers) {
539 push_constant_resource_binding.msl_buffer = dset_count;
540 } else {
541 push_constant_resource_binding.msl_buffer = next_index(Buffer, 1);
542 }
543 mtl_reflection_data.push_constant_binding = push_constant_resource_binding.msl_buffer;
544 }
545 }
546
547 for (uint32_t i = 0; i < p_spirv.size(); i++) {
548 StageData &stage_data = mtl_shaders.write[i];
549 const ReflectShaderStage &v = p_spirv[i];
550 RD::ShaderStage stage = v.shader_stage;
551 Span<uint32_t> spirv = v.spirv();
552 Parser parser(spirv.ptr(), spirv.size());
553 try {
554 parser.parse();
555 } catch (CompilerError &e) {
556 ERR_FAIL_V_MSG(false, "Failed to parse IR at stage " + String(RD::SHADER_STAGE_NAMES[stage]) + ": " + e.what());
557 }
558
559 CompilerMSL compiler(std::move(parser.get_parsed_ir()));
560 compiler.set_msl_options(msl_options);
561 compiler.set_common_options(options);
562
563 spv::ExecutionModel execution_model = map_stage(stage);
564 for (uint32_t jj = 0; jj < spirv_bindings.size(); jj++) {
565 MSLResourceBinding &rb = spirv_bindings.ptr()[jj].first;
566 rb.stage = execution_model;
567 compiler.add_msl_resource_binding(rb);
568 }
569
570 if (push_constant_resource_binding.desc_set == ResourceBindingPushConstantDescriptorSet) {
571 push_constant_resource_binding.stage = execution_model;
572 compiler.add_msl_resource_binding(push_constant_resource_binding);
573 }
574
575 std::unordered_set<VariableID> active = compiler.get_active_interface_variables();
576 ShaderResources resources = compiler.get_shader_resources();
577
578 std::string source;
579 try {
580 source = compiler.compile();
581 } catch (CompilerError &e) {
582 ERR_FAIL_V_MSG(false, "Failed to compile stage " + String(RD::SHADER_STAGE_NAMES[stage]) + ": " + e.what());
583 }
584
585 ERR_FAIL_COND_V_MSG(compiler.get_entry_points_and_stages().size() != 1, false, "Expected a single entry point and stage.");
586
587 SmallVector<EntryPoint> entry_pts_stages = compiler.get_entry_points_and_stages();
588 EntryPoint &entry_point_stage = entry_pts_stages.front();
589 SPIREntryPoint &entry_point = compiler.get_entry_point(entry_point_stage.name, entry_point_stage.execution_model);
590
591 for (auto ext : compiler.get_declared_extensions()) {
592 if (ext == "SPV_KHR_non_semantic_info" || ext == "SPV_KHR_printf") {
593 mtl_reflection_data.set_needs_debug_logging(true);
594 break;
595 }
596 }
597
598 if (!resources.stage_inputs.empty()) {
599 for (Resource const &res : resources.stage_inputs) {
600 uint32_t binding = compiler.get_automatic_msl_resource_binding(res.id);
601 if (binding != (uint32_t)-1) {
602 stage_data.vertex_input_binding_mask |= 1 << binding;
603 }
604 }
605 }
606
607 stage_data.is_position_invariant = compiler.is_position_invariant();
608 stage_data.supports_fast_math = !entry_point.flags.get(spv::ExecutionModeSignedZeroInfNanPreserve);
609 stage_data.hash = SHA256Digest(source.c_str(), source.length());
610 stage_data.source_size = source.length();
611 ::Vector<uint8_t> binary_data;
612 binary_data.resize(stage_data.source_size);
613 memcpy(binary_data.ptrw(), source.c_str(), stage_data.source_size);
614
615 if (export_mode) {
616 if (compiler_props.is_valid()) {
617 // Try to compile the Metal source code.
618 ::Vector<uint8_t> library_data;
619 Error compile_err = compile_metal_source(source.c_str(), stage_data, library_data);
620 if (compile_err == OK) {
621 // If we successfully compiled to a `.metallib`, there are greater restrictions on target platforms,
622 // so we must update the properties.
623 stage_data.library_size = library_data.size();
624 binary_data.resize(stage_data.source_size + stage_data.library_size);
625 memcpy(binary_data.ptrw() + stage_data.source_size, library_data.ptr(), stage_data.library_size);
626 }
627 } else {
628 WARN_PRINT_ONCE("Metal shader baking limited to SPIR-V: Unable to determine toolchain properties to compile .metallib");
629 }
630 }
631
632 uint32_t binary_data_size = binary_data.size();
633 Shader &shader = shaders.write[i];
634 shader.shader_stage = stage;
635 shader.code_decompressed_size = binary_data_size;
636 shader.code_compressed_bytes.resize(binary_data_size);
637
638 uint32_t compressed_size = 0;
639 bool compressed = compress_code(binary_data.ptr(), binary_data_size, shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);
640 ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", i));
641
642 shader.code_compressed_bytes.resize(compressed_size);
643 }
644
645 return true;
646 }
647
648 #pragma clang diagnostic pop
649
650 uint32_t RenderingShaderContainerMetal::_to_bytes_reflection_extra_data(uint8_t *p_bytes) const {
651 if (p_bytes != nullptr) {
652 *(HeaderData *)p_bytes = mtl_reflection_data;
653 }
654 return sizeof(HeaderData);
655 }
656
657 uint32_t RenderingShaderContainerMetal::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
658 if (p_bytes != nullptr) {
659 *(UniformData *)p_bytes = mtl_reflection_binding_set_uniforms_data[p_index];
660 }
661 return sizeof(UniformData);
662 }
663
664 uint32_t RenderingShaderContainerMetal::_to_bytes_shader_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
665 if (p_bytes != nullptr) {
666 *(StageData *)p_bytes = mtl_shaders[p_index];
667 }
668 return sizeof(StageData);
669 }
670
671 uint32_t RenderingShaderContainerMetal::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {
672 mtl_reflection_data = *(HeaderData *)p_bytes;
673 return sizeof(HeaderData);
674 }
675
676 uint32_t RenderingShaderContainerMetal::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {
677 mtl_reflection_binding_set_uniforms_data.resize(reflection_binding_set_uniforms_data.size());
678 return 0;
679 }
680
681 uint32_t RenderingShaderContainerMetal::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
682 mtl_reflection_binding_set_uniforms_data.ptrw()[p_index] = *(UniformData *)p_bytes;
683 return sizeof(UniformData);
684 }
685
686 uint32_t RenderingShaderContainerMetal::_from_bytes_shader_extra_data_start(const uint8_t *p_bytes) {
687 mtl_shaders.resize(shaders.size());
688 return 0;
689 }
690
691 uint32_t RenderingShaderContainerMetal::_from_bytes_shader_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
692 mtl_shaders.ptrw()[p_index] = *(StageData *)p_bytes;
693 return sizeof(StageData);
694 }
695
696 RenderingShaderContainerMetal::MetalShaderReflection RenderingShaderContainerMetal::get_metal_shader_reflection() const {
697 MetalShaderReflection res;
698
699 uint32_t uniform_set_count = reflection_binding_set_uniforms_count.size();
700 uint32_t start = 0;
701 res.uniform_sets.resize(uniform_set_count);
702 for (uint32_t i = 0; i < uniform_set_count; i++) {
703 Vector<UniformData> &set = res.uniform_sets.ptrw()[i];
704 uint32_t count = reflection_binding_set_uniforms_count.get(i);
705 set.resize(count);
706 memcpy(set.ptrw(), &mtl_reflection_binding_set_uniforms_data.ptr()[start], count * sizeof(UniformData));
707 start += count;
708 }
709
710 return res;
711 }
712
713 uint32_t RenderingShaderContainerMetal::_format() const {
714 return 0x42424242;
715 }
716
717 uint32_t RenderingShaderContainerMetal::_format_version() const {
718 return FORMAT_VERSION;
719 }
720
721 Ref<RenderingShaderContainer> RenderingShaderContainerFormatMetal::create_container() const {
722 Ref<RenderingShaderContainerMetal> result;
723 result.instantiate();
724 result->set_export_mode(export_mode);
725 result->set_device_profile(device_profile);
726 return result;
727 }
728
729 RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatMetal::get_shader_language_version() const {
730 return SHADER_LANGUAGE_VULKAN_VERSION_1_1;
731 }
732
733 RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatMetal::get_shader_spirv_version() const {
734 return SHADER_SPIRV_VERSION_1_6;
735 }
736
737 RenderingShaderContainerFormatMetal::RenderingShaderContainerFormatMetal(const MetalDeviceProfile *p_device_profile, bool p_export) :
738 export_mode(p_export), device_profile(p_device_profile) {
739 }
740
741 String MinOsVersion::to_compiler_os_version() const {
742 if (version == UINT32_MAX) {
743 return "";
744 }
745
746 uint32_t major = version / 10000;
747 uint32_t minor = (version % 10000) / 100;
748 return vformat("%d.%d", major, minor);
749 }
750
751 MinOsVersion::MinOsVersion(const String &p_version) {
752 int pos = p_version.find_char('.');
753 if (pos > 0) {
754 version = (uint32_t)(p_version.substr(0, pos).to_int() * 10000 +
755 p_version.substr(pos + 1).to_int() * 100);
756 } else {
757 version = (uint32_t)(p_version.to_int() * 10000);
758 }
759
760 if (version == 0) {
761 version = UINT32_MAX;
762 }
763 }