1
/*
2
 * Copyright © 2004 Carl Worth
3
 * Copyright © 2006 Red Hat, Inc.
4
 * Copyright © 2008 Chris Wilson
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it either under the terms of the GNU Lesser General Public
8
 * License version 2.1 as published by the Free Software Foundation
9
 * (the "LGPL") or, at your option, under the terms of the Mozilla
10
 * Public License Version 1.1 (the "MPL"). If you do not alter this
11
 * notice, a recipient may use your version of this file under either
12
 * the MPL or the LGPL.
13
 *
14
 * You should have received a copy of the LGPL along with this library
15
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17
 * You should have received a copy of the MPL along with this library
18
 * in the file COPYING-MPL-1.1
19
 *
20
 * The contents of this file are subject to the Mozilla Public License
21
 * Version 1.1 (the "License"); you may not use this file except in
22
 * compliance with the License. You may obtain a copy of the License at
23
 * http://www.mozilla.org/MPL/
24
 *
25
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27
 * the specific language governing rights and limitations.
28
 *
29
 * The Original Code is the cairo graphics library.
30
 *
31
 * The Initial Developer of the Original Code is Carl Worth
32
 *
33
 * Contributor(s):
34
 *	Carl D. Worth <cworth@cworth.org>
35
 *	Chris Wilson <chris@chris-wilson.co.uk>
36
 */
37

            
38
/* Provide definitions for standalone compilation */
39
#include "cairoint.h"
40

            
41
#include "cairo-combsort-inline.h"
42
#include "cairo-error-private.h"
43
#include "cairo-freelist-private.h"
44
#include "cairo-line-inline.h"
45
#include "cairo-traps-private.h"
46

            
47
#define DEBUG_PRINT_STATE 0
48
#define DEBUG_EVENTS 0
49
#define DEBUG_TRAPS 0
50

            
51
typedef cairo_point_t cairo_bo_point32_t;
52

            
53
typedef struct _cairo_bo_intersect_ordinate {
54
    int32_t ordinate;
55
    enum { EXACT, INEXACT } exactness;
56
} cairo_bo_intersect_ordinate_t;
57

            
58
typedef struct _cairo_bo_intersect_point {
59
    cairo_bo_intersect_ordinate_t x;
60
    cairo_bo_intersect_ordinate_t y;
61
} cairo_bo_intersect_point_t;
62

            
63
typedef struct _cairo_bo_edge cairo_bo_edge_t;
64
typedef struct _cairo_bo_trap cairo_bo_trap_t;
65

            
66
/* A deferred trapezoid of an edge */
67
struct _cairo_bo_trap {
68
    cairo_bo_edge_t *right;
69
    int32_t top;
70
};
71

            
72
struct _cairo_bo_edge {
73
    cairo_edge_t edge;
74
    cairo_bo_edge_t *prev;
75
    cairo_bo_edge_t *next;
76
    cairo_bo_edge_t *colinear;
77
    cairo_bo_trap_t deferred_trap;
78
};
79

            
80
/* the parent is always given by index/2 */
81
#define PQ_PARENT_INDEX(i) ((i) >> 1)
82
#define PQ_FIRST_ENTRY 1
83

            
84
/* left and right children are index * 2 and (index * 2) +1 respectively */
85
#define PQ_LEFT_CHILD_INDEX(i) ((i) << 1)
86

            
87
typedef enum {
88
    CAIRO_BO_EVENT_TYPE_STOP,
89
    CAIRO_BO_EVENT_TYPE_INTERSECTION,
90
    CAIRO_BO_EVENT_TYPE_START
91
} cairo_bo_event_type_t;
92

            
93
typedef struct _cairo_bo_event {
94
    cairo_bo_event_type_t type;
95
    cairo_point_t point;
96
} cairo_bo_event_t;
97

            
98
typedef struct _cairo_bo_start_event {
99
    cairo_bo_event_type_t type;
100
    cairo_point_t point;
101
    cairo_bo_edge_t edge;
102
} cairo_bo_start_event_t;
103

            
104
typedef struct _cairo_bo_queue_event {
105
    cairo_bo_event_type_t type;
106
    cairo_point_t point;
107
    cairo_bo_edge_t *e1;
108
    cairo_bo_edge_t *e2;
109
} cairo_bo_queue_event_t;
110

            
111
typedef struct _pqueue {
112
    int size, max_size;
113

            
114
    cairo_bo_event_t **elements;
115
    cairo_bo_event_t *elements_embedded[1024];
116
} pqueue_t;
117

            
118
typedef struct _cairo_bo_event_queue {
119
    cairo_freepool_t pool;
120
    pqueue_t pqueue;
121
    cairo_bo_event_t **start_events;
122
} cairo_bo_event_queue_t;
123

            
124
typedef struct _cairo_bo_sweep_line {
125
    cairo_bo_edge_t *head;
126
    cairo_bo_edge_t *stopped;
127
    int32_t current_y;
128
    cairo_bo_edge_t *current_edge;
129
} cairo_bo_sweep_line_t;
130

            
131
#if DEBUG_TRAPS
132
static void
133
dump_traps (cairo_traps_t *traps, const char *filename)
134
{
135
    FILE *file;
136
    cairo_box_t extents;
137
    int n;
138

            
139
    if (getenv ("CAIRO_DEBUG_TRAPS") == NULL)
140
	return;
141

            
142
#if 0
143
    if (traps->has_limits) {
144
	printf ("%s: limits=(%d, %d, %d, %d)\n",
145
		filename,
146
		traps->limits.p1.x, traps->limits.p1.y,
147
		traps->limits.p2.x, traps->limits.p2.y);
148
    }
149
#endif
150
    _cairo_traps_extents (traps, &extents);
151
    printf ("%s: extents=(%d, %d, %d, %d)\n",
152
	    filename,
153
	    extents.p1.x, extents.p1.y,
154
	    extents.p2.x, extents.p2.y);
155

            
156
    file = fopen (filename, "a");
157
    if (file != NULL) {
158
	for (n = 0; n < traps->num_traps; n++) {
159
	    fprintf (file, "%d %d L:(%d, %d), (%d, %d) R:(%d, %d), (%d, %d)\n",
160
		     traps->traps[n].top,
161
		     traps->traps[n].bottom,
162
		     traps->traps[n].left.p1.x,
163
		     traps->traps[n].left.p1.y,
164
		     traps->traps[n].left.p2.x,
165
		     traps->traps[n].left.p2.y,
166
		     traps->traps[n].right.p1.x,
167
		     traps->traps[n].right.p1.y,
168
		     traps->traps[n].right.p2.x,
169
		     traps->traps[n].right.p2.y);
170
	}
171
	fprintf (file, "\n");
172
	fclose (file);
173
    }
174
}
175

            
176
static void
177
dump_edges (cairo_bo_start_event_t *events,
178
	    int num_edges,
179
	    const char *filename)
180
{
181
    FILE *file;
182
    int n;
183

            
184
    if (getenv ("CAIRO_DEBUG_TRAPS") == NULL)
185
	return;
186

            
187
    file = fopen (filename, "a");
188
    if (file != NULL) {
189
	for (n = 0; n < num_edges; n++) {
190
	    fprintf (file, "(%d, %d), (%d, %d) %d %d %d\n",
191
		     events[n].edge.edge.line.p1.x,
192
		     events[n].edge.edge.line.p1.y,
193
		     events[n].edge.edge.line.p2.x,
194
		     events[n].edge.edge.line.p2.y,
195
		     events[n].edge.edge.top,
196
		     events[n].edge.edge.bottom,
197
		     events[n].edge.edge.dir);
198
	}
199
	fprintf (file, "\n");
200
	fclose (file);
201
    }
202
}
203
#endif
204

            
205
static cairo_fixed_t
206
112902
_line_compute_intersection_x_for_y (const cairo_line_t *line,
207
				    cairo_fixed_t y)
208
{
209
    cairo_fixed_t x, dy;
210

            
211
112902
    if (y == line->p1.y)
212
48186
	return line->p1.x;
213
64716
    if (y == line->p2.y)
214
48090
	return line->p2.x;
215

            
216
16626
    x = line->p1.x;
217
16626
    dy = line->p2.y - line->p1.y;
218
16626
    if (dy != 0) {
219
16626
	x += _cairo_fixed_mul_div_floor (y - line->p1.y,
220
16626
					 line->p2.x - line->p1.x,
221
					 dy);
222
    }
223

            
224
16626
    return x;
225
}
226

            
227
static inline int
228
927433
_cairo_bo_point32_compare (cairo_bo_point32_t const *a,
229
			   cairo_bo_point32_t const *b)
