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