1 /*
2 * Copyright 2006 The Android Open Source Project
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 #ifndef SkGlyph_DEFINED
9 #define SkGlyph_DEFINED
10
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkPath.h"
13 #include "include/core/SkPicture.h"
14 #include "include/core/SkPoint.h"
15 #include "include/core/SkRect.h"
16 #include "include/core/SkRefCnt.h"
17 #include "include/core/SkScalar.h"
18 #include "include/core/SkString.h"
19 #include "include/core/SkTypes.h"
20 #include "include/private/base/SkDebug.h"
21 #include "include/private/base/SkFixed.h"
22 #include "include/private/base/SkTo.h"
23 #include "src/base/SkVx.h"
24 #include "src/core/SkChecksum.h"
25 #include "src/core/SkMask.h"
26
27 #include <algorithm>
28 #include <cmath>
29 #include <cstddef>
30 #include <cstdint>
31 #include <limits>
32 #include <optional>
33
34 class SkArenaAlloc;
35 class SkCanvas;
36 class SkGlyph;
37 class SkReadBuffer;
38 class SkScalerContext;
39 class SkWriteBuffer;
40 namespace sktext {
41 class StrikeForGPU;
42 } // namespace sktext
43
44 // -- SkPackedGlyphID ------------------------------------------------------------------------------
45 // A combination of SkGlyphID and sub-pixel position information.
46 struct SkPackedGlyphID {
47 inline static constexpr uint32_t kImpossibleID = ~0u;
48 enum {
49 // Lengths
50 kGlyphIDLen = 16u,
51 kSubPixelPosLen = 2u,
52
53 // Bit positions
54 kSubPixelX = 0u,
55 kGlyphID = kSubPixelPosLen,
56 kSubPixelY = kGlyphIDLen + kSubPixelPosLen,
57 kEndData = kGlyphIDLen + 2 * kSubPixelPosLen,
58
59 // Masks
60 kGlyphIDMask = (1u << kGlyphIDLen) - 1,
61 kSubPixelPosMask = (1u << kSubPixelPosLen) - 1,
62 kMaskAll = (1u << kEndData) - 1,
63
64 // Location of sub pixel info in a fixed pointer number.
65 kFixedPointBinaryPointPos = 16u,
66 kFixedPointSubPixelPosBits = kFixedPointBinaryPointPos - kSubPixelPosLen,
67 };
68
69 inline static const constexpr SkScalar kSubpixelRound =
70 1.f / (1u << (SkPackedGlyphID::kSubPixelPosLen + 1));
71
72 inline static const constexpr SkIPoint kXYFieldMask{kSubPixelPosMask << kSubPixelX,
73 kSubPixelPosMask << kSubPixelY};
74
75 struct Hash {
operatorSkPackedGlyphID::Hash76 uint32_t operator() (SkPackedGlyphID packedID) const {
77 return packedID.hash();
78 }
79 };
80
SkPackedGlyphIDSkPackedGlyphID81 constexpr explicit SkPackedGlyphID(SkGlyphID glyphID)
82 : fID{(uint32_t)glyphID << kGlyphID} { }
83
SkPackedGlyphIDSkPackedGlyphID84 constexpr SkPackedGlyphID(SkGlyphID glyphID, SkFixed x, SkFixed y)
85 : fID {PackIDXY(glyphID, x, y)} { }
86
SkPackedGlyphIDSkPackedGlyphID87 constexpr SkPackedGlyphID(SkGlyphID glyphID, uint32_t x, uint32_t y)
88 : fID {PackIDSubXSubY(glyphID, x, y)} { }
89
SkPackedGlyphIDSkPackedGlyphID90 SkPackedGlyphID(SkGlyphID glyphID, SkPoint pt, SkIPoint mask)
91 : fID{PackIDSkPoint(glyphID, pt, mask)} { }
92
SkPackedGlyphIDSkPackedGlyphID93 constexpr explicit SkPackedGlyphID(uint32_t v) : fID{v & kMaskAll} { }
SkPackedGlyphIDSkPackedGlyphID94 constexpr SkPackedGlyphID() : fID{kImpossibleID} {}
95
96 bool operator==(const SkPackedGlyphID& that) const {
97 return fID == that.fID;
98 }
99 bool operator!=(const SkPackedGlyphID& that) const {
100 return !(*this == that);
101 }
102 bool operator<(SkPackedGlyphID that) const {
103 return this->fID < that.fID;
104 }
105
glyphIDSkPackedGlyphID106 SkGlyphID glyphID() const {
107 return (fID >> kGlyphID) & kGlyphIDMask;
108 }
109
valueSkPackedGlyphID110 uint32_t value() const {
111 return fID;
112 }
113
getSubXFixedSkPackedGlyphID114 SkFixed getSubXFixed() const {
115 return this->subToFixed(kSubPixelX);
116 }
117
getSubYFixedSkPackedGlyphID118 SkFixed getSubYFixed() const {
119 return this->subToFixed(kSubPixelY);
120 }
121
hashSkPackedGlyphID122 uint32_t hash() const {
123 return SkChecksum::CheapMix(fID);
124 }
125
dumpSkPackedGlyphID126 SkString dump() const {
127 SkString str;
128 str.appendf("glyphID: %d, x: %d, y:%d", glyphID(), getSubXFixed(), getSubYFixed());
129 return str;
130 }
131
shortDumpSkPackedGlyphID132 SkString shortDump() const {
133 SkString str;
134 str.appendf("0x%x|%1u|%1u", this->glyphID(),
135 this->subPixelField(kSubPixelX),
136 this->subPixelField(kSubPixelY));
137 return str;
138 }
139
140 private:
PackIDSubXSubYSkPackedGlyphID141 static constexpr uint32_t PackIDSubXSubY(SkGlyphID glyphID, uint32_t x, uint32_t y) {
142 SkASSERT(x < (1u << kSubPixelPosLen));
143 SkASSERT(y < (1u << kSubPixelPosLen));
144
145 return (x << kSubPixelX) | (y << kSubPixelY) | (glyphID << kGlyphID);
146 }
147
148 // Assumptions: pt is properly rounded. mask is set for the x or y fields.
149 //
150 // A sub-pixel field is a number on the interval [2^kSubPixel, 2^(kSubPixel + kSubPixelPosLen)).
151 // Where kSubPixel is either kSubPixelX or kSubPixelY. Given a number x on [0, 1) we can
152 // generate a sub-pixel field using:
153 // sub-pixel-field = x * 2^(kSubPixel + kSubPixelPosLen)
154 //
155 // We can generate the integer sub-pixel field by &-ing the integer part of sub-filed with the
156 // sub-pixel field mask.
157 // int-sub-pixel-field = int(sub-pixel-field) & (kSubPixelPosMask << kSubPixel)
158 //
159 // The last trick is to extend the range from [0, 1) to [0, 2). The extend range is
160 // necessary because the modulo 1 calculation (pt - floor(pt)) generates numbers on [-1, 1).
161 // This does not round (floor) properly when converting to integer. Adding one to the range
162 // causes truncation and floor to be the same. Coincidentally, masking to produce the field also
163 // removes the +1.
PackIDSkPointSkPackedGlyphID164 static uint32_t PackIDSkPoint(SkGlyphID glyphID, SkPoint pt, SkIPoint mask) {
165 #if 0
166 // TODO: why does this code not work on GCC 8.3 x86 Debug builds?
167 using namespace skvx;
168 using XY = Vec<2, float>;
169 using SubXY = Vec<2, int>;
170
171 const XY magic = {1.f * (1u << (kSubPixelPosLen + kSubPixelX)),
172 1.f * (1u << (kSubPixelPosLen + kSubPixelY))};
173 XY pos{pt.x(), pt.y()};
174 XY subPos = (pos - floor(pos)) + 1.0f;
175 SubXY sub = cast<int>(subPos * magic) & SubXY{mask.x(), mask.y()};
176 #else
177 const float magicX = 1.f * (1u << (kSubPixelPosLen + kSubPixelX)),
178 magicY = 1.f * (1u << (kSubPixelPosLen + kSubPixelY));
179
180 float x = pt.x(),
181 y = pt.y();
182 x = (x - floorf(x)) + 1.0f;
183 y = (y - floorf(y)) + 1.0f;
184 int sub[] = {
185 (int)(x * magicX) & mask.x(),
186 (int)(y * magicY) & mask.y(),
187 };
188 #endif
189
190 SkASSERT(sub[0] / (1u << kSubPixelX) < (1u << kSubPixelPosLen));
191 SkASSERT(sub[1] / (1u << kSubPixelY) < (1u << kSubPixelPosLen));
192 return (glyphID << kGlyphID) | sub[0] | sub[1];
193 }
194
PackIDXYSkPackedGlyphID195 static constexpr uint32_t PackIDXY(SkGlyphID glyphID, SkFixed x, SkFixed y) {
196 return PackIDSubXSubY(glyphID, FixedToSub(x), FixedToSub(y));
197 }
198
FixedToSubSkPackedGlyphID199 static constexpr uint32_t FixedToSub(SkFixed n) {
200 return ((uint32_t)n >> kFixedPointSubPixelPosBits) & kSubPixelPosMask;
201 }
202
subPixelFieldSkPackedGlyphID203 constexpr uint32_t subPixelField(uint32_t subPixelPosBit) const {
204 return (fID >> subPixelPosBit) & kSubPixelPosMask;
205 }
206
subToFixedSkPackedGlyphID207 constexpr SkFixed subToFixed(uint32_t subPixelPosBit) const {
208 uint32_t subPixelPosition = this->subPixelField(subPixelPosBit);
209 return subPixelPosition << kFixedPointSubPixelPosBits;
210 }
211
212 uint32_t fID;
213 };
214
215 // -- SkAxisAlignment ------------------------------------------------------------------------------
216 // SkAxisAlignment specifies the x component of a glyph's position is rounded when kX, and the y
217 // component is rounded when kY. If kNone then neither are rounded.
218 enum class SkAxisAlignment : uint32_t {
219 kNone,
220 kX,
221 kY,
222 };
223
224 // round and ignorePositionMask are used to calculate the subpixel position of a glyph.
225 // The per component (x or y) calculation is:
226 //
227 // subpixelOffset = (floor((viewportPosition + rounding) & mask) >> 14) & 3
228 //
229 // where mask is either 0 or ~0, and rounding is either
230 // 1/2 for non-subpixel or 1/8 for subpixel.
231 struct SkGlyphPositionRoundingSpec {
232 SkGlyphPositionRoundingSpec(bool isSubpixel, SkAxisAlignment axisAlignment);
233 const SkVector halfAxisSampleFreq;
234 const SkIPoint ignorePositionMask;
235 const SkIPoint ignorePositionFieldMask;
236
237 private:
238 static SkVector HalfAxisSampleFreq(bool isSubpixel, SkAxisAlignment axisAlignment);
239 static SkIPoint IgnorePositionMask(bool isSubpixel, SkAxisAlignment axisAlignment);
240 static SkIPoint IgnorePositionFieldMask(bool isSubpixel, SkAxisAlignment axisAlignment);
241 };
242
243 class SkGlyphRect;
244 namespace skglyph {
245 SkGlyphRect rect_union(SkGlyphRect, SkGlyphRect);
246 SkGlyphRect rect_intersection(SkGlyphRect, SkGlyphRect);
247 } // namespace skglyph
248
249 // SkGlyphRect encodes rectangles with coordinates using SkScalar. It is specialized for
250 // rectangle union and intersection operations.
251 class SkGlyphRect {
252 public:
253 SkGlyphRect() = default;
SkGlyphRect(SkScalar left,SkScalar top,SkScalar right,SkScalar bottom)254 SkGlyphRect(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom)
255 : fRect{-left, -top, right, bottom} { }
empty()256 bool empty() const {
257 return -fRect[0] >= fRect[2] || -fRect[1] >= fRect[3];
258 }
rect()259 SkRect rect() const {
260 return SkRect::MakeLTRB(-fRect[0], -fRect[1], fRect[2], fRect[3]);
261 }
offset(SkScalar x,SkScalar y)262 SkGlyphRect offset(SkScalar x, SkScalar y) const {
263 return SkGlyphRect{fRect + Storage{-x, -y, x, y}};
264 }
offset(SkPoint pt)265 SkGlyphRect offset(SkPoint pt) const {
266 return this->offset(pt.x(), pt.y());
267 }
scaleAndOffset(SkScalar scale,SkPoint offset)268 SkGlyphRect scaleAndOffset(SkScalar scale, SkPoint offset) const {
269 auto [x, y] = offset;
270 return fRect * scale + Storage{-x, -y, x, y};
271 }
inset(SkScalar dx,SkScalar dy)272 SkGlyphRect inset(SkScalar dx, SkScalar dy) const {
273 return fRect - Storage{dx, dy, dx, dy};
274 }
leftTop()275 SkPoint leftTop() const { return -this->negLeftTop(); }
rightBottom()276 SkPoint rightBottom() const { return {fRect[2], fRect[3]}; }
widthHeight()277 SkPoint widthHeight() const { return this->rightBottom() + negLeftTop(); }
278 friend SkGlyphRect skglyph::rect_union(SkGlyphRect, SkGlyphRect);
279 friend SkGlyphRect skglyph::rect_intersection(SkGlyphRect, SkGlyphRect);
280
281 private:
negLeftTop()282 SkPoint negLeftTop() const { return {fRect[0], fRect[1]}; }
283 using Storage = skvx::Vec<4, SkScalar>;
SkGlyphRect(Storage rect)284 SkGlyphRect(Storage rect) : fRect{rect} { }
285 Storage fRect;
286 };
287
288 namespace skglyph {
empty_rect()289 inline SkGlyphRect empty_rect() {
290 constexpr SkScalar max = std::numeric_limits<SkScalar>::max();
291 return {max, max, -max, -max};
292 }
full_rect()293 inline SkGlyphRect full_rect() {
294 constexpr SkScalar max = std::numeric_limits<SkScalar>::max();
295 return {-max, -max, max, max};
296 }
rect_union(SkGlyphRect a,SkGlyphRect b)297 inline SkGlyphRect rect_union(SkGlyphRect a, SkGlyphRect b) {
298 return skvx::max(a.fRect, b.fRect);
299 }
rect_intersection(SkGlyphRect a,SkGlyphRect b)300 inline SkGlyphRect rect_intersection(SkGlyphRect a, SkGlyphRect b) {
301 return skvx::min(a.fRect, b.fRect);
302 }
303
304 enum class GlyphAction {
305 kUnset,
306 kAccept,
307 kReject,
308 kDrop,
309 kSize,
310 };
311
312 enum ActionType {
313 kDirectMask = 0,
314 kDirectMaskCPU = 2,
315 kMask = 4,
316 kSDFT = 6,
317 kPath = 8,
318 kDrawable = 10,
319 };
320
321 enum ActionTypeSize {
322 kTotalBits = 12
323 };
324 } // namespace skglyph
325
326 // SkGlyphDigest contains a digest of information for making GPU drawing decisions. It can be
327 // referenced instead of the glyph itself in many situations. In the remote glyphs cache the
328 // SkGlyphDigest is the only information that needs to be stored in the cache.
329 class SkGlyphDigest {
330 public:
331 // An atlas consists of plots, and plots hold glyphs. The minimum a plot can be is 256x256.
332 // This means that the maximum size a glyph can be is 256x256.
333 static constexpr uint16_t kSkSideTooBigForAtlas = 256;
334
335 // Default ctor is only needed for the hash table.
336 SkGlyphDigest() = default;
337 SkGlyphDigest(size_t index, const SkGlyph& glyph);
index()338 int index() const { return fIndex; }
isEmpty()339 bool isEmpty() const { return fIsEmpty; }
isColor()340 bool isColor() const { return fFormat == SkMask::kARGB32_Format; }
maskFormat()341 SkMask::Format maskFormat() const { return static_cast<SkMask::Format>(fFormat); }
342
actionFor(skglyph::ActionType actionType)343 skglyph::GlyphAction actionFor(skglyph::ActionType actionType) const {
344 return static_cast<skglyph::GlyphAction>((fActions >> actionType) & 0b11);
345 }
346
347 void setActionFor(skglyph::ActionType, SkGlyph*, sktext::StrikeForGPU*);
348
maxDimension()349 uint16_t maxDimension() const {
350 return std::max(fWidth, fHeight);
351 }
352
fitsInAtlasDirect()353 bool fitsInAtlasDirect() const {
354 return this->maxDimension() <= kSkSideTooBigForAtlas;
355 }
356
fitsInAtlasInterpolated()357 bool fitsInAtlasInterpolated() const {
358 // Include the padding needed for interpolating the glyph when drawing.
359 return this->maxDimension() <= kSkSideTooBigForAtlas - 2;
360 }
361
bounds()362 SkGlyphRect bounds() const {
363 return SkGlyphRect(fLeft, fTop, (SkScalar)fLeft + fWidth, (SkScalar)fTop + fHeight);
364 }
365
366 static bool FitsInAtlas(const SkGlyph& glyph);
367
368 // GetKey and Hash implement the required methods for THashTable.
GetKey(SkGlyphDigest digest)369 static SkPackedGlyphID GetKey(SkGlyphDigest digest) {
370 return SkPackedGlyphID{SkTo<uint32_t>(digest.fPackedID)};
371 }
Hash(SkPackedGlyphID packedID)372 static uint32_t Hash(SkPackedGlyphID packedID) {
373 return packedID.hash();
374 }
ShouldGrow(int count,int capacity)375 static bool ShouldGrow(int count, int capacity) {
376 // Having the 50% load factor results in performance improvements and significantly reduces
377 // the average number of probes on the Speedometer3 Editor-TipTap benchmark.
378 return 2 * count >= capacity;
379 }
ShouldShrink(int count,int capacity)380 static bool ShouldShrink(int count, int capacity) {
381 // Use 1/6 as the minimal load.
382 return 6 * count <= capacity;
383 }
384
385 private:
setAction(skglyph::ActionType actionType,skglyph::GlyphAction action)386 void setAction(skglyph::ActionType actionType, skglyph::GlyphAction action) {
387 using namespace skglyph;
388 SkASSERT(action != GlyphAction::kUnset);
389 SkASSERT(this->actionFor(actionType) == GlyphAction::kUnset);
390 const uint64_t mask = 0b11 << actionType;
391 fActions &= ~mask;
392 fActions |= SkTo<uint64_t>(action) << actionType;
393 }
394
395 static_assert(SkPackedGlyphID::kEndData == 20);
396 static_assert(SkMask::kCountMaskFormats <= 8);
397 static_assert(SkTo<int>(skglyph::GlyphAction::kSize) <= 4);
398 struct {
399 uint64_t fPackedID : SkPackedGlyphID::kEndData;
400 uint64_t fIndex : SkPackedGlyphID::kEndData;
401 uint64_t fIsEmpty : 1;
402 uint64_t fFormat : 3;
403 uint64_t fActions : skglyph::ActionTypeSize::kTotalBits;
404 };
405 int16_t fLeft, fTop;
406 uint16_t fWidth, fHeight;
407 };
408
409 class SkPictureBackedGlyphDrawable final : public SkDrawable {
410 public:
411 static sk_sp<SkPictureBackedGlyphDrawable>MakeFromBuffer(SkReadBuffer& buffer);
412 static void FlattenDrawable(SkWriteBuffer& buffer, SkDrawable* drawable);
413 SkPictureBackedGlyphDrawable(sk_sp<SkPicture> self);
414
415 private:
416 sk_sp<SkPicture> fPicture;
417 SkRect onGetBounds() override;
418 size_t onApproximateBytesUsed() override;
419 void onDraw(SkCanvas* canvas) override;
420 };
421
422 class SkGlyph {
423 public:
424 static std::optional<SkGlyph> MakeFromBuffer(SkReadBuffer&);
425 // SkGlyph() is used for testing.
SkGlyph()426 constexpr SkGlyph() : SkGlyph{SkPackedGlyphID()} { }
427 SkGlyph(const SkGlyph&) = default;
428 SkGlyph& operator=(const SkGlyph&) = default;
429 SkGlyph(SkGlyph&&) = default;
430 SkGlyph& operator=(SkGlyph&&) = default;
431 ~SkGlyph() = default;
SkGlyph(SkPackedGlyphID id)432 constexpr explicit SkGlyph(SkPackedGlyphID id) : fID{id} { }
433
advanceVector()434 SkVector advanceVector() const { return SkVector{fAdvanceX, fAdvanceY}; }
advanceX()435 SkScalar advanceX() const { return fAdvanceX; }
advanceY()436 SkScalar advanceY() const { return fAdvanceY; }
437
getGlyphID()438 SkGlyphID getGlyphID() const { return fID.glyphID(); }
getPackedID()439 SkPackedGlyphID getPackedID() const { return fID; }
getSubXFixed()440 SkFixed getSubXFixed() const { return fID.getSubXFixed(); }
getSubYFixed()441 SkFixed getSubYFixed() const { return fID.getSubYFixed(); }
442
443 size_t rowBytes() const;
444 size_t rowBytesUsingFormat(SkMask::Format format) const;
445
446 // Call this to set all the metrics fields to 0 (e.g. if the scaler
447 // encounters an error measuring a glyph). Note: this does not alter the
448 // fImage, fPath, fID, fMaskFormat fields.
449 void zeroMetrics();
450
451 SkMask mask() const;
452
453 SkMask mask(SkPoint position) const;
454
455 // Image
456 // If we haven't already tried to associate an image with this glyph
457 // (i.e. setImageHasBeenCalled() returns false), then use the
458 // SkScalerContext or const void* argument to set the image.
459 bool setImage(SkArenaAlloc* alloc, SkScalerContext* scalerContext);
460 bool setImage(SkArenaAlloc* alloc, const void* image);
461
462 // Merge the 'from' glyph into this glyph using alloc to allocate image data. Return the number
463 // of bytes allocated. Copy the width, height, top, left, format, and image into this glyph
464 // making a copy of the image using the alloc.
465 size_t setMetricsAndImage(SkArenaAlloc* alloc, const SkGlyph& from);
466
467 // Returns true if the image has been set.
setImageHasBeenCalled()468 bool setImageHasBeenCalled() const {
469 // Check for empty bounds first to guard against fImage somehow being set.
470 return this->isEmpty() || fImage != nullptr || this->imageTooLarge();
471 }
472
473 // Return a pointer to the path if the image exists, otherwise return nullptr.
image()474 const void* image() const { SkASSERT(this->setImageHasBeenCalled()); return fImage; }
475
476 // Return the size of the image.
477 size_t imageSize() const;
478
479 // Path
480 // If we haven't already tried to associate a path to this glyph
481 // (i.e. setPathHasBeenCalled() returns false), then use the
482 // SkScalerContext or SkPath argument to try to do so. N.B. this
483 // may still result in no path being associated with this glyph,
484 // e.g. if you pass a null SkPath or the typeface is bitmap-only.
485 //
486 // This setPath() call is sticky... once you call it, the glyph
487 // stays in its state permanently, ignoring any future calls.
488 //
489 // Returns true if this is the first time you called setPath()
490 // and there actually is a path; call path() to get it.
491 bool setPath(SkArenaAlloc* alloc, SkScalerContext* scalerContext);
492 bool setPath(SkArenaAlloc* alloc, const SkPath* path, bool hairline, bool modified);
493
494 // Returns true if that path has been set.
setPathHasBeenCalled()495 bool setPathHasBeenCalled() const { return fPathData != nullptr; }
496
497 // Return a pointer to the path if it exists, otherwise return nullptr. Only works if the
498 // path was previously set.
499 const SkPath* path() const;
500 bool pathIsHairline() const;
501 bool pathIsModified() const;
502
503 bool setDrawable(SkArenaAlloc* alloc, SkScalerContext* scalerContext);
504 bool setDrawable(SkArenaAlloc* alloc, sk_sp<SkDrawable> drawable);
setDrawableHasBeenCalled()505 bool setDrawableHasBeenCalled() const { return fDrawableData != nullptr; }
506 SkDrawable* drawable() const;
507
508 // Format
isColor()509 bool isColor() const { return fMaskFormat == SkMask::kARGB32_Format; }
maskFormat()510 SkMask::Format maskFormat() const { return fMaskFormat; }
511 size_t formatAlignment() const;
512
513 // Bounds
maxDimension()514 int maxDimension() const { return std::max(fWidth, fHeight); }
iRect()515 SkIRect iRect() const { return SkIRect::MakeXYWH(fLeft, fTop, fWidth, fHeight); }
rect()516 SkRect rect() const { return SkRect::MakeXYWH(fLeft, fTop, fWidth, fHeight); }
glyphRect()517 SkGlyphRect glyphRect() const {
518 return SkGlyphRect(fLeft, fTop, fLeft + fWidth, fTop + fHeight);
519 }
left()520 int left() const { return fLeft; }
top()521 int top() const { return fTop; }
width()522 int width() const { return fWidth; }
height()523 int height() const { return fHeight; }
isEmpty()524 bool isEmpty() const {
525 return fWidth == 0 || fHeight == 0;
526 }
imageTooLarge()527 bool imageTooLarge() const { return fWidth >= kMaxGlyphWidth; }
528
extraBits()529 uint16_t extraBits() const { return fScalerContextBits; }
530
531 // Make sure that the intercept information is on the glyph and return it, or return it if it
532 // already exists.
533 // * bounds - [0] - top of underline; [1] - bottom of underline.
534 // * scale, xPos - information about how wide the gap is.
535 // * array - accumulated gaps for many characters if not null.
536 // * count - the number of gaps.
537 void ensureIntercepts(const SkScalar bounds[2], SkScalar scale, SkScalar xPos,
538 SkScalar* array, int* count, SkArenaAlloc* alloc);
539
540 // Deprecated. Do not use. The last use is in SkChromeRemoteCache, and will be deleted soon.
setImage(void * image)541 void setImage(void* image) { fImage = image; }
542
543 // Serialize/deserialize functions.
544 // Flatten the metrics portions, but no drawing data.
545 void flattenMetrics(SkWriteBuffer&) const;
546
547 // Flatten just the the mask data.
548 void flattenImage(SkWriteBuffer&) const;
549
550 // Read the image data, store it in the alloc, and add it to the glyph.
551 size_t addImageFromBuffer(SkReadBuffer&, SkArenaAlloc*);
552
553 // Flatten just the path data.
554 void flattenPath(SkWriteBuffer&) const;
555
556 // Read the path data, create the glyph's path data in the alloc, and add it to the glyph.
557 size_t addPathFromBuffer(SkReadBuffer&, SkArenaAlloc*);
558
559 // Flatten just the drawable data.
560 void flattenDrawable(SkWriteBuffer&) const;
561
562 // Read the drawable data, create the glyph's drawable data in the alloc, and add it to the
563 // glyph.
564 size_t addDrawableFromBuffer(SkReadBuffer&, SkArenaAlloc*);
565
566 private:
567 // There are two sides to an SkGlyph, the scaler side (things that create glyph data) have
568 // access to all the fields. Scalers are assumed to maintain all the SkGlyph invariants. The
569 // consumer side has a tighter interface.
570 friend class SkScalerContext;
571 friend class SkGlyphTestPeer;
572
573 inline static constexpr uint16_t kMaxGlyphWidth = 1u << 13u;
574
575 // Support horizontal and vertical skipping strike-through / underlines.
576 // The caller walks the linked list looking for a match. For a horizontal underline,
577 // the fBounds contains the top and bottom of the underline. The fInterval pair contains the
578 // beginning and end of the intersection of the bounds and the glyph's path.
579 // If interval[0] >= interval[1], no intersection was found.
580 struct Intercept {
581 Intercept* fNext;
582 SkScalar fBounds[2]; // for horz underlines, the boundaries in Y
583 SkScalar fInterval[2]; // the outside intersections of the axis and the glyph
584 };
585
586 struct PathData {
587 Intercept* fIntercept{nullptr};
588 SkPath fPath;
589 bool fHasPath{false};
590 // A normal user-path will have patheffects applied to it and eventually become a dev-path.
591 // A dev-path is always a fill-path, except when it is hairline.
592 // The fPath is a dev-path, so sidecar the paths hairline status.
593 // This allows the user to avoid filling paths which should not be filled.
594 bool fHairline{false};
595 // This is set if the path is significantly different from what a reasonable interpreter of
596 // the underlying font data would produce. This is set if any non-identity matrix, stroke,
597 // path effect, emboldening, etc is applied.
598 // This allows Document implementations to know if a glyph should be drawn out of the font
599 // data or needs to be embedded differently.
600 bool fModified{false};
601 };
602
603 struct DrawableData {
604 Intercept* fIntercept{nullptr};
605 sk_sp<SkDrawable> fDrawable;
606 bool fHasDrawable{false};
607 };
608
609 size_t allocImage(SkArenaAlloc* alloc);
610
installImage(void * imageData)611 void installImage(void* imageData) {
612 SkASSERT(!this->setImageHasBeenCalled());
613 fImage = imageData;
614 }
615
616 // path == nullptr indicates that there is no path.
617 void installPath(SkArenaAlloc* alloc, const SkPath* path, bool hairline, bool modified);
618
619 // drawable == nullptr indicates that there is no path.
620 void installDrawable(SkArenaAlloc* alloc, sk_sp<SkDrawable> drawable);
621
622 // The width and height of the glyph mask.
623 uint16_t fWidth = 0,
624 fHeight = 0;
625
626 // The offset from the glyphs origin on the baseline to the top left of the glyph mask.
627 int16_t fTop = 0,
628 fLeft = 0;
629
630 // fImage must remain null if the glyph is empty or if width > kMaxGlyphWidth.
631 void* fImage = nullptr;
632
633 // Path data has tricky state. If the glyph isEmpty, then fPathData should always be nullptr,
634 // else if fPathData is not null, then a path has been requested. The fPath field of fPathData
635 // may still be null after the request meaning that there is no path for this glyph.
636 PathData* fPathData = nullptr;
637 DrawableData* fDrawableData = nullptr;
638
639 // The advance for this glyph.
640 float fAdvanceX = 0,
641 fAdvanceY = 0;
642
643 SkMask::Format fMaskFormat{SkMask::kBW_Format};
644
645 // Used by the SkScalerContext to pass state from generateMetrics to generateImage.
646 // Usually specifies which glyph representation was used to generate the metrics.
647 uint16_t fScalerContextBits = 0;
648
649 // An SkGlyph can be created with just a packedID, but generally speaking some glyph factory
650 // needs to actually fill out the glyph before it can be used as part of that system.
651 SkDEBUGCODE(bool fAdvancesBoundsFormatAndInitialPathDone{false};)
652
653 SkPackedGlyphID fID;
654 };
655
656 #endif
657