[Impeller] Implement morphology image filter (flutter/engine#35584)

This commit is contained in:
ColdPaleLight
2022-08-26 10:11:18 +08:00
committed by GitHub
parent 017b782e8e
commit 8bc606fb63
12 changed files with 473 additions and 2 deletions

View File

@@ -584,6 +584,8 @@ FILE: ../../../flutter/impeller/entity/contents/filters/inputs/texture_filter_in
FILE: ../../../flutter/impeller/entity/contents/filters/inputs/texture_filter_input.h
FILE: ../../../flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc
FILE: ../../../flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h
FILE: ../../../flutter/impeller/entity/contents/filters/morphology_filter_contents.cc
FILE: ../../../flutter/impeller/entity/contents/filters/morphology_filter_contents.h
FILE: ../../../flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc
FILE: ../../../flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.h
FILE: ../../../flutter/impeller/entity/contents/linear_gradient_contents.cc
@@ -650,6 +652,8 @@ FILE: ../../../flutter/impeller/entity/shaders/gradient_fill.vert
FILE: ../../../flutter/impeller/entity/shaders/linear_gradient_fill.frag
FILE: ../../../flutter/impeller/entity/shaders/linear_to_srgb_filter.frag
FILE: ../../../flutter/impeller/entity/shaders/linear_to_srgb_filter.vert
FILE: ../../../flutter/impeller/entity/shaders/morphology_filter.frag
FILE: ../../../flutter/impeller/entity/shaders/morphology_filter.vert
FILE: ../../../flutter/impeller/entity/shaders/radial_gradient_fill.frag
FILE: ../../../flutter/impeller/entity/shaders/rrect_blur.frag
FILE: ../../../flutter/impeller/entity/shaders/rrect_blur.vert

View File

@@ -534,8 +534,36 @@ static std::optional<Paint::ImageFilterProc> ToImageFilterProc(
break;
}
case flutter::DlImageFilterType::kDilate:
case flutter::DlImageFilterType::kErode:
case flutter::DlImageFilterType::kDilate: {
auto dilate = filter->asDilate();
FML_DCHECK(dilate);
if (dilate->radius_x() < 0 || dilate->radius_y() < 0) {
return std::nullopt;
}
auto radius_x = Radius(dilate->radius_x());
auto radius_y = Radius(dilate->radius_y());
return [radius_x, radius_y](FilterInput::Ref input,
const Matrix& effect_transform) {
return FilterContents::MakeMorphology(
input, radius_x, radius_y, FilterContents::MorphType::kDilate);
};
break;
}
case flutter::DlImageFilterType::kErode: {
auto erode = filter->asErode();
FML_DCHECK(erode);
if (erode->radius_x() < 0 || erode->radius_y() < 0) {
return std::nullopt;
}
auto radius_x = Radius(erode->radius_x());
auto radius_y = Radius(erode->radius_y());
return [radius_x, radius_y](FilterInput::Ref input,
const Matrix& effect_transform) {
return FilterContents::MakeMorphology(
input, radius_x, radius_y, FilterContents::MorphType::kErode);
};
break;
}
case flutter::DlImageFilterType::kMatrix:
case flutter::DlImageFilterType::kLocalMatrixFilter:
case flutter::DlImageFilterType::kComposeFilter:

View File

@@ -40,6 +40,8 @@ impeller_shaders("entity_shaders") {
"shaders/linear_to_srgb_filter.frag",
"shaders/linear_to_srgb_filter.vert",
"shaders/linear_gradient_fill.frag",
"shaders/morphology_filter.frag",
"shaders/morphology_filter.vert",
"shaders/radial_gradient_fill.frag",
"shaders/rrect_blur.vert",
"shaders/rrect_blur.frag",
@@ -91,6 +93,8 @@ impeller_component("entity") {
"contents/filters/inputs/texture_filter_input.h",
"contents/filters/linear_to_srgb_filter_contents.cc",
"contents/filters/linear_to_srgb_filter_contents.h",
"contents/filters/morphology_filter_contents.cc",
"contents/filters/morphology_filter_contents.h",
"contents/filters/srgb_to_linear_filter_contents.cc",
"contents/filters/srgb_to_linear_filter_contents.h",
"contents/linear_gradient_contents.cc",

View File

@@ -197,6 +197,8 @@ ContentContext::ContentContext(std::shared_ptr<Context> context)
CreateDefaultPipeline<GaussianBlurPipeline>(*context_);
border_mask_blur_pipelines_[{}] =
CreateDefaultPipeline<BorderMaskBlurPipeline>(*context_);
morphology_filter_pipelines_[{}] =
CreateDefaultPipeline<MorphologyFilterPipeline>(*context_);
color_matrix_color_filter_pipelines_[{}] =
CreateDefaultPipeline<ColorMatrixColorFilterPipeline>(*context_);
linear_to_srgb_filter_pipelines_[{}] =

View File

@@ -44,6 +44,8 @@
#include "impeller/entity/linear_gradient_fill.frag.h"
#include "impeller/entity/linear_to_srgb_filter.frag.h"
#include "impeller/entity/linear_to_srgb_filter.vert.h"
#include "impeller/entity/morphology_filter.frag.h"
#include "impeller/entity/morphology_filter.vert.h"
#include "impeller/entity/radial_gradient_fill.frag.h"
#include "impeller/entity/rrect_blur.frag.h"
#include "impeller/entity/rrect_blur.vert.h"
@@ -114,6 +116,8 @@ using GaussianBlurPipeline =
PipelineT<GaussianBlurVertexShader, GaussianBlurFragmentShader>;
using BorderMaskBlurPipeline =
PipelineT<BorderMaskBlurVertexShader, BorderMaskBlurFragmentShader>;
using MorphologyFilterPipeline =
PipelineT<MorphologyFilterVertexShader, MorphologyFilterFragmentShader>;
using ColorMatrixColorFilterPipeline =
PipelineT<ColorMatrixColorFilterVertexShader,
ColorMatrixColorFilterFragmentShader>;
@@ -214,6 +218,11 @@ class ContentContext {
return GetPipeline(border_mask_blur_pipelines_, opts);
}
std::shared_ptr<Pipeline> GetMorphologyFilterPipeline(
ContentContextOptions opts) const {
return GetPipeline(morphology_filter_pipelines_, opts);
}
std::shared_ptr<Pipeline> GetColorMatrixColorFilterPipeline(
ContentContextOptions opts) const {
return GetPipeline(color_matrix_color_filter_pipelines_, opts);
@@ -361,6 +370,7 @@ class ContentContext {
mutable Variants<TiledTexturePipeline> tiled_texture_pipelines_;
mutable Variants<GaussianBlurPipeline> gaussian_blur_pipelines_;
mutable Variants<BorderMaskBlurPipeline> border_mask_blur_pipelines_;
mutable Variants<MorphologyFilterPipeline> morphology_filter_pipelines_;
mutable Variants<ColorMatrixColorFilterPipeline>
color_matrix_color_filter_pipelines_;
mutable Variants<LinearToSrgbFilterPipeline> linear_to_srgb_filter_pipelines_;

View File

@@ -20,6 +20,7 @@
#include "impeller/entity/contents/filters/gaussian_blur_filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/entity/contents/filters/linear_to_srgb_filter_contents.h"
#include "impeller/entity/contents/filters/morphology_filter_contents.h"
#include "impeller/entity/contents/filters/srgb_to_linear_filter_contents.h"
#include "impeller/entity/contents/texture_contents.h"
#include "impeller/entity/entity.h"
@@ -123,6 +124,31 @@ std::shared_ptr<FilterContents> FilterContents::MakeBorderMaskBlur(
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeDirectionalMorphology(
FilterInput::Ref input,
Radius radius,
Vector2 direction,
MorphType morph_type) {
auto filter = std::make_shared<DirectionalMorphologyFilterContents>();
filter->SetInputs({input});
filter->SetRadius(radius);
filter->SetDirection(direction);
filter->SetMorphType(morph_type);
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeMorphology(
FilterInput::Ref input,
Radius radius_x,
Radius radius_y,
MorphType morph_type) {
auto x_morphology =
MakeDirectionalMorphology(input, radius_x, Point(1, 0), morph_type);
auto y_morphology = MakeDirectionalMorphology(
FilterInput::Make(x_morphology), radius_y, Point(0, 1), morph_type);
return y_morphology;
}
std::shared_ptr<FilterContents> FilterContents::MakeColorMatrix(
FilterInput::Ref input,
const ColorMatrix& matrix) {

View File

@@ -36,6 +36,8 @@ class FilterContents : public Contents {
float array[20];
};
enum class MorphType { kDilate, kErode };
static std::shared_ptr<FilterContents> MakeBlend(
Entity::BlendMode blend_mode,
FilterInput::Vector inputs,
@@ -66,6 +68,17 @@ class FilterContents : public Contents {
BlurStyle blur_style = BlurStyle::kNormal,
const Matrix& effect_transform = Matrix());
static std::shared_ptr<FilterContents> MakeDirectionalMorphology(
FilterInput::Ref input,
Radius radius,
Vector2 direction,
MorphType morph_type);
static std::shared_ptr<FilterContents> MakeMorphology(FilterInput::Ref input,
Radius radius_x,
Radius radius_y,
MorphType morph_type);
static std::shared_ptr<FilterContents> MakeColorMatrix(
FilterInput::Ref input,
const ColorMatrix& matrix);

View File

@@ -0,0 +1,169 @@
// 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/entity/contents/filters/morphology_filter_contents.h"
#include <cmath>
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/sampler_library.h"
namespace impeller {
DirectionalMorphologyFilterContents::DirectionalMorphologyFilterContents() =
default;
DirectionalMorphologyFilterContents::~DirectionalMorphologyFilterContents() =
default;
void DirectionalMorphologyFilterContents::SetRadius(Radius radius) {
radius_ = radius;
}
void DirectionalMorphologyFilterContents::SetDirection(Vector2 direction) {
direction_ = direction.Normalize();
if (direction_.IsZero()) {
direction_ = Vector2(0, 1);
}
}
void DirectionalMorphologyFilterContents::SetMorphType(MorphType morph_type) {
morph_type_ = morph_type;
}
std::optional<Snapshot> DirectionalMorphologyFilterContents::RenderFilter(
const FilterInput::Vector& inputs,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage) const {
using VS = MorphologyFilterPipeline::VertexShader;
using FS = MorphologyFilterPipeline::FragmentShader;
//----------------------------------------------------------------------------
/// Handle inputs.
///
if (inputs.empty()) {
return std::nullopt;
}
auto input_snapshot = inputs[0]->GetSnapshot(renderer, entity);
if (!input_snapshot.has_value()) {
return std::nullopt;
}
if (radius_.radius < kEhCloseEnough) {
return input_snapshot.value();
}
auto maybe_input_uvs = input_snapshot->GetCoverageUVs(coverage);
if (!maybe_input_uvs.has_value()) {
return std::nullopt;
}
auto input_uvs = maybe_input_uvs.value();
//----------------------------------------------------------------------------
/// Render to texture.
///
ContentContext::SubpassCallback callback = [&](const ContentContext& renderer,
RenderPass& pass) {
auto& host_buffer = pass.GetTransientsBuffer();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(0, 0), input_uvs[0]},
{Point(1, 0), input_uvs[1]},
{Point(1, 1), input_uvs[3]},
{Point(0, 0), input_uvs[0]},
{Point(1, 1), input_uvs[3]},
{Point(0, 1), input_uvs[2]},
});
auto vtx_buffer = vtx_builder.CreateVertexBuffer(host_buffer);
VS::FrameInfo frame_info;
frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1));
auto transformed_radius = entity.GetTransformation().TransformDirection(
direction_ * radius_.radius);
auto transformed_texture_vertices =
Rect(Size(input_snapshot->texture->GetSize()))
.GetTransformedPoints(input_snapshot->transform);
auto transformed_texture_width =
transformed_texture_vertices[0].GetDistance(
transformed_texture_vertices[1]);
auto transformed_texture_height =
transformed_texture_vertices[0].GetDistance(
transformed_texture_vertices[2]);
FS::FragInfo frag_info;
frag_info.texture_sampler_y_coord_scale =
input_snapshot->texture->GetYCoordScale();
frag_info.radius = std::round(transformed_radius.GetLength());
frag_info.direction = input_snapshot->transform.Invert()
.TransformDirection(transformed_radius)
.Normalize();
frag_info.texture_size =
Point(transformed_texture_width, transformed_texture_height);
frag_info.morph_type = static_cast<Scalar>(morph_type_);
Command cmd;
cmd.label = "Morphology Filter";
auto options = OptionsFromPass(pass);
options.blend_mode = Entity::BlendMode::kSource;
cmd.pipeline = renderer.GetMorphologyFilterPipeline(options);
cmd.BindVertices(vtx_buffer);
FS::BindTextureSampler(
cmd, input_snapshot->texture,
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
input_snapshot->sampler_descriptor));
VS::BindFrameInfo(cmd, host_buffer.EmplaceUniform(frame_info));
FS::BindFragInfo(cmd, host_buffer.EmplaceUniform(frag_info));
return pass.AddCommand(cmd);
};
auto out_texture = renderer.MakeSubpass(ISize(coverage.size), callback);
if (!out_texture) {
return std::nullopt;
}
out_texture->SetLabel("DirectionalMorphologyFilter Texture");
SamplerDescriptor sampler_desc;
sampler_desc.min_filter = MinMagFilter::kLinear;
sampler_desc.mag_filter = MinMagFilter::kLinear;
return Snapshot{.texture = out_texture,
.transform = Matrix::MakeTranslation(coverage.origin),
.sampler_descriptor = sampler_desc};
}
std::optional<Rect> DirectionalMorphologyFilterContents::GetFilterCoverage(
const FilterInput::Vector& inputs,
const Entity& entity,
const Matrix& effect_transform) const {
if (inputs.empty()) {
return std::nullopt;
}
auto coverage = inputs[0]->GetCoverage(entity);
if (!coverage.has_value()) {
return std::nullopt;
}
auto transformed_vector = inputs[0]
->GetTransform(entity)
.TransformDirection(direction_ * radius_.radius)
.Abs();
auto extent = coverage->size + transformed_vector * 2;
return Rect(coverage->origin - transformed_vector, Size(extent.x, extent.y));
}
} // namespace impeller

View File

@@ -0,0 +1,48 @@
// 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 <memory>
#include <optional>
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
namespace impeller {
class DirectionalMorphologyFilterContents final : public FilterContents {
public:
DirectionalMorphologyFilterContents();
~DirectionalMorphologyFilterContents() override;
void SetRadius(Radius radius);
void SetDirection(Vector2 direction);
void SetMorphType(MorphType morph_type);
// |FilterContents|
std::optional<Rect> GetFilterCoverage(
const FilterInput::Vector& inputs,
const Entity& entity,
const Matrix& effect_transform) const override;
private:
// |FilterContents|
std::optional<Snapshot> RenderFilter(
const FilterInput::Vector& input_textures,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage) const override;
Radius radius_;
Vector2 direction_;
MorphType morph_type_;
FML_DISALLOW_COPY_AND_ASSIGN(DirectionalMorphologyFilterContents);
};
} // namespace impeller

View File

@@ -991,6 +991,107 @@ TEST_P(EntityTest, GaussianBlurFilter) {
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(EntityTest, MorphologyFilter) {
auto boston = CreateTextureForFixture("boston.jpg");
ASSERT_TRUE(boston);
bool first_frame = true;
auto callback = [&](ContentContext& context, RenderPass& pass) -> bool {
if (first_frame) {
first_frame = false;
ImGui::SetNextWindowPos({10, 10});
}
const char* morphology_type_names[] = {"Dilate", "Erode"};
const FilterContents::MorphType morphology_types[] = {
FilterContents::MorphType::kDilate, FilterContents::MorphType::kErode};
static Color input_color = Color::Black();
// UI state.
static int selected_morphology_type = 0;
static float radius[2] = {20, 20};
static Color cover_color(1, 0, 0, 0.2);
static Color bounds_color(0, 1, 0, 0.1);
static float offset[2] = {500, 400};
static float rotation = 0;
static float scale[2] = {0.65, 0.65};
static float skew[2] = {0, 0};
static float path_rect[4] = {0, 0,
static_cast<float>(boston->GetSize().width),
static_cast<float>(boston->GetSize().height)};
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
{
ImGui::Combo("Morphology type", &selected_morphology_type,
morphology_type_names,
sizeof(morphology_type_names) / sizeof(char*));
ImGui::SliderFloat2("Radius", radius, 0, 200);
ImGui::SliderFloat("Input opacity", &input_color.alpha, 0, 1);
ImGui::ColorEdit4("Cover color", reinterpret_cast<float*>(&cover_color));
ImGui::ColorEdit4("Bounds color",
reinterpret_cast<float*>(&bounds_color));
ImGui::SliderFloat2("Translation", offset, 0,
pass.GetRenderTargetSize().width);
ImGui::SliderFloat("Rotation", &rotation, 0, kPi * 2);
ImGui::SliderFloat2("Scale", scale, 0, 3);
ImGui::SliderFloat2("Skew", skew, -3, 3);
ImGui::SliderFloat4("Path XYWH", path_rect, -1000, 1000);
}
ImGui::End();
std::shared_ptr<Contents> input;
Size input_size;
auto input_rect =
Rect::MakeXYWH(path_rect[0], path_rect[1], path_rect[2], path_rect[3]);
auto texture = std::make_shared<TextureContents>();
texture->SetSourceRect(Rect::MakeSize(boston->GetSize()));
texture->SetPath(PathBuilder{}.AddRect(input_rect).TakePath());
texture->SetTexture(boston);
texture->SetOpacity(input_color.alpha);
input = texture;
input_size = input_rect.size;
auto contents = FilterContents::MakeMorphology(
FilterInput::Make(input), Radius{radius[0]}, Radius{radius[1]},
morphology_types[selected_morphology_type]);
auto ctm = Matrix::MakeScale(GetContentScale()) *
Matrix::MakeTranslation(Vector3(offset[0], offset[1])) *
Matrix::MakeRotationZ(Radians(rotation)) *
Matrix::MakeScale(Vector2(scale[0], scale[1])) *
Matrix::MakeSkew(skew[0], skew[1]) *
Matrix::MakeTranslation(-Point(input_size) / 2);
Entity entity;
entity.SetContents(contents);
entity.SetTransformation(ctm);
entity.Render(context, pass);
// Renders a red "cover" rectangle that shows the original position of the
// unfiltered input.
Entity cover_entity;
cover_entity.SetContents(SolidColorContents::Make(
PathBuilder{}.AddRect(input_rect).TakePath(), cover_color));
cover_entity.SetTransformation(ctm);
cover_entity.Render(context, pass);
// Renders a green bounding rect of the target filter.
Entity bounds_entity;
bounds_entity.SetContents(SolidColorContents::Make(
PathBuilder{}.AddRect(contents->GetCoverage(entity).value()).TakePath(),
bounds_color));
bounds_entity.SetTransformation(Matrix());
bounds_entity.Render(context, pass);
return true;
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(EntityTest, SetBlendMode) {
Entity entity;
ASSERT_EQ(entity.GetBlendMode(), Entity::BlendMode::kSourceOver);

View File

@@ -0,0 +1,48 @@
// 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/constants.glsl>
#include <impeller/texture.glsl>
// These values must correspond to the order of the items in the
// 'FilterContents::MorphType' enum class.
const float kMorphTypeDilate = 0;
const float kMorphTypeErode = 1;
uniform sampler2D texture_sampler;
uniform FragInfo {
float texture_sampler_y_coord_scale;
vec2 texture_size;
vec2 direction;
float radius;
float morph_type;
}
frag_info;
in vec2 v_texture_coords;
out vec4 frag_color;
void main() {
vec4 result = frag_info.morph_type == kMorphTypeDilate ? vec4(0) : vec4(1);
vec2 uv_offset = frag_info.direction / frag_info.texture_size;
for (float i = -frag_info.radius; i <= frag_info.radius; i++) {
vec2 texture_coords = v_texture_coords + uv_offset * i;
vec4 color;
color =
IPSampleWithTileMode(
texture_sampler, // sampler
texture_coords, // texture coordinates
frag_info.texture_sampler_y_coord_scale, // y coordinate scale
kTileModeDecal // tile mode
);
if (frag_info.morph_type == kMorphTypeDilate) {
result = max(color, result);
} else {
result = min(color, result);
}
}
frag_color = result;
}

View File

@@ -0,0 +1,18 @@
// 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.
uniform FrameInfo {
mat4 mvp;
}
frame_info;
in vec2 position;
in vec2 texture_coords;
out vec2 v_texture_coords;
void main() {
gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0);
v_texture_coords = texture_coords;
}