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