230
{
231
    int cmp;
232

            
233
927433
    cmp = a->y - b->y;
234
927433
    if (cmp)
235
690493
	return cmp;
236

            
237
236940
    return a->x - b->x;
238
}
239

            
240
/* Compare the slope of a to the slope of b, returning 1, 0, -1 if the
241
 * slope a is respectively greater than, equal to, or less than the
242
 * slope of b.
243
 *
244
 * For each edge, consider the direction vector formed from:
245
 *
246
 *	top -> bottom
247
 *
248
 * which is:
249
 *
250
 *	(dx, dy) = (line.p2.x - line.p1.x, line.p2.y - line.p1.y)
251
 *
252
 * We then define the slope of each edge as dx/dy, (which is the
253
 * inverse of the slope typically used in math instruction). We never
254
 * compute a slope directly as the value approaches infinity, but we
255
 * can derive a slope comparison without division as follows, (where
256
 * the ? represents our compare operator).
257
 *
258
 * 1.	   slope(a) ? slope(b)
259
 * 2.	    adx/ady ? bdx/bdy
260
 * 3.	(adx * bdy) ? (bdx * ady)
261
 *
262
 * Note that from step 2 to step 3 there is no change needed in the
263
 * sign of the result since both ady and bdy are guaranteed to be
264
 * greater than or equal to 0.
265
 *
266
 * When using this slope comparison to sort edges, some care is needed
267
 * when interpreting the results. Since the slope compare operates on
268
 * distance vectors from top to bottom it gives a correct left to
269
 * right sort for edges that have a common top point, (such as two
270
 * edges with start events at the same location). On the other hand,
271
 * the sense of the result will be exactly reversed for two edges that
272
 * have a common stop point.
273
 */
274
static inline int
275
101731
_slope_compare (const cairo_bo_edge_t *a,
276
		const cairo_bo_edge_t *b)
277
{
278
    /* XXX: We're assuming here that dx and dy will still fit in 32
279
     * bits. That's not true in general as there could be overflow. We
280
     * should prevent that before the tessellation algorithm
281
     * begins.
282
     */
283
101731
    int32_t adx = a->edge.line.p2.x - a->edge.line.p1.x;
284
101731
    int32_t bdx = b->edge.line.p2.x - b->edge.line.p1.x;
285

            
286
    /* Since the dy's are all positive by construction we can fast
287
     * path several common cases.
288
     */
289

            
290
    /* First check for vertical lines. */
291
101731
    if (adx == 0)
292
8391
	return -bdx;
293
93340
    if (bdx == 0)
294
4187
	return adx;
295

            
296
    /* Then where the two edges point in different directions wrt x. */
297
89153
    if ((adx ^ bdx) < 0)
298
38766
	return adx;
299

            
300
    /* Finally we actually need to do the general comparison. */
301
    {
302
50387
	int32_t ady = a->edge.line.p2.y - a->edge.line.p1.y;
303
50387
	int32_t bdy = b->edge.line.p2.y - b->edge.line.p1.y;
304
50387
	cairo_int64_t adx_bdy = _cairo_int32x32_64_mul (adx, bdy);
305
50387
	cairo_int64_t bdx_ady = _cairo_int32x32_64_mul (bdx, ady);
306

            
307
50387
	return _cairo_int64_cmp (adx_bdy, bdx_ady);
308
    }
309
}
310

            
311

            
312
/*
313
 * We need to compare the x-coordinate of a line for a particular y wrt to a
314
 * given x, without loss of precision.
315
 *
316
 * The x-coordinate along an edge for a given y is:
317
 *   X = A_x + (Y - A_y) * A_dx / A_dy
318
 *
319
 * So the inequality we wish to test is:
320
 *   A_x + (Y - A_y) * A_dx / A_dy ∘ X
321
 * where ∘ is our inequality operator.
322
 *
323
 * By construction, we know that A_dy (and (Y - A_y)) are
324
 * all positive, so we can rearrange it thus without causing a sign change:
325
 *   (Y - A_y) * A_dx ∘ (X - A_x) * A_dy
326
 *
327
 * Given the assumption that all the deltas fit within 32 bits, we can compute
328
 * this comparison directly using 64 bit arithmetic.
329
 *
330
 * See the similar discussion for _slope_compare() and
331
 * edges_compare_x_for_y_general().
332
 */
333
static int
334
858
edge_compare_for_y_against_x (const cairo_bo_edge_t *a,
335
			      int32_t y,
336
			      int32_t x)
337
{
338
    int32_t adx, ady;
339
    int32_t dx, dy;
340
    cairo_int64_t L, R;
341

            
342
858
    if (x < a->edge.line.p1.x && x < a->edge.line.p2.x)
343
609
	return 1;
344
249
    if (x > a->edge.line.p1.x && x > a->edge.line.p2.x)
345
72
	return -1;
346

            
347
177
    adx = a->edge.line.p2.x - a->edge.line.p1.x;
348
177
    dx = x - a->edge.line.p1.x;
349

            
350
177
    if (adx == 0)
351
	return -dx;
352
177
    if (dx == 0 || (adx ^ dx) < 0)
353
	return adx;
354

            
355
177
    dy = y - a->edge.line.p1.y;
356
177
    ady = a->edge.line.p2.y - a->edge.line.p1.y;
357

            
358
177
    L = _cairo_int32x32_64_mul (dy, adx);
359
177
    R = _cairo_int32x32_64_mul (dx, ady);
360

            
361
177
    return _cairo_int64_cmp (L, R);
362
}
363

            
364
static inline int
365
171300
_cairo_bo_sweep_line_compare_edges (const cairo_bo_sweep_line_t	*sweep_line,
366
				    const cairo_bo_edge_t	*a,
367
				    const cairo_bo_edge_t	*b)
368
{
369
    int cmp;
370

            
371
171300
    cmp = _cairo_lines_compare_at_y (&a->edge.line,
372
				    &b->edge.line,
373
171300
				    sweep_line->current_y);
374
171300
    if (cmp)
375
160326
	    return cmp;
376

            
377
    /* We've got two collinear edges now. */
378
10974
    return b->edge.bottom - a->edge.bottom;
379
}
380

            
381
static inline cairo_int64_t
382
16257
det32_64 (int32_t a, int32_t b,
383
	  int32_t c, int32_t d)
384
{
385
    /* det = a * d - b * c */
386
16257
    return _cairo_int64_sub (_cairo_int32x32_64_mul (a, d),
387
			     _cairo_int32x32_64_mul (b, c));
388
}
389

            
390
static inline cairo_int128_t
391
4314
det64x32_128 (cairo_int64_t a, int32_t       b,
392
	      cairo_int64_t c, int32_t       d)
393
{
394
    /* det = a * d - b * c */
395
4314
    return _cairo_int128_sub (_cairo_int64x32_128_mul (a, d),
396
			      _cairo_int64x32_128_mul (c, b));
397
}
398

            
399
/* Compute the intersection of two lines as defined by two edges. The
400
 * result is provided as a coordinate pair of 128-bit integers.
401
 *
402
 * Returns %CAIRO_BO_STATUS_INTERSECTION if there is an intersection or
403
 * %CAIRO_BO_STATUS_PARALLEL if the two lines are exactly parallel.
404
 */
405
static cairo_bool_t
406
4782
intersect_lines (cairo_bo_edge_t		*a,
407
		 cairo_bo_edge_t		*b,
408
		 cairo_bo_intersect_point_t	*intersection)
