001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------------------------
028 * SamplingXYLineRenderer.java
029 * ---------------------------
030 * (C) Copyright 2008-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 * Changes:
036 * --------
037 * 02-Oct-2008 : Version 1 (DG);
038 * 28-Apr-2009 : Fixed bug in legend shape display, and deprecated
039 *               getLegendLine() and setLegendLine() - these methods
040 *               are unnecessary because a mechanism already exists in the
041 *               superclass for specifying a custom legend shape (DG);
042 * 03-Jul-2013 : Use ParamChecks (DG);
043 *
044 */
045
046package org.jfree.chart.renderer.xy;
047
048import java.awt.Graphics2D;
049import java.awt.Shape;
050import java.awt.geom.GeneralPath;
051import java.awt.geom.Line2D;
052import java.awt.geom.PathIterator;
053import java.awt.geom.Rectangle2D;
054import java.io.IOException;
055import java.io.ObjectInputStream;
056import java.io.ObjectOutputStream;
057import java.io.Serializable;
058
059import org.jfree.chart.axis.ValueAxis;
060import org.jfree.chart.plot.CrosshairState;
061import org.jfree.chart.plot.PlotOrientation;
062import org.jfree.chart.plot.PlotRenderingInfo;
063import org.jfree.chart.plot.XYPlot;
064import org.jfree.chart.ui.RectangleEdge;
065import org.jfree.chart.util.PublicCloneable;
066import org.jfree.chart.util.SerialUtils;
067import org.jfree.chart.util.ShapeUtils;
068import org.jfree.data.xy.XYDataset;
069
070/**
071 * A renderer that draws line charts.  The renderer doesn't necessarily plot
072 * every data item - instead, it tries to plot only those data items that
073 * make a difference to the visual output (the other data items are skipped).  
074 * This renderer is designed for use with the {@link XYPlot} class.
075 *
076 * @since 1.0.13
077 */
078public class SamplingXYLineRenderer extends AbstractXYItemRenderer
079        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
080
081    /** The shape that is used to represent a line in the legend. */
082    private transient Shape legendLine;
083
084    /**
085     * Creates a new renderer.
086     */
087    public SamplingXYLineRenderer() {
088        this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
089        setDefaultLegendShape(this.legendLine);
090        setTreatLegendShapeAsLine(true);
091    }
092
093    /**
094     * Returns the number of passes through the data that the renderer requires
095     * in order to draw the chart.  Most charts will require a single pass, but
096     * some require two passes.
097     *
098     * @return The pass count.
099     */
100    @Override
101    public int getPassCount() {
102        return 1;
103    }
104
105    /**
106     * Records the state for the renderer.  This is used to preserve state
107     * information between calls to the drawItem() method for a single chart
108     * drawing.
109     */
110    public static class State extends XYItemRendererState {
111
112        /** The path for the current series. */
113        GeneralPath seriesPath;
114
115        /**
116         * A second path that draws vertical intervals to cover any extreme
117         * values.
118         */
119        GeneralPath intervalPath;
120
121        /**
122         * The minimum change in the x-value needed to trigger an update to
123         * the seriesPath.
124         */
125        double dX = 1.0;
126
127        /** The last x-coordinate visited by the seriesPath. */
128        double lastX;
129
130        /** The initial y-coordinate for the current x-coordinate. */
131        double openY = 0.0;
132
133        /** The highest y-coordinate for the current x-coordinate. */
134        double highY = 0.0;
135
136        /** The lowest y-coordinate for the current x-coordinate. */
137        double lowY = 0.0;
138
139        /** The final y-coordinate for the current x-coordinate. */
140        double closeY = 0.0;
141
142        /**
143         * A flag that indicates if the last (x, y) point was 'good'
144         * (non-null).
145         */
146        boolean lastPointGood;
147
148        /**
149         * Creates a new state instance.
150         *
151         * @param info  the plot rendering info.
152         */
153        public State(PlotRenderingInfo info) {
154            super(info);
155        }
156
157        /**
158         * This method is called by the {@link XYPlot} at the start of each
159         * series pass.  We reset the state for the current series.
160         *
161         * @param dataset  the dataset.
162         * @param series  the series index.
163         * @param firstItem  the first item index for this pass.
164         * @param lastItem  the last item index for this pass.
165         * @param pass  the current pass index.
166         * @param passCount  the number of passes.
167         */
168        @Override
169        public void startSeriesPass(XYDataset dataset, int series,
170                int firstItem, int lastItem, int pass, int passCount) {
171            this.seriesPath.reset();
172            this.intervalPath.reset();
173            this.lastPointGood = false;
174            super.startSeriesPass(dataset, series, firstItem, lastItem, pass,
175                    passCount);
176        }
177
178    }
179
180    /**
181     * Initialises the renderer.
182     * <P>
183     * This method will be called before the first item is rendered, giving the
184     * renderer an opportunity to initialise any state information it wants to
185     * maintain.  The renderer can do nothing if it chooses.
186     *
187     * @param g2  the graphics device.
188     * @param dataArea  the area inside the axes.
189     * @param plot  the plot.
190     * @param data  the data.
191     * @param info  an optional info collection object to return data back to
192     *              the caller.
193     *
194     * @return The renderer state.
195     */
196    @Override
197    public XYItemRendererState initialise(Graphics2D g2,
198            Rectangle2D dataArea, XYPlot plot, XYDataset data,
199            PlotRenderingInfo info) {
200
201        double dpi = 72;
202    //        Integer dpiVal = (Integer) g2.getRenderingHint(HintKey.DPI);
203    //        if (dpiVal != null) {
204    //            dpi = dpiVal.intValue();
205    //        }
206        State state = new State(info);
207        state.seriesPath = new GeneralPath();
208        state.intervalPath = new GeneralPath();
209        state.dX = 72.0 / dpi;
210        return state;
211    }
212
213    /**
214     * Draws the visual representation of a single data item.
215     *
216     * @param g2  the graphics device.
217     * @param state  the renderer state.
218     * @param dataArea  the area within which the data is being drawn.
219     * @param info  collects information about the drawing.
220     * @param plot  the plot (can be used to obtain standard color
221     *              information etc).
222     * @param domainAxis  the domain axis.
223     * @param rangeAxis  the range axis.
224     * @param dataset  the dataset.
225     * @param series  the series index (zero-based).
226     * @param item  the item index (zero-based).
227     * @param crosshairState  crosshair information for the plot
228     *                        ({@code null} permitted).
229     * @param pass  the pass index.
230     */
231    @Override
232    public void drawItem(Graphics2D g2, XYItemRendererState state, 
233            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
234            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
235            int series, int item, CrosshairState crosshairState, int pass) {
236
237        // do nothing if item is not visible
238        if (!getItemVisible(series, item)) {
239            return;
240        }
241        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
242        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
243
244        // get the data point...
245        double x1 = dataset.getXValue(series, item);
246        double y1 = dataset.getYValue(series, item);
247        double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
248        double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
249
250        State s = (State) state;
251        // update path to reflect latest point
252        if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
253            float x = (float) transX1;
254            float y = (float) transY1;
255            PlotOrientation orientation = plot.getOrientation();
256            if (orientation == PlotOrientation.HORIZONTAL) {
257                x = (float) transY1;
258                y = (float) transX1;
259            }
260            if (s.lastPointGood) {
261                if ((Math.abs(x - s.lastX) > s.dX)) {
262                    s.seriesPath.lineTo(x, y);
263                    if (s.lowY < s.highY) {
264                        s.intervalPath.moveTo((float) s.lastX, (float) s.lowY);
265                        s.intervalPath.lineTo((float) s.lastX, (float) s.highY);
266                    }
267                    s.lastX = x;
268                    s.openY = y;
269                    s.highY = y;
270                    s.lowY = y;
271                    s.closeY = y;
272                }
273                else {
274                    s.highY = Math.max(s.highY, y);
275                    s.lowY = Math.min(s.lowY, y);
276                    s.closeY = y;
277                }
278            }
279            else {
280                s.seriesPath.moveTo(x, y);
281                s.lastX = x;
282                s.openY = y;
283                s.highY = y;
284                s.lowY = y;
285                s.closeY = y;
286            }
287            s.lastPointGood = true;
288        }
289        else {
290            s.lastPointGood = false;
291        }
292        // if this is the last item, draw the path ...
293        if (item == s.getLastItemIndex()) {
294            // draw path
295            PathIterator pi = s.seriesPath.getPathIterator(null);
296            int count = 0;
297            while (!pi.isDone()) {
298                count++;
299                pi.next();
300            }
301            g2.setStroke(getItemStroke(series, item));
302            g2.setPaint(getItemPaint(series, item));
303            g2.draw(s.seriesPath);
304            g2.draw(s.intervalPath);
305        }
306    }
307
308    /**
309     * Returns a clone of the renderer.
310     *
311     * @return A clone.
312     *
313     * @throws CloneNotSupportedException if the clone cannot be created.
314     */
315    @Override
316    public Object clone() throws CloneNotSupportedException {
317        SamplingXYLineRenderer clone = (SamplingXYLineRenderer) super.clone();
318        if (this.legendLine != null) {
319            clone.legendLine = ShapeUtils.clone(this.legendLine);
320        }
321        return clone;
322    }
323
324    /**
325     * Tests this renderer for equality with an arbitrary object.
326     *
327     * @param obj  the object ({@code null} permitted).
328     *
329     * @return {@code true} or {@code false}.
330     */
331    @Override
332    public boolean equals(Object obj) {
333        if (obj == this) {
334            return true;
335        }
336        if (!(obj instanceof SamplingXYLineRenderer)) {
337            return false;
338        }
339        if (!super.equals(obj)) {
340            return false;
341        }
342        SamplingXYLineRenderer that = (SamplingXYLineRenderer) obj;
343        if (!ShapeUtils.equal(this.legendLine, that.legendLine)) {
344            return false;
345        }
346        return true;
347    }
348
349    /**
350     * Provides serialization support.
351     *
352     * @param stream  the input stream.
353     *
354     * @throws IOException  if there is an I/O error.
355     * @throws ClassNotFoundException  if there is a classpath problem.
356     */
357    private void readObject(ObjectInputStream stream)
358            throws IOException, ClassNotFoundException {
359        stream.defaultReadObject();
360        this.legendLine = SerialUtils.readShape(stream);
361    }
362
363    /**
364     * Provides serialization support.
365     *
366     * @param stream  the output stream.
367     *
368     * @throws IOException  if there is an I/O error.
369     */
370    private void writeObject(ObjectOutputStream stream) throws IOException {
371        stream.defaultWriteObject();
372        SerialUtils.writeShape(this.legendLine, stream);
373    }
374
375}