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 "SkPathRef.h"
9
10 #include "SkBuffer.h"
11 #include "SkNx.h"
12 #include "SkOnce.h"
13 #include "SkPath.h"
14 #include "SkPathPriv.h"
15 #include "SkSafeMath.h"
16 #include "SkTo.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 SkDEBUGCODE((*dst)->validate();)
247 }
248
validate_verb_sequence(const uint8_t verbs[],int vCount)249 static bool validate_verb_sequence(const uint8_t verbs[], int vCount) {
250 // verbs are stored backwards, but we need to visit them in logical order to determine if
251 // they form a valid sequence.
252
253 bool needsMoveTo = true;
254 bool invalidSequence = false;
255
256 for (int i = vCount - 1; i >= 0; --i) {
257 switch (verbs[i]) {
258 case SkPath::kMove_Verb:
259 needsMoveTo = false;
260 break;
261 case SkPath::kLine_Verb:
262 case SkPath::kQuad_Verb:
263 case SkPath::kConic_Verb:
264 case SkPath::kCubic_Verb:
265 invalidSequence |= needsMoveTo;
266 break;
267 case SkPath::kClose_Verb:
268 needsMoveTo = true;
269 break;
270 default:
271 return false; // unknown verb
272 }
273 }
274 return !invalidSequence;
275 }
276
277 // Given the verb array, deduce the required number of pts and conics,
278 // or if an invalid verb is encountered, return false.
deduce_pts_conics(const uint8_t verbs[],int vCount,int * ptCountPtr,int * conicCountPtr)279 static bool deduce_pts_conics(const uint8_t verbs[], int vCount, int* ptCountPtr,
280 int* conicCountPtr) {
281 // When there is at least one verb, the first is required to be kMove_Verb.
282 if (0 < vCount && verbs[vCount-1] != SkPath::kMove_Verb) {
283 return false;
284 }
285
286 SkSafeMath safe;
287 int ptCount = 0;
288 int conicCount = 0;
289 for (int i = 0; i < vCount; ++i) {
290 switch (verbs[i]) {
291 case SkPath::kMove_Verb:
292 case SkPath::kLine_Verb:
293 ptCount = safe.addInt(ptCount, 1);
294 break;
295 case SkPath::kConic_Verb:
296 conicCount += 1;
297 // fall-through
298 case SkPath::kQuad_Verb:
299 ptCount = safe.addInt(ptCount, 2);
300 break;
301 case SkPath::kCubic_Verb:
302 ptCount = safe.addInt(ptCount, 3);
303 break;
304 case SkPath::kClose_Verb:
305 break;
306 default:
307 return false;
308 }
309 }
310 if (!safe) {
311 return false;
312 }
313 *ptCountPtr = ptCount;
314 *conicCountPtr = conicCount;
315 return true;
316 }
317
CreateFromBuffer(SkRBuffer * buffer)318 SkPathRef* SkPathRef::CreateFromBuffer(SkRBuffer* buffer) {
319 std::unique_ptr<SkPathRef> ref(new SkPathRef);
320
321 int32_t packed;
322 if (!buffer->readS32(&packed)) {
323 return nullptr;
324 }
325
326 ref->fIsFinite = (packed >> kIsFinite_SerializationShift) & 1;
327
328 int32_t verbCount, pointCount, conicCount;
329 if (!buffer->readU32(&(ref->fGenerationID)) ||
330 !buffer->readS32(&verbCount) || (verbCount < 0) ||
331 !buffer->readS32(&pointCount) || (pointCount < 0) ||
332 !buffer->readS32(&conicCount) || (conicCount < 0))
333 {
334 return nullptr;
335 }
336
337 uint64_t pointSize64 = sk_64_mul(pointCount, sizeof(SkPoint));
338 uint64_t conicSize64 = sk_64_mul(conicCount, sizeof(SkScalar));
339 if (!SkTFitsIn<size_t>(pointSize64) || !SkTFitsIn<size_t>(conicSize64)) {
340 return nullptr;
341 }
342
343 size_t verbSize = verbCount * sizeof(uint8_t);
344 size_t pointSize = SkToSizeT(pointSize64);
345 size_t conicSize = SkToSizeT(conicSize64);
346
347 {
348 uint64_t requiredBufferSize = sizeof(SkRect);
349 requiredBufferSize += verbSize;
350 requiredBufferSize += pointSize;
351 requiredBufferSize += conicSize;
352 if (buffer->available() < requiredBufferSize) {
353 return nullptr;
354 }
355 }
356
357 ref->resetToSize(verbCount, pointCount, conicCount);
358 SkASSERT(verbCount == ref->countVerbs());
359 SkASSERT(pointCount == ref->countPoints());
360 SkASSERT(conicCount == ref->fConicWeights.count());
361
362 if (!buffer->read(ref->verbsMemWritable(), verbSize) ||
363 !buffer->read(ref->fPoints, pointSize) ||
364 !buffer->read(ref->fConicWeights.begin(), conicSize) ||
365 !buffer->read(&ref->fBounds, sizeof(SkRect))) {
366 return nullptr;
367 }
368
369 // Check that the verbs are valid, and imply the correct number of pts and conics
370 {
371 int pCount, cCount;
372 if (!validate_verb_sequence(ref->verbsMemBegin(), ref->countVerbs())) {
373 return nullptr;
374 }
375 if (!deduce_pts_conics(ref->verbsMemBegin(), ref->countVerbs(), &pCount, &cCount) ||
376 pCount != ref->countPoints() || cCount != ref->fConicWeights.count()) {
377 return nullptr;
378 }
379 if (!validate_conic_weights(ref->fConicWeights.begin(), ref->fConicWeights.count())) {
380 return nullptr;
381 }
382 // Check that the bounds match the serialized bounds.
383 SkRect bounds;
384 if (ComputePtBounds(&bounds, *ref) != SkToBool(ref->fIsFinite) || bounds != ref->fBounds) {
385 return nullptr;
386 }
387
388 // call this after validate_verb_sequence, since it relies on valid verbs
389 ref->fSegmentMask = ref->computeSegmentMask();
390 }
391
392 ref->fBoundsIsDirty = false;
393
394 return ref.release();
395 }
396
Rewind(sk_sp<SkPathRef> * pathRef)397 void SkPathRef::Rewind(sk_sp<SkPathRef>* pathRef) {
398 if ((*pathRef)->unique()) {
399 SkDEBUGCODE((*pathRef)->validate();)
400 (*pathRef)->callGenIDChangeListeners();
401 (*pathRef)->fBoundsIsDirty = true; // this also invalidates fIsFinite
402 (*pathRef)->fVerbCnt = 0;
403 (*pathRef)->fPointCnt = 0;
404 (*pathRef)->fFreeSpace = (*pathRef)->currSize();
405 (*pathRef)->fGenerationID = 0;
406 (*pathRef)->fConicWeights.rewind();
407 (*pathRef)->fSegmentMask = 0;
408 (*pathRef)->fIsOval = false;
409 (*pathRef)->fIsRRect = false;
410 SkDEBUGCODE((*pathRef)->validate();)
411 } else {
412 int oldVCnt = (*pathRef)->countVerbs();
413 int oldPCnt = (*pathRef)->countPoints();
414 pathRef->reset(new SkPathRef);
415 (*pathRef)->resetToSize(0, 0, 0, oldVCnt, oldPCnt);
416 }
417 }
418
operator ==(const SkPathRef & ref) const419 bool SkPathRef::operator== (const SkPathRef& ref) const {
420 SkDEBUGCODE(this->validate();)
421 SkDEBUGCODE(ref.validate();)
422
423 // We explicitly check fSegmentMask as a quick-reject. We could skip it,
424 // since it is only a cache of info in the fVerbs, but its a fast way to
425 // notice a difference
426 if (fSegmentMask != ref.fSegmentMask) {
427 return false;
428 }
429
430 bool genIDMatch = fGenerationID && fGenerationID == ref.fGenerationID;
431 #ifdef SK_RELEASE
432 if (genIDMatch) {
433 return true;
434 }
435 #endif
436 if (fPointCnt != ref.fPointCnt ||
437 fVerbCnt != ref.fVerbCnt) {
438 SkASSERT(!genIDMatch);
439 return false;
440 }
441 if (0 == ref.fVerbCnt) {
442 SkASSERT(0 == ref.fPointCnt);
443 return true;
444 }
445 SkASSERT(this->verbsMemBegin() && ref.verbsMemBegin());
446 if (0 != memcmp(this->verbsMemBegin(),
447 ref.verbsMemBegin(),
448 ref.fVerbCnt * sizeof(uint8_t))) {
449 SkASSERT(!genIDMatch);
450 return false;
451 }
452 SkASSERT(this->points() && ref.points());
453 if (0 != memcmp(this->points(),
454 ref.points(),
455 ref.fPointCnt * sizeof(SkPoint))) {
456 SkASSERT(!genIDMatch);
457 return false;
458 }
459 if (fConicWeights != ref.fConicWeights) {
460 SkASSERT(!genIDMatch);
461 return false;
462 }
463 return true;
464 }
465
writeToBuffer(SkWBuffer * buffer) const466 void SkPathRef::writeToBuffer(SkWBuffer* buffer) const {
467 SkDEBUGCODE(this->validate();)
468 SkDEBUGCODE(size_t beforePos = buffer->pos();)
469
470 // Call getBounds() to ensure (as a side-effect) that fBounds
471 // and fIsFinite are computed.
472 const SkRect& bounds = this->getBounds();
473
474 // We store fSegmentMask for older readers, but current readers can't trust it, so they
475 // don't read it.
476 int32_t packed = ((fIsFinite & 1) << kIsFinite_SerializationShift) |
477 (fSegmentMask << kSegmentMask_SerializationShift);
478 buffer->write32(packed);
479
480 // TODO: write gen ID here. Problem: We don't know if we're cross process or not from
481 // SkWBuffer. Until this is fixed we write 0.
482 buffer->write32(0);
483 buffer->write32(fVerbCnt);
484 buffer->write32(fPointCnt);
485 buffer->write32(fConicWeights.count());
486 buffer->write(verbsMemBegin(), fVerbCnt * sizeof(uint8_t));
487 buffer->write(fPoints, fPointCnt * sizeof(SkPoint));
488 buffer->write(fConicWeights.begin(), fConicWeights.bytes());
489 buffer->write(&bounds, sizeof(bounds));
490
491 SkASSERT(buffer->pos() - beforePos == (size_t) this->writeSize());
492 }
493
writeSize() const494 uint32_t SkPathRef::writeSize() const {
495 return uint32_t(5 * sizeof(uint32_t) +
496 fVerbCnt * sizeof(uint8_t) +
497 fPointCnt * sizeof(SkPoint) +
498 fConicWeights.bytes() +
499 sizeof(SkRect));
500 }
501
copy(const SkPathRef & ref,int additionalReserveVerbs,int additionalReservePoints)502 void SkPathRef::copy(const SkPathRef& ref,
503 int additionalReserveVerbs,
504 int additionalReservePoints) {
505 SkDEBUGCODE(this->validate();)
506 this->resetToSize(ref.fVerbCnt, ref.fPointCnt, ref.fConicWeights.count(),
507 additionalReserveVerbs, additionalReservePoints);
508 sk_careful_memcpy(this->verbsMemWritable(), ref.verbsMemBegin(), ref.fVerbCnt*sizeof(uint8_t));
509 sk_careful_memcpy(this->fPoints, ref.fPoints, ref.fPointCnt * sizeof(SkPoint));
510 fConicWeights = ref.fConicWeights;
511 fBoundsIsDirty = ref.fBoundsIsDirty;
512 if (!fBoundsIsDirty) {
513 fBounds = ref.fBounds;
514 fIsFinite = ref.fIsFinite;
515 }
516 fSegmentMask = ref.fSegmentMask;
517 fIsOval = ref.fIsOval;
518 fIsRRect = ref.fIsRRect;
519 fRRectOrOvalIsCCW = ref.fRRectOrOvalIsCCW;
520 fRRectOrOvalStartIdx = ref.fRRectOrOvalStartIdx;
521 SkDEBUGCODE(this->validate();)
522 }
523
computeSegmentMask() const524 unsigned SkPathRef::computeSegmentMask() const {
525 const uint8_t* verbs = this->verbsMemBegin();
526 unsigned mask = 0;
527 for (int i = this->countVerbs() - 1; i >= 0; --i) {
528 switch (verbs[i]) {
529 case SkPath::kLine_Verb: mask |= SkPath::kLine_SegmentMask; break;
530 case SkPath::kQuad_Verb: mask |= SkPath::kQuad_SegmentMask; break;
531 case SkPath::kConic_Verb: mask |= SkPath::kConic_SegmentMask; break;
532 case SkPath::kCubic_Verb: mask |= SkPath::kCubic_SegmentMask; break;
533 default: break;
534 }
535 }
536 return mask;
537 }
538
interpolate(const SkPathRef & ending,SkScalar weight,SkPathRef * out) const539 void SkPathRef::interpolate(const SkPathRef& ending, SkScalar weight, SkPathRef* out) const {
540 const SkScalar* inValues = &ending.getPoints()->fX;
541 SkScalar* outValues = &out->getPoints()->fX;
542 int count = out->countPoints() * 2;
543 for (int index = 0; index < count; ++index) {
544 outValues[index] = outValues[index] * weight + inValues[index] * (1 - weight);
545 }
546 out->fBoundsIsDirty = true;
547 out->fIsOval = false;
548 out->fIsRRect = false;
549 }
550
growForRepeatedVerb(int verb,int numVbs,SkScalar ** weights)551 SkPoint* SkPathRef::growForRepeatedVerb(int /*SkPath::Verb*/ verb,
552 int numVbs,
553 SkScalar** weights) {
554 // This value is just made-up for now. When count is 4, calling memset was much
555 // slower than just writing the loop. This seems odd, and hopefully in the
556 // future this will appear to have been a fluke...
557 static const unsigned int kMIN_COUNT_FOR_MEMSET_TO_BE_FAST = 16;
558
559 SkDEBUGCODE(this->validate();)
560 int pCnt;
561 switch (verb) {
562 case SkPath::kMove_Verb:
563 pCnt = numVbs;
564 break;
565 case SkPath::kLine_Verb:
566 fSegmentMask |= SkPath::kLine_SegmentMask;
567 pCnt = numVbs;
568 break;
569 case SkPath::kQuad_Verb:
570 fSegmentMask |= SkPath::kQuad_SegmentMask;
571 pCnt = 2 * numVbs;
572 break;
573 case SkPath::kConic_Verb:
574 fSegmentMask |= SkPath::kConic_SegmentMask;
575 pCnt = 2 * numVbs;
576 break;
577 case SkPath::kCubic_Verb:
578 fSegmentMask |= SkPath::kCubic_SegmentMask;
579 pCnt = 3 * numVbs;
580 break;
581 case SkPath::kClose_Verb:
582 SkDEBUGFAIL("growForRepeatedVerb called for kClose_Verb");
583 pCnt = 0;
584 break;
585 case SkPath::kDone_Verb:
586 SkDEBUGFAIL("growForRepeatedVerb called for kDone");
587 // fall through
588 default:
589 SkDEBUGFAIL("default should not be reached");
590 pCnt = 0;
591 }
592
593 size_t space = numVbs * sizeof(uint8_t) + pCnt * sizeof (SkPoint);
594 this->makeSpace(space);
595
596 SkPoint* ret = fPoints + fPointCnt;
597 uint8_t* vb = fVerbs - fVerbCnt;
598
599 // cast to unsigned, so if kMIN_COUNT_FOR_MEMSET_TO_BE_FAST is defined to
600 // be 0, the compiler will remove the test/branch entirely.
601 if ((unsigned)numVbs >= kMIN_COUNT_FOR_MEMSET_TO_BE_FAST) {
602 memset(vb - numVbs, verb, numVbs);
603 } else {
604 for (int i = 0; i < numVbs; ++i) {
605 vb[~i] = verb;
606 }
607 }
608
609 SkSafeMath safe;
610 fVerbCnt = safe.addInt(fVerbCnt, numVbs);
611 fPointCnt = safe.addInt(fPointCnt, pCnt);
612 if (!safe) {
613 SK_ABORT("cannot grow path");
614 }
615 fFreeSpace -= space;
616 fBoundsIsDirty = true; // this also invalidates fIsFinite
617 fIsOval = false;
618 fIsRRect = false;
619
620 if (SkPath::kConic_Verb == verb) {
621 SkASSERT(weights);
622 *weights = fConicWeights.append(numVbs);
623 }
624
625 SkDEBUGCODE(this->validate();)
626 return ret;
627 }
628
growForVerb(int verb,SkScalar weight)629 SkPoint* SkPathRef::growForVerb(int /* SkPath::Verb*/ verb, SkScalar weight) {
630 SkDEBUGCODE(this->validate();)
631 int pCnt;
632 unsigned mask = 0;
633 switch (verb) {
634 case SkPath::kMove_Verb:
635 pCnt = 1;
636 break;
637 case SkPath::kLine_Verb:
638 mask = SkPath::kLine_SegmentMask;
639 pCnt = 1;
640 break;
641 case SkPath::kQuad_Verb:
642 mask = SkPath::kQuad_SegmentMask;
643 pCnt = 2;
644 break;
645 case SkPath::kConic_Verb:
646 mask = SkPath::kConic_SegmentMask;
647 pCnt = 2;
648 break;
649 case SkPath::kCubic_Verb:
650 mask = SkPath::kCubic_SegmentMask;
651 pCnt = 3;
652 break;
653 case SkPath::kClose_Verb:
654 pCnt = 0;
655 break;
656 case SkPath::kDone_Verb:
657 SkDEBUGFAIL("growForVerb called for kDone");
658 // fall through
659 default:
660 SkDEBUGFAIL("default is not reached");
661 pCnt = 0;
662 }
663 SkSafeMath safe;
664 int newPointCnt = safe.addInt(fPointCnt, pCnt);
665 int newVerbCnt = safe.addInt(fVerbCnt, 1);
666 if (!safe) {
667 SK_ABORT("cannot grow path");
668 }
669 size_t space = sizeof(uint8_t) + pCnt * sizeof (SkPoint);
670 this->makeSpace(space);
671 this->fVerbs[~fVerbCnt] = verb;
672 SkPoint* ret = fPoints + fPointCnt;
673 fVerbCnt = newVerbCnt;
674 fPointCnt = newPointCnt;
675 fSegmentMask |= mask;
676 fFreeSpace -= space;
677 fBoundsIsDirty = true; // this also invalidates fIsFinite
678 fIsOval = false;
679 fIsRRect = false;
680
681 if (SkPath::kConic_Verb == verb) {
682 *fConicWeights.append() = weight;
683 }
684
685 SkDEBUGCODE(this->validate();)
686 return ret;
687 }
688
genID() const689 uint32_t SkPathRef::genID() const {
690 SkASSERT(fEditorsAttached.load() == 0);
691 static const uint32_t kMask = (static_cast<int64_t>(1) << SkPathPriv::kPathRefGenIDBitCnt) - 1;
692
693 if (fGenerationID == 0) {
694 if (fPointCnt == 0 && fVerbCnt == 0) {
695 fGenerationID = kEmptyGenID;
696 } else {
697 static std::atomic<uint32_t> nextID{kEmptyGenID + 1};
698 do {
699 fGenerationID = nextID.fetch_add(1, std::memory_order_relaxed) & kMask;
700 } while (fGenerationID == 0 || fGenerationID == kEmptyGenID);
701 }
702 }
703 return fGenerationID;
704 }
705
addGenIDChangeListener(sk_sp<GenIDChangeListener> listener)706 void SkPathRef::addGenIDChangeListener(sk_sp<GenIDChangeListener> listener) {
707 if (nullptr == listener || this == gEmpty) {
708 return;
709 }
710
711 SkAutoMutexAcquire lock(fGenIDChangeListenersMutex);
712
713 // Clean out any stale listeners before we append the new one.
714 for (int i = 0; i < fGenIDChangeListeners.count(); ++i) {
715 if (fGenIDChangeListeners[i]->shouldUnregisterFromPath()) {
716 fGenIDChangeListeners[i]->unref();
717 fGenIDChangeListeners.removeShuffle(i--); // No need to preserve the order after i.
718 }
719 }
720
721 SkASSERT(!listener->shouldUnregisterFromPath());
722 *fGenIDChangeListeners.append() = listener.release();
723 }
724
725 // we need to be called *before* the genID gets changed or zerod
callGenIDChangeListeners()726 void SkPathRef::callGenIDChangeListeners() {
727 SkAutoMutexAcquire lock(fGenIDChangeListenersMutex);
728 for (GenIDChangeListener* listener : fGenIDChangeListeners) {
729 if (!listener->shouldUnregisterFromPath()) {
730 listener->onChange();
731 }
732 // Listeners get at most one shot, so whether these triggered or not, blow them away.
733 listener->unref();
734 }
735
736 fGenIDChangeListeners.reset();
737 }
738
getRRect() const739 SkRRect SkPathRef::getRRect() const {
740 const SkRect& bounds = this->getBounds();
741 SkVector radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
742 Iter iter(*this);
743 SkPoint pts[4];
744 uint8_t verb = iter.next(pts);
745 SkASSERT(SkPath::kMove_Verb == verb);
746 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
747 if (SkPath::kConic_Verb == verb) {
748 SkVector v1_0 = pts[1] - pts[0];
749 SkVector v2_1 = pts[2] - pts[1];
750 SkVector dxdy;
751 if (v1_0.fX) {
752 SkASSERT(!v2_1.fX && !v1_0.fY);
753 dxdy.set(SkScalarAbs(v1_0.fX), SkScalarAbs(v2_1.fY));
754 } else if (!v1_0.fY) {
755 SkASSERT(!v2_1.fX || !v2_1.fY);
756 dxdy.set(SkScalarAbs(v2_1.fX), SkScalarAbs(v2_1.fY));
757 } else {
758 SkASSERT(!v2_1.fY);
759 dxdy.set(SkScalarAbs(v2_1.fX), SkScalarAbs(v1_0.fY));
760 }
761 SkRRect::Corner corner =
762 pts[1].fX == bounds.fLeft ?
763 pts[1].fY == bounds.fTop ?
764 SkRRect::kUpperLeft_Corner : SkRRect::kLowerLeft_Corner :
765 pts[1].fY == bounds.fTop ?
766 SkRRect::kUpperRight_Corner : SkRRect::kLowerRight_Corner;
767 SkASSERT(!radii[corner].fX && !radii[corner].fY);
768 radii[corner] = dxdy;
769 } else {
770 SkASSERT((verb == SkPath::kLine_Verb
771 && (!(pts[1].fX - pts[0].fX) || !(pts[1].fY - pts[0].fY)))
772 || verb == SkPath::kClose_Verb);
773 }
774 }
775 SkRRect rrect;
776 rrect.setRectRadii(bounds, radii);
777 return rrect;
778 }
779
780 ///////////////////////////////////////////////////////////////////////////////
781
Iter()782 SkPathRef::Iter::Iter() {
783 #ifdef SK_DEBUG
784 fPts = nullptr;
785 fConicWeights = nullptr;
786 #endif
787 // need to init enough to make next() harmlessly return kDone_Verb
788 fVerbs = nullptr;
789 fVerbStop = nullptr;
790 }
791
Iter(const SkPathRef & path)792 SkPathRef::Iter::Iter(const SkPathRef& path) {
793 this->setPathRef(path);
794 }
795
setPathRef(const SkPathRef & path)796 void SkPathRef::Iter::setPathRef(const SkPathRef& path) {
797 fPts = path.points();
798 fVerbs = path.verbs();
799 fVerbStop = path.verbsMemBegin();
800 fConicWeights = path.conicWeights();
801 if (fConicWeights) {
802 fConicWeights -= 1; // begin one behind
803 }
804
805 // Don't allow iteration through non-finite points.
806 if (!path.isFinite()) {
807 fVerbStop = fVerbs;
808 }
809 }
810
next(SkPoint pts[4])811 uint8_t SkPathRef::Iter::next(SkPoint pts[4]) {
812 SkASSERT(pts);
813 if (fVerbs == fVerbStop) {
814 return (uint8_t) SkPath::kDone_Verb;
815 }
816
817 // fVerbs points one beyond next verb so decrement first.
818 unsigned verb = *(--fVerbs);
819 const SkPoint* srcPts = fPts;
820
821 switch (verb) {
822 case SkPath::kMove_Verb:
823 pts[0] = srcPts[0];
824 srcPts += 1;
825 break;
826 case SkPath::kLine_Verb:
827 pts[0] = srcPts[-1];
828 pts[1] = srcPts[0];
829 srcPts += 1;
830 break;
831 case SkPath::kConic_Verb:
832 fConicWeights += 1;
833 // fall-through
834 case SkPath::kQuad_Verb:
835 pts[0] = srcPts[-1];
836 pts[1] = srcPts[0];
837 pts[2] = srcPts[1];
838 srcPts += 2;
839 break;
840 case SkPath::kCubic_Verb:
841 pts[0] = srcPts[-1];
842 pts[1] = srcPts[0];
843 pts[2] = srcPts[1];
844 pts[3] = srcPts[2];
845 srcPts += 3;
846 break;
847 case SkPath::kClose_Verb:
848 break;
849 case SkPath::kDone_Verb:
850 SkASSERT(fVerbs == fVerbStop);
851 break;
852 }
853 fPts = srcPts;
854 return (uint8_t) verb;
855 }
856
peek() const857 uint8_t SkPathRef::Iter::peek() const {
858 const uint8_t* next = fVerbs - 1;
859 return next <= fVerbStop ? (uint8_t) SkPath::kDone_Verb : *next;
860 }
861
862
isValid() const863 bool SkPathRef::isValid() const {
864 if (static_cast<ptrdiff_t>(fFreeSpace) < 0) {
865 return false;
866 }
867 if (reinterpret_cast<intptr_t>(fVerbs) - reinterpret_cast<intptr_t>(fPoints) < 0) {
868 return false;
869 }
870 if ((nullptr == fPoints) != (nullptr == fVerbs)) {
871 return false;
872 }
873 if (nullptr == fPoints && 0 != fFreeSpace) {
874 return false;
875 }
876 if (nullptr == fPoints && fPointCnt) {
877 return false;
878 }
879 if (nullptr == fVerbs && fVerbCnt) {
880 return false;
881 }
882 if (this->currSize() !=
883 fFreeSpace + sizeof(SkPoint) * fPointCnt + sizeof(uint8_t) * fVerbCnt) {
884 return false;
885 }
886
887 if (fIsOval || fIsRRect) {
888 // Currently we don't allow both of these to be set, even though ovals are ro
889 if (fIsOval == fIsRRect) {
890 return false;
891 }
892 if (fIsOval) {
893 if (fRRectOrOvalStartIdx >= 4) {
894 return false;
895 }
896 } else {
897 if (fRRectOrOvalStartIdx >= 8) {
898 return false;
899 }
900 }
901 }
902
903 if (!fBoundsIsDirty && !fBounds.isEmpty()) {
904 bool isFinite = true;
905 Sk2s leftTop = Sk2s(fBounds.fLeft, fBounds.fTop);
906 Sk2s rightBot = Sk2s(fBounds.fRight, fBounds.fBottom);
907 for (int i = 0; i < fPointCnt; ++i) {
908 Sk2s point = Sk2s(fPoints[i].fX, fPoints[i].fY);
909 #ifdef SK_DEBUG
910 if (fPoints[i].isFinite() &&
911 ((point < leftTop).anyTrue() || (point > rightBot).anyTrue())) {
912 SkDebugf("bad SkPathRef bounds: %g %g %g %g\n",
913 fBounds.fLeft, fBounds.fTop, fBounds.fRight, fBounds.fBottom);
914 for (int j = 0; j < fPointCnt; ++j) {
915 if (i == j) {
916 SkDebugf("*** bounds do not contain: ");
917 }
918 SkDebugf("%g %g\n", fPoints[j].fX, fPoints[j].fY);
919 }
920 return false;
921 }
922 #endif
923
924 if (fPoints[i].isFinite() && (point < leftTop).anyTrue() && !(point > rightBot).anyTrue())
925 return false;
926 if (!fPoints[i].isFinite()) {
927 isFinite = false;
928 }
929 }
930 if (SkToBool(fIsFinite) != isFinite) {
931 return false;
932 }
933 }
934 return true;
935 }
936