001/*
002 * SVG Salamander
003 * Copyright (c) 2004, Mark McKay
004 * All rights reserved.
005 *
006 * Redistribution and use in source and binary forms, with or 
007 * without modification, are permitted provided that the following
008 * conditions are met:
009 *
010 *   - Redistributions of source code must retain the above 
011 *     copyright notice, this list of conditions and the following
012 *     disclaimer.
013 *   - Redistributions in binary form must reproduce the above
014 *     copyright notice, this list of conditions and the following
015 *     disclaimer in the documentation and/or other materials 
016 *     provided with the distribution.
017 *
018 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
019 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
020 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
021 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
022 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
023 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
025 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
026 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
027 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
028 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
029 * OF THE POSSIBILITY OF SUCH DAMAGE. 
030 * 
031 * Mark McKay can be contacted at mark@kitfox.com.  Salamander and other
032 * projects can be found at http://www.kitfox.com
033 *
034 * Created on January 26, 2004, 8:40 PM
035 */
036
037package com.kitfox.svg.pathcmd;
038
039//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
040import java.awt.*;
041import java.awt.geom.*;
042
043/**
044 * This is a little used SVG function, as most editors will save curves as 
045 * Beziers.  To reduce the need to rely on the Batik library, this functionallity
046 * is being bypassed for the time being.  In the future, it would be nice to
047 * extend the GeneralPath command to include the arcTo ability provided by Batik.
048 *
049 * @author Mark McKay
050 * @author <a href="mailto:mark@kitfox.com">Mark McKay</a>
051 */
052public class Arc extends PathCommand 
053{
054
055    public float rx = 0f;
056    public float ry = 0f;
057    public float xAxisRot = 0f;
058    public boolean largeArc = false;
059    public boolean sweep = false;
060    public float x = 0f;
061    public float y = 0f;
062
063    /** Creates a new instance of MoveTo */
064    public Arc() {
065    }
066
067    public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) {
068        super(isRelative);
069        this.rx = rx;
070        this.ry = ry;
071        this.xAxisRot = xAxisRot;
072        this.largeArc = largeArc;
073        this.sweep = sweep;
074        this.x = x;
075        this.y = y;
076    }
077
078//    public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
079    @Override
080    public void appendPath(GeneralPath path, BuildHistory hist)
081    {
082        float offx = isRelative ? hist.lastPoint.x : 0f;
083        float offy = isRelative ? hist.lastPoint.y : 0f;
084
085        arcTo(path, rx, ry, xAxisRot, largeArc, sweep,
086            x + offx, y + offy,
087            hist.lastPoint.x, hist.lastPoint.y);
088//        path.lineTo(x + offx, y + offy);
089//        hist.setPoint(x + offx, y + offy);
090        hist.setLastPoint(x + offx, y + offy);
091        hist.setLastKnot(x + offx, y + offy);
092    }
093
094    @Override
095    public int getNumKnotsAdded()
096    {
097        return 6;
098    }
099
100    /**
101     * Adds an elliptical arc, defined by two radii, an angle from the
102     * x-axis, a flag to choose the large arc or not, a flag to
103     * indicate if we increase or decrease the angles and the final
104     * point of the arc.
105     *
106     * @param path The path that the arc will be appended to.
107     * 
108     * @param rx the x radius of the ellipse
109     * @param ry the y radius of the ellipse
110     *
111     * @param angle the angle from the x-axis of the current
112     * coordinate system to the x-axis of the ellipse in degrees.
113     *
114     * @param largeArcFlag the large arc flag. If true the arc
115     * spanning less than or equal to 180 degrees is chosen, otherwise
116     * the arc spanning greater than 180 degrees is chosen
117     *
118     * @param sweepFlag the sweep flag. If true the line joining
119     * center to arc sweeps through decreasing angles otherwise it
120     * sweeps through increasing angles
121     *
122     * @param x the absolute x coordinate of the final point of the arc.
123     * @param y the absolute y coordinate of the final point of the arc.
124     * @param x0 - The absolute x coordinate of the initial point of the arc.
125     * @param y0 - The absolute y coordinate of the initial point of the arc.
126     */
127    public void arcTo(GeneralPath path, float rx, float ry,
128                                   float angle,
129                                   boolean largeArcFlag,
130                                   boolean sweepFlag,
131                                   float x, float y, float x0, float y0) 
132    {
133
134        // Ensure radii are valid
135        if (rx == 0 || ry == 0) {
136            path.lineTo((float) x, (float) y);
137            return;
138        }
139
140        if (x0 == x && y0 == y) {
141            // If the endpoints (x, y) and (x0, y0) are identical, then this
142            // is equivalent to omitting the elliptical arc segment entirely.
143            return;
144        }
145
146        Arc2D arc = computeArc(x0, y0, rx, ry, angle, 
147                               largeArcFlag, sweepFlag, x, y);
148        if (arc == null) return;
149
150        AffineTransform t = AffineTransform.getRotateInstance
151            (Math.toRadians(angle), arc.getCenterX(), arc.getCenterY());
152        Shape s = t.createTransformedShape(arc);
153        path.append(s, true);
154    }
155
156
157    /** 
158     * This constructs an unrotated Arc2D from the SVG specification of an 
159     * Elliptical arc.  To get the final arc you need to apply a rotation
160     * transform such as:
161     * 
162     * AffineTransform.getRotateInstance
163     *     (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2);
164     * 
165     * @param x0 origin of arc in x
166     * @param y0 origin of arc in y
167     * @param rx radius of arc in x
168     * @param ry radius of arc in y
169     * @param angle number of radians in arc
170     * @param largeArcFlag
171     * @param sweepFlag
172     * @param x ending coordinate of arc in x
173     * @param y ending coordinate of arc in y
174     * @return arc shape
175     * 
176     */
177    public static Arc2D computeArc(double x0, double y0,
178                                   double rx, double ry,
179                                   double angle,
180                                   boolean largeArcFlag,
181                                   boolean sweepFlag,
182                                   double x, double y) {
183        //
184        // Elliptical arc implementation based on the SVG specification notes
185        //
186
187        // Compute the half distance between the current and the final point
188        double dx2 = (x0 - x) / 2.0;
189        double dy2 = (y0 - y) / 2.0;
190        // Convert angle from degrees to radians
191        angle = Math.toRadians(angle % 360.0);
192        double cosAngle = Math.cos(angle);
193        double sinAngle = Math.sin(angle);
194
195        //
196        // Step 1 : Compute (x1, y1)
197        //
198        double x1 = (cosAngle * dx2 + sinAngle * dy2);
199        double y1 = (-sinAngle * dx2 + cosAngle * dy2);
200        // Ensure radii are large enough
201        rx = Math.abs(rx);
202        ry = Math.abs(ry);
203        double Prx = rx * rx;
204        double Pry = ry * ry;
205        double Px1 = x1 * x1;
206        double Py1 = y1 * y1;
207        // check that radii are large enough
208        double radiiCheck = Px1/Prx + Py1/Pry;
209        if (radiiCheck > 1) {
210            rx = Math.sqrt(radiiCheck) * rx;
211            ry = Math.sqrt(radiiCheck) * ry;
212            Prx = rx * rx;
213            Pry = ry * ry;
214        }
215
216        //
217        // Step 2 : Compute (cx1, cy1)
218        //
219        double sign = (largeArcFlag == sweepFlag) ? -1 : 1;
220        double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1));
221        sq = (sq < 0) ? 0 : sq;
222        double coef = (sign * Math.sqrt(sq));
223        double cx1 = coef * ((rx * y1) / ry);
224        double cy1 = coef * -((ry * x1) / rx);
225
226        //
227        // Step 3 : Compute (cx, cy) from (cx1, cy1)
228        //
229        double sx2 = (x0 + x) / 2.0;
230        double sy2 = (y0 + y) / 2.0;
231        double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1);
232        double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1);
233
234        //
235        // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
236        //
237        double ux = (x1 - cx1) / rx;
238        double uy = (y1 - cy1) / ry;
239        double vx = (-x1 - cx1) / rx;
240        double vy = (-y1 - cy1) / ry;
241        double p, n;
242        // Compute the angle start
243        n = Math.sqrt((ux * ux) + (uy * uy));
244        p = ux; // (1 * ux) + (0 * uy)
245        sign = (uy < 0) ? -1d : 1d;
246        double angleStart = Math.toDegrees(sign * Math.acos(p / n));
247
248        // Compute the angle extent
249        n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
250        p = ux * vx + uy * vy;
251        sign = (ux * vy - uy * vx < 0) ? -1d : 1d;
252        double angleExtent = Math.toDegrees(sign * Math.acos(p / n));
253        if(!sweepFlag && angleExtent > 0) {
254            angleExtent -= 360f;
255        } else if (sweepFlag && angleExtent < 0) {
256            angleExtent += 360f;
257        }
258        angleExtent %= 360f;
259        angleStart %= 360f;
260
261        //
262        // We can now build the resulting Arc2D in double precision
263        //
264        Arc2D.Double arc = new Arc2D.Double();
265        arc.x = cx - rx;
266        arc.y = cy - ry;
267        arc.width = rx * 2.0;
268        arc.height = ry * 2.0;
269        arc.start = -angleStart;
270        arc.extent = -angleExtent;
271
272        return arc;
273    }
274
275    @Override
276    public String toString()
277    {
278        return "A " + rx + " " + ry
279             + " " + xAxisRot + " " + largeArc
280             + " " + sweep
281             + " " + x + " " + y;
282    }
283}