GrTessellator.cpp revision 2e2cb9bc768bd13e1beeafc9acf8b8f19bea3215
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 "GrTessellator.h"
9
10#include "GrDefaultGeoProcFactory.h"
11#include "GrPathUtils.h"
12
13#include "SkChunkAlloc.h"
14#include "SkGeometry.h"
15#include "SkPath.h"
16
17#include <stdio.h>
18
19/*
20 * There are six stages to the basic algorithm:
21 *
22 * 1) Linearize the path contours into piecewise linear segments (path_to_contours()).
23 * 2) Build a mesh of edges connecting the vertices (build_edges()).
24 * 3) Sort the vertices in Y (and secondarily in X) (merge_sort()).
25 * 4) Simplify the mesh by inserting new vertices at intersecting edges (simplify()).
26 * 5) Tessellate the simplified mesh into monotone polygons (tessellate()).
27 * 6) Triangulate the monotone polygons directly into a vertex buffer (polys_to_triangles()).
28 *
29 * For screenspace antialiasing, the algorithm is modified as follows:
30 *
31 * Run steps 1-5 above to produce polygons.
32 * 5b) Apply fill rules to extract boundary contours from the polygons (extract_boundaries()).
33 * 5c) Simplify boundaries to remove "pointy" vertices which cause inversions (simplify_boundary()).
34 * 5d) Displace edges by half a pixel inward and outward along their normals. Intersect to find
35 *     new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a new
36 *     antialiased mesh from those vertices (boundary_to_aa_mesh()).
37 * Run steps 3-6 above on the new mesh, and produce antialiased triangles.
38 *
39 * The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
40 * of vertices (and the necessity of inserting new vertices on intersection).
41 *
42 * Stages (4) and (5) use an active edge list, which a list of all edges for which the
43 * sweep line has crossed the top vertex, but not the bottom vertex.  It's sorted
44 * left-to-right based on the point where both edges are active (when both top vertices
45 * have been seen, so the "lower" top vertex of the two). If the top vertices are equal
46 * (shared), it's sorted based on the last point where both edges are active, so the
47 * "upper" bottom vertex.
48 *
49 * The most complex step is the simplification (4). It's based on the Bentley-Ottman
50 * line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
51 * not exact and may violate the mesh topology or active edge list ordering. We
52 * accommodate this by adjusting the topology of the mesh and AEL to match the intersection
53 * points. This occurs in three ways:
54 *
55 * A) Intersections may cause a shortened edge to no longer be ordered with respect to its
56 *    neighbouring edges at the top or bottom vertex. This is handled by merging the
57 *    edges (merge_collinear_edges()).
58 * B) Intersections may cause an edge to violate the left-to-right ordering of the
59 *    active edge list. This is handled by splitting the neighbour edge on the
60 *    intersected vertex (cleanup_active_edges()).
61 * C) Shortening an edge may cause an active edge to become inactive or an inactive edge
62 *    to become active. This is handled by removing or inserting the edge in the active
63 *    edge list (fix_active_state()).
64 *
65 * The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
66 * Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
67 * currently uses a linked list for the active edge list, rather than a 2-3 tree as the
68 * paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
69 * become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
70 * insertions and removals was greater than the cost of infrequent O(N) lookups with the
71 * linked list implementation. With the latter, all removals are O(1), and most insertions
72 * are O(1), since we know the adjacent edge in the active edge list based on the topology.
73 * Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
74 * frequent. There may be other data structures worth investigating, however.
75 *
76 * Note that the orientation of the line sweep algorithms is determined by the aspect ratio of the
77 * path bounds. When the path is taller than it is wide, we sort vertices based on increasing Y
78 * coordinate, and secondarily by increasing X coordinate. When the path is wider than it is tall,
79 * we sort by increasing X coordinate, but secondarily by *decreasing* Y coordinate. This is so
80 * that the "left" and "right" orientation in the code remains correct (edges to the left are
81 * increasing in Y; edges to the right are decreasing in Y). That is, the setting rotates 90
82 * degrees counterclockwise, rather that transposing.
83 */
84
85#define LOGGING_ENABLED 0
86
87#if LOGGING_ENABLED
88#define LOG printf
89#else
90#define LOG(...)
91#endif
92
93#define ALLOC_NEW(Type, args, alloc) new (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 list_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 list_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 = nullptr;
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, uint8_t alpha)
145    : fPoint(point), fPrev(nullptr), fNext(nullptr)
146    , fFirstEdgeAbove(nullptr), fLastEdgeAbove(nullptr)
147    , fFirstEdgeBelow(nullptr), fLastEdgeBelow(nullptr)
148    , fProcessed(false)
149    , fAlpha(alpha)
150#if LOGGING_ENABLED
151    , fID (-1.0f)
152#endif
153    {}
154    SkPoint fPoint;           // Vertex position
155    Vertex* fPrev;            // Linked list of contours, then Y-sorted vertices.
156    Vertex* fNext;            // "
157    Edge*   fFirstEdgeAbove;  // Linked list of edges above this vertex.
158    Edge*   fLastEdgeAbove;   // "
159    Edge*   fFirstEdgeBelow;  // Linked list of edges below this vertex.
160    Edge*   fLastEdgeBelow;   // "
161    bool    fProcessed;       // Has this vertex been seen in simplify()?
162    uint8_t fAlpha;
163#if LOGGING_ENABLED
164    float   fID;              // Identifier used for logging.
165#endif
166};
167
168/***************************************************************************************/
169
170struct AAParams {
171    bool fTweakAlpha;
172    GrColor fColor;
173};
174
175typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
176
177struct Comparator {
178    CompareFunc sweep_lt;
179    CompareFunc sweep_gt;
180};
181
182bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
183    return a.fX == b.fX ? a.fY > b.fY : a.fX < b.fX;
184}
185
186bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
187    return a.fY == b.fY ? a.fX < b.fX : a.fY < b.fY;
188}
189
190bool sweep_gt_horiz(const SkPoint& a, const SkPoint& b) {
191    return a.fX == b.fX ? a.fY < b.fY : a.fX > b.fX;
192}
193
194bool sweep_gt_vert(const SkPoint& a, const SkPoint& b) {
195    return a.fY == b.fY ? a.fX > b.fX : a.fY > b.fY;
196}
197
198inline void* emit_vertex(Vertex* v, const AAParams* aaParams, void* data) {
199    if (!aaParams) {
200        SkPoint* d = static_cast<SkPoint*>(data);
201        *d++ = v->fPoint;
202        return d;
203    }
204    if (aaParams->fTweakAlpha) {
205        auto d = static_cast<GrDefaultGeoProcFactory::PositionColorAttr*>(data);
206        d->fPosition = v->fPoint;
207        d->fColor = SkAlphaMulQ(aaParams->fColor, SkAlpha255To256(v->fAlpha));
208        d++;
209        return d;
210    }
211    auto d = static_cast<GrDefaultGeoProcFactory::PositionColorCoverageAttr*>(data);
212    d->fPosition = v->fPoint;
213    d->fColor = aaParams->fColor;
214    d->fCoverage = GrNormalizeByteToFloat(v->fAlpha);
215    d++;
216    return d;
217}
218
219void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, const AAParams* aaParams, void* data) {
220#if TESSELLATOR_WIREFRAME
221    data = emit_vertex(v0, aaParams, data);
222    data = emit_vertex(v1, aaParams, data);
223    data = emit_vertex(v1, aaParams, data);
224    data = emit_vertex(v2, aaParams, data);
225    data = emit_vertex(v2, aaParams, data);
226    data = emit_vertex(v0, aaParams, data);
227#else
228    data = emit_vertex(v0, aaParams, data);
229    data = emit_vertex(v1, aaParams, data);
230    data = emit_vertex(v2, aaParams, data);
231#endif
232    return data;
233}
234
235struct VertexList {
236    VertexList() : fHead(nullptr), fTail(nullptr) {}
237    Vertex* fHead;
238    Vertex* fTail;
239    void insert(Vertex* v, Vertex* prev, Vertex* next) {
240        list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
241    }
242    void append(Vertex* v) {
243        insert(v, fTail, nullptr);
244    }
245    void prepend(Vertex* v) {
246        insert(v, nullptr, fHead);
247    }
248    void remove(Vertex* v) {
249        list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
250    }
251    void close() {
252        if (fHead && fTail) {
253            fTail->fNext = fHead;
254            fHead->fPrev = fTail;
255        }
256    }
257};
258
259// Round to nearest quarter-pixel. This is used for screenspace tessellation.
260
261inline void round(SkPoint* p) {
262    p->fX = SkScalarRoundToScalar(p->fX * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
263    p->fY = SkScalarRoundToScalar(p->fY * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
264}
265
266// A line equation in implicit form. fA * x + fB * y + fC = 0, for all points (x, y) on the line.
267struct Line {
268    Line(Vertex* p, Vertex* q) : Line(p->fPoint, q->fPoint) {}
269    Line(const SkPoint& p, const SkPoint& q)
270        : fA(static_cast<double>(q.fY) - p.fY)      // a = dY
271        , fB(static_cast<double>(p.fX) - q.fX)      // b = -dX
272        , fC(static_cast<double>(p.fY) * q.fX -     // c = cross(q, p)
273             static_cast<double>(p.fX) * q.fY) {}
274    double dist(const SkPoint& p) const {
275        return fA * p.fX + fB * p.fY + fC;
276    }
277    double magSq() const {
278        return fA * fA + fB * fB;
279    }
280
281    // Compute the intersection of two (infinite) Lines.
282    bool intersect(const Line& other, SkPoint* point) {
283        double denom = fA * other.fB - fB * other.fA;
284        if (denom == 0.0) {
285            return false;
286        }
287        double scale = 1.0f / denom;
288        point->fX = SkDoubleToScalar((fB * other.fC - other.fB * fC) * scale);
289        point->fY = SkDoubleToScalar((other.fA * fC - fA * other.fC) * scale);
290        round(point);
291        return true;
292    }
293    double fA, fB, fC;
294};
295
296/**
297 * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
298 * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
299 * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
300 * point). For speed, that case is only tested by the callers which require it (e.g.,
301 * cleanup_active_edges()). Edges also handle checking for intersection with other edges.
302 * Currently, this converts the edges to the parametric form, in order to avoid doing a division
303 * until an intersection has been confirmed. This is slightly slower in the "found" case, but
304 * a lot faster in the "not found" case.
305 *
306 * The coefficients of the line equation stored in double precision to avoid catastrphic
307 * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
308 * correct in float, since it's a polynomial of degree 2. The intersect() function, being
309 * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
310 * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
311 * this file).
312 */
313
314struct Edge {
315    enum class Type { kInner, kOuter, kConnector };
316    Edge(Vertex* top, Vertex* bottom, int winding, Type type)
317        : fWinding(winding)
318        , fTop(top)
319        , fBottom(bottom)
320        , fType(type)
321        , fLeft(nullptr)
322        , fRight(nullptr)
323        , fPrevEdgeAbove(nullptr)
324        , fNextEdgeAbove(nullptr)
325        , fPrevEdgeBelow(nullptr)
326        , fNextEdgeBelow(nullptr)
327        , fLeftPoly(nullptr)
328        , fRightPoly(nullptr)
329        , fLeftPolyPrev(nullptr)
330        , fLeftPolyNext(nullptr)
331        , fRightPolyPrev(nullptr)
332        , fRightPolyNext(nullptr)
333        , fUsedInLeftPoly(false)
334        , fUsedInRightPoly(false)
335        , fLine(top, bottom) {
336        }
337    int      fWinding;          // 1 == edge goes downward; -1 = edge goes upward.
338    Vertex*  fTop;              // The top vertex in vertex-sort-order (sweep_lt).
339    Vertex*  fBottom;           // The bottom vertex in vertex-sort-order.
340    Type     fType;
341    Edge*    fLeft;             // The linked list of edges in the active edge list.
342    Edge*    fRight;            // "
343    Edge*    fPrevEdgeAbove;    // The linked list of edges in the bottom Vertex's "edges above".
344    Edge*    fNextEdgeAbove;    // "
345    Edge*    fPrevEdgeBelow;    // The linked list of edges in the top Vertex's "edges below".
346    Edge*    fNextEdgeBelow;    // "
347    Poly*    fLeftPoly;         // The Poly to the left of this edge, if any.
348    Poly*    fRightPoly;        // The Poly to the right of this edge, if any.
349    Edge*    fLeftPolyPrev;
350    Edge*    fLeftPolyNext;
351    Edge*    fRightPolyPrev;
352    Edge*    fRightPolyNext;
353    bool     fUsedInLeftPoly;
354    bool     fUsedInRightPoly;
355    Line     fLine;
356    double dist(const SkPoint& p) const {
357        return fLine.dist(p);
358    }
359    bool isRightOf(Vertex* v) const {
360        return fLine.dist(v->fPoint) < 0.0;
361    }
362    bool isLeftOf(Vertex* v) const {
363        return fLine.dist(v->fPoint) > 0.0;
364    }
365    void recompute() {
366        fLine = Line(fTop, fBottom);
367    }
368    bool intersect(const Edge& other, SkPoint* p) {
369        LOG("intersecting %g -> %g with %g -> %g\n",
370               fTop->fID, fBottom->fID,
371               other.fTop->fID, other.fBottom->fID);
372        if (fTop == other.fTop || fBottom == other.fBottom) {
373            return false;
374        }
375        double denom = fLine.fA * other.fLine.fB - fLine.fB * other.fLine.fA;
376        if (denom == 0.0) {
377            return false;
378        }
379        double dx = static_cast<double>(fTop->fPoint.fX) - other.fTop->fPoint.fX;
380        double dy = static_cast<double>(fTop->fPoint.fY) - other.fTop->fPoint.fY;
381        double sNumer = -dy * other.fLine.fB - dx * other.fLine.fA;
382        double tNumer = -dy * fLine.fB - dx * fLine.fA;
383        // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
384        // This saves us doing the divide below unless absolutely necessary.
385        if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
386                        : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
387            return false;
388        }
389        double s = sNumer / denom;
390        SkASSERT(s >= 0.0 && s <= 1.0);
391        p->fX = SkDoubleToScalar(fTop->fPoint.fX - s * fLine.fB);
392        p->fY = SkDoubleToScalar(fTop->fPoint.fY + s * fLine.fA);
393        return true;
394    }
395};
396
397struct EdgeList {
398    EdgeList() : fHead(nullptr), fTail(nullptr), fNext(nullptr), fCount(0) {}
399    Edge* fHead;
400    Edge* fTail;
401    EdgeList* fNext;
402    int fCount;
403    void insert(Edge* edge, Edge* prev, Edge* next) {
404        list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
405        fCount++;
406    }
407    void append(Edge* e) {
408        insert(e, fTail, nullptr);
409    }
410    void remove(Edge* edge) {
411        list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
412        fCount--;
413    }
414    void close() {
415        if (fHead && fTail) {
416            fTail->fRight = fHead;
417            fHead->fLeft = fTail;
418        }
419    }
420    bool contains(Edge* edge) const {
421        return edge->fLeft || edge->fRight || fHead == edge;
422    }
423};
424
425/***************************************************************************************/
426
427struct Poly {
428    Poly(Vertex* v, int winding)
429        : fFirstVertex(v)
430        , fWinding(winding)
431        , fHead(nullptr)
432        , fTail(nullptr)
433        , fNext(nullptr)
434        , fPartner(nullptr)
435        , fCount(0)
436    {
437#if LOGGING_ENABLED
438        static int gID = 0;
439        fID = gID++;
440        LOG("*** created Poly %d\n", fID);
441#endif
442    }
443    typedef enum { kLeft_Side, kRight_Side } Side;
444    struct MonotonePoly {
445        MonotonePoly(Edge* edge, Side side)
446            : fSide(side)
447            , fFirstEdge(nullptr)
448            , fLastEdge(nullptr)
449            , fPrev(nullptr)
450            , fNext(nullptr) {
451            this->addEdge(edge);
452        }
453        Side          fSide;
454        Edge*         fFirstEdge;
455        Edge*         fLastEdge;
456        MonotonePoly* fPrev;
457        MonotonePoly* fNext;
458        void addEdge(Edge* edge) {
459            if (fSide == kRight_Side) {
460                SkASSERT(!edge->fUsedInRightPoly);
461                list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
462                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
463                edge->fUsedInRightPoly = true;
464            } else {
465                SkASSERT(!edge->fUsedInLeftPoly);
466                list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
467                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
468                edge->fUsedInLeftPoly = true;
469            }
470        }
471
472        void* emit(const AAParams* aaParams, void* data) {
473            Edge* e = fFirstEdge;
474            e->fTop->fPrev = e->fTop->fNext = nullptr;
475            VertexList vertices;
476            vertices.append(e->fTop);
477            while (e != nullptr) {
478                e->fBottom->fPrev = e->fBottom->fNext = nullptr;
479                if (kRight_Side == fSide) {
480                    vertices.append(e->fBottom);
481                    e = e->fRightPolyNext;
482                } else {
483                    vertices.prepend(e->fBottom);
484                    e = e->fLeftPolyNext;
485                }
486            }
487            Vertex* first = vertices.fHead;
488            Vertex* v = first->fNext;
489            while (v != vertices.fTail) {
490                SkASSERT(v && v->fPrev && v->fNext);
491                Vertex* prev = v->fPrev;
492                Vertex* curr = v;
493                Vertex* next = v->fNext;
494                double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
495                double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
496                double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
497                double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
498                if (ax * by - ay * bx >= 0.0) {
499                    data = emit_triangle(prev, curr, next, aaParams, data);
500                    v->fPrev->fNext = v->fNext;
501                    v->fNext->fPrev = v->fPrev;
502                    if (v->fPrev == first) {
503                        v = v->fNext;
504                    } else {
505                        v = v->fPrev;
506                    }
507                } else {
508                    v = v->fNext;
509                }
510            }
511            return data;
512        }
513    };
514    Poly* addEdge(Edge* e, Side side, SkChunkAlloc& alloc) {
515        LOG("addEdge (%g -> %g) to poly %d, %s side\n",
516               e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
517        Poly* partner = fPartner;
518        Poly* poly = this;
519        if (side == kRight_Side) {
520            if (e->fUsedInRightPoly) {
521                return this;
522            }
523        } else {
524            if (e->fUsedInLeftPoly) {
525                return this;
526            }
527        }
528        if (partner) {
529            fPartner = partner->fPartner = nullptr;
530        }
531        if (!fTail) {
532            fHead = fTail = ALLOC_NEW(MonotonePoly, (e, side), alloc);
533            fCount += 2;
534        } else if (e->fBottom == fTail->fLastEdge->fBottom) {
535            return poly;
536        } else if (side == fTail->fSide) {
537            fTail->addEdge(e);
538            fCount++;
539        } else {
540            e = ALLOC_NEW(Edge, (fTail->fLastEdge->fBottom, e->fBottom, 1, Edge::Type::kInner),
541                          alloc);
542            fTail->addEdge(e);
543            fCount++;
544            if (partner) {
545                partner->addEdge(e, side, alloc);
546                poly = partner;
547            } else {
548                MonotonePoly* m = ALLOC_NEW(MonotonePoly, (e, side), alloc);
549                m->fPrev = fTail;
550                fTail->fNext = m;
551                fTail = m;
552            }
553        }
554        return poly;
555    }
556    void* emit(const AAParams* aaParams, void *data) {
557        if (fCount < 3) {
558            return data;
559        }
560        LOG("emit() %d, size %d\n", fID, fCount);
561        for (MonotonePoly* m = fHead; m != nullptr; m = m->fNext) {
562            data = m->emit(aaParams, data);
563        }
564        return data;
565    }
566    Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
567    Vertex* fFirstVertex;
568    int fWinding;
569    MonotonePoly* fHead;
570    MonotonePoly* fTail;
571    Poly* fNext;
572    Poly* fPartner;
573    int fCount;
574#if LOGGING_ENABLED
575    int fID;
576#endif
577};
578
579/***************************************************************************************/
580
581bool coincident(const SkPoint& a, const SkPoint& b) {
582    return a == b;
583}
584
585Poly* new_poly(Poly** head, Vertex* v, int winding, SkChunkAlloc& alloc) {
586    Poly* poly = ALLOC_NEW(Poly, (v, winding), alloc);
587    poly->fNext = *head;
588    *head = poly;
589    return poly;
590}
591
592EdgeList* new_contour(EdgeList** head, SkChunkAlloc& alloc) {
593    EdgeList* contour = ALLOC_NEW(EdgeList, (), alloc);
594    contour->fNext = *head;
595    *head = contour;
596    return contour;
597}
598
599Vertex* append_point_to_contour(const SkPoint& p, Vertex* prev, Vertex** head,
600                                SkChunkAlloc& alloc) {
601    Vertex* v = ALLOC_NEW(Vertex, (p, 255), alloc);
602#if LOGGING_ENABLED
603    static float gID = 0.0f;
604    v->fID = gID++;
605#endif
606    if (prev) {
607        prev->fNext = v;
608        v->fPrev = prev;
609    } else {
610        *head = v;
611    }
612    return v;
613}
614
615Vertex* generate_quadratic_points(const SkPoint& p0,
616                                  const SkPoint& p1,
617                                  const SkPoint& p2,
618                                  SkScalar tolSqd,
619                                  Vertex* prev,
620                                  Vertex** head,
621                                  int pointsLeft,
622                                  SkChunkAlloc& alloc) {
623    SkScalar d = p1.distanceToLineSegmentBetweenSqd(p0, p2);
624    if (pointsLeft < 2 || d < tolSqd || !SkScalarIsFinite(d)) {
625        return append_point_to_contour(p2, prev, head, alloc);
626    }
627
628    const SkPoint q[] = {
629        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
630        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
631    };
632    const SkPoint r = { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) };
633
634    pointsLeft >>= 1;
635    prev = generate_quadratic_points(p0, q[0], r, tolSqd, prev, head, pointsLeft, alloc);
636    prev = generate_quadratic_points(r, q[1], p2, tolSqd, prev, head, pointsLeft, alloc);
637    return prev;
638}
639
640Vertex* generate_cubic_points(const SkPoint& p0,
641                              const SkPoint& p1,
642                              const SkPoint& p2,
643                              const SkPoint& p3,
644                              SkScalar tolSqd,
645                              Vertex* prev,
646                              Vertex** head,
647                              int pointsLeft,
648                              SkChunkAlloc& alloc) {
649    SkScalar d1 = p1.distanceToLineSegmentBetweenSqd(p0, p3);
650    SkScalar d2 = p2.distanceToLineSegmentBetweenSqd(p0, p3);
651    if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
652        !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
653        return append_point_to_contour(p3, prev, head, alloc);
654    }
655    const SkPoint q[] = {
656        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
657        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
658        { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
659    };
660    const SkPoint r[] = {
661        { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
662        { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
663    };
664    const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
665    pointsLeft >>= 1;
666    prev = generate_cubic_points(p0, q[0], r[0], s, tolSqd, prev, head, pointsLeft, alloc);
667    prev = generate_cubic_points(s, r[1], q[2], p3, tolSqd, prev, head, pointsLeft, alloc);
668    return prev;
669}
670
671// Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
672
673void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
674                      Vertex** contours, SkChunkAlloc& alloc, bool *isLinear) {
675    SkScalar toleranceSqd = tolerance * tolerance;
676
677    SkPoint pts[4];
678    bool done = false;
679    *isLinear = true;
680    SkPath::Iter iter(path, false);
681    Vertex* prev = nullptr;
682    Vertex* head = nullptr;
683    if (path.isInverseFillType()) {
684        SkPoint quad[4];
685        clipBounds.toQuad(quad);
686        for (int i = 3; i >= 0; i--) {
687            prev = append_point_to_contour(quad[i], prev, &head, alloc);
688        }
689        head->fPrev = prev;
690        prev->fNext = head;
691        *contours++ = head;
692        head = prev = nullptr;
693    }
694    SkAutoConicToQuads converter;
695    while (!done) {
696        SkPath::Verb verb = iter.next(pts);
697        switch (verb) {
698            case SkPath::kConic_Verb: {
699                SkScalar weight = iter.conicWeight();
700                const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
701                for (int i = 0; i < converter.countQuads(); ++i) {
702                    int pointsLeft = GrPathUtils::quadraticPointCount(quadPts, tolerance);
703                    prev = generate_quadratic_points(quadPts[0], quadPts[1], quadPts[2],
704                                                     toleranceSqd, prev, &head, pointsLeft, alloc);
705                    quadPts += 2;
706                }
707                *isLinear = false;
708                break;
709            }
710            case SkPath::kMove_Verb:
711                if (head) {
712                    head->fPrev = prev;
713                    prev->fNext = head;
714                    *contours++ = head;
715                }
716                head = prev = nullptr;
717                prev = append_point_to_contour(pts[0], prev, &head, alloc);
718                break;
719            case SkPath::kLine_Verb: {
720                prev = append_point_to_contour(pts[1], prev, &head, alloc);
721                break;
722            }
723            case SkPath::kQuad_Verb: {
724                int pointsLeft = GrPathUtils::quadraticPointCount(pts, tolerance);
725                prev = generate_quadratic_points(pts[0], pts[1], pts[2], toleranceSqd, prev,
726                                                 &head, pointsLeft, alloc);
727                *isLinear = false;
728                break;
729            }
730            case SkPath::kCubic_Verb: {
731                int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
732                prev = generate_cubic_points(pts[0], pts[1], pts[2], pts[3],
733                                toleranceSqd, prev, &head, pointsLeft, alloc);
734                *isLinear = false;
735                break;
736            }
737            case SkPath::kClose_Verb:
738                if (head) {
739                    head->fPrev = prev;
740                    prev->fNext = head;
741                    *contours++ = head;
742                }
743                head = prev = nullptr;
744                break;
745            case SkPath::kDone_Verb:
746                if (head) {
747                    head->fPrev = prev;
748                    prev->fNext = head;
749                    *contours++ = head;
750                }
751                done = true;
752                break;
753        }
754    }
755}
756
757inline bool apply_fill_type(SkPath::FillType fillType, Poly* poly) {
758    if (!poly) {
759        return false;
760    }
761    int winding = poly->fWinding;
762    switch (fillType) {
763        case SkPath::kWinding_FillType:
764            return winding != 0;
765        case SkPath::kEvenOdd_FillType:
766            return (winding & 1) != 0;
767        case SkPath::kInverseWinding_FillType:
768            return winding == 1;
769        case SkPath::kInverseEvenOdd_FillType:
770            return (winding & 1) == 1;
771        default:
772            SkASSERT(false);
773            return false;
774    }
775}
776
777Edge* new_edge(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkChunkAlloc& alloc) {
778    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
779    Vertex* top = winding < 0 ? next : prev;
780    Vertex* bottom = winding < 0 ? prev : next;
781    return ALLOC_NEW(Edge, (top, bottom, winding, type), alloc);
782}
783
784void remove_edge(Edge* edge, EdgeList* edges) {
785    LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
786    SkASSERT(edges->contains(edge));
787    edges->remove(edge);
788}
789
790void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
791    LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
792    SkASSERT(!edges->contains(edge));
793    Edge* next = prev ? prev->fRight : edges->fHead;
794    edges->insert(edge, prev, next);
795}
796
797void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
798    if (v->fFirstEdgeAbove) {
799        *left = v->fFirstEdgeAbove->fLeft;
800        *right = v->fLastEdgeAbove->fRight;
801        return;
802    }
803    Edge* next = nullptr;
804    Edge* prev;
805    for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
806        if (prev->isLeftOf(v)) {
807            break;
808        }
809        next = prev;
810    }
811    *left = prev;
812    *right = next;
813}
814
815void find_enclosing_edges(Edge* edge, EdgeList* edges, Comparator& c, Edge** left, Edge** right) {
816    Edge* prev = nullptr;
817    Edge* next;
818    for (next = edges->fHead; next != nullptr; next = next->fRight) {
819        if ((c.sweep_gt(edge->fTop->fPoint, next->fTop->fPoint) && next->isRightOf(edge->fTop)) ||
820            (c.sweep_gt(next->fTop->fPoint, edge->fTop->fPoint) && edge->isLeftOf(next->fTop)) ||
821            (c.sweep_lt(edge->fBottom->fPoint, next->fBottom->fPoint) &&
822             next->isRightOf(edge->fBottom)) ||
823            (c.sweep_lt(next->fBottom->fPoint, edge->fBottom->fPoint) &&
824             edge->isLeftOf(next->fBottom))) {
825            break;
826        }
827        prev = next;
828    }
829    *left = prev;
830    *right = next;
831}
832
833void fix_active_state(Edge* edge, EdgeList* activeEdges, Comparator& c) {
834    if (!activeEdges) {
835        return;
836    }
837    if (activeEdges->contains(edge)) {
838        if (edge->fBottom->fProcessed || !edge->fTop->fProcessed) {
839            remove_edge(edge, activeEdges);
840        }
841    } else if (edge->fTop->fProcessed && !edge->fBottom->fProcessed) {
842        Edge* left;
843        Edge* right;
844        find_enclosing_edges(edge, activeEdges, c, &left, &right);
845        insert_edge(edge, left, activeEdges);
846    }
847}
848
849void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
850    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
851        c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
852        return;
853    }
854    LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
855    Edge* prev = nullptr;
856    Edge* next;
857    for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
858        if (next->isRightOf(edge->fTop)) {
859            break;
860        }
861        prev = next;
862    }
863    list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
864        edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
865}
866
867void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
868    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
869        c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
870        return;
871    }
872    LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
873    Edge* prev = nullptr;
874    Edge* next;
875    for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
876        if (next->isRightOf(edge->fBottom)) {
877            break;
878        }
879        prev = next;
880    }
881    list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
882        edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
883}
884
885void remove_edge_above(Edge* edge) {
886    LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
887        edge->fBottom->fID);
888    list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
889        edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
890}
891
892void remove_edge_below(Edge* edge) {
893    LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
894        edge->fTop->fID);
895    list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
896        edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
897}
898
899void erase_edge_if_zero_winding(Edge* edge, EdgeList* edges) {
900    if (edge->fWinding != 0) {
901        return;
902    }
903    LOG("erasing edge (%g -> %g)\n", edge->fTop->fID, edge->fBottom->fID);
904    remove_edge_above(edge);
905    remove_edge_below(edge);
906    if (edges && edges->contains(edge)) {
907        remove_edge(edge, edges);
908    }
909}
910
911void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c);
912
913void set_top(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
914    remove_edge_below(edge);
915    edge->fTop = v;
916    edge->recompute();
917    insert_edge_below(edge, v, c);
918    fix_active_state(edge, activeEdges, c);
919    merge_collinear_edges(edge, activeEdges, c);
920}
921
922void set_bottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
923    remove_edge_above(edge);
924    edge->fBottom = v;
925    edge->recompute();
926    insert_edge_above(edge, v, c);
927    fix_active_state(edge, activeEdges, c);
928    merge_collinear_edges(edge, activeEdges, c);
929}
930
931void merge_edges_above(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
932    if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
933        LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
934            edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
935            edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
936        other->fWinding += edge->fWinding;
937        erase_edge_if_zero_winding(other, activeEdges);
938        edge->fWinding = 0;
939        erase_edge_if_zero_winding(edge, activeEdges);
940    } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
941        other->fWinding += edge->fWinding;
942        erase_edge_if_zero_winding(other, activeEdges);
943        set_bottom(edge, other->fTop, activeEdges, c);
944    } else {
945        edge->fWinding += other->fWinding;
946        erase_edge_if_zero_winding(edge, activeEdges);
947        set_bottom(other, edge->fTop, activeEdges, c);
948    }
949}
950
951void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
952    if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
953        LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
954            edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
955            edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
956        other->fWinding += edge->fWinding;
957        erase_edge_if_zero_winding(other, activeEdges);
958        edge->fWinding = 0;
959        erase_edge_if_zero_winding(edge, activeEdges);
960    } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
961        edge->fWinding += other->fWinding;
962        erase_edge_if_zero_winding(edge, activeEdges);
963        set_top(other, edge->fBottom, activeEdges, c);
964    } else {
965        other->fWinding += edge->fWinding;
966        erase_edge_if_zero_winding(other, activeEdges);
967        set_top(edge, other->fBottom, activeEdges, c);
968    }
969}
970
971void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c) {
972    if (edge->fPrevEdgeAbove && (edge->fTop == edge->fPrevEdgeAbove->fTop ||
973                                 !edge->fPrevEdgeAbove->isLeftOf(edge->fTop))) {
974        merge_edges_above(edge, edge->fPrevEdgeAbove, activeEdges, c);
975    } else if (edge->fNextEdgeAbove && (edge->fTop == edge->fNextEdgeAbove->fTop ||
976                                        !edge->isLeftOf(edge->fNextEdgeAbove->fTop))) {
977        merge_edges_above(edge, edge->fNextEdgeAbove, activeEdges, c);
978    }
979    if (edge->fPrevEdgeBelow && (edge->fBottom == edge->fPrevEdgeBelow->fBottom ||
980                                 !edge->fPrevEdgeBelow->isLeftOf(edge->fBottom))) {
981        merge_edges_below(edge, edge->fPrevEdgeBelow, activeEdges, c);
982    } else if (edge->fNextEdgeBelow && (edge->fBottom == edge->fNextEdgeBelow->fBottom ||
983                                        !edge->isLeftOf(edge->fNextEdgeBelow->fBottom))) {
984        merge_edges_below(edge, edge->fNextEdgeBelow, activeEdges, c);
985    }
986}
987
988void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc);
989
990void cleanup_active_edges(Edge* edge, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc) {
991    Vertex* top = edge->fTop;
992    Vertex* bottom = edge->fBottom;
993    if (edge->fLeft) {
994        Vertex* leftTop = edge->fLeft->fTop;
995        Vertex* leftBottom = edge->fLeft->fBottom;
996        if (c.sweep_gt(top->fPoint, leftTop->fPoint) && !edge->fLeft->isLeftOf(top)) {
997            split_edge(edge->fLeft, edge->fTop, activeEdges, c, alloc);
998        } else if (c.sweep_gt(leftTop->fPoint, top->fPoint) && !edge->isRightOf(leftTop)) {
999            split_edge(edge, leftTop, activeEdges, c, alloc);
1000        } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
1001                   !edge->fLeft->isLeftOf(bottom)) {
1002            split_edge(edge->fLeft, bottom, activeEdges, c, alloc);
1003        } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
1004            split_edge(edge, leftBottom, activeEdges, c, alloc);
1005        }
1006    }
1007    if (edge->fRight) {
1008        Vertex* rightTop = edge->fRight->fTop;
1009        Vertex* rightBottom = edge->fRight->fBottom;
1010        if (c.sweep_gt(top->fPoint, rightTop->fPoint) && !edge->fRight->isRightOf(top)) {
1011            split_edge(edge->fRight, top, activeEdges, c, alloc);
1012        } else if (c.sweep_gt(rightTop->fPoint, top->fPoint) && !edge->isLeftOf(rightTop)) {
1013            split_edge(edge, rightTop, activeEdges, c, alloc);
1014        } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
1015                   !edge->fRight->isRightOf(bottom)) {
1016            split_edge(edge->fRight, bottom, activeEdges, c, alloc);
1017        } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
1018                   !edge->isLeftOf(rightBottom)) {
1019            split_edge(edge, rightBottom, activeEdges, c, alloc);
1020        }
1021    }
1022}
1023
1024void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkChunkAlloc& alloc) {
1025    LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
1026        edge->fTop->fID, edge->fBottom->fID,
1027        v->fID, v->fPoint.fX, v->fPoint.fY);
1028    if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1029        set_top(edge, v, activeEdges, c);
1030    } else if (c.sweep_gt(v->fPoint, edge->fBottom->fPoint)) {
1031        set_bottom(edge, v, activeEdges, c);
1032    } else {
1033        Edge* newEdge = ALLOC_NEW(Edge, (v, edge->fBottom, edge->fWinding, edge->fType), alloc);
1034        insert_edge_below(newEdge, v, c);
1035        insert_edge_above(newEdge, edge->fBottom, c);
1036        set_bottom(edge, v, activeEdges, c);
1037        cleanup_active_edges(edge, activeEdges, c, alloc);
1038        fix_active_state(newEdge, activeEdges, c);
1039        merge_collinear_edges(newEdge, activeEdges, c);
1040    }
1041}
1042
1043Edge* connect(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkChunkAlloc& alloc) {
1044    Edge* edge = new_edge(prev, next, type, c, alloc);
1045    if (edge->fWinding > 0) {
1046        insert_edge_below(edge, prev, c);
1047        insert_edge_above(edge, next, c);
1048    } else {
1049        insert_edge_below(edge, next, c);
1050        insert_edge_above(edge, prev, c);
1051    }
1052    merge_collinear_edges(edge, nullptr, c);
1053    return edge;
1054}
1055
1056void merge_vertices(Vertex* src, Vertex* dst, VertexList* mesh, Comparator& c,
1057                    SkChunkAlloc& alloc) {
1058    LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
1059        src->fID, dst->fID);
1060    dst->fAlpha = SkTMax(src->fAlpha, dst->fAlpha);
1061    for (Edge* edge = src->fFirstEdgeAbove; edge;) {
1062        Edge* next = edge->fNextEdgeAbove;
1063        set_bottom(edge, dst, nullptr, c);
1064        edge = next;
1065    }
1066    for (Edge* edge = src->fFirstEdgeBelow; edge;) {
1067        Edge* next = edge->fNextEdgeBelow;
1068        set_top(edge, dst, nullptr, c);
1069        edge = next;
1070    }
1071    mesh->remove(src);
1072}
1073
1074uint8_t max_edge_alpha(Edge* a, Edge* b) {
1075    if (a->fType == Edge::Type::kInner && b->fType == Edge::Type::kInner) {
1076        return 255;
1077    } else if (a->fType == Edge::Type::kOuter && b->fType == Edge::Type::kOuter) {
1078        return 0;
1079    } else {
1080        return SkTMax(SkTMax(a->fTop->fAlpha, a->fBottom->fAlpha),
1081                      SkTMax(b->fTop->fAlpha, b->fBottom->fAlpha));
1082    }
1083}
1084
1085Vertex* check_for_intersection(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c,
1086                               SkChunkAlloc& alloc) {
1087    SkPoint p;
1088    if (!edge || !other) {
1089        return nullptr;
1090    }
1091    if (edge->intersect(*other, &p)) {
1092        Vertex* v;
1093        LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1094        if (p == edge->fTop->fPoint || c.sweep_lt(p, edge->fTop->fPoint)) {
1095            split_edge(other, edge->fTop, activeEdges, c, alloc);
1096            v = edge->fTop;
1097        } else if (p == edge->fBottom->fPoint || c.sweep_gt(p, edge->fBottom->fPoint)) {
1098            split_edge(other, edge->fBottom, activeEdges, c, alloc);
1099            v = edge->fBottom;
1100        } else if (p == other->fTop->fPoint || c.sweep_lt(p, other->fTop->fPoint)) {
1101            split_edge(edge, other->fTop, activeEdges, c, alloc);
1102            v = other->fTop;
1103        } else if (p == other->fBottom->fPoint || c.sweep_gt(p, other->fBottom->fPoint)) {
1104            split_edge(edge, other->fBottom, activeEdges, c, alloc);
1105            v = other->fBottom;
1106        } else {
1107            Vertex* nextV = edge->fTop;
1108            while (c.sweep_lt(p, nextV->fPoint)) {
1109                nextV = nextV->fPrev;
1110            }
1111            while (c.sweep_lt(nextV->fPoint, p)) {
1112                nextV = nextV->fNext;
1113            }
1114            Vertex* prevV = nextV->fPrev;
1115            if (coincident(prevV->fPoint, p)) {
1116                v = prevV;
1117            } else if (coincident(nextV->fPoint, p)) {
1118                v = nextV;
1119            } else {
1120                uint8_t alpha = max_edge_alpha(edge, other);
1121                v = ALLOC_NEW(Vertex, (p, alpha), alloc);
1122                LOG("inserting between %g (%g, %g) and %g (%g, %g)\n",
1123                    prevV->fID, prevV->fPoint.fX, prevV->fPoint.fY,
1124                    nextV->fID, nextV->fPoint.fX, nextV->fPoint.fY);
1125#if LOGGING_ENABLED
1126                v->fID = (nextV->fID + prevV->fID) * 0.5f;
1127#endif
1128                v->fPrev = prevV;
1129                v->fNext = nextV;
1130                prevV->fNext = v;
1131                nextV->fPrev = v;
1132            }
1133            split_edge(edge, v, activeEdges, c, alloc);
1134            split_edge(other, v, activeEdges, c, alloc);
1135        }
1136        return v;
1137    }
1138    return nullptr;
1139}
1140
1141void sanitize_contours(Vertex** contours, int contourCnt, bool approximate) {
1142    for (int i = 0; i < contourCnt; ++i) {
1143        SkASSERT(contours[i]);
1144        for (Vertex* v = contours[i];;) {
1145            if (approximate) {
1146                round(&v->fPoint);
1147            }
1148            if (coincident(v->fPrev->fPoint, v->fPoint)) {
1149                LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1150                if (v->fPrev == v) {
1151                    contours[i] = nullptr;
1152                    break;
1153                }
1154                v->fPrev->fNext = v->fNext;
1155                v->fNext->fPrev = v->fPrev;
1156                if (contours[i] == v) {
1157                    contours[i] = v->fNext;
1158                }
1159                v = v->fPrev;
1160            } else {
1161                v = v->fNext;
1162                if (v == contours[i]) break;
1163            }
1164        }
1165    }
1166}
1167
1168void merge_coincident_vertices(VertexList* mesh, Comparator& c, SkChunkAlloc& alloc) {
1169    for (Vertex* v = mesh->fHead->fNext; v != nullptr; v = v->fNext) {
1170        if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1171            v->fPoint = v->fPrev->fPoint;
1172        }
1173        if (coincident(v->fPrev->fPoint, v->fPoint)) {
1174            merge_vertices(v->fPrev, v, mesh, c, alloc);
1175        }
1176    }
1177}
1178
1179// Stage 2: convert the contours to a mesh of edges connecting the vertices.
1180
1181void build_edges(Vertex** contours, int contourCnt, VertexList* mesh, Comparator& c,
1182                 SkChunkAlloc& alloc) {
1183    Vertex* prev = nullptr;
1184    for (int i = 0; i < contourCnt; ++i) {
1185        for (Vertex* v = contours[i]; v != nullptr;) {
1186            Vertex* vNext = v->fNext;
1187            connect(v->fPrev, v, Edge::Type::kInner, c, alloc);
1188            if (prev) {
1189                prev->fNext = v;
1190                v->fPrev = prev;
1191            } else {
1192                mesh->fHead = v;
1193            }
1194            prev = v;
1195            v = vNext;
1196            if (v == contours[i]) break;
1197        }
1198    }
1199    if (prev) {
1200        prev->fNext = mesh->fHead->fPrev = nullptr;
1201    }
1202    mesh->fTail = prev;
1203}
1204
1205// Stage 3: sort the vertices by increasing sweep direction.
1206
1207void sorted_merge(Vertex* a, Vertex* b, VertexList* result, Comparator& c);
1208
1209void front_back_split(VertexList* v, VertexList* front, VertexList* back) {
1210    Vertex* fast;
1211    Vertex* slow;
1212    if (!v->fHead || !v->fHead->fNext) {
1213        *front = *v;
1214    } else {
1215        slow = v->fHead;
1216        fast = v->fHead->fNext;
1217
1218        while (fast != nullptr) {
1219            fast = fast->fNext;
1220            if (fast != nullptr) {
1221                slow = slow->fNext;
1222                fast = fast->fNext;
1223            }
1224        }
1225        front->fHead = v->fHead;
1226        front->fTail = slow;
1227        back->fHead = slow->fNext;
1228        back->fTail = v->fTail;
1229        slow->fNext->fPrev = nullptr;
1230        slow->fNext = nullptr;
1231    }
1232    v->fHead = v->fTail = nullptr;
1233}
1234
1235void merge_sort(VertexList* mesh, Comparator& c) {
1236    if (!mesh->fHead || !mesh->fHead->fNext) {
1237        return;
1238    }
1239
1240    VertexList a;
1241    VertexList b;
1242    front_back_split(mesh, &a, &b);
1243
1244    merge_sort(&a, c);
1245    merge_sort(&b, c);
1246
1247    sorted_merge(a.fHead, b.fHead, mesh, c);
1248}
1249
1250void sorted_merge(Vertex* a, Vertex* b, VertexList* result, Comparator& c) {
1251    VertexList vertices;
1252    while (a && b) {
1253        if (c.sweep_lt(a->fPoint, b->fPoint)) {
1254            Vertex* next = a->fNext;
1255            vertices.append(a);
1256            a = next;
1257        } else {
1258            Vertex* next = b->fNext;
1259            vertices.append(b);
1260            b = next;
1261        }
1262    }
1263    if (a) {
1264        vertices.insert(a, vertices.fTail, a->fNext);
1265    }
1266    if (b) {
1267        vertices.insert(b, vertices.fTail, b->fNext);
1268    }
1269    *result = vertices;
1270}
1271
1272// Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1273
1274void simplify(const VertexList& vertices, Comparator& c, SkChunkAlloc& alloc) {
1275    LOG("simplifying complex polygons\n");
1276    EdgeList activeEdges;
1277    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1278        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1279            continue;
1280        }
1281#if LOGGING_ENABLED
1282        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1283#endif
1284        Edge* leftEnclosingEdge = nullptr;
1285        Edge* rightEnclosingEdge = nullptr;
1286        bool restartChecks;
1287        do {
1288            restartChecks = false;
1289            find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1290            if (v->fFirstEdgeBelow) {
1291                for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1292                    if (check_for_intersection(edge, leftEnclosingEdge, &activeEdges, c, alloc)) {
1293                        restartChecks = true;
1294                        break;
1295                    }
1296                    if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, c, alloc)) {
1297                        restartChecks = true;
1298                        break;
1299                    }
1300                }
1301            } else {
1302                if (Vertex* pv = check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
1303                                                        &activeEdges, c, alloc)) {
1304                    if (c.sweep_lt(pv->fPoint, v->fPoint)) {
1305                        v = pv;
1306                    }
1307                    restartChecks = true;
1308                }
1309
1310            }
1311        } while (restartChecks);
1312        if (v->fAlpha == 0) {
1313            if ((leftEnclosingEdge && leftEnclosingEdge->fWinding > 0) &&
1314                (rightEnclosingEdge && rightEnclosingEdge->fWinding < 0)) {
1315                v->fAlpha = max_edge_alpha(leftEnclosingEdge, rightEnclosingEdge);
1316            }
1317        }
1318        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1319            remove_edge(e, &activeEdges);
1320        }
1321        Edge* leftEdge = leftEnclosingEdge;
1322        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1323            insert_edge(e, leftEdge, &activeEdges);
1324            leftEdge = e;
1325        }
1326        v->fProcessed = true;
1327    }
1328}
1329
1330// Stage 5: Tessellate the simplified mesh into monotone polygons.
1331
1332Poly* tessellate(const VertexList& vertices, SkChunkAlloc& alloc) {
1333    LOG("tessellating simple polygons\n");
1334    EdgeList activeEdges;
1335    Poly* polys = nullptr;
1336    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1337        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1338            continue;
1339        }
1340#if LOGGING_ENABLED
1341        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1342#endif
1343        Edge* leftEnclosingEdge = nullptr;
1344        Edge* rightEnclosingEdge = nullptr;
1345        find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1346        Poly* leftPoly = nullptr;
1347        Poly* rightPoly = nullptr;
1348        if (v->fFirstEdgeAbove) {
1349            leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1350            rightPoly = v->fLastEdgeAbove->fRightPoly;
1351        } else {
1352            leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1353            rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1354        }
1355#if LOGGING_ENABLED
1356        LOG("edges above:\n");
1357        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1358            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1359                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1360        }
1361        LOG("edges below:\n");
1362        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1363            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1364                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1365        }
1366#endif
1367        if (v->fFirstEdgeAbove) {
1368            if (leftPoly) {
1369                leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Poly::kRight_Side, alloc);
1370            }
1371            if (rightPoly) {
1372                rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Poly::kLeft_Side, alloc);
1373            }
1374            for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1375                Edge* leftEdge = e;
1376                Edge* rightEdge = e->fNextEdgeAbove;
1377                SkASSERT(rightEdge->isRightOf(leftEdge->fTop));
1378                remove_edge(leftEdge, &activeEdges);
1379                if (leftEdge->fRightPoly) {
1380                    leftEdge->fRightPoly->addEdge(e, Poly::kLeft_Side, alloc);
1381                }
1382                if (rightEdge->fLeftPoly) {
1383                    rightEdge->fLeftPoly->addEdge(e, Poly::kRight_Side, alloc);
1384                }
1385            }
1386            remove_edge(v->fLastEdgeAbove, &activeEdges);
1387            if (!v->fFirstEdgeBelow) {
1388                if (leftPoly && rightPoly && leftPoly != rightPoly) {
1389                    SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1390                    rightPoly->fPartner = leftPoly;
1391                    leftPoly->fPartner = rightPoly;
1392                }
1393            }
1394        }
1395        if (v->fFirstEdgeBelow) {
1396            if (!v->fFirstEdgeAbove) {
1397                if (leftPoly && rightPoly) {
1398                    if (leftPoly == rightPoly) {
1399                        if (leftPoly->fTail && leftPoly->fTail->fSide == Poly::kLeft_Side) {
1400                            leftPoly = new_poly(&polys, leftPoly->lastVertex(),
1401                                                 leftPoly->fWinding, alloc);
1402                            leftEnclosingEdge->fRightPoly = leftPoly;
1403                        } else {
1404                            rightPoly = new_poly(&polys, rightPoly->lastVertex(),
1405                                                 rightPoly->fWinding, alloc);
1406                            rightEnclosingEdge->fLeftPoly = rightPoly;
1407                        }
1408                    }
1409                    Edge* join = ALLOC_NEW(Edge,
1410                        (leftPoly->lastVertex(), v, 1, Edge::Type::kInner), alloc);
1411                    leftPoly = leftPoly->addEdge(join, Poly::kRight_Side, alloc);
1412                    rightPoly = rightPoly->addEdge(join, Poly::kLeft_Side, alloc);
1413                }
1414            }
1415            Edge* leftEdge = v->fFirstEdgeBelow;
1416            leftEdge->fLeftPoly = leftPoly;
1417            insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1418            for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1419                 rightEdge = rightEdge->fNextEdgeBelow) {
1420                insert_edge(rightEdge, leftEdge, &activeEdges);
1421                int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1422                winding += leftEdge->fWinding;
1423                if (winding != 0) {
1424                    Poly* poly = new_poly(&polys, v, winding, alloc);
1425                    leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1426                }
1427                leftEdge = rightEdge;
1428            }
1429            v->fLastEdgeBelow->fRightPoly = rightPoly;
1430        }
1431#if LOGGING_ENABLED
1432        LOG("\nactive edges:\n");
1433        for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1434            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1435                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1436        }
1437#endif
1438    }
1439    return polys;
1440}
1441
1442bool is_boundary_edge(Edge* edge, SkPath::FillType fillType) {
1443    return apply_fill_type(fillType, edge->fLeftPoly) !=
1444           apply_fill_type(fillType, edge->fRightPoly);
1445}
1446
1447bool is_boundary_start(Edge* edge, SkPath::FillType fillType) {
1448    return !apply_fill_type(fillType, edge->fLeftPoly) &&
1449            apply_fill_type(fillType, edge->fRightPoly);
1450}
1451
1452void remove_non_boundary_edges(const VertexList& mesh, SkPath::FillType fillType,
1453                               SkChunkAlloc& alloc) {
1454    for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1455        for (Edge* e = v->fFirstEdgeBelow; e != nullptr;) {
1456            Edge* next = e->fNextEdgeBelow;
1457            if (!is_boundary_edge(e, fillType)) {
1458                remove_edge_above(e);
1459                remove_edge_below(e);
1460            }
1461            e = next;
1462        }
1463    }
1464}
1465
1466void get_edge_normal(const Edge* e, SkVector* normal) {
1467    normal->setNormalize(SkDoubleToScalar(-e->fLine.fB) * e->fWinding,
1468                         SkDoubleToScalar(e->fLine.fA) * e->fWinding);
1469}
1470
1471// Stage 5c: detect and remove "pointy" vertices whose edge normals point in opposite directions
1472// and whose adjacent vertices are less than a quarter pixel from an edge. These are guaranteed to
1473// invert on stroking.
1474
1475void simplify_boundary(EdgeList* boundary, Comparator& c, SkChunkAlloc& alloc) {
1476    Edge* prevEdge = boundary->fTail;
1477    SkVector prevNormal;
1478    get_edge_normal(prevEdge, &prevNormal);
1479    for (Edge* e = boundary->fHead; e != nullptr;) {
1480        Vertex* prev = prevEdge->fWinding == 1 ? prevEdge->fTop : prevEdge->fBottom;
1481        Vertex* next = e->fWinding == 1 ? e->fBottom : e->fTop;
1482        double dist = e->dist(prev->fPoint);
1483        SkVector normal;
1484        get_edge_normal(e, &normal);
1485        float denom = 0.25f * static_cast<float>(e->fLine.magSq());
1486        if (prevNormal.dot(normal) < 0.0 && (dist * dist) <= denom) {
1487            Edge* join = new_edge(prev, next, Edge::Type::kInner, c, alloc);
1488            insert_edge(join, e, boundary);
1489            remove_edge(prevEdge, boundary);
1490            remove_edge(e, boundary);
1491            if (join->fLeft && join->fRight) {
1492                prevEdge = join->fLeft;
1493                e = join;
1494            } else {
1495                prevEdge = boundary->fTail;
1496                e = boundary->fHead; // join->fLeft ? join->fLeft : join;
1497            }
1498            get_edge_normal(prevEdge, &prevNormal);
1499        } else {
1500            prevEdge = e;
1501            prevNormal = normal;
1502            e = e->fRight;
1503        }
1504    }
1505}
1506
1507// Stage 5d: Displace edges by half a pixel inward and outward along their normals. Intersect to
1508// find new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a
1509// new antialiased mesh from those vertices.
1510
1511void boundary_to_aa_mesh(EdgeList* boundary, VertexList* mesh, Comparator& c, SkChunkAlloc& alloc) {
1512    EdgeList outerContour;
1513    Edge* prevEdge = boundary->fTail;
1514    float radius = 0.5f;
1515    double offset = radius * sqrt(prevEdge->fLine.magSq()) * prevEdge->fWinding;
1516    Line prevInner(prevEdge->fTop, prevEdge->fBottom);
1517    prevInner.fC -= offset;
1518    Line prevOuter(prevEdge->fTop, prevEdge->fBottom);
1519    prevOuter.fC += offset;
1520    VertexList innerVertices;
1521    VertexList outerVertices;
1522    SkScalar innerCount = SK_Scalar1, outerCount = SK_Scalar1;
1523    for (Edge* e = boundary->fHead; e != nullptr; e = e->fRight) {
1524        double offset = radius * sqrt(e->fLine.magSq()) * e->fWinding;
1525        Line inner(e->fTop, e->fBottom);
1526        inner.fC -= offset;
1527        Line outer(e->fTop, e->fBottom);
1528        outer.fC += offset;
1529        SkPoint innerPoint, outerPoint;
1530        if (prevInner.intersect(inner, &innerPoint) &&
1531            prevOuter.intersect(outer, &outerPoint)) {
1532            Vertex* innerVertex = ALLOC_NEW(Vertex, (innerPoint, 255), alloc);
1533            Vertex* outerVertex = ALLOC_NEW(Vertex, (outerPoint, 0), alloc);
1534            if (innerVertices.fTail && outerVertices.fTail) {
1535                Edge innerEdge(innerVertices.fTail, innerVertex, 1, Edge::Type::kInner);
1536                Edge outerEdge(outerVertices.fTail, outerVertex, 1, Edge::Type::kInner);
1537                SkVector innerNormal;
1538                get_edge_normal(&innerEdge, &innerNormal);
1539                SkVector outerNormal;
1540                get_edge_normal(&outerEdge, &outerNormal);
1541                SkVector normal;
1542                get_edge_normal(prevEdge, &normal);
1543                if (normal.dot(innerNormal) < 0) {
1544                    innerPoint += innerVertices.fTail->fPoint * innerCount;
1545                    innerCount++;
1546                    innerPoint *= SkScalarInvert(innerCount);
1547                    innerVertices.fTail->fPoint = innerVertex->fPoint = innerPoint;
1548                } else {
1549                    innerCount = SK_Scalar1;
1550                }
1551                if (normal.dot(outerNormal) < 0) {
1552                    outerPoint += outerVertices.fTail->fPoint * outerCount;
1553                    outerCount++;
1554                    outerPoint *= SkScalarInvert(outerCount);
1555                    outerVertices.fTail->fPoint = outerVertex->fPoint = outerPoint;
1556                } else {
1557                    outerCount = SK_Scalar1;
1558                }
1559            }
1560            innerVertices.append(innerVertex);
1561            outerVertices.append(outerVertex);
1562            prevEdge = e;
1563        }
1564        prevInner = inner;
1565        prevOuter = outer;
1566    }
1567    innerVertices.close();
1568    outerVertices.close();
1569
1570    Vertex* innerVertex = innerVertices.fHead;
1571    Vertex* outerVertex = outerVertices.fHead;
1572    // Alternate clockwise and counterclockwise polys, so the tesselator
1573    // doesn't cancel out the interior edges.
1574    if (!innerVertex || !outerVertex) {
1575        return;
1576    }
1577    do {
1578        connect(outerVertex->fPrev, outerVertex, Edge::Type::kOuter, c, alloc);
1579        connect(innerVertex->fPrev, innerVertex, Edge::Type::kInner, c, alloc);
1580        connect(outerVertex, innerVertex, Edge::Type::kConnector, c, alloc)->fWinding = 0;
1581        Vertex* innerNext = innerVertex->fNext;
1582        Vertex* outerNext = outerVertex->fNext;
1583        mesh->append(innerVertex);
1584        mesh->append(outerVertex);
1585        innerVertex = innerNext;
1586        outerVertex = outerNext;
1587    } while (innerVertex != innerVertices.fHead && outerVertex != outerVertices.fHead);
1588}
1589
1590void extract_boundary(EdgeList* boundary, Edge* e, SkPath::FillType fillType, SkChunkAlloc& alloc) {
1591    bool down = is_boundary_start(e, fillType);
1592    while (e) {
1593        e->fWinding = down ? 1 : -1;
1594        Edge* next;
1595        boundary->append(e);
1596        if (down) {
1597            // Find outgoing edge, in clockwise order.
1598            if ((next = e->fNextEdgeAbove)) {
1599                down = false;
1600            } else if ((next = e->fBottom->fLastEdgeBelow)) {
1601                down = true;
1602            } else if ((next = e->fPrevEdgeAbove)) {
1603                down = false;
1604            }
1605        } else {
1606            // Find outgoing edge, in counter-clockwise order.
1607            if ((next = e->fPrevEdgeBelow)) {
1608                down = true;
1609            } else if ((next = e->fTop->fFirstEdgeAbove)) {
1610                down = false;
1611            } else if ((next = e->fNextEdgeBelow)) {
1612                down = true;
1613            }
1614        }
1615        remove_edge_above(e);
1616        remove_edge_below(e);
1617        e = next;
1618    }
1619}
1620
1621// Stage 5b: Extract boundary edges.
1622
1623EdgeList* extract_boundaries(const VertexList& mesh, SkPath::FillType fillType,
1624                             SkChunkAlloc& alloc) {
1625    LOG("extracting boundaries\n");
1626    remove_non_boundary_edges(mesh, fillType, alloc);
1627    EdgeList* boundaries = nullptr;
1628    for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1629        while (v->fFirstEdgeBelow) {
1630            EdgeList* boundary = new_contour(&boundaries, alloc);
1631            extract_boundary(boundary, v->fFirstEdgeBelow, fillType, alloc);
1632        }
1633    }
1634    return boundaries;
1635}
1636
1637// This is a driver function which calls stages 2-5 in turn.
1638
1639void contours_to_mesh(Vertex** contours, int contourCnt, bool antialias,
1640                      VertexList* mesh, Comparator& c, SkChunkAlloc& alloc) {
1641#if LOGGING_ENABLED
1642    for (int i = 0; i < contourCnt; ++i) {
1643        Vertex* v = contours[i];
1644        SkASSERT(v);
1645        LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1646        for (v = v->fNext; v != contours[i]; v = v->fNext) {
1647            LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1648        }
1649    }
1650#endif
1651    sanitize_contours(contours, contourCnt, antialias);
1652    build_edges(contours, contourCnt, mesh, c, alloc);
1653}
1654
1655void sort_and_simplify(VertexList* vertices, Comparator& c, SkChunkAlloc& alloc) {
1656    if (!vertices || !vertices->fHead) {
1657        return;
1658    }
1659
1660    // Sort vertices in Y (secondarily in X).
1661    merge_sort(vertices, c);
1662    merge_coincident_vertices(vertices, c, alloc);
1663#if LOGGING_ENABLED
1664    for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
1665        static float gID = 0.0f;
1666        v->fID = gID++;
1667    }
1668#endif
1669    simplify(*vertices, c, alloc);
1670}
1671
1672Poly* mesh_to_polys(VertexList* vertices, Comparator& c, SkChunkAlloc& alloc) {
1673    sort_and_simplify(vertices, c, alloc);
1674    return tessellate(*vertices, alloc);
1675}
1676
1677Poly* contours_to_polys(Vertex** contours, int contourCnt, SkPath::FillType fillType,
1678                        const SkRect& pathBounds, bool antialias,
1679                        SkChunkAlloc& alloc) {
1680    Comparator c;
1681    if (pathBounds.width() > pathBounds.height()) {
1682        c.sweep_lt = sweep_lt_horiz;
1683        c.sweep_gt = sweep_gt_horiz;
1684    } else {
1685        c.sweep_lt = sweep_lt_vert;
1686        c.sweep_gt = sweep_gt_vert;
1687    }
1688    VertexList mesh;
1689    contours_to_mesh(contours, contourCnt, antialias, &mesh, c, alloc);
1690    Poly* polys = mesh_to_polys(&mesh, c, alloc);
1691    if (antialias) {
1692        EdgeList* boundaries = extract_boundaries(mesh, fillType, alloc);
1693        VertexList aaMesh;
1694        for (EdgeList* boundary = boundaries; boundary != nullptr; boundary = boundary->fNext) {
1695            simplify_boundary(boundary, c, alloc);
1696            if (boundary->fCount > 2) {
1697                boundary_to_aa_mesh(boundary, &aaMesh, c, alloc);
1698            }
1699        }
1700        sort_and_simplify(&aaMesh, c, alloc);
1701        return tessellate(aaMesh, alloc);
1702    }
1703    return polys;
1704}
1705
1706// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1707void* polys_to_triangles(Poly* polys, SkPath::FillType fillType, const AAParams* aaParams,
1708                         void* data) {
1709    for (Poly* poly = polys; poly; poly = poly->fNext) {
1710        if (apply_fill_type(fillType, poly)) {
1711            data = poly->emit(aaParams, data);
1712        }
1713    }
1714    return data;
1715}
1716
1717Poly* path_to_polys(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1718                    int contourCnt, SkChunkAlloc& alloc, bool antialias, bool* isLinear) {
1719    SkPath::FillType fillType = path.getFillType();
1720    if (SkPath::IsInverseFillType(fillType)) {
1721        contourCnt++;
1722    }
1723    std::unique_ptr<Vertex*[]> contours(new Vertex* [contourCnt]);
1724
1725    path_to_contours(path, tolerance, clipBounds, contours.get(), alloc, isLinear);
1726    return contours_to_polys(contours.get(), contourCnt, path.getFillType(), path.getBounds(),
1727                             antialias, alloc);
1728}
1729
1730void get_contour_count_and_size_estimate(const SkPath& path, SkScalar tolerance, int* contourCnt,
1731                                         int* sizeEstimate) {
1732    int maxPts = GrPathUtils::worstCasePointCount(path, contourCnt, tolerance);
1733    if (maxPts <= 0) {
1734        *contourCnt = 0;
1735        return;
1736    }
1737    if (maxPts > ((int)SK_MaxU16 + 1)) {
1738        SkDebugf("Path not rendered, too many verts (%d)\n", maxPts);
1739        *contourCnt = 0;
1740        return;
1741    }
1742    // For the initial size of the chunk allocator, estimate based on the point count:
1743    // one vertex per point for the initial passes, plus two for the vertices in the
1744    // resulting Polys, since the same point may end up in two Polys.  Assume minimal
1745    // connectivity of one Edge per Vertex (will grow for intersections).
1746    *sizeEstimate = maxPts * (3 * sizeof(Vertex) + sizeof(Edge));
1747}
1748
1749int count_points(Poly* polys, SkPath::FillType fillType) {
1750    int count = 0;
1751    for (Poly* poly = polys; poly; poly = poly->fNext) {
1752        if (apply_fill_type(fillType, poly) && poly->fCount >= 3) {
1753            count += (poly->fCount - 2) * (TESSELLATOR_WIREFRAME ? 6 : 3);
1754        }
1755    }
1756    return count;
1757}
1758
1759} // namespace
1760
1761namespace GrTessellator {
1762
1763// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1764
1765int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1766                    VertexAllocator* vertexAllocator, bool antialias, const GrColor& color,
1767                    bool canTweakAlphaForCoverage, bool* isLinear) {
1768    int contourCnt;
1769    int sizeEstimate;
1770    get_contour_count_and_size_estimate(path, tolerance, &contourCnt, &sizeEstimate);
1771    if (contourCnt <= 0) {
1772        *isLinear = true;
1773        return 0;
1774    }
1775    SkChunkAlloc alloc(sizeEstimate);
1776    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, antialias,
1777                                isLinear);
1778    SkPath::FillType fillType = antialias ? SkPath::kWinding_FillType : path.getFillType();
1779    int count = count_points(polys, fillType);
1780    if (0 == count) {
1781        return 0;
1782    }
1783
1784    void* verts = vertexAllocator->lock(count);
1785    if (!verts) {
1786        SkDebugf("Could not allocate vertices\n");
1787        return 0;
1788    }
1789
1790    LOG("emitting %d verts\n", count);
1791    AAParams aaParams;
1792    aaParams.fTweakAlpha = canTweakAlphaForCoverage;
1793    aaParams.fColor = color;
1794
1795    void* end = polys_to_triangles(polys, fillType, antialias ? &aaParams : nullptr, verts);
1796    int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
1797                                       / vertexAllocator->stride());
1798    SkASSERT(actualCount <= count);
1799    vertexAllocator->unlock(actualCount);
1800    return actualCount;
1801}
1802
1803int PathToVertices(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1804                   GrTessellator::WindingVertex** verts) {
1805    int contourCnt;
1806    int sizeEstimate;
1807    get_contour_count_and_size_estimate(path, tolerance, &contourCnt, &sizeEstimate);
1808    if (contourCnt <= 0) {
1809        return 0;
1810    }
1811    SkChunkAlloc alloc(sizeEstimate);
1812    bool isLinear;
1813    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, false, &isLinear);
1814    SkPath::FillType fillType = path.getFillType();
1815    int count = count_points(polys, fillType);
1816    if (0 == count) {
1817        *verts = nullptr;
1818        return 0;
1819    }
1820
1821    *verts = new GrTessellator::WindingVertex[count];
1822    GrTessellator::WindingVertex* vertsEnd = *verts;
1823    SkPoint* points = new SkPoint[count];
1824    SkPoint* pointsEnd = points;
1825    for (Poly* poly = polys; poly; poly = poly->fNext) {
1826        if (apply_fill_type(fillType, poly)) {
1827            SkPoint* start = pointsEnd;
1828            pointsEnd = static_cast<SkPoint*>(poly->emit(nullptr, pointsEnd));
1829            while (start != pointsEnd) {
1830                vertsEnd->fPos = *start;
1831                vertsEnd->fWinding = poly->fWinding;
1832                ++start;
1833                ++vertsEnd;
1834            }
1835        }
1836    }
1837    int actualCount = static_cast<int>(vertsEnd - *verts);
1838    SkASSERT(actualCount <= count);
1839    SkASSERT(pointsEnd - points == actualCount);
1840    delete[] points;
1841    return actualCount;
1842}
1843
1844} // namespace
1845