[Flutter GPU] Shader bundle improvements: Uniform structs & member offset reflection, GLES metadata, separate from runtime stage. (flutter/engine#49485)

* Switch from legacy uniform semantics to uniform structs.
* Completely separate shader bundle from runtime stage.
* Packing multiple backends per shader.
* Pack struct and member fields into the shader bundle flatbuffer.
* Bind uniforms with correct metadata for GLES.
* Add uniform struct size and member offset reflection.
This commit is contained in:
Brandon DeRosier
2024-01-08 11:44:20 -08:00
committed by GitHub
parent 0a1f59f902
commit fa43ada615
34 changed files with 1249 additions and 426 deletions

View File

@@ -5016,6 +5016,8 @@ ORIGIN: ../../../flutter/impeller/compiler/runtime_stage_data.cc + ../../../flut
ORIGIN: ../../../flutter/impeller/compiler/runtime_stage_data.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_bundle.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_bundle.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_bundle_data.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_bundle_data.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_lib/flutter/runtime_effect.glsl + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_lib/impeller/blending.glsl + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/impeller/compiler/shader_lib/impeller/branching.glsl + ../../../flutter/LICENSE
@@ -7831,6 +7833,8 @@ FILE: ../../../flutter/impeller/compiler/runtime_stage_data.cc
FILE: ../../../flutter/impeller/compiler/runtime_stage_data.h
FILE: ../../../flutter/impeller/compiler/shader_bundle.cc
FILE: ../../../flutter/impeller/compiler/shader_bundle.h
FILE: ../../../flutter/impeller/compiler/shader_bundle_data.cc
FILE: ../../../flutter/impeller/compiler/shader_bundle_data.h
FILE: ../../../flutter/impeller/compiler/shader_lib/flutter/runtime_effect.glsl
FILE: ../../../flutter/impeller/compiler/shader_lib/impeller/blending.glsl
FILE: ../../../flutter/impeller/compiler/shader_lib/impeller/branching.glsl

View File

@@ -48,6 +48,8 @@ impeller_component("compiler_lib") {
"runtime_stage_data.h",
"shader_bundle.cc",
"shader_bundle.h",
"shader_bundle_data.cc",
"shader_bundle_data.h",
"source_options.cc",
"source_options.h",
"spirv_compiler.cc",

View File

@@ -15,6 +15,7 @@
#include "impeller/base/strings.h"
#include "impeller/base/validation.h"
#include "impeller/compiler/code_gen_template.h"
#include "impeller/compiler/shader_bundle_data.h"
#include "impeller/compiler/types.h"
#include "impeller/compiler/uniform_sorter.h"
#include "impeller/compiler/utilities.h"
@@ -131,6 +132,11 @@ Reflector::Reflector(Options options,
runtime_stage_shader_ = GenerateRuntimeStageData();
shader_bundle_data_ = GenerateShaderBundleData();
if (!shader_bundle_data_) {
return;
}
is_valid_ = true;
}
@@ -166,6 +172,10 @@ std::shared_ptr<RuntimeStageData::Shader> Reflector::GetRuntimeStageShaderData()
return runtime_stage_shader_;
}
std::shared_ptr<ShaderBundleData> Reflector::GetShaderBundleData() const {
return shader_bundle_data_;
}
std::optional<nlohmann::json> Reflector::GenerateTemplateArguments() const {
nlohmann::json root;
@@ -407,6 +417,103 @@ std::shared_ptr<RuntimeStageData::Shader> Reflector::GenerateRuntimeStageData()
return data;
}
std::shared_ptr<ShaderBundleData> Reflector::GenerateShaderBundleData() const {
const auto& entrypoints = compiler_->get_entry_points_and_stages();
if (entrypoints.size() != 1u) {
VALIDATION_LOG << "Single entrypoint not found.";
return nullptr;
}
auto data = std::make_shared<ShaderBundleData>(
options_.entry_point_name, //
entrypoints.front().execution_model, //
options_.target_platform //
);
data->SetShaderData(shader_data_);
const auto uniforms = compiler_->get_shader_resources().uniform_buffers;
for (const auto& uniform : uniforms) {
ShaderBundleData::ShaderUniformStruct uniform_struct;
uniform_struct.name = uniform.name;
uniform_struct.ext_res_0 = compiler_.GetExtendedMSLResourceBinding(
CompilerBackend::ExtendedResourceIndex::kPrimary, uniform.id);
uniform_struct.set = compiler_->get_decoration(
uniform.id, spv::Decoration::DecorationDescriptorSet);
uniform_struct.binding = compiler_->get_decoration(
uniform.id, spv::Decoration::DecorationBinding);
const auto type = compiler_->get_type(uniform.type_id);
if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) {
std::cerr << "Error: Uniform \"" << uniform.name
<< "\" is not a struct. All Flutter GPU shader uniforms must "
"be structs."
<< std::endl;
return nullptr;
}
size_t size_in_bytes = 0;
for (const auto& struct_member : ReadStructMembers(uniform.type_id)) {
size_in_bytes += struct_member.byte_length;
if (StringStartsWith(struct_member.name, "_PADDING_")) {
continue;
}
ShaderBundleData::ShaderUniformStructField uniform_struct_field;
uniform_struct_field.name = struct_member.name;
uniform_struct_field.type = struct_member.base_type;
uniform_struct_field.offset_in_bytes = struct_member.offset;
uniform_struct_field.element_size_in_bytes = struct_member.size;
uniform_struct_field.total_size_in_bytes = struct_member.byte_length;
uniform_struct_field.array_elements = struct_member.array_elements;
uniform_struct.fields.push_back(uniform_struct_field);
}
uniform_struct.size_in_bytes = size_in_bytes;
data->AddUniformStruct(uniform_struct);
}
const auto sampled_images = compiler_->get_shader_resources().sampled_images;
for (const auto& image : sampled_images) {
ShaderBundleData::ShaderUniformTexture uniform_texture;
uniform_texture.name = image.name;
uniform_texture.ext_res_0 = compiler_.GetExtendedMSLResourceBinding(
CompilerBackend::ExtendedResourceIndex::kPrimary, image.id);
uniform_texture.set = compiler_->get_decoration(
image.id, spv::Decoration::DecorationDescriptorSet);
uniform_texture.binding =
compiler_->get_decoration(image.id, spv::Decoration::DecorationBinding);
data->AddUniformTexture(uniform_texture);
}
// We only need to worry about storing vertex attributes.
if (entrypoints.front().execution_model == spv::ExecutionModelVertex) {
const auto inputs = compiler_->get_shader_resources().stage_inputs;
auto input_offsets = ComputeOffsets(inputs);
for (const auto& input : inputs) {
auto location = compiler_->get_decoration(
input.id, spv::Decoration::DecorationLocation);
std::optional<size_t> offset = input_offsets[location];
const auto type = compiler_->get_type(input.type_id);
InputDescription input_description;
input_description.name = input.name;
input_description.location = compiler_->get_decoration(
input.id, spv::Decoration::DecorationLocation);
input_description.set = compiler_->get_decoration(
input.id, spv::Decoration::DecorationDescriptorSet);
input_description.binding = compiler_->get_decoration(
input.id, spv::Decoration::DecorationBinding);
input_description.type = type.basetype;
input_description.bit_width = type.width;
input_description.vec_size = type.vecsize;
input_description.columns = type.columns;
input_description.offset = offset.value_or(0u);
data->AddInputDescription(std::move(input_description));
}
}
return data;
}
std::optional<uint32_t> Reflector::GetArrayElements(
const spirv_cross::SPIRType& type) const {
if (type.array.empty()) {
@@ -530,7 +637,7 @@ std::optional<nlohmann::json::object_t> Reflector::ReflectType(
auto member = nlohmann::json::object_t{};
member["name"] = struct_member.name;
member["type"] = struct_member.type;
member["base_type"] = struct_member.base_type;
member["base_type"] = BaseTypeToString(struct_member.base_type);
member["offset"] = struct_member.offset;
member["size"] = struct_member.size;
member["byte_length"] = struct_member.byte_length;
@@ -657,8 +764,8 @@ std::vector<StructMember> Reflector::ReadStructMembers(
if (struct_member_offset > current_byte_offset) {
const auto alignment_pad = struct_member_offset - current_byte_offset;
result.emplace_back(StructMember{
TypeNameWithPaddingOfSize(alignment_pad), // type
BaseTypeToString(spirv_cross::SPIRType::BaseType::Void), // basetype
TypeNameWithPaddingOfSize(alignment_pad), // type
spirv_cross::SPIRType::BaseType::Void, // basetype
SPrintF("_PADDING_%s_",
GetMemberNameAtIndex(struct_type, i).c_str()), // name
current_byte_offset, // offset
@@ -687,7 +794,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - size;
result.emplace_back(StructMember{
compiler_->get_name(member.self), // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
size, // size
@@ -710,7 +817,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(Matrix);
result.emplace_back(StructMember{
"Matrix", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(Matrix), // size
@@ -733,7 +840,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(UintPoint32);
result.emplace_back(StructMember{
"UintPoint32", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(UintPoint32), // size
@@ -756,7 +863,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(IPoint32);
result.emplace_back(StructMember{
"IPoint32", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(IPoint32), // size
@@ -778,7 +885,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(Point);
result.emplace_back(StructMember{
"Point", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(Point), // size
@@ -800,7 +907,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(Vector3);
result.emplace_back(StructMember{
"Vector3", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(Vector3), // size
@@ -822,7 +929,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(Vector4);
result.emplace_back(StructMember{
"Vector4", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(Vector4), // size
@@ -845,7 +952,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(HalfVector2);
result.emplace_back(StructMember{
"HalfVector2", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(HalfVector2), // size
@@ -868,7 +975,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(HalfVector3);
result.emplace_back(StructMember{
"HalfVector3", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(HalfVector3), // size
@@ -891,7 +998,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
uint32_t element_padding = stride - sizeof(HalfVector4);
result.emplace_back(StructMember{
"HalfVector4", // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
sizeof(HalfVector4), // size
@@ -918,7 +1025,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
// Add the type directly.
result.emplace_back(StructMember{
maybe_known_type.value().name, // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
maybe_known_type.value().byte_size, // size
@@ -942,7 +1049,7 @@ std::vector<StructMember> Reflector::ReadStructMembers(
auto element_padding = stride - size;
result.emplace_back(StructMember{
TypeNameWithPaddingOfSize(size), // type
BaseTypeToString(member.basetype), // basetype
member.basetype, // basetype
GetMemberNameAtIndex(struct_type, i), // name
struct_member_offset, // offset
size, // size
@@ -962,15 +1069,14 @@ std::vector<StructMember> Reflector::ReadStructMembers(
if (excess != 0) {
const auto padding = max_member_alignment - excess;
result.emplace_back(StructMember{
TypeNameWithPaddingOfSize(padding), // type
BaseTypeToString(
spirv_cross::SPIRType::BaseType::Void), // basetype
"_PADDING_", // name
current_byte_offset, // offset
padding, // size
padding, // byte_length
std::nullopt, // array_elements
0, // element_padding
TypeNameWithPaddingOfSize(padding), // type
spirv_cross::SPIRType::BaseType::Void, // basetype
"_PADDING_", // name
current_byte_offset, // offset
padding, // size
padding, // byte_length
std::nullopt, // array_elements
0, // element_padding
});
}
}
@@ -1011,7 +1117,7 @@ nlohmann::json::object_t Reflector::EmitStructDefinition(
auto& member = members.emplace_back(nlohmann::json::object_t{});
member["name"] = struct_member.name;
member["type"] = struct_member.type;
member["base_type"] = struct_member.base_type;
member["base_type"] = BaseTypeToString(struct_member.base_type);
member["offset"] = struct_member.offset;
member["byte_length"] = struct_member.byte_length;
if (struct_member.array_elements.has_value()) {
@@ -1026,7 +1132,7 @@ nlohmann::json::object_t Reflector::EmitStructDefinition(
struct VertexType {
std::string type_name;
std::string base_type_name;
spirv_cross::SPIRType::BaseType base_type;
std::string variable_name;
size_t byte_length = 0u;
};
@@ -1037,7 +1143,7 @@ static VertexType VertexTypeFromInputResource(
VertexType result;
result.variable_name = resource->name;
const auto type = compiler.get_type(resource->type_id);
result.base_type_name = BaseTypeToString(type.basetype);
result.base_type = type.basetype;
const auto total_size = type.columns * type.vecsize * type.width / 8u;
result.byte_length = total_size;
@@ -1126,14 +1232,14 @@ Reflector::ReflectPerVertexStructDefinition(
VertexTypeFromInputResource(*compiler_.GetCompiler(), resource);
auto member = StructMember{
vertex_type.type_name, // type
vertex_type.base_type_name, // base type
vertex_type.variable_name, // name
struc.byte_length, // offset
vertex_type.byte_length, // size
vertex_type.byte_length, // byte_length
std::nullopt, // array_elements
0, // element_padding
vertex_type.type_name, // type
vertex_type.base_type, // base type
vertex_type.variable_name, // name
struc.byte_length, // offset
vertex_type.byte_length, // size
vertex_type.byte_length, // byte_length
std::nullopt, // array_elements
0, // element_padding
};
struc.byte_length += vertex_type.byte_length;
struc.members.emplace_back(std::move(member));

View File

@@ -13,6 +13,7 @@
#include "flutter/fml/mapping.h"
#include "impeller/compiler/compiler_backend.h"
#include "impeller/compiler/runtime_stage_data.h"
#include "impeller/compiler/shader_bundle_data.h"
#include "inja/inja.hpp"
#include "spirv_msl.hpp"
#include "spirv_parser.hpp"
@@ -22,7 +23,7 @@ namespace compiler {
struct StructMember {
std::string type;
std::string base_type;
spirv_cross::SPIRType::BaseType base_type;
std::string name;
size_t offset = 0u;
size_t size = 0u;
@@ -31,7 +32,7 @@ struct StructMember {
size_t element_padding = 0u;
StructMember(std::string p_type,
std::string p_base_type,
spirv_cross::SPIRType::BaseType p_base_type,
std::string p_name,
size_t p_offset,
size_t p_size,
@@ -39,7 +40,7 @@ struct StructMember {
std::optional<size_t> p_array_elements,
size_t p_element_padding)
: type(std::move(p_type)),
base_type(std::move(p_base_type)),
base_type(p_base_type),
name(std::move(p_name)),
offset(p_offset),
size(p_size),
@@ -74,6 +75,8 @@ class Reflector {
std::shared_ptr<RuntimeStageData::Shader> GetRuntimeStageShaderData() const;
std::shared_ptr<ShaderBundleData> GetShaderBundleData() const;
private:
struct StructDefinition {
std::string name;
@@ -101,6 +104,7 @@ class Reflector {
std::shared_ptr<fml::Mapping> reflection_header_;
std::shared_ptr<fml::Mapping> reflection_cc_;
std::shared_ptr<RuntimeStageData::Shader> runtime_stage_shader_;
std::shared_ptr<ShaderBundleData> shader_bundle_data_;
bool is_valid_ = false;
std::optional<nlohmann::json> GenerateTemplateArguments() const;
@@ -111,6 +115,8 @@ class Reflector {
std::shared_ptr<RuntimeStageData::Shader> GenerateRuntimeStageData() const;
std::shared_ptr<ShaderBundleData> GenerateShaderBundleData() const;
std::shared_ptr<fml::Mapping> InflateTemplate(std::string_view tmpl) const;
std::optional<nlohmann::json::object_t> ReflectResource(

View File

@@ -293,79 +293,92 @@ std::shared_ptr<fml::Mapping> RuntimeStageData::CreateJsonMapping() const {
json_string->size(), [json_string](auto, auto) {});
}
std::unique_ptr<fb::RuntimeStagesT> RuntimeStageData::CreateFlatbuffer() const {
std::unique_ptr<fb::RuntimeStageT> RuntimeStageData::CreateStageFlatbuffer(
impeller::RuntimeStageBackend backend) const {
auto kvp = data_.find(backend);
if (kvp == data_.end()) {
return nullptr;
}
auto runtime_stage = std::make_unique<fb::RuntimeStageT>();
runtime_stage->entrypoint = kvp->second->entrypoint;
const auto stage = ToStage(kvp->second->stage);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid runtime stage.";
return nullptr;
}
runtime_stage->stage = stage.value();
if (!kvp->second->shader) {
VALIDATION_LOG << "No shader specified for runtime stage.";
return nullptr;
}
if (kvp->second->shader->GetSize() > 0u) {
runtime_stage->shader = {
kvp->second->shader->GetMapping(),
kvp->second->shader->GetMapping() + kvp->second->shader->GetSize()};
}
for (const auto& uniform : kvp->second->uniforms) {
auto desc = std::make_unique<fb::UniformDescriptionT>();
desc->name = uniform.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->location = uniform.location;
desc->rows = uniform.rows;
desc->columns = uniform.columns;
auto uniform_type = ToUniformType(uniform.type);
if (!uniform_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = uniform_type.value();
desc->bit_width = uniform.bit_width;
if (uniform.array_elements.has_value()) {
desc->array_elements = uniform.array_elements.value();
}
runtime_stage->uniforms.emplace_back(std::move(desc));
}
for (const auto& input : kvp->second->inputs) {
auto desc = std::make_unique<fb::StageInputT>();
desc->name = input.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Stage input name cannot be empty.";
return nullptr;
}
desc->location = input.location;
desc->set = input.set;
desc->binding = input.binding;
auto input_type = ToInputType(input.type);
if (!input_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = input_type.value();
desc->bit_width = input.bit_width;
desc->vec_size = input.vec_size;
desc->columns = input.columns;
desc->offset = input.offset;
runtime_stage->inputs.emplace_back(std::move(desc));
}
return runtime_stage;
}
std::unique_ptr<fb::RuntimeStagesT>
RuntimeStageData::CreateMultiStageFlatbuffer() const {
// The high level object API is used here for writing to the buffer. This is
// just a convenience.
auto runtime_stages = std::make_unique<fb::RuntimeStagesT>();
for (const auto& kvp : data_) {
auto runtime_stage = std::make_unique<fb::RuntimeStageT>();
runtime_stage->entrypoint = kvp.second->entrypoint;
const auto stage = ToStage(kvp.second->stage);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid runtime stage.";
return nullptr;
}
runtime_stage->stage = stage.value();
if (!kvp.second->shader) {
VALIDATION_LOG << "No shader specified for runtime stage.";
return nullptr;
}
if (kvp.second->shader->GetSize() > 0u) {
runtime_stage->shader = {
kvp.second->shader->GetMapping(),
kvp.second->shader->GetMapping() + kvp.second->shader->GetSize()};
}
for (const auto& uniform : kvp.second->uniforms) {
auto desc = std::make_unique<fb::UniformDescriptionT>();
desc->name = uniform.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->location = uniform.location;
desc->rows = uniform.rows;
desc->columns = uniform.columns;
auto uniform_type = ToUniformType(uniform.type);
if (!uniform_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = uniform_type.value();
desc->bit_width = uniform.bit_width;
if (uniform.array_elements.has_value()) {
desc->array_elements = uniform.array_elements.value();
}
runtime_stage->uniforms.emplace_back(std::move(desc));
}
for (const auto& input : kvp.second->inputs) {
auto desc = std::make_unique<fb::StageInputT>();
desc->name = input.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Stage input name cannot be empty.";
return nullptr;
}
desc->location = input.location;
desc->set = input.set;
desc->binding = input.binding;
auto input_type = ToInputType(input.type);
if (!input_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = input_type.value();
desc->bit_width = input.bit_width;
desc->vec_size = input.vec_size;
desc->columns = input.columns;
desc->offset = input.offset;
runtime_stage->inputs.emplace_back(std::move(desc));
}
auto runtime_stage = CreateStageFlatbuffer(kvp.first);
switch (kvp.first) {
case RuntimeStageBackend::kSkSL:
runtime_stages->sksl = std::move(runtime_stage);
@@ -385,7 +398,7 @@ std::unique_ptr<fb::RuntimeStagesT> RuntimeStageData::CreateFlatbuffer() const {
}
std::shared_ptr<fml::Mapping> RuntimeStageData::CreateMapping() const {
auto runtime_stages = CreateFlatbuffer();
auto runtime_stages = CreateMultiStageFlatbuffer();
if (!runtime_stages) {
return nullptr;
}

View File

@@ -18,29 +18,6 @@
namespace impeller {
namespace compiler {
struct UniformDescription {
std::string name;
size_t location = 0u;
spirv_cross::SPIRType::BaseType type = spirv_cross::SPIRType::BaseType::Float;
size_t rows = 0u;
size_t columns = 0u;
size_t bit_width = 0u;
std::optional<size_t> array_elements = std::nullopt;
};
struct InputDescription {
std::string name;
size_t location;
size_t set;
size_t binding;
spirv_cross::SPIRType::BaseType type =
spirv_cross::SPIRType::BaseType::Unknown;
size_t bit_width;
size_t vec_size;
size_t columns;
size_t offset;
};
class RuntimeStageData {
public:
struct Shader {
@@ -63,7 +40,10 @@ class RuntimeStageData {
void AddShader(const std::shared_ptr<Shader>& data);
std::unique_ptr<fb::RuntimeStagesT> CreateFlatbuffer() const;
std::unique_ptr<fb::RuntimeStageT> CreateStageFlatbuffer(
impeller::RuntimeStageBackend backend) const;
std::unique_ptr<fb::RuntimeStagesT> CreateMultiStageFlatbuffer() const;
std::shared_ptr<fml::Mapping> CreateJsonMapping() const;

View File

@@ -81,12 +81,12 @@ std::optional<ShaderBundleConfig> ParseShaderBundleConfig(
return bundle;
}
static std::unique_ptr<fb::ShaderT> GenerateShaderFB(
SourceOptions options,
const std::string& shader_name,
const ShaderConfig& shader_config) {
auto result = std::make_unique<fb::ShaderT>();
result->name = shader_name;
static std::unique_ptr<fb::shaderbundle::BackendShaderT>
GenerateShaderBackendFB(TargetPlatform target_platform,
SourceOptions& options,
const std::string& shader_name,
const ShaderConfig& shader_config) {
auto result = std::make_unique<fb::shaderbundle::BackendShaderT>();
std::shared_ptr<fml::FileMapping> source_file_mapping =
fml::FileMapping::CreateReadOnly(shader_config.source_file_name);
@@ -97,6 +97,8 @@ static std::unique_ptr<fb::ShaderT> GenerateShaderFB(
}
/// Override options.
options.target_platform = target_platform;
options.file_name = shader_name; // This is just used for error messages.
options.type = shader_config.type;
options.source_language = shader_config.language;
options.entry_point_name = EntryPointFunctionNameFromSourceName(
@@ -123,16 +125,15 @@ static std::unique_ptr<fb::ShaderT> GenerateShaderFB(
return nullptr;
}
auto stage_data = reflector->GetRuntimeStageShaderData();
if (!stage_data) {
std::cerr << "Runtime stage information was nil for bundled shader \""
<< shader_name << "\"." << std::endl;
auto bundle_data = reflector->GetShaderBundleData();
if (!bundle_data) {
std::cerr << "Bundled shader information was nil for \"" << shader_name
<< "\"." << std::endl;
return nullptr;
}
RuntimeStageData stages;
stages.AddShader(stage_data);
result->shader = stages.CreateFlatbuffer();
if (!result->shader) {
result = bundle_data->CreateFlatbuffer();
if (!result) {
std::cerr << "Failed to create flatbuffer for bundled shader \""
<< shader_name << "\"." << std::endl;
return nullptr;
@@ -141,7 +142,41 @@ static std::unique_ptr<fb::ShaderT> GenerateShaderFB(
return result;
}
std::optional<fb::ShaderBundleT> GenerateShaderBundleFlatbuffer(
static std::unique_ptr<fb::shaderbundle::ShaderT> GenerateShaderFB(
SourceOptions options,
const std::string& shader_name,
const ShaderConfig& shader_config) {
auto result = std::make_unique<fb::shaderbundle::ShaderT>();
result->name = shader_name;
result->metal_ios = GenerateShaderBackendFB(
TargetPlatform::kMetalIOS, options, shader_name, shader_config);
if (!result->metal_ios) {
return nullptr;
}
result->metal_desktop = GenerateShaderBackendFB(
TargetPlatform::kMetalDesktop, options, shader_name, shader_config);
if (!result->metal_desktop) {
return nullptr;
}
result->opengl_es = GenerateShaderBackendFB(
TargetPlatform::kOpenGLES, options, shader_name, shader_config);
if (!result->opengl_es) {
return nullptr;
}
result->opengl_desktop = GenerateShaderBackendFB(
TargetPlatform::kOpenGLDesktop, options, shader_name, shader_config);
if (!result->opengl_desktop) {
return nullptr;
}
result->vulkan = GenerateShaderBackendFB(TargetPlatform::kVulkan, options,
shader_name, shader_config);
if (!result->vulkan) {
return nullptr;
}
return result;
}
std::optional<fb::shaderbundle::ShaderBundleT> GenerateShaderBundleFlatbuffer(
const std::string& bundle_config_json,
const SourceOptions& options) {
// --------------------------------------------------------------------------
@@ -158,10 +193,10 @@ std::optional<fb::ShaderBundleT> GenerateShaderBundleFlatbuffer(
/// 2. Build the deserialized shader bundle.
///
fb::ShaderBundleT shader_bundle;
fb::shaderbundle::ShaderBundleT shader_bundle;
for (const auto& [shader_name, shader_config] : bundle_config.value()) {
std::unique_ptr<fb::ShaderT> shader =
std::unique_ptr<fb::shaderbundle::ShaderT> shader =
GenerateShaderFB(options, shader_name, shader_config);
if (!shader) {
return std::nullopt;
@@ -190,9 +225,9 @@ bool GenerateShaderBundle(Switches& switches) {
///
auto builder = std::make_shared<flatbuffers::FlatBufferBuilder>();
builder->Finish(
fb::ShaderBundle::Pack(*builder.get(), &shader_bundle.value()),
fb::ShaderBundleIdentifier());
builder->Finish(fb::shaderbundle::ShaderBundle::Pack(*builder.get(),
&shader_bundle.value()),
fb::shaderbundle::ShaderBundleIdentifier());
auto mapping = std::make_shared<fml::NonOwnedMapping>(
builder->GetBufferPointer(), builder->GetSize(),
[builder](auto, auto) {});

View File

@@ -22,7 +22,7 @@ std::optional<ShaderBundleConfig> ParseShaderBundleConfig(
///
/// @note Exposed only for testing purposes. Use `GenerateShaderBundle`
/// directly.
std::optional<fb::ShaderBundleT> GenerateShaderBundleFlatbuffer(
std::optional<fb::shaderbundle::ShaderBundleT> GenerateShaderBundleFlatbuffer(
const std::string& bundle_config_json,
const SourceOptions& options);

View File

@@ -0,0 +1,241 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/compiler/shader_bundle_data.h"
#include <optional>
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
#include "impeller/base/validation.h"
namespace impeller {
namespace compiler {
ShaderBundleData::ShaderBundleData(std::string entrypoint,
spv::ExecutionModel stage,
TargetPlatform target_platform)
: entrypoint_(std::move(entrypoint)),
stage_(stage),
target_platform_(target_platform) {}
ShaderBundleData::~ShaderBundleData() = default;
void ShaderBundleData::AddUniformStruct(ShaderUniformStruct uniform_struct) {
uniform_structs_.emplace_back(std::move(uniform_struct));
}
void ShaderBundleData::AddUniformTexture(ShaderUniformTexture uniform_texture) {
uniform_textures_.emplace_back(std::move(uniform_texture));
}
void ShaderBundleData::AddInputDescription(InputDescription input) {
inputs_.emplace_back(std::move(input));
}
void ShaderBundleData::SetShaderData(std::shared_ptr<fml::Mapping> shader) {
shader_ = std::move(shader);
}
static std::optional<fb::shaderbundle::ShaderStage> ToStage(
spv::ExecutionModel stage) {
switch (stage) {
case spv::ExecutionModel::ExecutionModelVertex:
return fb::shaderbundle::ShaderStage::kVertex;
case spv::ExecutionModel::ExecutionModelFragment:
return fb::shaderbundle::ShaderStage::kFragment;
case spv::ExecutionModel::ExecutionModelGLCompute:
return fb::shaderbundle::ShaderStage::kCompute;
default:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::shaderbundle::UniformDataType> ToUniformType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return fb::shaderbundle::UniformDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return fb::shaderbundle::UniformDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return fb::shaderbundle::UniformDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return fb::shaderbundle::UniformDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return fb::shaderbundle::UniformDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return fb::shaderbundle::UniformDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return fb::shaderbundle::UniformDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return fb::shaderbundle::UniformDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return fb::shaderbundle::UniformDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Half:
return fb::shaderbundle::UniformDataType::kHalfFloat;
case spirv_cross::SPIRType::Float:
return fb::shaderbundle::UniformDataType::kFloat;
case spirv_cross::SPIRType::Double:
return fb::shaderbundle::UniformDataType::kDouble;
case spirv_cross::SPIRType::SampledImage:
return fb::shaderbundle::UniformDataType::kSampledImage;
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Char:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::Struct:
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::shaderbundle::InputDataType> ToInputType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return fb::shaderbundle::InputDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return fb::shaderbundle::InputDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return fb::shaderbundle::InputDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return fb::shaderbundle::InputDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return fb::shaderbundle::InputDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return fb::shaderbundle::InputDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return fb::shaderbundle::InputDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return fb::shaderbundle::InputDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return fb::shaderbundle::InputDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Float:
return fb::shaderbundle::InputDataType::kFloat;
case spirv_cross::SPIRType::Double:
return fb::shaderbundle::InputDataType::kDouble;
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
case spirv_cross::SPIRType::Half:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Struct:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::SampledImage:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::Char:
return std::nullopt;
}
FML_UNREACHABLE();
}
std::unique_ptr<fb::shaderbundle::BackendShaderT>
ShaderBundleData::CreateFlatbuffer() const {
auto shader_bundle = std::make_unique<fb::shaderbundle::BackendShaderT>();
// The high level object API is used here for writing to the buffer. This is
// just a convenience.
shader_bundle->entrypoint = entrypoint_;
const auto stage = ToStage(stage_);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid shader bundle.";
return nullptr;
}
shader_bundle->stage = stage.value();
// This field is ignored, so just set it to anything.
if (!shader_) {
VALIDATION_LOG << "No shader specified for shader bundle.";
return nullptr;
}
if (shader_->GetSize() > 0u) {
shader_bundle->shader = {shader_->GetMapping(),
shader_->GetMapping() + shader_->GetSize()};
}
for (const auto& uniform : uniform_structs_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderUniformStructT>();
desc->name = uniform.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->ext_res_0 = uniform.ext_res_0;
desc->set = uniform.set;
desc->binding = uniform.binding;
desc->size_in_bytes = uniform.size_in_bytes;
for (const auto& field : uniform.fields) {
auto field_desc =
std::make_unique<fb::shaderbundle::ShaderUniformStructFieldT>();
field_desc->name = field.name;
auto type = ToUniformType(field.type);
if (!type.has_value()) {
VALIDATION_LOG << " Invalid shader type " << field.type << ".";
return nullptr;
}
field_desc->type = type.value();
field_desc->offset_in_bytes = field.offset_in_bytes;
field_desc->element_size_in_bytes = field.element_size_in_bytes;
field_desc->total_size_in_bytes = field.total_size_in_bytes;
field_desc->array_elements = field.array_elements.value_or(0);
desc->fields.push_back(std::move(field_desc));
}
shader_bundle->uniform_structs.emplace_back(std::move(desc));
}
for (const auto& texture : uniform_textures_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderUniformTextureT>();
desc->name = texture.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->ext_res_0 = texture.ext_res_0;
desc->set = texture.set;
desc->binding = texture.binding;
shader_bundle->uniform_textures.emplace_back(std::move(desc));
}
for (const auto& input : inputs_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderInputT>();
desc->name = input.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Stage input name cannot be empty.";
return nullptr;
}
desc->location = input.location;
desc->set = input.set;
desc->binding = input.binding;
auto input_type = ToInputType(input.type);
if (!input_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = input_type.value();
desc->bit_width = input.bit_width;
desc->vec_size = input.vec_size;
desc->columns = input.columns;
desc->offset = input.offset;
shader_bundle->inputs.emplace_back(std::move(desc));
}
return shader_bundle;
}
} // namespace compiler
} // namespace impeller

View File

@@ -0,0 +1,82 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_
#define FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_
#include <memory>
#include <vector>
#include "flutter/fml/mapping.h"
#include "impeller/compiler/types.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
namespace impeller {
namespace compiler {
class ShaderBundleData {
public:
struct ShaderUniformStructField {
std::string name;
spirv_cross::SPIRType::BaseType type =
spirv_cross::SPIRType::BaseType::Float;
size_t offset_in_bytes = 0u;
size_t element_size_in_bytes = 0u;
size_t total_size_in_bytes = 0u;
std::optional<size_t> array_elements = std::nullopt;
};
struct ShaderUniformStruct {
std::string name;
size_t ext_res_0 = 0u;
size_t set = 0u;
size_t binding = 0u;
size_t size_in_bytes = 0u;
std::vector<ShaderUniformStructField> fields;
};
struct ShaderUniformTexture {
std::string name;
size_t ext_res_0 = 0u;
size_t set = 0u;
size_t binding = 0u;
};
ShaderBundleData(std::string entrypoint,
spv::ExecutionModel stage,
TargetPlatform target_platform);
~ShaderBundleData();
void AddUniformStruct(ShaderUniformStruct uniform_struct);
void AddUniformTexture(ShaderUniformTexture uniform_texture);
void AddInputDescription(InputDescription input);
void SetShaderData(std::shared_ptr<fml::Mapping> shader);
void SetSkSLData(std::shared_ptr<fml::Mapping> sksl);
std::unique_ptr<fb::shaderbundle::BackendShaderT> CreateFlatbuffer() const;
private:
const std::string entrypoint_;
const spv::ExecutionModel stage_;
const TargetPlatform target_platform_;
std::vector<ShaderUniformStruct> uniform_structs_;
std::vector<ShaderUniformTexture> uniform_textures_;
std::vector<InputDescription> inputs_;
std::shared_ptr<fml::Mapping> shader_;
std::shared_ptr<fml::Mapping> sksl_;
ShaderBundleData(const ShaderBundleData&) = delete;
ShaderBundleData& operator=(const ShaderBundleData&) = delete;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_

View File

@@ -8,7 +8,6 @@
#include "flutter/testing/testing.h"
#include "impeller/compiler/source_options.h"
#include "impeller/compiler/types.h"
#include "impeller/runtime_stage/runtime_stage_types_flatbuffers.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
namespace impeller {
@@ -141,7 +140,7 @@ TEST(ShaderBundleTest, GenerateShaderBundleFlatbufferProducesCorrectResult) {
options.target_platform = TargetPlatform::kRuntimeStageMetal;
options.source_language = SourceLanguage::kGLSL;
std::optional<fb::ShaderBundleT> bundle =
std::optional<fb::shaderbundle::ShaderBundleT> bundle =
GenerateShaderBundleFlatbuffer(config, options);
ASSERT_TRUE(bundle.has_value());
@@ -156,57 +155,62 @@ TEST(ShaderBundleTest, GenerateShaderBundleFlatbufferProducesCorrectResult) {
/// Verify vertex shader.
///
EXPECT_TRUE(vertex->shader->metal);
EXPECT_STREQ(vertex->shader->metal->entrypoint.c_str(),
EXPECT_STREQ(vertex->metal_desktop->entrypoint.c_str(),
"flutter_gpu_unlit_vertex_main");
EXPECT_EQ(vertex->shader->metal->stage, fb::Stage::kVertex);
EXPECT_EQ(vertex->metal_desktop->stage,
fb::shaderbundle::ShaderStage::kVertex);
// Inputs.
ASSERT_EQ(vertex->shader->metal->inputs.size(), 1u);
const auto& v_in_position = vertex->shader->metal->inputs[0];
ASSERT_EQ(vertex->metal_desktop->inputs.size(), 1u);
const auto& v_in_position = vertex->metal_desktop->inputs[0];
EXPECT_STREQ(v_in_position->name.c_str(), "position");
EXPECT_EQ(v_in_position->location, 0u);
EXPECT_EQ(v_in_position->set, 0u);
EXPECT_EQ(v_in_position->binding, 0u);
EXPECT_EQ(v_in_position->type, fb::InputDataType::kFloat);
EXPECT_EQ(v_in_position->type, fb::shaderbundle::InputDataType::kFloat);
EXPECT_EQ(v_in_position->bit_width, 32u);
EXPECT_EQ(v_in_position->vec_size, 2u);
EXPECT_EQ(v_in_position->columns, 1u);
EXPECT_EQ(v_in_position->offset, 0u);
// Uniforms.
ASSERT_EQ(vertex->shader->metal->uniforms.size(), 2u);
const auto* v_mvp = FindByName(vertex->shader->metal->uniforms, "mvp");
ASSERT_NE(v_mvp, nullptr);
EXPECT_EQ(v_mvp->location, 0u);
EXPECT_EQ(v_mvp->type, fb::UniformDataType::kFloat);
EXPECT_EQ(v_mvp->bit_width, 32u);
EXPECT_EQ(v_mvp->rows, 4u);
EXPECT_EQ(v_mvp->columns, 4u);
EXPECT_EQ(v_mvp->array_elements, 0u);
const auto* v_color = FindByName(vertex->shader->metal->uniforms, "color");
ASSERT_NE(v_color, nullptr);
EXPECT_EQ(v_color->location, 1u);
EXPECT_EQ(v_color->type, fb::UniformDataType::kFloat);
EXPECT_EQ(v_color->bit_width, 32u);
EXPECT_EQ(v_color->rows, 4u);
EXPECT_EQ(v_color->columns, 1u);
EXPECT_EQ(v_color->array_elements, 0u);
ASSERT_EQ(vertex->metal_desktop->uniform_structs.size(), 1u);
const auto* vert_info =
FindByName(vertex->metal_desktop->uniform_structs, "VertInfo");
ASSERT_NE(vert_info, nullptr);
EXPECT_EQ(vert_info->ext_res_0, 0u);
EXPECT_EQ(vert_info->set, 0u);
EXPECT_EQ(vert_info->binding, 0u);
ASSERT_EQ(vert_info->fields.size(), 2u);
const auto& mvp = vert_info->fields[0];
EXPECT_STREQ(mvp->name.c_str(), "mvp");
EXPECT_EQ(mvp->type, fb::shaderbundle::UniformDataType::kFloat);
EXPECT_EQ(mvp->offset_in_bytes, 0u);
EXPECT_EQ(mvp->element_size_in_bytes, 64u);
EXPECT_EQ(mvp->total_size_in_bytes, 64u);
EXPECT_EQ(mvp->array_elements, 0u);
const auto& color = vert_info->fields[1];
EXPECT_STREQ(color->name.c_str(), "color");
EXPECT_EQ(color->type, fb::shaderbundle::UniformDataType::kFloat);
EXPECT_EQ(color->offset_in_bytes, 64u);
EXPECT_EQ(color->element_size_in_bytes, 16u);
EXPECT_EQ(color->total_size_in_bytes, 16u);
EXPECT_EQ(color->array_elements, 0u);
// --------------------------------------------------------------------------
/// Verify fragment shader.
///
EXPECT_TRUE(fragment->shader->metal);
EXPECT_STREQ(fragment->shader->metal->entrypoint.c_str(),
EXPECT_STREQ(fragment->metal_desktop->entrypoint.c_str(),
"flutter_gpu_unlit_fragment_main");
EXPECT_EQ(fragment->shader->metal->stage, fb::Stage::kFragment);
EXPECT_EQ(fragment->metal_desktop->stage,
fb::shaderbundle::ShaderStage::kFragment);
// Inputs (not recorded for fragment shaders).
ASSERT_EQ(fragment->shader->metal->inputs.size(), 0u);
ASSERT_EQ(fragment->metal_desktop->inputs.size(), 0u);
// Uniforms.
ASSERT_EQ(fragment->shader->metal->inputs.size(), 0u);
ASSERT_EQ(fragment->metal_desktop->inputs.size(), 0u);
}
} // namespace testing

View File

@@ -244,14 +244,15 @@ bool Switches::AreValid(std::ostream& explain) const {
const bool shader_bundle_mode = !shader_bundle.empty();
bool valid = true;
if (target_platform_ == TargetPlatform::kUnknown && runtime_stages_.empty()) {
if (target_platform_ == TargetPlatform::kUnknown && runtime_stages_.empty() &&
!shader_bundle_mode) {
explain << "Either a target platform was not specified, or no runtime "
"stages were specified."
<< std::endl;
valid = false;
}
if (source_language == SourceLanguage::kUnknown) {
if (source_language == SourceLanguage::kUnknown && !shader_bundle_mode) {
explain << "Invalid source language type." << std::endl;
valid = false;
}
@@ -296,7 +297,8 @@ std::vector<TargetPlatform> Switches::PlatformsToCompile() const {
}
TargetPlatform Switches::SelectDefaultTargetPlatform() const {
if (target_platform_ == TargetPlatform::kUnknown) {
if (target_platform_ == TargetPlatform::kUnknown &&
!runtime_stages_.empty()) {
return runtime_stages_.front();
}
return target_platform_;

View File

@@ -67,7 +67,7 @@ class Switches {
// Use |SelectDefaultTargetPlatform|.
TargetPlatform target_platform_ = TargetPlatform::kUnknown;
// Use |PlatformsToCompile|.
std::vector<TargetPlatform> runtime_stages_ = {};
std::vector<TargetPlatform> runtime_stages_;
};
} // namespace compiler

View File

@@ -8,6 +8,7 @@
#include <codecvt>
#include <locale>
#include <map>
#include <optional>
#include <string>
#include "flutter/fml/macros.h"
@@ -44,6 +45,29 @@ enum class SourceLanguage {
kHLSL,
};
struct UniformDescription {
std::string name;
size_t location = 0u;
spirv_cross::SPIRType::BaseType type = spirv_cross::SPIRType::BaseType::Float;
size_t rows = 0u;
size_t columns = 0u;
size_t bit_width = 0u;
std::optional<size_t> array_elements = std::nullopt;
};
struct InputDescription {
std::string name;
size_t location;
size_t set;
size_t binding;
spirv_cross::SPIRType::BaseType type =
spirv_cross::SPIRType::BaseType::Unknown;
size_t bit_width;
size_t vec_size;
size_t columns;
size_t offset;
};
/// A shader config parsed as part of a ShaderBundleConfig.
struct ShaderConfig {
std::string source_file_name;

View File

@@ -130,7 +130,7 @@ impellerc("flutter_gpu_shaders") {
"flutter_gpu_texture.frag",
"flutter_gpu_texture.vert",
]
shader_target_flags = [ "--runtime-stage-metal" ]
shader_bundle = "{\"UnlitFragment\": {\"type\": \"fragment\", \"file\": \"../../flutter/impeller/fixtures/flutter_gpu_unlit.frag\"}, \"UnlitVertex\": {\"type\": \"vertex\", \"file\": \"../../flutter/impeller/fixtures/flutter_gpu_unlit.vert\"}, \"TextureFragment\": {\"type\": \"fragment\", \"file\": \"../../flutter/impeller/fixtures/flutter_gpu_texture.frag\"}, \"TextureVertex\": {\"type\": \"vertex\", \"file\": \"../../flutter/impeller/fixtures/flutter_gpu_texture.vert\"}}"
shader_bundle_output = "playground.shaderbundle"
}

View File

@@ -93,9 +93,9 @@ void canCreateTexture() {
assert(texture!.storageMode == gpu.StorageMode.hostVisible);
assert(texture!.sampleCount == 1);
assert(texture!.format == gpu.PixelFormat.r8g8b8a8UNormInt);
assert(texture!.enableRenderTargetUsage == true);
assert(texture!.enableShaderReadUsage == true);
assert(texture!.enableShaderWriteUsage == false);
assert(texture!.enableRenderTargetUsage);
assert(texture!.enableShaderReadUsage);
assert(!texture!.enableShaderWriteUsage);
assert(texture!.bytesPerTexel == 4);
assert(texture!.GetBaseMipLevelSizeInBytes() == 40000);
}
@@ -168,6 +168,24 @@ void canCreateShaderLibrary() {
assert(shader != null);
}
@pragma('vm:entry-point')
void canReflectUniformStructs() {
final gpu.RenderPipeline pipeline = createUnlitRenderPipeline();
final gpu.UniformSlot vertInfo =
pipeline.vertexShader.getUniformSlot('VertInfo');
assert(vertInfo.uniformName == 'VertInfo');
final int? totalSize = vertInfo.sizeInBytes;
assert(totalSize != null);
assert(totalSize! == 128);
final int? mvpOffset = vertInfo.getMemberOffsetInBytes('mvp');
assert(mvpOffset != null);
assert(mvpOffset! == 0);
final int? colorOffset = vertInfo.getMemberOffsetInBytes('color');
assert(colorOffset != null);
assert(colorOffset! == 64);
}
gpu.RenderPipeline createUnlitRenderPipeline() {
final gpu.ShaderLibrary? library = gpu.ShaderLibrary.fromAsset('playground');
assert(library != null);
@@ -208,21 +226,18 @@ void canCreateRenderPassAndSubmit() {
0.5, 0.5, //
0.5, -0.5, //
]));
final gpu.BufferView color =
transients.emplace(float32(<double>[0, 1, 0, 1])); // rgba
final gpu.BufferView mvp = transients.emplace(float32(<double>[
1, 0, 0, 0, //
0, 1, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1, //
final gpu.BufferView vertInfoData = transients.emplace(float32(<double>[
1, 0, 0, 0, // mvp
0, 1, 0, 0, // mvp
0, 0, 1, 0, // mvp
0, 0, 0, 1, // mvp
0, 1, 0, 1, // color
]));
encoder.bindVertexBuffer(vertices, 3);
final gpu.UniformSlot? colorSlot =
pipeline.vertexShader.getUniformSlot('color');
final gpu.UniformSlot? mvpSlot = pipeline.vertexShader.getUniformSlot('mvp');
encoder.bindUniform(mvpSlot!, mvp);
encoder.bindUniform(colorSlot!, color);
final gpu.UniformSlot vertInfo =
pipeline.vertexShader.getUniformSlot('VertInfo');
encoder.bindUniform(vertInfo, vertInfoData);
encoder.draw();
commandBuffer.submit();

View File

@@ -2,7 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform mat4 mvp;
uniform VertInfo {
mat4 mvp;
}
vert_info;
in vec3 position;
in vec2 texture_coords;
@@ -13,5 +16,5 @@ out vec4 v_color;
void main() {
v_texture_coords = texture_coords;
v_color = color;
gl_Position = mvp * vec4(position, 1.0);
gl_Position = vert_info.mvp * vec4(position, 1.0);
}

View File

@@ -2,15 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#version 320 es
layout(location = 0) uniform mat4 mvp;
layout(location = 1) uniform vec4 color;
uniform VertInfo { // 128 bytes (alignment = NPOT(largest member))
mat4 mvp; // offset 0 bytes, size 64 bytes
vec4 color; // offset 64 bytes, size 16 bytes
}
vert_info;
in vec2 position;
out vec4 v_color;
void main() {
v_color = color;
gl_Position = mvp * vec4(position, 0.0, 1.0);
v_color = vert_info.color;
gl_Position = vert_info.mvp * vec4(position, 0.0, 1.0);
}

View File

@@ -9,7 +9,6 @@
#include "flutter/common/settings.h"
#include "flutter/common/task_runners.h"
#include "flutter/lib/gpu/context.h"
#include "flutter/lib/gpu/shader.h"
#include "flutter/lib/gpu/shader_library.h"
#include "flutter/runtime/dart_isolate.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
@@ -17,11 +16,8 @@
#include "flutter/testing/dart_isolate_runner.h"
#include "flutter/testing/testing.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/core/shader_types.h"
#include "impeller/playground/playground_test.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_descriptor.h"
#include "impeller/runtime_stage/runtime_stage.h"
#include "gtest/gtest.h"
#include "third_party/imgui/imgui.h"
@@ -29,11 +25,11 @@
namespace impeller {
namespace testing {
static void InstantiateTestShaderLibrary() {
static void InstantiateTestShaderLibrary(Context::BackendType backend_type) {
auto fixture =
flutter::testing::OpenFixtureAsMapping("playground.shaderbundle");
auto library =
flutter::gpu::ShaderLibrary::MakeFromFlatbuffer(std::move(fixture));
auto library = flutter::gpu::ShaderLibrary::MakeFromFlatbuffer(
backend_type, std::move(fixture));
flutter::gpu::ShaderLibrary::SetOverride(library);
}
@@ -57,7 +53,7 @@ class RendererDartTest : public PlaygroundTest,
assert(GetContext() != nullptr);
flutter::gpu::Context::SetOverrideContext(GetContext());
InstantiateTestShaderLibrary();
InstantiateTestShaderLibrary(GetContext()->GetBackendType());
return isolate_.get();
}
@@ -148,6 +144,7 @@ DART_TEST_CASE(textureAsImageReturnsAValidUIImageHandle);
DART_TEST_CASE(textureAsImageThrowsWhenNotShaderReadable);
DART_TEST_CASE(canCreateShaderLibrary);
DART_TEST_CASE(canReflectUniformStructs);
DART_TEST_CASE(canCreateRenderPassAndSubmit);

View File

@@ -9,7 +9,6 @@
#include <memory>
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "flutter/impeller/core/runtime_types.h"

View File

@@ -7,10 +7,6 @@ import("../tools/impeller.gni")
flatbuffers("shader_bundle_flatbuffers") {
flatbuffers = [ "shader_bundle.fbs" ]
public_configs = [ "//flutter/impeller/runtime_stage:runtime_stage_config" ]
public_deps = [
"//flutter/impeller/runtime_stage:runtime_stage_flatbuffers",
"//flutter/impeller/runtime_stage:runtime_stage_types_flatbuffers",
"//flutter/third_party/flatbuffers",
]
public_configs = [ "//flutter/impeller:impeller_public_config" ]
public_deps = [ "//flutter/third_party/flatbuffers" ]
}

View File

@@ -2,13 +2,102 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
include "../runtime_stage/runtime_stage_types.fbs";
namespace impeller.fb.shaderbundle;
namespace impeller.fb;
enum ShaderStage:byte {
kVertex,
kFragment,
kCompute,
}
// The subset of impeller::ShaderType that may be used for vertex attributes.
enum InputDataType:uint32 {
kBoolean,
kSignedByte,
kUnsignedByte,
kSignedShort,
kUnsignedShort,
kSignedInt,
kUnsignedInt,
kSignedInt64,
kUnsignedInt64,
kFloat,
kDouble,
}
// The subset of impeller::ShaderType that may be used for uniform bindings.
enum UniformDataType:uint32 {
kBoolean,
kSignedByte,
kUnsignedByte,
kSignedShort,
kUnsignedShort,
kSignedInt,
kUnsignedInt,
kSignedInt64,
kUnsignedInt64,
kHalfFloat,
kFloat,
kDouble,
kSampledImage,
}
// This contains the same attribute reflection data as
// impeller::ShaderStageIOSlot.
table ShaderInput {
name: string;
location: uint64;
set: uint64;
binding: uint64;
type: InputDataType;
bit_width: uint64;
vec_size: uint64;
columns: uint64;
offset: uint64;
}
table ShaderUniformStructField {
name: string;
type: UniformDataType;
offset_in_bytes: uint64;
element_size_in_bytes: uint64;
total_size_in_bytes: uint64;
// Zero indicates that this field is not an array element.
array_elements: uint64;
}
table ShaderUniformStruct {
name: string;
ext_res_0: uint64;
set: uint64;
binding: uint64;
size_in_bytes: uint64; // Includes all alignment padding.
fields: [ShaderUniformStructField];
}
table ShaderUniformTexture {
name: string;
ext_res_0: uint64;
set: uint64;
binding: uint64;
}
table BackendShader {
stage: ShaderStage;
entrypoint: string;
inputs: [ShaderInput];
uniform_structs: [ShaderUniformStruct];
uniform_textures: [ShaderUniformTexture];
shader: [ubyte];
}
table Shader {
name: string;
shader: RuntimeStages;
metal_ios: BackendShader;
metal_desktop: BackendShader;
opengl_es: BackendShader;
opengl_desktop: BackendShader;
vulkan: BackendShader;
}
table ShaderBundle {

View File

@@ -289,6 +289,7 @@ template("_impellerc") {
# --vulkan
# --runtime-stage-metal
# --runtime-stage-gles
# Not required for --shader_bundle mode.
# Required: sl_file_extension The file extension to use for output files.
# Not required for --shader_bundle mode.
# Optional: iplr Causes --sl output to be in iplr/runtime
@@ -306,7 +307,7 @@ template("_impellerc") {
# flatbuffer.
template("impellerc") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.shader_target_flags),
assert(defined(invoker.shader_target_flags) || defined(invoker.shader_bundle),
"The flag to impellerc for target selection must be specified.")
assert(defined(invoker.sl_file_extension) || defined(invoker.shader_bundle),
"The extension of the SL file must be specified (metal, glsl, etc..).")
@@ -316,8 +317,14 @@ template("impellerc") {
"When shader_bundle is specified, shader_output_bundle must also be specified.")
}
if (defined(invoker.shader_target_flags)) {
shader_target_flags = invoker.shader_target_flags
} else {
shader_target_flags = []
}
sksl = false
foreach(shader_target_flag, invoker.shader_target_flags) {
foreach(shader_target_flag, shader_target_flags) {
sksl = shader_target_flag == "--sksl"
}
iplr = false
@@ -351,8 +358,6 @@ template("impellerc") {
generated_dir = "$target_gen_dir"
}
shader_target_flags = invoker.shader_target_flags
shader_lib_dir = rebase_path("//flutter/impeller/compiler/shader_lib")
args = [ "--include=$shader_lib_dir" ] + shader_target_flags
@@ -366,6 +371,10 @@ template("impellerc") {
"--include={{source_dir}}",
"--depfile=$depfile_intermediate_path",
]
if (defined(invoker.shader_target_flag)) {
args += [ "${invoker.shader_target_flag}" ]
}
}
if (defined(invoker.gles_language_version)) {

View File

@@ -22,10 +22,41 @@ void Context::SetOverrideContext(std::shared_ptr<impeller::Context> context) {
default_context_ = std::move(context);
}
std::shared_ptr<impeller::Context> Context::GetDefaultContext() {
std::shared_ptr<impeller::Context> Context::GetOverrideContext() {
return default_context_;
}
std::shared_ptr<impeller::Context> Context::GetDefaultContext(
std::optional<std::string>& out_error) {
auto override_context = GetOverrideContext();
if (override_context) {
return override_context;
}
auto dart_state = flutter::UIDartState::Current();
if (!dart_state->IsImpellerEnabled()) {
out_error =
"Flutter GPU requires the Impeller rendering backend to be enabled.";
return nullptr;
}
// Grab the Impeller context from the IO manager.
std::promise<std::shared_ptr<impeller::Context>> context_promise;
auto impeller_context_future = context_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
dart_state->GetTaskRunners().GetIOTaskRunner(),
fml::MakeCopyable([promise = std::move(context_promise),
io_manager = dart_state->GetIOManager()]() mutable {
promise.set_value(io_manager ? io_manager->GetImpellerContext()
: nullptr);
}));
auto context = impeller_context_future.get();
if (!context) {
out_error = "Unable to retrieve the Impeller context.";
}
return context;
}
Context::Context(std::shared_ptr<impeller::Context> context)
: context_(std::move(context)) {}
@@ -43,33 +74,12 @@ std::shared_ptr<impeller::Context> Context::GetContext() {
///
Dart_Handle InternalFlutterGpu_Context_InitializeDefault(Dart_Handle wrapper) {
auto dart_state = flutter::UIDartState::Current();
std::shared_ptr<impeller::Context> impeller_context =
flutter::gpu::Context::GetDefaultContext();
if (!impeller_context) {
if (!dart_state->IsImpellerEnabled()) {
return tonic::ToDart(
"Flutter GPU requires the Impeller rendering backend to be enabled.");
}
// Grab the Impeller context from the IO manager.
std::promise<std::shared_ptr<impeller::Context>> context_promise;
auto impeller_context_future = context_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
dart_state->GetTaskRunners().GetIOTaskRunner(),
fml::MakeCopyable([promise = std::move(context_promise),
io_manager = dart_state->GetIOManager()]() mutable {
promise.set_value(io_manager ? io_manager->GetImpellerContext()
: nullptr);
}));
impeller_context = impeller_context_future.get();
std::optional<std::string> out_error;
auto impeller_context = flutter::gpu::Context::GetDefaultContext(out_error);
if (out_error.has_value()) {
return tonic::ToDart(out_error.value());
}
if (!impeller_context) {
return tonic::ToDart("Unable to retrieve the Impeller context.");
}
auto res = fml::MakeRefCounted<flutter::gpu::Context>(impeller_context);
res->AssociateWithDartWrapper(wrapper);

View File

@@ -20,7 +20,10 @@ class Context : public RefCountedDartWrappable<Context> {
public:
static void SetOverrideContext(std::shared_ptr<impeller::Context> context);
static std::shared_ptr<impeller::Context> GetDefaultContext();
static std::shared_ptr<impeller::Context> GetOverrideContext();
static std::shared_ptr<impeller::Context> GetDefaultContext(
std::optional<std::string>& out_error);
explicit Context(std::shared_ptr<impeller::Context> context);
~Context() override;

View File

@@ -78,8 +78,8 @@ base class DeviceBuffer extends NativeFieldWrapperClass1 with Buffer {
@override
bool _bindAsUniform(RenderPass renderPass, UniformSlot slot,
int offsetInBytes, int lengthInBytes) {
return renderPass._bindUniformDevice(slot.shaderStage.index, slot.slotId,
this, offsetInBytes, lengthInBytes);
return renderPass._bindUniformDevice(
slot.shader, slot.uniformName, this, offsetInBytes, lengthInBytes);
}
/// Wrap with native counterpart.
@@ -156,8 +156,8 @@ base class HostBuffer extends NativeFieldWrapperClass1 with Buffer {
@override
bool _bindAsUniform(RenderPass renderPass, UniformSlot slot,
int offsetInBytes, int lengthInBytes) {
return renderPass._bindUniformHost(slot.shaderStage.index, slot.slotId,
this, offsetInBytes, lengthInBytes);
return renderPass._bindUniformHost(
slot.shader, slot.uniformName, this, offsetInBytes, lengthInBytes);
}
/// Wrap with native counterpart.

View File

@@ -162,8 +162,8 @@ base class RenderPass extends NativeFieldWrapperClass1 {
}
bool success = _bindTexture(
slot.shaderStage.index,
slot.slotId,
slot.shader,
slot.uniformName,
texture,
sampler.minFilter.index,
sampler.magFilter.index,
@@ -266,22 +266,32 @@ base class RenderPass extends NativeFieldWrapperClass1 {
external void _bindIndexBufferHost(HostBuffer buffer, int offsetInBytes,
int lengthInBytes, int indexType, int indexCount);
@Native<Bool Function(Pointer<Void>, Int, Int, Pointer<Void>, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindUniformDevice')
external bool _bindUniformDevice(int stage, int slotId, DeviceBuffer buffer,
int offsetInBytes, int lengthInBytes);
@Native<Bool Function(Pointer<Void>, Int, Int, Pointer<Void>, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindUniformHost')
external bool _bindUniformHost(int stage, int slotId, HostBuffer buffer,
int offsetInBytes, int lengthInBytes);
@Native<
Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformDevice')
external bool _bindUniformDevice(Shader shader, String uniformName,
DeviceBuffer buffer, int offsetInBytes, int lengthInBytes);
@Native<
Bool Function(Pointer<Void>, Int, Int, Pointer<Void>, Int, Int, Int, Int,
Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformHost')
external bool _bindUniformHost(Shader shader, String uniformName,
HostBuffer buffer, int offsetInBytes, int lengthInBytes);
@Native<
Bool Function(
Pointer<Void>,
Pointer<Void>,
Handle,
Pointer<Void>,
Int,
Int,
Int,
Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindTexture')
external bool _bindTexture(
int stage,
int slotId,
Shader shader,
String uniformName,
Texture texture,
int minFilter,
int magFilter,

View File

@@ -7,29 +7,44 @@
part of flutter_gpu;
base class UniformSlot {
const UniformSlot(this.slotId, this.shaderStage);
UniformSlot._(this.shader, this.uniformName);
final Shader shader;
final String uniformName;
final int slotId;
final ShaderStage shaderStage;
/// The reflected total size of a shader's uniform struct by name.
///
/// Returns [null] if the shader does not contain a uniform struct with the
/// given name.
int? get sizeInBytes {
int size = shader._getUniformStructSize(uniformName);
return size < 0 ? null : size;
}
/// Get the reflected offset of a named member in the uniform struct.
///
/// Returns [null] if the shader does not contain a uniform struct with the
/// given name, or if the uniform struct does not contain a member with the
/// given name.
int? getMemberOffsetInBytes(String memberName) {
int offset = shader._getUniformMemberOffset(uniformName, memberName);
return offset < 0 ? null : offset;
}
}
base class Shader extends NativeFieldWrapperClass1 {
// [Shader] handles are instantiated when interacting with a [ShaderLibrary].
Shader._();
UniformSlot? getUniformSlot(String name) {
int slot = _getUniformSlot(name);
if (slot < 0) {
return null;
}
return UniformSlot(slot, ShaderStage.values[_getShaderStage()]);
UniformSlot getUniformSlot(String uniformName) {
return UniformSlot._(this, uniformName);
}
@Native<Int Function(Pointer<Void>)>(
symbol: 'InternalFlutterGpu_Shader_GetShaderStage')
external int _getShaderStage();
@Native<Int Function(Pointer<Void>, Handle)>(
symbol: 'InternalFlutterGpu_Shader_GetUniformSlot')
external int _getUniformSlot(String name);
symbol: 'InternalFlutterGpu_Shader_GetUniformStructSize')
external int _getUniformStructSize(String uniformStructName);
@Native<Int Function(Pointer<Void>, Handle, Handle)>(
symbol: 'InternalFlutterGpu_Shader_GetUniformMemberOffset')
external int _getUniformMemberOffset(
String uniformStructName, String memberName);
}

View File

@@ -6,6 +6,7 @@
#include "flutter/lib/gpu/formats.h"
#include "flutter/lib/gpu/render_pipeline.h"
#include "flutter/lib/gpu/shader.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/core/buffer_view.h"
#include "impeller/core/formats.h"
@@ -311,23 +312,24 @@ void InternalFlutterGpu_RenderPass_BindIndexBufferHost(
template <typename TBuffer>
static bool BindUniform(flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
TBuffer* buffer,
int offset_in_bytes,
int length_in_bytes) {
// TODO(113715): Populate this metadata once GLES is able to handle
// non-struct uniform names.
std::shared_ptr<impeller::ShaderMetadata> metadata =
std::make_shared<impeller::ShaderMetadata>();
auto& command = wrapper->GetCommand();
impeller::ShaderUniformSlot slot;
// Don't populate the slot name... we don't have it here and Impeller doesn't
// even use it for anything.
slot.ext_res_0 = slot_id;
auto uniform_name = tonic::StdStringFromDart(uniform_name_handle);
const flutter::gpu::Shader::UniformBinding* uniform_struct =
shader->GetUniformStruct(uniform_name);
// TODO(bdero): Return an error string stating that no uniform struct with
// this name exists and throw an exception.
if (!uniform_struct) {
return false;
}
return command.BindResource(
flutter::gpu::ToImpellerShaderStage(stage), slot, metadata,
shader->GetShaderStage(), uniform_struct->slot, uniform_struct->metadata,
impeller::BufferView{
.buffer = buffer->GetBuffer(),
.range = impeller::Range(offset_in_bytes, length_in_bytes),
@@ -336,30 +338,30 @@ static bool BindUniform(flutter::gpu::RenderPass* wrapper,
bool InternalFlutterGpu_RenderPass_BindUniformDevice(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::DeviceBuffer* device_buffer,
int offset_in_bytes,
int length_in_bytes) {
return BindUniform(wrapper, stage, slot_id, device_buffer, offset_in_bytes,
length_in_bytes);
return BindUniform(wrapper, shader, uniform_name_handle, device_buffer,
offset_in_bytes, length_in_bytes);
}
bool InternalFlutterGpu_RenderPass_BindUniformHost(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::HostBuffer* host_buffer,
int offset_in_bytes,
int length_in_bytes) {
return BindUniform(wrapper, stage, slot_id, host_buffer, offset_in_bytes,
length_in_bytes);
return BindUniform(wrapper, shader, uniform_name_handle, host_buffer,
offset_in_bytes, length_in_bytes);
}
bool InternalFlutterGpu_RenderPass_BindTexture(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::Texture* texture,
int min_filter,
int mag_filter,
@@ -368,9 +370,14 @@ bool InternalFlutterGpu_RenderPass_BindTexture(
int height_address_mode) {
auto& command = wrapper->GetCommand();
// TODO(113715): Populate this metadata once GLES is able to handle
// non-struct uniform names.
impeller::ShaderMetadata metadata;
auto uniform_name = tonic::StdStringFromDart(uniform_name_handle);
const impeller::SampledImageSlot* image_slot =
shader->GetUniformTexture(uniform_name);
// TODO(bdero): Return an error string stating that no uniform texture with
// this name exists and throw an exception.
if (!image_slot) {
return false;
}
impeller::SamplerDescriptor sampler_desc;
sampler_desc.min_filter = flutter::gpu::ToImpellerMinMagFilter(min_filter);
@@ -383,10 +390,8 @@ bool InternalFlutterGpu_RenderPass_BindTexture(
auto sampler = wrapper->GetContext().lock()->GetSamplerLibrary()->GetSampler(
sampler_desc);
impeller::SampledImageSlot image_slot;
image_slot.texture_index = slot_id;
return command.BindResource(flutter::gpu::ToImpellerShaderStage(stage),
image_slot, metadata, texture->GetTexture(),
return command.BindResource(shader->GetShaderStage(), *image_slot,
impeller::ShaderMetadata{}, texture->GetTexture(),
sampler);
}

View File

@@ -163,8 +163,8 @@ extern void InternalFlutterGpu_RenderPass_BindIndexBufferHost(
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_RenderPass_BindUniformDevice(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::DeviceBuffer* device_buffer,
int offset_in_bytes,
int length_in_bytes);
@@ -172,8 +172,8 @@ extern bool InternalFlutterGpu_RenderPass_BindUniformDevice(
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_RenderPass_BindUniformHost(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::HostBuffer* host_buffer,
int offset_in_bytes,
int length_in_bytes);
@@ -181,8 +181,8 @@ extern bool InternalFlutterGpu_RenderPass_BindUniformHost(
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_RenderPass_BindTexture(
flutter::gpu::RenderPass* wrapper,
int stage,
int slot_id,
flutter::gpu::Shader* shader,
Dart_Handle uniform_name_handle,
flutter::gpu::Texture* texture,
int min_filter,
int mag_filter,

View File

@@ -16,6 +16,19 @@
namespace flutter {
namespace gpu {
const impeller::ShaderStructMemberMetadata*
Shader::UniformBinding::GetMemberMetadata(const std::string& name) const {
auto result =
std::find_if(metadata.members.begin(), metadata.members.end(),
[&name](const impeller::ShaderStructMemberMetadata& member) {
return member.name == name;
});
if (result == metadata.members.end()) {
return nullptr;
}
return &(*result);
}
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, Shader);
Shader::Shader() = default;
@@ -26,31 +39,17 @@ fml::RefPtr<Shader> Shader::Make(
std::string entrypoint,
impeller::ShaderStage stage,
std::shared_ptr<fml::Mapping> code_mapping,
std::vector<impeller::RuntimeUniformDescription> uniforms,
std::shared_ptr<impeller::VertexDescriptor> vertex_desc) {
// Sampler/texture slots start at 0. See runtime_effect_contents.cc
// TODO(bdero): I'm skeptical about the correctness of this. Verify what
// happens with multiple texture samplers spaced apart with other
// uniforms in-between.
size_t minimum_sampler_index = 100000000;
for (const auto& uniform : uniforms) {
if (uniform.type == impeller::kSampledImage &&
uniform.location < minimum_sampler_index) {
minimum_sampler_index = uniform.location;
}
}
for (auto& uniform : uniforms) {
if (uniform.type == impeller::kSampledImage) {
uniform.location -= minimum_sampler_index;
}
}
std::shared_ptr<impeller::VertexDescriptor> vertex_desc,
std::unordered_map<std::string, UniformBinding> uniform_structs,
std::unordered_map<std::string, impeller::SampledImageSlot>
uniform_textures) {
auto shader = fml::MakeRefCounted<Shader>();
shader->entrypoint_ = std::move(entrypoint);
shader->stage_ = stage;
shader->code_mapping_ = std::move(code_mapping);
shader->uniforms_ = std::move(uniforms);
shader->vertex_desc_ = std::move(vertex_desc);
shader->uniform_structs_ = std::move(uniform_structs);
shader->uniform_textures_ = std::move(uniform_textures);
return shader;
}
@@ -93,13 +92,22 @@ impeller::ShaderStage Shader::GetShaderStage() const {
return stage_;
}
int Shader::GetUniformSlot(const std::string& name) const {
for (const auto& uniform : uniforms_) {
if (name == uniform.name) {
return uniform.location;
}
const Shader::UniformBinding* Shader::GetUniformStruct(
const std::string& name) const {
auto uniform = uniform_structs_.find(name);
if (uniform == uniform_structs_.end()) {
return nullptr;
}
return -1;
return &uniform->second;
}
const impeller::SampledImageSlot* Shader::GetUniformTexture(
const std::string& name) const {
auto uniform = uniform_textures_.find(name);
if (uniform == uniform_textures_.end()) {
return nullptr;
}
return &uniform->second;
}
} // namespace gpu
@@ -109,13 +117,33 @@ int Shader::GetUniformSlot(const std::string& name) const {
/// Exports
///
int InternalFlutterGpu_Shader_GetShaderStage(flutter::gpu::Shader* wrapper) {
return static_cast<int>(
flutter::gpu::FromImpellerShaderStage(wrapper->GetShaderStage()));
int InternalFlutterGpu_Shader_GetUniformStructSize(
flutter::gpu::Shader* wrapper,
Dart_Handle struct_name_handle) {
auto name = tonic::StdStringFromDart(struct_name_handle);
const auto* uniform = wrapper->GetUniformStruct(name);
if (uniform == nullptr) {
return -1;
}
return uniform->size_in_bytes;
}
int InternalFlutterGpu_Shader_GetUniformSlot(flutter::gpu::Shader* wrapper,
Dart_Handle name_handle) {
auto name = tonic::StdStringFromDart(name_handle);
return wrapper->GetUniformSlot(name);
int InternalFlutterGpu_Shader_GetUniformMemberOffset(
flutter::gpu::Shader* wrapper,
Dart_Handle struct_name_handle,
Dart_Handle member_name_handle) {
auto struct_name = tonic::StdStringFromDart(struct_name_handle);
const auto* uniform = wrapper->GetUniformStruct(struct_name);
if (uniform == nullptr) {
return -1;
}
auto member_name = tonic::StdStringFromDart(member_name_handle);
const auto* member = uniform->GetMemberMetadata(member_name);
if (member == nullptr) {
return -1;
}
return member->offset;
}

View File

@@ -5,13 +5,13 @@
#ifndef FLUTTER_LIB_GPU_SHADER_H_
#define FLUTTER_LIB_GPU_SHADER_H_
#include <algorithm>
#include <memory>
#include <string>
#include "flutter/lib/gpu/context.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/core/runtime_types.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/shader_function.h"
#include "impeller/renderer/vertex_descriptor.h"
@@ -25,14 +25,25 @@ class Shader : public RefCountedDartWrappable<Shader> {
FML_FRIEND_MAKE_REF_COUNTED(Shader);
public:
struct UniformBinding {
impeller::ShaderUniformSlot slot;
impeller::ShaderMetadata metadata;
size_t size_in_bytes = 0;
const impeller::ShaderStructMemberMetadata* GetMemberMetadata(
const std::string& name) const;
};
~Shader() override;
static fml::RefPtr<Shader> Make(
std::string entrypoint,
impeller::ShaderStage stage,
std::shared_ptr<fml::Mapping> code_mapping,
std::vector<impeller::RuntimeUniformDescription> uniforms,
std::shared_ptr<impeller::VertexDescriptor> vertex_desc);
std::shared_ptr<impeller::VertexDescriptor> vertex_desc,
std::unordered_map<std::string, UniformBinding> uniform_structs,
std::unordered_map<std::string, impeller::SampledImageSlot>
uniform_textures);
std::shared_ptr<const impeller::ShaderFunction> GetFunctionFromLibrary(
impeller::ShaderLibrary& library);
@@ -45,7 +56,10 @@ class Shader : public RefCountedDartWrappable<Shader> {
impeller::ShaderStage GetShaderStage() const;
int GetUniformSlot(const std::string& name) const;
const Shader::UniformBinding* GetUniformStruct(const std::string& name) const;
const impeller::SampledImageSlot* GetUniformTexture(
const std::string& name) const;
private:
Shader();
@@ -53,8 +67,9 @@ class Shader : public RefCountedDartWrappable<Shader> {
std::string entrypoint_;
impeller::ShaderStage stage_;
std::shared_ptr<fml::Mapping> code_mapping_;
std::vector<impeller::RuntimeUniformDescription> uniforms_;
std::shared_ptr<impeller::VertexDescriptor> vertex_desc_;
std::unordered_map<std::string, UniformBinding> uniform_structs_;
std::unordered_map<std::string, impeller::SampledImageSlot> uniform_textures_;
FML_DISALLOW_COPY_AND_ASSIGN(Shader);
};
@@ -69,13 +84,15 @@ class Shader : public RefCountedDartWrappable<Shader> {
extern "C" {
FLUTTER_GPU_EXPORT
extern int InternalFlutterGpu_Shader_GetShaderStage(
flutter::gpu::Shader* wrapper);
extern int InternalFlutterGpu_Shader_GetUniformStructSize(
flutter::gpu::Shader* wrapper,
Dart_Handle struct_name_handle);
FLUTTER_GPU_EXPORT
extern int InternalFlutterGpu_Shader_GetUniformSlot(
extern int InternalFlutterGpu_Shader_GetUniformMemberOffset(
flutter::gpu::Shader* wrapper,
Dart_Handle name_handle);
Dart_Handle struct_name_handle,
Dart_Handle member_name_handle);
} // extern "C"

View File

@@ -4,21 +4,20 @@
#include "flutter/lib/gpu/shader_library.h"
#include <optional>
#include <utility>
#include "flutter/assets/asset_manager.h"
#include "flutter/impeller/runtime_stage/runtime_stage_types_flatbuffers.h"
#include "flutter/lib/gpu/fixtures.h"
#include "flutter/lib/gpu/shader.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "fml/mapping.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/core/runtime_types.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/vertex_descriptor.h"
#include "impeller/runtime_stage/runtime_stage.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
#include "lib/gpu/context.h"
namespace flutter {
namespace gpu {
@@ -28,6 +27,7 @@ IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, ShaderLibrary);
fml::RefPtr<ShaderLibrary> ShaderLibrary::override_shader_library_;
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromAsset(
impeller::Context::BackendType backend_type,
const std::string& name,
std::string& out_error) {
if (override_shader_library_) {
@@ -44,7 +44,7 @@ fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromAsset(
return nullptr;
}
return MakeFromFlatbuffer(std::move(data));
return MakeFromFlatbuffer(backend_type, std::move(data));
}
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromShaders(ShaderMap shaders) {
@@ -52,70 +52,140 @@ fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromShaders(ShaderMap shaders) {
std::move(shaders));
}
static impeller::ShaderStage ToShaderStage(
impeller::fb::shaderbundle::ShaderStage stage) {
switch (stage) {
case impeller::fb::shaderbundle::ShaderStage::kVertex:
return impeller::ShaderStage::kVertex;
case impeller::fb::shaderbundle::ShaderStage::kFragment:
return impeller::ShaderStage::kFragment;
case impeller::fb::shaderbundle::ShaderStage::kCompute:
return impeller::ShaderStage::kCompute;
}
FML_UNREACHABLE();
}
static impeller::ShaderType FromInputType(
impeller::fb::InputDataType input_type) {
impeller::fb::shaderbundle::InputDataType input_type) {
switch (input_type) {
case impeller::fb::InputDataType::kBoolean:
case impeller::fb::shaderbundle::InputDataType::kBoolean:
return impeller::ShaderType::kBoolean;
case impeller::fb::InputDataType::kSignedByte:
case impeller::fb::shaderbundle::InputDataType::kSignedByte:
return impeller::ShaderType::kSignedByte;
case impeller::fb::InputDataType::kUnsignedByte:
case impeller::fb::shaderbundle::InputDataType::kUnsignedByte:
return impeller::ShaderType::kUnsignedByte;
case impeller::fb::InputDataType::kSignedShort:
case impeller::fb::shaderbundle::InputDataType::kSignedShort:
return impeller::ShaderType::kSignedShort;
case impeller::fb::InputDataType::kUnsignedShort:
case impeller::fb::shaderbundle::InputDataType::kUnsignedShort:
return impeller::ShaderType::kUnsignedShort;
case impeller::fb::InputDataType::kSignedInt:
case impeller::fb::shaderbundle::InputDataType::kSignedInt:
return impeller::ShaderType::kSignedInt;
case impeller::fb::InputDataType::kUnsignedInt:
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt:
return impeller::ShaderType::kUnsignedInt;
case impeller::fb::InputDataType::kSignedInt64:
case impeller::fb::shaderbundle::InputDataType::kSignedInt64:
return impeller::ShaderType::kSignedInt64;
case impeller::fb::InputDataType::kUnsignedInt64:
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt64:
return impeller::ShaderType::kUnsignedInt64;
case impeller::fb::InputDataType::kFloat:
case impeller::fb::shaderbundle::InputDataType::kFloat:
return impeller::ShaderType::kFloat;
case impeller::fb::InputDataType::kDouble:
case impeller::fb::shaderbundle::InputDataType::kDouble:
return impeller::ShaderType::kDouble;
}
}
static size_t SizeOfInputType(impeller::fb::InputDataType input_type) {
static impeller::ShaderType FromUniformType(
impeller::fb::shaderbundle::UniformDataType uniform_type) {
switch (uniform_type) {
case impeller::fb::shaderbundle::UniformDataType::kBoolean:
return impeller::ShaderType::kBoolean;
case impeller::fb::shaderbundle::UniformDataType::kSignedByte:
return impeller::ShaderType::kSignedByte;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedByte:
return impeller::ShaderType::kUnsignedByte;
case impeller::fb::shaderbundle::UniformDataType::kSignedShort:
return impeller::ShaderType::kSignedShort;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedShort:
return impeller::ShaderType::kUnsignedShort;
case impeller::fb::shaderbundle::UniformDataType::kSignedInt:
return impeller::ShaderType::kSignedInt;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedInt:
return impeller::ShaderType::kUnsignedInt;
case impeller::fb::shaderbundle::UniformDataType::kSignedInt64:
return impeller::ShaderType::kSignedInt64;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedInt64:
return impeller::ShaderType::kUnsignedInt64;
case impeller::fb::shaderbundle::UniformDataType::kFloat:
return impeller::ShaderType::kFloat;
case impeller::fb::shaderbundle::UniformDataType::kDouble:
return impeller::ShaderType::kDouble;
case impeller::fb::shaderbundle::UniformDataType::kHalfFloat:
return impeller::ShaderType::kHalfFloat;
case impeller::fb::shaderbundle::UniformDataType::kSampledImage:
return impeller::ShaderType::kSampledImage;
}
}
static size_t SizeOfInputType(
impeller::fb::shaderbundle::InputDataType input_type) {
switch (input_type) {
case impeller::fb::InputDataType::kBoolean:
case impeller::fb::shaderbundle::InputDataType::kBoolean:
return 1;
case impeller::fb::InputDataType::kSignedByte:
case impeller::fb::shaderbundle::InputDataType::kSignedByte:
return 1;
case impeller::fb::InputDataType::kUnsignedByte:
case impeller::fb::shaderbundle::InputDataType::kUnsignedByte:
return 1;
case impeller::fb::InputDataType::kSignedShort:
case impeller::fb::shaderbundle::InputDataType::kSignedShort:
return 2;
case impeller::fb::InputDataType::kUnsignedShort:
case impeller::fb::shaderbundle::InputDataType::kUnsignedShort:
return 2;
case impeller::fb::InputDataType::kSignedInt:
case impeller::fb::shaderbundle::InputDataType::kSignedInt:
return 4;
case impeller::fb::InputDataType::kUnsignedInt:
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt:
return 4;
case impeller::fb::InputDataType::kSignedInt64:
case impeller::fb::shaderbundle::InputDataType::kSignedInt64:
return 8;
case impeller::fb::InputDataType::kUnsignedInt64:
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt64:
return 8;
case impeller::fb::InputDataType::kFloat:
case impeller::fb::shaderbundle::InputDataType::kFloat:
return 4;
case impeller::fb::InputDataType::kDouble:
case impeller::fb::shaderbundle::InputDataType::kDouble:
return 8;
}
}
static const impeller::fb::shaderbundle::BackendShader* GetShaderBackend(
impeller::Context::BackendType backend_type,
const impeller::fb::shaderbundle::Shader* shader) {
switch (backend_type) {
case impeller::Context::BackendType::kMetal:
#ifdef FML_OS_IOS
return shader->metal_ios();
#else
return shader->metal_desktop();
#endif
case impeller::Context::BackendType::kOpenGLES:
#ifdef FML_OS_ANDROID
return shader->opengl_es();
#else
return shader->opengl_desktop();
#endif
case impeller::Context::BackendType::kVulkan:
return shader->vulkan();
}
}
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromFlatbuffer(
impeller::Context::BackendType backend_type,
std::shared_ptr<fml::Mapping> payload) {
if (payload == nullptr || !payload->GetMapping()) {
return nullptr;
}
if (!impeller::fb::ShaderBundleBufferHasIdentifier(payload->GetMapping())) {
if (!impeller::fb::shaderbundle::ShaderBundleBufferHasIdentifier(
payload->GetMapping())) {
return nullptr;
}
auto* bundle = impeller::fb::GetShaderBundle(payload->GetMapping());
auto* bundle =
impeller::fb::shaderbundle::GetShaderBundle(payload->GetMapping());
if (!bundle) {
return nullptr;
}
@@ -123,31 +193,78 @@ fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromFlatbuffer(
ShaderLibrary::ShaderMap shader_map;
for (const auto* bundled_shader : *bundle->shaders()) {
auto* runtime_stages = bundled_shader->shader();
const impeller::fb::RuntimeStage* runtime_stage = nullptr;
auto backend = UIDartState::Current()->GetRuntimeStageBackend();
switch (backend) {
case impeller::RuntimeStageBackend::kSkSL:
FML_LOG(ERROR) << "Cannot target SkSL";
return nullptr;
case impeller::RuntimeStageBackend::kMetal:
runtime_stage = runtime_stages->metal();
break;
case impeller::RuntimeStageBackend::kOpenGLES:
runtime_stage = runtime_stages->opengles();
break;
case impeller::RuntimeStageBackend::kVulkan:
runtime_stage = runtime_stages->vulkan();
break;
const impeller::fb::shaderbundle::BackendShader* backend_shader =
GetShaderBackend(backend_type, bundled_shader);
if (!backend_shader) {
VALIDATION_LOG << "Failed to unpack shader \""
<< bundled_shader->name()->c_str() << "\" from bundle.";
continue;
}
impeller::RuntimeStage stage(runtime_stage, payload);
auto code_mapping = std::make_shared<fml::NonOwnedMapping>(
backend_shader->shader()->data(), //
backend_shader->shader()->size(), //
[payload = payload](auto, auto) {} //
);
std::unordered_map<std::string, Shader::UniformBinding> uniform_structs;
if (backend_shader->uniform_structs() != nullptr) {
for (const auto& uniform : *backend_shader->uniform_structs()) {
std::vector<impeller::ShaderStructMemberMetadata> members;
if (uniform->fields() != nullptr) {
for (const auto& struct_member : *uniform->fields()) {
members.push_back(impeller::ShaderStructMemberMetadata{
.type = FromUniformType(struct_member->type()),
.name = struct_member->name()->c_str(),
.offset = static_cast<size_t>(struct_member->offset_in_bytes()),
.size =
static_cast<size_t>(struct_member->element_size_in_bytes()),
.byte_length =
static_cast<size_t>(struct_member->total_size_in_bytes()),
.array_elements =
struct_member->array_elements() != 0
? std::optional<size_t>(std::nullopt)
: static_cast<size_t>(struct_member->array_elements()),
});
}
}
uniform_structs[uniform->name()->str()] = Shader::UniformBinding{
.slot =
impeller::ShaderUniformSlot{
.name = uniform->name()->c_str(),
.ext_res_0 = static_cast<size_t>(uniform->ext_res_0()),
.set = static_cast<size_t>(uniform->set()),
.binding = static_cast<size_t>(uniform->binding()),
},
.metadata =
impeller::ShaderMetadata{
.name = uniform->name()->c_str(),
.members = members,
},
.size_in_bytes = static_cast<size_t>(uniform->size_in_bytes()),
};
}
}
std::unordered_map<std::string, impeller::SampledImageSlot>
uniform_textures;
if (backend_shader->uniform_textures() != nullptr) {
for (const auto& uniform : *backend_shader->uniform_textures()) {
uniform_textures[uniform->name()->str()] = impeller::SampledImageSlot{
.name = uniform->name()->c_str(),
.texture_index = static_cast<size_t>(uniform->ext_res_0()),
.set = static_cast<size_t>(uniform->set()),
.binding = static_cast<size_t>(uniform->binding()),
};
}
}
std::shared_ptr<impeller::VertexDescriptor> vertex_descriptor = nullptr;
if (stage.GetShaderStage() == impeller::RuntimeShaderStage::kVertex) {
if (backend_shader->stage() ==
impeller::fb::shaderbundle::ShaderStage::kVertex) {
vertex_descriptor = std::make_shared<impeller::VertexDescriptor>();
auto inputs_fb = runtime_stage->inputs();
auto inputs_fb = backend_shader->inputs();
std::vector<impeller::ShaderStageIOSlot> inputs;
inputs.reserve(inputs_fb->size());
@@ -178,9 +295,10 @@ fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromFlatbuffer(
}
auto shader = flutter::gpu::Shader::Make(
stage.GetEntrypoint(), ToShaderStage(stage.GetShaderStage()),
stage.GetCodeMapping(), stage.GetUniforms(),
std::move(vertex_descriptor));
backend_shader->entrypoint()->str(),
ToShaderStage(backend_shader->stage()), std::move(code_mapping),
std::move(vertex_descriptor), std::move(uniform_structs),
std::move(uniform_textures));
shader_map[bundled_shader->name()->str()] = std::move(shader);
}
@@ -227,9 +345,16 @@ Dart_Handle InternalFlutterGpu_ShaderLibrary_InitializeWithAsset(
return tonic::ToDart("Asset name must be a string");
}
std::optional<std::string> out_error;
auto impeller_context = flutter::gpu::Context::GetDefaultContext(out_error);
if (out_error.has_value()) {
return tonic::ToDart(out_error.value());
}
std::string error;
auto res = flutter::gpu::ShaderLibrary::MakeFromAsset(
tonic::StdStringFromDart(asset_name), error);
impeller_context->GetBackendType(), tonic::StdStringFromDart(asset_name),
error);
if (!res) {
return tonic::ToDart(error);
}

View File

@@ -13,7 +13,6 @@
#include "flutter/lib/gpu/shader.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
namespace flutter {
namespace gpu {
@@ -26,12 +25,15 @@ class ShaderLibrary : public RefCountedDartWrappable<ShaderLibrary> {
public:
using ShaderMap = std::unordered_map<std::string, fml::RefPtr<Shader>>;
static fml::RefPtr<ShaderLibrary> MakeFromAsset(const std::string& name,
std::string& out_error);
static fml::RefPtr<ShaderLibrary> MakeFromAsset(
impeller::Context::BackendType backend_type,
const std::string& name,
std::string& out_error);
static fml::RefPtr<ShaderLibrary> MakeFromShaders(ShaderMap shaders);
static fml::RefPtr<ShaderLibrary> MakeFromFlatbuffer(
impeller::Context::BackendType backend_type,
std::shared_ptr<fml::Mapping> payload);
/// Sets a return override for `MakeFromAsset` for testing purposes.