Debian Codegraph @

modules/skottie/src/text/TextAdapter.cpp

raw
1 /*
2 * Copyright 2019 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 #include "modules/skottie/src/text/TextAdapter.h"
8
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkColor.h"
11 #include "include/core/SkContourMeasure.h"
12 #include "include/core/SkFont.h"
13 #include "include/core/SkFontMgr.h"
14 #include "include/core/SkM44.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkPath.h"
18 #include "include/core/SkRect.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkSpan.h"
21 #include "include/core/SkString.h"
22 #include "include/core/SkTypes.h"
23 #include "include/private/base/SkTPin.h"
24 #include "include/private/base/SkTo.h"
25 #include "include/utils/SkTextUtils.h"
26 #include "modules/jsonreader/SkJSONReader.h"
27 #include "modules/skottie/include/Skottie.h"
28 #include "modules/skottie/include/SkottieProperty.h"
29 #include "modules/skottie/src/SkottieJson.h"
30 #include "modules/skottie/src/SkottiePriv.h"
31 #include "modules/skottie/src/text/RangeSelector.h" // IWYU pragma: keep
32 #include "modules/skottie/src/text/TextAnimator.h"
33 #include "modules/sksg/include/SkSGDraw.h"
34 #include "modules/sksg/include/SkSGGeometryNode.h"
35 #include "modules/sksg/include/SkSGGroup.h"
36 #include "modules/sksg/include/SkSGPaint.h"
37 #include "modules/sksg/include/SkSGPath.h"
38 #include "modules/sksg/include/SkSGRect.h"
39 #include "modules/sksg/include/SkSGRenderEffect.h"
40 #include "modules/sksg/include/SkSGRenderNode.h"
41 #include "modules/sksg/include/SkSGTransform.h"
42 #include "modules/sksg/src/SkSGTransformPriv.h"
43 #include "modules/skshaper/include/SkShaper_factory.h"
44 #include "src/core/SkPathPriv.h"
45
46 #include <algorithm>
47 #include <cmath>
48 #include <cstddef>
49 #include <limits>
50 #include <tuple>
51 #include <utility>
52
53 namespace sksg {
54 class InvalidationController;
55 }
56
57 // Enable for text layout debugging.
58 #define SHOW_LAYOUT_BOXES 0
59
60 namespace skottie::internal {
61
62 namespace {
63
64 class GlyphTextNode final : public sksg::GeometryNode {
65 public:
66 explicit GlyphTextNode(Shaper::ShapedGlyphs&& glyphs) : fGlyphs(std::move(glyphs)) {}
67
68 ~GlyphTextNode() override = default;
69
70 const Shaper::ShapedGlyphs* glyphs() const { return &fGlyphs; }
71
72 protected:
73 SkRect onRevalidate(sksg::InvalidationController*, const SkMatrix&) override {
74 return fGlyphs.computeBounds(Shaper::ShapedGlyphs::BoundsType::kTight);
75 }
76
77 void onDraw(SkCanvas* canvas, const SkPaint& paint) const override {
78 fGlyphs.draw(canvas, {0,0}, paint);
79 }
80
81 void onClip(SkCanvas* canvas, bool antiAlias) const override {
82 canvas->clipPath(this->asPath(), antiAlias);
83 }
84
85 bool onContains(const SkPoint& p) const override {
86 return this->asPath().contains(p.x(), p.y());
87 }
88
89 SkPath onAsPath() const override {
90 // TODO
91 return SkPath();
92 }
93
94 private:
95 const Shaper::ShapedGlyphs fGlyphs;
96 };
97
98 static float align_factor(SkTextUtils::Align a) {
99 switch (a) {
100 case SkTextUtils::kLeft_Align : return 0.0f;
101 case SkTextUtils::kCenter_Align: return 0.5f;
102 case SkTextUtils::kRight_Align : return 1.0f;
103 }
104
105 SkUNREACHABLE;
106 }
107
108 } // namespace
109
110 class TextAdapter::GlyphDecoratorNode final : public sksg::Group {
111 public:
112 GlyphDecoratorNode(sk_sp<GlyphDecorator> decorator, float scale)
113 : fDecorator(std::move(decorator))
114 , fScale(scale)
115 {}
116
117 ~GlyphDecoratorNode() override = default;
118
119 void updateFragmentData(const std::vector<TextAdapter::FragmentRec>& recs) {
120 fFragCount = recs.size();
121
122 SkASSERT(!fFragInfo);
123 fFragInfo = std::make_unique<FragmentInfo[]>(recs.size());
124
125 for (size_t i = 0; i < recs.size(); ++i) {
126 const auto& rec = recs[i];
127 fFragInfo[i] = {rec.fGlyphs, rec.fMatrixNode, rec.fAdvance};
128 }
129
130 SkASSERT(!fDecoratorInfo);
131 fDecoratorInfo = std::make_unique<GlyphDecorator::GlyphInfo[]>(recs.size());
132 }
133
134 SkRect onRevalidate(sksg::InvalidationController* ic, const SkMatrix& ctm) override {
135 const auto child_bounds = INHERITED::onRevalidate(ic, ctm);
136
137 for (size_t i = 0; i < fFragCount; ++i) {
138 const auto* glyphs = fFragInfo[i].fGlyphs;
139 fDecoratorInfo[i].fBounds =
140 glyphs->computeBounds(Shaper::ShapedGlyphs::BoundsType::kTight);
141 fDecoratorInfo[i].fMatrix = sksg::TransformPriv::As<SkMatrix>(fFragInfo[i].fMatrixNode);
142
143 fDecoratorInfo[i].fCluster = glyphs->fClusters.empty() ? 0 : glyphs->fClusters.front();
144 fDecoratorInfo[i].fAdvance = fFragInfo[i].fAdvance;
145 }
146
147 return child_bounds;
148 }
149
150 void onRender(SkCanvas* canvas, const RenderContext* ctx) const override {
151 auto local_ctx = ScopedRenderContext(canvas, ctx).setIsolation(this->bounds(),
152 canvas->getTotalMatrix(),
153 true);
154 this->INHERITED::onRender(canvas, local_ctx);
155
156 fDecorator->onDecorate(canvas, {
157 SkSpan(fDecoratorInfo.get(), fFragCount),
158 fScale
159 });
160 }
161
162 private:
163 struct FragmentInfo {
164 const Shaper::ShapedGlyphs* fGlyphs;
165 sk_sp<sksg::Matrix<SkM44>> fMatrixNode;
166 float fAdvance;
167 };
168
169 const sk_sp<GlyphDecorator> fDecorator;
170 const float fScale;
171
172 std::unique_ptr<FragmentInfo[]> fFragInfo;
173 std::unique_ptr<GlyphDecorator::GlyphInfo[]> fDecoratorInfo;
174 size_t fFragCount;
175
176 using INHERITED = Group;
177 };
178
179 // Text path semantics
180 //
181 // * glyphs are positioned on the path based on their horizontal/x anchor point, interpreted as
182 // a distance along the path
183 //
184 // * horizontal alignment is applied relative to the path start/end points
185 //
186 // * "Reverse Path" allows reversing the path direction
187 //
188 // * "Perpendicular To Path" determines whether glyphs are rotated to be perpendicular
189 // to the path tangent, or not (just positioned).
190 //
191 // * two controls ("First Margin" and "Last Margin") allow arbitrary offseting along the path,
192 // depending on horizontal alignement:
193 // - left: offset = first margin
194 // - center: offset = first margin + last margin
195 // - right: offset = last margin
196 //
197 // * extranormal path positions (d < 0, d > path len) are allowed
198 // - closed path: the position wraps around in both directions
199 // - open path: extrapolates from extremes' positions/slopes
200 //
201 struct TextAdapter::PathInfo {
202 ShapeValue fPath;
203 ScalarValue fPathFMargin = 0,
204 fPathLMargin = 0,
205 fPathPerpendicular = 0,
206 fPathReverse = 0;
207
208 void updateContourData() {
209 const auto reverse = fPathReverse != 0;
210
211 if (fPath != fCurrentPath || reverse != fCurrentReversed) {
212 // reinitialize cached contour data
213 auto path = static_cast<SkPath>(fPath);
214 if (reverse) {
215 path = SkPathPriv::ReversePath(path);
216 }
217
218 SkContourMeasureIter iter(path, /*forceClosed = */false);
219 fCurrentMeasure = iter.next();
220 fCurrentClosed = path.isLastContourClosed();
221 fCurrentReversed = reverse;
222 fCurrentPath = fPath;
223
224 // AE paths are always single-contour (no moves allowed).
225 SkASSERT(!iter.next());
226 }
227 }
228
229 float pathLength() const {
230 SkASSERT(fPath == fCurrentPath);
231 SkASSERT((fPathReverse != 0) == fCurrentReversed);
232
233 return fCurrentMeasure ? fCurrentMeasure->length() : 0;
234 }
235
236 SkM44 getMatrix(float distance, SkTextUtils::Align alignment) const {
237 SkASSERT(fPath == fCurrentPath);
238 SkASSERT((fPathReverse != 0) == fCurrentReversed);
239
240 if (!fCurrentMeasure) {
241 return SkM44();
242 }
243
244 const auto path_len = fCurrentMeasure->length();
245
246 // First/last margin adjustment also depends on alignment.
247 switch (alignment) {
248 case SkTextUtils::Align::kLeft_Align: distance += fPathFMargin; break;
249 case SkTextUtils::Align::kCenter_Align: distance += fPathFMargin +
250 fPathLMargin; break;
251 case SkTextUtils::Align::kRight_Align: distance += fPathLMargin; break;
252 }
253
254 // For closed paths, extranormal distances wrap around the contour.
255 if (fCurrentClosed) {
256 distance = std::fmod(distance, path_len);
257 if (distance < 0) {
258 distance += path_len;
259 }
260 SkASSERT(0 <= distance && distance <= path_len);
261 }
262
263 SkPoint pos;
264 SkVector tan;
265 if (!fCurrentMeasure->getPosTan(distance, &pos, &tan)) {
266 return SkM44();
267 }
268
269 // For open paths, extranormal distances are extrapolated from extremes.
270 // Note:
271 // - getPosTan above clamps to the extremes
272 // - the extrapolation below only kicks in for extranormal values
273 const auto underflow = std::min(0.0f, distance),
274 overflow = std::max(0.0f, distance - path_len);
275 pos += tan*(underflow + overflow);
276
277 auto m = SkM44::Translate(pos.x(), pos.y());
278
279 // The "perpendicular" flag controls whether fragments are positioned and rotated,
280 // or just positioned.
281 if (fPathPerpendicular != 0) {
282 m = m * SkM44::Rotate({0,0,1}, std::atan2(tan.y(), tan.x()));
283 }
284
285 return m;
286 }
287
288 private:
289 // Cached contour data.
290 ShapeValue fCurrentPath;
291 sk_sp<SkContourMeasure> fCurrentMeasure;
292 bool fCurrentReversed = false,
293 fCurrentClosed = false;
294 };
295
296 sk_sp<TextAdapter> TextAdapter::Make(const skjson::ObjectValue& jlayer,
297 const AnimationBuilder* abuilder,
298 sk_sp<SkFontMgr> fontmgr,
299 sk_sp<CustomFont::GlyphCompMapper> custom_glyph_mapper,
300 sk_sp<Logger> logger,
301 sk_sp<::SkShapers::Factory> factory) {
302 // General text node format:
303 // "t": {
304 // "a": [], // animators (see TextAnimator)
305 // "d": {
306 // "k": [
307 // {
308 // "s": {
309 // "f": "Roboto-Regular",
310 // "fc": [
311 // 0.42,
312 // 0.15,
313 // 0.15
314 // ],
315 // "j": 1,
316 // "lh": 60,
317 // "ls": 0,
318 // "s": 50,
319 // "t": "text align right",
320 // "tr": 0
321 // },
322 // "t": 0
323 // }
324 // ],
325 // "sid": "optionalSlotID"
326 // },
327 // "m": { // more options
328 // "g": 1, // Anchor Point Grouping
329 // "a": {...} // Grouping Alignment
330 // },
331 // "p": { // path options
332 // "a": 0, // force alignment
333 // "f": {}, // first margin
334 // "l": {}, // last margin
335 // "m": 1, // mask index
336 // "p": 1, // perpendicular
337 // "r": 0 // reverse path
338 // }
339
340 // },
341
342 const skjson::ObjectValue* jt = jlayer["t"];
343 const skjson::ObjectValue* jd = jt ? static_cast<const skjson::ObjectValue*>((*jt)["d"])
344 : nullptr;
345 if (!jd) {
346 abuilder->log(Logger::Level::kError, &jlayer, "Invalid text layer.");
347 return nullptr;
348 }
349
350 // "More options"
351 const skjson::ObjectValue* jm = (*jt)["m"];
352 static constexpr AnchorPointGrouping gGroupingMap[] = {
353 AnchorPointGrouping::kCharacter, // 'g': 1
354 AnchorPointGrouping::kWord, // 'g': 2
355 AnchorPointGrouping::kLine, // 'g': 3
356 AnchorPointGrouping::kAll, // 'g': 4
357 };
358 const auto apg = jm
359 ? SkTPin<int>(ParseDefault<int>((*jm)["g"], 1), 1, std::size(gGroupingMap))
360 : 1;
361
362 auto adapter = sk_sp<TextAdapter>(new TextAdapter(std::move(fontmgr),
363 std::move(custom_glyph_mapper),
364 std::move(logger),
365 std::move(factory),
366 gGroupingMap[SkToSizeT(apg - 1)]));
367
368 adapter->bind(*abuilder, jd, adapter->fText.fCurrentValue);
369 if (jm) {
370 adapter->bind(*abuilder, (*jm)["a"], adapter->fGroupingAlignment);
371 }
372
373 // Animators
374 if (const skjson::ArrayValue* janimators = (*jt)["a"]) {
375 adapter->fAnimators.reserve(janimators->size());
376
377 for (const skjson::ObjectValue* janimator : *janimators) {
378 if (auto animator = TextAnimator::Make(janimator, abuilder, adapter.get())) {
379 adapter->fHasBlurAnimator |= animator->hasBlur();
380 adapter->fRequiresAnchorPoint |= animator->requiresAnchorPoint();
381 adapter->fRequiresLineAdjustments |= animator->requiresLineAdjustments();
382
383 adapter->fAnimators.push_back(std::move(animator));
384 }
385 }
386 }
387
388 // Optional text path
389 const auto attach_path = [&](const skjson::ObjectValue* jpath) -> std::unique_ptr<PathInfo> {
390 if (!jpath) {
391 return nullptr;
392 }
393
394 // the actual path is identified as an index in the layer mask stack
395 const auto mask_index =
396 ParseDefault<size_t>((*jpath)["m"], std::numeric_limits<size_t>::max());
397 const skjson::ArrayValue* jmasks = jlayer["masksProperties"];
398 if (!jmasks || mask_index >= jmasks->size()) {
399 return nullptr;
400 }
401
402 const skjson::ObjectValue* mask = (*jmasks)[mask_index];
403 if (!mask) {
404 return nullptr;
405 }
406
407 auto pinfo = std::make_unique<PathInfo>();
408 adapter->bind(*abuilder, (*mask)["pt"], &pinfo->fPath);
409 adapter->bind(*abuilder, (*jpath)["f"], &pinfo->fPathFMargin);
410 adapter->bind(*abuilder, (*jpath)["l"], &pinfo->fPathLMargin);
411 adapter->bind(*abuilder, (*jpath)["p"], &pinfo->fPathPerpendicular);
412 adapter->bind(*abuilder, (*jpath)["r"], &pinfo->fPathReverse);
413
414 // TODO: force align support
415
416 // Historically, these used to be exported as static properties.
417 // Attempt parsing both ways, for backward compat.
418 skottie::Parse((*jpath)["p"], &pinfo->fPathPerpendicular);
419 skottie::Parse((*jpath)["r"], &pinfo->fPathReverse);
420
421 // Path positioning requires anchor point info.
422 adapter->fRequiresAnchorPoint = true;
423
424 return pinfo;
425 };
426
427 adapter->fPathInfo = attach_path((*jt)["p"]);
428 abuilder->dispatchTextProperty(adapter, jd);
429
430 return adapter;
431 }
432
433 TextAdapter::TextAdapter(sk_sp<SkFontMgr> fontmgr,
434 sk_sp<CustomFont::GlyphCompMapper> custom_glyph_mapper,
435 sk_sp<Logger> logger,
436 sk_sp<SkShapers::Factory> factory,
437 AnchorPointGrouping apg)
438 : fRoot(sksg::Group::Make())
439 , fFontMgr(std::move(fontmgr))
440 , fCustomGlyphMapper(std::move(custom_glyph_mapper))
441 , fLogger(std::move(logger))
442 , fShapingFactory(std::move(factory))
443 , fAnchorPointGrouping(apg)
444 , fHasBlurAnimator(false)
445 , fRequiresAnchorPoint(false)
446 , fRequiresLineAdjustments(false) {}
447
448 TextAdapter::~TextAdapter() = default;
449
450 std::vector<sk_sp<sksg::RenderNode>>
451 TextAdapter::buildGlyphCompNodes(Shaper::ShapedGlyphs& glyphs) const {
452 std::vector<sk_sp<sksg::RenderNode>> draws;
453
454 if (fCustomGlyphMapper) {
455 size_t run_offset = 0;
456 for (auto& run : glyphs.fRuns) {
457 for (size_t i = 0; i < run.fSize; ++i) {
458 const size_t goffset = run_offset + i;
459 const SkGlyphID gid = glyphs.fGlyphIDs[goffset];
460
461 if (auto gcomp = fCustomGlyphMapper->getGlyphComp(run.fFont.getTypeface(), gid)) {
462 // Position and scale the "glyph".
463 const auto m = SkMatrix::Translate(glyphs.fGlyphPos[goffset])
464 * SkMatrix::Scale(fText->fTextSize*fTextShapingScale,
465 fText->fTextSize*fTextShapingScale);
466
467 draws.push_back(sksg::TransformEffect::Make(std::move(gcomp), m));
468
469 // Remove all related data from the fragment, so we don't attempt to render
470 // this as a regular glyph.
471 SkASSERT(glyphs.fGlyphIDs.size() > goffset);
472 glyphs.fGlyphIDs.erase(glyphs.fGlyphIDs.begin() + goffset);
473 SkASSERT(glyphs.fGlyphPos.size() > goffset);
474 glyphs.fGlyphPos.erase(glyphs.fGlyphPos.begin() + goffset);
475 if (!glyphs.fClusters.empty()) {
476 SkASSERT(glyphs.fClusters.size() > goffset);
477 glyphs.fClusters.erase(glyphs.fClusters.begin() + goffset);
478 }
479 i -= 1;
480 run.fSize -= 1;
481 }
482 }
483 run_offset += run.fSize;
484 }
485 }
486
487 return draws;
488 }
489
490 void TextAdapter::addFragment(Shaper::Fragment& frag, sksg::Group* container) {
491 // For a given shaped fragment, build a corresponding SG fragment:
492 //
493 // [TransformEffect] -> [Transform]
494 // [Group]
495 // [Draw] -> [GlyphTextNode*] [FillPaint] // SkTypeface-based glyph.
496 // [Draw] -> [GlyphTextNode*] [StrokePaint] // SkTypeface-based glyph.
497 // [CompRenderTree] // Comp glyph.
498 // ...
499 //
500
501 FragmentRec rec;
502 rec.fOrigin = frag.fOrigin;
503 rec.fAdvance = frag.fAdvance;
504 rec.fAscent = frag.fAscent;
505 rec.fMatrixNode = sksg::Matrix<SkM44>::Make(SkM44::Translate(frag.fOrigin.x(),
506 frag.fOrigin.y()));
507
508 // Start off substituting existing comp nodes for all composition-based glyphs.
509 std::vector<sk_sp<sksg::RenderNode>> draws = this->buildGlyphCompNodes(frag.fGlyphs);
510
511 // Use a regular GlyphTextNode for the remaining glyphs (backed by a real SkTypeface).
512 auto text_node = sk_make_sp<GlyphTextNode>(std::move(frag.fGlyphs));
513 rec.fGlyphs = text_node->glyphs();
514
515 draws.reserve(draws.size() +
516 static_cast<size_t>(fText->fHasFill) +
517 static_cast<size_t>(fText->fHasStroke));
518
519 SkASSERT(fText->fHasFill || fText->fHasStroke);
520
521 auto add_fill = [&]() {
522 if (fText->fHasFill) {
523 rec.fFillColorNode = sksg::Color::Make(fText->fFillColor);
524 rec.fFillColorNode->setAntiAlias(true);
525 draws.push_back(sksg::Draw::Make(text_node, rec.fFillColorNode));
526 }
527 };
528 auto add_stroke = [&] {
529 if (fText->fHasStroke) {
530 rec.fStrokeColorNode = sksg::Color::Make(fText->fStrokeColor);
531 rec.fStrokeColorNode->setAntiAlias(true);
532 rec.fStrokeColorNode->setStyle(SkPaint::kStroke_Style);
533 rec.fStrokeColorNode->setStrokeWidth(fText->fStrokeWidth * fTextShapingScale);
534 rec.fStrokeColorNode->setStrokeJoin(fText->fStrokeJoin);
535 draws.push_back(sksg::Draw::Make(text_node, rec.fStrokeColorNode));
536 }
537 };
538
539 if (fText->fPaintOrder == TextPaintOrder::kFillStroke) {
540 add_fill();
541 add_stroke();
542 } else {
543 add_stroke();
544 add_fill();
545 }
546
547 SkASSERT(!draws.empty());
548
549 if (SHOW_LAYOUT_BOXES) {
550 // visualize fragment ascent boxes
551 auto box_color = sksg::Color::Make(0xff0000ff);
552 box_color->setStyle(SkPaint::kStroke_Style);
553 box_color->setStrokeWidth(1);
554 box_color->setAntiAlias(true);
555 auto box = SkRect::MakeLTRB(0, rec.fAscent, rec.fAdvance, 0);
556 draws.push_back(sksg::Draw::Make(sksg::Rect::Make(box), std::move(box_color)));
557 }
558
559 draws.shrink_to_fit();
560
561 auto draws_node = (draws.size() > 1)
562 ? sksg::Group::Make(std::move(draws))
563 : std::move(draws[0]);
564
565 if (fHasBlurAnimator) {
566 // Optional blur effect.
567 rec.fBlur = sksg::BlurImageFilter::Make();
568 draws_node = sksg::ImageFilterEffect::Make(std::move(draws_node), rec.fBlur);
569 }
570
571 container->addChild(sksg::TransformEffect::Make(std::move(draws_node), rec.fMatrixNode));
572 fFragments.push_back(std::move(rec));
573 }
574
575 void TextAdapter::buildDomainMaps(const Shaper::Result& shape_result) {
576 fMaps.fNonWhitespaceMap.clear();
577 fMaps.fWordsMap.clear();
578 fMaps.fLinesMap.clear();
579
580 size_t i = 0,
581 line = 0,
582 line_start = 0,
583 word_start = 0;
584
585 float word_advance = 0,
586 word_ascent = 0,
587 line_advance = 0,
588 line_ascent = 0;
589
590 bool in_word = false;
591
592 // TODO: use ICU for building the word map?
593 for (; i < shape_result.fFragments.size(); ++i) {
594 const auto& frag = shape_result.fFragments[i];
595 const bool is_new_line = frag.fLineIndex != line;
596
597 if (frag.fIsWhitespace || is_new_line) {
598 // Both whitespace and new lines break words.
599 if (in_word) {
600 in_word = false;
601 fMaps.fWordsMap.push_back({word_start, i - word_start, word_advance, word_ascent});
602 }
603 }
604
605 if (!frag.fIsWhitespace) {
606 fMaps.fNonWhitespaceMap.push_back({i, 1, 0, 0});
607
608 if (!in_word) {
609 in_word = true;
610 word_start = i;
611 word_advance = word_ascent = 0;
612 }
613
614 word_advance += frag.fAdvance;
615 word_ascent = std::min(word_ascent, frag.fAscent); // negative ascent
616 }
617
618 if (is_new_line) {
619 SkASSERT(frag.fLineIndex == line + 1);
620 fMaps.fLinesMap.push_back({line_start, i - line_start, line_advance, line_ascent});
621 line = frag.fLineIndex;
622 line_start = i;
623 line_advance = line_ascent = 0;
624 }
625
626 line_advance += frag.fAdvance;
627 line_ascent = std::min(line_ascent, frag.fAscent); // negative ascent
628 }
629
630 if (i > word_start) {
631 fMaps.fWordsMap.push_back({word_start, i - word_start, word_advance, word_ascent});
632 }
633
634 if (i > line_start) {
635 fMaps.fLinesMap.push_back({line_start, i - line_start, line_advance, line_ascent});
636 }
637 }
638
639 void TextAdapter::setText(const TextValue& txt) {
640 fText.fCurrentValue = txt;
641 this->onSync();
642 }
643
644 uint32_t TextAdapter::shaperFlags() const {
645 uint32_t flags = Shaper::Flags::kNone;
646
647 // We need granular fragments (as opposed to consolidated blobs):
648 // - when animating
649 // - when positioning on a path
650 // - when clamping the number or lines (for accurate line count)
651 // - when a text decorator is present
652 if (!fAnimators.empty() || fPathInfo || fText->fMaxLines || fText->fDecorator) {
653 flags |= Shaper::Flags::kFragmentGlyphs;
654 }
655
656 if (fRequiresAnchorPoint || fText->fDecorator) {
657 flags |= Shaper::Flags::kTrackFragmentAdvanceAscent;
658 }
659
660 if (fText->fDecorator) {
661 flags |= Shaper::Flags::kClusters;
662 }
663
664 return flags;
665 }
666
667 void TextAdapter::reshape() {
668 // AE clamps the font size to a reasonable range.
669 // We do the same, since HB is susceptible to int overflows for degenerate values.
670 static constexpr float kMinSize = 0.1f,
671 kMaxSize = 1296.0f;
672 const Shaper::TextDesc text_desc = {
673 fText->fTypeface,
674 SkTPin(fText->fTextSize, kMinSize, kMaxSize),
675 SkTPin(fText->fMinTextSize, kMinSize, kMaxSize),
676 SkTPin(fText->fMaxTextSize, kMinSize, kMaxSize),
677 fText->fLineHeight,
678 fText->fLineShift,
679 fText->fAscent,
680 fText->fHAlign,
681 fText->fVAlign,
682 fText->fResize,
683 fText->fLineBreak,
684 fText->fDirection,
685 fText->fCapitalization,
686 fText->fMaxLines,
687 this->shaperFlags(),
688 fText->fLocale.isEmpty() ? nullptr : fText->fLocale.c_str(),
689 fText->fFontFamily.isEmpty() ? nullptr : fText->fFontFamily.c_str(),
690 };
691 auto shape_result = Shaper::Shape(fText->fText, text_desc, fText->fBox, fFontMgr,
692 fShapingFactory);
693
694 if (fLogger) {
695 if (shape_result.fFragments.empty() && fText->fText.size() > 0) {
696 const auto msg = SkStringPrintf("Text layout failed for '%s'.",
697 fText->fText.c_str());
698 fLogger->log(Logger::Level::kError, msg.c_str());
699
700 // These may trigger repeatedly when the text is animating.
701 // To avoid spamming, only log once.
702 fLogger = nullptr;
703 }
704
705 if (shape_result.fMissingGlyphCount > 0) {
706 const auto msg = SkStringPrintf("Missing %zu glyphs for '%s'.",
707 shape_result.fMissingGlyphCount,
708 fText->fText.c_str());
709 fLogger->log(Logger::Level::kWarning, msg.c_str());
710 fLogger = nullptr;
711 }
712 }
713
714 // Save the text shaping scale for later adjustments.
715 fTextShapingScale = shape_result.fScale;
716
717 // Rebuild all fragments.
718 // TODO: we can be smarter here and try to reuse the existing SG structure if needed.
719
720 fRoot->clear();
721 fFragments.clear();
722
723 if (SHOW_LAYOUT_BOXES) {
724 auto box_color = sksg::Color::Make(0xffff0000);
725 box_color->setStyle(SkPaint::kStroke_Style);
726 box_color->setStrokeWidth(1);
727 box_color->setAntiAlias(true);
728
729 auto bounds_color = sksg::Color::Make(0xff00ff00);
730 bounds_color->setStyle(SkPaint::kStroke_Style);
731 bounds_color->setStrokeWidth(1);
732 bounds_color->setAntiAlias(true);
733
734 fRoot->addChild(sksg::Draw::Make(sksg::Rect::Make(fText->fBox),
735 std::move(box_color)));
736 fRoot->addChild(sksg::Draw::Make(sksg::Rect::Make(shape_result.computeVisualBounds()),
737 std::move(bounds_color)));
738
739 if (fPathInfo) {
740 auto path_color = sksg::Color::Make(0xffffff00);
741 path_color->setStyle(SkPaint::kStroke_Style);
742 path_color->setStrokeWidth(1);
743 path_color->setAntiAlias(true);
744
745 fRoot->addChild(
746 sksg::Draw::Make(sksg::Path::Make(static_cast<SkPath>(fPathInfo->fPath)),
747 std::move(path_color)));
748 }
749 }
750
751 // Depending on whether a GlyphDecorator is present, we either add the glyph render nodes
752 // directly to the root group, or to an intermediate GlyphDecoratorNode container.
753 sksg::Group* container = fRoot.get();
754 sk_sp<GlyphDecoratorNode> decorator_node;
755 if (fText->fDecorator) {
756 decorator_node = sk_make_sp<GlyphDecoratorNode>(fText->fDecorator, fTextShapingScale);
757 container = decorator_node.get();
758 }
759
760 // N.B. addFragment moves shaped glyph data out of the fragment, so only the fragment
761 // metrics are valid after this block.
762 for (size_t i = 0; i < shape_result.fFragments.size(); ++i) {
763 this->addFragment(shape_result.fFragments[i], container);
764 }
765
766 if (decorator_node) {
767 decorator_node->updateFragmentData(fFragments);
768 fRoot->addChild(std::move(decorator_node));
769 }
770
771 if (!fAnimators.empty() || fPathInfo) {
772 // Range selectors and text paths require fragment domain maps.
773 this->buildDomainMaps(shape_result);
774 }
775 }
776
777 void TextAdapter::onSync() {
778 if (!fText->fHasFill && !fText->fHasStroke) {
779 return;
780 }
781
782 if (fText.hasChanged()) {
783 this->reshape();
784 }
785
786 if (fFragments.empty()) {
787 return;
788 }
789
790 // Update the path contour measure, if needed.
791 if (fPathInfo) {
792 fPathInfo->updateContourData();
793 }
794
795 // Seed props from the current text value.
796 TextAnimator::ResolvedProps seed_props;
797 seed_props.fill_color = fText->fFillColor;
798 seed_props.stroke_color = fText->fStrokeColor;
799 seed_props.stroke_width = fText->fStrokeWidth;
800
801 TextAnimator::ModulatorBuffer buf;
802 buf.resize(fFragments.size(), { seed_props, 0 });
803
804 // Apply all animators to the modulator buffer.
805 for (const auto& animator : fAnimators) {
806 animator->modulateProps(fMaps, buf);
807 }
808
809 const TextAnimator::DomainMap* grouping_domain = nullptr;
810 switch (fAnchorPointGrouping) {
811 // for word/line grouping, we rely on domain map info
812 case AnchorPointGrouping::kWord: grouping_domain = &fMaps.fWordsMap; break;
813 case AnchorPointGrouping::kLine: grouping_domain = &fMaps.fLinesMap; break;
814 // remaining grouping modes (character/all) do not need (or have) domain map data
815 default: break;
816 }
817
818 size_t grouping_span_index = 0;
819 SkV2 current_line_offset = { 0, 0 }; // cumulative line spacing
820
821 auto compute_linewide_props = [this](const TextAnimator::ModulatorBuffer& buf,
822 const TextAnimator::DomainSpan& line_span) {
823 SkV2 total_spacing = {0,0};
824 float total_tracking = 0;
825
826 // Only compute these when needed.
827 if (fRequiresLineAdjustments && line_span.fCount) {
828 for (size_t i = line_span.fOffset; i < line_span.fOffset + line_span.fCount; ++i) {
829 const auto& props = buf[i].props;
830 total_spacing += props.line_spacing;
831 total_tracking += props.tracking;
832 }
833
834 // The first glyph does not contribute |before| tracking, and the last one does not
835 // contribute |after| tracking.
836 total_tracking -= 0.5f * (buf[line_span.fOffset].props.tracking +
837 buf[line_span.fOffset + line_span.fCount - 1].props.tracking);
838 }
839
840 return std::make_tuple(total_spacing, total_tracking);
841 };
842
843 // Finally, push all props to their corresponding fragment.
844 for (const auto& line_span : fMaps.fLinesMap) {
845 const auto [line_spacing, line_tracking] = compute_linewide_props(buf, line_span);
846 const auto align_offset = -line_tracking * align_factor(fText->fHAlign);
847
848 // line spacing of the first line is ignored (nothing to "space" against)
849 if (&line_span != &fMaps.fLinesMap.front() && line_span.fCount) {
850 // For each line, the actual spacing is an average of individual fragment spacing
851 // (to preserve the "line").
852 current_line_offset += line_spacing / line_span.fCount;
853 }
854
855 float tracking_acc = 0;
856 for (size_t i = line_span.fOffset; i < line_span.fOffset + line_span.fCount; ++i) {
857 // Track the grouping domain span in parallel.
858 if (grouping_domain && i >= (*grouping_domain)[grouping_span_index].fOffset +
859 (*grouping_domain)[grouping_span_index].fCount) {
860 grouping_span_index += 1;
861 SkASSERT(i < (*grouping_domain)[grouping_span_index].fOffset +
862 (*grouping_domain)[grouping_span_index].fCount);
863 }
864
865 const auto& props = buf[i].props;
866 const auto& frag = fFragments[i];
867
868 // AE tracking is defined per glyph, based on two components: |before| and |after|.
869 // BodyMovin only exports "balanced" tracking values, where before = after = tracking/2.
870 //
871 // Tracking is applied as a local glyph offset, and contributes to the line width for
872 // alignment purposes.
873 //
874 // No |before| tracking for the first glyph, nor |after| tracking for the last one.
875 const auto track_before = i > line_span.fOffset
876 ? props.tracking * 0.5f : 0.0f,
877 track_after = i < line_span.fOffset + line_span.fCount - 1
878 ? props.tracking * 0.5f : 0.0f;
879
880 const auto frag_offset = current_line_offset +
881 SkV2{align_offset + tracking_acc + track_before, 0};
882
883 tracking_acc += track_before + track_after;
884
885 this->pushPropsToFragment(props, frag, frag_offset, fGroupingAlignment * .01f, // %
886 grouping_domain ? &(*grouping_domain)[grouping_span_index]
887 : nullptr);
888 }
889 }
890 }
891
892 SkV2 TextAdapter::fragmentAnchorPoint(const FragmentRec& rec,
893 const SkV2& grouping_alignment,
894 const TextAnimator::DomainSpan* grouping_span) const {
895 // Construct the following 2x ascent box:
896 //
897 // -------------
898 // | |
899 // | | ascent
900 // | |
901 // ----+-------------+---------- baseline
902 // (pos) |
903 // | | ascent
904 // | |
905 // -------------
906 // advance
907
908 auto make_box = [](const SkPoint& pos, float advance, float ascent) {
909 // note: negative ascent
910 return SkRect::MakeXYWH(pos.fX, pos.fY + ascent, advance, -2 * ascent);
911 };
912
913 // Compute a grouping-dependent anchor point box.
914 // The default anchor point is at the center, and gets adjusted relative to the bounds
915 // based on |grouping_alignment|.
916 auto anchor_box = [&]() -> SkRect {
917 switch (fAnchorPointGrouping) {
918 case AnchorPointGrouping::kCharacter:
919 // Anchor box relative to each individual fragment.
920 return make_box(rec.fOrigin, rec.fAdvance, rec.fAscent);
921 case AnchorPointGrouping::kWord:
922 // Fall through
923 case AnchorPointGrouping::kLine: {
924 SkASSERT(grouping_span);
925 // Anchor box relative to the first fragment in the word/line.
926 const auto& first_span_fragment = fFragments[grouping_span->fOffset];
927 return make_box(first_span_fragment.fOrigin,
928 grouping_span->fAdvance,
929 grouping_span->fAscent);
930 }
931 case AnchorPointGrouping::kAll:
932 // Anchor box is the same as the text box.
933 return fText->fBox;
934 }
935 SkUNREACHABLE;
936 };
937
938 const auto ab = anchor_box();
939
940 // Apply grouping alignment.
941 const auto ap = SkV2 { ab.centerX() + ab.width() * 0.5f * grouping_alignment.x,
942 ab.centerY() + ab.height() * 0.5f * grouping_alignment.y };
943
944 // The anchor point is relative to the fragment position.
945 return ap - SkV2 { rec.fOrigin.fX, rec.fOrigin.fY };
946 }
947
948 SkM44 TextAdapter::fragmentMatrix(const TextAnimator::ResolvedProps& props,
949 const FragmentRec& rec, const SkV2& frag_offset) const {
950 const SkV3 pos = {
951 props.position.x + rec.fOrigin.fX + frag_offset.x,
952 props.position.y + rec.fOrigin.fY + frag_offset.y,
953 props.position.z
954 };
955
956 if (!fPathInfo) {
957 return SkM44::Translate(pos.x, pos.y, pos.z);
958 }
959
960 // "Align" the paragraph box left/center/right to path start/mid/end, respectively.
961 const auto align_offset =
962 align_factor(fText->fHAlign)*(fPathInfo->pathLength() - fText->fBox.width());
963
964 // Path positioning is based on the fragment position relative to the paragraph box
965 // upper-left corner:
966 //
967 // - the horizontal component determines the distance on path
968 //
969 // - the vertical component is post-applied after orienting on path
970 //
971 // Note: in point-text mode, the box adjustments have no effect as fBox is {0,0,0,0}.
972 //
973 const auto rel_pos = SkV2{pos.x, pos.y} - SkV2{fText->fBox.fLeft, fText->fBox.fTop};
974 const auto path_distance = rel_pos.x + align_offset;
975
976 return fPathInfo->getMatrix(path_distance, fText->fHAlign)
977 * SkM44::Translate(0, rel_pos.y, pos.z);
978 }
979
980 void TextAdapter::pushPropsToFragment(const TextAnimator::ResolvedProps& props,
981 const FragmentRec& rec,
982 const SkV2& frag_offset,
983 const SkV2& grouping_alignment,
984 const TextAnimator::DomainSpan* grouping_span) const {
985 const auto anchor_point = this->fragmentAnchorPoint(rec, grouping_alignment, grouping_span);
986
987 rec.fMatrixNode->setMatrix(
988 this->fragmentMatrix(props, rec, anchor_point + frag_offset)
989 * SkM44::Rotate({ 1, 0, 0 }, SkDegreesToRadians(props.rotation.x))
990 * SkM44::Rotate({ 0, 1, 0 }, SkDegreesToRadians(props.rotation.y))
991 * SkM44::Rotate({ 0, 0, 1 }, SkDegreesToRadians(props.rotation.z))
992 * SkM44::Scale(props.scale.x, props.scale.y, props.scale.z)
993 * SkM44::Translate(-anchor_point.x, -anchor_point.y, 0));
994
995 const auto scale_alpha = [](SkColor c, float o) {
996 return SkColorSetA(c, SkScalarRoundToInt(o * SkColorGetA(c)));
997 };
998
999 if (rec.fFillColorNode) {
1000 rec.fFillColorNode->setColor(scale_alpha(props.fill_color, props.opacity));
1001 }
1002 if (rec.fStrokeColorNode) {
1003 rec.fStrokeColorNode->setColor(scale_alpha(props.stroke_color, props.opacity));
1004 rec.fStrokeColorNode->setStrokeWidth(props.stroke_width * fTextShapingScale);
1005 }
1006 if (rec.fBlur) {
1007 rec.fBlur->setSigma({ props.blur.x * kBlurSizeToSigma,
1008 props.blur.y * kBlurSizeToSigma });
1009 }
1010 }
1011
1012 } // namespace skottie::internal