1 /*
   2  * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.marlin;
  27 
  28 import static com.sun.marlin.OffHeapArray.SIZE_INT;
  29 import sun.misc.Unsafe;
  30 
  31 public final class RendererNoAA implements MarlinRenderer, MarlinConst {
  32 
  33     static final boolean DISABLE_RENDER = false;
  34 
  35     private static final int ALL_BUT_LSB = 0xFFFFFFFE;
  36     private static final int ERR_STEP_MAX = 0x7FFFFFFF; // = 2^31 - 1
  37 
  38     private static final double POWER_2_TO_32 = 0x1.0p32d;
  39 
  40     private static final float RDR_OFFSET_X = 0.5f;
  41     private static final float RDR_OFFSET_Y = 0.5f;
  42 
  43     // common to all types of input path segments.
  44     // OFFSET as bytes
  45     // only integer values:
  46     public static final long OFF_CURX_OR  = 0;
  47     public static final long OFF_ERROR    = OFF_CURX_OR  + SIZE_INT;
  48     public static final long OFF_BUMP_X   = OFF_ERROR    + SIZE_INT;
  49     public static final long OFF_BUMP_ERR = OFF_BUMP_X   + SIZE_INT;
  50     public static final long OFF_NEXT     = OFF_BUMP_ERR + SIZE_INT;
  51     public static final long OFF_YMAX     = OFF_NEXT     + SIZE_INT;
  52 
  53     // size of one edge in bytes
  54     public static final int SIZEOF_EDGE_BYTES = (int)(OFF_YMAX + SIZE_INT);
  55 
  56     // curve break into lines
  57     // cubic error in subpixels to decrement step
  58     private static final float CUB_DEC_ERR_SUBPIX
  59         = MarlinProperties.getCubicDecD2() * (1.0f / 8.0f); // 1 pixel
  60     // cubic error in subpixels to increment step
  61     private static final float CUB_INC_ERR_SUBPIX
  62         = MarlinProperties.getCubicIncD1() * (1.0f / 8.0f); // 0.4 pixel
  63 
  64     // TestNonAARasterization (JDK-8170879): cubics
  65     // bad paths (59294/100000 == 59,29%, 94335 bad pixels (avg = 1,59), 3966 warnings (avg = 0,07)
  66 
  67     // cubic bind length to decrement step
  68     public static final float CUB_DEC_BND
  69         = 8.0f * CUB_DEC_ERR_SUBPIX;
  70     // cubic bind length to increment step
  71     public static final float CUB_INC_BND
  72         = 8.0f * CUB_INC_ERR_SUBPIX;
  73 
  74     // cubic countlg
  75     public static final int CUB_COUNT_LG = 2;
  76     // cubic count = 2^countlg
  77     private static final int CUB_COUNT = 1 << CUB_COUNT_LG;
  78     // cubic count^2 = 4^countlg
  79     private static final int CUB_COUNT_2 = 1 << (2 * CUB_COUNT_LG);
  80     // cubic count^3 = 8^countlg
  81     private static final int CUB_COUNT_3 = 1 << (3 * CUB_COUNT_LG);
  82     // cubic dt = 1 / count
  83     private static final float CUB_INV_COUNT = 1.0f / CUB_COUNT;
  84     // cubic dt^2 = 1 / count^2 = 1 / 4^countlg
  85     private static final float CUB_INV_COUNT_2 = 1.0f / CUB_COUNT_2;
  86     // cubic dt^3 = 1 / count^3 = 1 / 8^countlg
  87     private static final float CUB_INV_COUNT_3 = 1.0f / CUB_COUNT_3;
  88 
  89     // quad break into lines
  90     // quadratic error in subpixels
  91     private static final float QUAD_DEC_ERR_SUBPIX
  92         = MarlinProperties.getQuadDecD2() * (1.0f / 8.0f); // 0.5 pixel
  93 
  94     // TestNonAARasterization (JDK-8170879): quads
  95     // bad paths (62916/100000 == 62,92%, 103818 bad pixels (avg = 1,65), 6514 warnings (avg = 0,10)
  96 
  97     // quadratic bind length to decrement step
  98     public static final float QUAD_DEC_BND
  99         = 8.0f * QUAD_DEC_ERR_SUBPIX;
 100 
 101 //////////////////////////////////////////////////////////////////////////////
 102 //  SCAN LINE
 103 //////////////////////////////////////////////////////////////////////////////
 104     // crossings ie subpixel edge x coordinates
 105     private int[] crossings;
 106     // auxiliary storage for crossings (merge sort)
 107     private int[] aux_crossings;
 108 
 109     // indices into the segment pointer lists. They indicate the "active"
 110     // sublist in the segment lists (the portion of the list that contains
 111     // all the segments that cross the next scan line).
 112     private int edgeCount;
 113     private int[] edgePtrs;
 114     // auxiliary storage for edge pointers (merge sort)
 115     private int[] aux_edgePtrs;
 116 
 117     // max used for both edgePtrs and crossings (stats only)
 118     private int activeEdgeMaxUsed;
 119 
 120     // crossings ref (dirty)
 121     private final IntArrayCache.Reference crossings_ref;
 122     // edgePtrs ref (dirty)
 123     private final IntArrayCache.Reference edgePtrs_ref;
 124     // merge sort initial arrays (large enough to satisfy most usages) (1024)
 125     // aux_crossings ref (dirty)
 126     private final IntArrayCache.Reference aux_crossings_ref;
 127     // aux_edgePtrs ref (dirty)
 128     private final IntArrayCache.Reference aux_edgePtrs_ref;
 129 
 130 //////////////////////////////////////////////////////////////////////////////
 131 //  EDGE LIST
 132 //////////////////////////////////////////////////////////////////////////////
 133     private int edgeMinY = Integer.MAX_VALUE;
 134     private int edgeMaxY = Integer.MIN_VALUE;
 135     private float edgeMinX = Float.POSITIVE_INFINITY;
 136     private float edgeMaxX = Float.NEGATIVE_INFINITY;
 137 
 138     // edges [ints] stored in off-heap memory
 139     private final OffHeapArray edges;
 140 
 141     private int[] edgeBuckets;
 142     private int[] edgeBucketCounts; // 2*newedges + (1 if pruning needed)
 143     // used range for edgeBuckets / edgeBucketCounts
 144     private int buckets_minY;
 145     private int buckets_maxY;
 146 
 147     // edgeBuckets ref (clean)
 148     private final IntArrayCache.Reference edgeBuckets_ref;
 149     // edgeBucketCounts ref (clean)
 150     private final IntArrayCache.Reference edgeBucketCounts_ref;
 151 
 152     boolean useRLE = false;
 153 
 154     // Flattens using adaptive forward differencing. This only carries out
 155     // one iteration of the AFD loop. All it does is update AFD variables (i.e.
 156     // X0, Y0, D*[X|Y], COUNT; not variables used for computing scanline crossings).
 157     private void quadBreakIntoLinesAndAdd(float x0, float y0,
 158                                           final Curve c,
 159                                           final float x2, final float y2)
 160     {
 161         int count = 1; // dt = 1 / count
 162 
 163         // maximum(ddX|Y) = norm(dbx, dby) * dt^2 (= 1)
 164         float maxDD = Math.abs(c.dbx) + Math.abs(c.dby);
 165 
 166         final float _DEC_BND = QUAD_DEC_BND;
 167 
 168         while (maxDD >= _DEC_BND) {
 169             // divide step by half:
 170             maxDD /= 4.0f; // error divided by 2^2 = 4
 171 
 172             count <<= 1;
 173             if (DO_STATS) {
 174                 rdrCtx.stats.stat_rdr_quadBreak_dec.add(count);
 175             }
 176         }
 177 
 178         int nL = 0; // line count
 179         if (count > 1) {
 180             final float icount = 1.0f / count; // dt
 181             final float icount2 = icount * icount; // dt^2
 182 
 183             final float ddx = c.dbx * icount2;
 184             final float ddy = c.dby * icount2;
 185             float dx = c.bx * icount2 + c.cx * icount;
 186             float dy = c.by * icount2 + c.cy * icount;
 187 
 188             float x1, y1;
 189 
 190             while (--count > 0) {
 191                 x1 = x0 + dx;
 192                 dx += ddx;
 193                 y1 = y0 + dy;
 194                 dy += ddy;
 195 
 196                 addLine(x0, y0, x1, y1);
 197 
 198                 if (DO_STATS) { nL++; }
 199                 x0 = x1;
 200                 y0 = y1;
 201             }
 202         }
 203         addLine(x0, y0, x2, y2);
 204 
 205         if (DO_STATS) {
 206             rdrCtx.stats.stat_rdr_quadBreak.add(nL + 1);
 207         }
 208     }
 209 
 210     // x0, y0 and x3,y3 are the endpoints of the curve. We could compute these
 211     // using c.xat(0),c.yat(0) and c.xat(1),c.yat(1), but this might introduce
 212     // numerical errors, and our callers already have the exact values.
 213     // Another alternative would be to pass all the control points, and call
 214     // c.set here, but then too many numbers are passed around.
 215     private void curveBreakIntoLinesAndAdd(float x0, float y0,
 216                                            final Curve c,
 217                                            final float x3, final float y3)
 218     {
 219         int count           = CUB_COUNT;
 220         final float icount  = CUB_INV_COUNT;   // dt
 221         final float icount2 = CUB_INV_COUNT_2; // dt^2
 222         final float icount3 = CUB_INV_COUNT_3; // dt^3
 223 
 224         // the dx and dy refer to forward differencing variables, not the last
 225         // coefficients of the "points" polynomial
 226         float dddx, dddy, ddx, ddy, dx, dy;
 227         dddx = 2.0f * c.dax * icount3;
 228         dddy = 2.0f * c.day * icount3;
 229         ddx = dddx + c.dbx * icount2;
 230         ddy = dddy + c.dby * icount2;
 231         dx = c.ax * icount3 + c.bx * icount2 + c.cx * icount;
 232         dy = c.ay * icount3 + c.by * icount2 + c.cy * icount;
 233 
 234         // we use x0, y0 to walk the line
 235         float x1 = x0, y1 = y0;
 236         int nL = 0; // line count
 237 
 238         final float _DEC_BND = CUB_DEC_BND;
 239         final float _INC_BND = CUB_INC_BND;
 240 
 241         while (count > 0) {
 242             // divide step by half:
 243             while (Math.abs(ddx) + Math.abs(ddy) >= _DEC_BND) {
 244                 dddx /= 8.0f;
 245                 dddy /= 8.0f;
 246                 ddx = ddx / 4.0f - dddx;
 247                 ddy = ddy / 4.0f - dddy;
 248                 dx = (dx - ddx) / 2.0f;
 249                 dy = (dy - ddy) / 2.0f;
 250 
 251                 count <<= 1;
 252                 if (DO_STATS) {
 253                     rdrCtx.stats.stat_rdr_curveBreak_dec.add(count);
 254                 }
 255             }
 256 
 257             // double step:
 258             // can only do this on even "count" values, because we must divide count by 2
 259             while (count % 2 == 0
 260                    && Math.abs(dx) + Math.abs(dy) <= _INC_BND)
 261             {
 262                 dx = 2.0f * dx + ddx;
 263                 dy = 2.0f * dy + ddy;
 264                 ddx = 4.0f * (ddx + dddx);
 265                 ddy = 4.0f * (ddy + dddy);
 266                 dddx *= 8.0f;
 267                 dddy *= 8.0f;
 268 
 269                 count >>= 1;
 270                 if (DO_STATS) {
 271                     rdrCtx.stats.stat_rdr_curveBreak_inc.add(count);
 272                 }
 273             }
 274             if (--count > 0) {
 275                 x1 += dx;
 276                 dx += ddx;
 277                 ddx += dddx;
 278                 y1 += dy;
 279                 dy += ddy;
 280                 ddy += dddy;
 281             } else {
 282                 x1 = x3;
 283                 y1 = y3;
 284             }
 285 
 286             addLine(x0, y0, x1, y1);
 287 
 288             if (DO_STATS) { nL++; }
 289             x0 = x1;
 290             y0 = y1;
 291         }
 292         if (DO_STATS) {
 293             rdrCtx.stats.stat_rdr_curveBreak.add(nL);
 294         }
 295     }
 296 
 297     private void addLine(float x1, float y1, float x2, float y2) {
 298         if (DO_MONITORS) {
 299             rdrCtx.stats.mon_rdr_addLine.start();
 300         }
 301         if (DO_STATS) {
 302             rdrCtx.stats.stat_rdr_addLine.add(1);
 303         }
 304         int or = 1; // orientation of the line. 1 if y increases, 0 otherwise.
 305         if (y2 < y1) {
 306             or = 0;
 307             float tmp = y2;
 308             y2 = y1;
 309             y1 = tmp;
 310             tmp = x2;
 311             x2 = x1;
 312             x1 = tmp;
 313         }
 314 
 315         // convert subpixel coordinates [float] into pixel positions [int]
 316 
 317         // The index of the pixel that holds the next HPC is at ceil(trueY - 0.5)
 318         // Since y1 and y2 are biased by -0.5 in tosubpixy(), this is simply
 319         // ceil(y1) or ceil(y2)
 320         // upper integer (inclusive)
 321         final int firstCrossing = FloatMath.max(FloatMath.ceil_int(y1), boundsMinY);
 322 
 323         // note: use boundsMaxY (last Y exclusive) to compute correct coverage
 324         // upper integer (exclusive)
 325         final int lastCrossing  = FloatMath.min(FloatMath.ceil_int(y2), boundsMaxY);
 326 
 327         /* skip horizontal lines in pixel space and clip edges
 328            out of y range [boundsMinY; boundsMaxY] */
 329         if (firstCrossing >= lastCrossing) {
 330             if (DO_MONITORS) {
 331                 rdrCtx.stats.mon_rdr_addLine.stop();
 332             }
 333             if (DO_STATS) {
 334                 rdrCtx.stats.stat_rdr_addLine_skip.add(1);
 335             }
 336             return;
 337         }
 338 
 339         // edge min/max X/Y are in subpixel space (half-open interval):
 340         // note: Use integer crossings to ensure consistent range within
 341         // edgeBuckets / edgeBucketCounts arrays in case of NaN values (int = 0)
 342         if (firstCrossing < edgeMinY) {
 343             edgeMinY = firstCrossing;
 344         }
 345         if (lastCrossing > edgeMaxY) {
 346             edgeMaxY = lastCrossing;
 347         }
 348 
 349         // Use double-precision for improved accuracy:
 350         final double x1d   = x1;
 351         final double y1d   = y1;
 352         final double slope = (x1d - x2) / (y1d - y2);
 353 
 354         if (slope >= 0.0d) { // <==> x1 < x2
 355             if (x1 < edgeMinX) {
 356                 edgeMinX = x1;
 357             }
 358             if (x2 > edgeMaxX) {
 359                 edgeMaxX = x2;
 360             }
 361         } else {
 362             if (x2 < edgeMinX) {
 363                 edgeMinX = x2;
 364             }
 365             if (x1 > edgeMaxX) {
 366                 edgeMaxX = x1;
 367             }
 368         }
 369 
 370         // local variables for performance:
 371         final int _SIZEOF_EDGE_BYTES = SIZEOF_EDGE_BYTES;
 372 
 373         final OffHeapArray _edges = edges;
 374 
 375         // get free pointer (ie length in bytes)
 376         final int edgePtr = _edges.used;
 377 
 378         // use substraction to avoid integer overflow:
 379         if (_edges.length - edgePtr < _SIZEOF_EDGE_BYTES) {
 380             // suppose _edges.length > _SIZEOF_EDGE_BYTES
 381             // so doubling size is enough to add needed bytes
 382             // note: throw IOOB if neededSize > 2Gb:
 383             final long edgeNewSize = ArrayCacheConst.getNewLargeSize(
 384                                         _edges.length,
 385                                         edgePtr + _SIZEOF_EDGE_BYTES);
 386 
 387             if (DO_STATS) {
 388                 rdrCtx.stats.stat_rdr_edges_resizes.add(edgeNewSize);
 389             }
 390             _edges.resize(edgeNewSize);
 391         }
 392 
 393 
 394         final Unsafe _unsafe = OffHeapArray.UNSAFE;
 395         final long SIZE_INT = 4L;
 396         long addr   = _edges.address + edgePtr;
 397 
 398         // The x value must be bumped up to its position at the next HPC we will evaluate.
 399         // "firstcrossing" is the (sub)pixel number where the next crossing occurs
 400         // thus, the actual coordinate of the next HPC is "firstcrossing + 0.5"
 401         // so the Y distance we cover is "firstcrossing + 0.5 - trueY".
 402         // Note that since y1 (and y2) are already biased by -0.5 in tosubpixy(), we have
 403         // y1 = trueY - 0.5
 404         // trueY = y1 + 0.5
 405         // firstcrossing + 0.5 - trueY = firstcrossing + 0.5 - (y1 + 0.5)
 406         //                             = firstcrossing - y1
 407         // The x coordinate at that HPC is then:
 408         // x1_intercept = x1 + (firstcrossing - y1) * slope
 409         // The next VPC is then given by:
 410         // VPC index = ceil(x1_intercept - 0.5), or alternately
 411         // VPC index = floor(x1_intercept - 0.5 + 1 - epsilon)
 412         // epsilon is hard to pin down in floating point, but easy in fixed point, so if
 413         // we convert to fixed point then these operations get easier:
 414         // long x1_fixed = x1_intercept * 2^32;  (fixed point 32.32 format)
 415         // curx = next VPC = fixed_floor(x1_fixed - 2^31 + 2^32 - 1)
 416         //                 = fixed_floor(x1_fixed + 2^31 - 1)
 417         //                 = fixed_floor(x1_fixed + 0x7FFFFFFF)
 418         // and error       = fixed_fract(x1_fixed + 0x7FFFFFFF)
 419         final double x1_intercept = x1d + (firstCrossing - y1d) * slope;
 420 
 421         // inlined scalb(x1_intercept, 32):
 422         final long x1_fixed_biased = ((long) (POWER_2_TO_32 * x1_intercept))
 423                                      + 0x7FFFFFFFL;
 424         // curx:
 425         // last bit corresponds to the orientation
 426         _unsafe.putInt(addr, (((int) (x1_fixed_biased >> 31L)) & ALL_BUT_LSB) | or);
 427         addr += SIZE_INT;
 428         _unsafe.putInt(addr,  ((int)  x1_fixed_biased) >>> 1);
 429         addr += SIZE_INT;
 430 
 431         // inlined scalb(slope, 32):
 432         final long slope_fixed = (long) (POWER_2_TO_32 * slope);
 433 
 434         // last bit set to 0 to keep orientation:
 435         _unsafe.putInt(addr, (((int) (slope_fixed >> 31L)) & ALL_BUT_LSB));
 436         addr += SIZE_INT;
 437         _unsafe.putInt(addr,  ((int)  slope_fixed) >>> 1);
 438         addr += SIZE_INT;
 439 
 440         final int[] _edgeBuckets      = edgeBuckets;
 441         final int[] _edgeBucketCounts = edgeBucketCounts;
 442 
 443         final int _boundsMinY = boundsMinY;
 444 
 445         // each bucket is a linked list. this method adds ptr to the
 446         // start of the "bucket"th linked list.
 447         final int bucketIdx = firstCrossing - _boundsMinY;
 448 
 449         // pointer from bucket
 450         _unsafe.putInt(addr, _edgeBuckets[bucketIdx]);
 451         addr += SIZE_INT;
 452         // y max (exclusive)
 453         _unsafe.putInt(addr,  lastCrossing);
 454 
 455         // Update buckets:
 456         // directly the edge struct "pointer"
 457         _edgeBuckets[bucketIdx]       = edgePtr;
 458         _edgeBucketCounts[bucketIdx] += 2; // 1 << 1
 459         // last bit means edge end
 460         _edgeBucketCounts[lastCrossing - _boundsMinY] |= 0x1;
 461 
 462         // update free pointer (ie length in bytes)
 463         _edges.used += _SIZEOF_EDGE_BYTES;
 464 
 465         if (DO_MONITORS) {
 466             rdrCtx.stats.mon_rdr_addLine.stop();
 467         }
 468     }
 469 
 470 // END EDGE LIST
 471 //////////////////////////////////////////////////////////////////////////////
 472 
 473     // Bounds of the drawing region, at subpixel precision.
 474     private int boundsMinX, boundsMinY, boundsMaxX, boundsMaxY;
 475 
 476     // Current winding rule
 477     private int windingRule;
 478 
 479     // Current drawing position, i.e., final point of last segment
 480     private float x0, y0;
 481 
 482     // Position of most recent 'moveTo' command
 483     private float sx0, sy0;
 484 
 485     // per-thread renderer context
 486     final RendererContext rdrCtx;
 487     // dirty curve
 488     private final Curve curve;
 489 
 490     // clean alpha array (zero filled)
 491     private int[] alphaLine;
 492 
 493     // alphaLine ref (clean)
 494     private final IntArrayCache.Reference alphaLine_ref;
 495 
 496     private boolean enableBlkFlags = false;
 497     private boolean prevUseBlkFlags = false;
 498 
 499     /* block flags (0|1) */
 500     private int[] blkFlags;
 501 
 502     // blkFlags ref (clean)
 503     private final IntArrayCache.Reference blkFlags_ref;
 504 
 505     RendererNoAA(final RendererContext rdrCtx) {
 506         this.rdrCtx = rdrCtx;
 507         this.curve = rdrCtx.curve;
 508 
 509         this.edges = rdrCtx.rdrMem.edges;
 510 
 511         edgeBuckets_ref      = rdrCtx.rdrMem.edgeBuckets_ref;
 512         edgeBucketCounts_ref = rdrCtx.rdrMem.edgeBucketCounts_ref;
 513 
 514         edgeBuckets      = edgeBuckets_ref.initial;
 515         edgeBucketCounts = edgeBucketCounts_ref.initial;
 516 
 517         alphaLine_ref = rdrCtx.rdrMem.alphaLine_ref;
 518         alphaLine     = alphaLine_ref.initial;
 519 
 520         crossings_ref     = rdrCtx.rdrMem.crossings_ref;
 521         aux_crossings_ref = rdrCtx.rdrMem.aux_crossings_ref;
 522         edgePtrs_ref      = rdrCtx.rdrMem.edgePtrs_ref;
 523         aux_edgePtrs_ref  = rdrCtx.rdrMem.aux_edgePtrs_ref;
 524 
 525         crossings     = crossings_ref.initial;
 526         aux_crossings = aux_crossings_ref.initial;
 527         edgePtrs      = edgePtrs_ref.initial;
 528         aux_edgePtrs  = aux_edgePtrs_ref.initial;
 529 
 530         blkFlags_ref = rdrCtx.rdrMem.blkFlags_ref;
 531         blkFlags     = blkFlags_ref.initial;
 532     }
 533 
 534     public RendererNoAA init(final int pix_boundsX, final int pix_boundsY,
 535                   final int pix_boundsWidth, final int pix_boundsHeight,
 536                   final int windingRule)
 537     {
 538         this.windingRule = windingRule;
 539 
 540         // bounds as half-open intervals: minX <= x < maxX and minY <= y < maxY
 541         this.boundsMinX = pix_boundsX;
 542         this.boundsMaxX = pix_boundsX + pix_boundsWidth;
 543         this.boundsMinY = pix_boundsY;
 544         this.boundsMaxY = pix_boundsY + pix_boundsHeight;
 545 
 546         if (DO_LOG_BOUNDS) {
 547             MarlinUtils.logInfo("boundsXY = [" + boundsMinX + " ... "
 548                                 + boundsMaxX + "[ [" + boundsMinY + " ... "
 549                                 + boundsMaxY + "[");
 550         }
 551 
 552         // see addLine: ceil(boundsMaxY) => boundsMaxY + 1
 553         // +1 for edgeBucketCounts
 554         final int edgeBucketsLength = (boundsMaxY - boundsMinY) + 1;
 555 
 556         if (edgeBucketsLength > INITIAL_BUCKET_ARRAY) {
 557             if (DO_STATS) {
 558                 rdrCtx.stats.stat_array_renderer_edgeBuckets
 559                     .add(edgeBucketsLength);
 560                 rdrCtx.stats.stat_array_renderer_edgeBucketCounts
 561                     .add(edgeBucketsLength);
 562             }
 563             edgeBuckets = edgeBuckets_ref.getArray(edgeBucketsLength);
 564             edgeBucketCounts = edgeBucketCounts_ref.getArray(edgeBucketsLength);
 565         }
 566 
 567         edgeMinY = Integer.MAX_VALUE;
 568         edgeMaxY = Integer.MIN_VALUE;
 569         edgeMinX = Float.POSITIVE_INFINITY;
 570         edgeMaxX = Float.NEGATIVE_INFINITY;
 571 
 572         // reset used mark:
 573         edgeCount = 0;
 574         activeEdgeMaxUsed = 0;
 575         edges.used = 0;
 576 
 577         // reset bbox:
 578         bboxX0 = 0;
 579         bboxX1 = 0;
 580 
 581         return this; // fluent API
 582     }
 583 
 584     /**
 585      * Disposes this renderer and recycle it clean up before reusing this instance
 586      */
 587     public void dispose() {
 588         if (DO_STATS) {
 589             rdrCtx.stats.stat_rdr_activeEdges.add(activeEdgeMaxUsed);
 590             rdrCtx.stats.stat_rdr_edges.add(edges.used);
 591             rdrCtx.stats.stat_rdr_edges_count.add(edges.used / SIZEOF_EDGE_BYTES);
 592             rdrCtx.stats.hist_rdr_edges_count.add(edges.used / SIZEOF_EDGE_BYTES);
 593             rdrCtx.stats.totalOffHeap += edges.length;
 594         }
 595         // Return arrays:
 596         crossings = crossings_ref.putArray(crossings);
 597         aux_crossings = aux_crossings_ref.putArray(aux_crossings);
 598 
 599         edgePtrs = edgePtrs_ref.putArray(edgePtrs);
 600         aux_edgePtrs = aux_edgePtrs_ref.putArray(aux_edgePtrs);
 601 
 602         alphaLine = alphaLine_ref.putArray(alphaLine, 0, 0); // already zero filled
 603         blkFlags  = blkFlags_ref.putArray(blkFlags, 0, 0); // already zero filled
 604 
 605         if (edgeMinY != Integer.MAX_VALUE) {
 606             // if context is maked as DIRTY:
 607             if (rdrCtx.dirty) {
 608                 // may happen if an exception if thrown in the pipeline processing:
 609                 // clear completely buckets arrays:
 610                 buckets_minY = 0;
 611                 buckets_maxY = boundsMaxY - boundsMinY;
 612             }
 613             // clear only used part
 614             edgeBuckets = edgeBuckets_ref.putArray(edgeBuckets, buckets_minY,
 615                                                                 buckets_maxY);
 616             edgeBucketCounts = edgeBucketCounts_ref.putArray(edgeBucketCounts,
 617                                                              buckets_minY,
 618                                                              buckets_maxY + 1);
 619         } else {
 620             // unused arrays
 621             edgeBuckets = edgeBuckets_ref.putArray(edgeBuckets, 0, 0);
 622             edgeBucketCounts = edgeBucketCounts_ref.putArray(edgeBucketCounts, 0, 0);
 623         }
 624 
 625         // At last: resize back off-heap edges to initial size
 626         if (edges.length != INITIAL_EDGES_CAPACITY) {
 627             // note: may throw OOME:
 628             edges.resize(INITIAL_EDGES_CAPACITY);
 629         }
 630         if (DO_CLEAN_DIRTY) {
 631             // Force zero-fill dirty arrays:
 632             edges.fill(BYTE_0);
 633         }
 634         if (DO_MONITORS) {
 635             rdrCtx.stats.mon_rdr_endRendering.stop();
 636         }
 637     }
 638 
 639     private static float tosubpixx(final float pix_x) {
 640         return pix_x;
 641     }
 642 
 643     private static float tosubpixy(final float pix_y) {
 644         // shift y by -0.5 for fast ceil(y - 0.5):
 645         return pix_y - 0.5f;
 646     }
 647 
 648     @Override
 649     public void moveTo(final float pix_x0, final float pix_y0) {
 650         closePath();
 651         final float sx = tosubpixx(pix_x0);
 652         final float sy = tosubpixy(pix_y0);
 653         this.sx0 = sx;
 654         this.sy0 = sy;
 655         this.x0 = sx;
 656         this.y0 = sy;
 657     }
 658 
 659     @Override
 660     public void lineTo(final float pix_x1, final float pix_y1) {
 661         final float x1 = tosubpixx(pix_x1);
 662         final float y1 = tosubpixy(pix_y1);
 663         addLine(x0, y0, x1, y1);
 664         x0 = x1;
 665         y0 = y1;
 666     }
 667 
 668     @Override
 669     public void curveTo(final float pix_x1, final float pix_y1,
 670                         final float pix_x2, final float pix_y2,
 671                         final float pix_x3, final float pix_y3)
 672     {
 673         final float xe = tosubpixx(pix_x3);
 674         final float ye = tosubpixy(pix_y3);
 675         curve.set(x0, y0, tosubpixx(pix_x1), tosubpixy(pix_y1),
 676                   tosubpixx(pix_x2), tosubpixy(pix_y2), xe, ye);
 677         curveBreakIntoLinesAndAdd(x0, y0, curve, xe, ye);
 678         x0 = xe;
 679         y0 = ye;
 680     }
 681 
 682     @Override
 683     public void quadTo(final float pix_x1, final float pix_y1,
 684                        final float pix_x2, final float pix_y2)
 685     {
 686         final float xe = tosubpixx(pix_x2);
 687         final float ye = tosubpixy(pix_y2);
 688         curve.set(x0, y0, tosubpixx(pix_x1), tosubpixy(pix_y1), xe, ye);
 689         quadBreakIntoLinesAndAdd(x0, y0, curve, xe, ye);
 690         x0 = xe;
 691         y0 = ye;
 692     }
 693 
 694     @Override
 695     public void closePath() {
 696         if (x0 != sx0 || y0 != sy0) {
 697             addLine(x0, y0, sx0, sy0);
 698             x0 = sx0;
 699             y0 = sy0;
 700         }
 701     }
 702 
 703     @Override
 704     public void pathDone() {
 705         closePath();
 706 
 707         // call endRendering() to determine the boundaries:
 708         endRendering();
 709     }
 710 
 711     private void _endRendering(final int ymin, final int ymax,
 712                                final MarlinAlphaConsumer ac)
 713     {
 714         if (DISABLE_RENDER) {
 715             return;
 716         }
 717 
 718         // Get X bounds as true pixel boundaries to compute correct pixel coverage:
 719         final int bboxx0 = bbox_spminX;
 720         final int bboxx1 = bbox_spmaxX;
 721 
 722         final boolean windingRuleEvenOdd = (windingRule == WIND_EVEN_ODD);
 723 
 724         // Useful when processing tile line by tile line
 725         final int[] _alpha = alphaLine;
 726 
 727         // local vars (performance):
 728         final OffHeapArray _edges = edges;
 729         final int[] _edgeBuckets = edgeBuckets;
 730         final int[] _edgeBucketCounts = edgeBucketCounts;
 731 
 732         int[] _crossings = this.crossings;
 733         int[] _edgePtrs  = this.edgePtrs;
 734 
 735         // merge sort auxiliary storage:
 736         int[] _aux_crossings = this.aux_crossings;
 737         int[] _aux_edgePtrs  = this.aux_edgePtrs;
 738 
 739         // copy constants:
 740         final long _OFF_ERROR    = OFF_ERROR;
 741         final long _OFF_BUMP_X   = OFF_BUMP_X;
 742         final long _OFF_BUMP_ERR = OFF_BUMP_ERR;
 743 
 744         final long _OFF_NEXT     = OFF_NEXT;
 745         final long _OFF_YMAX     = OFF_YMAX;
 746 
 747         final int _ALL_BUT_LSB   = ALL_BUT_LSB;
 748         final int _ERR_STEP_MAX  = ERR_STEP_MAX;
 749 
 750         // unsafe I/O:
 751         final Unsafe _unsafe = OffHeapArray.UNSAFE;
 752         final long    addr0  = _edges.address;
 753         long addr;
 754 
 755         final int _MIN_VALUE = Integer.MIN_VALUE;
 756         final int _MAX_VALUE = Integer.MAX_VALUE;
 757 
 758         // Now we iterate through the scanlines. We must tell emitRow the coord
 759         // of the first non-transparent pixel, so we must keep accumulators for
 760         // the first and last pixels of the section of the current pixel row
 761         // that we will emit.
 762         // We also need to accumulate pix_bbox, but the iterator does it
 763         // for us. We will just get the values from it once this loop is done
 764         int minX = _MAX_VALUE;
 765         int maxX = _MIN_VALUE;
 766 
 767         int y = ymin;
 768         int bucket = y - boundsMinY;
 769 
 770         int numCrossings = this.edgeCount;
 771         int edgePtrsLen = _edgePtrs.length;
 772         int crossingsLen = _crossings.length;
 773         int _arrayMaxUsed = activeEdgeMaxUsed;
 774         int ptrLen = 0, newCount, ptrEnd;
 775 
 776         int bucketcount, i, j, ecur;
 777         int cross, lastCross;
 778         int x0, x1, tmp, sum, prev, curx, curxo, crorientation, err;
 779 
 780         int low, high, mid, prevNumCrossings;
 781         boolean useBinarySearch;
 782 
 783         final int[] _blkFlags = blkFlags;
 784         final int _BLK_SIZE_LG = BLOCK_SIZE_LG;
 785         final int _BLK_SIZE = BLOCK_SIZE;
 786 
 787         final boolean _enableBlkFlagsHeuristics = ENABLE_BLOCK_FLAGS_HEURISTICS && this.enableBlkFlags;
 788 
 789         // Use block flags if large pixel span and few crossings:
 790         // ie mean(distance between crossings) is high
 791         boolean useBlkFlags = this.prevUseBlkFlags;
 792 
 793         final int stroking = rdrCtx.stroking;
 794 
 795         int lastY = -1; // last emited row
 796 
 797 
 798         // Iteration on scanlines
 799         for (; y < ymax; y++, bucket++) {
 800             // --- from former ScanLineIterator.next()
 801             bucketcount = _edgeBucketCounts[bucket];
 802 
 803             // marker on previously sorted edges:
 804             prevNumCrossings = numCrossings;
 805 
 806             // bucketCount indicates new edge / edge end:
 807             if (bucketcount != 0) {
 808                 if (DO_STATS) {
 809                     rdrCtx.stats.stat_rdr_activeEdges_updates.add(numCrossings);
 810                 }
 811 
 812                 // last bit set to 1 means that edges ends
 813                 if ((bucketcount & 0x1) != 0) {
 814                     // eviction in active edge list
 815                     // cache edges[] address + offset
 816                     addr = addr0 + _OFF_YMAX;
 817 
 818                     for (i = 0, newCount = 0; i < numCrossings; i++) {
 819                         // get the pointer to the edge
 820                         ecur = _edgePtrs[i];
 821                         // random access so use unsafe:
 822                         if (_unsafe.getInt(addr + ecur) > y) {
 823                             _edgePtrs[newCount++] = ecur;
 824                         }
 825                     }
 826                     // update marker on sorted edges minus removed edges:
 827                     prevNumCrossings = numCrossings = newCount;
 828                 }
 829 
 830                 ptrLen = bucketcount >> 1; // number of new edge
 831 
 832                 if (ptrLen != 0) {
 833                     if (DO_STATS) {
 834                         rdrCtx.stats.stat_rdr_activeEdges_adds.add(ptrLen);
 835                         if (ptrLen > 10) {
 836                             rdrCtx.stats.stat_rdr_activeEdges_adds_high.add(ptrLen);
 837                         }
 838                     }
 839                     ptrEnd = numCrossings + ptrLen;
 840 
 841                     if (edgePtrsLen < ptrEnd) {
 842                         if (DO_STATS) {
 843                             rdrCtx.stats.stat_array_renderer_edgePtrs.add(ptrEnd);
 844                         }
 845                         this.edgePtrs = _edgePtrs
 846                             = edgePtrs_ref.widenArray(_edgePtrs, numCrossings,
 847                                                       ptrEnd);
 848 
 849                         edgePtrsLen = _edgePtrs.length;
 850                         // Get larger auxiliary storage:
 851                         aux_edgePtrs_ref.putArray(_aux_edgePtrs);
 852 
 853                         // use ArrayCache.getNewSize() to use the same growing
 854                         // factor than widenArray():
 855                         if (DO_STATS) {
 856                             rdrCtx.stats.stat_array_renderer_aux_edgePtrs.add(ptrEnd);
 857                         }
 858                         this.aux_edgePtrs = _aux_edgePtrs
 859                             = aux_edgePtrs_ref.getArray(
 860                                 ArrayCacheConst.getNewSize(numCrossings, ptrEnd)
 861                             );
 862                     }
 863 
 864                     // cache edges[] address + offset
 865                     addr = addr0 + _OFF_NEXT;
 866 
 867                     // add new edges to active edge list:
 868                     for (ecur = _edgeBuckets[bucket];
 869                          numCrossings < ptrEnd; numCrossings++)
 870                     {
 871                         // store the pointer to the edge
 872                         _edgePtrs[numCrossings] = ecur;
 873                         // random access so use unsafe:
 874                         ecur = _unsafe.getInt(addr + ecur);
 875                     }
 876 
 877                     if (crossingsLen < numCrossings) {
 878                         // Get larger array:
 879                         crossings_ref.putArray(_crossings);
 880 
 881                         if (DO_STATS) {
 882                             rdrCtx.stats.stat_array_renderer_crossings
 883                                 .add(numCrossings);
 884                         }
 885                         this.crossings = _crossings
 886                             = crossings_ref.getArray(numCrossings);
 887 
 888                         // Get larger auxiliary storage:
 889                         aux_crossings_ref.putArray(_aux_crossings);
 890 
 891                         if (DO_STATS) {
 892                             rdrCtx.stats.stat_array_renderer_aux_crossings
 893                                 .add(numCrossings);
 894                         }
 895                         this.aux_crossings = _aux_crossings
 896                             = aux_crossings_ref.getArray(numCrossings);
 897 
 898                         crossingsLen = _crossings.length;
 899                     }
 900                     if (DO_STATS) {
 901                         // update max used mark
 902                         if (numCrossings > _arrayMaxUsed) {
 903                             _arrayMaxUsed = numCrossings;
 904                         }
 905                     }
 906                 } // ptrLen != 0
 907             } // bucketCount != 0
 908 
 909 
 910             if (numCrossings != 0) {
 911                 /*
 912                  * thresholds to switch to optimized merge sort
 913                  * for newly added edges + final merge pass.
 914                  */
 915                 if ((ptrLen < 10) || (numCrossings < 40)) {
 916                     if (DO_STATS) {
 917                         rdrCtx.stats.hist_rdr_crossings.add(numCrossings);
 918                         rdrCtx.stats.hist_rdr_crossings_adds.add(ptrLen);
 919                     }
 920 
 921                     /*
 922                      * threshold to use binary insertion sort instead of
 923                      * straight insertion sort (to reduce minimize comparisons).
 924                      */
 925                     useBinarySearch = (numCrossings >= 20);
 926 
 927                     // if small enough:
 928                     lastCross = _MIN_VALUE;
 929 
 930                     for (i = 0; i < numCrossings; i++) {
 931                         // get the pointer to the edge
 932                         ecur = _edgePtrs[i];
 933 
 934                         /* convert subpixel coordinates into pixel
 935                             positions for coming scanline */
 936                         /* note: it is faster to always update edges even
 937                            if it is removed from AEL for coming or last scanline */
 938 
 939                         // random access so use unsafe:
 940                         addr = addr0 + ecur; // ecur + OFF_F_CURX
 941 
 942                         // get current crossing:
 943                         curx = _unsafe.getInt(addr);
 944 
 945                         // update crossing with orientation at last bit:
 946                         cross = curx;
 947 
 948                         // Increment x using DDA (fixed point):
 949                         curx += _unsafe.getInt(addr + _OFF_BUMP_X);
 950 
 951                         // Increment error:
 952                         err  =  _unsafe.getInt(addr + _OFF_ERROR)
 953                               + _unsafe.getInt(addr + _OFF_BUMP_ERR);
 954 
 955                         // Manual carry handling:
 956                         // keep sign and carry bit only and ignore last bit (preserve orientation):
 957                         _unsafe.putInt(addr,               curx - ((err >> 30) & _ALL_BUT_LSB));
 958                         _unsafe.putInt(addr + _OFF_ERROR, (err & _ERR_STEP_MAX));
 959 
 960                         if (DO_STATS) {
 961                             rdrCtx.stats.stat_rdr_crossings_updates.add(numCrossings);
 962                         }
 963 
 964                         // insertion sort of crossings:
 965                         if (cross < lastCross) {
 966                             if (DO_STATS) {
 967                                 rdrCtx.stats.stat_rdr_crossings_sorts.add(i);
 968                             }
 969 
 970                             /* use binary search for newly added edges
 971                                in crossings if arrays are large enough */
 972                             if (useBinarySearch && (i >= prevNumCrossings)) {
 973                                 if (DO_STATS) {
 974                                     rdrCtx.stats.stat_rdr_crossings_bsearch.add(i);
 975                                 }
 976                                 low = 0;
 977                                 high = i - 1;
 978 
 979                                 do {
 980                                     // note: use signed shift (not >>>) for performance
 981                                     // as indices are small enough to exceed Integer.MAX_VALUE
 982                                     mid = (low + high) >> 1;
 983 
 984                                     if (_crossings[mid] < cross) {
 985                                         low = mid + 1;
 986                                     } else {
 987                                         high = mid - 1;
 988                                     }
 989                                 } while (low <= high);
 990 
 991                                 for (j = i - 1; j >= low; j--) {
 992                                     _crossings[j + 1] = _crossings[j];
 993                                     _edgePtrs [j + 1] = _edgePtrs[j];
 994                                 }
 995                                 _crossings[low] = cross;
 996                                 _edgePtrs [low] = ecur;
 997 
 998                             } else {
 999                                 j = i - 1;
1000                                 _crossings[i] = _crossings[j];
1001                                 _edgePtrs[i] = _edgePtrs[j];
1002 
1003                                 while ((--j >= 0) && (_crossings[j] > cross)) {
1004                                     _crossings[j + 1] = _crossings[j];
1005                                     _edgePtrs [j + 1] = _edgePtrs[j];
1006                                 }
1007                                 _crossings[j + 1] = cross;
1008                                 _edgePtrs [j + 1] = ecur;
1009                             }
1010 
1011                         } else {
1012                             _crossings[i] = lastCross = cross;
1013                         }
1014                     }
1015                 } else {
1016                     if (DO_STATS) {
1017                         rdrCtx.stats.stat_rdr_crossings_msorts.add(numCrossings);
1018                         rdrCtx.stats.hist_rdr_crossings_ratio
1019                             .add((1000 * ptrLen) / numCrossings);
1020                         rdrCtx.stats.hist_rdr_crossings_msorts.add(numCrossings);
1021                         rdrCtx.stats.hist_rdr_crossings_msorts_adds.add(ptrLen);
1022                     }
1023 
1024                     // Copy sorted data in auxiliary arrays
1025                     // and perform insertion sort on almost sorted data
1026                     // (ie i < prevNumCrossings):
1027 
1028                     lastCross = _MIN_VALUE;
1029 
1030                     for (i = 0; i < numCrossings; i++) {
1031                         // get the pointer to the edge
1032                         ecur = _edgePtrs[i];
1033 
1034                         /* convert subpixel coordinates into pixel
1035                             positions for coming scanline */
1036                         /* note: it is faster to always update edges even
1037                            if it is removed from AEL for coming or last scanline */
1038 
1039                         // random access so use unsafe:
1040                         addr = addr0 + ecur; // ecur + OFF_F_CURX
1041 
1042                         // get current crossing:
1043                         curx = _unsafe.getInt(addr);
1044 
1045                         // update crossing with orientation at last bit:
1046                         cross = curx;
1047 
1048                         // Increment x using DDA (fixed point):
1049                         curx += _unsafe.getInt(addr + _OFF_BUMP_X);
1050 
1051                         // Increment error:
1052                         err  =  _unsafe.getInt(addr + _OFF_ERROR)
1053                               + _unsafe.getInt(addr + _OFF_BUMP_ERR);
1054 
1055                         // Manual carry handling:
1056                         // keep sign and carry bit only and ignore last bit (preserve orientation):
1057                         _unsafe.putInt(addr,               curx - ((err >> 30) & _ALL_BUT_LSB));
1058                         _unsafe.putInt(addr + _OFF_ERROR, (err & _ERR_STEP_MAX));
1059 
1060                         if (DO_STATS) {
1061                             rdrCtx.stats.stat_rdr_crossings_updates.add(numCrossings);
1062                         }
1063 
1064                         if (i >= prevNumCrossings) {
1065                             // simply store crossing as edgePtrs is in-place:
1066                             // will be copied and sorted efficiently by mergesort later:
1067                             _crossings[i]     = cross;
1068 
1069                         } else if (cross < lastCross) {
1070                             if (DO_STATS) {
1071                                 rdrCtx.stats.stat_rdr_crossings_sorts.add(i);
1072                             }
1073 
1074                             // (straight) insertion sort of crossings:
1075                             j = i - 1;
1076                             _aux_crossings[i] = _aux_crossings[j];
1077                             _aux_edgePtrs[i] = _aux_edgePtrs[j];
1078 
1079                             while ((--j >= 0) && (_aux_crossings[j] > cross)) {
1080                                 _aux_crossings[j + 1] = _aux_crossings[j];
1081                                 _aux_edgePtrs [j + 1] = _aux_edgePtrs[j];
1082                             }
1083                             _aux_crossings[j + 1] = cross;
1084                             _aux_edgePtrs [j + 1] = ecur;
1085 
1086                         } else {
1087                             // auxiliary storage:
1088                             _aux_crossings[i] = lastCross = cross;
1089                             _aux_edgePtrs [i] = ecur;
1090                         }
1091                     }
1092 
1093                     // use Mergesort using auxiliary arrays (sort only right part)
1094                     MergeSort.mergeSortNoCopy(_crossings,     _edgePtrs,
1095                                               _aux_crossings, _aux_edgePtrs,
1096                                               numCrossings,   prevNumCrossings);
1097                 }
1098 
1099                 // reset ptrLen
1100                 ptrLen = 0;
1101                 // --- from former ScanLineIterator.next()
1102 
1103 
1104                 /* note: bboxx0 and bboxx1 must be pixel boundaries
1105                    to have correct coverage computation */
1106 
1107                 // right shift on crossings to get the x-coordinate:
1108                 curxo = _crossings[0];
1109                 x0    = curxo >> 1;
1110                 if (x0 < minX) {
1111                     minX = x0; // subpixel coordinate
1112                 }
1113 
1114                 x1 = _crossings[numCrossings - 1] >> 1;
1115                 if (x1 > maxX) {
1116                     maxX = x1; // subpixel coordinate
1117                 }
1118 
1119 
1120                 // compute pixel coverages
1121                 prev = curx = x0;
1122                 // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1123                 // last bit contains orientation (0 or 1)
1124                 crorientation = ((curxo & 0x1) << 1) - 1;
1125 
1126                 if (windingRuleEvenOdd) {
1127                     sum = crorientation;
1128 
1129                     // Even Odd winding rule: take care of mask ie sum(orientations)
1130                     for (i = 1; i < numCrossings; i++) {
1131                         curxo = _crossings[i];
1132                         curx  =  curxo >> 1;
1133                         // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1134                         // last bit contains orientation (0 or 1)
1135                         crorientation = ((curxo & 0x1) << 1) - 1;
1136 
1137                         if ((sum & 0x1) != 0) {
1138                             // TODO: perform line clipping on left-right sides
1139                             // to avoid such bound checks:
1140                             x0 = (prev > bboxx0) ? prev : bboxx0;
1141 
1142                             if (curx < bboxx1) {
1143                                 x1 = curx;
1144                             } else {
1145                                 x1 = bboxx1;
1146                                 // skip right side (fast exit loop):
1147                                 i = numCrossings;
1148                             }
1149 
1150                             if (x0 < x1) {
1151                                 x0 -= bboxx0; // turn x0, x1 from coords to indices
1152                                 x1 -= bboxx0; // in the alpha array.
1153 
1154                                 _alpha[x0] += 1;
1155                                 _alpha[x1] -= 1;
1156 
1157                                 if (useBlkFlags) {
1158                                     // flag used blocks:
1159                                     // note: block processing handles extra pixel:
1160                                     _blkFlags[x0 >> _BLK_SIZE_LG] = 1;
1161                                     _blkFlags[x1 >> _BLK_SIZE_LG] = 1;
1162                                 }
1163                             }
1164                         }
1165 
1166                         sum += crorientation;
1167                         prev = curx;
1168                     }
1169                 } else {
1170                     // Non-zero winding rule: optimize that case (default)
1171                     // and avoid processing intermediate crossings
1172                     for (i = 1, sum = 0;; i++) {
1173                         sum += crorientation;
1174 
1175                         if (sum != 0) {
1176                             // prev = min(curx)
1177                             if (prev > curx) {
1178                                 prev = curx;
1179                             }
1180                         } else {
1181                             // TODO: perform line clipping on left-right sides
1182                             // to avoid such bound checks:
1183                             x0 = (prev > bboxx0) ? prev : bboxx0;
1184 
1185                             if (curx < bboxx1) {
1186                                 x1 = curx;
1187                             } else {
1188                                 x1 = bboxx1;
1189                                 // skip right side (fast exit loop):
1190                                 i = numCrossings;
1191                             }
1192 
1193                             if (x0 < x1) {
1194                                 x0 -= bboxx0; // turn x0, x1 from coords to indices
1195                                 x1 -= bboxx0; // in the alpha array.
1196 
1197                                 _alpha[x0] += 1;
1198                                 _alpha[x1] -= 1;
1199 
1200                                 if (useBlkFlags) {
1201                                     // flag used blocks:
1202                                     // note: block processing handles extra pixel:
1203                                     _blkFlags[x0 >> _BLK_SIZE_LG] = 1;
1204                                     _blkFlags[x1 >> _BLK_SIZE_LG] = 1;
1205                                 }
1206                             }
1207                             prev = _MAX_VALUE;
1208                         }
1209 
1210                         if (i == numCrossings) {
1211                             break;
1212                         }
1213 
1214                         curxo = _crossings[i];
1215                         curx  =  curxo >> 1;
1216                         // to turn {0, 1} into {-1, 1}, multiply by 2 and subtract 1.
1217                         // last bit contains orientation (0 or 1)
1218                         crorientation = ((curxo & 0x1) << 1) - 1;
1219                     }
1220                 }
1221             } // numCrossings > 0
1222 
1223             // even if this last row had no crossings, alpha will be zeroed
1224             // from the last emitRow call. But this doesn't matter because
1225             // maxX < minX, so no row will be emitted to the AlphaConsumer.
1226             if (true) {
1227                 lastY = y;
1228 
1229                 // convert subpixel to pixel coordinate within boundaries:
1230                 minX = FloatMath.max(minX, bboxx0);
1231                 maxX = FloatMath.min(maxX, bboxx1);
1232 
1233                 if (maxX >= minX) {
1234                     // note: alpha array will be zeroed by copyAARow()
1235                     // +1 because alpha [pix_minX; pix_maxX[
1236                     // fix range [x0; x1[
1237                     // note: if x1=bboxx1, then alpha is written up to bboxx1+1
1238                     // inclusive: alpha[bboxx1] ignored, alpha[bboxx1+1] == 0
1239                     // (normally so never cleared below)
1240                     copyAARow(_alpha, lastY, minX, maxX + 1, useBlkFlags, ac);
1241 
1242                     // speculative for next pixel row (scanline coherence):
1243                     if (_enableBlkFlagsHeuristics) {
1244                         // Use block flags if large pixel span and few crossings:
1245                         // ie mean(distance between crossings) is larger than
1246                         // 1 block size;
1247 
1248                         // fast check width:
1249                         maxX -= minX;
1250 
1251                         // if stroking: numCrossings /= 2
1252                         // => shift numCrossings by 1
1253                         // condition = (width / (numCrossings - 1)) > blockSize
1254                         useBlkFlags = (maxX > _BLK_SIZE) && (maxX >
1255                             (((numCrossings >> stroking) - 1) << _BLK_SIZE_LG));
1256 
1257                         if (DO_STATS) {
1258                             tmp = FloatMath.max(1,
1259                                     ((numCrossings >> stroking) - 1));
1260                             rdrCtx.stats.hist_tile_generator_encoding_dist
1261                                 .add(maxX / tmp);
1262                         }
1263                     }
1264                 } else {
1265                     ac.clearAlphas(lastY);
1266                 }
1267                 minX = _MAX_VALUE;
1268                 maxX = _MIN_VALUE;
1269             }
1270         } // scan line iterator
1271 
1272         // Emit final row
1273         y--;
1274 
1275         // convert subpixel to pixel coordinate within boundaries:
1276         minX = FloatMath.max(minX, bboxx0);
1277         maxX = FloatMath.min(maxX, bboxx1);
1278 
1279         if (maxX >= minX) {
1280             // note: alpha array will be zeroed by copyAARow()
1281             // +1 because alpha [pix_minX; pix_maxX[
1282             // fix range [x0; x1[
1283             // note: if x1=bboxx1, then alpha is written up to bboxx1+1
1284             // inclusive: alpha[bboxx1] ignored then cleared and
1285             // alpha[bboxx1+1] == 0 (normally so never cleared after)
1286             copyAARow(_alpha, y, minX, maxX + 1, useBlkFlags, ac);
1287         } else if (y != lastY) {
1288             ac.clearAlphas(y);
1289         }
1290 
1291         // update member:
1292         edgeCount = numCrossings;
1293         prevUseBlkFlags = useBlkFlags;
1294 
1295         if (DO_STATS) {
1296             // update max used mark
1297             activeEdgeMaxUsed = _arrayMaxUsed;
1298         }
1299     }
1300 
1301     void endRendering() {
1302         if (DO_MONITORS) {
1303             rdrCtx.stats.mon_rdr_endRendering.start();
1304         }
1305         if (edgeMinY == Integer.MAX_VALUE) {
1306             return; // undefined edges bounds
1307         }
1308 
1309         // bounds as half-open intervals
1310         final int spminX = FloatMath.max(FloatMath.ceil_int(edgeMinX - 0.5f), boundsMinX);
1311         final int spmaxX = FloatMath.min(FloatMath.ceil_int(edgeMaxX - 0.5f), boundsMaxX);
1312 
1313         // edge Min/Max Y are already rounded to subpixels within bounds:
1314         final int spminY = edgeMinY;
1315         final int spmaxY = edgeMaxY;
1316 
1317         buckets_minY = spminY - boundsMinY;
1318         buckets_maxY = spmaxY - boundsMinY;
1319 
1320         if (DO_LOG_BOUNDS) {
1321             MarlinUtils.logInfo("edgesXY = [" + edgeMinX + " ... " + edgeMaxX
1322                                 + "[ [" + edgeMinY + " ... " + edgeMaxY + "[");
1323             MarlinUtils.logInfo("spXY    = [" + spminX + " ... " + spmaxX
1324                                 + "[ [" + spminY + " ... " + spmaxY + "[");
1325         }
1326 
1327         // test clipping for shapes out of bounds
1328         if ((spminX >= spmaxX) || (spminY >= spmaxY)) {
1329             return;
1330         }
1331 
1332         // half open intervals
1333         // inclusive:
1334         final int pminX = spminX;
1335         // exclusive:
1336         final int pmaxX = spmaxX;
1337         // inclusive:
1338         final int pminY = spminY;
1339         // exclusive:
1340         final int pmaxY = spmaxY;
1341 
1342         // store BBox to answer ptg.getBBox():
1343         initConsumer(pminX, pminY, pmaxX, pmaxY);
1344 
1345         // Heuristics for using block flags:
1346         if (ENABLE_BLOCK_FLAGS) {
1347             enableBlkFlags = this.useRLE;
1348             prevUseBlkFlags = enableBlkFlags && !ENABLE_BLOCK_FLAGS_HEURISTICS;
1349 
1350             if (enableBlkFlags) {
1351                 // ensure blockFlags array is large enough:
1352                 // note: +2 to ensure enough space left at end
1353                 final int blkLen = ((pmaxX - pminX) >> BLOCK_SIZE_LG) + 2;
1354                 if (blkLen > INITIAL_ARRAY) {
1355                     blkFlags = blkFlags_ref.getArray(blkLen);
1356                 }
1357             }
1358         }
1359 
1360         // memorize the rendering bounding box:
1361         /* note: bbox_spminX and bbox_spmaxX must be pixel boundaries
1362            to have correct coverage computation */
1363         // inclusive:
1364         bbox_spminX = pminX;
1365         // exclusive:
1366         bbox_spmaxX = pmaxX;
1367         // inclusive:
1368         bbox_spminY = spminY;
1369         // exclusive:
1370         bbox_spmaxY = spmaxY;
1371 
1372         if (DO_LOG_BOUNDS) {
1373             MarlinUtils.logInfo("pXY       = [" + pminX + " ... " + pmaxX
1374                                 + "[ [" + pminY + " ... " + pmaxY + "[");
1375             MarlinUtils.logInfo("bbox_spXY = [" + bbox_spminX + " ... "
1376                                 + bbox_spmaxX + "[ [" + bbox_spminY + " ... "
1377                                 + bbox_spmaxY + "[");
1378         }
1379 
1380         // Prepare alpha line:
1381         // add 2 to better deal with the last pixel in a pixel row.
1382         final int width = (pmaxX - pminX) + 2;
1383 
1384         // Useful when processing tile line by tile line
1385         if (width > INITIAL_AA_ARRAY) {
1386             if (DO_STATS) {
1387                 rdrCtx.stats.stat_array_renderer_alphaline.add(width);
1388             }
1389             alphaLine = alphaLine_ref.getArray(width);
1390         }
1391     }
1392 
1393     void initConsumer(int minx, int miny, int maxx, int maxy)
1394     {
1395         // assert maxy >= miny && maxx >= minx;
1396         bboxX0 = minx;
1397         bboxX1 = maxx;
1398         bboxY0 = miny;
1399         bboxY1 = maxy;
1400 
1401         final int width = (maxx - minx);
1402 
1403         if (FORCE_NO_RLE) {
1404             useRLE = false;
1405         } else if (FORCE_RLE) {
1406             useRLE = true;
1407         } else {
1408             // heuristics: use both bbox area and complexity
1409             // ie number of primitives:
1410 
1411             // fast check min width:
1412             useRLE = (width > RLE_MIN_WIDTH);
1413         }
1414     }
1415 
1416     private int bbox_spminX, bbox_spmaxX, bbox_spminY, bbox_spmaxY;
1417 
1418     public void produceAlphas(final MarlinAlphaConsumer ac) {
1419         ac.setMaxAlpha(1);
1420 
1421         if (enableBlkFlags && !ac.supportBlockFlags()) {
1422             // consumer does not support block flag optimization:
1423             enableBlkFlags = false;
1424             prevUseBlkFlags = false;
1425         }
1426 
1427         if (DO_MONITORS) {
1428             rdrCtx.stats.mon_rdr_endRendering_Y.start();
1429         }
1430 
1431         // Process all scan lines:
1432         _endRendering(bbox_spminY, bbox_spmaxY, ac);
1433 
1434         if (DO_MONITORS) {
1435             rdrCtx.stats.mon_rdr_endRendering_Y.stop();
1436         }
1437     }
1438 
1439     void copyAARow(final int[] alphaRow,
1440                    final int pix_y, final int pix_from, final int pix_to,
1441                    final boolean useBlockFlags,
1442                    final MarlinAlphaConsumer ac)
1443     {
1444         if (DO_MONITORS) {
1445             rdrCtx.stats.mon_rdr_copyAARow.start();
1446         }
1447         if (DO_STATS) {
1448             rdrCtx.stats.stat_cache_rowAA.add(pix_to - pix_from);
1449         }
1450 
1451         if (useBlockFlags) {
1452             if (DO_STATS) {
1453                 rdrCtx.stats.hist_tile_generator_encoding.add(1);
1454             }
1455             ac.setAndClearRelativeAlphas(blkFlags, alphaRow, pix_y, pix_from, pix_to);
1456         } else {
1457             if (DO_STATS) {
1458                 rdrCtx.stats.hist_tile_generator_encoding.add(0);
1459             }
1460             ac.setAndClearRelativeAlphas(alphaRow, pix_y, pix_from, pix_to);
1461         }
1462         if (DO_MONITORS) {
1463             rdrCtx.stats.mon_rdr_copyAARow.stop();
1464         }
1465     }
1466 
1467     // output pixel bounding box:
1468     int bboxX0, bboxX1, bboxY0, bboxY1;
1469 
1470     @Override
1471     public int getOutpixMinX() {
1472         return bboxX0;
1473     }
1474 
1475     @Override
1476     public int getOutpixMaxX() {
1477         return bboxX1;
1478     }
1479 
1480     @Override
1481     public int getOutpixMinY() {
1482         return bboxY0;
1483     }
1484 
1485     @Override
1486     public int getOutpixMaxY() {
1487         return bboxY1;
1488     }
1489 
1490     @Override
1491     public float getOffsetX() {
1492         return RDR_OFFSET_X;
1493     }
1494 
1495     @Override
1496     public float getOffsetY() {
1497         return RDR_OFFSET_Y;
1498     }
1499 }