Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/java2d/marlin/Dasher.java
38918 views
/*1* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.java2d.marlin;2627import java.util.Arrays;28import sun.awt.geom.PathConsumer2D;2930/**31* The <code>Dasher</code> class takes a series of linear commands32* (<code>moveTo</code>, <code>lineTo</code>, <code>close</code> and33* <code>end</code>) and breaks them into smaller segments according to a34* dash pattern array and a starting dash phase.35*36* <p> Issues: in J2Se, a zero length dash segment as drawn as a very37* short dash, whereas Pisces does not draw anything. The PostScript38* semantics are unclear.39*40*/41final class Dasher implements sun.awt.geom.PathConsumer2D, MarlinConst {4243static final int recLimit = 4;44static final float ERR = 0.01f;45static final float minTincrement = 1f / (1 << recLimit);4647private PathConsumer2D out;48private float[] dash;49private int dashLen;50private float startPhase;51private boolean startDashOn;52private int startIdx;5354private boolean starting;55private boolean needsMoveTo;5657private int idx;58private boolean dashOn;59private float phase;6061private float sx, sy;62private float x0, y0;6364// temporary storage for the current curve65private final float[] curCurvepts;6667// per-thread renderer context68final RendererContext rdrCtx;6970// dashes array (dirty)71final float[] dashes_initial = new float[INITIAL_ARRAY];7273// flag to recycle dash array copy74boolean recycleDashes;7576// per-thread initial arrays (large enough to satisfy most usages77// +1 to avoid recycling in Helpers.widenArray()78private final float[] firstSegmentsBuffer_initial = new float[INITIAL_ARRAY + 1];7980/**81* Constructs a <code>Dasher</code>.82* @param rdrCtx per-thread renderer context83*/84Dasher(final RendererContext rdrCtx) {85this.rdrCtx = rdrCtx;8687firstSegmentsBuffer = firstSegmentsBuffer_initial;8889// we need curCurvepts to be able to contain 2 curves because when90// dashing curves, we need to subdivide it91curCurvepts = new float[8 * 2];92}9394/**95* Initialize the <code>Dasher</code>.96*97* @param out an output <code>PathConsumer2D</code>.98* @param dash an array of <code>float</code>s containing the dash pattern99* @param dashLen length of the given dash array100* @param phase a <code>float</code> containing the dash phase101* @param recycleDashes true to indicate to recycle the given dash array102* @return this instance103*/104Dasher init(final PathConsumer2D out, float[] dash, int dashLen,105float phase, boolean recycleDashes)106{107if (phase < 0f) {108throw new IllegalArgumentException("phase < 0 !");109}110this.out = out;111112// Normalize so 0 <= phase < dash[0]113int idx = 0;114dashOn = true;115float d;116while (phase >= (d = dash[idx])) {117phase -= d;118idx = (idx + 1) % dashLen;119dashOn = !dashOn;120}121122this.dash = dash;123this.dashLen = dashLen;124this.startPhase = this.phase = phase;125this.startDashOn = dashOn;126this.startIdx = idx;127this.starting = true;128needsMoveTo = false;129firstSegidx = 0;130131this.recycleDashes = recycleDashes;132133return this; // fluent API134}135136/**137* Disposes this dasher:138* clean up before reusing this instance139*/140void dispose() {141if (doCleanDirty) {142// Force zero-fill dirty arrays:143Arrays.fill(curCurvepts, 0f);144Arrays.fill(firstSegmentsBuffer, 0f);145}146// Return arrays:147if (recycleDashes && dash != dashes_initial) {148rdrCtx.putDirtyFloatArray(dash);149dash = null;150}151152if (firstSegmentsBuffer != firstSegmentsBuffer_initial) {153rdrCtx.putDirtyFloatArray(firstSegmentsBuffer);154firstSegmentsBuffer = firstSegmentsBuffer_initial;155}156}157158@Override159public void moveTo(float x0, float y0) {160if (firstSegidx > 0) {161out.moveTo(sx, sy);162emitFirstSegments();163}164needsMoveTo = true;165this.idx = startIdx;166this.dashOn = this.startDashOn;167this.phase = this.startPhase;168this.sx = this.x0 = x0;169this.sy = this.y0 = y0;170this.starting = true;171}172173private void emitSeg(float[] buf, int off, int type) {174switch (type) {175case 8:176out.curveTo(buf[off+0], buf[off+1],177buf[off+2], buf[off+3],178buf[off+4], buf[off+5]);179return;180case 6:181out.quadTo(buf[off+0], buf[off+1],182buf[off+2], buf[off+3]);183return;184case 4:185out.lineTo(buf[off], buf[off+1]);186return;187default:188}189}190191private void emitFirstSegments() {192final float[] fSegBuf = firstSegmentsBuffer;193194for (int i = 0; i < firstSegidx; ) {195int type = (int)fSegBuf[i];196emitSeg(fSegBuf, i + 1, type);197i += (type - 1);198}199firstSegidx = 0;200}201// We don't emit the first dash right away. If we did, caps would be202// drawn on it, but we need joins to be drawn if there's a closePath()203// So, we store the path elements that make up the first dash in the204// buffer below.205private float[] firstSegmentsBuffer; // dynamic array206private int firstSegidx;207208// precondition: pts must be in relative coordinates (relative to x0,y0)209// fullCurve is true iff the curve in pts has not been split.210private void goTo(float[] pts, int off, final int type) {211float x = pts[off + type - 4];212float y = pts[off + type - 3];213if (dashOn) {214if (starting) {215int len = type - 2 + 1;216int segIdx = firstSegidx;217float[] buf = firstSegmentsBuffer;218if (segIdx + len > buf.length) {219if (doStats) {220RendererContext.stats.stat_array_dasher_firstSegmentsBuffer221.add(segIdx + len);222}223firstSegmentsBuffer = buf224= rdrCtx.widenDirtyFloatArray(buf, segIdx, segIdx + len);225}226buf[segIdx++] = type;227len--;228// small arraycopy (2, 4 or 6) but with offset:229System.arraycopy(pts, off, buf, segIdx, len);230segIdx += len;231firstSegidx = segIdx;232} else {233if (needsMoveTo) {234out.moveTo(x0, y0);235needsMoveTo = false;236}237emitSeg(pts, off, type);238}239} else {240starting = false;241needsMoveTo = true;242}243this.x0 = x;244this.y0 = y;245}246247@Override248public void lineTo(float x1, float y1) {249float dx = x1 - x0;250float dy = y1 - y0;251252float len = dx*dx + dy*dy;253if (len == 0f) {254return;255}256len = (float) Math.sqrt(len);257258// The scaling factors needed to get the dx and dy of the259// transformed dash segments.260final float cx = dx / len;261final float cy = dy / len;262263final float[] _curCurvepts = curCurvepts;264final float[] _dash = dash;265266float leftInThisDashSegment;267float dashdx, dashdy, p;268269while (true) {270leftInThisDashSegment = _dash[idx] - phase;271272if (len <= leftInThisDashSegment) {273_curCurvepts[0] = x1;274_curCurvepts[1] = y1;275goTo(_curCurvepts, 0, 4);276277// Advance phase within current dash segment278phase += len;279// TODO: compare float values using epsilon:280if (len == leftInThisDashSegment) {281phase = 0f;282idx = (idx + 1) % dashLen;283dashOn = !dashOn;284}285return;286}287288dashdx = _dash[idx] * cx;289dashdy = _dash[idx] * cy;290291if (phase == 0f) {292_curCurvepts[0] = x0 + dashdx;293_curCurvepts[1] = y0 + dashdy;294} else {295p = leftInThisDashSegment / _dash[idx];296_curCurvepts[0] = x0 + p * dashdx;297_curCurvepts[1] = y0 + p * dashdy;298}299300goTo(_curCurvepts, 0, 4);301302len -= leftInThisDashSegment;303// Advance to next dash segment304idx = (idx + 1) % dashLen;305dashOn = !dashOn;306phase = 0f;307}308}309310// shared instance in Dasher311private final LengthIterator li = new LengthIterator();312313// preconditions: curCurvepts must be an array of length at least 2 * type,314// that contains the curve we want to dash in the first type elements315private void somethingTo(int type) {316if (pointCurve(curCurvepts, type)) {317return;318}319li.initializeIterationOnCurve(curCurvepts, type);320321// initially the current curve is at curCurvepts[0...type]322int curCurveoff = 0;323float lastSplitT = 0f;324float t;325float leftInThisDashSegment = dash[idx] - phase;326327while ((t = li.next(leftInThisDashSegment)) < 1f) {328if (t != 0f) {329Helpers.subdivideAt((t - lastSplitT) / (1f - lastSplitT),330curCurvepts, curCurveoff,331curCurvepts, 0,332curCurvepts, type, type);333lastSplitT = t;334goTo(curCurvepts, 2, type);335curCurveoff = type;336}337// Advance to next dash segment338idx = (idx + 1) % dashLen;339dashOn = !dashOn;340phase = 0f;341leftInThisDashSegment = dash[idx];342}343goTo(curCurvepts, curCurveoff+2, type);344phase += li.lastSegLen();345if (phase >= dash[idx]) {346phase = 0f;347idx = (idx + 1) % dashLen;348dashOn = !dashOn;349}350// reset LengthIterator:351li.reset();352}353354private static boolean pointCurve(float[] curve, int type) {355for (int i = 2; i < type; i++) {356if (curve[i] != curve[i-2]) {357return false;358}359}360return true;361}362363// Objects of this class are used to iterate through curves. They return364// t values where the left side of the curve has a specified length.365// It does this by subdividing the input curve until a certain error366// condition has been met. A recursive subdivision procedure would367// return as many as 1<<limit curves, but this is an iterator and we368// don't need all the curves all at once, so what we carry out a369// lazy inorder traversal of the recursion tree (meaning we only move370// through the tree when we need the next subdivided curve). This saves371// us a lot of memory because at any one time we only need to store372// limit+1 curves - one for each level of the tree + 1.373// NOTE: the way we do things here is not enough to traverse a general374// tree; however, the trees we are interested in have the property that375// every non leaf node has exactly 2 children376static final class LengthIterator {377private enum Side {LEFT, RIGHT};378// Holds the curves at various levels of the recursion. The root379// (i.e. the original curve) is at recCurveStack[0] (but then it380// gets subdivided, the left half is put at 1, so most of the time381// only the right half of the original curve is at 0)382private final float[][] recCurveStack; // dirty383// sides[i] indicates whether the node at level i+1 in the path from384// the root to the current leaf is a left or right child of its parent.385private final Side[] sides; // dirty386private int curveType;387// lastT and nextT delimit the current leaf.388private float nextT;389private float lenAtNextT;390private float lastT;391private float lenAtLastT;392private float lenAtLastSplit;393private float lastSegLen;394// the current level in the recursion tree. 0 is the root. limit395// is the deepest possible leaf.396private int recLevel;397private boolean done;398399// the lengths of the lines of the control polygon. Only its first400// curveType/2 - 1 elements are valid. This is an optimization. See401// next(float) for more detail.402private final float[] curLeafCtrlPolyLengths = new float[3];403404LengthIterator() {405this.recCurveStack = new float[recLimit + 1][8];406this.sides = new Side[recLimit];407// if any methods are called without first initializing this object408// on a curve, we want it to fail ASAP.409this.nextT = Float.MAX_VALUE;410this.lenAtNextT = Float.MAX_VALUE;411this.lenAtLastSplit = Float.MIN_VALUE;412this.recLevel = Integer.MIN_VALUE;413this.lastSegLen = Float.MAX_VALUE;414this.done = true;415}416417/**418* Reset this LengthIterator.419*/420void reset() {421// keep data dirty422// as it appears not useful to reset data:423if (doCleanDirty) {424final int recLimit = recCurveStack.length - 1;425for (int i = recLimit; i >= 0; i--) {426Arrays.fill(recCurveStack[i], 0f);427}428Arrays.fill(sides, Side.LEFT);429Arrays.fill(curLeafCtrlPolyLengths, 0f);430Arrays.fill(nextRoots, 0f);431Arrays.fill(flatLeafCoefCache, 0f);432flatLeafCoefCache[2] = -1f;433}434}435436void initializeIterationOnCurve(float[] pts, int type) {437// optimize arraycopy (8 values faster than 6 = type):438System.arraycopy(pts, 0, recCurveStack[0], 0, 8);439this.curveType = type;440this.recLevel = 0;441this.lastT = 0f;442this.lenAtLastT = 0f;443this.nextT = 0f;444this.lenAtNextT = 0f;445goLeft(); // initializes nextT and lenAtNextT properly446this.lenAtLastSplit = 0f;447if (recLevel > 0) {448this.sides[0] = Side.LEFT;449this.done = false;450} else {451// the root of the tree is a leaf so we're done.452this.sides[0] = Side.RIGHT;453this.done = true;454}455this.lastSegLen = 0f;456}457458// 0 == false, 1 == true, -1 == invalid cached value.459private int cachedHaveLowAcceleration = -1;460461private boolean haveLowAcceleration(float err) {462if (cachedHaveLowAcceleration == -1) {463final float len1 = curLeafCtrlPolyLengths[0];464final float len2 = curLeafCtrlPolyLengths[1];465// the test below is equivalent to !within(len1/len2, 1, err).466// It is using a multiplication instead of a division, so it467// should be a bit faster.468if (!Helpers.within(len1, len2, err*len2)) {469cachedHaveLowAcceleration = 0;470return false;471}472if (curveType == 8) {473final float len3 = curLeafCtrlPolyLengths[2];474// if len1 is close to 2 and 2 is close to 3, that probably475// means 1 is close to 3 so the second part of this test might476// not be needed, but it doesn't hurt to include it.477final float errLen3 = err * len3;478if (!(Helpers.within(len2, len3, errLen3) &&479Helpers.within(len1, len3, errLen3))) {480cachedHaveLowAcceleration = 0;481return false;482}483}484cachedHaveLowAcceleration = 1;485return true;486}487488return (cachedHaveLowAcceleration == 1);489}490491// we want to avoid allocations/gc so we keep this array so we492// can put roots in it,493private final float[] nextRoots = new float[4];494495// caches the coefficients of the current leaf in its flattened496// form (see inside next() for what that means). The cache is497// invalid when it's third element is negative, since in any498// valid flattened curve, this would be >= 0.499private final float[] flatLeafCoefCache = new float[]{0f, 0f, -1f, 0f};500501// returns the t value where the remaining curve should be split in502// order for the left subdivided curve to have length len. If len503// is >= than the length of the uniterated curve, it returns 1.504float next(final float len) {505final float targetLength = lenAtLastSplit + len;506while (lenAtNextT < targetLength) {507if (done) {508lastSegLen = lenAtNextT - lenAtLastSplit;509return 1f;510}511goToNextLeaf();512}513lenAtLastSplit = targetLength;514final float leaflen = lenAtNextT - lenAtLastT;515float t = (targetLength - lenAtLastT) / leaflen;516517// cubicRootsInAB is a fairly expensive call, so we just don't do it518// if the acceleration in this section of the curve is small enough.519if (!haveLowAcceleration(0.05f)) {520// We flatten the current leaf along the x axis, so that we're521// left with a, b, c which define a 1D Bezier curve. We then522// solve this to get the parameter of the original leaf that523// gives us the desired length.524final float[] _flatLeafCoefCache = flatLeafCoefCache;525526if (_flatLeafCoefCache[2] < 0) {527float x = 0f + curLeafCtrlPolyLengths[0],528y = x + curLeafCtrlPolyLengths[1];529if (curveType == 8) {530float z = y + curLeafCtrlPolyLengths[2];531_flatLeafCoefCache[0] = 3f * (x - y) + z;532_flatLeafCoefCache[1] = 3f * (y - 2f * x);533_flatLeafCoefCache[2] = 3f * x;534_flatLeafCoefCache[3] = -z;535} else if (curveType == 6) {536_flatLeafCoefCache[0] = 0f;537_flatLeafCoefCache[1] = y - 2f * x;538_flatLeafCoefCache[2] = 2f * x;539_flatLeafCoefCache[3] = -y;540}541}542float a = _flatLeafCoefCache[0];543float b = _flatLeafCoefCache[1];544float c = _flatLeafCoefCache[2];545float d = t * _flatLeafCoefCache[3];546547// we use cubicRootsInAB here, because we want only roots in 0, 1,548// and our quadratic root finder doesn't filter, so it's just a549// matter of convenience.550int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0, 1);551if (n == 1 && !Float.isNaN(nextRoots[0])) {552t = nextRoots[0];553}554}555// t is relative to the current leaf, so we must make it a valid parameter556// of the original curve.557t = t * (nextT - lastT) + lastT;558if (t >= 1f) {559t = 1f;560done = true;561}562// even if done = true, if we're here, that means targetLength563// is equal to, or very, very close to the total length of the564// curve, so lastSegLen won't be too high. In cases where len565// overshoots the curve, this method will exit in the while566// loop, and lastSegLen will still be set to the right value.567lastSegLen = len;568return t;569}570571float lastSegLen() {572return lastSegLen;573}574575// go to the next leaf (in an inorder traversal) in the recursion tree576// preconditions: must be on a leaf, and that leaf must not be the root.577private void goToNextLeaf() {578// We must go to the first ancestor node that has an unvisited579// right child.580int _recLevel = recLevel;581final Side[] _sides = sides;582583_recLevel--;584while(_sides[_recLevel] == Side.RIGHT) {585if (_recLevel == 0) {586recLevel = 0;587done = true;588return;589}590_recLevel--;591}592593_sides[_recLevel] = Side.RIGHT;594// optimize arraycopy (8 values faster than 6 = type):595System.arraycopy(recCurveStack[_recLevel], 0,596recCurveStack[_recLevel+1], 0, 8);597_recLevel++;598599recLevel = _recLevel;600goLeft();601}602603// go to the leftmost node from the current node. Return its length.604private void goLeft() {605float len = onLeaf();606if (len >= 0f) {607lastT = nextT;608lenAtLastT = lenAtNextT;609nextT += (1 << (recLimit - recLevel)) * minTincrement;610lenAtNextT += len;611// invalidate caches612flatLeafCoefCache[2] = -1f;613cachedHaveLowAcceleration = -1;614} else {615Helpers.subdivide(recCurveStack[recLevel], 0,616recCurveStack[recLevel+1], 0,617recCurveStack[recLevel], 0, curveType);618sides[recLevel] = Side.LEFT;619recLevel++;620goLeft();621}622}623624// this is a bit of a hack. It returns -1 if we're not on a leaf, and625// the length of the leaf if we are on a leaf.626private float onLeaf() {627float[] curve = recCurveStack[recLevel];628float polyLen = 0f;629630float x0 = curve[0], y0 = curve[1];631for (int i = 2; i < curveType; i += 2) {632final float x1 = curve[i], y1 = curve[i+1];633final float len = Helpers.linelen(x0, y0, x1, y1);634polyLen += len;635curLeafCtrlPolyLengths[i/2 - 1] = len;636x0 = x1;637y0 = y1;638}639640final float lineLen = Helpers.linelen(curve[0], curve[1],641curve[curveType-2],642curve[curveType-1]);643if ((polyLen - lineLen) < ERR || recLevel == recLimit) {644return (polyLen + lineLen) / 2f;645}646return -1f;647}648}649650@Override651public void curveTo(float x1, float y1,652float x2, float y2,653float x3, float y3)654{655final float[] _curCurvepts = curCurvepts;656_curCurvepts[0] = x0; _curCurvepts[1] = y0;657_curCurvepts[2] = x1; _curCurvepts[3] = y1;658_curCurvepts[4] = x2; _curCurvepts[5] = y2;659_curCurvepts[6] = x3; _curCurvepts[7] = y3;660somethingTo(8);661}662663@Override664public void quadTo(float x1, float y1, float x2, float y2) {665final float[] _curCurvepts = curCurvepts;666_curCurvepts[0] = x0; _curCurvepts[1] = y0;667_curCurvepts[2] = x1; _curCurvepts[3] = y1;668_curCurvepts[4] = x2; _curCurvepts[5] = y2;669somethingTo(6);670}671672@Override673public void closePath() {674lineTo(sx, sy);675if (firstSegidx > 0) {676if (!dashOn || needsMoveTo) {677out.moveTo(sx, sy);678}679emitFirstSegments();680}681moveTo(sx, sy);682}683684@Override685public void pathDone() {686if (firstSegidx > 0) {687out.moveTo(sx, sy);688emitFirstSegments();689}690out.pathDone();691692// Dispose this instance:693dispose();694}695696@Override697public long getNativeConsumer() {698throw new InternalError("Dasher does not use a native consumer");699}700}701702703704