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