1
/* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */
2
/* glitter-paths - polygon scan converter
3
 *
4
 * Copyright (c) 2008  M Joonas Pihlaja
5
 * Copyright (c) 2007  David Turner
6
 *
7
 * Permission is hereby granted, free of charge, to any person
8
 * obtaining a copy of this software and associated documentation
9
 * files (the "Software"), to deal in the Software without
10
 * restriction, including without limitation the rights to use,
11
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the
13
 * Software is furnished to do so, subject to the following
14
 * conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be
17
 * included in all copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26
 * OTHER DEALINGS IN THE SOFTWARE.
27
 */
28
/* This is the Glitter paths scan converter incorporated into cairo.
29
 * The source is from commit 734c53237a867a773640bd5b64816249fa1730f8
30
 * of
31
 *
32
 *   https://gitweb.freedesktop.org/?p=users/joonas/glitter-paths
33
 */
34
/* Glitter-paths is a stand alone polygon rasteriser derived from
35
 * David Turner's reimplementation of Tor Anderssons's 15x17
36
 * supersampling rasteriser from the Apparition graphics library.  The
37
 * main new feature here is cheaply choosing per-scan line between
38
 * doing fully analytical coverage computation for an entire row at a
39
 * time vs. using a supersampling approach.
40
 *
41
 * David Turner's code can be found at
42
 *
43
 *   http://david.freetype.org/rasterizer-shootout/raster-comparison-20070813.tar.bz2
44
 *
45
 * In particular this file incorporates large parts of ftgrays_tor10.h
46
 * from raster-comparison-20070813.tar.bz2
47
 */
48
/* Overview
49
 *
50
 * A scan converter's basic purpose to take polygon edges and convert
51
 * them into an RLE compressed A8 mask.  This one works in two phases:
52
 * gathering edges and generating spans.
53
 *
54
 * 1) As the user feeds the scan converter edges they are vertically
55
 * clipped and bucketted into a _polygon_ data structure.  The edges
56
 * are also snapped from the user's coordinates to the subpixel grid
57
 * coordinates used during scan conversion.
58
 *
59
 *     user
60
 *      |
61
 *      | edges
62
 *      V
63
 *    polygon buckets
64
 *
65
 * 2) Generating spans works by performing a vertical sweep of pixel
66
 * rows from top to bottom and maintaining an _active_list_ of edges
67
 * that intersect the row.  From the active list the fill rule
68
 * determines which edges are the left and right edges of the start of
69
 * each span, and their contribution is then accumulated into a pixel
70
 * coverage list (_cell_list_) as coverage deltas.  Once the coverage
71
 * deltas of all edges are known we can form spans of constant pixel
72
 * coverage by summing the deltas during a traversal of the cell list.
73
 * At the end of a pixel row the cell list is sent to a coverage
74
 * blitter for rendering to some target surface.
75
 *
76
 * The pixel coverages are computed by either supersampling the row
77
 * and box filtering a mono rasterisation, or by computing the exact
78
 * coverages of edges in the active list.  The supersampling method is
79
 * used whenever some edge starts or stops within the row or there are
80
 * edge intersections in the row.
81
 *
82
 *   polygon bucket for       \
83
 *   current pixel row        |
84
 *      |                     |
85
 *      | activate new edges  |  Repeat GRID_Y times if we
86
 *      V                     \  are supersampling this row,
87
 *   active list              /  or just once if we're computing
88
 *      |                     |  analytical coverage.
89
 *      | coverage deltas     |
90
 *      V                     |
91
 *   pixel coverage list     /
92
 *      |
93
 *      V
94
 *   coverage blitter
95
 */
96
#include "cairoint.h"
97
#include "cairo-spans-private.h"
98
#include "cairo-error-private.h"
99

            
100
#include <stdlib.h>
101
#include <string.h>
102
#include <limits.h>
103
#include <setjmp.h>
104

            
105
/*-------------------------------------------------------------------------
106
 * cairo specific config
107
 */
108
#define I static
109

            
110
/* Prefer cairo's status type. */
111
#define GLITTER_HAVE_STATUS_T 1
112
#define GLITTER_STATUS_SUCCESS CAIRO_STATUS_SUCCESS
113
#define GLITTER_STATUS_NO_MEMORY CAIRO_STATUS_NO_MEMORY
114
typedef cairo_status_t glitter_status_t;
115

            
116
/* The input coordinate scale and the rasterisation grid scales. */
117
#define GLITTER_INPUT_BITS CAIRO_FIXED_FRAC_BITS
118
//#define GRID_X_BITS CAIRO_FIXED_FRAC_BITS
119
//#define GRID_Y 15
120
#define GRID_X_BITS 2
121
#define GRID_Y_BITS 2
122

            
123
/* Set glitter up to use a cairo span renderer to do the coverage
124
 * blitting. */
125
struct pool;
126
struct cell_list;
127

            
128
/*-------------------------------------------------------------------------
129
 * glitter-paths.h
130
 */
131

            
132
/* "Input scaled" numbers are fixed precision reals with multiplier
133
 * 2**GLITTER_INPUT_BITS.  Input coordinates are given to glitter as
134
 * pixel scaled numbers.  These get converted to the internal grid
135
 * scaled numbers as soon as possible. Internal overflow is possible
136
 * if GRID_X/Y inside glitter-paths.c is larger than
137
 * 1<<GLITTER_INPUT_BITS. */
138
#ifndef GLITTER_INPUT_BITS
139
#  define GLITTER_INPUT_BITS 8
140
#endif
141
#define GLITTER_INPUT_SCALE (1<<GLITTER_INPUT_BITS)
142
typedef int glitter_input_scaled_t;
143

            
144
#if !GLITTER_HAVE_STATUS_T
145
typedef enum {
146
    GLITTER_STATUS_SUCCESS = 0,
147
    GLITTER_STATUS_NO_MEMORY
148
} glitter_status_t;
149
#endif
150

            
151
#ifndef I
152
# define I /*static*/
153
#endif
154

            
155
/* Opaque type for scan converting. */
156
typedef struct glitter_scan_converter glitter_scan_converter_t;
157

            
158
/* Reset a scan converter to accept polygon edges and set the clip box
159
 * in pixels.  Allocates O(ymax-ymin) bytes of memory.	The clip box
160
 * is set to integer pixel coordinates xmin <= x < xmax, ymin <= y <
161
 * ymax. */
162
I glitter_status_t
163
glitter_scan_converter_reset(
164
    glitter_scan_converter_t *converter,
165
    int xmin, int ymin,
166
    int xmax, int ymax);
167

            
168
/* Render the polygon in the scan converter to the given A8 format
169
 * image raster.  Only the pixels accessible as pixels[y*stride+x] for
170
 * x,y inside the clip box are written to, where xmin <= x < xmax,
171
 * ymin <= y < ymax.  The image is assumed to be clear on input.
172
 *
173
 * If nonzero_fill is true then the interior of the polygon is
174
 * computed with the non-zero fill rule.  Otherwise the even-odd fill
175
 * rule is used.
176
 *
177
 * The scan converter must be reset or destroyed after this call. */
178

            
179
/*-------------------------------------------------------------------------
180
 * glitter-paths.c: Implementation internal types
181
 */
182
#include <stdlib.h>
183
#include <string.h>
184
#include <limits.h>
185

            
186
/* All polygon coordinates are snapped onto a subsample grid. "Grid
187
 * scaled" numbers are fixed precision reals with multiplier GRID_X or
188
 * GRID_Y. */
