< prev index next >

modules/javafx.graphics/src/main/java/com/sun/marlin/Dasher.java

Print this page




  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;


  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 = dashes_ref.initial;
 194         } else {
 195             if (DO_STATS) {
 196                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 197             }
 198             newDashes = dashes_ref.getArray(len);
 199         }
 200         System.arraycopy(dashes, 0, newDashes, 0, len);


 279                 if (needsMoveTo) {
 280                     out.moveTo(x0, y0);
 281                     needsMoveTo = false;
 282                 }
 283                 emitSeg(pts, off, type);
 284             }
 285         } else {
 286             starting = false;
 287             needsMoveTo = true;
 288         }
 289         this.x0 = x;
 290         this.y0 = y;
 291     }
 292 
 293     @Override
 294     public void lineTo(float x1, float y1) {
 295         float dx = x1 - x0;
 296         float dy = y1 - y0;
 297 
 298         float len = dx*dx + dy*dy;
 299         if (len == 0f) {
 300             return;
 301         }
 302         len = (float) Math.sqrt(len);
 303 
 304         // The scaling factors needed to get the dx and dy of the
 305         // transformed dash segments.
 306         final float cx = dx / len;
 307         final float cy = dy / len;
 308 
 309         final float[] _curCurvepts = curCurvepts;
 310         final float[] _dash = dash;
 311 
 312         float leftInThisDashSegment;
 313         float dashdx, dashdy, p;
 314 
 315         while (true) {
 316             leftInThisDashSegment = _dash[idx] - phase;
 317 
 318             if (len <= leftInThisDashSegment) {
 319                 _curCurvepts[0] = x1;
 320                 _curCurvepts[1] = y1;
 321                 goTo(_curCurvepts, 0, 4);
 322 
 323                 // Advance phase within current dash segment
 324                 phase += len;
 325                 // TODO: compare float values using epsilon:
 326                 if (len == leftInThisDashSegment) {
 327                     phase = 0f;
 328                     idx = (idx + 1) % dashLen;
 329                     dashOn = !dashOn;
 330                 }
 331                 return;
 332             }
 333 
 334             dashdx = _dash[idx] * cx;
 335             dashdy = _dash[idx] * cy;
 336 
 337             if (phase == 0f) {
 338                 _curCurvepts[0] = x0 + dashdx;
 339                 _curCurvepts[1] = y0 + dashdy;
 340             } else {
 341                 p = leftInThisDashSegment / _dash[idx];
 342                 _curCurvepts[0] = x0 + p * dashdx;
 343                 _curCurvepts[1] = y0 + p * dashdy;
 344             }
 345 
 346             goTo(_curCurvepts, 0, 4);
 347 
 348             len -= leftInThisDashSegment;
 349             // Advance to next dash segment
 350             idx = (idx + 1) % dashLen;
 351             dashOn = !dashOn;
 352             phase = 0f;
 353         }
 354     }
 355 
 356     // shared instance in Dasher
 357     private final LengthIterator li = new LengthIterator();
 358 
 359     // preconditions: curCurvepts must be an array of length at least 2 * type,
 360     // that contains the curve we want to dash in the first type elements
 361     private void somethingTo(int type) {
 362         if (pointCurve(curCurvepts, type)) {
 363             return;
 364         }
 365         li.initializeIterationOnCurve(curCurvepts, type);
 366 
 367         // initially the current curve is at curCurvepts[0...type]
 368         int curCurveoff = 0;
 369         float lastSplitT = 0f;
 370         float t;
 371         float leftInThisDashSegment = dash[idx] - phase;
 372 
 373         while ((t = li.next(leftInThisDashSegment)) < 1f) {
 374             if (t != 0f) {
 375                 Helpers.subdivideAt((t - lastSplitT) / (1f - lastSplitT),
 376                                     curCurvepts, curCurveoff,
 377                                     curCurvepts, 0,
 378                                     curCurvepts, type, type);
 379                 lastSplitT = t;
 380                 goTo(curCurvepts, 2, type);
 381                 curCurveoff = type;
 382             }
 383             // Advance to next dash segment
 384             idx = (idx + 1) % dashLen;
 385             dashOn = !dashOn;
 386             phase = 0f;
 387             leftInThisDashSegment = dash[idx];
 388         }
 389         goTo(curCurvepts, curCurveoff+2, type);
 390         phase += li.lastSegLen();
 391         if (phase >= dash[idx]) {
 392             phase = 0f;
 393             idx = (idx + 1) % dashLen;
 394             dashOn = !dashOn;
 395         }
 396         // reset LengthIterator:
 397         li.reset();
 398     }
 399 
 400     private static boolean pointCurve(float[] curve, int type) {
 401         for (int i = 2; i < type; i++) {
 402             if (curve[i] != curve[i-2]) {
 403                 return false;
 404             }
 405         }
 406         return true;
 407     }
 408 
 409     // Objects of this class are used to iterate through curves. They return
 410     // t values where the left side of the curve has a specified length.
 411     // It does this by subdividing the input curve until a certain error
 412     // condition has been met. A recursive subdivision procedure would


 427         // only the right half of the original curve is at 0)
 428         private final float[][] recCurveStack; // dirty
 429         // sides[i] indicates whether the node at level i+1 in the path from
 430         // the root to the current leaf is a left or right child of its parent.
 431         private final Side[] sides; // dirty
 432         private int curveType;
 433         // lastT and nextT delimit the current leaf.
 434         private float nextT;
 435         private float lenAtNextT;
 436         private float lastT;
 437         private float lenAtLastT;
 438         private float lenAtLastSplit;
 439         private float lastSegLen;
 440         // the current level in the recursion tree. 0 is the root. limit
 441         // is the deepest possible leaf.
 442         private int recLevel;
 443         private boolean done;
 444 
 445         // the lengths of the lines of the control polygon. Only its first
 446         // curveType/2 - 1 elements are valid. This is an optimization. See
 447         // next(float) for more detail.
 448         private final float[] curLeafCtrlPolyLengths = new float[3];
 449 
 450         LengthIterator() {
 451             this.recCurveStack = new float[REC_LIMIT + 1][8];
 452             this.sides = new Side[REC_LIMIT];
 453             // if any methods are called without first initializing this object
 454             // on a curve, we want it to fail ASAP.
 455             this.nextT = Float.MAX_VALUE;
 456             this.lenAtNextT = Float.MAX_VALUE;
 457             this.lenAtLastSplit = Float.MIN_VALUE;
 458             this.recLevel = Integer.MIN_VALUE;
 459             this.lastSegLen = Float.MAX_VALUE;
 460             this.done = true;
 461         }
 462 
 463         /**
 464          * Reset this LengthIterator.
 465          */
 466         void reset() {
 467             // keep data dirty
 468             // as it appears not useful to reset data:
 469             if (DO_CLEAN_DIRTY) {
 470                 final int recLimit = recCurveStack.length - 1;
 471                 for (int i = recLimit; i >= 0; i--) {
 472                     Arrays.fill(recCurveStack[i], 0f);
 473                 }
 474                 Arrays.fill(sides, Side.LEFT);
 475                 Arrays.fill(curLeafCtrlPolyLengths, 0f);
 476                 Arrays.fill(nextRoots, 0f);
 477                 Arrays.fill(flatLeafCoefCache, 0f);
 478                 flatLeafCoefCache[2] = -1f;
 479             }
 480         }
 481 
 482         void initializeIterationOnCurve(float[] pts, int type) {
 483             // optimize arraycopy (8 values faster than 6 = type):
 484             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 485             this.curveType = type;
 486             this.recLevel = 0;
 487             this.lastT = 0f;
 488             this.lenAtLastT = 0f;
 489             this.nextT = 0f;
 490             this.lenAtNextT = 0f;
 491             goLeft(); // initializes nextT and lenAtNextT properly
 492             this.lenAtLastSplit = 0f;
 493             if (recLevel > 0) {
 494                 this.sides[0] = Side.LEFT;
 495                 this.done = false;
 496             } else {
 497                 // the root of the tree is a leaf so we're done.
 498                 this.sides[0] = Side.RIGHT;
 499                 this.done = true;
 500             }
 501             this.lastSegLen = 0f;
 502         }
 503 
 504         // 0 == false, 1 == true, -1 == invalid cached value.
 505         private int cachedHaveLowAcceleration = -1;
 506 
 507         private boolean haveLowAcceleration(float err) {
 508             if (cachedHaveLowAcceleration == -1) {
 509                 final float len1 = curLeafCtrlPolyLengths[0];
 510                 final float len2 = curLeafCtrlPolyLengths[1];
 511                 // the test below is equivalent to !within(len1/len2, 1, err).
 512                 // It is using a multiplication instead of a division, so it
 513                 // should be a bit faster.
 514                 if (!Helpers.within(len1, len2, err*len2)) {
 515                     cachedHaveLowAcceleration = 0;
 516                     return false;
 517                 }
 518                 if (curveType == 8) {
 519                     final float len3 = curLeafCtrlPolyLengths[2];
 520                     // if len1 is close to 2 and 2 is close to 3, that probably
 521                     // means 1 is close to 3 so the second part of this test might


 525                           Helpers.within(len1, len3, errLen3))) {
 526                         cachedHaveLowAcceleration = 0;
 527                         return false;
 528                     }
 529                 }
 530                 cachedHaveLowAcceleration = 1;
 531                 return true;
 532             }
 533 
 534             return (cachedHaveLowAcceleration == 1);
 535         }
 536 
 537         // we want to avoid allocations/gc so we keep this array so we
 538         // can put roots in it,
 539         private final float[] nextRoots = new float[4];
 540 
 541         // caches the coefficients of the current leaf in its flattened
 542         // form (see inside next() for what that means). The cache is
 543         // invalid when it's third element is negative, since in any
 544         // valid flattened curve, this would be >= 0.
 545         private final float[] flatLeafCoefCache = new float[]{0f, 0f, -1f, 0f};
 546 
 547         // returns the t value where the remaining curve should be split in
 548         // order for the left subdivided curve to have length len. If len
 549         // is >= than the length of the uniterated curve, it returns 1.
 550         float next(final float len) {
 551             final float targetLength = lenAtLastSplit + len;
 552             while (lenAtNextT < targetLength) {
 553                 if (done) {
 554                     lastSegLen = lenAtNextT - lenAtLastSplit;
 555                     return 1f;
 556                 }
 557                 goToNextLeaf();
 558             }
 559             lenAtLastSplit = targetLength;
 560             final float leaflen = lenAtNextT - lenAtLastT;
 561             float t = (targetLength - lenAtLastT) / leaflen;
 562 
 563             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 564             // if the acceleration in this section of the curve is small enough.
 565             if (!haveLowAcceleration(0.05f)) {
 566                 // We flatten the current leaf along the x axis, so that we're
 567                 // left with a, b, c which define a 1D Bezier curve. We then
 568                 // solve this to get the parameter of the original leaf that
 569                 // gives us the desired length.
 570                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 571 
 572                 if (_flatLeafCoefCache[2] < 0f) {
 573                     float x = 0f + curLeafCtrlPolyLengths[0],
 574                           y = x  + curLeafCtrlPolyLengths[1];
 575                     if (curveType == 8) {
 576                         float z = y + curLeafCtrlPolyLengths[2];
 577                         _flatLeafCoefCache[0] = 3f * (x - y) + z;
 578                         _flatLeafCoefCache[1] = 3f * (y - 2f * x);
 579                         _flatLeafCoefCache[2] = 3f * x;
 580                         _flatLeafCoefCache[3] = -z;
 581                     } else if (curveType == 6) {
 582                         _flatLeafCoefCache[0] = 0f;
 583                         _flatLeafCoefCache[1] = y - 2f * x;
 584                         _flatLeafCoefCache[2] = 2f * x;
 585                         _flatLeafCoefCache[3] = -y;
 586                     }
 587                 }
 588                 float a = _flatLeafCoefCache[0];
 589                 float b = _flatLeafCoefCache[1];
 590                 float c = _flatLeafCoefCache[2];
 591                 float d = t * _flatLeafCoefCache[3];
 592 
 593                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 594                 // and our quadratic root finder doesn't filter, so it's just a
 595                 // matter of convenience.
 596                 int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0f, 1f);
 597                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 598                     t = nextRoots[0];
 599                 }
 600             }
 601             // t is relative to the current leaf, so we must make it a valid parameter
 602             // of the original curve.
 603             t = t * (nextT - lastT) + lastT;
 604             if (t >= 1f) {
 605                 t = 1f;
 606                 done = true;
 607             }
 608             // even if done = true, if we're here, that means targetLength
 609             // is equal to, or very, very close to the total length of the
 610             // curve, so lastSegLen won't be too high. In cases where len
 611             // overshoots the curve, this method will exit in the while
 612             // loop, and lastSegLen will still be set to the right value.
 613             lastSegLen = len;
 614             return t;
 615         }
 616 
 617         float lastSegLen() {
 618             return lastSegLen;
 619         }
 620 
 621         // go to the next leaf (in an inorder traversal) in the recursion tree
 622         // preconditions: must be on a leaf, and that leaf must not be the root.
 623         private void goToNextLeaf() {
 624             // We must go to the first ancestor node that has an unvisited
 625             // right child.


 632                     recLevel = 0;
 633                     done = true;
 634                     return;
 635                 }
 636                 _recLevel--;
 637             }
 638 
 639             _sides[_recLevel] = Side.RIGHT;
 640             // optimize arraycopy (8 values faster than 6 = type):
 641             System.arraycopy(recCurveStack[_recLevel], 0,
 642                              recCurveStack[_recLevel+1], 0, 8);
 643             _recLevel++;
 644 
 645             recLevel = _recLevel;
 646             goLeft();
 647         }
 648 
 649         // go to the leftmost node from the current node. Return its length.
 650         private void goLeft() {
 651             float len = onLeaf();
 652             if (len >= 0f) {
 653                 lastT = nextT;
 654                 lenAtLastT = lenAtNextT;
 655                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 656                 lenAtNextT += len;
 657                 // invalidate caches
 658                 flatLeafCoefCache[2] = -1f;
 659                 cachedHaveLowAcceleration = -1;
 660             } else {
 661                 Helpers.subdivide(recCurveStack[recLevel], 0,
 662                                   recCurveStack[recLevel+1], 0,
 663                                   recCurveStack[recLevel], 0, curveType);
 664                 sides[recLevel] = Side.LEFT;
 665                 recLevel++;
 666                 goLeft();
 667             }
 668         }
 669 
 670         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 671         // the length of the leaf if we are on a leaf.
 672         private float onLeaf() {
 673             float[] curve = recCurveStack[recLevel];
 674             float polyLen = 0f;
 675 
 676             float x0 = curve[0], y0 = curve[1];
 677             for (int i = 2; i < curveType; i += 2) {
 678                 final float x1 = curve[i], y1 = curve[i+1];
 679                 final float len = Helpers.linelen(x0, y0, x1, y1);
 680                 polyLen += len;
 681                 curLeafCtrlPolyLengths[i/2 - 1] = len;
 682                 x0 = x1;
 683                 y0 = y1;
 684             }
 685 
 686             final float lineLen = Helpers.linelen(curve[0], curve[1],
 687                                                   curve[curveType-2],
 688                                                   curve[curveType-1]);
 689             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 690                 return (polyLen + lineLen) / 2f;
 691             }
 692             return -1f;
 693         }
 694     }
 695 
 696     @Override
 697     public void curveTo(float x1, float y1,
 698                         float x2, float y2,
 699                         float x3, float y3)
 700     {
 701         final float[] _curCurvepts = curCurvepts;
 702         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 703         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 704         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 705         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 706         somethingTo(8);
 707     }
 708 
 709     @Override
 710     public void quadTo(float x1, float y1, float x2, float y2) {
 711         final float[] _curCurvepts = curCurvepts;
 712         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;




  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 = 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;


  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 = 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) {
 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.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, 0.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 = dashes_ref.initial;
 194         } else {
 195             if (DO_STATS) {
 196                 rdrCtx.stats.stat_array_dasher_dasher.add(len);
 197             }
 198             newDashes = dashes_ref.getArray(len);
 199         }
 200         System.arraycopy(dashes, 0, newDashes, 0, len);


 279                 if (needsMoveTo) {
 280                     out.moveTo(x0, y0);
 281                     needsMoveTo = false;
 282                 }
 283                 emitSeg(pts, off, type);
 284             }
 285         } else {
 286             starting = false;
 287             needsMoveTo = true;
 288         }
 289         this.x0 = x;
 290         this.y0 = y;
 291     }
 292 
 293     @Override
 294     public void lineTo(float x1, float y1) {
 295         float dx = x1 - x0;
 296         float dy = y1 - y0;
 297 
 298         float len = dx*dx + dy*dy;
 299         if (len == 0.0f) {
 300             return;
 301         }
 302         len = (float) Math.sqrt(len);
 303 
 304         // The scaling factors needed to get the dx and dy of the
 305         // transformed dash segments.
 306         final float cx = dx / len;
 307         final float cy = dy / len;
 308 
 309         final float[] _curCurvepts = curCurvepts;
 310         final float[] _dash = dash;
 311 
 312         float leftInThisDashSegment;
 313         float dashdx, dashdy, p;
 314 
 315         while (true) {
 316             leftInThisDashSegment = _dash[idx] - phase;
 317 
 318             if (len <= leftInThisDashSegment) {
 319                 _curCurvepts[0] = x1;
 320                 _curCurvepts[1] = y1;
 321                 goTo(_curCurvepts, 0, 4);
 322 
 323                 // Advance phase within current dash segment
 324                 phase += len;
 325                 // TODO: compare float values using epsilon:
 326                 if (len == leftInThisDashSegment) {
 327                     phase = 0.0f;
 328                     idx = (idx + 1) % dashLen;
 329                     dashOn = !dashOn;
 330                 }
 331                 return;
 332             }
 333 
 334             dashdx = _dash[idx] * cx;
 335             dashdy = _dash[idx] * cy;
 336 
 337             if (phase == 0.0f) {
 338                 _curCurvepts[0] = x0 + dashdx;
 339                 _curCurvepts[1] = y0 + dashdy;
 340             } else {
 341                 p = leftInThisDashSegment / _dash[idx];
 342                 _curCurvepts[0] = x0 + p * dashdx;
 343                 _curCurvepts[1] = y0 + p * dashdy;
 344             }
 345 
 346             goTo(_curCurvepts, 0, 4);
 347 
 348             len -= leftInThisDashSegment;
 349             // Advance to next dash segment
 350             idx = (idx + 1) % dashLen;
 351             dashOn = !dashOn;
 352             phase = 0.0f;
 353         }
 354     }
 355 
 356     // shared instance in Dasher
 357     private final LengthIterator li = new LengthIterator();
 358 
 359     // preconditions: curCurvepts must be an array of length at least 2 * type,
 360     // that contains the curve we want to dash in the first type elements
 361     private void somethingTo(int type) {
 362         if (pointCurve(curCurvepts, type)) {
 363             return;
 364         }
 365         li.initializeIterationOnCurve(curCurvepts, type);
 366 
 367         // initially the current curve is at curCurvepts[0...type]
 368         int curCurveoff = 0;
 369         float lastSplitT = 0.0f;
 370         float t;
 371         float leftInThisDashSegment = dash[idx] - phase;
 372 
 373         while ((t = li.next(leftInThisDashSegment)) < 1.0f) {
 374             if (t != 0.0f) {
 375                 Helpers.subdivideAt((t - lastSplitT) / (1.0f - lastSplitT),
 376                                     curCurvepts, curCurveoff,
 377                                     curCurvepts, 0,
 378                                     curCurvepts, type, type);
 379                 lastSplitT = t;
 380                 goTo(curCurvepts, 2, type);
 381                 curCurveoff = type;
 382             }
 383             // Advance to next dash segment
 384             idx = (idx + 1) % dashLen;
 385             dashOn = !dashOn;
 386             phase = 0.0f;
 387             leftInThisDashSegment = dash[idx];
 388         }
 389         goTo(curCurvepts, curCurveoff+2, type);
 390         phase += li.lastSegLen();
 391         if (phase >= dash[idx]) {
 392             phase = 0.0f;
 393             idx = (idx + 1) % dashLen;
 394             dashOn = !dashOn;
 395         }
 396         // reset LengthIterator:
 397         li.reset();
 398     }
 399 
 400     private static boolean pointCurve(float[] curve, int type) {
 401         for (int i = 2; i < type; i++) {
 402             if (curve[i] != curve[i-2]) {
 403                 return false;
 404             }
 405         }
 406         return true;
 407     }
 408 
 409     // Objects of this class are used to iterate through curves. They return
 410     // t values where the left side of the curve has a specified length.
 411     // It does this by subdividing the input curve until a certain error
 412     // condition has been met. A recursive subdivision procedure would


 427         // only the right half of the original curve is at 0)
 428         private final float[][] recCurveStack; // dirty
 429         // sides[i] indicates whether the node at level i+1 in the path from
 430         // the root to the current leaf is a left or right child of its parent.
 431         private final Side[] sides; // dirty
 432         private int curveType;
 433         // lastT and nextT delimit the current leaf.
 434         private float nextT;
 435         private float lenAtNextT;
 436         private float lastT;
 437         private float lenAtLastT;
 438         private float lenAtLastSplit;
 439         private float lastSegLen;
 440         // the current level in the recursion tree. 0 is the root. limit
 441         // is the deepest possible leaf.
 442         private int recLevel;
 443         private boolean done;
 444 
 445         // the lengths of the lines of the control polygon. Only its first
 446         // curveType/2 - 1 elements are valid. This is an optimization. See
 447         // next() for more detail.
 448         private final float[] curLeafCtrlPolyLengths = new float[3];
 449 
 450         LengthIterator() {
 451             this.recCurveStack = new float[REC_LIMIT + 1][8];
 452             this.sides = new Side[REC_LIMIT];
 453             // if any methods are called without first initializing this object
 454             // on a curve, we want it to fail ASAP.
 455             this.nextT = Float.MAX_VALUE;
 456             this.lenAtNextT = Float.MAX_VALUE;
 457             this.lenAtLastSplit = Float.MIN_VALUE;
 458             this.recLevel = Integer.MIN_VALUE;
 459             this.lastSegLen = Float.MAX_VALUE;
 460             this.done = true;
 461         }
 462 
 463         /**
 464          * Reset this LengthIterator.
 465          */
 466         void reset() {
 467             // keep data dirty
 468             // as it appears not useful to reset data:
 469             if (DO_CLEAN_DIRTY) {
 470                 final int recLimit = recCurveStack.length - 1;
 471                 for (int i = recLimit; i >= 0; i--) {
 472                     Arrays.fill(recCurveStack[i], 0.0f);
 473                 }
 474                 Arrays.fill(sides, Side.LEFT);
 475                 Arrays.fill(curLeafCtrlPolyLengths, 0.0f);
 476                 Arrays.fill(nextRoots, 0.0f);
 477                 Arrays.fill(flatLeafCoefCache, 0.0f);
 478                 flatLeafCoefCache[2] = -1.0f;
 479             }
 480         }
 481 
 482         void initializeIterationOnCurve(float[] pts, int type) {
 483             // optimize arraycopy (8 values faster than 6 = type):
 484             System.arraycopy(pts, 0, recCurveStack[0], 0, 8);
 485             this.curveType = type;
 486             this.recLevel = 0;
 487             this.lastT = 0.0f;
 488             this.lenAtLastT = 0.0f;
 489             this.nextT = 0.0f;
 490             this.lenAtNextT = 0.0f;
 491             goLeft(); // initializes nextT and lenAtNextT properly
 492             this.lenAtLastSplit = 0.0f;
 493             if (recLevel > 0) {
 494                 this.sides[0] = Side.LEFT;
 495                 this.done = false;
 496             } else {
 497                 // the root of the tree is a leaf so we're done.
 498                 this.sides[0] = Side.RIGHT;
 499                 this.done = true;
 500             }
 501             this.lastSegLen = 0.0f;
 502         }
 503 
 504         // 0 == false, 1 == true, -1 == invalid cached value.
 505         private int cachedHaveLowAcceleration = -1;
 506 
 507         private boolean haveLowAcceleration(float err) {
 508             if (cachedHaveLowAcceleration == -1) {
 509                 final float len1 = curLeafCtrlPolyLengths[0];
 510                 final float len2 = curLeafCtrlPolyLengths[1];
 511                 // the test below is equivalent to !within(len1/len2, 1, err).
 512                 // It is using a multiplication instead of a division, so it
 513                 // should be a bit faster.
 514                 if (!Helpers.within(len1, len2, err*len2)) {
 515                     cachedHaveLowAcceleration = 0;
 516                     return false;
 517                 }
 518                 if (curveType == 8) {
 519                     final float len3 = curLeafCtrlPolyLengths[2];
 520                     // if len1 is close to 2 and 2 is close to 3, that probably
 521                     // means 1 is close to 3 so the second part of this test might


 525                           Helpers.within(len1, len3, errLen3))) {
 526                         cachedHaveLowAcceleration = 0;
 527                         return false;
 528                     }
 529                 }
 530                 cachedHaveLowAcceleration = 1;
 531                 return true;
 532             }
 533 
 534             return (cachedHaveLowAcceleration == 1);
 535         }
 536 
 537         // we want to avoid allocations/gc so we keep this array so we
 538         // can put roots in it,
 539         private final float[] nextRoots = new float[4];
 540 
 541         // caches the coefficients of the current leaf in its flattened
 542         // form (see inside next() for what that means). The cache is
 543         // invalid when it's third element is negative, since in any
 544         // valid flattened curve, this would be >= 0.
 545         private final float[] flatLeafCoefCache = new float[]{0.0f, 0.0f, -1.0f, 0.0f};
 546 
 547         // returns the t value where the remaining curve should be split in
 548         // order for the left subdivided curve to have length len. If len
 549         // is >= than the length of the uniterated curve, it returns 1.
 550         float next(final float len) {
 551             final float targetLength = lenAtLastSplit + len;
 552             while (lenAtNextT < targetLength) {
 553                 if (done) {
 554                     lastSegLen = lenAtNextT - lenAtLastSplit;
 555                     return 1.0f;
 556                 }
 557                 goToNextLeaf();
 558             }
 559             lenAtLastSplit = targetLength;
 560             final float leaflen = lenAtNextT - lenAtLastT;
 561             float t = (targetLength - lenAtLastT) / leaflen;
 562 
 563             // cubicRootsInAB is a fairly expensive call, so we just don't do it
 564             // if the acceleration in this section of the curve is small enough.
 565             if (!haveLowAcceleration(0.05f)) {
 566                 // We flatten the current leaf along the x axis, so that we're
 567                 // left with a, b, c which define a 1D Bezier curve. We then
 568                 // solve this to get the parameter of the original leaf that
 569                 // gives us the desired length.
 570                 final float[] _flatLeafCoefCache = flatLeafCoefCache;
 571 
 572                 if (_flatLeafCoefCache[2] < 0.0f) {
 573                     float x =     curLeafCtrlPolyLengths[0],
 574                           y = x + curLeafCtrlPolyLengths[1];
 575                     if (curveType == 8) {
 576                         float z = y + curLeafCtrlPolyLengths[2];
 577                         _flatLeafCoefCache[0] = 3.0f * (x - y) + z;
 578                         _flatLeafCoefCache[1] = 3.0f * (y - 2.0f * x);
 579                         _flatLeafCoefCache[2] = 3.0f * x;
 580                         _flatLeafCoefCache[3] = -z;
 581                     } else if (curveType == 6) {
 582                         _flatLeafCoefCache[0] = 0.0f;
 583                         _flatLeafCoefCache[1] = y - 2.0f * x;
 584                         _flatLeafCoefCache[2] = 2.0f * x;
 585                         _flatLeafCoefCache[3] = -y;
 586                     }
 587                 }
 588                 float a = _flatLeafCoefCache[0];
 589                 float b = _flatLeafCoefCache[1];
 590                 float c = _flatLeafCoefCache[2];
 591                 float d = t * _flatLeafCoefCache[3];
 592 
 593                 // we use cubicRootsInAB here, because we want only roots in 0, 1,
 594                 // and our quadratic root finder doesn't filter, so it's just a
 595                 // matter of convenience.
 596                 int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0.0f, 1.0f);
 597                 if (n == 1 && !Float.isNaN(nextRoots[0])) {
 598                     t = nextRoots[0];
 599                 }
 600             }
 601             // t is relative to the current leaf, so we must make it a valid parameter
 602             // of the original curve.
 603             t = t * (nextT - lastT) + lastT;
 604             if (t >= 1.0f) {
 605                 t = 1.0f;
 606                 done = true;
 607             }
 608             // even if done = true, if we're here, that means targetLength
 609             // is equal to, or very, very close to the total length of the
 610             // curve, so lastSegLen won't be too high. In cases where len
 611             // overshoots the curve, this method will exit in the while
 612             // loop, and lastSegLen will still be set to the right value.
 613             lastSegLen = len;
 614             return t;
 615         }
 616 
 617         float lastSegLen() {
 618             return lastSegLen;
 619         }
 620 
 621         // go to the next leaf (in an inorder traversal) in the recursion tree
 622         // preconditions: must be on a leaf, and that leaf must not be the root.
 623         private void goToNextLeaf() {
 624             // We must go to the first ancestor node that has an unvisited
 625             // right child.


 632                     recLevel = 0;
 633                     done = true;
 634                     return;
 635                 }
 636                 _recLevel--;
 637             }
 638 
 639             _sides[_recLevel] = Side.RIGHT;
 640             // optimize arraycopy (8 values faster than 6 = type):
 641             System.arraycopy(recCurveStack[_recLevel], 0,
 642                              recCurveStack[_recLevel+1], 0, 8);
 643             _recLevel++;
 644 
 645             recLevel = _recLevel;
 646             goLeft();
 647         }
 648 
 649         // go to the leftmost node from the current node. Return its length.
 650         private void goLeft() {
 651             float len = onLeaf();
 652             if (len >= 0.0f) {
 653                 lastT = nextT;
 654                 lenAtLastT = lenAtNextT;
 655                 nextT += (1 << (REC_LIMIT - recLevel)) * MIN_T_INC;
 656                 lenAtNextT += len;
 657                 // invalidate caches
 658                 flatLeafCoefCache[2] = -1.0f;
 659                 cachedHaveLowAcceleration = -1;
 660             } else {
 661                 Helpers.subdivide(recCurveStack[recLevel], 0,
 662                                   recCurveStack[recLevel+1], 0,
 663                                   recCurveStack[recLevel], 0, curveType);
 664                 sides[recLevel] = Side.LEFT;
 665                 recLevel++;
 666                 goLeft();
 667             }
 668         }
 669 
 670         // this is a bit of a hack. It returns -1 if we're not on a leaf, and
 671         // the length of the leaf if we are on a leaf.
 672         private float onLeaf() {
 673             float[] curve = recCurveStack[recLevel];
 674             float polyLen = 0.0f;
 675 
 676             float x0 = curve[0], y0 = curve[1];
 677             for (int i = 2; i < curveType; i += 2) {
 678                 final float x1 = curve[i], y1 = curve[i+1];
 679                 final float len = Helpers.linelen(x0, y0, x1, y1);
 680                 polyLen += len;
 681                 curLeafCtrlPolyLengths[i/2 - 1] = len;
 682                 x0 = x1;
 683                 y0 = y1;
 684             }
 685 
 686             final float lineLen = Helpers.linelen(curve[0], curve[1],
 687                                                   curve[curveType-2],
 688                                                   curve[curveType-1]);
 689             if ((polyLen - lineLen) < ERR || recLevel == REC_LIMIT) {
 690                 return (polyLen + lineLen) / 2.0f;
 691             }
 692             return -1.0f;
 693         }
 694     }
 695 
 696     @Override
 697     public void curveTo(float x1, float y1,
 698                         float x2, float y2,
 699                         float x3, float y3)
 700     {
 701         final float[] _curCurvepts = curCurvepts;
 702         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;
 703         _curCurvepts[2] = x1;        _curCurvepts[3] = y1;
 704         _curCurvepts[4] = x2;        _curCurvepts[5] = y2;
 705         _curCurvepts[6] = x3;        _curCurvepts[7] = y3;
 706         somethingTo(8);
 707     }
 708 
 709     @Override
 710     public void quadTo(float x1, float y1, float x2, float y2) {
 711         final float[] _curCurvepts = curCurvepts;
 712         _curCurvepts[0] = x0;        _curCurvepts[1] = y0;


< prev index next >