Debian Codegraph @

src/text/gpu/SubRunContainer.cpp

raw ◀ ▶
3 Debian patches touch this file
1 /*
2 * Copyright 2022 Google LLC
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
8 #include "src/text/gpu/SubRunContainer.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkFont.h"
13 #include "include/core/SkMaskFilter.h"
14 #include "include/core/SkMatrix.h"
15 #include "include/core/SkPaint.h"
16 #include "include/core/SkPath.h"
17 #include "include/core/SkPathEffect.h"
18 #include "include/core/SkRect.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkStrokeRec.h"
21 #include "include/core/SkSurfaceProps.h"
22 #include "include/core/SkTypes.h"
23 #include "include/effects/SkDashPathEffect.h"
24 #include "include/private/base/SkFloatingPoint.h"
25 #include "include/private/base/SkOnce.h"
26 #include "include/private/base/SkTArray.h"
27 #include "include/private/base/SkTLogic.h"
28 #include "include/private/base/SkTo.h"
29 #include "src/base/SkZip.h"
30 #include "src/core/SkDevice.h"
31 #include "src/core/SkDistanceFieldGen.h"
32 #include "src/core/SkEnumerate.h"
33 #include "src/core/SkFontPriv.h"
34 #include "src/core/SkGlyph.h"
35 #include "src/core/SkMask.h"
36 #include "src/core/SkMaskFilterBase.h"
37 #include "src/core/SkMatrixPriv.h"
38 #include "src/core/SkPathEffectBase.h"
39 #include "src/core/SkReadBuffer.h"
40 #include "src/core/SkScalerContext.h"
41 #include "src/core/SkStrike.h"
42 #include "src/core/SkStrikeCache.h"
43 #include "src/core/SkStrikeSpec.h"
44 #include "src/core/SkWriteBuffer.h"
45 #include "src/gpu/AtlasTypes.h"
46 #include "src/text/GlyphRun.h"
47 #include "src/text/StrikeForGPU.h"
48 #include "src/text/gpu/Glyph.h"
49 #include "src/text/gpu/SDFMaskFilter.h"
50 #include "src/text/gpu/StrikeCache.h"
51 #include "src/text/gpu/SubRunControl.h"
52
53 #include <algorithm>
54 #include <climits>
55 #include <cstdint>
56 #include <new>
57 #include <optional>
58 #include <vector>
59
60 using namespace skia_private;
61 using namespace skglyph;
62
63 // -- GPU Text -------------------------------------------------------------------------------------
64 // Naming conventions
65 // * drawMatrix - the CTM from the canvas.
66 // * drawOrigin - the x, y location of the drawTextBlob call.
67 // * positionMatrix - this is the combination of the drawMatrix and the drawOrigin:
68 // positionMatrix = drawMatrix * TranslationMatrix(drawOrigin.x, drawOrigin.y);
69 //
70 // Note:
71 // In order to transform Slugs, you need to set the fSupportBilerpFromGlyphAtlas on
72 // GrContextOptions.
73
74 namespace sktext::gpu {
75 // -- SubRunStreamTag ------------------------------------------------------------------------------
76 enum SubRun::SubRunStreamTag : int {
77 kBad = 0, // Make this 0 to line up with errors from readInt.
78 kDirectMaskStreamTag,
79 #if !defined(SK_DISABLE_SDF_TEXT)
80 kSDFTStreamTag,
81 #endif
82 kTransformMaskStreamTag,
83 kPathStreamTag,
84 kDrawableStreamTag,
85 kSubRunStreamTagCount,
86 };
87
88 } // namespace sktext::gpu
89
90 using MaskFormat = skgpu::MaskFormat;
91
92 using namespace sktext;
93 using namespace sktext::gpu;
94
95 namespace {
96 SkSpan<const SkPackedGlyphID> get_packedIDs(SkZip<const SkPackedGlyphID, const SkPoint> accepted) {
97 return accepted.get<0>();
98 }
99
100 SkSpan<const SkGlyphID> get_glyphIDs(SkZip<const SkGlyphID, const SkPoint> accepted) {
101 return accepted.get<0>();
102 }
103
•104 template <typename U> SkSpan<const SkPoint> get_positions(SkZip<U, const SkPoint> accepted) {
105 return accepted.template get<1>();
106 }
107
•108 SkGlyphRect glyph_bounds(SkGlyphDigest digest, int inset, SkPoint origin) {
109 return digest.bounds().inset(inset, inset).offset(origin);
110 }
111
112 SkGlyphRect glyph_bounds_from_left_top(SkGlyphDigest digest, int inset, SkPoint leftTop) {
113 SkGlyphRect bounds = digest.bounds();
114 SkPoint offset = leftTop - bounds.leftTop() - SkPoint{SkIntToScalar(inset),
115 SkIntToScalar(inset)};
116 return glyph_bounds(digest, inset, offset);
117 }
118
119 // Returns the empty span if there is a problem reading the positions.
120 SkSpan<SkPoint> make_points_from_buffer(SkReadBuffer& buffer, SubRunAllocator* alloc) {
121 uint32_t glyphCount = buffer.getArrayCount();
122
123 // Zero indicates a problem with serialization.
124 if (!buffer.validate(glyphCount != 0)) { return {}; }
125
126 // Check that the count will not overflow the arena.
127 if (!buffer.validate(glyphCount <= INT_MAX &&
128 BagOfBytes::WillCountFit<SkPoint>(glyphCount))) { return {}; }
129
130 SkPoint* positionsData = alloc->makePODArray<SkPoint>(glyphCount);
131 if (!buffer.readPointArray({positionsData, glyphCount})) { return {}; }
132 return {positionsData, glyphCount};
133 }
134
135 SkRect reconstruct_safe_bounds(SkSpan<const SkPoint> leftTop,
136 GlyphVector* glyphVector,
137 skglyph::ActionType actionType,
138 int inset) {
139 int count = leftTop.size();
140
141 StrikeForGPU* strike = glyphVector->strikePromise().strike();
142 StrikeMutationMonitor m{strike};
143
144 SkGlyphRect boundingRect = skglyph::empty_rect();
145 for (int i = 0; i < count; ++i) {
146 SkPackedGlyphID packedID = glyphVector->getPackedGlyphID(i);
147 SkGlyphDigest digest = strike->digestFor(actionType, packedID);
148 boundingRect = skglyph::rect_union(
149 boundingRect, glyph_bounds_from_left_top(digest, inset, leftTop[i]));
150 }
151 return boundingRect.empty() ? SkRect::MakeEmpty() : boundingRect.rect();
152 }
153
154 void flatten_vertex_filler(SkWriteBuffer &buffer, const VertexFiller& vf) {
155 buffer.writeInt(static_cast<int>(vf.maskFormat()));
156 buffer.writeBool(vf.canDrawDirect());
157 buffer.writeMatrix(vf.creationMatrix());
158 buffer.writePointArray(vf.topLefts());
159 }
160
161 std::optional<VertexFiller> make_vertex_filler_from_buffer(SkReadBuffer& buffer,
162 SubRunAllocator* alloc,
163 GlyphVector* glyphVector,
164 skglyph::ActionType actionType,
165 int inset) {
166 MaskFormat maskFormat = buffer.read32LE(MaskFormat::kLast);
167
168 const bool canDrawDirect = buffer.readBool();
169
170 SkMatrix creationMatrix;
171 buffer.readMatrix(&creationMatrix);
•172 // The only valid creationMatrices do not have perspective and many rendering parts assume
173 // they are non-affine, so reject any malformed matrices here.
174 if (!buffer.validate(!creationMatrix.hasPerspective())) {
175 return std::nullopt;
176 }
177
178 SkSpan<SkPoint> leftTop = make_points_from_buffer(buffer, alloc);
179 if (leftTop.empty()) {
180 return std::nullopt;
181 }
182
183 if (!buffer.validate(glyphVector->glyphCount() == (int)leftTop.size())) {
184 return std::nullopt;
185 }
186
187 SkRect safeBounds = reconstruct_safe_bounds(leftTop, glyphVector, actionType, inset);
188
189 return VertexFiller{maskFormat, creationMatrix, safeBounds, leftTop, canDrawDirect};
190 }
191
192 // -- PathOpSubmitter ------------------------------------------------------------------------------
193 // PathOpSubmitter holds glyph ids until ready to draw. During drawing, the glyph ids are
194 // converted to SkPaths. PathOpSubmitter can only be serialized when it is holding glyph ids;
195 // it can only be serialized before submitDraws has been called.
196 class PathOpSubmitter {
197 public:
198 PathOpSubmitter() = delete;
199 PathOpSubmitter(const PathOpSubmitter&) = delete;
200 const PathOpSubmitter& operator=(const PathOpSubmitter&) = delete;
201 PathOpSubmitter(PathOpSubmitter&& that)
202 // Transfer ownership of fIDsOrPaths from that to this.
203 : fIDsOrPaths{std::exchange(
204 const_cast<SkSpan<IDOrPath>&>(that.fIDsOrPaths), SkSpan<IDOrPath>{})}
205 , fPositions{that.fPositions}
206 , fStrikeToSourceScale{that.fStrikeToSourceScale}
207 , fIsAntiAliased{that.fIsAntiAliased}
208 , fStrikePromise{std::move(that.fStrikePromise)} {}
209 PathOpSubmitter& operator=(PathOpSubmitter&& that) {
210 this->~PathOpSubmitter();
211 new (this) PathOpSubmitter{std::move(that)};
212 return *this;
213 }
214 PathOpSubmitter(bool isAntiAliased,
215 SkScalar strikeToSourceScale,
216 SkSpan<SkPoint> positions,
217 SkSpan<IDOrPath> idsOrPaths,
218 SkStrikePromise&& strikePromise);
219
220 ~PathOpSubmitter();
221
222 static PathOpSubmitter Make(SkZip<const SkGlyphID, const SkPoint> accepted,
223 bool isAntiAliased,
224 SkScalar strikeToSourceScale,
225 SkStrikePromise&& strikePromise,
226 SubRunAllocator* alloc);
227
228 int unflattenSize() const;
229 void flatten(SkWriteBuffer& buffer) const;
230 static std::optional<PathOpSubmitter> MakeFromBuffer(SkReadBuffer& buffer,
231 SubRunAllocator* alloc,
232 const SkStrikeClient* client);
233
234 // submitDraws is not thread safe. It only occurs the single thread drawing portion of the GPU
235 // rendering.
236 void submitDraws(SkCanvas*,
237 SkPoint drawOrigin,
238 const SkPaint& paint) const;
239
240 private:
241 // When PathOpSubmitter is created only the glyphIDs are needed, during the submitDraws call,
242 // the glyphIDs are converted to SkPaths.
243 const SkSpan<IDOrPath> fIDsOrPaths;
244 const SkSpan<const SkPoint> fPositions;
245 const SkScalar fStrikeToSourceScale;
246 const bool fIsAntiAliased;
247
248 mutable SkStrikePromise fStrikePromise;
249 mutable SkOnce fConvertIDsToPaths;
250 mutable bool fPathsAreCreated{false};
251 };
252
253 int PathOpSubmitter::unflattenSize() const {
254 return fPositions.size_bytes() + fIDsOrPaths.size_bytes();
255 }
256
257 void PathOpSubmitter::flatten(SkWriteBuffer& buffer) const {
258 fStrikePromise.flatten(buffer);
259
260 buffer.writeInt(fIsAntiAliased);
261 buffer.writeScalar(fStrikeToSourceScale);
262 buffer.writePointArray(fPositions);
263 for (IDOrPath& idOrPath : fIDsOrPaths) {
264 buffer.writeInt(idOrPath.fGlyphID);
265 }
266 }
267
268 std::optional<PathOpSubmitter> PathOpSubmitter::MakeFromBuffer(SkReadBuffer& buffer,
269 SubRunAllocator* alloc,
270 const SkStrikeClient* client) {
271 std::optional<SkStrikePromise> strikePromise =
272 SkStrikePromise::MakeFromBuffer(buffer, client, SkStrikeCache::GlobalStrikeCache());
273 if (!buffer.validate(strikePromise.has_value())) {
274 return std::nullopt;
275 }
276
277 bool isAntiAlias = buffer.readInt();
278
279 SkScalar strikeToSourceScale = buffer.readScalar();
280 if (!buffer.validate(0 < strikeToSourceScale)) { return std::nullopt; }
281
•282 SkSpan<SkPoint> positions = make_points_from_buffer(buffer, alloc);
283 if (positions.empty()) { return std::nullopt; }
284 const int glyphCount = SkCount(positions);
285
286 // Remember, we stored an int for glyph id.
287 if (!buffer.validateCanReadN<int>(glyphCount)) { return std::nullopt; }
288 auto idsOrPaths = SkSpan(alloc->makeUniqueArray<IDOrPath>(glyphCount).release(), glyphCount);
289 for (auto& idOrPath : idsOrPaths) {
290 idOrPath.fGlyphID = SkTo<SkGlyphID>(buffer.readInt());
291 }
292
293 if (!buffer.isValid()) { return std::nullopt; }
294
295 return PathOpSubmitter{isAntiAlias,
296 strikeToSourceScale,
297 positions,
298 idsOrPaths,
299 std::move(strikePromise.value())};
300 }
301
302 PathOpSubmitter::PathOpSubmitter(
303 bool isAntiAliased,
304 SkScalar strikeToSourceScale,
305 SkSpan<SkPoint> positions,
306 SkSpan<IDOrPath> idsOrPaths,
307 SkStrikePromise&& strikePromise)
308 : fIDsOrPaths{idsOrPaths}
309 , fPositions{positions}
310 , fStrikeToSourceScale{strikeToSourceScale}
311 , fIsAntiAliased{isAntiAliased}
312 , fStrikePromise{std::move(strikePromise)} {
313 SkASSERT(!fPositions.empty());
314 }
315
316 PathOpSubmitter::~PathOpSubmitter() {
317 // If we have converted glyph IDs to paths, then clean up the SkPaths.
318 if (fPathsAreCreated) {
319 for (auto& idOrPath : fIDsOrPaths) {
320 idOrPath.fPath.~SkPath();
321 }
322 }
323 }
324
325 PathOpSubmitter PathOpSubmitter::Make(SkZip<const SkGlyphID, const SkPoint> accepted,
326 bool isAntiAliased,
327 SkScalar strikeToSourceScale,
328 SkStrikePromise&& strikePromise,
329 SubRunAllocator* alloc) {
330 auto mapToIDOrPath = [](SkGlyphID glyphID) { return IDOrPath{glyphID}; };
331
332 IDOrPath* const rawIDsOrPaths =
333 alloc->makeUniqueArray<IDOrPath>(get_glyphIDs(accepted), mapToIDOrPath).release();
334
335 return PathOpSubmitter{isAntiAliased,
336 strikeToSourceScale,
337 alloc->makePODSpan(get_positions(accepted)),
338 SkSpan(rawIDsOrPaths, accepted.size()),
339 std::move(strikePromise)};
340 }
341
342 void
343 PathOpSubmitter::submitDraws(SkCanvas* canvas, SkPoint drawOrigin, const SkPaint& paint) const {
344 // Convert the glyph IDs to paths if it hasn't been done yet. This is thread safe.
345 fConvertIDsToPaths([&]() {
346 if (SkStrike* strike = fStrikePromise.strike()) {
347 strike->glyphIDsToPaths(fIDsOrPaths);
348
349 // Drop ref to strike so that it can be purged from the cache if needed.
350 fStrikePromise.resetStrike();
351 fPathsAreCreated = true;
352 }
353 });
354
355 SkPaint runPaint{paint};
356 runPaint.setAntiAlias(fIsAntiAliased);
357
358 SkMaskFilterBase* maskFilter = as_MFB(runPaint.getMaskFilter());
359
360 // Calculate the matrix that maps the path glyphs from their size in the strike to
361 // the graphics source space.
362 SkMatrix strikeToSource = SkMatrix::Scale(fStrikeToSourceScale, fStrikeToSourceScale);
363 strikeToSource.postTranslate(drawOrigin.x(), drawOrigin.y());
364
365 // If there are shaders, non-blur mask filters or styles, the path must be scaled into source
366 // space independently of the CTM. This allows the CTM to be correct for the different effects.
367 SkStrokeRec style(runPaint);
368 bool needsExactCTM = runPaint.getShader()
369 || runPaint.getPathEffect()
370 || (!style.isFillStyle() && !style.isHairlineStyle())
371 || (maskFilter != nullptr && !maskFilter->asABlur(nullptr));
372 if (!needsExactCTM) {
373 SkMaskFilterBase::BlurRec blurRec;
374
375 // If there is a blur mask filter, then sigma needs to be adjusted to account for the
376 // scaling of fStrikeToSourceScale.
377 if (maskFilter != nullptr && maskFilter->asABlur(&blurRec)) {
378 runPaint.setMaskFilter(
379 SkMaskFilter::MakeBlur(blurRec.fStyle, blurRec.fSigma / fStrikeToSourceScale));
380 }
381 for (auto [idOrPath, pos] : SkMakeZip(fIDsOrPaths, fPositions)) {
382 // Transform the glyph to source space.
383 SkMatrix pathMatrix = strikeToSource;
384 pathMatrix.postTranslate(pos.x(), pos.y());
385
386 SkAutoCanvasRestore acr(canvas, true);
387 canvas->concat(pathMatrix);
388 canvas->drawPath(idOrPath.fPath, runPaint);
389 }
390 } else {
391 // Transform the path to device because the deviceMatrix must be unchanged to
392 // draw effect, filter or shader paths.
393 for (auto [idOrPath, pos] : SkMakeZip(fIDsOrPaths, fPositions)) {
394 // Transform the glyph to source space.
395 SkMatrix pathMatrix = strikeToSource;
396 pathMatrix.postTranslate(pos.x(), pos.y());
397
398 SkPath deviceOutline = idOrPath.fPath.makeTransform(pathMatrix);
399 deviceOutline.setIsVolatile(true);
400 canvas->drawPath(deviceOutline, runPaint);
401 }
402 }
403 }
404
405 // -- PathSubRun -----------------------------------------------------------------------------------
406 class PathSubRun final : public SubRun {
407 public:
408 PathSubRun(PathOpSubmitter&& pathDrawing) : fPathDrawing(std::move(pathDrawing)) {}
409
410 static SubRunOwner Make(SkZip<const SkGlyphID, const SkPoint> accepted,
411 bool isAntiAliased,
412 SkScalar strikeToSourceScale,
413 SkStrikePromise&& strikePromise,
414 SubRunAllocator* alloc) {
415 return alloc->makeUnique<PathSubRun>(
416 PathOpSubmitter::Make(
417 accepted, isAntiAliased, strikeToSourceScale, std::move(strikePromise), alloc));
418 }
419
420 void draw(SkCanvas* canvas,
421 SkPoint drawOrigin,
422 const SkPaint& paint,
423 sk_sp<SkRefCnt>,
424 const AtlasDrawDelegate&) const override {
425 fPathDrawing.submitDraws(canvas, drawOrigin, paint);
426 }
427
428 int unflattenSize() const override;
429
430 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
431 return true;
432 }
433 const AtlasSubRun* testingOnly_atlasSubRun() const override { return nullptr; }
434 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
435 SubRunAllocator* alloc,
436 const SkStrikeClient* client);
437
438 protected:
439 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kPathStreamTag; }
440 void doFlatten(SkWriteBuffer& buffer) const override;
441
442 private:
443 PathOpSubmitter fPathDrawing;
444 };
445
446 int PathSubRun::unflattenSize() const {
447 return sizeof(PathSubRun) + fPathDrawing.unflattenSize();
448 }
449
450 void PathSubRun::doFlatten(SkWriteBuffer& buffer) const {
451 fPathDrawing.flatten(buffer);
452 }
453
454 SubRunOwner PathSubRun::MakeFromBuffer(SkReadBuffer& buffer,
455 SubRunAllocator* alloc,
456 const SkStrikeClient* client) {
457 auto pathOpSubmitter = PathOpSubmitter::MakeFromBuffer(buffer, alloc, client);
458 if (!buffer.validate(pathOpSubmitter.has_value())) { return nullptr; }
459 return alloc->makeUnique<PathSubRun>(std::move(*pathOpSubmitter));
460 }
461
462 // -- DrawableOpSubmitter --------------------------------------------------------------------------
463 // Shared code for submitting GPU ops for drawing glyphs as drawables.
464 class DrawableOpSubmitter {
465 public:
466 DrawableOpSubmitter() = delete;
467 DrawableOpSubmitter(const DrawableOpSubmitter&) = delete;
468 const DrawableOpSubmitter& operator=(const DrawableOpSubmitter&) = delete;
469 DrawableOpSubmitter(DrawableOpSubmitter&& that)
470 : fStrikeToSourceScale{that.fStrikeToSourceScale}
471 , fPositions{that.fPositions}
472 , fIDsOrDrawables{that.fIDsOrDrawables}
473 , fStrikePromise{std::move(that.fStrikePromise)} {}
474 DrawableOpSubmitter& operator=(DrawableOpSubmitter&& that) {
475 this->~DrawableOpSubmitter();
476 new (this) DrawableOpSubmitter{std::move(that)};
477 return *this;
478 }
479 DrawableOpSubmitter(SkScalar strikeToSourceScale,
480 SkSpan<SkPoint> positions,
481 SkSpan<IDOrDrawable> idsOrDrawables,
482 SkStrikePromise&& strikePromise);
483
484 static DrawableOpSubmitter Make(SkZip<const SkGlyphID, const SkPoint> accepted,
485 SkScalar strikeToSourceScale,
486 SkStrikePromise&& strikePromise,
487 SubRunAllocator* alloc) {
488 auto mapToIDOrDrawable = [](const SkGlyphID glyphID) { return IDOrDrawable{glyphID}; };
489
490 return DrawableOpSubmitter{
491 strikeToSourceScale,
492 alloc->makePODSpan(get_positions(accepted)),
493 alloc->makePODArray<IDOrDrawable>(get_glyphIDs(accepted), mapToIDOrDrawable),
494 std::move(strikePromise)};
495 }
496
497 int unflattenSize() const;
498 void flatten(SkWriteBuffer& buffer) const;
499 static std::optional<DrawableOpSubmitter> MakeFromBuffer(SkReadBuffer& buffer,
500 SubRunAllocator* alloc,
501 const SkStrikeClient* client);
502 void submitDraws(SkCanvas* canvas, SkPoint drawOrigin, const SkPaint& paint) const;
503
504 private:
505 const SkScalar fStrikeToSourceScale;
506 const SkSpan<SkPoint> fPositions;
507 const SkSpan<IDOrDrawable> fIDsOrDrawables;
508 // When the promise is converted to a strike it acts as the ref on the strike to keep the
509 // SkDrawable data alive.
510 mutable SkStrikePromise fStrikePromise;
511 mutable SkOnce fConvertIDsToDrawables;
512 };
513
514 int DrawableOpSubmitter::unflattenSize() const {
515 return fPositions.size_bytes() + fIDsOrDrawables.size_bytes();
516 }
517
518 void DrawableOpSubmitter::flatten(SkWriteBuffer& buffer) const {
519 fStrikePromise.flatten(buffer);
520
521 buffer.writeScalar(fStrikeToSourceScale);
522 buffer.writePointArray(fPositions);
523 for (IDOrDrawable idOrDrawable : fIDsOrDrawables) {
524 buffer.writeInt(idOrDrawable.fGlyphID);
525 }
526 }
527
528 std::optional<DrawableOpSubmitter> DrawableOpSubmitter::MakeFromBuffer(
529 SkReadBuffer& buffer, SubRunAllocator* alloc, const SkStrikeClient* client) {
530 std::optional<SkStrikePromise> strikePromise =
531 SkStrikePromise::MakeFromBuffer(buffer, client, SkStrikeCache::GlobalStrikeCache());
532 if (!buffer.validate(strikePromise.has_value())) {
533 return std::nullopt;
534 }
535
536 SkScalar strikeToSourceScale = buffer.readScalar();
537 if (!buffer.validate(0 < strikeToSourceScale)) { return std::nullopt; }
538
•539 SkSpan<SkPoint> positions = make_points_from_buffer(buffer, alloc);
540 if (positions.empty()) { return std::nullopt; }
541 const int glyphCount = SkCount(positions);
542
543 if (!buffer.validateCanReadN<int>(glyphCount)) { return std::nullopt; }
544 auto idsOrDrawables = alloc->makePODArray<IDOrDrawable>(glyphCount);
545 for (int i = 0; i < SkToInt(glyphCount); ++i) {
546 // Remember, we stored an int for glyph id.
547 idsOrDrawables[i].fGlyphID = SkTo<SkGlyphID>(buffer.readInt());
548 }
549
550 if (!buffer.isValid()) {
551 return std::nullopt;
552 }
553
554 return DrawableOpSubmitter{strikeToSourceScale,
555 positions,
556 SkSpan(idsOrDrawables, glyphCount),
557 std::move(strikePromise.value())};
558 }
559
560 DrawableOpSubmitter::DrawableOpSubmitter(
561 SkScalar strikeToSourceScale,
562 SkSpan<SkPoint> positions,
563 SkSpan<IDOrDrawable> idsOrDrawables,
564 SkStrikePromise&& strikePromise)
565 : fStrikeToSourceScale{strikeToSourceScale}
566 , fPositions{positions}
567 , fIDsOrDrawables{idsOrDrawables}
568 , fStrikePromise(std::move(strikePromise)) {
569 SkASSERT(!fPositions.empty());
570 }
571
572 void
573 DrawableOpSubmitter::submitDraws(SkCanvas* canvas, SkPoint drawOrigin,const SkPaint& paint) const {
574 // Convert glyph IDs to Drawables if it hasn't been done yet.
575 fConvertIDsToDrawables([&]() {
576 fStrikePromise.strike()->glyphIDsToDrawables(fIDsOrDrawables);
577 // Do not call resetStrike() because the strike must remain owned to ensure the Drawable
578 // data is not freed.
579 });
580
581 // Calculate the matrix that maps the path glyphs from their size in the strike to
582 // the graphics source space.
583 SkMatrix strikeToSource = SkMatrix::Scale(fStrikeToSourceScale, fStrikeToSourceScale);
584 strikeToSource.postTranslate(drawOrigin.x(), drawOrigin.y());
585
586 // Transform the path to device because the deviceMatrix must be unchanged to
587 // draw effect, filter or shader paths.
588 for (auto [i, position] : SkMakeEnumerate(fPositions)) {
589 SkDrawable* drawable = fIDsOrDrawables[i].fDrawable;
590
591 if (drawable == nullptr) {
592 // This better be pinned to keep the drawable data alive.
593 fStrikePromise.strike()->verifyPinnedStrike();
594 SkDEBUGFAIL("Drawable should not be nullptr.");
595 continue;
596 }
597
598 // Transform the glyph to source space.
599 SkMatrix pathMatrix = strikeToSource;
600 pathMatrix.postTranslate(position.x(), position.y());
601
602 SkAutoCanvasRestore acr(canvas, false);
603 SkRect drawableBounds = drawable->getBounds();
604 pathMatrix.mapRect(&drawableBounds);
605 canvas->saveLayer(&drawableBounds, &paint);
606 drawable->draw(canvas, &pathMatrix);
607 }
608 }
609
610 // -- DrawableSubRun -------------------------------------------------------------------------------
611 class DrawableSubRun : public SubRun {
612 public:
613 DrawableSubRun(DrawableOpSubmitter&& drawingDrawing)
614 : fDrawingDrawing(std::move(drawingDrawing)) {}
615
616 static SubRunOwner Make(SkZip<const SkGlyphID, const SkPoint> drawables,
617 SkScalar strikeToSourceScale,
618 SkStrikePromise&& strikePromise,
619 SubRunAllocator* alloc) {
620 return alloc->makeUnique<DrawableSubRun>(
621 DrawableOpSubmitter::Make(drawables,
622 strikeToSourceScale,
623 std::move(strikePromise),
624 alloc));
625 }
626
627 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
628 SubRunAllocator* alloc,
629 const SkStrikeClient* client);
630
631 void draw(SkCanvas* canvas,
632 SkPoint drawOrigin,
633 const SkPaint& paint,
634 sk_sp<SkRefCnt>,
635 const AtlasDrawDelegate&) const override {
636 fDrawingDrawing.submitDraws(canvas, drawOrigin, paint);
637 }
638
639 int unflattenSize() const override;
640
641 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override;
642
643 const AtlasSubRun* testingOnly_atlasSubRun() const override;
644
645 protected:
646 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kDrawableStreamTag; }
647 void doFlatten(SkWriteBuffer& buffer) const override;
648
649 private:
650 DrawableOpSubmitter fDrawingDrawing;
651 };
652
653 int DrawableSubRun::unflattenSize() const {
654 return sizeof(DrawableSubRun) + fDrawingDrawing.unflattenSize();
655 }
656
657 void DrawableSubRun::doFlatten(SkWriteBuffer& buffer) const {
658 fDrawingDrawing.flatten(buffer);
659 }
660
661 SubRunOwner DrawableSubRun::MakeFromBuffer(SkReadBuffer& buffer,
662 SubRunAllocator* alloc,
663 const SkStrikeClient* client) {
664 auto drawableOpSubmitter = DrawableOpSubmitter::MakeFromBuffer(buffer, alloc, client);
665 if (!buffer.validate(drawableOpSubmitter.has_value())) { return nullptr; }
666 return alloc->makeUnique<DrawableSubRun>(std::move(*drawableOpSubmitter));
667 }
668
669 bool DrawableSubRun::canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const {
670 return true;
671 }
672
673 const AtlasSubRun* DrawableSubRun::testingOnly_atlasSubRun() const {
674 return nullptr;
675 }
676
677 // -- DirectMaskSubRun -----------------------------------------------------------------------------
678 class DirectMaskSubRun final : public AtlasSubRun {
679 public:
•680 static constexpr int kGlyphInsetting = 0;
681
682 DirectMaskSubRun(VertexFiller&& vertexFiller,
683 GlyphVector&& glyphs)
684 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs)) {}
685
686 static SubRunOwner Make(SkRect creationBounds,
687 SkZip<const SkPackedGlyphID, const SkPoint> accepted,
688 const SkMatrix& creationMatrix,
689 SkStrikePromise&& strikePromise,
690 MaskFormat maskType,
691 SubRunAllocator* alloc) {
692 auto vertexFiller = VertexFiller::Make(maskType,
693 creationMatrix,
694 creationBounds,
695 get_positions(accepted),
696 alloc,
697 kIsDirect);
698
699 auto glyphVector =
700 GlyphVector::Make(std::move(strikePromise), get_packedIDs(accepted), alloc);
701
702 return alloc->makeUnique<DirectMaskSubRun>(std::move(vertexFiller), std::move(glyphVector));
703 }
704
705 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
706 SubRunAllocator* alloc,
707 const SkStrikeClient* client) {
708 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
709 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
•710 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
711 skglyph::kDirectMask, kGlyphInsetting);
712 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
713
714 SkASSERT(buffer.isValid());
715 return alloc->makeUnique<DirectMaskSubRun>(
716 std::move(*vertexFiller), std::move(*glyphVector));
717 }
718
719 void draw(SkCanvas*,
720 SkPoint drawOrigin,
721 const SkPaint& paint,
722 sk_sp<SkRefCnt> subRunStorage,
723 const AtlasDrawDelegate& drawAtlas) const override {
724 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
725 {/* isSDF = */false, fVertexFiller.isLCD(), fVertexFiller.grMaskType()});
726 }
727
728 int unflattenSize() const override {
729 return sizeof(DirectMaskSubRun) +
730 fGlyphs.unflattenSize() +
731 fVertexFiller.unflattenSize();
732 }
733
•734 int glyphSrcPadding() const override { return kGlyphInsetting; }
735
736 void testingOnly_packedGlyphIDToGlyph(StrikeCache* cache,
737 skgpu::MaskFormat maskFormat) const override {
738 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
739 }
740
741 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
742 const SkMatrix &positionMatrix) const override {
743 auto [integerTranslate, deviceRect] =
744 fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
745 return {!integerTranslate, deviceRect};
746 }
747
748 GlyphParams glyphParams() const override {
749 // Since this is non-SDF, isAA will be ignored so we just pass true
750 return { /*isSDF=*/false, fVertexFiller.isLCD(), /*isAA=*/true };
751 }
752
753 std::tuple<bool, int> regenerateAtlas(int begin, int end,
754 RegenerateAtlasDelegate regenerateAtlas) const override {
755 return regenerateAtlas(
756 &fGlyphs, begin, end, fVertexFiller.grMaskType(), this->glyphSrcPadding());
757 }
758
759 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
760 auto [reuse, _] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
761 return reuse;
762 }
763
764 const AtlasSubRun* testingOnly_atlasSubRun() const override {
765 return this;
766 }
767
768 protected:
769 SubRunStreamTag subRunStreamTag() const override {
770 return SubRunStreamTag::kDirectMaskStreamTag;
771 }
772
773 void doFlatten(SkWriteBuffer& buffer) const override {
774 fGlyphs.flatten(buffer);
•775 flatten_vertex_filler(buffer, fVertexFiller);
776 }
777 };
778
779 // -- TransformedMaskSubRun ------------------------------------------------------------------------
780 class TransformedMaskSubRun final : public AtlasSubRun {
781 public:
•782 static constexpr int kGlyphInsetting = 0;
783
784 TransformedMaskSubRun(bool isBigEnough,
785 VertexFiller&& vertexFiller,
786 GlyphVector&& glyphs)
787 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs))
788 , fIsBigEnough{isBigEnough} {}
789
790 static SubRunOwner Make(SkZip<const SkPackedGlyphID, const SkPoint> accepted,
791 const SkMatrix& initialPositionMatrix,
792 SkStrikePromise&& strikePromise,
793 SkMatrix creationMatrix,
794 SkRect creationBounds,
795 MaskFormat maskType,
796 SubRunAllocator* alloc) {
797 auto vertexFiller = VertexFiller::Make(maskType,
798 creationMatrix,
799 creationBounds,
800 get_positions(accepted),
801 alloc,
802 kIsTransformed);
803
804 auto glyphVector = GlyphVector::Make(
805 std::move(strikePromise), get_packedIDs(accepted), alloc);
806
807 return alloc->makeUnique<TransformedMaskSubRun>(
•808 AtlasSubRun::IsBigEnough(initialPositionMatrix),
809 std::move(vertexFiller),
810 std::move(glyphVector));
811 }
812
813 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
814 SubRunAllocator* alloc,
815 const SkStrikeClient* client) {
816 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
817 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
•818 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
819 skglyph::kMask, kGlyphInsetting);
820 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
821
822 const bool isBigEnough = buffer.readBool();
823 return alloc->makeUnique<TransformedMaskSubRun>(
•824 AtlasSubRun::IsBigEnough(vertexFiller->creationMatrix()),
825 std::move(*vertexFiller), std::move(*glyphVector));
826 }
827
828 int unflattenSize() const override {
829 return sizeof(TransformedMaskSubRun) +
830 fGlyphs.unflattenSize() +
831 fVertexFiller.unflattenSize();
832 }
833
834 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
835 // If we are not scaling the cache entry to be larger, than a cache with smaller glyphs may
836 // be better.
837 return fIsBigEnough;
838 }
839
840 const AtlasSubRun* testingOnly_atlasSubRun() const override { return this; }
841
842 void testingOnly_packedGlyphIDToGlyph(StrikeCache *cache,
843 skgpu::MaskFormat maskFormat) const override {
844 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
845 }
846
•847 int glyphSrcPadding() const override { return 1; } // Padding NOT equal to insetting
848
849 void draw(SkCanvas*,
850 SkPoint drawOrigin,
851 const SkPaint& paint,
852 sk_sp<SkRefCnt> subRunStorage,
853 const AtlasDrawDelegate& drawAtlas) const override {
854 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
855 {/* isSDF = */false, fVertexFiller.isLCD(), fVertexFiller.grMaskType()});
856 }
857
858 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
859 const SkMatrix &positionMatrix) const override {
860 auto [_, deviceRect] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
861 return {true, deviceRect};
862 }
863
864 GlyphParams glyphParams() const override {
865 // Since this is non-SDF, isAA will be ignored so we just pass true
866 return { /*isSDF=*/false, fVertexFiller.isLCD(), /*isAA=*/true };
867 }
868
869 std::tuple<bool, int> regenerateAtlas(int begin, int end,
870 RegenerateAtlasDelegate regenerateAtlas) const override {
871 return regenerateAtlas(
872 &fGlyphs, begin, end, fVertexFiller.grMaskType(), this->glyphSrcPadding());
873 }
874
875 protected:
876 SubRunStreamTag subRunStreamTag() const override {
877 return SubRunStreamTag::kTransformMaskStreamTag;
878 }
879
880 void doFlatten(SkWriteBuffer& buffer) const override {
881 fGlyphs.flatten(buffer);
•882 flatten_vertex_filler(buffer, fVertexFiller);
883 }
884
885 private:
886 const bool fIsBigEnough;
887 }; // class TransformedMaskSubRun
888
889 // -- SDFTSubRun -----------------------------------------------------------------------------------
890
891 bool has_some_antialiasing(const SkFont& font ) {
892 SkFont::Edging edging = font.getEdging();
893 return edging == SkFont::Edging::kAntiAlias
894 || edging == SkFont::Edging::kSubpixelAntiAlias;
895 }
896
897 #if !defined(SK_DISABLE_SDF_TEXT)
898
899 class SDFTSubRun final : public AtlasSubRun {
900 public:
•901 static constexpr int kGlyphInsetting = SK_DistanceFieldInset;
902
903 SDFTSubRun(bool useLCDText,
904 bool antiAliased,
905 const SDFTMatrixRange& matrixRange,
906 VertexFiller&& vertexFiller,
907 GlyphVector&& glyphs)
908 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs))
909 , fUseLCDText{useLCDText}
910 , fAntiAliased{antiAliased}
911 , fMatrixRange{matrixRange} {
•912 SkASSERT_RELEASE(fVertexFiller.grMaskType() == MaskFormat::kA8);
913 }
914
915 static SubRunOwner Make(SkZip<const SkPackedGlyphID, const SkPoint> accepted,
916 const SkFont& runFont,
917 SkStrikePromise&& strikePromise,
918 const SkMatrix& creationMatrix,
919 SkRect creationBounds,
920 const SDFTMatrixRange& matrixRange,
921 SubRunAllocator* alloc) {
922 // NOTE: The MaskFormat is hard coded to kA8 here. This means that when isLCD() is called
923 // from VertexFiller, it always returns false. However, VertexFiller has no other behavior
924 // that depends on this function, and drawAtlasSubrun instead determines LCD based on the
925 // fUseLCDText member variable. If this ever changes, VertexFiller will need to take an
926 // additional isLCD argument on the constructor.
927 auto vertexFiller = VertexFiller::Make(MaskFormat::kA8,
928 creationMatrix,
929 creationBounds,
930 get_positions(accepted),
931 alloc,
932 kIsTransformed);
933
934 auto glyphVector = GlyphVector::Make(
935 std::move(strikePromise), get_packedIDs(accepted), alloc);
936
937 // NOTE: When creating the SubRun, only the runFont edging determines LCD usage. This is
938 // because the upstream preparation in SubRunContainer::MakeInAlloc is identical between
939 // LCD and non-LCD. Instead LCD is set here, so that when the subRun is consumed in
940 // drawAtlasSubRun, the SDFLCD renderer is chosen.
941 return alloc->makeUnique<SDFTSubRun>(
942 runFont.getEdging() == SkFont::Edging::kSubpixelAntiAlias,
943 has_some_antialiasing(runFont),
944 matrixRange,
945 std::move(vertexFiller),
946 std::move(glyphVector));
947 }
948
949 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
950 SubRunAllocator* alloc,
951 const SkStrikeClient* client) {
952 int useLCD = buffer.readInt();
953 int isAntiAliased = buffer.readInt();
954 SDFTMatrixRange matrixRange = SDFTMatrixRange::MakeFromBuffer(buffer);
•955
956 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
957 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
•958 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
959 skglyph::kSDFT, kGlyphInsetting);
960 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
961
•962 if (!buffer.validate(vertexFiller->maskFormat() == MaskFormat::kA8)) { return nullptr; }
963
964 return alloc->makeUnique<SDFTSubRun>(useLCD,
965 isAntiAliased,
966 matrixRange,
967 std::move(*vertexFiller),
968 std::move(*glyphVector));
969 }
970
971 int unflattenSize() const override {
972 return sizeof(SDFTSubRun) + fGlyphs.unflattenSize() + fVertexFiller.unflattenSize();
973 }
974
975 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
976 return fMatrixRange.matrixInRange(positionMatrix);
977 }
978
979 const AtlasSubRun* testingOnly_atlasSubRun() const override { return this; }
980
981 void testingOnly_packedGlyphIDToGlyph(StrikeCache *cache,
982 skgpu::MaskFormat maskFormat) const override {
983 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
984 }
985
•986 int glyphSrcPadding() const override { return kGlyphInsetting; }
987
988 void draw(SkCanvas*,
989 SkPoint drawOrigin,
990 const SkPaint& paint,
991 sk_sp<SkRefCnt> subRunStorage,
992 const AtlasDrawDelegate& drawAtlas) const override {
993 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
994 {/* isSDF = */true, /* isLCD = */fUseLCDText, skgpu::MaskFormat::kA8});
995 }
996
997 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
998 const SkMatrix &positionMatrix) const override {
999 auto [_, deviceRect] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
1000 return {true, deviceRect};
1001 }
1002
1003 GlyphParams glyphParams() const override {
1004 return { /*isSDF=*/true, fUseLCDText, /*isAA=*/fAntiAliased };
1005 }
1006
1007 std::tuple<bool, int> regenerateAtlas(int begin, int end,
1008 RegenerateAtlasDelegate regenerateAtlas) const override {
1009 return regenerateAtlas(&fGlyphs, begin, end, MaskFormat::kA8, this->glyphSrcPadding());
1010 }
1011
1012 protected:
1013 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kSDFTStreamTag; }
1014 void doFlatten(SkWriteBuffer& buffer) const override {
1015 buffer.writeInt(fUseLCDText);
1016 buffer.writeInt(fAntiAliased);
1017 fMatrixRange.flatten(buffer);
1018 fGlyphs.flatten(buffer);
•1019 flatten_vertex_filler(buffer, fVertexFiller);
1020 }
1021
1022 private:
1023 const bool fUseLCDText;
1024 const bool fAntiAliased;
1025 const SDFTMatrixRange fMatrixRange;
1026 }; // class SDFTSubRun
1027
1028 #endif // !defined(SK_DISABLE_SDF_TEXT)
1029
1030 // -- SubRun ---------------------------------------------------------------------------------------
1031
1032 template<typename AddSingleMaskFormat>
1033 void add_multi_mask_format(
1034 AddSingleMaskFormat addSingleMaskFormat,
1035 SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format> accepted) {
1036 if (accepted.empty()) { return; }
1037
1038 auto maskSpan = accepted.get<2>();
1039 MaskFormat format = Glyph::FormatFromSkGlyph(maskSpan[0]);
1040 size_t startIndex = 0;
1041 for (size_t i = 1; i < accepted.size(); i++) {
1042 MaskFormat nextFormat = Glyph::FormatFromSkGlyph(maskSpan[i]);
1043 if (format != nextFormat) {
1044 auto interval = accepted.subspan(startIndex, i - startIndex);
1045 // Only pass the packed glyph ids and positions.
1046 auto glyphsWithSameFormat = SkMakeZip(interval.get<0>(), interval.get<1>());
1047 // Take a ref on the strike. This should rarely happen.
1048 addSingleMaskFormat(glyphsWithSameFormat, format);
1049 format = nextFormat;
1050 startIndex = i;
1051 }
1052 }
1053 auto interval = accepted.last(accepted.size() - startIndex);
1054 auto glyphsWithSameFormat = SkMakeZip(interval.get<0>(), interval.get<1>());
1055 addSingleMaskFormat(glyphsWithSameFormat, format);
1056 }
1057 } // anonymous namespace
1058
1059 namespace sktext::gpu {
1060 SubRun::~SubRun() = default;
•1061
1062 void SubRun::flatten(SkWriteBuffer& buffer) const {
1063 buffer.writeInt(this->subRunStreamTag());
1064 this->doFlatten(buffer);
1065 }
1066
1067 SubRunOwner SubRun::MakeFromBuffer(SkReadBuffer& buffer,
1068 SubRunAllocator* alloc,
1069 const SkStrikeClient* client) {
1070 using Maker = SubRunOwner (*)(SkReadBuffer&,
1071 SubRunAllocator*,
1072 const SkStrikeClient*);
1073
1074 static Maker makers[kSubRunStreamTagCount] = {
1075 nullptr, // 0 index is bad.
1076 DirectMaskSubRun::MakeFromBuffer,
1077 #if !defined(SK_DISABLE_SDF_TEXT)
1078 SDFTSubRun::MakeFromBuffer,
1079 #endif
1080 TransformedMaskSubRun::MakeFromBuffer,
1081 PathSubRun::MakeFromBuffer,
1082 DrawableSubRun::MakeFromBuffer,
1083 };
1084 int subRunTypeInt = buffer.readInt();
1085 if (!buffer.validate(kBad < subRunTypeInt && subRunTypeInt < kSubRunStreamTagCount)) {
1086 return nullptr;
1087 }
1088 auto maker = makers[subRunTypeInt];
1089 if (!buffer.validate(maker != nullptr)) { return nullptr; }
1090 return maker(buffer, alloc, client);
1091 }
1092
1093 // -- SubRunContainer ------------------------------------------------------------------------------
1094 SubRunContainer::SubRunContainer(const SkMatrix& initialPositionMatrix)
1095 : fInitialPositionMatrix{initialPositionMatrix} {}
1096
1097 void SubRunContainer::flattenAllocSizeHint(SkWriteBuffer& buffer) const {
1098 int unflattenSizeHint = 0;
1099 for (auto& subrun : fSubRuns) {
1100 unflattenSizeHint += subrun.unflattenSize();
1101 }
1102 buffer.writeInt(unflattenSizeHint);
1103 }
1104
1105 int SubRunContainer::AllocSizeHintFromBuffer(SkReadBuffer& buffer) {
1106 int subRunsSizeHint = buffer.readInt();
1107
1108 // Since the hint doesn't affect correctness, if it looks fishy just pick a reasonable
1109 // value.
1110 if (subRunsSizeHint < 0 || (1 << 16) < subRunsSizeHint) {
1111 subRunsSizeHint = 128;
1112 }
1113 return subRunsSizeHint;
1114 }
1115
1116 void SubRunContainer::flattenRuns(SkWriteBuffer& buffer) const {
1117 buffer.writeMatrix(fInitialPositionMatrix);
1118 int subRunCount = 0;
1119 for ([[maybe_unused]] auto& subRun : fSubRuns) {
1120 subRunCount += 1;
1121 }
1122 buffer.writeInt(subRunCount);
1123 for (auto& subRun : fSubRuns) {
1124 subRun.flatten(buffer);
1125 }
1126 }
1127
1128 SubRunContainerOwner SubRunContainer::MakeFromBufferInAlloc(SkReadBuffer& buffer,
1129 const SkStrikeClient* client,
1130 SubRunAllocator* alloc) {
1131 SkMatrix positionMatrix;
1132 buffer.readMatrix(&positionMatrix);
1133 if (!buffer.isValid()) { return nullptr; }
1134 SubRunContainerOwner container = alloc->makeUnique<SubRunContainer>(positionMatrix);
1135
1136 int subRunCount = buffer.readInt();
1137 if (!buffer.validate(subRunCount > 0)) { return nullptr; }
1138 for (int i = 0; i < subRunCount; ++i) {
1139 auto subRunOwner = SubRun::MakeFromBuffer(buffer, alloc, client);
1140 if (!buffer.validate(subRunOwner != nullptr)) { return nullptr; }
1141 if (subRunOwner != nullptr) {
1142 container->fSubRuns.append(std::move(subRunOwner));
1143 }
1144 }
1145 return container;
1146 }
1147
1148 size_t SubRunContainer::EstimateAllocSize(const GlyphRunList& glyphRunList) {
1149 // The difference in alignment from the per-glyph data to the SubRun;
1150 constexpr size_t alignDiff = alignof(DirectMaskSubRun) - alignof(SkPoint);
1151 constexpr size_t vertexDataToSubRunPadding = alignDiff > 0 ? alignDiff : 0;
1152 size_t totalGlyphCount = glyphRunList.totalGlyphCount();
1153 // This is optimized for DirectMaskSubRun which is by far the most common case.
1154 return totalGlyphCount * sizeof(SkPoint)
1155 + GlyphVector::GlyphVectorSize(totalGlyphCount)
1156 + glyphRunList.runCount() * (sizeof(DirectMaskSubRun) + vertexDataToSubRunPadding)
1157 + sizeof(SubRunContainer);
1158 }
1159
1160 SkScalar find_maximum_glyph_dimension(StrikeForGPU* strike, SkSpan<const SkGlyphID> glyphs) {
1161 StrikeMutationMonitor m{strike};
1162 SkScalar maxDimension = 0;
1163 for (SkGlyphID glyphID : glyphs) {
1164 SkGlyphDigest digest = strike->digestFor(kMask, SkPackedGlyphID{glyphID});
1165 maxDimension = std::max(static_cast<SkScalar>(digest.maxDimension()), maxDimension);
1166 }
1167
1168 return maxDimension;
1169 }
1170
1171 #if !defined(SK_DISABLE_SDF_TEXT)
1172 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>, SkRect>
1173 prepare_for_SDFT_drawing(StrikeForGPU* strike,
1174 const SkMatrix& creationMatrix,
1175 SkZip<const SkGlyphID, const SkPoint> source,
1176 SkZip<SkPackedGlyphID, SkPoint> acceptedBuffer,
1177 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1178 int acceptedSize = 0,
1179 rejectedSize = 0;
1180 SkGlyphRect boundingRect = skglyph::empty_rect();
1181 StrikeMutationMonitor m{strike};
1182 for (const auto [glyphID, pos] : source) {
1183 if (!SkIsFinite(pos.x(), pos.y())) {
1184 continue;
1185 }
1186
1187 const SkPackedGlyphID packedID{glyphID};
1188 switch (const SkGlyphDigest digest = strike->digestFor(skglyph::kSDFT, packedID);
1189 digest.actionFor(skglyph::kSDFT)) {
1190 case GlyphAction::kAccept: {
1191 SkPoint mappedPos = creationMatrix.mapPoint(pos);
1192 const SkGlyphRect glyphBounds =
•1193 glyph_bounds(digest, SDFTSubRun::kGlyphInsetting, mappedPos);
1194 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1195 acceptedBuffer[acceptedSize++] = std::make_tuple(packedID, glyphBounds.leftTop());
1196 break;
1197 }
1198 case GlyphAction::kReject:
1199 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1200 break;
1201 default:
1202 break;
1203 }
1204 }
1205
1206 return {acceptedBuffer.first(acceptedSize),
1207 rejectedBuffer.first(rejectedSize),
1208 boundingRect.rect()};
1209 }
1210 #endif
1211
1212 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format>,
1213 SkZip<SkGlyphID, SkPoint>,
1214 SkRect>
1215 prepare_for_direct_mask_drawing(StrikeForGPU* strike,
1216 const SkMatrix& positionMatrix,
1217 SkZip<const SkGlyphID, const SkPoint> source,
1218 SkZip<SkPackedGlyphID, SkPoint, SkMask::Format> acceptedBuffer,
1219 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1220 const SkIPoint mask = strike->roundingSpec().ignorePositionFieldMask;
1221 const SkPoint halfSampleFreq = strike->roundingSpec().halfAxisSampleFreq;
1222
1223 // Build up the mapping from source space to device space. Add the rounding constant
1224 // halfSampleFreq, so we just need to floor to get the device result.
1225 SkMatrix positionMatrixWithRounding = positionMatrix;
1226 positionMatrixWithRounding.postTranslate(halfSampleFreq.x(), halfSampleFreq.y());
1227
1228 int acceptedSize = 0,
1229 rejectedSize = 0;
1230 SkGlyphRect boundingRect = skglyph::empty_rect();
1231 StrikeMutationMonitor m{strike};
1232 for (auto [glyphID, pos] : source) {
1233 if (!SkIsFinite(pos.x(), pos.y())) {
1234 continue;
1235 }
1236
1237 const SkPoint mappedPos = positionMatrixWithRounding.mapPoint(pos);
1238 const SkPackedGlyphID packedID{glyphID, mappedPos, mask};
1239 switch (const SkGlyphDigest digest = strike->digestFor(skglyph::kDirectMask, packedID);
1240 digest.actionFor(skglyph::kDirectMask)) {
1241 case GlyphAction::kAccept: {
1242 const SkPoint roundedPos{SkScalarFloorToScalar(mappedPos.x()),
1243 SkScalarFloorToScalar(mappedPos.y())};
•1244 const SkGlyphRect glyphBounds = glyph_bounds(digest,
1245 DirectMaskSubRun::kGlyphInsetting,
1246 roundedPos);
1247 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1248 acceptedBuffer[acceptedSize++] =
1249 std::make_tuple(packedID, glyphBounds.leftTop(), digest.maskFormat());
1250 break;
1251 }
1252 case GlyphAction::kReject:
1253 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1254 break;
1255 default:
1256 break;
1257 }
1258 }
1259
1260 return {acceptedBuffer.first(acceptedSize),
1261 rejectedBuffer.first(rejectedSize),
1262 boundingRect.rect()};
1263 }
1264
1265 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format>,
1266 SkZip<SkGlyphID, SkPoint>,
1267 SkRect>
1268 prepare_for_mask_drawing(StrikeForGPU* strike,
1269 const SkMatrix& creationMatrix,
1270 SkZip<const SkGlyphID, const SkPoint> source,
1271 SkZip<SkPackedGlyphID, SkPoint, SkMask::Format> acceptedBuffer,
1272 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1273 int acceptedSize = 0,
1274 rejectedSize = 0;
1275 SkGlyphRect boundingRect = skglyph::empty_rect();
1276 StrikeMutationMonitor m{strike};
1277 for (auto [glyphID, pos] : source) {
1278 if (!SkIsFinite(pos.x(), pos.y())) {
1279 continue;
1280 }
1281
1282 const SkPackedGlyphID packedID{glyphID};
1283 switch (const SkGlyphDigest digest = strike->digestFor(kMask, packedID);
1284 digest.actionFor(kMask)) {
1285 case GlyphAction::kAccept: {
1286 const SkPoint mappedPos = creationMatrix.mapPoint(pos);
•1287 const SkGlyphRect glyphBounds =
1288 glyph_bounds(digest, TransformedMaskSubRun::kGlyphInsetting, mappedPos);
1289 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1290 acceptedBuffer[acceptedSize++] =
1291 std::make_tuple(packedID, glyphBounds.leftTop(), digest.maskFormat());
1292 break;
1293 }
1294 case GlyphAction::kReject:
1295 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1296 break;
1297 default:
1298 break;
1299 }
1300 }
1301
1302 return {acceptedBuffer.first(acceptedSize),
1303 rejectedBuffer.first(rejectedSize),
1304 boundingRect.rect()};
1305 }
1306
1307 std::tuple<SkZip<const SkGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>>
1308 prepare_for_path_drawing(StrikeForGPU* strike,
1309 SkZip<const SkGlyphID, const SkPoint> source,
1310 SkZip<SkGlyphID, SkPoint> acceptedBuffer,
1311 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1312 int acceptedSize = 0;
1313 int rejectedSize = 0;
1314 StrikeMutationMonitor m{strike};
1315 for (const auto [glyphID, pos] : source) {
1316 if (!SkIsFinite(pos.x(), pos.y())) {
1317 continue;
1318 }
1319
1320 switch (strike->digestFor(skglyph::kPath, SkPackedGlyphID{glyphID})
1321 .actionFor(skglyph::kPath)) {
1322 case GlyphAction::kAccept:
1323 acceptedBuffer[acceptedSize++] = std::make_tuple(glyphID, pos);
1324 break;
1325 case GlyphAction::kReject:
1326 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1327 break;
1328 default:
1329 break;
1330 }
1331 }
1332 return {acceptedBuffer.first(acceptedSize), rejectedBuffer.first(rejectedSize)};
1333 }
1334
1335 std::tuple<SkZip<const SkGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>>
•1336 prepare_for_drawable_drawing(StrikeForGPU* strike,
1337 SkZip<const SkGlyphID, const SkPoint> source,
1338 SkZip<SkGlyphID, SkPoint> acceptedBuffer,
1339 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1340 int acceptedSize = 0;
1341 int rejectedSize = 0;
1342 StrikeMutationMonitor m{strike};
1343 for (const auto [glyphID, pos] : source) {
1344 if (!SkIsFinite(pos.x(), pos.y())) {
1345 continue;
1346 }
1347
1348 switch (strike->digestFor(skglyph::kDrawable, SkPackedGlyphID{glyphID})
1349 .actionFor(skglyph::kDrawable)) {
1350 case GlyphAction::kAccept:
1351 acceptedBuffer[acceptedSize++] = std::make_tuple(glyphID, pos);
1352 break;
1353 case GlyphAction::kReject:
1354 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1355 break;
1356 default:
1357 break;
1358 }
1359 }
1360 return {acceptedBuffer.first(acceptedSize), rejectedBuffer.first(rejectedSize)};
1361 }
1362
1363 #if !defined(SK_DISABLE_SDF_TEXT)
1364 static std::tuple<SkStrikeSpec, SkScalar, sktext::gpu::SDFTMatrixRange>
1365 make_sdft_strike_spec(const SkFont& font, const SkPaint& paint,
1366 const SkSurfaceProps& surfaceProps, const SkMatrix& deviceMatrix,
1367 const SkPoint& textLocation, const sktext::gpu::SubRunControl& control) {
1368 // Add filter to the paint which creates the SDFT data for A8 masks.
1369 SkPaint dfPaint{paint};
1370 dfPaint.setMaskFilter(sktext::gpu::SDFMaskFilter::Make());
1371
1372 auto [dfFont, strikeToSourceScale, matrixRange] = control.getSDFFont(font, deviceMatrix,
1373 textLocation);
1374
1375 // Adjust the stroke width by the scale factor for drawing the SDFT.
1376 dfPaint.setStrokeWidth(paint.getStrokeWidth() / strikeToSourceScale);
1377
1378 // Check for dashing and adjust the intervals.
1379 if (SkPathEffect* pathEffect = paint.getPathEffect(); pathEffect != nullptr) {
1380 if (auto info = as_PEB(pathEffect)->asADash()) {
1381 SkSpan<const SkScalar> src = info->fIntervals;
1382 SkASSERT(src.size() > 1);
1383 // Allocate the intervals.
1384 std::vector<SkScalar> scaledIntervals(src.size());
1385 for (size_t i = 0; i < src.size(); ++i) {
1386 scaledIntervals[i] = src[i] / strikeToSourceScale;
1387 }
1388 auto scaledDashes = SkDashPathEffect::Make(scaledIntervals,
1389 info->fPhase / strikeToSourceScale);
1390 dfPaint.setPathEffect(scaledDashes);
1391 }
1392 }
1393
1394 // Fake-gamma and subpixel antialiasing are applied in the shader, so we ignore the
1395 // passed-in scaler context flags. (It's only used when we fall-back to bitmap text).
1396 SkScalerContextFlags flags = SkScalerContextFlags::kNone;
1397 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeMask(dfFont, dfPaint, surfaceProps, flags,
1398 SkMatrix::I());
1399
1400 return std::make_tuple(std::move(strikeSpec), strikeToSourceScale, matrixRange);
1401 }
1402 #endif
1403
1404 SubRunContainerOwner SubRunContainer::MakeInAlloc(
1405 const GlyphRunList& glyphRunList,
1406 const SkMatrix& positionMatrix,
1407 const SkPaint& runPaint,
1408 SkStrikeDeviceInfo strikeDeviceInfo,
1409 StrikeForGPUCacheInterface* strikeCache,
1410 SubRunAllocator* alloc,
1411 SubRunCreationBehavior creationBehavior,
1412 const char* tag) {
1413 SkASSERT(alloc != nullptr);
1414 SkASSERT(strikeDeviceInfo.fSubRunControl != nullptr);
1415
1416 SubRunContainerOwner container = alloc->makeUnique<SubRunContainer>(positionMatrix);
1417 // If there is no SubRunControl description ignore all SubRuns.
1418 if (strikeDeviceInfo.fSubRunControl == nullptr) {
1419 return container;
1420 }
1421
1422 const SkSurfaceProps deviceProps = strikeDeviceInfo.fSurfaceProps;
1423 const SkScalerContextFlags scalerContextFlags = strikeDeviceInfo.fScalerContextFlags;
1424 const SubRunControl* subRunControl = strikeDeviceInfo.fSubRunControl;
1425 #if !defined(SK_DISABLE_SDF_TEXT)
1426 const SkScalar maxMaskSize = subRunControl->maxSize();
1427 #else
1428 const SkScalar maxMaskSize = 256;
1429 #endif
1430
1431 // TODO: hoist the buffer structure to the GlyphRunBuilder. The buffer structure here is
1432 // still begin tuned, and this is expected to be slower until tuned.
1433 const int maxGlyphRunSize = glyphRunList.maxGlyphRunSize();
1434
1435 // Accepted buffers.
1436 STArray<64, SkPackedGlyphID> acceptedPackedGlyphIDs;
1437 STArray<64, SkGlyphID> acceptedGlyphIDs;
1438 STArray<64, SkPoint> acceptedPositions;
1439 STArray<64, SkMask::Format> acceptedFormats;
1440 acceptedPackedGlyphIDs.resize(maxGlyphRunSize);
1441 acceptedGlyphIDs.resize(maxGlyphRunSize);
1442 acceptedPositions.resize(maxGlyphRunSize);
1443 acceptedFormats.resize(maxGlyphRunSize);
1444
1445 // Rejected buffers.
1446 STArray<64, SkGlyphID> rejectedGlyphIDs;
1447 STArray<64, SkPoint> rejectedPositions;
1448 rejectedGlyphIDs.resize(maxGlyphRunSize);
1449 rejectedPositions.resize(maxGlyphRunSize);
1450 const auto rejectedBuffer = SkMakeZip(rejectedGlyphIDs, rejectedPositions);
1451
1452 const SkPoint glyphRunListLocation = glyphRunList.sourceBounds().center();
1453
1454 // Handle all the runs in the glyphRunList
1455 for (auto& glyphRun : glyphRunList) {
1456 SkZip<const SkGlyphID, const SkPoint> source = glyphRun.source();
1457 const SkFont& runFont = glyphRun.font();
1458
1459 const SkScalar approximateDeviceTextSize =
1460 // Since the positionMatrix has the origin prepended, use the plain
1461 // sourceBounds from above.
1462 SkFontPriv::ApproximateTransformedTextSize(runFont, positionMatrix,
1463 glyphRunListLocation);
1464
1465 // Atlas mask cases - SDFT and direct mask
1466 // Only consider using direct or SDFT drawing if not drawing hairlines and not too big.
1467 if ((runPaint.getStyle() != SkPaint::kStroke_Style || runPaint.getStrokeWidth() != 0) &&
1468 approximateDeviceTextSize < maxMaskSize) {
1469
1470 #if !defined(SK_DISABLE_SDF_TEXT)
1471 // SDFT case
1472 if (subRunControl->isSDFT(approximateDeviceTextSize, runPaint, positionMatrix)) {
1473 // Process SDFT - This should be the .009% case.
1474 const auto& [strikeSpec, strikeToSourceScale, matrixRange] =
1475 make_sdft_strike_spec(
1476 runFont, runPaint, deviceProps, positionMatrix,
1477 glyphRunListLocation, *subRunControl);
1478
1479 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1480 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1481
1482 // The creationMatrix needs to scale the strike data when inverted and
1483 // multiplied by the positionMatrix. The final CTM should be:
1484 // [positionMatrix][scale by strikeToSourceScale],
1485 // which should equal the following because of the transform during the vertex
1486 // calculation,
1487 // [positionMatrix][creationMatrix]^-1.
1488 // So, the creation matrix needs to be
1489 // [scale by 1/strikeToSourceScale].
1490 SkMatrix creationMatrix =
1491 SkMatrix::Scale(1.f/strikeToSourceScale, 1.f/strikeToSourceScale);
1492
1493 auto acceptedBuffer = SkMakeZip(acceptedPackedGlyphIDs, acceptedPositions);
1494 auto [accepted, rejected, creationBounds] = prepare_for_SDFT_drawing(
1495 strike.get(), creationMatrix, source, acceptedBuffer, rejectedBuffer);
1496 source = rejected;
1497
1498 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1499 container->fSubRuns.append(SDFTSubRun::Make(
1500 accepted,
1501 runFont,
1502 strike->strikePromise(),
1503 creationMatrix,
1504 creationBounds,
1505 matrixRange,
1506 alloc));
1507 }
1508 }
1509 }
1510 #endif // !defined(SK_DISABLE_SDF_TEXT)
1511 // Mask filters with 3D format (e.g. EmbossMaskFilter) need to be drawn as a path
1512 // in order to apply the filter through the Canvas AutoLayer system.
1513 const bool needsAutoLayer = runPaint.getMaskFilter() &&
1514 as_MFB(runPaint.getMaskFilter())->getFormat() == SkMask::k3D_Format;
1515 // Direct Mask case
1516 // Handle all the directly mapped mask subruns.
1517 if (!source.empty() && !positionMatrix.hasPerspective() && !needsAutoLayer) {
1518 // Process masks including ARGB - this should be the 99.99% case.
1519 // This will handle medium size emoji that are sharing the run with SDFT drawn text.
1520 // If things are too big they will be passed along to the drawing of last resort
1521 // below.
1522 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeMask(
1523 runFont, runPaint, deviceProps, scalerContextFlags, positionMatrix);
1524
1525 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1526
1527 auto acceptedBuffer = SkMakeZip(acceptedPackedGlyphIDs,
1528 acceptedPositions,
1529 acceptedFormats);
1530 auto [accepted, rejected, creationBounds] = prepare_for_direct_mask_drawing(
1531 strike.get(), positionMatrix, source, acceptedBuffer, rejectedBuffer);
1532 source = rejected;
1533
1534 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1535 auto addGlyphsWithSameFormat =
1536 [&, bounds = creationBounds](
1537 SkZip<const SkPackedGlyphID, const SkPoint> subrun,
1538 MaskFormat format) {
1539 container->fSubRuns.append(
1540 DirectMaskSubRun::Make(bounds,
1541 subrun,
1542 container->initialPosition(),
1543 strike->strikePromise(),
1544 format,
1545 alloc));
1546 };
1547 add_multi_mask_format(addGlyphsWithSameFormat, accepted);
1548 }
1549 }
1550 }
1551
1552 // Drawable case
1553 // Handle all the drawable glyphs - usually large or perspective color glyphs.
1554 if (!source.empty()) {
1555 auto [strikeSpec, strikeToSourceScale] =
1556 SkStrikeSpec::MakePath(runFont, runPaint, deviceProps, scalerContextFlags);
1557
1558 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1559 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1560
1561 auto acceptedBuffer = SkMakeZip(acceptedGlyphIDs, acceptedPositions);
1562 auto [accepted, rejected] =
1563 prepare_for_drawable_drawing(strike.get(), source, acceptedBuffer, rejectedBuffer);
1564 source = rejected;
1565
1566 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1567 container->fSubRuns.append(
1568 DrawableSubRun::Make(
1569 accepted,
1570 strikeToSourceScale,
1571 strike->strikePromise(),
1572 alloc));
1573 }
1574 }
1575 }
1576
1577 // Path case
1578 // Handle path subruns. Mainly, large or large perspective glyphs with no color.
1579 if (!source.empty()) {
1580 auto [strikeSpec, strikeToSourceScale] =
1581 SkStrikeSpec::MakePath(runFont, runPaint, deviceProps, scalerContextFlags);
1582
1583 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1584 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1585
1586 auto acceptedBuffer = SkMakeZip(acceptedGlyphIDs, acceptedPositions);
1587 auto [accepted, rejected] =
1588 prepare_for_path_drawing(strike.get(), source, acceptedBuffer, rejectedBuffer);
1589 source = rejected;
1590
1591 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1592 const bool isAntiAliased =
1593 subRunControl->forcePathAA() || has_some_antialiasing(runFont);
1594 container->fSubRuns.append(
1595 PathSubRun::Make(accepted,
1596 isAntiAliased,
1597 strikeToSourceScale,
1598 strike->strikePromise(),
1599 alloc));
1600 }
1601 }
1602 }
1603
1604 // Drawing of last resort case
1605 // Draw all the rest of the rejected glyphs from above. This scales out of the atlas to
1606 // the screen, so quality will suffer. This mainly handles large color or perspective
1607 // color not handled by Drawables.
1608 if (!source.empty() && !SkScalarNearlyZero(approximateDeviceTextSize)) {
1609 // Creation matrix will be changed below to meet the following criteria:
1610 // * No perspective - the font scaler and the strikes can't handle perspective masks.
1611 // * Fits atlas - creationMatrix will be conditioned so that the maximum glyph
1612 // dimension for this run will be < kMaxBilerpAtlasDimension.
1613 SkMatrix creationMatrix = positionMatrix;
1614
1615 // Condition creationMatrix for perspective.
1616 if (creationMatrix.hasPerspective()) {
1617 // Find a scale factor that reduces pixelation caused by keystoning.
1618 SkPoint center = glyphRunList.sourceBounds().center();
1619 SkScalar maxAreaScale = SkMatrixPriv::DifferentialAreaScale(creationMatrix, center);
1620 SkScalar perspectiveFactor = 1;
1621 if (SkIsFinite(maxAreaScale) && !SkScalarNearlyZero(maxAreaScale)) {
1622 perspectiveFactor = SkScalarSqrt(maxAreaScale);
1623 }
1624
1625 // Masks can not be created in perspective. Create a non-perspective font with a
1626 // scale that will support the perspective keystoning.
1627 creationMatrix = SkMatrix::Scale(perspectiveFactor, perspectiveFactor);
1628 }
1629
1630 // Reduce to make a one pixel border for the bilerp padding.
1631 static const constexpr SkScalar kMaxBilerpAtlasDimension =
1632 SkGlyphDigest::kSkSideTooBigForAtlas - 2;
1633
1634 // Get the raw glyph IDs to simulate device drawing to figure the maximum device
1635 // dimension.
1636 const SkSpan<const SkGlyphID> glyphs = get_glyphIDs(source);
1637
1638 // maxGlyphDimension always returns an integer even though the return type is SkScalar.
1639 auto maxGlyphDimension = [&](const SkMatrix& m) {
1640 const SkStrikeSpec strikeSpec = SkStrikeSpec::MakeTransformMask(
1641 runFont, runPaint, deviceProps, scalerContextFlags, m);
1642 const sk_sp<StrikeForGPU> gaugingStrike =
1643 strikeSpec.findOrCreateScopedStrike(strikeCache);
1644 const SkScalar maxDimension =
1645 find_maximum_glyph_dimension(gaugingStrike.get(), glyphs);
1646 // TODO: There is a problem where a small character (say .) and a large
1647 // character (say M) are in the same run. If the run is scaled to be very
1648 // large, then the M may return 0 because its dimensions are > 65535, but
1649 // the small character produces regular result because its largest dimension
1650 // is < 65535. This will create an improper scale factor causing the M to be
1651 // too large to fit in the atlas. Tracked by skbug.com/40044801.
1652 return maxDimension;
1653 };
1654
1655 // Condition the creationMatrix so that glyphs fit in the atlas.
1656 for (SkScalar maxDimension = maxGlyphDimension(creationMatrix);
1657 kMaxBilerpAtlasDimension < maxDimension;
1658 maxDimension = maxGlyphDimension(creationMatrix))
1659 {
1660 // The SkScalerContext has a limit of 65536 maximum dimension.
1661 // reductionFactor will always be < 1 because
1662 // maxDimension > kMaxBilerpAtlasDimension, and because maxDimension will always
1663 // be an integer the reduction factor will always be at most 254 / 255.
1664 SkScalar reductionFactor = kMaxBilerpAtlasDimension / maxDimension;
1665 creationMatrix.postScale(reductionFactor, reductionFactor);
1666 }
1667
1668 // Draw using the creationMatrix.
1669 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeTransformMask(
1670 runFont, runPaint, deviceProps, scalerContextFlags, creationMatrix);
1671
1672 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1673
1674 auto acceptedBuffer =
1675 SkMakeZip(acceptedPackedGlyphIDs, acceptedPositions, acceptedFormats);
1676 auto [accepted, rejected, creationBounds] =
1677 prepare_for_mask_drawing(
1678 strike.get(), creationMatrix, source, acceptedBuffer, rejectedBuffer);
1679 source = rejected;
1680
1681 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1682
1683 auto addGlyphsWithSameFormat =
1684 [&, bounds = creationBounds](
1685 SkZip<const SkPackedGlyphID, const SkPoint> subrun,
1686 MaskFormat format) {
1687 container->fSubRuns.append(
1688 TransformedMaskSubRun::Make(subrun,
1689 container->initialPosition(),
1690 strike->strikePromise(),
1691 creationMatrix,
1692 bounds,
1693 format,
1694 alloc));
1695 };
1696 add_multi_mask_format(addGlyphsWithSameFormat, accepted);
1697 }
1698 }
1699 }
1700
1701 return container;
1702 }
1703
1704 void SubRunContainer::draw(SkCanvas* canvas,
1705 SkPoint drawOrigin,
1706 const SkPaint& paint,
1707 const SkRefCnt* subRunStorage,
1708 const AtlasDrawDelegate& atlasDelegate) const {
1709 for (auto& subRun : fSubRuns) {
1710 subRun.draw(canvas, drawOrigin, paint, sk_ref_sp(subRunStorage), atlasDelegate);
1711 }
1712 }
1713
1714 bool SubRunContainer::canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const {
1715 for (const SubRun& subRun : fSubRuns) {
1716 if (!subRun.canReuse(paint, positionMatrix)) {
1717 return false;
1718 }
1719 }
1720 return true;
1721 }
1722
1723 } // namespace sktext::gpu