189
typedef int grid_scaled_t;
190
typedef int grid_scaled_x_t;
191
typedef int grid_scaled_y_t;
192

            
193
/* Default x/y scale factors.
194
 *  You can either define GRID_X/Y_BITS to get a power-of-two scale
195
 *  or define GRID_X/Y separately. */
196
#if !defined(GRID_X) && !defined(GRID_X_BITS)
197
#  define GRID_X_BITS 8
198
#endif
199
#if !defined(GRID_Y) && !defined(GRID_Y_BITS)
200
#  define GRID_Y 15
201
#endif
202

            
203
/* Use GRID_X/Y_BITS to define GRID_X/Y if they're available. */
204
#ifdef GRID_X_BITS
205
#  define GRID_X (1 << GRID_X_BITS)
206
#endif
207
#ifdef GRID_Y_BITS
208
#  define GRID_Y (1 << GRID_Y_BITS)
209
#endif
210

            
211
/* The GRID_X_TO_INT_FRAC macro splits a grid scaled coordinate into
212
 * integer and fractional parts. The integer part is floored. */
213
#if defined(GRID_X_TO_INT_FRAC)
214
  /* do nothing */
215
#elif defined(GRID_X_BITS)
216
#  define GRID_X_TO_INT_FRAC(x, i, f) \
217
	_GRID_TO_INT_FRAC_shift(x, i, f, GRID_X_BITS)
218
#else
219
#  define GRID_X_TO_INT_FRAC(x, i, f) \
220
	_GRID_TO_INT_FRAC_general(x, i, f, GRID_X)
221
#endif
222

            
223
#define _GRID_TO_INT_FRAC_general(t, i, f, m) do {	\
224
    (i) = (t) / (m);					\
225
    (f) = (t) % (m);					\
226
    if ((f) < 0) {					\
227
	--(i);						\
228
	(f) += (m);					\
229
    }							\
230
} while (0)
231

            
232
#define _GRID_TO_INT_FRAC_shift(t, i, f, b) do {	\
233
    (f) = (t) & ((1 << (b)) - 1);			\
234
    (i) = (t) >> (b);					\
235
} while (0)
236

            
237
/* A grid area is a real in [0,1] scaled by 2*GRID_X*GRID_Y.  We want
238
 * to be able to represent exactly areas of subpixel trapezoids whose
239
 * vertices are given in grid scaled coordinates.  The scale factor
240
 * comes from needing to accurately represent the area 0.5*dx*dy of a
241
 * triangle with base dx and height dy in grid scaled numbers. */
242
#define GRID_XY (2*GRID_X*GRID_Y) /* Unit area on the grid. */
243

            
244
/* GRID_AREA_TO_ALPHA(area): map [0,GRID_XY] to [0,255]. */
245
#if GRID_XY == 510
246
#  define GRID_AREA_TO_ALPHA(c)	  (((c)+1) >> 1)
247
#elif GRID_XY == 255
248
#  define  GRID_AREA_TO_ALPHA(c)  (c)
249
#elif GRID_XY == 64
250
#  define  GRID_AREA_TO_ALPHA(c)  (((c) << 2) | -(((c) & 0x40) >> 6))
251
#elif GRID_XY == 32
252
#  define  GRID_AREA_TO_ALPHA(c)  (((c) << 3) | -(((c) & 0x20) >> 5))
253
#elif GRID_XY == 128
254
#  define  GRID_AREA_TO_ALPHA(c)  ((((c) << 1) | -((c) >> 7)) & 255)
255
#elif GRID_XY == 256
256
#  define  GRID_AREA_TO_ALPHA(c)  (((c) | -((c) >> 8)) & 255)
257
#elif GRID_XY == 15
258
#  define  GRID_AREA_TO_ALPHA(c)  (((c) << 4) + (c))
259
#elif GRID_XY == 2*256*15
260
#  define  GRID_AREA_TO_ALPHA(c)  (((c) + ((c)<<4) + 256) >> 9)
261
#else
262
#  define  GRID_AREA_TO_ALPHA(c)  (((c)*255 + GRID_XY/2) / GRID_XY)
263
#endif
264

            
265
#define UNROLL3(x) x x x
266

            
267
struct quorem {
268
    int32_t quo;
269
    int32_t rem;
270
};
271

            
272
/* Header for a chunk of memory in a memory pool. */
273
struct _pool_chunk {
274
    /* # bytes used in this chunk. */
275
    size_t size;
276

            
277
    /* # bytes total in this chunk */
278
    size_t capacity;
279

            
280
    /* Pointer to the previous chunk or %NULL if this is the sentinel
281
     * chunk in the pool header. */
282
    struct _pool_chunk *prev_chunk;
283

            
284
    /* Actual data starts here.	 Well aligned for pointers. */
285
};
286

            
287
/* A memory pool.  This is supposed to be embedded on the stack or
288
 * within some other structure.	 It may optionally be followed by an
289
 * embedded array from which requests are fulfilled until
290
 * malloc needs to be called to allocate a first real chunk. */
291
struct pool {
292
    /* Chunk we're allocating from. */
293
    struct _pool_chunk *current;
294

            
295
    jmp_buf *jmp;
296

            
297
    /* Free list of previously allocated chunks.  All have >= default
298
     * capacity. */
299
    struct _pool_chunk *first_free;
300

            
301
    /* The default capacity of a chunk. */
302
    size_t default_capacity;
303

            
304
    /* Header for the sentinel chunk.  Directly following the pool
305
     * struct should be some space for embedded elements from which
306
     * the sentinel chunk allocates from. */
307
    struct _pool_chunk sentinel[1];
308
};
309

            
310
/* A polygon edge. */
311
struct edge {
312
    /* Next in y-bucket or active list. */
313
    struct edge *next, *prev;
314

            
315
    /* Number of subsample rows remaining to scan convert of this
316
     * edge. */
317
    grid_scaled_y_t height_left;
318

            
319
    /* Original sign of the edge: +1 for downwards, -1 for upwards
320
     * edges.  */
321
    int dir;
322
    int vertical;
323

            
324
    /* Current x coordinate while the edge is on the active
325
     * list. Initialised to the x coordinate of the top of the
326
     * edge. The quotient is in grid_scaled_x_t units and the
327
     * remainder is mod dy in grid_scaled_y_t units.*/
328
    struct quorem x;
329

            
330
    /* Advance of the current x when moving down a subsample line. */
331
    struct quorem dxdy;
332

            
333
    /* The clipped y of the top of the edge. */
334
    grid_scaled_y_t ytop;
335

            
336
    /* y2-y1 after orienting the edge downwards.  */
337
    grid_scaled_y_t dy;
338
};
339

            
340
#define EDGE_Y_BUCKET_INDEX(y, ymin) (((y) - (ymin))/GRID_Y)
341

            
342
/* A collection of sorted and vertically clipped edges of the polygon.
343
 * Edges are moved from the polygon to an active list while scan
344
 * converting. */
