From e677fa488ed2103032130dc4a48c88333edeed90 Mon Sep 17 00:00:00 2001 From: Jim Graham Date: Fri, 8 Dec 2023 14:23:03 -0800 Subject: [PATCH] [Impeller] Directly tessellate filled ellipses (flutter/engine#48770) Add support for filling ellipses/ovals and greatly simplify the primitive tessellation mechanisms. --- .../flutter/ci/licenses_golden/excluded_files | 1 - .../ci/licenses_golden/licenses_flutter | 8 +- .../flutter/impeller/aiks/aiks_unittests.cc | 71 ++++ engine/src/flutter/impeller/aiks/canvas.cc | 33 +- engine/src/flutter/impeller/aiks/canvas.h | 8 +- .../impeller/display_list/dl_dispatcher.cc | 16 +- engine/src/flutter/impeller/entity/BUILD.gn | 2 + .../entity/geometry/circle_geometry.cc | 98 +++++ .../entity/geometry/circle_geometry.h | 57 +++ .../entity/geometry/ellipse_geometry.cc | 164 +------- .../entity/geometry/ellipse_geometry.h | 29 +- .../impeller/entity/geometry/geometry.cc | 89 +++- .../impeller/entity/geometry/geometry.h | 32 +- .../impeller/entity/geometry/line_geometry.cc | 119 ++---- .../entity/geometry/point_field_geometry.cc | 24 +- engine/src/flutter/impeller/geometry/rect.h | 8 + .../impeller/geometry/rect_unittests.cc | 19 + engine/src/flutter/impeller/geometry/size.h | 4 + .../impeller/geometry/size_unittests.cc | 24 ++ engine/src/flutter/impeller/geometry/trig.h | 7 + .../impeller/geometry/trig_unittests.cc | 14 + .../src/flutter/impeller/tessellator/BUILD.gn | 11 +- .../tessellator/circle_tessellator.cc | 261 ------------ .../impeller/tessellator/circle_tessellator.h | 154 ------- .../circle_tessellator_unittests.cc | 170 -------- .../impeller/tessellator/tessellator.cc | 391 ++++++++++++++++++ .../impeller/tessellator/tessellator.h | 218 +++++++++- .../tessellator/tessellator_unittests.cc | 279 +++++++++++++ 28 files changed, 1410 insertions(+), 901 deletions(-) create mode 100644 engine/src/flutter/impeller/entity/geometry/circle_geometry.cc create mode 100644 engine/src/flutter/impeller/entity/geometry/circle_geometry.h delete mode 100644 engine/src/flutter/impeller/tessellator/circle_tessellator.cc delete mode 100644 engine/src/flutter/impeller/tessellator/circle_tessellator.h delete mode 100644 engine/src/flutter/impeller/tessellator/circle_tessellator_unittests.cc diff --git a/engine/src/flutter/ci/licenses_golden/excluded_files b/engine/src/flutter/ci/licenses_golden/excluded_files index 1a3d32805d..ede6fc4037 100644 --- a/engine/src/flutter/ci/licenses_golden/excluded_files +++ b/engine/src/flutter/ci/licenses_golden/excluded_files @@ -194,7 +194,6 @@ ../../../flutter/impeller/scene/importer/importer_unittests.cc ../../../flutter/impeller/scene/scene_unittests.cc ../../../flutter/impeller/shader_archive/shader_archive_unittests.cc -../../../flutter/impeller/tessellator/circle_tessellator_unittests.cc ../../../flutter/impeller/tessellator/dart/.dart_tool ../../../flutter/impeller/tessellator/dart/pubspec.lock ../../../flutter/impeller/tessellator/dart/pubspec.yaml diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index c61168f67d..2393b61f71 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -5099,6 +5099,8 @@ ORIGIN: ../../../flutter/impeller/entity/entity_pass_target.cc + ../../../flutte ORIGIN: ../../../flutter/impeller/entity/entity_pass_target.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/entity/entity_playground.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/entity/entity_playground.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/entity/geometry/circle_geometry.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/entity/geometry/circle_geometry.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/entity/geometry/cover_geometry.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/entity/geometry/cover_geometry.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/entity/geometry/ellipse_geometry.cc + ../../../flutter/LICENSE @@ -5527,8 +5529,6 @@ ORIGIN: ../../../flutter/impeller/shader_archive/shader_archive_writer.cc + ../. ORIGIN: ../../../flutter/impeller/shader_archive/shader_archive_writer.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/tessellator/c/tessellator.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/tessellator/c/tessellator.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/tessellator/circle_tessellator.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/tessellator/circle_tessellator.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/tessellator/dart/lib/tessellator.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/tessellator/tessellator.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/tessellator/tessellator.h + ../../../flutter/LICENSE @@ -7898,6 +7898,8 @@ FILE: ../../../flutter/impeller/entity/entity_pass_target.cc FILE: ../../../flutter/impeller/entity/entity_pass_target.h FILE: ../../../flutter/impeller/entity/entity_playground.cc FILE: ../../../flutter/impeller/entity/entity_playground.h +FILE: ../../../flutter/impeller/entity/geometry/circle_geometry.cc +FILE: ../../../flutter/impeller/entity/geometry/circle_geometry.h FILE: ../../../flutter/impeller/entity/geometry/cover_geometry.cc FILE: ../../../flutter/impeller/entity/geometry/cover_geometry.h FILE: ../../../flutter/impeller/entity/geometry/ellipse_geometry.cc @@ -8327,8 +8329,6 @@ FILE: ../../../flutter/impeller/shader_archive/shader_archive_writer.cc FILE: ../../../flutter/impeller/shader_archive/shader_archive_writer.h FILE: ../../../flutter/impeller/tessellator/c/tessellator.cc FILE: ../../../flutter/impeller/tessellator/c/tessellator.h -FILE: ../../../flutter/impeller/tessellator/circle_tessellator.cc -FILE: ../../../flutter/impeller/tessellator/circle_tessellator.h FILE: ../../../flutter/impeller/tessellator/dart/lib/tessellator.dart FILE: ../../../flutter/impeller/tessellator/tessellator.cc FILE: ../../../flutter/impeller/tessellator/tessellator.h diff --git a/engine/src/flutter/impeller/aiks/aiks_unittests.cc b/engine/src/flutter/impeller/aiks/aiks_unittests.cc index 050feedd00..de64dc27ec 100644 --- a/engine/src/flutter/impeller/aiks/aiks_unittests.cc +++ b/engine/src/flutter/impeller/aiks/aiks_unittests.cc @@ -2193,6 +2193,77 @@ TEST_P(AiksTest, StrokedCirclesRenderCorrectly) { ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); } +TEST_P(AiksTest, FilledEllipsesRenderCorrectly) { + Canvas canvas; + canvas.Scale(GetContentScale()); + Paint paint; + const int color_count = 3; + Color colors[color_count] = { + Color::Blue(), + Color::Green(), + Color::Crimson(), + }; + + paint.color = Color::White(); + canvas.DrawPaint(paint); + + int c_index = 0; + int long_radius = 600; + int short_radius = 600; + while (long_radius > 0 && short_radius > 0) { + paint.color = colors[(c_index++) % color_count]; + canvas.DrawOval(Rect::MakeXYWH(10 - long_radius, 10 - short_radius, + long_radius * 2, short_radius * 2), + paint); + canvas.DrawOval(Rect::MakeXYWH(1000 - short_radius, 750 - long_radius, + short_radius * 2, long_radius * 2), + paint); + if (short_radius > 30) { + short_radius -= 10; + long_radius -= 5; + } else { + short_radius -= 2; + long_radius -= 1; + } + } + + std::vector gradient_colors = { + Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0}, + Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0}, + Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0}, + Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0}, + Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0}, + Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0}, + Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}}; + std::vector stops = { + 0.0, + (1.0 / 6.0) * 1, + (1.0 / 6.0) * 2, + (1.0 / 6.0) * 3, + (1.0 / 6.0) * 4, + (1.0 / 6.0) * 5, + 1.0, + }; + auto texture = CreateTextureForFixture("airplane.jpg", + /*enable_mipmapping=*/true); + + paint.color = Color::White().WithAlpha(0.5); + + paint.color_source = ColorSource::MakeRadialGradient( + {300, 650}, 75, std::move(gradient_colors), std::move(stops), + Entity::TileMode::kMirror, {}); + canvas.DrawOval(Rect::MakeXYWH(200, 625, 200, 50), paint); + canvas.DrawOval(Rect::MakeXYWH(275, 550, 50, 200), paint); + + paint.color_source = ColorSource::MakeImage( + texture, Entity::TileMode::kRepeat, Entity::TileMode::kRepeat, {}, + Matrix::MakeTranslation({610, 15})); + canvas.DrawOval(Rect::MakeXYWH(610, 90, 200, 50), paint); + canvas.DrawOval(Rect::MakeXYWH(685, 15, 50, 200), paint); + + ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); +} + TEST_P(AiksTest, GradientStrokesRenderCorrectly) { // Compare with https://fiddle.skia.org/c/027392122bec8ac2b5d5de00a4b9bbe2 auto callback = [&](AiksContext& renderer) -> std::optional { diff --git a/engine/src/flutter/impeller/aiks/canvas.cc b/engine/src/flutter/impeller/aiks/canvas.cc index 5b6953828f..221326aff4 100644 --- a/engine/src/flutter/impeller/aiks/canvas.cc +++ b/engine/src/flutter/impeller/aiks/canvas.cc @@ -318,7 +318,7 @@ void Canvas::DrawLine(const Point& p0, const Point& p1, const Paint& paint) { GetCurrentPass().AddEntity(std::move(entity)); } -void Canvas::DrawRect(Rect rect, const Paint& paint) { +void Canvas::DrawRect(const Rect& rect, const Paint& paint) { if (paint.style == Paint::Style::kStroke) { DrawPath(PathBuilder{}.AddRect(rect).TakePath(), paint); return; @@ -338,6 +338,33 @@ void Canvas::DrawRect(Rect rect, const Paint& paint) { GetCurrentPass().AddEntity(std::move(entity)); } +void Canvas::DrawOval(const Rect& rect, const Paint& paint) { + if (rect.IsSquare()) { + // Circles have slightly less overhead and can do stroking + DrawCircle(rect.GetCenter(), rect.GetSize().width * 0.5f, paint); + return; + } + + if (paint.style == Paint::Style::kStroke) { + // No stroked ellipses yet + DrawPath(PathBuilder{}.AddOval(rect).TakePath(), paint); + return; + } + + if (AttemptDrawBlurredRRect(rect, 0, paint)) { + return; + } + + Entity entity; + entity.SetTransform(GetCurrentTransform()); + entity.SetClipDepth(GetClipDepth()); + entity.SetBlendMode(paint.blend_mode); + entity.SetContents( + CreateContentsForGeometryWithFilters(paint, Geometry::MakeOval(rect))); + + GetCurrentPass().AddEntity(std::move(entity)); +} + void Canvas::DrawRRect(Rect rect, Point corner_radii, const Paint& paint) { if (corner_radii.x == corner_radii.y && AttemptDrawBlurredRRect(rect, corner_radii.x, paint)) { @@ -362,7 +389,9 @@ void Canvas::DrawRRect(Rect rect, Point corner_radii, const Paint& paint) { DrawPath(std::move(path), paint); } -void Canvas::DrawCircle(Point center, Scalar radius, const Paint& paint) { +void Canvas::DrawCircle(const Point& center, + Scalar radius, + const Paint& paint) { Size half_size(radius, radius); if (AttemptDrawBlurredRRect( Rect::MakeOriginSize(center - half_size, half_size * 2), radius, diff --git a/engine/src/flutter/impeller/aiks/canvas.h b/engine/src/flutter/impeller/aiks/canvas.h index 88274f8d24..70c85cb1ef 100644 --- a/engine/src/flutter/impeller/aiks/canvas.h +++ b/engine/src/flutter/impeller/aiks/canvas.h @@ -102,13 +102,15 @@ class Canvas { void DrawLine(const Point& p0, const Point& p1, const Paint& paint); - void DrawRect(Rect rect, const Paint& paint); + void DrawRect(const Rect& rect, const Paint& paint); + + void DrawOval(const Rect& rect, const Paint& paint); void DrawRRect(Rect rect, Point corner_radii, const Paint& paint); - void DrawCircle(Point center, Scalar radius, const Paint& paint); + void DrawCircle(const Point& center, Scalar radius, const Paint& paint); - void DrawPoints(std::vector, + void DrawPoints(std::vector points, Scalar radius, const Paint& paint, PointStyle point_style); diff --git a/engine/src/flutter/impeller/display_list/dl_dispatcher.cc b/engine/src/flutter/impeller/display_list/dl_dispatcher.cc index e251fdcd71..465b71f49c 100644 --- a/engine/src/flutter/impeller/display_list/dl_dispatcher.cc +++ b/engine/src/flutter/impeller/display_list/dl_dispatcher.cc @@ -770,16 +770,7 @@ void DlDispatcher::drawRect(const SkRect& rect) { // |flutter::DlOpReceiver| void DlDispatcher::drawOval(const SkRect& bounds) { - if (bounds.width() == bounds.height()) { - canvas_.DrawCircle(skia_conversions::ToPoint(bounds.center()), - bounds.width() * 0.5, paint_); - } else { - auto path = PathBuilder{} - .AddOval(skia_conversions::ToRect(bounds)) - .SetConvexity(Convexity::kConvex) - .TakePath(); - canvas_.DrawPath(std::move(path), paint_); - } + canvas_.DrawOval(skia_conversions::ToRect(bounds), paint_); } // |flutter::DlOpReceiver| @@ -831,9 +822,8 @@ void DlDispatcher::SimplifyOrDrawPath(CanvasType& canvas, } SkRect oval; - if (path.isOval(&oval) && oval.width() == oval.height()) { - canvas.DrawCircle(skia_conversions::ToPoint(oval.center()), - oval.width() * 0.5, paint); + if (path.isOval(&oval)) { + canvas.DrawOval(skia_conversions::ToRect(oval), paint); return; } diff --git a/engine/src/flutter/impeller/entity/BUILD.gn b/engine/src/flutter/impeller/entity/BUILD.gn index 9d92ed95cc..6c3f9ff273 100644 --- a/engine/src/flutter/impeller/entity/BUILD.gn +++ b/engine/src/flutter/impeller/entity/BUILD.gn @@ -191,6 +191,8 @@ impeller_component("entity") { "entity_pass_delegate.h", "entity_pass_target.cc", "entity_pass_target.h", + "geometry/circle_geometry.cc", + "geometry/circle_geometry.h", "geometry/cover_geometry.cc", "geometry/cover_geometry.h", "geometry/ellipse_geometry.cc", diff --git a/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc b/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc new file mode 100644 index 0000000000..908485a811 --- /dev/null +++ b/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc @@ -0,0 +1,98 @@ +// 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 "flutter/impeller/entity/geometry/circle_geometry.h" + +#include "flutter/impeller/entity/geometry/line_geometry.h" + +namespace impeller { + +CircleGeometry::CircleGeometry(const Point& center, Scalar radius) + : center_(center), radius_(radius), stroke_width_(-1.0f) { + FML_DCHECK(radius >= 0); +} + +CircleGeometry::CircleGeometry(const Point& center, + Scalar radius, + Scalar stroke_width) + : center_(center), + radius_(radius), + stroke_width_(std::max(stroke_width, 0.0f)) { + FML_DCHECK(radius >= 0); + FML_DCHECK(stroke_width >= 0); +} + +GeometryResult CircleGeometry::GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& transform = entity.GetTransform(); + + Scalar half_width = stroke_width_ < 0 ? 0.0 + : LineGeometry::ComputePixelHalfWidth( + transform, stroke_width_); + + std::shared_ptr tessellator = renderer.GetTessellator(); + + // We call the StrokedCircle method which will simplify to a + // FilledCircleGenerator if the inner_radius is <= 0. + auto generator = + tessellator->StrokedCircle(transform, center_, radius_, half_width); + + return ComputePositionGeometry(generator, entity, pass); +} + +// |Geometry| +GeometryResult CircleGeometry::GetPositionUVBuffer( + Rect texture_coverage, + Matrix effect_transform, + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& transform = entity.GetTransform(); + auto uv_transform = + texture_coverage.GetNormalizingTransform() * effect_transform; + + Scalar half_width = stroke_width_ < 0 ? 0.0 + : LineGeometry::ComputePixelHalfWidth( + transform, stroke_width_); + std::shared_ptr tessellator = renderer.GetTessellator(); + + // We call the StrokedCircle method which will simplify to a + // FilledCircleGenerator if the inner_radius is <= 0. + auto generator = + tessellator->StrokedCircle(transform, center_, radius_, half_width); + + return ComputePositionUVGeometry(generator, uv_transform, entity, pass); +} + +GeometryVertexType CircleGeometry::GetVertexType() const { + return GeometryVertexType::kPosition; +} + +std::optional CircleGeometry::GetCoverage(const Matrix& transform) const { + Point corners[4]{ + {center_.x, center_.y - radius_}, + {center_.x + radius_, center_.y}, + {center_.x, center_.y + radius_}, + {center_.x - radius_, center_.y}, + }; + + for (int i = 0; i < 4; i++) { + corners[i] = transform * corners[i]; + } + return Rect::MakePointBounds(std::begin(corners), std::end(corners)); +} + +bool CircleGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + return false; +} + +bool CircleGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/entity/geometry/circle_geometry.h b/engine/src/flutter/impeller/entity/geometry/circle_geometry.h new file mode 100644 index 0000000000..d74c41b99c --- /dev/null +++ b/engine/src/flutter/impeller/entity/geometry/circle_geometry.h @@ -0,0 +1,57 @@ +// 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 "impeller/entity/geometry/geometry.h" + +namespace impeller { + +// Geometry class that can generate vertices (with or without texture +// coordinates) for either filled or stroked circles +class CircleGeometry final : public Geometry { + public: + explicit CircleGeometry(const Point& center, Scalar radius); + + explicit CircleGeometry(const Point& center, + Scalar radius, + Scalar stroke_width); + + ~CircleGeometry() = default; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + GeometryVertexType GetVertexType() const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + // |Geometry| + GeometryResult GetPositionUVBuffer(Rect texture_coverage, + Matrix effect_transform, + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + Point center_; + Scalar radius_; + Scalar stroke_width_; + + CircleGeometry(const CircleGeometry&) = delete; + + CircleGeometry& operator=(const CircleGeometry&) = delete; +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc b/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc index 3d9668ce42..ef4438e6ed 100644 --- a/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc +++ b/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc @@ -7,91 +7,18 @@ #include "flutter/impeller/entity/geometry/ellipse_geometry.h" #include "flutter/impeller/entity/geometry/line_geometry.h" -#include "flutter/impeller/tessellator/circle_tessellator.h" namespace impeller { -EllipseGeometry::EllipseGeometry(Point center, Scalar radius) - : center_(center), radius_(radius), stroke_width_(-1.0) { - FML_DCHECK(radius >= 0); -} - -EllipseGeometry::EllipseGeometry(Point center, - Scalar radius, - Scalar stroke_width) - : center_(center), - radius_(radius), - stroke_width_(std::max(stroke_width, 0.0f)) { - FML_DCHECK(radius >= 0); - FML_DCHECK(stroke_width >= 0); -} +EllipseGeometry::EllipseGeometry(Rect bounds) : bounds_(bounds) {} GeometryResult EllipseGeometry::GetPositionBuffer( const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { - auto& host_buffer = pass.GetTransientsBuffer(); - using VT = SolidFillVertexShader::PerVertexData; - - Scalar half_width = stroke_width_ < 0 - ? 0.0 - : LineGeometry::ComputePixelHalfWidth( - entity.GetTransform(), stroke_width_); - Scalar outer_radius = radius_ + half_width; - Scalar inner_radius = half_width <= 0 ? 0.0 : radius_ - half_width; - - const Point& center = center_; - std::shared_ptr tessellator = renderer.GetTessellator(); - CircleTessellator circle_tessellator(tessellator, entity.GetTransform(), - outer_radius); - - BufferView vertex_buffer; - size_t count; - if (inner_radius > 0) { - count = circle_tessellator.GetStrokedCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &count, ¢er, outer_radius, - inner_radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateStrokedCircleTriangleStrip( - [&vertices](const Point& p) { // - *vertices++ = { - .position = p, - }; - }, - center, outer_radius, inner_radius); - FML_DCHECK(vertices == reinterpret_cast(buffer) + count); - }); - } else { - count = circle_tessellator.GetCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &count, ¢er, outer_radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateCircleTriangleStrip( - [&vertices](const Point& p) { // - *vertices++ = { - .position = p, - }; - }, - center, outer_radius); - FML_DCHECK(vertices == reinterpret_cast(buffer) + count); - }); - } - - return GeometryResult{ - .type = PrimitiveType::kTriangleStrip, - .vertex_buffer = - { - .vertex_buffer = vertex_buffer, - .vertex_count = count, - .index_type = IndexType::kNone, - }, - .transform = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * - entity.GetTransform(), - .prevent_overdraw = false, - }; + return ComputePositionGeometry( + renderer.GetTessellator()->FilledEllipse(entity.GetTransform(), bounds_), + entity, pass); } // |Geometry| @@ -101,73 +28,10 @@ GeometryResult EllipseGeometry::GetPositionUVBuffer( const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { - auto& host_buffer = pass.GetTransientsBuffer(); - using VT = TextureFillVertexShader::PerVertexData; - auto uv_transform = - texture_coverage.GetNormalizingTransform() * effect_transform; - - Scalar half_width = stroke_width_ < 0 - ? 0.0 - : LineGeometry::ComputePixelHalfWidth( - entity.GetTransform(), stroke_width_); - Scalar outer_radius = radius_ + half_width; - Scalar inner_radius = half_width <= 0 ? 0.0 : radius_ - half_width; - - const Point& center = center_; - std::shared_ptr tessellator = renderer.GetTessellator(); - CircleTessellator circle_tessellator(tessellator, entity.GetTransform(), - outer_radius); - - BufferView vertex_buffer; - size_t count; - if (inner_radius > 0) { - count = circle_tessellator.GetStrokedCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &uv_transform, &count, ¢er, outer_radius, - inner_radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateStrokedCircleTriangleStrip( - [&vertices, &uv_transform](const Point& p) { // - *vertices++ = { - .position = p, - .texture_coords = uv_transform * p, - }; - }, - center, outer_radius, inner_radius); - FML_DCHECK(vertices == reinterpret_cast(buffer) + count); - }); - } else { - count = circle_tessellator.GetCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &uv_transform, &count, ¢er, - outer_radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateCircleTriangleStrip( - [&vertices, &uv_transform](const Point& p) { // - *vertices++ = { - .position = p, - .texture_coords = uv_transform * p, - }; - }, - center, outer_radius); - FML_DCHECK(vertices == reinterpret_cast(buffer) + count); - }); - } - - return GeometryResult{ - .type = PrimitiveType::kTriangleStrip, - .vertex_buffer = - { - .vertex_buffer = vertex_buffer, - .vertex_count = count, - .index_type = IndexType::kNone, - }, - .transform = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * - entity.GetTransform(), - .prevent_overdraw = false, - }; + return ComputePositionUVGeometry( + renderer.GetTessellator()->FilledEllipse(entity.GetTransform(), bounds_), + texture_coverage.GetNormalizingTransform() * effect_transform, entity, + pass); } GeometryVertexType EllipseGeometry::GetVertexType() const { @@ -176,17 +40,7 @@ GeometryVertexType EllipseGeometry::GetVertexType() const { std::optional EllipseGeometry::GetCoverage( const Matrix& transform) const { - Point corners[4]{ - {center_.x, center_.y - radius_}, - {center_.x + radius_, center_.y}, - {center_.x, center_.y + radius_}, - {center_.x - radius_, center_.y}, - }; - - for (int i = 0; i < 4; i++) { - corners[i] = transform * corners[i]; - } - return Rect::MakePointBounds(std::begin(corners), std::end(corners)); + return bounds_.TransformBounds(transform); } bool EllipseGeometry::CoversArea(const Matrix& transform, diff --git a/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h b/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h index 58b3e1401d..cd294a67bd 100644 --- a/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h +++ b/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h @@ -8,10 +8,13 @@ namespace impeller { +// Geometry class that can generate vertices (with or without texture +// coordinates) for filled ellipses. Generating vertices for a stroked +// ellipse would require a lot more work since the line width must be +// applied perpendicular to the distorted ellipse shape. class EllipseGeometry final : public Geometry { public: - explicit EllipseGeometry(Point center, Scalar radius); - explicit EllipseGeometry(Point center, Scalar radius, Scalar stroke_width); + explicit EllipseGeometry(Rect bounds); ~EllipseGeometry() = default; @@ -22,24 +25,6 @@ class EllipseGeometry final : public Geometry { bool IsAxisAlignedRect() const override; private: - // Computes the 4 corners of a rectangle that defines the line and - // possibly extended endpoints which will be rendered under the given - // transform, and returns true if such a rectangle is defined. - // - // The coordinates will be generated in the original coordinate system - // of the line end points and the transform will only be used to determine - // the minimum line width. - // - // For kButt and kSquare end caps the ends should always be exteded as - // per that decoration, but for kRound caps the ends might be extended - // if the goal is to get a conservative bounds and might not be extended - // if the calling code is planning to draw the round caps on the ends. - // - // @return true if the transform and width were not degenerate - bool ComputeCorners(Point corners[4], - const Matrix& transform, - bool extend_endpoints) const; - // |Geometry| GeometryResult GetPositionBuffer(const ContentContext& renderer, const Entity& entity, @@ -58,9 +43,7 @@ class EllipseGeometry final : public Geometry { const Entity& entity, RenderPass& pass) const override; - Point center_; - Scalar radius_; - Scalar stroke_width_; + Rect bounds_; EllipseGeometry(const EllipseGeometry&) = delete; diff --git a/engine/src/flutter/impeller/entity/geometry/geometry.cc b/engine/src/flutter/impeller/entity/geometry/geometry.cc index 597445375a..44f3d91ee9 100644 --- a/engine/src/flutter/impeller/entity/geometry/geometry.cc +++ b/engine/src/flutter/impeller/entity/geometry/geometry.cc @@ -7,6 +7,7 @@ #include #include +#include "impeller/entity/geometry/circle_geometry.h" #include "impeller/entity/geometry/cover_geometry.h" #include "impeller/entity/geometry/ellipse_geometry.h" #include "impeller/entity/geometry/fill_path_geometry.h" @@ -18,6 +19,75 @@ namespace impeller { +GeometryResult Geometry::ComputePositionGeometry( + const Tessellator::VertexGenerator& generator, + const Entity& entity, + RenderPass& pass) { + using VT = SolidFillVertexShader::PerVertexData; + + size_t count = generator.GetVertexCount(); + + return GeometryResult{ + .type = generator.GetTriangleType(), + .vertex_buffer = + { + .vertex_buffer = pass.GetTransientsBuffer().Emplace( + count * sizeof(VT), alignof(VT), + [&generator](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + generator.GenerateVertices([&vertices](const Point& p) { + *vertices++ = { + .position = p, + }; + }); + FML_DCHECK(vertices == reinterpret_cast(buffer) + + generator.GetVertexCount()); + }), + .vertex_count = count, + .index_type = IndexType::kNone, + }, + .transform = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + entity.GetTransform(), + .prevent_overdraw = false, + }; +} + +GeometryResult Geometry::ComputePositionUVGeometry( + const Tessellator::VertexGenerator& generator, + const Matrix& uv_transform, + const Entity& entity, + RenderPass& pass) { + using VT = TextureFillVertexShader::PerVertexData; + + size_t count = generator.GetVertexCount(); + + return GeometryResult{ + .type = generator.GetTriangleType(), + .vertex_buffer = + { + .vertex_buffer = pass.GetTransientsBuffer().Emplace( + count * sizeof(VT), alignof(VT), + [&generator, &uv_transform](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + generator.GenerateVertices( + [&vertices, &uv_transform](const Point& p) { // + *vertices++ = { + .position = p, + .texture_coords = uv_transform * p, + }; + }); + FML_DCHECK(vertices == reinterpret_cast(buffer) + + generator.GetVertexCount()); + }), + .vertex_count = count, + .index_type = IndexType::kNone, + }, + .transform = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + entity.GetTransform(), + .prevent_overdraw = false, + }; +} + VertexBufferBuilder ComputeUVGeometryCPU( VertexBufferBuilder& input, @@ -108,25 +178,30 @@ std::shared_ptr Geometry::MakeCover() { return std::make_shared(); } -std::shared_ptr Geometry::MakeRect(Rect rect) { +std::shared_ptr Geometry::MakeRect(const Rect& rect) { return std::make_shared(rect); } -std::shared_ptr Geometry::MakeLine(Point p0, - Point p1, +std::shared_ptr Geometry::MakeOval(const Rect& rect) { + return std::make_shared(rect); +} + +std::shared_ptr Geometry::MakeLine(const Point& p0, + const Point& p1, Scalar width, Cap cap) { return std::make_shared(p0, p1, width, cap); } -std::shared_ptr Geometry::MakeCircle(Point center, Scalar radius) { - return std::make_shared(center, radius); +std::shared_ptr Geometry::MakeCircle(const Point& center, + Scalar radius) { + return std::make_shared(center, radius); } -std::shared_ptr Geometry::MakeStrokedCircle(Point center, +std::shared_ptr Geometry::MakeStrokedCircle(const Point& center, Scalar radius, Scalar stroke_width) { - return std::make_shared(center, radius, stroke_width); + return std::make_shared(center, radius, stroke_width); } bool Geometry::CoversArea(const Matrix& transform, const Rect& rect) const { diff --git a/engine/src/flutter/impeller/entity/geometry/geometry.h b/engine/src/flutter/impeller/entity/geometry/geometry.h index de2f0e40c3..353bd2b5e7 100644 --- a/engine/src/flutter/impeller/entity/geometry/geometry.h +++ b/engine/src/flutter/impeller/entity/geometry/geometry.h @@ -23,6 +23,13 @@ struct GeometryResult { bool prevent_overdraw; }; +static const GeometryResult kEmptyResult = { + .vertex_buffer = + { + .index_type = IndexType::kNone, + }, +}; + enum GeometryVertexType { kPosition, kColor, @@ -62,16 +69,19 @@ class Geometry { static std::shared_ptr MakeCover(); - static std::shared_ptr MakeRect(Rect rect); + static std::shared_ptr MakeRect(const Rect& rect); - static std::shared_ptr MakeLine(Point p0, - Point p1, + static std::shared_ptr MakeOval(const Rect& rect); + + static std::shared_ptr MakeLine(const Point& p0, + const Point& p1, Scalar width, Cap cap); - static std::shared_ptr MakeCircle(Point center, Scalar radius); + static std::shared_ptr MakeCircle(const Point& center, + Scalar radius); - static std::shared_ptr MakeStrokedCircle(Point center, + static std::shared_ptr MakeStrokedCircle(const Point& center, Scalar radius, Scalar stroke_width); @@ -106,6 +116,18 @@ class Geometry { virtual bool CoversArea(const Matrix& transform, const Rect& rect) const; virtual bool IsAxisAlignedRect() const; + + protected: + static GeometryResult ComputePositionGeometry( + const Tessellator::VertexGenerator& generator, + const Entity& entity, + RenderPass& pass); + + static GeometryResult ComputePositionUVGeometry( + const Tessellator::VertexGenerator& generator, + const Matrix& uv_transform, + const Entity& entity, + RenderPass& pass); }; } // namespace impeller diff --git a/engine/src/flutter/impeller/entity/geometry/line_geometry.cc b/engine/src/flutter/impeller/entity/geometry/line_geometry.cc index 83c48af4ee..d2a9bd5d49 100644 --- a/engine/src/flutter/impeller/entity/geometry/line_geometry.cc +++ b/engine/src/flutter/impeller/entity/geometry/line_geometry.cc @@ -4,8 +4,6 @@ #include "impeller/entity/geometry/line_geometry.h" -#include "flutter/impeller/tessellator/circle_tessellator.h" - namespace impeller { LineGeometry::LineGeometry(Point p0, Point p1, Scalar width, Cap cap) @@ -69,52 +67,35 @@ bool LineGeometry::ComputeCorners(Point corners[4], GeometryResult LineGeometry::GetPositionBuffer(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { - auto& host_buffer = pass.GetTransientsBuffer(); using VT = SolidFillVertexShader::PerVertexData; auto& transform = entity.GetTransform(); auto radius = ComputePixelHalfWidth(transform, width_); - size_t count; - BufferView vertex_buffer; if (cap_ == Cap::kRound) { - const Point& p0 = p0_; - const Point& p1 = p1_; - std::shared_ptr tessellator = renderer.GetTessellator(); - CircleTessellator circle_tessellator(tessellator, entity.GetTransform(), - radius); - count = circle_tessellator.GetCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &p0, &p1, radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateRoundCapLineTriangleStrip( - [&vertices](const Point& p) { // - *vertices++ = { - .position = p, - }; - }, - p0, p1, radius); - }); - } else { - Point corners[4]; - if (ComputeCorners(corners, transform, cap_ == Cap::kSquare)) { - count = 4; - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), [&corners](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - for (auto& corner : corners) { - *vertices++ = { - .position = corner, - }; - } - }); - } else { - return {}; - } + auto generator = tessellator->RoundCapLine(transform, p0_, p1_, radius); + return ComputePositionGeometry(generator, entity, pass); } + Point corners[4]; + if (!ComputeCorners(corners, transform, cap_ == Cap::kSquare)) { + return kEmptyResult; + } + + auto& host_buffer = pass.GetTransientsBuffer(); + + size_t count = 4; + BufferView vertex_buffer = host_buffer.Emplace( + count * sizeof(VT), alignof(VT), [&corners](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + for (auto& corner : corners) { + *vertices++ = { + .position = corner, + }; + } + }); + return GeometryResult{ .type = PrimitiveType::kTriangleStrip, .vertex_buffer = @@ -144,50 +125,30 @@ GeometryResult LineGeometry::GetPositionUVBuffer(Rect texture_coverage, auto uv_transform = texture_coverage.GetNormalizingTransform() * effect_transform; - size_t count; - BufferView vertex_buffer; if (cap_ == Cap::kRound) { - const Point& p0 = p0_; - const Point& p1 = p1_; - std::shared_ptr tessellator = renderer.GetTessellator(); - CircleTessellator circle_tessellator(tessellator, entity.GetTransform(), - radius); - count = circle_tessellator.GetCircleVertexCount(); - vertex_buffer = host_buffer.Emplace( - count * sizeof(VT), alignof(VT), - [&circle_tessellator, &uv_transform, &p0, &p1, - radius](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - circle_tessellator.GenerateRoundCapLineTriangleStrip( - [&vertices, &uv_transform](const Point& p) { // - *vertices++ = { - .position = p, - .texture_coords = uv_transform * p, - }; - }, - p0, p1, radius); - }); - } else { - Point corners[4]; - if (ComputeCorners(corners, transform, cap_ == Cap::kSquare)) { - count = 4; - vertex_buffer = - host_buffer.Emplace(count * sizeof(VT), alignof(VT), - [&uv_transform, &corners](uint8_t* buffer) { - auto vertices = reinterpret_cast(buffer); - for (auto& corner : corners) { - *vertices++ = { - .position = corner, - .texture_coords = uv_transform * corner, - }; - } - }); - } else { - return {}; - } + auto generator = tessellator->RoundCapLine(transform, p0_, p1_, radius); + return ComputePositionUVGeometry(generator, uv_transform, entity, pass); } + Point corners[4]; + if (!ComputeCorners(corners, transform, cap_ == Cap::kSquare)) { + return kEmptyResult; + } + + size_t count = 4; + BufferView vertex_buffer = + host_buffer.Emplace(count * sizeof(VT), alignof(VT), + [&uv_transform, &corners](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + for (auto& corner : corners) { + *vertices++ = { + .position = corner, + .texture_coords = uv_transform * corner, + }; + } + }); + return GeometryResult{ .type = PrimitiveType::kTriangleStrip, .vertex_buffer = diff --git a/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc b/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc index ebbf78af8f..6eb9477faf 100644 --- a/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc +++ b/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc @@ -4,7 +4,6 @@ #include "impeller/entity/geometry/point_field_geometry.h" -#include "flutter/impeller/tessellator/circle_tessellator.h" #include "impeller/renderer/command_buffer.h" #include "impeller/renderer/compute_command.h" @@ -72,7 +71,8 @@ PointFieldGeometry::GetPositionBufferCPU(const ContentContext& renderer, if (radius_ < 0.0) { return std::nullopt; } - auto determinant = entity.GetTransform().GetDeterminant(); + auto transform = entity.GetTransform(); + auto determinant = transform.GetDeterminant(); if (determinant == 0) { return std::nullopt; } @@ -83,21 +83,17 @@ PointFieldGeometry::GetPositionBufferCPU(const ContentContext& renderer, VertexBufferBuilder vtx_builder; if (round_) { - std::shared_ptr tessellator = renderer.GetTessellator(); - CircleTessellator circle_tessellator(tessellator, entity.GetTransform(), - radius_); - // Get triangulation relative to {0, 0} so we can translate it to each // point in turn. + auto generator = + renderer.GetTessellator()->FilledCircle(transform, {}, radius); + FML_DCHECK(generator.GetTriangleType() == PrimitiveType::kTriangleStrip); std::vector circle_vertices; - circle_vertices.reserve(circle_tessellator.GetCircleVertexCount()); - circle_tessellator.GenerateCircleTriangleStrip( - [&circle_vertices](const Point& p) { // - circle_vertices.push_back(p); - }, - {}, radius); - FML_DCHECK(circle_vertices.size() == - circle_tessellator.GetCircleVertexCount()); + circle_vertices.reserve(generator.GetVertexCount()); + generator.GenerateVertices([&circle_vertices](const Point& p) { // + circle_vertices.push_back(p); + }); + FML_DCHECK(circle_vertices.size() == generator.GetVertexCount()); vtx_builder.Reserve((circle_vertices.size() + 2) * points_.size() - 2); for (auto& center : points_) { diff --git a/engine/src/flutter/impeller/geometry/rect.h b/engine/src/flutter/impeller/geometry/rect.h index bcb22edbcd..8d0fc5da49 100644 --- a/engine/src/flutter/impeller/geometry/rect.h +++ b/engine/src/flutter/impeller/geometry/rect.h @@ -132,6 +132,9 @@ struct TRect { /// Returns true if either of the width or height are 0, negative, or NaN. constexpr bool IsEmpty() const { return size.IsEmpty(); } + /// Returns true if width and height are equal and neither is NaN. + constexpr bool IsSquare() const { return size.IsSquare(); } + constexpr bool IsMaximum() const { return *this == MakeMaximum(); } /// @brief Returns the upper left corner of the rectangle as specified @@ -186,6 +189,11 @@ struct TRect { return {GetRight(), GetBottom()}; } + /// @brief Get the center point as a |Point|. + constexpr Point GetCenter() const { + return Point(origin.x + size.width * 0.5f, origin.y + size.height * 0.5f); + } + constexpr std::array GetLTRB() const { return {GetLeft(), GetTop(), GetRight(), GetBottom()}; } diff --git a/engine/src/flutter/impeller/geometry/rect_unittests.cc b/engine/src/flutter/impeller/geometry/rect_unittests.cc index 3cdc4fb4a0..dcac4d8734 100644 --- a/engine/src/flutter/impeller/geometry/rect_unittests.cc +++ b/engine/src/flutter/impeller/geometry/rect_unittests.cc @@ -248,5 +248,24 @@ TEST(RectTest, MakePointBoundsQuad) { } } +TEST(RectTest, IsSquare) { + EXPECT_TRUE(Rect::MakeXYWH(10, 30, 20, 20).IsSquare()); + EXPECT_FALSE(Rect::MakeXYWH(10, 30, 20, 19).IsSquare()); + EXPECT_FALSE(Rect::MakeXYWH(10, 30, 19, 20).IsSquare()); + + EXPECT_TRUE(IRect::MakeXYWH(10, 30, 20, 20).IsSquare()); + EXPECT_FALSE(IRect::MakeXYWH(10, 30, 20, 19).IsSquare()); + EXPECT_FALSE(IRect::MakeXYWH(10, 30, 19, 20).IsSquare()); +} + +TEST(RectTest, GetCenter) { + EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); + EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); + + // Note that we expect a Point as the answer from an IRect + EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); + EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); +} + } // namespace testing } // namespace impeller diff --git a/engine/src/flutter/impeller/geometry/size.h b/engine/src/flutter/impeller/geometry/size.h index 7ee34d1218..d8f26994cc 100644 --- a/engine/src/flutter/impeller/geometry/size.h +++ b/engine/src/flutter/impeller/geometry/size.h @@ -82,6 +82,8 @@ struct TSize { }; } + constexpr Type MaxDimension() const { return std::max(width, height); } + constexpr TSize Abs() const { return {std::fabs(width), std::fabs(height)}; } constexpr TSize Floor() const { @@ -99,6 +101,8 @@ struct TSize { /// Returns true if either of the width or height are 0, negative, or NaN. constexpr bool IsEmpty() const { return !(width > 0 && height > 0); } + constexpr bool IsSquare() const { return width == height; } + template static constexpr TSize Ceil(const TSize& other) { return TSize{static_cast(std::ceil(other.width)), diff --git a/engine/src/flutter/impeller/geometry/size_unittests.cc b/engine/src/flutter/impeller/geometry/size_unittests.cc index df8d26bfd2..e0857f0190 100644 --- a/engine/src/flutter/impeller/geometry/size_unittests.cc +++ b/engine/src/flutter/impeller/geometry/size_unittests.cc @@ -50,5 +50,29 @@ TEST(SizeTest, ISizeIsEmpty) { EXPECT_TRUE(ISize(-1, 7).IsEmpty()); } +TEST(SizeTest, IsSquare) { + EXPECT_TRUE(Size(20, 20).IsSquare()); + EXPECT_FALSE(Size(20, 19).IsSquare()); + EXPECT_FALSE(Size(19, 20).IsSquare()); + + EXPECT_TRUE(ISize(20, 20).IsSquare()); + EXPECT_FALSE(ISize(20, 19).IsSquare()); + EXPECT_FALSE(ISize(19, 20).IsSquare()); +} + +TEST(SizeTest, MaxDimension) { + EXPECT_EQ(Size(20, 20).MaxDimension(), 20); + EXPECT_EQ(Size(20, 19).MaxDimension(), 20); + EXPECT_EQ(Size(19, 20).MaxDimension(), 20); + EXPECT_EQ(Size(20, 21).MaxDimension(), 21); + EXPECT_EQ(Size(21, 20).MaxDimension(), 21); + + EXPECT_EQ(ISize(20, 20).MaxDimension(), 20); + EXPECT_EQ(ISize(20, 19).MaxDimension(), 20); + EXPECT_EQ(ISize(19, 20).MaxDimension(), 20); + EXPECT_EQ(ISize(20, 21).MaxDimension(), 21); + EXPECT_EQ(ISize(21, 20).MaxDimension(), 21); +} + } // namespace testing } // namespace impeller diff --git a/engine/src/flutter/impeller/geometry/trig.h b/engine/src/flutter/impeller/geometry/trig.h index eddf6552f5..332c8ee1dd 100644 --- a/engine/src/flutter/impeller/geometry/trig.h +++ b/engine/src/flutter/impeller/geometry/trig.h @@ -23,10 +23,17 @@ struct Trig { double cos; double sin; + /// @brief Returns the corresponding point on a circle of a given |radius|. Vector2 operator*(double radius) const { return Vector2(static_cast(cos * radius), static_cast(sin * radius)); } + + /// @brief Returns the corresponding point on an ellipse with the given size. + Vector2 operator*(const Size& ellipse_radii) const { + return Vector2(static_cast(cos * ellipse_radii.width), + static_cast(sin * ellipse_radii.height)); + } }; } // namespace impeller diff --git a/engine/src/flutter/impeller/geometry/trig_unittests.cc b/engine/src/flutter/impeller/geometry/trig_unittests.cc index dcdc6b6da2..ff15c974b5 100644 --- a/engine/src/flutter/impeller/geometry/trig_unittests.cc +++ b/engine/src/flutter/impeller/geometry/trig_unittests.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include + #include "fml/logging.h" #include "gtest/gtest.h" @@ -60,5 +62,17 @@ TEST(TrigTest, TrigAngles) { } } +TEST(TrigTest, MultiplyByScalarRadius) { + for (int i = 0; i <= 360; i++) { + for (int i = 1; i <= 10; i++) { + Scalar radius = i * 5.0f; + EXPECT_EQ(Trig(Degrees(i)) * radius, + Point(radius * std::cos(i * kPi / 180), + radius * std::sin(i * kPi / 180))) + << "at " << i << " degrees and radius " << radius; + } + } +} + } // namespace testing } // namespace impeller diff --git a/engine/src/flutter/impeller/tessellator/BUILD.gn b/engine/src/flutter/impeller/tessellator/BUILD.gn index d49c245949..bc56fb770f 100644 --- a/engine/src/flutter/impeller/tessellator/BUILD.gn +++ b/engine/src/flutter/impeller/tessellator/BUILD.gn @@ -6,8 +6,6 @@ import("//flutter/impeller/tools/impeller.gni") impeller_component("tessellator") { sources = [ - "circle_tessellator.cc", - "circle_tessellator.h", "tessellator.cc", "tessellator.h", ] @@ -15,6 +13,7 @@ impeller_component("tessellator") { public_deps = [ "../geometry" ] deps = [ + "../core", "//flutter/fml", "//third_party/libtess2", ] @@ -31,13 +30,12 @@ impeller_component("tessellator_shared") { sources = [ "c/tessellator.cc", "c/tessellator.h", - "circle_tessellator.cc", - "circle_tessellator.h", "tessellator.cc", "tessellator.h", ] deps = [ + "../core", "../geometry", "//flutter/fml", "//third_party/libtess2", @@ -50,10 +48,7 @@ impeller_component("tessellator_shared") { impeller_component("tessellator_unittests") { testonly = true - sources = [ - "circle_tessellator_unittests.cc", - "tessellator_unittests.cc", - ] + sources = [ "tessellator_unittests.cc" ] deps = [ ":tessellator", "../geometry:geometry_asserts", diff --git a/engine/src/flutter/impeller/tessellator/circle_tessellator.cc b/engine/src/flutter/impeller/tessellator/circle_tessellator.cc deleted file mode 100644 index 35932fc1df..0000000000 --- a/engine/src/flutter/impeller/tessellator/circle_tessellator.cc +++ /dev/null @@ -1,261 +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/tessellator/circle_tessellator.h" - -#include "flutter/fml/logging.h" - -namespace impeller { - -int CircleTessellator::kPrecomputedDivisions[kPrecomputedDivisionCount] = { - // clang-format off - 1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, - 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, - 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, - 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, - 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, - 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, - 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, - 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, - 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, - 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, - 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, - 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, - 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, - 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, - 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, - 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, - 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, - 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, - 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, - 41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, - 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, - 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, - 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, - 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, - 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, - 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, - 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 47, - 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, - 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 48, 48, 48, - 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, - 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, - 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, - 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, - 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, - 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, - 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, - 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, - 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, - 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, - 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, - 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, - 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, - 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, - 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, - 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, - 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, - 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, - 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, - // clang-format on -}; - -size_t CircleTessellator::ComputeQuadrantDivisions(Scalar pixel_radius) { - if (pixel_radius <= 0.0) { - return 1; - } - int radius_index = ceil(pixel_radius); - if (radius_index < kPrecomputedDivisionCount) { - return kPrecomputedDivisions[radius_index]; - } - - // For a circle with N divisions per quadrant, the maximum deviation of - // the polgyon approximation from the true circle will be at the center - // of the base of each triangular pie slice. We can compute that distance - // by finding the midpoint of the line of the first slice and compare - // its distance from the center of the circle to the radius. We will aim - // to have the length of that bisector to be within |kCircleTolerance| - // from the radius in pixels. - // - // Each vertex will appear at an angle of: - // theta(i) = (kPi / 2) * (i / N) // for i in [0..N] - // with each point falling at: - // point(i) = r * (cos(theta), sin(theta)) - // If we consider the unit circle to simplify the calculations below then - // we need to scale the tolerance from its absolute quantity into a unit - // circle fraction: - // k = tolerance / radius - // Using this scaled tolerance below to avoid multiplying by the radius - // throughout all of the math, we have: - // first point = (1, 0) // theta(0) == 0 - // theta = kPi / 2 / N // theta(1) - // second point = (cos(theta), sin(theta)) = (c, s) - // midpoint = (first + second) * 0.5 = ((1 + c)/2, s/2) - // |midpoint| = sqrt((1 + c)*(1 + c)/4 + s*s/4) - // = sqrt((1 + c + c + c*c + s*s) / 4) - // = sqrt((1 + 2c + 1) / 4) - // = sqrt((2 + 2c) / 4) - // = sqrt((1 + c) / 2) - // = cos(theta / 2) // using half-angle cosine formula - // error = 1 - |midpoint| = 1 - cos(theta / 2) - // cos(theta/2) = 1 - error - // theta/2 = acos(1 - error) - // kPi / 2 / N / 2 = acos(1 - error) - // kPi / 4 / acos(1 - error) = N - // Since we need error <= k, we want divisions >= N, so we use: - // N = ceil(kPi / 4 / acos(1 - k)) - // - // Math is confirmed in https://math.stackexchange.com/a/4132095 - // (keeping in mind that we are computing quarter circle divisions here) - // which also points out a performance optimization that is accurate - // to within an over-estimation of 1 division would be: - // N = ceil(kPi / 4 / sqrt(2 * k)) - // Since we have precomputed the divisions for radii up to 1024, we can - // afford to be more accurate using the acos formula here for larger radii. - double k = kCircleTolerance / pixel_radius; - return ceil(kPiOver4 / std::acos(1 - k)); -} - -const std::vector& CircleTessellator::GetTrigsForDivisions( - std::shared_ptr& tessellator, - size_t divisions) { - std::vector& trigs = (divisions < Tessellator::kCachedTrigCount) - ? tessellator->precomputed_trigs_[divisions] - : temp_trigs_; - - if (trigs.empty()) { - // Either not cached yet, or we are usig the temp vector... - trigs.reserve(divisions + 1); - - double angle_scale = kPiOver2 / divisions; - - trigs.emplace_back(1.0, 0.0); - for (size_t i = 1; i < divisions; i++) { - trigs.emplace_back(Radians(i * angle_scale)); - } - trigs.emplace_back(0.0, 1.0); - - FML_DCHECK(trigs.size() == divisions + 1); - } - - return trigs; -} - -void CircleTessellator::GenerateCircleTriangleStrip( - const TessellatedPointProc& proc, - const Point& center, - Scalar radius) const { - // Quadrant 1 connecting with Quadrant 4: - for (auto& trig : trigs_) { - auto offset = trig * radius; - proc({center.x - offset.x, center.y + offset.y}); - proc({center.x - offset.x, center.y - offset.y}); - } - - // The second half of the circle should be iterated in reverse, but - // we can instead iterate forward and swap the x/y values of the - // offset as the angles should be symmetric and thus should generate - // symmetrically reversed trig vectors. - // Quadrant 2 connecting with Quadrant 2: - for (auto& trig : trigs_) { - auto offset = trig * radius; - proc({center.x + offset.y, center.y + offset.x}); - proc({center.x + offset.y, center.y - offset.x}); - } -} - -void CircleTessellator::GenerateStrokedCircleTriangleStrip( - const TessellatedPointProc& proc, - const Point& center, - Scalar outer_radius, - Scalar inner_radius) const { - // Zig-zag back and forth between points on the outer circle and the - // inner circle. Both circles are evaluated at the same number of - // quadrant divisions so the points for a given division should match - // 1 for 1 other than their applied radius. - - // Quadrant 1: - for (auto& trig : trigs_) { - auto outer = trig * outer_radius; - auto inner = trig * inner_radius; - proc({center.x - outer.x, center.y - outer.y}); - proc({center.x - inner.x, center.y - inner.y}); - } - - // The even quadrants of the circle should be iterated in reverse, but - // we can instead iterate forward and swap the x/y values of the - // offset as the angles should be symmetric and thus should generate - // symmetrically reversed trig vectors. - // Quadrant 2: - for (auto& trig : trigs_) { - auto outer = trig * outer_radius; - auto inner = trig * inner_radius; - proc({center.x + outer.y, center.y - outer.x}); - proc({center.x + inner.y, center.y - inner.x}); - } - - // Quadrant 3: - for (auto& trig : trigs_) { - auto outer = trig * outer_radius; - auto inner = trig * inner_radius; - proc({center.x + outer.x, center.y + outer.y}); - proc({center.x + inner.x, center.y + inner.y}); - } - - // Quadrant 4: - for (auto& trig : trigs_) { - auto outer = trig * outer_radius; - auto inner = trig * inner_radius; - proc({center.x - outer.y, center.y + outer.x}); - proc({center.x - inner.y, center.y + inner.x}); - } -} - -void CircleTessellator::GenerateRoundCapLineTriangleStrip( - const TessellatedPointProc& proc, - const Point& p0, - const Point& p1, - Scalar radius) const { - auto along = p1 - p0; - auto length = along.GetLength(); - if (length < kEhCloseEnough) { - return GenerateCircleTriangleStrip(proc, p0, radius); - } - along *= radius / length; - auto across = Point(-along.y, along.x); - - for (auto& trig : trigs_) { - auto relative_across = across * trig.cos; - auto relative_along = along * trig.sin; - proc({p0 + relative_across - relative_along}); - proc({p1 + relative_across + relative_along}); - } - // The second half of the round caps should be iterated in reverse, but - // we can instead iterate forward and swap the sin/cos values as they - // should be symmetric. - for (auto& trig : trigs_) { - auto relative_across = across * trig.sin; - auto relative_along = along * trig.cos; - proc({p0 - relative_across - relative_along}); - proc({p1 - relative_across + relative_along}); - } -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/tessellator/circle_tessellator.h b/engine/src/flutter/impeller/tessellator/circle_tessellator.h deleted file mode 100644 index d2dc15d6f9..0000000000 --- a/engine/src/flutter/impeller/tessellator/circle_tessellator.h +++ /dev/null @@ -1,154 +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. - -#pragma once - -#include -#include - -#include "flutter/impeller/geometry/matrix.h" -#include "flutter/impeller/geometry/point.h" -#include "flutter/impeller/geometry/scalar.h" -#include "flutter/impeller/geometry/trig.h" -#include "flutter/impeller/tessellator/tessellator.h" - -namespace impeller { - -using TessellatedPointProc = std::function; - -/// @brief A utility class to compute the number of divisions for a circle -/// given a transform-adjusted pixel radius and methods for generating -/// a tessellated set of triangles for a quarter or full circle. -/// -/// The constructor will compute the device pixel radius size for -/// the specified geometry-space |radius| when viewed under -/// a specified geometry-to-device |transform|. -/// -/// The object should be constructed with the expected transform and -/// radius of the circle, but can then be used to generate a triangular -/// tessellation with the computed number of divisions for any -/// radius after that. Since the coordinate space in which the -/// circle being tessellated is not necessarily device pixel space, -/// the radius supplied during tessellation might not match the -/// pixel radius computed during construction, but the two values -/// should be related by the transform in place when the tessellated -/// triangles are rendered for maximum tessellation fidelity. -class CircleTessellator { - public: - /// @brief The pixel tolerance used by the algorighm to determine how - /// many divisions to create for a circle. - /// - /// No point on the polygon of vertices should deviate from the - /// true circle by more than this tolerance. - static constexpr Scalar kCircleTolerance = 0.1; - - /// @brief Constructs a CircleTessellator that produces enough segments - /// to reasonably approximate a circle with a specified |radius| - /// when viewed under the specified |transform|. - CircleTessellator(std::shared_ptr& tessellator, - const Matrix& transform, - Scalar radius) - : CircleTessellator(tessellator, transform.GetMaxBasisLength() * radius) { - } - - ~CircleTessellator() = default; - - /// @brief Return the number of divisions computed by the algorithm for - /// a single quarter circle. - size_t GetQuadrantDivisionCount() const { return trigs_.size() - 1; } - - /// @brief Return the number of vertices that will be generated to - /// tessellate a full circle with a triangle strip. - /// - /// This value can be used to pre-allocate space in a vector - /// to hold the vertices that will be produced by the - /// |GenerateCircleTriangleStrip| and - /// |GenerateRoundCapLineTriangleStrip| methods. - size_t GetCircleVertexCount() const { return trigs_.size() * 4; } - - /// @brief Return the number of vertices that will be generated to - /// tessellate a full stroked circle with a triangle strip. - /// - /// This value can be used to pre-allocate space in a vector - /// to hold the vertices that will be produced by the - /// |GenerateCircleTriangleStrip| and - /// |GenerateRoundCapLineTriangleStrip| methods. - size_t GetStrokedCircleVertexCount() const { return trigs_.size() * 8; } - - /// @brief Generate the vertices for a triangle strip that covers the - /// circle at a given |radius| from a given |center|, delivering - /// the computed coordinates to the supplied |proc|. - /// - /// This procedure will generate no more than the number of - /// vertices returned by |GetCircleVertexCount| in an order - /// appropriate for rendering as a triangle strip. - void GenerateCircleTriangleStrip(const TessellatedPointProc& proc, - const Point& center, - Scalar radius) const; - - /// @brief Generate the vertices for a triangle strip that draws the gap - /// between 2 circles at |outer_radius| and |inner_radius| - /// from a given |center|, delivering the computed coordinates to - /// the supplied |proc|. - /// - /// This procedure will generate no more than the number of - /// vertices returned by |GetStrokedCircleVertexCount| in an order - /// appropriate for rendering as a triangle strip. - void GenerateStrokedCircleTriangleStrip(const TessellatedPointProc& proc, - const Point& center, - Scalar outer_radius, - Scalar inner_radius) const; - - /// @brief Generate the vertices for a triangle strip that covers the - /// line from |p0| to |p1| with round caps of the specified - /// |radius|, delivering the computed coordinates to the supplied - /// |proc|. - /// - /// This procedure will generate no more than the number of - /// vertices returned by |GetCircleVertexCount| in an order - /// appropriate for rendering as a triangle strip. - void GenerateRoundCapLineTriangleStrip(const TessellatedPointProc& proc, - const Point& p0, - const Point& p1, - Scalar radius) const; - - private: - const std::vector& trigs_; - std::vector temp_trigs_; - - /// @brief Constructs a CircleTessellator that produces enough segments - /// to reasonably approximate a circle with a specified radius - /// in pixels. - explicit CircleTessellator(std::shared_ptr& tessellator, - Scalar pixel_radius) - : trigs_(GetTrigsForDivisions(tessellator, - ComputeQuadrantDivisions(pixel_radius))) {} - - CircleTessellator(const CircleTessellator&) = delete; - - CircleTessellator& operator=(const CircleTessellator&) = delete; - - /// @brief Compute the number of vertices to divide each quadrant of - /// the circle into based on the expected pixel space radius. - /// - /// @return the number of vertices. - static size_t ComputeQuadrantDivisions(Scalar pixel_radius); - - /// @brief Compute the sine and cosine for each angle in the number of - /// divisions [0, divisions] of a quarter circle and return the - /// values in a vector of trig objects. - /// - /// Note that since the 0th division is included, the vector will - /// contain (divisions + 1) values. - /// - /// @return The vector of (divisions + 1) trig values. - const std::vector& GetTrigsForDivisions( - std::shared_ptr& tessellator, - size_t divisions); - - static constexpr int kPrecomputedDivisionCount = 1024; - static int kPrecomputedDivisions[kPrecomputedDivisionCount]; -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/tessellator/circle_tessellator_unittests.cc b/engine/src/flutter/impeller/tessellator/circle_tessellator_unittests.cc deleted file mode 100644 index 2a5d858435..0000000000 --- a/engine/src/flutter/impeller/tessellator/circle_tessellator_unittests.cc +++ /dev/null @@ -1,170 +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 "fml/logging.h" -#include "gtest/gtest.h" - -#include "flutter/impeller/geometry/geometry_asserts.h" -#include "flutter/impeller/tessellator/circle_tessellator.h" - -namespace impeller { -namespace testing { - -TEST(CircleTessellator, DivisionAndVertexCounts) { - auto tessellator = std::make_shared(); - - auto test = [&tessellator](const Matrix& transform, Scalar radius) { - CircleTessellator circle_tessellator(tessellator, transform, radius); - size_t quadrant_divisions = circle_tessellator.GetQuadrantDivisionCount(); - - EXPECT_EQ(circle_tessellator.GetCircleVertexCount(), - (quadrant_divisions + 1) * 4) - << "transform = " << transform << ", radius = " << radius; - - EXPECT_EQ(circle_tessellator.GetStrokedCircleVertexCount(), - (quadrant_divisions + 1) * 8) - << "transform = " << transform << ", radius = " << radius; - - // Confirm the approximation error is within the currently accepted - // |kCircleTolerance| value advertised by |CircleTessellator|. - // (With an additional 1% tolerance for floating point rounding.) - double angle = kPiOver2 / quadrant_divisions; - Point first = {radius, 0}; - Point next = {static_cast(cos(angle) * radius), - static_cast(sin(angle) * radius)}; - Point midpoint = (first + next) * 0.5; - EXPECT_GE(midpoint.GetLength(), - radius - CircleTessellator::kCircleTolerance * 1.01) - << ", transform = " << transform << ", radius = " << radius - << ", divisions = " << quadrant_divisions; - }; - - test({}, 0.0); - test({}, 0.9); - test({}, 1.0); - test({}, 1.9); - test(Matrix::MakeScale(Vector2(2.0, 2.0)), 0.95); - test({}, 2.0); - test(Matrix::MakeScale(Vector2(2.0, 2.0)), 1.0); - test({}, 11.9); - test({}, 12.0); - test({}, 35.9); - for (int i = 36; i < 10000; i += 4) { - test({}, i); - } -} - -TEST(CircleTessellator, FilledCircleTessellationVertices) { - auto tessellator = std::make_shared(); - - auto test = [&tessellator](Scalar pixel_radius, Point center, Scalar radius) { - CircleTessellator circle_tessellator(tessellator, {}, pixel_radius); - - auto vertex_count = circle_tessellator.GetCircleVertexCount(); - auto vertices = std::vector(); - circle_tessellator.GenerateCircleTriangleStrip( - [&vertices](const Point& p) { // - vertices.push_back(p); - }, - center, radius); - EXPECT_EQ(vertices.size(), vertex_count); - ASSERT_EQ(vertex_count % 4, 0u); - - auto quadrant_count = vertex_count / 4; - for (size_t i = 0; i < quadrant_count; i++) { - double angle = kPiOver2 * i / (quadrant_count - 1); - double degrees = angle * 180.0 / kPi; - double rsin = sin(angle) * radius; - double rcos = cos(angle) * radius; - EXPECT_POINT_NEAR(vertices[i * 2], - Point(center.x - rcos, center.y + rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[i * 2 + 1], - Point(center.x - rcos, center.y - rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], - Point(center.x + rcos, center.y - rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], - Point(center.x + rcos, center.y + rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - } - }; - - test(2.0, {}, 2.0); - test(2.0, {10, 10}, 2.0); - test(1000.0, {}, 2.0); - test(2.0, {}, 1000.0); -} - -TEST(CircleTessellator, StrokedCircleTessellationVertices) { - auto tessellator = std::make_shared(); - - auto test = [&tessellator](Scalar pixel_radius, Point center, Scalar radius, - Scalar width) { - ASSERT_GT(radius, width); - CircleTessellator circle_tessellator(tessellator, {}, pixel_radius); - - auto vertex_count = circle_tessellator.GetStrokedCircleVertexCount(); - auto vertices = std::vector(); - circle_tessellator.GenerateStrokedCircleTriangleStrip( - [&vertices](const Point& p) { // - vertices.push_back(p); - }, - center, radius + width, radius - width); - EXPECT_EQ(vertices.size(), vertex_count); - ASSERT_EQ(vertex_count % 4, 0u); - - auto quadrant_count = vertex_count / 8; - - // Test outer points first - for (size_t i = 0; i < quadrant_count; i++) { - double angle = kPiOver2 * i / (quadrant_count - 1); - double degrees = angle * 180.0 / kPi; - double rsin = sin(angle) * (radius + width); - double rcos = cos(angle) * (radius + width); - EXPECT_POINT_NEAR(vertices[i * 2], - Point(center.x - rcos, center.y - rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2], - Point(center.x + rsin, center.y - rcos)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2], - Point(center.x + rcos, center.y + rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2], - Point(center.x - rsin, center.y + rcos)) - << "vertex " << i << ", angle = " << degrees << std::endl; - } - - // Then test innerer points - for (size_t i = 0; i < quadrant_count; i++) { - double angle = kPiOver2 * i / (quadrant_count - 1); - double degrees = angle * 180.0 / kPi; - double rsin = sin(angle) * (radius - width); - double rcos = cos(angle) * (radius - width); - EXPECT_POINT_NEAR(vertices[i * 2 + 1], - Point(center.x - rcos, center.y - rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2 + 1], - Point(center.x + rsin, center.y - rcos)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2 + 1], - Point(center.x + rcos, center.y + rsin)) - << "vertex " << i << ", angle = " << degrees << std::endl; - EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2 + 1], - Point(center.x - rsin, center.y + rcos)) - << "vertex " << i << ", angle = " << degrees << std::endl; - } - }; - - test(2.0, {}, 2.0, 1.0); - test(2.0, {}, 2.0, 0.5); - test(2.0, {10, 10}, 2.0, 1.0); - test(1000.0, {}, 2.0, 1.0); - test(2.0, {}, 1000.0, 10.0); -} - -} // namespace testing -} // namespace impeller diff --git a/engine/src/flutter/impeller/tessellator/tessellator.cc b/engine/src/flutter/impeller/tessellator/tessellator.cc index 292b1f29ec..4a89f42bd6 100644 --- a/engine/src/flutter/impeller/tessellator/tessellator.cc +++ b/engine/src/flutter/impeller/tessellator/tessellator.cc @@ -224,4 +224,395 @@ void DestroyTessellator(TESStesselator* tessellator) { } } +static constexpr int kPrecomputedDivisionCount = 1024; +static int kPrecomputedDivisions[kPrecomputedDivisionCount] = { + // clang-format off + 1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, + 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, + 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, + 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, + 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, + 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, + 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, + 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, + 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, + 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, + 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, + 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, + 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, + 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 47, + 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, + 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 48, 48, 48, + 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, + 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, + 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, + 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, + 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, + 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, + 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, + 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, + 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, + 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, + 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, + // clang-format on +}; + +static size_t ComputeQuadrantDivisions(Scalar pixel_radius) { + if (pixel_radius <= 0.0) { + return 1; + } + int radius_index = ceil(pixel_radius); + if (radius_index < kPrecomputedDivisionCount) { + return kPrecomputedDivisions[radius_index]; + } + + // For a circle with N divisions per quadrant, the maximum deviation of + // the polgyon approximation from the true circle will be at the center + // of the base of each triangular pie slice. We can compute that distance + // by finding the midpoint of the line of the first slice and compare + // its distance from the center of the circle to the radius. We will aim + // to have the length of that bisector to be within |kCircleTolerance| + // from the radius in pixels. + // + // Each vertex will appear at an angle of: + // theta(i) = (kPi / 2) * (i / N) // for i in [0..N] + // with each point falling at: + // point(i) = r * (cos(theta), sin(theta)) + // If we consider the unit circle to simplify the calculations below then + // we need to scale the tolerance from its absolute quantity into a unit + // circle fraction: + // k = tolerance / radius + // Using this scaled tolerance below to avoid multiplying by the radius + // throughout all of the math, we have: + // first point = (1, 0) // theta(0) == 0 + // theta = kPi / 2 / N // theta(1) + // second point = (cos(theta), sin(theta)) = (c, s) + // midpoint = (first + second) * 0.5 = ((1 + c)/2, s/2) + // |midpoint| = sqrt((1 + c)*(1 + c)/4 + s*s/4) + // = sqrt((1 + c + c + c*c + s*s) / 4) + // = sqrt((1 + 2c + 1) / 4) + // = sqrt((2 + 2c) / 4) + // = sqrt((1 + c) / 2) + // = cos(theta / 2) // using half-angle cosine formula + // error = 1 - |midpoint| = 1 - cos(theta / 2) + // cos(theta/2) = 1 - error + // theta/2 = acos(1 - error) + // kPi / 2 / N / 2 = acos(1 - error) + // kPi / 4 / acos(1 - error) = N + // Since we need error <= k, we want divisions >= N, so we use: + // N = ceil(kPi / 4 / acos(1 - k)) + // + // Math is confirmed in https://math.stackexchange.com/a/4132095 + // (keeping in mind that we are computing quarter circle divisions here) + // which also points out a performance optimization that is accurate + // to within an over-estimation of 1 division would be: + // N = ceil(kPi / 4 / sqrt(2 * k)) + // Since we have precomputed the divisions for radii up to 1024, we can + // afford to be more accurate using the acos formula here for larger radii. + double k = Tessellator::kCircleTolerance / pixel_radius; + return ceil(kPiOver4 / std::acos(1 - k)); +} + +void Tessellator::Trigs::init(size_t divisions) { + if (!trigs_.empty()) { + return; + } + + // Either not cached yet, or we are using the temp storage... + trigs_.reserve(divisions + 1); + + double angle_scale = kPiOver2 / divisions; + + trigs_.emplace_back(1.0, 0.0); + for (size_t i = 1; i < divisions; i++) { + trigs_.emplace_back(Radians(i * angle_scale)); + } + trigs_.emplace_back(0.0, 1.0); +} + +Tessellator::Trigs Tessellator::GetTrigsForDivisions(size_t divisions) { + return divisions < Tessellator::kCachedTrigCount + ? Trigs(precomputed_trigs_[divisions], divisions) + : Trigs(divisions); +} + +using TessellatedVertexProc = Tessellator::TessellatedVertexProc; +using EllipticalVertexGenerator = Tessellator::EllipticalVertexGenerator; + +EllipticalVertexGenerator::EllipticalVertexGenerator( + EllipticalVertexGenerator::GeneratorProc& generator, + Trigs&& trigs, + PrimitiveType triangle_type, + size_t vertices_per_trig, + Data&& data) + : impl_(generator), + trigs_(std::move(trigs)), + data_(data), + vertices_per_trig_(vertices_per_trig) {} + +EllipticalVertexGenerator Tessellator::FilledCircle( + const Matrix& view_transform, + const Point& center, + Scalar radius) { + auto divisions = + ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * radius); + return EllipticalVertexGenerator(Tessellator::GenerateFilledCircle, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {center, center}, + .radii = {radius, radius}, + .half_width = -1.0f, + }); +} + +EllipticalVertexGenerator Tessellator::StrokedCircle( + const Matrix& view_transform, + const Point& center, + Scalar radius, + Scalar half_width) { + if (half_width > 0) { + auto divisions = ComputeQuadrantDivisions( + view_transform.GetMaxBasisLength() * radius + half_width); + return EllipticalVertexGenerator(Tessellator::GenerateStrokedCircle, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 8, + { + .reference_centers = {center, center}, + .radii = {radius, radius}, + .half_width = half_width, + }); + } else { + return FilledCircle(view_transform, center, radius); + } +} + +EllipticalVertexGenerator Tessellator::RoundCapLine( + const Matrix& view_transform, + const Point& p0, + const Point& p1, + Scalar radius) { + auto along = p1 - p0; + auto length = along.GetLength(); + if (length > kEhCloseEnough) { + auto divisions = + ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * radius); + return EllipticalVertexGenerator(Tessellator::GenerateRoundCapLine, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {p0, p1}, + .radii = {radius, radius}, + .half_width = -1.0f, + }); + } else { + return FilledCircle(view_transform, p0, radius); + } +} + +EllipticalVertexGenerator Tessellator::FilledEllipse( + const Matrix& view_transform, + const Rect& bounds) { + if (bounds.IsSquare()) { + return FilledCircle(view_transform, bounds.GetCenter(), + bounds.GetSize().width * 0.5f); + } + auto max_radius = bounds.GetSize().MaxDimension(); + auto divisions = + ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * max_radius); + auto center = bounds.GetCenter(); + return EllipticalVertexGenerator(Tessellator::GenerateFilledEllipse, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {center, center}, + .radii = bounds.GetSize() * 0.5f, + .half_width = -1.0f, + }); +} + +void Tessellator::GenerateFilledCircle( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + auto radius = data.radii.width; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(radius == data.radii.height); + FML_DCHECK(data.half_width < 0); + + // Quadrant 1 connecting with Quadrant 4: + for (auto& trig : trigs) { + auto offset = trig * radius; + proc({center.x - offset.x, center.y + offset.y}); + proc({center.x - offset.x, center.y - offset.y}); + } + + // The second half of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2 connecting with Quadrant 2: + for (auto& trig : trigs) { + auto offset = trig * radius; + proc({center.x + offset.y, center.y + offset.x}); + proc({center.x + offset.y, center.y - offset.x}); + } +} + +void Tessellator::GenerateStrokedCircle( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(data.radii.IsSquare()); + FML_DCHECK(data.half_width > 0 && data.half_width < data.radii.width); + + auto outer_radius = data.radii.width + data.half_width; + auto inner_radius = data.radii.width - data.half_width; + + // Zig-zag back and forth between points on the outer circle and the + // inner circle. Both circles are evaluated at the same number of + // quadrant divisions so the points for a given division should match + // 1 for 1 other than their applied radius. + + // Quadrant 1: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x - outer.x, center.y - outer.y}); + proc({center.x - inner.x, center.y - inner.y}); + } + + // The even quadrants of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x + outer.y, center.y - outer.x}); + proc({center.x + inner.y, center.y - inner.x}); + } + + // Quadrant 3: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x + outer.x, center.y + outer.y}); + proc({center.x + inner.x, center.y + inner.y}); + } + + // Quadrant 4: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x - outer.y, center.y + outer.x}); + proc({center.x - inner.y, center.y + inner.x}); + } +} + +void Tessellator::GenerateRoundCapLine( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto p0 = data.reference_centers[0]; + auto p1 = data.reference_centers[1]; + auto radius = data.radii.width; + + FML_DCHECK(radius == data.radii.height); + FML_DCHECK(data.half_width < 0); + + auto along = p1 - p0; + along *= radius / along.GetLength(); + auto across = Point(-along.y, along.x); + + for (auto& trig : trigs) { + auto relative_along = along * trig.cos; + auto relative_across = across * trig.sin; + proc(p0 - relative_along + relative_across); + proc(p0 - relative_along - relative_across); + } + + // The second half of the round caps should be iterated in reverse, but + // we can instead iterate forward and swap the sin/cos values as they + // should be symmetric. + for (auto& trig : trigs) { + auto relative_along = along * trig.sin; + auto relative_across = across * trig.cos; + proc(p1 + relative_along + relative_across); + proc(p1 + relative_along - relative_across); + } +} + +void Tessellator::GenerateFilledEllipse( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + auto radii = data.radii; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(data.half_width < 0); + + // Quadrant 1 connecting with Quadrant 4: + for (auto& trig : trigs) { + auto offset = trig * radii; + proc({center.x - offset.x, center.y + offset.y}); + proc({center.x - offset.x, center.y - offset.y}); + } + + // The second half of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2 connecting with Quadrant 2: + for (auto& trig : trigs) { + auto offset = Point(trig.sin * radii.width, trig.cos * radii.height); + proc({center.x + offset.x, center.y + offset.y}); + proc({center.x + offset.x, center.y - offset.y}); + } +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/tessellator/tessellator.h b/engine/src/flutter/impeller/tessellator/tessellator.h index 3f5b5d7ebb..686c8d3f25 100644 --- a/engine/src/flutter/impeller/tessellator/tessellator.h +++ b/engine/src/flutter/impeller/tessellator/tessellator.h @@ -9,6 +9,7 @@ #include #include "flutter/fml/macros.h" +#include "impeller/core/formats.h" #include "impeller/geometry/path.h" #include "impeller/geometry/point.h" #include "impeller/geometry/trig.h" @@ -35,6 +36,43 @@ enum class WindingOrder { /// called from multiple threads. /// class Tessellator { + private: + /// Essentially just a vector of Trig objects, but supports storing a + /// reference to either a cached vector or a locally generated vector. + /// The constructor will fill the vector with quarter circular samples + /// for the indicated number of equal divisions if the vector is new. + class Trigs { + public: + explicit Trigs(std::vector& trigs, size_t divisions) : trigs_(trigs) { + init(divisions); + FML_DCHECK(trigs_.size() == divisions + 1); + } + + explicit Trigs(size_t divisions) + : local_storage_(std::make_unique>()), + trigs_(*local_storage_) { + init(divisions); + FML_DCHECK(trigs_.size() == divisions + 1); + } + + // Utility forwards of the indicated vector methods. + auto inline size() const { return trigs_.size(); } + auto inline begin() const { return trigs_.begin(); } + auto inline end() const { return trigs_.end(); } + + private: + // nullptr if a cached vector is used, otherwise the actual storage + std::unique_ptr> local_storage_; + + // Whether or not a cached vector or the local storage is used, this + // this reference will always be valid + std::vector& trigs_; + + // Fill the vector with the indicated number of equal divisions of + // trigonometric values if it is empty. + void init(size_t divisions); + }; + public: enum class Result { kSuccess, @@ -42,6 +80,100 @@ class Tessellator { kTessellationError, }; + /// @brief A callback function for a |VertexGenerator| to deliver + /// the vertices it computes as |Point| objects. + using TessellatedVertexProc = std::function; + + /// @brief An object which produces a list of vertices as |Point|s that + /// tessellate a previously provided shape and delivers the vertices + /// through a |TessellatedVertexProc| callback. + /// + /// The object can also provide advance information on how many + /// vertices it will generate. + /// + /// @see |Tessellator::FilledCircle| + /// @see |Tessellator::StrokedCircle| + /// @see |Tessellator::RoundCapLine| + /// @see |Tessellator::FilledEllipse| + class VertexGenerator { + public: + /// @brief Returns the |PrimitiveType| that describes the relationship + /// among the list of vertices produced by the |GenerateVertices| + /// method. + /// + /// Most generators will deliver |kTriangleStrip| triangles + virtual PrimitiveType GetTriangleType() const = 0; + + /// @brief Returns the number of vertices that the generator plans to + /// produce, if known. + /// + /// This value is advisory only and can be used to reserve space + /// where the vertices will be placed, but the count may be an + /// estimate. + /// + /// Implementations are encouraged to avoid overestimating + /// the count by too large a number and to provide a best + /// guess so as to minimize potential buffer reallocations + /// as the vertices are delivered. + virtual size_t GetVertexCount() const = 0; + + /// @brief Generate the vertices and deliver them in the necessary + /// order (as required by the PrimitiveType) to the given + /// callback function. + virtual void GenerateVertices(const TessellatedVertexProc& proc) const = 0; + }; + + /// @brief The |VertexGenerator| implementation common to all shapes + /// that are based on a polygonal representation of an ellipse. + class EllipticalVertexGenerator : public virtual VertexGenerator { + public: + /// |VertexGenerator| + PrimitiveType GetTriangleType() const override { + return PrimitiveType::kTriangleStrip; + } + + /// |VertexGenerator| + size_t GetVertexCount() const override { + return trigs_.size() * vertices_per_trig_; + } + + /// |VertexGenerator| + void GenerateVertices(const TessellatedVertexProc& proc) const override { + impl_(trigs_, data_, proc); + } + + private: + friend class Tessellator; + + struct Data { + // Circles and Ellipses only use one of these points. + // RoundCapLines use both as the endpoints of the unexpanded line. + // A round rect can specify its interior rectangle by using the + // 2 points as opposing corners. + const Point reference_centers[2]; + // Circular shapes have the same value in radii.width and radii.height + const Size radii; + // half_width is only used in cases where the generator will be + // generating 2 different outlines, such as StrokedCircle + const Scalar half_width; + }; + + typedef void GeneratorProc(const Trigs& trigs, + const Data& data, + const TessellatedVertexProc& proc); + + GeneratorProc& impl_; + const Trigs trigs_; + const Data data_; + const size_t vertices_per_trig_; + + EllipticalVertexGenerator(GeneratorProc& generator, + Trigs&& trigs, + PrimitiveType triangle_type, + size_t vertices_per_trig, + Data&& data); + }; + Tessellator(); ~Tessellator(); @@ -85,15 +217,97 @@ class Tessellator { /// std::vector TessellateConvex(const Path& path, Scalar tolerance); + /// @brief The pixel tolerance used by the algorighm to determine how + /// many divisions to create for a circle. + /// + /// No point on the polygon of vertices should deviate from the + /// true circle by more than this tolerance. + static constexpr Scalar kCircleTolerance = 0.1f; + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a filled circle of the given radius around the given center + /// with enough polygon sub-divisions to provide reasonable + /// fidelity when viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the center point. + EllipticalVertexGenerator FilledCircle(const Matrix& view_transform, + const Point& center, + Scalar radius); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a stroked circle of the given radius and half_width around + /// the given shared center with enough polygon sub-divisions + /// to provide reasonable fidelity when viewed under the given + /// view transform. The outer edge of the stroked circle is + /// generated at (radius + half_width) and the inner edge is + /// generated at (radius - half_width). + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the center point. + EllipticalVertexGenerator StrokedCircle(const Matrix& view_transform, + const Point& center, + Scalar radius, + Scalar half_width); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a line with round end caps of the given radius with enough + /// polygon sub-divisions to provide reasonable fidelity when + /// viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the two points. + EllipticalVertexGenerator RoundCapLine(const Matrix& view_transform, + const Point& p0, + const Point& p1, + Scalar radius); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a filled ellipse inscribed within the given bounds with + /// enough polygon sub-divisions to provide reasonable + /// fidelity when viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the bounds. + EllipticalVertexGenerator FilledEllipse(const Matrix& view_transform, + const Rect& bounds); + private: /// Used for polyline generation. std::unique_ptr> point_buffer_; CTessellator c_tessellator_; - // Cached data for CircleTessellator + // Data for variouos Circle/EllipseGenerator classes, cached per + // Tessellator instance which is usually the foreground life of an app + // if not longer. static constexpr size_t kCachedTrigCount = 300; std::vector precomputed_trigs_[kCachedTrigCount]; - friend class CircleTessellator; + + Trigs GetTrigsForDivisions(size_t divisions); + + static void GenerateFilledCircle(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateStrokedCircle(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateRoundCapLine(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateFilledEllipse(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); Tessellator(const Tessellator&) = delete; diff --git a/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc b/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc index b1c807f58f..10f64493d1 100644 --- a/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc +++ b/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc @@ -4,6 +4,8 @@ #include "flutter/testing/testing.h" #include "gtest/gtest.h" + +#include "impeller/geometry/geometry_asserts.h" #include "impeller/geometry/path.h" #include "impeller/geometry/path_builder.h" #include "impeller/tessellator/tessellator.h" @@ -132,5 +134,282 @@ TEST(TessellatorTest, TessellateConvex) { } } +TEST(TessellatorTest, CircleVertexCounts) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, Scalar radius) { + auto generator = tessellator->FilledCircle(transform, {}, radius); + size_t quadrant_divisions = generator.GetVertexCount() / 4; + + // Confirm the approximation error is within the currently accepted + // |kCircleTolerance| value advertised by |CircleTessellator|. + // (With an additional 1% tolerance for floating point rounding.) + double angle = kPiOver2 / quadrant_divisions; + Point first = {radius, 0}; + Point next = {static_cast(cos(angle) * radius), + static_cast(sin(angle) * radius)}; + Point midpoint = (first + next) * 0.5; + EXPECT_GE(midpoint.GetLength(), + radius - Tessellator::kCircleTolerance * 1.01) + << ", transform = " << transform << ", radius = " << radius + << ", divisions = " << quadrant_divisions; + }; + + test({}, 0.0); + test({}, 0.9); + test({}, 1.0); + test({}, 1.9); + test(Matrix::MakeScale(Vector2(2.0, 2.0)), 0.95); + test({}, 2.0); + test(Matrix::MakeScale(Vector2(2.0, 2.0)), 1.0); + test({}, 11.9); + test({}, 12.0); + test({}, 35.9); + for (int i = 36; i < 10000; i += 4) { + test({}, i); + } +} + +TEST(TessellatorTest, FilledCircleTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& center, + Scalar radius) { + auto generator = tessellator->FilledCircle(transform, center, radius); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * radius; + double rcos = cos(angle) * radius; + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], + Point(center.x + rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + }; + + test({}, {}, 2.0); + test({}, {10, 10}, 2.0); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {}, 2.0); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {}, 1000.0); +} + +TEST(TessellatorTest, StrokedCircleTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& center, + Scalar radius, Scalar half_width) { + ASSERT_GT(radius, half_width); + auto generator = + tessellator->StrokedCircle(transform, center, radius, half_width); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 8; + + // Test outer points first + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * (radius + half_width); + double rcos = cos(angle) * (radius + half_width); + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2], + Point(center.x + rsin, center.y - rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2], + Point(center.x - rsin, center.y + rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + + // Then test innerer points + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * (radius - half_width); + double rcos = cos(angle) * (radius - half_width); + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2 + 1], + Point(center.x + rsin, center.y - rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2 + 1], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2 + 1], + Point(center.x - rsin, center.y + rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + }; + + test({}, {}, 2.0, 1.0); + test({}, {}, 2.0, 0.5); + test({}, {10, 10}, 2.0, 1.0); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {}, 2.0, 1.0); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {}, 1000.0, 10.0); +} + +TEST(TessellatorTest, RoundCapLineTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& p0, + const Point& p1, Scalar radius) { + auto generator = tessellator->RoundCapLine(transform, p0, p1, radius); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + Point along = p1 - p0; + Scalar length = along.GetLength(); + if (length > 0) { + along *= radius / length; + } else { + along = {radius, 0}; + } + Point across = {-along.y, along.x}; + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + Point relative_along = along * cos(angle); + Point relative_across = across * sin(angle); + EXPECT_POINT_NEAR(vertices[i * 2], // + p0 - relative_along + relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], // + p0 - relative_along - relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], // + p1 + relative_along - relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], // + p1 + relative_along + relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + } + }; + + // Empty line should actually use the circle generator, but its + // results should match the same math as the round cap generator. + test({}, {0, 0}, {0, 0}, 10); + + test({}, {0, 0}, {10, 0}, 2); + test({}, {10, 0}, {0, 0}, 2); + test({}, {0, 0}, {10, 10}, 2); + + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {0, 0}, {10, 0}, 2); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {10, 0}, {0, 0}, 2); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {0, 0}, {10, 10}, 2); + + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {0, 0}, {10, 0}, 2); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {10, 0}, {0, 0}, 2); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {0, 0}, {10, 10}, 2); +} + +TEST(TessellatorTest, FilledEllipseTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Rect& bounds) { + auto center = bounds.GetCenter(); + auto half_size = bounds.GetSize() * 0.5f; + + auto generator = tessellator->FilledEllipse(transform, bounds); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rcos = cos(angle) * half_size.width; + double rsin = sin(angle) * half_size.height; + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], + Point(center.x + rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + } + }; + + // Square bounds should actually use the circle generator, but its + // results should match the same math as the ellipse generator. + test({}, Rect::MakeLTRB(0, 0, 2, 2)); + + test({}, Rect::MakeLTRB(0, 0, 2, 3)); + test({}, Rect::MakeLTRB(0, 0, 3, 2)); + test({}, Rect::MakeLTRB(5, 10, 2, 3)); + test({}, Rect::MakeLTRB(16, 7, 3, 2)); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeLTRB(5, 10, 3, 2)); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeLTRB(5, 10, 2, 3)); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeLTRB(5000, 10000, 3000, 2000)); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeLTRB(5000, 10000, 2000, 3000)); +} + } // namespace testing } // namespace impeller