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