409
{
410
    cairo_int64_t a_det, b_det;
411

            
412
    /* XXX: We're assuming here that dx and dy will still fit in 32
413
     * bits. That's not true in general as there could be overflow. We
414
     * should prevent that before the tessellation algorithm begins.
415
     * What we're doing to mitigate this is to perform clamping in
416
     * cairo_bo_tessellate_polygon().
417
     */
418
4782
    int32_t dx1 = a->edge.line.p1.x - a->edge.line.p2.x;
419
4782
    int32_t dy1 = a->edge.line.p1.y - a->edge.line.p2.y;
420

            
421
4782
    int32_t dx2 = b->edge.line.p1.x - b->edge.line.p2.x;
422
4782
    int32_t dy2 = b->edge.line.p1.y - b->edge.line.p2.y;
423

            
424
    cairo_int64_t den_det;
425
    cairo_int64_t R;
426
    cairo_quorem64_t qr;
427

            
428
4782
    den_det = det32_64 (dx1, dy1, dx2, dy2);
429

            
430
     /* Q: Can we determine that the lines do not intersect (within range)
431
      * much more cheaply than computing the intersection point i.e. by
432
      * avoiding the division?
433
      *
434
      *   X = ax + t * adx = bx + s * bdx;
435
      *   Y = ay + t * ady = by + s * bdy;
436
      *   ∴ t * (ady*bdx - bdy*adx) = bdx * (by - ay) + bdy * (ax - bx)
437
      *   => t * L = R
438
      *
439
      * Therefore we can reject any intersection (under the criteria for
440
      * valid intersection events) if:
441
      *   L^R < 0 => t < 0, or
442
      *   L<R => t > 1
443
      *
444
      * (where top/bottom must at least extend to the line endpoints).
445
      *
446
      * A similar substitution can be performed for s, yielding:
447
      *   s * (ady*bdx - bdy*adx) = ady * (ax - bx) - adx * (ay - by)
448
      */
449
4782
    R = det32_64 (dx2, dy2,
450
4782
		  b->edge.line.p1.x - a->edge.line.p1.x,
451
4782
		  b->edge.line.p1.y - a->edge.line.p1.y);
452
4782
    if (_cairo_int64_negative (den_det)) {
453
	if (_cairo_int64_ge (den_det, R))
454
	    return FALSE;
455
    } else {
456
4782
	if (_cairo_int64_le (den_det, R))
457
2403
	    return FALSE;
458
    }
459

            
460
2379
    R = det32_64 (dy1, dx1,
461
2379
		  a->edge.line.p1.y - b->edge.line.p1.y,
462
2379
		  a->edge.line.p1.x - b->edge.line.p1.x);
463
2379
    if (_cairo_int64_negative (den_det)) {
464
	if (_cairo_int64_ge (den_det, R))
465
	    return FALSE;
466
    } else {
467
2379
	if (_cairo_int64_le (den_det, R))
468
222
	    return FALSE;
469
    }
470

            
471
    /* We now know that the two lines should intersect within range. */
472

            
473
2157
    a_det = det32_64 (a->edge.line.p1.x, a->edge.line.p1.y,
474
		      a->edge.line.p2.x, a->edge.line.p2.y);
475
2157
    b_det = det32_64 (b->edge.line.p1.x, b->edge.line.p1.y,
476
		      b->edge.line.p2.x, b->edge.line.p2.y);
477

            
478
    /* x = det (a_det, dx1, b_det, dx2) / den_det */
479
2157
    qr = _cairo_int_96by64_32x64_divrem (det64x32_128 (a_det, dx1,
480
						       b_det, dx2),
481
					 den_det);
482
2157
    if (_cairo_int64_eq (qr.rem, den_det))
483
	return FALSE;
484
#if 0
485
    intersection->x.exactness = _cairo_int64_is_zero (qr.rem) ? EXACT : INEXACT;
486
#else
487
2157
    intersection->x.exactness = EXACT;
488
2157
    if (! _cairo_int64_is_zero (qr.rem)) {
489
798
	if (_cairo_int64_negative (den_det) ^ _cairo_int64_negative (qr.rem))
490
	    qr.rem = _cairo_int64_negate (qr.rem);
491
798
	qr.rem = _cairo_int64_mul (qr.rem, _cairo_int32_to_int64 (2));
492
798
	if (_cairo_int64_ge (qr.rem, den_det)) {
493
480
	    qr.quo = _cairo_int64_add (qr.quo,
494
				       _cairo_int32_to_int64 (_cairo_int64_negative (qr.quo) ? -1 : 1));
495
	} else
496
318
	    intersection->x.exactness = INEXACT;
497
    }
498
#endif
499
2157
    intersection->x.ordinate = _cairo_int64_to_int32 (qr.quo);
500

            
501
    /* y = det (a_det, dy1, b_det, dy2) / den_det */
502
2157
    qr = _cairo_int_96by64_32x64_divrem (det64x32_128 (a_det, dy1,
503
						       b_det, dy2),
504
					 den_det);
505
2157
    if (_cairo_int64_eq (qr.rem, den_det))
506
	return FALSE;
507
#if 0
508
    intersection->y.exactness = _cairo_int64_is_zero (qr.rem) ? EXACT : INEXACT;
509
#else
510
2157
    intersection->y.exactness = EXACT;
511
2157
    if (! _cairo_int64_is_zero (qr.rem)) {
512
1236
	if (_cairo_int64_negative (den_det) ^ _cairo_int64_negative (qr.rem))
513
432
	    qr.rem = _cairo_int64_negate (qr.rem);
514
1236
	qr.rem = _cairo_int64_mul (qr.rem, _cairo_int32_to_int64 (2));
515
1236
	if (_cairo_int64_ge (qr.rem, den_det)) {
516
495
	    qr.quo = _cairo_int64_add (qr.quo,
517
				       _cairo_int32_to_int64 (_cairo_int64_negative (qr.quo) ? -1 : 1));
518
	} else
519
741
	    intersection->y.exactness = INEXACT;
520
    }
521
#endif
522
2157
    intersection->y.ordinate = _cairo_int64_to_int32 (qr.quo);
523

            
524
2157
    return TRUE;
525
}
526

            
527
static int
528
7044
_cairo_bo_intersect_ordinate_32_compare (cairo_bo_intersect_ordinate_t	a,
529
					 int32_t			b)
530
{
531
    /* First compare the quotient */
532
7044
    if (a.ordinate > b)
533
3771
	return +1;
534
3273
    if (a.ordinate < b)
535
2121
	return -1;
536
    /* With quotient identical, if remainder is 0 then compare equal */
537
    /* Otherwise, the non-zero remainder makes a > b */
538
1152
    return INEXACT == a.exactness;
539
}
540

            
541
/* Does the given edge contain the given point. The point must already
542
 * be known to be contained within the line determined by the edge,
543
 * (most likely the point results from an intersection of this edge
544
 * with another).
545
 *
546
 * If we had exact arithmetic, then this function would simply be a
547
 * matter of examining whether the y value of the point lies within
548
 * the range of y values of the edge. But since intersection points
549
 * are not exact due to being rounded to the nearest integer within
550
 * the available precision, we must also examine the x value of the
551
 * point.
552
 *
553
 * The definition of "contains" here is that the given intersection
554
 * point will be seen by the sweep line after the start event for the
555
 * given edge and before the stop event for the edge. See the comments
556
 * in the implementation for more details.
557
 */
558
static cairo_bool_t
559
3333
_cairo_bo_edge_contains_intersect_point (cairo_bo_edge_t		*edge,
560
					 cairo_bo_intersect_point_t	*point)
561
{
562
    int cmp_top, cmp_bottom;
563

            
564
    /* XXX: When running the actual algorithm, we don't actually need to
565
     * compare against edge->top at all here, since any intersection above
566
     * top is eliminated early via a slope comparison. We're leaving these
567
     * here for now only for the sake of the quadratic-time intersection
568
     * finder which needs them.
569
     */
570

            
571
3333
    cmp_top = _cairo_bo_intersect_ordinate_32_compare (point->y,
572
						       edge->edge.top);
573
3333
    cmp_bottom = _cairo_bo_intersect_ordinate_32_compare (point->y,
574
							  edge->edge.bottom);
575

            
576
3333
    if (cmp_top < 0 || cmp_bottom > 0)
577
    {
578
897
	return FALSE;
579
    }
580

            
581
2436
    if (cmp_top > 0 && cmp_bottom < 0)
582
    {
583
2058
	return TRUE;
584
    }
585

            
586
    /* At this stage, the point lies on the same y value as either
587
     * edge->top or edge->bottom, so we have to examine the x value in
588
     * order to properly determine containment. */
589

            
590
    /* If the y value of the point is the same as the y value of the
591
     * top of the edge, then the x value of the point must be greater
592
     * to be considered as inside the edge. Similarly, if the y value
593
     * of the point is the same as the y value of the bottom of the
594
     * edge, then the x value of the point must be less to be
595
     * considered as inside. */
596

            
597
378
    if (cmp_top == 0) {
598
	cairo_fixed_t top_x;
599

            
600
60
	top_x = _line_compute_intersection_x_for_y (&edge->edge.line,
601
						    edge->edge.top);
602
60
	return _cairo_bo_intersect_ordinate_32_compare (point->x, top_x) > 0;
603
    } else { /* cmp_bottom == 0 */
604
	cairo_fixed_t bot_x;
605

            
606
318
	bot_x = _line_compute_intersection_x_for_y (&edge->edge.line,
607
						    edge->edge.bottom);
608
318
	return _cairo_bo_intersect_ordinate_32_compare (point->x, bot_x) < 0;
609
    }
610
}
611

            
612
/* Compute the intersection of two edges. The result is provided as a
613
 * coordinate pair of 128-bit integers.
614
 *
615
 * Returns %CAIRO_BO_STATUS_INTERSECTION if there is an intersection
616
 * that is within both edges, %CAIRO_BO_STATUS_NO_INTERSECTION if the
617
 * intersection of the lines defined by the edges occurs outside of
618
 * one or both edges, and %CAIRO_BO_STATUS_PARALLEL if the two edges
619
 * are exactly parallel.
620
 *
621
 * Note that when determining if a candidate intersection is "inside"
622
 * an edge, we consider both the infinitesimal shortening and the
623
 * infinitesimal tilt rules described by John Hobby. Specifically, if
624
 * the intersection is exactly the same as an edge point, it is
625
 * effectively outside (no intersection is returned). Also, if the
626
 * intersection point has the same
627
 */
628
static cairo_bool_t
629
4782
_cairo_bo_edge_intersect (cairo_bo_edge_t	*a,
630
			  cairo_bo_edge_t	*b,
631
			  cairo_bo_point32_t	*intersection)
632
{
633
    cairo_bo_intersect_point_t quorem;
634

            
635
4782
    if (! intersect_lines (a, b, &quorem))
636
2625
	return FALSE;
637

            
638
2157
    if (! _cairo_bo_edge_contains_intersect_point (a, &quorem))
639
981
	return FALSE;
640

            
641
1176
    if (! _cairo_bo_edge_contains_intersect_point (b, &quorem))
642
243
	return FALSE;
643

            
644
    /* Now that we've correctly compared the intersection point and
645
     * determined that it lies within the edge, then we know that we
646
     * no longer need any more bits of storage for the intersection
647
     * than we do for our edge coordinates. We also no longer need the
648
     * remainder from the division. */
649
933
    intersection->x = quorem.x.ordinate;
650
933
    intersection->y = quorem.y.ordinate;
651

            
652
933
    return TRUE;
653
}
654

            
655
static inline int
656
927433
cairo_bo_event_compare (const cairo_bo_event_t *a,
657
			const cairo_bo_event_t *b)
