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