1 /*
   2  * Copyright (c) 2007, 2016, 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 java.util.Arrays;
  29 import com.sun.javafx.geom.PathConsumer2D;
  30 
  31 /**
  32  * The <code>Dasher</code> class takes a series of linear commands
  33  * (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and
  34  * <code>end</code>) and breaks them into smaller segments according to a
  35  * dash pattern array and a starting dash phase.
  36  *
  37  * <p> Issues: in J2Se, a zero length dash segment as drawn as a very
  38  * short dash, whereas Pisces does not draw anything.  The PostScript
  39  * semantics are unclear.
  40  *
  41  */
  42 public final class Dasher implements PathConsumer2D, MarlinConst {
  43 
  44     static final int REC_LIMIT = 4;
  45     static final float ERR = 0.01f;
  46     static final float MIN_T_INC = 1f / (1 << REC_LIMIT);
  47 
  48     // More than 24 bits of mantissa means we can no longer accurately
  49     // measure the number of times cycled through the dash array so we
  50     // punt and override the phase to just be 0 past that point.
  51     static final float MAX_CYCLES = 16000000f;
  52 
  53     private PathConsumer2D out;
  54     private float[] dash;
  55     private int dashLen;
  56     private float startPhase;
  57     private boolean startDashOn;
  58     private int startIdx;
  59 
  60     private boolean starting;
  61     private boolean needsMoveTo;
  62 
  63     private int idx;
  64     private boolean dashOn;
  65     private float phase;
  66 
  67     private float sx, sy;
  68     private float x0, y0;
  69 
  70     // temporary storage for the current curve
  71     private final float[] curCurvepts;
  72 
  73     // per-thread renderer context
  74     final RendererContext rdrCtx;
  75 
  76     // flag to recycle dash array copy
  77     boolean recycleDashes;
  78 
  79     // dashes ref (dirty)
  80     final FloatArrayCache.Reference dashes_ref;
  81     // firstSegmentsBuffer ref (dirty)
  82     final FloatArrayCache.Reference firstSegmentsBuffer_ref;
  83 
  84     /**
  85      * Constructs a <code>Dasher</code>.
  86      * @param rdrCtx per-thread renderer context
  87      */
  88     Dasher(final RendererContext rdrCtx) {
  89         this.rdrCtx = rdrCtx;
  90 
  91         dashes_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
  92 
  93         firstSegmentsBuffer_ref = rdrCtx.newDirtyFloatArrayRef(INITIAL_ARRAY); // 1K
  94         firstSegmentsBuffer     = firstSegmentsBuffer_ref.initial;
  95 
  96         // we need curCurvepts to be able to contain 2 curves because when
  97         // dashing curves, we need to subdivide it
  98         curCurvepts = new float[8 * 2];
  99     }
 100 
 101     /**
 102      * Initialize the <code>Dasher</code>.
 103      *
 104      * @param out an output <code>PathConsumer2D</code>.
 105      * @param dash an array of <code>float</code>s containing the dash pattern
 106      * @param dashLen length of the given dash array
 107      * @param phase a <code>float</code> containing the dash phase
 108      * @param recycleDashes true to indicate to recycle the given dash array
 109      * @return this instance
 110      */
 111     public Dasher init(final PathConsumer2D out, float[] dash, int dashLen,
 112                 float phase, boolean recycleDashes)
 113     {
 114         this.out = out;
 115 
 116         // Normalize so 0 <= phase < dash[0]
 117         int sidx = 0;
 118         dashOn = true;
 119         float sum = 0f;
 120         for (float d : dash) {
 121             sum += d;
 122         }
 123         float cycles = phase / sum;
 124         if (phase < 0f) {
 125             if (-cycles >= MAX_CYCLES) {
 126                 phase = 0f;
 127             } else {
 128                 int fullcycles = FloatMath.floor_int(-cycles);
 129                 if ((fullcycles & dash.length & 1) != 0) {
 130                     dashOn = !dashOn;
 131                 }
 132                 phase += fullcycles * sum;
 133                 while (phase < 0f) {
 134                     if (--sidx < 0) {
 135                         sidx = dash.length - 1;
 136                     }
 137                     phase += dash[sidx];
 138                     dashOn = !dashOn;
 139                 }
 140             }
 141         } else if (phase > 0) {
 142             if (cycles >= MAX_CYCLES) {
 143                 phase = 0f;
 144             } else {
 145                 int fullcycles = FloatMath.floor_int(cycles);
 146                 if ((fullcycles & dash.length & 1) != 0) {
 147                     dashOn = !dashOn;
 148                 }
 149                 phase -= fullcycles * sum;
 150                 float d;
 151                 while (phase >= (d = dash[sidx])) {
 152                     phase -= d;
 153                     sidx = (sidx + 1) % dash.length;
 154                     dashOn = !dashOn;
 155                 }
 156             }
 157         }
 158 
 159         this.dash = dash;
 160         this.dashLen = dashLen;
 161         this.startPhase = this.phase = phase;
 162         this.startDashOn = dashOn;
 163         this.startIdx = sidx;
 164         this.starting = true;
 165         needsMoveTo = false;
 166         firstSegidx = 0;
 167 
 168         this.recycleDashes = recycleDashes;
 169 
 170         return this; // fluent API
 171     }
 172 
 173     /**
 174      * Disposes this dasher:
 175      * clean up before reusing this instance
 176      */
 177     void dispose() {
 178         if (DO_CLEAN_DIRTY) {
 179             // Force zero-fill dirty arrays:
 180             Arrays.fill(curCurvepts, 0f);
 181         }
 182         // Return arrays:
 183         if (recycleDashes) {
 184             dash = dashes_ref.putArray(dash);
 185         }
 186         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 187     }
 188 
 189     public float[] copyDashArray(final float[] dashes) {
 190         final int len = dashes.length;
 191         final float[] newDashes;
 192         if (len <= MarlinConst.INITIAL_ARRAY) {
 193             newDashes = rdrCtx.dasher.dashes_ref.initial;
 194         } else {
 195             if (DO_STATS) {
 196                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 197             }
 198             newDashes = rdrCtx.dasher.dashes_ref.getArray(len);
 199         }
 200         System.arraycopy(dashes, 0, newDashes, 0, len);
 201         return newDashes;
 202     }
 203 
 204     @Override
 205     public void moveTo(float x0, float y0) {
 206         if (firstSegidx > 0) {
 207             out.moveTo(sx, sy);
 208             emitFirstSegments();
 209         }
 210         needsMoveTo = true;
 211         this.idx = startIdx;
 212         this.dashOn = this.startDashOn;
 213         this.phase = this.startPhase;
 214         this.sx = this.x0 = x0;
 215         this.sy = this.y0 = y0;
 216         this.starting = true;
 217     }
 218 
 219     private void emitSeg(float[] buf, int off, int type) {
 220         switch (type) {
 221         case 8:
 222             out.curveTo(buf[off+0], buf[off+1],
 223                         buf[off+2], buf[off+3],
 224                         buf[off+4], buf[off+5]);
 225             return;
 226         case 6:
 227             out.quadTo(buf[off+0], buf[off+1],
 228                        buf[off+2], buf[off+3]);
 229             return;
 230         case 4:
 231             out.lineTo(buf[off], buf[off+1]);
 232             return;
 233         default:
 234         }
 235     }
 236 
 237     private void emitFirstSegments() {
 238         final float[] fSegBuf = firstSegmentsBuffer;
 239 
 240         for (int i = 0; i < firstSegidx; ) {
 241             int type = (int)fSegBuf[i];
 242             emitSeg(fSegBuf, i + 1, type);
 243             i += (type - 1);
 244         }
 245         firstSegidx = 0;
 246     }
 247     // We don't emit the first dash right away. If we did, caps would be
 248     // drawn on it, but we need joins to be drawn if there's a closePath()
 249     // So, we store the path elements that make up the first dash in the
 250     // buffer below.
 251     private float[] firstSegmentsBuffer; // dynamic array
 252     private int firstSegidx;
 253 
 254     // precondition: pts must be in relative coordinates (relative to x0,y0)
 255     // fullCurve is true iff the curve in pts has not been split.
 256     private void goTo(float[] pts, int off, final int type) {
 257         float x = pts[off + type - 4];
 258         float y = pts[off + type - 3];
 259         if (dashOn) {
 260             if (starting) {
 261                 int len = type - 1; // - 2 + 1
 262                 int segIdx = firstSegidx;
 263                 float[] buf = firstSegmentsBuffer;
 264                 if (segIdx + len  > buf.length) {
 265                     if (DO_STATS) {
 266                         rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 267                             .add(segIdx + len);
 268                     }
 269                     firstSegmentsBuffer = buf
 270                         = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 271                                                              segIdx + len);
 272                 }
 273                 buf[segIdx++] = type;
 274                 len--;
 275                 // small arraycopy (2, 4 or 6) but with offset:
 276                 System.arraycopy(pts, off, buf, segIdx, len);
 277                 segIdx += len;
 278                 firstSegidx = segIdx;
 279             } else {
 280                 if (needsMoveTo) {
 281                     out.moveTo(x0, y0);
 282                     needsMoveTo = false;
 283                 }
 284                 emitSeg(pts, off, type);
 285             }
 286         } else {
 287             starting = false;
 288             needsMoveTo = true;
 289         }
 290         this.x0 = x;
 291         this.y0 = y;
 292     }
 293 
 294     @Override
 295     public void lineTo(float x1, float y1) {
 296         float dx = x1 - x0;
 297         float dy = y1 - y0;
 298 
 299         float len = dx*dx + dy*dy;
 300         if (len == 0f) {
 301             return;
 302         }
 303         len = (float) Math.sqrt(len);
 304 
 305         // The scaling factors needed to get the dx and dy of the
 306         // transformed dash segments.
 307         final float cx = dx / len;
 308         final float cy = dy / len;
 309 
 310         final float[] _curCurvepts = curCurvepts;
 311         final float[] _dash = dash;
 312 
 313         float leftInThisDashSegment;
 314         float dashdx, dashdy, p;
 315 
 316         while (true) {
 317             leftInThisDashSegment = _dash[idx] - phase;
 318 
 319             if (len <= leftInThisDashSegment) {
 320                 _curCurvepts[0] = x1;
 321                 _curCurvepts[1] = y1;
 322                 goTo(_curCurvepts, 0, 4);
 323 
 324                 // Advance phase within current dash segment
 325                 phase += len;
 326                 // TODO: compare float values using epsilon:
 327                 if (len == leftInThisDashSegment) {
 328                     phase = 0f;
 329                     idx = (idx + 1) % dashLen;
 330                     dashOn = !dashOn;
 331                 }
 332                 return;
 333             }
 334 
 335             dashdx = _dash[idx] * cx;
 336             dashdy = _dash[idx] * cy;
 337 
 338             if (phase == 0f) {
 339                 _curCurvepts[0] = x0 + dashdx;
 340                 _curCurvepts[1] = y0 + dashdy;
 341             } else {
 342                 p = leftInThisDashSegment / _dash[idx];
 343                 _curCurvepts[0] = x0 + p * dashdx;
 344                 _curCurvepts[1] = y0 + p * dashdy;
 345             }
 346 
 347             goTo(_curCurvepts, 0, 4);
 348 
 349             len -= leftInThisDashSegment;
 350             // Advance to next dash segment
 351             idx = (idx + 1) % dashLen;
 352             dashOn = !dashOn;
 353             phase = 0f;
 354         }
 355     }
 356 
 357     // shared instance in Dasher
 358     private final LengthIterator li = new LengthIterator();
 359 
 360     // preconditions: curCurvepts must be an array of length at least 2 * type,
 361     // that contains the curve we want to dash in the first type elements
 362     private void somethingTo(int type) {
 363         if (pointCurve(curCurvepts, type)) {
 364             return;
 365         }
 366         li.initializeIterationOnCurve(curCurvepts, type);
 367 
 368         // initially the current curve is at curCurvepts[0...type]
 369         int curCurveoff = 0;
 370         float lastSplitT = 0f;
 371         float t;
 372         float leftInThisDashSegment = dash[idx] - phase;
 373 
 374         while ((t = li.next(leftInThisDashSegment)) < 1f) {
 375             if (t != 0f) {
 376                 Helpers.subdivideAt((t - lastSplitT) / (1f - lastSplitT),
 377                                     curCurvepts, curCurveoff,
 378                                     curCurvepts, 0,
 379                                     curCurvepts, type, type);
 380                 lastSplitT = t;
 381                 goTo(curCurvepts, 2, type);
 382                 curCurveoff = type;
 383             }
 384             // Advance to next dash segment
 385             idx = (idx + 1) % dashLen;
 386             dashOn = !dashOn;
 387             phase = 0f;
 388             leftInThisDashSegment = dash[idx];
 389         }
 390         goTo(curCurvepts, curCurveoff+2, type);
 391         phase += li.lastSegLen();
 392         if (phase >= dash[idx]) {
 393             phase = 0f;
 394             idx = (idx + 1) % dashLen;
 395             dashOn = !dashOn;
 396         }
 397         // reset LengthIterator:
 398         li.reset();
 399     }
 400 
 401     private static boolean pointCurve(float[] curve, int type) {
 402         for (int i = 2; i < type; i++) {
 403             if (curve[i] != curve[i-2]) {
 404                 return false;
 405             }
 406         }
 407         return true;
 408     }
 409 
 410     // Objects of this class are used to iterate through curves. They return
 411     // t values where the left side of the curve has a specified length.
 412     // It does this by subdividing the input curve until a certain error
 413     // condition has been met. A recursive subdivision procedure would
 414     // return as many as 1<<limit curves, but this is an iterator and we
 415     // don't need all the curves all at once, so what we carry out a
 416     // lazy inorder traversal of the recursion tree (meaning we only move
 417     // through the tree when we need the next subdivided curve). This saves
 418     // us a lot of memory because at any one time we only need to store
 419     // limit+1 curves - one for each level of the tree + 1.
 420     // NOTE: the way we do things here is not enough to traverse a general
 421     // tree; however, the trees we are interested in have the property that
 422     // every non leaf node has exactly 2 children
 423     static final class LengthIterator {
 424         private enum Side {LEFT, RIGHT};
 425         // Holds the curves at various levels of the recursion. The root
 426         // (i.e. the original curve) is at recCurveStack[0] (but then it
 427         // gets subdivided, the left half is put at 1, so most of the time
 428         // only the right half of the original curve is at 0)
 429         private final float[][] recCurveStack; // dirty
 430         // sides[i] indicates whether the node at level i+1 in the path from
 431         // the root to the current leaf is a left or right child of its parent.
 432         private final Side[] sides; // dirty
 433         private int curveType;
 434         // lastT and nextT delimit the current leaf.
 435         private float nextT;
 436         private float lenAtNextT;
 437         private float lastT;
 438         private float lenAtLastT;
 439         private float lenAtLastSplit;
 440         private float lastSegLen;
 441         // the current level in the recursion tree. 0 is the root. limit
 442         // is the deepest possible leaf.
 443         private int recLevel;
 444         private boolean done;
 445 
 446         // the lengths of the lines of the control polygon. Only its first
 447         // curveType/2 - 1 elements are valid. This is an optimization. See
 448         // next(float) for more detail.
 449         private final float[] curLeafCtrlPolyLengths = new float[3];
 450 
 451         LengthIterator() {
 452             this.recCurveStack = new float[REC_LIMIT + 1][8];
 453             this.sides = new Side[REC_LIMIT];
 454             // if any methods are called without first initializing this object
 455             // on a curve, we want it to fail ASAP.
 456             this.nextT = Float.MAX_VALUE;
 457             this.lenAtNextT = Float.MAX_VALUE;
 458             this.lenAtLastSplit = Float.MIN_VALUE;
 459             this.recLevel = Integer.MIN_VALUE;
 460             this.lastSegLen = Float.MAX_VALUE;
 461             this.done = true;
 462         }
 463 
 464         /**
 465          * Reset this LengthIterator.
 466          */
 467         void reset() {
 468             // keep data dirty
 469             // as it appears not useful to reset data:
 470             if (DO_CLEAN_DIRTY) {
 471                 final int recLimit = recCurveStack.length - 1;
 472                 for (int i = recLimit; i >= 0; i--) {
 473                     Arrays.fill(recCurveStack[i], 0f);
 474                 }
 475                 Arrays.fill(sides, Side.LEFT);
 476                 Arrays.fill(curLeafCtrlPolyLengths, 0f);
 477                 Arrays.fill(nextRoots, 0f);
 478                 Arrays.fill(flatLeafCoefCache, 0f);
 479                 flatLeafCoefCache[2] = -1f;
 480             }
 481         }
 482 
 483         void initializeIterationOnCurve(float[] pts, int type) {
 484             // optimize arraycopy (8 values faster than 6 = type):
 485             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 486             this.curveType = type;
 487             this.recLevel = 0;
 488             this.lastT = 0f;
 489             this.lenAtLastT = 0f;
 490             this.nextT = 0f;
 491             this.lenAtNextT = 0f;
 492             goLeft(); // initializes nextT and lenAtNextT properly
 493             this.lenAtLastSplit = 0f;
 494             if (recLevel > 0) {
 495                 this.sides[0] = Side.LEFT;
 496                 this.done = false;
 497             } else {
 498                 // the root of the tree is a leaf so we're done.
 499                 this.sides[0] = Side.RIGHT;
 500                 this.done = true;
 501             }
 502             this.lastSegLen = 0f;
 503         }
 504 
 505         // 0 == false, 1 == true, -1 == invalid cached value.
 506         private int cachedHaveLowAcceleration = -1;
 507 
 508         private boolean haveLowAcceleration(float err) {
 509             if (cachedHaveLowAcceleration == -1) {
 510                 final float len1 = curLeafCtrlPolyLengths[0];
 511                 final float len2 = curLeafCtrlPolyLengths[1];
 512                 // the test below is equivalent to !within(len1/len2, 1, err).
 513                 // It is using a multiplication instead of a division, so it
 514                 // should be a bit faster.
 515                 if (!Helpers.within(len1, len2, err*len2)) {
 516                     cachedHaveLowAcceleration = 0;
 517                     return false;
 518                 }
 519                 if (curveType == 8) {
 520                     final float len3 = curLeafCtrlPolyLengths[2];
 521                     // if len1 is close to 2 and 2 is close to 3, that probably
 522                     // means 1 is close to 3 so the second part of this test might
 523                     // not be needed, but it doesn't hurt to include it.
 524                     final float errLen3 = err * len3;
 525                     if (!(Helpers.within(len2, len3, errLen3) &&
 526                           Helpers.within(len1, len3, errLen3))) {
 527                         cachedHaveLowAcceleration = 0;
 528                         return false;
 529                     }
 530                 }
 531                 cachedHaveLowAcceleration = 1;
 532                 return true;
 533             }
 534 
 535             return (cachedHaveLowAcceleration == 1);
 536         }
 537 
 538         // we want to avoid allocations/gc so we keep this array so we
 539         // can put roots in it,
 540         private final float[] nextRoots = new float[4];
 541 
 542         // caches the coefficients of the current leaf in its flattened
 543         // form (see inside next() for what that means). The cache is
 544         // invalid when it's third element is negative, since in any
 545         // valid flattened curve, this would be >= 0.
 546         private final float[] flatLeafCoefCache = new float[]{0f, 0f, -1f, 0f};
 547 
 548         // returns the t value where the remaining curve should be split in
 549         // order for the left subdivided curve to have length len. If len
 550         // is >= than the length of the uniterated curve, it returns 1.
 551         float next(final float len) {
 552             final float targetLength = lenAtLastSplit + len;
 553             while (lenAtNextT < targetLength) {
 554                 if (done) {
 555                     lastSegLen = lenAtNextT - lenAtLastSplit;
 556                     return 1f;
 557                 }
 558                 goToNextLeaf();
 559             }
 560             lenAtLastSplit = targetLength;
 561             final float leaflen = lenAtNextT - lenAtLastT;
 562             float t = (targetLength - lenAtLastT) / leaflen;
 563 
 564             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 565             // if the acceleration in this section of the curve is small enough.
 566             if (!haveLowAcceleration(0.05f)) {
 567                 // We flatten the current leaf along the x axis, so that we're
 568                 // left with a, b, c which define a 1D Bezier curve. We then
 569                 // solve this to get the parameter of the original leaf that
 570                 // gives us the desired length.
 571                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 572 
 573                 if (_flatLeafCoefCache[2] < 0) {
 574                     float x = 0f + curLeafCtrlPolyLengths[0],
 575                           y = x  + curLeafCtrlPolyLengths[1];
 576                     if (curveType == 8) {
 577                         float z = y + curLeafCtrlPolyLengths[2];
 578                         _flatLeafCoefCache[0] = 3f * (x - y) + z;
 579                         _flatLeafCoefCache[1] = 3f * (y - 2f * x);
 580                         _flatLeafCoefCache[2] = 3f * x;
 581                         _flatLeafCoefCache[3] = -z;
 582                     } else if (curveType == 6) {
 583                         _flatLeafCoefCache[0] = 0f;
 584                         _flatLeafCoefCache[1] = y - 2f * x;
 585                         _flatLeafCoefCache[2] = 2f * x;
 586                         _flatLeafCoefCache[3] = -y;
 587                     }
 588                 }
 589                 float a = _flatLeafCoefCache[0];
 590                 float b = _flatLeafCoefCache[1];
 591                 float c = _flatLeafCoefCache[2];
 592                 float d = t * _flatLeafCoefCache[3];
 593 
 594                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 595                 // and our quadratic root finder doesn't filter, so it's just a
 596                 // matter of convenience.
 597                 int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0, 1);
 598                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 599                     t = nextRoots[0];
 600                 }
 601             }
 602             // t is relative to the current leaf, so we must make it a valid parameter
 603             // of the original curve.
 604             t = t * (nextT - lastT) + lastT;
 605             if (t >= 1f) {
 606                 t = 1f;
 607                 done = true;
 608             }
 609             // even if done = true, if we're here, that means targetLength
 610             // is equal to, or very, very close to the total length of the
 611             // curve, so lastSegLen won't be too high. In cases where len
 612             // overshoots the curve, this method will exit in the while
 613             // loop, and lastSegLen will still be set to the right value.
 614             lastSegLen = len;
 615             return t;
 616         }
 617 
 618         float lastSegLen() {
 619             return lastSegLen;
 620         }
 621 
 622         // go to the next leaf (in an inorder traversal) in the recursion tree
 623         // preconditions: must be on a leaf, and that leaf must not be the root.
 624         private void goToNextLeaf() {
 625             // We must go to the first ancestor node that has an unvisited
 626             // right child.
 627             int _recLevel = recLevel;
 628             final Side[] _sides = sides;
 629 
 630             _recLevel--;
 631             while(_sides[_recLevel] == Side.RIGHT) {
 632                 if (_recLevel == 0) {
 633                     recLevel = 0;
 634                     done = true;
 635                     return;
 636                 }
 637                 _recLevel--;
 638             }
 639 
 640             _sides[_recLevel] = Side.RIGHT;
 641             // optimize arraycopy (8 values faster than 6 = type):
 642             System.arraycopy(recCurveStack[_recLevel], 0,
 643                              recCurveStack[_recLevel+1], 0, 8);
 644             _recLevel++;
 645 
 646             recLevel = _recLevel;
 647             goLeft();
 648         }
 649 
 650         // go to the leftmost node from the current node. Return its length.
 651         private void goLeft() {
 652             float len = onLeaf();
 653             if (len >= 0f) {
 654                 lastT = nextT;
 655                 lenAtLastT = lenAtNextT;
 656                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 657                 lenAtNextT += len;
 658                 // invalidate caches
 659                 flatLeafCoefCache[2] = -1f;
 660                 cachedHaveLowAcceleration = -1;
 661             } else {
 662                 Helpers.subdivide(recCurveStack[recLevel], 0,
 663                                   recCurveStack[recLevel+1], 0,
 664                                   recCurveStack[recLevel], 0, curveType);
 665                 sides[recLevel] = Side.LEFT;
 666                 recLevel++;
 667                 goLeft();
 668             }
 669         }
 670 
 671         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 672         // the length of the leaf if we are on a leaf.
 673         private float onLeaf() {
 674             float[] curve = recCurveStack[recLevel];
 675             float polyLen = 0f;
 676 
 677             float x0 = curve[0], y0 = curve[1];
 678             for (int i = 2; i < curveType; i += 2) {
 679                 final float x1 = curve[i], y1 = curve[i+1];
 680                 final float len = Helpers.linelen(x0, y0, x1, y1);
 681                 polyLen += len;
 682                 curLeafCtrlPolyLengths[i/2 - 1] = len;
 683                 x0 = x1;
 684                 y0 = y1;
 685             }
 686 
 687             final float lineLen = Helpers.linelen(curve[0], curve[1],
 688                                                   curve[curveType-2],
 689                                                   curve[curveType-1]);
 690             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 691                 return (polyLen + lineLen) / 2f;
 692             }
 693             return -1f;
 694         }
 695     }
 696 
 697     @Override
 698     public void curveTo(float x1, float y1,
 699                         float x2, float y2,
 700                         float x3, float y3)
 701     {
 702         final float[] _curCurvepts = curCurvepts;
 703         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 704         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 705         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 706         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 707         somethingTo(8);
 708     }
 709 
 710     @Override
 711     public void quadTo(float x1, float y1, float x2, float y2) {
 712         final float[] _curCurvepts = curCurvepts;
 713         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 714         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 715         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 716         somethingTo(6);
 717     }
 718 
 719     @Override
 720     public void closePath() {
 721         lineTo(sx, sy);
 722         if (firstSegidx > 0) {
 723             if (!dashOn || needsMoveTo) {
 724                 out.moveTo(sx, sy);
 725             }
 726             emitFirstSegments();
 727         }
 728         moveTo(sx, sy);
 729     }
 730 
 731     @Override
 732     public void pathDone() {
 733         if (firstSegidx > 0) {
 734             out.moveTo(sx, sy);
 735             emitFirstSegments();
 736         }
 737         out.pathDone();
 738 
 739         // Dispose this instance:
 740         dispose();
 741     }
 742 }
 743