Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
runtime_effect_contents.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
6
7#include <algorithm>
8#include <future>
9#include <memory>
10
11#include "flutter/fml/logging.h"
12#include "flutter/fml/make_copyable.h"
18#include "impeller/entity/runtime_effect.vert.h"
24
25namespace impeller {
26
28 std::shared_ptr<RuntimeStage> runtime_stage) {
29 runtime_stage_ = std::move(runtime_stage);
30}
31
33 std::shared_ptr<std::vector<uint8_t>> uniform_data) {
34 uniform_data_ = std::move(uniform_data);
35}
36
38 std::vector<TextureInput> texture_inputs) {
39 texture_inputs_ = std::move(texture_inputs);
40}
41
43 return false;
44}
45
47 switch (type) {
48 case kSampledImage:
50 case kFloat:
51 return ShaderType::kFloat;
52 case kStruct:
54 }
55}
56
57static std::shared_ptr<ShaderMetadata> MakeShaderMetadata(
58 const RuntimeUniformDescription& uniform) {
59 auto metadata = std::make_shared<ShaderMetadata>();
60 metadata->name = uniform.name;
61 metadata->members.emplace_back(ShaderStructMemberMetadata{
62 .type = GetShaderType(uniform.type),
63 .size = uniform.GetSize(),
64 .byte_length = uniform.bit_width / 8,
65 });
66
67 return metadata;
68}
69
71 const ContentContext& renderer) const {
72 if (!RegisterShader(renderer)) {
73 return false;
74 }
77 renderer.GetContext()->GetCapabilities()->GetDefaultColorFormat();
78 return !!CreatePipeline(renderer, options);
79}
80
81bool RuntimeEffectContents::RegisterShader(
82 const ContentContext& renderer) const {
83 const std::shared_ptr<Context>& context = renderer.GetContext();
84 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
85
86 std::shared_ptr<const ShaderFunction> function = library->GetFunction(
87 runtime_stage_->GetEntrypoint(), ShaderStage::kFragment);
88
89 //--------------------------------------------------------------------------
90 /// Resolve runtime stage function.
91 ///
92
93 if (function && runtime_stage_->IsDirty()) {
94 renderer.ClearCachedRuntimeEffectPipeline(runtime_stage_->GetEntrypoint());
95 context->GetPipelineLibrary()->RemovePipelinesWithEntryPoint(function);
96 library->UnregisterFunction(runtime_stage_->GetEntrypoint(),
98
99 function = nullptr;
100 }
101
102 if (!function) {
103 std::promise<bool> promise;
104 auto future = promise.get_future();
105
106 library->RegisterFunction(
107 runtime_stage_->GetEntrypoint(),
108 ToShaderStage(runtime_stage_->GetShaderStage()),
109 runtime_stage_->GetCodeMapping(),
110 fml::MakeCopyable([promise = std::move(promise)](bool result) mutable {
111 promise.set_value(result);
112 }));
113
114 if (!future.get()) {
115 VALIDATION_LOG << "Failed to build runtime effect (entry point: "
116 << runtime_stage_->GetEntrypoint() << ")";
117 return false;
118 }
119
120 function = library->GetFunction(runtime_stage_->GetEntrypoint(),
122 if (!function) {
124 << "Failed to fetch runtime effect function immediately after "
125 "registering it (entry point: "
126 << runtime_stage_->GetEntrypoint() << ")";
127 return false;
128 }
129
130 runtime_stage_->SetClean();
131 }
132 return true;
133}
134
135std::shared_ptr<Pipeline<PipelineDescriptor>>
136RuntimeEffectContents::CreatePipeline(const ContentContext& renderer,
137 ContentContextOptions options) const {
138 const std::shared_ptr<Context>& context = renderer.GetContext();
139 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
140 const std::shared_ptr<const Capabilities>& caps = context->GetCapabilities();
141 const auto color_attachment_format = caps->GetDefaultColorFormat();
142 const auto stencil_attachment_format = caps->GetDefaultDepthStencilFormat();
143
144 using VS = RuntimeEffectVertexShader;
145
146 PipelineDescriptor desc;
147 desc.SetLabel("Runtime Stage");
148 desc.AddStageEntrypoint(
149 library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
150 desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(),
152
153 std::shared_ptr<VertexDescriptor> vertex_descriptor =
154 std::make_shared<VertexDescriptor>();
155 vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs,
156 VS::kInterleavedBufferLayout);
157 vertex_descriptor->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts);
158 vertex_descriptor->RegisterDescriptorSetLayouts(
159 runtime_stage_->GetDescriptorSetLayouts().data(),
160 runtime_stage_->GetDescriptorSetLayouts().size());
161 desc.SetVertexDescriptor(std::move(vertex_descriptor));
162 desc.SetColorAttachmentDescriptor(
163 0u, {.format = color_attachment_format, .blending_enabled = true});
164
165 desc.SetStencilAttachmentDescriptors(StencilAttachmentDescriptor{});
166 desc.SetStencilPixelFormat(stencil_attachment_format);
167
168 desc.SetDepthStencilAttachmentDescriptor(DepthAttachmentDescriptor{});
169 desc.SetDepthPixelFormat(stencil_attachment_format);
170
171 options.ApplyToPipelineDescriptor(desc);
172 auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get();
173 if (!pipeline) {
174 VALIDATION_LOG << "Failed to get or create runtime effect pipeline.";
175 return nullptr;
176 }
177
178 return pipeline;
179}
180
182 const Entity& entity,
183 RenderPass& pass) const {
184 const std::shared_ptr<Context>& context = renderer.GetContext();
185 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
186
187 //--------------------------------------------------------------------------
188 /// Get or register shader. Flutter will do this when the runtime effect
189 /// is first loaded, but this check is added to supporting testing of the
190 /// Aiks API and non-flutter usage of Impeller.
191 ///
192 if (!RegisterShader(renderer)) {
193 return false;
194 }
195
196 //--------------------------------------------------------------------------
197 /// Fragment stage uniforms.
198 ///
199 BindFragmentCallback bind_callback = [this, &renderer,
200 &context](RenderPass& pass) {
201 size_t minimum_sampler_index = 100000000;
202 size_t buffer_index = 0;
203 size_t buffer_offset = 0;
204
205 for (const auto& uniform : runtime_stage_->GetUniforms()) {
206 std::shared_ptr<ShaderMetadata> metadata = MakeShaderMetadata(uniform);
207
208 switch (uniform.type) {
209 case kSampledImage: {
210 // Sampler uniforms are ordered in the IPLR according to their
211 // declaration and the uniform location reflects the correct offset to
212 // be mapped to - except that it may include all proceeding float
213 // uniforms. For example, a float sampler that comes after 4 float
214 // uniforms may have a location of 4. To convert to the actual offset
215 // we need to find the largest location assigned to a float uniform
216 // and then subtract this from all uniform locations. This is more or
217 // less the same operation we previously performed in the shader
218 // compiler.
219 minimum_sampler_index =
220 std::min(minimum_sampler_index, uniform.location);
221 break;
222 }
223 case kFloat: {
224 FML_DCHECK(renderer.GetContext()->GetBackendType() !=
226 << "Uniform " << uniform.name
227 << " had unexpected type kFloat for Vulkan backend.";
228
229 size_t alignment =
230 std::max(uniform.bit_width / 8, DefaultUniformAlignment());
231 BufferView buffer_view = renderer.GetTransientsBuffer().Emplace(
232 uniform_data_->data() + buffer_offset, uniform.GetSize(),
233 alignment);
234
235 ShaderUniformSlot uniform_slot;
236 uniform_slot.name = uniform.name.c_str();
237 uniform_slot.ext_res_0 = uniform.location;
239 DescriptorType::kUniformBuffer, uniform_slot,
240 metadata, std::move(buffer_view));
241 buffer_index++;
242 buffer_offset += uniform.GetSize();
243 break;
244 }
245 case kStruct: {
246 FML_DCHECK(renderer.GetContext()->GetBackendType() ==
248 ShaderUniformSlot uniform_slot;
249 uniform_slot.name = uniform.name.c_str();
250 uniform_slot.binding = uniform.location;
251
252 // TODO(jonahwilliams): rewrite this to emplace directly into
253 // HostBuffer.
254 std::vector<float> uniform_buffer;
255 uniform_buffer.reserve(uniform.struct_layout.size());
256 size_t uniform_byte_index = 0u;
257 for (const auto& byte_type : uniform.struct_layout) {
258 if (byte_type == 0) {
259 uniform_buffer.push_back(0.f);
260 } else if (byte_type == 1) {
261 uniform_buffer.push_back(reinterpret_cast<float*>(
262 uniform_data_->data())[uniform_byte_index++]);
263 } else {
265 }
266 }
267 size_t alignment = std::max(sizeof(float) * uniform_buffer.size(),
269
270 BufferView buffer_view = renderer.GetTransientsBuffer().Emplace(
271 reinterpret_cast<const void*>(uniform_buffer.data()),
272 sizeof(float) * uniform_buffer.size(), alignment);
274 DescriptorType::kUniformBuffer, uniform_slot,
275 ShaderMetadata{}, std::move(buffer_view));
276 }
277 }
278 }
279
280 size_t sampler_index = 0;
281 for (const auto& uniform : runtime_stage_->GetUniforms()) {
282 std::shared_ptr<ShaderMetadata> metadata = MakeShaderMetadata(uniform);
283
284 switch (uniform.type) {
285 case kSampledImage: {
286 FML_DCHECK(sampler_index < texture_inputs_.size());
287 auto& input = texture_inputs_[sampler_index];
288
289 const std::unique_ptr<const Sampler>& sampler =
290 context->GetSamplerLibrary()->GetSampler(
291 input.sampler_descriptor);
292
293 SampledImageSlot image_slot;
294 image_slot.name = uniform.name.c_str();
295 image_slot.binding = uniform.binding;
296 image_slot.texture_index = uniform.location - minimum_sampler_index;
299 *metadata, input.texture, sampler);
300
301 sampler_index++;
302 break;
303 }
304 default:
305 continue;
306 }
307 }
308 return true;
309 };
310
311 /// Now that the descriptor set layouts are known, get the pipeline.
312 using VS = RuntimeEffectVertexShader;
313
314 PipelineBuilderCallback pipeline_callback =
316 // Pipeline creation callback for the cache handler to call.
317 return renderer.GetCachedRuntimeEffectPipeline(
318 runtime_stage_->GetEntrypoint(), options,
319 [&]() { return CreatePipeline(renderer, options); });
320 };
321
322 return ColorSourceContents::DrawGeometry<VS>(renderer, entity, pass,
323 pipeline_callback,
324 VS::FrameInfo{}, bind_callback);
325}
326
327} // namespace impeller
const char * options
std::function< std::shared_ptr< Pipeline< PipelineDescriptor > >(ContentContextOptions)> PipelineBuilderCallback
std::function< bool(RenderPass &pass)> BindFragmentCallback
Render passes encode render commands directed as one specific render target into an underlying comman...
Definition render_pass.h:33
virtual bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot &slot, const ShaderMetadata &metadata, BufferView view) override
bool Render(const ContentContext &renderer, const Entity &entity, RenderPass &pass) const override
bool BootstrapShader(const ContentContext &renderer) const
Load the runtime effect and ensure a default PSO is initialized.
void SetRuntimeStage(std::shared_ptr< RuntimeStage > runtime_stage)
void SetTextureInputs(std::vector< TextureInput > texture_inputs)
void SetUniformData(std::shared_ptr< std::vector< uint8_t > > uniform_data)
bool CanInheritOpacity(const Entity &entity) const override
Whether or not this contents can accept the opacity peephole optimization.
GAsyncResult * result
#define FML_UNREACHABLE()
Definition logging.h:109
#define FML_DCHECK(condition)
Definition logging.h:103
Dart_NativeFunction function
Definition fuchsia.cc:51
internal::CopyableLambda< T > MakeCopyable(T lambda)
static std::shared_ptr< ShaderMetadata > MakeShaderMetadata(const RuntimeUniformDescription &uniform)
constexpr ShaderStage ToShaderStage(RuntimeShaderStage stage)
SolidFillVertexShader VS
static ShaderType GetShaderType(RuntimeUniformType type)
constexpr size_t DefaultUniformAlignment()
Definition platform.h:15
size_t GetSize() const
Computes the total number of bytes that this uniform requires.
Metadata required to bind a combined texture and sampler.
size_t texture_index
ext_res_0 is the Metal binding value.
const char * name
The name of the uniform slot.
size_t binding
The Vulkan binding value.
Metadata required to bind a buffer.
size_t binding
The Vulkan binding value.
size_t ext_res_0
ext_res_0 is the Metal binding value.
const char * name
The name of the uniform slot.
#define VALIDATION_LOG
Definition validation.h:73