• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 "src/utils/SkPolyUtils.h"
9 
10 #include <limits>
11 
12 #include "include/private/SkNx.h"
13 #include "include/private/SkTArray.h"
14 #include "include/private/SkTemplates.h"
15 #include "src/core/SkPointPriv.h"
16 #include "src/core/SkRectPriv.h"
17 #include "src/core/SkTDPQueue.h"
18 #include "src/core/SkTInternalLList.h"
19 
20 //////////////////////////////////////////////////////////////////////////////////
21 // Helper data structures and functions
22 
23 struct OffsetSegment {
24     SkPoint fP0;
25     SkVector fV;
26 };
27 
28 constexpr SkScalar kCrossTolerance = SK_ScalarNearlyZero * SK_ScalarNearlyZero;
29 
30 // Computes perpDot for point p compared to segment defined by origin p0 and vector v.
31 // A positive value means the point is to the left of the segment,
32 // negative is to the right, 0 is collinear.
compute_side(const SkPoint & p0,const SkVector & v,const SkPoint & p)33 static int compute_side(const SkPoint& p0, const SkVector& v, const SkPoint& p) {
34     SkVector w = p - p0;
35     SkScalar perpDot = v.cross(w);
36     if (!SkScalarNearlyZero(perpDot, kCrossTolerance)) {
37         return ((perpDot > 0) ? 1 : -1);
38     }
39 
40     return 0;
41 }
42 
43 // Returns 1 for cw, -1 for ccw and 0 if zero signed area (either degenerate or self-intersecting)
SkGetPolygonWinding(const SkPoint * polygonVerts,int polygonSize)44 int SkGetPolygonWinding(const SkPoint* polygonVerts, int polygonSize) {
45     if (polygonSize < 3) {
46         return 0;
47     }
48 
49     // compute area and use sign to determine winding
50     SkScalar quadArea = 0;
51     SkVector v0 = polygonVerts[1] - polygonVerts[0];
52     for (int curr = 2; curr < polygonSize; ++curr) {
53         SkVector v1 = polygonVerts[curr] - polygonVerts[0];
54         quadArea += v0.cross(v1);
55         v0 = v1;
56     }
57     if (SkScalarNearlyZero(quadArea, kCrossTolerance)) {
58         return 0;
59     }
60     // 1 == ccw, -1 == cw
61     return (quadArea > 0) ? 1 : -1;
62 }
63 
64 // Compute difference vector to offset p0-p1 'offset' units in direction specified by 'side'
compute_offset_vector(const SkPoint & p0,const SkPoint & p1,SkScalar offset,int side,SkPoint * vector)65 bool compute_offset_vector(const SkPoint& p0, const SkPoint& p1, SkScalar offset, int side,
66                            SkPoint* vector) {
67     SkASSERT(side == -1 || side == 1);
68     // if distances are equal, can just outset by the perpendicular
69     SkVector perp = SkVector::Make(p0.fY - p1.fY, p1.fX - p0.fX);
70     if (!perp.setLength(offset*side)) {
71         return false;
72     }
73     *vector = perp;
74     return true;
75 }
76 
77 // check interval to see if intersection is in segment
outside_interval(SkScalar numer,SkScalar denom,bool denomPositive)78 static inline bool outside_interval(SkScalar numer, SkScalar denom, bool denomPositive) {
79     return (denomPositive && (numer < 0 || numer > denom)) ||
80            (!denomPositive && (numer > 0 || numer < denom));
81 }
82 
83 // special zero-length test when we're using vdotv as a denominator
zero_length(const SkPoint & v,SkScalar vdotv)84 static inline bool zero_length(const SkPoint& v, SkScalar vdotv) {
85     return !(SkScalarsAreFinite(v.fX, v.fY) && vdotv);
86 }
87 
88 // Compute the intersection 'p' between segments s0 and s1, if any.
89 // 's' is the parametric value for the intersection along 's0' & 't' is the same for 's1'.
90 // Returns false if there is no intersection.
91 // If the length squared of a segment is 0, then we treat the segment as degenerate
92 // and use only the first endpoint for tests.
compute_intersection(const OffsetSegment & s0,const OffsetSegment & s1,SkPoint * p,SkScalar * s,SkScalar * t)93 static bool compute_intersection(const OffsetSegment& s0, const OffsetSegment& s1,
94                                  SkPoint* p, SkScalar* s, SkScalar* t) {
95     const SkVector& v0 = s0.fV;
96     const SkVector& v1 = s1.fV;
97     SkVector w = s1.fP0 - s0.fP0;
98     SkScalar denom = v0.cross(v1);
99     bool denomPositive = (denom > 0);
100     SkScalar sNumer, tNumer;
101     if (SkScalarNearlyZero(denom, kCrossTolerance)) {
102         // segments are parallel, but not collinear
103         if (!SkScalarNearlyZero(w.cross(v0), kCrossTolerance) ||
104             !SkScalarNearlyZero(w.cross(v1), kCrossTolerance)) {
105             return false;
106         }
107 
108         // Check for zero-length segments
109         SkScalar v0dotv0 = v0.dot(v0);
110         if (zero_length(v0, v0dotv0)) {
111             // Both are zero-length
112             SkScalar v1dotv1 = v1.dot(v1);
113             if (zero_length(v1, v1dotv1)) {
114                 // Check if they're the same point
115                 if (!SkPointPriv::CanNormalize(w.fX, w.fY)) {
116                     *p = s0.fP0;
117                     *s = 0;
118                     *t = 0;
119                     return true;
120                 } else {
121                     // Intersection is indeterminate
122                     return false;
123                 }
124             }
125             // Otherwise project segment0's origin onto segment1
126             tNumer = v1.dot(-w);
127             denom = v1dotv1;
128             if (outside_interval(tNumer, denom, true)) {
129                 return false;
130             }
131             sNumer = 0;
132         } else {
133             // Project segment1's endpoints onto segment0
134             sNumer = v0.dot(w);
135             denom = v0dotv0;
136             tNumer = 0;
137             if (outside_interval(sNumer, denom, true)) {
138                 // The first endpoint doesn't lie on segment0
139                 // If segment1 is degenerate, then there's no collision
140                 SkScalar v1dotv1 = v1.dot(v1);
141                 if (zero_length(v1, v1dotv1)) {
142                     return false;
143                 }
144 
145                 // Otherwise try the other one
146                 SkScalar oldSNumer = sNumer;
147                 sNumer = v0.dot(w + v1);
148                 tNumer = denom;
149                 if (outside_interval(sNumer, denom, true)) {
150                     // it's possible that segment1's interval surrounds segment0
151                     // this is false if params have the same signs, and in that case no collision
152                     if (sNumer*oldSNumer > 0) {
153                         return false;
154                     }
155                     // otherwise project segment0's endpoint onto segment1 instead
156                     sNumer = 0;
157                     tNumer = v1.dot(-w);
158                     denom = v1dotv1;
159                 }
160             }
161         }
162     } else {
163         sNumer = w.cross(v1);
164         if (outside_interval(sNumer, denom, denomPositive)) {
165             return false;
166         }
167         tNumer = w.cross(v0);
168         if (outside_interval(tNumer, denom, denomPositive)) {
169             return false;
170         }
171     }
172 
173     SkScalar localS = sNumer/denom;
174     SkScalar localT = tNumer/denom;
175 
176     *p = s0.fP0 + v0*localS;
177     *s = localS;
178     *t = localT;
179 
180     return true;
181 }
182 
SkIsConvexPolygon(const SkPoint * polygonVerts,int polygonSize)183 bool SkIsConvexPolygon(const SkPoint* polygonVerts, int polygonSize) {
184     if (polygonSize < 3) {
185         return false;
186     }
187 
188     SkScalar lastPerpDot = 0;
189     int xSignChangeCount = 0;
190     int ySignChangeCount = 0;
191 
192     int prevIndex = polygonSize - 1;
193     int currIndex = 0;
194     int nextIndex = 1;
195     SkVector v0 = polygonVerts[currIndex] - polygonVerts[prevIndex];
196     SkVector v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
197     for (int i = 0; i < polygonSize; ++i) {
198         if (!polygonVerts[i].isFinite()) {
199             return false;
200         }
201 
202         // Check that winding direction is always the same (otherwise we have a reflex vertex)
203         SkScalar perpDot = v0.cross(v1);
204         if (lastPerpDot*perpDot < 0) {
205             return false;
206         }
207         if (0 != perpDot) {
208             lastPerpDot = perpDot;
209         }
210 
211         // Check that the signs of the edge vectors don't change more than twice per coordinate
212         if (v0.fX*v1.fX < 0) {
213             xSignChangeCount++;
214         }
215         if (v0.fY*v1.fY < 0) {
216             ySignChangeCount++;
217         }
218         if (xSignChangeCount > 2 || ySignChangeCount > 2) {
219             return false;
220         }
221         prevIndex = currIndex;
222         currIndex = nextIndex;
223         nextIndex = (currIndex + 1) % polygonSize;
224         v0 = v1;
225         v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
226     }
227 
228     return true;
229 }
230 
231 struct OffsetEdge {
232     OffsetEdge*   fPrev;
233     OffsetEdge*   fNext;
234     OffsetSegment fOffset;
235     SkPoint       fIntersection;
236     SkScalar      fTValue;
237     uint16_t      fIndex;
238     uint16_t      fEnd;
239 
initOffsetEdge240     void init(uint16_t start = 0, uint16_t end = 0) {
241         fIntersection = fOffset.fP0;
242         fTValue = SK_ScalarMin;
243         fIndex = start;
244         fEnd = end;
245     }
246 
247     // special intersection check that looks for endpoint intersection
checkIntersectionOffsetEdge248     bool checkIntersection(const OffsetEdge* that,
249                            SkPoint* p, SkScalar* s, SkScalar* t) {
250         if (this->fEnd == that->fIndex) {
251             SkPoint p1 = this->fOffset.fP0 + this->fOffset.fV;
252             if (SkPointPriv::EqualsWithinTolerance(p1, that->fOffset.fP0)) {
253                 *p = p1;
254                 *s = SK_Scalar1;
255                 *t = 0;
256                 return true;
257             }
258         }
259 
260         return compute_intersection(this->fOffset, that->fOffset, p, s, t);
261     }
262 
263     // computes the line intersection and then the "distance" from that to this
264     // this is really a signed squared distance, where negative means that
265     // the intersection lies inside this->fOffset
computeCrossingDistanceOffsetEdge266     SkScalar computeCrossingDistance(const OffsetEdge* that) {
267         const OffsetSegment& s0 = this->fOffset;
268         const OffsetSegment& s1 = that->fOffset;
269         const SkVector& v0 = s0.fV;
270         const SkVector& v1 = s1.fV;
271 
272         SkScalar denom = v0.cross(v1);
273         if (SkScalarNearlyZero(denom, kCrossTolerance)) {
274             // segments are parallel
275             return SK_ScalarMax;
276         }
277 
278         SkVector w = s1.fP0 - s0.fP0;
279         SkScalar localS = w.cross(v1) / denom;
280         if (localS < 0) {
281             localS = -localS;
282         } else {
283             localS -= SK_Scalar1;
284         }
285 
286         localS *= SkScalarAbs(localS);
287         localS *= v0.dot(v0);
288 
289         return localS;
290     }
291 
292 };
293 
remove_node(const OffsetEdge * node,OffsetEdge ** head)294 static void remove_node(const OffsetEdge* node, OffsetEdge** head) {
295     // remove from linked list
296     node->fPrev->fNext = node->fNext;
297     node->fNext->fPrev = node->fPrev;
298     if (node == *head) {
299         *head = (node->fNext == node) ? nullptr : node->fNext;
300     }
301 }
302 
303 //////////////////////////////////////////////////////////////////////////////////
304 
305 // The objective here is to inset all of the edges by the given distance, and then
306 // remove any invalid inset edges by detecting right-hand turns. In a ccw polygon,
307 // we should only be making left-hand turns (for cw polygons, we use the winding
308 // parameter to reverse this). We detect this by checking whether the second intersection
309 // on an edge is closer to its tail than the first one.
310 //
311 // We might also have the case that there is no intersection between two neighboring inset edges.
312 // In this case, one edge will lie to the right of the other and should be discarded along with
313 // its previous intersection (if any).
314 //
315 // Note: the assumption is that inputPolygon is convex and has no coincident points.
316 //
SkInsetConvexPolygon(const SkPoint * inputPolygonVerts,int inputPolygonSize,SkScalar inset,SkTDArray<SkPoint> * insetPolygon)317 bool SkInsetConvexPolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
318                           SkScalar inset, SkTDArray<SkPoint>* insetPolygon) {
319     if (inputPolygonSize < 3) {
320         return false;
321     }
322 
323     // restrict this to match other routines
324     // practically we don't want anything bigger than this anyway
325     if (inputPolygonSize > std::numeric_limits<uint16_t>::max()) {
326         return false;
327     }
328 
329     // can't inset by a negative or non-finite amount
330     if (inset < -SK_ScalarNearlyZero || !SkScalarIsFinite(inset)) {
331         return false;
332     }
333 
334     // insetting close to zero just returns the original poly
335     if (inset <= SK_ScalarNearlyZero) {
336         for (int i = 0; i < inputPolygonSize; ++i) {
337             *insetPolygon->push() = inputPolygonVerts[i];
338         }
339         return true;
340     }
341 
342     // get winding direction
343     int winding = SkGetPolygonWinding(inputPolygonVerts, inputPolygonSize);
344     if (0 == winding) {
345         return false;
346     }
347 
348     // set up
349     SkAutoSTMalloc<64, OffsetEdge> edgeData(inputPolygonSize);
350     int prev = inputPolygonSize - 1;
351     for (int curr = 0; curr < inputPolygonSize; prev = curr, ++curr) {
352         int next = (curr + 1) % inputPolygonSize;
353         if (!inputPolygonVerts[curr].isFinite()) {
354             return false;
355         }
356         // check for convexity just to be sure
357         if (compute_side(inputPolygonVerts[prev], inputPolygonVerts[curr] - inputPolygonVerts[prev],
358                          inputPolygonVerts[next])*winding < 0) {
359             return false;
360         }
361         SkVector v = inputPolygonVerts[next] - inputPolygonVerts[curr];
362         SkVector perp = SkVector::Make(-v.fY, v.fX);
363         perp.setLength(inset*winding);
364         edgeData[curr].fPrev = &edgeData[prev];
365         edgeData[curr].fNext = &edgeData[next];
366         edgeData[curr].fOffset.fP0 = inputPolygonVerts[curr] + perp;
367         edgeData[curr].fOffset.fV = v;
368         edgeData[curr].init();
369     }
370 
371     OffsetEdge* head = &edgeData[0];
372     OffsetEdge* currEdge = head;
373     OffsetEdge* prevEdge = currEdge->fPrev;
374     int insetVertexCount = inputPolygonSize;
375     unsigned int iterations = 0;
376     unsigned int maxIterations = inputPolygonSize * inputPolygonSize;
377     while (head && prevEdge != currEdge) {
378         ++iterations;
379         // we should check each edge against each other edge at most once
380         if (iterations > maxIterations) {
381             return false;
382         }
383 
384         SkScalar s, t;
385         SkPoint intersection;
386         if (compute_intersection(prevEdge->fOffset, currEdge->fOffset,
387                                  &intersection, &s, &t)) {
388             // if new intersection is further back on previous inset from the prior intersection
389             if (s < prevEdge->fTValue) {
390                 // no point in considering this one again
391                 remove_node(prevEdge, &head);
392                 --insetVertexCount;
393                 // go back one segment
394                 prevEdge = prevEdge->fPrev;
395             // we've already considered this intersection, we're done
396             } else if (currEdge->fTValue > SK_ScalarMin &&
397                        SkPointPriv::EqualsWithinTolerance(intersection,
398                                                           currEdge->fIntersection,
399                                                           1.0e-6f)) {
400                 break;
401             } else {
402                 // add intersection
403                 currEdge->fIntersection = intersection;
404                 currEdge->fTValue = t;
405 
406                 // go to next segment
407                 prevEdge = currEdge;
408                 currEdge = currEdge->fNext;
409             }
410         } else {
411             // if prev to right side of curr
412             int side = winding*compute_side(currEdge->fOffset.fP0,
413                                             currEdge->fOffset.fV,
414                                             prevEdge->fOffset.fP0);
415             if (side < 0 &&
416                 side == winding*compute_side(currEdge->fOffset.fP0,
417                                              currEdge->fOffset.fV,
418                                              prevEdge->fOffset.fP0 + prevEdge->fOffset.fV)) {
419                 // no point in considering this one again
420                 remove_node(prevEdge, &head);
421                 --insetVertexCount;
422                 // go back one segment
423                 prevEdge = prevEdge->fPrev;
424             } else {
425                 // move to next segment
426                 remove_node(currEdge, &head);
427                 --insetVertexCount;
428                 currEdge = currEdge->fNext;
429             }
430         }
431     }
432 
433     // store all the valid intersections that aren't nearly coincident
434     // TODO: look at the main algorithm and see if we can detect these better
435     insetPolygon->reset();
436     if (!head) {
437         return false;
438     }
439 
440     static constexpr SkScalar kCleanupTolerance = 0.01f;
441     if (insetVertexCount >= 0) {
442         insetPolygon->setReserve(insetVertexCount);
443     }
444     int currIndex = 0;
445     *insetPolygon->push() = head->fIntersection;
446     currEdge = head->fNext;
447     while (currEdge != head) {
448         if (!SkPointPriv::EqualsWithinTolerance(currEdge->fIntersection,
449                                                 (*insetPolygon)[currIndex],
450                                                 kCleanupTolerance)) {
451             *insetPolygon->push() = currEdge->fIntersection;
452             currIndex++;
453         }
454         currEdge = currEdge->fNext;
455     }
456     // make sure the first and last points aren't coincident
457     if (currIndex >= 1 &&
458         SkPointPriv::EqualsWithinTolerance((*insetPolygon)[0], (*insetPolygon)[currIndex],
459                                             kCleanupTolerance)) {
460         insetPolygon->pop();
461     }
462 
463     return SkIsConvexPolygon(insetPolygon->begin(), insetPolygon->count());
464 }
465 
466 ///////////////////////////////////////////////////////////////////////////////////////////
467 
468 // compute the number of points needed for a circular join when offsetting a reflex vertex
SkComputeRadialSteps(const SkVector & v1,const SkVector & v2,SkScalar offset,SkScalar * rotSin,SkScalar * rotCos,int * n)469 bool SkComputeRadialSteps(const SkVector& v1, const SkVector& v2, SkScalar offset,
470                           SkScalar* rotSin, SkScalar* rotCos, int* n) {
471     const SkScalar kRecipPixelsPerArcSegment = 0.25f;
472 
473     SkScalar rCos = v1.dot(v2);
474     if (!SkScalarIsFinite(rCos)) {
475         return false;
476     }
477     SkScalar rSin = v1.cross(v2);
478     if (!SkScalarIsFinite(rSin)) {
479         return false;
480     }
481     SkScalar theta = SkScalarATan2(rSin, rCos);
482 
483     SkScalar floatSteps = SkScalarAbs(offset*theta*kRecipPixelsPerArcSegment);
484     // limit the number of steps to at most max uint16_t (that's all we can index)
485     // knock one value off the top to account for rounding
486     if (floatSteps >= std::numeric_limits<uint16_t>::max()) {
487         return false;
488     }
489     int steps = SkScalarRoundToInt(floatSteps);
490 
491     SkScalar dTheta = steps > 0 ? theta / steps : 0;
492     *rotSin = SkScalarSin(dTheta);
493     *rotCos = SkScalarCos(dTheta);
494     // Our offset may be so large that we end up with a tiny dTheta, in which case we
495     // lose precision when computing rotSin and rotCos.
496     if (steps > 0 && (*rotSin == 0 || *rotCos == 1)) {
497         return false;
498     }
499     *n = steps;
500     return true;
501 }
502 
503 ///////////////////////////////////////////////////////////////////////////////////////////
504 
505 // a point is "left" to another if its x-coord is less, or if equal, its y-coord is greater
left(const SkPoint & p0,const SkPoint & p1)506 static bool left(const SkPoint& p0, const SkPoint& p1) {
507     return p0.fX < p1.fX || (!(p0.fX > p1.fX) && p0.fY > p1.fY);
508 }
509 
510 // a point is "right" to another if its x-coord is greater, or if equal, its y-coord is less
right(const SkPoint & p0,const SkPoint & p1)511 static bool right(const SkPoint& p0, const SkPoint& p1) {
512     return p0.fX > p1.fX || (!(p0.fX < p1.fX) && p0.fY < p1.fY);
513 }
514 
515 struct Vertex {
LeftVertex516     static bool Left(const Vertex& qv0, const Vertex& qv1) {
517         return left(qv0.fPosition, qv1.fPosition);
518     }
519 
520     // packed to fit into 16 bytes (one cache line)
521     SkPoint  fPosition;
522     uint16_t fIndex;       // index in unsorted polygon
523     uint16_t fPrevIndex;   // indices for previous and next vertex in unsorted polygon
524     uint16_t fNextIndex;
525     uint16_t fFlags;
526 };
527 
528 enum VertexFlags {
529     kPrevLeft_VertexFlag = 0x1,
530     kNextLeft_VertexFlag = 0x2,
531 };
532 
533 struct ActiveEdge {
ActiveEdgeActiveEdge534     ActiveEdge() : fChild{ nullptr, nullptr }, fAbove(nullptr), fBelow(nullptr), fRed(false) {}
ActiveEdgeActiveEdge535     ActiveEdge(const SkPoint& p0, const SkVector& v, uint16_t index0, uint16_t index1)
536         : fSegment({ p0, v })
537         , fIndex0(index0)
538         , fIndex1(index1)
539         , fAbove(nullptr)
540         , fBelow(nullptr)
541         , fRed(true) {
542         fChild[0] = nullptr;
543         fChild[1] = nullptr;
544     }
545 
546     // Returns true if "this" is above "that", assuming this->p0 is to the left of that->p0
547     // This is only used to verify the edgelist -- the actual test for insertion/deletion is much
548     // simpler because we can make certain assumptions then.
aboveIfLeftActiveEdge549     bool aboveIfLeft(const ActiveEdge* that) const {
550         const SkPoint& p0 = this->fSegment.fP0;
551         const SkPoint& q0 = that->fSegment.fP0;
552         SkASSERT(p0.fX <= q0.fX);
553         SkVector d = q0 - p0;
554         const SkVector& v = this->fSegment.fV;
555         const SkVector& w = that->fSegment.fV;
556         // The idea here is that if the vector between the origins of the two segments (d)
557         // rotates counterclockwise up to the vector representing the "this" segment (v),
558         // then we know that "this" is above "that". If the result is clockwise we say it's below.
559         if (this->fIndex0 != that->fIndex0) {
560             SkScalar cross = d.cross(v);
561             if (cross > kCrossTolerance) {
562                 return true;
563             } else if (cross < -kCrossTolerance) {
564                 return false;
565             }
566         } else if (this->fIndex1 == that->fIndex1) {
567             return false;
568         }
569         // At this point either the two origins are nearly equal or the origin of "that"
570         // lies on dv. So then we try the same for the vector from the tail of "this"
571         // to the head of "that". Again, ccw means "this" is above "that".
572         // d = that.P1 - this.P0
573         //   = that.fP0 + that.fV - this.fP0
574         //   = that.fP0 - this.fP0 + that.fV
575         //   = old_d + that.fV
576         d += w;
577         SkScalar cross = d.cross(v);
578         if (cross > kCrossTolerance) {
579             return true;
580         } else if (cross < -kCrossTolerance) {
581             return false;
582         }
583         // If the previous check fails, the two segments are nearly collinear
584         // First check y-coord of first endpoints
585         if (p0.fX < q0.fX) {
586             return (p0.fY >= q0.fY);
587         } else if (p0.fY > q0.fY) {
588             return true;
589         } else if (p0.fY < q0.fY) {
590             return false;
591         }
592         // The first endpoints are the same, so check the other endpoint
593         SkPoint p1 = p0 + v;
594         SkPoint q1 = q0 + w;
595         if (p1.fX < q1.fX) {
596             return (p1.fY >= q1.fY);
597         } else {
598             return (p1.fY > q1.fY);
599         }
600     }
601 
602     // same as leftAndAbove(), but generalized
aboveActiveEdge603     bool above(const ActiveEdge* that) const {
604         const SkPoint& p0 = this->fSegment.fP0;
605         const SkPoint& q0 = that->fSegment.fP0;
606         if (right(p0, q0)) {
607             return !that->aboveIfLeft(this);
608         } else {
609             return this->aboveIfLeft(that);
610         }
611     }
612 
intersectActiveEdge613     bool intersect(const SkPoint& q0, const SkVector& w, uint16_t index0, uint16_t index1) const {
614         // check first to see if these edges are neighbors in the polygon
615         if (this->fIndex0 == index0 || this->fIndex1 == index0 ||
616             this->fIndex0 == index1 || this->fIndex1 == index1) {
617             return false;
618         }
619 
620         // We don't need the exact intersection point so we can do a simpler test here.
621         const SkPoint& p0 = this->fSegment.fP0;
622         const SkVector& v = this->fSegment.fV;
623         SkPoint p1 = p0 + v;
624         SkPoint q1 = q0 + w;
625 
626         // We assume some x-overlap due to how the edgelist works
627         // This allows us to simplify our test
628         // We need some slop here because storing the vector and recomputing the second endpoint
629         // doesn't necessary give us the original result in floating point.
630         // TODO: Store vector as double? Store endpoint as well?
631         SkASSERT(q0.fX <= p1.fX + SK_ScalarNearlyZero);
632 
633         // if each segment straddles the other (i.e., the endpoints have different sides)
634         // then they intersect
635         bool result;
636         if (p0.fX < q0.fX) {
637             if (q1.fX < p1.fX) {
638                 result = (compute_side(p0, v, q0)*compute_side(p0, v, q1) < 0);
639             } else {
640                 result = (compute_side(p0, v, q0)*compute_side(q0, w, p1) > 0);
641             }
642         } else {
643             if (p1.fX < q1.fX) {
644                 result = (compute_side(q0, w, p0)*compute_side(q0, w, p1) < 0);
645             } else {
646                 result = (compute_side(q0, w, p0)*compute_side(p0, v, q1) > 0);
647             }
648         }
649         return result;
650     }
651 
intersectActiveEdge652     bool intersect(const ActiveEdge* edge) {
653         return this->intersect(edge->fSegment.fP0, edge->fSegment.fV, edge->fIndex0, edge->fIndex1);
654     }
655 
lessThanActiveEdge656     bool lessThan(const ActiveEdge* that) const {
657         SkASSERT(!this->above(this));
658         SkASSERT(!that->above(that));
659         SkASSERT(!(this->above(that) && that->above(this)));
660         return this->above(that);
661     }
662 
equalsActiveEdge663     bool equals(uint16_t index0, uint16_t index1) const {
664         return (this->fIndex0 == index0 && this->fIndex1 == index1);
665     }
666 
667     OffsetSegment fSegment;
668     uint16_t fIndex0;   // indices for previous and next vertex in polygon
669     uint16_t fIndex1;
670     ActiveEdge* fChild[2];
671     ActiveEdge* fAbove;
672     ActiveEdge* fBelow;
673     int32_t  fRed;
674 };
675 
676 class ActiveEdgeList {
677 public:
ActiveEdgeList(int maxEdges)678     ActiveEdgeList(int maxEdges) {
679         fAllocation = (char*) sk_malloc_throw(sizeof(ActiveEdge)*maxEdges);
680         fCurrFree = 0;
681         fMaxFree = maxEdges;
682     }
~ActiveEdgeList()683     ~ActiveEdgeList() {
684         fTreeHead.fChild[1] = nullptr;
685         sk_free(fAllocation);
686     }
687 
insert(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)688     bool insert(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
689         SkVector v = p1 - p0;
690         if (!v.isFinite()) {
691             return false;
692         }
693         // empty tree case -- easy
694         if (!fTreeHead.fChild[1]) {
695             ActiveEdge* root = fTreeHead.fChild[1] = this->allocate(p0, v, index0, index1);
696             SkASSERT(root);
697             if (!root) {
698                 return false;
699             }
700             root->fRed = false;
701             return true;
702         }
703 
704         // set up helpers
705         ActiveEdge* top = &fTreeHead;
706         ActiveEdge *grandparent = nullptr;
707         ActiveEdge *parent = nullptr;
708         ActiveEdge *curr = top->fChild[1];
709         int dir = 0;
710         int last = 0; // ?
711         // predecessor and successor, for intersection check
712         ActiveEdge* pred = nullptr;
713         ActiveEdge* succ = nullptr;
714 
715         // search down the tree
716         while (true) {
717             if (!curr) {
718                 // check for intersection with predecessor and successor
719                 if ((pred && pred->intersect(p0, v, index0, index1)) ||
720                     (succ && succ->intersect(p0, v, index0, index1))) {
721                     return false;
722                 }
723                 // insert new node at bottom
724                 parent->fChild[dir] = curr = this->allocate(p0, v, index0, index1);
725                 SkASSERT(curr);
726                 if (!curr) {
727                     return false;
728                 }
729                 curr->fAbove = pred;
730                 curr->fBelow = succ;
731                 if (pred) {
732                     pred->fBelow = curr;
733                 }
734                 if (succ) {
735                     succ->fAbove = curr;
736                 }
737                 if (IsRed(parent)) {
738                     int dir2 = (top->fChild[1] == grandparent);
739                     if (curr == parent->fChild[last]) {
740                         top->fChild[dir2] = SingleRotation(grandparent, !last);
741                     } else {
742                         top->fChild[dir2] = DoubleRotation(grandparent, !last);
743                     }
744                 }
745                 break;
746             } else if (IsRed(curr->fChild[0]) && IsRed(curr->fChild[1])) {
747                 // color flip
748                 curr->fRed = true;
749                 curr->fChild[0]->fRed = false;
750                 curr->fChild[1]->fRed = false;
751                 if (IsRed(parent)) {
752                     int dir2 = (top->fChild[1] == grandparent);
753                     if (curr == parent->fChild[last]) {
754                         top->fChild[dir2] = SingleRotation(grandparent, !last);
755                     } else {
756                         top->fChild[dir2] = DoubleRotation(grandparent, !last);
757                     }
758                 }
759             }
760 
761             last = dir;
762             int side;
763             // check to see if segment is above or below
764             if (curr->fIndex0 == index0) {
765                 side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
766             } else {
767                 side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
768             }
769             if (0 == side) {
770                 return false;
771             }
772             dir = (side < 0);
773 
774             if (0 == dir) {
775                 succ = curr;
776             } else {
777                 pred = curr;
778             }
779 
780             // update helpers
781             if (grandparent) {
782                 top = grandparent;
783             }
784             grandparent = parent;
785             parent = curr;
786             curr = curr->fChild[dir];
787         }
788 
789         // update root and make it black
790         fTreeHead.fChild[1]->fRed = false;
791 
792         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
793 
794         return true;
795     }
796 
797     // replaces edge p0p1 with p1p2
replace(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,uint16_t index0,uint16_t index1,uint16_t index2)798     bool replace(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
799                  uint16_t index0, uint16_t index1, uint16_t index2) {
800         if (!fTreeHead.fChild[1]) {
801             return false;
802         }
803 
804         SkVector v = p2 - p1;
805         ActiveEdge* curr = &fTreeHead;
806         ActiveEdge* found = nullptr;
807         int dir = 1;
808 
809         // search
810         while (curr->fChild[dir] != nullptr) {
811             // update helpers
812             curr = curr->fChild[dir];
813             // save found node
814             if (curr->equals(index0, index1)) {
815                 found = curr;
816                 break;
817             } else {
818                 // check to see if segment is above or below
819                 int side;
820                 if (curr->fIndex1 == index1) {
821                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
822                 } else {
823                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
824                 }
825                 if (0 == side) {
826                     return false;
827                 }
828                 dir = (side < 0);
829             }
830         }
831 
832         if (!found) {
833             return false;
834         }
835 
836         // replace if found
837         ActiveEdge* pred = found->fAbove;
838         ActiveEdge* succ = found->fBelow;
839         // check deletion and insert intersection cases
840         if (pred && (pred->intersect(found) || pred->intersect(p1, v, index1, index2))) {
841             return false;
842         }
843         if (succ && (succ->intersect(found) || succ->intersect(p1, v, index1, index2))) {
844             return false;
845         }
846         found->fSegment.fP0 = p1;
847         found->fSegment.fV = v;
848         found->fIndex0 = index1;
849         found->fIndex1 = index2;
850         // above and below should stay the same
851 
852         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
853 
854         return true;
855     }
856 
remove(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)857     bool remove(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
858         if (!fTreeHead.fChild[1]) {
859             return false;
860         }
861 
862         ActiveEdge* curr = &fTreeHead;
863         ActiveEdge* parent = nullptr;
864         ActiveEdge* grandparent = nullptr;
865         ActiveEdge* found = nullptr;
866         int dir = 1;
867 
868         // search and push a red node down
869         while (curr->fChild[dir] != nullptr) {
870             int last = dir;
871 
872             // update helpers
873             grandparent = parent;
874             parent = curr;
875             curr = curr->fChild[dir];
876             // save found node
877             if (curr->equals(index0, index1)) {
878                 found = curr;
879                 dir = 0;
880             } else {
881                 // check to see if segment is above or below
882                 int side;
883                 if (curr->fIndex1 == index1) {
884                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
885                 } else {
886                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
887                 }
888                 if (0 == side) {
889                     return false;
890                 }
891                 dir = (side < 0);
892             }
893 
894             // push the red node down
895             if (!IsRed(curr) && !IsRed(curr->fChild[dir])) {
896                 if (IsRed(curr->fChild[!dir])) {
897                     parent = parent->fChild[last] = SingleRotation(curr, dir);
898                 } else {
899                     ActiveEdge *s = parent->fChild[!last];
900 
901                     if (s != nullptr) {
902                         if (!IsRed(s->fChild[!last]) && !IsRed(s->fChild[last])) {
903                             // color flip
904                             parent->fRed = false;
905                             s->fRed = true;
906                             curr->fRed = true;
907                         } else {
908                             int dir2 = (grandparent->fChild[1] == parent);
909 
910                             if (IsRed(s->fChild[last])) {
911                                 grandparent->fChild[dir2] = DoubleRotation(parent, last);
912                             } else if (IsRed(s->fChild[!last])) {
913                                 grandparent->fChild[dir2] = SingleRotation(parent, last);
914                             }
915 
916                             // ensure correct coloring
917                             curr->fRed = grandparent->fChild[dir2]->fRed = true;
918                             grandparent->fChild[dir2]->fChild[0]->fRed = false;
919                             grandparent->fChild[dir2]->fChild[1]->fRed = false;
920                         }
921                     }
922                 }
923             }
924         }
925 
926         // replace and remove if found
927         if (found) {
928             ActiveEdge* pred = found->fAbove;
929             ActiveEdge* succ = found->fBelow;
930             if ((pred && pred->intersect(found)) || (succ && succ->intersect(found))) {
931                 return false;
932             }
933             if (found != curr) {
934                 found->fSegment = curr->fSegment;
935                 found->fIndex0 = curr->fIndex0;
936                 found->fIndex1 = curr->fIndex1;
937                 found->fAbove = curr->fAbove;
938                 pred = found->fAbove;
939                 // we don't need to set found->fBelow here
940             } else {
941                 if (succ) {
942                     succ->fAbove = pred;
943                 }
944             }
945             if (pred) {
946                 pred->fBelow = curr->fBelow;
947             }
948             parent->fChild[parent->fChild[1] == curr] = curr->fChild[!curr->fChild[0]];
949 
950             // no need to delete
951             curr->fAbove = reinterpret_cast<ActiveEdge*>(0xdeadbeefll);
952             curr->fBelow = reinterpret_cast<ActiveEdge*>(0xdeadbeefll);
953             if (fTreeHead.fChild[1]) {
954                 fTreeHead.fChild[1]->fRed = false;
955             }
956         }
957 
958         // update root and make it black
959         if (fTreeHead.fChild[1]) {
960             fTreeHead.fChild[1]->fRed = false;
961         }
962 
963         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
964 
965         return true;
966     }
967 
968 private:
969     // allocator
allocate(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)970     ActiveEdge * allocate(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
971         if (fCurrFree >= fMaxFree) {
972             return nullptr;
973         }
974         char* bytes = fAllocation + sizeof(ActiveEdge)*fCurrFree;
975         ++fCurrFree;
976         return new(bytes) ActiveEdge(p0, p1, index0, index1);
977     }
978 
979     ///////////////////////////////////////////////////////////////////////////////////
980     // Red-black tree methods
981     ///////////////////////////////////////////////////////////////////////////////////
IsRed(const ActiveEdge * node)982     static bool IsRed(const ActiveEdge* node) {
983         return node && node->fRed;
984     }
985 
SingleRotation(ActiveEdge * node,int dir)986     static ActiveEdge* SingleRotation(ActiveEdge* node, int dir) {
987         ActiveEdge* tmp = node->fChild[!dir];
988 
989         node->fChild[!dir] = tmp->fChild[dir];
990         tmp->fChild[dir] = node;
991 
992         node->fRed = true;
993         tmp->fRed = false;
994 
995         return tmp;
996     }
997 
DoubleRotation(ActiveEdge * node,int dir)998     static ActiveEdge* DoubleRotation(ActiveEdge* node, int dir) {
999         node->fChild[!dir] = SingleRotation(node->fChild[!dir], !dir);
1000 
1001         return SingleRotation(node, dir);
1002     }
1003 
1004     // returns black link count
VerifyTree(const ActiveEdge * tree)1005     static int VerifyTree(const ActiveEdge* tree) {
1006         if (!tree) {
1007             return 1;
1008         }
1009 
1010         const ActiveEdge* left = tree->fChild[0];
1011         const ActiveEdge* right = tree->fChild[1];
1012 
1013         // no consecutive red links
1014         if (IsRed(tree) && (IsRed(left) || IsRed(right))) {
1015             SkASSERT(false);
1016             return 0;
1017         }
1018 
1019         // check secondary links
1020         if (tree->fAbove) {
1021             SkASSERT(tree->fAbove->fBelow == tree);
1022             SkASSERT(tree->fAbove->lessThan(tree));
1023         }
1024         if (tree->fBelow) {
1025             SkASSERT(tree->fBelow->fAbove == tree);
1026             SkASSERT(tree->lessThan(tree->fBelow));
1027         }
1028 
1029         // violates binary tree order
1030         if ((left && tree->lessThan(left)) || (right && right->lessThan(tree))) {
1031             SkASSERT(false);
1032             return 0;
1033         }
1034 
1035         int leftCount = VerifyTree(left);
1036         int rightCount = VerifyTree(right);
1037 
1038         // return black link count
1039         if (leftCount != 0 && rightCount != 0) {
1040             // black height mismatch
1041             if (leftCount != rightCount) {
1042                 SkASSERT(false);
1043                 return 0;
1044             }
1045             return IsRed(tree) ? leftCount : leftCount + 1;
1046         } else {
1047             return 0;
1048         }
1049     }
1050 
1051     ActiveEdge fTreeHead;
1052     char*      fAllocation;
1053     int        fCurrFree;
1054     int        fMaxFree;
1055 };
1056 
1057 // Here we implement a sweep line algorithm to determine whether the provided points
1058 // represent a simple polygon, i.e., the polygon is non-self-intersecting.
1059 // We first insert the vertices into a priority queue sorting horizontally from left to right.
1060 // Then as we pop the vertices from the queue we generate events which indicate that an edge
1061 // should be added or removed from an edge list. If any intersections are detected in the edge
1062 // list, then we know the polygon is self-intersecting and hence not simple.
SkIsSimplePolygon(const SkPoint * polygon,int polygonSize)1063 bool SkIsSimplePolygon(const SkPoint* polygon, int polygonSize) {
1064     if (polygonSize < 3) {
1065         return false;
1066     }
1067 
1068     // If it's convex, it's simple
1069     if (SkIsConvexPolygon(polygon, polygonSize)) {
1070         return true;
1071     }
1072 
1073     // practically speaking, it takes too long to process large polygons
1074     if (polygonSize > 2048) {
1075         return false;
1076     }
1077 
1078     SkTDPQueue <Vertex, Vertex::Left> vertexQueue(polygonSize);
1079     for (int i = 0; i < polygonSize; ++i) {
1080         Vertex newVertex;
1081         if (!polygon[i].isFinite()) {
1082             return false;
1083         }
1084         newVertex.fPosition = polygon[i];
1085         newVertex.fIndex = i;
1086         newVertex.fPrevIndex = (i - 1 + polygonSize) % polygonSize;
1087         newVertex.fNextIndex = (i + 1) % polygonSize;
1088         newVertex.fFlags = 0;
1089         // The two edges adjacent to this vertex are the same, so polygon is not simple
1090         if (polygon[newVertex.fPrevIndex] == polygon[newVertex.fNextIndex]) {
1091             return false;
1092         }
1093         if (left(polygon[newVertex.fPrevIndex], polygon[i])) {
1094             newVertex.fFlags |= kPrevLeft_VertexFlag;
1095         }
1096         if (left(polygon[newVertex.fNextIndex], polygon[i])) {
1097             newVertex.fFlags |= kNextLeft_VertexFlag;
1098         }
1099         vertexQueue.insert(newVertex);
1100     }
1101 
1102     // pop each vertex from the queue and generate events depending on
1103     // where it lies relative to its neighboring edges
1104     ActiveEdgeList sweepLine(polygonSize);
1105     while (vertexQueue.count() > 0) {
1106         const Vertex& v = vertexQueue.peek();
1107 
1108         // both to the right -- insert both
1109         if (v.fFlags == 0) {
1110             if (!sweepLine.insert(v.fPosition, polygon[v.fPrevIndex], v.fIndex, v.fPrevIndex)) {
1111                 break;
1112             }
1113             if (!sweepLine.insert(v.fPosition, polygon[v.fNextIndex], v.fIndex, v.fNextIndex)) {
1114                 break;
1115             }
1116         // both to the left -- remove both
1117         } else if (v.fFlags == (kPrevLeft_VertexFlag | kNextLeft_VertexFlag)) {
1118             if (!sweepLine.remove(polygon[v.fPrevIndex], v.fPosition, v.fPrevIndex, v.fIndex)) {
1119                 break;
1120             }
1121             if (!sweepLine.remove(polygon[v.fNextIndex], v.fPosition, v.fNextIndex, v.fIndex)) {
1122                 break;
1123             }
1124         // one to left and right -- replace one with another
1125         } else {
1126             if (v.fFlags & kPrevLeft_VertexFlag) {
1127                 if (!sweepLine.replace(polygon[v.fPrevIndex], v.fPosition, polygon[v.fNextIndex],
1128                                        v.fPrevIndex, v.fIndex, v.fNextIndex)) {
1129                     break;
1130                 }
1131             } else {
1132                 SkASSERT(v.fFlags & kNextLeft_VertexFlag);
1133                 if (!sweepLine.replace(polygon[v.fNextIndex], v.fPosition, polygon[v.fPrevIndex],
1134                                        v.fNextIndex, v.fIndex, v.fPrevIndex)) {
1135                     break;
1136                 }
1137             }
1138         }
1139 
1140         vertexQueue.pop();
1141     }
1142 
1143     return (vertexQueue.count() == 0);
1144 }
1145 
1146 ///////////////////////////////////////////////////////////////////////////////////////////
1147 
1148 // helper function for SkOffsetSimplePolygon
setup_offset_edge(OffsetEdge * currEdge,const SkPoint & endpoint0,const SkPoint & endpoint1,uint16_t startIndex,uint16_t endIndex)1149 static void setup_offset_edge(OffsetEdge* currEdge,
1150                               const SkPoint& endpoint0, const SkPoint& endpoint1,
1151                               uint16_t startIndex, uint16_t endIndex) {
1152     currEdge->fOffset.fP0 = endpoint0;
1153     currEdge->fOffset.fV = endpoint1 - endpoint0;
1154     currEdge->init(startIndex, endIndex);
1155 }
1156 
is_reflex_vertex(const SkPoint * inputPolygonVerts,int winding,SkScalar offset,uint16_t prevIndex,uint16_t currIndex,uint16_t nextIndex)1157 static bool is_reflex_vertex(const SkPoint* inputPolygonVerts, int winding, SkScalar offset,
1158                              uint16_t prevIndex, uint16_t currIndex, uint16_t nextIndex) {
1159     int side = compute_side(inputPolygonVerts[prevIndex],
1160                             inputPolygonVerts[currIndex] - inputPolygonVerts[prevIndex],
1161                             inputPolygonVerts[nextIndex]);
1162     // if reflex point, we need to add extra edges
1163     return (side*winding*offset < 0);
1164 }
1165 
SkOffsetSimplePolygon(const SkPoint * inputPolygonVerts,int inputPolygonSize,const SkRect & bounds,SkScalar offset,SkTDArray<SkPoint> * offsetPolygon,SkTDArray<int> * polygonIndices)1166 bool SkOffsetSimplePolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
1167                            const SkRect& bounds, SkScalar offset,
1168                            SkTDArray<SkPoint>* offsetPolygon, SkTDArray<int>* polygonIndices) {
1169     if (inputPolygonSize < 3) {
1170         return false;
1171     }
1172 
1173     // need to be able to represent all the vertices in the 16-bit indices
1174     if (inputPolygonSize >= std::numeric_limits<uint16_t>::max()) {
1175         return false;
1176     }
1177 
1178     if (!SkScalarIsFinite(offset)) {
1179         return false;
1180     }
1181 
1182     // can't inset more than the half bounds of the polygon
1183     if (offset > std::min(SkTAbs(SkRectPriv::HalfWidth(bounds)),
1184                           SkTAbs(SkRectPriv::HalfHeight(bounds)))) {
1185         return false;
1186     }
1187 
1188     // offsetting close to zero just returns the original poly
1189     if (SkScalarNearlyZero(offset)) {
1190         for (int i = 0; i < inputPolygonSize; ++i) {
1191             *offsetPolygon->push() = inputPolygonVerts[i];
1192             if (polygonIndices) {
1193                 *polygonIndices->push() = i;
1194             }
1195         }
1196         return true;
1197     }
1198 
1199     // get winding direction
1200     int winding = SkGetPolygonWinding(inputPolygonVerts, inputPolygonSize);
1201     if (0 == winding) {
1202         return false;
1203     }
1204 
1205     // build normals
1206     SkAutoSTMalloc<64, SkVector> normals(inputPolygonSize);
1207     unsigned int numEdges = 0;
1208     for (int currIndex = 0, prevIndex = inputPolygonSize - 1;
1209          currIndex < inputPolygonSize;
1210          prevIndex = currIndex, ++currIndex) {
1211         if (!inputPolygonVerts[currIndex].isFinite()) {
1212             return false;
1213         }
1214         int nextIndex = (currIndex + 1) % inputPolygonSize;
1215         if (!compute_offset_vector(inputPolygonVerts[currIndex], inputPolygonVerts[nextIndex],
1216                                    offset, winding, &normals[currIndex])) {
1217             return false;
1218         }
1219         if (currIndex > 0) {
1220             // if reflex point, we need to add extra edges
1221             if (is_reflex_vertex(inputPolygonVerts, winding, offset,
1222                                  prevIndex, currIndex, nextIndex)) {
1223                 SkScalar rotSin, rotCos;
1224                 int numSteps;
1225                 if (!SkComputeRadialSteps(normals[prevIndex], normals[currIndex], offset,
1226                                           &rotSin, &rotCos, &numSteps)) {
1227                     return false;
1228                 }
1229                 numEdges += std::max(numSteps, 1);
1230             }
1231         }
1232         numEdges++;
1233     }
1234     // finish up the edge counting
1235     if (is_reflex_vertex(inputPolygonVerts, winding, offset, inputPolygonSize-1, 0, 1)) {
1236         SkScalar rotSin, rotCos;
1237         int numSteps;
1238         if (!SkComputeRadialSteps(normals[inputPolygonSize-1], normals[0], offset,
1239                                   &rotSin, &rotCos, &numSteps)) {
1240             return false;
1241         }
1242         numEdges += std::max(numSteps, 1);
1243     }
1244 
1245     // Make sure we don't overflow the max array count.
1246     // We shouldn't overflow numEdges, as SkComputeRadialSteps returns a max of 2^16-1,
1247     // and we have a max of 2^16-1 original vertices.
1248     if (numEdges > (unsigned int)std::numeric_limits<int32_t>::max()) {
1249         return false;
1250     }
1251 
1252     // build initial offset edge list
1253     SkSTArray<64, OffsetEdge> edgeData(numEdges);
1254     OffsetEdge* prevEdge = nullptr;
1255     for (int currIndex = 0, prevIndex = inputPolygonSize - 1;
1256          currIndex < inputPolygonSize;
1257          prevIndex = currIndex, ++currIndex) {
1258         int nextIndex = (currIndex + 1) % inputPolygonSize;
1259         // if reflex point, fill in curve
1260         if (is_reflex_vertex(inputPolygonVerts, winding, offset,
1261                              prevIndex, currIndex, nextIndex)) {
1262             SkScalar rotSin, rotCos;
1263             int numSteps;
1264             SkVector prevNormal = normals[prevIndex];
1265             if (!SkComputeRadialSteps(prevNormal, normals[currIndex], offset,
1266                                       &rotSin, &rotCos, &numSteps)) {
1267                 return false;
1268             }
1269             auto currEdge = edgeData.push_back_n(std::max(numSteps, 1));
1270             for (int i = 0; i < numSteps - 1; ++i) {
1271                 SkVector currNormal = SkVector::Make(prevNormal.fX*rotCos - prevNormal.fY*rotSin,
1272                                                      prevNormal.fY*rotCos + prevNormal.fX*rotSin);
1273                 setup_offset_edge(currEdge,
1274                                   inputPolygonVerts[currIndex] + prevNormal,
1275                                   inputPolygonVerts[currIndex] + currNormal,
1276                                   currIndex, currIndex);
1277                 prevNormal = currNormal;
1278                 currEdge->fPrev = prevEdge;
1279                 if (prevEdge) {
1280                     prevEdge->fNext = currEdge;
1281                 }
1282                 prevEdge = currEdge;
1283                 ++currEdge;
1284             }
1285             setup_offset_edge(currEdge,
1286                               inputPolygonVerts[currIndex] + prevNormal,
1287                               inputPolygonVerts[currIndex] + normals[currIndex],
1288                               currIndex, currIndex);
1289             currEdge->fPrev = prevEdge;
1290             if (prevEdge) {
1291                 prevEdge->fNext = currEdge;
1292             }
1293             prevEdge = currEdge;
1294         }
1295 
1296         // Add the edge
1297         auto currEdge = edgeData.push_back_n(1);
1298         setup_offset_edge(currEdge,
1299                           inputPolygonVerts[currIndex] + normals[currIndex],
1300                           inputPolygonVerts[nextIndex] + normals[currIndex],
1301                           currIndex, nextIndex);
1302         currEdge->fPrev = prevEdge;
1303         if (prevEdge) {
1304             prevEdge->fNext = currEdge;
1305         }
1306         prevEdge = currEdge;
1307     }
1308     // close up the linked list
1309     SkASSERT(prevEdge);
1310     prevEdge->fNext = &edgeData[0];
1311     edgeData[0].fPrev = prevEdge;
1312 
1313     // now clip edges
1314     SkASSERT(edgeData.count() == (int)numEdges);
1315     auto head = &edgeData[0];
1316     auto currEdge = head;
1317     unsigned int offsetVertexCount = numEdges;
1318     unsigned long long iterations = 0;
1319     unsigned long long maxIterations = (unsigned long long)(numEdges) * numEdges;
1320     while (head && prevEdge != currEdge && offsetVertexCount > 0) {
1321         ++iterations;
1322         // we should check each edge against each other edge at most once
1323         if (iterations > maxIterations) {
1324             return false;
1325         }
1326 
1327         SkScalar s, t;
1328         SkPoint intersection;
1329         if (prevEdge->checkIntersection(currEdge, &intersection, &s, &t)) {
1330             // if new intersection is further back on previous inset from the prior intersection
1331             if (s < prevEdge->fTValue) {
1332                 // no point in considering this one again
1333                 remove_node(prevEdge, &head);
1334                 --offsetVertexCount;
1335                 // go back one segment
1336                 prevEdge = prevEdge->fPrev;
1337                 // we've already considered this intersection, we're done
1338             } else if (currEdge->fTValue > SK_ScalarMin &&
1339                        SkPointPriv::EqualsWithinTolerance(intersection,
1340                                                           currEdge->fIntersection,
1341                                                           1.0e-6f)) {
1342                 break;
1343             } else {
1344                 // add intersection
1345                 currEdge->fIntersection = intersection;
1346                 currEdge->fTValue = t;
1347                 currEdge->fIndex = prevEdge->fEnd;
1348 
1349                 // go to next segment
1350                 prevEdge = currEdge;
1351                 currEdge = currEdge->fNext;
1352             }
1353         } else {
1354             // If there is no intersection, we want to minimize the distance between
1355             // the point where the segment lines cross and the segments themselves.
1356             OffsetEdge* prevPrevEdge = prevEdge->fPrev;
1357             OffsetEdge* currNextEdge = currEdge->fNext;
1358             SkScalar dist0 = currEdge->computeCrossingDistance(prevPrevEdge);
1359             SkScalar dist1 = prevEdge->computeCrossingDistance(currNextEdge);
1360             // if both lead to direct collision
1361             if (dist0 < 0 && dist1 < 0) {
1362                 // check first to see if either represent parts of one contour
1363                 SkPoint p1 = prevPrevEdge->fOffset.fP0 + prevPrevEdge->fOffset.fV;
1364                 bool prevSameContour = SkPointPriv::EqualsWithinTolerance(p1,
1365                                                                           prevEdge->fOffset.fP0);
1366                 p1 = currEdge->fOffset.fP0 + currEdge->fOffset.fV;
1367                 bool currSameContour = SkPointPriv::EqualsWithinTolerance(p1,
1368                                                                          currNextEdge->fOffset.fP0);
1369 
1370                 // want to step along contour to find intersections rather than jump to new one
1371                 if (currSameContour && !prevSameContour) {
1372                     remove_node(currEdge, &head);
1373                     currEdge = currNextEdge;
1374                     --offsetVertexCount;
1375                     continue;
1376                 } else if (prevSameContour && !currSameContour) {
1377                     remove_node(prevEdge, &head);
1378                     prevEdge = prevPrevEdge;
1379                     --offsetVertexCount;
1380                     continue;
1381                 }
1382             }
1383 
1384             // otherwise minimize collision distance along segment
1385             if (dist0 < dist1) {
1386                 remove_node(prevEdge, &head);
1387                 prevEdge = prevPrevEdge;
1388             } else {
1389                 remove_node(currEdge, &head);
1390                 currEdge = currNextEdge;
1391             }
1392             --offsetVertexCount;
1393         }
1394     }
1395 
1396     // store all the valid intersections that aren't nearly coincident
1397     // TODO: look at the main algorithm and see if we can detect these better
1398     offsetPolygon->reset();
1399     if (!head || offsetVertexCount == 0 ||
1400         offsetVertexCount >= std::numeric_limits<uint16_t>::max()) {
1401         return false;
1402     }
1403 
1404     static constexpr SkScalar kCleanupTolerance = 0.01f;
1405     offsetPolygon->setReserve(offsetVertexCount);
1406     int currIndex = 0;
1407     *offsetPolygon->push() = head->fIntersection;
1408     if (polygonIndices) {
1409         *polygonIndices->push() = head->fIndex;
1410     }
1411     currEdge = head->fNext;
1412     while (currEdge != head) {
1413         if (!SkPointPriv::EqualsWithinTolerance(currEdge->fIntersection,
1414                                                 (*offsetPolygon)[currIndex],
1415                                                 kCleanupTolerance)) {
1416             *offsetPolygon->push() = currEdge->fIntersection;
1417             if (polygonIndices) {
1418                 *polygonIndices->push() = currEdge->fIndex;
1419             }
1420             currIndex++;
1421         }
1422         currEdge = currEdge->fNext;
1423     }
1424     // make sure the first and last points aren't coincident
1425     if (currIndex >= 1 &&
1426         SkPointPriv::EqualsWithinTolerance((*offsetPolygon)[0], (*offsetPolygon)[currIndex],
1427                                             kCleanupTolerance)) {
1428         offsetPolygon->pop();
1429         if (polygonIndices) {
1430             polygonIndices->pop();
1431         }
1432     }
1433 
1434     // check winding of offset polygon (it should be same as the original polygon)
1435     SkScalar offsetWinding = SkGetPolygonWinding(offsetPolygon->begin(), offsetPolygon->count());
1436 
1437     return (winding*offsetWinding > 0 &&
1438             SkIsSimplePolygon(offsetPolygon->begin(), offsetPolygon->count()));
1439 }
1440 
1441 //////////////////////////////////////////////////////////////////////////////////////////
1442 
1443 struct TriangulationVertex {
1444     SK_DECLARE_INTERNAL_LLIST_INTERFACE(TriangulationVertex);
1445 
1446     enum class VertexType { kConvex, kReflex };
1447 
1448     SkPoint    fPosition;
1449     VertexType fVertexType;
1450     uint16_t   fIndex;
1451     uint16_t   fPrevIndex;
1452     uint16_t   fNextIndex;
1453 };
1454 
compute_triangle_bounds(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,SkRect * bounds)1455 static void compute_triangle_bounds(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1456                                     SkRect* bounds) {
1457     Sk4s min, max;
1458     min = max = Sk4s(p0.fX, p0.fY, p0.fX, p0.fY);
1459     Sk4s xy(p1.fX, p1.fY, p2.fX, p2.fY);
1460     min = Sk4s::Min(min, xy);
1461     max = Sk4s::Max(max, xy);
1462     bounds->setLTRB(std::min(min[0], min[2]), std::min(min[1], min[3]),
1463                     std::max(max[0], max[2]), std::max(max[1], max[3]));
1464 }
1465 
1466 // test to see if point p is in triangle p0p1p2.
1467 // for now assuming strictly inside -- if on the edge it's outside
point_in_triangle(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const SkPoint & p)1468 static bool point_in_triangle(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1469                               const SkPoint& p) {
1470     SkVector v0 = p1 - p0;
1471     SkVector v1 = p2 - p1;
1472     SkScalar n = v0.cross(v1);
1473 
1474     SkVector w0 = p - p0;
1475     if (n*v0.cross(w0) < SK_ScalarNearlyZero) {
1476         return false;
1477     }
1478 
1479     SkVector w1 = p - p1;
1480     if (n*v1.cross(w1) < SK_ScalarNearlyZero) {
1481         return false;
1482     }
1483 
1484     SkVector v2 = p0 - p2;
1485     SkVector w2 = p - p2;
1486     if (n*v2.cross(w2) < SK_ScalarNearlyZero) {
1487         return false;
1488     }
1489 
1490     return true;
1491 }
1492 
1493 // Data structure to track reflex vertices and check whether any are inside a given triangle
1494 class ReflexHash {
1495 public:
init(const SkRect & bounds,int vertexCount)1496     bool init(const SkRect& bounds, int vertexCount) {
1497         fBounds = bounds;
1498         fNumVerts = 0;
1499         SkScalar width = bounds.width();
1500         SkScalar height = bounds.height();
1501         if (!SkScalarIsFinite(width) || !SkScalarIsFinite(height)) {
1502             return false;
1503         }
1504 
1505         // We want vertexCount grid cells, roughly distributed to match the bounds ratio
1506         SkScalar hCount = SkScalarSqrt(sk_ieee_float_divide(vertexCount*width, height));
1507         if (!SkScalarIsFinite(hCount)) {
1508             return false;
1509         }
1510         fHCount = std::max(std::min(SkScalarRoundToInt(hCount), vertexCount), 1);
1511         fVCount = vertexCount/fHCount;
1512         fGridConversion.set(sk_ieee_float_divide(fHCount - 0.001f, width),
1513                             sk_ieee_float_divide(fVCount - 0.001f, height));
1514         if (!fGridConversion.isFinite()) {
1515             return false;
1516         }
1517 
1518         fGrid.setCount(fHCount*fVCount);
1519         for (int i = 0; i < fGrid.count(); ++i) {
1520             fGrid[i].reset();
1521         }
1522 
1523         return true;
1524     }
1525 
add(TriangulationVertex * v)1526     void add(TriangulationVertex* v) {
1527         int index = hash(v);
1528         fGrid[index].addToTail(v);
1529         ++fNumVerts;
1530     }
1531 
remove(TriangulationVertex * v)1532     void remove(TriangulationVertex* v) {
1533         int index = hash(v);
1534         fGrid[index].remove(v);
1535         --fNumVerts;
1536     }
1537 
checkTriangle(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,uint16_t ignoreIndex0,uint16_t ignoreIndex1) const1538     bool checkTriangle(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1539                        uint16_t ignoreIndex0, uint16_t ignoreIndex1) const {
1540         if (!fNumVerts) {
1541             return false;
1542         }
1543 
1544         SkRect triBounds;
1545         compute_triangle_bounds(p0, p1, p2, &triBounds);
1546         int h0 = (triBounds.fLeft - fBounds.fLeft)*fGridConversion.fX;
1547         int h1 = (triBounds.fRight - fBounds.fLeft)*fGridConversion.fX;
1548         int v0 = (triBounds.fTop - fBounds.fTop)*fGridConversion.fY;
1549         int v1 = (triBounds.fBottom - fBounds.fTop)*fGridConversion.fY;
1550 
1551         for (int v = v0; v <= v1; ++v) {
1552             for (int h = h0; h <= h1; ++h) {
1553                 int i = v * fHCount + h;
1554                 for (SkTInternalLList<TriangulationVertex>::Iter reflexIter = fGrid[i].begin();
1555                      reflexIter != fGrid[i].end(); ++reflexIter) {
1556                     TriangulationVertex* reflexVertex = *reflexIter;
1557                     if (reflexVertex->fIndex != ignoreIndex0 &&
1558                         reflexVertex->fIndex != ignoreIndex1 &&
1559                         point_in_triangle(p0, p1, p2, reflexVertex->fPosition)) {
1560                         return true;
1561                     }
1562                 }
1563 
1564             }
1565         }
1566 
1567         return false;
1568     }
1569 
1570 private:
hash(TriangulationVertex * vert) const1571     int hash(TriangulationVertex* vert) const {
1572         int h = (vert->fPosition.fX - fBounds.fLeft)*fGridConversion.fX;
1573         int v = (vert->fPosition.fY - fBounds.fTop)*fGridConversion.fY;
1574         SkASSERT(v*fHCount + h >= 0);
1575         return v*fHCount + h;
1576     }
1577 
1578     SkRect fBounds;
1579     int fHCount;
1580     int fVCount;
1581     int fNumVerts;
1582     // converts distance from the origin to a grid location (when cast to int)
1583     SkVector fGridConversion;
1584     SkTDArray<SkTInternalLList<TriangulationVertex>> fGrid;
1585 };
1586 
1587 // Check to see if a reflex vertex has become a convex vertex after clipping an ear
reclassify_vertex(TriangulationVertex * p,const SkPoint * polygonVerts,int winding,ReflexHash * reflexHash,SkTInternalLList<TriangulationVertex> * convexList)1588 static void reclassify_vertex(TriangulationVertex* p, const SkPoint* polygonVerts,
1589                               int winding, ReflexHash* reflexHash,
1590                               SkTInternalLList<TriangulationVertex>* convexList) {
1591     if (TriangulationVertex::VertexType::kReflex == p->fVertexType) {
1592         SkVector v0 = p->fPosition - polygonVerts[p->fPrevIndex];
1593         SkVector v1 = polygonVerts[p->fNextIndex] - p->fPosition;
1594         if (winding*v0.cross(v1) > SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
1595             p->fVertexType = TriangulationVertex::VertexType::kConvex;
1596             reflexHash->remove(p);
1597             p->fPrev = p->fNext = nullptr;
1598             convexList->addToTail(p);
1599         }
1600     }
1601 }
1602 
SkTriangulateSimplePolygon(const SkPoint * polygonVerts,uint16_t * indexMap,int polygonSize,SkTDArray<uint16_t> * triangleIndices)1603 bool SkTriangulateSimplePolygon(const SkPoint* polygonVerts, uint16_t* indexMap, int polygonSize,
1604                                 SkTDArray<uint16_t>* triangleIndices) {
1605     if (polygonSize < 3) {
1606         return false;
1607     }
1608     // need to be able to represent all the vertices in the 16-bit indices
1609     if (polygonSize >= std::numeric_limits<uint16_t>::max()) {
1610         return false;
1611     }
1612 
1613     // get bounds
1614     SkRect bounds;
1615     if (!bounds.setBoundsCheck(polygonVerts, polygonSize)) {
1616         return false;
1617     }
1618     // get winding direction
1619     // TODO: we do this for all the polygon routines -- might be better to have the client
1620     // compute it and pass it in
1621     int winding = SkGetPolygonWinding(polygonVerts, polygonSize);
1622     if (0 == winding) {
1623         return false;
1624     }
1625 
1626     // Set up vertices
1627     SkAutoSTArray<64, TriangulationVertex> triangulationVertices(polygonSize);
1628     int prevIndex = polygonSize - 1;
1629     SkVector v0 = polygonVerts[0] - polygonVerts[prevIndex];
1630     for (int currIndex = 0; currIndex < polygonSize; ++currIndex) {
1631         int nextIndex = (currIndex + 1) % polygonSize;
1632 
1633         triangulationVertices[currIndex] = TriangulationVertex{};
1634         triangulationVertices[currIndex].fPosition = polygonVerts[currIndex];
1635         triangulationVertices[currIndex].fIndex = currIndex;
1636         triangulationVertices[currIndex].fPrevIndex = prevIndex;
1637         triangulationVertices[currIndex].fNextIndex = nextIndex;
1638         SkVector v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
1639         if (winding*v0.cross(v1) > SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
1640             triangulationVertices[currIndex].fVertexType = TriangulationVertex::VertexType::kConvex;
1641         } else {
1642             triangulationVertices[currIndex].fVertexType = TriangulationVertex::VertexType::kReflex;
1643         }
1644 
1645         prevIndex = currIndex;
1646         v0 = v1;
1647     }
1648 
1649     // Classify initial vertices into a list of convex vertices and a hash of reflex vertices
1650     // TODO: possibly sort the convexList in some way to get better triangles
1651     SkTInternalLList<TriangulationVertex> convexList;
1652     ReflexHash reflexHash;
1653     if (!reflexHash.init(bounds, polygonSize)) {
1654         return false;
1655     }
1656     prevIndex = polygonSize - 1;
1657     for (int currIndex = 0; currIndex < polygonSize; prevIndex = currIndex, ++currIndex) {
1658         TriangulationVertex::VertexType currType = triangulationVertices[currIndex].fVertexType;
1659         if (TriangulationVertex::VertexType::kConvex == currType) {
1660             int nextIndex = (currIndex + 1) % polygonSize;
1661             TriangulationVertex::VertexType prevType = triangulationVertices[prevIndex].fVertexType;
1662             TriangulationVertex::VertexType nextType = triangulationVertices[nextIndex].fVertexType;
1663             // We prioritize clipping vertices with neighboring reflex vertices.
1664             // The intent here is that it will cull reflex vertices more quickly.
1665             if (TriangulationVertex::VertexType::kReflex == prevType ||
1666                 TriangulationVertex::VertexType::kReflex == nextType) {
1667                 convexList.addToHead(&triangulationVertices[currIndex]);
1668             } else {
1669                 convexList.addToTail(&triangulationVertices[currIndex]);
1670             }
1671         } else {
1672             // We treat near collinear vertices as reflex
1673             reflexHash.add(&triangulationVertices[currIndex]);
1674         }
1675     }
1676 
1677     // The general concept: We are trying to find three neighboring vertices where
1678     // no other vertex lies inside the triangle (an "ear"). If we find one, we clip
1679     // that ear off, and then repeat on the new polygon. Once we get down to three vertices
1680     // we have triangulated the entire polygon.
1681     // In the worst case this is an n^2 algorithm. We can cut down the search space somewhat by
1682     // noting that only convex vertices can be potential ears, and we only need to check whether
1683     // any reflex vertices lie inside the ear.
1684     triangleIndices->setReserve(triangleIndices->count() + 3 * (polygonSize - 2));
1685     int vertexCount = polygonSize;
1686     while (vertexCount > 3) {
1687         bool success = false;
1688         TriangulationVertex* earVertex = nullptr;
1689         TriangulationVertex* p0 = nullptr;
1690         TriangulationVertex* p2 = nullptr;
1691         // find a convex vertex to clip
1692         for (SkTInternalLList<TriangulationVertex>::Iter convexIter = convexList.begin();
1693              convexIter != convexList.end(); ++convexIter) {
1694             earVertex = *convexIter;
1695             SkASSERT(TriangulationVertex::VertexType::kReflex != earVertex->fVertexType);
1696 
1697             p0 = &triangulationVertices[earVertex->fPrevIndex];
1698             p2 = &triangulationVertices[earVertex->fNextIndex];
1699 
1700             // see if any reflex vertices are inside the ear
1701             bool failed = reflexHash.checkTriangle(p0->fPosition, earVertex->fPosition,
1702                                                    p2->fPosition, p0->fIndex, p2->fIndex);
1703             if (failed) {
1704                 continue;
1705             }
1706 
1707             // found one we can clip
1708             success = true;
1709             break;
1710         }
1711         // If we can't find any ears to clip, this probably isn't a simple polygon
1712         if (!success) {
1713             return false;
1714         }
1715 
1716         // add indices
1717         auto indices = triangleIndices->append(3);
1718         indices[0] = indexMap[p0->fIndex];
1719         indices[1] = indexMap[earVertex->fIndex];
1720         indices[2] = indexMap[p2->fIndex];
1721 
1722         // clip the ear
1723         convexList.remove(earVertex);
1724         --vertexCount;
1725 
1726         // reclassify reflex verts
1727         p0->fNextIndex = earVertex->fNextIndex;
1728         reclassify_vertex(p0, polygonVerts, winding, &reflexHash, &convexList);
1729 
1730         p2->fPrevIndex = earVertex->fPrevIndex;
1731         reclassify_vertex(p2, polygonVerts, winding, &reflexHash, &convexList);
1732     }
1733 
1734     // output indices
1735     for (SkTInternalLList<TriangulationVertex>::Iter vertexIter = convexList.begin();
1736          vertexIter != convexList.end(); ++vertexIter) {
1737         TriangulationVertex* vertex = *vertexIter;
1738         *triangleIndices->push() = indexMap[vertex->fIndex];
1739     }
1740 
1741     return true;
1742 }
1743 
1744 ///////////
1745 
crs(SkVector a,SkVector b)1746 static double crs(SkVector a, SkVector b) {
1747     return a.fX * b.fY - a.fY * b.fX;
1748 }
1749 
sign(SkScalar v)1750 static int sign(SkScalar v) {
1751     return v < 0 ? -1 : (v > 0);
1752 }
1753 
1754 struct SignTracker {
1755     int fSign;
1756     int fSignChanges;
1757 
resetSignTracker1758     void reset() {
1759         fSign = 0;
1760         fSignChanges = 0;
1761     }
1762 
initSignTracker1763     void init(int s) {
1764         SkASSERT(fSignChanges == 0);
1765         SkASSERT(s == 1 || s == -1 || s == 0);
1766         fSign = s;
1767         fSignChanges = 1;
1768     }
1769 
updateSignTracker1770     void update(int s) {
1771         if (s) {
1772             if (fSign != s) {
1773                 fSignChanges += 1;
1774                 fSign = s;
1775             }
1776         }
1777     }
1778 };
1779 
1780 struct ConvexTracker {
1781     SkVector    fFirst, fPrev;
1782     SignTracker fDSign, fCSign;
1783     int         fVecCounter;
1784     bool        fIsConcave;
1785 
ConvexTrackerConvexTracker1786     ConvexTracker() { this->reset(); }
1787 
resetConvexTracker1788     void reset() {
1789         fPrev = {0, 0};
1790         fDSign.reset();
1791         fCSign.reset();
1792         fVecCounter = 0;
1793         fIsConcave = false;
1794     }
1795 
addVecConvexTracker1796     void addVec(SkPoint p1, SkPoint p0) {
1797         this->addVec(p1 - p0);
1798     }
addVecConvexTracker1799     void addVec(SkVector v) {
1800         if (v.fX == 0 && v.fY == 0) {
1801             return;
1802         }
1803 
1804         fVecCounter += 1;
1805         if (fVecCounter == 1) {
1806             fFirst = fPrev = v;
1807             fDSign.update(sign(v.fX));
1808             return;
1809         }
1810 
1811         SkScalar d = v.fX;
1812         SkScalar c = crs(fPrev, v);
1813         int sign_c;
1814         if (c) {
1815             sign_c = sign(c);
1816         } else {
1817             if (d >= 0) {
1818                 sign_c = fCSign.fSign;
1819             } else {
1820                 sign_c = -fCSign.fSign;
1821             }
1822         }
1823 
1824         fDSign.update(sign(d));
1825         fCSign.update(sign_c);
1826         fPrev = v;
1827 
1828         if (fDSign.fSignChanges > 3 || fCSign.fSignChanges > 1) {
1829             fIsConcave = true;
1830         }
1831     }
1832 
finalCrossConvexTracker1833     void finalCross() {
1834         this->addVec(fFirst);
1835     }
1836 };
1837 
SkIsPolyConvex_experimental(const SkPoint pts[],int count)1838 bool SkIsPolyConvex_experimental(const SkPoint pts[], int count) {
1839     if (count <= 3) {
1840         return true;
1841     }
1842 
1843     ConvexTracker tracker;
1844 
1845     for (int i = 0; i < count - 1; ++i) {
1846         tracker.addVec(pts[i + 1], pts[i]);
1847         if (tracker.fIsConcave) {
1848             return false;
1849         }
1850     }
1851     tracker.addVec(pts[0], pts[count - 1]);
1852     tracker.finalCross();
1853     return !tracker.fIsConcave;
1854 }
1855 
1856