658
{
659
    int cmp;
660

            
661
927433
    cmp = _cairo_bo_point32_compare (&a->point, &b->point);
662
927433
    if (cmp)
663
847605
	return cmp;
664

            
665
79828
    cmp = a->type - b->type;
666
79828
    if (cmp)
667
48765
	return cmp;
668

            
669
31063
    return a - b;
670
}
671

            
672
static inline void
673
1311
_pqueue_init (pqueue_t *pq)
674
{
675
1311
    pq->max_size = ARRAY_LENGTH (pq->elements_embedded);
676
1311
    pq->size = 0;
677

            
678
1311
    pq->elements = pq->elements_embedded;
679
1311
}
680

            
681
static inline void
682
1311
_pqueue_fini (pqueue_t *pq)
683
{
684
1311
    if (pq->elements != pq->elements_embedded)
685
	free (pq->elements);
686
1311
}
687

            
688
static cairo_status_t
689
_pqueue_grow (pqueue_t *pq)
690
{
691
    cairo_bo_event_t **new_elements;
692
    pq->max_size *= 2;
693

            
694
    if (pq->elements == pq->elements_embedded) {
695
	new_elements = _cairo_malloc_ab (pq->max_size,
696
					 sizeof (cairo_bo_event_t *));
697
	if (unlikely (new_elements == NULL))
698
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
699

            
700
	memcpy (new_elements, pq->elements_embedded,
701
		sizeof (pq->elements_embedded));
702
    } else {
703
	new_elements = _cairo_realloc_ab (pq->elements,
704
					  pq->max_size,
705
					  sizeof (cairo_bo_event_t *));
706
	if (unlikely (new_elements == NULL))
707
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
708
    }
709

            
710
    pq->elements = new_elements;
711
    return CAIRO_STATUS_SUCCESS;
712
}
713

            
714
static inline cairo_status_t
715
57195
_pqueue_push (pqueue_t *pq, cairo_bo_event_t *event)
716
{
717
    cairo_bo_event_t **elements;
718
    int i, parent;
719

            
720
57195
    if (unlikely (pq->size + 1 == pq->max_size)) {
721
	cairo_status_t status;
722

            
723
	status = _pqueue_grow (pq);
724
	if (unlikely (status))
725
	    return status;
726
    }
727

            
728
57195
    elements = pq->elements;
729

            
730
57195
    for (i = ++pq->size;
731
151952
	 i != PQ_FIRST_ENTRY &&
732
73269
	 cairo_bo_event_compare (event,
733
73269
				 elements[parent = PQ_PARENT_INDEX (i)]) < 0;
734
21488
	 i = parent)
735
    {
736
21488
	elements[i] = elements[parent];
737
    }
738

            
739
57195
    elements[i] = event;
740

            
741
57195
    return CAIRO_STATUS_SUCCESS;
742
}
743

            
744
static inline void
745
57195
_pqueue_pop (pqueue_t *pq)
746
{
747
57195
    cairo_bo_event_t **elements = pq->elements;
748
    cairo_bo_event_t *tail;
749
    int child, i;
750

            
751
57195
    tail = elements[pq->size--];
752
57195
    if (pq->size == 0) {
753
1377
	elements[PQ_FIRST_ENTRY] = NULL;
754
1377
	return;
755
    }
756

            
757
55818
    for (i = PQ_FIRST_ENTRY;
758
123558
	 (child = PQ_LEFT_CHILD_INDEX (i)) <= pq->size;
759
67740
	 i = child)
760
    {
761
141394
	if (child != pq->size &&
762
68200
	    cairo_bo_event_compare (elements[child+1],
763
68200
				    elements[child]) < 0)
764
	{
765
29139
	    child++;
766
	}
767

            
768
73194
	if (cairo_bo_event_compare (elements[child], tail) >= 0)
769
5454
	    break;
770

            
771
67740
	elements[i] = elements[child];
772
    }
773
55818
    elements[i] = tail;
774
}
775

            
776
static inline cairo_status_t
777
57195
_cairo_bo_event_queue_insert (cairo_bo_event_queue_t	*queue,
778
			      cairo_bo_event_type_t	 type,
779
			      cairo_bo_edge_t		*e1,
780
			      cairo_bo_edge_t		*e2,
781
			      const cairo_point_t	 *point)
782
{
783
    cairo_bo_queue_event_t *event;
784

            
785
57195
    event = _cairo_freepool_alloc (&queue->pool);
786
57195
    if (unlikely (event == NULL))
787
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
788

            
789
57195
    event->type = type;
790
57195
    event->e1 = e1;
791
57195
    event->e2 = e2;
792
57195
    event->point = *point;
793

            
794
57195
    return _pqueue_push (&queue->pqueue, (cairo_bo_event_t *) event);
795
}
796

            
797
static void
798
57195
_cairo_bo_event_queue_delete (cairo_bo_event_queue_t *queue,
799
			      cairo_bo_event_t	     *event)
800
{
801
57195
    _cairo_freepool_free (&queue->pool, event);
802
57195
}
803

            
804
static cairo_bo_event_t *
805
114768
_cairo_bo_event_dequeue (cairo_bo_event_queue_t *event_queue)
806
{
807
    cairo_bo_event_t *event, *cmp;
808

            
809
114768
    event = event_queue->pqueue.elements[PQ_FIRST_ENTRY];
810
114768
    cmp = *event_queue->start_events;
811
114768
    if (event == NULL ||
812
108612
	(cmp != NULL && cairo_bo_event_compare (cmp, event) < 0))
813
    {
814
57573
	event = cmp;
815
57573
	event_queue->start_events++;
816
    }
817
    else
818
    {
819
57195
	_pqueue_pop (&event_queue->pqueue);
820
    }
821

            
822
114768
    return event;
823
}
824

            
825
619485
CAIRO_COMBSORT_DECLARE (_cairo_bo_event_queue_sort,
826
			cairo_bo_event_t *,
827
			cairo_bo_event_compare)
828

            
829
static void
830
1311
_cairo_bo_event_queue_init (cairo_bo_event_queue_t	 *event_queue,
831
			    cairo_bo_event_t		**start_events,
832
			    int				  num_events)
833
{
834
1311
    event_queue->start_events = start_events;
835

            
836
1311
    _cairo_freepool_init (&event_queue->pool,
837
			  sizeof (cairo_bo_queue_event_t));
838
1311
    _pqueue_init (&event_queue->pqueue);
839
1311
    event_queue->pqueue.elements[PQ_FIRST_ENTRY] = NULL;
840
1311
}
841

            
842
static cairo_status_t
843
56262
_cairo_bo_event_queue_insert_stop (cairo_bo_event_queue_t	*event_queue,
844
				   cairo_bo_edge_t		*edge)
845
{
846
    cairo_bo_point32_t point;
847

            
848
56262
    point.y = edge->edge.bottom;
849
56262
    point.x = _line_compute_intersection_x_for_y (&edge->edge.line,
850
						  point.y);
851
56262
    return _cairo_bo_event_queue_insert (event_queue,
852
					 CAIRO_BO_EVENT_TYPE_STOP,
853
					 edge, NULL,
854
					 &point);
855
}
856

            
857
static void
858
1311
_cairo_bo_event_queue_fini (cairo_bo_event_queue_t *event_queue)
859
{
860
1311
    _pqueue_fini (&event_queue->pqueue);
861
1311
    _cairo_freepool_fini (&event_queue->pool);
862
1311
}
863

            
864
static inline cairo_status_t
865
107754
_cairo_bo_event_queue_insert_if_intersect_below_current_y (cairo_bo_event_queue_t	*event_queue,
866
							   cairo_bo_edge_t	*left,
867
							   cairo_bo_edge_t *right)
868
{
869
    cairo_bo_point32_t intersection;
870

            
871
107754
    if (MAX (left->edge.line.p1.x, left->edge.line.p2.x) <=
872
107754
	MIN (right->edge.line.p1.x, right->edge.line.p2.x))
873
95120
	return CAIRO_STATUS_SUCCESS;
874

            
875
12634
    if (cairo_lines_equal (&left->edge.line, &right->edge.line))
876
3423
	return CAIRO_STATUS_SUCCESS;
877

            
878
    /* The names "left" and "right" here are correct descriptions of
879
     * the order of the two edges within the active edge list. So if a
880
     * slope comparison also puts left less than right, then we know
881
     * that the intersection of these two segments has already
882
     * occurred before the current sweep line position. */
883
9211
    if (_slope_compare (left, right) <= 0)
884
4429
	return CAIRO_STATUS_SUCCESS;
885

            
886
4782
    if (! _cairo_bo_edge_intersect (left, right, &intersection))
887
3849
	return CAIRO_STATUS_SUCCESS;
888

            
889
933
    return _cairo_bo_event_queue_insert (event_queue,
890
					 CAIRO_BO_EVENT_TYPE_INTERSECTION,
891
					 left, right,
892
					 &intersection);
893
}
894

            
895
static void
896
1311
_cairo_bo_sweep_line_init (cairo_bo_sweep_line_t *sweep_line)
897
{
898
1311
    sweep_line->head = NULL;
899
1311
    sweep_line->stopped = NULL;
900
1311
    sweep_line->current_y = INT32_MIN;
901
1311
    sweep_line->current_edge = NULL;
902
1311
}
903

            
904
static void
905
56262
_cairo_bo_sweep_line_insert (cairo_bo_sweep_line_t	*sweep_line,
906
			     cairo_bo_edge_t		*edge)
