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