blob: 47b41250e2f5578e1b5c3ddc713a939775593ca0 [file] [log] [blame]
Brian Salomonab664fa2017-03-24 16:07:20 +00001/*
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
Jim Van Verth41964ed2018-03-28 10:10:30 -04008#include "SkOffsetPolygon.h"
Brian Salomonab664fa2017-03-24 16:07:20 +00009
Cary Clarkdf429f32017-11-08 11:44:31 -050010#include "SkPointPriv.h"
Jim Van Verth4db18ed2018-04-03 10:00:37 -040011#include "SkTArray.h"
Brian Salomonab664fa2017-03-24 16:07:20 +000012#include "SkTemplates.h"
Jim Van Verth4db18ed2018-04-03 10:00:37 -040013#include "SkTDPQueue.h"
Brian Salomonab664fa2017-03-24 16:07:20 +000014
Jim Van Verth4db18ed2018-04-03 10:00:37 -040015struct OffsetSegment {
Brian Salomonab664fa2017-03-24 16:07:20 +000016 SkPoint fP0;
17 SkPoint fP1;
18};
19
20// Computes perpDot for point compared to segment.
21// A positive value means the point is to the left of the segment,
22// negative is to the right, 0 is collinear.
23static int compute_side(const SkPoint& s0, const SkPoint& s1, const SkPoint& p) {
24 SkVector v0 = s1 - s0;
25 SkVector v1 = p - s0;
26 SkScalar perpDot = v0.cross(v1);
27 if (!SkScalarNearlyZero(perpDot)) {
28 return ((perpDot > 0) ? 1 : -1);
29 }
30
31 return 0;
32}
33
34// returns 1 for ccw, -1 for cw and 0 if degenerate
35static int get_winding(const SkPoint* polygonVerts, int polygonSize) {
36 SkPoint p0 = polygonVerts[0];
37 SkPoint p1 = polygonVerts[1];
38
39 for (int i = 2; i < polygonSize; ++i) {
40 SkPoint p2 = polygonVerts[i];
41
42 // determine if cw or ccw
43 int side = compute_side(p0, p1, p2);
44 if (0 != side) {
45 return ((side > 0) ? 1 : -1);
46 }
47
48 // if nearly collinear, treat as straight line and continue
49 p1 = p2;
50 }
51
52 return 0;
53}
54
Jim Van Verthda965502017-04-11 15:29:14 -040055// Offset line segment p0-p1 'd0' and 'd1' units in the direction specified by 'side'
56bool SkOffsetSegment(const SkPoint& p0, const SkPoint& p1, SkScalar d0, SkScalar d1,
57 int side, SkPoint* offset0, SkPoint* offset1) {
58 SkASSERT(side == -1 || side == 1);
59 SkVector perp = SkVector::Make(p0.fY - p1.fY, p1.fX - p0.fX);
60 if (SkScalarNearlyEqual(d0, d1)) {
61 // if distances are equal, can just outset by the perpendicular
62 perp.setLength(d0*side);
63 *offset0 = p0 + perp;
64 *offset1 = p1 + perp;
65 } else {
66 // Otherwise we need to compute the outer tangent.
67 // See: http://www.ambrsoft.com/TrigoCalc/Circles2/Circles2Tangent_.htm
68 if (d0 < d1) {
69 side = -side;
70 }
71 SkScalar dD = d0 - d1;
72 // if one circle is inside another, we can't compute an offset
Cary Clarkdf429f32017-11-08 11:44:31 -050073 if (dD*dD >= SkPointPriv::DistanceToSqd(p0, p1)) {
Jim Van Verthda965502017-04-11 15:29:14 -040074 return false;
75 }
76 SkPoint outerTangentIntersect = SkPoint::Make((p1.fX*d0 - p0.fX*d1) / dD,
77 (p1.fY*d0 - p0.fY*d1) / dD);
78
79 SkScalar d0sq = d0*d0;
80 SkVector dP = outerTangentIntersect - p0;
Cary Clarkdf429f32017-11-08 11:44:31 -050081 SkScalar dPlenSq = SkPointPriv::LengthSqd(dP);
Jim Van Verthda965502017-04-11 15:29:14 -040082 SkScalar discrim = SkScalarSqrt(dPlenSq - d0sq);
83 offset0->fX = p0.fX + (d0sq*dP.fX - side*d0*dP.fY*discrim) / dPlenSq;
84 offset0->fY = p0.fY + (d0sq*dP.fY + side*d0*dP.fX*discrim) / dPlenSq;
85
86 SkScalar d1sq = d1*d1;
87 dP = outerTangentIntersect - p1;
Cary Clarkdf429f32017-11-08 11:44:31 -050088 dPlenSq = SkPointPriv::LengthSqd(dP);
Jim Van Verthda965502017-04-11 15:29:14 -040089 discrim = SkScalarSqrt(dPlenSq - d1sq);
90 offset1->fX = p1.fX + (d1sq*dP.fX - side*d1*dP.fY*discrim) / dPlenSq;
91 offset1->fY = p1.fY + (d1sq*dP.fY + side*d1*dP.fX*discrim) / dPlenSq;
92 }
93
94 return true;
Brian Salomonab664fa2017-03-24 16:07:20 +000095}
96
97// Compute the intersection 'p' between segments s0 and s1, if any.
98// 's' is the parametric value for the intersection along 's0' & 't' is the same for 's1'.
99// Returns false if there is no intersection.
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400100static bool compute_intersection(const OffsetSegment& s0, const OffsetSegment& s1,
Brian Salomonab664fa2017-03-24 16:07:20 +0000101 SkPoint* p, SkScalar* s, SkScalar* t) {
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400102 // Common cases for polygon chains -- check if endpoints are touching
103 if (SkPointPriv::EqualsWithinTolerance(s0.fP1, s1.fP0)) {
104 *p = s0.fP1;
105 *s = SK_Scalar1;
106 *t = 0;
107 return true;
108 }
109 if (SkPointPriv::EqualsWithinTolerance(s1.fP1, s0.fP0)) {
110 *p = s1.fP1;
111 *s = 0;
112 *t = SK_Scalar1;
113 return true;
114 }
115
Brian Salomonab664fa2017-03-24 16:07:20 +0000116 SkVector v0 = s0.fP1 - s0.fP0;
117 SkVector v1 = s1.fP1 - s1.fP0;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400118 // We should have culled coincident points before this
119 SkASSERT(!SkPointPriv::EqualsWithinTolerance(s0.fP0, s0.fP1));
120 SkASSERT(!SkPointPriv::EqualsWithinTolerance(s1.fP0, s1.fP1));
Brian Salomonab664fa2017-03-24 16:07:20 +0000121
122 SkVector d = s1.fP0 - s0.fP0;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400123 SkScalar perpDot = v0.cross(v1);
124 SkScalar localS, localT;
125 if (SkScalarNearlyZero(perpDot)) {
126 // segments are parallel, but not collinear
127 if (!SkScalarNearlyZero(d.dot(d), SK_ScalarNearlyZero*SK_ScalarNearlyZero)) {
128 return false;
129 }
130
131 // project segment1's endpoints onto segment0
132 localS = d.fX / v0.fX;
133 localT = 0;
134 if (localS < 0 || localS > SK_Scalar1) {
135 // the first endpoint doesn't lie on segment0, try the other one
136 SkScalar oldLocalS = localS;
137 localS = (s1.fP1.fX - s0.fP0.fX) / v0.fX;
138 localT = SK_Scalar1;
139 if (localS < 0 || localS > SK_Scalar1) {
140 // it's possible that segment1's interval surrounds segment0
141 // this is false if the params have the same signs, and in that case no collision
142 if (localS*oldLocalS > 0) {
143 return false;
144 }
145 // otherwise project segment0's endpoint onto segment1 instead
146 localS = 0;
147 localT = -d.fX / v1.fX;
148 }
149 }
150 } else {
151 localS = d.cross(v1) / perpDot;
152 if (localS < 0 || localS > SK_Scalar1) {
153 return false;
154 }
155 localT = d.cross(v0) / perpDot;
156 if (localT < 0 || localT > SK_Scalar1) {
157 return false;
158 }
Brian Salomonab664fa2017-03-24 16:07:20 +0000159 }
160
161 v0 *= localS;
162 *p = s0.fP0 + v0;
163 *s = localS;
164 *t = localT;
165
166 return true;
167}
168
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400169// computes the line intersection and then the distance to s0's endpoint
170static SkScalar compute_crossing_distance(const OffsetSegment& s0, const OffsetSegment& s1) {
171 SkVector v0 = s0.fP1 - s0.fP0;
172 SkVector v1 = s1.fP1 - s1.fP0;
173
174 SkScalar perpDot = v0.cross(v1);
175 if (SkScalarNearlyZero(perpDot)) {
176 // segments are parallel
177 return SK_ScalarMax;
178 }
179
180 SkVector d = s1.fP0 - s0.fP0;
181 SkScalar localS = d.cross(v1) / perpDot;
182 if (localS < 0) {
183 localS = -localS;
184 } else {
185 localS -= SK_Scalar1;
186 }
187
188 localS *= v0.length();
189
190 return localS;
191}
192
Jim Van Verth0513f142017-03-24 14:28:57 -0400193static bool is_convex(const SkTDArray<SkPoint>& poly) {
194 if (poly.count() <= 3) {
195 return true;
196 }
197
198 SkVector v0 = poly[0] - poly[poly.count() - 1];
199 SkVector v1 = poly[1] - poly[poly.count() - 1];
200 SkScalar winding = v0.cross(v1);
201
202 for (int i = 0; i < poly.count() - 1; ++i) {
203 int j = i + 1;
204 int k = (i + 2) % poly.count();
205
206 SkVector v0 = poly[j] - poly[i];
207 SkVector v1 = poly[k] - poly[i];
208 SkScalar perpDot = v0.cross(v1);
Jim Van Verth291932e2017-03-29 14:37:28 -0400209 if (winding*perpDot < 0) {
Jim Van Verth0513f142017-03-24 14:28:57 -0400210 return false;
211 }
212 }
213
214 return true;
215}
Jim Van Verth0513f142017-03-24 14:28:57 -0400216
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400217struct EdgeData {
218 OffsetSegment fInset;
219 SkPoint fIntersection;
220 SkScalar fTValue;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400221 uint16_t fStart;
222 uint16_t fEnd;
223 uint16_t fIndex;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400224 bool fValid;
225
226 void init() {
227 fIntersection = fInset.fP0;
228 fTValue = SK_ScalarMin;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400229 fStart = 0;
230 fEnd = 0;
231 fIndex = 0;
232 fValid = true;
233 }
234
235 void init(uint16_t start, uint16_t end) {
236 fIntersection = fInset.fP0;
237 fTValue = SK_ScalarMin;
238 fStart = start;
239 fEnd = end;
240 fIndex = start;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400241 fValid = true;
242 }
243};
244
Brian Salomonab664fa2017-03-24 16:07:20 +0000245// The objective here is to inset all of the edges by the given distance, and then
246// remove any invalid inset edges by detecting right-hand turns. In a ccw polygon,
247// we should only be making left-hand turns (for cw polygons, we use the winding
248// parameter to reverse this). We detect this by checking whether the second intersection
249// on an edge is closer to its tail than the first one.
250//
251// We might also have the case that there is no intersection between two neighboring inset edges.
252// In this case, one edge will lie to the right of the other and should be discarded along with
253// its previous intersection (if any).
254//
255// Note: the assumption is that inputPolygon is convex and has no coincident points.
256//
257bool SkInsetConvexPolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
Jim Van Verthda965502017-04-11 15:29:14 -0400258 std::function<SkScalar(int index)> insetDistanceFunc,
259 SkTDArray<SkPoint>* insetPolygon) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000260 if (inputPolygonSize < 3) {
261 return false;
262 }
263
264 int winding = get_winding(inputPolygonVerts, inputPolygonSize);
265 if (0 == winding) {
266 return false;
267 }
268
269 // set up
Brian Salomonab664fa2017-03-24 16:07:20 +0000270 SkAutoSTMalloc<64, EdgeData> edgeData(inputPolygonSize);
271 for (int i = 0; i < inputPolygonSize; ++i) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000272 int j = (i + 1) % inputPolygonSize;
Jim Van Verthb55eb282017-07-18 14:13:45 -0400273 int k = (i + 2) % inputPolygonSize;
274 // check for convexity just to be sure
275 if (compute_side(inputPolygonVerts[i], inputPolygonVerts[j],
276 inputPolygonVerts[k])*winding < 0) {
277 return false;
278 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400279 if (!SkOffsetSegment(inputPolygonVerts[i], inputPolygonVerts[j],
280 insetDistanceFunc(i), insetDistanceFunc(j),
281 winding,
282 &edgeData[i].fInset.fP0, &edgeData[i].fInset.fP1)) {
283 return false;
284 }
285 edgeData[i].init();
Brian Salomonab664fa2017-03-24 16:07:20 +0000286 }
287
288 int prevIndex = inputPolygonSize - 1;
289 int currIndex = 0;
290 int insetVertexCount = inputPolygonSize;
291 while (prevIndex != currIndex) {
292 if (!edgeData[prevIndex].fValid) {
293 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
294 continue;
295 }
296
297 SkScalar s, t;
298 SkPoint intersection;
299 if (compute_intersection(edgeData[prevIndex].fInset, edgeData[currIndex].fInset,
300 &intersection, &s, &t)) {
301 // if new intersection is further back on previous inset from the prior intersection
302 if (s < edgeData[prevIndex].fTValue) {
303 // no point in considering this one again
304 edgeData[prevIndex].fValid = false;
305 --insetVertexCount;
306 // go back one segment
307 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
308 // we've already considered this intersection, we're done
309 } else if (edgeData[currIndex].fTValue > SK_ScalarMin &&
Cary Clarkdf429f32017-11-08 11:44:31 -0500310 SkPointPriv::EqualsWithinTolerance(intersection,
311 edgeData[currIndex].fIntersection,
Brian Salomonab664fa2017-03-24 16:07:20 +0000312 1.0e-6f)) {
313 break;
314 } else {
315 // add intersection
316 edgeData[currIndex].fIntersection = intersection;
317 edgeData[currIndex].fTValue = t;
318
319 // go to next segment
320 prevIndex = currIndex;
321 currIndex = (currIndex + 1) % inputPolygonSize;
322 }
323 } else {
324 // if prev to right side of curr
325 int side = winding*compute_side(edgeData[currIndex].fInset.fP0,
326 edgeData[currIndex].fInset.fP1,
327 edgeData[prevIndex].fInset.fP1);
328 if (side < 0 && side == winding*compute_side(edgeData[currIndex].fInset.fP0,
329 edgeData[currIndex].fInset.fP1,
330 edgeData[prevIndex].fInset.fP0)) {
331 // no point in considering this one again
332 edgeData[prevIndex].fValid = false;
333 --insetVertexCount;
334 // go back one segment
335 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
336 } else {
337 // move to next segment
338 edgeData[currIndex].fValid = false;
339 --insetVertexCount;
340 currIndex = (currIndex + 1) % inputPolygonSize;
341 }
342 }
343 }
344
Jim Van Verthda965502017-04-11 15:29:14 -0400345 // store all the valid intersections that aren't nearly coincident
346 // TODO: look at the main algorithm and see if we can detect these better
347 static constexpr SkScalar kCleanupTolerance = 0.01f;
348
Brian Salomonab664fa2017-03-24 16:07:20 +0000349 insetPolygon->reset();
Mike Klein23e45442018-04-19 09:29:02 -0400350 if (insetVertexCount >= 0) {
351 insetPolygon->setReserve(insetVertexCount);
352 }
Jim Van Verthda965502017-04-11 15:29:14 -0400353 currIndex = -1;
Brian Salomonab664fa2017-03-24 16:07:20 +0000354 for (int i = 0; i < inputPolygonSize; ++i) {
Jim Van Verthda965502017-04-11 15:29:14 -0400355 if (edgeData[i].fValid && (currIndex == -1 ||
Cary Clarkdf429f32017-11-08 11:44:31 -0500356 !SkPointPriv::EqualsWithinTolerance(edgeData[i].fIntersection,
357 (*insetPolygon)[currIndex],
358 kCleanupTolerance))) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000359 *insetPolygon->push() = edgeData[i].fIntersection;
Jim Van Verthda965502017-04-11 15:29:14 -0400360 currIndex++;
Brian Salomonab664fa2017-03-24 16:07:20 +0000361 }
362 }
Jim Van Verthda965502017-04-11 15:29:14 -0400363 // make sure the first and last points aren't coincident
364 if (currIndex >= 1 &&
Cary Clarkdf429f32017-11-08 11:44:31 -0500365 SkPointPriv::EqualsWithinTolerance((*insetPolygon)[0], (*insetPolygon)[currIndex],
366 kCleanupTolerance)) {
Jim Van Verthda965502017-04-11 15:29:14 -0400367 insetPolygon->pop();
368 }
Brian Salomonab664fa2017-03-24 16:07:20 +0000369
Jim Van Verthb55eb282017-07-18 14:13:45 -0400370 return (insetPolygon->count() >= 3 && is_convex(*insetPolygon));
Brian Salomonab664fa2017-03-24 16:07:20 +0000371}
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400372
373// compute the number of points needed for a circular join when offsetting a reflex vertex
374static void compute_radial_steps(const SkVector& v1, const SkVector& v2, SkScalar r,
375 SkScalar* rotSin, SkScalar* rotCos, int* n) {
376 const SkScalar kRecipPixelsPerArcSegment = 0.25f;
377
378 SkScalar rCos = v1.dot(v2);
379 SkScalar rSin = v1.cross(v2);
380 SkScalar theta = SkScalarATan2(rSin, rCos);
381
382 int steps = SkScalarRoundToInt(SkScalarAbs(r*theta*kRecipPixelsPerArcSegment));
383
384 SkScalar dTheta = theta / steps;
385 *rotSin = SkScalarSinCos(dTheta, rotCos);
386 *n = steps;
387}
388
389// tolerant less-than comparison
390static inline bool nearly_lt(SkScalar a, SkScalar b, SkScalar tolerance = SK_ScalarNearlyZero) {
391 return a < b - tolerance;
392}
393
394// a point is "left" to another if its x coordinate is less, or if equal, its y coordinate
395static bool left(const SkPoint& p0, const SkPoint& p1) {
396 return nearly_lt(p0.fX, p1.fX) ||
397 (SkScalarNearlyEqual(p0.fX, p1.fX) && nearly_lt(p0.fY, p1.fY));
398}
399
400struct Vertex {
401 static bool Left(const Vertex& qv0, const Vertex& qv1) {
402 return left(qv0.fPosition, qv1.fPosition);
403 }
404 // packed to fit into 16 bytes (one cache line)
405 SkPoint fPosition;
406 uint16_t fIndex; // index in unsorted polygon
407 uint16_t fPrevIndex; // indices for previous and next vertex in unsorted polygon
408 uint16_t fNextIndex;
409 uint16_t fFlags;
410};
411
412enum VertexFlags {
413 kPrevLeft_VertexFlag = 0x1,
414 kNextLeft_VertexFlag = 0x2,
415};
416
417struct Edge {
418 // returns true if "this" is above "that"
419 bool above(const Edge& that, SkScalar tolerance = SK_ScalarNearlyZero) {
420 SkASSERT(nearly_lt(this->fSegment.fP0.fX, that.fSegment.fP0.fX, tolerance) ||
421 SkScalarNearlyEqual(this->fSegment.fP0.fX, that.fSegment.fP0.fX, tolerance));
422 // The idea here is that if the vector between the origins of the two segments (dv)
423 // rotates counterclockwise up to the vector representing the "this" segment (u),
424 // then we know that "this" is above that. If the result is clockwise we say it's below.
425 SkVector dv = that.fSegment.fP0 - this->fSegment.fP0;
426 SkVector u = this->fSegment.fP1 - this->fSegment.fP0;
427 SkScalar cross = dv.cross(u);
428 if (cross > tolerance) {
429 return true;
430 } else if (cross < -tolerance) {
431 return false;
432 }
433 // If the result is 0 then either the two origins are equal or the origin of "that"
434 // lies on dv. So then we try the same for the vector from the tail of "this"
435 // to the head of "that". Again, ccw means "this" is above "that".
436 dv = that.fSegment.fP1 - this->fSegment.fP0;
437 return (dv.cross(u) > tolerance);
438 }
439
440 bool intersect(const Edge& that) const {
441 SkPoint intersection;
442 SkScalar s, t;
443 // check first to see if these edges are neighbors in the polygon
444 if (this->fIndex0 == that.fIndex0 || this->fIndex1 == that.fIndex0 ||
445 this->fIndex0 == that.fIndex1 || this->fIndex1 == that.fIndex1) {
446 return false;
447 }
448 return compute_intersection(this->fSegment, that.fSegment, &intersection, &s, &t);
449 }
450
451 bool operator==(const Edge& that) const {
452 return (this->fIndex0 == that.fIndex0 && this->fIndex1 == that.fIndex1);
453 }
454
455 bool operator!=(const Edge& that) const {
456 return !operator==(that);
457 }
458
459 OffsetSegment fSegment;
460 int32_t fIndex0; // indices for previous and next vertex
461 int32_t fIndex1;
462};
463
464class EdgeList {
465public:
466 void reserve(int count) { fEdges.reserve(count); }
467
468 bool insert(const Edge& newEdge) {
469 // linear search for now (expected case is very few active edges)
470 int insertIndex = 0;
471 while (insertIndex < fEdges.count() && fEdges[insertIndex].above(newEdge)) {
472 ++insertIndex;
473 }
474 // if we intersect with the existing edge above or below us
475 // then we know this polygon is not simple, so don't insert, just fail
476 if (insertIndex > 0 && newEdge.intersect(fEdges[insertIndex - 1])) {
477 return false;
478 }
479 if (insertIndex < fEdges.count() && newEdge.intersect(fEdges[insertIndex])) {
480 return false;
481 }
482
483 fEdges.push_back();
484 for (int i = fEdges.count() - 1; i > insertIndex; --i) {
485 fEdges[i] = fEdges[i - 1];
486 }
487 fEdges[insertIndex] = newEdge;
488
489 return true;
490 }
491
492 bool remove(const Edge& edge) {
493 SkASSERT(fEdges.count() > 0);
494
495 // linear search for now (expected case is very few active edges)
496 int removeIndex = 0;
497 while (removeIndex < fEdges.count() && fEdges[removeIndex] != edge) {
498 ++removeIndex;
499 }
500 // we'd better find it or something is wrong
501 SkASSERT(removeIndex < fEdges.count());
502
503 // if we intersect with the edge above or below us
504 // then we know this polygon is not simple, so don't remove, just fail
505 if (removeIndex > 0 && fEdges[removeIndex].intersect(fEdges[removeIndex-1])) {
506 return false;
507 }
508 if (removeIndex < fEdges.count()-1) {
509 if (fEdges[removeIndex].intersect(fEdges[removeIndex + 1])) {
510 return false;
511 }
512 // copy over the old entry
513 memmove(&fEdges[removeIndex], &fEdges[removeIndex + 1],
514 sizeof(Edge)*(fEdges.count() - removeIndex - 1));
515 }
516
517 fEdges.pop_back();
518 return true;
519 }
520
521private:
522 SkSTArray<1, Edge> fEdges;
523};
524
525// Here we implement a sweep line algorithm to determine whether the provided points
526// represent a simple polygon, i.e., the polygon is non-self-intersecting.
527// We first insert the vertices into a priority queue sorting horizontally from left to right.
528// Then as we pop the vertices from the queue we generate events which indicate that an edge
529// should be added or removed from an edge list. If any intersections are detected in the edge
530// list, then we know the polygon is self-intersecting and hence not simple.
531static bool is_simple_polygon(const SkPoint* polygon, int polygonSize) {
532 SkTDPQueue <Vertex, Vertex::Left> vertexQueue;
533 EdgeList sweepLine;
534
535 sweepLine.reserve(polygonSize);
536 for (int i = 0; i < polygonSize; ++i) {
537 Vertex newVertex;
538 newVertex.fPosition = polygon[i];
539 newVertex.fIndex = i;
540 newVertex.fPrevIndex = (i - 1 + polygonSize) % polygonSize;
541 newVertex.fNextIndex = (i + 1) % polygonSize;
542 newVertex.fFlags = 0;
543 if (left(polygon[newVertex.fPrevIndex], polygon[i])) {
544 newVertex.fFlags |= kPrevLeft_VertexFlag;
545 }
546 if (left(polygon[newVertex.fNextIndex], polygon[i])) {
547 newVertex.fFlags |= kNextLeft_VertexFlag;
548 }
549 vertexQueue.insert(newVertex);
550 }
551
552 // pop each vertex from the queue and generate events depending on
553 // where it lies relative to its neighboring edges
554 while (vertexQueue.count() > 0) {
555 const Vertex& v = vertexQueue.peek();
556
557 // check edge to previous vertex
558 if (v.fFlags & kPrevLeft_VertexFlag) {
559 Edge edge{ { polygon[v.fPrevIndex], v.fPosition }, v.fPrevIndex, v.fIndex };
560 if (!sweepLine.remove(edge)) {
561 break;
562 }
563 } else {
564 Edge edge{ { v.fPosition, polygon[v.fPrevIndex] }, v.fIndex, v.fPrevIndex };
565 if (!sweepLine.insert(edge)) {
566 break;
567 }
568 }
569
570 // check edge to next vertex
571 if (v.fFlags & kNextLeft_VertexFlag) {
572 Edge edge{ { polygon[v.fNextIndex], v.fPosition }, v.fNextIndex, v.fIndex };
573 if (!sweepLine.remove(edge)) {
574 break;
575 }
576 } else {
577 Edge edge{ { v.fPosition, polygon[v.fNextIndex] }, v.fIndex, v.fNextIndex };
578 if (!sweepLine.insert(edge)) {
579 break;
580 }
581 }
582
583 vertexQueue.pop();
584 }
585
586 return (vertexQueue.count() == 0);
587}
588
589// TODO: assuming a constant offset here -- do we want to support variable offset?
590bool SkOffsetSimplePolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
Jim Van Verth872da6b2018-04-10 11:24:11 -0400591 SkScalar offset, SkTDArray<SkPoint>* offsetPolygon,
592 SkTDArray<int>* polygonIndices) {
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400593 if (inputPolygonSize < 3) {
594 return false;
595 }
596
597 if (!is_simple_polygon(inputPolygonVerts, inputPolygonSize)) {
598 return false;
599 }
600
601 // compute area and use sign to determine winding
602 // do initial pass to build normals
603 SkAutoSTMalloc<64, SkVector> normals(inputPolygonSize);
604 SkScalar quadArea = 0;
605 for (int curr = 0; curr < inputPolygonSize; ++curr) {
606 int next = (curr + 1) % inputPolygonSize;
607 SkVector tangent = inputPolygonVerts[next] - inputPolygonVerts[curr];
608 SkVector normal = SkVector::Make(-tangent.fY, tangent.fX);
609 normals[curr] = normal;
610 quadArea += inputPolygonVerts[curr].cross(inputPolygonVerts[next]);
611 }
612 // 1 == ccw, -1 == cw
613 int winding = (quadArea > 0) ? 1 : -1;
614 if (0 == winding) {
615 return false;
616 }
617
618 // resize normals to match offset
619 for (int curr = 0; curr < inputPolygonSize; ++curr) {
620 normals[curr].setLength(winding*offset);
621 }
622
623 // build initial offset edge list
624 SkSTArray<64, EdgeData> edgeData(inputPolygonSize);
625 int prevIndex = inputPolygonSize - 1;
626 int currIndex = 0;
627 int nextIndex = 1;
628 while (currIndex < inputPolygonSize) {
629 int side = compute_side(inputPolygonVerts[prevIndex],
630 inputPolygonVerts[currIndex],
631 inputPolygonVerts[nextIndex]);
632
633 // if reflex point, fill in curve
634 if (side*winding*offset < 0) {
635 SkScalar rotSin, rotCos;
636 int numSteps;
637 SkVector prevNormal = normals[prevIndex];
638 compute_radial_steps(prevNormal, normals[currIndex], SkScalarAbs(offset),
639 &rotSin, &rotCos, &numSteps);
640 for (int i = 0; i < numSteps - 1; ++i) {
641 SkVector currNormal = SkVector::Make(prevNormal.fX*rotCos - prevNormal.fY*rotSin,
642 prevNormal.fY*rotCos + prevNormal.fX*rotSin);
643 EdgeData& edge = edgeData.push_back();
644 edge.fInset.fP0 = inputPolygonVerts[currIndex] + prevNormal;
645 edge.fInset.fP1 = inputPolygonVerts[currIndex] + currNormal;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400646 edge.init(currIndex, currIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400647 prevNormal = currNormal;
648 }
649 EdgeData& edge = edgeData.push_back();
650 edge.fInset.fP0 = inputPolygonVerts[currIndex] + prevNormal;
651 edge.fInset.fP1 = inputPolygonVerts[currIndex] + normals[currIndex];
Jim Van Verth872da6b2018-04-10 11:24:11 -0400652 edge.init(currIndex, currIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400653 }
654
655 // Add the edge
656 EdgeData& edge = edgeData.push_back();
657 edge.fInset.fP0 = inputPolygonVerts[currIndex] + normals[currIndex];
658 edge.fInset.fP1 = inputPolygonVerts[nextIndex] + normals[currIndex];
Jim Van Verth872da6b2018-04-10 11:24:11 -0400659 edge.init(currIndex, nextIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400660
661 prevIndex = currIndex;
662 currIndex++;
663 nextIndex = (nextIndex + 1) % inputPolygonSize;
664 }
665
666 int edgeDataSize = edgeData.count();
667 prevIndex = edgeDataSize - 1;
668 currIndex = 0;
669 int insetVertexCount = edgeDataSize;
670 while (prevIndex != currIndex) {
671 if (!edgeData[prevIndex].fValid) {
672 prevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
673 continue;
674 }
Jim Van Verth872da6b2018-04-10 11:24:11 -0400675 if (!edgeData[currIndex].fValid) {
676 currIndex = (currIndex + 1) % edgeDataSize;
677 continue;
678 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400679
680 SkScalar s, t;
681 SkPoint intersection;
682 if (compute_intersection(edgeData[prevIndex].fInset, edgeData[currIndex].fInset,
683 &intersection, &s, &t)) {
684 // if new intersection is further back on previous inset from the prior intersection
685 if (s < edgeData[prevIndex].fTValue) {
686 // no point in considering this one again
687 edgeData[prevIndex].fValid = false;
688 --insetVertexCount;
689 // go back one segment
690 prevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
691 // we've already considered this intersection, we're done
692 } else if (edgeData[currIndex].fTValue > SK_ScalarMin &&
693 SkPointPriv::EqualsWithinTolerance(intersection,
694 edgeData[currIndex].fIntersection,
695 1.0e-6f)) {
696 break;
697 } else {
698 // add intersection
699 edgeData[currIndex].fIntersection = intersection;
700 edgeData[currIndex].fTValue = t;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400701 edgeData[currIndex].fIndex = edgeData[prevIndex].fEnd;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400702
703 // go to next segment
704 prevIndex = currIndex;
705 currIndex = (currIndex + 1) % edgeDataSize;
706 }
707 } else {
708 // If there is no intersection, we want to minimize the distance between
709 // the point where the segment lines cross and the segments themselves.
710 SkScalar prevPrevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
711 SkScalar currNextIndex = (currIndex + 1) % edgeDataSize;
712 SkScalar dist0 = compute_crossing_distance(edgeData[currIndex].fInset,
713 edgeData[prevPrevIndex].fInset);
714 SkScalar dist1 = compute_crossing_distance(edgeData[prevIndex].fInset,
715 edgeData[currNextIndex].fInset);
716 if (dist0 < dist1) {
717 edgeData[prevIndex].fValid = false;
718 prevIndex = prevPrevIndex;
719 } else {
720 edgeData[currIndex].fValid = false;
721 currIndex = currNextIndex;
722 }
723 --insetVertexCount;
724 }
725 }
726
727 // store all the valid intersections that aren't nearly coincident
728 // TODO: look at the main algorithm and see if we can detect these better
729 static constexpr SkScalar kCleanupTolerance = 0.01f;
730
731 offsetPolygon->reset();
732 offsetPolygon->setReserve(insetVertexCount);
733 currIndex = -1;
734 for (int i = 0; i < edgeData.count(); ++i) {
735 if (edgeData[i].fValid && (currIndex == -1 ||
736 !SkPointPriv::EqualsWithinTolerance(edgeData[i].fIntersection,
737 (*offsetPolygon)[currIndex],
738 kCleanupTolerance))) {
739 *offsetPolygon->push() = edgeData[i].fIntersection;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400740 if (polygonIndices) {
741 *polygonIndices->push() = edgeData[i].fIndex;
742 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400743 currIndex++;
744 }
745 }
746 // make sure the first and last points aren't coincident
747 if (currIndex >= 1 &&
748 SkPointPriv::EqualsWithinTolerance((*offsetPolygon)[0], (*offsetPolygon)[currIndex],
749 kCleanupTolerance)) {
750 offsetPolygon->pop();
Jim Van Verth872da6b2018-04-10 11:24:11 -0400751 if (polygonIndices) {
752 polygonIndices->pop();
753 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400754 }
755
756 // compute signed area to check winding (it should be same as the original polygon)
757 quadArea = 0;
758 for (int curr = 0; curr < offsetPolygon->count(); ++curr) {
759 int next = (curr + 1) % offsetPolygon->count();
760 quadArea += (*offsetPolygon)[curr].cross((*offsetPolygon)[next]);
761 }
762
763 return (winding*quadArea > 0 &&
764 is_simple_polygon(offsetPolygon->begin(), offsetPolygon->count()));
765}
766