blob: 30be341e0edc13fb882fb47d7d328a52e950a694 [file] [log] [blame]
senorblancod6ed19c2015-02-26 06:58:17 -08001/*
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 "GrTessellatingPathRenderer.h"
9
senorblanco9ba39722015-03-05 07:13:42 -080010#include "GrBatchTarget.h"
joshualitt2fbd4062015-05-07 13:06:41 -070011#include "GrBatchTest.h"
senorblancod6ed19c2015-02-26 06:58:17 -080012#include "GrDefaultGeoProcFactory.h"
13#include "GrPathUtils.h"
bsalomoncb8979d2015-05-05 09:51:38 -070014#include "GrVertices.h"
senorblanco84cd6212015-08-04 10:01:58 -070015#include "GrResourceCache.h"
16#include "GrResourceProvider.h"
senorblancod6ed19c2015-02-26 06:58:17 -080017#include "SkChunkAlloc.h"
18#include "SkGeometry.h"
19
joshualitt74417822015-08-07 11:42:16 -070020#include "batches/GrBatch.h"
21
senorblancod6ed19c2015-02-26 06:58:17 -080022#include <stdio.h>
23
24/*
25 * This path renderer tessellates the path into triangles, uploads the triangles to a
26 * vertex buffer, and renders them with a single draw call. It does not currently do
27 * antialiasing, so it must be used in conjunction with multisampling.
28 *
29 * There are six stages to the algorithm:
30 *
31 * 1) Linearize the path contours into piecewise linear segments (path_to_contours()).
32 * 2) Build a mesh of edges connecting the vertices (build_edges()).
33 * 3) Sort the vertices in Y (and secondarily in X) (merge_sort()).
34 * 4) Simplify the mesh by inserting new vertices at intersecting edges (simplify()).
35 * 5) Tessellate the simplified mesh into monotone polygons (tessellate()).
36 * 6) Triangulate the monotone polygons directly into a vertex buffer (polys_to_triangles()).
37 *
38 * The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
39 * of vertices (and the necessity of inserting new vertices on intersection).
40 *
41 * Stages (4) and (5) use an active edge list, which a list of all edges for which the
42 * sweep line has crossed the top vertex, but not the bottom vertex. It's sorted
43 * left-to-right based on the point where both edges are active (when both top vertices
44 * have been seen, so the "lower" top vertex of the two). If the top vertices are equal
45 * (shared), it's sorted based on the last point where both edges are active, so the
46 * "upper" bottom vertex.
47 *
48 * The most complex step is the simplification (4). It's based on the Bentley-Ottman
49 * line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
50 * not exact and may violate the mesh topology or active edge list ordering. We
51 * accommodate this by adjusting the topology of the mesh and AEL to match the intersection
52 * points. This occurs in three ways:
53 *
54 * A) Intersections may cause a shortened edge to no longer be ordered with respect to its
55 * neighbouring edges at the top or bottom vertex. This is handled by merging the
56 * edges (merge_collinear_edges()).
57 * B) Intersections may cause an edge to violate the left-to-right ordering of the
58 * active edge list. This is handled by splitting the neighbour edge on the
59 * intersected vertex (cleanup_active_edges()).
60 * C) Shortening an edge may cause an active edge to become inactive or an inactive edge
61 * to become active. This is handled by removing or inserting the edge in the active
62 * edge list (fix_active_state()).
63 *
64 * The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
65 * Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
66 * currently uses a linked list for the active edge list, rather than a 2-3 tree as the
67 * paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
68 * become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
69 * insertions and removals was greater than the cost of infrequent O(N) lookups with the
70 * linked list implementation. With the latter, all removals are O(1), and most insertions
71 * are O(1), since we know the adjacent edge in the active edge list based on the topology.
72 * Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
73 * frequent. There may be other data structures worth investigating, however.
74 *
senorblanco6bd51372015-04-15 07:32:27 -070075 * Note that the orientation of the line sweep algorithms is determined by the aspect ratio of the
76 * path bounds. When the path is taller than it is wide, we sort vertices based on increasing Y
77 * coordinate, and secondarily by increasing X coordinate. When the path is wider than it is tall,
78 * we sort by increasing X coordinate, but secondarily by *decreasing* Y coordinate. This is so
79 * that the "left" and "right" orientation in the code remains correct (edges to the left are
80 * increasing in Y; edges to the right are decreasing in Y). That is, the setting rotates 90
81 * degrees counterclockwise, rather that transposing.
senorblancod6ed19c2015-02-26 06:58:17 -080082 */
83#define LOGGING_ENABLED 0
84#define WIREFRAME 0
senorblancod6ed19c2015-02-26 06:58:17 -080085
86#if LOGGING_ENABLED
87#define LOG printf
88#else
89#define LOG(...)
90#endif
91
92#define ALLOC_NEW(Type, args, alloc) \
93 SkNEW_PLACEMENT_ARGS(alloc.allocThrow(sizeof(Type)), Type, args)
94
95namespace {
96
97struct Vertex;
98struct Edge;
99struct Poly;
100
101template <class T, T* T::*Prev, T* T::*Next>
102void insert(T* t, T* prev, T* next, T** head, T** tail) {
103 t->*Prev = prev;
104 t->*Next = next;
105 if (prev) {
106 prev->*Next = t;
107 } else if (head) {
108 *head = t;
109 }
110 if (next) {
111 next->*Prev = t;
112 } else if (tail) {
113 *tail = t;
114 }
115}
116
117template <class T, T* T::*Prev, T* T::*Next>
118void remove(T* t, T** head, T** tail) {
119 if (t->*Prev) {
120 t->*Prev->*Next = t->*Next;
121 } else if (head) {
122 *head = t->*Next;
123 }
124 if (t->*Next) {
125 t->*Next->*Prev = t->*Prev;
126 } else if (tail) {
127 *tail = t->*Prev;
128 }
129 t->*Prev = t->*Next = NULL;
130}
131
132/**
133 * Vertices are used in three ways: first, the path contours are converted into a
134 * circularly-linked list of Vertices for each contour. After edge construction, the same Vertices
135 * are re-ordered by the merge sort according to the sweep_lt comparator (usually, increasing
136 * in Y) using the same fPrev/fNext pointers that were used for the contours, to avoid
137 * reallocation. Finally, MonotonePolys are built containing a circularly-linked list of
138 * Vertices. (Currently, those Vertices are newly-allocated for the MonotonePolys, since
139 * an individual Vertex from the path mesh may belong to multiple
140 * MonotonePolys, so the original Vertices cannot be re-used.
141 */
142
143struct Vertex {
144 Vertex(const SkPoint& point)
145 : fPoint(point), fPrev(NULL), fNext(NULL)
146 , fFirstEdgeAbove(NULL), fLastEdgeAbove(NULL)
147 , fFirstEdgeBelow(NULL), fLastEdgeBelow(NULL)
148 , fProcessed(false)
149#if LOGGING_ENABLED
150 , fID (-1.0f)
151#endif
152 {}
153 SkPoint fPoint; // Vertex position
154 Vertex* fPrev; // Linked list of contours, then Y-sorted vertices.
155 Vertex* fNext; // "
156 Edge* fFirstEdgeAbove; // Linked list of edges above this vertex.
157 Edge* fLastEdgeAbove; // "
158 Edge* fFirstEdgeBelow; // Linked list of edges below this vertex.
159 Edge* fLastEdgeBelow; // "
160 bool fProcessed; // Has this vertex been seen in simplify()?
161#if LOGGING_ENABLED
162 float fID; // Identifier used for logging.
163#endif
164};
165
166/***************************************************************************************/
167
senorblanco6bd51372015-04-15 07:32:27 -0700168typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
169
170struct Comparator {
171 CompareFunc sweep_lt;
172 CompareFunc sweep_gt;
173};
174
175bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
senorblancod6ed19c2015-02-26 06:58:17 -0800176 return a.fX == b.fX ? a.fY > b.fY : a.fX < b.fX;
senorblancod6ed19c2015-02-26 06:58:17 -0800177}
178
senorblanco6bd51372015-04-15 07:32:27 -0700179bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
180 return a.fY == b.fY ? a.fX < b.fX : a.fY < b.fY;
181}
182
183bool sweep_gt_horiz(const SkPoint& a, const SkPoint& b) {
senorblancod6ed19c2015-02-26 06:58:17 -0800184 return a.fX == b.fX ? a.fY < b.fY : a.fX > b.fX;
senorblanco6bd51372015-04-15 07:32:27 -0700185}
186
187bool sweep_gt_vert(const SkPoint& a, const SkPoint& b) {
senorblancod6ed19c2015-02-26 06:58:17 -0800188 return a.fY == b.fY ? a.fX > b.fX : a.fY > b.fY;
senorblancod6ed19c2015-02-26 06:58:17 -0800189}
190
senorblancod4d83eb2015-05-14 09:08:14 -0700191inline SkPoint* emit_vertex(Vertex* v, SkPoint* data) {
192 *data++ = v->fPoint;
193 return data;
senorblancod6ed19c2015-02-26 06:58:17 -0800194}
195
senorblancod4d83eb2015-05-14 09:08:14 -0700196SkPoint* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, SkPoint* data) {
senorblancod6ed19c2015-02-26 06:58:17 -0800197#if WIREFRAME
198 data = emit_vertex(v0, data);
199 data = emit_vertex(v1, data);
200 data = emit_vertex(v1, data);
201 data = emit_vertex(v2, data);
202 data = emit_vertex(v2, data);
203 data = emit_vertex(v0, data);
204#else
205 data = emit_vertex(v0, data);
206 data = emit_vertex(v1, data);
207 data = emit_vertex(v2, data);
208#endif
209 return data;
210}
211
senorblanco5b9f42c2015-04-16 11:47:18 -0700212struct EdgeList {
213 EdgeList() : fHead(NULL), fTail(NULL) {}
214 Edge* fHead;
215 Edge* fTail;
216};
217
senorblancod6ed19c2015-02-26 06:58:17 -0800218/**
219 * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
220 * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
221 * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
222 * point). For speed, that case is only tested by the callers which require it (e.g.,
223 * cleanup_active_edges()). Edges also handle checking for intersection with other edges.
224 * Currently, this converts the edges to the parametric form, in order to avoid doing a division
225 * until an intersection has been confirmed. This is slightly slower in the "found" case, but
226 * a lot faster in the "not found" case.
227 *
228 * The coefficients of the line equation stored in double precision to avoid catastrphic
229 * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
230 * correct in float, since it's a polynomial of degree 2. The intersect() function, being
231 * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
232 * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
233 * this file).
234 */
235
236struct Edge {
237 Edge(Vertex* top, Vertex* bottom, int winding)
238 : fWinding(winding)
239 , fTop(top)
240 , fBottom(bottom)
241 , fLeft(NULL)
242 , fRight(NULL)
243 , fPrevEdgeAbove(NULL)
244 , fNextEdgeAbove(NULL)
245 , fPrevEdgeBelow(NULL)
246 , fNextEdgeBelow(NULL)
247 , fLeftPoly(NULL)
248 , fRightPoly(NULL) {
249 recompute();
250 }
251 int fWinding; // 1 == edge goes downward; -1 = edge goes upward.
252 Vertex* fTop; // The top vertex in vertex-sort-order (sweep_lt).
253 Vertex* fBottom; // The bottom vertex in vertex-sort-order.
254 Edge* fLeft; // The linked list of edges in the active edge list.
255 Edge* fRight; // "
256 Edge* fPrevEdgeAbove; // The linked list of edges in the bottom Vertex's "edges above".
257 Edge* fNextEdgeAbove; // "
258 Edge* fPrevEdgeBelow; // The linked list of edges in the top Vertex's "edges below".
259 Edge* fNextEdgeBelow; // "
260 Poly* fLeftPoly; // The Poly to the left of this edge, if any.
261 Poly* fRightPoly; // The Poly to the right of this edge, if any.
262 double fDX; // The line equation for this edge, in implicit form.
263 double fDY; // fDY * x + fDX * y + fC = 0, for point (x, y) on the line.
264 double fC;
265 double dist(const SkPoint& p) const {
266 return fDY * p.fX - fDX * p.fY + fC;
267 }
268 bool isRightOf(Vertex* v) const {
269 return dist(v->fPoint) < 0.0;
270 }
271 bool isLeftOf(Vertex* v) const {
272 return dist(v->fPoint) > 0.0;
273 }
274 void recompute() {
275 fDX = static_cast<double>(fBottom->fPoint.fX) - fTop->fPoint.fX;
276 fDY = static_cast<double>(fBottom->fPoint.fY) - fTop->fPoint.fY;
277 fC = static_cast<double>(fTop->fPoint.fY) * fBottom->fPoint.fX -
278 static_cast<double>(fTop->fPoint.fX) * fBottom->fPoint.fY;
279 }
280 bool intersect(const Edge& other, SkPoint* p) {
281 LOG("intersecting %g -> %g with %g -> %g\n",
282 fTop->fID, fBottom->fID,
283 other.fTop->fID, other.fBottom->fID);
284 if (fTop == other.fTop || fBottom == other.fBottom) {
285 return false;
286 }
287 double denom = fDX * other.fDY - fDY * other.fDX;
288 if (denom == 0.0) {
289 return false;
290 }
291 double dx = static_cast<double>(fTop->fPoint.fX) - other.fTop->fPoint.fX;
292 double dy = static_cast<double>(fTop->fPoint.fY) - other.fTop->fPoint.fY;
293 double sNumer = dy * other.fDX - dx * other.fDY;
294 double tNumer = dy * fDX - dx * fDY;
295 // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
296 // This saves us doing the divide below unless absolutely necessary.
297 if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
298 : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
299 return false;
300 }
301 double s = sNumer / denom;
302 SkASSERT(s >= 0.0 && s <= 1.0);
303 p->fX = SkDoubleToScalar(fTop->fPoint.fX + s * fDX);
304 p->fY = SkDoubleToScalar(fTop->fPoint.fY + s * fDY);
305 return true;
306 }
senorblanco5b9f42c2015-04-16 11:47:18 -0700307 bool isActive(EdgeList* activeEdges) const {
308 return activeEdges && (fLeft || fRight || activeEdges->fHead == this);
senorblancod6ed19c2015-02-26 06:58:17 -0800309 }
310};
311
312/***************************************************************************************/
313
314struct Poly {
315 Poly(int winding)
316 : fWinding(winding)
317 , fHead(NULL)
318 , fTail(NULL)
319 , fActive(NULL)
320 , fNext(NULL)
321 , fPartner(NULL)
322 , fCount(0)
323 {
324#if LOGGING_ENABLED
325 static int gID = 0;
326 fID = gID++;
327 LOG("*** created Poly %d\n", fID);
328#endif
329 }
330 typedef enum { kNeither_Side, kLeft_Side, kRight_Side } Side;
331 struct MonotonePoly {
332 MonotonePoly()
333 : fSide(kNeither_Side)
334 , fHead(NULL)
335 , fTail(NULL)
336 , fPrev(NULL)
337 , fNext(NULL) {}
338 Side fSide;
339 Vertex* fHead;
340 Vertex* fTail;
341 MonotonePoly* fPrev;
342 MonotonePoly* fNext;
343 bool addVertex(Vertex* v, Side side, SkChunkAlloc& alloc) {
344 Vertex* newV = ALLOC_NEW(Vertex, (v->fPoint), alloc);
345 bool done = false;
346 if (fSide == kNeither_Side) {
347 fSide = side;
348 } else {
349 done = side != fSide;
350 }
351 if (fHead == NULL) {
352 fHead = fTail = newV;
353 } else if (fSide == kRight_Side) {
354 newV->fPrev = fTail;
355 fTail->fNext = newV;
356 fTail = newV;
357 } else {
358 newV->fNext = fHead;
359 fHead->fPrev = newV;
360 fHead = newV;
361 }
362 return done;
363 }
364
senorblancod4d83eb2015-05-14 09:08:14 -0700365 SkPoint* emit(SkPoint* data) {
senorblancod6ed19c2015-02-26 06:58:17 -0800366 Vertex* first = fHead;
367 Vertex* v = first->fNext;
368 while (v != fTail) {
369 SkASSERT(v && v->fPrev && v->fNext);
senorblancod6ed19c2015-02-26 06:58:17 -0800370 Vertex* prev = v->fPrev;
371 Vertex* curr = v;
372 Vertex* next = v->fNext;
373 double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
374 double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
375 double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
376 double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
377 if (ax * by - ay * bx >= 0.0) {
378 data = emit_triangle(prev, curr, next, data);
379 v->fPrev->fNext = v->fNext;
380 v->fNext->fPrev = v->fPrev;
381 if (v->fPrev == first) {
382 v = v->fNext;
383 } else {
384 v = v->fPrev;
385 }
386 } else {
387 v = v->fNext;
senorblancod6ed19c2015-02-26 06:58:17 -0800388 }
389 }
390 return data;
391 }
senorblancod6ed19c2015-02-26 06:58:17 -0800392 };
393 Poly* addVertex(Vertex* v, Side side, SkChunkAlloc& alloc) {
394 LOG("addVertex() to %d at %g (%g, %g), %s side\n", fID, v->fID, v->fPoint.fX, v->fPoint.fY,
395 side == kLeft_Side ? "left" : side == kRight_Side ? "right" : "neither");
396 Poly* partner = fPartner;
397 Poly* poly = this;
398 if (partner) {
399 fPartner = partner->fPartner = NULL;
400 }
401 if (!fActive) {
402 fActive = ALLOC_NEW(MonotonePoly, (), alloc);
403 }
404 if (fActive->addVertex(v, side, alloc)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800405 if (fTail) {
406 fActive->fPrev = fTail;
407 fTail->fNext = fActive;
408 fTail = fActive;
409 } else {
410 fHead = fTail = fActive;
411 }
412 if (partner) {
413 partner->addVertex(v, side, alloc);
414 poly = partner;
415 } else {
416 Vertex* prev = fActive->fSide == Poly::kLeft_Side ?
417 fActive->fHead->fNext : fActive->fTail->fPrev;
418 fActive = ALLOC_NEW(MonotonePoly, , alloc);
419 fActive->addVertex(prev, Poly::kNeither_Side, alloc);
420 fActive->addVertex(v, side, alloc);
421 }
422 }
423 fCount++;
424 return poly;
425 }
426 void end(Vertex* v, SkChunkAlloc& alloc) {
427 LOG("end() %d at %g, %g\n", fID, v->fPoint.fX, v->fPoint.fY);
428 if (fPartner) {
429 fPartner = fPartner->fPartner = NULL;
430 }
431 addVertex(v, fActive->fSide == kLeft_Side ? kRight_Side : kLeft_Side, alloc);
432 }
senorblancod4d83eb2015-05-14 09:08:14 -0700433 SkPoint* emit(SkPoint *data) {
senorblancod6ed19c2015-02-26 06:58:17 -0800434 if (fCount < 3) {
435 return data;
436 }
437 LOG("emit() %d, size %d\n", fID, fCount);
438 for (MonotonePoly* m = fHead; m != NULL; m = m->fNext) {
439 data = m->emit(data);
440 }
441 return data;
442 }
443 int fWinding;
444 MonotonePoly* fHead;
445 MonotonePoly* fTail;
446 MonotonePoly* fActive;
447 Poly* fNext;
448 Poly* fPartner;
449 int fCount;
450#if LOGGING_ENABLED
451 int fID;
452#endif
453};
454
455/***************************************************************************************/
456
457bool coincident(const SkPoint& a, const SkPoint& b) {
458 return a == b;
459}
460
461Poly* new_poly(Poly** head, Vertex* v, int winding, SkChunkAlloc& alloc) {
462 Poly* poly = ALLOC_NEW(Poly, (winding), alloc);
463 poly->addVertex(v, Poly::kNeither_Side, alloc);
464 poly->fNext = *head;
465 *head = poly;
466 return poly;
467}
468
senorblancod6ed19c2015-02-26 06:58:17 -0800469Vertex* append_point_to_contour(const SkPoint& p, Vertex* prev, Vertex** head,
470 SkChunkAlloc& alloc) {
471 Vertex* v = ALLOC_NEW(Vertex, (p), alloc);
472#if LOGGING_ENABLED
473 static float gID = 0.0f;
474 v->fID = gID++;
475#endif
476 if (prev) {
477 prev->fNext = v;
478 v->fPrev = prev;
479 } else {
480 *head = v;
481 }
482 return v;
483}
484
485Vertex* generate_quadratic_points(const SkPoint& p0,
486 const SkPoint& p1,
487 const SkPoint& p2,
488 SkScalar tolSqd,
489 Vertex* prev,
490 Vertex** head,
491 int pointsLeft,
492 SkChunkAlloc& alloc) {
493 SkScalar d = p1.distanceToLineSegmentBetweenSqd(p0, p2);
494 if (pointsLeft < 2 || d < tolSqd || !SkScalarIsFinite(d)) {
495 return append_point_to_contour(p2, prev, head, alloc);
496 }
497
498 const SkPoint q[] = {
499 { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
500 { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
501 };
502 const SkPoint r = { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) };
503
504 pointsLeft >>= 1;
505 prev = generate_quadratic_points(p0, q[0], r, tolSqd, prev, head, pointsLeft, alloc);
506 prev = generate_quadratic_points(r, q[1], p2, tolSqd, prev, head, pointsLeft, alloc);
507 return prev;
508}
509
510Vertex* generate_cubic_points(const SkPoint& p0,
511 const SkPoint& p1,
512 const SkPoint& p2,
513 const SkPoint& p3,
514 SkScalar tolSqd,
515 Vertex* prev,
516 Vertex** head,
517 int pointsLeft,
518 SkChunkAlloc& alloc) {
519 SkScalar d1 = p1.distanceToLineSegmentBetweenSqd(p0, p3);
520 SkScalar d2 = p2.distanceToLineSegmentBetweenSqd(p0, p3);
521 if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
522 !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
523 return append_point_to_contour(p3, prev, head, alloc);
524 }
525 const SkPoint q[] = {
526 { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
527 { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
528 { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
529 };
530 const SkPoint r[] = {
531 { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
532 { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
533 };
534 const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
535 pointsLeft >>= 1;
536 prev = generate_cubic_points(p0, q[0], r[0], s, tolSqd, prev, head, pointsLeft, alloc);
537 prev = generate_cubic_points(s, r[1], q[2], p3, tolSqd, prev, head, pointsLeft, alloc);
538 return prev;
539}
540
541// Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
542
543void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
senorblanco84cd6212015-08-04 10:01:58 -0700544 Vertex** contours, SkChunkAlloc& alloc, bool *isLinear) {
senorblancod6ed19c2015-02-26 06:58:17 -0800545
546 SkScalar toleranceSqd = tolerance * tolerance;
547
548 SkPoint pts[4];
549 bool done = false;
senorblanco84cd6212015-08-04 10:01:58 -0700550 *isLinear = true;
senorblancod6ed19c2015-02-26 06:58:17 -0800551 SkPath::Iter iter(path, false);
552 Vertex* prev = NULL;
553 Vertex* head = NULL;
554 if (path.isInverseFillType()) {
555 SkPoint quad[4];
556 clipBounds.toQuad(quad);
557 for (int i = 3; i >= 0; i--) {
558 prev = append_point_to_contour(quad[i], prev, &head, alloc);
559 }
560 head->fPrev = prev;
561 prev->fNext = head;
562 *contours++ = head;
563 head = prev = NULL;
564 }
565 SkAutoConicToQuads converter;
566 while (!done) {
567 SkPath::Verb verb = iter.next(pts);
568 switch (verb) {
569 case SkPath::kConic_Verb: {
570 SkScalar weight = iter.conicWeight();
571 const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
572 for (int i = 0; i < converter.countQuads(); ++i) {
senorblanco6d88bdb2015-04-20 05:41:48 -0700573 int pointsLeft = GrPathUtils::quadraticPointCount(quadPts, tolerance);
senorblancod6ed19c2015-02-26 06:58:17 -0800574 prev = generate_quadratic_points(quadPts[0], quadPts[1], quadPts[2],
575 toleranceSqd, prev, &head, pointsLeft, alloc);
576 quadPts += 2;
577 }
senorblanco84cd6212015-08-04 10:01:58 -0700578 *isLinear = false;
senorblancod6ed19c2015-02-26 06:58:17 -0800579 break;
580 }
581 case SkPath::kMove_Verb:
582 if (head) {
583 head->fPrev = prev;
584 prev->fNext = head;
585 *contours++ = head;
586 }
587 head = prev = NULL;
588 prev = append_point_to_contour(pts[0], prev, &head, alloc);
589 break;
590 case SkPath::kLine_Verb: {
591 prev = append_point_to_contour(pts[1], prev, &head, alloc);
592 break;
593 }
594 case SkPath::kQuad_Verb: {
senorblanco6d88bdb2015-04-20 05:41:48 -0700595 int pointsLeft = GrPathUtils::quadraticPointCount(pts, tolerance);
senorblancod6ed19c2015-02-26 06:58:17 -0800596 prev = generate_quadratic_points(pts[0], pts[1], pts[2], toleranceSqd, prev,
597 &head, pointsLeft, alloc);
senorblanco84cd6212015-08-04 10:01:58 -0700598 *isLinear = false;
senorblancod6ed19c2015-02-26 06:58:17 -0800599 break;
600 }
601 case SkPath::kCubic_Verb: {
senorblanco6d88bdb2015-04-20 05:41:48 -0700602 int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
senorblancod6ed19c2015-02-26 06:58:17 -0800603 prev = generate_cubic_points(pts[0], pts[1], pts[2], pts[3],
604 toleranceSqd, prev, &head, pointsLeft, alloc);
senorblanco84cd6212015-08-04 10:01:58 -0700605 *isLinear = false;
senorblancod6ed19c2015-02-26 06:58:17 -0800606 break;
607 }
608 case SkPath::kClose_Verb:
609 if (head) {
610 head->fPrev = prev;
611 prev->fNext = head;
612 *contours++ = head;
613 }
614 head = prev = NULL;
615 break;
616 case SkPath::kDone_Verb:
617 if (head) {
618 head->fPrev = prev;
619 prev->fNext = head;
620 *contours++ = head;
621 }
622 done = true;
623 break;
624 }
625 }
626}
627
628inline bool apply_fill_type(SkPath::FillType fillType, int winding) {
629 switch (fillType) {
630 case SkPath::kWinding_FillType:
631 return winding != 0;
632 case SkPath::kEvenOdd_FillType:
633 return (winding & 1) != 0;
634 case SkPath::kInverseWinding_FillType:
635 return winding == 1;
636 case SkPath::kInverseEvenOdd_FillType:
637 return (winding & 1) == 1;
638 default:
639 SkASSERT(false);
640 return false;
641 }
642}
643
senorblanco6bd51372015-04-15 07:32:27 -0700644Edge* new_edge(Vertex* prev, Vertex* next, SkChunkAlloc& alloc, Comparator& c) {
645 int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
senorblancod6ed19c2015-02-26 06:58:17 -0800646 Vertex* top = winding < 0 ? next : prev;
647 Vertex* bottom = winding < 0 ? prev : next;
648 return ALLOC_NEW(Edge, (top, bottom, winding), alloc);
649}
650
senorblanco5b9f42c2015-04-16 11:47:18 -0700651void remove_edge(Edge* edge, EdgeList* edges) {
senorblancod6ed19c2015-02-26 06:58:17 -0800652 LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
senorblanco5b9f42c2015-04-16 11:47:18 -0700653 SkASSERT(edge->isActive(edges));
654 remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &edges->fHead, &edges->fTail);
senorblancod6ed19c2015-02-26 06:58:17 -0800655}
656
senorblanco5b9f42c2015-04-16 11:47:18 -0700657void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
senorblancod6ed19c2015-02-26 06:58:17 -0800658 LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
senorblanco5b9f42c2015-04-16 11:47:18 -0700659 SkASSERT(!edge->isActive(edges));
660 Edge* next = prev ? prev->fRight : edges->fHead;
661 insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &edges->fHead, &edges->fTail);
senorblancod6ed19c2015-02-26 06:58:17 -0800662}
663
senorblanco5b9f42c2015-04-16 11:47:18 -0700664void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
senorblancod6ed19c2015-02-26 06:58:17 -0800665 if (v->fFirstEdgeAbove) {
666 *left = v->fFirstEdgeAbove->fLeft;
667 *right = v->fLastEdgeAbove->fRight;
668 return;
669 }
senorblanco5b9f42c2015-04-16 11:47:18 -0700670 Edge* next = NULL;
671 Edge* prev;
672 for (prev = edges->fTail; prev != NULL; prev = prev->fLeft) {
673 if (prev->isLeftOf(v)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800674 break;
675 }
senorblanco5b9f42c2015-04-16 11:47:18 -0700676 next = prev;
senorblancod6ed19c2015-02-26 06:58:17 -0800677 }
678 *left = prev;
679 *right = next;
680 return;
681}
682
senorblanco5b9f42c2015-04-16 11:47:18 -0700683void find_enclosing_edges(Edge* edge, EdgeList* edges, Comparator& c, Edge** left, Edge** right) {
senorblancod6ed19c2015-02-26 06:58:17 -0800684 Edge* prev = NULL;
685 Edge* next;
senorblanco5b9f42c2015-04-16 11:47:18 -0700686 for (next = edges->fHead; next != NULL; next = next->fRight) {
senorblanco6bd51372015-04-15 07:32:27 -0700687 if ((c.sweep_gt(edge->fTop->fPoint, next->fTop->fPoint) && next->isRightOf(edge->fTop)) ||
688 (c.sweep_gt(next->fTop->fPoint, edge->fTop->fPoint) && edge->isLeftOf(next->fTop)) ||
689 (c.sweep_lt(edge->fBottom->fPoint, next->fBottom->fPoint) &&
senorblancod6ed19c2015-02-26 06:58:17 -0800690 next->isRightOf(edge->fBottom)) ||
senorblanco6bd51372015-04-15 07:32:27 -0700691 (c.sweep_lt(next->fBottom->fPoint, edge->fBottom->fPoint) &&
senorblancod6ed19c2015-02-26 06:58:17 -0800692 edge->isLeftOf(next->fBottom))) {
693 break;
694 }
695 prev = next;
696 }
697 *left = prev;
698 *right = next;
699 return;
700}
701
senorblanco5b9f42c2015-04-16 11:47:18 -0700702void fix_active_state(Edge* edge, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800703 if (edge->isActive(activeEdges)) {
704 if (edge->fBottom->fProcessed || !edge->fTop->fProcessed) {
705 remove_edge(edge, activeEdges);
706 }
707 } else if (edge->fTop->fProcessed && !edge->fBottom->fProcessed) {
708 Edge* left;
709 Edge* right;
senorblanco5b9f42c2015-04-16 11:47:18 -0700710 find_enclosing_edges(edge, activeEdges, c, &left, &right);
senorblancod6ed19c2015-02-26 06:58:17 -0800711 insert_edge(edge, left, activeEdges);
712 }
713}
714
senorblanco6bd51372015-04-15 07:32:27 -0700715void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800716 if (edge->fTop->fPoint == edge->fBottom->fPoint ||
senorblanco6bd51372015-04-15 07:32:27 -0700717 c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800718 return;
719 }
720 LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
721 Edge* prev = NULL;
722 Edge* next;
723 for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
724 if (next->isRightOf(edge->fTop)) {
725 break;
726 }
727 prev = next;
728 }
729 insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
730 edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
731}
732
senorblanco6bd51372015-04-15 07:32:27 -0700733void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800734 if (edge->fTop->fPoint == edge->fBottom->fPoint ||
senorblanco6bd51372015-04-15 07:32:27 -0700735 c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800736 return;
737 }
738 LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
739 Edge* prev = NULL;
740 Edge* next;
741 for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
742 if (next->isRightOf(edge->fBottom)) {
743 break;
744 }
745 prev = next;
746 }
747 insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
748 edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
749}
750
751void remove_edge_above(Edge* edge) {
752 LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
753 edge->fBottom->fID);
754 remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
755 edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
756}
757
758void remove_edge_below(Edge* edge) {
759 LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
760 edge->fTop->fID);
761 remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
762 edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
763}
764
senorblanco5b9f42c2015-04-16 11:47:18 -0700765void erase_edge_if_zero_winding(Edge* edge, EdgeList* edges) {
senorblancod6ed19c2015-02-26 06:58:17 -0800766 if (edge->fWinding != 0) {
767 return;
768 }
769 LOG("erasing edge (%g -> %g)\n", edge->fTop->fID, edge->fBottom->fID);
770 remove_edge_above(edge);
771 remove_edge_below(edge);
senorblanco5b9f42c2015-04-16 11:47:18 -0700772 if (edge->isActive(edges)) {
773 remove_edge(edge, edges);
senorblancod6ed19c2015-02-26 06:58:17 -0800774 }
775}
776
senorblanco5b9f42c2015-04-16 11:47:18 -0700777void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c);
senorblancod6ed19c2015-02-26 06:58:17 -0800778
senorblanco5b9f42c2015-04-16 11:47:18 -0700779void set_top(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800780 remove_edge_below(edge);
781 edge->fTop = v;
782 edge->recompute();
senorblanco6bd51372015-04-15 07:32:27 -0700783 insert_edge_below(edge, v, c);
784 fix_active_state(edge, activeEdges, c);
785 merge_collinear_edges(edge, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800786}
787
senorblanco5b9f42c2015-04-16 11:47:18 -0700788void set_bottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800789 remove_edge_above(edge);
790 edge->fBottom = v;
791 edge->recompute();
senorblanco6bd51372015-04-15 07:32:27 -0700792 insert_edge_above(edge, v, c);
793 fix_active_state(edge, activeEdges, c);
794 merge_collinear_edges(edge, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800795}
796
senorblanco5b9f42c2015-04-16 11:47:18 -0700797void merge_edges_above(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800798 if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
799 LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
800 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
801 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
802 other->fWinding += edge->fWinding;
803 erase_edge_if_zero_winding(other, activeEdges);
804 edge->fWinding = 0;
805 erase_edge_if_zero_winding(edge, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700806 } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800807 other->fWinding += edge->fWinding;
808 erase_edge_if_zero_winding(other, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700809 set_bottom(edge, other->fTop, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800810 } else {
811 edge->fWinding += other->fWinding;
812 erase_edge_if_zero_winding(edge, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700813 set_bottom(other, edge->fTop, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800814 }
815}
816
senorblanco5b9f42c2015-04-16 11:47:18 -0700817void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800818 if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
819 LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
820 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
821 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
822 other->fWinding += edge->fWinding;
823 erase_edge_if_zero_winding(other, activeEdges);
824 edge->fWinding = 0;
825 erase_edge_if_zero_winding(edge, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700826 } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800827 edge->fWinding += other->fWinding;
828 erase_edge_if_zero_winding(edge, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700829 set_top(other, edge->fBottom, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800830 } else {
831 other->fWinding += edge->fWinding;
832 erase_edge_if_zero_winding(other, activeEdges);
senorblanco6bd51372015-04-15 07:32:27 -0700833 set_top(edge, other->fBottom, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800834 }
835}
836
senorblanco5b9f42c2015-04-16 11:47:18 -0700837void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -0800838 if (edge->fPrevEdgeAbove && (edge->fTop == edge->fPrevEdgeAbove->fTop ||
839 !edge->fPrevEdgeAbove->isLeftOf(edge->fTop))) {
senorblanco6bd51372015-04-15 07:32:27 -0700840 merge_edges_above(edge, edge->fPrevEdgeAbove, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800841 } else if (edge->fNextEdgeAbove && (edge->fTop == edge->fNextEdgeAbove->fTop ||
842 !edge->isLeftOf(edge->fNextEdgeAbove->fTop))) {
senorblanco6bd51372015-04-15 07:32:27 -0700843 merge_edges_above(edge, edge->fNextEdgeAbove, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800844 }
845 if (edge->fPrevEdgeBelow && (edge->fBottom == edge->fPrevEdgeBelow->fBottom ||
846 !edge->fPrevEdgeBelow->isLeftOf(edge->fBottom))) {
senorblanco6bd51372015-04-15 07:32:27 -0700847 merge_edges_below(edge, edge->fPrevEdgeBelow, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800848 } else if (edge->fNextEdgeBelow && (edge->fBottom == edge->fNextEdgeBelow->fBottom ||
849 !edge->isLeftOf(edge->fNextEdgeBelow->fBottom))) {
senorblanco6bd51372015-04-15 07:32:27 -0700850 merge_edges_below(edge, edge->fNextEdgeBelow, activeEdges, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800851 }
852}
853
senorblanco5b9f42c2015-04-16 11:47:18 -0700854void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800855
senorblanco5b9f42c2015-04-16 11:47:18 -0700856void cleanup_active_edges(Edge* edge, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -0800857 Vertex* top = edge->fTop;
858 Vertex* bottom = edge->fBottom;
859 if (edge->fLeft) {
860 Vertex* leftTop = edge->fLeft->fTop;
861 Vertex* leftBottom = edge->fLeft->fBottom;
senorblanco6bd51372015-04-15 07:32:27 -0700862 if (c.sweep_gt(top->fPoint, leftTop->fPoint) && !edge->fLeft->isLeftOf(top)) {
863 split_edge(edge->fLeft, edge->fTop, activeEdges, c, alloc);
864 } else if (c.sweep_gt(leftTop->fPoint, top->fPoint) && !edge->isRightOf(leftTop)) {
865 split_edge(edge, leftTop, activeEdges, c, alloc);
866 } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
867 !edge->fLeft->isLeftOf(bottom)) {
868 split_edge(edge->fLeft, bottom, activeEdges, c, alloc);
869 } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
870 split_edge(edge, leftBottom, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800871 }
872 }
873 if (edge->fRight) {
874 Vertex* rightTop = edge->fRight->fTop;
875 Vertex* rightBottom = edge->fRight->fBottom;
senorblanco6bd51372015-04-15 07:32:27 -0700876 if (c.sweep_gt(top->fPoint, rightTop->fPoint) && !edge->fRight->isRightOf(top)) {
877 split_edge(edge->fRight, top, activeEdges, c, alloc);
878 } else if (c.sweep_gt(rightTop->fPoint, top->fPoint) && !edge->isLeftOf(rightTop)) {
879 split_edge(edge, rightTop, activeEdges, c, alloc);
880 } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
senorblancod6ed19c2015-02-26 06:58:17 -0800881 !edge->fRight->isRightOf(bottom)) {
senorblanco6bd51372015-04-15 07:32:27 -0700882 split_edge(edge->fRight, bottom, activeEdges, c, alloc);
883 } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
senorblancod6ed19c2015-02-26 06:58:17 -0800884 !edge->isLeftOf(rightBottom)) {
senorblanco6bd51372015-04-15 07:32:27 -0700885 split_edge(edge, rightBottom, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800886 }
887 }
888}
889
senorblanco5b9f42c2015-04-16 11:47:18 -0700890void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -0800891 LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
892 edge->fTop->fID, edge->fBottom->fID,
893 v->fID, v->fPoint.fX, v->fPoint.fY);
senorblanco6bd51372015-04-15 07:32:27 -0700894 if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
895 set_top(edge, v, activeEdges, c);
896 } else if (c.sweep_gt(v->fPoint, edge->fBottom->fPoint)) {
897 set_bottom(edge, v, activeEdges, c);
senorblancoa2b6d282015-03-02 09:34:13 -0800898 } else {
899 Edge* newEdge = ALLOC_NEW(Edge, (v, edge->fBottom, edge->fWinding), alloc);
senorblanco6bd51372015-04-15 07:32:27 -0700900 insert_edge_below(newEdge, v, c);
901 insert_edge_above(newEdge, edge->fBottom, c);
902 set_bottom(edge, v, activeEdges, c);
903 cleanup_active_edges(edge, activeEdges, c, alloc);
904 fix_active_state(newEdge, activeEdges, c);
905 merge_collinear_edges(newEdge, activeEdges, c);
senorblancoa2b6d282015-03-02 09:34:13 -0800906 }
senorblancod6ed19c2015-02-26 06:58:17 -0800907}
908
senorblanco6bd51372015-04-15 07:32:27 -0700909void merge_vertices(Vertex* src, Vertex* dst, Vertex** head, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -0800910 LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
911 src->fID, dst->fID);
912 for (Edge* edge = src->fFirstEdgeAbove; edge;) {
913 Edge* next = edge->fNextEdgeAbove;
senorblanco6bd51372015-04-15 07:32:27 -0700914 set_bottom(edge, dst, NULL, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800915 edge = next;
916 }
917 for (Edge* edge = src->fFirstEdgeBelow; edge;) {
918 Edge* next = edge->fNextEdgeBelow;
senorblanco6bd51372015-04-15 07:32:27 -0700919 set_top(edge, dst, NULL, c);
senorblancod6ed19c2015-02-26 06:58:17 -0800920 edge = next;
921 }
922 remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(src, head, NULL);
923}
924
senorblanco5b9f42c2015-04-16 11:47:18 -0700925Vertex* check_for_intersection(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c,
senorblanco6bd51372015-04-15 07:32:27 -0700926 SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -0800927 SkPoint p;
928 if (!edge || !other) {
929 return NULL;
930 }
931 if (edge->intersect(*other, &p)) {
932 Vertex* v;
933 LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
senorblanco6bd51372015-04-15 07:32:27 -0700934 if (p == edge->fTop->fPoint || c.sweep_lt(p, edge->fTop->fPoint)) {
935 split_edge(other, edge->fTop, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800936 v = edge->fTop;
senorblanco6bd51372015-04-15 07:32:27 -0700937 } else if (p == edge->fBottom->fPoint || c.sweep_gt(p, edge->fBottom->fPoint)) {
938 split_edge(other, edge->fBottom, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800939 v = edge->fBottom;
senorblanco6bd51372015-04-15 07:32:27 -0700940 } else if (p == other->fTop->fPoint || c.sweep_lt(p, other->fTop->fPoint)) {
941 split_edge(edge, other->fTop, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800942 v = other->fTop;
senorblanco6bd51372015-04-15 07:32:27 -0700943 } else if (p == other->fBottom->fPoint || c.sweep_gt(p, other->fBottom->fPoint)) {
944 split_edge(edge, other->fBottom, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800945 v = other->fBottom;
946 } else {
947 Vertex* nextV = edge->fTop;
senorblanco6bd51372015-04-15 07:32:27 -0700948 while (c.sweep_lt(p, nextV->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800949 nextV = nextV->fPrev;
950 }
senorblanco6bd51372015-04-15 07:32:27 -0700951 while (c.sweep_lt(nextV->fPoint, p)) {
senorblancod6ed19c2015-02-26 06:58:17 -0800952 nextV = nextV->fNext;
953 }
954 Vertex* prevV = nextV->fPrev;
955 if (coincident(prevV->fPoint, p)) {
956 v = prevV;
957 } else if (coincident(nextV->fPoint, p)) {
958 v = nextV;
959 } else {
960 v = ALLOC_NEW(Vertex, (p), alloc);
961 LOG("inserting between %g (%g, %g) and %g (%g, %g)\n",
962 prevV->fID, prevV->fPoint.fX, prevV->fPoint.fY,
963 nextV->fID, nextV->fPoint.fX, nextV->fPoint.fY);
964#if LOGGING_ENABLED
965 v->fID = (nextV->fID + prevV->fID) * 0.5f;
966#endif
967 v->fPrev = prevV;
968 v->fNext = nextV;
969 prevV->fNext = v;
970 nextV->fPrev = v;
971 }
senorblanco6bd51372015-04-15 07:32:27 -0700972 split_edge(edge, v, activeEdges, c, alloc);
973 split_edge(other, v, activeEdges, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -0800974 }
senorblancod6ed19c2015-02-26 06:58:17 -0800975 return v;
976 }
977 return NULL;
978}
979
980void sanitize_contours(Vertex** contours, int contourCnt) {
981 for (int i = 0; i < contourCnt; ++i) {
982 SkASSERT(contours[i]);
983 for (Vertex* v = contours[i];;) {
984 if (coincident(v->fPrev->fPoint, v->fPoint)) {
985 LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
986 if (v->fPrev == v) {
987 contours[i] = NULL;
988 break;
989 }
990 v->fPrev->fNext = v->fNext;
991 v->fNext->fPrev = v->fPrev;
992 if (contours[i] == v) {
993 contours[i] = v->fNext;
994 }
995 v = v->fPrev;
996 } else {
997 v = v->fNext;
998 if (v == contours[i]) break;
999 }
1000 }
1001 }
1002}
1003
senorblanco6bd51372015-04-15 07:32:27 -07001004void merge_coincident_vertices(Vertex** vertices, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -08001005 for (Vertex* v = (*vertices)->fNext; v != NULL; v = v->fNext) {
senorblanco6bd51372015-04-15 07:32:27 -07001006 if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -08001007 v->fPoint = v->fPrev->fPoint;
1008 }
1009 if (coincident(v->fPrev->fPoint, v->fPoint)) {
senorblanco6bd51372015-04-15 07:32:27 -07001010 merge_vertices(v->fPrev, v, vertices, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -08001011 }
1012 }
1013}
1014
1015// Stage 2: convert the contours to a mesh of edges connecting the vertices.
1016
senorblanco6bd51372015-04-15 07:32:27 -07001017Vertex* build_edges(Vertex** contours, int contourCnt, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -08001018 Vertex* vertices = NULL;
1019 Vertex* prev = NULL;
1020 for (int i = 0; i < contourCnt; ++i) {
1021 for (Vertex* v = contours[i]; v != NULL;) {
1022 Vertex* vNext = v->fNext;
senorblanco6bd51372015-04-15 07:32:27 -07001023 Edge* edge = new_edge(v->fPrev, v, alloc, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001024 if (edge->fWinding > 0) {
senorblanco6bd51372015-04-15 07:32:27 -07001025 insert_edge_below(edge, v->fPrev, c);
1026 insert_edge_above(edge, v, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001027 } else {
senorblanco6bd51372015-04-15 07:32:27 -07001028 insert_edge_below(edge, v, c);
1029 insert_edge_above(edge, v->fPrev, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001030 }
senorblanco6bd51372015-04-15 07:32:27 -07001031 merge_collinear_edges(edge, NULL, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001032 if (prev) {
1033 prev->fNext = v;
1034 v->fPrev = prev;
1035 } else {
1036 vertices = v;
1037 }
1038 prev = v;
1039 v = vNext;
1040 if (v == contours[i]) break;
1041 }
1042 }
1043 if (prev) {
1044 prev->fNext = vertices->fPrev = NULL;
1045 }
1046 return vertices;
1047}
1048
senorblanco6bd51372015-04-15 07:32:27 -07001049// Stage 3: sort the vertices by increasing sweep direction.
senorblancod6ed19c2015-02-26 06:58:17 -08001050
senorblanco6bd51372015-04-15 07:32:27 -07001051Vertex* sorted_merge(Vertex* a, Vertex* b, Comparator& c);
senorblancod6ed19c2015-02-26 06:58:17 -08001052
1053void front_back_split(Vertex* v, Vertex** pFront, Vertex** pBack) {
1054 Vertex* fast;
1055 Vertex* slow;
1056 if (!v || !v->fNext) {
1057 *pFront = v;
1058 *pBack = NULL;
1059 } else {
1060 slow = v;
1061 fast = v->fNext;
1062
1063 while (fast != NULL) {
1064 fast = fast->fNext;
1065 if (fast != NULL) {
1066 slow = slow->fNext;
1067 fast = fast->fNext;
1068 }
1069 }
1070
1071 *pFront = v;
1072 *pBack = slow->fNext;
1073 slow->fNext->fPrev = NULL;
1074 slow->fNext = NULL;
1075 }
1076}
1077
senorblanco6bd51372015-04-15 07:32:27 -07001078void merge_sort(Vertex** head, Comparator& c) {
senorblancod6ed19c2015-02-26 06:58:17 -08001079 if (!*head || !(*head)->fNext) {
1080 return;
1081 }
1082
1083 Vertex* a;
1084 Vertex* b;
1085 front_back_split(*head, &a, &b);
1086
senorblanco6bd51372015-04-15 07:32:27 -07001087 merge_sort(&a, c);
1088 merge_sort(&b, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001089
senorblanco6bd51372015-04-15 07:32:27 -07001090 *head = sorted_merge(a, b, c);
senorblancod6ed19c2015-02-26 06:58:17 -08001091}
1092
senorblanco7ef63c82015-04-13 14:27:37 -07001093inline void append_vertex(Vertex* v, Vertex** head, Vertex** tail) {
1094 insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, *tail, NULL, head, tail);
1095}
1096
1097inline void append_vertex_list(Vertex* v, Vertex** head, Vertex** tail) {
1098 insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, *tail, v->fNext, head, tail);
1099}
1100
senorblanco6bd51372015-04-15 07:32:27 -07001101Vertex* sorted_merge(Vertex* a, Vertex* b, Comparator& c) {
senorblanco7ef63c82015-04-13 14:27:37 -07001102 Vertex* head = NULL;
1103 Vertex* tail = NULL;
senorblancod6ed19c2015-02-26 06:58:17 -08001104
senorblanco7ef63c82015-04-13 14:27:37 -07001105 while (a && b) {
senorblanco6bd51372015-04-15 07:32:27 -07001106 if (c.sweep_lt(a->fPoint, b->fPoint)) {
senorblanco7ef63c82015-04-13 14:27:37 -07001107 Vertex* next = a->fNext;
1108 append_vertex(a, &head, &tail);
1109 a = next;
1110 } else {
1111 Vertex* next = b->fNext;
1112 append_vertex(b, &head, &tail);
1113 b = next;
1114 }
senorblancod6ed19c2015-02-26 06:58:17 -08001115 }
senorblanco7ef63c82015-04-13 14:27:37 -07001116 if (a) {
1117 append_vertex_list(a, &head, &tail);
1118 }
1119 if (b) {
1120 append_vertex_list(b, &head, &tail);
1121 }
1122 return head;
senorblancod6ed19c2015-02-26 06:58:17 -08001123}
1124
1125// Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1126
senorblanco6bd51372015-04-15 07:32:27 -07001127void simplify(Vertex* vertices, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -08001128 LOG("simplifying complex polygons\n");
senorblanco5b9f42c2015-04-16 11:47:18 -07001129 EdgeList activeEdges;
senorblancod6ed19c2015-02-26 06:58:17 -08001130 for (Vertex* v = vertices; v != NULL; v = v->fNext) {
1131 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1132 continue;
1133 }
1134#if LOGGING_ENABLED
1135 LOG("\nvertex %g: (%g,%g)\n", v->fID, v->fPoint.fX, v->fPoint.fY);
1136#endif
senorblancod6ed19c2015-02-26 06:58:17 -08001137 Edge* leftEnclosingEdge = NULL;
1138 Edge* rightEnclosingEdge = NULL;
1139 bool restartChecks;
1140 do {
1141 restartChecks = false;
senorblanco5b9f42c2015-04-16 11:47:18 -07001142 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
senorblancod6ed19c2015-02-26 06:58:17 -08001143 if (v->fFirstEdgeBelow) {
1144 for (Edge* edge = v->fFirstEdgeBelow; edge != NULL; edge = edge->fNextEdgeBelow) {
senorblanco6bd51372015-04-15 07:32:27 -07001145 if (check_for_intersection(edge, leftEnclosingEdge, &activeEdges, c, alloc)) {
senorblancod6ed19c2015-02-26 06:58:17 -08001146 restartChecks = true;
1147 break;
1148 }
senorblanco6bd51372015-04-15 07:32:27 -07001149 if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, c, alloc)) {
senorblancod6ed19c2015-02-26 06:58:17 -08001150 restartChecks = true;
1151 break;
1152 }
1153 }
1154 } else {
1155 if (Vertex* pv = check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
senorblanco6bd51372015-04-15 07:32:27 -07001156 &activeEdges, c, alloc)) {
1157 if (c.sweep_lt(pv->fPoint, v->fPoint)) {
senorblancod6ed19c2015-02-26 06:58:17 -08001158 v = pv;
1159 }
1160 restartChecks = true;
1161 }
1162
1163 }
1164 } while (restartChecks);
senorblancod6ed19c2015-02-26 06:58:17 -08001165 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1166 remove_edge(e, &activeEdges);
1167 }
1168 Edge* leftEdge = leftEnclosingEdge;
1169 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1170 insert_edge(e, leftEdge, &activeEdges);
1171 leftEdge = e;
1172 }
1173 v->fProcessed = true;
1174 }
1175}
1176
1177// Stage 5: Tessellate the simplified mesh into monotone polygons.
1178
1179Poly* tessellate(Vertex* vertices, SkChunkAlloc& alloc) {
1180 LOG("tessellating simple polygons\n");
senorblanco5b9f42c2015-04-16 11:47:18 -07001181 EdgeList activeEdges;
senorblancod6ed19c2015-02-26 06:58:17 -08001182 Poly* polys = NULL;
1183 for (Vertex* v = vertices; v != NULL; v = v->fNext) {
1184 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1185 continue;
1186 }
1187#if LOGGING_ENABLED
1188 LOG("\nvertex %g: (%g,%g)\n", v->fID, v->fPoint.fX, v->fPoint.fY);
1189#endif
senorblancod6ed19c2015-02-26 06:58:17 -08001190 Edge* leftEnclosingEdge = NULL;
1191 Edge* rightEnclosingEdge = NULL;
senorblanco5b9f42c2015-04-16 11:47:18 -07001192 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
senorblancod6ed19c2015-02-26 06:58:17 -08001193 Poly* leftPoly = NULL;
1194 Poly* rightPoly = NULL;
1195 if (v->fFirstEdgeAbove) {
1196 leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1197 rightPoly = v->fLastEdgeAbove->fRightPoly;
1198 } else {
1199 leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : NULL;
1200 rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : NULL;
1201 }
1202#if LOGGING_ENABLED
1203 LOG("edges above:\n");
1204 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1205 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1206 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1207 }
1208 LOG("edges below:\n");
1209 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1210 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1211 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1212 }
1213#endif
1214 if (v->fFirstEdgeAbove) {
1215 if (leftPoly) {
1216 leftPoly = leftPoly->addVertex(v, Poly::kRight_Side, alloc);
1217 }
1218 if (rightPoly) {
1219 rightPoly = rightPoly->addVertex(v, Poly::kLeft_Side, alloc);
1220 }
1221 for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1222 Edge* leftEdge = e;
1223 Edge* rightEdge = e->fNextEdgeAbove;
1224 SkASSERT(rightEdge->isRightOf(leftEdge->fTop));
1225 remove_edge(leftEdge, &activeEdges);
1226 if (leftEdge->fRightPoly) {
1227 leftEdge->fRightPoly->end(v, alloc);
1228 }
1229 if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != leftEdge->fRightPoly) {
1230 rightEdge->fLeftPoly->end(v, alloc);
1231 }
1232 }
1233 remove_edge(v->fLastEdgeAbove, &activeEdges);
1234 if (!v->fFirstEdgeBelow) {
1235 if (leftPoly && rightPoly && leftPoly != rightPoly) {
1236 SkASSERT(leftPoly->fPartner == NULL && rightPoly->fPartner == NULL);
1237 rightPoly->fPartner = leftPoly;
1238 leftPoly->fPartner = rightPoly;
1239 }
1240 }
1241 }
1242 if (v->fFirstEdgeBelow) {
1243 if (!v->fFirstEdgeAbove) {
1244 if (leftPoly && leftPoly == rightPoly) {
1245 // Split the poly.
1246 if (leftPoly->fActive->fSide == Poly::kLeft_Side) {
1247 leftPoly = new_poly(&polys, leftEnclosingEdge->fTop, leftPoly->fWinding,
1248 alloc);
1249 leftPoly->addVertex(v, Poly::kRight_Side, alloc);
1250 rightPoly->addVertex(v, Poly::kLeft_Side, alloc);
1251 leftEnclosingEdge->fRightPoly = leftPoly;
1252 } else {
1253 rightPoly = new_poly(&polys, rightEnclosingEdge->fTop, rightPoly->fWinding,
1254 alloc);
1255 rightPoly->addVertex(v, Poly::kLeft_Side, alloc);
1256 leftPoly->addVertex(v, Poly::kRight_Side, alloc);
1257 rightEnclosingEdge->fLeftPoly = rightPoly;
1258 }
1259 } else {
1260 if (leftPoly) {
1261 leftPoly = leftPoly->addVertex(v, Poly::kRight_Side, alloc);
1262 }
1263 if (rightPoly) {
1264 rightPoly = rightPoly->addVertex(v, Poly::kLeft_Side, alloc);
1265 }
1266 }
1267 }
1268 Edge* leftEdge = v->fFirstEdgeBelow;
1269 leftEdge->fLeftPoly = leftPoly;
1270 insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1271 for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1272 rightEdge = rightEdge->fNextEdgeBelow) {
1273 insert_edge(rightEdge, leftEdge, &activeEdges);
1274 int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1275 winding += leftEdge->fWinding;
1276 if (winding != 0) {
1277 Poly* poly = new_poly(&polys, v, winding, alloc);
1278 leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1279 }
1280 leftEdge = rightEdge;
1281 }
1282 v->fLastEdgeBelow->fRightPoly = rightPoly;
1283 }
senorblancod6ed19c2015-02-26 06:58:17 -08001284#if LOGGING_ENABLED
1285 LOG("\nactive edges:\n");
senorblancod4d83eb2015-05-14 09:08:14 -07001286 for (Edge* e = activeEdges.fHead; e != NULL; e = e->fRight) {
senorblancod6ed19c2015-02-26 06:58:17 -08001287 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1288 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1289 }
1290#endif
1291 }
1292 return polys;
1293}
1294
1295// This is a driver function which calls stages 2-5 in turn.
1296
senorblanco6bd51372015-04-15 07:32:27 -07001297Poly* contours_to_polys(Vertex** contours, int contourCnt, Comparator& c, SkChunkAlloc& alloc) {
senorblancod6ed19c2015-02-26 06:58:17 -08001298#if LOGGING_ENABLED
1299 for (int i = 0; i < contourCnt; ++i) {
1300 Vertex* v = contours[i];
1301 SkASSERT(v);
1302 LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1303 for (v = v->fNext; v != contours[i]; v = v->fNext) {
1304 LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1305 }
1306 }
1307#endif
1308 sanitize_contours(contours, contourCnt);
senorblanco6bd51372015-04-15 07:32:27 -07001309 Vertex* vertices = build_edges(contours, contourCnt, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -08001310 if (!vertices) {
1311 return NULL;
1312 }
1313
1314 // Sort vertices in Y (secondarily in X).
senorblanco6bd51372015-04-15 07:32:27 -07001315 merge_sort(&vertices, c);
1316 merge_coincident_vertices(&vertices, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -08001317#if LOGGING_ENABLED
1318 for (Vertex* v = vertices; v != NULL; v = v->fNext) {
1319 static float gID = 0.0f;
1320 v->fID = gID++;
1321 }
1322#endif
senorblanco6bd51372015-04-15 07:32:27 -07001323 simplify(vertices, c, alloc);
senorblancod6ed19c2015-02-26 06:58:17 -08001324 return tessellate(vertices, alloc);
1325}
1326
1327// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1328
senorblancod4d83eb2015-05-14 09:08:14 -07001329SkPoint* polys_to_triangles(Poly* polys, SkPath::FillType fillType, SkPoint* data) {
1330 SkPoint* d = data;
senorblancod6ed19c2015-02-26 06:58:17 -08001331 for (Poly* poly = polys; poly; poly = poly->fNext) {
1332 if (apply_fill_type(fillType, poly->fWinding)) {
1333 d = poly->emit(d);
1334 }
1335 }
1336 return d;
1337}
1338
senorblanco84cd6212015-08-04 10:01:58 -07001339struct TessInfo {
1340 SkScalar fTolerance;
1341 int fCount;
1342};
1343
1344bool cache_match(GrVertexBuffer* vertexBuffer, SkScalar tol, int* actualCount) {
1345 if (!vertexBuffer) {
1346 return false;
1347 }
1348 const SkData* data = vertexBuffer->getUniqueKey().getCustomData();
1349 SkASSERT(data);
1350 const TessInfo* info = static_cast<const TessInfo*>(data->data());
1351 if (info->fTolerance == 0 || info->fTolerance < 3.0f * tol) {
1352 *actualCount = info->fCount;
1353 return true;
1354 }
1355 return false;
1356}
1357
senorblancod6ed19c2015-02-26 06:58:17 -08001358};
1359
1360GrTessellatingPathRenderer::GrTessellatingPathRenderer() {
1361}
1362
senorblanco84cd6212015-08-04 10:01:58 -07001363namespace {
1364
1365// When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
1366class PathInvalidator : public SkPathRef::GenIDChangeListener {
1367public:
1368 explicit PathInvalidator(const GrUniqueKey& key) : fMsg(key) {}
1369private:
1370 GrUniqueKeyInvalidatedMessage fMsg;
1371
1372 void onChange() override {
1373 SkMessageBus<GrUniqueKeyInvalidatedMessage>::Post(fMsg);
1374 }
1375};
1376
1377} // namespace
1378
bsalomon0aff2fa2015-07-31 06:48:27 -07001379bool GrTessellatingPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
senorblancob4f9d0e2015-08-06 10:28:55 -07001380 // This path renderer can draw all fill styles, all stroke styles except hairlines, but does
1381 // not do antialiasing. It can do convex and concave paths, but we'll leave the convex ones to
1382 // simpler algorithms.
1383 return !IsStrokeHairlineOrEquivalent(*args.fStroke, *args.fViewMatrix, NULL) &&
1384 !args.fAntiAlias && !args.fPath->isConvex();
senorblancod6ed19c2015-02-26 06:58:17 -08001385}
1386
bsalomonabd30f52015-08-13 13:34:48 -07001387class TessellatingPathBatch : public GrVertexBatch {
senorblanco9ba39722015-03-05 07:13:42 -08001388public:
1389
bsalomonabd30f52015-08-13 13:34:48 -07001390 static GrDrawBatch* Create(const GrColor& color,
1391 const SkPath& path,
1392 const GrStrokeInfo& stroke,
1393 const SkMatrix& viewMatrix,
1394 SkRect clipBounds) {
senorblancob4f9d0e2015-08-06 10:28:55 -07001395 return SkNEW_ARGS(TessellatingPathBatch, (color, path, stroke, viewMatrix, clipBounds));
senorblanco9ba39722015-03-05 07:13:42 -08001396 }
1397
mtklein36352bf2015-03-25 18:17:31 -07001398 const char* name() const override { return "TessellatingPathBatch"; }
senorblanco9ba39722015-03-05 07:13:42 -08001399
mtklein36352bf2015-03-25 18:17:31 -07001400 void getInvariantOutputColor(GrInitInvariantOutput* out) const override {
senorblanco9ba39722015-03-05 07:13:42 -08001401 out->setKnownFourComponents(fColor);
1402 }
1403
mtklein36352bf2015-03-25 18:17:31 -07001404 void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override {
senorblanco9ba39722015-03-05 07:13:42 -08001405 out->setUnknownSingleComponent();
1406 }
1407
bsalomon91d844d2015-08-10 10:47:29 -07001408 void initBatchTracker(const GrPipelineOptimizations& opt) override {
senorblanco9ba39722015-03-05 07:13:42 -08001409 // Handle any color overrides
bsalomon91d844d2015-08-10 10:47:29 -07001410 if (!opt.readsColor()) {
senorblanco9ba39722015-03-05 07:13:42 -08001411 fColor = GrColor_ILLEGAL;
senorblanco9ba39722015-03-05 07:13:42 -08001412 }
bsalomon91d844d2015-08-10 10:47:29 -07001413 opt.getOverrideColorIfSet(&fColor);
1414 fPipelineInfo = opt;
senorblanco9ba39722015-03-05 07:13:42 -08001415 }
1416
senorblanco84cd6212015-08-04 10:01:58 -07001417 int tessellate(GrUniqueKey* key,
1418 GrResourceProvider* resourceProvider,
1419 SkAutoTUnref<GrVertexBuffer>& vertexBuffer) {
senorblancob4f9d0e2015-08-06 10:28:55 -07001420 SkPath path;
1421 GrStrokeInfo stroke(fStroke);
1422 if (stroke.isDashed()) {
1423 if (!stroke.applyDashToPath(&path, &stroke, fPath)) {
1424 return 0;
1425 }
1426 } else {
1427 path = fPath;
1428 }
1429 if (!stroke.isFillStyle()) {
1430 stroke.setResScale(SkScalarAbs(fViewMatrix.getMaxScale()));
1431 if (!stroke.applyToPath(&path, path)) {
1432 return 0;
1433 }
1434 stroke.setFillStyle();
1435 }
1436 SkRect pathBounds = path.getBounds();
senorblanco6bd51372015-04-15 07:32:27 -07001437 Comparator c;
1438 if (pathBounds.width() > pathBounds.height()) {
1439 c.sweep_lt = sweep_lt_horiz;
1440 c.sweep_gt = sweep_gt_horiz;
1441 } else {
1442 c.sweep_lt = sweep_lt_vert;
1443 c.sweep_gt = sweep_gt_vert;
1444 }
senorblanco2b4bb072015-04-22 13:45:18 -07001445 SkScalar screenSpaceTol = GrPathUtils::kDefaultTolerance;
1446 SkScalar tol = GrPathUtils::scaleToleranceToSrc(screenSpaceTol, fViewMatrix, pathBounds);
senorblanco9ba39722015-03-05 07:13:42 -08001447 int contourCnt;
senorblancob4f9d0e2015-08-06 10:28:55 -07001448 int maxPts = GrPathUtils::worstCasePointCount(path, &contourCnt, tol);
senorblanco9ba39722015-03-05 07:13:42 -08001449 if (maxPts <= 0) {
senorblanco84cd6212015-08-04 10:01:58 -07001450 return 0;
senorblanco9ba39722015-03-05 07:13:42 -08001451 }
1452 if (maxPts > ((int)SK_MaxU16 + 1)) {
1453 SkDebugf("Path not rendered, too many verts (%d)\n", maxPts);
senorblanco84cd6212015-08-04 10:01:58 -07001454 return 0;
senorblanco9ba39722015-03-05 07:13:42 -08001455 }
senorblancob4f9d0e2015-08-06 10:28:55 -07001456 SkPath::FillType fillType = path.getFillType();
senorblanco9ba39722015-03-05 07:13:42 -08001457 if (SkPath::IsInverseFillType(fillType)) {
1458 contourCnt++;
1459 }
1460
1461 LOG("got %d pts, %d contours\n", maxPts, contourCnt);
senorblanco84cd6212015-08-04 10:01:58 -07001462 SkAutoTDeleteArray<Vertex*> contours(SkNEW_ARRAY(Vertex *, contourCnt));
1463
1464 // For the initial size of the chunk allocator, estimate based on the point count:
1465 // one vertex per point for the initial passes, plus two for the vertices in the
1466 // resulting Polys, since the same point may end up in two Polys. Assume minimal
1467 // connectivity of one Edge per Vertex (will grow for intersections).
1468 SkChunkAlloc alloc(maxPts * (3 * sizeof(Vertex) + sizeof(Edge)));
1469 bool isLinear;
senorblancob4f9d0e2015-08-06 10:28:55 -07001470 path_to_contours(path, tol, fClipBounds, contours.get(), alloc, &isLinear);
senorblanco84cd6212015-08-04 10:01:58 -07001471 Poly* polys;
1472 polys = contours_to_polys(contours.get(), contourCnt, c, alloc);
1473 int count = 0;
1474 for (Poly* poly = polys; poly; poly = poly->fNext) {
1475 if (apply_fill_type(fillType, poly->fWinding) && poly->fCount >= 3) {
1476 count += (poly->fCount - 2) * (WIREFRAME ? 6 : 3);
1477 }
1478 }
1479 if (0 == count) {
1480 return 0;
1481 }
1482
1483 size_t size = count * sizeof(SkPoint);
1484 if (!vertexBuffer.get() || vertexBuffer->gpuMemorySize() < size) {
1485 vertexBuffer.reset(resourceProvider->createVertexBuffer(
1486 size, GrResourceProvider::kStatic_BufferUsage, 0));
1487 }
1488 if (!vertexBuffer.get()) {
1489 SkDebugf("Could not allocate vertices\n");
1490 return 0;
1491 }
1492 SkPoint* verts = static_cast<SkPoint*>(vertexBuffer->map());
1493 LOG("emitting %d verts\n", count);
1494 SkPoint* end = polys_to_triangles(polys, fillType, verts);
1495 vertexBuffer->unmap();
1496 int actualCount = static_cast<int>(end - verts);
1497 LOG("actual count: %d\n", actualCount);
1498 SkASSERT(actualCount <= count);
1499
1500 if (!fPath.isVolatile()) {
1501 TessInfo info;
1502 info.fTolerance = isLinear ? 0 : tol;
1503 info.fCount = actualCount;
1504 SkAutoTUnref<SkData> data(SkData::NewWithCopy(&info, sizeof(info)));
1505 key->setCustomData(data.get());
1506 resourceProvider->assignUniqueKeyToResource(*key, vertexBuffer.get());
1507 SkPathPriv::AddGenIDChangeListener(fPath, SkNEW(PathInvalidator(*key)));
1508 }
1509 return actualCount;
1510 }
1511
bsalomonfb1141a2015-08-06 08:52:49 -07001512 void generateGeometry(GrBatchTarget* batchTarget) override {
senorblanco84cd6212015-08-04 10:01:58 -07001513 // construct a cache key from the path's genID and the view matrix
1514 static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
1515 GrUniqueKey key;
1516 int clipBoundsSize32 =
1517 fPath.isInverseFillType() ? sizeof(fClipBounds) / sizeof(uint32_t) : 0;
senorblancob4f9d0e2015-08-06 10:28:55 -07001518 int strokeDataSize32 = fStroke.computeUniqueKeyFragmentData32Cnt();
1519 GrUniqueKey::Builder builder(&key, kDomain, 2 + clipBoundsSize32 + strokeDataSize32);
senorblanco84cd6212015-08-04 10:01:58 -07001520 builder[0] = fPath.getGenerationID();
1521 builder[1] = fPath.getFillType();
1522 // For inverse fills, the tessellation is dependent on clip bounds.
1523 if (fPath.isInverseFillType()) {
1524 memcpy(&builder[2], &fClipBounds, sizeof(fClipBounds));
1525 }
senorblancob4f9d0e2015-08-06 10:28:55 -07001526 fStroke.asUniqueKeyFragment(&builder[2 + clipBoundsSize32]);
senorblanco84cd6212015-08-04 10:01:58 -07001527 builder.finish();
1528 GrResourceProvider* rp = batchTarget->resourceProvider();
1529 SkAutoTUnref<GrVertexBuffer> vertexBuffer(rp->findAndRefTByUniqueKey<GrVertexBuffer>(key));
1530 int actualCount;
1531 SkScalar screenSpaceTol = GrPathUtils::kDefaultTolerance;
1532 SkScalar tol = GrPathUtils::scaleToleranceToSrc(
1533 screenSpaceTol, fViewMatrix, fPath.getBounds());
1534 if (!cache_match(vertexBuffer.get(), tol, &actualCount)) {
1535 actualCount = tessellate(&key, rp, vertexBuffer);
1536 }
1537
1538 if (actualCount == 0) {
1539 return;
1540 }
1541
joshualittdf0c5572015-08-03 11:35:28 -07001542 SkAutoTUnref<const GrGeometryProcessor> gp;
1543 {
1544 using namespace GrDefaultGeoProcFactory;
1545
1546 Color color(fColor);
1547 LocalCoords localCoords(fPipelineInfo.readsLocalCoords() ?
1548 LocalCoords::kUsePosition_Type :
1549 LocalCoords::kUnused_Type);
1550 Coverage::Type coverageType;
1551 if (fPipelineInfo.readsCoverage()) {
1552 coverageType = Coverage::kSolid_Type;
1553 } else {
1554 coverageType = Coverage::kNone_Type;
1555 }
1556 Coverage coverage(coverageType);
1557 gp.reset(GrDefaultGeoProcFactory::Create(color, coverage, localCoords,
1558 fViewMatrix));
1559 }
senorblanco84cd6212015-08-04 10:01:58 -07001560
bsalomonfb1141a2015-08-06 08:52:49 -07001561 batchTarget->initDraw(gp, this->pipeline());
senorblanco84cd6212015-08-04 10:01:58 -07001562 SkASSERT(gp->getVertexStride() == sizeof(SkPoint));
senorblanco9ba39722015-03-05 07:13:42 -08001563
1564 GrPrimitiveType primitiveType = WIREFRAME ? kLines_GrPrimitiveType
1565 : kTriangles_GrPrimitiveType;
bsalomoncb8979d2015-05-05 09:51:38 -07001566 GrVertices vertices;
senorblanco84cd6212015-08-04 10:01:58 -07001567 vertices.init(primitiveType, vertexBuffer.get(), 0, actualCount);
bsalomoncb8979d2015-05-05 09:51:38 -07001568 batchTarget->draw(vertices);
senorblanco9ba39722015-03-05 07:13:42 -08001569 }
1570
bsalomoncb02b382015-08-12 11:14:50 -07001571 bool onCombineIfPossible(GrBatch*, const GrCaps&) override { return false; }
senorblanco9ba39722015-03-05 07:13:42 -08001572
1573private:
1574 TessellatingPathBatch(const GrColor& color,
1575 const SkPath& path,
senorblancob4f9d0e2015-08-06 10:28:55 -07001576 const GrStrokeInfo& stroke,
senorblanco9ba39722015-03-05 07:13:42 -08001577 const SkMatrix& viewMatrix,
1578 const SkRect& clipBounds)
1579 : fColor(color)
1580 , fPath(path)
senorblancob4f9d0e2015-08-06 10:28:55 -07001581 , fStroke(stroke)
senorblanco9ba39722015-03-05 07:13:42 -08001582 , fViewMatrix(viewMatrix)
1583 , fClipBounds(clipBounds) {
1584 this->initClassID<TessellatingPathBatch>();
joshualitt99c7c072015-05-01 13:43:30 -07001585
1586 fBounds = path.getBounds();
senorblancob4f9d0e2015-08-06 10:28:55 -07001587 if (!stroke.isFillStyle()) {
1588 SkScalar radius = SkScalarHalf(stroke.getWidth());
1589 if (stroke.getJoin() == SkPaint::kMiter_Join) {
1590 SkScalar scale = stroke.getMiter();
1591 if (scale > SK_Scalar1) {
1592 radius = SkScalarMul(radius, scale);
1593 }
1594 }
1595 fBounds.outset(radius, radius);
1596 }
joshualitt99c7c072015-05-01 13:43:30 -07001597 viewMatrix.mapRect(&fBounds);
senorblanco9ba39722015-03-05 07:13:42 -08001598 }
1599
bsalomon91d844d2015-08-10 10:47:29 -07001600 GrColor fColor;
1601 SkPath fPath;
1602 GrStrokeInfo fStroke;
1603 SkMatrix fViewMatrix;
1604 SkRect fClipBounds; // in source space
1605 GrPipelineOptimizations fPipelineInfo;
senorblanco9ba39722015-03-05 07:13:42 -08001606};
1607
bsalomon0aff2fa2015-07-31 06:48:27 -07001608bool GrTessellatingPathRenderer::onDrawPath(const DrawPathArgs& args) {
1609 SkASSERT(!args.fAntiAlias);
1610 const GrRenderTarget* rt = args.fPipelineBuilder->getRenderTarget();
senorblancod6ed19c2015-02-26 06:58:17 -08001611 if (NULL == rt) {
1612 return false;
1613 }
1614
senorblancod6ed19c2015-02-26 06:58:17 -08001615 SkIRect clipBoundsI;
bsalomon0aff2fa2015-07-31 06:48:27 -07001616 args.fPipelineBuilder->clip().getConservativeBounds(rt, &clipBoundsI);
senorblancod6ed19c2015-02-26 06:58:17 -08001617 SkRect clipBounds = SkRect::Make(clipBoundsI);
1618 SkMatrix vmi;
bsalomon0aff2fa2015-07-31 06:48:27 -07001619 if (!args.fViewMatrix->invert(&vmi)) {
senorblancod6ed19c2015-02-26 06:58:17 -08001620 return false;
1621 }
1622 vmi.mapRect(&clipBounds);
bsalomonabd30f52015-08-13 13:34:48 -07001623 SkAutoTUnref<GrDrawBatch> batch(TessellatingPathBatch::Create(args.fColor, *args.fPath,
1624 *args.fStroke, *args.fViewMatrix,
1625 clipBounds));
bsalomon0aff2fa2015-07-31 06:48:27 -07001626 args.fTarget->drawBatch(*args.fPipelineBuilder, batch);
senorblancod6ed19c2015-02-26 06:58:17 -08001627
1628 return true;
1629}
joshualitt2fbd4062015-05-07 13:06:41 -07001630
1631///////////////////////////////////////////////////////////////////////////////////////////////////
1632
1633#ifdef GR_TEST_UTILS
1634
bsalomonabd30f52015-08-13 13:34:48 -07001635DRAW_BATCH_TEST_DEFINE(TesselatingPathBatch) {
joshualitt2fbd4062015-05-07 13:06:41 -07001636 GrColor color = GrRandomColor(random);
1637 SkMatrix viewMatrix = GrTest::TestMatrixInvertible(random);
1638 SkPath path = GrTest::TestPath(random);
1639 SkRect clipBounds = GrTest::TestRect(random);
1640 SkMatrix vmi;
1641 bool result = viewMatrix.invert(&vmi);
1642 if (!result) {
1643 SkFAIL("Cannot invert matrix\n");
1644 }
1645 vmi.mapRect(&clipBounds);
senorblancob4f9d0e2015-08-06 10:28:55 -07001646 GrStrokeInfo strokeInfo = GrTest::TestStrokeInfo(random);
1647 return TessellatingPathBatch::Create(color, path, strokeInfo, viewMatrix, clipBounds);
joshualitt2fbd4062015-05-07 13:06:41 -07001648}
1649
1650#endif