Add //impeller/typographer. (flutter/engine#36)

Renders shaped text frames. Has the ability to plug into to different text
shapers and render glyphs using different techniques.

For now, the Aiks layer expects a prepared glyph atlas. But this will be changed
so that render pass will be responsible for preparing these and setting these on
the content renderer after pass consolidation.
This commit is contained in:
Chinmay Garde
2022-02-25 14:50:32 -08:00
committed by Dan Field
parent 106ef2d16e
commit 1c21164f30
63 changed files with 1778 additions and 23 deletions

View File

@@ -21,6 +21,7 @@ group("impeller") {
"geometry",
"image",
"renderer",
"typographer",
]
if (is_host) {
@@ -43,5 +44,6 @@ executable("impeller_unittests") {
"image:image_unittests",
"playground",
"renderer:renderer_unittests",
"typographer:typographer_unittests",
]
}

View File

@@ -8,6 +8,9 @@
#include "impeller/aiks/image.h"
#include "impeller/geometry/geometry_unittests.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/typographer/backends/skia/text_frame_skia.h"
#include "impeller/typographer/backends/skia/text_render_context_skia.h"
#include "third_party/skia/include/core/SkData.h"
namespace impeller {
namespace testing {
@@ -283,5 +286,114 @@ TEST_F(AiksTest, CanRenderDifferencePaths) {
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
static sk_sp<SkData> OpenFixtureAsSkData(const char* fixture_name) {
auto mapping = flutter::testing::OpenFixtureAsMapping(fixture_name);
if (!mapping) {
return nullptr;
}
return SkData::MakeWithProc(
mapping->GetMapping(), mapping->GetSize(),
[](const void* ptr, void* context) {
delete reinterpret_cast<fml::Mapping*>(context);
},
mapping.release());
}
TEST_F(AiksTest, CanRenderTextFrame) {
Canvas canvas;
Scalar baseline = 200.0;
Point text_position = {100, baseline};
// Draw the baseline.
canvas.DrawRect({50, baseline, 900, 10},
Paint{.color = Color::Aqua().WithAlpha(0.25)});
// Mark the point at which the text is drawn.
canvas.DrawCircle(text_position, 5.0,
Paint{.color = Color::Red().WithAlpha(0.25)});
// Construct the text blob.
auto mapping = OpenFixtureAsSkData("Roboto-Regular.ttf");
ASSERT_TRUE(mapping);
SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0);
auto blob = SkTextBlob::MakeFromString(
"the quick brown fox jumped over the lazy dog!.?", sk_font);
ASSERT_TRUE(blob);
// Create the Impeller text frame and draw it at the designated baseline.
auto frame = TextFrameFromTextBlob(blob);
TextRenderContextSkia text_context(GetContext());
ASSERT_TRUE(text_context.IsValid());
auto atlas = text_context.CreateGlyphAtlas(frame);
ASSERT_NE(atlas, nullptr);
canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_F(AiksTest, CanRenderItalicizedText) {
Canvas canvas;
Scalar baseline = 200.0;
Point text_position = {100, baseline};
// Draw the baseline.
canvas.DrawRect({50, baseline, 900, 10},
Paint{.color = Color::Aqua().WithAlpha(0.25)});
// Mark the point at which the text is drawn.
canvas.DrawCircle(text_position, 5.0,
Paint{.color = Color::Red().WithAlpha(0.25)});
// Construct the text blob.
auto mapping = OpenFixtureAsSkData("HomemadeApple.ttf");
ASSERT_TRUE(mapping);
SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0);
auto blob = SkTextBlob::MakeFromString(
"the quick brown fox jumped over the lazy dog!.?", sk_font);
ASSERT_TRUE(blob);
// Create the Impeller text frame and draw it at the designated baseline.
auto frame = TextFrameFromTextBlob(blob);
TextRenderContextSkia text_context(GetContext());
ASSERT_TRUE(text_context.IsValid());
auto atlas = text_context.CreateGlyphAtlas(frame);
ASSERT_NE(atlas, nullptr);
canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_F(AiksTest, CanRenderEmojiTextFrame) {
Canvas canvas;
Scalar baseline = 200.0;
Point text_position = {100, baseline};
// Draw the baseline.
canvas.DrawRect({50, baseline, 900, 10},
Paint{.color = Color::Aqua().WithAlpha(0.25)});
// Mark the point at which the text is drawn.
canvas.DrawCircle(text_position, 5.0,
Paint{.color = Color::Red().WithAlpha(0.25)});
// Construct the text blob.
auto mapping = OpenFixtureAsSkData("NotoColorEmoji.ttf");
ASSERT_TRUE(mapping);
SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0);
auto blob = SkTextBlob::MakeFromString(
"😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊", sk_font);
ASSERT_TRUE(blob);
// Create the Impeller text frame and draw it at the designated baseline.
auto frame = TextFrameFromTextBlob(blob);
TextRenderContextSkia text_context(GetContext());
ASSERT_TRUE(text_context.IsValid());
auto atlas = text_context.CreateGlyphAtlas(frame);
ASSERT_NE(atlas, nullptr);
canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace testing
} // namespace impeller

View File

@@ -252,4 +252,25 @@ void Canvas::Save(bool create_subpass) {
xformation_stack_.emplace_back(std::move(entry));
}
void Canvas::DrawTextFrame(TextFrame text_frame,
std::shared_ptr<GlyphAtlas> atlas,
Point position) {
if (!atlas || !atlas->IsValid()) {
return;
}
auto text_contents = std::make_shared<TextContents>();
text_contents->SetTextFrame(std::move(text_frame));
text_contents->SetGlyphAtlas(std::move(atlas));
Entity entity;
entity.SetTransformation(GetCurrentTransformation() *
Matrix::MakeTranslation(position));
entity.SetPath({});
entity.SetStencilDepth(GetStencilDepth());
entity.SetContents(std::move(text_contents));
GetCurrentPass().AddEntity(std::move(entity));
}
} // namespace impeller

View File

@@ -18,6 +18,7 @@
#include "impeller/geometry/path.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/vector.h"
#include "impeller/typographer/text_frame.h"
namespace impeller {
@@ -74,6 +75,10 @@ class Canvas {
void DrawPicture(Picture picture);
void DrawTextFrame(TextFrame text_frame,
std::shared_ptr<GlyphAtlas> atlas,
Point position);
Picture EndRecordingAsPicture();
private:

View File

@@ -7,6 +7,10 @@
namespace impeller {
std::shared_ptr<Contents> Paint::CreateContentsForEntity() const {
if (contents) {
return contents;
}
switch (style) {
case Style::kFill: {
auto solid_color = std::make_shared<SolidColorContents>();

View File

@@ -21,6 +21,7 @@ struct Paint {
Color color = Color::Black();
Scalar stroke_width = 0.0;
Style style = Style::kFill;
std::shared_ptr<Contents> contents;
std::shared_ptr<Contents> CreateContentsForEntity() const;
};

View File

@@ -8,6 +8,7 @@ impeller_component("base") {
sources = [
"allocation.cc",
"allocation.h",
"backend_cast.h",
"base.h",
"config.h",
"promise.cc",

View File

@@ -38,7 +38,7 @@ bool Allocation::Truncate(size_t length, bool npot) {
return true;
}
static uint32_t NextPowerOfTwoSize(uint32_t x) {
uint32_t Allocation::NextPowerOfTwoSize(uint32_t x) {
if (x == 0) {
return 1;
}

View File

@@ -25,6 +25,8 @@ class Allocation {
[[nodiscard]] bool Truncate(size_t length, bool npot = true);
static uint32_t NextPowerOfTwoSize(uint32_t x);
private:
uint8_t* buffer_ = nullptr;
size_t length_ = 0;

View File

@@ -6,6 +6,9 @@
#include "flutter/fml/trace_event.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/typographer/backends/skia/text_frame_skia.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkShader.h"
namespace impeller {
@@ -72,8 +75,56 @@ void DisplayListDispatcher::setStrokeJoin(SkPaint::Join join) {
UNIMPLEMENTED;
}
static Point ToPoint(const SkPoint& point) {
return Point::MakeXY(point.fX, point.fY);
}
static Color ToColor(const SkColor& color) {
return {
static_cast<Scalar>(SkColorGetR(color) / 255.0), //
static_cast<Scalar>(SkColorGetG(color) / 255.0), //
static_cast<Scalar>(SkColorGetB(color) / 255.0), //
static_cast<Scalar>(SkColorGetA(color) / 255.0) //
};
}
// |flutter::Dispatcher|
void DisplayListDispatcher::setShader(sk_sp<SkShader> shader) {
if (!shader) {
return;
}
{
SkShader::GradientInfo info = {};
constexpr auto kColorsArrayCount = 2u;
info.fColorCount = kColorsArrayCount;
SkColor sk_colors[kColorsArrayCount];
info.fColors = sk_colors;
auto gradient_type = shader->asAGradient(&info);
switch (gradient_type) {
case SkShader::kLinear_GradientType: {
auto contents = std::make_shared<LinearGradientContents>();
contents->SetEndPoints(ToPoint(info.fPoint[0]),
ToPoint(info.fPoint[1]));
std::vector<Color> colors;
for (auto i = 0; i < info.fColorCount; i++) {
colors.emplace_back(ToColor(sk_colors[i]));
}
contents->SetColors(std::move(colors));
paint_.contents = std::move(contents);
return;
} break;
case SkShader::kNone_GradientType:
case SkShader::kColor_GradientType:
case SkShader::kRadial_GradientType:
case SkShader::kSweep_GradientType:
case SkShader::kConical_GradientType:
default:
UNIMPLEMENTED;
break;
}
}
// Needs https://github.com/flutter/flutter/issues/95434
UNIMPLEMENTED;
}
@@ -154,9 +205,8 @@ static std::optional<Rect> ToRect(const SkRect* rect) {
// |flutter::Dispatcher|
void DisplayListDispatcher::saveLayer(const SkRect* bounds,
const flutter::SaveLayerOptions options) {
canvas_.SaveLayer(
options.renders_with_attributes() ? paint_ : Paint{},
ToRect(bounds));
canvas_.SaveLayer(options.renders_with_attributes() ? paint_ : Paint{},
ToRect(bounds));
}
// |flutter::Dispatcher|
@@ -242,10 +292,6 @@ void DisplayListDispatcher::clipRect(const SkRect& rect,
canvas_.ClipPath(std::move(path));
}
static Point ToPoint(const SkVector& vector) {
return {vector.fX, vector.fY};
}
static PathBuilder::RoundingRadii ToRoundingRadii(const SkRRect& rrect) {
using Corner = SkRRect::Corner;
PathBuilder::RoundingRadii radii;

View File

@@ -16,6 +16,8 @@ impeller_shaders("entity_shaders") {
"shaders/solid_stroke.vert",
"shaders/texture_fill.frag",
"shaders/texture_fill.vert",
"shaders/glyph_atlas.frag",
"shaders/glyph_atlas.vert",
]
}
@@ -38,6 +40,7 @@ impeller_component("entity") {
"../archivist",
"../image",
"../renderer",
"../typographer",
]
}

View File

@@ -21,6 +21,7 @@ ContentContext::ContentContext(std::shared_ptr<Context> context)
texture_pipelines_[{}] = std::make_unique<TexturePipeline>(*context_);
solid_stroke_pipelines_[{}] =
std::make_unique<SolidStrokePipeline>(*context_);
glyph_atlas_pipelines_[{}] = std::make_unique<GlyphAtlasPipeline>(*context_);
// Pipelines that are variants of the base pipelines with custom descriptors.
// TODO(98684): Rework this API to allow fetching the descriptor without

View File

@@ -9,6 +9,8 @@
#include "flutter/fml/hash_combine.h"
#include "flutter/fml/macros.h"
#include "flutter/impeller/entity/glyph_atlas.frag.h"
#include "flutter/impeller/entity/glyph_atlas.vert.h"
#include "flutter/impeller/entity/gradient_fill.frag.h"
#include "flutter/impeller/entity/gradient_fill.vert.h"
#include "flutter/impeller/entity/solid_fill.frag.h"
@@ -29,6 +31,8 @@ using TexturePipeline =
PipelineT<TextureFillVertexShader, TextureFillFragmentShader>;
using SolidStrokePipeline =
PipelineT<SolidStrokeVertexShader, SolidStrokeFragmentShader>;
using GlyphAtlasPipeline =
PipelineT<GlyphAtlasVertexShader, GlyphAtlasFragmentShader>;
// Instead of requiring new shaders for clips, the solid fill stages are used
// to redirect writing to the stencil instead of color attachments.
using ClipPipeline = PipelineT<SolidFillVertexShader, SolidFillFragmentShader>;
@@ -81,6 +85,10 @@ class ContentContext {
return GetPipeline(clip_restoration_pipelines_, opts);
}
std::shared_ptr<Pipeline> GetGlyphAtlasPipeline(Options opts) const {
return GetPipeline(glyph_atlas_pipelines_, opts);
}
std::shared_ptr<Context> GetContext() const;
private:
@@ -99,6 +107,7 @@ class ContentContext {
mutable Variants<SolidStrokePipeline> solid_stroke_pipelines_;
mutable Variants<ClipPipeline> clip_pipelines_;
mutable Variants<ClipPipeline> clip_restoration_pipelines_;
mutable Variants<GlyphAtlasPipeline> glyph_atlas_pipelines_;
static void ApplyOptionsToDescriptor(PipelineDescriptor& desc,
const Options& options) {

View File

@@ -551,4 +551,121 @@ bool ClipRestoreContents::Render(const ContentContext& renderer,
return true;
}
/*******************************************************************************
******* TextContents
******************************************************************************/
TextContents::TextContents() = default;
TextContents::~TextContents() = default;
void TextContents::SetTextFrame(TextFrame frame) {
frame_ = std::move(frame);
}
void TextContents::SetGlyphAtlas(std::shared_ptr<GlyphAtlas> atlas) {
atlas_ = std::move(atlas);
}
bool TextContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (!atlas_ || !atlas_->IsValid()) {
VALIDATION_LOG << "Cannot render glyphs without prepared atlas.";
return false;
}
using VS = GlyphAtlasPipeline::VertexShader;
using FS = GlyphAtlasPipeline::FragmentShader;
// Information shared by all glyph draw calls.
Command cmd;
cmd.label = "Glyph";
cmd.primitive_type = PrimitiveType::kTriangle;
cmd.pipeline = renderer.GetGlyphAtlasPipeline(OptionsFromPass(pass));
cmd.stencil_reference = entity.GetStencilDepth();
// Common vertex uniforms for all glyphs.
VS::FrameInfo frame_info;
frame_info.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) *
entity.GetTransformation();
frame_info.atlas_size =
Point{static_cast<Scalar>(atlas_->GetTexture()->GetSize().width),
static_cast<Scalar>(atlas_->GetTexture()->GetSize().height)};
VS::BindFrameInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(frame_info));
// Common fragment uniforms for all glyphs.
FS::BindGlyphAtlasSampler(
cmd, // command
atlas_->GetTexture(), // texture
renderer.GetContext()->GetSamplerLibrary()->GetSampler({}) // sampler
);
// Common vertex information for all glyphs.
// Currently, glyphs are being drawn individually. This can be batched later.
// But we don't want to give each glyph unique vertex information. So all
// glyphs are given the same vertex information in the form of a unit-sized
// quad. The size of the glyph is specified in uniform data and the vertex
// shader uses this to size the glyph correctly. The interpolated vertex
// information is also used in the fragment shader to sample from the glyph
// atlas.
{
VertexBufferBuilder<VS::PerVertexData> vertex_builder;
if (!Tessellator{FillType::kPositive}.Tessellate(
PathBuilder{}
.AddRect(Rect::MakeXYWH(0.0, 0.0, 1.0, 1.0))
.TakePath()
.CreatePolyline(),
[&vertex_builder](Point point) {
VS::PerVertexData vtx;
vtx.unit_vertex = point;
vertex_builder.AppendVertex(std::move(vtx));
})) {
return false;
}
auto dummy = vertex_builder.CreateVertexBuffer(pass.GetTransientsBuffer());
auto vertex_buffer = dummy;
if (!vertex_buffer) {
return false;
}
cmd.BindVertices(std::move(vertex_buffer));
}
// Iterate through all the runs in the blob.
for (const auto& run : frame_.GetRuns()) {
auto font = run.GetFont();
auto glyph_size = font.GetGlyphSize();
if (!glyph_size.has_value()) {
VALIDATION_LOG << "Glyph has no size.";
return false;
}
// Draw each glyph individually. This should probably be batched.
for (const auto& glyph_position : run.GetGlyphPositions()) {
FontGlyphPair font_glyph_pair{font, glyph_position.glyph};
auto atlas_glyph_pos = atlas_->FindFontGlyphPosition(font_glyph_pair);
if (!atlas_glyph_pos.has_value()) {
VALIDATION_LOG << "Could not find glyph position in the atlas.";
return false;
}
VS::GlyphInfo glyph_info;
glyph_info.position = glyph_position.position.Translate(
{0.0, font.GetMetrics().ascent, 0.0});
glyph_info.glyph_size = {static_cast<Scalar>(glyph_size->width),
static_cast<Scalar>(glyph_size->height)};
glyph_info.atlas_position = atlas_glyph_pos->origin;
glyph_info.atlas_glyph_size = {atlas_glyph_pos->size.width,
atlas_glyph_pos->size.height};
VS::BindGlyphInfo(cmd,
pass.GetTransientsBuffer().EmplaceUniform(glyph_info));
if (!pass.AddCommand(cmd)) {
return false;
}
}
}
return true;
}
} // namespace impeller

View File

@@ -12,6 +12,8 @@
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/texture.h"
#include "impeller/typographer/glyph_atlas.h"
#include "impeller/typographer/text_frame.h"
namespace impeller {
@@ -187,6 +189,8 @@ class ClipRestoreContents final : public Contents {
~ClipRestoreContents();
void SetGlyphAtlas(std::shared_ptr<GlyphAtlas> atlas);
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
@@ -196,4 +200,26 @@ class ClipRestoreContents final : public Contents {
FML_DISALLOW_COPY_AND_ASSIGN(ClipRestoreContents);
};
class TextContents final : public Contents {
public:
TextContents();
~TextContents();
void SetTextFrame(TextFrame frame);
void SetGlyphAtlas(std::shared_ptr<GlyphAtlas> atlas);
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
private:
TextFrame frame_;
std::shared_ptr<GlyphAtlas> atlas_;
FML_DISALLOW_COPY_AND_ASSIGN(TextContents);
};
} // namespace impeller

View File

@@ -0,0 +1,22 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform sampler2D glyph_atlas_sampler;
in vec2 v_unit_vertex;
in vec2 v_atlas_position;
in vec2 v_atlas_glyph_size;
in vec2 v_atlas_size;
out vec4 frag_color;
void main() {
vec2 scale_perspective = v_atlas_glyph_size / v_atlas_size;
vec2 offset = v_atlas_position / v_atlas_size;
frag_color = texture(
glyph_atlas_sampler,
v_unit_vertex * scale_perspective + offset
);
}

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FrameInfo {
mat4 mvp;
vec2 atlas_size;
} frame_info;
uniform GlyphInfo {
mat4 position;
vec2 glyph_size;
vec2 atlas_position;
vec2 atlas_glyph_size;
} glyph_info;
in vec2 unit_vertex;
out vec2 v_unit_vertex;
out vec2 v_atlas_position;
out vec2 v_atlas_glyph_size;
out vec2 v_atlas_size;
void main() {
mat4 scale = mat4(
glyph_info.glyph_size.x, 0.0, 0.0, 0.0,
0.0, glyph_info.glyph_size.y, 0.0, 0.0,
0.0, 0.0, 1.0 , 0.0,
0.0, 0.0, 0.0 , 1.0
);
gl_Position = frame_info.mvp
* glyph_info.position
* scale
* vec4(unit_vertex, 0.0, 1.0);
v_unit_vertex = unit_vertex;
v_atlas_position = glyph_info.atlas_position;
v_atlas_glyph_size = glyph_info.atlas_glyph_size;
v_atlas_size = frame_info.atlas_size;
}

View File

@@ -26,6 +26,9 @@ test_fixtures("file_fixtures") {
"boston.jpg",
"embarcadero.jpg",
"kalimba.jpg",
"//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf",
"//flutter/third_party/txt/third_party/fonts/NotoColorEmoji.ttf",
"//flutter/third_party/txt/third_party/fonts/HomemadeApple.ttf",
]
}

View File

@@ -5,6 +5,7 @@
#pragma once
#include <cstdlib>
#include <ostream>
#include "impeller/geometry/scalar.h"
@@ -683,3 +684,13 @@ struct ColorHSB {
static_assert(sizeof(Color) == 4 * sizeof(Scalar));
} // namespace impeller
namespace std {
inline std::ostream& operator<<(std::ostream& out, const impeller::Color& c) {
out << "(" << c.red << ", " << c.green << ", " << c.blue << ", " << c.alpha
<< ")";
return out;
}
} // namespace std

View File

@@ -92,6 +92,22 @@ struct TRect {
constexpr bool IsEmpty() const { return size.IsEmpty(); }
constexpr auto GetLeft() const {
return std::min(origin.x, origin.x + size.width);
}
constexpr auto GetTop() const {
return std::min(origin.y, origin.y + size.height);
}
constexpr auto GetRight() const {
return std::max(origin.x, origin.x + size.width);
}
constexpr auto GetBottom() const {
return std::max(origin.y, origin.y + size.height);
}
constexpr std::array<T, 4> GetLTRB() const {
const auto left = std::min(origin.x, origin.x + size.width);
const auto top = std::min(origin.y, origin.y + size.height);

View File

@@ -29,6 +29,10 @@ struct TSize {
: TSize(static_cast<Type>(other.width), static_cast<Type>(other.height)) {
}
static constexpr TSize MakeWH(Type width, Type height) {
return TSize{width, height};
}
static constexpr TSize Infinite() {
return TSize{std::numeric_limits<Type>::max(),
std::numeric_limits<Type>::max()};

View File

@@ -49,7 +49,8 @@ ShaderLibraryMappingsForPlayground() {
}
Playground::Playground()
: renderer_(ContextMTL::Create(ShaderLibraryMappingsForPlayground())) {}
: renderer_(ContextMTL::Create(ShaderLibraryMappingsForPlayground(),
"Playground Library")) {}
Playground::~Playground() = default;

View File

@@ -8,7 +8,6 @@ impeller_component("renderer") {
metal_backend_sources = [
"backend/metal/allocator_mtl.h",
"backend/metal/allocator_mtl.mm",
"backend/metal/backend_cast.h",
"backend/metal/command_buffer_mtl.h",
"backend/metal/command_buffer_mtl.mm",
"backend/metal/context_mtl.h",

View File

@@ -10,8 +10,8 @@
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/metal/allocator_mtl.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/renderer/backend/metal/command_buffer_mtl.h"
#include "impeller/renderer/backend/metal/pipeline_library_mtl.h"
#include "impeller/renderer/backend/metal/shader_library_mtl.h"
@@ -27,7 +27,8 @@ class ContextMTL final : public Context,
const std::vector<std::string>& shader_library_paths);
static std::shared_ptr<Context> Create(
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data);
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::string& label);
// |Context|
~ContextMTL() override;

View File

@@ -105,7 +105,8 @@ static NSArray<id<MTLLibrary>>* MTLShaderLibraryFromFilePaths(
static NSArray<id<MTLLibrary>>* MTLShaderLibraryFromFileData(
id<MTLDevice> device,
const std::vector<std::shared_ptr<fml::Mapping>>& libraries_data) {
const std::vector<std::shared_ptr<fml::Mapping>>& libraries_data,
const std::string& label) {
NSMutableArray<id<MTLLibrary>>* found_libraries = [NSMutableArray array];
for (const auto& library_data : libraries_data) {
if (library_data == nullptr) {
@@ -159,10 +160,12 @@ std::shared_ptr<Context> ContextMTL::Create(
}
std::shared_ptr<Context> ContextMTL::Create(
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data) {
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::string& label) {
auto device = CreateMetalDevice();
auto context = std::shared_ptr<ContextMTL>(new ContextMTL(
device, MTLShaderLibraryFromFileData(device, shader_libraries_data)));
device,
MTLShaderLibraryFromFileData(device, shader_libraries_data, label)));
if (!context->IsValid()) {
FML_LOG(ERROR) << "Could not create Metal context.";
return nullptr;

View File

@@ -7,7 +7,7 @@
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/device_buffer.h"
namespace impeller {

View File

@@ -21,6 +21,8 @@ constexpr PixelFormat FromMTLPixelFormat(MTLPixelFormat format) {
switch (format) {
case MTLPixelFormatInvalid:
return PixelFormat::kUnknown;
case MTLPixelFormatR8Unorm:
return PixelFormat::kR8UNormInt;
case MTLPixelFormatBGRA8Unorm:
return PixelFormat::kB8G8R8A8UNormInt;
case MTLPixelFormatBGRA8Unorm_sRGB:
@@ -41,6 +43,8 @@ constexpr MTLPixelFormat ToMTLPixelFormat(PixelFormat format) {
switch (format) {
case PixelFormat::kUnknown:
return MTLPixelFormatInvalid;
case PixelFormat::kR8UNormInt:
return MTLPixelFormatR8Unorm;
case PixelFormat::kB8G8R8A8UNormInt:
return MTLPixelFormatBGRA8Unorm;
case PixelFormat::kB8G8R8A8UNormIntSRGB:

View File

@@ -7,7 +7,7 @@
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/pipeline.h"
namespace impeller {

View File

@@ -136,6 +136,7 @@ RenderPassMTL::RenderPassMTL(id<MTLCommandBuffer> buffer, RenderTarget target)
if (!buffer_ || !desc_ || !render_target_.IsValid()) {
return;
}
SetLabel("RenderPass");
is_valid_ = true;
}

View File

@@ -10,7 +10,7 @@
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/comparable.h"
#include "impeller/renderer/sampler_descriptor.h"
#include "impeller/renderer/sampler_library.h"

View File

@@ -28,6 +28,11 @@ std::shared_ptr<const Sampler> SamplerLibraryMTL::GetSampler(
desc.sAddressMode = MTLSamplerAddressMode(descriptor.width_address_mode);
desc.rAddressMode = MTLSamplerAddressMode(descriptor.depth_address_mode);
desc.tAddressMode = MTLSamplerAddressMode(descriptor.height_address_mode);
if (!descriptor.label.empty()) {
desc.label = @(descriptor.label.c_str());
}
auto mtl_sampler = [device_ newSamplerStateWithDescriptor:desc];
if (!mtl_sampler) {
return nullptr;

View File

@@ -7,7 +7,7 @@
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/sampler.h"
namespace impeller {

View File

@@ -7,7 +7,7 @@
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/shader_function.h"
namespace impeller {

View File

@@ -52,7 +52,7 @@ std::unique_ptr<Surface> SurfaceMTL::WrapCurrentMetalLayerDrawable(
return nullptr;
}
msaa_tex->SetLabel("ImpellerOnscreenColor4xMSAA");
msaa_tex->SetLabel("ImpellerOnscreenColorMSAA");
TextureDescriptor color0_resolve_tex_desc;
color0_resolve_tex_desc.format = color_format;

View File

@@ -7,7 +7,7 @@
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/texture.h"
namespace impeller {

View File

@@ -7,7 +7,7 @@
#include <set>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/backend_cast.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/vertex_descriptor.h"
namespace impeller {

View File

@@ -48,6 +48,7 @@ class Texture;
///
enum class PixelFormat {
kUnknown,
kR8UNormInt,
kR8G8B8A8UNormInt,
kR8G8B8A8UNormIntSRGB,
kB8G8R8A8UNormInt,
@@ -193,6 +194,7 @@ constexpr size_t BytesPerPixelForPixelFormat(PixelFormat format) {
switch (format) {
case PixelFormat::kUnknown:
return 0u;
case PixelFormat::kR8UNormInt:
case PixelFormat::kS8UInt:
return 1u;
case PixelFormat::kR8G8B8A8UNormInt:

View File

@@ -21,6 +21,8 @@ struct SamplerDescriptor final : public Comparable<SamplerDescriptor> {
SamplerAddressMode height_address_mode = SamplerAddressMode::kClampToEdge;
SamplerAddressMode depth_address_mode = SamplerAddressMode::kClampToEdge;
std::string label = "NN Clamp Sampler";
// Comparable<SamplerDescriptor>
std::size_t GetHash() const override {
return fml::HashCombine(min_filter, mag_filter, width_address_mode,

View File

@@ -0,0 +1,50 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/impeller/tools/impeller.gni")
impeller_component("typographer") {
sources = [
"backends/skia/text_frame_skia.cc",
"backends/skia/text_frame_skia.h",
"backends/skia/text_render_context_skia.cc",
"backends/skia/text_render_context_skia.h",
"backends/skia/typeface_skia.cc",
"backends/skia/typeface_skia.h",
"font.cc",
"font.h",
"font_glyph_pair.cc",
"font_glyph_pair.h",
"glyph.cc",
"glyph.h",
"glyph_atlas.cc",
"glyph_atlas.h",
"text_frame.cc",
"text_frame.h",
"text_render_context.cc",
"text_render_context.h",
"text_run.cc",
"text_run.h",
"typeface.cc",
"typeface.h",
]
public_deps = [
"../base",
"../geometry",
"../renderer",
"//third_party/skia",
]
}
impeller_component("typographer_unittests") {
testonly = true
sources = [ "typographer_unittests.cc" ]
deps = [
":typographer",
"../playground",
]
}

View File

@@ -0,0 +1,69 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/backends/skia/text_frame_skia.h"
#include "flutter/fml/logging.h"
#include "impeller/typographer/backends/skia/typeface_skia.h"
#include "third_party/skia/include/core/SkFont.h"
#include "third_party/skia/include/core/SkFontMetrics.h"
#include "third_party/skia/src/core/SkTextBlobPriv.h" // nogncheck
namespace impeller {
static Font ToFont(const SkFont& font) {
auto typeface = std::make_shared<TypefaceSkia>(font.refTypefaceOrDefault());
SkFontMetrics sk_metrics;
font.getMetrics(&sk_metrics);
Font::Metrics metrics;
metrics.point_size = font.getSize();
metrics.ascent = sk_metrics.fAscent;
metrics.descent = sk_metrics.fDescent;
return Font{std::move(typeface), std::move(metrics)};
}
TextFrame TextFrameFromTextBlob(sk_sp<SkTextBlob> blob) {
if (!blob) {
return {};
}
TextFrame frame;
for (SkTextBlobRunIterator run(blob.get()); !run.done(); run.next()) {
TextRun text_run(ToFont(run.font()));
const auto glyph_count = run.glyphCount();
const auto* glyphs = run.glyphs();
switch (run.positioning()) {
case SkTextBlobRunIterator::kDefault_Positioning:
FML_DLOG(ERROR) << "Unimplemented.";
break;
case SkTextBlobRunIterator::kHorizontal_Positioning:
FML_DLOG(ERROR) << "Unimplemented.";
break;
case SkTextBlobRunIterator::kFull_Positioning:
for (auto i = 0u; i < glyph_count; i++) {
// kFull_Positioning has two scalars per glyph.
const SkPoint* glyph_points = run.points();
const auto* point = glyph_points + i;
text_run.AddGlyph(glyphs[i],
Matrix::MakeTranslation({point->x(), point->y()}));
}
break;
case SkTextBlobRunIterator::kRSXform_Positioning:
FML_DLOG(ERROR) << "Unimplemented.";
break;
default:
FML_DLOG(ERROR) << "Unimplemented.";
continue;
}
frame.AddTextRun(std::move(text_run));
}
return frame;
}
} // namespace impeller

View File

@@ -0,0 +1,15 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/typographer/text_frame.h"
#include "third_party/skia/include/core/SkTextBlob.h"
namespace impeller {
TextFrame TextFrameFromTextBlob(sk_sp<SkTextBlob> blob);
} // namespace impeller

View File

@@ -0,0 +1,252 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/backends/skia/text_render_context_skia.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/allocation.h"
#include "impeller/renderer/allocator.h"
#include "impeller/typographer/backends/skia/typeface_skia.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkFont.h"
#include "third_party/skia/include/core/SkFontMetrics.h"
#include "third_party/skia/include/core/SkRSXform.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/src/core/SkIPoint16.h" //nogncheck
#include "third_party/skia/src/gpu/GrRectanizer.h" //nogncheck
namespace impeller {
TextRenderContextSkia::TextRenderContextSkia(std::shared_ptr<Context> context)
: TextRenderContext(std::move(context)) {}
TextRenderContextSkia::~TextRenderContextSkia() = default;
static FontGlyphPair::Set CollectUniqueFontGlyphPairsSet(
const std::vector<TextRun>& runs) {
FontGlyphPair::Set set;
for (const auto& run : runs) {
auto font = run.GetFont();
for (const auto& glyph_position : run.GetGlyphPositions()) {
set.insert({font, glyph_position.glyph});
}
}
return set;
}
static FontGlyphPair::Vector CollectUniqueFontGlyphPairs(
const std::vector<TextRun>& runs) {
TRACE_EVENT0("impeller", __FUNCTION__);
FontGlyphPair::Vector vector;
auto set = CollectUniqueFontGlyphPairsSet(runs);
vector.reserve(set.size());
for (const auto& item : set) {
vector.emplace_back(std::move(item));
}
return vector;
}
static bool PairsFitInAtlasOfSize(const FontGlyphPair::Vector& pairs,
size_t atlas_size,
std::vector<Rect>& glyph_positions) {
if (atlas_size == 0u) {
return false;
}
auto rect_packer = std::unique_ptr<GrRectanizer>(
GrRectanizer::Factory(atlas_size, atlas_size));
glyph_positions.clear();
glyph_positions.reserve(pairs.size());
for (const auto& pair : pairs) {
auto glyph_size = pair.font.GetGlyphSize();
if (!glyph_size.has_value()) {
continue;
}
SkIPoint16 location_in_atlas;
if (!rect_packer->addRect(glyph_size->width, //
glyph_size->height, //
&location_in_atlas //
)) {
return false;
}
glyph_positions.emplace_back(Rect::MakeXYWH(location_in_atlas.x(), //
location_in_atlas.y(), //
glyph_size->width, //
glyph_size->height //
));
}
return true;
}
static size_t OptimumAtlasSizeForFontGlyphPairs(
const FontGlyphPair::Vector& pairs,
std::vector<Rect>& glyph_positions) {
static constexpr auto kMinAtlasSize = 8u;
static constexpr auto kMaxAtlasSize = 4096u;
TRACE_EVENT0("impeller", __FUNCTION__);
size_t current_size = kMinAtlasSize;
do {
if (PairsFitInAtlasOfSize(pairs, current_size, glyph_positions)) {
return current_size;
}
current_size = Allocation::NextPowerOfTwoSize(current_size + 1);
} while (current_size <= kMaxAtlasSize);
return 0u;
}
static std::optional<SkBitmap> CreateAtlasBitmap(const GlyphAtlas& atlas,
size_t atlas_size) {
TRACE_EVENT0("impeller", __FUNCTION__);
SkBitmap bitmap;
auto image_info = SkImageInfo::MakeN32Premul(atlas_size, atlas_size);
if (!bitmap.tryAllocPixels(image_info)) {
return std::nullopt;
}
auto surface = SkSurface::MakeRasterDirect(bitmap.pixmap());
if (!surface) {
return std::nullopt;
}
auto canvas = surface->getCanvas();
if (!canvas) {
return std::nullopt;
}
atlas.IterateGlyphs([canvas](const FontGlyphPair& font_glyph,
const Rect& location) -> bool {
const auto position = SkPoint::Make(location.origin.x, location.origin.y);
SkGlyphID glyph_id = font_glyph.glyph.index;
SkFont font(
TypefaceSkia::Cast(*font_glyph.font.GetTypeface()).GetSkiaTypeface(),
font_glyph.font.GetMetrics().point_size);
SkFontMetrics metrics;
font.getMetrics(&metrics);
SkPaint glyph_paint;
glyph_paint.setColor(SK_ColorWHITE);
canvas->drawGlyphs(1u, // count
&glyph_id, // glyphs
&position, // positions
SkPoint::Make(0.0,
-metrics.fAscent), // origin
font, // font
glyph_paint // paint
);
return true;
});
return bitmap;
}
static std::shared_ptr<Texture> UploadGlyphTextureAtlas(
std::shared_ptr<Allocator> allocator,
const SkBitmap& bitmap,
size_t atlas_size) {
TRACE_EVENT0("impeller", __FUNCTION__);
if (!allocator) {
return nullptr;
}
const auto& pixmap = bitmap.pixmap();
TextureDescriptor texture_descriptor;
texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = ISize::MakeWH(atlas_size, atlas_size);
if (pixmap.rowBytes() * pixmap.height() !=
texture_descriptor.GetSizeOfBaseMipLevel()) {
return nullptr;
}
auto texture =
allocator->CreateTexture(StorageMode::kHostVisible, texture_descriptor);
if (!texture || !texture->IsValid()) {
return nullptr;
}
texture->SetLabel("GlyphAtlas");
if (!texture->SetContents(static_cast<const uint8_t*>(pixmap.addr()),
pixmap.rowBytes() * pixmap.height())) {
return nullptr;
}
return texture;
}
std::shared_ptr<GlyphAtlas> TextRenderContextSkia::CreateGlyphAtlas(
const TextFrame& frame) const {
TRACE_EVENT0("impeller", __FUNCTION__);
if (!IsValid()) {
return nullptr;
}
auto glyph_atlas = std::make_shared<GlyphAtlas>();
// ---------------------------------------------------------------------------
// Step 1: Collect unique font-glyph pairs in the frame.
// ---------------------------------------------------------------------------
auto font_glyph_pairs = CollectUniqueFontGlyphPairs(frame.GetRuns());
if (font_glyph_pairs.empty()) {
return glyph_atlas;
}
// ---------------------------------------------------------------------------
// Step 2: Get the optimum size of the texture atlas.
// ---------------------------------------------------------------------------
std::vector<Rect> glyph_positions;
const auto atlas_size =
OptimumAtlasSizeForFontGlyphPairs(font_glyph_pairs, glyph_positions);
if (atlas_size == 0u) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 3: Find location of font-glyph pairs in the atlas. We have this from
// the last step. So no need to do create another rect packer. But just do a
// sanity check of counts. This could also be just an assertion as only a
// construction issue would cause such a failure.
// ---------------------------------------------------------------------------
if (glyph_positions.size() != font_glyph_pairs.size()) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 4: Record the positions in the glyph atlas.
// ---------------------------------------------------------------------------
for (size_t i = 0, count = glyph_positions.size(); i < count; i++) {
glyph_atlas->AddTypefaceGlyphPosition(font_glyph_pairs[i],
glyph_positions[i]);
}
// ---------------------------------------------------------------------------
// Step 5: Draw font-glyph pairs in the correct spot in the atlas.
// ---------------------------------------------------------------------------
auto bitmap = CreateAtlasBitmap(*glyph_atlas, atlas_size);
if (!bitmap.has_value()) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 6: Upload the atlas as a texture.
// ---------------------------------------------------------------------------
auto texture = UploadGlyphTextureAtlas(GetContext()->GetTransientsAllocator(),
bitmap.value(), atlas_size);
if (!texture) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 7: Record the texture in the glyph atlas.
// ---------------------------------------------------------------------------
glyph_atlas->SetTexture(std::move(texture));
return glyph_atlas;
}
} // namespace impeller

View File

@@ -0,0 +1,26 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/typographer/text_render_context.h"
namespace impeller {
class TextRenderContextSkia : public TextRenderContext {
public:
TextRenderContextSkia(std::shared_ptr<Context> context);
~TextRenderContextSkia() override;
// |TextRenderContext|
std::shared_ptr<GlyphAtlas> CreateGlyphAtlas(
const TextFrame& frame) const override;
private:
FML_DISALLOW_COPY_AND_ASSIGN(TextRenderContextSkia);
};
} // namespace impeller

View File

@@ -0,0 +1,46 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/backends/skia/typeface_skia.h"
namespace impeller {
TypefaceSkia::TypefaceSkia(sk_sp<SkTypeface> typeface)
: typeface_(std::move(typeface)) {}
TypefaceSkia::~TypefaceSkia() = default;
bool TypefaceSkia::IsValid() const {
return !!typeface_;
}
std::size_t TypefaceSkia::GetHash() const {
if (!IsValid()) {
return 0u;
}
return reinterpret_cast<size_t>(typeface_.get());
}
bool TypefaceSkia::IsEqual(const Typeface& other) const {
auto sk_other = reinterpret_cast<const TypefaceSkia*>(&other);
return sk_other->typeface_ == typeface_;
}
Rect TypefaceSkia::GetBoundingBox() const {
if (!IsValid()) {
return {};
}
const auto bounds = typeface_->getBounds();
return Rect::MakeLTRB(bounds.left(), bounds.top(), bounds.right(),
bounds.bottom());
}
const sk_sp<SkTypeface>& TypefaceSkia::GetSkiaTypeface() const {
return typeface_;
}
} // namespace impeller

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/typographer/typeface.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace impeller {
class TypefaceSkia final : public Typeface,
public BackendCast<TypefaceSkia, Typeface> {
public:
TypefaceSkia(sk_sp<SkTypeface> typeface);
~TypefaceSkia() override;
// |Typeface|
bool IsValid() const override;
// |Comparable<Typeface>|
std::size_t GetHash() const override;
// |Comparable<Typeface>|
bool IsEqual(const Typeface& other) const override;
// |Typeface|
Rect GetBoundingBox() const override;
const sk_sp<SkTypeface>& GetSkiaTypeface() const;
private:
sk_sp<SkTypeface> typeface_;
FML_DISALLOW_COPY_AND_ASSIGN(TypefaceSkia);
};
} // namespace impeller

View File

@@ -0,0 +1,48 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/font.h"
namespace impeller {
Font::Font(std::shared_ptr<Typeface> typeface, Metrics metrics)
: typeface_(std::move(typeface)), metrics_(std::move(metrics)) {
if (!typeface_) {
return;
}
is_valid_ = true;
}
Font::~Font() = default;
bool Font::IsValid() const {
return is_valid_;
}
const std::shared_ptr<Typeface>& Font::GetTypeface() const {
return typeface_;
}
std::size_t Font::GetHash() const {
return fml::HashCombine(is_valid_, typeface_ ? typeface_->GetHash() : 0u,
metrics_);
}
bool Font::IsEqual(const Font& other) const {
return DeepComparePointer(typeface_, other.typeface_) &&
is_valid_ == other.is_valid_ && metrics_ == other.metrics_;
}
std::optional<ISize> Font::GetGlyphSize() const {
if (!IsValid()) {
return std::nullopt;
}
return ISize::Ceil(typeface_->GetBoundingBox().size * metrics_.point_size);
}
const Font::Metrics& Font::GetMetrics() const {
return metrics_;
}
} // namespace impeller

View File

@@ -0,0 +1,96 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "impeller/renderer/comparable.h"
#include "impeller/typographer/glyph.h"
#include "impeller/typographer/typeface.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Describes a typeface along with any modifications to its
/// intrinsic properties.
///
class Font : public Comparable<Font> {
public:
//----------------------------------------------------------------------------
/// @brief Describes the modifications made to the intrinsic properties
/// of a typeface.
///
/// The coordinate system of a font has its origin at (0, 0) on
/// the baseline with an upper-left-origin coordinate system.
///
struct Metrics {
//--------------------------------------------------------------------------
/// The point size of the font.
///
Scalar point_size = 12.0f;
//--------------------------------------------------------------------------
/// The font ascent relative to the baseline. This is usually negative as
/// moving upwards (ascending) in an upper-left-origin coordinate system
/// yields smaller numbers.
///
Scalar ascent = 0.0f;
//--------------------------------------------------------------------------
/// The font descent relative to the baseline. This is usually positive as
/// moving downwards (descending) in an upper-left-origin coordinate system
/// yields larger numbers.
///
Scalar descent = 0.0f;
constexpr bool operator==(const Metrics& o) const {
return point_size == o.point_size && ascent == o.ascent &&
descent == o.descent;
}
};
Font(std::shared_ptr<Typeface> typeface, Metrics metrics);
~Font();
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief The typeface whose intrinsic properties this font modifies.
///
/// @return The typeface.
///
const std::shared_ptr<Typeface>& GetTypeface() const;
//----------------------------------------------------------------------------
/// @brief A conservatively large scaled bounding box of all glyphs in
/// this font.
///
/// @return The scaled glyph size.
///
std::optional<ISize> GetGlyphSize() const;
const Metrics& GetMetrics() const;
// |Comparable<Font>|
std::size_t GetHash() const override;
// |Comparable<Font>|
bool IsEqual(const Font& other) const override;
private:
std::shared_ptr<Typeface> typeface_;
Metrics metrics_ = {};
bool is_valid_ = false;
};
} // namespace impeller
template <>
struct std::hash<impeller::Font::Metrics> {
constexpr std::size_t operator()(const impeller::Font::Metrics& m) const {
return fml::HashCombine(m.point_size, m.ascent, m.descent);
}
};

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/font_glyph_pair.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,44 @@
// 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 <optional>
#include <unordered_set>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/geometry/size.h"
#include "impeller/typographer/font.h"
#include "impeller/typographer/glyph.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A font along with a glyph in that font. Used in glyph atlases as
/// keys.
///
struct FontGlyphPair {
struct Hash;
struct Equal;
using Set = std::unordered_set<FontGlyphPair, Hash, Equal>;
using Vector = std::vector<FontGlyphPair>;
Font font;
Glyph glyph;
struct Hash {
std::size_t operator()(const FontGlyphPair& p) const {
return fml::HashCombine(p.font.GetHash(), p.glyph);
}
};
struct Equal {
bool operator()(const FontGlyphPair& lhs, const FontGlyphPair& rhs) const {
return lhs.font.IsEqual(rhs.font) && lhs.glyph.index == rhs.glyph.index;
}
};
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/glyph.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,38 @@
// 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 <cstdint>
#include <functional>
#include "flutter/fml/macros.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief The glyph index in the typeface.
///
struct Glyph {
uint16_t index = 0;
Glyph(uint16_t p_index) : index(p_index) {}
};
} // namespace impeller
template <>
struct std::hash<impeller::Glyph> {
constexpr std::size_t operator()(const impeller::Glyph& g) const {
return g.index;
}
};
template <>
struct std::less<impeller::Glyph> {
constexpr bool operator()(const impeller::Glyph& lhs,
const impeller::Glyph& rhs) const {
return lhs.index < rhs.index;
}
};

View File

@@ -0,0 +1,59 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/glyph_atlas.h"
namespace impeller {
GlyphAtlas::GlyphAtlas() = default;
GlyphAtlas::~GlyphAtlas() = default;
bool GlyphAtlas::IsValid() const {
return !!texture_;
}
const std::shared_ptr<Texture>& GlyphAtlas::GetTexture() const {
return texture_;
}
void GlyphAtlas::SetTexture(std::shared_ptr<Texture> texture) {
texture_ = std::move(texture);
}
void GlyphAtlas::AddTypefaceGlyphPosition(FontGlyphPair pair, Rect rect) {
positions_[pair] = rect;
}
std::optional<Rect> GlyphAtlas::FindFontGlyphPosition(
const FontGlyphPair& pair) const {
auto found = positions_.find(pair);
if (found == positions_.end()) {
return std::nullopt;
}
return found->second;
}
size_t GlyphAtlas::GetGlyphCount() const {
return positions_.size();
}
size_t GlyphAtlas::IterateGlyphs(
std::function<bool(const FontGlyphPair& pair, const Rect& rect)> iterator)
const {
if (!iterator) {
return 0u;
}
size_t count = 0u;
for (const auto& position : positions_) {
count++;
if (!iterator(position.first, position.second)) {
return count;
}
}
return count;
}
} // namespace impeller

View File

@@ -0,0 +1,99 @@
// 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 <functional>
#include <memory>
#include <optional>
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/texture.h"
#include "impeller/typographer/font_glyph_pair.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A texture containing the bitmap representation of glyphs in
/// different fonts along with the ability to query the location of
/// specific font glyphs within the texture.
///
class GlyphAtlas {
public:
//----------------------------------------------------------------------------
/// @brief Create an empty glyph atlas.
///
GlyphAtlas();
~GlyphAtlas();
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Set the texture for the glyph atlas.
///
/// @param[in] texture The texture
///
void SetTexture(std::shared_ptr<Texture> texture);
//----------------------------------------------------------------------------
/// @brief Get the texture for the glyph atlas.
///
/// @return The texture.
///
const std::shared_ptr<Texture>& GetTexture() const;
//----------------------------------------------------------------------------
/// @brief Record there location of a specific font-glyph pair within the
/// atlas.
///
/// @param[in] pair The font-glyph pair
/// @param[in] rect The rectangle
///
void AddTypefaceGlyphPosition(FontGlyphPair pair, Rect rect);
//----------------------------------------------------------------------------
/// @brief Get the number of unique font-glyph pairs in this atlas.
///
/// @return The glyph count.
///
size_t GetGlyphCount() const;
//----------------------------------------------------------------------------
/// @brief Iterate of all the glyphs along with their locations in the
/// atlas.
///
/// @param[in] iterator The iterator. Return `false` from the iterator to
/// stop iterating.
///
/// @return The number of glyphs iterated over.
///
size_t IterateGlyphs(std::function<bool(const FontGlyphPair& pair,
const Rect& rect)> iterator) const;
//----------------------------------------------------------------------------
/// @brief Find the location of a specific font-glyph pair in the atlas.
///
/// @param[in] pair The font-glyph pair
///
/// @return The location of the font-glyph pair in the atlas.
/// `std::nullopt` of the pair in not in the atlas.
///
std::optional<Rect> FindFontGlyphPosition(const FontGlyphPair& pair) const;
private:
std::shared_ptr<Texture> texture_;
std::unordered_map<FontGlyphPair,
Rect,
FontGlyphPair::Hash,
FontGlyphPair::Equal>
positions_;
FML_DISALLOW_COPY_AND_ASSIGN(GlyphAtlas);
};
} // namespace impeller

View File

@@ -0,0 +1,29 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/text_frame.h"
namespace impeller {
TextFrame::TextFrame() = default;
TextFrame::~TextFrame() = default;
bool TextFrame::AddTextRun(TextRun run) {
if (!run.IsValid()) {
return false;
}
runs_.emplace_back(std::move(run));
return true;
}
size_t TextFrame::GetRunCount() const {
return runs_.size();
}
const std::vector<TextRun>& TextFrame::GetRuns() const {
return runs_;
}
} // namespace impeller

View File

@@ -0,0 +1,51 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/typographer/text_run.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Represents a collection of shaped text runs.
///
/// This object is typically the entrypoint in the Impeller type
/// rendering subsystem.
///
class TextFrame {
public:
TextFrame();
~TextFrame();
//----------------------------------------------------------------------------
/// @brief The number of runs in this text frame.
///
/// @return The run count.
///
size_t GetRunCount() const;
//----------------------------------------------------------------------------
/// @brief Adds a new text run to the text frame.
///
/// @param[in] run The run
///
/// @return If the text run could be added to this frame.
///
bool AddTextRun(TextRun run);
//----------------------------------------------------------------------------
/// @brief Returns a reference to all the text runs in this frame.
///
/// @return The runs in this frame.
///
const std::vector<TextRun>& GetRuns() const;
private:
std::vector<TextRun> runs_;
};
} // namespace impeller

View File

@@ -0,0 +1,27 @@
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/text_render_context.h"
namespace impeller {
TextRenderContext::TextRenderContext(std::shared_ptr<Context> context)
: context_(std::move(context)) {
if (!context_ || !context_->IsValid()) {
return;
}
is_valid_ = true;
}
TextRenderContext::~TextRenderContext() = default;
bool TextRenderContext::IsValid() const {
return is_valid_;
}
const std::shared_ptr<Context>& TextRenderContext::GetContext() const {
return context_;
}
} // namespace impeller

View File

@@ -0,0 +1,63 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/renderer/context.h"
#include "impeller/typographer/glyph_atlas.h"
#include "impeller/typographer/text_frame.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief The graphics context necessary to render text.
///
/// This is necessary to create and reference resources related to
/// rendering text on the GPU.
///
/// It is caller responsibility to create as few of these and keep
/// these around for as long possible.
///
class TextRenderContext {
public:
//----------------------------------------------------------------------------
/// @brief Create a new context to render text that talks to an
/// underlying graphics context.
///
/// @param[in] context The graphics context
///
TextRenderContext(std::shared_ptr<Context> context);
virtual ~TextRenderContext();
virtual bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Get the underlying graphics context.
///
/// @return The context.
///
const std::shared_ptr<Context>& GetContext() const;
//----------------------------------------------------------------------------
/// @brief Create a new glyph atlas for the specified text frame.
///
/// @param[in] frame The text frame
///
/// @return A valid glyph atlas or null.
///
virtual std::shared_ptr<GlyphAtlas> CreateGlyphAtlas(
const TextFrame& frame) const = 0;
private:
std::shared_ptr<Context> context_;
bool is_valid_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(TextRenderContext);
};
} // namespace impeller

View File

@@ -0,0 +1,39 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/text_run.h"
namespace impeller {
TextRun::TextRun(Font font) : font_(std::move(font)) {
if (!font.IsValid()) {
return;
}
is_valid_ = true;
}
TextRun::~TextRun() = default;
bool TextRun::AddGlyph(Glyph glyph, Matrix position) {
glyphs_.emplace_back(GlyphPosition{glyph, position});
return true;
}
bool TextRun::IsValid() const {
return is_valid_;
}
const std::vector<TextRun::GlyphPosition>& TextRun::GetGlyphPositions() const {
return glyphs_;
}
size_t TextRun::GetGlyphCount() const {
return glyphs_.size();
}
const Font& TextRun::GetFont() const {
return font_;
}
} // namespace impeller

View File

@@ -0,0 +1,77 @@
// 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 <vector>
#include "impeller/geometry/matrix.h"
#include "impeller/typographer/font.h"
#include "impeller/typographer/glyph.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Represents a collection of positioned glyphs from a specific
/// font.
///
class TextRun {
public:
struct GlyphPosition {
Glyph glyph;
Matrix position;
GlyphPosition(Glyph p_glyph, Matrix p_position)
: glyph(p_glyph), position(p_position) {}
};
//----------------------------------------------------------------------------
/// @brief Create an empty text run with the specified font.
///
/// @param[in] font The font
///
TextRun(Font font);
~TextRun();
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Add a glyph at the specified position to the run.
///
/// @param[in] glyph The glyph
/// @param[in] position The position
///
/// @return If the glyph could be added to the run.
///
bool AddGlyph(Glyph glyph, Matrix position);
//----------------------------------------------------------------------------
/// @brief Get the number of glyphs in the run.
///
/// @return The glyph count.
///
size_t GetGlyphCount() const;
//----------------------------------------------------------------------------
/// @brief Get a reference to all the glyph positions within the run.
///
/// @return The glyph positions.
///
const std::vector<GlyphPosition>& GetGlyphPositions() const;
//----------------------------------------------------------------------------
/// @brief Get the font for this run.
///
/// @return The font.
///
const Font& GetFont() const;
private:
Font font_;
std::vector<GlyphPosition> glyphs_;
bool is_valid_ = false;
};
} // namespace impeller

View File

@@ -0,0 +1,13 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/typeface.h"
namespace impeller {
Typeface::Typeface() = default;
Typeface::~Typeface() = default;
} // namespace impeller

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/comparable.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A typeface, usually obtained from a font-file, on disk describes
/// the intrinsic properties of the font. Typefaces are rarely used
/// directly. Instead, font refer to typefaces along with any
/// modifications applied to its intrinsic properties.
///
class Typeface : public Comparable<Typeface> {
public:
Typeface();
virtual ~Typeface();
virtual bool IsValid() const = 0;
//----------------------------------------------------------------------------
/// @brief Get the union of the bounding boxes of all glyphs in the
/// typeface. This box is unit-scaled and conservatively large to
/// cover all glyphs.
///
/// @return The conservative unit-scaled bounding box.
///
virtual Rect GetBoundingBox() const = 0;
private:
FML_DISALLOW_COPY_AND_ASSIGN(Typeface);
};
} // namespace impeller

View File

@@ -0,0 +1,46 @@
// 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/testing/testing.h"
#include "impeller/playground/playground.h"
#include "impeller/typographer/backends/skia/text_frame_skia.h"
#include "impeller/typographer/backends/skia/text_render_context_skia.h"
#include "third_party/skia/include/core/SkTextBlob.h"
namespace impeller {
namespace testing {
using TypographerTest = Playground;
TEST_F(TypographerTest, CanConvertTextBlob) {
SkFont font;
auto blob = SkTextBlob::MakeFromString(
"the quick brown fox jumped over the lazy dog.", font);
ASSERT_TRUE(blob);
auto frame = TextFrameFromTextBlob(blob);
ASSERT_EQ(frame.GetRunCount(), 1u);
for (const auto& run : frame.GetRuns()) {
ASSERT_TRUE(run.IsValid());
ASSERT_EQ(run.GetGlyphCount(), 45u);
}
}
TEST_F(TypographerTest, CanCreateRenderContext) {
auto context = std::make_shared<TextRenderContextSkia>(GetContext());
ASSERT_TRUE(context->IsValid());
}
TEST_F(TypographerTest, CanCreateGlyphAtlas) {
auto context = std::make_shared<TextRenderContextSkia>(GetContext());
ASSERT_TRUE(context->IsValid());
SkFont sk_font;
auto blob = SkTextBlob::MakeFromString("hello", sk_font);
ASSERT_TRUE(blob);
auto atlas = context->CreateGlyphAtlas(TextFrameFromTextBlob(blob));
ASSERT_NE(atlas, nullptr);
OpenPlaygroundHere([](auto&) { return true; });
}
} // namespace testing
} // namespace impeller