diff --git a/engine/src/flutter/impeller/BUILD.gn b/engine/src/flutter/impeller/BUILD.gn index 4a46e0e8a6..c7aeb4641f 100644 --- a/engine/src/flutter/impeller/BUILD.gn +++ b/engine/src/flutter/impeller/BUILD.gn @@ -13,7 +13,6 @@ group("impeller") { "compositor", "entity", "geometry", - "host", "image", "primitives", "shader_glue", diff --git a/engine/src/flutter/impeller/compiler/code_gen_template.h b/engine/src/flutter/impeller/compiler/code_gen_template.h index 3edca285eb..a93b8fd3bd 100644 --- a/engine/src/flutter/impeller/compiler/code_gen_template.h +++ b/engine/src/flutter/impeller/compiler/code_gen_template.h @@ -16,9 +16,8 @@ constexpr std::string_view kReflectionHeaderTemplate = #include "shader_types.h" namespace impeller { -namespace shader { -struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info { +struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader { // =========================================================================== // Stage Info ================================================================ // =========================================================================== @@ -116,10 +115,9 @@ struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info { }; {% endif %} -}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info +}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader -} // namespace shader -} // namespace impeller +} // namespace impeller )~~"; constexpr std::string_view kReflectionCCTemplate = @@ -131,22 +129,19 @@ constexpr std::string_view kReflectionCCTemplate = #include namespace impeller { -namespace shader { -using Info = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info; +using Shader = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader; {% for def in struct_definitions %} // Sanity checks for {{def.name}} -static_assert(std::is_standard_layout_v); -static_assert(sizeof(Info::{{def.name}}) == {{def.byte_length}}); +static_assert(std::is_standard_layout_v); +static_assert(sizeof(Shader::{{def.name}}) == {{def.byte_length}}); {% for member in def.members %} -static_assert(offsetof(Info::{{def.name}}, {{member.name}}) == {{member.offset}}); +static_assert(offsetof(Shader::{{def.name}}, {{member.name}}) == {{member.offset}}); {% endfor %} {% endfor %} - -} // namespace shader -} // namespace impeller +} // namespace impeller )~~"; } // namespace compiler diff --git a/engine/src/flutter/impeller/compositor/BUILD.gn b/engine/src/flutter/impeller/compositor/BUILD.gn index 3e2eec64d6..3104174490 100644 --- a/engine/src/flutter/impeller/compositor/BUILD.gn +++ b/engine/src/flutter/impeller/compositor/BUILD.gn @@ -30,6 +30,8 @@ impeller_component("compositor") { "host_buffer.mm", "pipeline.h", "pipeline.mm", + "pipeline_builder.h", + "pipeline_builder.mm", "pipeline_descriptor.h", "pipeline_descriptor.mm", "pipeline_library.h", diff --git a/engine/src/flutter/impeller/compositor/pipeline_builder.h b/engine/src/flutter/impeller/compositor/pipeline_builder.h new file mode 100644 index 0000000000..a5249c09ec --- /dev/null +++ b/engine/src/flutter/impeller/compositor/pipeline_builder.h @@ -0,0 +1,107 @@ +// 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. + +#pragma once + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "impeller/compositor/context.h" +#include "impeller/compositor/pipeline_descriptor.h" +#include "impeller/compositor/shader_library.h" +#include "impeller/compositor/vertex_descriptor.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A utility for creating pipelines from reflected shader +/// information. +/// +/// @tparam VertexShader_ The reflected vertex shader information. Found +/// in a generated header file called +/// .vert.h. +/// @tparam FragmentShader_ The reflected fragment shader information. +/// Found in a generated header file called +/// .frag.h. +/// +template +struct PipelineBuilder { + public: + using VertexShader = VertexShader_; + using FragmentShader = FragmentShader_; + + static constexpr size_t kVertexBufferIndex = + VertexDescriptor::kReservedVertexBufferIndex; + + //---------------------------------------------------------------------------- + /// @brief Create a default pipeline descriptor using the combination + /// reflected shader information. The descriptor can be configured + /// further before a pipline state object is created using it. + /// + /// @param[in] context The context + /// + /// @return If the combination of reflected shader information is + /// compatible and the requisite functions can be found in the + /// context, a pipeine descriptor. + /// + static std::optional MakeDefaultPipelineDescriptor( + const Context& context) { + PipelineDescriptor desc; + + // Setup debug instrumentation. + desc.SetLabel(SPrintF("%s Pipeline", VertexShader::kLabel.data())); + + // Resolve pipeline entrypoints. + { + auto vertex_function = context.GetShaderLibrary()->GetFunction( + VertexShader::kEntrypointName, ShaderStage::kVertex); + auto fragment_function = context.GetShaderLibrary()->GetFunction( + FragmentShader::kEntrypointName, ShaderStage::kFragment); + + if (!vertex_function || !fragment_function) { + FML_LOG(ERROR) << "Could not resolve pipeline entrypoint(s)."; + return std::nullopt; + } + + desc.AddStageEntrypoint(std::move(vertex_function)); + desc.AddStageEntrypoint(std::move(fragment_function)); + } + + // Setup the vertex descriptor from reflected information. + { + auto vertex_descriptor = std::make_shared(); + if (!vertex_descriptor->SetStageInputs( + VertexShader::kAllShaderStageInputs)) { + FML_LOG(ERROR) << "Could not configure vertex descriptor."; + return std::nullopt; + } + desc.SetVertexDescriptor(std::move(vertex_descriptor)); + } + + // Setup fragment shader output descriptions. + { + // Configure the sole color attachments pixel format. + // TODO(csg): This can be easily reflected but we are sticking to the + // convention that the first stage output is the color output. + ColorAttachmentDescriptor color0; + color0.format = PixelFormat::kPixelFormat_B8G8R8A8_UNormInt_SRGB; + desc.SetColorAttachmentDescriptor(0u, std::move(color0)); + } + + // Setup depth and stencil attachment descriptions. + { + // Configure the stencil attachment. + // TODO(csg): Make this configurable if possible as the D32 component is + // wasted. This can even be moved out of the "default" descriptor + // construction as a case can be made that this is caller responsibility. + const auto combined_depth_stencil_format = + PixelFormat::kPixelFormat_D32_Float_S8_UNormInt; + desc.SetDepthPixelFormat(combined_depth_stencil_format); + desc.SetStencilPixelFormat(combined_depth_stencil_format); + } + + return desc; + } +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/host/assets_location.h b/engine/src/flutter/impeller/compositor/pipeline_builder.mm similarity index 65% rename from engine/src/flutter/impeller/host/assets_location.h rename to engine/src/flutter/impeller/compositor/pipeline_builder.mm index ea139a5a6d..dbea9cc563 100644 --- a/engine/src/flutter/impeller/host/assets_location.h +++ b/engine/src/flutter/impeller/compositor/pipeline_builder.mm @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include +#include "impeller/compositor/pipeline_builder.h" namespace impeller { -std::string GetAssetLocation(const char* asset_path); +// -} // namespace impeller +} // namespace impeller diff --git a/engine/src/flutter/impeller/compositor/pipeline_descriptor.h b/engine/src/flutter/impeller/compositor/pipeline_descriptor.h index 295c3751c1..1d6a1d2e01 100644 --- a/engine/src/flutter/impeller/compositor/pipeline_descriptor.h +++ b/engine/src/flutter/impeller/compositor/pipeline_descriptor.h @@ -24,7 +24,7 @@ namespace impeller { class ShaderFunction; class VertexDescriptor; -class PipelineDescriptor : public Comparable { +class PipelineDescriptor final : public Comparable { public: PipelineDescriptor(); diff --git a/engine/src/flutter/impeller/compositor/vertex_descriptor.h b/engine/src/flutter/impeller/compositor/vertex_descriptor.h index f05885d403..d6c97de75e 100644 --- a/engine/src/flutter/impeller/compositor/vertex_descriptor.h +++ b/engine/src/flutter/impeller/compositor/vertex_descriptor.h @@ -16,6 +16,9 @@ namespace impeller { class VertexDescriptor final : public Comparable { public: + static constexpr size_t kReservedVertexBufferIndex = + 30u; // The final slot available. Regular buffer indices go up from 0. + VertexDescriptor(); virtual ~VertexDescriptor(); @@ -31,8 +34,6 @@ class VertexDescriptor final : public Comparable { MTLVertexDescriptor* GetMTLVertexDescriptor() const; - size_t GetVertexBufferIndex() const; - //| Comparable| std::size_t GetHash() const override; diff --git a/engine/src/flutter/impeller/compositor/vertex_descriptor.mm b/engine/src/flutter/impeller/compositor/vertex_descriptor.mm index 3ab58eab7d..9707db0e7e 100644 --- a/engine/src/flutter/impeller/compositor/vertex_descriptor.mm +++ b/engine/src/flutter/impeller/compositor/vertex_descriptor.mm @@ -188,16 +188,10 @@ bool VertexDescriptor::SetStageInputs( return true; } -size_t VertexDescriptor::GetVertexBufferIndex() const { - static constexpr size_t kReservedVertexBufferIndex = - 30u; // The final slot available. - return kReservedVertexBufferIndex; -} - MTLVertexDescriptor* VertexDescriptor::GetMTLVertexDescriptor() const { auto descriptor = [MTLVertexDescriptor vertexDescriptor]; - const size_t vertex_buffer_index = GetVertexBufferIndex(); + const size_t vertex_buffer_index = kReservedVertexBufferIndex; size_t stride = 0u; for (const auto& input : stage_inputs_) { diff --git a/engine/src/flutter/impeller/entity/BUILD.gn b/engine/src/flutter/impeller/entity/BUILD.gn index c3fa607152..bd19c0ed5a 100644 --- a/engine/src/flutter/impeller/entity/BUILD.gn +++ b/engine/src/flutter/impeller/entity/BUILD.gn @@ -24,5 +24,8 @@ impeller_component("entity_unittests") { sources = [ "entity_unittests.mm" ] - deps = [ "../playground" ] + deps = [ + ":entity", + "../playground", + ] } diff --git a/engine/src/flutter/impeller/entity/entity_renderer.mm b/engine/src/flutter/impeller/entity/entity_renderer.mm index 08c55bb56d..22878ab878 100644 --- a/engine/src/flutter/impeller/entity/entity_renderer.mm +++ b/engine/src/flutter/impeller/entity/entity_renderer.mm @@ -30,7 +30,7 @@ EntityRenderer::EntityRenderer(std::string shaders_directory) return; } - VertexBufferBuilder vertex_builder; + VertexBufferBuilder vertex_builder; vertex_builder.SetLabel("Box"); vertex_builder.AddVertices({ {{100, 100, 0.0}, {Color::Red()}, {0.0, 0.0}}, // 1 @@ -61,30 +61,23 @@ bool EntityRenderer::OnIsValid() const { bool EntityRenderer::OnRender(const Surface& surface, RenderPass& pass) { pass.SetLabel("EntityRenderer Render Pass"); - shader::BoxVertexInfo::UniformBuffer uniforms; + BoxVertexShader::UniformBuffer uniforms; uniforms.mvp = Matrix::MakeOrthographic(surface.GetSize()); Command cmd; cmd.label = "Box"; cmd.pipeline = box_primitive_->GetPipeline(); - cmd.vertex_bindings.buffers[box_primitive_->GetVertexBufferIndex()] = vertex_buffer_.vertex_buffer; - cmd.vertex_bindings - .buffers[shader::BoxVertexInfo::kUniformUniformBuffer.binding] = + cmd.vertex_bindings.buffers[BoxVertexShader::kUniformUniformBuffer.binding] = pass.GetTransientsBuffer().EmplaceUniform(uniforms); - - cmd.fragment_bindings - .samplers[shader::BoxFragmentInfo::kInputContents1.binding] = + cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents1.binding] = GetContext()->GetSamplerLibrary()->GetSampler({}); - cmd.fragment_bindings - .samplers[shader::BoxFragmentInfo::kInputContents2.binding] = + cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents2.binding] = GetContext()->GetSamplerLibrary()->GetSampler({}); - cmd.fragment_bindings - .samplers[shader::BoxFragmentInfo::kInputContents3.binding] = + cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents3.binding] = GetContext()->GetSamplerLibrary()->GetSampler({}); - cmd.index_buffer = vertex_buffer_.index_buffer; cmd.index_count = vertex_buffer_.index_count; cmd.primitive_type = PrimitiveType::kTriange; diff --git a/engine/src/flutter/impeller/host/BUILD.gn b/engine/src/flutter/impeller/host/BUILD.gn deleted file mode 100644 index dcde833a58..0000000000 --- a/engine/src/flutter/impeller/host/BUILD.gn +++ /dev/null @@ -1,53 +0,0 @@ -# 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. - -import("//flutter/impeller/tools/impeller.gni") -import("//flutter/testing/testing.gni") - -metal_library("impeller_host_shaders") { - name = "impeller_host" - sources = [ "shaders.metal" ] -} - -test_fixtures("impeller_host_fixtures") { - fixtures = [ "assets/ColorMap.png" ] -} - -executable("host") { - cflags_objc = flutter_cflags_objc_arc - cflags_objcc = flutter_cflags_objcc_arc - - cflags_objcc += [ "-Wno-auto-var-id" ] - - output_name = "impeller" - - sources = [ - "ShaderTypes.h", - "assets_location.cc", - "assets_location.h", - "impeller_host_view_controller.h", - "impeller_host_view_controller.mm", - "impeller_renderer.h", - "impeller_renderer.mm", - "main.mm", - "shaders_location.cc", - "shaders_location.h", - ] - - libs = [ - "AppKit.framework", - "Metal.framework", - "MetalKit.framework", - "QuartzCore.framework", - "ModelIO.framework", - ] - - deps = [ - ":impeller_host_fixtures", - ":impeller_host_shaders", - "../entity", - "../primitives", - "//flutter/fml", - ] -} diff --git a/engine/src/flutter/impeller/host/ShaderTypes.h b/engine/src/flutter/impeller/host/ShaderTypes.h deleted file mode 100644 index 34a71c4619..0000000000 --- a/engine/src/flutter/impeller/host/ShaderTypes.h +++ /dev/null @@ -1,39 +0,0 @@ -// 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 ShaderTypes_h -#define ShaderTypes_h - -#ifdef __METAL_VERSION__ -#define NS_ENUM(_type, _name) \ - enum _name : _type _name; \ - enum _name : _type -#define NSInteger metal::int32_t -#else -#import -#endif - -#include - -typedef NS_ENUM(NSInteger, BufferIndex) { - BufferIndexMeshPositions = 0, - BufferIndexMeshGenerics = 1, - BufferIndexUniforms = 2 -}; - -typedef NS_ENUM(NSInteger, VertexAttribute) { - VertexAttributePosition = 0, - VertexAttributeTexcoord = 1, -}; - -typedef NS_ENUM(NSInteger, TextureIndex) { - TextureIndexColor = 0, -}; - -typedef struct { - matrix_float4x4 projectionMatrix; - matrix_float4x4 modelViewMatrix; -} Uniforms; - -#endif /* ShaderTypes_h */ diff --git a/engine/src/flutter/impeller/host/Shaders.metal b/engine/src/flutter/impeller/host/Shaders.metal deleted file mode 100644 index a2e0ac5eb1..0000000000 --- a/engine/src/flutter/impeller/host/Shaders.metal +++ /dev/null @@ -1,50 +0,0 @@ -// 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. - -// File for Metal kernel and shader functions - -#include -#include - -// Including header shared between this Metal shader code and Swift/C code executing Metal API commands -#import "ShaderTypes.h" - -using namespace metal; - -typedef struct -{ - float3 position [[attribute(VertexAttributePosition)]]; - float2 texCoord [[attribute(VertexAttributeTexcoord)]]; -} Vertex; - -typedef struct -{ - float4 position [[position]]; - float2 texCoord; -} ColorInOut; - -vertex ColorInOut vertexShader(Vertex in [[stage_in]], - constant Uniforms & uniforms [[ buffer(BufferIndexUniforms) ]]) -{ - ColorInOut out; - - float4 position = float4(in.position, 1.0); - out.position = uniforms.projectionMatrix * uniforms.modelViewMatrix * position; - out.texCoord = in.texCoord; - - return out; -} - -fragment float4 fragmentShader(ColorInOut in [[stage_in]], - constant Uniforms & uniforms [[ buffer(BufferIndexUniforms) ]], - texture2d colorMap [[ texture(TextureIndexColor) ]]) -{ - constexpr sampler colorSampler(mip_filter::linear, - mag_filter::linear, - min_filter::linear); - - half4 colorSample = colorMap.sample(colorSampler, in.texCoord.xy); - - return float4(colorSample); -} diff --git a/engine/src/flutter/impeller/host/assets/ColorMap.png b/engine/src/flutter/impeller/host/assets/ColorMap.png deleted file mode 100644 index ddf9519d46..0000000000 Binary files a/engine/src/flutter/impeller/host/assets/ColorMap.png and /dev/null differ diff --git a/engine/src/flutter/impeller/host/assets_location.cc b/engine/src/flutter/impeller/host/assets_location.cc deleted file mode 100644 index 369e3cd370..0000000000 --- a/engine/src/flutter/impeller/host/assets_location.cc +++ /dev/null @@ -1,31 +0,0 @@ -// 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 "flutter/impeller/host/assets_location.h" - -#include "flutter/fml/paths.h" - -namespace flutter::testing { - -//------------------------------------------------------------------------------ -/// @brief Returns the directory containing the test fixture for the target -/// if this target has fixtures configured. If there are no -/// fixtures, this is a link error. If you see a linker error on -/// this symbol, the unit-test target needs to depend on a -/// `test_fixtures` target. -/// -/// @return The fixtures path. -/// -const char* GetFixturesPath(); - -} // namespace flutter::testing - -namespace impeller { - -std::string GetAssetLocation(const char* asset_path) { - return fml::paths::JoinPaths( - {flutter::testing::GetFixturesPath(), std::string{asset_path}}); -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/host/impeller_host_view_controller.h b/engine/src/flutter/impeller/host/impeller_host_view_controller.h deleted file mode 100644 index 72e11620bf..0000000000 --- a/engine/src/flutter/impeller/host/impeller_host_view_controller.h +++ /dev/null @@ -1,12 +0,0 @@ -// 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. - -#import -#import -#import -#import "impeller_renderer.h" - -@interface ImpellerHostViewController : NSViewController - -@end diff --git a/engine/src/flutter/impeller/host/impeller_host_view_controller.mm b/engine/src/flutter/impeller/host/impeller_host_view_controller.mm deleted file mode 100644 index 188030b29e..0000000000 --- a/engine/src/flutter/impeller/host/impeller_host_view_controller.mm +++ /dev/null @@ -1,35 +0,0 @@ -// 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. - -#import "impeller_host_view_controller.h" - -#import "impeller_renderer.h" - -@implementation ImpellerHostViewController { - MTKView* view_; - ImpellerRenderer* renderer_; -} - -- (void)loadView { - view_ = [[MTKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600)]; - view_.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; - self.view = view_; -} - -- (void)viewDidLoad { - [super viewDidLoad]; - view_.device = MTLCreateSystemDefaultDevice(); - - if (!view_.device) { - NSLog(@"Metal is not supported on this device"); - self.view = [[NSView alloc] initWithFrame:self.view.frame]; - return; - } - - renderer_ = [[ImpellerRenderer alloc] initWithMetalKitView:view_]; - [renderer_ mtkView:view_ drawableSizeWillChange:view_.bounds.size]; - view_.delegate = renderer_; -} - -@end diff --git a/engine/src/flutter/impeller/host/impeller_renderer.h b/engine/src/flutter/impeller/host/impeller_renderer.h deleted file mode 100644 index 09ea512848..0000000000 --- a/engine/src/flutter/impeller/host/impeller_renderer.h +++ /dev/null @@ -1,11 +0,0 @@ -// 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. - -#import - -@interface ImpellerRenderer : NSObject - -- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view; - -@end diff --git a/engine/src/flutter/impeller/host/impeller_renderer.mm b/engine/src/flutter/impeller/host/impeller_renderer.mm deleted file mode 100644 index a874a6f35c..0000000000 --- a/engine/src/flutter/impeller/host/impeller_renderer.mm +++ /dev/null @@ -1,353 +0,0 @@ -// 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. - -#import -#import -#import "ShaderTypes.h" - -#include "assets_location.h" -#include "flutter/fml/logging.h" -#include "impeller/compositor/formats_metal.h" -#include "impeller/compositor/surface.h" -#include "impeller/entity/entity_renderer.h" -#include "impeller/primitives/box_primitive.h" -#include "impeller_renderer.h" -#include "shaders_location.h" - -static const NSUInteger kMaxBuffersInFlight = 3; - -static const size_t kAlignedUniformsSize = (sizeof(Uniforms) & ~0xFF) + 0x100; - -@implementation ImpellerRenderer { - dispatch_semaphore_t _inFlightSemaphore; - id _device; - id _commandQueue; - - id _dynamicUniformBuffer; - id _pipelineState; - id _depthState; - id _colorMap; - MTLVertexDescriptor* _mtlVertexDescriptor; - - uint32_t _uniformBufferOffset; - - uint8_t _uniformBufferIndex; - - void* _uniformBufferAddress; - - matrix_float4x4 _projectionMatrix; - - float _rotation; - - MTKMesh* _mesh; - std::unique_ptr renderer_; -} - -- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view { - self = [super init]; - if (self) { - _device = view.device; - _inFlightSemaphore = dispatch_semaphore_create(kMaxBuffersInFlight); - [self _loadMetalWithView:view]; - [self _loadAssets]; - } - - renderer_ = std::make_unique( - impeller::ImpellerShadersDirectory()); - FML_CHECK(renderer_->IsValid()) << "Impeller Renderer is not valid."; - return self; -} - -- (void)_loadMetalWithView:(nonnull MTKView*)view { - /// Load Metal state objects and initialize renderer dependent view properties - - view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8; - view.colorPixelFormat = MTLPixelFormatBGRA8Unorm_sRGB; - view.sampleCount = 1; - - _mtlVertexDescriptor = [[MTLVertexDescriptor alloc] init]; - - _mtlVertexDescriptor.attributes[VertexAttributePosition].format = - MTLVertexFormatFloat3; - _mtlVertexDescriptor.attributes[VertexAttributePosition].offset = 0; - _mtlVertexDescriptor.attributes[VertexAttributePosition].bufferIndex = - BufferIndexMeshPositions; - - _mtlVertexDescriptor.attributes[VertexAttributeTexcoord].format = - MTLVertexFormatFloat2; - _mtlVertexDescriptor.attributes[VertexAttributeTexcoord].offset = 0; - _mtlVertexDescriptor.attributes[VertexAttributeTexcoord].bufferIndex = - BufferIndexMeshGenerics; - - _mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stride = 12; - _mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stepRate = 1; - _mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stepFunction = - MTLVertexStepFunctionPerVertex; - - _mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stride = 8; - _mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stepRate = 1; - _mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stepFunction = - MTLVertexStepFunctionPerVertex; - - auto shader_library_path = - impeller::ImpellerShadersLocation("impeller_host.metallib"); - - FML_CHECK(shader_library_path.has_value()); - - NSError* shader_library_error = nil; - - id defaultLibrary = - [_device newLibraryWithFile:@(shader_library_path.value().c_str()) - error:&shader_library_error]; - - id vertexFunction = - [defaultLibrary newFunctionWithName:@"vertexShader"]; - - id fragmentFunction = - [defaultLibrary newFunctionWithName:@"fragmentShader"]; - - MTLRenderPipelineDescriptor* pipelineStateDescriptor = - [[MTLRenderPipelineDescriptor alloc] init]; - pipelineStateDescriptor.label = @"MyPipeline"; - pipelineStateDescriptor.sampleCount = view.sampleCount; - pipelineStateDescriptor.vertexFunction = vertexFunction; - pipelineStateDescriptor.fragmentFunction = fragmentFunction; - pipelineStateDescriptor.vertexDescriptor = _mtlVertexDescriptor; - pipelineStateDescriptor.colorAttachments[0].pixelFormat = - view.colorPixelFormat; - pipelineStateDescriptor.depthAttachmentPixelFormat = - view.depthStencilPixelFormat; - pipelineStateDescriptor.stencilAttachmentPixelFormat = - view.depthStencilPixelFormat; - - NSError* error = NULL; - _pipelineState = - [_device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor - error:&error]; - if (!_pipelineState) { - NSLog(@"Failed to created pipeline state, error %@", error); - } - - MTLDepthStencilDescriptor* depthStateDesc = - [[MTLDepthStencilDescriptor alloc] init]; - depthStateDesc.depthCompareFunction = MTLCompareFunctionLess; - depthStateDesc.depthWriteEnabled = YES; - _depthState = [_device newDepthStencilStateWithDescriptor:depthStateDesc]; - - NSUInteger uniformBufferSize = kAlignedUniformsSize * kMaxBuffersInFlight; - - _dynamicUniformBuffer = - [_device newBufferWithLength:uniformBufferSize - options:MTLResourceStorageModeShared]; - - _dynamicUniformBuffer.label = @"UniformBuffer"; - - _commandQueue = [_device newCommandQueue]; -} - -- (void)_loadAssets { - /// Load assets into metal objects - - NSError* error; - - MTKMeshBufferAllocator* metalAllocator = - [[MTKMeshBufferAllocator alloc] initWithDevice:_device]; - - MDLMesh* mdlMesh = [MDLMesh newBoxWithDimensions:(vector_float3){4, 4, 4} - segments:(vector_uint3){2, 2, 2} - geometryType:MDLGeometryTypeTriangles - inwardNormals:NO - allocator:metalAllocator]; - - MDLVertexDescriptor* mdlVertexDescriptor = - MTKModelIOVertexDescriptorFromMetal(_mtlVertexDescriptor); - - mdlVertexDescriptor.attributes[VertexAttributePosition].name = - MDLVertexAttributePosition; - mdlVertexDescriptor.attributes[VertexAttributeTexcoord].name = - MDLVertexAttributeTextureCoordinate; - - mdlMesh.vertexDescriptor = mdlVertexDescriptor; - - _mesh = [[MTKMesh alloc] initWithMesh:mdlMesh device:_device error:&error]; - - if (!_mesh || error) { - NSLog(@"Error creating MetalKit mesh %@", error.localizedDescription); - } - - MTKTextureLoader* textureLoader = - [[MTKTextureLoader alloc] initWithDevice:_device]; - - NSDictionary* textureLoaderOptions = @{ - MTKTextureLoaderOptionTextureUsage : @(MTLTextureUsageShaderRead), - MTKTextureLoaderOptionTextureStorageMode : @(MTLStorageModePrivate) - }; - - auto color_map_data = [NSData - dataWithContentsOfFile:@(impeller::GetAssetLocation("ColorMap.png") - .c_str())]; - - _colorMap = [textureLoader newTextureWithData:color_map_data - options:textureLoaderOptions - error:&error]; - - if (!_colorMap || error) { - NSLog(@"Error creating texture %@", error.localizedDescription); - } -} - -- (void)_updateDynamicBufferState { - /// Update the state of our uniform buffers before rendering - - _uniformBufferIndex = (_uniformBufferIndex + 1) % kMaxBuffersInFlight; - - _uniformBufferOffset = kAlignedUniformsSize * _uniformBufferIndex; - - _uniformBufferAddress = - ((uint8_t*)_dynamicUniformBuffer.contents) + _uniformBufferOffset; -} - -- (void)_updateGameState { - /// Update any game state before encoding renderint commands to our drawable - - Uniforms* uniforms = (Uniforms*)_uniformBufferAddress; - - uniforms->projectionMatrix = _projectionMatrix; - - vector_float3 rotationAxis = {1, 1, 0}; - matrix_float4x4 modelMatrix = matrix4x4_rotation(_rotation, rotationAxis); - matrix_float4x4 viewMatrix = matrix4x4_translation(0.0, 0.0, -8.0); - - uniforms->modelViewMatrix = matrix_multiply(viewMatrix, modelMatrix); - - _rotation += .01; -} - -- (void)drawInMTKView:(nonnull MTKView*)view { - impeller::Surface surface( - impeller::FromMTLRenderPassDescriptor(view.currentRenderPassDescriptor), - [drawable = view.currentDrawable]() { - [drawable present]; - return true; - }); - if (!renderer_->Render(surface)) { - FML_LOG(ERROR) << "Could not render."; - } - return; - /// Per frame updates here - dispatch_semaphore_wait(_inFlightSemaphore, DISPATCH_TIME_FOREVER); - - id commandBuffer = [_commandQueue commandBuffer]; - commandBuffer.label = @"MyCommand"; - - __block dispatch_semaphore_t block_sema = _inFlightSemaphore; - [commandBuffer addCompletedHandler:^(id buffer) { - dispatch_semaphore_signal(block_sema); - }]; - - [self _updateDynamicBufferState]; - - [self _updateGameState]; - - /// Delay getting the currentRenderPassDescriptor until we absolutely need it - /// to avoid holding onto the drawable and blocking the display pipeline any - /// longer than necessary - MTLRenderPassDescriptor* renderPassDescriptor = - view.currentRenderPassDescriptor; - - if (renderPassDescriptor != nil) { - /// Final pass rendering code here - - id renderEncoder = - [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; - renderEncoder.label = @"MyRenderEncoder"; - - [renderEncoder pushDebugGroup:@"DrawBox"]; - - [renderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; - [renderEncoder setCullMode:MTLCullModeBack]; - [renderEncoder setRenderPipelineState:_pipelineState]; - [renderEncoder setDepthStencilState:_depthState]; - - [renderEncoder setVertexBuffer:_dynamicUniformBuffer - offset:_uniformBufferOffset - atIndex:BufferIndexUniforms]; - - [renderEncoder setFragmentBuffer:_dynamicUniformBuffer - offset:_uniformBufferOffset - atIndex:BufferIndexUniforms]; - - for (NSUInteger bufferIndex = 0; bufferIndex < _mesh.vertexBuffers.count; - bufferIndex++) { - MTKMeshBuffer* vertexBuffer = _mesh.vertexBuffers[bufferIndex]; - if ((NSNull*)vertexBuffer != [NSNull null]) { - [renderEncoder setVertexBuffer:vertexBuffer.buffer - offset:vertexBuffer.offset - atIndex:bufferIndex]; - } - } - - [renderEncoder setFragmentTexture:_colorMap atIndex:TextureIndexColor]; - - for (MTKSubmesh* submesh in _mesh.submeshes) { - [renderEncoder drawIndexedPrimitives:submesh.primitiveType - indexCount:submesh.indexCount - indexType:submesh.indexType - indexBuffer:submesh.indexBuffer.buffer - indexBufferOffset:submesh.indexBuffer.offset]; - } - - [renderEncoder popDebugGroup]; - - [renderEncoder endEncoding]; - - [commandBuffer presentDrawable:view.currentDrawable]; - } - - [commandBuffer commit]; -} - -- (void)mtkView:(nonnull MTKView*)view drawableSizeWillChange:(CGSize)size { - float aspect = size.width / (float)size.height; - _projectionMatrix = matrix_perspective_right_hand(65.0f * (M_PI / 180.0f), - aspect, 0.1f, 100.0f); -} - -#pragma mark Matrix Math Utilities - -// NOLINTNEXTLINE -matrix_float4x4 matrix4x4_translation(float tx, float ty, float tz) { - return (matrix_float4x4){ - {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {tx, ty, tz, 1}}}; -} - -// NOLINTNEXTLINE -static matrix_float4x4 matrix4x4_rotation(float radians, vector_float3 axis) { - axis = vector_normalize(axis); - float ct = cosf(radians); - float st = sinf(radians); - float ci = 1 - ct; - float x = axis.x, y = axis.y, z = axis.z; - - return (matrix_float4x4){ - {{ct + x * x * ci, y * x * ci + z * st, z * x * ci - y * st, 0}, - {x * y * ci - z * st, ct + y * y * ci, z * y * ci + x * st, 0}, - {x * z * ci + y * st, y * z * ci - x * st, ct + z * z * ci, 0}, - {0, 0, 0, 1}}}; -} - -// NOLINTNEXTLINE -matrix_float4x4 matrix_perspective_right_hand(float fovyRadians, - float aspect, - float nearZ, - float farZ) { - float ys = 1 / tanf(fovyRadians * 0.5); - float xs = ys / aspect; - float zs = farZ / (nearZ - farZ); - - return (matrix_float4x4){ - {{xs, 0, 0, 0}, {0, ys, 0, 0}, {0, 0, zs, -1}, {0, 0, nearZ * zs, 0}}}; -} - -@end diff --git a/engine/src/flutter/impeller/host/main.mm b/engine/src/flutter/impeller/host/main.mm deleted file mode 100644 index db234115d8..0000000000 --- a/engine/src/flutter/impeller/host/main.mm +++ /dev/null @@ -1,62 +0,0 @@ -// 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. - -#import - -#include "impeller_host_view_controller.h" - -@interface ImpellerAppDelegate - : NSObject { - NSWindow* window_; - ImpellerHostViewController* view_controller_; -} -@end - -@implementation ImpellerAppDelegate : NSObject - -- (id)init { - if (self = [super init]) { - view_controller_ = [[ImpellerHostViewController alloc] init]; - window_ = [[NSWindow alloc] - initWithContentRect:NSMakeRect(200, 200, 800, 600) - styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable - backing:NSBackingStoreBuffered - defer:NO]; - window_.styleMask |= NSWindowStyleMaskResizable; - [window_ setContentViewController:view_controller_]; - } - return self; -} - -- (void)applicationDidFinishLaunching:(NSNotification*)notification { - [window_ setTitle:@"Impeller Host"]; - [window_ makeKeyAndOrderFront:self]; -} - -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender { - return YES; -} - -@end - -int main(int argc, const char* argv[]) { - NSApplication* app = [NSApplication sharedApplication]; - [app setActivationPolicy:NSApplicationActivationPolicyRegular]; - NSMenuItem* item = [[NSMenuItem alloc] init]; - app.mainMenu = [[NSMenu alloc] init]; - item.submenu = [[NSMenu alloc] init]; - [app.mainMenu addItem:item]; - [item.submenu - addItem:[[NSMenuItem alloc] - initWithTitle:[@"Quit " - stringByAppendingString:[NSProcessInfo - processInfo] - .processName] - action:@selector(terminate:) - keyEquivalent:@"q"]]; - ImpellerAppDelegate* appDelegate = [[ImpellerAppDelegate alloc] init]; - [app setDelegate:appDelegate]; - [app run]; - return 0; -} diff --git a/engine/src/flutter/impeller/host/shaders_location.cc b/engine/src/flutter/impeller/host/shaders_location.cc deleted file mode 100644 index 6ce60a7ef6..0000000000 --- a/engine/src/flutter/impeller/host/shaders_location.cc +++ /dev/null @@ -1,31 +0,0 @@ -// 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 "shaders_location.h" - -#include "flutter/fml/file.h" -#include "flutter/fml/paths.h" - -namespace impeller { - -std::string ImpellerShadersDirectory() { - auto path_result = fml::paths::GetExecutableDirectoryPath(); - if (!path_result.first) { - return {}; - } - return fml::paths::JoinPaths({path_result.second, "shaders"}); -} - -std::optional ImpellerShadersLocation(std::string library_name) { - auto path = fml::paths::JoinPaths({ImpellerShadersDirectory(), library_name}); - - if (!fml::IsFile(path)) { - FML_LOG(ERROR) << "The shader library does not exist: " << path; - return std::nullopt; - } - - return path; -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/host/shaders_location.h b/engine/src/flutter/impeller/host/shaders_location.h deleted file mode 100644 index cd26132f12..0000000000 --- a/engine/src/flutter/impeller/host/shaders_location.h +++ /dev/null @@ -1,14 +0,0 @@ -// 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 -#include - -namespace impeller { - -std::string ImpellerShadersDirectory(); - -std::optional ImpellerShadersLocation(std::string library_name); - -} // namespace impeller diff --git a/engine/src/flutter/impeller/playground/BUILD.gn b/engine/src/flutter/impeller/playground/BUILD.gn index d4fa603a0b..0a912bef5d 100644 --- a/engine/src/flutter/impeller/playground/BUILD.gn +++ b/engine/src/flutter/impeller/playground/BUILD.gn @@ -14,6 +14,7 @@ impeller_component("playground") { ] public_deps = [ + "../compositor", "//flutter/testing", "//third_party/glfw", ] diff --git a/engine/src/flutter/impeller/primitives/box_primitive.mm b/engine/src/flutter/impeller/primitives/box_primitive.mm index 485179770e..556a05dbc4 100644 --- a/engine/src/flutter/impeller/primitives/box_primitive.mm +++ b/engine/src/flutter/impeller/primitives/box_primitive.mm @@ -8,6 +8,7 @@ #include "flutter/fml/logging.h" #include "impeller/base/base.h" +#include "impeller/compositor/pipeline_builder.h" #include "impeller/compositor/pipeline_descriptor.h" #include "impeller/compositor/shader_library.h" #include "impeller/compositor/vertex_descriptor.h" @@ -16,55 +17,17 @@ namespace impeller { BoxPrimitive::BoxPrimitive(std::shared_ptr context) : Primitive(context) { - PipelineDescriptor desc; - desc.SetLabel(SPrintF("%s Pipeline", shader::BoxVertexInfo::kLabel.data())); - - { - auto fragment_function = context->GetShaderLibrary()->GetFunction( - shader::BoxFragmentInfo::kEntrypointName, ShaderStage::kFragment); - auto vertex_function = context->GetShaderLibrary()->GetFunction( - shader::BoxVertexInfo::kEntrypointName, ShaderStage::kVertex); - - desc.AddStageEntrypoint(vertex_function); - desc.AddStageEntrypoint(fragment_function); - } - - { - auto vertex_descriptor = std::make_shared(); - vertex_buffer_index_ = vertex_descriptor->GetVertexBufferIndex(); - if (!vertex_descriptor->SetStageInputs( - shader::BoxVertexInfo::kAllShaderStageInputs)) { - FML_LOG(ERROR) << "Could not configure vertex descriptor."; - return; - } - desc.SetVertexDescriptor(std::move(vertex_descriptor)); - } - - { - // Configure the sole color attachments pixel format. - ColorAttachmentDescriptor color0; - color0.format = PixelFormat::kPixelFormat_B8G8R8A8_UNormInt_SRGB; - - desc.SetColorAttachmentDescriptor(0u, std::move(color0)); - } - - { - // Configure the stencil attachment. - // TODO(wip): Make this configurable if possible as the D32 component is - // wasted. - const auto combined_depth_stencil_format = - PixelFormat::kPixelFormat_D32_Float_S8_UNormInt; - desc.SetDepthPixelFormat(combined_depth_stencil_format); - desc.SetStencilPixelFormat(combined_depth_stencil_format); - } - - pipeline_ = - context->GetPipelineLibrary()->GetRenderPipeline(std::move(desc)).get(); - if (!pipeline_) { - FML_LOG(ERROR) << "Could not create the render pipeline."; + using Builder = PipelineBuilder; + auto pipeline_descriptor = Builder::MakeDefaultPipelineDescriptor(*context); + if (!pipeline_descriptor.has_value()) { + return; + } + pipeline_ = context->GetPipelineLibrary() + ->GetRenderPipeline(pipeline_descriptor.value()) + .get(); + if (!pipeline_) { return; } - is_valid_ = true; }