345
struct polygon {
346
    /* The vertical clip extents. */
347
    grid_scaled_y_t ymin, ymax;
348

            
349
    /* Array of edges all starting in the same bucket.	An edge is put
350
     * into bucket EDGE_BUCKET_INDEX(edge->ytop, polygon->ymin) when
351
     * it is added to the polygon. */
352
    struct edge **y_buckets;
353
    struct edge *y_buckets_embedded[64];
354

            
355
    struct {
356
	struct pool base[1];
357
	struct edge embedded[32];
358
    } edge_pool;
359
};
360

            
361
/* A cell records the effect on pixel coverage of polygon edges
362
 * passing through a pixel.  It contains two accumulators of pixel
363
 * coverage.
364
 *
365
 * Consider the effects of a polygon edge on the coverage of a pixel
366
 * it intersects and that of the following one.  The coverage of the
367
 * following pixel is the height of the edge multiplied by the width
368
 * of the pixel, and the coverage of the pixel itself is the area of
369
 * the trapezoid formed by the edge and the right side of the pixel.
370
 *
371
 * +-----------------------+-----------------------+
372
 * |                       |                       |
373
 * |                       |                       |
374
 * |_______________________|_______________________|
375
 * |   \...................|.......................|\
376
 * |    \..................|.......................| |
377
 * |     \.................|.......................| |
378
 * |      \....covered.....|.......................| |
379
 * |       \....area.......|.......................| } covered height
380
 * |        \..............|.......................| |
381
 * |uncovered\.............|.......................| |
382
 * |  area    \............|.......................| |
383
 * |___________\...........|.......................|/
384
 * |                       |                       |
385
 * |                       |                       |
386
 * |                       |                       |
387
 * +-----------------------+-----------------------+
388
 *
389
 * Since the coverage of the following pixel will always be a multiple
390
 * of the width of the pixel, we can store the height of the covered
391
 * area instead.  The coverage of the pixel itself is the total
392
 * coverage minus the area of the uncovered area to the left of the
393
 * edge.  As it's faster to compute the uncovered area we only store
394
 * that and subtract it from the total coverage later when forming
395
 * spans to blit.
396
 *
397
 * The heights and areas are signed, with left edges of the polygon
398
 * having positive sign and right edges having negative sign.  When
399
 * two edges intersect they swap their left/rightness so their
400
 * contribution above and below the intersection point must be
401
 * computed separately. */
402
struct cell {
403
    struct cell		*next;
404
    int			 x;
405
    int16_t		 uncovered_area;
406
    int16_t		 covered_height;
407
};
408

            
409
/* A cell list represents the scan line sparsely as cells ordered by
410
 * ascending x.  It is geared towards scanning the cells in order
411
 * using an internal cursor. */
412
struct cell_list {
413
    /* Sentinel nodes */
414
    struct cell head, tail;
415

            
416
    /* Cursor state for iterating through the cell list. */
417
    struct cell *cursor, *rewind;
418

            
419
    /* Cells in the cell list are owned by the cell list and are
420
     * allocated from this pool.  */
421
    struct {
422
	struct pool base[1];
423
	struct cell embedded[32];
424
    } cell_pool;
425
};
426

            
427
struct cell_pair {
428
    struct cell *cell1;
429
    struct cell *cell2;
430
};
431

            
432
/* The active list contains edges in the current scan line ordered by
433
 * the x-coordinate of the intercept of the edge and the scan line. */
434
struct active_list {
435
    /* Leftmost edge on the current scan line. */
436
    struct edge head, tail;
437

            
438
    /* A lower bound on the height of the active edges is used to
439
     * estimate how soon some active edge ends.	 We can't advance the
440
     * scan conversion by a full pixel row if an edge ends somewhere
441
     * within it. */
442
    grid_scaled_y_t min_height;
443
    int is_vertical;
444
};
445

            
446
struct glitter_scan_converter {
447
    struct polygon	polygon[1];
448
    struct active_list	active[1];
449
    struct cell_list	coverages[1];
450

            
451
    cairo_half_open_span_t *spans;
452
    cairo_half_open_span_t spans_embedded[64];
453

            
454
    /* Clip box. */
455
    grid_scaled_x_t xmin, xmax;
456
    grid_scaled_y_t ymin, ymax;
457
};
458

            
459
/* Compute the floored division a/b. Assumes / and % perform symmetric
460
 * division. */
461
inline static struct quorem
462
204
floored_divrem(int a, int b)
463
{
464
    struct quorem qr;
465
204
    qr.quo = a/b;
466
204
    qr.rem = a%b;
467
204
    if ((a^b)<0 && qr.rem) {
468
	qr.quo -= 1;
469
	qr.rem += b;
470
    }
471
204
    return qr;
472
}
473

            
474
/* Compute the floored division (x*a)/b. Assumes / and % perform symmetric
475
 * division. */
476
static struct quorem
477
floored_muldivrem(int x, int a, int b)
478
{
479
    struct quorem qr;
480
    long long xa = (long long)x*a;
481
    qr.quo = xa/b;
482
    qr.rem = xa%b;
483
    if ((xa>=0) != (b>=0) && qr.rem) {
484
	qr.quo -= 1;
485
	qr.rem += b;
486
    }
487
    return qr;
488
}
489

            
490
static struct _pool_chunk *
491
15
_pool_chunk_init(
492
    struct _pool_chunk *p,
493
    struct _pool_chunk *prev_chunk,
494
    size_t capacity)
495
{
496
15
    p->prev_chunk = prev_chunk;
497
15
    p->size = 0;
498
15
    p->capacity = capacity;
499
15
    return p;
500
}
501

            
502
static struct _pool_chunk *
503
6
_pool_chunk_create(struct pool *pool, size_t size)
504
{
505
    struct _pool_chunk *p;
506

            
507
6
    p = _cairo_malloc (size + sizeof(struct _pool_chunk));
508
6
    if (unlikely (NULL == p))
509
	longjmp (*pool->jmp, _cairo_error (CAIRO_STATUS_NO_MEMORY));
510

            
511
6
    return _pool_chunk_init(p, pool->current, size);
512
}
513

            
514
static void
515
6
pool_init(struct pool *pool,
516
	  jmp_buf *jmp,
517
	  size_t default_capacity,
518
	  size_t embedded_capacity)
519
{
520
6
    pool->jmp = jmp;
521
6
    pool->current = pool->sentinel;
522
6
    pool->first_free = NULL;
523
6
    pool->default_capacity = default_capacity;
524
6
    _pool_chunk_init(pool->sentinel, NULL, embedded_capacity);
525
6
}
526

            
527
static void
528
6
pool_fini(struct pool *pool)
529
{
530
6
    struct _pool_chunk *p = pool->current;
531
    do {
532
21
	while (NULL != p) {
533
12
	    struct _pool_chunk *prev = p->prev_chunk;
534
12
	    if (p != pool->sentinel)
535
6
		free(p);
536
12
	    p = prev;
537
	}
538
9
	p = pool->first_free;
539
9
	pool->first_free = NULL;
540
9
    } while (NULL != p);
541
6
}
542

            
543
/* Satisfy an allocation by first allocating a new large enough chunk
544
 * and adding it to the head of the pool's chunk list. This function
545
 * is called as a fallback if pool_alloc() couldn't do a quick
546
 * allocation from the current chunk in the pool. */
547
static void *
548
9
_pool_alloc_from_new_chunk(
549
    struct pool *pool,
550
    size_t size)
551
{
552
    struct _pool_chunk *chunk;
553
    void *obj;
554
    size_t capacity;
555

            
556
    /* If the allocation is smaller than the default chunk size then
557
     * try getting a chunk off the free list.  Force alloc of a new
558
     * chunk for large requests. */
559
9
    capacity = size;
560
9
    chunk = NULL;
561
9
    if (size < pool->default_capacity) {
562
9
	capacity = pool->default_capacity;
563
9
	chunk = pool->first_free;
564
9
	if (chunk) {
565
3
	    pool->first_free = chunk->prev_chunk;
566
3
	    _pool_chunk_init(chunk, pool->current, chunk->capacity);
567
	}
568
    }
569

            
570
9
    if (NULL == chunk)
571
6
	chunk = _pool_chunk_create (pool, capacity);
572
9
    pool->current = chunk;
573

            
574
9
    obj = ((unsigned char*)chunk + sizeof(*chunk) + chunk->size);
575
9
    chunk->size += size;
576
9
    return obj;
577
}
578

            
579
/* Allocate size bytes from the pool.  The first allocated address
580
 * returned from a pool is aligned to sizeof(void*).  Subsequent
581
 * addresses will maintain alignment as long as multiples of void* are
582
 * allocated.  Returns the address of a new memory area or %NULL on
583
 * allocation failures.	 The pool retains ownership of the returned
584
 * memory. */
