1 /*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/private/SkPathRef.h"
9
10 #include "include/core/SkPath.h"
11 #include "include/private/SkNx.h"
12 #include "include/private/SkOnce.h"
13 #include "include/private/SkTo.h"
14 #include "src/core/SkBuffer.h"
15 #include "src/core/SkPathPriv.h"
16 #include "src/core/SkSafeMath.h"
17
18 // Conic weights must be 0 < weight <= finite
validate_conic_weights(const SkScalar weights[],int count)19 static bool validate_conic_weights(const SkScalar weights[], int count) {
20 for (int i = 0; i < count; ++i) {
21 if (weights[i] <= 0 || !SkScalarIsFinite(weights[i])) {
22 return false;
23 }
24 }
25 return true;
26 }
27
28 //////////////////////////////////////////////////////////////////////////////
Editor(sk_sp<SkPathRef> * pathRef,int incReserveVerbs,int incReservePoints)29 SkPathRef::Editor::Editor(sk_sp<SkPathRef>* pathRef,
30 int incReserveVerbs,
31 int incReservePoints)
32 {
33 SkASSERT(incReserveVerbs >= 0);
34 SkASSERT(incReservePoints >= 0);
35
36 if ((*pathRef)->unique()) {
37 (*pathRef)->incReserve(incReserveVerbs, incReservePoints);
38 } else {
39 SkPathRef* copy = new SkPathRef;
40 copy->copy(**pathRef, incReserveVerbs, incReservePoints);
41 pathRef->reset(copy);
42 }
43 fPathRef = pathRef->get();
44 fPathRef->callGenIDChangeListeners();
45 fPathRef->fGenerationID = 0;
46 fPathRef->fBoundsIsDirty = true;
47 SkDEBUGCODE(fPathRef->fEditorsAttached++;)
48 }
49
50 // Sort of like makeSpace(0) but the the additional requirement that we actively shrink the
51 // allocations to just fit the current needs. makeSpace() will only grow, but never shrinks.
52 //
shrinkToFit()53 void SkPath::shrinkToFit() {
54 const size_t kMinFreeSpaceForShrink = 8; // just made up a small number
55
56 if (fPathRef->fFreeSpace <= kMinFreeSpaceForShrink) {
57 return;
58 }
59
60 if (fPathRef->unique()) {
61 int pointCount = fPathRef->fPointCnt;
62 int verbCount = fPathRef->fVerbCnt;
63
64 size_t ptsSize = sizeof(SkPoint) * pointCount;
65 size_t vrbSize = sizeof(uint8_t) * verbCount;
66 size_t minSize = ptsSize + vrbSize;
67
68 void* newAlloc = sk_malloc_canfail(minSize);
69 if (!newAlloc) {
70 return; // couldn't allocate the smaller buffer, but that's ok
71 }
72
73 sk_careful_memcpy(newAlloc, fPathRef->fPoints, ptsSize);
74 sk_careful_memcpy((char*)newAlloc + minSize - vrbSize, fPathRef->verbsMemBegin(), vrbSize);
75
76 sk_free(fPathRef->fPoints);
77 fPathRef->fPoints = static_cast<SkPoint*>(newAlloc);
78 fPathRef->fVerbs = (uint8_t*)newAlloc + minSize;
79 fPathRef->fFreeSpace = 0;
80 fPathRef->fConicWeights.shrinkToFit();
81 } else {
82 sk_sp<SkPathRef> pr(new SkPathRef);
83 pr->copy(*fPathRef, 0, 0);
84 fPathRef = std::move(pr);
85 }
86
87 SkDEBUGCODE(fPathRef->validate();)
88 }
89
90 //////////////////////////////////////////////////////////////////////////////
91
~SkPathRef()92 SkPathRef::~SkPathRef() {
93 // Deliberately don't validate() this path ref, otherwise there's no way
94 // to read one that's not valid and then free its memory without asserting.
95 this->callGenIDChangeListeners();
96 SkASSERT(fGenIDChangeListeners.empty()); // These are raw ptrs.
97 sk_free(fPoints);
98
99 SkDEBUGCODE(fPoints = nullptr;)
100 SkDEBUGCODE(fVerbs = nullptr;)
101 SkDEBUGCODE(fVerbCnt = 0x9999999;)
102 SkDEBUGCODE(fPointCnt = 0xAAAAAAA;)
103 SkDEBUGCODE(fPointCnt = 0xBBBBBBB;)
104 SkDEBUGCODE(fGenerationID = 0xEEEEEEEE;)
105 SkDEBUGCODE(fEditorsAttached.store(0x7777777);)
106 }
107
108 static SkPathRef* gEmpty = nullptr;
109
CreateEmpty()110 SkPathRef* SkPathRef::CreateEmpty() {
111 static SkOnce once;
112 once([]{
113 gEmpty = new SkPathRef;
114 gEmpty->computeBounds(); // Avoids races later to be the first to do this.
115 });
116 return SkRef(gEmpty);
117 }
118
transform_dir_and_start(const SkMatrix & matrix,bool isRRect,bool * isCCW,unsigned * start)119 static void transform_dir_and_start(const SkMatrix& matrix, bool isRRect, bool* isCCW,
120 unsigned* start) {
121 int inStart = *start;
122 int rm = 0;
123 if (isRRect) {
124 // Degenerate rrect indices to oval indices and remember the remainder.
125 // Ovals have one index per side whereas rrects have two.
126 rm = inStart & 0b1;
127 inStart /= 2;
128 }
129 // Is the antidiagonal non-zero (otherwise the diagonal is zero)
130 int antiDiag;
131 // Is the non-zero value in the top row (either kMScaleX or kMSkewX) negative
132 int topNeg;
133 // Are the two non-zero diagonal or antidiagonal values the same sign.
134 int sameSign;
135 if (matrix.get(SkMatrix::kMScaleX) != 0) {
136 antiDiag = 0b00;
137 if (matrix.get(SkMatrix::kMScaleX) > 0) {
138 topNeg = 0b00;
139 sameSign = matrix.get(SkMatrix::kMScaleY) > 0 ? 0b01 : 0b00;
140 } else {
141 topNeg = 0b10;
142 sameSign = matrix.get(SkMatrix::kMScaleY) > 0 ? 0b00 : 0b01;
143 }
144 } else {
145 antiDiag = 0b01;
146 if (matrix.get(SkMatrix::kMSkewX) > 0) {
147 topNeg = 0b00;
148 sameSign = matrix.get(SkMatrix::kMSkewY) > 0 ? 0b01 : 0b00;
149 } else {
150 topNeg = 0b10;
151 sameSign = matrix.get(SkMatrix::kMSkewY) > 0 ? 0b00 : 0b01;
152 }
153 }
154 if (sameSign != antiDiag) {
155 // This is a rotation (and maybe scale). The direction is unchanged.
156 // Trust me on the start computation (or draw yourself some pictures)
157 *start = (inStart + 4 - (topNeg | antiDiag)) % 4;
158 SkASSERT(*start < 4);
159 if (isRRect) {
160 *start = 2 * *start + rm;
161 }
162 } else {
163 // This is a mirror (and maybe scale). The direction is reversed.
164 *isCCW = !*isCCW;
165 // Trust me on the start computation (or draw yourself some pictures)
166 *start = (6 + (topNeg | antiDiag) - inStart) % 4;
167 SkASSERT(*start < 4);
168 if (isRRect) {
169 *start = 2 * *start + (rm ? 0 : 1);
170 }
171 }
172 }
173
CreateTransformedCopy(sk_sp<SkPathRef> * dst,const SkPathRef & src,const SkMatrix & matrix)174 void SkPathRef::CreateTransformedCopy(sk_sp<SkPathRef>* dst,
175 const SkPathRef& src,
176 const SkMatrix& matrix) {
177 SkDEBUGCODE(src.validate();)
178 if (matrix.isIdentity()) {
179 if (dst->get() != &src) {
180 src.ref();
181 dst->reset(const_cast<SkPathRef*>(&src));
182 SkDEBUGCODE((*dst)->validate();)
183 }
184 return;
185 }
186
187 if (!(*dst)->unique()) {
188 dst->reset(new SkPathRef);
189 }
190
191 if (dst->get() != &src) {
192 (*dst)->resetToSize(src.fVerbCnt, src.fPointCnt, src.fConicWeights.count());
193 sk_careful_memcpy((*dst)->verbsMemWritable(), src.verbsMemBegin(),
194 src.fVerbCnt * sizeof(uint8_t));
195 (*dst)->fConicWeights = src.fConicWeights;
196 }
197
198 SkASSERT((*dst)->countPoints() == src.countPoints());
199 SkASSERT((*dst)->countVerbs() == src.countVerbs());
200 SkASSERT((*dst)->fConicWeights.count() == src.fConicWeights.count());
201
202 // Need to check this here in case (&src == dst)
203 bool canXformBounds = !src.fBoundsIsDirty && matrix.rectStaysRect() && src.countPoints() > 1;
204
205 matrix.mapPoints((*dst)->fPoints, src.points(), src.fPointCnt);
206
207 /*
208 * Here we optimize the bounds computation, by noting if the bounds are
209 * already known, and if so, we just transform those as well and mark
210 * them as "known", rather than force the transformed path to have to
211 * recompute them.
212 *
213 * Special gotchas if the path is effectively empty (<= 1 point) or
214 * if it is non-finite. In those cases bounds need to stay empty,
215 * regardless of the matrix.
216 */
217 if (canXformBounds) {
218 (*dst)->fBoundsIsDirty = false;
219 if (src.fIsFinite) {
220 matrix.mapRect(&(*dst)->fBounds, src.fBounds);
221 if (!((*dst)->fIsFinite = (*dst)->fBounds.isFinite())) {
222 (*dst)->fBounds.setEmpty();
223 }
224 } else {
225 (*dst)->fIsFinite = false;
226 (*dst)->fBounds.setEmpty();
227 }
228 } else {
229 (*dst)->fBoundsIsDirty = true;
230 }
231
232 (*dst)->fSegmentMask = src.fSegmentMask;
233
234 // It's an oval only if it stays a rect.
235 bool rectStaysRect = matrix.rectStaysRect();
236 (*dst)->fIsOval = src.fIsOval && rectStaysRect;
237 (*dst)->fIsRRect = src.fIsRRect && rectStaysRect;
238 if ((*dst)->fIsOval || (*dst)->fIsRRect) {
239 unsigned start = src.fRRectOrOvalStartIdx;
240 bool isCCW = SkToBool(src.fRRectOrOvalIsCCW);
241 transform_dir_and_start(matrix, (*dst)->fIsRRect, &isCCW, &start);
242 (*dst)->fRRectOrOvalIsCCW = isCCW;
243 (*dst)->fRRectOrOvalStartIdx = start;
244 }
245
246 if (dst->get() == &src) {
247 (*dst)->callGenIDChangeListeners();
248 (*dst)->fGenerationID = 0;
249 }
250
251 SkDEBUGCODE((*dst)->validate();)
252 }
253
validate_verb_sequence(const uint8_t verbs[],int vCount)254 static bool validate_verb_sequence(const uint8_t verbs[], int vCount) {
255 // verbs are stored backwards, but we need to visit them in logical order to determine if
256 // they form a valid sequence.
257
258 bool needsMoveTo = true;
259 bool invalidSequence = false;
260
261 for (int i = vCount - 1; i >= 0; --i) {
262 switch (verbs[i]) {
263 case SkPath::kMove_Verb:
264 needsMoveTo = false;
265 break;
266 case SkPath::kLine_Verb:
267 case SkPath::kQuad_Verb:
268 case SkPath::kConic_Verb:
269 case SkPath::kCubic_Verb:
270 invalidSequence |= needsMoveTo;
271 break;
272 case SkPath::kClose_Verb:
273 needsMoveTo = true;
274 break;
275 default:
276 return false; // unknown verb
277 }
278 }
279 return !invalidSequence;
280 }
281
282 // Given the verb array, deduce the required number of pts and conics,
283 // or if an invalid verb is encountered, return false.
deduce_pts_conics(const uint8_t verbs[],int vCount,int * ptCountPtr,int * conicCountPtr)284 static bool deduce_pts_conics(const uint8_t verbs[], int vCount, int* ptCountPtr,
285 int* conicCountPtr) {
286 // When there is at least one verb, the first is required to be kMove_Verb.
287 if (0 < vCount && verbs[vCount-1] != SkPath::kMove_Verb) {
288 return false;
289 }
290
291 SkSafeMath safe;
292 int ptCount = 0;
293 int conicCount = 0;
294 for (int i = 0; i < vCount; ++i) {
295 switch (verbs[i]) {
296 case SkPath::kMove_Verb:
297 case SkPath::kLine_Verb:
298 ptCount = safe.addInt(ptCount, 1);
299 break;
300 case SkPath::kConic_Verb:
301 conicCount += 1;
302 // fall-through
303 case SkPath::kQuad_Verb:
304 ptCount = safe.addInt(ptCount, 2);
305 break;
306 case SkPath::kCubic_Verb:
307 ptCount = safe.addInt(ptCount, 3);
308 break;
309 case SkPath::kClose_Verb:
310 break;
311 default:
312 return false;
313 }
314 }
315 if (!safe) {
316 return false;
317 }
318 *ptCountPtr = ptCount;
319 *conicCountPtr = conicCount;
320 return true;
321 }
322
CreateFromBuffer(SkRBuffer * buffer)323 SkPathRef* SkPathRef::CreateFromBuffer(SkRBuffer* buffer) {
324 std::unique_ptr<SkPathRef> ref(new SkPathRef);
325
326 int32_t packed;
327 if (!buffer->readS32(&packed)) {
328 return nullptr;
329 }
330
331 ref->fIsFinite = (packed >> kIsFinite_SerializationShift) & 1;
332
333 int32_t verbCount, pointCount, conicCount;
334 if (!buffer->readU32(&(ref->fGenerationID)) ||
335 !buffer->readS32(&verbCount) || (verbCount < 0) ||
336 !buffer->readS32(&pointCount) || (pointCount < 0) ||
337 !buffer->readS32(&conicCount) || (conicCount < 0))
338 {
339 return nullptr;
340 }
341
342 uint64_t pointSize64 = sk_64_mul(pointCount, sizeof(SkPoint));
343 uint64_t conicSize64 = sk_64_mul(conicCount, sizeof(SkScalar));
344 if (!SkTFitsIn<size_t>(pointSize64) || !SkTFitsIn<size_t>(conicSize64)) {
345 return nullptr;
346 }
347
348 size_t verbSize = verbCount * sizeof(uint8_t);
349 size_t pointSize = SkToSizeT(pointSize64);
350 size_t conicSize = SkToSizeT(conicSize64);
351
352 {
353 uint64_t requiredBufferSize = sizeof(SkRect);
354 requiredBufferSize += verbSize;
355 requiredBufferSize += pointSize;
356 requiredBufferSize += conicSize;
357 if (buffer->available() < requiredBufferSize) {
358 return nullptr;
359 }
360 }
361
362 ref->resetToSize(verbCount, pointCount, conicCount);
363 SkASSERT(verbCount == ref->countVerbs());
364 SkASSERT(pointCount == ref->countPoints());
365 SkASSERT(conicCount == ref->fConicWeights.count());
366
367 if (!buffer->read(ref->verbsMemWritable(), verbSize) ||
368 !buffer->read(ref->fPoints, pointSize) ||
369 !buffer->read(ref->fConicWeights.begin(), conicSize) ||
370 !buffer->read(&ref->fBounds, sizeof(SkRect))) {
371 return nullptr;
372 }
373
374 // Check that the verbs are valid, and imply the correct number of pts and conics
375 {
376 int pCount, cCount;
377 if (!validate_verb_sequence(ref->verbsMemBegin(), ref->countVerbs())) {
378 return nullptr;
379 }
380 if (!deduce_pts_conics(ref->verbsMemBegin(), ref->countVerbs(), &pCount, &cCount) ||
381 pCount != ref->countPoints() || cCount != ref->fConicWeights.count()) {
382 return nullptr;
383 }
384 if (!validate_conic_weights(ref->fConicWeights.begin(), ref->fConicWeights.count())) {
385 return nullptr;
386 }
387 // Check that the bounds match the serialized bounds.
388 SkRect bounds;
389 if (ComputePtBounds(&bounds, *ref) != SkToBool(ref->fIsFinite) || bounds != ref->fBounds) {
390 return nullptr;
391 }
392
393 // call this after validate_verb_sequence, since it relies on valid verbs
394 ref->fSegmentMask = ref->computeSegmentMask();
395 }
396
397 ref->fBoundsIsDirty = false;
398
399 return ref.release();
400 }
401
Rewind(sk_sp<SkPathRef> * pathRef)402 void SkPathRef::Rewind(sk_sp<SkPathRef>* pathRef) {
403 if ((*pathRef)->unique()) {
404 SkDEBUGCODE((*pathRef)->validate();)
405 (*pathRef)->callGenIDChangeListeners();
406 (*pathRef)->fBoundsIsDirty = true; // this also invalidates fIsFinite
407 (*pathRef)->fVerbCnt = 0;
408 (*pathRef)->fPointCnt = 0;
409 (*pathRef)->fFreeSpace = (*pathRef)->currSize();
410 (*pathRef)->fGenerationID = 0;
411 (*pathRef)->fConicWeights.rewind();
412 (*pathRef)->fSegmentMask = 0;
413 (*pathRef)->fIsOval = false;
414 (*pathRef)->fIsRRect = false;
415 SkDEBUGCODE((*pathRef)->validate();)
416 } else {
417 int oldVCnt = (*pathRef)->countVerbs();
418 int oldPCnt = (*pathRef)->countPoints();
419 pathRef->reset(new SkPathRef);
420 (*pathRef)->resetToSize(0, 0, 0, oldVCnt, oldPCnt);
421 }
422 }
423
operator ==(const SkPathRef & ref) const424 bool SkPathRef::operator== (const SkPathRef& ref) const {
425 SkDEBUGCODE(this->validate();)
426 SkDEBUGCODE(ref.validate();)
427
428 // We explicitly check fSegmentMask as a quick-reject. We could skip it,
429 // since it is only a cache of info in the fVerbs, but its a fast way to
430 // notice a difference
431 if (fSegmentMask != ref.fSegmentMask) {
432 return false;
433 }
434
435 bool genIDMatch = fGenerationID && fGenerationID == ref.fGenerationID;
436 #ifdef SK_RELEASE
437 if (genIDMatch) {
438 return true;
439 }
440 #endif
441 if (fPointCnt != ref.fPointCnt ||
442 fVerbCnt != ref.fVerbCnt) {
443 SkASSERT(!genIDMatch);
444 return false;
445 }
446 if (0 == ref.fVerbCnt) {
447 SkASSERT(0 == ref.fPointCnt);
448 return true;
449 }
450 SkASSERT(this->verbsMemBegin() && ref.verbsMemBegin());
451 if (0 != memcmp(this->verbsMemBegin(),
452 ref.verbsMemBegin(),
453 ref.fVerbCnt * sizeof(uint8_t))) {
454 SkASSERT(!genIDMatch);
455 return false;
456 }
457 SkASSERT(this->points() && ref.points());
458 if (0 != memcmp(this->points(),
459 ref.points(),
460 ref.fPointCnt * sizeof(SkPoint))) {
461 SkASSERT(!genIDMatch);
462 return false;
463 }
464 if (fConicWeights != ref.fConicWeights) {
465 SkASSERT(!genIDMatch);
466 return false;
467 }
468 return true;
469 }
470
writeToBuffer(SkWBuffer * buffer) const471 void SkPathRef::writeToBuffer(SkWBuffer* buffer) const {
472 SkDEBUGCODE(this->validate();)
473 SkDEBUGCODE(size_t beforePos = buffer->pos();)
474
475 // Call getBounds() to ensure (as a side-effect) that fBounds
476 // and fIsFinite are computed.
477 const SkRect& bounds = this->getBounds();
478
479 // We store fSegmentMask for older readers, but current readers can't trust it, so they
480 // don't read it.
481 int32_t packed = ((fIsFinite & 1) << kIsFinite_SerializationShift) |
482 (fSegmentMask << kSegmentMask_SerializationShift);
483 buffer->write32(packed);
484
485 // TODO: write gen ID here. Problem: We don't know if we're cross process or not from
486 // SkWBuffer. Until this is fixed we write 0.
487 buffer->write32(0);
488 buffer->write32(fVerbCnt);
489 buffer->write32(fPointCnt);
490 buffer->write32(fConicWeights.count());
491 buffer->write(verbsMemBegin(), fVerbCnt * sizeof(uint8_t));
492 buffer->write(fPoints, fPointCnt * sizeof(SkPoint));
493 buffer->write(fConicWeights.begin(), fConicWeights.bytes());
494 buffer->write(&bounds, sizeof(bounds));
495
496 SkASSERT(buffer->pos() - beforePos == (size_t) this->writeSize());
497 }
498
writeSize() const499 uint32_t SkPathRef::writeSize() const {
500 return uint32_t(5 * sizeof(uint32_t) +
501 fVerbCnt * sizeof(uint8_t) +
502 fPointCnt * sizeof(SkPoint) +
503 fConicWeights.bytes() +
504 sizeof(SkRect));
505 }
506
copy(const SkPathRef & ref,int additionalReserveVerbs,int additionalReservePoints)507 void SkPathRef::copy(const SkPathRef& ref,
508 int additionalReserveVerbs,
509 int additionalReservePoints) {
510 SkDEBUGCODE(this->validate();)
511 this->resetToSize(ref.fVerbCnt, ref.fPointCnt, ref.fConicWeights.count(),
512 additionalReserveVerbs, additionalReservePoints);
513 sk_careful_memcpy(this->verbsMemWritable(), ref.verbsMemBegin(), ref.fVerbCnt*sizeof(uint8_t));
514 sk_careful_memcpy(this->fPoints, ref.fPoints, ref.fPointCnt * sizeof(SkPoint));
515 fConicWeights = ref.fConicWeights;
516 fBoundsIsDirty = ref.fBoundsIsDirty;
517 if (!fBoundsIsDirty) {
518 fBounds = ref.fBounds;
519 fIsFinite = ref.fIsFinite;
520 }
521 fSegmentMask = ref.fSegmentMask;
522 fIsOval = ref.fIsOval;
523 fIsRRect = ref.fIsRRect;
524 fRRectOrOvalIsCCW = ref.fRRectOrOvalIsCCW;
525 fRRectOrOvalStartIdx = ref.fRRectOrOvalStartIdx;
526 SkDEBUGCODE(this->validate();)
527 }
528
computeSegmentMask() const529 unsigned SkPathRef::computeSegmentMask() const {
530 const uint8_t* verbs = this->verbsMemBegin();
531 unsigned mask = 0;
532 for (int i = this->countVerbs() - 1; i >= 0; --i) {
533 switch (verbs[i]) {
534 case SkPath::kLine_Verb: mask |= SkPath::kLine_SegmentMask; break;
535 case SkPath::kQuad_Verb: mask |= SkPath::kQuad_SegmentMask; break;
536 case SkPath::kConic_Verb: mask |= SkPath::kConic_SegmentMask; break;
537 case SkPath::kCubic_Verb: mask |= SkPath::kCubic_SegmentMask; break;
538 default: break;
539 }
540 }
541 return mask;
542 }
543
interpolate(const SkPathRef & ending,SkScalar weight,SkPathRef * out) const544 void SkPathRef::interpolate(const SkPathRef& ending, SkScalar weight, SkPathRef* out) const {
545 const SkScalar* inValues = &ending.getPoints()->fX;
546 SkScalar* outValues = &out->getPoints()->fX;
547 int count = out->countPoints() * 2;
548 for (int index = 0; index < count; ++index) {
549 outValues[index] = outValues[index] * weight + inValues[index] * (1 - weight);
550 }
551 out->fBoundsIsDirty = true;
552 out->fIsOval = false;
553 out->fIsRRect = false;
554 }
555
growForRepeatedVerb(int verb,int numVbs,SkScalar ** weights)556 SkPoint* SkPathRef::growForRepeatedVerb(int /*SkPath::Verb*/ verb,
557 int numVbs,
558 SkScalar** weights) {
559 // This value is just made-up for now. When count is 4, calling memset was much
560 // slower than just writing the loop. This seems odd, and hopefully in the
561 // future this will appear to have been a fluke...
562 static const unsigned int kMIN_COUNT_FOR_MEMSET_TO_BE_FAST = 16;
563
564 SkDEBUGCODE(this->validate();)
565 int pCnt;
566 switch (verb) {
567 case SkPath::kMove_Verb:
568 pCnt = numVbs;
569 break;
570 case SkPath::kLine_Verb:
571 fSegmentMask |= SkPath::kLine_SegmentMask;
572 pCnt = numVbs;
573 break;
574 case SkPath::kQuad_Verb:
575 fSegmentMask |= SkPath::kQuad_SegmentMask;
576 pCnt = 2 * numVbs;
577 break;
578 case SkPath::kConic_Verb:
579 fSegmentMask |= SkPath::kConic_SegmentMask;
580 pCnt = 2 * numVbs;
581 break;
582 case SkPath::kCubic_Verb:
583 fSegmentMask |= SkPath::kCubic_SegmentMask;
584 pCnt = 3 * numVbs;
585 break;
586 case SkPath::kClose_Verb:
587 SkDEBUGFAIL("growForRepeatedVerb called for kClose_Verb");
588 pCnt = 0;
589 break;
590 case SkPath::kDone_Verb:
591 SkDEBUGFAIL("growForRepeatedVerb called for kDone");
592 // fall through
593 default:
594 SkDEBUGFAIL("default should not be reached");
595 pCnt = 0;
596 }
597
598 size_t space = numVbs * sizeof(uint8_t) + pCnt * sizeof (SkPoint);
599 this->makeSpace(space);
600
601 SkPoint* ret = fPoints + fPointCnt;
602 uint8_t* vb = fVerbs - fVerbCnt;
603
604 // cast to unsigned, so if kMIN_COUNT_FOR_MEMSET_TO_BE_FAST is defined to
605 // be 0, the compiler will remove the test/branch entirely.
606 if ((unsigned)numVbs >= kMIN_COUNT_FOR_MEMSET_TO_BE_FAST) {
607 memset(vb - numVbs, verb, numVbs);
608 } else {
609 for (int i = 0; i < numVbs; ++i) {
610 vb[~i] = verb;
611 }
612 }
613
614 SkSafeMath safe;
615 fVerbCnt = safe.addInt(fVerbCnt, numVbs);
616 fPointCnt = safe.addInt(fPointCnt, pCnt);
617 if (!safe) {
618 SK_ABORT("cannot grow path");
619 }
620 fFreeSpace -= space;
621 fBoundsIsDirty = true; // this also invalidates fIsFinite
622 fIsOval = false;
623 fIsRRect = false;
624
625 if (SkPath::kConic_Verb == verb) {
626 SkASSERT(weights);
627 *weights = fConicWeights.append(numVbs);
628 }
629
630 SkDEBUGCODE(this->validate();)
631 return ret;
632 }
633
growForVerb(int verb,SkScalar weight)634 SkPoint* SkPathRef::growForVerb(int /* SkPath::Verb*/ verb, SkScalar weight) {
635 SkDEBUGCODE(this->validate();)
636 int pCnt;
637 unsigned mask = 0;
638 switch (verb) {
639 case SkPath::kMove_Verb:
640 pCnt = 1;
641 break;
642 case SkPath::kLine_Verb:
643 mask = SkPath::kLine_SegmentMask;
644 pCnt = 1;
645 break;
646 case SkPath::kQuad_Verb:
647 mask = SkPath::kQuad_SegmentMask;
648 pCnt = 2;
649 break;
650 case SkPath::kConic_Verb:
651 mask = SkPath::kConic_SegmentMask;
652 pCnt = 2;
653 break;
654 case SkPath::kCubic_Verb:
655 mask = SkPath::kCubic_SegmentMask;
656 pCnt = 3;
657 break;
658 case SkPath::kClose_Verb:
659 pCnt = 0;
660 break;
661 case SkPath::kDone_Verb:
662 SkDEBUGFAIL("growForVerb called for kDone");
663 // fall through
664 default:
665 SkDEBUGFAIL("default is not reached");
666 pCnt = 0;
667 }
668 SkSafeMath safe;
669 int newPointCnt = safe.addInt(fPointCnt, pCnt);
670 int newVerbCnt = safe.addInt(fVerbCnt, 1);
671 if (!safe) {
672 SK_ABORT("cannot grow path");
673 }
674 size_t space = sizeof(uint8_t) + pCnt * sizeof (SkPoint);
675 this->makeSpace(space);
676 this->fVerbs[~fVerbCnt] = verb;
677 SkPoint* ret = fPoints + fPointCnt;
678 fVerbCnt = newVerbCnt;
679 fPointCnt = newPointCnt;
680 fSegmentMask |= mask;
681 fFreeSpace -= space;
682 fBoundsIsDirty = true; // this also invalidates fIsFinite
683 fIsOval = false;
684 fIsRRect = false;
685
686 if (SkPath::kConic_Verb == verb) {
687 *fConicWeights.append() = weight;
688 }
689
690 SkDEBUGCODE(this->validate();)
691 return ret;
692 }
693
genID() const694 uint32_t SkPathRef::genID() const {
695 SkASSERT(fEditorsAttached.load() == 0);
696 static const uint32_t kMask = (static_cast<int64_t>(1) << SkPathPriv::kPathRefGenIDBitCnt) - 1;
697
698 if (fGenerationID == 0) {
699 if (fPointCnt == 0 && fVerbCnt == 0) {
700 fGenerationID = kEmptyGenID;
701 } else {
702 static std::atomic<uint32_t> nextID{kEmptyGenID + 1};
703 do {
704 fGenerationID = nextID.fetch_add(1, std::memory_order_relaxed) & kMask;
705 } while (fGenerationID == 0 || fGenerationID == kEmptyGenID);
706 }
707 }
708 return fGenerationID;
709 }
710
addGenIDChangeListener(sk_sp<GenIDChangeListener> listener)711 void SkPathRef::addGenIDChangeListener(sk_sp<GenIDChangeListener> listener) {
712 if (nullptr == listener || this == gEmpty) {
713 return;
714 }
715
716 SkAutoMutexExclusive lock(fGenIDChangeListenersMutex);
717
718 // Clean out any stale listeners before we append the new one.
719 for (int i = 0; i < fGenIDChangeListeners.count(); ++i) {
720 if (fGenIDChangeListeners[i]->shouldUnregisterFromPath()) {
721 fGenIDChangeListeners[i]->unref();
722 fGenIDChangeListeners.removeShuffle(i--); // No need to preserve the order after i.
723 }
724 }
725
726 SkASSERT(!listener->shouldUnregisterFromPath());
727 *fGenIDChangeListeners.append() = listener.release();
728 }
729
730 // we need to be called *before* the genID gets changed or zerod
callGenIDChangeListeners()731 void SkPathRef::callGenIDChangeListeners() {
732 SkAutoMutexExclusive lock(fGenIDChangeListenersMutex);
733 for (GenIDChangeListener* listener : fGenIDChangeListeners) {
734 if (!listener->shouldUnregisterFromPath()) {
735 listener->onChange();
736 }
737 // Listeners get at most one shot, so whether these triggered or not, blow them away.
738 listener->unref();
739 }
740
741 fGenIDChangeListeners.reset();
742 }
743
getRRect() const744 SkRRect SkPathRef::getRRect() const {
745 const SkRect& bounds = this->getBounds();
746 SkVector radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
747 Iter iter(*this);
748 SkPoint pts[4];
749 uint8_t verb = iter.next(pts);
750 SkASSERT(SkPath::kMove_Verb == verb);
751 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
752 if (SkPath::kConic_Verb == verb) {
753 SkVector v1_0 = pts[1] - pts[0];
754 SkVector v2_1 = pts[2] - pts[1];
755 SkVector dxdy;
756 if (v1_0.fX) {
757 SkASSERT(!v2_1.fX && !v1_0.fY);
758 dxdy.set(SkScalarAbs(v1_0.fX), SkScalarAbs(v2_1.fY));
759 } else if (!v1_0.fY) {
760 SkASSERT(!v2_1.fX || !v2_1.fY);
761 dxdy.set(SkScalarAbs(v2_1.fX), SkScalarAbs(v2_1.fY));
762 } else {
763 SkASSERT(!v2_1.fY);
764 dxdy.set(SkScalarAbs(v2_1.fX), SkScalarAbs(v1_0.fY));
765 }
766 SkRRect::Corner corner =
767 pts[1].fX == bounds.fLeft ?
768 pts[1].fY == bounds.fTop ?
769 SkRRect::kUpperLeft_Corner : SkRRect::kLowerLeft_Corner :
770 pts[1].fY == bounds.fTop ?
771 SkRRect::kUpperRight_Corner : SkRRect::kLowerRight_Corner;
772 SkASSERT(!radii[corner].fX && !radii[corner].fY);
773 radii[corner] = dxdy;
774 } else {
775 SkASSERT((verb == SkPath::kLine_Verb
776 && (!(pts[1].fX - pts[0].fX) || !(pts[1].fY - pts[0].fY)))
777 || verb == SkPath::kClose_Verb);
778 }
779 }
780 SkRRect rrect;
781 rrect.setRectRadii(bounds, radii);
782 return rrect;
783 }
784
785 ///////////////////////////////////////////////////////////////////////////////
786
Iter()787 SkPathRef::Iter::Iter() {
788 #ifdef SK_DEBUG
789 fPts = nullptr;
790 fConicWeights = nullptr;
791 #endif
792 // need to init enough to make next() harmlessly return kDone_Verb
793 fVerbs = nullptr;
794 fVerbStop = nullptr;
795 }
796
Iter(const SkPathRef & path)797 SkPathRef::Iter::Iter(const SkPathRef& path) {
798 this->setPathRef(path);
799 }
800
setPathRef(const SkPathRef & path)801 void SkPathRef::Iter::setPathRef(const SkPathRef& path) {
802 fPts = path.points();
803 fVerbs = path.verbs();
804 fVerbStop = path.verbsMemBegin();
805 fConicWeights = path.conicWeights();
806 if (fConicWeights) {
807 fConicWeights -= 1; // begin one behind
808 }
809
810 // Don't allow iteration through non-finite points.
811 if (!path.isFinite()) {
812 fVerbStop = fVerbs;
813 }
814 }
815
next(SkPoint pts[4])816 uint8_t SkPathRef::Iter::next(SkPoint pts[4]) {
817 SkASSERT(pts);
818
819 SkDEBUGCODE(unsigned peekResult = this->peek();)
820
821 if (fVerbs == fVerbStop) {
822 SkASSERT(peekResult == SkPath::kDone_Verb);
823 return (uint8_t) SkPath::kDone_Verb;
824 }
825
826 // fVerbs points one beyond next verb so decrement first.
827 unsigned verb = *(--fVerbs);
828 const SkPoint* srcPts = fPts;
829
830 switch (verb) {
831 case SkPath::kMove_Verb:
832 pts[0] = srcPts[0];
833 srcPts += 1;
834 break;
835 case SkPath::kLine_Verb:
836 pts[0] = srcPts[-1];
837 pts[1] = srcPts[0];
838 srcPts += 1;
839 break;
840 case SkPath::kConic_Verb:
841 fConicWeights += 1;
842 // fall-through
843 case SkPath::kQuad_Verb:
844 pts[0] = srcPts[-1];
845 pts[1] = srcPts[0];
846 pts[2] = srcPts[1];
847 srcPts += 2;
848 break;
849 case SkPath::kCubic_Verb:
850 pts[0] = srcPts[-1];
851 pts[1] = srcPts[0];
852 pts[2] = srcPts[1];
853 pts[3] = srcPts[2];
854 srcPts += 3;
855 break;
856 case SkPath::kClose_Verb:
857 break;
858 case SkPath::kDone_Verb:
859 SkASSERT(fVerbs == fVerbStop);
860 break;
861 }
862 fPts = srcPts;
863 SkASSERT(peekResult == verb);
864 return (uint8_t) verb;
865 }
866
peek() const867 uint8_t SkPathRef::Iter::peek() const {
868 const uint8_t* next = fVerbs;
869 return next <= fVerbStop ? (uint8_t) SkPath::kDone_Verb : next[-1];
870 }
871
872
isValid() const873 bool SkPathRef::isValid() const {
874 if (static_cast<ptrdiff_t>(fFreeSpace) < 0) {
875 return false;
876 }
877 if (reinterpret_cast<intptr_t>(fVerbs) - reinterpret_cast<intptr_t>(fPoints) < 0) {
878 return false;
879 }
880 if ((nullptr == fPoints) != (nullptr == fVerbs)) {
881 return false;
882 }
883 if (nullptr == fPoints && 0 != fFreeSpace) {
884 return false;
885 }
886 if (nullptr == fPoints && fPointCnt) {
887 return false;
888 }
889 if (nullptr == fVerbs && fVerbCnt) {
890 return false;
891 }
892 if (this->currSize() !=
893 fFreeSpace + sizeof(SkPoint) * fPointCnt + sizeof(uint8_t) * fVerbCnt) {
894 return false;
895 }
896
897 if (fIsOval || fIsRRect) {
898 // Currently we don't allow both of these to be set, even though ovals are ro
899 if (fIsOval == fIsRRect) {
900 return false;
901 }
902 if (fIsOval) {
903 if (fRRectOrOvalStartIdx >= 4) {
904 return false;
905 }
906 } else {
907 if (fRRectOrOvalStartIdx >= 8) {
908 return false;
909 }
910 }
911 }
912
913 if (!fBoundsIsDirty && !fBounds.isEmpty()) {
914 bool isFinite = true;
915 Sk2s leftTop = Sk2s(fBounds.fLeft, fBounds.fTop);
916 Sk2s rightBot = Sk2s(fBounds.fRight, fBounds.fBottom);
917 for (int i = 0; i < fPointCnt; ++i) {
918 Sk2s point = Sk2s(fPoints[i].fX, fPoints[i].fY);
919 #ifdef SK_DEBUG
920 if (fPoints[i].isFinite() &&
921 ((point < leftTop).anyTrue() || (point > rightBot).anyTrue())) {
922 SkDebugf("bad SkPathRef bounds: %g %g %g %g\n",
923 fBounds.fLeft, fBounds.fTop, fBounds.fRight, fBounds.fBottom);
924 for (int j = 0; j < fPointCnt; ++j) {
925 if (i == j) {
926 SkDebugf("*** bounds do not contain: ");
927 }
928 SkDebugf("%g %g\n", fPoints[j].fX, fPoints[j].fY);
929 }
930 return false;
931 }
932 #endif
933
934 if (fPoints[i].isFinite() && (point < leftTop).anyTrue() && !(point > rightBot).anyTrue())
935 return false;
936 if (!fPoints[i].isFinite()) {
937 isFinite = false;
938 }
939 }
940 if (SkToBool(fIsFinite) != isFinite) {
941 return false;
942 }
943 }
944 return true;
945 }
946