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