585
inline static void *
586
510
pool_alloc (struct pool *pool, size_t size)
587
{
588
510
    struct _pool_chunk *chunk = pool->current;
589

            
590
510
    if (size <= chunk->capacity - chunk->size) {
591
501
	void *obj = ((unsigned char*)chunk + sizeof(*chunk) + chunk->size);
592
501
	chunk->size += size;
593
501
	return obj;
594
    } else {
595
9
	return _pool_alloc_from_new_chunk(pool, size);
596
    }
597
}
598

            
599
/* Relinquish all pool_alloced memory back to the pool. */
600
static void
601
12
pool_reset (struct pool *pool)
602
{
603
    /* Transfer all used chunks to the chunk free list. */
604
12
    struct _pool_chunk *chunk = pool->current;
605
12
    if (chunk != pool->sentinel) {
606
6
	while (chunk->prev_chunk != pool->sentinel) {
607
	    chunk = chunk->prev_chunk;
608
	}
609
6
	chunk->prev_chunk = pool->first_free;
610
6
	pool->first_free = pool->current;
611
    }
612
    /* Reset the sentinel as the current chunk. */
613
12
    pool->current = pool->sentinel;
614
12
    pool->sentinel->size = 0;
615
12
}
616

            
617
/* Rewinds the cell list's cursor to the beginning.  After rewinding
618
 * we're good to cell_list_find() the cell any x coordinate. */
619
inline static void
620
36
cell_list_rewind (struct cell_list *cells)
621
{
622
36
    cells->cursor = &cells->head;
623
36
}
624

            
625
inline static void
626
cell_list_set_rewind (struct cell_list *cells)
627
{
628
    cells->rewind = cells->cursor;
629
}
630

            
631
static void
632
3
cell_list_init(struct cell_list *cells, jmp_buf *jmp)
633
{
634
3
    pool_init(cells->cell_pool.base, jmp,
635
	      256*sizeof(struct cell),
636
	      sizeof(cells->cell_pool.embedded));
637
3
    cells->tail.next = NULL;
638
3
    cells->tail.x = INT_MAX;
639
3
    cells->head.x = INT_MIN;
640
3
    cells->head.next = &cells->tail;
641
3
    cell_list_rewind (cells);
642
3
}
643

            
644
static void
645
3
cell_list_fini(struct cell_list *cells)
646
{
647
3
    pool_fini (cells->cell_pool.base);
648
3
}
649

            
650
/* Empty the cell list.  This is called at the start of every pixel
651
 * row. */
652
inline static void
653
9
cell_list_reset (struct cell_list *cells)
654
{
655
9
    cell_list_rewind (cells);
656
9
    cells->head.next = &cells->tail;
657
9
    pool_reset (cells->cell_pool.base);
658
9
}
659

            
660
inline static struct cell *
661
306
cell_list_alloc (struct cell_list *cells,
662
		 struct cell *tail,
663
		 int x)
664
{
665
    struct cell *cell;
666

            
667
306
    cell = pool_alloc (cells->cell_pool.base, sizeof (struct cell));
668
306
    cell->next = tail->next;
669
306
    tail->next = cell;
670
306
    cell->x = x;
671
306
    *(uint32_t *)&cell->uncovered_area = 0;
672

            
673
306
    return cell;
674
}
675

            
676
/* Find a cell at the given x-coordinate.  Returns %NULL if a new cell
677
 * needed to be allocated but couldn't be.  Cells must be found with
678
 * non-decreasing x-coordinate until the cell list is rewound using
679
 * cell_list_rewind(). Ownership of the returned cell is retained by
680
 * the cell list. */
681
inline static struct cell *
682
cell_list_find (struct cell_list *cells, int x)
683
{
684
    struct cell *tail = cells->cursor;
685

            
686
    if (tail->x == x)
687
	return tail;
688

            
689
    while (1) {
690
	UNROLL3({
691
		if (tail->next->x > x)
692
			break;
693
		tail = tail->next;
694
	});
695
    }
696

            
697
    if (tail->x != x)
698
	tail = cell_list_alloc (cells, tail, x);
699
    return cells->cursor = tail;
700

            
701
}
702

            
703
/* Find two cells at x1 and x2.	 This is exactly equivalent
704
 * to
705
 *
706
 *   pair.cell1 = cell_list_find(cells, x1);
707
 *   pair.cell2 = cell_list_find(cells, x2);
708
 *
709
 * except with less function call overhead. */
710
inline static struct cell_pair
711
408
cell_list_find_pair(struct cell_list *cells, int x1, int x2)
712
{
713
    struct cell_pair pair;
714

            
715
408
    pair.cell1 = cells->cursor;
716
    while (1) {
717
408
	UNROLL3({
718
		if (pair.cell1->next->x > x1)
719
			break;
720
		pair.cell1 = pair.cell1->next;
721
	});
722
    }
723
408
    if (pair.cell1->x != x1)
724
153
	pair.cell1 = cell_list_alloc (cells, pair.cell1, x1);
725

            
726
408
    pair.cell2 = pair.cell1;
727
    while (1) {
728
408
	UNROLL3({
729
		if (pair.cell2->next->x > x2)
730
			break;
731
		pair.cell2 = pair.cell2->next;
732
	});
733
    }
734
408
    if (pair.cell2->x != x2)
735
153
	pair.cell2 = cell_list_alloc (cells, pair.cell2, x2);
736

            
737
408
    cells->cursor = pair.cell2;
738
408
    return pair;
739
}
740

            
741
/* Add a subpixel span covering [x1, x2) to the coverage cells. */
742
inline static void
743
408
cell_list_add_subspan(struct cell_list *cells,
744
		      grid_scaled_x_t x1,
745
		      grid_scaled_x_t x2)
746
{
747
    int ix1, fx1;
748
    int ix2, fx2;
749

            
750
408
    if (x1 == x2)
751
	return;
752

            
753
408
    GRID_X_TO_INT_FRAC(x1, ix1, fx1);
754
408
    GRID_X_TO_INT_FRAC(x2, ix2, fx2);
755

            
756
408
    if (ix1 != ix2) {
757
	struct cell_pair p;
758
408
	p = cell_list_find_pair(cells, ix1, ix2);
759
408
	p.cell1->uncovered_area += 2*fx1;
760
408
	++p.cell1->covered_height;
761
408
	p.cell2->uncovered_area -= 2*fx2;
762
408
	--p.cell2->covered_height;
763
    } else {
764
	struct cell *cell = cell_list_find(cells, ix1);
765
	cell->uncovered_area += 2*(fx1-fx2);
766
    }
767
}
768

            
769
/* Adds the analytical coverage of an edge crossing the current pixel
770
 * row to the coverage cells and advances the edge's x position to the
771
 * following row.
772
 *
773
 * This function is only called when we know that during this pixel row:
774
 *
775
 * 1) The relative order of all edges on the active list doesn't
776
 * change.  In particular, no edges intersect within this row to pixel
777
 * precision.
778
 *
779
 * 2) No new edges start in this row.
780
 *
781
 * 3) No existing edges end mid-row.
782
 *
783
 * This function depends on being called with all edges from the
784
 * active list in the order they appear on the list (i.e. with
785
 * non-decreasing x-coordinate.)  */
