| Flutter Impeller |

reflector.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/105732
6
7 #include "impeller/compiler/reflector.h"
8
9 #include <atomic>
10 #include <optional>
11 #include <set>
12 #include <sstream>
13
14 #include "flutter/fml/logging.h"
15 #include "fml/backtrace.h"
16 #include "impeller/base/strings.h"
17 #include "impeller/base/validation.h"
18 #include "impeller/compiler/code_gen_template.h"
19 #include "impeller/compiler/shader_bundle_data.h"
20 #include "impeller/compiler/types.h"
21 #include "impeller/compiler/uniform_sorter.h"
22 #include "impeller/compiler/utilities.h"
23 #include "impeller/core/runtime_types.h"
24 #include "impeller/geometry/half.h"
25 #include "impeller/geometry/matrix.h"
26 #include "impeller/geometry/scalar.h"
27 #include "impeller/runtime_stage/runtime_stage.h"
28 #include "spirv_common.hpp"
29
30 namespace impeller {
31 namespace compiler {
32
33 static std::string ExecutionModelToString(spv::ExecutionModel model) {
34 switch (model) {
35 case spv::ExecutionModel::ExecutionModelVertex:
36 return "vertex";
37 case spv::ExecutionModel::ExecutionModelFragment:
38 return "fragment";
39 case spv::ExecutionModel::ExecutionModelGLCompute:
40 return "compute";
41 default:
42 return "unsupported";
43 }
44 }
45
46 static std::string StringToShaderStage(const std::string& str) {
47 if (str == "vertex") {
48 return "ShaderStage::kVertex";
49 }
50
51 if (str == "fragment") {
52 return "ShaderStage::kFragment";
53 }
54
55 if (str == "compute") {
56 return "ShaderStage::kCompute";
57 }
58
59 return "ShaderStage::kUnknown";
60 }
61
62 Reflector::Reflector(Options options,
63 const std::shared_ptr<const spirv_cross::ParsedIR>& ir,
64 const std::shared_ptr<fml::Mapping>& shader_data,
65 const CompilerBackend& compiler)
66 : options_(std::move(options)),
67 ir_(ir),
68 shader_data_(shader_data),
69 compiler_(compiler) {
70 if (!ir_ || !compiler_) {
71 return;
72 }
73
74 if (auto template_arguments = GenerateTemplateArguments();
75 template_arguments.has_value()) {
76 template_arguments_ =
77 std::make_unique<nlohmann::json>(std::move(template_arguments.value()));
78 } else {
79 return;
80 }
81
82 reflection_header_ = GenerateReflectionHeader();
83 if (!reflection_header_) {
84 return;
85 }
86
87 reflection_cc_ = GenerateReflectionCC();
88 if (!reflection_cc_) {
89 return;
90 }
91
92 runtime_stage_shader_ = GenerateRuntimeStageData();
93
94 shader_bundle_data_ = GenerateShaderBundleData();
95 if (!shader_bundle_data_) {
96 return;
97 }
98
99 is_valid_ = true;
100 }
101
102 Reflector::~Reflector() = default;
103
104 bool Reflector::IsValid() const {
105 return is_valid_;
106 }
107
108 std::shared_ptr<fml::Mapping> Reflector::GetReflectionJSON() const {
109 if (!is_valid_) {
110 return nullptr;
111 }
112
113 auto json_string =
114 std::make_shared<std::string>(template_arguments_->dump(2u));
115
116 return std::make_shared<fml::NonOwnedMapping>(
117 reinterpret_cast<const uint8_t*>(json_string->data()),
118 json_string->size(), [json_string](auto, auto) {});
119 }
120
121 std::shared_ptr<fml::Mapping> Reflector::GetReflectionHeader() const {
122 return reflection_header_;
123 }
124
125 std::shared_ptr<fml::Mapping> Reflector::GetReflectionCC() const {
126 return reflection_cc_;
127 }
128
129 std::shared_ptr<RuntimeStageData::Shader> Reflector::GetRuntimeStageShaderData()
130 const {
131 return runtime_stage_shader_;
132 }
133
134 std::shared_ptr<ShaderBundleData> Reflector::GetShaderBundleData() const {
135 return shader_bundle_data_;
136 }
137
138 std::optional<nlohmann::json> Reflector::GenerateTemplateArguments() const {
139 nlohmann::json root;
140
141 const auto& entrypoints = compiler_->get_entry_points_and_stages();
142 if (entrypoints.size() != 1) {
143 VALIDATION_LOG << "Incorrect number of entrypoints in the shader. Found "
144 << entrypoints.size() << " but expected 1.";
145 return std::nullopt;
146 }
147
148 auto execution_model = entrypoints.front().execution_model;
149 {
150 root["entrypoint"] = options_.entry_point_name;
151 root["shader_name"] = options_.shader_name;
152 root["shader_stage"] = ExecutionModelToString(execution_model);
153 root["header_file_name"] = options_.header_file_name;
154 }
155
156 const auto shader_resources = compiler_->get_shader_resources();
157
158 // Subpass Inputs.
159 {
160 auto& subpass_inputs = root["subpass_inputs"] = nlohmann::json::array_t{};
161 if (auto subpass_inputs_json =
162 ReflectResources(shader_resources.subpass_inputs);
163 subpass_inputs_json.has_value()) {
164 for (auto subpass_input : subpass_inputs_json.value()) {
165 subpass_input["descriptor_type"] = "DescriptorType::kInputAttachment";
166 subpass_inputs.emplace_back(std::move(subpass_input));
167 }
168 } else {
169 return std::nullopt;
170 }
171 }
172
173 // Uniform and storage buffers.
174 {
175 auto& buffers = root["buffers"] = nlohmann::json::array_t{};
176 if (auto uniform_buffers_json =
177 ReflectResources(shader_resources.uniform_buffers);
178 uniform_buffers_json.has_value()) {
179 for (auto uniform_buffer : uniform_buffers_json.value()) {
180 uniform_buffer["descriptor_type"] = "DescriptorType::kUniformBuffer";
181 buffers.emplace_back(std::move(uniform_buffer));
182 }
183 } else {
184 return std::nullopt;
185 }
186 if (auto storage_buffers_json =
187 ReflectResources(shader_resources.storage_buffers);
188 storage_buffers_json.has_value()) {
189 for (auto uniform_buffer : storage_buffers_json.value()) {
190 uniform_buffer["descriptor_type"] = "DescriptorType::kStorageBuffer";
191 buffers.emplace_back(std::move(uniform_buffer));
192 }
193 } else {
194 return std::nullopt;
195 }
196 }
197
198 {
199 auto& stage_inputs = root["stage_inputs"] = nlohmann::json::array_t{};
200 if (auto stage_inputs_json = ReflectResources(
201 shader_resources.stage_inputs,
202 /*compute_offsets=*/execution_model == spv::ExecutionModelVertex);
203 stage_inputs_json.has_value()) {
204 stage_inputs = std::move(stage_inputs_json.value());
205 } else {
206 return std::nullopt;
207 }
208 }
209
210 {
211 auto combined_sampled_images =
212 ReflectResources(shader_resources.sampled_images);
213 auto images = ReflectResources(shader_resources.separate_images);
214 auto samplers = ReflectResources(shader_resources.separate_samplers);
215 if (!combined_sampled_images.has_value() || !images.has_value() ||
216 !samplers.has_value()) {
217 return std::nullopt;
218 }
219 auto& sampled_images = root["sampled_images"] = nlohmann::json::array_t{};
220 for (auto value : combined_sampled_images.value()) {
221 value["descriptor_type"] = "DescriptorType::kSampledImage";
222 sampled_images.emplace_back(std::move(value));
223 }
224 for (auto value : images.value()) {
225 value["descriptor_type"] = "DescriptorType::kImage";
226 sampled_images.emplace_back(std::move(value));
227 }
228 for (auto value : samplers.value()) {
229 value["descriptor_type"] = "DescriptorType::kSampledSampler";
230 sampled_images.emplace_back(std::move(value));
231 }
232 }
233
234 if (auto stage_outputs = ReflectResources(shader_resources.stage_outputs);
235 stage_outputs.has_value()) {
236 root["stage_outputs"] = std::move(stage_outputs.value());
237 } else {
238 return std::nullopt;
239 }
240
241 {
242 auto& struct_definitions = root["struct_definitions"] =
243 nlohmann::json::array_t{};
244 if (entrypoints.front().execution_model ==
245 spv::ExecutionModel::ExecutionModelVertex &&
246 !shader_resources.stage_inputs.empty()) {
247 if (auto struc =
248 ReflectPerVertexStructDefinition(shader_resources.stage_inputs);
249 struc.has_value()) {
250 struct_definitions.emplace_back(EmitStructDefinition(struc.value()));
251 } else {
252 // If there are stage inputs, it is an error to not generate a per
253 // vertex data struct for a vertex like shader stage.
254 return std::nullopt;
255 }
256 }
257
258 std::set<spirv_cross::ID> known_structs;
259 ir_->for_each_typed_id<spirv_cross::SPIRType>(
260 [&](uint32_t, const spirv_cross::SPIRType& type) {
261 if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) {
262 return;
263 }
264 // Skip structs that do not have layout offset decorations.
265 // These structs are used internally within the shader and are not
266 // part of the shader's interface.
267 for (size_t i = 0; i < type.member_types.size(); i++) {
268 if (!compiler_->has_member_decoration(type.self, i,
269 spv::DecorationOffset)) {
270 return;
271 }
272 }
273 if (known_structs.find(type.self) != known_structs.end()) {
274 // Iterating over types this way leads to duplicates which may cause
275 // duplicate struct definitions.
276 return;
277 }
278 known_structs.insert(type.self);
279 if (auto struc = ReflectStructDefinition(type.self);
280 struc.has_value()) {
281 struct_definitions.emplace_back(
282 EmitStructDefinition(struc.value()));
283 }
284 });
285 }
286
287 root["bind_prototypes"] =
288 EmitBindPrototypes(shader_resources, execution_model);
289
290 return root;
291 }
292
293 std::shared_ptr<fml::Mapping> Reflector::GenerateReflectionHeader() const {
294 return InflateTemplate(kReflectionHeaderTemplate);
295 }
296
297 std::shared_ptr<fml::Mapping> Reflector::GenerateReflectionCC() const {
298 return InflateTemplate(kReflectionCCTemplate);
299 }
300
301 static std::optional<RuntimeStageBackend> GetRuntimeStageBackend(
302 TargetPlatform target_platform) {
303 switch (target_platform) {
304 case TargetPlatform::kUnknown:
305 case TargetPlatform::kMetalDesktop:
306 case TargetPlatform::kMetalIOS:
307 case TargetPlatform::kOpenGLES:
308 case TargetPlatform::kOpenGLDesktop:
309 case TargetPlatform::kVulkan:
310 return std::nullopt;
311 case TargetPlatform::kRuntimeStageMetal:
312 return RuntimeStageBackend::kMetal;
313 case TargetPlatform::kRuntimeStageGLES:
314 return RuntimeStageBackend::kOpenGLES;
315 case TargetPlatform::kRuntimeStageVulkan:
316 return RuntimeStageBackend::kVulkan;
317 case TargetPlatform::kSkSL:
318 return RuntimeStageBackend::kSkSL;
319 }
320 FML_UNREACHABLE();
321 }
322
323 std::shared_ptr<RuntimeStageData::Shader> Reflector::GenerateRuntimeStageData()
324 const {
325 auto backend = GetRuntimeStageBackend(options_.target_platform);
326 if (!backend.has_value()) {
327 return nullptr;
328 }
329
330 const auto& entrypoints = compiler_->get_entry_points_and_stages();
331 if (entrypoints.size() != 1u) {
332 VALIDATION_LOG << "Single entrypoint not found.";
333 return nullptr;
334 }
335 auto data = std::make_unique<RuntimeStageData::Shader>();
336 data->entrypoint = options_.entry_point_name;
337 data->stage = entrypoints.front().execution_model;
338 data->shader = shader_data_;
339 data->backend = backend.value();
340
341 // Sort the IR so that the uniforms are in declaration order.
342 std::vector<spirv_cross::ID> uniforms =
343 SortUniforms(ir_.get(), compiler_.GetCompiler());
344 for (auto& sorted_id : uniforms) {
345 auto var = ir_->ids[sorted_id].get<spirv_cross::SPIRVariable>();
346 const auto spir_type = compiler_->get_type(var.basetype);
347 UniformDescription uniform_description;
348 uniform_description.name = compiler_->get_name(var.self);
349 uniform_description.location = compiler_->get_decoration(
350 var.self, spv::Decoration::DecorationLocation);
351 uniform_description.type = spir_type.basetype;
352 uniform_description.rows = spir_type.vecsize;
353 uniform_description.columns = spir_type.columns;
354 uniform_description.bit_width = spir_type.width;
355 uniform_description.array_elements = GetArrayElements(spir_type);
356 FML_CHECK(data->backend != RuntimeStageBackend::kVulkan ||
357 spir_type.basetype ==
358 spirv_cross::SPIRType::BaseType::SampledImage)
359 << "Vulkan runtime effect had unexpected uniforms outside of the "
360 "uniform buffer object.";
361 data->uniforms.emplace_back(std::move(uniform_description));
362 }
363
364 const auto ubos = compiler_->get_shader_resources().uniform_buffers;
365 if (data->backend == RuntimeStageBackend::kVulkan && !ubos.empty()) {
366 if (ubos.size() != 1 && ubos[0].name != RuntimeStage::kVulkanUBOName) {
367 VALIDATION_LOG << "Expected a single UBO resource named "
368 "'"
369 << RuntimeStage::kVulkanUBOName
370 << "' "
371 "for Vulkan runtime stage backend.";
372 return nullptr;
373 }
374
375 const auto& ubo = ubos[0];
376
377 auto members = ReadStructMembers(ubo.type_id);
378 std::vector<uint8_t> struct_layout;
379 size_t float_count = 0;
380
381 for (size_t i = 0; i < members.size(); i += 1) {
382 const auto& member = members[i];
383 std::vector<int> bytes;
384 switch (member.underlying_type) {
385 case StructMember::UnderlyingType::kPadding: {
386 size_t padding_count =
387 (member.size + sizeof(float) - 1) / sizeof(float);
388 while (padding_count > 0) {
389 struct_layout.push_back(0);
390 padding_count--;
391 }
392 break;
393 }
394 case StructMember::UnderlyingType::kFloat: {
395 size_t member_float_count = member.byte_length / sizeof(float);
396 float_count += member_float_count;
397 while (member_float_count > 0) {
398 struct_layout.push_back(1);
399 member_float_count--;
400 }
401 break;
402 }
403 case StructMember::UnderlyingType::kOther:
404 VALIDATION_LOG << "Non-floating-type struct member " << member.name
405 << " is not supported.";
406 return nullptr;
407 }
408 }
409 data->uniforms.emplace_back(UniformDescription{
410 .name = ubo.name,
411 .location = 64, // Magic constant that must match the descriptor set
412 // location for fragment programs.
413 .type = spirv_cross::SPIRType::Struct,
414 .struct_layout = std::move(struct_layout),
415 .struct_float_count = float_count,
416 });
417 }
418
419 // We only need to worry about storing vertex attributes.
420 if (entrypoints.front().execution_model == spv::ExecutionModelVertex) {
421 const auto inputs = compiler_->get_shader_resources().stage_inputs;
422 auto input_offsets = ComputeOffsets(inputs);
423 for (const auto& input : inputs) {
424 std::optional<size_t> offset = GetOffset(input.id, input_offsets);
425
426 const auto type = compiler_->get_type(input.type_id);
427
428 InputDescription input_description;
429 input_description.name = input.name;
430 input_description.location = compiler_->get_decoration(
431 input.id, spv::Decoration::DecorationLocation);
432 input_description.set = compiler_->get_decoration(
433 input.id, spv::Decoration::DecorationDescriptorSet);
434 input_description.binding = compiler_->get_decoration(
435 input.id, spv::Decoration::DecorationBinding);
436 input_description.type = type.basetype;
437 input_description.bit_width = type.width;
438 input_description.vec_size = type.vecsize;
439 input_description.columns = type.columns;
440 input_description.offset = offset.value_or(0u);
441 data->inputs.emplace_back(std::move(input_description));
442 }
443 }
444
445 return data;
446 }
447
448 std::shared_ptr<ShaderBundleData> Reflector::GenerateShaderBundleData() const {
449 const auto& entrypoints = compiler_->get_entry_points_and_stages();
450 if (entrypoints.size() != 1u) {
451 VALIDATION_LOG << "Single entrypoint not found.";
452 return nullptr;
453 }
454 auto data = std::make_shared<ShaderBundleData>(
455 options_.entry_point_name, //
456 entrypoints.front().execution_model, //
457 options_.target_platform //
458 );
459 data->SetShaderData(shader_data_);
460
461 const auto uniforms = compiler_->get_shader_resources().uniform_buffers;
462 for (const auto& uniform : uniforms) {
463 ShaderBundleData::ShaderUniformStruct uniform_struct;
464 uniform_struct.name = uniform.name;
465 uniform_struct.ext_res_0 = compiler_.GetExtendedMSLResourceBinding(
466 CompilerBackend::ExtendedResourceIndex::kPrimary, uniform.id);
467 uniform_struct.set = compiler_->get_decoration(
468 uniform.id, spv::Decoration::DecorationDescriptorSet);
469 uniform_struct.binding = compiler_->get_decoration(
470 uniform.id, spv::Decoration::DecorationBinding);
471
472 const auto type = compiler_->get_type(uniform.type_id);
473 if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) {
474 std::cerr << "Error: Uniform \"" << uniform.name
475 << "\" is not a struct. All Flutter GPU shader uniforms must "
476 "be structs."
477 << std::endl;
478 return nullptr;
479 }
480
481 size_t size_in_bytes = 0;
482 for (const auto& struct_member : ReadStructMembers(uniform.type_id)) {
483 size_in_bytes += struct_member.byte_length;
484 if (StringStartsWith(struct_member.name, "_PADDING_")) {
485 continue;
486 }
487 ShaderBundleData::ShaderUniformStructField uniform_struct_field;
488 uniform_struct_field.name = struct_member.name;
489 uniform_struct_field.type = struct_member.base_type;
490 uniform_struct_field.offset_in_bytes = struct_member.offset;
491 uniform_struct_field.element_size_in_bytes = struct_member.size;
492 uniform_struct_field.total_size_in_bytes = struct_member.byte_length;
493 uniform_struct_field.array_elements = struct_member.array_elements;
494 uniform_struct.fields.push_back(uniform_struct_field);
495 }
496 uniform_struct.size_in_bytes = size_in_bytes;
497
498 data->AddUniformStruct(uniform_struct);
499 }
500
501 const auto sampled_images = compiler_->get_shader_resources().sampled_images;
502 for (const auto& image : sampled_images) {
503 ShaderBundleData::ShaderUniformTexture uniform_texture;
504 uniform_texture.name = image.name;
505 uniform_texture.ext_res_0 = compiler_.GetExtendedMSLResourceBinding(
506 CompilerBackend::ExtendedResourceIndex::kPrimary, image.id);
507 uniform_texture.set = compiler_->get_decoration(
508 image.id, spv::Decoration::DecorationDescriptorSet);
509 uniform_texture.binding =
510 compiler_->get_decoration(image.id, spv::Decoration::DecorationBinding);
511 data->AddUniformTexture(uniform_texture);
512 }
513
514 // We only need to worry about storing vertex attributes.
515 if (entrypoints.front().execution_model == spv::ExecutionModelVertex) {
516 const auto inputs = compiler_->get_shader_resources().stage_inputs;
517 auto input_offsets = ComputeOffsets(inputs);
518 for (const auto& input : inputs) {
519 std::optional<size_t> offset = GetOffset(input.id, input_offsets);
520
521 const auto type = compiler_->get_type(input.type_id);
522
523 InputDescription input_description;
524 input_description.name = input.name;
525 input_description.location = compiler_->get_decoration(
526 input.id, spv::Decoration::DecorationLocation);
527 input_description.set = compiler_->get_decoration(
528 input.id, spv::Decoration::DecorationDescriptorSet);
529 input_description.binding = compiler_->get_decoration(
530 input.id, spv::Decoration::DecorationBinding);
531 input_description.type = type.basetype;
532 input_description.bit_width = type.width;
533 input_description.vec_size = type.vecsize;
534 input_description.columns = type.columns;
535 input_description.offset = offset.value_or(0u);
536 data->AddInputDescription(std::move(input_description));
537 }
538 }
539
540 return data;
541 }
542
543 std::optional<uint32_t> Reflector::GetArrayElements(
544 const spirv_cross::SPIRType& type) const {
545 if (type.array.empty()) {
546 return std::nullopt;
547 }
548 FML_CHECK(type.array.size() == 1)
549 << "Multi-dimensional arrays are not supported.";
550 FML_CHECK(type.array_size_literal.front())
551 << "Must use a literal for array sizes.";
552 return type.array.front();
553 }
554
555 static std::string ToString(CompilerBackend::Type type) {
556 switch (type) {
557 case CompilerBackend::Type::kMSL:
558 return "Metal Shading Language";
559 case CompilerBackend::Type::kGLSL:
560 return "OpenGL Shading Language";
561 case CompilerBackend::Type::kGLSLVulkan:
562 return "OpenGL Shading Language (Relaxed Vulkan Semantics)";
563 case CompilerBackend::Type::kSkSL:
564 return "SkSL Shading Language";
565 }
566 FML_UNREACHABLE();
567 }
568
569 std::shared_ptr<fml::Mapping> Reflector::InflateTemplate(
570 std::string_view tmpl) const {
571 inja::Environment env;
572 env.set_trim_blocks(true);
573 env.set_lstrip_blocks(true);
574
575 env.add_callback("camel_case", 1u, [](inja::Arguments& args) {
576 return ToCamelCase(args.at(0u)->get<std::string>());
577 });
578
579 env.add_callback("to_shader_stage", 1u, [](inja::Arguments& args) {
580 return StringToShaderStage(args.at(0u)->get<std::string>());
581 });
582
583 env.add_callback("get_generator_name", 0u,
584 [type = compiler_.GetType()](inja::Arguments& args) {
585 return ToString(type);
586 });
587
588 auto inflated_template =
589 std::make_shared<std::string>(env.render(tmpl, *template_arguments_));
590
591 return std::make_shared<fml::NonOwnedMapping>(
592 reinterpret_cast<const uint8_t*>(inflated_template->data()),
593 inflated_template->size(), [inflated_template](auto, auto) {});
594 }
595
596 std::vector<size_t> Reflector::ComputeOffsets(
597 const spirv_cross::SmallVector<spirv_cross::Resource>& resources) const {
598 std::vector<size_t> offsets(resources.size(), 0);
599 if (resources.size() == 0) {
600 return offsets;
601 }
602 for (const auto& resource : resources) {
603 const auto type = compiler_->get_type(resource.type_id);
604 auto location = compiler_->get_decoration(
605 resource.id, spv::Decoration::DecorationLocation);
606 // Malformed shader, will be caught later on.
607 if (location >= resources.size() || location < 0) {
608 location = 0;
609 }
610 offsets[location] = (type.width * type.vecsize) / 8;
611 }
612 for (size_t i = 1; i < resources.size(); i++) {
613 offsets[i] += offsets[i - 1];
614 }
615 for (size_t i = resources.size() - 1; i > 0; i--) {
616 offsets[i] = offsets[i - 1];
617 }
618 offsets[0] = 0;
619
620 return offsets;
621 }
622
623 std::optional<size_t> Reflector::GetOffset(
624 spirv_cross::ID id,
625 const std::vector<size_t>& offsets) const {
626 uint32_t location =
627 compiler_->get_decoration(id, spv::Decoration::DecorationLocation);
628 if (location >= offsets.size()) {
629 return std::nullopt;
630 }
631 return offsets[location];
632 }
633
634 std::optional<nlohmann::json::object_t> Reflector::ReflectResource(
635 const spirv_cross::Resource& resource,
636 std::optional<size_t> offset) const {
637 nlohmann::json::object_t result;
638
639 result["name"] = resource.name;
640 result["descriptor_set"] = compiler_->get_decoration(
641 resource.id, spv::Decoration::DecorationDescriptorSet);
642 result["binding"] = compiler_->get_decoration(
643 resource.id, spv::Decoration::DecorationBinding);
644 result["set"] = compiler_->get_decoration(
645 resource.id, spv::Decoration::DecorationDescriptorSet);
646 result["location"] = compiler_->get_decoration(
647 resource.id, spv::Decoration::DecorationLocation);
648 result["index"] =
649 compiler_->get_decoration(resource.id, spv::Decoration::DecorationIndex);
650 result["ext_res_0"] = compiler_.GetExtendedMSLResourceBinding(
651 CompilerBackend::ExtendedResourceIndex::kPrimary, resource.id);
652 result["ext_res_1"] = compiler_.GetExtendedMSLResourceBinding(
653 CompilerBackend::ExtendedResourceIndex::kSecondary, resource.id);
654 auto type = ReflectType(resource.type_id);
655 if (!type.has_value()) {
656 return std::nullopt;
657 }
658 result["type"] = std::move(type.value());
659 result["offset"] = offset.value_or(0u);
660 return result;
661 }
662
663 std::optional<nlohmann::json::object_t> Reflector::ReflectType(
664 const spirv_cross::TypeID& type_id) const {
665 nlohmann::json::object_t result;
666
667 const auto type = compiler_->get_type(type_id);
668
669 result["type_name"] = StructMember::BaseTypeToString(type.basetype);
670 result["bit_width"] = type.width;
671 result["vec_size"] = type.vecsize;
672 result["columns"] = type.columns;
673 auto& members = result["members"] = nlohmann::json::array_t{};
674 if (type.basetype == spirv_cross::SPIRType::BaseType::Struct) {
675 for (const auto& struct_member : ReadStructMembers(type_id)) {
676 auto member = nlohmann::json::object_t{};
677 member["name"] = struct_member.name;
678 member["type"] = struct_member.type;
679 member["base_type"] =
680 StructMember::BaseTypeToString(struct_member.base_type);
681 member["offset"] = struct_member.offset;
682 member["size"] = struct_member.size;
683 member["byte_length"] = struct_member.byte_length;
684 if (struct_member.array_elements.has_value()) {
685 member["array_elements"] = struct_member.array_elements.value();
686 } else {
687 member["array_elements"] = "std::nullopt";
688 }
689 members.emplace_back(std::move(member));
690 }
691 }
692
693 return result;
694 }
695
696 std::optional<nlohmann::json::array_t> Reflector::ReflectResources(
697 const spirv_cross::SmallVector<spirv_cross::Resource>& resources,
698 bool compute_offsets) const {
699 nlohmann::json::array_t result;
700 result.reserve(resources.size());
701 std::vector<size_t> offsets;
702 if (compute_offsets) {
703 offsets = ComputeOffsets(resources);
704 }
705 for (const auto& resource : resources) {
706 std::optional<size_t> maybe_offset = std::nullopt;
707 if (compute_offsets) {
708 maybe_offset = GetOffset(resource.id, offsets);
709 }
710 if (auto reflected = ReflectResource(resource, maybe_offset);
711 reflected.has_value()) {
712 result.emplace_back(std::move(reflected.value()));
713 } else {
714 return std::nullopt;
715 }
716 }
717 return result;
718 }
719
720 static std::string TypeNameWithPaddingOfSize(size_t size) {
721 std::stringstream stream;
722 stream << "Padding<" << size << ">";
723 return stream.str();
724 }
725
726 struct KnownType {
727 std::string name;
728 size_t byte_size = 0;
729 };
730
731 static std::optional<KnownType> ReadKnownScalarType(
732 spirv_cross::SPIRType::BaseType type) {
733 switch (type) {
734 case spirv_cross::SPIRType::BaseType::Boolean:
735 return KnownType{
736 .name = "bool",
737 .byte_size = sizeof(bool),
738 };
739 case spirv_cross::SPIRType::BaseType::Float:
740 return KnownType{
741 .name = "Scalar",
742 .byte_size = sizeof(Scalar),
743 };
744 case spirv_cross::SPIRType::BaseType::Half:
745 return KnownType{
746 .name = "Half",
747 .byte_size = sizeof(Half),
748 };
749 case spirv_cross::SPIRType::BaseType::UInt:
750 return KnownType{
751 .name = "uint32_t",
752 .byte_size = sizeof(uint32_t),
753 };
754 case spirv_cross::SPIRType::BaseType::Int:
755 return KnownType{
756 .name = "int32_t",
757 .byte_size = sizeof(int32_t),
758 };
759 default:
760 break;
761 }
762 return std::nullopt;
763 }
764
765 //------------------------------------------------------------------------------
766 /// @brief Get the reflected struct size. In the vast majority of the
767 /// cases, this is the same as the declared struct size as given by
768 /// the compiler. But, additional padding may need to be introduced
769 /// after the end of the struct to keep in line with the alignment
770 /// requirement of the individual struct members. This method
771 /// figures out the actual size of the reflected struct that can be
772 /// referenced in native code.
773 ///
774 /// @param[in] members The members
775 ///
776 /// @return The reflected structure size.
777 ///
778 static size_t GetReflectedStructSize(const std::vector<StructMember>& members) {
779 auto struct_size = 0u;
780 for (const auto& member : members) {
781 struct_size += member.byte_length;
782 }
783 return struct_size;
784 }
785
786 std::vector<StructMember> Reflector::ReadStructMembers(
787 const spirv_cross::TypeID& type_id) const {
788 const auto& struct_type = compiler_->get_type(type_id);
789 FML_CHECK(struct_type.basetype == spirv_cross::SPIRType::BaseType::Struct);
790
791 std::vector<StructMember> result;
792
793 size_t current_byte_offset = 0;
794 size_t max_member_alignment = 0;
795
796 for (size_t i = 0; i < struct_type.member_types.size(); i++) {
797 const auto& member = compiler_->get_type(struct_type.member_types[i]);
798 const auto struct_member_offset =
799 compiler_->type_struct_member_offset(struct_type, i);
800 auto array_elements = GetArrayElements(member);
801
802 if (struct_member_offset > current_byte_offset) {
803 const auto alignment_pad = struct_member_offset - current_byte_offset;
804 result.emplace_back(StructMember{
805 TypeNameWithPaddingOfSize(alignment_pad), // type
806 spirv_cross::SPIRType::BaseType::Void, // basetype
807 SPrintF("_PADDING_%s_",
808 GetMemberNameAtIndex(struct_type, i).c_str()), // name
809 current_byte_offset, // offset
810 alignment_pad, // size
811 alignment_pad, // byte_length
812 std::nullopt, // array_elements
813 0, // element_padding
814 });
815 current_byte_offset += alignment_pad;
816 }
817
818 max_member_alignment =
819 std::max<size_t>(max_member_alignment,
820 (member.width / 8) * member.columns * member.vecsize);
821
822 FML_CHECK(current_byte_offset == struct_member_offset);
823
824 // A user defined struct.
825 if (member.basetype == spirv_cross::SPIRType::BaseType::Struct) {
826 const size_t size =
827 GetReflectedStructSize(ReadStructMembers(member.self));
828 uint32_t stride = GetArrayStride<0>(struct_type, member, i);
829 if (stride == 0) {
830 stride = size;
831 }
832 uint32_t element_padding = stride - size;
833 result.emplace_back(StructMember{
834 compiler_->get_name(member.self), // type
835 member.basetype, // basetype
836 GetMemberNameAtIndex(struct_type, i), // name
837 struct_member_offset, // offset
838 size, // size
839 stride * array_elements.value_or(1), // byte_length
840 array_elements, // array_elements
841 element_padding, // element_padding
842 });
843 current_byte_offset += stride * array_elements.value_or(1);
844 continue;
845 }
846
847 // Tightly packed 4x4 Matrix is special cased as we know how to work with
848 // those.
849 if (member.basetype == spirv_cross::SPIRType::BaseType::Float && //
850 member.width == sizeof(Scalar) * 8 && //
851 member.columns == 4 && //
852 member.vecsize == 4 //
853 ) {
854 uint32_t stride = GetArrayStride<sizeof(Matrix)>(struct_type, member, i);
855 uint32_t element_padding = stride - sizeof(Matrix);
856 result.emplace_back(StructMember{
857 "Matrix", // type
858 member.basetype, // basetype
859 GetMemberNameAtIndex(struct_type, i), // name
860 struct_member_offset, // offset
861 sizeof(Matrix), // size
862 stride * array_elements.value_or(1), // byte_length
863 array_elements, // array_elements
864 element_padding, // element_padding
865 });
866 current_byte_offset += stride * array_elements.value_or(1);
867 continue;
868 }
869
870 // Tightly packed UintPoint32 (uvec2)
871 if (member.basetype == spirv_cross::SPIRType::BaseType::UInt && //
872 member.width == sizeof(uint32_t) * 8 && //
873 member.columns == 1 && //
874 member.vecsize == 2 //
875 ) {
876 uint32_t stride =
877 GetArrayStride<sizeof(UintPoint32)>(struct_type, member, i);
878 uint32_t element_padding = stride - sizeof(UintPoint32);
879 result.emplace_back(StructMember{
880 "UintPoint32", // type
881 member.basetype, // basetype
882 GetMemberNameAtIndex(struct_type, i), // name
883 struct_member_offset, // offset
884 sizeof(UintPoint32), // size
885 stride * array_elements.value_or(1), // byte_length
886 array_elements, // array_elements
887 element_padding, // element_padding
888 });
889 current_byte_offset += stride * array_elements.value_or(1);
890 continue;
891 }
892
893 // Tightly packed UintPoint32 (ivec2)
894 if (member.basetype == spirv_cross::SPIRType::BaseType::Int && //
895 member.width == sizeof(int32_t) * 8 && //
896 member.columns == 1 && //
897 member.vecsize == 2 //
898 ) {
899 uint32_t stride =
900 GetArrayStride<sizeof(IPoint32)>(struct_type, member, i);
901 uint32_t element_padding = stride - sizeof(IPoint32);
902 result.emplace_back(StructMember{
903 "IPoint32", // type
904 member.basetype, // basetype
905 GetMemberNameAtIndex(struct_type, i), // name
906 struct_member_offset, // offset
907 sizeof(IPoint32), // size
908 stride * array_elements.value_or(1), // byte_length
909 array_elements, // array_elements
910 element_padding, // element_padding
911 });
912 current_byte_offset += stride * array_elements.value_or(1);
913 continue;
914 }
915
916 // Tightly packed Point (vec2).
917 if (member.basetype == spirv_cross::SPIRType::BaseType::Float && //
918 member.width == sizeof(float) * 8 && //
919 member.columns == 1 && //
920 member.vecsize == 2 //
921 ) {
922 uint32_t stride = GetArrayStride<sizeof(Point)>(struct_type, member, i);
923 uint32_t element_padding = stride - sizeof(Point);
924 result.emplace_back(StructMember{
925 "Point", // type
926 member.basetype, // basetype
927 GetMemberNameAtIndex(struct_type, i), // name
928 struct_member_offset, // offset
929 sizeof(Point), // size
930 stride * array_elements.value_or(1), // byte_length
931 array_elements, // array_elements
932 element_padding, // element_padding
933 });
934 current_byte_offset += stride * array_elements.value_or(1);
935 continue;
936 }
937
938 // Tightly packed Vector3.
939 if (member.basetype == spirv_cross::SPIRType::BaseType::Float && //
940 member.width == sizeof(float) * 8 && //
941 member.columns == 1 && //
942 member.vecsize == 3 //
943 ) {
944 uint32_t stride = GetArrayStride<sizeof(Vector3)>(struct_type, member, i);
945 uint32_t element_padding = stride - sizeof(Vector3);
946 result.emplace_back(StructMember{
947 "Vector3", // type
948 member.basetype, // basetype
949 GetMemberNameAtIndex(struct_type, i), // name
950 struct_member_offset, // offset
951 sizeof(Vector3), // size
952 stride * array_elements.value_or(1), // byte_length
953 array_elements, // array_elements
954 element_padding, // element_padding
955 });
956 current_byte_offset += stride * array_elements.value_or(1);
957 continue;
958 }
959
960 // Tightly packed Vector4.
961 if (member.basetype == spirv_cross::SPIRType::BaseType::Float && //
962 member.width == sizeof(float) * 8 && //
963 member.columns == 1 && //
964 member.vecsize == 4 //
965 ) {
966 uint32_t stride = GetArrayStride<sizeof(Vector4)>(struct_type, member, i);
967 uint32_t element_padding = stride - sizeof(Vector4);
968 result.emplace_back(StructMember{
969 "Vector4", // type
970 member.basetype, // basetype
971 GetMemberNameAtIndex(struct_type, i), // name
972 struct_member_offset, // offset
973 sizeof(Vector4), // size
974 stride * array_elements.value_or(1), // byte_length
975 array_elements, // array_elements
976 element_padding, // element_padding
977 });
978 current_byte_offset += stride * array_elements.value_or(1);
979 continue;
980 }
981
982 // Tightly packed half Point (vec2).
983 if (member.basetype == spirv_cross::SPIRType::BaseType::Half && //
984 member.width == sizeof(Half) * 8 && //
985 member.columns == 1 && //
986 member.vecsize == 2 //
987 ) {
988 uint32_t stride =
989 GetArrayStride<sizeof(HalfVector2)>(struct_type, member, i);
990 uint32_t element_padding = stride - sizeof(HalfVector2);
991 result.emplace_back(StructMember{
992 "HalfVector2", // type
993 member.basetype, // basetype
994 GetMemberNameAtIndex(struct_type, i), // name
995 struct_member_offset, // offset
996 sizeof(HalfVector2), // size
997 stride * array_elements.value_or(1), // byte_length
998 array_elements, // array_elements
999 element_padding, // element_padding
1000 });
1001 current_byte_offset += stride * array_elements.value_or(1);
1002 continue;
1003 }
1004
1005 // Tightly packed Half Float Vector3.
1006 if (member.basetype == spirv_cross::SPIRType::BaseType::Half && //
1007 member.width == sizeof(Half) * 8 && //
1008 member.columns == 1 && //
1009 member.vecsize == 3 //
1010 ) {
1011 uint32_t stride =
1012 GetArrayStride<sizeof(HalfVector3)>(struct_type, member, i);
1013 uint32_t element_padding = stride - sizeof(HalfVector3);
1014 result.emplace_back(StructMember{
1015 "HalfVector3", // type
1016 member.basetype, // basetype
1017 GetMemberNameAtIndex(struct_type, i), // name
1018 struct_member_offset, // offset
1019 sizeof(HalfVector3), // size
1020 stride * array_elements.value_or(1), // byte_length
1021 array_elements, // array_elements
1022 element_padding, // element_padding
1023 });
1024 current_byte_offset += stride * array_elements.value_or(1);
1025 continue;
1026 }
1027
1028 // Tightly packed Half Float Vector4.
1029 if (member.basetype == spirv_cross::SPIRType::BaseType::Half && //
1030 member.width == sizeof(Half) * 8 && //
1031 member.columns == 1 && //
1032 member.vecsize == 4 //
1033 ) {
1034 uint32_t stride =
1035 GetArrayStride<sizeof(HalfVector4)>(struct_type, member, i);
1036 uint32_t element_padding = stride - sizeof(HalfVector4);
1037 result.emplace_back(StructMember{
1038 "HalfVector4", // type
1039 member.basetype, // basetype
1040 GetMemberNameAtIndex(struct_type, i), // name
1041 struct_member_offset, // offset
1042 sizeof(HalfVector4), // size
1043 stride * array_elements.value_or(1), // byte_length
1044 array_elements, // array_elements
1045 element_padding, // element_padding
1046 });
1047 current_byte_offset += stride * array_elements.value_or(1);
1048 continue;
1049 }
1050
1051 // Other isolated scalars (like bool, int, float/Scalar, etc..).
1052 {
1053 auto maybe_known_type = ReadKnownScalarType(member.basetype);
1054 if (maybe_known_type.has_value() && //
1055 member.columns == 1 && //
1056 member.vecsize == 1 //
1057 ) {
1058 uint32_t stride = GetArrayStride<0>(struct_type, member, i);
1059 if (stride == 0) {
1060 stride = maybe_known_type.value().byte_size;
1061 }
1062 uint32_t element_padding = stride - maybe_known_type.value().byte_size;
1063 // Add the type directly.
1064 result.emplace_back(StructMember{
1065 maybe_known_type.value().name, // type
1066 member.basetype, // basetype
1067 GetMemberNameAtIndex(struct_type, i), // name
1068 struct_member_offset, // offset
1069 maybe_known_type.value().byte_size, // size
1070 stride * array_elements.value_or(1), // byte_length
1071 array_elements, // array_elements
1072 element_padding, // element_padding
1073 });
1074 current_byte_offset += stride * array_elements.value_or(1);
1075 continue;
1076 }
1077 }
1078
1079 // Catch all for unknown types. Just add the necessary padding to the struct
1080 // and move on.
1081 {
1082 const size_t size = (member.width * member.columns * member.vecsize) / 8u;
1083 uint32_t stride = GetArrayStride<0>(struct_type, member, i);
1084 if (stride == 0) {
1085 stride = size;
1086 }
1087 auto element_padding = stride - size;
1088 result.emplace_back(StructMember{
1089 TypeNameWithPaddingOfSize(size), // type
1090 member.basetype, // basetype
1091 GetMemberNameAtIndex(struct_type, i), // name
1092 struct_member_offset, // offset
1093 size, // size
1094 stride * array_elements.value_or(1), // byte_length
1095 array_elements, // array_elements
1096 element_padding, // element_padding
1097 });
1098 current_byte_offset += stride * array_elements.value_or(1);
1099 continue;
1100 }
1101 }
1102
1103 if (max_member_alignment > 0u) {
1104 const auto struct_length = current_byte_offset;
1105 {
1106 const auto excess = struct_length % max_member_alignment;
1107 if (excess != 0) {
1108 const auto padding = max_member_alignment - excess;
1109 result.emplace_back(StructMember{
1110 TypeNameWithPaddingOfSize(padding), // type
1111 spirv_cross::SPIRType::BaseType::Void, // basetype
1112 "_PADDING_", // name
1113 current_byte_offset, // offset
1114 padding, // size
1115 padding, // byte_length
1116 std::nullopt, // array_elements
1117 0, // element_padding
1118 });
1119 }
1120 }
1121 }
1122
1123 return result;
1124 }
1125
1126 std::optional<Reflector::StructDefinition> Reflector::ReflectStructDefinition(
1127 const spirv_cross::TypeID& type_id) const {
1128 const auto& type = compiler_->get_type(type_id);
1129 if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) {
1130 return std::nullopt;
1131 }
1132
1133 const auto struct_name = compiler_->get_name(type_id);
1134 if (struct_name.find("_RESERVED_IDENTIFIER_") != std::string::npos) {
1135 return std::nullopt;
1136 }
1137
1138 auto struct_members = ReadStructMembers(type_id);
1139 auto reflected_struct_size = GetReflectedStructSize(struct_members);
1140
1141 StructDefinition struc;
1142 struc.name = struct_name;
1143 struc.byte_length = reflected_struct_size;
1144 struc.members = std::move(struct_members);
1145 return struc;
1146 }
1147
1148 nlohmann::json::object_t Reflector::EmitStructDefinition(
1149 std::optional<Reflector::StructDefinition> struc) const {
1150 nlohmann::json::object_t result;
1151 result["name"] = struc->name;
1152 result["byte_length"] = struc->byte_length;
1153 auto& members = result["members"] = nlohmann::json::array_t{};
1154 for (const auto& struct_member : struc->members) {
1155 auto& member = members.emplace_back(nlohmann::json::object_t{});
1156 member["name"] = struct_member.name;
1157 member["type"] = struct_member.type;
1158 member["base_type"] =
1159 StructMember::BaseTypeToString(struct_member.base_type);
1160 member["offset"] = struct_member.offset;
1161 member["byte_length"] = struct_member.byte_length;
1162 if (struct_member.array_elements.has_value()) {
1163 member["array_elements"] = struct_member.array_elements.value();
1164 } else {
1165 member["array_elements"] = "std::nullopt";
1166 }
1167 member["element_padding"] = struct_member.element_padding;
1168 }
1169 return result;
1170 }
1171
1172 struct VertexType {
1173 std::string type_name;
1174 spirv_cross::SPIRType::BaseType base_type;
1175 std::string variable_name;
1176 size_t byte_length = 0u;
1177 };
1178
1179 static VertexType VertexTypeFromInputResource(
1180 const spirv_cross::Compiler& compiler,
1181 const spirv_cross::Resource* resource) {
1182 VertexType result;
1183 result.variable_name = resource->name;
1184 const auto& type = compiler.get_type(resource->type_id);
1185 result.base_type = type.basetype;
1186 const auto total_size = type.columns * type.vecsize * type.width / 8u;
1187 result.byte_length = total_size;
1188
1189 if (type.basetype == spirv_cross::SPIRType::BaseType::Float &&
1190 type.columns == 1u && type.vecsize == 2u &&
1191 type.width == sizeof(float) * 8u) {
1192 result.type_name = "Point";
1193 } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float &&
1194 type.columns == 1u && type.vecsize == 4u &&
1195 type.width == sizeof(float) * 8u) {
1196 result.type_name = "Vector4";
1197 } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float &&
1198 type.columns == 1u && type.vecsize == 3u &&
1199 type.width == sizeof(float) * 8u) {
1200 result.type_name = "Vector3";
1201 } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float &&
1202 type.columns == 1u && type.vecsize == 1u &&
1203 type.width == sizeof(float) * 8u) {
1204 result.type_name = "Scalar";
1205 } else if (type.basetype == spirv_cross::SPIRType::BaseType::Int &&
1206 type.columns == 1u && type.vecsize == 1u &&
1207 type.width == sizeof(int32_t) * 8u) {
1208 result.type_name = "int32_t";
1209 } else {
1210 // Catch all unknown padding.
1211 result.type_name = TypeNameWithPaddingOfSize(total_size);
1212 }
1213
1214 return result;
1215 }
1216
1217 std::optional<Reflector::StructDefinition>
1218 Reflector::ReflectPerVertexStructDefinition(
1219 const spirv_cross::SmallVector<spirv_cross::Resource>& stage_inputs) const {
1220 // Avoid emitting a zero sized structure. The code gen templates assume a
1221 // non-zero size.
1222 if (stage_inputs.empty()) {
1223 return std::nullopt;
1224 }
1225
1226 // Validate locations are contiguous and there are no duplicates.
1227 std::set<uint32_t> locations;
1228 for (const auto& input : stage_inputs) {
1229 auto location = compiler_->get_decoration(
1230 input.id, spv::Decoration::DecorationLocation);
1231 if (locations.count(location) != 0) {
1232 // Duplicate location. Bail.
1233 return std::nullopt;
1234 }
1235 locations.insert(location);
1236 }
1237
1238 for (size_t i = 0; i < locations.size(); i++) {
1239 if (locations.count(i) != 1) {
1240 // Locations are not contiguous. This usually happens when a single stage
1241 // input takes multiple input slots. No reflection information can be
1242 // generated for such cases anyway. So bail! It is up to the shader author
1243 // to make sure one stage input maps to a single input slot.
1244 return std::nullopt;
1245 }
1246 }
1247
1248 auto input_for_location =
1249 [&](uint32_t queried_location) -> const spirv_cross::Resource* {
1250 for (const auto& input : stage_inputs) {
1251 auto location = compiler_->get_decoration(
1252 input.id, spv::Decoration::DecorationLocation);
1253 if (location == queried_location) {
1254 return &input;
1255 }
1256 }
1257 // This really cannot happen with all the validation above.
1258 FML_UNREACHABLE();
1259 return nullptr;
1260 };
1261
1262 StructDefinition struc;
1263 struc.name = "PerVertexData";
1264 struc.byte_length = 0u;
1265 for (size_t i = 0; i < locations.size(); i++) {
1266 auto resource = input_for_location(i);
1267 if (resource == nullptr) {
1268 return std::nullopt;
1269 }
1270 const auto vertex_type =
1271 VertexTypeFromInputResource(*compiler_.GetCompiler(), resource);
1272
1273 auto member = StructMember{
1274 vertex_type.type_name, // type
1275 vertex_type.base_type, // base type
1276 vertex_type.variable_name, // name
1277 struc.byte_length, // offset
1278 vertex_type.byte_length, // size
1279 vertex_type.byte_length, // byte_length
1280 std::nullopt, // array_elements
1281 0, // element_padding
1282 };
1283 struc.byte_length += vertex_type.byte_length;
1284 struc.members.emplace_back(std::move(member));
1285 }
1286 return struc;
1287 }
1288
1289 std::optional<std::string> Reflector::GetMemberNameAtIndexIfExists(
1290 const spirv_cross::SPIRType& parent_type,
1291 size_t index) const {
1292 if (parent_type.type_alias != 0) {
1293 return GetMemberNameAtIndexIfExists(
1294 compiler_->get_type(parent_type.type_alias), index);
1295 }
1296
1297 if (auto found = ir_->meta.find(parent_type.self); found != ir_->meta.end()) {
1298 const auto& members = found->second.members;
1299 if (index < members.size() && !members[index].alias.empty()) {
1300 return members[index].alias;
1301 }
1302 }
1303 return std::nullopt;
1304 }
1305
1306 std::string Reflector::GetMemberNameAtIndex(
1307 const spirv_cross::SPIRType& parent_type,
1308 size_t index,
1309 std::string suffix) const {
1310 if (auto name = GetMemberNameAtIndexIfExists(parent_type, index);
1311 name.has_value()) {
1312 return name.value();
1313 }
1314 static std::atomic_size_t sUnnamedMembersID;
1315 std::stringstream stream;
1316 stream << "unnamed_" << sUnnamedMembersID++ << suffix;
1317 return stream.str();
1318 }
1319
1320 std::vector<Reflector::BindPrototype> Reflector::ReflectBindPrototypes(
1321 const spirv_cross::ShaderResources& resources,
1322 spv::ExecutionModel execution_model) const {
1323 std::vector<BindPrototype> prototypes;
1324 for (const auto& uniform_buffer : resources.uniform_buffers) {
1325 auto& proto = prototypes.emplace_back(BindPrototype{});
1326 proto.return_type = "bool";
1327 proto.name = ToCamelCase(uniform_buffer.name);
1328 proto.descriptor_type = "DescriptorType::kUniformBuffer";
1329 {
1330 std::stringstream stream;
1331 stream << "Bind uniform buffer for resource named " << uniform_buffer.name
1332 << ".";
1333 proto.docstring = stream.str();
1334 }
1335 proto.args.push_back(BindPrototypeArgument{
1336 .type_name = "ResourceBinder&",
1337 .argument_name = "command",
1338 });
1339 proto.args.push_back(BindPrototypeArgument{
1340 .type_name = "BufferView",
1341 .argument_name = "view",
1342 });
1343 }
1344 for (const auto& storage_buffer : resources.storage_buffers) {
1345 auto& proto = prototypes.emplace_back(BindPrototype{});
1346 proto.return_type = "bool";
1347 proto.name = ToCamelCase(storage_buffer.name);
1348 proto.descriptor_type = "DescriptorType::kStorageBuffer";
1349 {
1350 std::stringstream stream;
1351 stream << "Bind storage buffer for resource named " << storage_buffer.name
1352 << ".";
1353 proto.docstring = stream.str();
1354 }
1355 proto.args.push_back(BindPrototypeArgument{
1356 .type_name = "ResourceBinder&",
1357 .argument_name = "command",
1358 });
1359 proto.args.push_back(BindPrototypeArgument{
1360 .type_name = "BufferView",
1361 .argument_name = "view",
1362 });
1363 }
1364 for (const auto& sampled_image : resources.sampled_images) {
1365 auto& proto = prototypes.emplace_back(BindPrototype{});
1366 proto.return_type = "bool";
1367 proto.name = ToCamelCase(sampled_image.name);
1368 proto.descriptor_type = "DescriptorType::kSampledImage";
1369 {
1370 std::stringstream stream;
1371 stream << "Bind combined image sampler for resource named "
1372 << sampled_image.name << ".";
1373 proto.docstring = stream.str();
1374 }
1375 proto.args.push_back(BindPrototypeArgument{
1376 .type_name = "ResourceBinder&",
1377 .argument_name = "command",
1378 });
1379 proto.args.push_back(BindPrototypeArgument{
1380 .type_name = "std::shared_ptr<const Texture>",
1381 .argument_name = "texture",
1382 });
1383 proto.args.push_back(BindPrototypeArgument{
1384 .type_name = "const std::unique_ptr<const Sampler>&",
1385 .argument_name = "sampler",
1386 });
1387 }
1388 for (const auto& separate_image : resources.separate_images) {
1389 auto& proto = prototypes.emplace_back(BindPrototype{});
1390 proto.return_type = "bool";
1391 proto.name = ToCamelCase(separate_image.name);
1392 proto.descriptor_type = "DescriptorType::kImage";
1393 {
1394 std::stringstream stream;
1395 stream << "Bind separate image for resource named " << separate_image.name
1396 << ".";
1397 proto.docstring = stream.str();
1398 }
1399 proto.args.push_back(BindPrototypeArgument{
1400 .type_name = "Command&",
1401 .argument_name = "command",
1402 });
1403 proto.args.push_back(BindPrototypeArgument{
1404 .type_name = "std::shared_ptr<const Texture>",
1405 .argument_name = "texture",
1406 });
1407 }
1408 for (const auto& separate_sampler : resources.separate_samplers) {
1409 auto& proto = prototypes.emplace_back(BindPrototype{});
1410 proto.return_type = "bool";
1411 proto.name = ToCamelCase(separate_sampler.name);
1412 proto.descriptor_type = "DescriptorType::kSampler";
1413 {
1414 std::stringstream stream;
1415 stream << "Bind separate sampler for resource named "
1416 << separate_sampler.name << ".";
1417 proto.docstring = stream.str();
1418 }
1419 proto.args.push_back(BindPrototypeArgument{
1420 .type_name = "Command&",
1421 .argument_name = "command",
1422 });
1423 proto.args.push_back(BindPrototypeArgument{
1424 .type_name = "std::shared_ptr<const Sampler>",
1425 .argument_name = "sampler",
1426 });
1427 }
1428 return prototypes;
1429 }
1430
1431 nlohmann::json::array_t Reflector::EmitBindPrototypes(
1432 const spirv_cross::ShaderResources& resources,
1433 spv::ExecutionModel execution_model) const {
1434 const auto prototypes = ReflectBindPrototypes(resources, execution_model);
1435 nlohmann::json::array_t result;
1436 for (const auto& res : prototypes) {
1437 auto& item = result.emplace_back(nlohmann::json::object_t{});
1438 item["return_type"] = res.return_type;
1439 item["name"] = res.name;
1440 item["docstring"] = res.docstring;
1441 item["descriptor_type"] = res.descriptor_type;
1442 auto& args = item["args"] = nlohmann::json::array_t{};
1443 for (const auto& arg : res.args) {
1444 auto& json_arg = args.emplace_back(nlohmann::json::object_t{});
1445 json_arg["type_name"] = arg.type_name;
1446 json_arg["argument_name"] = arg.argument_name;
1447 }
1448 }
1449 return result;
1450 }
1451
1452 } // namespace compiler
1453 } // namespace impeller
impeller::compiler::ToCamelCase
std::string ToCamelCase(std::string_view string)
Definition: utilities.cc:39
impeller::compiler::GetRuntimeStageBackend
static std::optional< RuntimeStageBackend > GetRuntimeStageBackend(TargetPlatform target_platform)
Definition: reflector.cc:301
uniform_sorter.h
impeller::Scalar
float Scalar
Definition: scalar.h:18
impeller::RuntimeStageBackend::kVulkan
@ kVulkan
impeller::compiler::VertexType::byte_length
size_t byte_length
Definition: reflector.cc:1176
impeller::compiler::CompilerBackend
Definition: compiler_backend.h:21
impeller::compiler::VertexType::variable_name
std::string variable_name
Definition: reflector.cc:1175
impeller::RuntimeStage::kVulkanUBOName
static const char * kVulkanUBOName
Definition: runtime_stage.h:21
impeller::compiler::TargetPlatform::kMetalDesktop
@ kMetalDesktop
impeller::compiler::VertexType::base_type
spirv_cross::SPIRType::BaseType base_type
Definition: reflector.cc:1174
impeller::compiler::StructMember::UnderlyingType::kFloat
@ kFloat
impeller::UintPoint32
TPoint< uint32_t > UintPoint32
Definition: point.h:319
impeller::compiler::StructMember::UnderlyingType::kOther
@ kOther
impeller::compiler::TargetPlatform::kMetalIOS
@ kMetalIOS
impeller::compiler::KnownType
Definition: reflector.cc:726
impeller::compiler::CompilerBackend::Type::kGLSLVulkan
@ kGLSLVulkan
impeller::compiler::Reflector::GetReflectionCC
std::shared_ptr< fml::Mapping > GetReflectionCC() const
Definition: reflector.cc:125
impeller::compiler::Reflector::Options::header_file_name
std::string header_file_name
Definition: reflector.h:152
validation.h
impeller::compiler::TargetPlatform
TargetPlatform
Definition: types.h:29
impeller::compiler::VertexTypeFromInputResource
static VertexType VertexTypeFromInputResource(const spirv_cross::Compiler &compiler, const spirv_cross::Resource *resource)
Definition: reflector.cc:1179
impeller::compiler::Reflector::GetReflectionHeader
std::shared_ptr< fml::Mapping > GetReflectionHeader() const
Definition: reflector.cc:121
runtime_types.h
impeller::RuntimeStageBackend::kOpenGLES
@ kOpenGLES
impeller::compiler::Reflector::Options::target_platform
TargetPlatform target_platform
Definition: reflector.h:149
code_gen_template.h
reflector.h
impeller::compiler::Reflector::GetRuntimeStageShaderData
std::shared_ptr< RuntimeStageData::Shader > GetRuntimeStageShaderData() const
Definition: reflector.cc:129
matrix.h
shader_bundle_data.h
impeller::compiler::KnownType::byte_size
size_t byte_size
Definition: reflector.cc:728
impeller::compiler::StructMember::UnderlyingType::kPadding
@ kPadding
impeller::Point
TPoint< Scalar > Point
Definition: point.h:316
runtime_stage.h
impeller::Half
A storage only class for half precision floating point.
Definition: half.h:41
impeller::compiler::CompilerBackend::Type
Type
Definition: compiler_backend.h:27
impeller::compiler::KnownType::name
std::string name
Definition: reflector.cc:727
impeller::SortUniforms
std::vector< spirv_cross::ID > SortUniforms(const spirv_cross::ParsedIR *ir, const spirv_cross::Compiler *compiler, std::optional< spirv_cross::SPIRType::BaseType > type_filter, bool include)
Sorts uniform declarations in an IR according to decoration order.
Definition: uniform_sorter.cc:11
impeller::compiler::TargetPlatform::kVulkan
@ kVulkan
impeller::SPrintF
std::string SPrintF(const char *format,...)
Definition: strings.cc:12
impeller::compiler::Reflector::Options::shader_name
std::string shader_name
Definition: reflector.h:151
impeller::compiler::TargetPlatform::kRuntimeStageVulkan
@ kRuntimeStageVulkan
impeller::compiler::kReflectionCCTemplate
constexpr std::string_view kReflectionCCTemplate
Definition: code_gen_template.h:204
impeller::compiler::CompilerBackend::ExtendedResourceIndex::kSecondary
@ kSecondary
impeller::compiler::ExecutionModelToString
static std::string ExecutionModelToString(spv::ExecutionModel model)
Definition: reflector.cc:33
impeller::compiler::CompilerBackend::GetExtendedMSLResourceBinding
uint32_t GetExtendedMSLResourceBinding(ExtendedResourceIndex index, spirv_cross::ID id) const
Definition: compiler_backend.cc:35
impeller::IPoint32
TPoint< int32_t > IPoint32
Definition: point.h:318
impeller::compiler::CompilerBackend::Type::kGLSL
@ kGLSL
impeller::compiler::CompilerBackend::GetType
Type GetType() const
Definition: compiler_backend.cc:108
impeller::compiler::VertexType::type_name
std::string type_name
Definition: reflector.cc:1173
impeller::compiler::ReadKnownScalarType
static std::optional< KnownType > ReadKnownScalarType(spirv_cross::SPIRType::BaseType type)
Definition: reflector.cc:731
impeller::compiler::Reflector::~Reflector
~Reflector()
impeller::compiler::Reflector::Options
Definition: reflector.h:148
impeller::compiler::kReflectionHeaderTemplate
constexpr std::string_view kReflectionHeaderTemplate
Definition: code_gen_template.h:10
impeller::compiler::StructMember::BaseTypeToString
static std::string BaseTypeToString(spirv_cross::SPIRType::BaseType type)
Definition: reflector.h:46
impeller::compiler::ToString
static std::string ToString(CompilerBackend::Type type)
Definition: reflector.cc:555
utilities.h
strings.h
impeller::compiler::CompilerBackend::GetCompiler
spirv_cross::Compiler * GetCompiler()
Definition: compiler_backend.cc:54
impeller::compiler::StringToShaderStage
static std::string StringToShaderStage(const std::string &str)
Definition: reflector.cc:46
scalar.h
VALIDATION_LOG
#define VALIDATION_LOG
Definition: validation.h:73
impeller::compiler::CompilerBackend::Type::kSkSL
@ kSkSL
half.h
impeller::RuntimeStageBackend::kSkSL
@ kSkSL
std
Definition: comparable.h:95
impeller::compiler::TargetPlatform::kOpenGLDesktop
@ kOpenGLDesktop
impeller::compiler::TargetPlatform::kUnknown
@ kUnknown
impeller::compiler::TargetPlatform::kOpenGLES
@ kOpenGLES
impeller::compiler::CompilerBackend::Type::kMSL
@ kMSL
impeller::compiler::Reflector::GetShaderBundleData
std::shared_ptr< ShaderBundleData > GetShaderBundleData() const
Definition: reflector.cc:134
impeller::compiler::TargetPlatform::kRuntimeStageMetal
@ kRuntimeStageMetal
impeller::compiler::Reflector::GetReflectionJSON
std::shared_ptr< fml::Mapping > GetReflectionJSON() const
Definition: reflector.cc:108
offset
Point offset
Definition: stroke_path_geometry.cc:300
impeller::compiler::CompilerBackend::ExtendedResourceIndex::kPrimary
@ kPrimary
impeller::compiler::Reflector::Options::entry_point_name
std::string entry_point_name
Definition: reflector.h:150
impeller::compiler::Reflector::IsValid
bool IsValid() const
Definition: reflector.cc:104
impeller::compiler::GetReflectedStructSize
static size_t GetReflectedStructSize(const std::vector< StructMember > &members)
Get the reflected struct size. In the vast majority of the cases, this is the same as the declared st...
Definition: reflector.cc:778
impeller::RuntimeStageBackend::kMetal
@ kMetal
impeller::compiler::StringStartsWith
bool StringStartsWith(const std::string &target, const std::string &prefix)
Definition: utilities.cc:87
impeller
Definition: aiks_blur_unittests.cc:20
impeller::compiler::TypeNameWithPaddingOfSize
static std::string TypeNameWithPaddingOfSize(size_t size)
Definition: reflector.cc:720
impeller::compiler::Reflector::Reflector
Reflector(Options options, const std::shared_ptr< const spirv_cross::ParsedIR > &ir, const std::shared_ptr< fml::Mapping > &shader_data, const CompilerBackend &compiler)
Definition: reflector.cc:62
types.h
impeller::compiler::VertexType
Definition: reflector.cc:1172
impeller::compiler::TargetPlatform::kSkSL
@ kSkSL
impeller::compiler::TargetPlatform::kRuntimeStageGLES
@ kRuntimeStageGLES