907
{
908
56262
    if (sweep_line->current_edge != NULL) {
909
	cairo_bo_edge_t *prev, *next;
910
	int cmp;
911

            
912
54885
	cmp = _cairo_bo_sweep_line_compare_edges (sweep_line,
913
54885
						  sweep_line->current_edge,
914
						  edge);
915
54885
	if (cmp < 0) {
916
29694
	    prev = sweep_line->current_edge;
917
29694
	    next = prev->next;
918
129687
	    while (next != NULL &&
919
57759
		   _cairo_bo_sweep_line_compare_edges (sweep_line,
920
						       next, edge) < 0)
921
	    {
922
42234
		prev = next, next = prev->next;
923
	    }
924

            
925
29694
	    prev->next = edge;
926
29694
	    edge->prev = prev;
927
29694
	    edge->next = next;
928
29694
	    if (next != NULL)
929
15525
		next->prev = edge;
930
25191
	} else if (cmp > 0) {
931
21201
	    next = sweep_line->current_edge;
932
21201
	    prev = next->prev;
933
130902
	    while (prev != NULL &&
934
58656
		   _cairo_bo_sweep_line_compare_edges (sweep_line,
935
						       prev, edge) > 0)
936
	    {
937
51045
		next = prev, prev = next->prev;
938
	    }
939

            
940
21201
	    next->prev = edge;
941
21201
	    edge->next = next;
942
21201
	    edge->prev = prev;
943
21201
	    if (prev != NULL)
944
7611
		prev->next = edge;
945
	    else
946
13590
		sweep_line->head = edge;
947
	} else {
948
3990
	    prev = sweep_line->current_edge;
949
3990
	    edge->prev = prev;
950
3990
	    edge->next = prev->next;
951
3990
	    if (prev->next != NULL)
952
2538
		prev->next->prev = edge;
953
3990
	    prev->next = edge;
954
	}
955
    } else {
956
1377
	sweep_line->head = edge;
957
1377
	edge->next = NULL;
958
    }
959

            
960
56262
    sweep_line->current_edge = edge;
961
56262
}
962

            
963
static void
964
56262
_cairo_bo_sweep_line_delete (cairo_bo_sweep_line_t	*sweep_line,
965
			     cairo_bo_edge_t	*edge)
966
{
967
56262
    if (edge->prev != NULL)
968
40551
	edge->prev->next = edge->next;
969
    else
970
15711
	sweep_line->head = edge->next;
971

            
972
56262
    if (edge->next != NULL)
973
39852
	edge->next->prev = edge->prev;
974

            
975
56262
    if (sweep_line->current_edge == edge)
976
5558
	sweep_line->current_edge = edge->prev ? edge->prev : edge->next;
977
56262
}
978

            
979
static void
980
885
_cairo_bo_sweep_line_swap (cairo_bo_sweep_line_t	*sweep_line,
981
			   cairo_bo_edge_t		*left,
982
			   cairo_bo_edge_t		*right)
983
{
984
885
    if (left->prev != NULL)
985
843
	left->prev->next = right;
986
    else
987
42
	sweep_line->head = right;
988

            
989
885
    if (right->next != NULL)
990
834
	right->next->prev = left;
991

            
992
885
    left->next = right->next;
993
885
    right->next = left;
994

            
995
885
    right->prev = left->prev;
996
885
    left->prev = right;
997
885
}
998

            
999
#if DEBUG_PRINT_STATE
static void
_cairo_bo_edge_print (cairo_bo_edge_t *edge)
{
    printf ("(0x%x, 0x%x)-(0x%x, 0x%x)",
	    edge->edge.line.p1.x, edge->edge.line.p1.y,
	    edge->edge.line.p2.x, edge->edge.line.p2.y);
}
static void
_cairo_bo_event_print (cairo_bo_event_t *event)
{
    switch (event->type) {
    case CAIRO_BO_EVENT_TYPE_START:
	printf ("Start: ");
	break;
    case CAIRO_BO_EVENT_TYPE_STOP:
	printf ("Stop: ");
	break;
    case CAIRO_BO_EVENT_TYPE_INTERSECTION:
	printf ("Intersection: ");
	break;
    }
    printf ("(%d, %d)\t", event->point.x, event->point.y);
    _cairo_bo_edge_print (event->e1);
    if (event->type == CAIRO_BO_EVENT_TYPE_INTERSECTION) {
	printf (" X ");
	_cairo_bo_edge_print (event->e2);
    }
    printf ("\n");
}
static void
_cairo_bo_event_queue_print (cairo_bo_event_queue_t *event_queue)
{
    /* XXX: fixme to print the start/stop array too. */
    printf ("Event queue:\n");
}
static void
_cairo_bo_sweep_line_print (cairo_bo_sweep_line_t *sweep_line)
{
    cairo_bool_t first = TRUE;
    cairo_bo_edge_t *edge;
    printf ("Sweep line from edge list: ");
    first = TRUE;
    for (edge = sweep_line->head;
	 edge;
	 edge = edge->next)
    {
	if (!first)
	    printf (", ");
	_cairo_bo_edge_print (edge);
	first = FALSE;
    }
    printf ("\n");
}
static void
print_state (const char			*msg,
	     cairo_bo_event_t		*event,
	     cairo_bo_event_queue_t	*event_queue,
	     cairo_bo_sweep_line_t	*sweep_line)
{
    printf ("%s ", msg);
    _cairo_bo_event_print (event);
    _cairo_bo_event_queue_print (event_queue);
    _cairo_bo_sweep_line_print (sweep_line);
    printf ("\n");
}
#endif
#if DEBUG_EVENTS
static void CAIRO_PRINTF_FORMAT (1, 2)
event_log (const char *fmt, ...)
{
    FILE *file;
    if (getenv ("CAIRO_DEBUG_EVENTS") == NULL)
	return;
    file = fopen ("bo-events.txt", "a");
    if (file != NULL) {
	va_list ap;
	va_start (ap, fmt);
	vfprintf (file, fmt, ap);
	va_end (ap);
	fclose (file);
    }
}
#endif
#define HAS_COLINEAR(a, b) ((cairo_bo_edge_t *)(((uintptr_t)(a))&~1) == (b))
#define IS_COLINEAR(e) (((uintptr_t)(e))&1)
#define MARK_COLINEAR(e, v) ((cairo_bo_edge_t *)(((uintptr_t)(e))|(v)))
static inline cairo_bool_t
153081
edges_colinear (cairo_bo_edge_t *a, const cairo_bo_edge_t *b)
{
    unsigned p;
153081
    if (HAS_COLINEAR(a->colinear, b))
52101
	return IS_COLINEAR(a->colinear);
100980
    if (HAS_COLINEAR(b->colinear, a)) {
153
	p = IS_COLINEAR(b->colinear);
153
	a->colinear = MARK_COLINEAR(b, p);
153
	return p;
    }
100827
    p = 0;
100827
    p |= (a->edge.line.p1.x == b->edge.line.p1.x) << 0;
100827
    p |= (a->edge.line.p1.y == b->edge.line.p1.y) << 1;
100827
    p |= (a->edge.line.p2.x == b->edge.line.p2.x) << 3;
100827
    p |= (a->edge.line.p2.y == b->edge.line.p2.y) << 4;
100827
    if (p == ((1 << 0) | (1 << 1) | (1 << 3) | (1 << 4))) {
8307
	a->colinear = MARK_COLINEAR(b, 1);
8307
	return TRUE;
    }
92520
    if (_slope_compare (a, b)) {
89013
	a->colinear = MARK_COLINEAR(b, 0);
89013
	return FALSE;
    }
    /* The choice of y is not truly arbitrary since we must guarantee that it
     * is greater than the start of either line.
     */
3507
    if (p != 0) {
	/* colinear if either end-point are coincident */
2649
	p = (((p >> 1) & p) & 5) != 0;
858
    } else if (a->edge.line.p1.y < b->edge.line.p1.y) {
177
	p = edge_compare_for_y_against_x (b,
					  a->edge.line.p1.y,
177
					  a->edge.line.p1.x) == 0;
    } else {
1362
	p = edge_compare_for_y_against_x (a,
681
					  b->edge.line.p1.y,
681
					  b->edge.line.p1.x) == 0;
    }
3507
    a->colinear = MARK_COLINEAR(b, p);
3507
    return p;
}
/* Adds the trapezoid, if any, of the left edge to the #cairo_traps_t */
static void
30111
_cairo_bo_edge_end_trap (cairo_bo_edge_t	*left,
			 int32_t		 bot,
			 cairo_traps_t	        *traps)
{
30111
    cairo_bo_trap_t *trap = &left->deferred_trap;
    /* Only emit (trivial) non-degenerate trapezoids with positive height. */
30111
    if (likely (trap->top < bot)) {
30111
	_cairo_traps_add_trap (traps,
			       trap->top, bot,
30111
			       &left->edge.line, &trap->right->edge.line);
#if DEBUG_PRINT_STATE
	printf ("Deferred trap: left=(%x, %x)-(%x,%x) "
		"right=(%x,%x)-(%x,%x) top=%x, bot=%x\n",
		left->edge.line.p1.x, left->edge.line.p1.y,
		left->edge.line.p2.x, left->edge.line.p2.y,
		trap->right->edge.line.p1.x, trap->right->edge.line.p1.y,
		trap->right->edge.line.p2.x, trap->right->edge.line.p2.y,
		trap->top, bot);
#endif
#if DEBUG_EVENTS
	event_log ("end trap: %lu %lu %d %d\n",
		   (long) left,
		   (long) trap->right,
		   trap->top,
		   bot);
#endif
    }
30111
    trap->right = NULL;
30111
}
/* Start a new trapezoid at the given top y coordinate, whose edges
 * are `edge' and `edge->next'. If `edge' already has a trapezoid,
 * then either add it to the traps in `traps', if the trapezoid's
 * right edge differs from `edge->next', or do nothing if the new
 * trapezoid would be a continuation of the existing one. */