786
static void
787
cell_list_render_edge(struct cell_list *cells,
788
		      struct edge *edge,
789
		      int sign)
790
{
791
    grid_scaled_x_t fx;
792
    struct cell *cell;
793
    int ix;
794

            
795
    GRID_X_TO_INT_FRAC(edge->x.quo, ix, fx);
796

            
797
    /* We always know that ix1 is >= the cell list cursor in this
798
     * case due to the no-intersections precondition.  */
799
    cell = cell_list_find(cells, ix);
800
    cell->covered_height += sign*GRID_Y;
801
    cell->uncovered_area += sign*2*fx*GRID_Y;
802
}
803

            
804
static void
805
3
polygon_init (struct polygon *polygon, jmp_buf *jmp)
806
{
807
3
    polygon->ymin = polygon->ymax = 0;
808
3
    polygon->y_buckets = polygon->y_buckets_embedded;
809
3
    pool_init (polygon->edge_pool.base, jmp,
810
	       8192 - sizeof (struct _pool_chunk),
811
	       sizeof (polygon->edge_pool.embedded));
812
3
}
813

            
814
static void
815
3
polygon_fini (struct polygon *polygon)
816
{
817
3
    if (polygon->y_buckets != polygon->y_buckets_embedded)
818
	free (polygon->y_buckets);
819

            
820
3
    pool_fini (polygon->edge_pool.base);
821
3
}
822

            
823
/* Empties the polygon of all edges. The polygon is then prepared to
824
 * receive new edges and clip them to the vertical range
825
 * [ymin,ymax). */
826
static glitter_status_t
827
3
polygon_reset (struct polygon *polygon,
828
	       grid_scaled_y_t ymin,
829
	       grid_scaled_y_t ymax)
830
{
831
3
    unsigned h = ymax - ymin;
832
3
    unsigned num_buckets = EDGE_Y_BUCKET_INDEX(ymax + GRID_Y-1, ymin);
833

            
834
3
    pool_reset(polygon->edge_pool.base);
835

            
836
3
    if (unlikely (h > 0x7FFFFFFFU - GRID_Y))
837
	goto bail_no_mem; /* even if you could, you wouldn't want to. */
838

            
839
3
    if (polygon->y_buckets != polygon->y_buckets_embedded)
840
	free (polygon->y_buckets);
841

            
842
3
    polygon->y_buckets =  polygon->y_buckets_embedded;
843
3
    if (num_buckets > ARRAY_LENGTH (polygon->y_buckets_embedded)) {
844
	polygon->y_buckets = _cairo_malloc_ab (num_buckets,
845
					       sizeof (struct edge *));
846
	if (unlikely (NULL == polygon->y_buckets))
847
	    goto bail_no_mem;
848
    }
849
3
    memset (polygon->y_buckets, 0, num_buckets * sizeof (struct edge *));
850

            
851
3
    polygon->ymin = ymin;
852
3
    polygon->ymax = ymax;
853
3
    return GLITTER_STATUS_SUCCESS;
854

            
855
bail_no_mem:
856
    polygon->ymin = 0;
857
    polygon->ymax = 0;
858
    return GLITTER_STATUS_NO_MEMORY;
859
}
860

            
861
static void
862
204
_polygon_insert_edge_into_its_y_bucket(struct polygon *polygon,
863
				       struct edge *e)
864
{
865
204
    unsigned ix = EDGE_Y_BUCKET_INDEX(e->ytop, polygon->ymin);
866
204
    struct edge **ptail = &polygon->y_buckets[ix];
867
204
    e->next = *ptail;
868
204
    *ptail = e;
869
204
}
870

            
871
inline static void
872
204
polygon_add_edge (struct polygon *polygon,
873
		  const cairo_edge_t *edge)
874
{
875
    struct edge *e;
876
    grid_scaled_x_t dx;
877
    grid_scaled_y_t dy;
878
    grid_scaled_y_t ytop, ybot;
879
204
    grid_scaled_y_t ymin = polygon->ymin;
880
204
    grid_scaled_y_t ymax = polygon->ymax;
881

            
882
204
    if (unlikely (edge->top >= ymax || edge->bottom <= ymin))
883
	return;
884

            
885
204
    e = pool_alloc (polygon->edge_pool.base, sizeof (struct edge));
886

            
887
204
    dx = edge->line.p2.x - edge->line.p1.x;
888
204
    dy = edge->line.p2.y - edge->line.p1.y;
889
204
    e->dy = dy;
890
204
    e->dir = edge->dir;
891

            
892
204
    ytop = edge->top >= ymin ? edge->top : ymin;
893
204
    ybot = edge->bottom <= ymax ? edge->bottom : ymax;
894
204
    e->ytop = ytop;
895
204
    e->height_left = ybot - ytop;
896

            
897
204
    if (dx == 0) {
898
	e->vertical = TRUE;
899
	e->x.quo = edge->line.p1.x;
900
	e->x.rem = 0;
901
	e->dxdy.quo = 0;
902
	e->dxdy.rem = 0;
903
    } else {
904
204
	e->vertical = FALSE;
905
204
	e->dxdy = floored_divrem (dx, dy);
906
204
	if (ytop == edge->line.p1.y) {
907
204
	    e->x.quo = edge->line.p1.x;
908
204
	    e->x.rem = 0;
909
	} else {
910
	    e->x = floored_muldivrem (ytop - edge->line.p1.y, dx, dy);
911
	    e->x.quo += edge->line.p1.x;
912
	}
913
    }
914

            
915
204
    _polygon_insert_edge_into_its_y_bucket (polygon, e);
916

            
917
204
    e->x.rem -= dy;		/* Bias the remainder for faster
918
				 * edge advancement. */
919
}
920

            
921
static void
922
6
active_list_reset (struct active_list *active)
923
{
924
6
    active->head.vertical = 1;
925
6
    active->head.height_left = INT_MAX;
926
6
    active->head.x.quo = INT_MIN;
927
6
    active->head.prev = NULL;
928
6
    active->head.next = &active->tail;
929
6
    active->tail.prev = &active->head;
930
6
    active->tail.next = NULL;
931
6
    active->tail.x.quo = INT_MAX;
932
6
    active->tail.height_left = INT_MAX;
933
6
    active->tail.vertical = 1;
934
6
    active->min_height = 0;
935
6
    active->is_vertical = 1;
936
6
}
937

            
938
static void
939
3
active_list_init(struct active_list *active)
940
{
941
3
    active_list_reset(active);
942
3
}
943

            
944
/*
945
 * Merge two sorted edge lists.
946
 * Input:
947
 *  - head_a: The head of the first list.
948
 *  - head_b: The head of the second list; head_b cannot be NULL.
949
 * Output:
950
 * Returns the head of the merged list.
951
 *
952
 * Implementation notes:
953
 * To make it fast (in particular, to reduce to an insertion sort whenever
954
 * one of the two input lists only has a single element) we iterate through
955
 * a list until its head becomes greater than the head of the other list,
956
 * then we switch their roles. As soon as one of the two lists is empty, we
957
 * just attach the other one to the current list and exit.
958
 * Writes to memory are only needed to "switch" lists (as it also requires
959
 * attaching to the output list the list which we will be iterating next) and
960
 * to attach the last non-empty list.
961
 */
