Simplify.cpp revision 0c803d048c826fadfeed51207488867e17e0cc10
1/*
2 * Copyright 2012 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#include "Simplify.h"
8
9#undef SkASSERT
10#define SkASSERT(cond) while (!(cond)) { sk_throw(); }
11
12// Terminology:
13// A Path contains one of more Contours
14// A Contour is made up of Segment array
15// A Segment is described by a Verb and a Point array with 2, 3, or 4 points
16// A Verb is one of Line, Quad(ratic), or Cubic
17// A Segment contains a Span array
18// A Span is describes a portion of a Segment using starting and ending T
19// T values range from 0 to 1, where 0 is the first Point in the Segment
20// An Edge is a Segment generated from a Span
21
22// FIXME: remove once debugging is complete
23#ifdef SK_DEBUG
24int gDebugMaxWindSum = SK_MaxS32;
25int gDebugMaxWindValue = SK_MaxS32;
26#endif
27
28#define DEBUG_UNUSED 0 // set to expose unused functions
29
30#if 0 // set to 1 for multiple thread -- no debugging
31
32const bool gRunTestsInOneThread = false;
33
34#define DEBUG_ACTIVE_SPANS 0
35#define DEBUG_ADD_INTERSECTING_TS 0
36#define DEBUG_ADD_T_PAIR 0
37#define DEBUG_CONCIDENT 0
38#define DEBUG_CROSS 0
39#define DEBUG_DUMP 0
40#define DEBUG_MARK_DONE 0
41#define DEBUG_PATH_CONSTRUCTION 0
42#define DEBUG_SORT 0
43#define DEBUG_WIND_BUMP 0
44#define DEBUG_WINDING 0
45
46#else
47
48const bool gRunTestsInOneThread = true;
49
50#define DEBUG_ACTIVE_SPANS 1
51#define DEBUG_ADD_INTERSECTING_TS 0
52#define DEBUG_ADD_T_PAIR 1
53#define DEBUG_CONCIDENT 1
54#define DEBUG_CROSS 0
55#define DEBUG_DUMP 1
56#define DEBUG_MARK_DONE 1
57#define DEBUG_PATH_CONSTRUCTION 1
58#define DEBUG_SORT 1
59#define DEBUG_WIND_BUMP 0
60#define DEBUG_WINDING 1
61
62#endif
63
64#if (DEBUG_ACTIVE_SPANS || DEBUG_CONCIDENT || DEBUG_SORT) && !DEBUG_DUMP
65#undef DEBUG_DUMP
66#define DEBUG_DUMP 1
67#endif
68
69#if DEBUG_DUMP
70static const char* kLVerbStr[] = {"", "line", "quad", "cubic"};
71// static const char* kUVerbStr[] = {"", "Line", "Quad", "Cubic"};
72static int gContourID;
73static int gSegmentID;
74#endif
75
76#ifndef DEBUG_TEST
77#define DEBUG_TEST 0
78#endif
79
80static int LineIntersect(const SkPoint a[2], const SkPoint b[2],
81        Intersections& intersections) {
82    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
83    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
84    return intersect(aLine, bLine, intersections.fT[0], intersections.fT[1]);
85}
86
87static int QuadLineIntersect(const SkPoint a[3], const SkPoint b[2],
88        Intersections& intersections) {
89    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
90    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
91    intersect(aQuad, bLine, intersections);
92    return intersections.fUsed;
93}
94
95static int CubicLineIntersect(const SkPoint a[2], const SkPoint b[3],
96        Intersections& intersections) {
97    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
98            {a[3].fX, a[3].fY}};
99    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
100    return intersect(aCubic, bLine, intersections.fT[0], intersections.fT[1]);
101}
102
103static int QuadIntersect(const SkPoint a[3], const SkPoint b[3],
104        Intersections& intersections) {
105    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
106    const Quadratic bQuad = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}, {b[2].fX, b[2].fY}};
107    intersect(aQuad, bQuad, intersections);
108    return intersections.fUsed;
109}
110
111static int CubicIntersect(const SkPoint a[4], const SkPoint b[4],
112        Intersections& intersections) {
113    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
114            {a[3].fX, a[3].fY}};
115    const Cubic bCubic = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}, {b[2].fX, b[2].fY},
116            {b[3].fX, b[3].fY}};
117    intersect(aCubic, bCubic, intersections);
118    return intersections.fUsed;
119}
120
121static int HLineIntersect(const SkPoint a[2], SkScalar left, SkScalar right,
122        SkScalar y, bool flipped, Intersections& intersections) {
123    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
124    return horizontalIntersect(aLine, left, right, y, flipped, intersections);
125}
126
127static int HQuadIntersect(const SkPoint a[3], SkScalar left, SkScalar right,
128        SkScalar y, bool flipped, Intersections& intersections) {
129    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
130    return horizontalIntersect(aQuad, left, right, y, flipped, intersections);
131}
132
133static int HCubicIntersect(const SkPoint a[4], SkScalar left, SkScalar right,
134        SkScalar y, bool flipped, Intersections& intersections) {
135    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
136            {a[3].fX, a[3].fY}};
137    return horizontalIntersect(aCubic, left, right, y, flipped, intersections);
138}
139
140static int VLineIntersect(const SkPoint a[2], SkScalar top, SkScalar bottom,
141        SkScalar x, bool flipped, Intersections& intersections) {
142    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
143    return verticalIntersect(aLine, top, bottom, x, flipped, intersections);
144}
145
146static int VQuadIntersect(const SkPoint a[3], SkScalar top, SkScalar bottom,
147        SkScalar x, bool flipped, Intersections& intersections) {
148    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
149    return verticalIntersect(aQuad, top, bottom, x, flipped, intersections);
150}
151
152static int VCubicIntersect(const SkPoint a[4], SkScalar top, SkScalar bottom,
153        SkScalar x, bool flipped, Intersections& intersections) {
154    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
155            {a[3].fX, a[3].fY}};
156    return verticalIntersect(aCubic, top, bottom, x, flipped, intersections);
157}
158
159static int (* const VSegmentIntersect[])(const SkPoint [], SkScalar ,
160        SkScalar , SkScalar , bool , Intersections& ) = {
161    NULL,
162    VLineIntersect,
163    VQuadIntersect,
164    VCubicIntersect
165};
166
167static void LineXYAtT(const SkPoint a[2], double t, SkPoint* out) {
168    const _Line line = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
169    double x, y;
170    xy_at_t(line, t, x, y);
171    out->fX = SkDoubleToScalar(x);
172    out->fY = SkDoubleToScalar(y);
173}
174
175static void QuadXYAtT(const SkPoint a[3], double t, SkPoint* out) {
176    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
177    double x, y;
178    xy_at_t(quad, t, x, y);
179    out->fX = SkDoubleToScalar(x);
180    out->fY = SkDoubleToScalar(y);
181}
182
183static void CubicXYAtT(const SkPoint a[4], double t, SkPoint* out) {
184    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
185            {a[3].fX, a[3].fY}};
186    double x, y;
187    xy_at_t(cubic, t, x, y);
188    out->fX = SkDoubleToScalar(x);
189    out->fY = SkDoubleToScalar(y);
190}
191
192static void (* const SegmentXYAtT[])(const SkPoint [], double , SkPoint* ) = {
193    NULL,
194    LineXYAtT,
195    QuadXYAtT,
196    CubicXYAtT
197};
198
199static SkScalar LineXAtT(const SkPoint a[2], double t) {
200    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
201    double x;
202    xy_at_t(aLine, t, x, *(double*) 0);
203    return SkDoubleToScalar(x);
204}
205
206static SkScalar QuadXAtT(const SkPoint a[3], double t) {
207    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
208    double x;
209    xy_at_t(quad, t, x, *(double*) 0);
210    return SkDoubleToScalar(x);
211}
212
213static SkScalar CubicXAtT(const SkPoint a[4], double t) {
214    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
215            {a[3].fX, a[3].fY}};
216    double x;
217    xy_at_t(cubic, t, x, *(double*) 0);
218    return SkDoubleToScalar(x);
219}
220
221static SkScalar (* const SegmentXAtT[])(const SkPoint [], double ) = {
222    NULL,
223    LineXAtT,
224    QuadXAtT,
225    CubicXAtT
226};
227
228static SkScalar LineYAtT(const SkPoint a[2], double t) {
229    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
230    double y;
231    xy_at_t(aLine, t, *(double*) 0, y);
232    return SkDoubleToScalar(y);
233}
234
235static SkScalar QuadYAtT(const SkPoint a[3], double t) {
236    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
237    double y;
238    xy_at_t(quad, t, *(double*) 0, y);
239    return SkDoubleToScalar(y);
240}
241
242static SkScalar CubicYAtT(const SkPoint a[4], double t) {
243    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
244            {a[3].fX, a[3].fY}};
245    double y;
246    xy_at_t(cubic, t, *(double*) 0, y);
247    return SkDoubleToScalar(y);
248}
249
250static SkScalar (* const SegmentYAtT[])(const SkPoint [], double ) = {
251    NULL,
252    LineYAtT,
253    QuadYAtT,
254    CubicYAtT
255};
256
257static SkScalar LineDXAtT(const SkPoint a[2], double ) {
258    return a[1].fX - a[0].fX;
259}
260
261static SkScalar QuadDXAtT(const SkPoint a[3], double t) {
262    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
263    double x;
264    dxdy_at_t(quad, t, x, *(double*) 0);
265    return SkDoubleToScalar(x);
266}
267
268static SkScalar CubicDXAtT(const SkPoint a[4], double t) {
269    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
270            {a[3].fX, a[3].fY}};
271    double x;
272    dxdy_at_t(cubic, t, x, *(double*) 0);
273    return SkDoubleToScalar(x);
274}
275
276static SkScalar (* const SegmentDXAtT[])(const SkPoint [], double ) = {
277    NULL,
278    LineDXAtT,
279    QuadDXAtT,
280    CubicDXAtT
281};
282
283static void LineSubDivide(const SkPoint a[2], double startT, double endT,
284        SkPoint sub[2]) {
285    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
286    _Line dst;
287    sub_divide(aLine, startT, endT, dst);
288    sub[0].fX = SkDoubleToScalar(dst[0].x);
289    sub[0].fY = SkDoubleToScalar(dst[0].y);
290    sub[1].fX = SkDoubleToScalar(dst[1].x);
291    sub[1].fY = SkDoubleToScalar(dst[1].y);
292}
293
294static void QuadSubDivide(const SkPoint a[3], double startT, double endT,
295        SkPoint sub[3]) {
296    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
297            {a[2].fX, a[2].fY}};
298    Quadratic dst;
299    sub_divide(aQuad, startT, endT, dst);
300    sub[0].fX = SkDoubleToScalar(dst[0].x);
301    sub[0].fY = SkDoubleToScalar(dst[0].y);
302    sub[1].fX = SkDoubleToScalar(dst[1].x);
303    sub[1].fY = SkDoubleToScalar(dst[1].y);
304    sub[2].fX = SkDoubleToScalar(dst[2].x);
305    sub[2].fY = SkDoubleToScalar(dst[2].y);
306}
307
308static void CubicSubDivide(const SkPoint a[4], double startT, double endT,
309        SkPoint sub[4]) {
310    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
311            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
312    Cubic dst;
313    sub_divide(aCubic, startT, endT, dst);
314    sub[0].fX = SkDoubleToScalar(dst[0].x);
315    sub[0].fY = SkDoubleToScalar(dst[0].y);
316    sub[1].fX = SkDoubleToScalar(dst[1].x);
317    sub[1].fY = SkDoubleToScalar(dst[1].y);
318    sub[2].fX = SkDoubleToScalar(dst[2].x);
319    sub[2].fY = SkDoubleToScalar(dst[2].y);
320    sub[3].fX = SkDoubleToScalar(dst[3].x);
321    sub[3].fY = SkDoubleToScalar(dst[3].y);
322}
323
324static void (* const SegmentSubDivide[])(const SkPoint [], double , double ,
325        SkPoint []) = {
326    NULL,
327    LineSubDivide,
328    QuadSubDivide,
329    CubicSubDivide
330};
331
332#if DEBUG_UNUSED
333static void QuadSubBounds(const SkPoint a[3], double startT, double endT,
334        SkRect& bounds) {
335    SkPoint dst[3];
336    QuadSubDivide(a, startT, endT, dst);
337    bounds.fLeft = bounds.fRight = dst[0].fX;
338    bounds.fTop = bounds.fBottom = dst[0].fY;
339    for (int index = 1; index < 3; ++index) {
340        bounds.growToInclude(dst[index].fX, dst[index].fY);
341    }
342}
343
344static void CubicSubBounds(const SkPoint a[4], double startT, double endT,
345        SkRect& bounds) {
346    SkPoint dst[4];
347    CubicSubDivide(a, startT, endT, dst);
348    bounds.fLeft = bounds.fRight = dst[0].fX;
349    bounds.fTop = bounds.fBottom = dst[0].fY;
350    for (int index = 1; index < 4; ++index) {
351        bounds.growToInclude(dst[index].fX, dst[index].fY);
352    }
353}
354#endif
355
356static SkPath::Verb QuadReduceOrder(const SkPoint a[3],
357        SkTDArray<SkPoint>& reducePts) {
358    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
359            {a[2].fX, a[2].fY}};
360    Quadratic dst;
361    int order = reduceOrder(aQuad, dst);
362    if (order == 3) {
363        return SkPath::kQuad_Verb;
364    }
365    for (int index = 0; index < order; ++index) {
366        SkPoint* pt = reducePts.append();
367        pt->fX = SkDoubleToScalar(dst[index].x);
368        pt->fY = SkDoubleToScalar(dst[index].y);
369    }
370    return (SkPath::Verb) (order - 1);
371}
372
373static SkPath::Verb CubicReduceOrder(const SkPoint a[4],
374        SkTDArray<SkPoint>& reducePts) {
375    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
376            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
377    Cubic dst;
378    int order = reduceOrder(aCubic, dst, kReduceOrder_QuadraticsAllowed);
379    if (order == 4) {
380        return SkPath::kCubic_Verb;
381    }
382    for (int index = 0; index < order; ++index) {
383        SkPoint* pt = reducePts.append();
384        pt->fX = SkDoubleToScalar(dst[index].x);
385        pt->fY = SkDoubleToScalar(dst[index].y);
386    }
387    return (SkPath::Verb) (order - 1);
388}
389
390static bool QuadIsLinear(const SkPoint a[3]) {
391    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
392            {a[2].fX, a[2].fY}};
393    return isLinear(aQuad, 0, 2);
394}
395
396static bool CubicIsLinear(const SkPoint a[4]) {
397    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
398            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
399    return isLinear(aCubic, 0, 3);
400}
401
402static SkScalar LineLeftMost(const SkPoint a[2], double startT, double endT) {
403    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
404    double x[2];
405    xy_at_t(aLine, startT, x[0], *(double*) 0);
406    xy_at_t(aLine, endT, x[1], *(double*) 0);
407    return SkMinScalar((float) x[0], (float) x[1]);
408}
409
410static SkScalar QuadLeftMost(const SkPoint a[3], double startT, double endT) {
411    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
412            {a[2].fX, a[2].fY}};
413    return (float) leftMostT(aQuad, startT, endT);
414}
415
416static SkScalar CubicLeftMost(const SkPoint a[4], double startT, double endT) {
417    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
418            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
419    return (float) leftMostT(aCubic, startT, endT);
420}
421
422static SkScalar (* const SegmentLeftMost[])(const SkPoint [], double , double) = {
423    NULL,
424    LineLeftMost,
425    QuadLeftMost,
426    CubicLeftMost
427};
428
429#if DEBUG_UNUSED
430static bool IsCoincident(const SkPoint a[2], const SkPoint& above,
431        const SkPoint& below) {
432    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
433    const _Line bLine = {{above.fX, above.fY}, {below.fX, below.fY}};
434    return implicit_matches_ulps(aLine, bLine, 32);
435}
436#endif
437
438class Segment;
439
440// sorting angles
441// given angles of {dx dy ddx ddy dddx dddy} sort them
442class Angle {
443public:
444    // FIXME: this is bogus for quads and cubics
445    // if the quads and cubics' line from end pt to ctrl pt are coincident,
446    // there's no obvious way to determine the curve ordering from the
447    // derivatives alone. In particular, if one quadratic's coincident tangent
448    // is longer than the other curve, the final control point can place the
449    // longer curve on either side of the shorter one.
450    // Using Bezier curve focus http://cagd.cs.byu.edu/~tom/papers/bezclip.pdf
451    // may provide some help, but nothing has been figured out yet.
452    bool operator<(const Angle& rh) const {
453        if ((fDy < 0) ^ (rh.fDy < 0)) {
454            return fDy < 0;
455        }
456        if (fDy == 0 && rh.fDy == 0 && fDx != rh.fDx) {
457            return fDx < rh.fDx;
458        }
459        SkScalar cmp = fDx * rh.fDy - rh.fDx * fDy;
460        if (cmp) {
461            return cmp < 0;
462        }
463        if ((fDDy < 0) ^ (rh.fDDy < 0)) {
464            return fDDy < 0;
465        }
466        if (fDDy == 0 && rh.fDDy == 0 && fDDx != rh.fDDx) {
467            return fDDx < rh.fDDx;
468        }
469        cmp = fDDx * rh.fDDy - rh.fDDx * fDDy;
470        if (cmp) {
471            return cmp < 0;
472        }
473        if ((fDDDy < 0) ^ (rh.fDDDy < 0)) {
474            return fDDDy < 0;
475        }
476        if (fDDDy == 0 && rh.fDDDy == 0) {
477            return fDDDx < rh.fDDDx;
478        }
479        return fDDDx * rh.fDDDy < rh.fDDDx * fDDDy;
480    }
481
482    double dx() const {
483        return fDx;
484    }
485
486    double dy() const {
487        return fDy;
488    }
489
490    int end() const {
491        return fEnd;
492    }
493
494    bool firstBump(int sumWinding) const {
495        SkDebugf("%s sign=%d sumWinding=%d\n", __FUNCTION__, sign(), sumWinding);
496        return sign() * sumWinding > 0;
497    }
498
499    bool isHorizontal() const {
500        return fDy == 0 && fDDy == 0 && fDDDy == 0;
501    }
502
503    // since all angles share a point, this needs to know which point
504    // is the common origin, i.e., whether the center is at pts[0] or pts[verb]
505    // practically, this should only be called by addAngle
506    void set(const SkPoint* pts, SkPath::Verb verb, const Segment* segment,
507            int start, int end) {
508        SkASSERT(start != end);
509        fSegment = segment;
510        fStart = start;
511        fEnd = end;
512        fDx = pts[1].fX - pts[0].fX; // b - a
513        fDy = pts[1].fY - pts[0].fY;
514        if (verb == SkPath::kLine_Verb) {
515            fDDx = fDDy = fDDDx = fDDDy = 0;
516            return;
517        }
518        fDDx = pts[2].fX - pts[1].fX - fDx; // a - 2b + c
519        fDDy = pts[2].fY - pts[1].fY - fDy;
520        if (verb == SkPath::kQuad_Verb) {
521            fDDDx = fDDDy = 0;
522            return;
523        }
524        fDDDx = pts[3].fX + 3 * (pts[1].fX - pts[2].fX) - pts[0].fX;
525        fDDDy = pts[3].fY + 3 * (pts[1].fY - pts[2].fY) - pts[0].fY;
526    }
527
528    // noncoincident quads/cubics may have the same initial angle
529    // as lines, so must sort by derivatives as well
530    // if flatness turns out to be a reasonable way to sort, use the below:
531    void setFlat(const SkPoint* pts, SkPath::Verb verb, Segment* segment,
532            int start, int end) {
533        fSegment = segment;
534        fStart = start;
535        fEnd = end;
536        fDx = pts[1].fX - pts[0].fX; // b - a
537        fDy = pts[1].fY - pts[0].fY;
538        if (verb == SkPath::kLine_Verb) {
539            fDDx = fDDy = fDDDx = fDDDy = 0;
540            return;
541        }
542        if (verb == SkPath::kQuad_Verb) {
543            int uplsX = FloatAsInt(pts[2].fX - pts[1].fY - fDx);
544            int uplsY = FloatAsInt(pts[2].fY - pts[1].fY - fDy);
545            int larger = std::max(abs(uplsX), abs(uplsY));
546            int shift = 0;
547            double flatT;
548            SkPoint ddPt; // FIXME: get rid of copy (change fDD_ to point)
549            LineParameters implicitLine;
550            _Line tangent = {{pts[0].fX, pts[0].fY}, {pts[1].fX, pts[1].fY}};
551            implicitLine.lineEndPoints(tangent);
552            implicitLine.normalize();
553            while (larger > UlpsEpsilon * 1024) {
554                larger >>= 2;
555                ++shift;
556                flatT = 0.5 / (1 << shift);
557                QuadXYAtT(pts, flatT, &ddPt);
558                _Point _pt = {ddPt.fX, ddPt.fY};
559                double distance = implicitLine.pointDistance(_pt);
560                if (approximately_zero(distance)) {
561                    SkDebugf("%s ulps too small %1.9g\n", __FUNCTION__, distance);
562                    break;
563                }
564            }
565            flatT = 0.5 / (1 << shift);
566            QuadXYAtT(pts, flatT, &ddPt);
567            fDDx = ddPt.fX - pts[0].fX;
568            fDDy = ddPt.fY - pts[0].fY;
569            SkASSERT(fDDx != 0 || fDDy != 0);
570            fDDDx = fDDDy = 0;
571            return;
572        }
573        SkASSERT(0); // FIXME: add cubic case
574    }
575
576    Segment* segment() const {
577        return const_cast<Segment*>(fSegment);
578    }
579
580    int sign() const {
581        return SkSign32(fStart - fEnd);
582    }
583
584    int start() const {
585        return fStart;
586    }
587
588private:
589    SkScalar fDx;
590    SkScalar fDy;
591    SkScalar fDDx;
592    SkScalar fDDy;
593    SkScalar fDDDx;
594    SkScalar fDDDy;
595    const Segment* fSegment;
596    int fStart;
597    int fEnd;
598};
599
600static void sortAngles(SkTDArray<Angle>& angles, SkTDArray<Angle*>& angleList) {
601    int angleCount = angles.count();
602    int angleIndex;
603    angleList.setReserve(angleCount);
604    for (angleIndex = 0; angleIndex < angleCount; ++angleIndex) {
605        *angleList.append() = &angles[angleIndex];
606    }
607    QSort<Angle>(angleList.begin(), angleList.end() - 1);
608}
609
610// Bounds, unlike Rect, does not consider a line to be empty.
611struct Bounds : public SkRect {
612    static bool Intersects(const Bounds& a, const Bounds& b) {
613        return a.fLeft <= b.fRight && b.fLeft <= a.fRight &&
614                a.fTop <= b.fBottom && b.fTop <= a.fBottom;
615    }
616
617    void add(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom) {
618        if (left < fLeft) {
619            fLeft = left;
620        }
621        if (top < fTop) {
622            fTop = top;
623        }
624        if (right > fRight) {
625            fRight = right;
626        }
627        if (bottom > fBottom) {
628            fBottom = bottom;
629        }
630    }
631
632    void add(const Bounds& toAdd) {
633        add(toAdd.fLeft, toAdd.fTop, toAdd.fRight, toAdd.fBottom);
634    }
635
636    bool isEmpty() {
637        return fLeft > fRight || fTop > fBottom
638                || fLeft == fRight && fTop == fBottom
639                || isnan(fLeft) || isnan(fRight)
640                || isnan(fTop) || isnan(fBottom);
641    }
642
643    void setCubicBounds(const SkPoint a[4]) {
644        _Rect dRect;
645        Cubic cubic  = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
646            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
647        dRect.setBounds(cubic);
648        set((float) dRect.left, (float) dRect.top, (float) dRect.right,
649                (float) dRect.bottom);
650    }
651
652    void setQuadBounds(const SkPoint a[3]) {
653        const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
654                {a[2].fX, a[2].fY}};
655        _Rect dRect;
656        dRect.setBounds(quad);
657        set((float) dRect.left, (float) dRect.top, (float) dRect.right,
658                (float) dRect.bottom);
659    }
660};
661
662struct Span {
663    Segment* fOther;
664    mutable SkPoint fPt; // lazily computed as needed
665    double fT;
666    double fOtherT; // value at fOther[fOtherIndex].fT
667    int fOtherIndex;  // can't be used during intersection
668    int fWindSum; // accumulated from contours surrounding this one
669    int fWindValue; // 0 == canceled; 1 == normal; >1 == coincident
670    bool fDone; // if set, this span to next higher T has been processed
671};
672
673class Segment {
674public:
675    Segment() {
676#if DEBUG_DUMP
677        fID = ++gSegmentID;
678#endif
679    }
680
681    bool activeAngle(int index, int& done, SkTDArray<Angle>& angles) const {
682        if (activeAngleInner(index, done, angles)) {
683            return true;
684        }
685        double referenceT = fTs[index].fT;
686        int lesser = index;
687        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
688            if (activeAngleOther(lesser, done, angles)) {
689                return true;
690            }
691        }
692        do {
693            if (activeAngleOther(index, done, angles)) {
694                return true;
695            }
696        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
697        return false;
698    }
699
700    bool activeAngleOther(int index, int& done, SkTDArray<Angle>& angles) const {
701        Span* span = &fTs[index];
702        Segment* other = span->fOther;
703        int oIndex = span->fOtherIndex;
704        return other->activeAngleInner(oIndex, done, angles);
705    }
706
707    bool activeAngleInner(int index, int& done, SkTDArray<Angle>& angles) const {
708        int next = nextSpan(index, 1);
709        if (next > 0) {
710            const Span& upSpan = fTs[index];
711            if (upSpan.fWindValue) {
712                addAngle(angles, index, next);
713                if (upSpan.fDone) {
714                    done++;
715                } else if (upSpan.fWindSum != SK_MinS32) {
716                    return true;
717                }
718            }
719        }
720        int prev = nextSpan(index, -1);
721        // edge leading into junction
722        if (prev >= 0) {
723            const Span& downSpan = fTs[prev];
724            if (downSpan.fWindValue) {
725                addAngle(angles, index, prev);
726                if (downSpan.fDone) {
727                    done++;
728                 } else if (downSpan.fWindSum != SK_MinS32) {
729                    return true;
730                }
731            }
732        }
733        return false;
734    }
735
736    SkScalar activeTop() const {
737        SkASSERT(!done());
738        int count = fTs.count();
739        SkScalar result = SK_ScalarMax;
740        bool lastDone = true;
741        for (int index = 0; index < count; ++index) {
742            bool done = fTs[index].fDone;
743            if (!done || !lastDone) {
744                SkScalar y = yAtT(index);
745                if (result > y) {
746                    result = y;
747                }
748            }
749            lastDone = done;
750        }
751        SkASSERT(result < SK_ScalarMax);
752        return result;
753    }
754
755    void addAngle(SkTDArray<Angle>& angles, int start, int end) const {
756        SkASSERT(start != end);
757        SkPoint edge[4];
758        (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
759        Angle* angle = angles.append();
760        angle->set(edge, fVerb, this, start, end);
761    }
762
763    void addCancelOutsides(const SkTDArray<double>& outsideTs, Segment& other,
764            double oEnd) {
765        int tIndex = -1;
766        int tCount = fTs.count();
767        int oIndex = -1;
768        int oCount = other.fTs.count();
769        double tStart = outsideTs[0];
770        double oStart = outsideTs[1];
771        do {
772            ++tIndex;
773        } while (tStart - fTs[tIndex].fT >= FLT_EPSILON && tIndex < tCount);
774        int tIndexStart = tIndex;
775        do {
776            ++oIndex;
777        } while (oStart - other.fTs[oIndex].fT >= FLT_EPSILON && oIndex < oCount);
778        int oIndexStart = oIndex;
779        double nextT;
780        do {
781            nextT = fTs[++tIndex].fT;
782        } while (nextT < 1 && nextT - tStart < FLT_EPSILON);
783        double oNextT;
784        do {
785            oNextT = other.fTs[++oIndex].fT;
786        } while (oNextT < 1 && oNextT - oStart < FLT_EPSILON);
787        // at this point, spans before and after are at:
788        //  fTs[tIndexStart - 1], fTs[tIndexStart], fTs[tIndex]
789        // if tIndexStart == 0, no prior span
790        // if nextT == 1, no following span
791
792        // advance the span with zero winding
793        // if the following span exists (not past the end, non-zero winding)
794        // connect the two edges
795        if (!fTs[tIndexStart].fWindValue) {
796            if (tIndexStart > 0 && fTs[tIndexStart - 1].fWindValue) {
797    #if DEBUG_CONCIDENT
798                SkDebugf("%s 1 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
799                        __FUNCTION__, fID, other.fID, tIndexStart - 1,
800                        fTs[tIndexStart].fT, xyAtT(tIndexStart).fX,
801                        xyAtT(tIndexStart).fY);
802    #endif
803                addTPair(fTs[tIndexStart].fT, other, other.fTs[oIndex].fT);
804            }
805            if (nextT < 1 && fTs[tIndex].fWindValue) {
806    #if DEBUG_CONCIDENT
807                SkDebugf("%s 2 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
808                        __FUNCTION__, fID, other.fID, tIndex,
809                        fTs[tIndex].fT, xyAtT(tIndex).fX,
810                        xyAtT(tIndex).fY);
811    #endif
812                addTPair(fTs[tIndex].fT, other, other.fTs[oIndexStart].fT);
813            }
814        } else {
815            SkASSERT(!other.fTs[oIndexStart].fWindValue);
816            if (oIndexStart > 0 && other.fTs[oIndexStart - 1].fWindValue) {
817    #if DEBUG_CONCIDENT
818                SkDebugf("%s 3 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
819                        __FUNCTION__, fID, other.fID, oIndexStart - 1,
820                        other.fTs[oIndexStart].fT, other.xyAtT(oIndexStart).fX,
821                        other.xyAtT(oIndexStart).fY);
822                other.debugAddTPair(other.fTs[oIndexStart].fT, *this, fTs[tIndex].fT);
823    #endif
824            }
825            if (oNextT < 1 && other.fTs[oIndex].fWindValue) {
826    #if DEBUG_CONCIDENT
827                SkDebugf("%s 4 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
828                        __FUNCTION__, fID, other.fID, oIndex,
829                        other.fTs[oIndex].fT, other.xyAtT(oIndex).fX,
830                        other.xyAtT(oIndex).fY);
831                other.debugAddTPair(other.fTs[oIndex].fT, *this, fTs[tIndexStart].fT);
832    #endif
833            }
834        }
835    }
836
837    void addCoinOutsides(const SkTDArray<double>& outsideTs, Segment& other,
838            double oEnd) {
839        // walk this to outsideTs[0]
840        // walk other to outsideTs[1]
841        // if either is > 0, add a pointer to the other, copying adjacent winding
842        int tIndex = -1;
843        int oIndex = -1;
844        double tStart = outsideTs[0];
845        double oStart = outsideTs[1];
846        do {
847            ++tIndex;
848        } while (tStart - fTs[tIndex].fT >= FLT_EPSILON);
849        do {
850            ++oIndex;
851        } while (oStart - other.fTs[oIndex].fT >= FLT_EPSILON);
852        if (tIndex > 0 || oIndex > 0) {
853            addTPair(tStart, other, oStart);
854        }
855        tStart = fTs[tIndex].fT;
856        oStart = other.fTs[oIndex].fT;
857        do {
858            double nextT;
859            do {
860                nextT = fTs[++tIndex].fT;
861            } while (nextT - tStart < FLT_EPSILON);
862            tStart = nextT;
863            do {
864                nextT = other.fTs[++oIndex].fT;
865            } while (nextT - oStart < FLT_EPSILON);
866            oStart = nextT;
867            if (tStart == 1 && oStart == 1) {
868                break;
869            }
870            addTPair(tStart, other, oStart);
871        } while (tStart < 1 && oStart < 1 && oEnd - oStart >= FLT_EPSILON);
872    }
873
874    void addCubic(const SkPoint pts[4]) {
875        init(pts, SkPath::kCubic_Verb);
876        fBounds.setCubicBounds(pts);
877    }
878
879    // FIXME: this needs to defer add for aligned consecutive line segments
880    SkPoint addCurveTo(int start, int end, SkPath& path, bool active) {
881        SkPoint edge[4];
882        // OPTIMIZE? if not active, skip remainder and return xy_at_t(end)
883        (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
884        if (active) {
885    #if DEBUG_PATH_CONSTRUCTION
886            SkDebugf("%s %s (%1.9g,%1.9g)", __FUNCTION__,
887                    kLVerbStr[fVerb], edge[1].fX, edge[1].fY);
888            if (fVerb > 1) {
889                SkDebugf(" (%1.9g,%1.9g)", edge[2].fX, edge[2].fY);
890            }
891            if (fVerb > 2) {
892                SkDebugf(" (%1.9g,%1.9g)", edge[3].fX, edge[3].fY);
893            }
894            SkDebugf("\n");
895    #endif
896            switch (fVerb) {
897                case SkPath::kLine_Verb:
898                    path.lineTo(edge[1].fX, edge[1].fY);
899                    break;
900                case SkPath::kQuad_Verb:
901                    path.quadTo(edge[1].fX, edge[1].fY, edge[2].fX, edge[2].fY);
902                    break;
903                case SkPath::kCubic_Verb:
904                    path.cubicTo(edge[1].fX, edge[1].fY, edge[2].fX, edge[2].fY,
905                            edge[3].fX, edge[3].fY);
906                    break;
907            }
908        }
909        return edge[fVerb];
910    }
911
912    void addLine(const SkPoint pts[2]) {
913        init(pts, SkPath::kLine_Verb);
914        fBounds.set(pts, 2);
915    }
916
917    const SkPoint& addMoveTo(int tIndex, SkPath& path, bool active) {
918        const SkPoint& pt = xyAtT(tIndex);
919        if (active) {
920    #if DEBUG_PATH_CONSTRUCTION
921            SkDebugf("%s (%1.9g,%1.9g)\n", __FUNCTION__, pt.fX, pt.fY);
922    #endif
923            path.moveTo(pt.fX, pt.fY);
924        }
925        return pt;
926    }
927
928    // add 2 to edge or out of range values to get T extremes
929    void addOtherT(int index, double otherT, int otherIndex) {
930        Span& span = fTs[index];
931        span.fOtherT = otherT;
932        span.fOtherIndex = otherIndex;
933    }
934
935    void addQuad(const SkPoint pts[3]) {
936        init(pts, SkPath::kQuad_Verb);
937        fBounds.setQuadBounds(pts);
938    }
939
940    // Defer all coincident edge processing until
941    // after normal intersections have been computed
942
943// no need to be tricky; insert in normal T order
944// resolve overlapping ts when considering coincidence later
945
946    // add non-coincident intersection. Resulting edges are sorted in T.
947    int addT(double newT, Segment* other) {
948        // FIXME: in the pathological case where there is a ton of intercepts,
949        //  binary search?
950        int insertedAt = -1;
951        size_t tCount = fTs.count();
952        for (size_t index = 0; index < tCount; ++index) {
953            // OPTIMIZATION: if there are three or more identical Ts, then
954            // the fourth and following could be further insertion-sorted so
955            // that all the edges are clockwise or counterclockwise.
956            // This could later limit segment tests to the two adjacent
957            // neighbors, although it doesn't help with determining which
958            // circular direction to go in.
959            if (newT < fTs[index].fT) {
960                insertedAt = index;
961                break;
962            }
963        }
964        Span* span;
965        if (insertedAt >= 0) {
966            span = fTs.insert(insertedAt);
967        } else {
968            insertedAt = tCount;
969            span = fTs.append();
970        }
971        span->fT = newT;
972        span->fOther = other;
973        span->fPt.fX = SK_ScalarNaN;
974        span->fWindSum = SK_MinS32;
975        span->fWindValue = 1;
976        if ((span->fDone = newT == 1)) {
977            ++fDoneSpans;
978        }
979        return insertedAt;
980    }
981
982    // set spans from start to end to decrement by one
983    // note this walks other backwards
984    // FIMXE: there's probably an edge case that can be constructed where
985    // two span in one segment are separated by float epsilon on one span but
986    // not the other, if one segment is very small. For this
987    // case the counts asserted below may or may not be enough to separate the
988    // spans. Even if the counts work out, what if the spanw aren't correctly
989    // sorted? It feels better in such a case to match the span's other span
990    // pointer since both coincident segments must contain the same spans.
991    void addTCancel(double startT, double endT, Segment& other,
992            double oStartT, double oEndT) {
993        SkASSERT(endT - startT >= FLT_EPSILON);
994        SkASSERT(oEndT - oStartT >= FLT_EPSILON);
995        int index = 0;
996        while (startT - fTs[index].fT >= FLT_EPSILON) {
997            ++index;
998        }
999        int oIndex = other.fTs.count();
1000        while (other.fTs[--oIndex].fT - oEndT > -FLT_EPSILON)
1001            ;
1002        Span* test = &fTs[index];
1003        Span* oTest = &other.fTs[oIndex];
1004        SkTDArray<double> outsideTs;
1005        SkTDArray<double> oOutsideTs;
1006        do {
1007            bool decrement = test->fWindValue && oTest->fWindValue;
1008            bool track = test->fWindValue || oTest->fWindValue;
1009            double testT = test->fT;
1010            double oTestT = oTest->fT;
1011            Span* span = test;
1012            do {
1013                if (decrement) {
1014                    decrementSpan(span);
1015                } else if (track && span->fT < 1 && oTestT < 1) {
1016                    TrackOutside(outsideTs, span->fT, oTestT);
1017                }
1018                span = &fTs[++index];
1019            } while (span->fT - testT < FLT_EPSILON);
1020            Span* oSpan = oTest;
1021            do {
1022                if (decrement) {
1023                    other.decrementSpan(oSpan);
1024                } else if (track && oSpan->fT < 1 && testT < 1) {
1025                    TrackOutside(oOutsideTs, oSpan->fT, testT);
1026                }
1027                if (!oIndex) {
1028                    break;
1029                }
1030                oSpan = &other.fTs[--oIndex];
1031            } while (oTestT - oSpan->fT < FLT_EPSILON);
1032            test = span;
1033            oTest = oSpan;
1034        } while (test->fT < endT - FLT_EPSILON);
1035        SkASSERT(!oIndex || oTest->fT <= oStartT - FLT_EPSILON);
1036        // FIXME: determine if canceled edges need outside ts added
1037        if (!done() && outsideTs.count()) {
1038            addCancelOutsides(outsideTs, other, oEndT);
1039        }
1040        if (!other.done() && oOutsideTs.count()) {
1041            other.addCancelOutsides(oOutsideTs, *this, endT);
1042        }
1043    }
1044
1045    // set spans from start to end to increment the greater by one and decrement
1046    // the lesser
1047    void addTCoincident(double startT, double endT, Segment& other,
1048            double oStartT, double oEndT) {
1049        SkASSERT(endT - startT >= FLT_EPSILON);
1050        SkASSERT(oEndT - oStartT >= FLT_EPSILON);
1051        int index = 0;
1052        while (startT - fTs[index].fT >= FLT_EPSILON) {
1053            ++index;
1054        }
1055        int oIndex = 0;
1056        while (oStartT - other.fTs[oIndex].fT >= FLT_EPSILON) {
1057            ++oIndex;
1058        }
1059        Span* test = &fTs[index];
1060        Span* oTest = &other.fTs[oIndex];
1061        SkTDArray<double> outsideTs;
1062        SkTDArray<double> xOutsideTs;
1063        SkTDArray<double> oOutsideTs;
1064        SkTDArray<double> oxOutsideTs;
1065        do {
1066            bool transfer = test->fWindValue && oTest->fWindValue;
1067            bool decrementOther = test->fWindValue >= oTest->fWindValue;
1068            Span* end = test;
1069            double startT = end->fT;
1070            int startIndex = index;
1071            double oStartT = oTest->fT;
1072            int oStartIndex = oIndex;
1073            do {
1074                if (transfer) {
1075                    if (decrementOther) {
1076                        SkASSERT(abs(end->fWindValue) <= gDebugMaxWindValue);
1077                        ++(end->fWindValue);
1078                    } else if (decrementSpan(end)) {
1079                        TrackOutside(outsideTs, end->fT, oStartT);
1080                    }
1081                } else if (oTest->fWindValue) {
1082                    SkASSERT(!decrementOther);
1083                    if (startIndex > 0 && fTs[startIndex - 1].fWindValue) {
1084                        TrackOutside(xOutsideTs, end->fT, oStartT);
1085                    }
1086                }
1087                end = &fTs[++index];
1088            } while (end->fT - test->fT < FLT_EPSILON);
1089            Span* oEnd = oTest;
1090            do {
1091                if (transfer) {
1092                    if (!decrementOther) {
1093                        SkASSERT(abs(oEnd->fWindValue) <= gDebugMaxWindValue);
1094                        ++(oEnd->fWindValue);
1095                    } else if (other.decrementSpan(oEnd)) {
1096                        TrackOutside(oOutsideTs, oEnd->fT, startT);
1097                    }
1098                } else if (test->fWindValue) {
1099                    SkASSERT(!decrementOther);
1100                    if (oStartIndex > 0 && other.fTs[oStartIndex - 1].fWindValue) {
1101                        SkASSERT(0); // track for later?
1102                    }
1103                }
1104                oEnd = &other.fTs[++oIndex];
1105            } while (oEnd->fT - oTest->fT < FLT_EPSILON);
1106            test = end;
1107            oTest = oEnd;
1108        } while (test->fT < endT - FLT_EPSILON);
1109        SkASSERT(oTest->fT < oEndT + FLT_EPSILON);
1110        SkASSERT(oTest->fT > oEndT - FLT_EPSILON);
1111        if (!done()) {
1112            if (outsideTs.count()) {
1113                addCoinOutsides(outsideTs, other, oEndT);
1114            }
1115            if (xOutsideTs.count()) {
1116                addCoinOutsides(xOutsideTs, other, oEndT);
1117            }
1118        }
1119        if (!other.done() && oOutsideTs.count()) {
1120            other.addCoinOutsides(oOutsideTs, *this, endT);
1121        }
1122    }
1123
1124    // FIXME: this doesn't prevent the same span from being added twice
1125    // fix in caller, assert here?
1126    void addTPair(double t, Segment& other, double otherT) {
1127        int tCount = fTs.count();
1128        for (int tIndex = 0; tIndex < tCount; ++tIndex) {
1129            const Span& span = fTs[tIndex];
1130            if (span.fT > t) {
1131                break;
1132            }
1133            if (span.fT == t && span.fOther == &other && span.fOtherT == otherT) {
1134#if DEBUG_ADD_T_PAIR
1135                SkDebugf("%s addTPair duplicate this=%d %1.9g other=%d %1.9g\n",
1136                        __FUNCTION__, fID, t, other.fID, otherT);
1137#endif
1138                return;
1139            }
1140        }
1141#if DEBUG_ADD_T_PAIR
1142        SkDebugf("%s addTPair this=%d %1.9g other=%d %1.9g\n",
1143                __FUNCTION__, fID, t, other.fID, otherT);
1144#endif
1145        int insertedAt = addT(t, &other);
1146        int otherInsertedAt = other.addT(otherT, this);
1147        addOtherT(insertedAt, otherT, otherInsertedAt);
1148        other.addOtherT(otherInsertedAt, t, insertedAt);
1149        matchWindingValue(insertedAt, t);
1150        other.matchWindingValue(otherInsertedAt, otherT);
1151    }
1152
1153    void addTwoAngles(int start, int end, SkTDArray<Angle>& angles) const {
1154        // add edge leading into junction
1155        if (fTs[SkMin32(end, start)].fWindValue > 0) {
1156            addAngle(angles, end, start);
1157        }
1158        // add edge leading away from junction
1159        int step = SkSign32(end - start);
1160        int tIndex = nextSpan(end, step);
1161        if (tIndex >= 0 && fTs[SkMin32(end, tIndex)].fWindValue > 0) {
1162            addAngle(angles, end, tIndex);
1163        }
1164    }
1165
1166    const Bounds& bounds() const {
1167        return fBounds;
1168    }
1169
1170    void buildAngles(int index, SkTDArray<Angle>& angles) const {
1171        double referenceT = fTs[index].fT;
1172        int lesser = index;
1173        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1174            buildAnglesInner(lesser, angles);
1175        }
1176        do {
1177            buildAnglesInner(index, angles);
1178        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1179    }
1180
1181    void buildAnglesInner(int index, SkTDArray<Angle>& angles) const {
1182        Span* span = &fTs[index];
1183        Segment* other = span->fOther;
1184    // if there is only one live crossing, and no coincidence, continue
1185    // in the same direction
1186    // if there is coincidence, the only choice may be to reverse direction
1187        // find edge on either side of intersection
1188        int oIndex = span->fOtherIndex;
1189        // if done == -1, prior span has already been processed
1190        int step = 1;
1191        int next = other->nextSpan(oIndex, step);
1192        if (next < 0) {
1193            step = -step;
1194            next = other->nextSpan(oIndex, step);
1195        }
1196        // add candidate into and away from junction
1197        other->addTwoAngles(next, oIndex, angles);
1198    }
1199
1200    bool cancels(const Segment& other) const {
1201        SkASSERT(fVerb == SkPath::kLine_Verb);
1202        SkASSERT(other.fVerb == SkPath::kLine_Verb);
1203        SkPoint dxy = fPts[0] - fPts[1];
1204        SkPoint odxy = other.fPts[0] - other.fPts[1];
1205        return dxy.fX * odxy.fX < 0 || dxy.fY * odxy.fY < 0;
1206    }
1207
1208    // figure out if the segment's ascending T goes clockwise or not
1209    // not enough context to write this as shown
1210    // instead, add all segments meeting at the top
1211    // sort them using buildAngleList
1212    // find the first in the sort
1213    // see if ascendingT goes to top
1214    bool clockwise(int /* tIndex */) const {
1215        SkASSERT(0); // incomplete
1216        return false;
1217    }
1218
1219    int computeSum(int startIndex, int endIndex) {
1220        SkTDArray<Angle> angles;
1221        addTwoAngles(startIndex, endIndex, angles);
1222        buildAngles(endIndex, angles);
1223        SkTDArray<Angle*> sorted;
1224        sortAngles(angles, sorted);
1225        int angleCount = angles.count();
1226        const Angle* angle;
1227        const Segment* base;
1228        int winding;
1229        int firstIndex = 0;
1230        do {
1231            angle = sorted[firstIndex];
1232            base = angle->segment();
1233            winding = base->windSum(angle);
1234            if (winding != SK_MinS32) {
1235                break;
1236            }
1237            if (++firstIndex == angleCount) {
1238                return SK_MinS32;
1239            }
1240        } while (true);
1241        // turn winding into contourWinding
1242        int spanWinding = base->spanSign(angle->start(), angle->end());
1243        if (spanWinding * winding < 0) {
1244            winding += spanWinding;
1245        }
1246    #if DEBUG_SORT
1247        base->debugShowSort(sorted, firstIndex, winding);
1248    #endif
1249        int nextIndex = firstIndex + 1;
1250        int lastIndex = firstIndex != 0 ? firstIndex : angleCount;
1251        winding -= base->windBump(angle);
1252        do {
1253            if (nextIndex == angleCount) {
1254                nextIndex = 0;
1255            }
1256            angle = sorted[nextIndex];
1257            Segment* segment = angle->segment();
1258            int maxWinding = winding;
1259            winding -= segment->windBump(angle);
1260            if (segment->windSum(angle) == SK_MinS32) {
1261                if (abs(maxWinding) < abs(winding) || maxWinding * winding < 0) {
1262                    maxWinding = winding;
1263                }
1264                segment->markAndChaseWinding(angle, maxWinding);
1265            }
1266        } while (++nextIndex != lastIndex);
1267        return windSum(SkMin32(startIndex, endIndex));
1268    }
1269
1270    int crossedSpan(const SkPoint& basePt, SkScalar& bestY, double& hitT) const {
1271        int bestT = -1;
1272        SkScalar top = bounds().fTop;
1273        SkScalar bottom = bounds().fBottom;
1274        int end = 0;
1275        do {
1276            int start = end;
1277            end = nextSpan(start, 1);
1278            if (fTs[start].fWindValue == 0) {
1279                continue;
1280            }
1281            SkPoint edge[4];
1282            // OPTIMIZE: wrap this so that if start==0 end==fTCount-1 we can
1283            // work with the original data directly
1284            (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
1285            // intersect ray starting at basePt with edge
1286            Intersections intersections;
1287            int pts = (*VSegmentIntersect[fVerb])(edge, top, bottom, basePt.fX,
1288                    false, intersections);
1289            if (pts == 0) {
1290                continue;
1291            }
1292            if (pts > 1 && fVerb == SkPath::kLine_Verb) {
1293            // if the intersection is edge on, wait for another one
1294                continue;
1295            }
1296            SkASSERT(pts == 1); // FIXME: more code required to disambiguate
1297            SkPoint pt;
1298            double foundT = intersections.fT[0][0];
1299            (*SegmentXYAtT[fVerb])(fPts, foundT, &pt);
1300            if (bestY < pt.fY) {
1301                bestY = pt.fY;
1302                bestT = foundT < 1 ? start : end;
1303                hitT = fTs[start].fT + (fTs[end].fT - fTs[start].fT) * foundT;
1304            }
1305        } while (fTs[end].fT != 1);
1306        return bestT;
1307    }
1308
1309    bool crossedSpanHalves(const SkPoint& basePt, bool leftHalf, bool rightHalf) {
1310        // if a segment is connected to this one, consider it crossing
1311        int tIndex;
1312        if (fPts[0].fX == basePt.fX) {
1313            tIndex = 0;
1314            do {
1315                const Span& sSpan = fTs[tIndex];
1316                const Segment* sOther = sSpan.fOther;
1317                if (!sOther->fTs[sSpan.fOtherIndex].fWindValue) {
1318                    continue;
1319                }
1320                if (leftHalf ? sOther->fBounds.fLeft < basePt.fX
1321                        : sOther->fBounds.fRight > basePt.fX) {
1322                    return true;
1323                }
1324            } while (fTs[++tIndex].fT == 0);
1325        }
1326        if (fPts[fVerb].fX == basePt.fX) {
1327            tIndex = fTs.count() - 1;
1328            do {
1329                const Span& eSpan = fTs[tIndex];
1330                const Segment* eOther = eSpan.fOther;
1331                if (!eOther->fTs[eSpan.fOtherIndex].fWindValue) {
1332                    continue;
1333                }
1334                if (leftHalf ? eOther->fBounds.fLeft < basePt.fX
1335                        : eOther->fBounds.fRight > basePt.fX) {
1336                    return true;
1337                }
1338            } while (fTs[--tIndex].fT == 1);
1339        }
1340        return false;
1341    }
1342
1343    bool decrementSpan(Span* span) {
1344        SkASSERT(span->fWindValue > 0);
1345        if (--(span->fWindValue) == 0) {
1346            span->fDone = true;
1347            ++fDoneSpans;
1348            return true;
1349        }
1350        return false;
1351    }
1352
1353    bool done() const {
1354        SkASSERT(fDoneSpans <= fTs.count());
1355        return fDoneSpans == fTs.count();
1356    }
1357
1358    bool done(const Angle& angle) const {
1359        int start = angle.start();
1360        int end = angle.end();
1361        const Span& mSpan = fTs[SkMin32(start, end)];
1362        return mSpan.fDone;
1363    }
1364
1365    // so the span needs to contain the pairing info found here
1366    // this should include the winding computed for the edge, and
1367    //  what edge it connects to, and whether it is discarded
1368    //  (maybe discarded == abs(winding) > 1) ?
1369    // only need derivatives for duration of sorting, add a new struct
1370    // for pairings, remove extra spans that have zero length and
1371    //  reference an unused other
1372    // for coincident, the last span on the other may be marked done
1373    //  (always?)
1374
1375    // if loop is exhausted, contour may be closed.
1376    // FIXME: pass in close point so we can check for closure
1377
1378    // given a segment, and a sense of where 'inside' is, return the next
1379    // segment. If this segment has an intersection, or ends in multiple
1380    // segments, find the mate that continues the outside.
1381    // note that if there are multiples, but no coincidence, we can limit
1382    // choices to connections in the correct direction
1383
1384    // mark found segments as done
1385
1386    // start is the index of the beginning T of this edge
1387    // it is guaranteed to have an end which describes a non-zero length (?)
1388    // winding -1 means ccw, 1 means cw
1389    // firstFind allows coincident edges to be treated differently
1390    Segment* findNext(SkTDArray<Span*>& chase, bool firstFind, bool active,
1391            const int startIndex, const int endIndex, int& nextStart,
1392            int& nextEnd, int& winding, int& spanWinding) {
1393        int outerWinding = winding;
1394        int innerWinding = winding + spanWinding;
1395    #if DEBUG_WINDING
1396        SkDebugf("%s winding=%d spanWinding=%d outerWinding=%d innerWinding=%d\n",
1397                __FUNCTION__, winding, spanWinding, outerWinding, innerWinding);
1398    #endif
1399        if (abs(outerWinding) < abs(innerWinding)
1400                || outerWinding * innerWinding < 0) {
1401            outerWinding = innerWinding;
1402        }
1403        SkASSERT(startIndex != endIndex);
1404        int count = fTs.count();
1405        SkASSERT(startIndex < endIndex ? startIndex < count - 1
1406                : startIndex > 0);
1407        int step = SkSign32(endIndex - startIndex);
1408        int end = nextSpan(startIndex, step);
1409        SkASSERT(end >= 0);
1410        Span* endSpan = &fTs[end];
1411        Segment* other;
1412        if (isSimple(end)) {
1413        // mark the smaller of startIndex, endIndex done, and all adjacent
1414        // spans with the same T value (but not 'other' spans)
1415    #if DEBUG_WINDING
1416            SkDebugf("%s simple\n", __FUNCTION__);
1417    #endif
1418            markDone(SkMin32(startIndex, endIndex), outerWinding);
1419            other = endSpan->fOther;
1420            nextStart = endSpan->fOtherIndex;
1421            double startT = other->fTs[nextStart].fT;
1422            nextEnd = nextStart;
1423            do {
1424                nextEnd += step;
1425            } while (fabs(startT - other->fTs[nextEnd].fT) < FLT_EPSILON);
1426            SkASSERT(step < 0 ? nextEnd >= 0 : nextEnd < other->fTs.count());
1427            return other;
1428        }
1429        // more than one viable candidate -- measure angles to find best
1430        SkTDArray<Angle> angles;
1431        SkASSERT(startIndex - endIndex != 0);
1432        SkASSERT((startIndex - endIndex < 0) ^ (step < 0));
1433        addTwoAngles(startIndex, end, angles);
1434        buildAngles(end, angles);
1435        SkTDArray<Angle*> sorted;
1436        sortAngles(angles, sorted);
1437        int angleCount = angles.count();
1438        int firstIndex = findStartingEdge(sorted, startIndex, end);
1439        SkASSERT(firstIndex >= 0);
1440    #if DEBUG_SORT
1441        debugShowSort(sorted, firstIndex, winding);
1442    #endif
1443        SkASSERT(sorted[firstIndex]->segment() == this);
1444    #if DEBUG_WINDING
1445        SkDebugf("%s sign=%d\n", __FUNCTION__, sorted[firstIndex]->sign());
1446    #endif
1447        int sumWinding = winding - windBump(sorted[firstIndex]);
1448        int nextIndex = firstIndex + 1;
1449        int lastIndex = firstIndex != 0 ? firstIndex : angleCount;
1450        const Angle* foundAngle = NULL;
1451        bool foundDone = false;
1452        // iterate through the angle, and compute everyone's winding
1453        int toggleWinding = SK_MinS32;
1454        bool flipFound = false;
1455        int flipped = 1;
1456        Segment* nextSegment;
1457        do {
1458            if (nextIndex == angleCount) {
1459                nextIndex = 0;
1460            }
1461            const Angle* nextAngle = sorted[nextIndex];
1462            int maxWinding = sumWinding;
1463            nextSegment = nextAngle->segment();
1464            sumWinding -= nextSegment->windBump(nextAngle);
1465            SkASSERT(abs(sumWinding) <= gDebugMaxWindSum);
1466    #if DEBUG_WINDING
1467            SkDebugf("%s maxWinding=%d sumWinding=%d sign=%d\n", __FUNCTION__,
1468                    maxWinding, sumWinding, nextAngle->sign());
1469    #endif
1470            if (maxWinding * sumWinding < 0) {
1471                flipFound ^= true;
1472    #if DEBUG_WINDING
1473                SkDebugf("%s flipFound=%d maxWinding=%d sumWinding=%d\n",
1474                        __FUNCTION__, flipFound, maxWinding, sumWinding);
1475    #endif
1476            }
1477            if (!sumWinding) {
1478                if (!active) {
1479                    markDone(SkMin32(startIndex, endIndex), outerWinding);
1480                    nextSegment->markWinding(SkMin32(nextAngle->start(),
1481                                nextAngle->end()), maxWinding);
1482    #if DEBUG_WINDING
1483                    SkDebugf("%s inactive\n", __FUNCTION__);
1484    #endif
1485                    return NULL;
1486                }
1487                if (!foundAngle || foundDone) {
1488                    foundAngle = nextAngle;
1489                    foundDone = nextSegment->done(*nextAngle);
1490                    if (flipFound || (maxWinding * outerWinding < 0)) {
1491                        flipped = -flipped;
1492            #if DEBUG_WINDING
1493                        SkDebugf("%s flipped=%d flipFound=%d maxWinding=%d"
1494                                " outerWinding=%d\n", __FUNCTION__, flipped,
1495                                flipFound, maxWinding, outerWinding);
1496            #endif
1497                    }
1498                }
1499                continue;
1500            }
1501            if (!maxWinding && !foundAngle) {
1502        #if DEBUG_WINDING
1503                if (flipped > 0) {
1504                    SkDebugf("%s sumWinding=%d * outerWinding=%d < 0 (%s)\n",
1505                            __FUNCTION__, sumWinding, outerWinding,
1506                            sumWinding * outerWinding < 0 ? "true" : "false");
1507                }
1508        #endif
1509                if (sumWinding * outerWinding < 0 && flipped > 0) {
1510        #if DEBUG_WINDING
1511                    SkDebugf("%s toggleWinding=%d\n", __FUNCTION__, sumWinding);
1512        #endif
1513                    toggleWinding = sumWinding;
1514                } else if (outerWinding != sumWinding) {
1515        #if DEBUG_WINDING
1516                    SkDebugf("%s outerWinding=%d != sumWinding=%d winding=%d\n",
1517                            __FUNCTION__, outerWinding, sumWinding, winding);
1518        #endif
1519                    winding = sumWinding;
1520                }
1521                foundAngle = nextAngle;
1522                if (flipFound) {
1523                    flipped = -flipped;
1524        #if DEBUG_WINDING
1525                    SkDebugf("%s flipped flipFound=%d\n", __FUNCTION__, flipFound);
1526        #endif
1527                }
1528            }
1529            if (nextSegment->done()) {
1530                continue;
1531            }
1532            // if the winding is non-zero, nextAngle does not connect to
1533            // current chain. If we haven't done so already, mark the angle
1534            // as done, record the winding value, and mark connected unambiguous
1535            // segments as well.
1536            if (nextSegment->windSum(nextAngle) == SK_MinS32) {
1537                if (abs(maxWinding) < abs(sumWinding)
1538                        || maxWinding * sumWinding < 0) {
1539                    maxWinding = sumWinding;
1540                }
1541                Span* last;
1542                if (foundAngle) {
1543                    last = nextSegment->markAndChaseWinding(nextAngle, maxWinding);
1544                } else {
1545                    last = nextSegment->markAndChaseDone(nextAngle, maxWinding);
1546                }
1547                if (last) {
1548                    *chase.append() = last;
1549                }
1550            }
1551        } while (++nextIndex != lastIndex);
1552        SkASSERT(sorted[firstIndex]->segment() == this);
1553        markDone(SkMin32(startIndex, endIndex), outerWinding);
1554        if (!foundAngle) {
1555            return NULL;
1556        }
1557        nextStart = foundAngle->start();
1558        nextEnd = foundAngle->end();
1559        nextSegment = foundAngle->segment();
1560        spanWinding = SkSign32(spanWinding) * flipped * nextSegment->windValue(
1561                SkMin32(nextStart, nextEnd));
1562        if (toggleWinding != SK_MinS32) {
1563            winding = toggleWinding;
1564            spanWinding = -spanWinding;
1565        }
1566    #if DEBUG_WINDING
1567        SkDebugf("%s spanWinding=%d\n", __FUNCTION__, spanWinding);
1568    #endif
1569        return nextSegment;
1570    }
1571
1572    int findStartingEdge(SkTDArray<Angle*>& sorted, int start, int end) {
1573        int angleCount = sorted.count();
1574        int firstIndex = -1;
1575        for (int angleIndex = 0; angleIndex < angleCount; ++angleIndex) {
1576            const Angle* angle = sorted[angleIndex];
1577            if (angle->segment() == this && angle->start() == end &&
1578                    angle->end() == start) {
1579                firstIndex = angleIndex;
1580                break;
1581            }
1582        }
1583        return firstIndex;
1584    }
1585
1586    // FIXME: this is tricky code; needs its own unit test
1587    void findTooCloseToCall(int /* winding */ ) { // FIXME: winding should be considered
1588        int count = fTs.count();
1589        if (count < 3) { // require t=0, x, 1 at minimum
1590            return;
1591        }
1592        int matchIndex = 0;
1593        int moCount;
1594        Span* match;
1595        Segment* mOther;
1596        do {
1597            match = &fTs[matchIndex];
1598            mOther = match->fOther;
1599            moCount = mOther->fTs.count();
1600            if (moCount >= 3) {
1601                break;
1602            }
1603            if (++matchIndex >= count) {
1604                return;
1605            }
1606        } while (true); // require t=0, x, 1 at minimum
1607        // OPTIMIZATION: defer matchPt until qualifying toCount is found?
1608        const SkPoint* matchPt = &xyAtT(match);
1609        // look for a pair of nearby T values that map to the same (x,y) value
1610        // if found, see if the pair of other segments share a common point. If
1611        // so, the span from here to there is coincident.
1612        for (int index = matchIndex + 1; index < count; ++index) {
1613            Span* test = &fTs[index];
1614            if (test->fDone) {
1615                continue;
1616            }
1617            Segment* tOther = test->fOther;
1618            int toCount = tOther->fTs.count();
1619            if (toCount < 3) { // require t=0, x, 1 at minimum
1620                continue;
1621            }
1622            const SkPoint* testPt = &xyAtT(test);
1623            if (*matchPt != *testPt) {
1624                matchIndex = index;
1625                moCount = toCount;
1626                match = test;
1627                mOther = tOther;
1628                matchPt = testPt;
1629                continue;
1630            }
1631            int moStart = -1;
1632            int moEnd = -1;
1633            double moStartT, moEndT;
1634            for (int moIndex = 0; moIndex < moCount; ++moIndex) {
1635                Span& moSpan = mOther->fTs[moIndex];
1636                if (moSpan.fDone) {
1637                    continue;
1638                }
1639                if (moSpan.fOther == this) {
1640                    if (moSpan.fOtherT == match->fT) {
1641                        moStart = moIndex;
1642                        moStartT = moSpan.fT;
1643                    }
1644                    continue;
1645                }
1646                if (moSpan.fOther == tOther) {
1647                    SkASSERT(moEnd == -1);
1648                    moEnd = moIndex;
1649                    moEndT = moSpan.fT;
1650                }
1651            }
1652            if (moStart < 0 || moEnd < 0) {
1653                continue;
1654            }
1655            // FIXME: if moStartT, moEndT are initialized to NaN, can skip this test
1656            if (moStartT == moEndT) {
1657                continue;
1658            }
1659            int toStart = -1;
1660            int toEnd = -1;
1661            double toStartT, toEndT;
1662            for (int toIndex = 0; toIndex < toCount; ++toIndex) {
1663                Span& toSpan = tOther->fTs[toIndex];
1664                if (toSpan.fOther == this) {
1665                    if (toSpan.fOtherT == test->fT) {
1666                        toStart = toIndex;
1667                        toStartT = toSpan.fT;
1668                    }
1669                    continue;
1670                }
1671                if (toSpan.fOther == mOther && toSpan.fOtherT == moEndT) {
1672                    SkASSERT(toEnd == -1);
1673                    toEnd = toIndex;
1674                    toEndT = toSpan.fT;
1675                }
1676            }
1677            // FIXME: if toStartT, toEndT are initialized to NaN, can skip this test
1678            if (toStart <= 0 || toEnd <= 0) {
1679                continue;
1680            }
1681            if (toStartT == toEndT) {
1682                continue;
1683            }
1684            // test to see if the segment between there and here is linear
1685            if (!mOther->isLinear(moStart, moEnd)
1686                    || !tOther->isLinear(toStart, toEnd)) {
1687                continue;
1688            }
1689            // FIXME: defer implementation until the rest works
1690            // this may share code with regular coincident detection
1691            SkASSERT(0);
1692        #if 0
1693            if (flipped) {
1694                mOther->addTCancel(moStart, moEnd, tOther, tStart, tEnd);
1695            } else {
1696                mOther->addTCoincident(moStart, moEnd, tOther, tStart, tEnd);
1697            }
1698        #endif
1699        }
1700    }
1701
1702    // OPTIMIZATION : for a pair of lines, can we compute points at T (cached)
1703    // and use more concise logic like the old edge walker code?
1704    // FIXME: this needs to deal with coincident edges
1705    Segment* findTop(int& tIndex, int& endIndex) {
1706        // iterate through T intersections and return topmost
1707        // topmost tangent from y-min to first pt is closer to horizontal
1708        SkASSERT(!done());
1709        int firstT;
1710        int lastT;
1711        SkPoint topPt;
1712        topPt.fY = SK_ScalarMax;
1713        int count = fTs.count();
1714        // see if either end is not done since we want smaller Y of the pair
1715        bool lastDone = true;
1716        for (int index = 0; index < count; ++index) {
1717            const Span& span = fTs[index];
1718            if (!span.fDone || !lastDone) {
1719                const SkPoint& intercept = xyAtT(&span);
1720                if (topPt.fY > intercept.fY || (topPt.fY == intercept.fY
1721                        && topPt.fX > intercept.fX)) {
1722                    topPt = intercept;
1723                    firstT = lastT = index;
1724                } else if (topPt == intercept) {
1725                    lastT = index;
1726                }
1727            }
1728            lastDone = span.fDone;
1729        }
1730        // sort the edges to find the leftmost
1731        int step = 1;
1732        int end = nextSpan(firstT, step);
1733        if (end == -1) {
1734            step = -1;
1735            end = nextSpan(firstT, step);
1736            SkASSERT(end != -1);
1737        }
1738        // if the topmost T is not on end, or is three-way or more, find left
1739        // look for left-ness from tLeft to firstT (matching y of other)
1740        SkTDArray<Angle> angles;
1741        SkASSERT(firstT - end != 0);
1742        addTwoAngles(end, firstT, angles);
1743        buildAngles(firstT, angles);
1744        SkTDArray<Angle*> sorted;
1745        sortAngles(angles, sorted);
1746        // skip edges that have already been processed
1747        firstT = -1;
1748        Segment* leftSegment;
1749        do {
1750            const Angle* angle = sorted[++firstT];
1751            leftSegment = angle->segment();
1752            tIndex = angle->end();
1753            endIndex = angle->start();
1754        } while (leftSegment->fTs[SkMin32(tIndex, endIndex)].fDone);
1755        return leftSegment;
1756    }
1757
1758    bool firstBump(const Angle* angle, int sumWinding) const {
1759        int winding = spanSign(angle->start(), angle->end());
1760        sumWinding -= winding;
1761        if (sumWinding == 0) {
1762            sumWinding = winding;
1763        }
1764        bool result = angle->sign() * sumWinding > 0;
1765        SkASSERT(result == angle->firstBump(sumWinding));
1766        return result;
1767    }
1768
1769    // FIXME: not crazy about this
1770    // when the intersections are performed, the other index is into an
1771    // incomplete array. as the array grows, the indices become incorrect
1772    // while the following fixes the indices up again, it isn't smart about
1773    // skipping segments whose indices are already correct
1774    // assuming we leave the code that wrote the index in the first place
1775    void fixOtherTIndex() {
1776        int iCount = fTs.count();
1777        for (int i = 0; i < iCount; ++i) {
1778            Span& iSpan = fTs[i];
1779            double oT = iSpan.fOtherT;
1780            Segment* other = iSpan.fOther;
1781            int oCount = other->fTs.count();
1782            for (int o = 0; o < oCount; ++o) {
1783                Span& oSpan = other->fTs[o];
1784                if (oT == oSpan.fT && this == oSpan.fOther) {
1785                    iSpan.fOtherIndex = o;
1786                    break;
1787                }
1788            }
1789        }
1790    }
1791
1792    // OPTIMIZATION: uses tail recursion. Unwise?
1793    Span* innerChaseDone(int index, int step, int winding) {
1794        int end = nextSpan(index, step);
1795        SkASSERT(end >= 0);
1796        if (multipleSpans(end)) {
1797            return &fTs[end];
1798        }
1799        const Span& endSpan = fTs[end];
1800        Segment* other = endSpan.fOther;
1801        index = endSpan.fOtherIndex;
1802        int otherEnd = other->nextSpan(index, step);
1803        Span* last = other->innerChaseDone(index, step, winding);
1804        other->markDone(SkMin32(index, otherEnd), winding);
1805        return last;
1806    }
1807
1808    Span* innerChaseWinding(int index, int step, int winding) {
1809        int end = nextSpan(index, step);
1810        SkASSERT(end >= 0);
1811        if (multipleSpans(end)) {
1812            return &fTs[end];
1813        }
1814        const Span& endSpan = fTs[end];
1815        Segment* other = endSpan.fOther;
1816        index = endSpan.fOtherIndex;
1817        int otherEnd = other->nextSpan(index, step);
1818        int min = SkMin32(index, otherEnd);
1819        if (other->fTs[min].fWindSum != SK_MinS32) {
1820            SkASSERT(other->fTs[min].fWindSum == winding);
1821            return NULL;
1822        }
1823        Span* last = other->innerChaseWinding(index, step, winding);
1824        other->markWinding(min, winding);
1825        return last;
1826    }
1827
1828    void init(const SkPoint pts[], SkPath::Verb verb) {
1829        fPts = pts;
1830        fVerb = verb;
1831        fDoneSpans = 0;
1832    }
1833
1834    bool intersected() const {
1835        return fTs.count() > 0;
1836    }
1837
1838    bool isConnected(int startIndex, int endIndex) const {
1839        return fTs[startIndex].fWindSum != SK_MinS32
1840                || fTs[endIndex].fWindSum != SK_MinS32;
1841    }
1842
1843    bool isLinear(int start, int end) const {
1844        if (fVerb == SkPath::kLine_Verb) {
1845            return true;
1846        }
1847        if (fVerb == SkPath::kQuad_Verb) {
1848            SkPoint qPart[3];
1849            QuadSubDivide(fPts, fTs[start].fT, fTs[end].fT, qPart);
1850            return QuadIsLinear(qPart);
1851        } else {
1852            SkASSERT(fVerb == SkPath::kCubic_Verb);
1853            SkPoint cPart[4];
1854            CubicSubDivide(fPts, fTs[start].fT, fTs[end].fT, cPart);
1855            return CubicIsLinear(cPart);
1856        }
1857    }
1858
1859    // OPTIMIZE: successive calls could start were the last leaves off
1860    // or calls could specialize to walk forwards or backwards
1861    bool isMissing(double startT) const {
1862        size_t tCount = fTs.count();
1863        for (size_t index = 0; index < tCount; ++index) {
1864            if (fabs(startT - fTs[index].fT) < FLT_EPSILON) {
1865                return false;
1866            }
1867        }
1868        return true;
1869    }
1870
1871    bool isSimple(int end) const {
1872        int count = fTs.count();
1873        if (count == 2) {
1874            return true;
1875        }
1876        double t = fTs[end].fT;
1877        if (t < FLT_EPSILON) {
1878            return fTs[1].fT >= FLT_EPSILON;
1879        }
1880        if (t > 1 - FLT_EPSILON) {
1881            return fTs[count - 2].fT <= 1 - FLT_EPSILON;
1882        }
1883        return false;
1884    }
1885
1886    bool isHorizontal() const {
1887        return fBounds.fTop == fBounds.fBottom;
1888    }
1889
1890    bool isVertical() const {
1891        return fBounds.fLeft == fBounds.fRight;
1892    }
1893
1894    SkScalar leftMost(int start, int end) const {
1895        return (*SegmentLeftMost[fVerb])(fPts, fTs[start].fT, fTs[end].fT);
1896    }
1897
1898    // this span is excluded by the winding rule -- chase the ends
1899    // as long as they are unambiguous to mark connections as done
1900    // and give them the same winding value
1901    Span* markAndChaseDone(const Angle* angle, int winding) {
1902        int index = angle->start();
1903        int endIndex = angle->end();
1904        int step = SkSign32(endIndex - index);
1905        Span* last = innerChaseDone(index, step, winding);
1906        markDone(SkMin32(index, endIndex), winding);
1907        return last;
1908    }
1909
1910    Span* markAndChaseWinding(const Angle* angle, int winding) {
1911        int index = angle->start();
1912        int endIndex = angle->end();
1913        int min = SkMin32(index, endIndex);
1914        int step = SkSign32(endIndex - index);
1915        Span* last = innerChaseWinding(index, step, winding);
1916        markWinding(min, winding);
1917        return last;
1918    }
1919
1920    // FIXME: this should also mark spans with equal (x,y)
1921    // This may be called when the segment is already marked done. While this
1922    // wastes time, it shouldn't do any more than spin through the T spans.
1923    // OPTIMIZATION: abort on first done found (assuming that this code is
1924    // always called to mark segments done).
1925    void markDone(int index, int winding) {
1926      //  SkASSERT(!done());
1927        double referenceT = fTs[index].fT;
1928        int lesser = index;
1929        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1930            Span& span = fTs[lesser];
1931            if (span.fDone) {
1932                continue;
1933            }
1934        #if DEBUG_MARK_DONE
1935            debugShowNewWinding(__FUNCTION__, span, winding);
1936        #endif
1937            span.fDone = true;
1938            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1939            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1940            span.fWindSum = winding;
1941            fDoneSpans++;
1942        }
1943        do {
1944            Span& span = fTs[index];
1945     //       SkASSERT(!span.fDone);
1946            if (span.fDone) {
1947                continue;
1948            }
1949        #if DEBUG_MARK_DONE
1950            debugShowNewWinding(__FUNCTION__, span, winding);
1951        #endif
1952            span.fDone = true;
1953            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1954            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1955            span.fWindSum = winding;
1956            fDoneSpans++;
1957        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1958    }
1959
1960    void markWinding(int index, int winding) {
1961    //    SkASSERT(!done());
1962        double referenceT = fTs[index].fT;
1963        int lesser = index;
1964        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1965            Span& span = fTs[lesser];
1966            if (span.fDone) {
1967                continue;
1968            }
1969      //      SkASSERT(span.fWindValue == 1 || winding == 0);
1970            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1971        #if DEBUG_MARK_DONE
1972            debugShowNewWinding(__FUNCTION__, span, winding);
1973        #endif
1974            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1975            span.fWindSum = winding;
1976        }
1977        do {
1978            Span& span = fTs[index];
1979     //       SkASSERT(!span.fDone || span.fCoincident);
1980            if (span.fDone) {
1981                continue;
1982            }
1983     //       SkASSERT(span.fWindValue == 1 || winding == 0);
1984            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1985        #if DEBUG_MARK_DONE
1986            debugShowNewWinding(__FUNCTION__, span, winding);
1987        #endif
1988            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1989            span.fWindSum = winding;
1990        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1991    }
1992
1993    void matchWindingValue(int tIndex, double t) {
1994        int nextDoorWind = SK_MaxS32;
1995        if (tIndex > 0) {
1996            const Span& below = fTs[tIndex - 1];
1997            if (t - below.fT < FLT_EPSILON) {
1998                nextDoorWind = below.fWindValue;
1999            }
2000        }
2001        if (nextDoorWind == SK_MaxS32 && tIndex + 1 < fTs.count()) {
2002            const Span& above = fTs[tIndex + 1];
2003            if (above.fT - t < FLT_EPSILON) {
2004                nextDoorWind = above.fWindValue;
2005            }
2006        }
2007        if (nextDoorWind != SK_MaxS32) {
2008            Span& newSpan = fTs[tIndex];
2009            newSpan.fWindValue = nextDoorWind;
2010            if (!nextDoorWind) {
2011                newSpan.fDone = true;
2012                ++fDoneSpans;
2013            }
2014        }
2015    }
2016
2017    // return span if when chasing, two or more radiating spans are not done
2018    // OPTIMIZATION: ? multiple spans is detected when there is only one valid
2019    // candidate and the remaining spans have windValue == 0 (canceled by
2020    // coincidence). The coincident edges could either be removed altogether,
2021    // or this code could be more complicated in detecting this case. Worth it?
2022    bool multipleSpans(int end) const {
2023        return end > 0 && end < fTs.count() - 1;
2024    }
2025
2026    // This has callers for two different situations: one establishes the end
2027    // of the current span, and one establishes the beginning of the next span
2028    // (thus the name). When this is looking for the end of the current span,
2029    // coincidence is found when the beginning Ts contain -step and the end
2030    // contains step. When it is looking for the beginning of the next, the
2031    // first Ts found can be ignored and the last Ts should contain -step.
2032    // OPTIMIZATION: probably should split into two functions
2033    int nextSpan(int from, int step) const {
2034        const Span& fromSpan = fTs[from];
2035        int count = fTs.count();
2036        int to = from;
2037        while (step > 0 ? ++to < count : --to >= 0) {
2038            const Span& span = fTs[to];
2039            if ((step > 0 ? span.fT - fromSpan.fT : fromSpan.fT - span.fT) < FLT_EPSILON) {
2040                continue;
2041            }
2042            return to;
2043        }
2044        return -1;
2045    }
2046
2047    const SkPoint* pts() const {
2048        return fPts;
2049    }
2050
2051    void reset() {
2052        init(NULL, (SkPath::Verb) -1);
2053        fBounds.set(SK_ScalarMax, SK_ScalarMax, SK_ScalarMax, SK_ScalarMax);
2054        fTs.reset();
2055    }
2056
2057    // OPTIMIZATION: mark as debugging only if used solely by tests
2058    const Span& span(int tIndex) const {
2059        return fTs[tIndex];
2060    }
2061
2062    int spanSign(int startIndex, int endIndex) const {
2063        return startIndex < endIndex ? -fTs[startIndex].fWindValue :
2064                fTs[endIndex].fWindValue;
2065    }
2066
2067    // OPTIMIZATION: mark as debugging only if used solely by tests
2068    double t(int tIndex) const {
2069        return fTs[tIndex].fT;
2070    }
2071
2072    static void TrackOutside(SkTDArray<double>& outsideTs, double end,
2073            double start) {
2074        int outCount = outsideTs.count();
2075        if (outCount == 0 || end - outsideTs[outCount - 2] >= FLT_EPSILON) {
2076            *outsideTs.append() = end;
2077            *outsideTs.append() = start;
2078        }
2079    }
2080
2081    void updatePts(const SkPoint pts[]) {
2082        fPts = pts;
2083    }
2084
2085    SkPath::Verb verb() const {
2086        return fVerb;
2087    }
2088
2089    int windBump(const Angle* angle) const {
2090        SkASSERT(angle->segment() == this);
2091        const Span& span = fTs[SkMin32(angle->start(), angle->end())];
2092        int result = angle->sign() * span.fWindValue;
2093#if DEBUG_WIND_BUMP
2094        SkDebugf("%s bump=%d\n", __FUNCTION__, result);
2095#endif
2096        return result;
2097    }
2098
2099    int windSum(int tIndex) const {
2100        return fTs[tIndex].fWindSum;
2101    }
2102
2103    int windSum(const Angle* angle) const {
2104        int start = angle->start();
2105        int end = angle->end();
2106        int index = SkMin32(start, end);
2107        return windSum(index);
2108    }
2109
2110    int windValue(int tIndex) const {
2111        return fTs[tIndex].fWindValue;
2112    }
2113
2114    int windValue(const Angle* angle) const {
2115        int start = angle->start();
2116        int end = angle->end();
2117        int index = SkMin32(start, end);
2118        return windValue(index);
2119    }
2120
2121    SkScalar xAtT(const Span* span) const {
2122        return xyAtT(span).fX;
2123    }
2124
2125    const SkPoint& xyAtT(int index) const {
2126        return xyAtT(&fTs[index]);
2127    }
2128
2129    const SkPoint& xyAtT(const Span* span) const {
2130        if (SkScalarIsNaN(span->fPt.fX)) {
2131            if (span->fT == 0) {
2132                span->fPt = fPts[0];
2133            } else if (span->fT == 1) {
2134                span->fPt = fPts[fVerb];
2135            } else {
2136                (*SegmentXYAtT[fVerb])(fPts, span->fT, &span->fPt);
2137            }
2138        }
2139        return span->fPt;
2140    }
2141
2142    SkScalar yAtT(int index) const {
2143        return yAtT(&fTs[index]);
2144    }
2145
2146    SkScalar yAtT(const Span* span) const {
2147        return xyAtT(span).fY;
2148    }
2149
2150#if DEBUG_DUMP
2151    void dump() const {
2152        const char className[] = "Segment";
2153        const int tab = 4;
2154        for (int i = 0; i < fTs.count(); ++i) {
2155            SkPoint out;
2156            (*SegmentXYAtT[fVerb])(fPts, t(i), &out);
2157            SkDebugf("%*s [%d] %s.fTs[%d]=%1.9g (%1.9g,%1.9g) other=%d"
2158                    " otherT=%1.9g windSum=%d\n",
2159                    tab + sizeof(className), className, fID,
2160                    kLVerbStr[fVerb], i, fTs[i].fT, out.fX, out.fY,
2161                    fTs[i].fOther->fID, fTs[i].fOtherT, fTs[i].fWindSum);
2162        }
2163        SkDebugf("%*s [%d] fBounds=(l:%1.9g, t:%1.9g r:%1.9g, b:%1.9g)",
2164                tab + sizeof(className), className, fID,
2165                fBounds.fLeft, fBounds.fTop, fBounds.fRight, fBounds.fBottom);
2166    }
2167#endif
2168
2169#if DEBUG_CONCIDENT
2170    // assert if pair has not already been added
2171     void debugAddTPair(double t, const Segment& other, double otherT) const {
2172        for (int i = 0; i < fTs.count(); ++i) {
2173            if (fTs[i].fT == t && fTs[i].fOther == &other && fTs[i].fOtherT == otherT) {
2174                return;
2175            }
2176        }
2177        SkASSERT(0);
2178     }
2179#endif
2180
2181#if DEBUG_DUMP
2182    int debugID() const {
2183        return fID;
2184    }
2185#endif
2186
2187#if DEBUG_CONCIDENT
2188    void debugShowTs() const {
2189        SkDebugf("%s %d", __FUNCTION__, fID);
2190        for (int i = 0; i < fTs.count(); ++i) {
2191            SkDebugf(" [o=%d t=%1.3g %1.9g,%1.9g w=%d]", fTs[i].fOther->fID,
2192                    fTs[i].fT, xAtT(&fTs[i]), yAtT(&fTs[i]), fTs[i].fWindValue);
2193        }
2194        SkDebugf("\n");
2195    }
2196#endif
2197
2198#if DEBUG_ACTIVE_SPANS
2199    void debugShowActiveSpans() const {
2200        if (done()) {
2201            return;
2202        }
2203        for (int i = 0; i < fTs.count(); ++i) {
2204            if (fTs[i].fDone) {
2205                continue;
2206            }
2207            SkDebugf("%s id=%d", __FUNCTION__, fID);
2208            SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
2209            for (int vIndex = 1; vIndex <= fVerb; ++vIndex) {
2210                SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
2211            }
2212            const Span* span = &fTs[i];
2213            SkDebugf(") t=%1.9g (%1.9g,%1.9g)", fTs[i].fT,
2214                     xAtT(span), yAtT(span));
2215            const Segment* other = fTs[i].fOther;
2216            SkDebugf(" other=%d otherT=%1.9g otherIndex=%d windSum=",
2217                    other->fID, fTs[i].fOtherT, fTs[i].fOtherIndex);
2218            if (fTs[i].fWindSum == SK_MinS32) {
2219                SkDebugf("?");
2220            } else {
2221                SkDebugf("%d", fTs[i].fWindSum);
2222            }
2223            SkDebugf(" windValue=%d\n", fTs[i].fWindValue);
2224        }
2225    }
2226#endif
2227
2228#if DEBUG_MARK_DONE
2229    void debugShowNewWinding(const char* fun, const Span& span, int winding) {
2230        const SkPoint& pt = xyAtT(&span);
2231        SkDebugf("%s id=%d", fun, fID);
2232        SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
2233        for (int vIndex = 1; vIndex <= fVerb; ++vIndex) {
2234            SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
2235        }
2236        SkDebugf(") t=%1.9g (%1.9g,%1.9g) newWindSum=%d windSum=",
2237                span.fT, pt.fX, pt.fY, winding);
2238        if (span.fWindSum == SK_MinS32) {
2239            SkDebugf("?");
2240        } else {
2241            SkDebugf("%d", span.fWindSum);
2242        }
2243        SkDebugf(" windValue=%d\n", span.fWindValue);
2244    }
2245#endif
2246
2247#if DEBUG_SORT
2248    void debugShowSort(const SkTDArray<Angle*>& angles, int first,
2249            const int contourWinding) const {
2250        SkASSERT(angles[first]->segment() == this);
2251        SkASSERT(angles.count() > 1);
2252        int lastSum = contourWinding;
2253        int windSum = lastSum - windBump(angles[first]);
2254        SkDebugf("%s contourWinding=%d bump=%d\n", __FUNCTION__,
2255                contourWinding, windBump(angles[first]));
2256        int index = first;
2257        bool firstTime = true;
2258        do {
2259            const Angle& angle = *angles[index];
2260            const Segment& segment = *angle.segment();
2261            int start = angle.start();
2262            int end = angle.end();
2263            const Span& sSpan = segment.fTs[start];
2264            const Span& eSpan = segment.fTs[end];
2265            const Span& mSpan = segment.fTs[SkMin32(start, end)];
2266            if (!firstTime) {
2267                lastSum = windSum;
2268                windSum -= segment.windBump(&angle);
2269            }
2270            SkDebugf("%s [%d] id=%d start=%d (%1.9g,%,1.9g) end=%d (%1.9g,%,1.9g)"
2271                     " sign=%d windValue=%d winding: %d->%d (max=%d) done=%d\n",
2272                     __FUNCTION__, index, segment.fID, start, segment.xAtT(&sSpan),
2273                     segment.yAtT(&sSpan), end, segment.xAtT(&eSpan),
2274                     segment.yAtT(&eSpan), angle.sign(), mSpan.fWindValue,
2275                     lastSum, windSum, abs(lastSum) > abs(windSum) ? lastSum :
2276                     windSum, mSpan.fDone);
2277            ++index;
2278            if (index == angles.count()) {
2279                index = 0;
2280            }
2281            if (firstTime) {
2282                firstTime = false;
2283            }
2284        } while (index != first);
2285    }
2286#endif
2287
2288#if DEBUG_WINDING
2289    bool debugVerifyWinding(int start, int end, int winding) const {
2290        const Span& span = fTs[SkMin32(start, end)];
2291        int spanWinding = span.fWindSum;
2292        if (spanWinding == SK_MinS32) {
2293            return true;
2294        }
2295        int spanSign = SkSign32(start - end);
2296        int signedVal = spanSign * span.fWindValue;
2297        if (signedVal < 0) {
2298            spanWinding -= signedVal;
2299        }
2300        return span.fWindSum == winding;
2301    }
2302#endif
2303
2304private:
2305    const SkPoint* fPts;
2306    SkPath::Verb fVerb;
2307    Bounds fBounds;
2308    SkTDArray<Span> fTs; // two or more (always includes t=0 t=1)
2309    int fDoneSpans; // used for quick check that segment is finished
2310#if DEBUG_DUMP
2311    int fID;
2312#endif
2313};
2314
2315class Contour;
2316
2317struct Coincidence {
2318    Contour* fContours[2];
2319    int fSegments[2];
2320    double fTs[2][2];
2321};
2322
2323class Contour {
2324public:
2325    Contour() {
2326        reset();
2327#if DEBUG_DUMP
2328        fID = ++gContourID;
2329#endif
2330    }
2331
2332    bool operator<(const Contour& rh) const {
2333        return fBounds.fTop == rh.fBounds.fTop
2334                ? fBounds.fLeft < rh.fBounds.fLeft
2335                : fBounds.fTop < rh.fBounds.fTop;
2336    }
2337
2338    void addCoincident(int index, Contour* other, int otherIndex,
2339            const Intersections& ts, bool swap) {
2340        Coincidence& coincidence = *fCoincidences.append();
2341        coincidence.fContours[0] = this;
2342        coincidence.fContours[1] = other;
2343        coincidence.fSegments[0] = index;
2344        coincidence.fSegments[1] = otherIndex;
2345        coincidence.fTs[swap][0] = ts.fT[0][0];
2346        coincidence.fTs[swap][1] = ts.fT[0][1];
2347        coincidence.fTs[!swap][0] = ts.fT[1][0];
2348        coincidence.fTs[!swap][1] = ts.fT[1][1];
2349    }
2350
2351    void addCross(const Contour* crosser) {
2352#ifdef DEBUG_CROSS
2353        for (int index = 0; index < fCrosses.count(); ++index) {
2354            SkASSERT(fCrosses[index] != crosser);
2355        }
2356#endif
2357        *fCrosses.append() = crosser;
2358    }
2359
2360    void addCubic(const SkPoint pts[4]) {
2361        fSegments.push_back().addCubic(pts);
2362        fContainsCurves = true;
2363    }
2364
2365    int addLine(const SkPoint pts[2]) {
2366        fSegments.push_back().addLine(pts);
2367        return fSegments.count();
2368    }
2369
2370    void addOtherT(int segIndex, int tIndex, double otherT, int otherIndex) {
2371        fSegments[segIndex].addOtherT(tIndex, otherT, otherIndex);
2372    }
2373
2374    int addQuad(const SkPoint pts[3]) {
2375        fSegments.push_back().addQuad(pts);
2376        fContainsCurves = true;
2377        return fSegments.count();
2378    }
2379
2380    int addT(int segIndex, double newT, Contour* other, int otherIndex) {
2381        containsIntercepts();
2382        return fSegments[segIndex].addT(newT, &other->fSegments[otherIndex]);
2383    }
2384
2385    const Bounds& bounds() const {
2386        return fBounds;
2387    }
2388
2389    void complete() {
2390        setBounds();
2391        fContainsIntercepts = false;
2392    }
2393
2394    void containsIntercepts() {
2395        fContainsIntercepts = true;
2396    }
2397
2398    const Segment* crossedSegment(const SkPoint& basePt, SkScalar& bestY,
2399            int &tIndex, double& hitT) {
2400        int segmentCount = fSegments.count();
2401        const Segment* bestSegment = NULL;
2402        for (int test = 0; test < segmentCount; ++test) {
2403            Segment* testSegment = &fSegments[test];
2404            const SkRect& bounds = testSegment->bounds();
2405            if (bounds.fBottom <= bestY) {
2406                continue;
2407            }
2408            if (bounds.fTop >= basePt.fY) {
2409                continue;
2410            }
2411            if (bounds.fLeft > basePt.fX) {
2412                continue;
2413            }
2414            if (bounds.fRight < basePt.fX) {
2415                continue;
2416            }
2417            if (bounds.fLeft == bounds.fRight) {
2418                continue;
2419            }
2420     #if 0
2421            bool leftHalf = bounds.fLeft == basePt.fX;
2422            bool rightHalf = bounds.fRight == basePt.fX;
2423            if ((leftHalf || rightHalf) && !testSegment->crossedSpanHalves(
2424                    basePt, leftHalf, rightHalf)) {
2425                continue;
2426            }
2427     #endif
2428            double testHitT;
2429            int testT = testSegment->crossedSpan(basePt, bestY, testHitT);
2430            if (testT >= 0) {
2431                bestSegment = testSegment;
2432                tIndex = testT;
2433                hitT = testHitT;
2434            }
2435        }
2436        return bestSegment;
2437    }
2438
2439    bool crosses(const Contour* crosser) const {
2440        for (int index = 0; index < fCrosses.count(); ++index) {
2441            if (fCrosses[index] == crosser) {
2442                return true;
2443            }
2444        }
2445        return false;
2446    }
2447
2448    void findTooCloseToCall(int winding) {
2449        int segmentCount = fSegments.count();
2450        for (int sIndex = 0; sIndex < segmentCount; ++sIndex) {
2451            fSegments[sIndex].findTooCloseToCall(winding);
2452        }
2453    }
2454
2455    void fixOtherTIndex() {
2456        int segmentCount = fSegments.count();
2457        for (int sIndex = 0; sIndex < segmentCount; ++sIndex) {
2458            fSegments[sIndex].fixOtherTIndex();
2459        }
2460    }
2461
2462    void reset() {
2463        fSegments.reset();
2464        fBounds.set(SK_ScalarMax, SK_ScalarMax, SK_ScalarMax, SK_ScalarMax);
2465        fContainsCurves = fContainsIntercepts = false;
2466    }
2467
2468    void resolveCoincidence(int winding) {
2469        int count = fCoincidences.count();
2470        for (int index = 0; index < count; ++index) {
2471            Coincidence& coincidence = fCoincidences[index];
2472            Contour* thisContour = coincidence.fContours[0];
2473            Contour* otherContour = coincidence.fContours[1];
2474            int thisIndex = coincidence.fSegments[0];
2475            int otherIndex = coincidence.fSegments[1];
2476            Segment& thisOne = thisContour->fSegments[thisIndex];
2477            Segment& other = otherContour->fSegments[otherIndex];
2478        #if DEBUG_CONCIDENT
2479            thisOne.debugShowTs();
2480            other.debugShowTs();
2481        #endif
2482            double startT = coincidence.fTs[0][0];
2483            double endT = coincidence.fTs[0][1];
2484            if (startT > endT) {
2485                SkTSwap<double>(startT, endT);
2486            }
2487            SkASSERT(endT - startT >= FLT_EPSILON);
2488            double oStartT = coincidence.fTs[1][0];
2489            double oEndT = coincidence.fTs[1][1];
2490            if (oStartT > oEndT) {
2491                SkTSwap<double>(oStartT, oEndT);
2492            }
2493            SkASSERT(oEndT - oStartT >= FLT_EPSILON);
2494            if (winding > 0 || thisOne.cancels(other)) {
2495                        // make sure startT and endT have t entries
2496                if (thisOne.isMissing(startT) || other.isMissing(oEndT)) {
2497                    thisOne.addTPair(startT, other, oEndT);
2498                }
2499                if (thisOne.isMissing(endT) || other.isMissing(oStartT)) {
2500                    other.addTPair(oStartT, thisOne, endT);
2501                }
2502                thisOne.addTCancel(startT, endT, other, oStartT, oEndT);
2503            } else {
2504                if (startT > 0 || oStartT > 0
2505                        || thisOne.isMissing(startT) || other.isMissing(oStartT)) {
2506                    thisOne.addTPair(startT, other, oStartT);
2507                }
2508                if (endT < 1 || oEndT < 1
2509                        || thisOne.isMissing(endT) || other.isMissing(oEndT)) {
2510                    other.addTPair(oEndT, thisOne, endT);
2511                }
2512                thisOne.addTCoincident(startT, endT, other, oStartT, oEndT);
2513            }
2514        #if DEBUG_CONCIDENT
2515            thisOne.debugShowTs();
2516            other.debugShowTs();
2517        #endif
2518        }
2519    }
2520
2521    const SkTArray<Segment>& segments() {
2522        return fSegments;
2523    }
2524
2525    // OPTIMIZATION: feel pretty uneasy about this. It seems like once again
2526    // we need to sort and walk edges in y, but that on the surface opens the
2527    // same can of worms as before. But then, this is a rough sort based on
2528    // segments' top, and not a true sort, so it could be ameniable to regular
2529    // sorting instead of linear searching. Still feel like I'm missing something
2530    Segment* topSegment(SkScalar& bestY) {
2531        int segmentCount = fSegments.count();
2532        SkASSERT(segmentCount > 0);
2533        int best = -1;
2534        Segment* bestSegment = NULL;
2535        while (++best < segmentCount) {
2536            Segment* testSegment = &fSegments[best];
2537            if (testSegment->done()) {
2538                continue;
2539            }
2540            bestSegment = testSegment;
2541            break;
2542        }
2543        if (!bestSegment) {
2544            return NULL;
2545        }
2546        SkScalar bestTop = bestSegment->activeTop();
2547        for (int test = best + 1; test < segmentCount; ++test) {
2548            Segment* testSegment = &fSegments[test];
2549            if (testSegment->done()) {
2550                continue;
2551            }
2552            if (testSegment->bounds().fTop > bestTop) {
2553                continue;
2554            }
2555            SkScalar testTop = testSegment->activeTop();
2556            if (bestTop > testTop) {
2557                bestTop = testTop;
2558                bestSegment = testSegment;
2559            }
2560        }
2561        bestY = bestTop;
2562        return bestSegment;
2563    }
2564
2565    int updateSegment(int index, const SkPoint* pts) {
2566        Segment& segment = fSegments[index];
2567        segment.updatePts(pts);
2568        return segment.verb() + 1;
2569    }
2570
2571#if DEBUG_TEST
2572    SkTArray<Segment>& debugSegments() {
2573        return fSegments;
2574    }
2575#endif
2576
2577#if DEBUG_DUMP
2578    void dump() {
2579        int i;
2580        const char className[] = "Contour";
2581        const int tab = 4;
2582        SkDebugf("%s %p (contour=%d)\n", className, this, fID);
2583        for (i = 0; i < fSegments.count(); ++i) {
2584            SkDebugf("%*s.fSegments[%d]:\n", tab + sizeof(className),
2585                    className, i);
2586            fSegments[i].dump();
2587        }
2588        SkDebugf("%*s.fBounds=(l:%1.9g, t:%1.9g r:%1.9g, b:%1.9g)\n",
2589                tab + sizeof(className), className,
2590                fBounds.fLeft, fBounds.fTop,
2591                fBounds.fRight, fBounds.fBottom);
2592        SkDebugf("%*s.fContainsIntercepts=%d\n", tab + sizeof(className),
2593                className, fContainsIntercepts);
2594        SkDebugf("%*s.fContainsCurves=%d\n", tab + sizeof(className),
2595                className, fContainsCurves);
2596    }
2597#endif
2598
2599#if DEBUG_ACTIVE_SPANS
2600    void debugShowActiveSpans() {
2601        for (int index = 0; index < fSegments.count(); ++index) {
2602            fSegments[index].debugShowActiveSpans();
2603        }
2604    }
2605#endif
2606
2607protected:
2608    void setBounds() {
2609        int count = fSegments.count();
2610        if (count == 0) {
2611            SkDebugf("%s empty contour\n", __FUNCTION__);
2612            SkASSERT(0);
2613            // FIXME: delete empty contour?
2614            return;
2615        }
2616        fBounds = fSegments.front().bounds();
2617        for (int index = 1; index < count; ++index) {
2618            fBounds.add(fSegments[index].bounds());
2619        }
2620    }
2621
2622private:
2623    SkTArray<Segment> fSegments;
2624    SkTDArray<Coincidence> fCoincidences;
2625    SkTDArray<const Contour*> fCrosses;
2626    Bounds fBounds;
2627    bool fContainsIntercepts;
2628    bool fContainsCurves;
2629#if DEBUG_DUMP
2630    int fID;
2631#endif
2632};
2633
2634class EdgeBuilder {
2635public:
2636
2637EdgeBuilder(const SkPath& path, SkTArray<Contour>& contours)
2638    : fPath(path)
2639    , fCurrentContour(NULL)
2640    , fContours(contours)
2641{
2642#if DEBUG_DUMP
2643    gContourID = 0;
2644    gSegmentID = 0;
2645#endif
2646    walk();
2647}
2648
2649protected:
2650
2651void complete() {
2652    if (fCurrentContour && fCurrentContour->segments().count()) {
2653        fCurrentContour->complete();
2654        fCurrentContour = NULL;
2655    }
2656}
2657
2658void walk() {
2659    // FIXME:remove once we can access path pts directly
2660    SkPath::RawIter iter(fPath); // FIXME: access path directly when allowed
2661    SkPoint pts[4];
2662    SkPath::Verb verb;
2663    do {
2664        verb = iter.next(pts);
2665        *fPathVerbs.append() = verb;
2666        if (verb == SkPath::kMove_Verb) {
2667            *fPathPts.append() = pts[0];
2668        } else if (verb >= SkPath::kLine_Verb && verb <= SkPath::kCubic_Verb) {
2669            fPathPts.append(verb, &pts[1]);
2670        }
2671    } while (verb != SkPath::kDone_Verb);
2672    // FIXME: end of section to remove once path pts are accessed directly
2673
2674    SkPath::Verb reducedVerb;
2675    uint8_t* verbPtr = fPathVerbs.begin();
2676    const SkPoint* pointsPtr = fPathPts.begin();
2677    const SkPoint* finalCurveStart = NULL;
2678    const SkPoint* finalCurveEnd = NULL;
2679    while ((verb = (SkPath::Verb) *verbPtr++) != SkPath::kDone_Verb) {
2680        switch (verb) {
2681            case SkPath::kMove_Verb:
2682                complete();
2683                if (!fCurrentContour) {
2684                    fCurrentContour = fContours.push_back_n(1);
2685                    finalCurveEnd = pointsPtr++;
2686                    *fExtra.append() = -1; // start new contour
2687                }
2688                continue;
2689            case SkPath::kLine_Verb:
2690                // skip degenerate points
2691                if (pointsPtr[-1].fX != pointsPtr[0].fX
2692                        || pointsPtr[-1].fY != pointsPtr[0].fY) {
2693                    fCurrentContour->addLine(&pointsPtr[-1]);
2694                }
2695                break;
2696            case SkPath::kQuad_Verb:
2697
2698                reducedVerb = QuadReduceOrder(&pointsPtr[-1], fReducePts);
2699                if (reducedVerb == 0) {
2700                    break; // skip degenerate points
2701                }
2702                if (reducedVerb == 1) {
2703                    *fExtra.append() =
2704                            fCurrentContour->addLine(fReducePts.end() - 2);
2705                    break;
2706                }
2707                fCurrentContour->addQuad(&pointsPtr[-1]);
2708                break;
2709            case SkPath::kCubic_Verb:
2710                reducedVerb = CubicReduceOrder(&pointsPtr[-1], fReducePts);
2711                if (reducedVerb == 0) {
2712                    break; // skip degenerate points
2713                }
2714                if (reducedVerb == 1) {
2715                    *fExtra.append() =
2716                            fCurrentContour->addLine(fReducePts.end() - 2);
2717                    break;
2718                }
2719                if (reducedVerb == 2) {
2720                    *fExtra.append() =
2721                            fCurrentContour->addQuad(fReducePts.end() - 3);
2722                    break;
2723                }
2724                fCurrentContour->addCubic(&pointsPtr[-1]);
2725                break;
2726            case SkPath::kClose_Verb:
2727                SkASSERT(fCurrentContour);
2728                if (finalCurveStart && finalCurveEnd
2729                        && *finalCurveStart != *finalCurveEnd) {
2730                    *fReducePts.append() = *finalCurveStart;
2731                    *fReducePts.append() = *finalCurveEnd;
2732                    *fExtra.append() =
2733                            fCurrentContour->addLine(fReducePts.end() - 2);
2734                }
2735                complete();
2736                continue;
2737            default:
2738                SkDEBUGFAIL("bad verb");
2739                return;
2740        }
2741        finalCurveStart = &pointsPtr[verb - 1];
2742        pointsPtr += verb;
2743        SkASSERT(fCurrentContour);
2744    }
2745    complete();
2746    if (fCurrentContour && !fCurrentContour->segments().count()) {
2747        fContours.pop_back();
2748    }
2749    // correct pointers in contours since fReducePts may have moved as it grew
2750    int cIndex = 0;
2751    int extraCount = fExtra.count();
2752    SkASSERT(extraCount == 0 || fExtra[0] == -1);
2753    int eIndex = 0;
2754    int rIndex = 0;
2755    while (++eIndex < extraCount) {
2756        int offset = fExtra[eIndex];
2757        if (offset < 0) {
2758            ++cIndex;
2759            continue;
2760        }
2761        fCurrentContour = &fContours[cIndex];
2762        rIndex += fCurrentContour->updateSegment(offset - 1,
2763                &fReducePts[rIndex]);
2764    }
2765    fExtra.reset(); // we're done with this
2766}
2767
2768private:
2769    const SkPath& fPath;
2770    SkTDArray<SkPoint> fPathPts; // FIXME: point directly to path pts instead
2771    SkTDArray<uint8_t> fPathVerbs; // FIXME: remove
2772    Contour* fCurrentContour;
2773    SkTArray<Contour>& fContours;
2774    SkTDArray<SkPoint> fReducePts; // segments created on the fly
2775    SkTDArray<int> fExtra; // -1 marks new contour, > 0 offsets into contour
2776};
2777
2778class Work {
2779public:
2780    enum SegmentType {
2781        kHorizontalLine_Segment = -1,
2782        kVerticalLine_Segment = 0,
2783        kLine_Segment = SkPath::kLine_Verb,
2784        kQuad_Segment = SkPath::kQuad_Verb,
2785        kCubic_Segment = SkPath::kCubic_Verb,
2786    };
2787
2788    void addCoincident(Work& other, const Intersections& ts, bool swap) {
2789        fContour->addCoincident(fIndex, other.fContour, other.fIndex, ts, swap);
2790    }
2791
2792    // FIXME: does it make sense to write otherIndex now if we're going to
2793    // fix it up later?
2794    void addOtherT(int index, double otherT, int otherIndex) {
2795        fContour->addOtherT(fIndex, index, otherT, otherIndex);
2796    }
2797
2798    // Avoid collapsing t values that are close to the same since
2799    // we walk ts to describe consecutive intersections. Since a pair of ts can
2800    // be nearly equal, any problems caused by this should be taken care
2801    // of later.
2802    // On the edge or out of range values are negative; add 2 to get end
2803    int addT(double newT, const Work& other) {
2804        return fContour->addT(fIndex, newT, other.fContour, other.fIndex);
2805    }
2806
2807    bool advance() {
2808        return ++fIndex < fLast;
2809    }
2810
2811    SkScalar bottom() const {
2812        return bounds().fBottom;
2813    }
2814
2815    const Bounds& bounds() const {
2816        return fContour->segments()[fIndex].bounds();
2817    }
2818
2819    const SkPoint* cubic() const {
2820        return fCubic;
2821    }
2822
2823    void init(Contour* contour) {
2824        fContour = contour;
2825        fIndex = 0;
2826        fLast = contour->segments().count();
2827    }
2828
2829    bool isAdjacent(const Work& next) {
2830        return fContour == next.fContour && fIndex + 1 == next.fIndex;
2831    }
2832
2833    bool isFirstLast(const Work& next) {
2834        return fContour == next.fContour && fIndex == 0
2835                && next.fIndex == fLast - 1;
2836    }
2837
2838    SkScalar left() const {
2839        return bounds().fLeft;
2840    }
2841
2842    void promoteToCubic() {
2843        fCubic[0] = pts()[0];
2844        fCubic[2] = pts()[1];
2845        fCubic[3] = pts()[2];
2846        fCubic[1].fX = (fCubic[0].fX + fCubic[2].fX * 2) / 3;
2847        fCubic[1].fY = (fCubic[0].fY + fCubic[2].fY * 2) / 3;
2848        fCubic[2].fX = (fCubic[3].fX + fCubic[2].fX * 2) / 3;
2849        fCubic[2].fY = (fCubic[3].fY + fCubic[2].fY * 2) / 3;
2850    }
2851
2852    const SkPoint* pts() const {
2853        return fContour->segments()[fIndex].pts();
2854    }
2855
2856    SkScalar right() const {
2857        return bounds().fRight;
2858    }
2859
2860    ptrdiff_t segmentIndex() const {
2861        return fIndex;
2862    }
2863
2864    SegmentType segmentType() const {
2865        const Segment& segment = fContour->segments()[fIndex];
2866        SegmentType type = (SegmentType) segment.verb();
2867        if (type != kLine_Segment) {
2868            return type;
2869        }
2870        if (segment.isHorizontal()) {
2871            return kHorizontalLine_Segment;
2872        }
2873        if (segment.isVertical()) {
2874            return kVerticalLine_Segment;
2875        }
2876        return kLine_Segment;
2877    }
2878
2879    bool startAfter(const Work& after) {
2880        fIndex = after.fIndex;
2881        return advance();
2882    }
2883
2884    SkScalar top() const {
2885        return bounds().fTop;
2886    }
2887
2888    SkPath::Verb verb() const {
2889        return fContour->segments()[fIndex].verb();
2890    }
2891
2892    SkScalar x() const {
2893        return bounds().fLeft;
2894    }
2895
2896    bool xFlipped() const {
2897        return x() != pts()[0].fX;
2898    }
2899
2900    SkScalar y() const {
2901        return bounds().fTop;
2902    }
2903
2904    bool yFlipped() const {
2905        return y() != pts()[0].fY;
2906    }
2907
2908protected:
2909    Contour* fContour;
2910    SkPoint fCubic[4];
2911    int fIndex;
2912    int fLast;
2913};
2914
2915#if DEBUG_ADD_INTERSECTING_TS
2916static void debugShowLineIntersection(int pts, const Work& wt,
2917        const Work& wn, const double wtTs[2], const double wnTs[2]) {
2918    if (!pts) {
2919        SkDebugf("%s no intersect (%1.9g,%1.9g %1.9g,%1.9g) (%1.9g,%1.9g %1.9g,%1.9g)\n",
2920                __FUNCTION__, wt.pts()[0].fX, wt.pts()[0].fY,
2921                wt.pts()[1].fX, wt.pts()[1].fY, wn.pts()[0].fX, wn.pts()[0].fY,
2922                wn.pts()[1].fX, wn.pts()[1].fY);
2923        return;
2924    }
2925    SkPoint wtOutPt, wnOutPt;
2926    LineXYAtT(wt.pts(), wtTs[0], &wtOutPt);
2927    LineXYAtT(wn.pts(), wnTs[0], &wnOutPt);
2928    SkDebugf("%s wtTs[0]=%g (%g,%g, %g,%g) (%g,%g)",
2929            __FUNCTION__,
2930            wtTs[0], wt.pts()[0].fX, wt.pts()[0].fY,
2931            wt.pts()[1].fX, wt.pts()[1].fY, wtOutPt.fX, wtOutPt.fY);
2932    if (pts == 2) {
2933        SkDebugf(" wtTs[1]=%g", wtTs[1]);
2934    }
2935    SkDebugf(" wnTs[0]=%g (%g,%g, %g,%g) (%g,%g)",
2936            wnTs[0], wn.pts()[0].fX, wn.pts()[0].fY,
2937            wn.pts()[1].fX, wn.pts()[1].fY, wnOutPt.fX, wnOutPt.fY);
2938    if (pts == 2) {
2939        SkDebugf(" wnTs[1]=%g", wnTs[1]);
2940    }
2941    SkDebugf("\n");
2942}
2943#else
2944static void debugShowLineIntersection(int , const Work& ,
2945        const Work& , const double [2], const double [2]) {
2946}
2947#endif
2948
2949static bool addIntersectTs(Contour* test, Contour* next) {
2950
2951    if (test != next) {
2952        if (test->bounds().fBottom < next->bounds().fTop) {
2953            return false;
2954        }
2955        if (!Bounds::Intersects(test->bounds(), next->bounds())) {
2956            return true;
2957        }
2958    }
2959    Work wt;
2960    wt.init(test);
2961    bool foundCommonContour = test == next;
2962    do {
2963        Work wn;
2964        wn.init(next);
2965        if (test == next && !wn.startAfter(wt)) {
2966            continue;
2967        }
2968        do {
2969            if (!Bounds::Intersects(wt.bounds(), wn.bounds())) {
2970                continue;
2971            }
2972            int pts;
2973            Intersections ts;
2974            bool swap = false;
2975            switch (wt.segmentType()) {
2976                case Work::kHorizontalLine_Segment:
2977                    swap = true;
2978                    switch (wn.segmentType()) {
2979                        case Work::kHorizontalLine_Segment:
2980                        case Work::kVerticalLine_Segment:
2981                        case Work::kLine_Segment: {
2982                            pts = HLineIntersect(wn.pts(), wt.left(),
2983                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2984                            debugShowLineIntersection(pts, wt, wn,
2985                                    ts.fT[1], ts.fT[0]);
2986                            break;
2987                        }
2988                        case Work::kQuad_Segment: {
2989                            pts = HQuadIntersect(wn.pts(), wt.left(),
2990                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2991                            break;
2992                        }
2993                        case Work::kCubic_Segment: {
2994                            pts = HCubicIntersect(wn.pts(), wt.left(),
2995                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2996                            break;
2997                        }
2998                        default:
2999                            SkASSERT(0);
3000                    }
3001                    break;
3002                case Work::kVerticalLine_Segment:
3003                    swap = true;
3004                    switch (wn.segmentType()) {
3005                        case Work::kHorizontalLine_Segment:
3006                        case Work::kVerticalLine_Segment:
3007                        case Work::kLine_Segment: {
3008                            pts = VLineIntersect(wn.pts(), wt.top(),
3009                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
3010                            debugShowLineIntersection(pts, wt, wn,
3011                                    ts.fT[1], ts.fT[0]);
3012                            break;
3013                        }
3014                        case Work::kQuad_Segment: {
3015                            pts = VQuadIntersect(wn.pts(), wt.top(),
3016                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
3017                            break;
3018                        }
3019                        case Work::kCubic_Segment: {
3020                            pts = VCubicIntersect(wn.pts(), wt.top(),
3021                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
3022                            break;
3023                        }
3024                        default:
3025                            SkASSERT(0);
3026                    }
3027                    break;
3028                case Work::kLine_Segment:
3029                    switch (wn.segmentType()) {
3030                        case Work::kHorizontalLine_Segment:
3031                            pts = HLineIntersect(wt.pts(), wn.left(),
3032                                    wn.right(), wn.y(), wn.xFlipped(), ts);
3033                            debugShowLineIntersection(pts, wt, wn,
3034                                    ts.fT[1], ts.fT[0]);
3035                            break;
3036                        case Work::kVerticalLine_Segment:
3037                            pts = VLineIntersect(wt.pts(), wn.top(),
3038                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
3039                            debugShowLineIntersection(pts, wt, wn,
3040                                    ts.fT[1], ts.fT[0]);
3041                            break;
3042                        case Work::kLine_Segment: {
3043                            pts = LineIntersect(wt.pts(), wn.pts(), ts);
3044                            debugShowLineIntersection(pts, wt, wn,
3045                                    ts.fT[1], ts.fT[0]);
3046                            break;
3047                        }
3048                        case Work::kQuad_Segment: {
3049                            swap = true;
3050                            pts = QuadLineIntersect(wn.pts(), wt.pts(), ts);
3051                            break;
3052                        }
3053                        case Work::kCubic_Segment: {
3054                            swap = true;
3055                            pts = CubicLineIntersect(wn.pts(), wt.pts(), ts);
3056                            break;
3057                        }
3058                        default:
3059                            SkASSERT(0);
3060                    }
3061                    break;
3062                case Work::kQuad_Segment:
3063                    switch (wn.segmentType()) {
3064                        case Work::kHorizontalLine_Segment:
3065                            pts = HQuadIntersect(wt.pts(), wn.left(),
3066                                    wn.right(), wn.y(), wn.xFlipped(), ts);
3067                            break;
3068                        case Work::kVerticalLine_Segment:
3069                            pts = VQuadIntersect(wt.pts(), wn.top(),
3070                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
3071                            break;
3072                        case Work::kLine_Segment: {
3073                            pts = QuadLineIntersect(wt.pts(), wn.pts(), ts);
3074                            break;
3075                        }
3076                        case Work::kQuad_Segment: {
3077                            pts = QuadIntersect(wt.pts(), wn.pts(), ts);
3078                            break;
3079                        }
3080                        case Work::kCubic_Segment: {
3081                            wt.promoteToCubic();
3082                            pts = CubicIntersect(wt.cubic(), wn.pts(), ts);
3083                            break;
3084                        }
3085                        default:
3086                            SkASSERT(0);
3087                    }
3088                    break;
3089                case Work::kCubic_Segment:
3090                    switch (wn.segmentType()) {
3091                        case Work::kHorizontalLine_Segment:
3092                            pts = HCubicIntersect(wt.pts(), wn.left(),
3093                                    wn.right(), wn.y(), wn.xFlipped(), ts);
3094                            break;
3095                        case Work::kVerticalLine_Segment:
3096                            pts = VCubicIntersect(wt.pts(), wn.top(),
3097                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
3098                            break;
3099                        case Work::kLine_Segment: {
3100                            pts = CubicLineIntersect(wt.pts(), wn.pts(), ts);
3101                            break;
3102                        }
3103                        case Work::kQuad_Segment: {
3104                            wn.promoteToCubic();
3105                            pts = CubicIntersect(wt.pts(), wn.cubic(), ts);
3106                            break;
3107                        }
3108                        case Work::kCubic_Segment: {
3109                            pts = CubicIntersect(wt.pts(), wn.pts(), ts);
3110                            break;
3111                        }
3112                        default:
3113                            SkASSERT(0);
3114                    }
3115                    break;
3116                default:
3117                    SkASSERT(0);
3118            }
3119            if (!foundCommonContour && pts > 0) {
3120                test->addCross(next);
3121                next->addCross(test);
3122                foundCommonContour = true;
3123            }
3124            // in addition to recording T values, record matching segment
3125            if (pts == 2 && wn.segmentType() <= Work::kLine_Segment
3126                    && wt.segmentType() <= Work::kLine_Segment) {
3127                wt.addCoincident(wn, ts, swap);
3128                continue;
3129            }
3130            for (int pt = 0; pt < pts; ++pt) {
3131                SkASSERT(ts.fT[0][pt] >= 0 && ts.fT[0][pt] <= 1);
3132                SkASSERT(ts.fT[1][pt] >= 0 && ts.fT[1][pt] <= 1);
3133                int testTAt = wt.addT(ts.fT[swap][pt], wn);
3134                int nextTAt = wn.addT(ts.fT[!swap][pt], wt);
3135                wt.addOtherT(testTAt, ts.fT[!swap][pt], nextTAt);
3136                wn.addOtherT(nextTAt, ts.fT[swap][pt], testTAt);
3137            }
3138        } while (wn.advance());
3139    } while (wt.advance());
3140    return true;
3141}
3142
3143// resolve any coincident pairs found while intersecting, and
3144// see if coincidence is formed by clipping non-concident segments
3145static void coincidenceCheck(SkTDArray<Contour*>& contourList, int winding) {
3146    int contourCount = contourList.count();
3147    for (int cIndex = 0; cIndex < contourCount; ++cIndex) {
3148        Contour* contour = contourList[cIndex];
3149        contour->findTooCloseToCall(winding);
3150    }
3151    for (int cIndex = 0; cIndex < contourCount; ++cIndex) {
3152        Contour* contour = contourList[cIndex];
3153        contour->resolveCoincidence(winding);
3154    }
3155}
3156
3157// project a ray from the top of the contour up and see if it hits anything
3158// note: when we compute line intersections, we keep track of whether
3159// two contours touch, so we need only look at contours not touching this one.
3160// OPTIMIZATION: sort contourList vertically to avoid linear walk
3161static int innerContourCheck(SkTDArray<Contour*>& contourList,
3162        const Segment* current, int index, int endIndex) {
3163    const SkPoint& basePt = current->xyAtT(endIndex);
3164    int contourCount = contourList.count();
3165    SkScalar bestY = SK_ScalarMin;
3166    const Segment* test = NULL;
3167    int tIndex;
3168    double tHit;
3169 //   bool checkCrosses = true;
3170    for (int cTest = 0; cTest < contourCount; ++cTest) {
3171        Contour* contour = contourList[cTest];
3172        if (basePt.fY < contour->bounds().fTop) {
3173            continue;
3174        }
3175        if (bestY > contour->bounds().fBottom) {
3176            continue;
3177        }
3178#if 0
3179        // even though the contours crossed, if spans cancel through concidence,
3180        // the contours may be not have any span links to chase, and the current
3181        // segment may be isolated. Detect this by seeing if current has
3182        // uninitialized wind sums. If so, project a ray instead of relying on
3183        // previously found intersections.
3184        if (baseContour == contour) {
3185            continue;
3186        }
3187        if (checkCrosses && baseContour->crosses(contour)) {
3188            if (current->isConnected(index, endIndex)) {
3189                continue;
3190            }
3191            checkCrosses = false;
3192        }
3193#endif
3194        const Segment* next = contour->crossedSegment(basePt, bestY, tIndex, tHit);
3195        if (next) {
3196            test = next;
3197        }
3198    }
3199    if (!test) {
3200        return 0;
3201    }
3202    int winding, windValue;
3203    // If the ray hit the end of a span, we need to construct the wheel of
3204    // angles to find the span closest to the ray -- even if there are just
3205    // two spokes on the wheel.
3206    const Angle* angle = NULL;
3207    if (fabs(tHit - test->t(tIndex)) < FLT_EPSILON) {
3208        SkTDArray<Angle> angles;
3209        int end = test->nextSpan(tIndex, 1);
3210        if (end < 0) {
3211            end = test->nextSpan(tIndex, -1);
3212        }
3213        test->addTwoAngles(end, tIndex, angles);
3214        test->buildAngles(tIndex, angles);
3215        SkTDArray<Angle*> sorted;
3216        // OPTIMIZATION: call a sort that, if base point is the leftmost,
3217        // returns the first counterclockwise hour before 6 o'clock,
3218        // or if the base point is rightmost, returns the first clockwise
3219        // hour after 6 o'clock
3220        sortAngles(angles, sorted);
3221#if DEBUG_SORT
3222        sorted[0]->segment()->debugShowSort(sorted, 0, 0);
3223#endif
3224        // walk the sorted angle fan to find the lowest angle
3225        // above the base point. Currently, the first angle in the sorted array
3226        // is 12 noon or an earlier hour (the next counterclockwise)
3227        int count = sorted.count();
3228        int left = -1;
3229        int mid = -1;
3230        int right = -1;
3231        bool baseMatches = test->yAtT(tIndex) == basePt.fY;
3232        for (int index = 0; index < count; ++index) {
3233            const Angle* angle = sorted[index];
3234            if (baseMatches && angle->isHorizontal()) {
3235                continue;
3236            }
3237            double indexDx = angle->dx();
3238            if (indexDx < 0) {
3239                left = index;
3240            } else if (indexDx > 0) {
3241                right = index;
3242                break;
3243            } else {
3244                mid = index;
3245            }
3246        }
3247        if (left < 0 && right < 0) {
3248            left = mid;
3249        }
3250        SkASSERT(left >= 0 || right >= 0);
3251        if (left < 0) {
3252            left = right;
3253        } else if (left >= 0 && mid >= 0 && right >= 0
3254                && sorted[mid]->sign() == sorted[right]->sign()) {
3255            left = right;
3256        }
3257        angle = sorted[left];
3258        test = angle->segment();
3259        winding = test->windSum(angle);
3260        SkASSERT(winding != SK_MinS32);
3261        windValue = test->windValue(angle);
3262#if DEBUG_WINDING
3263        SkDebugf("%s angle winding=%d windValue=%d sign=%d\n", __FUNCTION__, winding,
3264                windValue, angle->sign());
3265#endif
3266    } else {
3267        winding = test->windSum(tIndex);
3268        SkASSERT(winding != SK_MinS32);
3269        windValue = test->windValue(tIndex);
3270#if DEBUG_WINDING
3271        SkDebugf("%s single winding=%d windValue=%d\n", __FUNCTION__, winding,
3272                windValue);
3273#endif
3274    }
3275    // see if a + change in T results in a +/- change in X (compute x'(T))
3276    SkScalar dx = (*SegmentDXAtT[test->verb()])(test->pts(), tHit);
3277#if DEBUG_WINDING
3278    SkDebugf("%s dx=%1.9g\n", __FUNCTION__, dx);
3279#endif
3280    if (dx == 0) {
3281        SkASSERT(angle);
3282        if (test->firstBump(angle, winding)) {
3283            winding -= test->windBump(angle);
3284        }
3285    } else if (winding * dx > 0) { // if same signs, result is negative
3286        winding += dx > 0 ? -windValue : windValue;
3287#if DEBUG_WINDING
3288        SkDebugf("%s final winding=%d\n", __FUNCTION__, winding);
3289#endif
3290    }
3291 //   start here;
3292    // we're broken because we find a vertical span
3293    return winding;
3294}
3295
3296// OPTIMIZATION: not crazy about linear search here to find top active y.
3297// seems like we should break down and do the sort, or maybe sort each
3298// contours' segments?
3299// Once the segment array is built, there's no reason I can think of not to
3300// sort it in Y. hmmm
3301// FIXME: return the contour found to pass to inner contour check
3302static Segment* findTopContour(SkTDArray<Contour*>& contourList) {
3303    int contourCount = contourList.count();
3304    int cIndex = 0;
3305    Segment* topStart;
3306    SkScalar bestY = SK_ScalarMax;
3307    Contour* contour;
3308    do {
3309        contour = contourList[cIndex];
3310        topStart = contour->topSegment(bestY);
3311    } while (!topStart && ++cIndex < contourCount);
3312    if (!topStart) {
3313        return NULL;
3314    }
3315    while (++cIndex < contourCount) {
3316        contour = contourList[cIndex];
3317        if (bestY < contour->bounds().fTop) {
3318            continue;
3319        }
3320        SkScalar testY = SK_ScalarMax;
3321        Segment* test = contour->topSegment(testY);
3322        if (!test || bestY <= testY) {
3323            continue;
3324        }
3325        topStart = test;
3326        bestY = testY;
3327    }
3328    return topStart;
3329}
3330
3331static Segment* findChase(SkTDArray<Span*>& chase, int& tIndex, int& endIndex,
3332        int contourWinding) {
3333    while (chase.count()) {
3334        Span* span = chase[chase.count() - 1];
3335        const Span& backPtr = span->fOther->span(span->fOtherIndex);
3336        Segment* segment = backPtr.fOther;
3337        tIndex = backPtr.fOtherIndex;
3338        SkTDArray<Angle> angles;
3339        int done = 0;
3340        if (segment->activeAngle(tIndex, done, angles)) {
3341            Angle* last = angles.end() - 1;
3342            tIndex = last->start();
3343            endIndex = last->end();
3344            return last->segment();
3345        }
3346        if (done == angles.count()) {
3347            chase.pop(&span);
3348            continue;
3349        }
3350        SkTDArray<Angle*> sorted;
3351        sortAngles(angles, sorted);
3352        // find first angle, initialize winding to computed fWindSum
3353        int firstIndex = -1;
3354        const Angle* angle;
3355        int winding;
3356        do {
3357            angle = sorted[++firstIndex];
3358            segment = angle->segment();
3359            winding = segment->windSum(angle);
3360        } while (winding == SK_MinS32);
3361        int spanWinding = segment->spanSign(angle->start(), angle->end());
3362    #if DEBUG_WINDING
3363        SkDebugf("%s winding=%d spanWinding=%d contourWinding=%d\n",
3364                __FUNCTION__, winding, spanWinding, contourWinding);
3365    #endif
3366        // turn swinding into contourWinding
3367        if (spanWinding * winding < 0) {
3368            winding += spanWinding;
3369        }
3370    #if DEBUG_SORT
3371        segment->debugShowSort(sorted, firstIndex, winding);
3372    #endif
3373        // we care about first sign and whether wind sum indicates this
3374        // edge is inside or outside. Maybe need to pass span winding
3375        // or first winding or something into this function?
3376        // advance to first undone angle, then return it and winding
3377        // (to set whether edges are active or not)
3378        int nextIndex = firstIndex + 1;
3379        int angleCount = sorted.count();
3380        int lastIndex = firstIndex != 0 ? firstIndex : angleCount;
3381        angle = sorted[firstIndex];
3382        winding -= angle->segment()->windBump(angle);
3383        do {
3384            SkASSERT(nextIndex != firstIndex);
3385            if (nextIndex == angleCount) {
3386                nextIndex = 0;
3387            }
3388            angle = sorted[nextIndex];
3389            segment = angle->segment();
3390            int maxWinding = winding;
3391            winding -= segment->windBump(angle);
3392    #if DEBUG_SORT
3393            SkDebugf("%s id=%d maxWinding=%d winding=%d\n", __FUNCTION__,
3394                    segment->debugID(), maxWinding, winding);
3395    #endif
3396            tIndex = angle->start();
3397            endIndex = angle->end();
3398            int lesser = SkMin32(tIndex, endIndex);
3399            const Span& nextSpan = segment->span(lesser);
3400            if (!nextSpan.fDone) {
3401#if 1
3402            // FIXME: this be wrong. assign startWinding if edge is in
3403            // same direction. If the direction is opposite, winding to
3404            // assign is flipped sign or +/- 1?
3405                if (abs(maxWinding) < abs(winding)) {
3406                    maxWinding = winding;
3407                }
3408                segment->markWinding(lesser, maxWinding);
3409#endif
3410                break;
3411            }
3412        } while (++nextIndex != lastIndex);
3413        return segment;
3414    }
3415    return NULL;
3416}
3417
3418#if DEBUG_ACTIVE_SPANS
3419static void debugShowActiveSpans(SkTDArray<Contour*>& contourList) {
3420    for (int index = 0; index < contourList.count(); ++ index) {
3421        contourList[index]->debugShowActiveSpans();
3422    }
3423}
3424#endif
3425
3426static bool windingIsActive(int winding, int spanWinding) {
3427    return winding * spanWinding <= 0 && abs(winding) <= abs(spanWinding)
3428            && (!winding || !spanWinding || winding == -spanWinding);
3429}
3430
3431// Each segment may have an inside or an outside. Segments contained within
3432// winding may have insides on either side, and form a contour that should be
3433// ignored. Segments that are coincident with opposing direction segments may
3434// have outsides on either side, and should also disappear.
3435// 'Normal' segments will have one inside and one outside. Subsequent connections
3436// when winding should follow the intersection direction. If more than one edge
3437// is an option, choose first edge that continues the inside.
3438    // since we start with leftmost top edge, we'll traverse through a
3439    // smaller angle counterclockwise to get to the next edge.
3440static void bridge(SkTDArray<Contour*>& contourList, SkPath& simple) {
3441    bool firstContour = true;
3442    do {
3443        Segment* topStart = findTopContour(contourList);
3444        if (!topStart) {
3445            break;
3446        }
3447        // Start at the top. Above the top is outside, below is inside.
3448        // follow edges to intersection by changing the index by direction.
3449        int index, endIndex;
3450        Segment* current = topStart->findTop(index, endIndex);
3451        int contourWinding;
3452        if (firstContour) {
3453            contourWinding = 0;
3454            firstContour = false;
3455        } else {
3456            int sumWinding = current->windSum(SkMin32(index, endIndex));
3457            // FIXME: don't I have to adjust windSum to get contourWinding?
3458            if (sumWinding == SK_MinS32) {
3459                sumWinding = current->computeSum(index, endIndex);
3460            }
3461            if (sumWinding == SK_MinS32) {
3462                contourWinding = innerContourCheck(contourList, current,
3463                        index, endIndex);
3464            } else {
3465                contourWinding = sumWinding;
3466                int spanWinding = current->spanSign(index, endIndex);
3467                if (spanWinding * sumWinding > 0) {
3468                    contourWinding -= spanWinding;
3469                }
3470            }
3471#if DEBUG_WINDING
3472         //   SkASSERT(current->debugVerifyWinding(index, endIndex, contourWinding));
3473            SkDebugf("%s contourWinding=%d\n", __FUNCTION__, contourWinding);
3474#endif
3475        }
3476        SkPoint lastPt;
3477        bool firstTime = true;
3478        int winding = contourWinding;
3479        int spanWinding = current->spanSign(index, endIndex);
3480        // FIXME: needs work. While it works in limited situations, it does
3481        // not always compute winding correctly. Active should be removed and instead
3482        // the initial winding should be correctly passed in so that if the
3483        // inner contour is wound the same way, it never finds an accumulated
3484        // winding of zero. Inside 'find next', we need to look for transitions
3485        // other than zero when resolving sorted angles.
3486        bool active = windingIsActive(winding, spanWinding);
3487        SkTDArray<Span*> chaseArray;
3488        do {
3489        #if DEBUG_WINDING
3490            SkDebugf("%s active=%s winding=%d spanWinding=%d\n",
3491                    __FUNCTION__, active ? "true" : "false",
3492                    winding, spanWinding);
3493        #endif
3494            const SkPoint* firstPt = NULL;
3495            do {
3496                SkASSERT(!current->done());
3497                int nextStart, nextEnd;
3498                Segment* next = current->findNext(chaseArray,
3499                        firstTime, active, index, endIndex,
3500                        nextStart, nextEnd, winding, spanWinding);
3501                if (!next) {
3502                    break;
3503                }
3504                if (!firstPt) {
3505                    firstPt = &current->addMoveTo(index, simple, active);
3506                }
3507                lastPt = current->addCurveTo(index, endIndex, simple, active);
3508                current = next;
3509                index = nextStart;
3510                endIndex = nextEnd;
3511                firstTime = false;
3512            } while (*firstPt != lastPt && (active || !current->done()));
3513            if (firstPt && active) {
3514        #if DEBUG_PATH_CONSTRUCTION
3515                SkDebugf("%s close\n", __FUNCTION__);
3516        #endif
3517                simple.close();
3518            }
3519            current = findChase(chaseArray, index, endIndex, contourWinding);
3520        #if DEBUG_ACTIVE_SPANS
3521            debugShowActiveSpans(contourList);
3522        #endif
3523            if (!current) {
3524                break;
3525            }
3526            int lesser = SkMin32(index, endIndex);
3527            spanWinding = current->spanSign(index, endIndex);
3528            winding = current->windSum(lesser);
3529            if (spanWinding * winding > 0) {
3530                winding -= spanWinding;
3531            }
3532            active = windingIsActive(winding, spanWinding);
3533        } while (true);
3534    } while (true);
3535}
3536
3537static void fixOtherTIndex(SkTDArray<Contour*>& contourList) {
3538    int contourCount = contourList.count();
3539    for (int cTest = 0; cTest < contourCount; ++cTest) {
3540        Contour* contour = contourList[cTest];
3541        contour->fixOtherTIndex();
3542    }
3543}
3544
3545static void makeContourList(SkTArray<Contour>& contours,
3546        SkTDArray<Contour*>& list) {
3547    int count = contours.count();
3548    if (count == 0) {
3549        return;
3550    }
3551    for (int index = 0; index < count; ++index) {
3552        *list.append() = &contours[index];
3553    }
3554    QSort<Contour>(list.begin(), list.end() - 1);
3555}
3556
3557void simplifyx(const SkPath& path, SkPath& simple) {
3558    // returns 1 for evenodd, -1 for winding, regardless of inverse-ness
3559    int winding = (path.getFillType() & 1) ? 1 : -1;
3560    simple.reset();
3561    simple.setFillType(SkPath::kEvenOdd_FillType);
3562
3563    // turn path into list of segments
3564    SkTArray<Contour> contours;
3565    // FIXME: add self-intersecting cubics' T values to segment
3566    EdgeBuilder builder(path, contours);
3567    SkTDArray<Contour*> contourList;
3568    makeContourList(contours, contourList);
3569    Contour** currentPtr = contourList.begin();
3570    if (!currentPtr) {
3571        return;
3572    }
3573    Contour** listEnd = contourList.end();
3574    // find all intersections between segments
3575    do {
3576        Contour** nextPtr = currentPtr;
3577        Contour* current = *currentPtr++;
3578        Contour* next;
3579        do {
3580            next = *nextPtr++;
3581        } while (addIntersectTs(current, next) && nextPtr != listEnd);
3582    } while (currentPtr != listEnd);
3583    // eat through coincident edges
3584    coincidenceCheck(contourList, winding);
3585    fixOtherTIndex(contourList);
3586    // construct closed contours
3587    bridge(contourList, simple);
3588}
3589
3590