static inline void
89724
_cairo_bo_edge_start_or_continue_trap (cairo_bo_edge_t	*left,
				       cairo_bo_edge_t  *right,
				       int               top,
				       cairo_traps_t	*traps)
{
89724
    if (left->deferred_trap.right == right)
53121
	return;
36603
    assert (right);
36603
    if (left->deferred_trap.right != NULL) {
10458
	if (edges_colinear (left->deferred_trap.right, right))
	{
	    /* continuation on right, so just swap edges */
393
	    left->deferred_trap.right = right;
393
	    return;
	}
10065
	_cairo_bo_edge_end_trap (left, top, traps);
    }
36210
    if (! edges_colinear (left, right)) {
30111
	left->deferred_trap.top = top;
30111
	left->deferred_trap.right = right;
#if DEBUG_EVENTS
	event_log ("begin trap: %lu %lu %d\n",
		   (long) left,
		   (long) right,
		   top);
#endif
    }
}
static inline void
29613
_active_edges_to_traps (cairo_bo_edge_t	*pos,
			int32_t		 top,
			unsigned	 mask,
			cairo_traps_t        *traps)
{
    cairo_bo_edge_t *left;
    int in_out;
#if DEBUG_PRINT_STATE
    printf ("Processing active edges for %x\n", top);
#endif
29613
    in_out = 0;
29613
    left = pos;
243177
    while (pos != NULL) {
213564
	if (pos != left && pos->deferred_trap.right) {
	    /* XXX It shouldn't be possible to here with 2 deferred traps
	     * on colinear edges... See bug-bo-rictoz.
	     */
981
	    if (left->deferred_trap.right == NULL &&
372
		edges_colinear (left, pos))
	    {
		/* continuation on left */
96
		left->deferred_trap = pos->deferred_trap;
96
		pos->deferred_trap.right = NULL;
	    }
	    else
	    {
513
		_cairo_bo_edge_end_trap (pos, top, traps);
	    }
	}
213564
	in_out += pos->edge.dir;
213564
	if ((in_out & mask) == 0) {
	    /* skip co-linear edges */
97242
	    if (pos->next == NULL || ! edges_colinear (pos, pos->next)) {
89724
		_cairo_bo_edge_start_or_continue_trap (left, pos, top, traps);
89724
		left = pos->next;
	    }
	}
213564
	pos = pos->next;
    }
29613
}
/* Execute a single pass of the Bentley-Ottmann algorithm on edges,
 * generating trapezoids according to the fill_rule and appending them
 * to traps. */