962
static struct edge *
963
102
merge_sorted_edges (struct edge *head_a, struct edge *head_b)
964
{
965
    struct edge *head, **next, *prev;
966
    int32_t x;
967

            
968
102
    prev = head_a->prev;
969
102
    next = &head;
970
102
    if (head_a->x.quo <= head_b->x.quo) {
971
90
	head = head_a;
972
    } else {
973
12
	head = head_b;
974
12
	head_b->prev = prev;
975
12
	goto start_with_b;
976
    }
977

            
978
    do {
979
96
	x = head_b->x.quo;
980
672
	while (head_a != NULL && head_a->x.quo <= x) {
981
576
	    prev = head_a;
982
576
	    next = &head_a->next;
983
576
	    head_a = head_a->next;
984
	}
985

            
986
96
	head_b->prev = prev;
987
96
	*next = head_b;
988
96
	if (head_a == NULL)
989
96
	    return head;
990

            
991
start_with_b:
992
12
	x = head_a->x.quo;
993
222
	while (head_b != NULL && head_b->x.quo <= x) {
994
210
	    prev = head_b;
995
210
	    next = &head_b->next;
996
210
	    head_b = head_b->next;
997
	}
998

            
999
12
	head_a->prev = prev;
12
	*next = head_a;
12
	if (head_b == NULL)
6
	    return head;
    } while (1);
}
/*
 * Sort (part of) a list.
 * Input:
 *  - list: The list to be sorted; list cannot be NULL.
 *  - limit: Recursion limit.
 * Output:
 *  - head_out: The head of the sorted list containing the first 2^(level+1) elements of the
 *              input list; if the input list has fewer elements, head_out be a sorted list
 *              containing all the elements of the input list.
 * Returns the head of the list of unprocessed elements (NULL if the sorted list contains
 * all the elements of the input list).
 *
 * Implementation notes:
 * Special case single element list, unroll/inline the sorting of the first two elements.
 * Some tail recursion is used since we iterate on the bottom-up solution of the problem
 * (we start with a small sorted list and keep merging other lists of the same size to it).
 */
static struct edge *
102
sort_edges (struct edge *list,
	    unsigned int level,
	    struct edge **head_out)
{
    struct edge *head_other, *remaining;
    unsigned int i;
102
    head_other = list->next;
102
    if (head_other == NULL) {
	*head_out = list;
	return NULL;
    }
102
    remaining = head_other->next;
102
    if (list->x.quo <= head_other->x.quo) {
102
	*head_out = list;
102
	head_other->next = NULL;
    } else {
	*head_out = head_other;
	head_other->prev = list->prev;
	head_other->next = list;
	list->prev = head_other;
	list->next = NULL;
    }
198
    for (i = 0; i < level && remaining; i++) {
96
	remaining = sort_edges (remaining, i, &head_other);
96
	*head_out = merge_sorted_edges (*head_out, head_other);
    }
102
    return remaining;
}
static struct edge *
6
merge_unsorted_edges (struct edge *head, struct edge *unsorted)
{
6
    sort_edges (unsorted, UINT_MAX, &unsorted);
6
    return merge_sorted_edges (head, unsorted);
}
/* Test if the edges on the active list can be safely advanced by a
 * full row without intersections or any edges ending. */
inline static int
can_do_full_row (struct active_list *active)
{
    const struct edge *e;
    /* Recomputes the minimum height of all edges on the active
     * list if we have been dropping edges. */
    if (active->min_height <= 0) {
	int min_height = INT_MAX;
	int is_vertical = 1;
	e = active->head.next;
	while (NULL != e) {
	    if (e->height_left < min_height)
		min_height = e->height_left;
	    is_vertical &= e->vertical;
	    e = e->next;
	}
	active->is_vertical = is_vertical;
	active->min_height = min_height;
    }
    if (active->min_height < GRID_Y)
	return 0;
    return active->is_vertical;
}
/* Merges edges on the given subpixel row from the polygon to the
 * active_list. */
inline static void
6
active_list_merge_edges_from_bucket(struct active_list *active,
				    struct edge *edges)
{
6
    active->head.next = merge_unsorted_edges (active->head.next, edges);
6
}
inline static void
6
polygon_fill_buckets (struct active_list *active,
		      struct edge *edge,
		      int y,
		      struct edge **buckets)
{
6
    grid_scaled_y_t min_height = active->min_height;
6
    int is_vertical = active->is_vertical;
210
    while (edge) {
204
	struct edge *next = edge->next;
204
	int suby = edge->ytop - y;
204
	if (buckets[suby])
198
	    buckets[suby]->prev = edge;
204
	edge->next = buckets[suby];
204
	edge->prev = NULL;
204
	buckets[suby] = edge;
204
	if (edge->height_left < min_height)
	    min_height = edge->height_left;
204
	is_vertical &= edge->vertical;
204
	edge = next;
    }
6
    active->is_vertical = is_vertical;
6
    active->min_height = min_height;
6
}
inline static void
24
sub_row (struct active_list *active,
	 struct cell_list *coverages,
	 unsigned int mask)
{
24
    struct edge *edge = active->head.next;
24
    int xstart = INT_MIN, prev_x = INT_MIN;
24
    int winding = 0;
24
    cell_list_rewind (coverages);
840
    while (&active->tail != edge) {
816
	struct edge *next = edge->next;
816
	int xend = edge->x.quo;
816
	if (--edge->height_left) {
612
	    edge->x.quo += edge->dxdy.quo;
612
	    edge->x.rem += edge->dxdy.rem;
612
	    if (edge->x.rem >= 0) {
		++edge->x.quo;
		edge->x.rem -= edge->dy;
	    }
612
	    if (edge->x.quo < prev_x) {
		struct edge *pos = edge->prev;
		pos->next = next;
		next->prev = pos;
		do {
		    pos = pos->prev;
		} while (edge->x.quo < pos->x.quo);
		pos->next->prev = edge;
		edge->next = pos->next;
		edge->prev = pos;
		pos->next = edge;
	    } else
612
		prev_x = edge->x.quo;
	} else {
204
	    edge->prev->next = next;
204
	    next->prev = edge->prev;
	}
816
	winding += edge->dir;
816
	if ((winding & mask) == 0) {
408
	    if (next->x.quo != xend) {
408
		cell_list_add_subspan (coverages, xstart, xend);
408
		xstart = INT_MIN;
	    }
408
	} else if (xstart == INT_MIN)
408
	    xstart = xend;
816
	edge = next;
    }
24
}
inline static void dec (struct edge *e, int h)
{
    e->height_left -= h;
    if (e->height_left == 0) {
	e->prev->next = e->next;
	e->next->prev = e->prev;
    }
}
static void
full_row (struct active_list *active,
	  struct cell_list *coverages,
	  unsigned int mask)
{
    struct edge *left = active->head.next;
    while (&active->tail != left) {
	struct edge *right;
	int winding;
	dec (left, GRID_Y);
	winding = left->dir;
	right = left->next;
	do {
	    dec (right, GRID_Y);
	    winding += right->dir;
	    if ((winding & mask) == 0 && right->next->x.quo != right->x.quo)
		break;
	    right = right->next;
	} while (1);
	cell_list_set_rewind (coverages);
	cell_list_render_edge (coverages, left, +1);
	cell_list_render_edge (coverages, right, -1);
	left = right->next;
    }
}
static void
3
_glitter_scan_converter_init(glitter_scan_converter_t *converter, jmp_buf *jmp)
{
3
    polygon_init(converter->polygon, jmp);
3
    active_list_init(converter->active);
3
    cell_list_init(converter->coverages, jmp);
3
    converter->xmin=0;
3
    converter->ymin=0;
3
    converter->xmax=0;
3
    converter->ymax=0;
3
}
static void
3
_glitter_scan_converter_fini(glitter_scan_converter_t *self)
{
3
    if (self->spans != self->spans_embedded)
3
	free (self->spans);
3
    polygon_fini(self->polygon);
3
    cell_list_fini(self->coverages);
3
    self->xmin=0;
3
    self->ymin=0;
3
    self->xmax=0;
3
    self->ymax=0;
3
}
static grid_scaled_t
12
int_to_grid_scaled(int i, int scale)
{
    /* Clamp to max/min representable scaled number. */
12
    if (i >= 0) {
12
	if (i >= INT_MAX/scale)
	    i = INT_MAX/scale;
    }
    else {
	if (i <= INT_MIN/scale)
	    i = INT_MIN/scale;
    }
12
    return i*scale;
}
#define int_to_grid_scaled_x(x) int_to_grid_scaled((x), GRID_X)
#define int_to_grid_scaled_y(x) int_to_grid_scaled((x), GRID_Y)
I glitter_status_t
3
glitter_scan_converter_reset(
			     glitter_scan_converter_t *converter,
			     int xmin, int ymin,
			     int xmax, int ymax)
{
    glitter_status_t status;
    int max_num_spans;
3
    converter->xmin = 0; converter->xmax = 0;
3
    converter->ymin = 0; converter->ymax = 0;
3
    max_num_spans = xmax - xmin + 1;
3
    if (max_num_spans > ARRAY_LENGTH(converter->spans_embedded)) {
3
	converter->spans = _cairo_malloc_ab (max_num_spans,
					     sizeof (cairo_half_open_span_t));
3
	if (unlikely (converter->spans == NULL))
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    } else
	converter->spans = converter->spans_embedded;
3
    xmin = int_to_grid_scaled_x(xmin);
3
    ymin = int_to_grid_scaled_y(ymin);
3
    xmax = int_to_grid_scaled_x(xmax);
3
    ymax = int_to_grid_scaled_y(ymax);
3
    active_list_reset(converter->active);
3
    cell_list_reset(converter->coverages);
3
    status = polygon_reset(converter->polygon, ymin, ymax);
3
    if (status)
	return status;
3
    converter->xmin = xmin;
3
    converter->xmax = xmax;
3
    converter->ymin = ymin;
3
    converter->ymax = ymax;
3
    return GLITTER_STATUS_SUCCESS;
}
/* INPUT_TO_GRID_X/Y (in_coord, out_grid_scaled, grid_scale)
 *   These macros convert an input coordinate in the client's
 *   device space to the rasterisation grid.
 */
