1 /*
2 * Copyright 2015 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/gpu/ganesh/geometry/GrTriangulator.h"
9
10 #include "include/core/SkPathTypes.h"
11 #include "include/core/SkRect.h"
12 #include "include/private/base/SkDebug.h"
13 #include "include/private/base/SkFloatingPoint.h"
14 #include "include/private/base/SkMath.h"
15 #include "include/private/base/SkTPin.h"
16 #include "src/base/SkVx.h"
17 #include "src/core/SkGeometry.h"
18 #include "src/core/SkPointPriv.h"
19 #include "src/gpu/BufferWriter.h"
20 #include "src/gpu/ganesh/GrColor.h"
21 #include "src/gpu/ganesh/GrEagerVertexAllocator.h"
22 #include "src/gpu/ganesh/geometry/GrPathUtils.h"
23
24 #include <algorithm>
25 #include <cstddef>
26 #include <limits>
27 #include <memory>
28 #include <tuple>
29 #include <utility>
30
31 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
32
33 #if TRIANGULATOR_LOGGING
34 #define TESS_LOG printf
35 #define DUMP_MESH(M) (M).dump()
36 #else
37 #define TESS_LOG(...)
38 #define DUMP_MESH(M)
39 #endif
40
41 using EdgeType = GrTriangulator::EdgeType;
42 using Vertex = GrTriangulator::Vertex;
43 using VertexList = GrTriangulator::VertexList;
44 using Line = GrTriangulator::Line;
45 using Edge = GrTriangulator::Edge;
46 using EdgeList = GrTriangulator::EdgeList;
47 using Poly = GrTriangulator::Poly;
48 using MonotonePoly = GrTriangulator::MonotonePoly;
49 using Comparator = GrTriangulator::Comparator;
50
51 template <class T, T* T::*Prev, T* T::*Next>
list_insert(T * t,T * prev,T * next,T ** head,T ** tail)52 static void list_insert(T* t, T* prev, T* next, T** head, T** tail) {
53 t->*Prev = prev;
54 t->*Next = next;
55 if (prev) {
56 prev->*Next = t;
57 } else if (head) {
58 *head = t;
59 }
60 if (next) {
61 next->*Prev = t;
62 } else if (tail) {
63 *tail = t;
64 }
65 }
66
67 template <class T, T* T::*Prev, T* T::*Next>
list_remove(T * t,T ** head,T ** tail)68 static void list_remove(T* t, T** head, T** tail) {
69 if (t->*Prev) {
70 t->*Prev->*Next = t->*Next;
71 } else if (head) {
72 *head = t->*Next;
73 }
74 if (t->*Next) {
75 t->*Next->*Prev = t->*Prev;
76 } else if (tail) {
77 *tail = t->*Prev;
78 }
79 t->*Prev = t->*Next = nullptr;
80 }
81
82 typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
83
sweep_lt_horiz(const SkPoint & a,const SkPoint & b)84 static bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
85 return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
86 }
87
sweep_lt_vert(const SkPoint & a,const SkPoint & b)88 static bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
89 return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
90 }
91
sweep_lt(const SkPoint & a,const SkPoint & b) const92 bool GrTriangulator::Comparator::sweep_lt(const SkPoint& a, const SkPoint& b) const {
93 return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
94 }
95
emit_vertex(Vertex * v,bool emitCoverage,skgpu::VertexWriter data)96 static inline skgpu::VertexWriter emit_vertex(Vertex* v,
97 bool emitCoverage,
98 skgpu::VertexWriter data) {
99 data << v->fPoint;
100
101 if (emitCoverage) {
102 data << GrNormalizeByteToFloat(v->fAlpha);
103 }
104
105 return data;
106 }
107
emit_triangle(Vertex * v0,Vertex * v1,Vertex * v2,bool emitCoverage,skgpu::VertexWriter data)108 static skgpu::VertexWriter emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2,
109 bool emitCoverage, skgpu::VertexWriter data) {
110 TESS_LOG("emit_triangle %g (%g, %g) %d\n", v0->fID, v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
111 TESS_LOG(" %g (%g, %g) %d\n", v1->fID, v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
112 TESS_LOG(" %g (%g, %g) %d\n", v2->fID, v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
113 #if TRIANGULATOR_WIREFRAME
114 data = emit_vertex(v0, emitCoverage, std::move(data));
115 data = emit_vertex(v1, emitCoverage, std::move(data));
116 data = emit_vertex(v1, emitCoverage, std::move(data));
117 data = emit_vertex(v2, emitCoverage, std::move(data));
118 data = emit_vertex(v2, emitCoverage, std::move(data));
119 data = emit_vertex(v0, emitCoverage, std::move(data));
120 #else
121 data = emit_vertex(v0, emitCoverage, std::move(data));
122 data = emit_vertex(v1, emitCoverage, std::move(data));
123 data = emit_vertex(v2, emitCoverage, std::move(data));
124 #endif
125 return data;
126 }
127
insert(Vertex * v,Vertex * prev,Vertex * next)128 void GrTriangulator::VertexList::insert(Vertex* v, Vertex* prev, Vertex* next) {
129 list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
130 }
131
remove(Vertex * v)132 void GrTriangulator::VertexList::remove(Vertex* v) {
133 list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
134 }
135
136 // Round to nearest quarter-pixel. This is used for screenspace tessellation.
137
round(SkPoint * p)138 static inline void round(SkPoint* p) {
139 p->fX = SkScalarRoundToScalar(p->fX * 4.0f) * 0.25f;
140 p->fY = SkScalarRoundToScalar(p->fY * 4.0f) * 0.25f;
141 }
142
double_to_clamped_scalar(double d)143 static inline SkScalar double_to_clamped_scalar(double d) {
144 // Clamps large values to what's finitely representable when cast back to a float.
145 static const double kMaxLimit = (double) SK_ScalarMax;
146 // It's not perfect, but a using a value larger than float_min helps protect from denormalized
147 // values and ill-conditions in intermediate calculations on coordinates.
148 static const double kNearZeroLimit = 16 * (double) std::numeric_limits<float>::min();
149 if (std::abs(d) < kNearZeroLimit) {
150 d = 0.f;
151 }
152 return SkDoubleToScalar(std::max(-kMaxLimit, std::min(d, kMaxLimit)));
153 }
154
intersect(const Line & other,SkPoint * point) const155 bool GrTriangulator::Line::intersect(const Line& other, SkPoint* point) const {
156 double denom = fA * other.fB - fB * other.fA;
157 if (denom == 0.0) {
158 return false;
159 }
160 double scale = 1.0 / denom;
161 point->fX = double_to_clamped_scalar((fB * other.fC - other.fB * fC) * scale);
162 point->fY = double_to_clamped_scalar((other.fA * fC - fA * other.fC) * scale);
163 round(point);
164 return point->isFinite();
165 }
166
167 // If the edge's vertices differ by many orders of magnitude, the computed line equation can have
168 // significant error in its distance and intersection tests. To avoid this, we recursively subdivide
169 // long edges and effectively perform a binary search to perform a more accurate intersection test.
edge_line_needs_recursion(const SkPoint & p0,const SkPoint & p1)170 static bool edge_line_needs_recursion(const SkPoint& p0, const SkPoint& p1) {
171 // ilogbf(0) returns an implementation-defined constant, but we are choosing to saturate
172 // negative exponents to 0 for comparisons sake. We're only trying to recurse on lines with
173 // very large coordinates.
174 int expDiffX = std::abs((std::abs(p0.fX) < 1.f ? 0 : std::ilogbf(p0.fX)) -
175 (std::abs(p1.fX) < 1.f ? 0 : std::ilogbf(p1.fX)));
176 int expDiffY = std::abs((std::abs(p0.fY) < 1.f ? 0 : std::ilogbf(p0.fY)) -
177 (std::abs(p1.fY) < 1.f ? 0 : std::ilogbf(p1.fY)));
178 // Differ by more than 2^20, or roughly a factor of one million.
179 return expDiffX > 20 || expDiffY > 20;
180 }
181
recursive_edge_intersect(const Line & u,SkPoint u0,SkPoint u1,const Line & v,SkPoint v0,SkPoint v1,SkPoint * p,double * s,double * t)182 static bool recursive_edge_intersect(const Line& u, SkPoint u0, SkPoint u1,
183 const Line& v, SkPoint v0, SkPoint v1,
184 SkPoint* p, double* s, double* t) {
185 // First check if the bounding boxes of [u0,u1] intersects [v0,v1]. If they do not, then the
186 // two line segments cannot intersect in their domain (even if the lines themselves might).
187 // - don't use SkRect::intersect since the vertices aren't sorted and horiz/vertical lines
188 // appear as empty rects, which then never "intersect" according to SkRect.
189 if (std::min(u0.fX, u1.fX) > std::max(v0.fX, v1.fX) ||
190 std::max(u0.fX, u1.fX) < std::min(v0.fX, v1.fX) ||
191 std::min(u0.fY, u1.fY) > std::max(v0.fY, v1.fY) ||
192 std::max(u0.fY, u1.fY) < std::min(v0.fY, v1.fY)) {
193 return false;
194 }
195
196 // Compute intersection based on current segment vertices; if an intersection is found but the
197 // vertices differ too much in magnitude, we recurse using the midpoint of the segment to
198 // reject false positives. We don't currently try to avoid false negatives (e.g. large magnitude
199 // line reports no intersection but there is one).
200 double denom = u.fA * v.fB - u.fB * v.fA;
201 if (denom == 0.0) {
202 return false;
203 }
204 double dx = static_cast<double>(v0.fX) - u0.fX;
205 double dy = static_cast<double>(v0.fY) - u0.fY;
206 double sNumer = dy * v.fB + dx * v.fA;
207 double tNumer = dy * u.fB + dx * u.fA;
208 // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
209 // This saves us doing the divide below unless absolutely necessary.
210 if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
211 : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
212 return false;
213 }
214
215 *s = sNumer / denom;
216 *t = tNumer / denom;
217 SkASSERT(*s >= 0.0 && *s <= 1.0 && *t >= 0.0 && *t <= 1.0);
218
219 const bool uNeedsSplit = edge_line_needs_recursion(u0, u1);
220 const bool vNeedsSplit = edge_line_needs_recursion(v0, v1);
221 if (!uNeedsSplit && !vNeedsSplit) {
222 p->fX = double_to_clamped_scalar(u0.fX - (*s) * u.fB);
223 p->fY = double_to_clamped_scalar(u0.fY + (*s) * u.fA);
224 return true;
225 } else {
226 double sScale = 1.0, sShift = 0.0;
227 double tScale = 1.0, tShift = 0.0;
228
229 if (uNeedsSplit) {
230 SkPoint uM = {(float) (0.5 * u0.fX + 0.5 * u1.fX),
231 (float) (0.5 * u0.fY + 0.5 * u1.fY)};
232 sScale = 0.5;
233 if (*s >= 0.5) {
234 u0 = uM;
235 sShift = 0.5;
236 } else {
237 u1 = uM;
238 }
239 }
240 if (vNeedsSplit) {
241 SkPoint vM = {(float) (0.5 * v0.fX + 0.5 * v1.fX),
242 (float) (0.5 * v0.fY + 0.5 * v1.fY)};
243 tScale = 0.5;
244 if (*t >= 0.5) {
245 v0 = vM;
246 tShift = 0.5;
247 } else {
248 v1 = vM;
249 }
250 }
251
252 // Just recompute both lines, even if only one was split; we're already in a slow path.
253 if (recursive_edge_intersect(Line(u0, u1), u0, u1, Line(v0, v1), v0, v1, p, s, t)) {
254 // Adjust s and t back to full range
255 *s = sScale * (*s) + sShift;
256 *t = tScale * (*t) + tShift;
257 return true;
258 } else {
259 // False positive
260 return false;
261 }
262 }
263 }
264
intersect(const Edge & other,SkPoint * p,uint8_t * alpha) const265 bool GrTriangulator::Edge::intersect(const Edge& other, SkPoint* p, uint8_t* alpha) const {
266 TESS_LOG("intersecting %g -> %g with %g -> %g\n",
267 fTop->fID, fBottom->fID, other.fTop->fID, other.fBottom->fID);
268 if (fTop == other.fTop || fBottom == other.fBottom ||
269 fTop == other.fBottom || fBottom == other.fTop) {
270 // If the two edges share a vertex by construction, they have already been split and
271 // shouldn't be considered "intersecting" anymore.
272 return false;
273 }
274
275 double s, t; // needed to interpolate vertex alpha
276 const bool intersects = recursive_edge_intersect(
277 fLine, fTop->fPoint, fBottom->fPoint,
278 other.fLine, other.fTop->fPoint, other.fBottom->fPoint,
279 p, &s, &t);
280 if (!intersects) {
281 return false;
282 }
283
284 if (alpha) {
285 if (fType == EdgeType::kInner || other.fType == EdgeType::kInner) {
286 // If the intersection is on any interior edge, it needs to stay fully opaque or later
287 // triangulation could leech transparency into the inner fill region.
288 *alpha = 255;
289 } else if (fType == EdgeType::kOuter && other.fType == EdgeType::kOuter) {
290 // Trivially, the intersection will be fully transparent since since it is by
291 // construction on the outer edge.
292 *alpha = 0;
293 } else {
294 // Could be two connectors crossing, or a connector crossing an outer edge.
295 // Take the max interpolated alpha
296 SkASSERT(fType == EdgeType::kConnector || other.fType == EdgeType::kConnector);
297 *alpha = std::max((1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha,
298 (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha);
299 }
300 }
301 return true;
302 }
303
insert(Edge * edge,Edge * prev,Edge * next)304 void GrTriangulator::EdgeList::insert(Edge* edge, Edge* prev, Edge* next) {
305 list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
306 }
307
remove(Edge * edge)308 bool GrTriangulator::EdgeList::remove(Edge* edge) {
309 TESS_LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
310 // SkASSERT(this->contains(edge)); // Leave this here for future debugging.
311 if (!this->contains(edge)) {
312 return false;
313 }
314 list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
315 return true;
316 }
317
addEdge(Edge * edge)318 void GrTriangulator::MonotonePoly::addEdge(Edge* edge) {
319 if (fSide == Side::kRight) {
320 SkASSERT(!edge->fUsedInRightPoly);
321 list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
322 edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
323 edge->fUsedInRightPoly = true;
324 } else {
325 SkASSERT(!edge->fUsedInLeftPoly);
326 list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
327 edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
328 edge->fUsedInLeftPoly = true;
329 }
330 }
331
emitMonotonePoly(const MonotonePoly * monotonePoly,skgpu::VertexWriter data) const332 skgpu::VertexWriter GrTriangulator::emitMonotonePoly(const MonotonePoly* monotonePoly,
333 skgpu::VertexWriter data) const {
334 SkASSERT(monotonePoly->fWinding != 0);
335 Edge* e = monotonePoly->fFirstEdge;
336 VertexList vertices;
337 vertices.append(e->fTop);
338 int count = 1;
339 while (e != nullptr) {
340 if (Side::kRight == monotonePoly->fSide) {
341 vertices.append(e->fBottom);
342 e = e->fRightPolyNext;
343 } else {
344 vertices.prepend(e->fBottom);
345 e = e->fLeftPolyNext;
346 }
347 count++;
348 }
349 Vertex* first = vertices.fHead;
350 Vertex* v = first->fNext;
351 while (v != vertices.fTail) {
352 SkASSERT(v && v->fPrev && v->fNext);
353 Vertex* prev = v->fPrev;
354 Vertex* curr = v;
355 Vertex* next = v->fNext;
356 if (count == 3) {
357 return this->emitTriangle(prev, curr, next, monotonePoly->fWinding, std::move(data));
358 }
359 double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
360 double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
361 double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
362 double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
363 if (ax * by - ay * bx >= 0.0) {
364 data = this->emitTriangle(prev, curr, next, monotonePoly->fWinding, std::move(data));
365 v->fPrev->fNext = v->fNext;
366 v->fNext->fPrev = v->fPrev;
367 count--;
368 if (v->fPrev == first) {
369 v = v->fNext;
370 } else {
371 v = v->fPrev;
372 }
373 } else {
374 v = v->fNext;
375 }
376 }
377 return data;
378 }
379
emitTriangle(Vertex * prev,Vertex * curr,Vertex * next,int winding,skgpu::VertexWriter data) const380 skgpu::VertexWriter GrTriangulator::emitTriangle(
381 Vertex* prev, Vertex* curr, Vertex* next, int winding, skgpu::VertexWriter data) const {
382 if (winding > 0) {
383 // Ensure our triangles always wind in the same direction as if the path had been
384 // triangulated as a simple fan (a la red book).
385 std::swap(prev, next);
386 }
387 if (fCollectBreadcrumbTriangles && abs(winding) > 1 &&
388 fPath.getFillType() == SkPathFillType::kWinding) {
389 // The first winding count will come from the actual triangle we emit. The remaining counts
390 // come from the breadcrumb triangle.
391 fBreadcrumbList.append(fAlloc, prev->fPoint, curr->fPoint, next->fPoint, abs(winding) - 1);
392 }
393 return emit_triangle(prev, curr, next, fEmitCoverage, std::move(data));
394 }
395
Poly(Vertex * v,int winding)396 GrTriangulator::Poly::Poly(Vertex* v, int winding)
397 : fFirstVertex(v)
398 , fWinding(winding)
399 , fHead(nullptr)
400 , fTail(nullptr)
401 , fNext(nullptr)
402 , fPartner(nullptr)
403 , fCount(0)
404 {
405 #if TRIANGULATOR_LOGGING
406 static int gID = 0;
407 fID = gID++;
408 TESS_LOG("*** created Poly %d\n", fID);
409 #endif
410 }
411
addEdge(Edge * e,Side side,GrTriangulator * tri)412 Poly* GrTriangulator::Poly::addEdge(Edge* e, Side side, GrTriangulator* tri) {
413 TESS_LOG("addEdge (%g -> %g) to poly %d, %s side\n",
414 e->fTop->fID,
415 e->fBottom->fID,
416 fID,
417 side == Side::kLeft ? "left" : "right");
418 Poly* partner = fPartner;
419 Poly* poly = this;
420 if (side == Side::kRight) {
421 if (e->fUsedInRightPoly) {
422 return this;
423 }
424 } else {
425 if (e->fUsedInLeftPoly) {
426 return this;
427 }
428 }
429 if (partner) {
430 fPartner = partner->fPartner = nullptr;
431 }
432 if (!fTail) {
433 fHead = fTail = tri->allocateMonotonePoly(e, side, fWinding);
434 fCount += 2;
435 } else if (e->fBottom == fTail->fLastEdge->fBottom) {
436 return poly;
437 } else if (side == fTail->fSide) {
438 fTail->addEdge(e);
439 fCount++;
440 } else {
441 e = tri->allocateEdge(fTail->fLastEdge->fBottom, e->fBottom, 1, EdgeType::kInner);
442 fTail->addEdge(e);
443 fCount++;
444 if (partner) {
445 partner->addEdge(e, side, tri);
446 poly = partner;
447 } else {
448 MonotonePoly* m = tri->allocateMonotonePoly(e, side, fWinding);
449 m->fPrev = fTail;
450 fTail->fNext = m;
451 fTail = m;
452 }
453 }
454 return poly;
455 }
emitPoly(const Poly * poly,skgpu::VertexWriter data) const456 skgpu::VertexWriter GrTriangulator::emitPoly(const Poly* poly, skgpu::VertexWriter data) const {
457 if (poly->fCount < 3) {
458 return data;
459 }
460 TESS_LOG("emit() %d, size %d\n", poly->fID, poly->fCount);
461 for (MonotonePoly* m = poly->fHead; m != nullptr; m = m->fNext) {
462 data = this->emitMonotonePoly(m, std::move(data));
463 }
464 return data;
465 }
466
coincident(const SkPoint & a,const SkPoint & b)467 static bool coincident(const SkPoint& a, const SkPoint& b) {
468 return a == b;
469 }
470
makePoly(Poly ** head,Vertex * v,int winding) const471 Poly* GrTriangulator::makePoly(Poly** head, Vertex* v, int winding) const {
472 Poly* poly = fAlloc->make<Poly>(v, winding);
473 poly->fNext = *head;
474 *head = poly;
475 return poly;
476 }
477
appendPointToContour(const SkPoint & p,VertexList * contour) const478 void GrTriangulator::appendPointToContour(const SkPoint& p, VertexList* contour) const {
479 Vertex* v = fAlloc->make<Vertex>(p, 255);
480 #if TRIANGULATOR_LOGGING
481 static float gID = 0.0f;
482 v->fID = gID++;
483 #endif
484 contour->append(v);
485 }
486
quad_error_at(const SkPoint pts[3],SkScalar t,SkScalar u)487 static SkScalar quad_error_at(const SkPoint pts[3], SkScalar t, SkScalar u) {
488 SkQuadCoeff quad(pts);
489 SkPoint p0 = to_point(quad.eval(t - 0.5f * u));
490 SkPoint mid = to_point(quad.eval(t));
491 SkPoint p1 = to_point(quad.eval(t + 0.5f * u));
492 if (!p0.isFinite() || !mid.isFinite() || !p1.isFinite()) {
493 return 0;
494 }
495 return SkPointPriv::DistanceToLineSegmentBetweenSqd(mid, p0, p1);
496 }
497
appendQuadraticToContour(const SkPoint pts[3],SkScalar toleranceSqd,VertexList * contour) const498 void GrTriangulator::appendQuadraticToContour(const SkPoint pts[3], SkScalar toleranceSqd,
499 VertexList* contour) const {
500 SkQuadCoeff quad(pts);
501 skvx::float2 aa = quad.fA * quad.fA;
502 SkScalar denom = 2.0f * (aa[0] + aa[1]);
503 skvx::float2 ab = quad.fA * quad.fB;
504 SkScalar t = denom ? (-ab[0] - ab[1]) / denom : 0.0f;
505 int nPoints = 1;
506 SkScalar u = 1.0f;
507 // Test possible subdivision values only at the point of maximum curvature.
508 // If it passes the flatness metric there, it'll pass everywhere.
509 while (nPoints < GrPathUtils::kMaxPointsPerCurve) {
510 u = 1.0f / nPoints;
511 if (quad_error_at(pts, t, u) < toleranceSqd) {
512 break;
513 }
514 nPoints++;
515 }
516 for (int j = 1; j <= nPoints; j++) {
517 this->appendPointToContour(to_point(quad.eval(j * u)), contour);
518 }
519 }
520
generateCubicPoints(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const SkPoint & p3,SkScalar tolSqd,VertexList * contour,int pointsLeft) const521 void GrTriangulator::generateCubicPoints(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
522 const SkPoint& p3, SkScalar tolSqd, VertexList* contour,
523 int pointsLeft) const {
524 SkScalar d1 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p1, p0, p3);
525 SkScalar d2 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p2, p0, p3);
526 if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) || !SkIsFinite(d1, d2)) {
527 this->appendPointToContour(p3, contour);
528 return;
529 }
530 const SkPoint q[] = {
531 { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
532 { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
533 { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
534 };
535 const SkPoint r[] = {
536 { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
537 { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
538 };
539 const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
540 pointsLeft >>= 1;
541 this->generateCubicPoints(p0, q[0], r[0], s, tolSqd, contour, pointsLeft);
542 this->generateCubicPoints(s, r[1], q[2], p3, tolSqd, contour, pointsLeft);
543 }
544
545 // Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
546
pathToContours(float tolerance,const SkRect & clipBounds,VertexList * contours,bool * isLinear) const547 void GrTriangulator::pathToContours(float tolerance, const SkRect& clipBounds,
548 VertexList* contours, bool* isLinear) const {
549 SkScalar toleranceSqd = tolerance * tolerance;
550 SkPoint pts[4];
551 *isLinear = true;
552 VertexList* contour = contours;
553 SkPath::Iter iter(fPath, false);
554 if (fPath.isInverseFillType()) {
555 SkPoint quad[4];
556 clipBounds.toQuad(quad);
557 for (int i = 3; i >= 0; i--) {
558 this->appendPointToContour(quad[i], contours);
559 }
560 contour++;
561 }
562 SkAutoConicToQuads converter;
563 SkPath::Verb verb;
564 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
565 switch (verb) {
566 case SkPath::kConic_Verb: {
567 *isLinear = false;
568 if (toleranceSqd == 0) {
569 this->appendPointToContour(pts[2], contour);
570 break;
571 }
572 SkScalar weight = iter.conicWeight();
573 const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
574 for (int i = 0; i < converter.countQuads(); ++i) {
575 this->appendQuadraticToContour(quadPts, toleranceSqd, contour);
576 quadPts += 2;
577 }
578 break;
579 }
580 case SkPath::kMove_Verb:
581 if (contour->fHead) {
582 contour++;
583 }
584 this->appendPointToContour(pts[0], contour);
585 break;
586 case SkPath::kLine_Verb: {
587 this->appendPointToContour(pts[1], contour);
588 break;
589 }
590 case SkPath::kQuad_Verb: {
591 *isLinear = false;
592 if (toleranceSqd == 0) {
593 this->appendPointToContour(pts[2], contour);
594 break;
595 }
596 this->appendQuadraticToContour(pts, toleranceSqd, contour);
597 break;
598 }
599 case SkPath::kCubic_Verb: {
600 *isLinear = false;
601 if (toleranceSqd == 0) {
602 this->appendPointToContour(pts[3], contour);
603 break;
604 }
605 int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
606 this->generateCubicPoints(pts[0], pts[1], pts[2], pts[3], toleranceSqd, contour,
607 pointsLeft);
608 break;
609 }
610 case SkPath::kClose_Verb:
611 case SkPath::kDone_Verb:
612 break;
613 }
614 }
615 }
616
apply_fill_type(SkPathFillType fillType,int winding)617 static inline bool apply_fill_type(SkPathFillType fillType, int winding) {
618 switch (fillType) {
619 case SkPathFillType::kWinding:
620 return winding != 0;
621 case SkPathFillType::kEvenOdd:
622 return (winding & 1) != 0;
623 case SkPathFillType::kInverseWinding:
624 return winding == 1;
625 case SkPathFillType::kInverseEvenOdd:
626 return (winding & 1) == 1;
627 default:
628 SkASSERT(false);
629 return false;
630 }
631 }
632
applyFillType(int winding) const633 bool GrTriangulator::applyFillType(int winding) const {
634 return apply_fill_type(fPath.getFillType(), winding);
635 }
636
apply_fill_type(SkPathFillType fillType,Poly * poly)637 static inline bool apply_fill_type(SkPathFillType fillType, Poly* poly) {
638 return poly && apply_fill_type(fillType, poly->fWinding);
639 }
640
allocateMonotonePoly(Edge * edge,Side side,int winding)641 MonotonePoly* GrTriangulator::allocateMonotonePoly(Edge* edge, Side side, int winding) {
642 ++fNumMonotonePolys;
643 return fAlloc->make<MonotonePoly>(edge, side, winding);
644 }
645
allocateEdge(Vertex * top,Vertex * bottom,int winding,EdgeType type)646 Edge* GrTriangulator::allocateEdge(Vertex* top, Vertex* bottom, int winding, EdgeType type) {
647 ++fNumEdges;
648 return fAlloc->make<Edge>(top, bottom, winding, type);
649 }
650
makeEdge(Vertex * prev,Vertex * next,EdgeType type,const Comparator & c)651 Edge* GrTriangulator::makeEdge(Vertex* prev, Vertex* next, EdgeType type,
652 const Comparator& c) {
653 SkASSERT(prev->fPoint != next->fPoint);
654 int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
655 Vertex* top = winding < 0 ? next : prev;
656 Vertex* bottom = winding < 0 ? prev : next;
657 return this->allocateEdge(top, bottom, winding, type);
658 }
659
insert(Edge * edge,Edge * prev)660 bool EdgeList::insert(Edge* edge, Edge* prev) {
661 TESS_LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
662 // SkASSERT(!this->contains(edge)); // Leave this here for debugging.
663 if (this->contains(edge)) {
664 return false;
665 }
666 Edge* next = prev ? prev->fRight : fHead;
667 this->insert(edge, prev, next);
668 return true;
669 }
670
FindEnclosingEdges(const Vertex & v,const EdgeList & edges,Edge ** left,Edge ** right)671 void GrTriangulator::FindEnclosingEdges(const Vertex& v,
672 const EdgeList& edges,
673 Edge** left, Edge**right) {
674 if (v.fFirstEdgeAbove && v.fLastEdgeAbove) {
675 *left = v.fFirstEdgeAbove->fLeft;
676 *right = v.fLastEdgeAbove->fRight;
677 return;
678 }
679 Edge* next = nullptr;
680 Edge* prev;
681 for (prev = edges.fTail; prev != nullptr; prev = prev->fLeft) {
682 if (prev->isLeftOf(v)) {
683 break;
684 }
685 next = prev;
686 }
687 *left = prev;
688 *right = next;
689 }
690
insertAbove(Vertex * v,const Comparator & c)691 void GrTriangulator::Edge::insertAbove(Vertex* v, const Comparator& c) {
692 if (fTop->fPoint == fBottom->fPoint ||
693 c.sweep_lt(fBottom->fPoint, fTop->fPoint)) {
694 return;
695 }
696 TESS_LOG("insert edge (%g -> %g) above vertex %g\n", fTop->fID, fBottom->fID, v->fID);
697 Edge* prev = nullptr;
698 Edge* next;
699 for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
700 if (next->isRightOf(*fTop)) {
701 break;
702 }
703 prev = next;
704 }
705 list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
706 this, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
707 }
708
insertBelow(Vertex * v,const Comparator & c)709 void GrTriangulator::Edge::insertBelow(Vertex* v, const Comparator& c) {
710 if (fTop->fPoint == fBottom->fPoint ||
711 c.sweep_lt(fBottom->fPoint, fTop->fPoint)) {
712 return;
713 }
714 TESS_LOG("insert edge (%g -> %g) below vertex %g\n", fTop->fID, fBottom->fID, v->fID);
715 Edge* prev = nullptr;
716 Edge* next;
717 for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
718 if (next->isRightOf(*fBottom)) {
719 break;
720 }
721 prev = next;
722 }
723 list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
724 this, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
725 }
726
remove_edge_above(Edge * edge)727 static void remove_edge_above(Edge* edge) {
728 SkASSERT(edge->fTop && edge->fBottom);
729 TESS_LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
730 edge->fBottom->fID);
731 list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
732 edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
733 }
734
remove_edge_below(Edge * edge)735 static void remove_edge_below(Edge* edge) {
736 SkASSERT(edge->fTop && edge->fBottom);
737 TESS_LOG("removing edge (%g -> %g) below vertex %g\n",
738 edge->fTop->fID, edge->fBottom->fID, edge->fTop->fID);
739 list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
740 edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
741 }
742
disconnect()743 void GrTriangulator::Edge::disconnect() {
744 remove_edge_above(this);
745 remove_edge_below(this);
746 }
747
rewind(EdgeList * activeEdges,Vertex ** current,Vertex * dst,const Comparator & c)748 static bool rewind(EdgeList* activeEdges, Vertex** current, Vertex* dst, const Comparator& c) {
749 if (!current || *current == dst || c.sweep_lt((*current)->fPoint, dst->fPoint)) {
750 return true;
751 }
752 Vertex* v = *current;
753 TESS_LOG("rewinding active edges from vertex %g to vertex %g\n", v->fID, dst->fID);
754 while (v != dst) {
755 v = v->fPrev;
756 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
757 if (!activeEdges->remove(e)) {
758 return false;
759 }
760 }
761 Edge* leftEdge = v->fLeftEnclosingEdge;
762 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
763 if (!activeEdges->insert(e, leftEdge)) {
764 return false;
765 }
766 leftEdge = e;
767 Vertex* top = e->fTop;
768 if (c.sweep_lt(top->fPoint, dst->fPoint) &&
769 ((top->fLeftEnclosingEdge && !top->fLeftEnclosingEdge->isLeftOf(*e->fTop)) ||
770 (top->fRightEnclosingEdge && !top->fRightEnclosingEdge->isRightOf(*e->fTop)))) {
771 dst = top;
772 }
773 }
774 }
775 *current = v;
776 return true;
777 }
778
rewind_if_necessary(Edge * edge,EdgeList * activeEdges,Vertex ** current,const Comparator & c)779 static bool rewind_if_necessary(Edge* edge, EdgeList* activeEdges, Vertex** current,
780 const Comparator& c) {
781 if (!activeEdges || !current) {
782 return true;
783 }
784 if (!edge) {
785 return false;
786 }
787 Vertex* top = edge->fTop;
788 Vertex* bottom = edge->fBottom;
789 if (edge->fLeft) {
790 Vertex* leftTop = edge->fLeft->fTop;
791 Vertex* leftBottom = edge->fLeft->fBottom;
792 if (leftTop && leftBottom) {
793 if (c.sweep_lt(leftTop->fPoint, top->fPoint) && !edge->fLeft->isLeftOf(*top)) {
794 if (!rewind(activeEdges, current, leftTop, c)) {
795 return false;
796 }
797 } else if (c.sweep_lt(top->fPoint, leftTop->fPoint) && !edge->isRightOf(*leftTop)) {
798 if (!rewind(activeEdges, current, top, c)) {
799 return false;
800 }
801 } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
802 !edge->fLeft->isLeftOf(*bottom)) {
803 if (!rewind(activeEdges, current, leftTop, c)) {
804 return false;
805 }
806 } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) &&
807 !edge->isRightOf(*leftBottom)) {
808 if (!rewind(activeEdges, current, top, c)) {
809 return false;
810 }
811 }
812 }
813 }
814 if (edge->fRight) {
815 Vertex* rightTop = edge->fRight->fTop;
816 Vertex* rightBottom = edge->fRight->fBottom;
817 if (rightTop && rightBottom) {
818 if (c.sweep_lt(rightTop->fPoint, top->fPoint) && !edge->fRight->isRightOf(*top)) {
819 if (!rewind(activeEdges, current, rightTop, c)) {
820 return false;
821 }
822 } else if (c.sweep_lt(top->fPoint, rightTop->fPoint) && !edge->isLeftOf(*rightTop)) {
823 if (!rewind(activeEdges, current, top, c)) {
824 return false;
825 }
826 } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
827 !edge->fRight->isRightOf(*bottom)) {
828 if (!rewind(activeEdges, current, rightTop, c)) {
829 return false;
830 }
831 } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
832 !edge->isLeftOf(*rightBottom)) {
833 if (!rewind(activeEdges, current, top, c)) {
834 return false;
835 }
836 }
837 }
838 }
839 return true;
840 }
841
setTop(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,const Comparator & c) const842 bool GrTriangulator::setTop(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
843 const Comparator& c) const {
844 remove_edge_below(edge);
845 if (fCollectBreadcrumbTriangles) {
846 fBreadcrumbList.append(fAlloc, edge->fTop->fPoint, edge->fBottom->fPoint, v->fPoint,
847 edge->fWinding);
848 }
849 edge->fTop = v;
850 edge->recompute();
851 edge->insertBelow(v, c);
852 if (!rewind_if_necessary(edge, activeEdges, current, c)) {
853 return false;
854 }
855 return this->mergeCollinearEdges(edge, activeEdges, current, c);
856 }
857
setBottom(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,const Comparator & c) const858 bool GrTriangulator::setBottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
859 const Comparator& c) const {
860 remove_edge_above(edge);
861 if (fCollectBreadcrumbTriangles) {
862 fBreadcrumbList.append(fAlloc, edge->fTop->fPoint, edge->fBottom->fPoint, v->fPoint,
863 edge->fWinding);
864 }
865 edge->fBottom = v;
866 edge->recompute();
867 edge->insertAbove(v, c);
868 if (!rewind_if_necessary(edge, activeEdges, current, c)) {
869 return false;
870 }
871 return this->mergeCollinearEdges(edge, activeEdges, current, c);
872 }
873
mergeEdgesAbove(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,const Comparator & c) const874 bool GrTriangulator::mergeEdgesAbove(Edge* edge, Edge* other, EdgeList* activeEdges,
875 Vertex** current, const Comparator& c) const {
876 if (!edge || !other) {
877 return false;
878 }
879 if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
880 TESS_LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
881 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
882 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
883 if (!rewind(activeEdges, current, edge->fTop, c)) {
884 return false;
885 }
886 other->fWinding += edge->fWinding;
887 edge->disconnect();
888 edge->fTop = edge->fBottom = nullptr;
889 } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
890 if (!rewind(activeEdges, current, edge->fTop, c)) {
891 return false;
892 }
893 other->fWinding += edge->fWinding;
894 if (!this->setBottom(edge, other->fTop, activeEdges, current, c)) {
895 return false;
896 }
897 } else {
898 if (!rewind(activeEdges, current, other->fTop, c)) {
899 return false;
900 }
901 edge->fWinding += other->fWinding;
902 if (!this->setBottom(other, edge->fTop, activeEdges, current, c)) {
903 return false;
904 }
905 }
906 return true;
907 }
908
mergeEdgesBelow(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,const Comparator & c) const909 bool GrTriangulator::mergeEdgesBelow(Edge* edge, Edge* other, EdgeList* activeEdges,
910 Vertex** current, const Comparator& c) const {
911 if (!edge || !other) {
912 return false;
913 }
914 if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
915 TESS_LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
916 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
917 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
918 if (!rewind(activeEdges, current, edge->fTop, c)) {
919 return false;
920 }
921 other->fWinding += edge->fWinding;
922 edge->disconnect();
923 edge->fTop = edge->fBottom = nullptr;
924 } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
925 if (!rewind(activeEdges, current, other->fTop, c)) {
926 return false;
927 }
928 edge->fWinding += other->fWinding;
929 if (!this->setTop(other, edge->fBottom, activeEdges, current, c)) {
930 return false;
931 }
932 } else {
933 if (!rewind(activeEdges, current, edge->fTop, c)) {
934 return false;
935 }
936 other->fWinding += edge->fWinding;
937 if (!this->setTop(edge, other->fBottom, activeEdges, current, c)) {
938 return false;
939 }
940 }
941 return true;
942 }
943
top_collinear(Edge * left,Edge * right)944 static bool top_collinear(Edge* left, Edge* right) {
945 if (!left || !right) {
946 return false;
947 }
948 return left->fTop->fPoint == right->fTop->fPoint ||
949 !left->isLeftOf(*right->fTop) || !right->isRightOf(*left->fTop);
950 }
951
bottom_collinear(Edge * left,Edge * right)952 static bool bottom_collinear(Edge* left, Edge* right) {
953 if (!left || !right) {
954 return false;
955 }
956 return left->fBottom->fPoint == right->fBottom->fPoint ||
957 !left->isLeftOf(*right->fBottom) || !right->isRightOf(*left->fBottom);
958 }
959
mergeCollinearEdges(Edge * edge,EdgeList * activeEdges,Vertex ** current,const Comparator & c) const960 bool GrTriangulator::mergeCollinearEdges(Edge* edge, EdgeList* activeEdges, Vertex** current,
961 const Comparator& c) const {
962 for (;;) {
963 if (top_collinear(edge->fPrevEdgeAbove, edge)) {
964 if (!this->mergeEdgesAbove(edge->fPrevEdgeAbove, edge, activeEdges, current, c)) {
965 return false;
966 }
967 } else if (top_collinear(edge, edge->fNextEdgeAbove)) {
968 if (!this->mergeEdgesAbove(edge->fNextEdgeAbove, edge, activeEdges, current, c)) {
969 return false;
970 }
971 } else if (bottom_collinear(edge->fPrevEdgeBelow, edge)) {
972 if (!this->mergeEdgesBelow(edge->fPrevEdgeBelow, edge, activeEdges, current, c)) {
973 return false;
974 }
975 } else if (bottom_collinear(edge, edge->fNextEdgeBelow)) {
976 if (!this->mergeEdgesBelow(edge->fNextEdgeBelow, edge, activeEdges, current, c)) {
977 return false;
978 }
979 } else {
980 break;
981 }
982 }
983 SkASSERT(!top_collinear(edge->fPrevEdgeAbove, edge));
984 SkASSERT(!top_collinear(edge, edge->fNextEdgeAbove));
985 SkASSERT(!bottom_collinear(edge->fPrevEdgeBelow, edge));
986 SkASSERT(!bottom_collinear(edge, edge->fNextEdgeBelow));
987 return true;
988 }
989
splitEdge(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,const Comparator & c)990 GrTriangulator::BoolFail GrTriangulator::splitEdge(
991 Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, const Comparator& c) {
992 if (!edge->fTop || !edge->fBottom || v == edge->fTop || v == edge->fBottom) {
993 return BoolFail::kFalse;
994 }
995 TESS_LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
996 edge->fTop->fID, edge->fBottom->fID, v->fID, v->fPoint.fX, v->fPoint.fY);
997 Vertex* top;
998 Vertex* bottom;
999 int winding = edge->fWinding;
1000 // Theoretically, and ideally, the edge betwee p0 and p1 is being split by v, and v is "between"
1001 // the segment end points according to c. This is equivalent to p0 < v < p1. Unfortunately, if
1002 // v was clamped/rounded this relation doesn't always hold.
1003 if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1004 // Actually "v < p0 < p1": update 'edge' to be v->p1 and add v->p0. We flip the winding on
1005 // the new edge so that it winds as if it were p0->v.
1006 top = v;
1007 bottom = edge->fTop;
1008 winding *= -1;
1009 if (!this->setTop(edge, v, activeEdges, current, c)) {
1010 return BoolFail::kFail;
1011 }
1012 } else if (c.sweep_lt(edge->fBottom->fPoint, v->fPoint)) {
1013 // Actually "p0 < p1 < v": update 'edge' to be p0->v and add p1->v. We flip the winding on
1014 // the new edge so that it winds as if it were v->p1.
1015 top = edge->fBottom;
1016 bottom = v;
1017 winding *= -1;
1018 if (!this->setBottom(edge, v, activeEdges, current, c)) {
1019 return BoolFail::kFail;
1020 }
1021 } else {
1022 // The ideal case, "p0 < v < p1": update 'edge' to be p0->v and add v->p1. Original winding
1023 // is valid for both edges.
1024 top = v;
1025 bottom = edge->fBottom;
1026 if (!this->setBottom(edge, v, activeEdges, current, c)) {
1027 return BoolFail::kFail;
1028 }
1029 }
1030 Edge* newEdge = this->allocateEdge(top, bottom, winding, edge->fType);
1031 newEdge->insertBelow(top, c);
1032 newEdge->insertAbove(bottom, c);
1033 if (!this->mergeCollinearEdges(newEdge, activeEdges, current, c)) {
1034 return BoolFail::kFail;
1035 }
1036 return BoolFail::kTrue;
1037 }
1038
intersectEdgePair(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,const Comparator & c)1039 GrTriangulator::BoolFail GrTriangulator::intersectEdgePair(
1040 Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current, const Comparator& c) {
1041 if (!left->fTop || !left->fBottom || !right->fTop || !right->fBottom) {
1042 return BoolFail::kFalse;
1043 }
1044 if (left->fTop == right->fTop || left->fBottom == right->fBottom) {
1045 return BoolFail::kFalse;
1046 }
1047
1048 // Check if the lines intersect as determined by isLeftOf and isRightOf, since that is the
1049 // source of ground truth. It may suggest an intersection even if Edge::intersect() did not have
1050 // the precision to check it. In this case we are explicitly correcting the edge topology to
1051 // match the sided-ness checks.
1052 Edge* split = nullptr;
1053 Vertex* splitAt = nullptr;
1054 if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1055 if (!left->isLeftOf(*right->fTop)) {
1056 split = left;
1057 splitAt = right->fTop;
1058 }
1059 } else {
1060 if (!right->isRightOf(*left->fTop)) {
1061 split = right;
1062 splitAt = left->fTop;
1063 }
1064 }
1065 if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1066 if (!left->isLeftOf(*right->fBottom)) {
1067 split = left;
1068 splitAt = right->fBottom;
1069 }
1070 } else {
1071 if (!right->isRightOf(*left->fBottom)) {
1072 split = right;
1073 splitAt = left->fBottom;
1074 }
1075 }
1076
1077 if (!split) {
1078 return BoolFail::kFalse;
1079 }
1080
1081 // Rewind to the top of the edge that is "moving" since this topology correction can change the
1082 // geometry of the split edge.
1083 if (!rewind(activeEdges, current, split->fTop, c)) {
1084 return BoolFail::kFail;
1085 }
1086 return this->splitEdge(split, splitAt, activeEdges, current, c);
1087 }
1088
makeConnectingEdge(Vertex * prev,Vertex * next,EdgeType type,const Comparator & c,int windingScale)1089 Edge* GrTriangulator::makeConnectingEdge(Vertex* prev, Vertex* next, EdgeType type,
1090 const Comparator& c, int windingScale) {
1091 if (!prev || !next || prev->fPoint == next->fPoint) {
1092 return nullptr;
1093 }
1094 Edge* edge = this->makeEdge(prev, next, type, c);
1095 edge->insertBelow(edge->fTop, c);
1096 edge->insertAbove(edge->fBottom, c);
1097 edge->fWinding *= windingScale;
1098 this->mergeCollinearEdges(edge, nullptr, nullptr, c);
1099 return edge;
1100 }
1101
mergeVertices(Vertex * src,Vertex * dst,VertexList * mesh,const Comparator & c) const1102 void GrTriangulator::mergeVertices(Vertex* src, Vertex* dst, VertexList* mesh,
1103 const Comparator& c) const {
1104 TESS_LOG("found coincident verts at %g, %g; merging %g into %g\n",
1105 src->fPoint.fX, src->fPoint.fY, src->fID, dst->fID);
1106 dst->fAlpha = std::max(src->fAlpha, dst->fAlpha);
1107 if (src->fPartner) {
1108 src->fPartner->fPartner = dst;
1109 }
1110 while (Edge* edge = src->fFirstEdgeAbove) {
1111 std::ignore = this->setBottom(edge, dst, nullptr, nullptr, c);
1112 }
1113 while (Edge* edge = src->fFirstEdgeBelow) {
1114 std::ignore = this->setTop(edge, dst, nullptr, nullptr, c);
1115 }
1116 mesh->remove(src);
1117 dst->fSynthetic = true;
1118 }
1119
makeSortedVertex(const SkPoint & p,uint8_t alpha,VertexList * mesh,Vertex * reference,const Comparator & c) const1120 Vertex* GrTriangulator::makeSortedVertex(const SkPoint& p, uint8_t alpha, VertexList* mesh,
1121 Vertex* reference, const Comparator& c) const {
1122 Vertex* prevV = reference;
1123 while (prevV && c.sweep_lt(p, prevV->fPoint)) {
1124 prevV = prevV->fPrev;
1125 }
1126 Vertex* nextV = prevV ? prevV->fNext : mesh->fHead;
1127 while (nextV && c.sweep_lt(nextV->fPoint, p)) {
1128 prevV = nextV;
1129 nextV = nextV->fNext;
1130 }
1131 Vertex* v;
1132 if (prevV && coincident(prevV->fPoint, p)) {
1133 v = prevV;
1134 } else if (nextV && coincident(nextV->fPoint, p)) {
1135 v = nextV;
1136 } else {
1137 v = fAlloc->make<Vertex>(p, alpha);
1138 #if TRIANGULATOR_LOGGING
1139 if (!prevV) {
1140 v->fID = mesh->fHead->fID - 1.0f;
1141 } else if (!nextV) {
1142 v->fID = mesh->fTail->fID + 1.0f;
1143 } else {
1144 v->fID = (prevV->fID + nextV->fID) * 0.5f;
1145 }
1146 #endif
1147 mesh->insert(v, prevV, nextV);
1148 }
1149 return v;
1150 }
1151
1152 // Clamps x and y coordinates independently, so the returned point will lie within the bounding
1153 // box formed by the corners of 'min' and 'max' (although min/max here refer to the ordering
1154 // imposed by 'c').
clamp(SkPoint p,SkPoint min,SkPoint max,const Comparator & c)1155 static SkPoint clamp(SkPoint p, SkPoint min, SkPoint max, const Comparator& c) {
1156 if (c.fDirection == Comparator::Direction::kHorizontal) {
1157 // With horizontal sorting, we know min.x <= max.x, but there's no relation between
1158 // Y components unless min.x == max.x.
1159 return {SkTPin(p.fX, min.fX, max.fX),
1160 min.fY < max.fY ? SkTPin(p.fY, min.fY, max.fY)
1161 : SkTPin(p.fY, max.fY, min.fY)};
1162 } else {
1163 // And with vertical sorting, we know Y's relation but not necessarily X's.
1164 return {min.fX < max.fX ? SkTPin(p.fX, min.fX, max.fX)
1165 : SkTPin(p.fX, max.fX, min.fX),
1166 SkTPin(p.fY, min.fY, max.fY)};
1167 }
1168 }
1169
computeBisector(Edge * edge1,Edge * edge2,Vertex * v) const1170 void GrTriangulator::computeBisector(Edge* edge1, Edge* edge2, Vertex* v) const {
1171 SkASSERT(fEmitCoverage); // Edge-AA only!
1172 Line line1 = edge1->fLine;
1173 Line line2 = edge2->fLine;
1174 line1.normalize();
1175 line2.normalize();
1176 double cosAngle = line1.fA * line2.fA + line1.fB * line2.fB;
1177 if (cosAngle > 0.999) {
1178 return;
1179 }
1180 line1.fC += edge1->fWinding > 0 ? -1 : 1;
1181 line2.fC += edge2->fWinding > 0 ? -1 : 1;
1182 SkPoint p;
1183 if (line1.intersect(line2, &p)) {
1184 uint8_t alpha = edge1->fType == EdgeType::kOuter ? 255 : 0;
1185 v->fPartner = fAlloc->make<Vertex>(p, alpha);
1186 TESS_LOG("computed bisector (%g,%g) alpha %d for vertex %g\n", p.fX, p.fY, alpha, v->fID);
1187 }
1188 }
1189
checkForIntersection(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,VertexList * mesh,const Comparator & c)1190 GrTriangulator::BoolFail GrTriangulator::checkForIntersection(
1191 Edge* left, Edge* right, EdgeList* activeEdges,
1192 Vertex** current, VertexList* mesh,
1193 const Comparator& c) {
1194 if (!left || !right) {
1195 return BoolFail::kFalse;
1196 }
1197 SkPoint p;
1198 uint8_t alpha;
1199 // If we are going to call intersect, then there must be tops and bottoms.
1200 if (!left->fTop || !left->fBottom || !right->fTop || !right->fBottom) {
1201 return BoolFail::kFail;
1202 }
1203 if (left->intersect(*right, &p, &alpha) && p.isFinite()) {
1204 Vertex* v;
1205 TESS_LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1206 Vertex* top = *current;
1207 // If the intersection point is above the current vertex, rewind to the vertex above the
1208 // intersection.
1209 while (top && c.sweep_lt(p, top->fPoint)) {
1210 top = top->fPrev;
1211 }
1212
1213 // Always clamp the intersection to lie between the vertices of each segment, since
1214 // in theory that's where the intersection is, but in reality, floating point error may
1215 // have computed an intersection beyond a vertex's component(s).
1216 p = clamp(p, left->fTop->fPoint, left->fBottom->fPoint, c);
1217 p = clamp(p, right->fTop->fPoint, right->fBottom->fPoint, c);
1218
1219 if (coincident(p, left->fTop->fPoint)) {
1220 v = left->fTop;
1221 } else if (coincident(p, left->fBottom->fPoint)) {
1222 v = left->fBottom;
1223 } else if (coincident(p, right->fTop->fPoint)) {
1224 v = right->fTop;
1225 } else if (coincident(p, right->fBottom->fPoint)) {
1226 v = right->fBottom;
1227 } else {
1228 v = this->makeSortedVertex(p, alpha, mesh, top, c);
1229 if (left->fTop->fPartner) {
1230 SkASSERT(fEmitCoverage); // Edge-AA only!
1231 v->fSynthetic = true;
1232 this->computeBisector(left, right, v);
1233 }
1234 }
1235 if (!rewind(activeEdges, current, top ? top : v, c)) {
1236 return BoolFail::kFail;
1237 }
1238 if (this->splitEdge(left, v, activeEdges, current, c) == BoolFail::kFail) {
1239 return BoolFail::kFail;
1240 }
1241 if (this->splitEdge(right, v, activeEdges, current, c) == BoolFail::kFail) {
1242 return BoolFail::kFail;
1243 }
1244 v->fAlpha = std::max(v->fAlpha, alpha);
1245 return BoolFail::kTrue;
1246 }
1247 return this->intersectEdgePair(left, right, activeEdges, current, c);
1248 }
1249
sanitizeContours(VertexList * contours,int contourCnt) const1250 void GrTriangulator::sanitizeContours(VertexList* contours, int contourCnt) const {
1251 for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1252 SkASSERT(contour->fHead);
1253 Vertex* prev = contour->fTail;
1254 prev->fPoint.fX = double_to_clamped_scalar((double) prev->fPoint.fX);
1255 prev->fPoint.fY = double_to_clamped_scalar((double) prev->fPoint.fY);
1256 if (fRoundVerticesToQuarterPixel) {
1257 round(&prev->fPoint);
1258 }
1259 for (Vertex* v = contour->fHead; v;) {
1260 v->fPoint.fX = double_to_clamped_scalar((double) v->fPoint.fX);
1261 v->fPoint.fY = double_to_clamped_scalar((double) v->fPoint.fY);
1262 if (fRoundVerticesToQuarterPixel) {
1263 round(&v->fPoint);
1264 }
1265 Vertex* next = v->fNext;
1266 Vertex* nextWrap = next ? next : contour->fHead;
1267 if (coincident(prev->fPoint, v->fPoint)) {
1268 TESS_LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1269 contour->remove(v);
1270 } else if (!v->fPoint.isFinite()) {
1271 TESS_LOG("vertex %g,%g non-finite; removing\n", v->fPoint.fX, v->fPoint.fY);
1272 contour->remove(v);
1273 } else if (!fPreserveCollinearVertices &&
1274 Line(prev->fPoint, nextWrap->fPoint).dist(v->fPoint) == 0.0) {
1275 TESS_LOG("vertex %g,%g collinear; removing\n", v->fPoint.fX, v->fPoint.fY);
1276 contour->remove(v);
1277 } else {
1278 prev = v;
1279 }
1280 v = next;
1281 }
1282 }
1283 }
1284
mergeCoincidentVertices(VertexList * mesh,const Comparator & c) const1285 bool GrTriangulator::mergeCoincidentVertices(VertexList* mesh, const Comparator& c) const {
1286 if (!mesh->fHead) {
1287 return false;
1288 }
1289 bool merged = false;
1290 for (Vertex* v = mesh->fHead->fNext; v;) {
1291 Vertex* next = v->fNext;
1292 if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1293 v->fPoint = v->fPrev->fPoint;
1294 }
1295 if (coincident(v->fPrev->fPoint, v->fPoint)) {
1296 this->mergeVertices(v, v->fPrev, mesh, c);
1297 merged = true;
1298 }
1299 v = next;
1300 }
1301 return merged;
1302 }
1303
1304 // Stage 2: convert the contours to a mesh of edges connecting the vertices.
1305
buildEdges(VertexList * contours,int contourCnt,VertexList * mesh,const Comparator & c)1306 void GrTriangulator::buildEdges(VertexList* contours, int contourCnt, VertexList* mesh,
1307 const Comparator& c) {
1308 for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1309 Vertex* prev = contour->fTail;
1310 for (Vertex* v = contour->fHead; v;) {
1311 Vertex* next = v->fNext;
1312 this->makeConnectingEdge(prev, v, EdgeType::kInner, c);
1313 mesh->append(v);
1314 prev = v;
1315 v = next;
1316 }
1317 }
1318 }
1319
1320 template <CompareFunc sweep_lt>
sorted_merge(VertexList * front,VertexList * back,VertexList * result)1321 static void sorted_merge(VertexList* front, VertexList* back, VertexList* result) {
1322 Vertex* a = front->fHead;
1323 Vertex* b = back->fHead;
1324 while (a && b) {
1325 if (sweep_lt(a->fPoint, b->fPoint)) {
1326 front->remove(a);
1327 result->append(a);
1328 a = front->fHead;
1329 } else {
1330 back->remove(b);
1331 result->append(b);
1332 b = back->fHead;
1333 }
1334 }
1335 result->append(*front);
1336 result->append(*back);
1337 }
1338
SortedMerge(VertexList * front,VertexList * back,VertexList * result,const Comparator & c)1339 void GrTriangulator::SortedMerge(VertexList* front, VertexList* back, VertexList* result,
1340 const Comparator& c) {
1341 if (c.fDirection == Comparator::Direction::kHorizontal) {
1342 sorted_merge<sweep_lt_horiz>(front, back, result);
1343 } else {
1344 sorted_merge<sweep_lt_vert>(front, back, result);
1345 }
1346 #if TRIANGULATOR_LOGGING
1347 float id = 0.0f;
1348 for (Vertex* v = result->fHead; v; v = v->fNext) {
1349 v->fID = id++;
1350 }
1351 #endif
1352 }
1353
1354 // Stage 3: sort the vertices by increasing sweep direction.
1355
1356 template <CompareFunc sweep_lt>
merge_sort(VertexList * vertices)1357 static void merge_sort(VertexList* vertices) {
1358 Vertex* slow = vertices->fHead;
1359 if (!slow) {
1360 return;
1361 }
1362 Vertex* fast = slow->fNext;
1363 if (!fast) {
1364 return;
1365 }
1366 do {
1367 fast = fast->fNext;
1368 if (fast) {
1369 fast = fast->fNext;
1370 slow = slow->fNext;
1371 }
1372 } while (fast);
1373 VertexList front(vertices->fHead, slow);
1374 VertexList back(slow->fNext, vertices->fTail);
1375 front.fTail->fNext = back.fHead->fPrev = nullptr;
1376
1377 merge_sort<sweep_lt>(&front);
1378 merge_sort<sweep_lt>(&back);
1379
1380 vertices->fHead = vertices->fTail = nullptr;
1381 sorted_merge<sweep_lt>(&front, &back, vertices);
1382 }
1383
1384 #if TRIANGULATOR_LOGGING
dump() const1385 void VertexList::dump() const {
1386 for (Vertex* v = fHead; v; v = v->fNext) {
1387 TESS_LOG("vertex %g (%g, %g) alpha %d", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1388 if (Vertex* p = v->fPartner) {
1389 TESS_LOG(", partner %g (%g, %g) alpha %d\n",
1390 p->fID, p->fPoint.fX, p->fPoint.fY, p->fAlpha);
1391 } else {
1392 TESS_LOG(", null partner\n");
1393 }
1394 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1395 TESS_LOG(" edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1396 }
1397 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1398 TESS_LOG(" edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1399 }
1400 }
1401 }
1402 #endif
1403
1404 #ifdef SK_DEBUG
validate_edge_pair(Edge * left,Edge * right,const Comparator & c)1405 static void validate_edge_pair(Edge* left, Edge* right, const Comparator& c) {
1406 if (!left || !right) {
1407 return;
1408 }
1409 if (left->fTop == right->fTop) {
1410 SkASSERT(left->isLeftOf(*right->fBottom));
1411 SkASSERT(right->isRightOf(*left->fBottom));
1412 } else if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1413 SkASSERT(left->isLeftOf(*right->fTop));
1414 } else {
1415 SkASSERT(right->isRightOf(*left->fTop));
1416 }
1417 if (left->fBottom == right->fBottom) {
1418 SkASSERT(left->isLeftOf(*right->fTop));
1419 SkASSERT(right->isRightOf(*left->fTop));
1420 } else if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1421 SkASSERT(left->isLeftOf(*right->fBottom));
1422 } else {
1423 SkASSERT(right->isRightOf(*left->fBottom));
1424 }
1425 }
1426
validate_edge_list(EdgeList * edges,const Comparator & c)1427 static void validate_edge_list(EdgeList* edges, const Comparator& c) {
1428 Edge* left = edges->fHead;
1429 if (!left) {
1430 return;
1431 }
1432 for (Edge* right = left->fRight; right; right = right->fRight) {
1433 validate_edge_pair(left, right, c);
1434 left = right;
1435 }
1436 }
1437 #endif
1438
1439 // Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1440
simplify(VertexList * mesh,const Comparator & c)1441 GrTriangulator::SimplifyResult GrTriangulator::simplify(VertexList* mesh,
1442 const Comparator& c) {
1443 TESS_LOG("simplifying complex polygons\n");
1444
1445 int initialNumEdges = fNumEdges;
1446 int initialNumVertices = 0;
1447 for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1448 ++initialNumVertices;
1449 }
1450 int numSelfIntersections = 0;
1451
1452 EdgeList activeEdges;
1453 auto result = SimplifyResult::kAlreadySimple;
1454 int numVisitedVertices = 0;
1455 for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1456 ++numVisitedVertices;
1457 if (!v->isConnected()) {
1458 continue;
1459 }
1460
1461 // The max increase across all skps, svgs and gms with only the triangulating and SW path
1462 // renderers enabled and with the triangulator's maxVerbCount set to the Chrome value is
1463 // 17x.
1464 if (fNumEdges > 170*initialNumEdges) {
1465 return SimplifyResult::kFailed;
1466 }
1467
1468 if (numVisitedVertices > 170*initialNumVertices) {
1469 return SimplifyResult::kFailed;
1470 }
1471
1472 Edge* leftEnclosingEdge;
1473 Edge* rightEnclosingEdge;
1474 bool restartChecks;
1475 do {
1476 TESS_LOG("\nvertex %g: (%g,%g), alpha %d\n",
1477 v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1478 restartChecks = false;
1479 FindEnclosingEdges(*v, activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1480 v->fLeftEnclosingEdge = leftEnclosingEdge;
1481 v->fRightEnclosingEdge = rightEnclosingEdge;
1482 if (v->fFirstEdgeBelow) {
1483 for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1484 BoolFail l = this->checkForIntersection(
1485 leftEnclosingEdge, edge, &activeEdges, &v, mesh, c);
1486 if (l == BoolFail::kFail) {
1487 return SimplifyResult::kFailed;
1488 }
1489 if (l == BoolFail::kFalse) {
1490 BoolFail r = this->checkForIntersection(
1491 edge, rightEnclosingEdge, &activeEdges, &v, mesh, c);
1492 if (r == BoolFail::kFail) {
1493 return SimplifyResult::kFailed;
1494 }
1495 if (r == BoolFail::kFalse) {
1496 // Neither l and r are both false.
1497 continue;
1498 }
1499 }
1500
1501 // Either l or r are true.
1502 result = SimplifyResult::kFoundSelfIntersection;
1503 restartChecks = true;
1504 ++numSelfIntersections;
1505 break;
1506 } // for
1507 } else {
1508 BoolFail bf = this->checkForIntersection(
1509 leftEnclosingEdge, rightEnclosingEdge, &activeEdges, &v, mesh, c);
1510 if (bf == BoolFail::kFail) {
1511 return SimplifyResult::kFailed;
1512 }
1513 if (bf == BoolFail::kTrue) {
1514 result = SimplifyResult::kFoundSelfIntersection;
1515 restartChecks = true;
1516 ++numSelfIntersections;
1517 }
1518 }
1519
1520 // In pathological cases, a path can intersect itself millions of times. After 500,000
1521 // self-intersections are found, reject the path.
1522 if (numSelfIntersections > 500000) {
1523 return SimplifyResult::kFailed;
1524 }
1525 } while (restartChecks);
1526 #ifdef SK_DEBUG
1527 validate_edge_list(&activeEdges, c);
1528 #endif
1529 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1530 if (!activeEdges.remove(e)) {
1531 return SimplifyResult::kFailed;
1532 }
1533 }
1534 Edge* leftEdge = leftEnclosingEdge;
1535 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1536 activeEdges.insert(e, leftEdge);
1537 leftEdge = e;
1538 }
1539 }
1540 SkASSERT(!activeEdges.fHead && !activeEdges.fTail);
1541 return result;
1542 }
1543
1544 // Stage 5: Tessellate the simplified mesh into monotone polygons.
1545
tessellate(const VertexList & vertices,const Comparator &)1546 std::tuple<Poly*, bool> GrTriangulator::tessellate(const VertexList& vertices, const Comparator&) {
1547 TESS_LOG("\ntessellating simple polygons\n");
1548 EdgeList activeEdges;
1549 Poly* polys = nullptr;
1550 for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1551 if (!v->isConnected()) {
1552 continue;
1553 }
1554 #if TRIANGULATOR_LOGGING
1555 TESS_LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1556 #endif
1557 Edge* leftEnclosingEdge;
1558 Edge* rightEnclosingEdge;
1559 FindEnclosingEdges(*v, activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1560 Poly* leftPoly;
1561 Poly* rightPoly;
1562 if (v->fFirstEdgeAbove) {
1563 leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1564 rightPoly = v->fLastEdgeAbove->fRightPoly;
1565 } else {
1566 leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1567 rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1568 }
1569 #if TRIANGULATOR_LOGGING
1570 TESS_LOG("edges above:\n");
1571 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1572 TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1573 e->fTop->fID, e->fBottom->fID,
1574 e->fLeftPoly ? e->fLeftPoly->fID : -1,
1575 e->fRightPoly ? e->fRightPoly->fID : -1);
1576 }
1577 TESS_LOG("edges below:\n");
1578 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1579 TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1580 e->fTop->fID, e->fBottom->fID,
1581 e->fLeftPoly ? e->fLeftPoly->fID : -1,
1582 e->fRightPoly ? e->fRightPoly->fID : -1);
1583 }
1584 #endif
1585 if (v->fFirstEdgeAbove) {
1586 if (leftPoly) {
1587 leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Side::kRight, this);
1588 }
1589 if (rightPoly) {
1590 rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Side::kLeft, this);
1591 }
1592 for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1593 Edge* rightEdge = e->fNextEdgeAbove;
1594 activeEdges.remove(e);
1595 if (e->fRightPoly) {
1596 e->fRightPoly->addEdge(e, Side::kLeft, this);
1597 }
1598 if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1599 rightEdge->fLeftPoly->addEdge(e, Side::kRight, this);
1600 }
1601 }
1602 activeEdges.remove(v->fLastEdgeAbove);
1603 if (!v->fFirstEdgeBelow) {
1604 if (leftPoly && rightPoly && leftPoly != rightPoly) {
1605 SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1606 rightPoly->fPartner = leftPoly;
1607 leftPoly->fPartner = rightPoly;
1608 }
1609 }
1610 }
1611 if (v->fFirstEdgeBelow) {
1612 if (!v->fFirstEdgeAbove) {
1613 if (leftPoly && rightPoly) {
1614 if (leftPoly == rightPoly) {
1615 if (leftPoly->fTail && leftPoly->fTail->fSide == Side::kLeft) {
1616 leftPoly = this->makePoly(&polys, leftPoly->lastVertex(),
1617 leftPoly->fWinding);
1618 leftEnclosingEdge->fRightPoly = leftPoly;
1619 } else {
1620 rightPoly = this->makePoly(&polys, rightPoly->lastVertex(),
1621 rightPoly->fWinding);
1622 rightEnclosingEdge->fLeftPoly = rightPoly;
1623 }
1624 }
1625 Edge* join = this->allocateEdge(leftPoly->lastVertex(), v, 1, EdgeType::kInner);
1626 leftPoly = leftPoly->addEdge(join, Side::kRight, this);
1627 rightPoly = rightPoly->addEdge(join, Side::kLeft, this);
1628 }
1629 }
1630 Edge* leftEdge = v->fFirstEdgeBelow;
1631 leftEdge->fLeftPoly = leftPoly;
1632 activeEdges.insert(leftEdge, leftEnclosingEdge);
1633 for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1634 rightEdge = rightEdge->fNextEdgeBelow) {
1635 activeEdges.insert(rightEdge, leftEdge);
1636 int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1637 winding += leftEdge->fWinding;
1638 if (winding != 0) {
1639 Poly* poly = this->makePoly(&polys, v, winding);
1640 leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1641 }
1642 leftEdge = rightEdge;
1643 }
1644 v->fLastEdgeBelow->fRightPoly = rightPoly;
1645 }
1646 #if TRIANGULATOR_LOGGING
1647 TESS_LOG("\nactive edges:\n");
1648 for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1649 TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1650 e->fTop->fID, e->fBottom->fID,
1651 e->fLeftPoly ? e->fLeftPoly->fID : -1,
1652 e->fRightPoly ? e->fRightPoly->fID : -1);
1653 }
1654 #endif
1655 }
1656 return { polys, true };
1657 }
1658
1659 // This is a driver function that calls stages 2-5 in turn.
1660
contoursToMesh(VertexList * contours,int contourCnt,VertexList * mesh,const Comparator & c)1661 void GrTriangulator::contoursToMesh(VertexList* contours, int contourCnt, VertexList* mesh,
1662 const Comparator& c) {
1663 #if TRIANGULATOR_LOGGING
1664 for (int i = 0; i < contourCnt; ++i) {
1665 Vertex* v = contours[i].fHead;
1666 SkASSERT(v);
1667 TESS_LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1668 for (v = v->fNext; v; v = v->fNext) {
1669 TESS_LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1670 }
1671 }
1672 #endif
1673 this->sanitizeContours(contours, contourCnt);
1674 this->buildEdges(contours, contourCnt, mesh, c);
1675 }
1676
SortMesh(VertexList * vertices,const Comparator & c)1677 void GrTriangulator::SortMesh(VertexList* vertices, const Comparator& c) {
1678 if (!vertices || !vertices->fHead) {
1679 return;
1680 }
1681
1682 // Sort vertices in Y (secondarily in X).
1683 if (c.fDirection == Comparator::Direction::kHorizontal) {
1684 merge_sort<sweep_lt_horiz>(vertices);
1685 } else {
1686 merge_sort<sweep_lt_vert>(vertices);
1687 }
1688 #if TRIANGULATOR_LOGGING
1689 for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
1690 static float gID = 0.0f;
1691 v->fID = gID++;
1692 }
1693 #endif
1694 }
1695
contoursToPolys(VertexList * contours,int contourCnt)1696 std::tuple<Poly*, bool> GrTriangulator::contoursToPolys(VertexList* contours, int contourCnt) {
1697 const SkRect& pathBounds = fPath.getBounds();
1698 Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
1699 : Comparator::Direction::kVertical);
1700 VertexList mesh;
1701 this->contoursToMesh(contours, contourCnt, &mesh, c);
1702 TESS_LOG("\ninitial mesh:\n");
1703 DUMP_MESH(mesh);
1704 SortMesh(&mesh, c);
1705 TESS_LOG("\nsorted mesh:\n");
1706 DUMP_MESH(mesh);
1707 this->mergeCoincidentVertices(&mesh, c);
1708 TESS_LOG("\nsorted+merged mesh:\n");
1709 DUMP_MESH(mesh);
1710 auto result = this->simplify(&mesh, c);
1711 if (result == SimplifyResult::kFailed) {
1712 return { nullptr, false };
1713 }
1714 TESS_LOG("\nsimplified mesh:\n");
1715 DUMP_MESH(mesh);
1716 return this->tessellate(mesh, c);
1717 }
1718
1719 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
polysToTriangles(Poly * polys,SkPathFillType overrideFillType,skgpu::VertexWriter data) const1720 skgpu::VertexWriter GrTriangulator::polysToTriangles(Poly* polys,
1721 SkPathFillType overrideFillType,
1722 skgpu::VertexWriter data) const {
1723 for (Poly* poly = polys; poly; poly = poly->fNext) {
1724 if (apply_fill_type(overrideFillType, poly)) {
1725 data = this->emitPoly(poly, std::move(data));
1726 }
1727 }
1728 return data;
1729 }
1730
get_contour_count(const SkPath & path,SkScalar tolerance)1731 static int get_contour_count(const SkPath& path, SkScalar tolerance) {
1732 // We could theoretically be more aggressive about not counting empty contours, but we need to
1733 // actually match the exact number of contour linked lists the tessellator will create later on.
1734 int contourCnt = 1;
1735 bool hasPoints = false;
1736
1737 SkPath::Iter iter(path, false);
1738 SkPath::Verb verb;
1739 SkPoint pts[4];
1740 bool first = true;
1741 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
1742 switch (verb) {
1743 case SkPath::kMove_Verb:
1744 if (!first) {
1745 ++contourCnt;
1746 }
1747 [[fallthrough]];
1748 case SkPath::kLine_Verb:
1749 case SkPath::kConic_Verb:
1750 case SkPath::kQuad_Verb:
1751 case SkPath::kCubic_Verb:
1752 hasPoints = true;
1753 break;
1754 default:
1755 break;
1756 }
1757 first = false;
1758 }
1759 if (!hasPoints) {
1760 return 0;
1761 }
1762 return contourCnt;
1763 }
1764
pathToPolys(float tolerance,const SkRect & clipBounds,bool * isLinear)1765 std::tuple<Poly*, bool> GrTriangulator::pathToPolys(float tolerance, const SkRect& clipBounds, bool* isLinear) {
1766 int contourCnt = get_contour_count(fPath, tolerance);
1767 if (contourCnt <= 0) {
1768 *isLinear = true;
1769 return { nullptr, true };
1770 }
1771
1772 if (SkPathFillType_IsInverse(fPath.getFillType())) {
1773 contourCnt++;
1774 }
1775 std::unique_ptr<VertexList[]> contours(new VertexList[contourCnt]);
1776
1777 this->pathToContours(tolerance, clipBounds, contours.get(), isLinear);
1778 return this->contoursToPolys(contours.get(), contourCnt);
1779 }
1780
CountPoints(Poly * polys,SkPathFillType overrideFillType)1781 int64_t GrTriangulator::CountPoints(Poly* polys, SkPathFillType overrideFillType) {
1782 int64_t count = 0;
1783 for (Poly* poly = polys; poly; poly = poly->fNext) {
1784 if (apply_fill_type(overrideFillType, poly) && poly->fCount >= 3) {
1785 count += (poly->fCount - 2) * (TRIANGULATOR_WIREFRAME ? 6 : 3);
1786 }
1787 }
1788 return count;
1789 }
1790
1791 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
1792
polysToTriangles(Poly * polys,GrEagerVertexAllocator * vertexAllocator) const1793 int GrTriangulator::polysToTriangles(Poly* polys, GrEagerVertexAllocator* vertexAllocator) const {
1794 int64_t count64 = CountPoints(polys, fPath.getFillType());
1795 if (0 == count64 || count64 > SK_MaxS32) {
1796 return 0;
1797 }
1798 int count = count64;
1799
1800 size_t vertexStride = sizeof(SkPoint);
1801 if (fEmitCoverage) {
1802 vertexStride += sizeof(float);
1803 }
1804 skgpu::VertexWriter verts = vertexAllocator->lockWriter(vertexStride, count);
1805 if (!verts) {
1806 SkDebugf("Could not allocate vertices\n");
1807 return 0;
1808 }
1809
1810 TESS_LOG("emitting %d verts\n", count);
1811
1812 skgpu::BufferWriter::Mark start = verts.mark();
1813 verts = this->polysToTriangles(polys, fPath.getFillType(), std::move(verts));
1814
1815 int actualCount = static_cast<int>((verts.mark() - start) / vertexStride);
1816 SkASSERT(actualCount <= count);
1817 vertexAllocator->unlock(actualCount);
1818 return actualCount;
1819 }
1820
1821 #endif // SK_ENABLE_OPTIMIZE_SIZE
1822