Skip to content

Commit

Permalink
refactor!: Simplify text rendering pipeline (#2663)
Browse files Browse the repository at this point in the history
While studying the existing text rendering pipeline and infrastructure, in order to better document it and add some easier user-facing ways to render rich text, I found it to be on a slightly overcomplicated state that seems to me to be an artifact of a migration.

Let me first briefly describe how it works with some diagrams (I am writing docs for everything and will re-use this content but wanted to propose this PR first as it will change how things look like).

We have 3 hierarchies related to rendering:

    renderers: children of TextRenderer, these define how to render text (style). do not include text
    formatters: children of TextFormatter, this also define how to render text (style), but a bit more higher level than TextRenderer.
    elements: these are laid-out, styled and ready-render pieces of text (style + string), created by formatters

Note that the renderers and formatters kinda serve the same purpose, but the renderers are a more low-level API. Here is how it it looks like today:

Not only that but all of our TextRenderer are actually FormatterTextRenderer, which just use a formatter to "comply" with the "renderer" interface. There are no "raw" TextRenderers anymore.

This current structure seems to clearly derive from an unfinished transition into the new, higher level and more flexible "formatter" structure while still supporting the "renderers" while we transition. That transition, though, seems to have completed.

The current state makes things more complicated as our current versions of components (TextComponent and TextBoxComponent), specifically the former, have branching code to support both the raw TextRenderer and the specific FormatterTextRenderer implementation, which breaks the inheritance encapsulation and voids its purpose in the first place.

The purpose of this PR is to simplify this class structure by:

    remove the base TextRenderer
    rename FormatterTextRenderer to TextRenderer: all renderers are formatter-based now
    update all references
    simplify the code of the components by only dealing with (former FormatterTextRenderer) TextRenderers

This is what it looks like now:

Note that while this is a breaking change, it should not affect most users as they should be using much more user-facing classes, like the aforementioned components, instead of the backing implementations. In fact even if they use the renderers, they probably use one of the concrete implementations anyway, TextPaint or SpriteFontRenderer. Notwithstanding, I added migration instructions below.

This is a small step towards a world where we completely combine the converts of renderers and formatters, as, in my eyes, they do the same thing (carry the style information w/o the text).

Possible future (but definitely breaking) changes:

    remove renderers entirely and use formatters directly
    consider renaming formatters to renderers (or not)
    rename TextPaint as the name does not make sense in any hierarchical model we use
    (what I am really interested in): allow the creation of text_ and text_box_ components directly from renderers + elements
  • Loading branch information
luanpotter authored Aug 24, 2023
1 parent d172146 commit 34f69b9
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 115 deletions.
44 changes: 24 additions & 20 deletions packages/flame/lib/src/components/text_box_component.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:math' as math;
import 'dart:math';
import 'dart:ui';

import 'package:collection/collection.dart';
Expand Down Expand Up @@ -133,18 +134,18 @@ class TextBoxComponent<T extends TextRenderer> extends TextComponent {
@internal
void updateBounds() {
lines.clear();
double? lineHeight;
var lineHeight = 0.0;
final maxBoxWidth = _fixedSize ? width : _boxConfig.maxWidth;
text.split(' ').forEach((word) {
final wordLines = word.split('\n');
final possibleLine =
lines.isEmpty ? wordLines[0] : '${lines.last} ${wordLines[0]}';
lineHeight ??= textRenderer.measureTextHeight(possibleLine);
final metrics = textRenderer.getLineMetrics(possibleLine);
lineHeight = max(lineHeight, metrics.height);

final textWidth = textRenderer.measureTextWidth(possibleLine);
_updateMaxWidth(textWidth);
var canAppend = false;
if (textWidth <= maxBoxWidth - _boxConfig.margins.horizontal) {
_updateMaxWidth(metrics.width);
final bool canAppend;
if (metrics.width <= maxBoxWidth - _boxConfig.margins.horizontal) {
canAppend = lines.isNotEmpty;
} else {
canAppend = lines.isNotEmpty && lines.last == '';
Expand All @@ -161,7 +162,7 @@ class TextBoxComponent<T extends TextRenderer> extends TextComponent {
}
});
_totalLines = lines.length;
_lineHeight = lineHeight ?? 0.0;
_lineHeight = lineHeight;
size = _recomputeSize();
}

Expand Down Expand Up @@ -197,9 +198,11 @@ class TextBoxComponent<T extends TextRenderer> extends TextComponent {
}

double getLineWidth(String line, int charCount) {
return textRenderer.measureTextWidth(
line.substring(0, math.min(charCount, line.length)),
);
return textRenderer
.getLineMetrics(
line.substring(0, math.min(charCount, line.length)),
)
.width;
}

Vector2 _recomputeSize() {
Expand Down Expand Up @@ -269,17 +272,18 @@ class TextBoxComponent<T extends TextRenderer> extends TextComponent {
final nChars = math.min(currentChar - charCount, line.length);
line = line.substring(0, nChars);
}
textRenderer.render(
canvas,
line,
Vector2(
boxConfig.margins.left +
(boxWidth - textRenderer.measureTextWidth(line)) * align.x,
boxConfig.margins.top +
(boxHeight - nLines * _lineHeight) * align.y +
i * _lineHeight,
),

final textElement = textRenderer.formatter.format(line);
final metrics = textElement.metrics;

final position = Vector2(
boxConfig.margins.left + (boxWidth - metrics.width) * align.x,
boxConfig.margins.top +
(boxHeight - nLines * _lineHeight) * align.y +
i * _lineHeight,
);
textRenderer.renderElement(canvas, textElement, position, anchor: anchor);

charCount += lines[i].length;
}
}
Expand Down
23 changes: 6 additions & 17 deletions packages/flame/lib/src/components/text_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flame/src/text/elements/text_element.dart';
import 'package:flame/src/text/formatter_text_renderer.dart';
import 'package:flame/src/text/text_renderer.dart';
import 'package:flutter/painting.dart';
import 'package:meta/meta.dart';
Expand Down Expand Up @@ -40,28 +39,18 @@ class TextComponent<T extends TextRenderer> extends PositionComponent {
updateBounds();
}

TextElement? _textElement;
late TextElement _textElement;

@internal
void updateBounds() {
if (_textRenderer is FormatterTextRenderer) {
_textElement =
(_textRenderer as FormatterTextRenderer).formatter.format(_text);
final measurements = _textElement!.metrics;
_textElement!.translate(0, measurements.ascent);
size.setValues(measurements.width, measurements.height);
} else {
final expectedSize = textRenderer.measureText(_text);
size.setValues(expectedSize.x, expectedSize.y);
}
_textElement = _textRenderer.formatter.format(_text);
final measurements = _textElement.metrics;
_textElement.translate(0, measurements.ascent);
size.setValues(measurements.width, measurements.height);
}

@override
void render(Canvas canvas) {
if (_textElement != null) {
_textElement!.render(canvas);
} else {
_textRenderer.render(canvas, text, Vector2.zero());
}
_textElement.render(canvas);
}
}
15 changes: 13 additions & 2 deletions packages/flame/lib/src/text/common/line_metrics.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'dart:ui';
import 'package:flame/extensions.dart';

/// The [LineMetrics] object contains measurements of a text line.
///
Expand All @@ -22,7 +22,9 @@ class LineMetrics {
_width = width,
_ascent = ascent ?? (height == null ? 0 : height - (descent ?? 0)),
_descent =
descent ?? (height == null ? 0 : height - (ascent ?? height));
descent ?? (height == null ? 0 : height - (ascent ?? height)) {
_updateSize();
}

/// X-coordinate of the left edge of the box.
double get left => _left;
Expand Down Expand Up @@ -50,6 +52,9 @@ class LineMetrics {
double get bottom => baseline + descent;
double get height => ascent + descent;

final Vector2 _size = Vector2.zero();
Vector2 get size => _size.clone();

/// Moves the [LineMetrics] box by the specified offset [dx], [dy] leaving its
/// width and height unmodified.
void translate(double dx, double dy) {
Expand All @@ -69,6 +74,7 @@ class LineMetrics {
void setLeftEdge(double x) {
_width = right - x;
_left = x;
_updateSize();
}

/// Appends another [LineMetrics] box that is adjacent to the current and on
Expand All @@ -86,6 +92,11 @@ class LineMetrics {
if (_descent < other.descent) {
_descent = other.descent;
}
_updateSize();
}

void _updateSize() {
_size.setValues(width, height);
}

Rect toRect() => Rect.fromLTWH(left, top, width, height);
Expand Down
34 changes: 0 additions & 34 deletions packages/flame/lib/src/text/formatter_text_renderer.dart

This file was deleted.

4 changes: 1 addition & 3 deletions packages/flame/lib/src/text/sprite_font_renderer.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'dart:ui';

import 'package:flame/src/text/common/sprite_font.dart';
import 'package:flame/src/text/formatter_text_renderer.dart';
import 'package:flame/src/text/formatters/sprite_font_text_formatter.dart';
import 'package:flame/src/text/text_renderer.dart';

Expand All @@ -22,8 +21,7 @@ import 'package:flame/src/text/text_renderer.dart';
/// The `paint` parameter is used to composite the character images onto the
/// canvas. Its default value will draw the character images as-is. Changing
/// the opacity of the paint's color will make the text semi-transparent.
class SpriteFontRenderer
extends FormatterTextRenderer<SpriteFontTextFormatter> {
class SpriteFontRenderer extends TextRenderer<SpriteFontTextFormatter> {
SpriteFontRenderer.fromFont(
SpriteFont font, {
Color? color,
Expand Down
3 changes: 1 addition & 2 deletions packages/flame/lib/src/text/text_paint.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'package:flame/src/cache/memory_cache.dart';
import 'package:flame/src/text/formatter_text_renderer.dart';
import 'package:flame/src/text/formatters/text_painter_text_formatter.dart';
import 'package:flame/src/text/text_renderer.dart';
import 'package:flutter/rendering.dart';
Expand All @@ -10,7 +9,7 @@ import 'package:flutter/rendering.dart';
/// modified dynamically, if you need to change any attribute of the text at
/// runtime, such as color, then create a new [TextPaint] object using
/// [copyWith].
class TextPaint extends FormatterTextRenderer<TextPainterTextFormatter> {
class TextPaint extends TextRenderer<TextPainterTextFormatter> {
TextPaint({
TextStyle? style,
TextDirection? textDirection,
Expand Down
63 changes: 37 additions & 26 deletions packages/flame/lib/src/text/text_renderer.dart
Original file line number Diff line number Diff line change
@@ -1,50 +1,61 @@
import 'dart:ui';

import 'package:flame/src/anchor.dart';
import 'package:flame/src/components/text_box_component.dart';
import 'package:flame/src/components/text_component.dart';
import 'package:flame/src/text/sprite_font_renderer.dart';
import 'package:flame/src/text/text_paint.dart';
import 'package:flame/text.dart';
import 'package:vector_math/vector_math_64.dart';

/// [TextRenderer] is the abstract API for drawing text.
/// [TextRenderer] is the most basic API for drawing text.
///
/// A text renderer usually embodies a particular style for rendering text, such
/// as font-family, color, size, and so on. At the same time, a text renderer
/// is not tied to a specific string -- it can render any text fragment that
/// you give it.
/// A text renderer contains a [formatter] that embodies a particular style
/// for rendering text, such as font-family, color, size, and so on.
/// At the same time, nor the text renderer or the [formatter] are tied to a
/// specific string -- it can render any text fragment that you give it.
///
/// A text renderer object has two functions: to measure the size of a text
/// string that it will have when rendered, and to actually render that string
/// onto a canvas.
///
/// [TextRenderer] is a low-level API that may be somewhat inconvenient to use
/// directly. Instead, consider using components such as [TextComponent] or
/// [TextBoxComponent].
/// directly. Instead, consider using components such as TextComponent or
/// TextBoxComponent.
///
/// The following text renderers are available in Flame:
/// - [TextPaint] which uses the standard Flutter's `TextPainter`;
/// - [SpriteFontRenderer] which uses a spritesheet as a font file;
abstract class TextRenderer {
/// Compute the dimensions of [text] when rendered.
Vector2 measureText(String text);
/// See [TextFormatter] for more information about existing options.
class TextRenderer<T extends TextFormatter> {
TextRenderer(this.formatter);

/// Compute the width of [text] when rendered.
double measureTextWidth(String text) => measureText(text).x;
final T formatter;

/// Compute the height of [text] when rendered.
double measureTextHeight(String text) => measureText(text).y;
TextElement format(String text) {
return formatter.format(text);
}

LineMetrics getLineMetrics(String text) {
return format(text).metrics;
}

/// Renders [text] on the [canvas] at a given [position].
///
/// For example, if [Anchor.center] is specified, it's going to be drawn
/// centered around [position].
void render(
Canvas canvas,
String text,
Vector2 position, {
Anchor anchor = Anchor.topLeft,
});
}) {
final element = format(text);
renderElement(canvas, element, position, anchor: anchor);
}

void renderElement(
Canvas canvas,
TextElement element,
Vector2 position, {
Anchor anchor = Anchor.topLeft,
}) {
final box = element.metrics;
element.translate(
position.x - box.width * anchor.x,
position.y - box.height * anchor.y - box.top,
);
element.render(canvas);
}

/// A registry containing default providers for every [TextRenderer] subclass;
/// used by [createDefault] to create default parameter values.
Expand Down
4 changes: 2 additions & 2 deletions packages/flame/test/components/text_box_component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'dart:ui' hide TextStyle;
import 'package:canvas_test/canvas_test.dart';
import 'package:flame/components.dart';
import 'package:flame/palette.dart';
import 'package:flame/src/text/formatter_text_renderer.dart';
import 'package:flame/text.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';

Expand Down Expand Up @@ -193,7 +193,7 @@ class _FramedTextBox extends TextBoxComponent {
super.position,
super.size,
}) : super(
textRenderer: FormatterTextRenderer(DebugTextFormatter(fontSize: 22)),
textRenderer: TextRenderer(DebugTextFormatter(fontSize: 22)),
);

final Paint _borderPaint = Paint()
Expand Down
25 changes: 17 additions & 8 deletions packages/flame/test/text/text_renderer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,24 @@ void main() {
});
}

class _CustomTextRenderer extends TextRenderer {
class _CustomTextRenderer extends TextRenderer<_CustomTextFormatter> {
_CustomTextRenderer() : super(_CustomTextFormatter());
}

class _CustomTextFormatter extends TextFormatter {
@override
TextElement format(String text) {
return CustomTextElement();
}
}

class CustomTextElement extends TextElement {
@override
LineMetrics get metrics => LineMetrics();

@override
Vector2 measureText(String text) => Vector2.zero();
void render(Canvas canvas) {}

@override
void render(
Canvas canvas,
String text,
Vector2 position, {
Anchor anchor = Anchor.topLeft,
}) {}
void translate(double dx, double dy) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class KawabungaSystem extends BaseSystem with UpdateSystem {
final textComponent = entity.get<TextComponent>()!;
final size = entity.get<SizeComponent>()!.size;
final textRenderer = TextPaint(style: textComponent.style);
size.setFrom(textRenderer.measureText(textComponent.text));
size.setFrom(textRenderer.getLineMetrics(textComponent.text).size);

final timer = entity.get<TimerComponent>()!;
timer.timePassed = timer.timePassed + delta;
Expand Down

0 comments on commit 34f69b9

Please sign in to comment.