/* Gah.. this bit of ugly defines INPUT_TO_GRID_X/Y so as to use
 * shifts if possible, and something saneish if not.
 */
#if !defined(INPUT_TO_GRID_Y) && defined(GRID_Y_BITS) && GRID_Y_BITS <= GLITTER_INPUT_BITS
#  define INPUT_TO_GRID_Y(in, out) (out) = (in) >> (GLITTER_INPUT_BITS - GRID_Y_BITS)
#else
#  define INPUT_TO_GRID_Y(in, out) INPUT_TO_GRID_general(in, out, GRID_Y)
#endif
#if !defined(INPUT_TO_GRID_X) && defined(GRID_X_BITS) && GRID_X_BITS <= GLITTER_INPUT_BITS
#  define INPUT_TO_GRID_X(in, out) (out) = (in) >> (GLITTER_INPUT_BITS - GRID_X_BITS)
#else
#  define INPUT_TO_GRID_X(in, out) INPUT_TO_GRID_general(in, out, GRID_X)
#endif
#define INPUT_TO_GRID_general(in, out, grid_scale) do {		\
    long long tmp__ = (long long)(grid_scale) * (in);	\
    tmp__ >>= GLITTER_INPUT_BITS;				\
    (out) = tmp__;						\
} while (0)
/* Add a new polygon edge from pixel (x1,y1) to (x2,y2) to the scan
 * converter.  The coordinates represent pixel positions scaled by
 * 2**GLITTER_PIXEL_BITS.  If this function fails then the scan
 * converter should be reset or destroyed.  Dir must be +1 or -1,
 * with the latter reversing the orientation of the edge. */
