001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2017, 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 * StackedXYAreaRenderer2.java
029 * ---------------------------
030 * (C) Copyright 2004-2017, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited), based on
033 *                   the StackedXYAreaRenderer class by Richard Atkinson;
034 * Contributor(s):   Ulrich Voigt (patch #312);
035 *
036 * Changes:
037 * --------
038 * 30-Apr-2004 : Version 1 (DG);
039 * 15-Jul-2004 : Switched getX() with getXValue() and getY() with
040 *               getYValue() (DG);
041 * 10-Sep-2004 : Removed getRangeType() method (DG);
042 * 06-Jan-2004 : Renamed getRangeExtent() --> findRangeBounds (DG);
043 * 28-Mar-2005 : Use getXValue() and getYValue() from dataset (DG);
044 * 03-Oct-2005 : Add entity generation to drawItem() method (DG);
045 * ------------- JFREECHART 1.0.x ---------------------------------------------
046 * 22-Aug-2006 : Handle null and empty datasets correctly in the
047 *               findRangeBounds() method (DG);
048 * 22-Sep-2006 : Added a flag to allow rounding of x-coordinates (after
049 *               translation to Java2D space) in order to avoid the striping
050 *               that can result from anti-aliasing (thanks to Doug
051 *               Clayton) (DG);
052 * 30-Nov-2006 : Added accessor methods for the roundXCoordinates flag (DG);
053 * 02-Jun-2008 : Fixed bug with PlotOrientation.HORIZONTAL (DG);
054 * 04-Aug-2014 : Fix entity hotspot (patch 312) (UV);
055 *
056 */
057
058package org.jfree.chart.renderer.xy;
059
060import java.awt.Graphics2D;
061import java.awt.Paint;
062import java.awt.geom.Area;
063import java.awt.geom.GeneralPath;
064import java.awt.geom.Rectangle2D;
065import java.io.Serializable;
066
067import org.jfree.chart.axis.ValueAxis;
068import org.jfree.chart.entity.EntityCollection;
069import org.jfree.chart.event.RendererChangeEvent;
070import org.jfree.chart.labels.XYToolTipGenerator;
071import org.jfree.chart.plot.CrosshairState;
072import org.jfree.chart.plot.PlotOrientation;
073import org.jfree.chart.plot.PlotRenderingInfo;
074import org.jfree.chart.plot.XYPlot;
075import org.jfree.chart.ui.RectangleEdge;
076import org.jfree.chart.urls.XYURLGenerator;
077import org.jfree.chart.util.PublicCloneable;
078import org.jfree.data.Range;
079import org.jfree.data.xy.TableXYDataset;
080import org.jfree.data.xy.XYDataset;
081
082/**
083 * A stacked area renderer for the {@link XYPlot} class.
084 * The example shown here is generated by the
085 * {@code StackedXYAreaChartDemo2.java} program included in the
086 * JFreeChart demo collection:
087 * <br><br>
088 * <img src="../../../../../images/StackedXYAreaRenderer2Sample.png"
089 * alt="StackedXYAreaRenderer2Sample.png">
090 */
091public class StackedXYAreaRenderer2 extends XYAreaRenderer2
092        implements Cloneable, PublicCloneable, Serializable {
093
094    /** For serialization. */
095    private static final long serialVersionUID = 7752676509764539182L;
096
097    /**
098     * This flag controls whether or not the x-coordinates (in Java2D space)
099     * are rounded to integers.  When set to true, this can avoid the vertical
100     * striping that anti-aliasing can generate.  However, the rounding may not
101     * be appropriate for output in high resolution formats (for example,
102     * vector graphics formats such as SVG and PDF).
103     *
104     * @since 1.0.3
105     */
106    private boolean roundXCoordinates;
107
108    /**
109     * Creates a new renderer.
110     */
111    public StackedXYAreaRenderer2() {
112        this(null, null);
113    }
114
115    /**
116     * Constructs a new renderer.
117     *
118     * @param labelGenerator  the tool tip generator to use ({@code null} 
119     *     permitted).
120     * @param urlGenerator  the URL generator ({@code null} permitted).
121     */
122    public StackedXYAreaRenderer2(XYToolTipGenerator labelGenerator,
123                                  XYURLGenerator urlGenerator) {
124        super(labelGenerator, urlGenerator);
125        this.roundXCoordinates = true;
126    }
127
128    /**
129     * Returns the flag that controls whether or not the x-coordinates (in
130     * Java2D space) are rounded to integer values.
131     *
132     * @return The flag.
133     *
134     * @since 1.0.4
135     *
136     * @see #setRoundXCoordinates(boolean)
137     */
138    public boolean getRoundXCoordinates() {
139        return this.roundXCoordinates;
140    }
141
142    /**
143     * Sets the flag that controls whether or not the x-coordinates (in
144     * Java2D space) are rounded to integer values, and sends a
145     * {@link RendererChangeEvent} to all registered listeners.
146     *
147     * @param round  the new flag value.
148     *
149     * @since 1.0.4
150     *
151     * @see #getRoundXCoordinates()
152     */
153    public void setRoundXCoordinates(boolean round) {
154        this.roundXCoordinates = round;
155        fireChangeEvent();
156    }
157
158    /**
159     * Returns the range of values the renderer requires to display all the
160     * items from the specified dataset.
161     *
162     * @param dataset  the dataset ({@code null} permitted).
163     *
164     * @return The range (or {@code null} if the dataset is {@code null} or 
165     *     empty).
166     */
167    @Override
168    public Range findRangeBounds(XYDataset dataset) {
169        if (dataset == null) {
170            return null;
171        }
172        double min = Double.POSITIVE_INFINITY;
173        double max = Double.NEGATIVE_INFINITY;
174        TableXYDataset d = (TableXYDataset) dataset;
175        int itemCount = d.getItemCount();
176        for (int i = 0; i < itemCount; i++) {
177            double[] stackValues = getStackValues((TableXYDataset) dataset,
178                    d.getSeriesCount(), i);
179            min = Math.min(min, stackValues[0]);
180            max = Math.max(max, stackValues[1]);
181        }
182        if (min == Double.POSITIVE_INFINITY) {
183            return null;
184        }
185        return new Range(min, max);
186    }
187
188    /**
189     * Returns the number of passes required by the renderer.
190     *
191     * @return 1.
192     */
193    @Override
194    public int getPassCount() {
195        return 1;
196    }
197
198    /**
199     * Draws the visual representation of a single data item.
200     *
201     * @param g2  the graphics device.
202     * @param state  the renderer state.
203     * @param dataArea  the area within which the data is being drawn.
204     * @param info  collects information about the drawing.
205     * @param plot  the plot (can be used to obtain standard color information
206     *              etc).
207     * @param domainAxis  the domain axis.
208     * @param rangeAxis  the range axis.
209     * @param dataset  the dataset.
210     * @param series  the series index (zero-based).
211     * @param item  the item index (zero-based).
212     * @param crosshairState  information about crosshairs on a plot.
213     * @param pass  the pass index.
214     */
215    @Override
216    public void drawItem(Graphics2D g2, XYItemRendererState state,
217            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
218            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
219            int series, int item, CrosshairState crosshairState, int pass) {
220
221        // setup for collecting optional entity info...
222        EntityCollection entities = null;
223        if (info != null) {
224            entities = info.getOwner().getEntityCollection();
225        }
226
227        TableXYDataset tdataset = (TableXYDataset) dataset;
228        PlotOrientation orientation = plot.getOrientation();
229
230        // get the data point...
231        double x1 = dataset.getXValue(series, item);
232        double y1 = dataset.getYValue(series, item);
233        if (Double.isNaN(y1)) {
234            y1 = 0.0;
235        }
236        double[] stack1 = getStackValues(tdataset, series, item);
237
238        // get the previous point and the next point so we can calculate a
239        // "hot spot" for the area (used by the chart entity)...
240        double x0 = dataset.getXValue(series, Math.max(item - 1, 0));
241        double y0 = dataset.getYValue(series, Math.max(item - 1, 0));
242        if (Double.isNaN(y0)) {
243            y0 = 0.0;
244        }
245        double[] stack0 = getStackValues(tdataset, series, Math.max(item - 1,
246                0));
247
248        int itemCount = dataset.getItemCount(series);
249        double x2 = dataset.getXValue(series, Math.min(item + 1,
250                itemCount - 1));
251        double y2 = dataset.getYValue(series, Math.min(item + 1,
252                itemCount - 1));
253        if (Double.isNaN(y2)) {
254            y2 = 0.0;
255        }
256        double[] stack2 = getStackValues(tdataset, series, Math.min(item + 1,
257                itemCount - 1));
258
259        double xleft = (x0 + x1) / 2.0;
260        double xright = (x1 + x2) / 2.0;
261        double[] stackLeft = averageStackValues(stack0, stack1);
262        double[] stackRight = averageStackValues(stack1, stack2);
263        double[] adjStackLeft = adjustedStackValues(stack0, stack1);
264        double[] adjStackRight = adjustedStackValues(stack1, stack2);
265
266        RectangleEdge edge0 = plot.getDomainAxisEdge();
267
268        float transX1 = (float) domainAxis.valueToJava2D(x1, dataArea, edge0);
269        float transXLeft = (float) domainAxis.valueToJava2D(xleft, dataArea,
270                edge0);
271        float transXRight = (float) domainAxis.valueToJava2D(xright, dataArea,
272                edge0);
273
274        if (this.roundXCoordinates) {
275            transX1 = Math.round(transX1);
276            transXLeft = Math.round(transXLeft);
277            transXRight = Math.round(transXRight);
278        }
279        float transY1;
280
281        RectangleEdge edge1 = plot.getRangeAxisEdge();
282
283        GeneralPath left = new GeneralPath();
284        GeneralPath right = new GeneralPath();
285        if (y1 >= 0.0) {  // handle positive value
286            transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea,
287                    edge1);
288            float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1],
289                    dataArea, edge1);
290            float transStackLeft = (float) rangeAxis.valueToJava2D(
291                    adjStackLeft[1], dataArea, edge1);
292
293            // LEFT POLYGON
294            if (y0 >= 0.0) {
295                double yleft = (y0 + y1) / 2.0 + stackLeft[1];
296                float transYLeft
297                    = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1);
298                if (orientation == PlotOrientation.VERTICAL) {
299                    left.moveTo(transX1, transY1);
300                    left.lineTo(transX1, transStack1);
301                    left.lineTo(transXLeft, transStackLeft);
302                    left.lineTo(transXLeft, transYLeft);
303                } else {
304                    left.moveTo(transY1, transX1);
305                    left.lineTo(transStack1, transX1);
306                    left.lineTo(transStackLeft, transXLeft);
307                    left.lineTo(transYLeft, transXLeft);
308                }
309                left.closePath();
310            } else {
311                if (orientation == PlotOrientation.VERTICAL) {
312                    left.moveTo(transX1, transStack1);
313                    left.lineTo(transX1, transY1);
314                    left.lineTo(transXLeft, transStackLeft);
315                } else {
316                    left.moveTo(transStack1, transX1);
317                    left.lineTo(transY1, transX1);
318                    left.lineTo(transStackLeft, transXLeft);
319                }
320                left.closePath();
321            }
322
323            float transStackRight = (float) rangeAxis.valueToJava2D(
324                    adjStackRight[1], dataArea, edge1);
325            // RIGHT POLYGON
326            if (y2 >= 0.0) {
327                double yright = (y1 + y2) / 2.0 + stackRight[1];
328                float transYRight
329                    = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1);
330                if (orientation == PlotOrientation.VERTICAL) {
331                    right.moveTo(transX1, transStack1);
332                    right.lineTo(transX1, transY1);
333                    right.lineTo(transXRight, transYRight);
334                    right.lineTo(transXRight, transStackRight);
335                } else {
336                    right.moveTo(transStack1, transX1);
337                    right.lineTo(transY1, transX1);
338                    right.lineTo(transYRight, transXRight);
339                    right.lineTo(transStackRight, transXRight);
340                }
341                right.closePath();
342            }
343            else {
344                if (orientation == PlotOrientation.VERTICAL) {
345                    right.moveTo(transX1, transStack1);
346                    right.lineTo(transX1, transY1);
347                    right.lineTo(transXRight, transStackRight);
348                } else {
349                    right.moveTo(transStack1, transX1);
350                    right.lineTo(transY1, transX1);
351                    right.lineTo(transStackRight, transXRight);
352                }
353                right.closePath();
354            }
355        }
356        else {  // handle negative value
357            transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[0], dataArea,
358                    edge1);
359            float transStack1 = (float) rangeAxis.valueToJava2D(stack1[0],
360                    dataArea, edge1);
361            float transStackLeft = (float) rangeAxis.valueToJava2D(
362                    adjStackLeft[0], dataArea, edge1);
363
364            // LEFT POLYGON
365            if (y0 >= 0.0) {
366                if (orientation == PlotOrientation.VERTICAL) {
367                    left.moveTo(transX1, transStack1);
368                    left.lineTo(transX1, transY1);
369                    left.lineTo(transXLeft, transStackLeft);
370                } else {
371                    left.moveTo(transStack1, transX1);
372                    left.lineTo(transY1, transX1);
373                    left.lineTo(transStackLeft, transXLeft);
374                }
375                left.clone();
376            } else {
377                double yleft = (y0 + y1) / 2.0 + stackLeft[0];
378                float transYLeft = (float) rangeAxis.valueToJava2D(yleft,
379                        dataArea, edge1);
380                if (orientation == PlotOrientation.VERTICAL) {
381                    left.moveTo(transX1, transY1);
382                    left.lineTo(transX1, transStack1);
383                    left.lineTo(transXLeft, transStackLeft);
384                    left.lineTo(transXLeft, transYLeft);
385                } else {
386                    left.moveTo(transY1, transX1);
387                    left.lineTo(transStack1, transX1);
388                    left.lineTo(transStackLeft, transXLeft);
389                    left.lineTo(transYLeft, transXLeft);
390                }
391                left.closePath();
392            }
393            float transStackRight = (float) rangeAxis.valueToJava2D(
394                    adjStackRight[0], dataArea, edge1);
395
396            // RIGHT POLYGON
397            if (y2 >= 0.0) {
398                if (orientation == PlotOrientation.VERTICAL) {
399                    right.moveTo(transX1, transStack1);
400                    right.lineTo(transX1, transY1);
401                    right.lineTo(transXRight, transStackRight);
402                } else {
403                    right.moveTo(transStack1, transX1);
404                    right.lineTo(transY1, transX1);
405                    right.lineTo(transStackRight, transXRight);
406                }
407                right.closePath();
408            } else {
409                double yright = (y1 + y2) / 2.0 + stackRight[0];
410                float transYRight = (float) rangeAxis.valueToJava2D(yright,
411                        dataArea, edge1);
412                if (orientation == PlotOrientation.VERTICAL) {
413                    right.moveTo(transX1, transStack1);
414                    right.lineTo(transX1, transY1);
415                    right.lineTo(transXRight, transYRight);
416                    right.lineTo(transXRight, transStackRight);
417                } else {
418                    right.moveTo(transStack1, transX1);
419                    right.lineTo(transY1, transX1);
420                    right.lineTo(transYRight, transXRight);
421                    right.lineTo(transStackRight, transXRight);
422                }
423                right.closePath();
424            }
425        }
426
427        //  Get series Paint and Stroke
428        Paint itemPaint = getItemPaint(series, item);
429        if (pass == 0) {
430            g2.setPaint(itemPaint);
431            g2.fill(left);
432            g2.fill(right);
433        }
434
435        // add an entity for the item...
436        if (entities != null) {
437            // Create the entity area and limit it to the data area
438            Area dataAreaHotspot = new Area(left);
439            dataAreaHotspot.add(new Area(right));
440            dataAreaHotspot.intersect(new Area(dataArea));
441
442            if (!dataAreaHotspot.isEmpty()) {
443                addEntity(entities, dataAreaHotspot, dataset, series, item,
444                     0.0, 0.0);
445            }
446        }
447    }
448
449    /**
450     * Calculates the stacked values (one positive and one negative) of all
451     * series up to, but not including, {@code series} for the specified
452     * item. It returns [0.0, 0.0] if {@code series} is the first series.
453     *
454     * @param dataset  the dataset ({@code null} not permitted).
455     * @param series  the series index.
456     * @param index  the item index.
457     *
458     * @return An array containing the cumulative negative and positive values
459     *     for all series values up to but excluding {@code series}
460     *     for {@code index}.
461     */
462    private double[] getStackValues(TableXYDataset dataset,
463                                    int series, int index) {
464        double[] result = new double[2];
465        for (int i = 0; i < series; i++) {
466            double v = dataset.getYValue(i, index);
467            if (!Double.isNaN(v)) {
468                if (v >= 0.0) {
469                    result[1] += v;
470                }
471                else {
472                    result[0] += v;
473                }
474            }
475        }
476        return result;
477    }
478
479    /**
480     * Returns a pair of "stack" values calculated as the mean of the two
481     * specified stack value pairs.
482     *
483     * @param stack1  the first stack pair.
484     * @param stack2  the second stack pair.
485     *
486     * @return A pair of average stack values.
487     */
488    private double[] averageStackValues(double[] stack1, double[] stack2) {
489        double[] result = new double[2];
490        result[0] = (stack1[0] + stack2[0]) / 2.0;
491        result[1] = (stack1[1] + stack2[1]) / 2.0;
492        return result;
493    }
494
495    /**
496     * Calculates adjusted stack values from the supplied values.  The value is
497     * the mean of the supplied values, unless either of the supplied values
498     * is zero, in which case the adjusted value is zero also.
499     *
500     * @param stack1  the first stack pair.
501     * @param stack2  the second stack pair.
502     *
503     * @return A pair of average stack values.
504     */
505    private double[] adjustedStackValues(double[] stack1, double[] stack2) {
506        double[] result = new double[2];
507        if (stack1[0] == 0.0 || stack2[0] == 0.0) {
508            result[0] = 0.0;
509        }
510        else {
511            result[0] = (stack1[0] + stack2[0]) / 2.0;
512        }
513        if (stack1[1] == 0.0 || stack2[1] == 0.0) {
514            result[1] = 0.0;
515        }
516        else {
517            result[1] = (stack1[1] + stack2[1]) / 2.0;
518        }
519        return result;
520    }
521
522    /**
523     * Tests this renderer for equality with an arbitrary object.
524     *
525     * @param obj  the object ({@code null} permitted).
526     *
527     * @return A boolean.
528     */
529    @Override
530    public boolean equals(Object obj) {
531        if (obj == this) {
532            return true;
533        }
534        if (!(obj instanceof StackedXYAreaRenderer2)) {
535            return false;
536        }
537        StackedXYAreaRenderer2 that = (StackedXYAreaRenderer2) obj;
538        if (this.roundXCoordinates != that.roundXCoordinates) {
539            return false;
540        }
541        return super.equals(obj);
542    }
543
544    /**
545     * Returns a clone of the renderer.
546     *
547     * @return A clone.
548     *
549     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
550     */
551    @Override
552    public Object clone() throws CloneNotSupportedException {
553        return super.clone();
554    }
555
556}