static cairo_status_t
1311
_cairo_bentley_ottmann_tessellate_bo_edges (cairo_bo_event_t   **start_events,
					    int			 num_events,
					    unsigned		 fill_rule,
					    cairo_traps_t	*traps,
					    int			*num_intersections)
{
    cairo_status_t status;
1311
    int intersection_count = 0;
    cairo_bo_event_queue_t event_queue;
    cairo_bo_sweep_line_t sweep_line;
    cairo_bo_event_t *event;
    cairo_bo_edge_t *left, *right;
    cairo_bo_edge_t *e1, *e2;
    /* convert the fill_rule into a winding mask */
1311
    if (fill_rule == CAIRO_FILL_RULE_WINDING)
1014
	fill_rule = (unsigned) -1;
    else
297
	fill_rule = 1;
#if DEBUG_EVENTS
    {
	int i;
	for (i = 0; i < num_events; i++) {
	    cairo_bo_start_event_t *event =
		((cairo_bo_start_event_t **) start_events)[i];
	    event_log ("edge: %lu (%d, %d) (%d, %d) (%d, %d) %d\n",
		       (long) &events[i].edge,
		       event->edge.edge.line.p1.x,
		       event->edge.edge.line.p1.y,
		       event->edge.edge.line.p2.x,
		       event->edge.edge.line.p2.y,
		       event->edge.top,
		       event->edge.bottom,
		       event->edge.edge.dir);
	}
    }
#endif
1311
    _cairo_bo_event_queue_init (&event_queue, start_events, num_events);
1311
    _cairo_bo_sweep_line_init (&sweep_line);
116079
    while ((event = _cairo_bo_event_dequeue (&event_queue))) {
113457
	if (event->point.y != sweep_line.current_y) {
47928
	    for (e1 = sweep_line.stopped; e1; e1 = e1->next) {
18315
		if (e1->deferred_trap.right != NULL) {
18315
		    _cairo_bo_edge_end_trap (e1,
					     e1->edge.bottom,
					     traps);
		}
	    }
29613
	    sweep_line.stopped = NULL;
29613
	    _active_edges_to_traps (sweep_line.head,
				    sweep_line.current_y,
				    fill_rule, traps);
29613
	    sweep_line.current_y = event->point.y;
	}
#if DEBUG_EVENTS
	event_log ("event: %d (%ld, %ld) %lu, %lu\n",
		   event->type,
		   (long) event->point.x,
		   (long) event->point.y,
		   (long) event->e1,
		   (long) event->e2);
#endif
113457
	switch (event->type) {
56262
	case CAIRO_BO_EVENT_TYPE_START:
56262
	    e1 = &((cairo_bo_start_event_t *) event)->edge;
56262
	    _cairo_bo_sweep_line_insert (&sweep_line, e1);
56262
	    status = _cairo_bo_event_queue_insert_stop (&event_queue, e1);
56262
	    if (unlikely (status))
		goto unwind;
	    /* check to see if this is a continuation of a stopped edge */
	    /* XXX change to an infinitesimal lengthening rule */
91476
	    for (left = sweep_line.stopped; left; left = left->next) {
74130
		if (e1->edge.top <= left->edge.bottom &&
37065
		    edges_colinear (e1, left))
		{
1851
		    e1->deferred_trap = left->deferred_trap;
1851
		    if (left->prev != NULL)
			left->prev = left->next;
		    else
1851
			sweep_line.stopped = left->next;
1851
		    if (left->next != NULL)
489
			left->next->prev = left->prev;
1851
		    break;
		}
	    }
56262
	    left = e1->prev;
56262
	    right = e1->next;
56262
	    if (left != NULL) {
41295
		status = _cairo_bo_event_queue_insert_if_intersect_below_current_y (&event_queue, left, e1);
41295
		if (unlikely (status))
		    goto unwind;
	    }
56262
	    if (right != NULL) {
39264
		status = _cairo_bo_event_queue_insert_if_intersect_below_current_y (&event_queue, e1, right);
39264
		if (unlikely (status))
		    goto unwind;
	    }
56262
	    break;
56262
	case CAIRO_BO_EVENT_TYPE_STOP:
56262
	    e1 = ((cairo_bo_queue_event_t *) event)->e1;
56262
	    _cairo_bo_event_queue_delete (&event_queue, event);
56262
	    left = e1->prev;
56262
	    right = e1->next;
56262
	    _cairo_bo_sweep_line_delete (&sweep_line, e1);
	    /* first, check to see if we have a continuation via a fresh edge */
56262
	    if (e1->deferred_trap.right != NULL) {
21384
		e1->next = sweep_line.stopped;
21384
		if (sweep_line.stopped != NULL)
2013
		    sweep_line.stopped->prev = e1;
21384
		sweep_line.stopped = e1;
21384
		e1->prev = NULL;
	    }
56262
	    if (left != NULL && right != NULL) {
25518
		status = _cairo_bo_event_queue_insert_if_intersect_below_current_y (&event_queue, left, right);
25518
		if (unlikely (status))
		    goto unwind;
	    }
56262
	    break;
933
	case CAIRO_BO_EVENT_TYPE_INTERSECTION:
933
	    e1 = ((cairo_bo_queue_event_t *) event)->e1;
933
	    e2 = ((cairo_bo_queue_event_t *) event)->e2;
933
	    _cairo_bo_event_queue_delete (&event_queue, event);
	    /* skip this intersection if its edges are not adjacent */
933
	    if (e2 != e1->next)
48
		break;
885
	    intersection_count++;
885
	    left = e1->prev;
885
	    right = e2->next;
885
	    _cairo_bo_sweep_line_swap (&sweep_line, e1, e2);
	    /* after the swap e2 is left of e1 */
885
	    if (left != NULL) {
843
		status = _cairo_bo_event_queue_insert_if_intersect_below_current_y (&event_queue, left, e2);
843
		if (unlikely (status))
		    goto unwind;
	    }
885
	    if (right != NULL) {
834
		status = _cairo_bo_event_queue_insert_if_intersect_below_current_y (&event_queue, e1, right);
834
		if (unlikely (status))
		    goto unwind;
	    }
885
	    break;
	}
    }
1311
    *num_intersections = intersection_count;
2529
    for (e1 = sweep_line.stopped; e1; e1 = e1->next) {
1218
	if (e1->deferred_trap.right != NULL) {
1218
	    _cairo_bo_edge_end_trap (e1, e1->edge.bottom, traps);
	}
    }
1311
    status = traps->status;
1311
 unwind:
1311
    _cairo_bo_event_queue_fini (&event_queue);
#if DEBUG_EVENTS
    event_log ("\n");
#endif
1311
    return status;
}
cairo_status_t
1311
_cairo_bentley_ottmann_tessellate_polygon (cairo_traps_t	 *traps,
					   const cairo_polygon_t *polygon,
					   cairo_fill_rule_t	  fill_rule)
{
    int intersections;
    cairo_bo_start_event_t stack_events[CAIRO_STACK_ARRAY_LENGTH (cairo_bo_start_event_t)];
    cairo_bo_start_event_t *events;
    cairo_bo_event_t *stack_event_ptrs[ARRAY_LENGTH (stack_events) + 1];
    cairo_bo_event_t **event_ptrs;
    cairo_bo_start_event_t *stack_event_y[64];
1311
    cairo_bo_start_event_t **event_y = NULL;
    int i, num_events, y, ymin, ymax;
    cairo_status_t status;
1311
    num_events = polygon->num_edges;
1311
    if (unlikely (0 == num_events))
	return CAIRO_STATUS_SUCCESS;
1311
    if (polygon->num_limits) {
138
	ymin = _cairo_fixed_integer_floor (polygon->limit.p1.y);
138
	ymax = _cairo_fixed_integer_ceil (polygon->limit.p2.y) - ymin;
138
	if (ymax > 64) {
	    event_y = _cairo_malloc_ab(sizeof (cairo_bo_event_t*), ymax);
	    if (unlikely (event_y == NULL))
		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
	} else {
138
	    event_y = stack_event_y;
	}
138
	memset (event_y, 0, ymax * sizeof(cairo_bo_event_t *));
    }
1311
    events = stack_events;
1311
    event_ptrs = stack_event_ptrs;
1311
    if (num_events > ARRAY_LENGTH (stack_events)) {
549
	events = _cairo_malloc_ab_plus_c (num_events,
					  sizeof (cairo_bo_start_event_t) +
					  sizeof (cairo_bo_event_t *),
					  sizeof (cairo_bo_event_t *));
549
	if (unlikely (events == NULL)) {
	    if (event_y != stack_event_y)
		free (event_y);
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
	}
549
	event_ptrs = (cairo_bo_event_t **) (events + num_events);
    }
57573
    for (i = 0; i < num_events; i++) {
56262
	events[i].type = CAIRO_BO_EVENT_TYPE_START;
56262
	events[i].point.y = polygon->edges[i].top;
112524
	events[i].point.x =
56262
	    _line_compute_intersection_x_for_y (&polygon->edges[i].line,
56262
						events[i].point.y);
56262
	events[i].edge.edge = polygon->edges[i];
56262
	events[i].edge.deferred_trap.right = NULL;
56262
	events[i].edge.prev = NULL;
56262
	events[i].edge.next = NULL;
56262
	events[i].edge.colinear = NULL;
56262
	if (event_y) {
11028
	    y = _cairo_fixed_integer_floor (events[i].point.y) - ymin;
11028
	    events[i].edge.next = (cairo_bo_edge_t *) event_y[y];
11028
	    event_y[y] = (cairo_bo_start_event_t *) &events[i];
	} else
45234
	    event_ptrs[i] = (cairo_bo_event_t *) &events[i];
    }
1311
    if (event_y) {
2232
	for (y = i = 0; y < ymax && i < num_events; y++) {
	    cairo_bo_start_event_t *e;
2094
	    int j = i;
13122
	    for (e = event_y[y]; e; e = (cairo_bo_start_event_t *)e->edge.next)
11028
		event_ptrs[i++] = (cairo_bo_event_t *) e;
2094
	    if (i > j + 1)
1500
		_cairo_bo_event_queue_sort (event_ptrs+j, i-j);
	}
138
	if (event_y != stack_event_y)
	    free (event_y);
    } else
1173
	_cairo_bo_event_queue_sort (event_ptrs, i);
1311
    event_ptrs[i] = NULL;
#if DEBUG_TRAPS
    dump_edges (events, num_events, "bo-polygon-edges.txt");
#endif
    /* XXX: This would be the convenient place to throw in multiple
     * passes of the Bentley-Ottmann algorithm. It would merely
     * require storing the results of each pass into a temporary
     * cairo_traps_t. */
1311
    status = _cairo_bentley_ottmann_tessellate_bo_edges (event_ptrs, num_events,
							 fill_rule, traps,
							 &intersections);
#if DEBUG_TRAPS
    dump_traps (traps, "bo-polygon-out.txt");
#endif
1311
    if (events != stack_events)
549
	free (events);
1311
    return status;
}
cairo_status_t
555
_cairo_bentley_ottmann_tessellate_traps (cairo_traps_t *traps,
					 cairo_fill_rule_t fill_rule)
{
    cairo_status_t status;
    cairo_polygon_t polygon;
    int i;
555
    if (unlikely (0 == traps->num_traps))
	return CAIRO_STATUS_SUCCESS;
#if DEBUG_TRAPS
    dump_traps (traps, "bo-traps-in.txt");
#endif
555
    _cairo_polygon_init (&polygon, traps->limits, traps->num_limits);
8043
    for (i = 0; i < traps->num_traps; i++) {
7488
	status = _cairo_polygon_add_line (&polygon,
7488
					  &traps->traps[i].left,
7488
					  traps->traps[i].top,
7488
					  traps->traps[i].bottom,
					  1);
7488
	if (unlikely (status))
	    goto CLEANUP;
7488
	status = _cairo_polygon_add_line (&polygon,
7488
					  &traps->traps[i].right,
7488
					  traps->traps[i].top,
7488
					  traps->traps[i].bottom,
					  -1);
7488
	if (unlikely (status))
	    goto CLEANUP;
    }
555
    _cairo_traps_clear (traps);
555
    status = _cairo_bentley_ottmann_tessellate_polygon (traps,
							&polygon,
							fill_rule);
#if DEBUG_TRAPS
    dump_traps (traps, "bo-traps-out.txt");
#endif
555
  CLEANUP:
555
    _cairo_polygon_fini (&polygon);
555
    return status;
}
#if 0
static cairo_bool_t
edges_have_an_intersection_quadratic (cairo_bo_edge_t	*edges,
				      int		 num_edges)
{
    int i, j;
    cairo_bo_edge_t *a, *b;
    cairo_bo_point32_t intersection;
    /* We must not be given any upside-down edges. */
    for (i = 0; i < num_edges; i++) {
	assert (_cairo_bo_point32_compare (&edges[i].top, &edges[i].bottom) < 0);
	edges[i].line.p1.x <<= CAIRO_BO_GUARD_BITS;
	edges[i].line.p1.y <<= CAIRO_BO_GUARD_BITS;
	edges[i].line.p2.x <<= CAIRO_BO_GUARD_BITS;
	edges[i].line.p2.y <<= CAIRO_BO_GUARD_BITS;
    }
    for (i = 0; i < num_edges; i++) {
	for (j = 0; j < num_edges; j++) {
	    if (i == j)
		continue;
	    a = &edges[i];
	    b = &edges[j];
	    if (! _cairo_bo_edge_intersect (a, b, &intersection))
		continue;
	    printf ("Found intersection (%d,%d) between (%d,%d)-(%d,%d) and (%d,%d)-(%d,%d)\n",
		    intersection.x,
		    intersection.y,
		    a->line.p1.x, a->line.p1.y,
		    a->line.p2.x, a->line.p2.y,
		    b->line.p1.x, b->line.p1.y,
		    b->line.p2.x, b->line.p2.y);
	    return TRUE;
	}
    }
    return FALSE;
}
#define TEST_MAX_EDGES 10
typedef struct test {
    const char *name;
    const char *description;
    int num_edges;
    cairo_bo_edge_t edges[TEST_MAX_EDGES];
} test_t;
static test_t
tests[] = {
    {
	"3 near misses",
	"3 edges all intersecting very close to each other",
	3,
	{
	    { { 4, 2}, {0, 0}, { 9, 9}, NULL, NULL },
	    { { 7, 2}, {0, 0}, { 2, 3}, NULL, NULL },
	    { { 5, 2}, {0, 0}, { 1, 7}, NULL, NULL }
	}
    },
    {
	"inconsistent data",
	"Derived from random testing---was leading to skip list and edge list disagreeing.",
	2,
	{
	    { { 2, 3}, {0, 0}, { 8, 9}, NULL, NULL },
	    { { 2, 3}, {0, 0}, { 6, 7}, NULL, NULL }
	}
    },
    {
	"failed sort",
	"A test derived from random testing that leads to an inconsistent sort --- looks like we just can't attempt to validate the sweep line with edge_compare?",
	3,
	{
	    { { 6, 2}, {0, 0}, { 6, 5}, NULL, NULL },
	    { { 3, 5}, {0, 0}, { 5, 6}, NULL, NULL },
	    { { 9, 2}, {0, 0}, { 5, 6}, NULL, NULL },
	}
    },
    {
	"minimal-intersection",
	"Intersection of a two from among the smallest possible edges.",
	2,
	{
	    { { 0, 0}, {0, 0}, { 1, 1}, NULL, NULL },
	    { { 1, 0}, {0, 0}, { 0, 1}, NULL, NULL }
	}
    },
    {
	"simple",
	"A simple intersection of two edges at an integer (2,2).",
	2,
	{
	    { { 1, 1}, {0, 0}, { 3, 3}, NULL, NULL },
	    { { 2, 1}, {0, 0}, { 2, 3}, NULL, NULL }
	}
    },
    {
	"bend-to-horizontal",
	"With intersection truncation one edge bends to horizontal",
	2,
	{
	    { { 9, 1}, {0, 0}, {3, 7}, NULL, NULL },
	    { { 3, 5}, {0, 0}, {9, 9}, NULL, NULL }
	}
    }
};
/*
    {
	"endpoint",
	"An intersection that occurs at the endpoint of a segment.",
	{
	    { { 4, 6}, { 5, 6}, NULL, { { NULL }} },
	    { { 4, 5}, { 5, 7}, NULL, { { NULL }} },
	    { { 0, 0}, { 0, 0}, NULL, { { NULL }} },
	}
    }
    {
	name = "overlapping",
	desc = "Parallel segments that share an endpoint, with different slopes.",
	edges = {
	    { top = { x = 2, y = 0}, bottom = { x = 1, y = 1}},
	    { top = { x = 2, y = 0}, bottom = { x = 0, y = 2}},
	    { top = { x = 0, y = 3}, bottom = { x = 1, y = 3}},
	    { top = { x = 0, y = 3}, bottom = { x = 2, y = 3}},
	    { top = { x = 0, y = 4}, bottom = { x = 0, y = 6}},
	    { top = { x = 0, y = 5}, bottom = { x = 0, y = 6}}
	}
    },
    {
	name = "hobby_stage_3",
	desc = "A particularly tricky part of the 3rd stage of the 'hobby' test below.",
	edges = {
	    { top = { x = -1, y = -2}, bottom = { x =  4, y = 2}},
	    { top = { x =  5, y =  3}, bottom = { x =  9, y = 5}},
	    { top = { x =  5, y =  3}, bottom = { x =  6, y = 3}},
	}
    },
    {
	name = "hobby",
	desc = "Example from John Hobby's paper. Requires 3 passes of the iterative algorithm.",
	edges = {
	    { top = { x =   0, y =   0}, bottom = { x =   9, y =   5}},
	    { top = { x =   0, y =   0}, bottom = { x =  13, y =   6}},
	    { top = { x =  -1, y =  -2}, bottom = { x =   9, y =   5}}
	}
    },
    {
	name = "slope",
	desc = "Edges with same start/stop points but different slopes",
	edges = {
	    { top = { x = 4, y = 1}, bottom = { x = 6, y = 3}},
	    { top = { x = 4, y = 1}, bottom = { x = 2, y = 3}},
	    { top = { x = 2, y = 4}, bottom = { x = 4, y = 6}},
	    { top = { x = 6, y = 4}, bottom = { x = 4, y = 6}}
	}
    },
    {
	name = "horizontal",
	desc = "Test of a horizontal edge",
	edges = {
	    { top = { x = 1, y = 1}, bottom = { x = 6, y = 6}},
	    { top = { x = 2, y = 3}, bottom = { x = 5, y = 3}}
	}
    },
    {
	name = "vertical",
	desc = "Test of a vertical edge",
	edges = {
	    { top = { x = 5, y = 1}, bottom = { x = 5, y = 7}},
	    { top = { x = 2, y = 4}, bottom = { x = 8, y = 5}}
	}
    },
    {
	name = "congruent",
	desc = "Two overlapping edges with the same slope",
	edges = {
	    { top = { x = 5, y = 1}, bottom = { x = 5, y = 7}},
	    { top = { x = 5, y = 2}, bottom = { x = 5, y = 6}},
	    { top = { x = 2, y = 4}, bottom = { x = 8, y = 5}}
	}
    },
    {
	name = "multi",
	desc = "Several segments with a common intersection point",
	edges = {
	    { top = { x = 1, y = 2}, bottom = { x = 5, y = 4} },
	    { top = { x = 1, y = 1}, bottom = { x = 5, y = 5} },
	    { top = { x = 2, y = 1}, bottom = { x = 4, y = 5} },
	    { top = { x = 4, y = 1}, bottom = { x = 2, y = 5} },
	    { top = { x = 5, y = 1}, bottom = { x = 1, y = 5} },
	    { top = { x = 5, y = 2}, bottom = { x = 1, y = 4} }
	}
    }
};
*/
static int
run_test (const char		*test_name,
          cairo_bo_edge_t	*test_edges,
          int			 num_edges)
{
    int i, intersections, passes;
    cairo_bo_edge_t *edges;
    cairo_array_t intersected_edges;
    printf ("Testing: %s\n", test_name);
    _cairo_array_init (&intersected_edges, sizeof (cairo_bo_edge_t));
    intersections = _cairo_bentley_ottmann_intersect_edges (test_edges, num_edges, &intersected_edges);
    if (intersections)
	printf ("Pass 1 found %d intersections:\n", intersections);
    /* XXX: Multi-pass Bentley-Ottmmann. Preferable would be to add a
     * pass of Hobby's tolerance-square algorithm instead. */
    passes = 1;
    while (intersections) {
	int num_edges = _cairo_array_num_elements (&intersected_edges);
	passes++;
	edges = _cairo_malloc_ab (num_edges, sizeof (cairo_bo_edge_t));
	assert (edges != NULL);
	memcpy (edges, _cairo_array_index (&intersected_edges, 0), num_edges * sizeof (cairo_bo_edge_t));
	_cairo_array_fini (&intersected_edges);
	_cairo_array_init (&intersected_edges, sizeof (cairo_bo_edge_t));
	intersections = _cairo_bentley_ottmann_intersect_edges (edges, num_edges, &intersected_edges);
	free (edges);
	if (intersections){
	    printf ("Pass %d found %d remaining intersections:\n", passes, intersections);
	} else {
	    if (passes > 3)
		for (i = 0; i < passes; i++)
		    printf ("*");
	    printf ("No remainining intersections found after pass %d\n", passes);
	}
    }
    if (edges_have_an_intersection_quadratic (_cairo_array_index (&intersected_edges, 0),
					      _cairo_array_num_elements (&intersected_edges)))
	printf ("*** FAIL ***\n");
    else
	printf ("PASS\n");
    _cairo_array_fini (&intersected_edges);
    return 0;
}
#define MAX_RANDOM 300
int
main (void)
{
    char random_name[] = "random-XX";
    cairo_bo_edge_t random_edges[MAX_RANDOM], *edge;
    unsigned int i, num_random;
    test_t *test;
    for (i = 0; i < ARRAY_LENGTH (tests); i++) {
	test = &tests[i];
	run_test (test->name, test->edges, test->num_edges);
    }
    for (num_random = 0; num_random < MAX_RANDOM; num_random++) {
	srand (0);
	for (i = 0; i < num_random; i++) {
	    do {
		edge = &random_edges[i];
		edge->line.p1.x = (int32_t) (10.0 * (rand() / (RAND_MAX + 1.0)));
		edge->line.p1.y = (int32_t) (10.0 * (rand() / (RAND_MAX + 1.0)));
		edge->line.p2.x = (int32_t) (10.0 * (rand() / (RAND_MAX + 1.0)));
		edge->line.p2.y = (int32_t) (10.0 * (rand() / (RAND_MAX + 1.0)));
		if (edge->line.p1.y > edge->line.p2.y) {
		    int32_t tmp = edge->line.p1.y;
		    edge->line.p1.y = edge->line.p2.y;
		    edge->line.p2.y = tmp;
		}
	    } while (edge->line.p1.y == edge->line.p2.y);
	}
	sprintf (random_name, "random-%02d", num_random);
	run_test (random_name, random_edges, num_random);
    }
    return 0;
}
#endif