I void
204
glitter_scan_converter_add_edge (glitter_scan_converter_t *converter,
				 const cairo_edge_t *edge)
{
    cairo_edge_t e;
204
    INPUT_TO_GRID_Y (edge->top, e.top);
204
    INPUT_TO_GRID_Y (edge->bottom, e.bottom);
204
    if (e.top >= e.bottom)
	return;
    /* XXX: possible overflows if GRID_X/Y > 2**GLITTER_INPUT_BITS */
204
    INPUT_TO_GRID_Y (edge->line.p1.y, e.line.p1.y);
204
    INPUT_TO_GRID_Y (edge->line.p2.y, e.line.p2.y);
204
    if (e.line.p1.y == e.line.p2.y)
	e.line.p2.y++; /* Fudge to prevent div-by-zero */
204
    INPUT_TO_GRID_X (edge->line.p1.x, e.line.p1.x);
204
    INPUT_TO_GRID_X (edge->line.p2.x, e.line.p2.x);
204
    e.dir = edge->dir;
204
    polygon_add_edge (converter->polygon, &e);
}
static void
step_edges (struct active_list *active, int count)
{
    struct edge *edge;
    count *= GRID_Y;
    for (edge = active->head.next; edge != &active->tail; edge = edge->next) {
	edge->height_left -= count;
	if (! edge->height_left) {
	    edge->prev->next = edge->next;
	    edge->next->prev = edge->prev;
	}
    }
}
static glitter_status_t
6
blit_a8 (struct cell_list *cells,
	 cairo_span_renderer_t *renderer,
	 cairo_half_open_span_t *spans,
	 int y, int height,
	 int xmin, int xmax)
{
6
    struct cell *cell = cells->head.next;
6
    int prev_x = xmin, last_x = -1;
6
    int16_t cover = 0, last_cover = 0;
    unsigned num_spans;
6
    if (cell == &cells->tail)
	return CAIRO_STATUS_SUCCESS;
    /* Skip cells to the left of the clip region. */
6
    while (cell->x < xmin) {
	cover += cell->covered_height;
	cell = cell->next;
    }
6
    cover *= GRID_X*2;
    /* Form the spans from the coverages and areas. */
6
    num_spans = 0;
309
    for (; cell->x < xmax; cell = cell->next) {
303
	int x = cell->x;
	int16_t area;
303
	if (x > prev_x && cover != last_cover) {
99
	    spans[num_spans].x = prev_x;
99
	    spans[num_spans].coverage = GRID_AREA_TO_ALPHA (cover);
99
	    last_cover = cover;
99
	    last_x = prev_x;
99
	    ++num_spans;
	}
303
	cover += cell->covered_height*GRID_X*2;
303
	area = cover - cell->uncovered_area;
303
	if (area != last_cover) {
303
	    spans[num_spans].x = x;
303
	    spans[num_spans].coverage = GRID_AREA_TO_ALPHA (area);
303
	    last_cover = area;
303
	    last_x = x;
303
	    ++num_spans;
	}
303
	prev_x = x+1;
    }
6
    if (prev_x <= xmax && cover != last_cover) {
6
	spans[num_spans].x = prev_x;
6
	spans[num_spans].coverage = GRID_AREA_TO_ALPHA (cover);
6
	last_cover = cover;
6
	last_x = prev_x;
6
	++num_spans;
    }
6
    if (last_x < xmax && last_cover) {
	spans[num_spans].x = xmax;
	spans[num_spans].coverage = 0;
	++num_spans;
    }
    /* Dump them into the renderer. */
6
    return renderer->render_rows (renderer, y, height, spans, num_spans);
}
#define GRID_AREA_TO_A1(A)  ((GRID_AREA_TO_ALPHA (A) > 127) ? 255 : 0)
static glitter_status_t
blit_a1 (struct cell_list *cells,
	 cairo_span_renderer_t *renderer,
	 cairo_half_open_span_t *spans,
	 int y, int height,
	 int xmin, int xmax)
{
    struct cell *cell = cells->head.next;
    int prev_x = xmin, last_x = -1;
    int16_t cover = 0;
    uint8_t coverage, last_cover = 0;
    unsigned num_spans;
    if (cell == &cells->tail)
	return CAIRO_STATUS_SUCCESS;
    /* Skip cells to the left of the clip region. */
    while (cell->x < xmin) {
	cover += cell->covered_height;
	cell = cell->next;
    }
    cover *= GRID_X*2;
    /* Form the spans from the coverages and areas. */
    num_spans = 0;
    for (; cell->x < xmax; cell = cell->next) {
	int x = cell->x;
	int16_t area;
	coverage = GRID_AREA_TO_A1 (cover);
	if (x > prev_x && coverage != last_cover) {
	    last_x = spans[num_spans].x = prev_x;
	    last_cover = spans[num_spans].coverage = coverage;
	    ++num_spans;
	}
	cover += cell->covered_height*GRID_X*2;
	area = cover - cell->uncovered_area;
	coverage = GRID_AREA_TO_A1 (area);
	if (coverage != last_cover) {
	    last_x = spans[num_spans].x = x;
	    last_cover = spans[num_spans].coverage = coverage;
	    ++num_spans;
	}
	prev_x = x+1;
    }
    coverage = GRID_AREA_TO_A1 (cover);
    if (prev_x <= xmax && coverage != last_cover) {
	last_x = spans[num_spans].x = prev_x;
	last_cover = spans[num_spans].coverage = coverage;
	++num_spans;
    }
    if (last_x < xmax && last_cover) {
	spans[num_spans].x = xmax;
	spans[num_spans].coverage = 0;
	++num_spans;
    }
    if (num_spans == 1)
	return CAIRO_STATUS_SUCCESS;
    /* Dump them into the renderer. */
    return renderer->render_rows (renderer, y, height, spans, num_spans);
}
I void
3
glitter_scan_converter_render(glitter_scan_converter_t *converter,
			      unsigned int winding_mask,
			      int antialias,
			      cairo_span_renderer_t *renderer)
{
    int i, j;
3
    int ymax_i = converter->ymax / GRID_Y;
3
    int ymin_i = converter->ymin / GRID_Y;
    int xmin_i, xmax_i;
3
    int h = ymax_i - ymin_i;
3
    struct polygon *polygon = converter->polygon;
3
    struct cell_list *coverages = converter->coverages;
3
    struct active_list *active = converter->active;
3
    struct edge *buckets[GRID_Y] = { 0 };
3
    xmin_i = converter->xmin / GRID_X;
3
    xmax_i = converter->xmax / GRID_X;
3
    if (xmin_i >= xmax_i)
	return;
    /* Render each pixel row. */
9
    for (i = 0; i < h; i = j) {
6
	int do_full_row = 0;
6
	j = i + 1;
	/* Determine if we can ignore this row or use the full pixel
	 * stepper. */
6
	if (! polygon->y_buckets[i]) {
	    if (active->head.next == &active->tail) {
		active->min_height = INT_MAX;
		active->is_vertical = 1;
		for (; j < h && ! polygon->y_buckets[j]; j++)
		    ;
		continue;
	    }
	    do_full_row = can_do_full_row (active);
	}
6
	if (do_full_row) {
	    /* Step by a full pixel row's worth. */
	    full_row (active, coverages, winding_mask);
	    if (active->is_vertical) {
		while (j < h &&
		       polygon->y_buckets[j] == NULL &&
		       active->min_height >= 2*GRID_Y)
		{
		    active->min_height -= GRID_Y;
		    j++;
		}
		if (j != i + 1)
		    step_edges (active, j - (i + 1));
	    }
	} else {
	    int sub;
6
	    polygon_fill_buckets (active,
6
				  polygon->y_buckets[i],
6
				  (i+ymin_i)*GRID_Y,
				  buckets);
	    /* Subsample this row. */
30
	    for (sub = 0; sub < GRID_Y; sub++) {
24
		if (buckets[sub]) {
6
		    active_list_merge_edges_from_bucket (active, buckets[sub]);
6
		    buckets[sub] = NULL;
		}
24
		sub_row (active, coverages, winding_mask);
	    }
	}
6
	if (antialias)
6
	    blit_a8 (coverages, renderer, converter->spans,
		     i+ymin_i, j-i, xmin_i, xmax_i);
	else
	    blit_a1 (coverages, renderer, converter->spans,
		     i+ymin_i, j-i, xmin_i, xmax_i);
6
	cell_list_reset (coverages);
6
	active->min_height -= GRID_Y;
    }
}
struct _cairo_tor22_scan_converter {
    cairo_scan_converter_t base;
    glitter_scan_converter_t converter[1];
    cairo_fill_rule_t fill_rule;
    cairo_antialias_t antialias;
    jmp_buf jmp;
};
typedef struct _cairo_tor22_scan_converter cairo_tor22_scan_converter_t;
static void
3
_cairo_tor22_scan_converter_destroy (void *converter)
{
3
    cairo_tor22_scan_converter_t *self = converter;
3
    if (self == NULL) {
	return;
    }
3
    _glitter_scan_converter_fini (self->converter);
3
    free(self);
}
cairo_status_t
3
_cairo_tor22_scan_converter_add_polygon (void		*converter,
				       const cairo_polygon_t *polygon)
{
3
    cairo_tor22_scan_converter_t *self = converter;
    int i;
#if 0
    FILE *file = fopen ("polygon.txt", "w");
    _cairo_debug_print_polygon (file, polygon);
    fclose (file);
#endif
207
    for (i = 0; i < polygon->num_edges; i++)
204
	 glitter_scan_converter_add_edge (self->converter, &polygon->edges[i]);
3
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
3
_cairo_tor22_scan_converter_generate (void			*converter,
				    cairo_span_renderer_t	*renderer)
{
3
    cairo_tor22_scan_converter_t *self = converter;
    cairo_status_t status;
3
    if ((status = setjmp (self->jmp)))
	return _cairo_scan_converter_set_error (self, _cairo_error (status));
3
    glitter_scan_converter_render (self->converter,
3
				   self->fill_rule == CAIRO_FILL_RULE_WINDING ? ~0 : 1,
3
				   self->antialias != CAIRO_ANTIALIAS_NONE,
				   renderer);
3
    return CAIRO_STATUS_SUCCESS;
}
cairo_scan_converter_t *
3
_cairo_tor22_scan_converter_create (int			xmin,
				  int			ymin,
				  int			xmax,
				  int			ymax,
				  cairo_fill_rule_t	fill_rule,
				  cairo_antialias_t	antialias)
{
    cairo_tor22_scan_converter_t *self;
    cairo_status_t status;
3
    self = _cairo_calloc (sizeof(struct _cairo_tor22_scan_converter));
3
    if (unlikely (self == NULL)) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto bail_nomem;
    }
3
    self->base.destroy = _cairo_tor22_scan_converter_destroy;
3
    self->base.generate = _cairo_tor22_scan_converter_generate;
3
    _glitter_scan_converter_init (self->converter, &self->jmp);
3
    status = glitter_scan_converter_reset (self->converter,
					   xmin, ymin, xmax, ymax);
3
    if (unlikely (status))
	goto bail;
3
    self->fill_rule = fill_rule;
3
    self->antialias = antialias;
3
    return &self->base;
 bail:
    self->base.destroy(&self->base);
 bail_nomem:
    return _cairo_scan_converter_create_in_error (status);
}