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