Debian Codegraph @

src/core/SkPath.cpp

raw
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 #include "include/core/SkPath.h"
9 #include "include/core/SkPathBuilder.h"
10 #include "include/core/SkPathTypes.h"
11 #include "include/core/SkRRect.h"
12 #include "include/core/SkSpan.h"
13 #include "include/private/base/SkMalloc.h"
14 #include "include/private/base/SkTArray.h"
15 #include "include/private/base/SkTo.h"
16 #include "src/base/SkFloatBits.h"
17 #include "src/core/SkEdgeClipper.h"
18 #include "src/core/SkGeometry.h"
19 #include "src/core/SkPathEnums.h"
20 #include "src/core/SkPathPriv.h"
21 #include "src/core/SkPathRawShapes.h"
22 #include "src/core/SkPointPriv.h"
23 #include "src/core/SkSpanPriv.h"
24
25 #include <algorithm>
26 #include <cmath>
27 #include <cstring>
28 #include <limits.h>
29 #include <utility>
30
31 SkPath::SkPath(sk_sp<SkPathData> pd, SkPathFillType ft, bool isVolatile)
32 : fPathData(std::move(pd))
33 , fFillType(ft)
34 , fIsVolatile(isVolatile)
35 {
36 SkASSERT(fPathData);
37 }
38
39 SkPath::SkPath(SkPathFillType ft)
40 : fPathData(SkPathData::Empty())
41 , fFillType(ft)
42 , fIsVolatile(false)
43 {}
44
45 SkPath::SkPath(const SkPath&) = default;
46 SkPath& SkPath::operator=(const SkPath&) = default;
47 SkPath::SkPath(SkPath&&) = default;
48 SkPath& SkPath::operator=(SkPath&&) = default;
49
50 SkPath::~SkPath() {
51 SkDEBUGCODE(this->validate();)
52 }
53
54 void SkPath::setConvexity(SkPathConvexity c) const {
55 fPathData->setConvexity(c);
56 }
57
58 SkPathConvexity SkPath::getConvexityOrUnknown() const {
59 return fPathData->getConvexityOrUnknown();
60 }
61
62 bool operator==(const SkPath& a, const SkPath& b) {
63 return &a == &b ||
64 (a.fFillType == b.fFillType && *a.fPathData == *b.fPathData);
65 }
66
67 void SkPath::swap(SkPath& that) {
68 if (this != &that) {
69 fPathData.swap(that.fPathData);
70 std::swap(fFillType, that.fFillType);
71 std::swap(fIsVolatile, that.fIsVolatile);
72 }
73 }
74
75 SkPath& SkPath::reset() {
76 *this = SkPath();
77 return *this;
78 }
79
80 const SkRect& SkPath::getBounds() const {
81 return fPathData->bounds();
82 }
83
84 uint32_t SkPath::getSegmentMasks() const {
85 return fPathData->segmentMask();
86 }
87
88 bool SkPath::isFinite() const {
89 return fPathData.get() != PeekErrorSingleton();
90 }
91
92 bool SkPath::isValid() const { return this->isFinite(); }
93
94 uint32_t SkPath::getGenerationID() const { return fPathData->uniqueID(); }
95
96 #ifdef SK_DEBUG
97 void SkPath::validate() const {}
98 #endif
99
100 std::optional<SkPathOvalInfo> SkPath::getOvalInfo() const { return fPathData->asOval(); }
101 std::optional<SkPathRRectInfo> SkPath::getRRectInfo() const { return fPathData->asRRect(); }
102
103 SkSpan<const SkPoint> SkPath::points() const { return fPathData->points(); }
104 SkSpan<const SkPathVerb> SkPath::verbs() const { return fPathData->verbs(); }
105 SkSpan<const float> SkPath::conicWeights() const { return fPathData->conics(); }
106
107 SkPath SkPath::Raw(SkSpan<const SkPoint> pts, SkSpan<const SkPathVerb> vbs,
108 SkSpan<const float> ws, SkPathFillType ft, bool isVolatile) {
109 return MakeNullCheck(SkPathData::Make(pts, vbs, ws), ft, isVolatile);
110 }
111
112 SkPath SkPath::Rect(const SkRect& r, SkPathFillType ft, SkPathDirection dir, unsigned startIndex) {
113 startIndex &= 3; // keep it legal
114 return MakeNullCheck(SkPathData::Rect(r, dir, startIndex), ft, false);
115 }
116
117 SkPath SkPath::Oval(const SkRect& r, SkPathDirection dir, unsigned startIndex) {
118 startIndex &= 3; // keep it legal
119 return MakeNullCheck(SkPathData::Oval(r, dir, startIndex), SkPathFillType::kDefault, false);
120 }
121
122 SkPath SkPath::RRect(const SkRRect& rr, SkPathDirection dir, unsigned startIndex) {
123 startIndex &= 7; // keep it legal
124 // To be backwards compatible with the old impl for building a rrect path, we
125 // first check to see if the rrect itself can be simplified...
126 const SkRect& bounds = rr.getBounds();
127 auto [asType, newIndex] = SkPathPriv::SimplifyRRect(rr, startIndex);
128 switch (asType) {
129 case SkPathPriv::RRectAsEnum::kRect:
130 return SkPath::Rect(bounds, SkPathFillType::kDefault, dir, newIndex);
131
132 case SkPathPriv::RRectAsEnum::kOval:
133 return SkPath::Oval(bounds, dir, newIndex);
134
135 case SkPathPriv::RRectAsEnum::kRRect:
136 // fall through
137 break;
138 }
139 return MakeNullCheck(SkPathData::RRect(rr, dir, newIndex), SkPathFillType::kDefault, false);
140 }
141
142 SkPath SkPath::Polygon(SkSpan<const SkPoint> pts, bool isClosed,
143 SkPathFillType ft, bool isVolatile) {
144 return MakeNullCheck(SkPathData::Polygon(pts, isClosed), ft, isVolatile);
145 }
146
147 std::optional<SkPath> SkPath::tryMakeTransform(const SkMatrix& matrix) const {
148 if (auto pdata = fPathData->makeTransform(matrix)) {
149 return SkPath(std::move(pdata), fFillType, fIsVolatile);
150 }
151 return {};
152 }
153
154 SkPath SkPath::makeTransform(const SkMatrix& matrix) const {
155 if (!this->isFinite()) {
156 return *this;
157 }
158 if (auto newpath = this->tryMakeTransform(matrix)) {
159 return *newpath;
160 }
161 return SkPath(sk_ref_sp(PeekErrorSingleton()), fFillType, false);
162 }
163
164 std::optional<SkPathRaw> SkPath::raw(SkResolveConvexity rc) const {
165 return fPathData->raw(fFillType, rc);
166 }
167
168 static inline bool check_edge_against_rect(const SkPoint& p0,
169 const SkPoint& p1,
170 const SkRect& rect,
171 SkPathDirection dir) {
172 const SkPoint* edgeBegin;
173 SkVector v;
174 if (SkPathDirection::kCW == dir) {
175 v = p1 - p0;
176 edgeBegin = &p0;
177 } else {
178 v = p0 - p1;
179 edgeBegin = &p1;
180 }
181 if (v.fX || v.fY) {
182 // check the cross product of v with the vec from edgeBegin to each rect corner
183 SkScalar yL = v.fY * (rect.fLeft - edgeBegin->fX);
184 SkScalar xT = v.fX * (rect.fTop - edgeBegin->fY);
185 SkScalar yR = v.fY * (rect.fRight - edgeBegin->fX);
186 SkScalar xB = v.fX * (rect.fBottom - edgeBegin->fY);
187 if ((xT < yL) || (xT < yR) || (xB < yL) || (xB < yR)) {
188 return false;
189 }
190 }
191 return true;
192 }
193
194 bool SkPath::conservativelyContainsRect(const SkRect& rect) const {
195 const SkPathConvexity convexity = this->getConvexity();
196 if (!SkPathConvexity_IsConvex(convexity)) {
197 return false;
198 }
199
200 const auto direction = SkPathConvexity_ToDirection(convexity);
201 if (!direction) {
202 return false;
203 }
204
205 SkPoint firstPt;
206 SkPoint prevPt;
207 int segmentCount = 0;
208 SkDEBUGCODE(int moveCnt = 0;)
209
210 for (auto [verb, pts, weight] : SkPathPriv::Iterate(*this)) {
211 if (verb == SkPathVerb::kClose || (segmentCount > 0 && verb == SkPathVerb::kMove)) {
212 // Closing the current contour; but since convexity is a precondition, it's the only
213 // contour that matters.
214 SkASSERT(moveCnt);
215 segmentCount++;
216 break;
217 } else if (verb == SkPathVerb::kMove) {
218 // A move at the start of the contour (or multiple leading moves, in which case we
219 // keep the last one before a non-move verb).
220 SkASSERT(!segmentCount);
221 SkDEBUGCODE(++moveCnt);
222 firstPt = prevPt = pts[0];
223 } else {
224 int pointCount = SkPathPriv::PtsInVerb((unsigned) verb);
225 SkASSERT(pointCount > 0);
226
227 if (!SkPathPriv::AllPointsEq({pts, (size_t)pointCount + 1})) {
228 SkASSERT(moveCnt);
229 int nextPt = pointCount;
230 segmentCount++;
231
232 if (prevPt == pts[nextPt]) {
233 // A pre-condition to getting here is that the path is convex, so if a
234 // verb's start and end points are the same, it means it's the only
235 // verb in the contour (and the only contour). While it's possible for
236 // such a single verb to be a convex curve, we do not have any non-zero
237 // length edges to conservatively test against without splitting or
238 // evaluating the curve. For simplicity, just reject the rectangle.
239 return false;
240 } else if (SkPathVerb::kConic == verb) {
241 SkConic orig;
242 orig.set(pts, *weight);
243 SkPoint quadPts[5];
244 int count = orig.chopIntoQuadsPOW2(quadPts, 1);
245 SkASSERT_RELEASE(2 == count);
246
247 if (!check_edge_against_rect(quadPts[0], quadPts[2], rect, *direction)) {
248 return false;
249 }
250 if (!check_edge_against_rect(quadPts[2], quadPts[4], rect, *direction)) {
251 return false;
252 }
253 } else {
254 if (!check_edge_against_rect(prevPt, pts[nextPt], rect, *direction)) {
255 return false;
256 }
257 }
258 prevPt = pts[nextPt];
259 }
260 }
261 }
262
263 if (segmentCount) {
264 return check_edge_against_rect(prevPt, firstPt, rect, *direction);
265 }
266 return false;
267 }
268
269 bool SkPath::isLastContourClosed() const {
270 SkSpan<const SkPathVerb> verbs = this->verbs();
271 return !verbs.empty() && verbs.back() == SkPathVerb::kClose;
272 }
273
274 bool SkPath::isLine(SkPoint line[2]) const {
275 SkSpan<const SkPathVerb> verbs = this->verbs();
276 if (verbs.size() == 2 && verbs[1] == SkPathVerb::kLine) {
277 SkASSERT(verbs[0] == SkPathVerb::kMove);
278 SkSpan<const SkPoint> pts = this->points();
279 SkASSERT(pts.size() == 2);
280 if (line) {
281 line[0] = pts[0];
282 line[1] = pts[1];
283 }
284 return true;
285 }
286 return false;
287 }
288
289 bool SkPath::isEmpty() const {
290 SkDEBUGCODE(this->validate();)
291 return this->verbs().empty();
292 }
293
294 bool SkPath::isConvex() const {
295 return SkPathConvexity_IsConvex(this->getConvexity());
296 }
297
298 bool SkPath::isRect(SkRect* rect, bool* isClosed, SkPathDirection* direction) const {
299 SkDEBUGCODE(this->validate();)
300 SkSpan<const SkPoint> pts = this->points();
301 SkSpan<const SkPathVerb> vbs = this->verbs();
302 if (auto rc = SkPathPriv::IsRectContour(pts, vbs, this->getSegmentMasks(), false)) {
303 if (rect) {
304 *rect = rc->fRect;
305 }
306 if (isClosed) {
307 *isClosed = rc->fIsClosed;
308 }
309 if (direction) {
310 *direction = rc->fDirection;
311 }
312 return true;
313 }
314 return false;
315 }
316
317 bool SkPath::isOval(SkRect* bounds) const {
318 if (auto info = this->getOvalInfo()) {
319 if (bounds) {
320 *bounds = info->fBounds;
321 }
322 return true;
323 }
324 return false;
325 }
326
327 bool SkPath::isRRect(SkRRect* rrect) const {
328 if (auto info = this->getRRectInfo()) {
329 if (rrect) {
330 *rrect = info->fRRect;
331 }
332 return true;
333 }
334 return false;
335 }
336
337 #ifdef SK_LEGACY_PATH_ACCESSORS
338 size_t SkPath::getPoints(SkSpan<SkPoint> dst) const {
339 SkDEBUGCODE(this->validate();)
340 SkSpan<const SkPoint> src = this->points();
341
342 const size_t n = std::min(dst.size(), src.size());
343 sk_careful_memcpy(dst.data(), src.data(), n * sizeof(SkPoint));
344 return src.size();
345 }
346
347 SkPoint SkPath::getPoint(int index) const {
348 SkSpan<const SkPoint> pts = this->points();
349 if ((unsigned)index < (unsigned)pts.size()) {
350 return pts[index];
351 }
352 return SkPoint::Make(0, 0);
353 }
354
355 size_t SkPath::getVerbs(SkSpan<uint8_t> dst) const {
356 SkDEBUGCODE(this->validate();)
357 SkSpan<const SkPathVerb> src = this->verbs();
358
359 const size_t n = std::min(dst.size(), src.size());
360 sk_careful_memcpy(dst.data(), src.data(), n);
361 return src.size();
362 }
363 #endif
364
365 size_t SkPath::approximateBytesUsed() const {
366 return sizeof(SkPath)
367 + this->points().size_bytes()
368 + this->verbs().size_bytes()
369 + this->conicWeights().size_bytes();
370 }
371
372 std::optional<SkPoint> SkPath::getLastPt() const {
373 SkDEBUGCODE(this->validate();)
374 SkSpan<const SkPoint> pts = this->points();
375 if (!pts.empty()) {
376 return pts.back();
377 }
378 return {};
379 }
380
381 SkPathConvexity SkPath::getConvexity() const {
382 // Enable once we fix all the bugs
383 // SkDEBUGCODE(this->isConvexityAccurate());
384 SkPathConvexity convexity = this->getConvexityOrUnknown();
385 if (convexity == SkPathConvexity::kUnknown) {
386 convexity = this->computeConvexity();
387 }
388 SkASSERT(convexity != SkPathConvexity::kUnknown);
389 return convexity;
390 }
391
392 SkPathIter SkPath::iter() const {
393 return { this->points(), this->verbs(), this->conicWeights() };
394 }
395
396 ///////////////////////////////////////////////////////////////////////////////
397
398 SkPath::Iter::Iter() {
399 #ifdef SK_DEBUG
400 fPts = nullptr;
401 fConicWeights = nullptr;
402 fMoveTo.fX = fMoveTo.fY = fLastPt.fX = fLastPt.fY = 0;
403 fForceClose = fCloseLine = false;
404 #endif
405 // need to init enough to make next() harmlessly return kDone_Verb
406 fVerbs = nullptr;
407 fVerbStop = nullptr;
408 fNeedClose = false;
409 }
410
411 SkPath::Iter::Iter(const SkPath& path, bool forceClose) {
412 this->setPath(path, forceClose);
413 }
414
415 void SkPath::Iter::setPath(const SkPath& path, bool forceClose) {
416 fPts = path.points().data();
417 fVerbs = path.verbs().data();
418 fVerbStop = fVerbs + path.verbs().size();
419 fConicWeights = path.conicWeights().data();
420 if (fConicWeights) {
421 fConicWeights -= 1; // begin one behind
422 }
423 fLastPt.fX = fLastPt.fY = 0;
424 fMoveTo.fX = fMoveTo.fY = 0;
425 fForceClose = SkToU8(forceClose);
426 fNeedClose = false;
427 }
428
429 bool SkPath::Iter::isClosedContour() const {
430 if (fVerbs == nullptr || fVerbs == fVerbStop) {
431 return false;
432 }
433 if (fForceClose) {
434 return true;
435 }
436
437 const SkPathVerb* verbs = fVerbs;
438 const SkPathVerb* stop = fVerbStop;
439
440 if (SkPathVerb::kMove == *verbs) {
441 verbs += 1; // skip the initial moveto
442 }
443
444 while (verbs < stop) {
445 // verbs points one beyond the current verb, decrement first.
446 SkPathVerb v = *verbs++;
447 if (SkPathVerb::kMove == v) {
448 break;
449 }
450 if (SkPathVerb::kClose == v) {
451 return true;
452 }
453 }
454 return false;
455 }
456
457 SkPathVerb SkPath::Iter::autoClose(SkPoint pts[2]) {
458 SkASSERT(pts);
459 if (fLastPt != fMoveTo) {
460 // A special case: if both points are NaN, SkPoint::operation== returns
461 // false, but the iterator expects that they are treated as the same.
462 // (consider SkPoint is a 2-dimension float point).
463 if (SkIsNaN(fLastPt.fX) || SkIsNaN(fLastPt.fY) ||
464 SkIsNaN(fMoveTo.fX) || SkIsNaN(fMoveTo.fY)) {
465 return SkPathVerb::kClose;
466 }
467
468 pts[0] = fLastPt;
469 pts[1] = fMoveTo;
470 fLastPt = fMoveTo;
471 fCloseLine = true;
472 return SkPathVerb::kLine;
473 }
474 pts[0] = fMoveTo;
475 return SkPathVerb::kClose;
476 }
477
478 SkPath::Verb SkPath::Iter::next(SkPoint ptsParam[4]) {
479 SkASSERT(ptsParam);
480
481 if (fVerbs == fVerbStop) {
482 // Close the curve if requested and if there is some curve to close
483 if (fNeedClose) {
484 if (SkPathVerb::kLine == this->autoClose(ptsParam)) {
485 return kLine_Verb;
486 }
487 fNeedClose = false;
488 return kClose_Verb;
489 }
490 return kDone_Verb;
491 }
492
493 SkPathVerb verb = *fVerbs++;
494 const SkPoint* SK_RESTRICT srcPts = fPts;
495 SkPoint* SK_RESTRICT pts = ptsParam;
496
497 switch (verb) {
498 case SkPathVerb::kMove:
499 if (fNeedClose) {
500 fVerbs--; // move back one verb
501 verb = this->autoClose(pts);
502 if (verb == SkPathVerb::kClose) {
503 fNeedClose = false;
504 }
505 return (Verb)verb;
506 }
507 if (fVerbs == fVerbStop) { // might be a trailing moveto
508 return kDone_Verb;
509 }
510 fMoveTo = *srcPts;
511 pts[0] = *srcPts;
512 srcPts += 1;
513 fLastPt = fMoveTo;
514 fNeedClose = fForceClose;
515 break;
516 case SkPathVerb::kLine:
517 pts[0] = fLastPt;
518 pts[1] = srcPts[0];
519 fLastPt = srcPts[0];
520 fCloseLine = false;
521 srcPts += 1;
522 break;
523 case SkPathVerb::kConic:
524 fConicWeights += 1;
525 [[fallthrough]];
526 case SkPathVerb::kQuad:
527 pts[0] = fLastPt;
528 memcpy(&pts[1], srcPts, 2 * sizeof(SkPoint));
529 fLastPt = srcPts[1];
530 srcPts += 2;
531 break;
532 case SkPathVerb::kCubic:
533 pts[0] = fLastPt;
534 memcpy(&pts[1], srcPts, 3 * sizeof(SkPoint));
535 fLastPt = srcPts[2];
536 srcPts += 3;
537 break;
538 case SkPathVerb::kClose:
539 verb = this->autoClose(pts);
540 if (verb == SkPathVerb::kLine) {
541 fVerbs--; // move back one verb
542 } else {
543 fNeedClose = false;
544 }
545 fLastPt = fMoveTo;
546 break;
547 }
548 fPts = srcPts;
549 return (Verb)verb;
550 }
551
552 static inline uint8_t SkPathIterPointsPerVerb(SkPathVerb verb) {
553 static const uint8_t gCounts[] = { 1, 2, 3, 3, 4, 0 };
554 unsigned index = static_cast<unsigned>(verb);
555 SkASSERT(index < std::size(gCounts));
556 return gCounts[index];
557 }
558
559 std::optional<SkPath::IterRec> SkPath::Iter::next() {
560 auto legacyVerb = this->next(fStorage.data());
561 if (legacyVerb == kDone_Verb) {
562 return {};
563 }
564
565 SkPathVerb verb = static_cast<SkPathVerb>(legacyVerb);
566 return {{
567 verb,
568 {fStorage.data(), SkPathIterPointsPerVerb(verb)},
569 verb == SkPathVerb::kConic ? *fConicWeights : 1,
570 }};
571 }
572
573 void SkPath::RawIter::setPath(const SkPath& path) {
574 SkPathPriv::Iterate iterate(path);
575 fIter = iterate.begin();
576 fEnd = iterate.end();
577 }
578
579 SkPath::Verb SkPath::RawIter::next(SkPoint pts[4]) {
580 if (!(fIter != fEnd)) {
581 return kDone_Verb;
582 }
583 auto [verb, iterPts, weights] = *fIter;
584 int numPts;
585 switch (verb) {
586 case SkPathVerb::kMove: numPts = 1; break;
587 case SkPathVerb::kLine: numPts = 2; break;
588 case SkPathVerb::kQuad: numPts = 3; break;
589 case SkPathVerb::kConic:
590 numPts = 3;
591 fConicWeight = *weights;
592 break;
593 case SkPathVerb::kCubic: numPts = 4; break;
594 case SkPathVerb::kClose: numPts = 0; break;
595 }
596 memcpy(pts, iterPts, sizeof(SkPoint) * numPts);
597 ++fIter;
598 return (Verb) verb;
599 }
600
601 std::optional<SkPath::IterRec> SkPath::RawIter::next() {
602 if (fIter == fEnd) {
603 return {};
604 }
605
606 auto [verb, iterPts, weights] = *fIter++;
607 return {{
608 verb,
609 {iterPts, SkPathIterPointsPerVerb(verb)},
610 verb == SkPathVerb::kConic ? *weights : 1
611 }};
612 }
613
614 ///////////////////////////////////////////////////////////////////////////////
615
616 SkPath SkPath::makeFillType(SkPathFillType ft) const {
617 SkPath copy = *this;
618 copy.setFillType(ft);
619 return copy;
620 }
621
622 SkPath SkPath::makeToggleInverseFillType() const {
623 return this->makeFillType(SkPathFillType_ToggleInverse(fFillType));
624 }
625
626 SkPath SkPath::makeIsVolatile(bool v) const {
627 SkPath copy = *this;
628 copy.fIsVolatile = v;
629 return copy;
630 }
631
632 SkPathConvexity SkPath::computeConvexity() const {
633 if (auto c = this->getConvexityOrUnknown(); c != SkPathConvexity::kUnknown) {
634 return c;
635 }
636
637 SkPathConvexity convexity = SkPathConvexity::kConcave;
638
639 if (this->isFinite()) {
640 convexity = SkPathPriv::ComputeConvexity(this->points(),
641 this->verbs(),
642 this->conicWeights());
643 }
644
645 SkASSERT(convexity != SkPathConvexity::kUnknown);
646 this->setConvexity(convexity);
647 return convexity;
648 }
649
650 bool SkPath::contains(SkPoint p) const {
651 const auto raw = SkPathPriv::Raw(*this, SkResolveConvexity::kNo);
652 return raw.has_value() && SkPathPriv::Contains(*raw, p);
653 }
654
655 int SkPath::ConvertConicToQuads(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
656 SkScalar w, SkPoint pts[], int pow2) {
657 const SkConic conic(p0, p1, p2, w);
658 return conic.chopIntoQuadsPOW2(pts, pow2);
659 }
660
661 ///////////////////////////////////////////////////////////////////////////////////////////////////
662
663 SkRect SkPath::computeTightBounds() const {
664 // If we're only lines, then our (quick) bounds is also tight.
665 if (this->getSegmentMasks() == SkPath::kLine_SegmentMask) {
666 return this->getBounds();
667 }
668
669 return SkPathPriv::ComputeTightBounds(this->points(),
670 this->verbs(),
671 this->conicWeights());
672 }
673
674 bool SkPath::IsLineDegenerate(const SkPoint& p1, const SkPoint& p2, bool exact) {
675 return exact ? p1 == p2 : SkPointPriv::EqualsWithinTolerance(p1, p2);
676 }
677
678 bool SkPath::IsQuadDegenerate(const SkPoint& p1, const SkPoint& p2,
679 const SkPoint& p3, bool exact) {
680 return exact ? p1 == p2 && p2 == p3 : SkPointPriv::EqualsWithinTolerance(p1, p2) &&
681 SkPointPriv::EqualsWithinTolerance(p2, p3);
682 }
683
684 bool SkPath::IsCubicDegenerate(const SkPoint& p1, const SkPoint& p2,
685 const SkPoint& p3, const SkPoint& p4, bool exact) {
686 return exact ? p1 == p2 && p2 == p3 && p3 == p4 :
687 SkPointPriv::EqualsWithinTolerance(p1, p2) &&
688 SkPointPriv::EqualsWithinTolerance(p2, p3) &&
689 SkPointPriv::EqualsWithinTolerance(p3, p4);
690 }
691
692 SkPath SkPath::RRect(const SkRRect& rr, SkPathDirection dir) {
693 // legacy start indices: 6 (CW) and 7 (CCW)
694 return RRect(rr, dir, dir == SkPathDirection::kCW ? 6 : 7);
695 }
696
697 SkPath SkPath::Oval(const SkRect& r, SkPathDirection dir) {
698 // legacy start index: 1
699 return Oval(r, dir, 1);
700 }
701
702 SkPath SkPath::Circle(SkScalar x, SkScalar y, SkScalar r, SkPathDirection dir) {
703 if (r >= 0) {
704 return Oval(SkRect::MakeLTRB(x - r, y - r, x + r, y + r), dir);
705 } else {
706 return SkPath();
707 }
708 }
709
710 SkPath SkPath::RRect(const SkRect& r, SkScalar rx, SkScalar ry, SkPathDirection dir) {
711 return RRect(SkRRect::MakeRectXY(r, rx, ry), dir);
712 }
713
714 SkPathFirstDirection SkPathPriv::ComputeFirstDirection(const SkPath& path) {
715 auto convexity = path.getConvexityOrUnknown();
716 if (SkPathConvexity_IsConvex(convexity)) {
717 // Note, this can return kUnknown. That is valid. If we've determined that the
718 // path is convex, then we've already tried to compute its first-direction. If
719 // that failed, then kUnknown is the right answer.
720 return SkPathConvexity_ToFirstDirection(convexity);
721 }
722
723 // Note, this can compute a 'first' direction, even for non-convex shapes.
724 if (auto raw = SkPathPriv::Raw(path, SkResolveConvexity::kNo)) {
725 return ComputeFirstDirection(*raw);
726 } else {
727 return SkPathFirstDirection::kUnknown;
728 }
729 }
730
731 /*
732 * This returns a singleton instance which SkPath uses to signify that its pathdata is in error:
733 * either because the inputs were invalid (e.g. bad verbs), or its coordintes were non-finite
734 * (either from the client, or after a makeTransform() call).
735 */
736 SkPathData* SkPath::PeekErrorSingleton() {
737 static SkPathData* gErrorSingleton = SkPathData::MakeNoCheck({}, {}, {}, {}, {}).release();
738
739 // Make sure MakeNoCheck() didn't alias us to the standard Empty instance. We want our
740 // pointer to be distinct from that one.
741 SkASSERT(gErrorSingleton != SkPathData::Empty().get());
742
743 return gErrorSingleton;
744 }
745
746 SkPath SkPath::MakeNullCheck(sk_sp<SkPathData> pdata, SkPathFillType ft, bool isVolatile) {
747 if (!pdata) {
748 pdata = sk_ref_sp(PeekErrorSingleton());
749 }
750 return SkPath(std::move(pdata), ft, isVolatile);
751 }
752
753 ///////////////////////////////////////////////////////////////////////////////////////////////////
754
755 struct SkHalfPlane {
756 SkScalar fA, fB, fC;
757
758 SkScalar eval(SkScalar x, SkScalar y) const {
759 return fA * x + fB * y + fC;
760 }
761 SkScalar operator()(SkScalar x, SkScalar y) const { return this->eval(x, y); }
762
763 bool normalize() {
764 double a = fA;
765 double b = fB;
766 double c = fC;
767 double dmag = sqrt(a * a + b * b);
768 // length of initial plane normal is zero
769 if (dmag == 0) {
770 fA = fB = 0;
771 fC = SK_Scalar1;
772 return true;
773 }
774 double dscale = sk_ieee_double_divide(1.0, dmag);
775 a *= dscale;
776 b *= dscale;
777 c *= dscale;
778 // check if we're not finite, or normal is zero-length
779 if (!SkIsFinite(a, b, c) ||
780 (a == 0 && b == 0)) {
781 fA = fB = 0;
782 fC = SK_Scalar1;
783 return false;
784 }
785 fA = a;
786 fB = b;
787 fC = c;
788 return true;
789 }
790
791 enum Result {
792 kAllNegative,
793 kAllPositive,
794 kMixed
795 };
796 Result test(const SkRect& bounds) const {
797 // check whether the diagonal aligned with the normal crosses the plane
798 SkPoint diagMin, diagMax;
799 if (fA >= 0) {
800 diagMin.fX = bounds.fLeft;
801 diagMax.fX = bounds.fRight;
802 } else {
803 diagMin.fX = bounds.fRight;
804 diagMax.fX = bounds.fLeft;
805 }
806 if (fB >= 0) {
807 diagMin.fY = bounds.fTop;
808 diagMax.fY = bounds.fBottom;
809 } else {
810 diagMin.fY = bounds.fBottom;
811 diagMax.fY = bounds.fTop;
812 }
813 SkScalar test = this->eval(diagMin.fX, diagMin.fY);
814 SkScalar sign = test*this->eval(diagMax.fX, diagMax.fY);
815 if (sign > 0) {
816 // the path is either all on one side of the half-plane or the other
817 if (test < 0) {
818 return kAllNegative;
819 } else {
820 return kAllPositive;
821 }
822 }
823 return kMixed;
824 }
825 };
826
827 // assumes plane is pre-normalized
828 static std::optional<SkPath> clip(const SkPath& path, const SkHalfPlane& plane) {
829 SkMatrix mx;
830 SkPoint p0 = { -plane.fA*plane.fC, -plane.fB*plane.fC };
831 mx.setAll( plane.fB, plane.fA, p0.fX,
832 -plane.fA, plane.fB, p0.fY,
833 0, 0, 1);
834 auto inv = mx.invert();
835 if (!inv) {
836 return {};
837 }
838
839 auto rotated = path.tryMakeTransform(*inv);
840 if (!rotated) {
841 return {};
842 }
843 auto raw = SkPathPriv::Raw(*rotated, SkResolveConvexity::kNo);
844 if (!raw) {
845 SkASSERT(false); // if rotated was valid, so should the raw
846 return {};
847 }
848
849 SkScalar big = SK_ScalarMax;
850 SkRect clip = {-big, 0, big, big };
851
852 struct Rec {
853 SkPathBuilder fResult;
854 SkPoint fPrev = {0,0};
855 } rec;
856
857 SkEdgeClipper::ClipPath(*raw, clip, false,
858 [](SkEdgeClipper* clipper, bool newCtr, void* ctx) {
859 Rec* rec = (Rec*)ctx;
860
861 bool addLineTo = false;
862 SkPoint pts[4];
863 while (auto verb = clipper->next(pts)) {
864 if (newCtr) {
865 rec->fResult.moveTo(pts[0]);
866 rec->fPrev = pts[0];
867 newCtr = false;
868 }
869
870 if (addLineTo || pts[0] != rec->fPrev) {
871 rec->fResult.lineTo(pts[0]);
872 }
873
874 switch (*verb) {
875 case SkPathVerb::kLine:
876 rec->fResult.lineTo(pts[1]);
877 rec->fPrev = pts[1];
878 break;
879 case SkPathVerb::kQuad:
880 rec->fResult.quadTo(pts[1], pts[2]);
881 rec->fPrev = pts[2];
882 break;
883 case SkPathVerb::kCubic:
884 rec->fResult.cubicTo(pts[1], pts[2], pts[3]);
885 rec->fPrev = pts[3];
886 break;
887 default: break;
888 }
889 addLineTo = true;
890 }
891 }, &rec);
892
893 rec.fResult.setFillType(path.getFillType());
894 SkPath result = rec.fResult.detach(&mx);
895 if (!result.isFinite()) {
896 return {};
897 }
898 return result;
899 }
900
901 // true means we have written to clippedPath
902 bool SkPathPriv::PerspectiveClip(const SkPath& path, const SkMatrix& matrix, SkPath* clippedPath) {
903 if (!matrix.hasPerspective()) {
904 return false;
905 }
906
907 SkHalfPlane plane {
908 matrix[SkMatrix::kMPersp0],
909 matrix[SkMatrix::kMPersp1],
910 matrix[SkMatrix::kMPersp2] - kW0PlaneDistance
911 };
912 if (plane.normalize()) {
913 switch (plane.test(path.getBounds())) {
914 case SkHalfPlane::kAllPositive:
915 return false;
916 case SkHalfPlane::kMixed: {
917 if (auto result = clip(path, plane)) {
918 *clippedPath = *result;
919 } else {
920 *clippedPath = SkPath(); // clipped out (or failed)
921 }
922 return true;
923 }
924 default: break; // handled outside of the switch
925 }
926 }
927 // clipped out (or failed)
928 *clippedPath = SkPath();
929 return true;
930 }
931
932 std::optional<SkPathRectInfo> SkPathPriv::IsSimpleRect(const SkPath& path, bool isSimpleFill) {
933 if (path.getSegmentMasks() != SkPath::kLine_SegmentMask) {
934 return {};
935 }
936 SkPoint rectPts[5];
937 int rectPtCnt = 0;
938 bool needsClose = !isSimpleFill;
939 for (auto [v, verbPts, w] : SkPathPriv::Iterate(path)) {
940 switch (v) {
941 case SkPathVerb::kMove:
942 if (0 != rectPtCnt) {
943 return {};
944 }
945 rectPts[0] = verbPts[0];
946 ++rectPtCnt;
947 break;
948 case SkPathVerb::kLine:
949 if (5 == rectPtCnt) {
950 return {};
951 }
952 rectPts[rectPtCnt] = verbPts[1];
953 ++rectPtCnt;
954 break;
955 case SkPathVerb::kClose:
956 if (4 == rectPtCnt) {
957 rectPts[4] = rectPts[0];
958 rectPtCnt = 5;
959 }
960 needsClose = false;
961 break;
962 case SkPathVerb::kQuad:
963 case SkPathVerb::kConic:
964 case SkPathVerb::kCubic:
965 return {};
966 }
967 }
968 if (needsClose) {
969 return {};
970 }
971 if (rectPtCnt < 5) {
972 return {};
973 }
974 if (rectPts[0] != rectPts[4]) {
975 return {};
976 }
977 // Check for two cases of rectangles: pts 0 and 3 form a vertical edge or a horizontal edge (
978 // and pts 1 and 2 the opposite vertical or horizontal edge).
979 bool vec03IsVertical;
980 if (rectPts[0].fX == rectPts[3].fX && rectPts[1].fX == rectPts[2].fX &&
981 rectPts[0].fY == rectPts[1].fY && rectPts[3].fY == rectPts[2].fY) {
982 // Make sure it has non-zero width and height
983 if (rectPts[0].fX == rectPts[1].fX || rectPts[0].fY == rectPts[3].fY) {
984 return {};
985 }
986 vec03IsVertical = true;
987 } else if (rectPts[0].fY == rectPts[3].fY && rectPts[1].fY == rectPts[2].fY &&
988 rectPts[0].fX == rectPts[1].fX && rectPts[3].fX == rectPts[2].fX) {
989 // Make sure it has non-zero width and height
990 if (rectPts[0].fY == rectPts[1].fY || rectPts[0].fX == rectPts[3].fX) {
991 return {};
992 }
993 vec03IsVertical = false;
994 } else {
995 return {};
996 }
997
998 SkPathRectInfo info;
999
1000 // Set sortFlags so that it has the low bit set if pt index 0 is on right edge and second bit
1001 // set if it is on the bottom edge.
1002 unsigned sortFlags =
1003 ((rectPts[0].fX < rectPts[2].fX) ? 0b00 : 0b01) |
1004 ((rectPts[0].fY < rectPts[2].fY) ? 0b00 : 0b10);
1005 switch (sortFlags) {
1006 case 0b00:
1007 info.fRect.setLTRB(rectPts[0].fX, rectPts[0].fY, rectPts[2].fX, rectPts[2].fY);
1008 info.fDirection = vec03IsVertical ? SkPathDirection::kCW : SkPathDirection::kCCW;
1009 info.fStartIndex = 0;
1010 break;
1011 case 0b01:
1012 info.fRect.setLTRB(rectPts[2].fX, rectPts[0].fY, rectPts[0].fX, rectPts[2].fY);
1013 info.fDirection = vec03IsVertical ? SkPathDirection::kCCW : SkPathDirection::kCW;
1014 info.fStartIndex = 1;
1015 break;
1016 case 0b10:
1017 info.fRect.setLTRB(rectPts[0].fX, rectPts[2].fY, rectPts[2].fX, rectPts[0].fY);
1018 info.fDirection = vec03IsVertical ? SkPathDirection::kCCW : SkPathDirection::kCW;
1019 info.fStartIndex = 3;
1020 break;
1021 case 0b11:
1022 info.fRect.setLTRB(rectPts[2].fX, rectPts[2].fY, rectPts[0].fX, rectPts[0].fY);
1023 info.fDirection = vec03IsVertical ? SkPathDirection::kCW : SkPathDirection::kCCW;
1024 info.fStartIndex = 2;
1025 break;
1026 }
1027 return info;
1028 }
1029
1030 //////////////////////////////////////////////////////////////////////////////////////////////////
1031
1032 SkPathEdgeIter::SkPathEdgeIter(const SkPathRaw& raw) {
1033 fMoveToPtr = fPts = raw.fPoints.data();
1034 fVerbs = raw.fVerbs.data();
1035 fVerbsStop = fVerbs + raw.fVerbs.size();
1036 fConicWeights = raw.fConics.data();
1037 if (fConicWeights) {
1038 fConicWeights -= 1; // begin one behind
1039 }
1040
1041 fNeedsCloseLine = false;
1042 fNextIsNewContour = false;
1043 SkDEBUGCODE(fIsConic = false;)
1044 }
1045
1046 SkPathEdgeIter::SkPathEdgeIter(const SkPath& path)
1047 : SkPathEdgeIter(SkPathPriv::Raw(path, SkResolveConvexity::kNo).value_or(SkPathRaw::Empty()))
1048 {}