1 /*
   2  * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.java2d.marlin;
  27 
  28 import java.util.Arrays;
  29 import sun.awt.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 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 = 1.0f / (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 = 16000000.0f;
  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     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 = 0.0f;
 120         for (float d : dash) {
 121             sum += d;
 122         }
 123         float cycles = phase / sum;
 124         if (phase < 0.0f) {
 125             if (-cycles >= MAX_CYCLES) {
 126                 phase = 0.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 < 0.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.0f) {
 142             if (cycles >= MAX_CYCLES) {
 143                 phase = 0.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.phase = phase;
 162         this.startPhase = phase;
 163         this.startDashOn = dashOn;
 164         this.startIdx = sidx;
 165         this.starting = true;
 166         this.needsMoveTo = false;
 167         this.firstSegidx = 0;
 168 
 169         this.recycleDashes = recycleDashes;
 170 
 171         return this; // fluent API
 172     }
 173 
 174     /**
 175      * Disposes this dasher:
 176      * clean up before reusing this instance
 177      */
 178     void dispose() {
 179         if (DO_CLEAN_DIRTY) {
 180             // Force zero-fill dirty arrays:
 181             Arrays.fill(curCurvepts, 0.0f);
 182         }
 183         // Return arrays:
 184         if (recycleDashes) {
 185             dash = dashes_ref.putArray(dash);
 186         }
 187         firstSegmentsBuffer = firstSegmentsBuffer_ref.putArray(firstSegmentsBuffer);
 188     }
 189 
 190     float[] copyDashArray(final float[] dashes) {
 191         final int len = dashes.length;
 192         final float[] newDashes;
 193         if (len <= MarlinConst.INITIAL_ARRAY) {
 194             newDashes = dashes_ref.initial;
 195         } else {
 196             if (DO_STATS) {
 197                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 198             }
 199             newDashes = dashes_ref.getArray(len);
 200         }
 201         System.arraycopy(dashes, 0, newDashes, 0, len);
 202         return newDashes;
 203     }
 204 
 205     @Override
 206     public void moveTo(float x0, float y0) {
 207         if (firstSegidx != 0) {
 208             out.moveTo(sx, sy);
 209             emitFirstSegments();
 210         }
 211         needsMoveTo = true;
 212         this.idx = startIdx;
 213         this.dashOn = this.startDashOn;
 214         this.phase = this.startPhase;
 215         this.sx = x0;
 216         this.sy = y0;
 217         this.x0 = x0;
 218         this.y0 = y0;
 219         this.starting = true;
 220     }
 221 
 222     private void emitSeg(float[] buf, int off, int type) {
 223         switch (type) {
 224         case 8:
 225             out.curveTo(buf[off+0], buf[off+1],
 226                         buf[off+2], buf[off+3],
 227                         buf[off+4], buf[off+5]);
 228             return;
 229         case 6:
 230             out.quadTo(buf[off+0], buf[off+1],
 231                        buf[off+2], buf[off+3]);
 232             return;
 233         case 4:
 234             out.lineTo(buf[off], buf[off+1]);
 235             return;
 236         default:
 237         }
 238     }
 239 
 240     private void emitFirstSegments() {
 241         final float[] fSegBuf = firstSegmentsBuffer;
 242 
 243         for (int i = 0, len = firstSegidx; i < len; ) {
 244             int type = (int)fSegBuf[i];
 245             emitSeg(fSegBuf, i + 1, type);
 246             i += (type - 1);
 247         }
 248         firstSegidx = 0;
 249     }
 250     // We don't emit the first dash right away. If we did, caps would be
 251     // drawn on it, but we need joins to be drawn if there's a closePath()
 252     // So, we store the path elements that make up the first dash in the
 253     // buffer below.
 254     private float[] firstSegmentsBuffer; // dynamic array
 255     private int firstSegidx;
 256 
 257     // precondition: pts must be in relative coordinates (relative to x0,y0)
 258     private void goTo(final float[] pts, final int off, final int type, final boolean on) {
 259         final int index = off + type;
 260         final float x = pts[index - 4];
 261         final float y = pts[index - 3];
 262 
 263         if (on) {
 264             if (starting) {
 265                 goTo_starting(pts, off, type);
 266             } else {
 267                 if (needsMoveTo) {
 268                     needsMoveTo = false;
 269                     out.moveTo(x0, y0);
 270                 }
 271                 emitSeg(pts, off, type);
 272             }
 273         } else {
 274             if (starting) {
 275                 // low probability test (hotspot)
 276                 starting = false;
 277             }
 278             needsMoveTo = true;
 279         }
 280         this.x0 = x;
 281         this.y0 = y;
 282     }
 283 
 284     private void goTo_starting(final float[] pts, final int off, final int type) {
 285         int len = type - 1; // - 2 + 1
 286         int segIdx = firstSegidx;
 287         float[] buf = firstSegmentsBuffer;
 288 
 289         if (segIdx + len  > buf.length) {
 290             if (DO_STATS) {
 291                 rdrCtx.stats.stat_array_dasher_firstSegmentsBuffer
 292                     .add(segIdx + len);
 293             }
 294             firstSegmentsBuffer = buf
 295                 = firstSegmentsBuffer_ref.widenArray(buf, segIdx,
 296                                                      segIdx + len);
 297         }
 298         buf[segIdx++] = type;
 299         len--;
 300         // small arraycopy (2, 4 or 6) but with offset:
 301         System.arraycopy(pts, off, buf, segIdx, len);
 302         firstSegidx = segIdx + len;
 303     }
 304 
 305     @Override
 306     public void lineTo(float x1, float y1) {
 307         final float dx = x1 - x0;
 308         final float dy = y1 - y0;
 309 
 310         float len = dx*dx + dy*dy;
 311         if (len == 0.0f) {
 312             return;
 313         }
 314         len = (float) Math.sqrt(len);
 315 
 316         // The scaling factors needed to get the dx and dy of the
 317         // transformed dash segments.
 318         final float cx = dx / len;
 319         final float cy = dy / len;
 320 
 321         final float[] _curCurvepts = curCurvepts;
 322         final float[] _dash = dash;
 323         final int _dashLen = this.dashLen;
 324 
 325         int _idx = idx;
 326         boolean _dashOn = dashOn;
 327         float _phase = phase;
 328 
 329         float leftInThisDashSegment;
 330         float d, dashdx, dashdy, p;
 331 
 332         while (true) {
 333             d = _dash[_idx];
 334             leftInThisDashSegment = d - _phase;
 335 
 336             if (len <= leftInThisDashSegment) {
 337                 _curCurvepts[0] = x1;
 338                 _curCurvepts[1] = y1;
 339 
 340                 goTo(_curCurvepts, 0, 4, _dashOn);
 341 
 342                 // Advance phase within current dash segment
 343                 _phase += len;
 344 
 345                 // TODO: compare float values using epsilon:
 346                 if (len == leftInThisDashSegment) {
 347                     _phase = 0.0f;
 348                     _idx = (_idx + 1) % _dashLen;
 349                     _dashOn = !_dashOn;
 350                 }
 351 
 352                 // Save local state:
 353                 idx = _idx;
 354                 dashOn = _dashOn;
 355                 phase = _phase;
 356                 return;
 357             }
 358 
 359             dashdx = d * cx;
 360             dashdy = d * cy;
 361 
 362             if (_phase == 0.0f) {
 363                 _curCurvepts[0] = x0 + dashdx;
 364                 _curCurvepts[1] = y0 + dashdy;
 365             } else {
 366                 p = leftInThisDashSegment / d;
 367                 _curCurvepts[0] = x0 + p * dashdx;
 368                 _curCurvepts[1] = y0 + p * dashdy;
 369             }
 370 
 371             goTo(_curCurvepts, 0, 4, _dashOn);
 372 
 373             len -= leftInThisDashSegment;
 374             // Advance to next dash segment
 375             _idx = (_idx + 1) % _dashLen;
 376             _dashOn = !_dashOn;
 377             _phase = 0.0f;
 378         }
 379     }
 380 
 381     // shared instance in Dasher
 382     private final LengthIterator li = new LengthIterator();
 383 
 384     // preconditions: curCurvepts must be an array of length at least 2 * type,
 385     // that contains the curve we want to dash in the first type elements
 386     private void somethingTo(int type) {
 387         if (pointCurve(curCurvepts, type)) {
 388             return;
 389         }
 390         final LengthIterator _li = li;
 391         final float[] _curCurvepts = curCurvepts;
 392         final float[] _dash = dash;
 393         final int _dashLen = this.dashLen;
 394 
 395         _li.initializeIterationOnCurve(_curCurvepts, type);
 396 
 397         int _idx = idx;
 398         boolean _dashOn = dashOn;
 399         float _phase = phase;
 400 
 401         // initially the current curve is at curCurvepts[0...type]
 402         int curCurveoff = 0;
 403         float lastSplitT = 0.0f;
 404         float t;
 405         float leftInThisDashSegment = _dash[_idx] - _phase;
 406 
 407         while ((t = _li.next(leftInThisDashSegment)) < 1.0f) {
 408             if (t != 0.0f) {
 409                 Helpers.subdivideAt((t - lastSplitT) / (1.0f - lastSplitT),
 410                                     _curCurvepts, curCurveoff,
 411                                     _curCurvepts, 0,
 412                                     _curCurvepts, type, type);
 413                 lastSplitT = t;
 414                 goTo(_curCurvepts, 2, type, _dashOn);
 415                 curCurveoff = type;
 416             }
 417             // Advance to next dash segment
 418             _idx = (_idx + 1) % _dashLen;
 419             _dashOn = !_dashOn;
 420             _phase = 0.0f;
 421             leftInThisDashSegment = _dash[_idx];
 422         }
 423         goTo(_curCurvepts, curCurveoff + 2, type, _dashOn);
 424         _phase += _li.lastSegLen();
 425         if (_phase >= _dash[_idx]) {
 426             _phase = 0.0f;
 427             _idx = (_idx + 1) % _dashLen;
 428             _dashOn = !_dashOn;
 429         }
 430         // Save local state:
 431         idx = _idx;
 432         dashOn = _dashOn;
 433         phase = _phase;
 434         // reset LengthIterator:
 435         _li.reset();
 436     }
 437 
 438     private static boolean pointCurve(float[] curve, int type) {
 439         for (int i = 2; i < type; i++) {
 440             if (curve[i] != curve[i-2]) {
 441                 return false;
 442             }
 443         }
 444         return true;
 445     }
 446 
 447     // Objects of this class are used to iterate through curves. They return
 448     // t values where the left side of the curve has a specified length.
 449     // It does this by subdividing the input curve until a certain error
 450     // condition has been met. A recursive subdivision procedure would
 451     // return as many as 1<<limit curves, but this is an iterator and we
 452     // don't need all the curves all at once, so what we carry out a
 453     // lazy inorder traversal of the recursion tree (meaning we only move
 454     // through the tree when we need the next subdivided curve). This saves
 455     // us a lot of memory because at any one time we only need to store
 456     // limit+1 curves - one for each level of the tree + 1.
 457     // NOTE: the way we do things here is not enough to traverse a general
 458     // tree; however, the trees we are interested in have the property that
 459     // every non leaf node has exactly 2 children
 460     static final class LengthIterator {
 461         private enum Side {LEFT, RIGHT};
 462         // Holds the curves at various levels of the recursion. The root
 463         // (i.e. the original curve) is at recCurveStack[0] (but then it
 464         // gets subdivided, the left half is put at 1, so most of the time
 465         // only the right half of the original curve is at 0)
 466         private final float[][] recCurveStack; // dirty
 467         // sides[i] indicates whether the node at level i+1 in the path from
 468         // the root to the current leaf is a left or right child of its parent.
 469         private final Side[] sides; // dirty
 470         private int curveType;
 471         // lastT and nextT delimit the current leaf.
 472         private float nextT;
 473         private float lenAtNextT;
 474         private float lastT;
 475         private float lenAtLastT;
 476         private float lenAtLastSplit;
 477         private float lastSegLen;
 478         // the current level in the recursion tree. 0 is the root. limit
 479         // is the deepest possible leaf.
 480         private int recLevel;
 481         private boolean done;
 482 
 483         // the lengths of the lines of the control polygon. Only its first
 484         // curveType/2 - 1 elements are valid. This is an optimization. See
 485         // next() for more detail.
 486         private final float[] curLeafCtrlPolyLengths = new float[3];
 487 
 488         LengthIterator() {
 489             this.recCurveStack = new float[REC_LIMIT + 1][8];
 490             this.sides = new Side[REC_LIMIT];
 491             // if any methods are called without first initializing this object
 492             // on a curve, we want it to fail ASAP.
 493             this.nextT = Float.MAX_VALUE;
 494             this.lenAtNextT = Float.MAX_VALUE;
 495             this.lenAtLastSplit = Float.MIN_VALUE;
 496             this.recLevel = Integer.MIN_VALUE;
 497             this.lastSegLen = Float.MAX_VALUE;
 498             this.done = true;
 499         }
 500 
 501         /**
 502          * Reset this LengthIterator.
 503          */
 504         void reset() {
 505             // keep data dirty
 506             // as it appears not useful to reset data:
 507             if (DO_CLEAN_DIRTY) {
 508                 final int recLimit = recCurveStack.length - 1;
 509                 for (int i = recLimit; i >= 0; i--) {
 510                     Arrays.fill(recCurveStack[i], 0.0f);
 511                 }
 512                 Arrays.fill(sides, Side.LEFT);
 513                 Arrays.fill(curLeafCtrlPolyLengths, 0.0f);
 514                 Arrays.fill(nextRoots, 0.0f);
 515                 Arrays.fill(flatLeafCoefCache, 0.0f);
 516                 flatLeafCoefCache[2] = -1.0f;
 517             }
 518         }
 519 
 520         void initializeIterationOnCurve(float[] pts, int type) {
 521             // optimize arraycopy (8 values faster than 6 = type):
 522             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 523             this.curveType = type;
 524             this.recLevel = 0;
 525             this.lastT = 0.0f;
 526             this.lenAtLastT = 0.0f;
 527             this.nextT = 0.0f;
 528             this.lenAtNextT = 0.0f;
 529             goLeft(); // initializes nextT and lenAtNextT properly
 530             this.lenAtLastSplit = 0.0f;
 531             if (recLevel > 0) {
 532                 this.sides[0] = Side.LEFT;
 533                 this.done = false;
 534             } else {
 535                 // the root of the tree is a leaf so we're done.
 536                 this.sides[0] = Side.RIGHT;
 537                 this.done = true;
 538             }
 539             this.lastSegLen = 0.0f;
 540         }
 541 
 542         // 0 == false, 1 == true, -1 == invalid cached value.
 543         private int cachedHaveLowAcceleration = -1;
 544 
 545         private boolean haveLowAcceleration(float err) {
 546             if (cachedHaveLowAcceleration == -1) {
 547                 final float len1 = curLeafCtrlPolyLengths[0];
 548                 final float len2 = curLeafCtrlPolyLengths[1];
 549                 // the test below is equivalent to !within(len1/len2, 1, err).
 550                 // It is using a multiplication instead of a division, so it
 551                 // should be a bit faster.
 552                 if (!Helpers.within(len1, len2, err * len2)) {
 553                     cachedHaveLowAcceleration = 0;
 554                     return false;
 555                 }
 556                 if (curveType == 8) {
 557                     final float len3 = curLeafCtrlPolyLengths[2];
 558                     // if len1 is close to 2 and 2 is close to 3, that probably
 559                     // means 1 is close to 3 so the second part of this test might
 560                     // not be needed, but it doesn't hurt to include it.
 561                     final float errLen3 = err * len3;
 562                     if (!(Helpers.within(len2, len3, errLen3) &&
 563                           Helpers.within(len1, len3, errLen3))) {
 564                         cachedHaveLowAcceleration = 0;
 565                         return false;
 566                     }
 567                 }
 568                 cachedHaveLowAcceleration = 1;
 569                 return true;
 570             }
 571 
 572             return (cachedHaveLowAcceleration == 1);
 573         }
 574 
 575         // we want to avoid allocations/gc so we keep this array so we
 576         // can put roots in it,
 577         private final float[] nextRoots = new float[4];
 578 
 579         // caches the coefficients of the current leaf in its flattened
 580         // form (see inside next() for what that means). The cache is
 581         // invalid when it's third element is negative, since in any
 582         // valid flattened curve, this would be >= 0.
 583         private final float[] flatLeafCoefCache = new float[]{0.0f, 0.0f, -1.0f, 0.0f};
 584 
 585         // returns the t value where the remaining curve should be split in
 586         // order for the left subdivided curve to have length len. If len
 587         // is >= than the length of the uniterated curve, it returns 1.
 588         float next(final float len) {
 589             final float targetLength = lenAtLastSplit + len;
 590             while (lenAtNextT < targetLength) {
 591                 if (done) {
 592                     lastSegLen = lenAtNextT - lenAtLastSplit;
 593                     return 1.0f;
 594                 }
 595                 goToNextLeaf();
 596             }
 597             lenAtLastSplit = targetLength;
 598             final float leaflen = lenAtNextT - lenAtLastT;
 599             float t = (targetLength - lenAtLastT) / leaflen;
 600 
 601             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 602             // if the acceleration in this section of the curve is small enough.
 603             if (!haveLowAcceleration(0.05f)) {
 604                 // We flatten the current leaf along the x axis, so that we're
 605                 // left with a, b, c which define a 1D Bezier curve. We then
 606                 // solve this to get the parameter of the original leaf that
 607                 // gives us the desired length.
 608                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 609 
 610                 if (_flatLeafCoefCache[2] < 0.0f) {
 611                     float x =     curLeafCtrlPolyLengths[0],
 612                           y = x + curLeafCtrlPolyLengths[1];
 613                     if (curveType == 8) {
 614                         float z = y + curLeafCtrlPolyLengths[2];
 615                         _flatLeafCoefCache[0] = 3.0f * (x - y) + z;
 616                         _flatLeafCoefCache[1] = 3.0f * (y - 2.0f * x);
 617                         _flatLeafCoefCache[2] = 3.0f * x;
 618                         _flatLeafCoefCache[3] = -z;
 619                     } else if (curveType == 6) {
 620                         _flatLeafCoefCache[0] = 0.0f;
 621                         _flatLeafCoefCache[1] = y - 2.0f * x;
 622                         _flatLeafCoefCache[2] = 2.0f * x;
 623                         _flatLeafCoefCache[3] = -y;
 624                     }
 625                 }
 626                 float a = _flatLeafCoefCache[0];
 627                 float b = _flatLeafCoefCache[1];
 628                 float c = _flatLeafCoefCache[2];
 629                 float d = t * _flatLeafCoefCache[3];
 630 
 631                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 632                 // and our quadratic root finder doesn't filter, so it's just a
 633                 // matter of convenience.
 634                 int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0f, 1.0f);
 635                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 636                     t = nextRoots[0];
 637                 }
 638             }
 639             // t is relative to the current leaf, so we must make it a valid parameter
 640             // of the original curve.
 641             t = t * (nextT - lastT) + lastT;
 642             if (t >= 1.0f) {
 643                 t = 1.0f;
 644                 done = true;
 645             }
 646             // even if done = true, if we're here, that means targetLength
 647             // is equal to, or very, very close to the total length of the
 648             // curve, so lastSegLen won't be too high. In cases where len
 649             // overshoots the curve, this method will exit in the while
 650             // loop, and lastSegLen will still be set to the right value.
 651             lastSegLen = len;
 652             return t;
 653         }
 654 
 655         float lastSegLen() {
 656             return lastSegLen;
 657         }
 658 
 659         // go to the next leaf (in an inorder traversal) in the recursion tree
 660         // preconditions: must be on a leaf, and that leaf must not be the root.
 661         private void goToNextLeaf() {
 662             // We must go to the first ancestor node that has an unvisited
 663             // right child.
 664             int _recLevel = recLevel;
 665             final Side[] _sides = sides;
 666 
 667             _recLevel--;
 668             while(_sides[_recLevel] == Side.RIGHT) {
 669                 if (_recLevel == 0) {
 670                     recLevel = 0;
 671                     done = true;
 672                     return;
 673                 }
 674                 _recLevel--;
 675             }
 676 
 677             _sides[_recLevel] = Side.RIGHT;
 678             // optimize arraycopy (8 values faster than 6 = type):
 679             System.arraycopy(recCurveStack[_recLevel], 0,
 680                              recCurveStack[_recLevel+1], 0, 8);
 681             _recLevel++;
 682 
 683             recLevel = _recLevel;
 684             goLeft();
 685         }
 686 
 687         // go to the leftmost node from the current node. Return its length.
 688         private void goLeft() {
 689             float len = onLeaf();
 690             if (len >= 0.0f) {
 691                 lastT = nextT;
 692                 lenAtLastT = lenAtNextT;
 693                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 694                 lenAtNextT += len;
 695                 // invalidate caches
 696                 flatLeafCoefCache[2] = -1.0f;
 697                 cachedHaveLowAcceleration = -1;
 698             } else {
 699                 Helpers.subdivide(recCurveStack[recLevel], 0,
 700                                   recCurveStack[recLevel+1], 0,
 701                                   recCurveStack[recLevel], 0, curveType);
 702                 sides[recLevel] = Side.LEFT;
 703                 recLevel++;
 704                 goLeft();
 705             }
 706         }
 707 
 708         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 709         // the length of the leaf if we are on a leaf.
 710         private float onLeaf() {
 711             final float[] curve = recCurveStack[recLevel];
 712             final int _curveType = curveType;
 713             float polyLen = 0.0f;
 714 
 715             float x0 = curve[0], y0 = curve[1];
 716             for (int i = 2; i < _curveType; i += 2) {
 717                 final float x1 = curve[i], y1 = curve[i+1];
 718                 final float len = Helpers.linelen(x0, y0, x1, y1);
 719                 polyLen += len;
 720                 curLeafCtrlPolyLengths[i/2 - 1] = len;
 721                 x0 = x1;
 722                 y0 = y1;
 723             }
 724 
 725             final float lineLen = Helpers.linelen(curve[0], curve[1],
 726                                                   curve[_curveType-2],
 727                                                   curve[_curveType-1]);
 728             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 729                 return (polyLen + lineLen) / 2.0f;
 730             }
 731             return -1.0f;
 732         }
 733     }
 734 
 735     @Override
 736     public void curveTo(float x1, float y1,
 737                         float x2, float y2,
 738                         float x3, float y3)
 739     {
 740         final float[] _curCurvepts = curCurvepts;
 741         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 742         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 743         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 744         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 745         somethingTo(8);
 746     }
 747 
 748     @Override
 749     public void quadTo(float x1, float y1, float x2, float y2) {
 750         final float[] _curCurvepts = curCurvepts;
 751         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 752         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 753         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 754         somethingTo(6);
 755     }
 756 
 757     @Override
 758     public void closePath() {
 759         lineTo(sx, sy);
 760         if (firstSegidx != 0) {
 761             if (!dashOn || needsMoveTo) {
 762                 out.moveTo(sx, sy);
 763             }
 764             emitFirstSegments();
 765         }
 766         moveTo(sx, sy);
 767     }
 768 
 769     @Override
 770     public void pathDone() {
 771         if (firstSegidx != 0) {
 772             out.moveTo(sx, sy);
 773             emitFirstSegments();
 774         }
 775         out.pathDone();
 776 
 777         // Dispose this instance:
 778         dispose();
 779     }
 780 
 781     @Override
 782     public long getNativeConsumer() {
 783         throw new InternalError("Dasher does not use a native consumer");
 784     }
 785 }
 786