GrTessellator.cpp revision b56dedf70bdbf1a5e1e04dfbc83a374bffe6b00f
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 "SkArenaAlloc.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
93namespace {
94
95const int kArenaChunkSize = 16 * 1024;
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
177bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
178    return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
179}
180
181bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
182    return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
183}
184
185struct Comparator {
186    enum class Direction { kVertical, kHorizontal };
187    Comparator(Direction direction) : fDirection(direction) {}
188    bool sweep_lt(const SkPoint& a, const SkPoint& b) const {
189        return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
190    }
191    Direction fDirection;
192};
193
194inline void* emit_vertex(Vertex* v, const AAParams* aaParams, void* data) {
195    if (!aaParams) {
196        SkPoint* d = static_cast<SkPoint*>(data);
197        *d++ = v->fPoint;
198        return d;
199    }
200    if (aaParams->fTweakAlpha) {
201        auto d = static_cast<GrDefaultGeoProcFactory::PositionColorAttr*>(data);
202        d->fPosition = v->fPoint;
203        d->fColor = SkAlphaMulQ(aaParams->fColor, SkAlpha255To256(v->fAlpha));
204        d++;
205        return d;
206    }
207    auto d = static_cast<GrDefaultGeoProcFactory::PositionColorCoverageAttr*>(data);
208    d->fPosition = v->fPoint;
209    d->fColor = aaParams->fColor;
210    d->fCoverage = GrNormalizeByteToFloat(v->fAlpha);
211    d++;
212    return d;
213}
214
215void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, const AAParams* aaParams, void* data) {
216    LOG("emit_triangle (%g, %g) %d\n", v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
217    LOG("              (%g, %g) %d\n", v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
218    LOG("              (%g, %g) %d\n", v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
219#if TESSELLATOR_WIREFRAME
220    data = emit_vertex(v0, aaParams, data);
221    data = emit_vertex(v1, aaParams, data);
222    data = emit_vertex(v1, aaParams, data);
223    data = emit_vertex(v2, aaParams, data);
224    data = emit_vertex(v2, aaParams, data);
225    data = emit_vertex(v0, aaParams, data);
226#else
227    data = emit_vertex(v0, aaParams, data);
228    data = emit_vertex(v1, aaParams, data);
229    data = emit_vertex(v2, aaParams, data);
230#endif
231    return data;
232}
233
234struct VertexList {
235    VertexList() : fHead(nullptr), fTail(nullptr) {}
236    VertexList(Vertex* head, Vertex* tail) : fHead(head), fTail(tail) {}
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, uint8_t* alpha = nullptr) {
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>(other.fTop->fPoint.fX) - fTop->fPoint.fX;
380        double dy = static_cast<double>(other.fTop->fPoint.fY) - 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        if (alpha) {
394            if (fType == Type::kConnector) {
395                *alpha = (1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha;
396            } else if (other.fType == Type::kConnector) {
397                double t = tNumer / denom;
398                *alpha = (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha;
399            } else if (fType == Type::kOuter && other.fType == Type::kOuter) {
400                *alpha = 0;
401            } else {
402                *alpha = 255;
403            }
404        }
405        return true;
406    }
407};
408
409struct EdgeList {
410    EdgeList() : fHead(nullptr), fTail(nullptr) {}
411    Edge* fHead;
412    Edge* fTail;
413    void insert(Edge* edge, Edge* prev, Edge* next) {
414        list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
415    }
416    void append(Edge* e) {
417        insert(e, fTail, nullptr);
418    }
419    void remove(Edge* edge) {
420        list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
421    }
422    void close() {
423        if (fHead && fTail) {
424            fTail->fRight = fHead;
425            fHead->fLeft = fTail;
426        }
427    }
428    bool contains(Edge* edge) const {
429        return edge->fLeft || edge->fRight || fHead == edge;
430    }
431};
432
433/***************************************************************************************/
434
435struct Poly {
436    Poly(Vertex* v, int winding)
437        : fFirstVertex(v)
438        , fWinding(winding)
439        , fHead(nullptr)
440        , fTail(nullptr)
441        , fNext(nullptr)
442        , fPartner(nullptr)
443        , fCount(0)
444    {
445#if LOGGING_ENABLED
446        static int gID = 0;
447        fID = gID++;
448        LOG("*** created Poly %d\n", fID);
449#endif
450    }
451    typedef enum { kLeft_Side, kRight_Side } Side;
452    struct MonotonePoly {
453        MonotonePoly(Edge* edge, Side side)
454            : fSide(side)
455            , fFirstEdge(nullptr)
456            , fLastEdge(nullptr)
457            , fPrev(nullptr)
458            , fNext(nullptr) {
459            this->addEdge(edge);
460        }
461        Side          fSide;
462        Edge*         fFirstEdge;
463        Edge*         fLastEdge;
464        MonotonePoly* fPrev;
465        MonotonePoly* fNext;
466        void addEdge(Edge* edge) {
467            if (fSide == kRight_Side) {
468                SkASSERT(!edge->fUsedInRightPoly);
469                list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
470                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
471                edge->fUsedInRightPoly = true;
472            } else {
473                SkASSERT(!edge->fUsedInLeftPoly);
474                list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
475                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
476                edge->fUsedInLeftPoly = true;
477            }
478        }
479
480        void* emit(const AAParams* aaParams, void* data) {
481            Edge* e = fFirstEdge;
482            VertexList vertices;
483            vertices.append(e->fTop);
484            while (e != nullptr) {
485                if (kRight_Side == fSide) {
486                    vertices.append(e->fBottom);
487                    e = e->fRightPolyNext;
488                } else {
489                    vertices.prepend(e->fBottom);
490                    e = e->fLeftPolyNext;
491                }
492            }
493            Vertex* first = vertices.fHead;
494            Vertex* v = first->fNext;
495            while (v != vertices.fTail) {
496                SkASSERT(v && v->fPrev && v->fNext);
497                Vertex* prev = v->fPrev;
498                Vertex* curr = v;
499                Vertex* next = v->fNext;
500                double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
501                double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
502                double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
503                double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
504                if (ax * by - ay * bx >= 0.0) {
505                    data = emit_triangle(prev, curr, next, aaParams, data);
506                    v->fPrev->fNext = v->fNext;
507                    v->fNext->fPrev = v->fPrev;
508                    if (v->fPrev == first) {
509                        v = v->fNext;
510                    } else {
511                        v = v->fPrev;
512                    }
513                } else {
514                    v = v->fNext;
515                }
516            }
517            return data;
518        }
519    };
520    Poly* addEdge(Edge* e, Side side, SkArenaAlloc& alloc) {
521        LOG("addEdge (%g -> %g) to poly %d, %s side\n",
522               e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
523        Poly* partner = fPartner;
524        Poly* poly = this;
525        if (side == kRight_Side) {
526            if (e->fUsedInRightPoly) {
527                return this;
528            }
529        } else {
530            if (e->fUsedInLeftPoly) {
531                return this;
532            }
533        }
534        if (partner) {
535            fPartner = partner->fPartner = nullptr;
536        }
537        if (!fTail) {
538            fHead = fTail = alloc.make<MonotonePoly>(e, side);
539            fCount += 2;
540        } else if (e->fBottom == fTail->fLastEdge->fBottom) {
541            return poly;
542        } else if (side == fTail->fSide) {
543            fTail->addEdge(e);
544            fCount++;
545        } else {
546            e = alloc.make<Edge>(fTail->fLastEdge->fBottom, e->fBottom, 1, Edge::Type::kInner);
547            fTail->addEdge(e);
548            fCount++;
549            if (partner) {
550                partner->addEdge(e, side, alloc);
551                poly = partner;
552            } else {
553                MonotonePoly* m = alloc.make<MonotonePoly>(e, side);
554                m->fPrev = fTail;
555                fTail->fNext = m;
556                fTail = m;
557            }
558        }
559        return poly;
560    }
561    void* emit(const AAParams* aaParams, void *data) {
562        if (fCount < 3) {
563            return data;
564        }
565        LOG("emit() %d, size %d\n", fID, fCount);
566        for (MonotonePoly* m = fHead; m != nullptr; m = m->fNext) {
567            data = m->emit(aaParams, data);
568        }
569        return data;
570    }
571    Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
572    Vertex* fFirstVertex;
573    int fWinding;
574    MonotonePoly* fHead;
575    MonotonePoly* fTail;
576    Poly* fNext;
577    Poly* fPartner;
578    int fCount;
579#if LOGGING_ENABLED
580    int fID;
581#endif
582};
583
584/***************************************************************************************/
585
586bool coincident(const SkPoint& a, const SkPoint& b) {
587    return a == b;
588}
589
590Poly* new_poly(Poly** head, Vertex* v, int winding, SkArenaAlloc& alloc) {
591    Poly* poly = alloc.make<Poly>(v, winding);
592    poly->fNext = *head;
593    *head = poly;
594    return poly;
595}
596
597Vertex* append_point_to_contour(const SkPoint& p, Vertex* prev, Vertex** head,
598                                SkArenaAlloc& alloc) {
599    Vertex* v = alloc.make<Vertex>(p, 255);
600#if LOGGING_ENABLED
601    static float gID = 0.0f;
602    v->fID = gID++;
603#endif
604    if (prev) {
605        prev->fNext = v;
606        v->fPrev = prev;
607    } else {
608        *head = v;
609    }
610    return v;
611}
612
613Vertex* generate_quadratic_points(const SkPoint& p0,
614                                  const SkPoint& p1,
615                                  const SkPoint& p2,
616                                  SkScalar tolSqd,
617                                  Vertex* prev,
618                                  Vertex** head,
619                                  int pointsLeft,
620                                  SkArenaAlloc& alloc) {
621    SkScalar d = p1.distanceToLineSegmentBetweenSqd(p0, p2);
622    if (pointsLeft < 2 || d < tolSqd || !SkScalarIsFinite(d)) {
623        return append_point_to_contour(p2, prev, head, alloc);
624    }
625
626    const SkPoint q[] = {
627        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
628        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
629    };
630    const SkPoint r = { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) };
631
632    pointsLeft >>= 1;
633    prev = generate_quadratic_points(p0, q[0], r, tolSqd, prev, head, pointsLeft, alloc);
634    prev = generate_quadratic_points(r, q[1], p2, tolSqd, prev, head, pointsLeft, alloc);
635    return prev;
636}
637
638Vertex* generate_cubic_points(const SkPoint& p0,
639                              const SkPoint& p1,
640                              const SkPoint& p2,
641                              const SkPoint& p3,
642                              SkScalar tolSqd,
643                              Vertex* prev,
644                              Vertex** head,
645                              int pointsLeft,
646                              SkArenaAlloc& alloc) {
647    SkScalar d1 = p1.distanceToLineSegmentBetweenSqd(p0, p3);
648    SkScalar d2 = p2.distanceToLineSegmentBetweenSqd(p0, p3);
649    if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
650        !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
651        return append_point_to_contour(p3, prev, head, alloc);
652    }
653    const SkPoint q[] = {
654        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
655        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
656        { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
657    };
658    const SkPoint r[] = {
659        { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
660        { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
661    };
662    const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
663    pointsLeft >>= 1;
664    prev = generate_cubic_points(p0, q[0], r[0], s, tolSqd, prev, head, pointsLeft, alloc);
665    prev = generate_cubic_points(s, r[1], q[2], p3, tolSqd, prev, head, pointsLeft, alloc);
666    return prev;
667}
668
669// Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
670
671void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
672                      Vertex** contours, SkArenaAlloc& alloc, bool *isLinear) {
673    SkScalar toleranceSqd = tolerance * tolerance;
674
675    SkPoint pts[4];
676    bool done = false;
677    *isLinear = true;
678    SkPath::Iter iter(path, false);
679    Vertex* prev = nullptr;
680    Vertex* head = nullptr;
681    if (path.isInverseFillType()) {
682        SkPoint quad[4];
683        clipBounds.toQuad(quad);
684        for (int i = 3; i >= 0; i--) {
685            prev = append_point_to_contour(quad[i], prev, &head, alloc);
686        }
687        head->fPrev = prev;
688        prev->fNext = head;
689        *contours++ = head;
690        head = prev = nullptr;
691    }
692    SkAutoConicToQuads converter;
693    while (!done) {
694        SkPath::Verb verb = iter.next(pts);
695        switch (verb) {
696            case SkPath::kConic_Verb: {
697                SkScalar weight = iter.conicWeight();
698                const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
699                for (int i = 0; i < converter.countQuads(); ++i) {
700                    int pointsLeft = GrPathUtils::quadraticPointCount(quadPts, tolerance);
701                    prev = generate_quadratic_points(quadPts[0], quadPts[1], quadPts[2],
702                                                     toleranceSqd, prev, &head, pointsLeft, alloc);
703                    quadPts += 2;
704                }
705                *isLinear = false;
706                break;
707            }
708            case SkPath::kMove_Verb:
709                if (head) {
710                    head->fPrev = prev;
711                    prev->fNext = head;
712                    *contours++ = head;
713                }
714                head = prev = nullptr;
715                prev = append_point_to_contour(pts[0], prev, &head, alloc);
716                break;
717            case SkPath::kLine_Verb: {
718                prev = append_point_to_contour(pts[1], prev, &head, alloc);
719                break;
720            }
721            case SkPath::kQuad_Verb: {
722                int pointsLeft = GrPathUtils::quadraticPointCount(pts, tolerance);
723                prev = generate_quadratic_points(pts[0], pts[1], pts[2], toleranceSqd, prev,
724                                                 &head, pointsLeft, alloc);
725                *isLinear = false;
726                break;
727            }
728            case SkPath::kCubic_Verb: {
729                int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
730                prev = generate_cubic_points(pts[0], pts[1], pts[2], pts[3],
731                                toleranceSqd, prev, &head, pointsLeft, alloc);
732                *isLinear = false;
733                break;
734            }
735            case SkPath::kClose_Verb:
736                if (head) {
737                    head->fPrev = prev;
738                    prev->fNext = head;
739                    *contours++ = head;
740                }
741                head = prev = nullptr;
742                break;
743            case SkPath::kDone_Verb:
744                if (head) {
745                    head->fPrev = prev;
746                    prev->fNext = head;
747                    *contours++ = head;
748                }
749                done = true;
750                break;
751        }
752    }
753}
754
755inline bool apply_fill_type(SkPath::FillType fillType, int winding) {
756    switch (fillType) {
757        case SkPath::kWinding_FillType:
758            return winding != 0;
759        case SkPath::kEvenOdd_FillType:
760            return (winding & 1) != 0;
761        case SkPath::kInverseWinding_FillType:
762            return winding == 1;
763        case SkPath::kInverseEvenOdd_FillType:
764            return (winding & 1) == 1;
765        default:
766            SkASSERT(false);
767            return false;
768    }
769}
770
771inline bool apply_fill_type(SkPath::FillType fillType, Poly* poly) {
772    return poly && apply_fill_type(fillType, poly->fWinding);
773}
774
775Edge* new_edge(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc) {
776    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
777    Vertex* top = winding < 0 ? next : prev;
778    Vertex* bottom = winding < 0 ? prev : next;
779    return alloc.make<Edge>(top, bottom, winding, type);
780}
781
782void remove_edge(Edge* edge, EdgeList* edges) {
783    LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
784    SkASSERT(edges->contains(edge));
785    edges->remove(edge);
786}
787
788void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
789    LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
790    SkASSERT(!edges->contains(edge));
791    Edge* next = prev ? prev->fRight : edges->fHead;
792    edges->insert(edge, prev, next);
793}
794
795void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
796    if (v->fFirstEdgeAbove) {
797        *left = v->fFirstEdgeAbove->fLeft;
798        *right = v->fLastEdgeAbove->fRight;
799        return;
800    }
801    Edge* next = nullptr;
802    Edge* prev;
803    for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
804        if (prev->isLeftOf(v)) {
805            break;
806        }
807        next = prev;
808    }
809    *left = prev;
810    *right = next;
811}
812
813void find_enclosing_edges(Edge* edge, EdgeList* edges, Comparator& c, Edge** left, Edge** right) {
814    Edge* prev = nullptr;
815    Edge* next;
816    for (next = edges->fHead; next != nullptr; next = next->fRight) {
817        if ((c.sweep_lt(next->fTop->fPoint, edge->fTop->fPoint) && next->isRightOf(edge->fTop)) ||
818            (c.sweep_lt(edge->fTop->fPoint, next->fTop->fPoint) && edge->isLeftOf(next->fTop)) ||
819            (c.sweep_lt(edge->fBottom->fPoint, next->fBottom->fPoint) &&
820             next->isRightOf(edge->fBottom)) ||
821            (c.sweep_lt(next->fBottom->fPoint, edge->fBottom->fPoint) &&
822             edge->isLeftOf(next->fBottom))) {
823            break;
824        }
825        prev = next;
826    }
827    *left = prev;
828    *right = next;
829}
830
831void fix_active_state(Edge* edge, EdgeList* activeEdges, Comparator& c) {
832    if (!activeEdges) {
833        return;
834    }
835    if (activeEdges->contains(edge)) {
836        if (edge->fBottom->fProcessed || !edge->fTop->fProcessed) {
837            remove_edge(edge, activeEdges);
838        }
839    } else if (edge->fTop->fProcessed && !edge->fBottom->fProcessed) {
840        Edge* left;
841        Edge* right;
842        find_enclosing_edges(edge, activeEdges, c, &left, &right);
843        insert_edge(edge, left, activeEdges);
844    }
845}
846
847void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
848    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
849        c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
850        return;
851    }
852    LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
853    Edge* prev = nullptr;
854    Edge* next;
855    for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
856        if (next->isRightOf(edge->fTop)) {
857            break;
858        }
859        prev = next;
860    }
861    list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
862        edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
863}
864
865void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
866    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
867        c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
868        return;
869    }
870    LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
871    Edge* prev = nullptr;
872    Edge* next;
873    for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
874        if (next->isRightOf(edge->fBottom)) {
875            break;
876        }
877        prev = next;
878    }
879    list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
880        edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
881}
882
883void remove_edge_above(Edge* edge) {
884    LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
885        edge->fBottom->fID);
886    list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
887        edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
888}
889
890void remove_edge_below(Edge* edge) {
891    LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
892        edge->fTop->fID);
893    list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
894        edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
895}
896
897void disconnect(Edge* edge)
898{
899    remove_edge_above(edge);
900    remove_edge_below(edge);
901}
902
903void erase_edge(Edge* edge, EdgeList* edges) {
904    LOG("erasing edge (%g -> %g)\n", edge->fTop->fID, edge->fBottom->fID);
905    disconnect(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(edge, activeEdges);
938    } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
939        other->fWinding += edge->fWinding;
940        set_bottom(edge, other->fTop, activeEdges, c);
941    } else {
942        edge->fWinding += other->fWinding;
943        set_bottom(other, edge->fTop, activeEdges, c);
944    }
945}
946
947void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
948    if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
949        LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
950            edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
951            edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
952        other->fWinding += edge->fWinding;
953        erase_edge(edge, activeEdges);
954    } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
955        edge->fWinding += other->fWinding;
956        set_top(other, edge->fBottom, activeEdges, c);
957    } else {
958        other->fWinding += edge->fWinding;
959        set_top(edge, other->fBottom, activeEdges, c);
960    }
961}
962
963void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c) {
964    if (edge->fPrevEdgeAbove && (edge->fTop == edge->fPrevEdgeAbove->fTop ||
965                                 !edge->fPrevEdgeAbove->isLeftOf(edge->fTop))) {
966        merge_edges_above(edge, edge->fPrevEdgeAbove, activeEdges, c);
967    } else if (edge->fNextEdgeAbove && (edge->fTop == edge->fNextEdgeAbove->fTop ||
968                                        !edge->isLeftOf(edge->fNextEdgeAbove->fTop))) {
969        merge_edges_above(edge, edge->fNextEdgeAbove, activeEdges, c);
970    }
971    if (edge->fPrevEdgeBelow && (edge->fBottom == edge->fPrevEdgeBelow->fBottom ||
972                                 !edge->fPrevEdgeBelow->isLeftOf(edge->fBottom))) {
973        merge_edges_below(edge, edge->fPrevEdgeBelow, activeEdges, c);
974    } else if (edge->fNextEdgeBelow && (edge->fBottom == edge->fNextEdgeBelow->fBottom ||
975                                        !edge->isLeftOf(edge->fNextEdgeBelow->fBottom))) {
976        merge_edges_below(edge, edge->fNextEdgeBelow, activeEdges, c);
977    }
978}
979
980void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc);
981
982void cleanup_active_edges(Edge* edge, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc) {
983    Vertex* top = edge->fTop;
984    Vertex* bottom = edge->fBottom;
985    if (edge->fLeft) {
986        Vertex* leftTop = edge->fLeft->fTop;
987        Vertex* leftBottom = edge->fLeft->fBottom;
988        if (c.sweep_lt(leftTop->fPoint, top->fPoint) && !edge->fLeft->isLeftOf(top)) {
989            split_edge(edge->fLeft, edge->fTop, activeEdges, c, alloc);
990        } else if (c.sweep_lt(top->fPoint, leftTop->fPoint) && !edge->isRightOf(leftTop)) {
991            split_edge(edge, leftTop, activeEdges, c, alloc);
992        } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
993                   !edge->fLeft->isLeftOf(bottom)) {
994            split_edge(edge->fLeft, bottom, activeEdges, c, alloc);
995        } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
996            split_edge(edge, leftBottom, activeEdges, c, alloc);
997        }
998    }
999    if (edge->fRight) {
1000        Vertex* rightTop = edge->fRight->fTop;
1001        Vertex* rightBottom = edge->fRight->fBottom;
1002        if (c.sweep_lt(rightTop->fPoint, top->fPoint) && !edge->fRight->isRightOf(top)) {
1003            split_edge(edge->fRight, top, activeEdges, c, alloc);
1004        } else if (c.sweep_lt(top->fPoint, rightTop->fPoint) && !edge->isLeftOf(rightTop)) {
1005            split_edge(edge, rightTop, activeEdges, c, alloc);
1006        } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
1007                   !edge->fRight->isRightOf(bottom)) {
1008            split_edge(edge->fRight, bottom, activeEdges, c, alloc);
1009        } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
1010                   !edge->isLeftOf(rightBottom)) {
1011            split_edge(edge, rightBottom, activeEdges, c, alloc);
1012        }
1013    }
1014}
1015
1016void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc) {
1017    LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
1018        edge->fTop->fID, edge->fBottom->fID,
1019        v->fID, v->fPoint.fX, v->fPoint.fY);
1020    if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1021        set_top(edge, v, activeEdges, c);
1022    } else if (c.sweep_lt(edge->fBottom->fPoint, v->fPoint)) {
1023        set_bottom(edge, v, activeEdges, c);
1024    } else {
1025        Edge* newEdge = alloc.make<Edge>(v, edge->fBottom, edge->fWinding, edge->fType);
1026        insert_edge_below(newEdge, v, c);
1027        insert_edge_above(newEdge, edge->fBottom, c);
1028        set_bottom(edge, v, activeEdges, c);
1029        cleanup_active_edges(edge, activeEdges, c, alloc);
1030        fix_active_state(newEdge, activeEdges, c);
1031        merge_collinear_edges(newEdge, activeEdges, c);
1032    }
1033}
1034
1035Edge* connect(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc,
1036              int winding_scale = 1) {
1037    Edge* edge = new_edge(prev, next, type, c, alloc);
1038    insert_edge_below(edge, edge->fTop, c);
1039    insert_edge_above(edge, edge->fBottom, c);
1040    edge->fWinding *= winding_scale;
1041    merge_collinear_edges(edge, nullptr, c);
1042    return edge;
1043}
1044
1045void merge_vertices(Vertex* src, Vertex* dst, VertexList* mesh, Comparator& c,
1046                    SkArenaAlloc& alloc) {
1047    LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
1048        src->fID, dst->fID);
1049    dst->fAlpha = SkTMax(src->fAlpha, dst->fAlpha);
1050    for (Edge* edge = src->fFirstEdgeAbove; edge;) {
1051        Edge* next = edge->fNextEdgeAbove;
1052        set_bottom(edge, dst, nullptr, c);
1053        edge = next;
1054    }
1055    for (Edge* edge = src->fFirstEdgeBelow; edge;) {
1056        Edge* next = edge->fNextEdgeBelow;
1057        set_top(edge, dst, nullptr, c);
1058        edge = next;
1059    }
1060    mesh->remove(src);
1061}
1062
1063uint8_t max_edge_alpha(Edge* a, Edge* b) {
1064    if (a->fType == Edge::Type::kInner || b->fType == Edge::Type::kInner) {
1065        return 255;
1066    } else if (a->fType == Edge::Type::kOuter && b->fType == Edge::Type::kOuter) {
1067        return 0;
1068    } else {
1069        return SkTMax(SkTMax(a->fTop->fAlpha, a->fBottom->fAlpha),
1070                      SkTMax(b->fTop->fAlpha, b->fBottom->fAlpha));
1071    }
1072}
1073
1074Vertex* check_for_intersection(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c,
1075                               SkArenaAlloc& alloc) {
1076    if (!edge || !other) {
1077        return nullptr;
1078    }
1079    SkPoint p;
1080    uint8_t alpha;
1081    if (edge->intersect(*other, &p, &alpha)) {
1082        Vertex* v;
1083        LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1084        if (p == edge->fTop->fPoint || c.sweep_lt(p, edge->fTop->fPoint)) {
1085            split_edge(other, edge->fTop, activeEdges, c, alloc);
1086            v = edge->fTop;
1087        } else if (p == edge->fBottom->fPoint || c.sweep_lt(edge->fBottom->fPoint, p)) {
1088            split_edge(other, edge->fBottom, activeEdges, c, alloc);
1089            v = edge->fBottom;
1090        } else if (p == other->fTop->fPoint || c.sweep_lt(p, other->fTop->fPoint)) {
1091            split_edge(edge, other->fTop, activeEdges, c, alloc);
1092            v = other->fTop;
1093        } else if (p == other->fBottom->fPoint || c.sweep_lt(other->fBottom->fPoint, p)) {
1094            split_edge(edge, other->fBottom, activeEdges, c, alloc);
1095            v = other->fBottom;
1096        } else {
1097            Vertex* nextV = edge->fTop;
1098            while (c.sweep_lt(p, nextV->fPoint)) {
1099                nextV = nextV->fPrev;
1100            }
1101            while (c.sweep_lt(nextV->fPoint, p)) {
1102                nextV = nextV->fNext;
1103            }
1104            Vertex* prevV = nextV->fPrev;
1105            if (coincident(prevV->fPoint, p)) {
1106                v = prevV;
1107            } else if (coincident(nextV->fPoint, p)) {
1108                v = nextV;
1109            } else {
1110                v = alloc.make<Vertex>(p, alpha);
1111                LOG("inserting between %g (%g, %g) and %g (%g, %g)\n",
1112                    prevV->fID, prevV->fPoint.fX, prevV->fPoint.fY,
1113                    nextV->fID, nextV->fPoint.fX, nextV->fPoint.fY);
1114#if LOGGING_ENABLED
1115                v->fID = (nextV->fID + prevV->fID) * 0.5f;
1116#endif
1117                v->fPrev = prevV;
1118                v->fNext = nextV;
1119                prevV->fNext = v;
1120                nextV->fPrev = v;
1121            }
1122            split_edge(edge, v, activeEdges, c, alloc);
1123            split_edge(other, v, activeEdges, c, alloc);
1124        }
1125        v->fAlpha = SkTMax(v->fAlpha, alpha);
1126        return v;
1127    }
1128    return nullptr;
1129}
1130
1131void sanitize_contours(Vertex** contours, int contourCnt, bool approximate) {
1132    for (int i = 0; i < contourCnt; ++i) {
1133        SkASSERT(contours[i]);
1134        if (approximate) {
1135            round(&contours[i]->fPrev->fPoint);
1136        }
1137        for (Vertex* v = contours[i];;) {
1138            if (approximate) {
1139                round(&v->fPoint);
1140            }
1141            if (coincident(v->fPrev->fPoint, v->fPoint)) {
1142                LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1143                if (v->fPrev == v) {
1144                    contours[i] = nullptr;
1145                    break;
1146                }
1147                v->fPrev->fNext = v->fNext;
1148                v->fNext->fPrev = v->fPrev;
1149                if (contours[i] == v) {
1150                    contours[i] = v->fPrev;
1151                }
1152                v = v->fPrev;
1153            } else {
1154                v = v->fNext;
1155                if (v == contours[i]) break;
1156            }
1157        }
1158    }
1159}
1160
1161void merge_coincident_vertices(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1162    for (Vertex* v = mesh->fHead->fNext; v != nullptr; v = v->fNext) {
1163        if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1164            v->fPoint = v->fPrev->fPoint;
1165        }
1166        if (coincident(v->fPrev->fPoint, v->fPoint)) {
1167            merge_vertices(v->fPrev, v, mesh, c, alloc);
1168        }
1169    }
1170}
1171
1172// Stage 2: convert the contours to a mesh of edges connecting the vertices.
1173
1174void build_edges(Vertex** contours, int contourCnt, VertexList* mesh, Comparator& c,
1175                 SkArenaAlloc& alloc) {
1176    Vertex* prev = nullptr;
1177    for (int i = 0; i < contourCnt; ++i) {
1178        for (Vertex* v = contours[i]; v != nullptr;) {
1179            Vertex* vNext = v->fNext;
1180            connect(v->fPrev, v, Edge::Type::kInner, c, alloc);
1181            if (prev) {
1182                prev->fNext = v;
1183                v->fPrev = prev;
1184            } else {
1185                mesh->fHead = v;
1186            }
1187            prev = v;
1188            v = vNext;
1189            if (v == contours[i]) break;
1190        }
1191    }
1192    if (prev) {
1193        prev->fNext = mesh->fHead->fPrev = nullptr;
1194    }
1195    mesh->fTail = prev;
1196}
1197
1198// Stage 3: sort the vertices by increasing sweep direction.
1199
1200template <CompareFunc sweep_lt>
1201void merge_sort(VertexList* vertices) {
1202    Vertex* slow = vertices->fHead;
1203    if (!slow) {
1204        return;
1205    }
1206    Vertex* fast = slow->fNext;
1207    if (!fast) {
1208        return;
1209    }
1210    do {
1211        fast = fast->fNext;
1212        if (fast) {
1213            fast = fast->fNext;
1214            slow = slow->fNext;
1215        }
1216    } while (fast);
1217    VertexList front(vertices->fHead, slow);
1218    VertexList back(slow->fNext, vertices->fTail);
1219    front.fTail->fNext = back.fHead->fPrev = nullptr;
1220
1221    merge_sort<sweep_lt>(&front);
1222    merge_sort<sweep_lt>(&back);
1223
1224    vertices->fHead = vertices->fTail = nullptr;
1225    Vertex* a = front.fHead;
1226    Vertex* b = back.fHead;
1227    while (a && b) {
1228        if (sweep_lt(a->fPoint, b->fPoint)) {
1229            Vertex* next = a->fNext;
1230            vertices->append(a);
1231            a = next;
1232        } else {
1233            Vertex* next = b->fNext;
1234            vertices->append(b);
1235            b = next;
1236        }
1237    }
1238    if (a) {
1239        vertices->insert(a, vertices->fTail, a->fNext);
1240    }
1241    if (b) {
1242        vertices->insert(b, vertices->fTail, b->fNext);
1243    }
1244}
1245
1246// Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1247
1248void simplify(const VertexList& vertices, Comparator& c, SkArenaAlloc& alloc) {
1249    LOG("simplifying complex polygons\n");
1250    EdgeList activeEdges;
1251    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1252        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1253            continue;
1254        }
1255#if LOGGING_ENABLED
1256        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1257#endif
1258        Edge* leftEnclosingEdge;
1259        Edge* rightEnclosingEdge;
1260        bool restartChecks;
1261        do {
1262            restartChecks = false;
1263            find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1264            if (v->fFirstEdgeBelow) {
1265                for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1266                    if (check_for_intersection(edge, leftEnclosingEdge, &activeEdges, c, alloc)) {
1267                        restartChecks = true;
1268                        break;
1269                    }
1270                    if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, c, alloc)) {
1271                        restartChecks = true;
1272                        break;
1273                    }
1274                }
1275            } else {
1276                if (Vertex* pv = check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
1277                                                        &activeEdges, c, alloc)) {
1278                    if (c.sweep_lt(pv->fPoint, v->fPoint)) {
1279                        v = pv;
1280                    }
1281                    restartChecks = true;
1282                }
1283
1284            }
1285        } while (restartChecks);
1286        if (v->fAlpha == 0) {
1287            if ((leftEnclosingEdge && leftEnclosingEdge->fWinding < 0) &&
1288                (rightEnclosingEdge && rightEnclosingEdge->fWinding > 0)) {
1289                v->fAlpha = max_edge_alpha(leftEnclosingEdge, rightEnclosingEdge);
1290            }
1291        }
1292        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1293            remove_edge(e, &activeEdges);
1294        }
1295        Edge* leftEdge = leftEnclosingEdge;
1296        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1297            insert_edge(e, leftEdge, &activeEdges);
1298            leftEdge = e;
1299        }
1300        v->fProcessed = true;
1301    }
1302}
1303
1304// Stage 5: Tessellate the simplified mesh into monotone polygons.
1305
1306Poly* tessellate(const VertexList& vertices, SkArenaAlloc& alloc) {
1307    LOG("tessellating simple polygons\n");
1308    EdgeList activeEdges;
1309    Poly* polys = nullptr;
1310    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1311        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1312            continue;
1313        }
1314#if LOGGING_ENABLED
1315        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1316#endif
1317        Edge* leftEnclosingEdge;
1318        Edge* rightEnclosingEdge;
1319        find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1320        Poly* leftPoly;
1321        Poly* rightPoly;
1322        if (v->fFirstEdgeAbove) {
1323            leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1324            rightPoly = v->fLastEdgeAbove->fRightPoly;
1325        } else {
1326            leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1327            rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1328        }
1329#if LOGGING_ENABLED
1330        LOG("edges above:\n");
1331        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1332            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1333                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1334        }
1335        LOG("edges below:\n");
1336        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1337            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1338                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1339        }
1340#endif
1341        if (v->fFirstEdgeAbove) {
1342            if (leftPoly) {
1343                leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Poly::kRight_Side, alloc);
1344            }
1345            if (rightPoly) {
1346                rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Poly::kLeft_Side, alloc);
1347            }
1348            for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1349                Edge* rightEdge = e->fNextEdgeAbove;
1350                SkASSERT(rightEdge->isRightOf(e->fTop));
1351                remove_edge(e, &activeEdges);
1352                if (e->fRightPoly) {
1353                    e->fRightPoly->addEdge(e, Poly::kLeft_Side, alloc);
1354                }
1355                if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1356                    rightEdge->fLeftPoly->addEdge(e, Poly::kRight_Side, alloc);
1357                }
1358            }
1359            remove_edge(v->fLastEdgeAbove, &activeEdges);
1360            if (!v->fFirstEdgeBelow) {
1361                if (leftPoly && rightPoly && leftPoly != rightPoly) {
1362                    SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1363                    rightPoly->fPartner = leftPoly;
1364                    leftPoly->fPartner = rightPoly;
1365                }
1366            }
1367        }
1368        if (v->fFirstEdgeBelow) {
1369            if (!v->fFirstEdgeAbove) {
1370                if (leftPoly && rightPoly) {
1371                    if (leftPoly == rightPoly) {
1372                        if (leftPoly->fTail && leftPoly->fTail->fSide == Poly::kLeft_Side) {
1373                            leftPoly = new_poly(&polys, leftPoly->lastVertex(),
1374                                                 leftPoly->fWinding, alloc);
1375                            leftEnclosingEdge->fRightPoly = leftPoly;
1376                        } else {
1377                            rightPoly = new_poly(&polys, rightPoly->lastVertex(),
1378                                                 rightPoly->fWinding, alloc);
1379                            rightEnclosingEdge->fLeftPoly = rightPoly;
1380                        }
1381                    }
1382                    Edge* join = alloc.make<Edge>(leftPoly->lastVertex(), v, 1, Edge::Type::kInner);
1383                    leftPoly = leftPoly->addEdge(join, Poly::kRight_Side, alloc);
1384                    rightPoly = rightPoly->addEdge(join, Poly::kLeft_Side, alloc);
1385                }
1386            }
1387            Edge* leftEdge = v->fFirstEdgeBelow;
1388            leftEdge->fLeftPoly = leftPoly;
1389            insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1390            for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1391                 rightEdge = rightEdge->fNextEdgeBelow) {
1392                insert_edge(rightEdge, leftEdge, &activeEdges);
1393                int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1394                winding += leftEdge->fWinding;
1395                if (winding != 0) {
1396                    Poly* poly = new_poly(&polys, v, winding, alloc);
1397                    leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1398                }
1399                leftEdge = rightEdge;
1400            }
1401            v->fLastEdgeBelow->fRightPoly = rightPoly;
1402        }
1403#if LOGGING_ENABLED
1404        LOG("\nactive edges:\n");
1405        for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1406            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1407                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1408        }
1409#endif
1410    }
1411    return polys;
1412}
1413
1414void remove_non_boundary_edges(const VertexList& mesh, SkPath::FillType fillType,
1415                               SkArenaAlloc& alloc) {
1416    LOG("removing non-boundary edges\n");
1417    EdgeList activeEdges;
1418    for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1419        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1420            continue;
1421        }
1422        Edge* leftEnclosingEdge;
1423        Edge* rightEnclosingEdge;
1424        find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1425        bool prevFilled = leftEnclosingEdge &&
1426                          apply_fill_type(fillType, leftEnclosingEdge->fWinding);
1427        for (Edge* e = v->fFirstEdgeAbove; e;) {
1428            Edge* next = e->fNextEdgeAbove;
1429            remove_edge(e, &activeEdges);
1430            bool filled = apply_fill_type(fillType, e->fWinding);
1431            if (filled == prevFilled) {
1432                disconnect(e);
1433            }
1434            prevFilled = filled;
1435            e = next;
1436        }
1437        Edge* prev = leftEnclosingEdge;
1438        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1439            if (prev) {
1440                e->fWinding += prev->fWinding;
1441            }
1442            insert_edge(e, prev, &activeEdges);
1443            prev = e;
1444        }
1445    }
1446}
1447
1448// Note: this is the normal to the edge, but not necessarily unit length.
1449void get_edge_normal(const Edge* e, SkVector* normal) {
1450    normal->set(SkDoubleToScalar(e->fLine.fA) * e->fWinding,
1451                SkDoubleToScalar(e->fLine.fB) * e->fWinding);
1452}
1453
1454// Stage 5c: detect and remove "pointy" vertices whose edge normals point in opposite directions
1455// and whose adjacent vertices are less than a quarter pixel from an edge. These are guaranteed to
1456// invert on stroking.
1457
1458void simplify_boundary(EdgeList* boundary, Comparator& c, SkArenaAlloc& alloc) {
1459    Edge* prevEdge = boundary->fTail;
1460    SkVector prevNormal;
1461    get_edge_normal(prevEdge, &prevNormal);
1462    for (Edge* e = boundary->fHead; e != nullptr;) {
1463        Vertex* prev = prevEdge->fWinding == 1 ? prevEdge->fTop : prevEdge->fBottom;
1464        Vertex* next = e->fWinding == 1 ? e->fBottom : e->fTop;
1465        double dist = e->dist(prev->fPoint);
1466        SkVector normal;
1467        get_edge_normal(e, &normal);
1468        double denom = 0.0625f * e->fLine.magSq();
1469        if (prevNormal.dot(normal) < 0.0 && (dist * dist) <= denom) {
1470            Edge* join = new_edge(prev, next, Edge::Type::kInner, c, alloc);
1471            insert_edge(join, e, boundary);
1472            remove_edge(prevEdge, boundary);
1473            remove_edge(e, boundary);
1474            if (join->fLeft && join->fRight) {
1475                prevEdge = join->fLeft;
1476                e = join;
1477            } else {
1478                prevEdge = boundary->fTail;
1479                e = boundary->fHead; // join->fLeft ? join->fLeft : join;
1480            }
1481            get_edge_normal(prevEdge, &prevNormal);
1482        } else {
1483            prevEdge = e;
1484            prevNormal = normal;
1485            e = e->fRight;
1486        }
1487    }
1488}
1489
1490void fix_inversions(Vertex* prev, Vertex* next, Edge* prevBisector, Edge* nextBisector,
1491                    Edge* prevEdge, Comparator& c) {
1492    if (!prev || !next) {
1493        return;
1494    }
1495    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
1496    SkPoint p;
1497    uint8_t alpha;
1498    if (winding != prevEdge->fWinding && prevBisector->intersect(*nextBisector, &p, &alpha)) {
1499        prev->fPoint = next->fPoint = p;
1500        prev->fAlpha = next->fAlpha = alpha;
1501    }
1502}
1503
1504// Stage 5d: Displace edges by half a pixel inward and outward along their normals. Intersect to
1505// find new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a
1506// new antialiased mesh from those vertices.
1507
1508void boundary_to_aa_mesh(EdgeList* boundary, VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1509    // A boundary with fewer than 3 edges is degenerate.
1510    if (!boundary->fHead || !boundary->fHead->fRight || !boundary->fHead->fRight->fRight) {
1511        return;
1512    }
1513    Edge* prevEdge = boundary->fTail;
1514    float radius = 0.5f;
1515    double offset = radius * sqrt(prevEdge->fLine.magSq()) * prevEdge->fWinding;
1516    Line prevInner(prevEdge->fLine);
1517    prevInner.fC -= offset;
1518    Line prevOuter(prevEdge->fLine);
1519    prevOuter.fC += offset;
1520    VertexList innerVertices;
1521    VertexList outerVertices;
1522    Edge* prevBisector = nullptr;
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->fLine);
1526        inner.fC -= offset;
1527        Line outer(e->fLine);
1528        outer.fC += offset;
1529        SkPoint innerPoint, outerPoint;
1530        if (prevInner.intersect(inner, &innerPoint) &&
1531            prevOuter.intersect(outer, &outerPoint)) {
1532            Vertex* innerVertex = alloc.make<Vertex>(innerPoint, 255);
1533            Vertex* outerVertex = alloc.make<Vertex>(outerPoint, 0);
1534            Edge* bisector = new_edge(outerVertex, innerVertex, Edge::Type::kConnector, c, alloc);
1535            fix_inversions(innerVertices.fTail, innerVertex, prevBisector, bisector, prevEdge, c);
1536            fix_inversions(outerVertices.fTail, outerVertex, prevBisector, bisector, prevEdge, c);
1537            innerVertices.append(innerVertex);
1538            outerVertices.append(outerVertex);
1539            prevBisector = bisector;
1540        }
1541        prevInner = inner;
1542        prevOuter = outer;
1543        prevEdge = e;
1544    }
1545    innerVertices.close();
1546    outerVertices.close();
1547
1548    Vertex* innerVertex = innerVertices.fHead;
1549    Vertex* outerVertex = outerVertices.fHead;
1550    if (!innerVertex || !outerVertex) {
1551        return;
1552    }
1553    Edge* bisector = new_edge(outerVertices.fHead, innerVertices.fHead, Edge::Type::kConnector, c,
1554                              alloc);
1555    fix_inversions(innerVertices.fTail, innerVertices.fHead, prevBisector, bisector, prevEdge, c);
1556    fix_inversions(outerVertices.fTail, outerVertices.fHead, prevBisector, bisector, prevEdge, c);
1557    do {
1558        // Connect vertices into a quad mesh. Outer edges get default (1) winding.
1559        // Inner edges get -2 winding. This ensures that the interior is always filled
1560        // (-1 winding number for normal cases, 3 for thin features where the interior inverts).
1561        // Connector edges get zero winding, since they're only structural (i.e., to ensure
1562        // no 0-0-0 alpha triangles are produced), and shouldn't affect the poly winding number.
1563        connect(outerVertex->fPrev, outerVertex, Edge::Type::kOuter, c, alloc);
1564        connect(innerVertex->fPrev, innerVertex, Edge::Type::kInner, c, alloc, -2);
1565        connect(outerVertex, innerVertex, Edge::Type::kConnector, c, alloc, 0);
1566        Vertex* innerNext = innerVertex->fNext;
1567        Vertex* outerNext = outerVertex->fNext;
1568        mesh->append(innerVertex);
1569        mesh->append(outerVertex);
1570        innerVertex = innerNext;
1571        outerVertex = outerNext;
1572    } while (innerVertex != innerVertices.fHead && outerVertex != outerVertices.fHead);
1573}
1574
1575void extract_boundary(EdgeList* boundary, Edge* e, SkPath::FillType fillType, SkArenaAlloc& alloc) {
1576    bool down = apply_fill_type(fillType, e->fWinding);
1577    while (e) {
1578        e->fWinding = down ? 1 : -1;
1579        Edge* next;
1580        boundary->append(e);
1581        if (down) {
1582            // Find outgoing edge, in clockwise order.
1583            if ((next = e->fNextEdgeAbove)) {
1584                down = false;
1585            } else if ((next = e->fBottom->fLastEdgeBelow)) {
1586                down = true;
1587            } else if ((next = e->fPrevEdgeAbove)) {
1588                down = false;
1589            }
1590        } else {
1591            // Find outgoing edge, in counter-clockwise order.
1592            if ((next = e->fPrevEdgeBelow)) {
1593                down = true;
1594            } else if ((next = e->fTop->fFirstEdgeAbove)) {
1595                down = false;
1596            } else if ((next = e->fNextEdgeBelow)) {
1597                down = true;
1598            }
1599        }
1600        disconnect(e);
1601        e = next;
1602    }
1603}
1604
1605// Stage 5b: Extract boundaries from mesh, simplify and stroke them into a new mesh.
1606
1607void extract_boundaries(const VertexList& inMesh, VertexList* outMesh, SkPath::FillType fillType,
1608                        Comparator& c, SkArenaAlloc& alloc) {
1609    remove_non_boundary_edges(inMesh, fillType, alloc);
1610    for (Vertex* v = inMesh.fHead; v; v = v->fNext) {
1611        while (v->fFirstEdgeBelow) {
1612            EdgeList boundary;
1613            extract_boundary(&boundary, v->fFirstEdgeBelow, fillType, alloc);
1614            simplify_boundary(&boundary, c, alloc);
1615            boundary_to_aa_mesh(&boundary, outMesh, c, alloc);
1616        }
1617    }
1618}
1619
1620// This is a driver function which calls stages 2-5 in turn.
1621
1622void contours_to_mesh(Vertex** contours, int contourCnt, bool antialias,
1623                      VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1624#if LOGGING_ENABLED
1625    for (int i = 0; i < contourCnt; ++i) {
1626        Vertex* v = contours[i];
1627        SkASSERT(v);
1628        LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1629        for (v = v->fNext; v != contours[i]; v = v->fNext) {
1630            LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1631        }
1632    }
1633#endif
1634    sanitize_contours(contours, contourCnt, antialias);
1635    build_edges(contours, contourCnt, mesh, c, alloc);
1636}
1637
1638void sort_and_simplify(VertexList* vertices, Comparator& c, SkArenaAlloc& alloc) {
1639    if (!vertices || !vertices->fHead) {
1640        return;
1641    }
1642
1643    // Sort vertices in Y (secondarily in X).
1644    if (c.fDirection == Comparator::Direction::kHorizontal) {
1645        merge_sort<sweep_lt_horiz>(vertices);
1646    } else {
1647        merge_sort<sweep_lt_vert>(vertices);
1648    }
1649    merge_coincident_vertices(vertices, c, alloc);
1650#if LOGGING_ENABLED
1651    for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
1652        static float gID = 0.0f;
1653        v->fID = gID++;
1654    }
1655#endif
1656    simplify(*vertices, c, alloc);
1657}
1658
1659Poly* contours_to_polys(Vertex** contours, int contourCnt, SkPath::FillType fillType,
1660                        const SkRect& pathBounds, bool antialias,
1661                        SkArenaAlloc& alloc) {
1662    Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
1663                                                          : Comparator::Direction::kVertical);
1664    VertexList mesh;
1665    contours_to_mesh(contours, contourCnt, antialias, &mesh, c, alloc);
1666    sort_and_simplify(&mesh, c, alloc);
1667    if (antialias) {
1668        VertexList aaMesh;
1669        extract_boundaries(mesh, &aaMesh, fillType, c, alloc);
1670        sort_and_simplify(&aaMesh, c, alloc);
1671        return tessellate(aaMesh, alloc);
1672    } else {
1673        return tessellate(mesh, alloc);
1674    }
1675}
1676
1677// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1678void* polys_to_triangles(Poly* polys, SkPath::FillType fillType, const AAParams* aaParams,
1679                         void* data) {
1680    for (Poly* poly = polys; poly; poly = poly->fNext) {
1681        if (apply_fill_type(fillType, poly)) {
1682            data = poly->emit(aaParams, data);
1683        }
1684    }
1685    return data;
1686}
1687
1688Poly* path_to_polys(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1689                    int contourCnt, SkArenaAlloc& alloc, bool antialias, bool* isLinear) {
1690    SkPath::FillType fillType = path.getFillType();
1691    if (SkPath::IsInverseFillType(fillType)) {
1692        contourCnt++;
1693    }
1694    std::unique_ptr<Vertex*[]> contours(new Vertex* [contourCnt]);
1695
1696    path_to_contours(path, tolerance, clipBounds, contours.get(), alloc, isLinear);
1697    return contours_to_polys(contours.get(), contourCnt, path.getFillType(), path.getBounds(),
1698                             antialias, alloc);
1699}
1700
1701int get_contour_count(const SkPath& path, SkScalar tolerance) {
1702    int contourCnt;
1703    int maxPts = GrPathUtils::worstCasePointCount(path, &contourCnt, tolerance);
1704    if (maxPts <= 0) {
1705        return 0;
1706    }
1707    if (maxPts > ((int)SK_MaxU16 + 1)) {
1708        SkDebugf("Path not rendered, too many verts (%d)\n", maxPts);
1709        return 0;
1710    }
1711    return contourCnt;
1712}
1713
1714int count_points(Poly* polys, SkPath::FillType fillType) {
1715    int count = 0;
1716    for (Poly* poly = polys; poly; poly = poly->fNext) {
1717        if (apply_fill_type(fillType, poly) && poly->fCount >= 3) {
1718            count += (poly->fCount - 2) * (TESSELLATOR_WIREFRAME ? 6 : 3);
1719        }
1720    }
1721    return count;
1722}
1723
1724} // namespace
1725
1726namespace GrTessellator {
1727
1728// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1729
1730int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1731                    VertexAllocator* vertexAllocator, bool antialias, const GrColor& color,
1732                    bool canTweakAlphaForCoverage, bool* isLinear) {
1733    int contourCnt = get_contour_count(path, tolerance);
1734    if (contourCnt <= 0) {
1735        *isLinear = true;
1736        return 0;
1737    }
1738    SkArenaAlloc alloc(kArenaChunkSize);
1739    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, antialias,
1740                                isLinear);
1741    SkPath::FillType fillType = antialias ? SkPath::kWinding_FillType : path.getFillType();
1742    int count = count_points(polys, fillType);
1743    if (0 == count) {
1744        return 0;
1745    }
1746
1747    void* verts = vertexAllocator->lock(count);
1748    if (!verts) {
1749        SkDebugf("Could not allocate vertices\n");
1750        return 0;
1751    }
1752
1753    LOG("emitting %d verts\n", count);
1754    AAParams aaParams;
1755    aaParams.fTweakAlpha = canTweakAlphaForCoverage;
1756    aaParams.fColor = color;
1757
1758    void* end = polys_to_triangles(polys, fillType, antialias ? &aaParams : nullptr, verts);
1759    int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
1760                                       / vertexAllocator->stride());
1761    SkASSERT(actualCount <= count);
1762    vertexAllocator->unlock(actualCount);
1763    return actualCount;
1764}
1765
1766int PathToVertices(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1767                   GrTessellator::WindingVertex** verts) {
1768    int contourCnt = get_contour_count(path, tolerance);
1769    if (contourCnt <= 0) {
1770        return 0;
1771    }
1772    SkArenaAlloc alloc(kArenaChunkSize);
1773    bool isLinear;
1774    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, false, &isLinear);
1775    SkPath::FillType fillType = path.getFillType();
1776    int count = count_points(polys, fillType);
1777    if (0 == count) {
1778        *verts = nullptr;
1779        return 0;
1780    }
1781
1782    *verts = new GrTessellator::WindingVertex[count];
1783    GrTessellator::WindingVertex* vertsEnd = *verts;
1784    SkPoint* points = new SkPoint[count];
1785    SkPoint* pointsEnd = points;
1786    for (Poly* poly = polys; poly; poly = poly->fNext) {
1787        if (apply_fill_type(fillType, poly)) {
1788            SkPoint* start = pointsEnd;
1789            pointsEnd = static_cast<SkPoint*>(poly->emit(nullptr, pointsEnd));
1790            while (start != pointsEnd) {
1791                vertsEnd->fPos = *start;
1792                vertsEnd->fWinding = poly->fWinding;
1793                ++start;
1794                ++vertsEnd;
1795            }
1796        }
1797    }
1798    int actualCount = static_cast<int>(vertsEnd - *verts);
1799    SkASSERT(actualCount <= count);
1800    SkASSERT(pointsEnd - points == actualCount);
1801    delete[] points;
1802    return actualCount;
1803}
1804
1805} // namespace
1806