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 * XYDifferenceRenderer.java
029 * -------------------------
030 * (C) Copyright 2003-2017, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Richard West, Advanced Micro Devices, Inc. (major rewrite
034 *                   of difference drawing algorithm);
035 *                   Patrick Schlott
036 *                   Christoph Schroeder
037 *                   Martin Hoeller
038 *
039 * Changes:
040 * --------
041 * 30-Apr-2003 : Version 1 (DG);
042 * 30-Jul-2003 : Modified entity constructor (CZ);
043 * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
044 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
045 * 09-Feb-2004 : Updated to support horizontal plot orientation (DG);
046 * 10-Feb-2004 : Added default constructor, setter methods and updated
047 *               Javadocs (DG);
048 * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG);
049 * 30-Mar-2004 : Fixed bug in getNegativePaint() method (DG);
050 * 15-Jul-2004 : Switched getX() with getXValue() and getY() with
051 *               getYValue() (DG);
052 * 25-Aug-2004 : Fixed a bug preventing the use of crosshairs (DG);
053 * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
054 * 19-Jan-2005 : Now accesses only primitive values from dataset (DG);
055 * 22-Feb-2005 : Override getLegendItem(int, int) to return "line" items (DG);
056 * 13-Apr-2005 : Fixed shape positioning bug (id = 1182062) (DG);
057 * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG);
058 * 04-May-2005 : Override equals() method, renamed get/setPlotShapes() -->
059 *               get/setShapesVisible (DG);
060 * 09-Jun-2005 : Updated equals() to handle GradientPaint (DG);
061 * 16-Jun-2005 : Fix bug (1221021) affecting stroke used for each series (DG);
062 * ------------- JFREECHART 1.0.x ---------------------------------------------
063 * 24-Jan-2007 : Added flag to allow rounding of x-coordinates, and fixed
064 *               bug in clone() (DG);
065 * 05-Feb-2007 : Added an extra call to updateCrosshairValues() in
066 *               drawItemPass1(), to fix bug 1564967 (DG);
067 * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
068 * 08-Mar-2007 : Fixed entity generation (DG);
069 * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG);
070 * 23-Apr-2007 : Rewrite of difference drawing algorithm to allow use of
071 *               series with disjoint x-values (RW);
072 * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG);
073 * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG);
074 * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG);
075 * 05-Nov-2007 : Draw item labels if visible (RW);
076 * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
077 * 13-Feb-2012 : Applied patch 3450234 for bug 3425881 by Patrick Schlott and
078 *               Christoph Schroeder (MH);
079 * 03-Jul-2013 : Use ParamChecks (DG);
080 * 18-Feb-2017 : Updates for crosshairs (bug #36) (DG);
081 *
082 */
083
084package org.jfree.chart.renderer.xy;
085
086import java.awt.Color;
087import java.awt.Graphics2D;
088import java.awt.Paint;
089import java.awt.Shape;
090import java.awt.Stroke;
091import java.awt.geom.GeneralPath;
092import java.awt.geom.Line2D;
093import java.awt.geom.Rectangle2D;
094import java.io.IOException;
095import java.io.ObjectInputStream;
096import java.io.ObjectOutputStream;
097import java.util.Collections;
098import java.util.LinkedList;
099
100import org.jfree.chart.LegendItem;
101import org.jfree.chart.axis.ValueAxis;
102import org.jfree.chart.entity.EntityCollection;
103import org.jfree.chart.entity.XYItemEntity;
104import org.jfree.chart.event.RendererChangeEvent;
105import org.jfree.chart.labels.XYToolTipGenerator;
106import org.jfree.chart.plot.CrosshairState;
107import org.jfree.chart.plot.PlotOrientation;
108import org.jfree.chart.plot.PlotRenderingInfo;
109import org.jfree.chart.plot.XYPlot;
110import org.jfree.chart.ui.RectangleEdge;
111import org.jfree.chart.urls.XYURLGenerator;
112import org.jfree.chart.util.PaintUtils;
113import org.jfree.chart.util.Args;
114import org.jfree.chart.util.PublicCloneable;
115import org.jfree.chart.util.SerialUtils;
116import org.jfree.chart.util.ShapeUtils;
117import org.jfree.data.xy.XYDataset;
118
119/**
120 * A renderer for an {@link XYPlot} that highlights the differences between two
121 * series.  The example shown here is generated by the
122 * {@code DifferenceChartDemo1.java} program included in the JFreeChart
123 * demo collection:
124 * <br><br>
125 * <img src="../../../../../images/XYDifferenceRendererSample.png"
126 * alt="XYDifferenceRendererSample.png">
127 */
128public class XYDifferenceRenderer extends AbstractXYItemRenderer
129        implements XYItemRenderer, PublicCloneable {
130
131    /** For serialization. */
132    private static final long serialVersionUID = -8447915602375584857L;
133
134    /** The paint used to highlight positive differences (y(0) > y(1)). */
135    private transient Paint positivePaint;
136
137    /** The paint used to highlight negative differences (y(0) < y(1)). */
138    private transient Paint negativePaint;
139
140    /** Display shapes at each point? */
141    private boolean shapesVisible;
142
143    /** The shape to display in the legend item. */
144    private transient Shape legendLine;
145
146    /**
147     * This flag controls whether or not the x-coordinates (in Java2D space)
148     * are rounded to integers.  When set to true, this can avoid the vertical
149     * striping that anti-aliasing can generate.  However, the rounding may not
150     * be appropriate for output in high resolution formats (for example,
151     * vector graphics formats such as SVG and PDF).
152     *
153     * @since 1.0.4
154     */
155    private boolean roundXCoordinates;
156
157    /**
158     * Creates a new renderer with default attributes.
159     */
160    public XYDifferenceRenderer() {
161        this(Color.GREEN, Color.RED, false);
162    }
163
164    /**
165     * Creates a new renderer.
166     *
167     * @param positivePaint  the highlight color for positive differences
168     *                       ({@code null} not permitted).
169     * @param negativePaint  the highlight color for negative differences
170     *                       ({@code null} not permitted).
171     * @param shapes  draw shapes?
172     */
173    public XYDifferenceRenderer(Paint positivePaint, Paint negativePaint,
174                                boolean shapes) {
175        Args.nullNotPermitted(positivePaint, "positivePaint");
176        Args.nullNotPermitted(negativePaint, "negativePaint");
177        this.positivePaint = positivePaint;
178        this.negativePaint = negativePaint;
179        this.shapesVisible = shapes;
180        this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
181        this.roundXCoordinates = false;
182    }
183
184    /**
185     * Returns the paint used to highlight positive differences.
186     *
187     * @return The paint (never {@code null}).
188     *
189     * @see #setPositivePaint(Paint)
190     */
191    public Paint getPositivePaint() {
192        return this.positivePaint;
193    }
194
195    /**
196     * Sets the paint used to highlight positive differences and sends a
197     * {@link RendererChangeEvent} to all registered listeners.
198     *
199     * @param paint  the paint ({@code null} not permitted).
200     *
201     * @see #getPositivePaint()
202     */
203    public void setPositivePaint(Paint paint) {
204        Args.nullNotPermitted(paint, "paint");
205        this.positivePaint = paint;
206        fireChangeEvent();
207    }
208
209    /**
210     * Returns the paint used to highlight negative differences.
211     *
212     * @return The paint (never {@code null}).
213     *
214     * @see #setNegativePaint(Paint)
215     */
216    public Paint getNegativePaint() {
217        return this.negativePaint;
218    }
219
220    /**
221     * Sets the paint used to highlight negative differences.
222     *
223     * @param paint  the paint ({@code null} not permitted).
224     *
225     * @see #getNegativePaint()
226     */
227    public void setNegativePaint(Paint paint) {
228        Args.nullNotPermitted(paint, "paint");
229        this.negativePaint = paint;
230        notifyListeners(new RendererChangeEvent(this));
231    }
232
233    /**
234     * Returns a flag that controls whether or not shapes are drawn for each
235     * data value.
236     *
237     * @return A boolean.
238     *
239     * @see #setShapesVisible(boolean)
240     */
241    public boolean getShapesVisible() {
242        return this.shapesVisible;
243    }
244
245    /**
246     * Sets a flag that controls whether or not shapes are drawn for each
247     * data value, and sends a {@link RendererChangeEvent} to all registered
248     * listeners.
249     *
250     * @param flag  the flag.
251     *
252     * @see #getShapesVisible()
253     */
254    public void setShapesVisible(boolean flag) {
255        this.shapesVisible = flag;
256        fireChangeEvent();
257    }
258
259    /**
260     * Returns the shape used to represent a line in the legend.
261     *
262     * @return The legend line (never {@code null}).
263     *
264     * @see #setLegendLine(Shape)
265     */
266    public Shape getLegendLine() {
267        return this.legendLine;
268    }
269
270    /**
271     * Sets the shape used as a line in each legend item and sends a
272     * {@link RendererChangeEvent} to all registered listeners.
273     *
274     * @param line  the line ({@code null} not permitted).
275     *
276     * @see #getLegendLine()
277     */
278    public void setLegendLine(Shape line) {
279        Args.nullNotPermitted(line, "line");
280        this.legendLine = line;
281        fireChangeEvent();
282    }
283
284    /**
285     * Returns the flag that controls whether or not the x-coordinates (in
286     * Java2D space) are rounded to integer values.
287     *
288     * @return The flag.
289     *
290     * @since 1.0.4
291     *
292     * @see #setRoundXCoordinates(boolean)
293     */
294    public boolean getRoundXCoordinates() {
295        return this.roundXCoordinates;
296    }
297
298    /**
299     * Sets the flag that controls whether or not the x-coordinates (in
300     * Java2D space) are rounded to integer values, and sends a
301     * {@link RendererChangeEvent} to all registered listeners.
302     *
303     * @param round  the new flag value.
304     *
305     * @since 1.0.4
306     *
307     * @see #getRoundXCoordinates()
308     */
309    public void setRoundXCoordinates(boolean round) {
310        this.roundXCoordinates = round;
311        fireChangeEvent();
312    }
313
314    /**
315     * Initialises the renderer and returns a state object that should be
316     * passed to subsequent calls to the drawItem() method.  This method will
317     * be called before the first item is rendered, giving the renderer an
318     * opportunity to initialise any state information it wants to maintain.
319     * The renderer can do nothing if it chooses.
320     *
321     * @param g2  the graphics device.
322     * @param dataArea  the area inside the axes.
323     * @param plot  the plot.
324     * @param data  the data.
325     * @param info  an optional info collection object to return data back to
326     *              the caller.
327     *
328     * @return A state object.
329     */
330    @Override
331    public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea,
332            XYPlot plot, XYDataset data, PlotRenderingInfo info) {
333        XYItemRendererState state = super.initialise(g2, dataArea, plot, data,
334                info);
335        state.setProcessVisibleItemsOnly(false);
336        return state;
337    }
338
339    /**
340     * Returns {@code 2}, the number of passes required by the renderer.
341     * The {@link XYPlot} will run through the dataset this number of times.
342     *
343     * @return The number of passes required by the renderer.
344     */
345    @Override
346    public int getPassCount() {
347        return 2;
348    }
349
350    /**
351     * Draws the visual representation of a single data item.
352     *
353     * @param g2  the graphics device.
354     * @param state  the renderer state.
355     * @param dataArea  the area within which the data is being drawn.
356     * @param info  collects information about the drawing.
357     * @param plot  the plot (can be used to obtain standard color
358     *              information etc).
359     * @param domainAxis  the domain (horizontal) axis.
360     * @param rangeAxis  the range (vertical) axis.
361     * @param dataset  the dataset.
362     * @param series  the series index (zero-based).
363     * @param item  the item index (zero-based).
364     * @param crosshairState  crosshair information for the plot
365     *                        ({@code null} permitted).
366     * @param pass  the pass index.
367     */
368    @Override
369    public void drawItem(Graphics2D g2, XYItemRendererState state,
370            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
371            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
372            int series, int item, CrosshairState crosshairState, int pass) {
373
374        if (pass == 0) {
375            drawItemPass0(g2, dataArea, info, plot, domainAxis, rangeAxis,
376                    dataset, series, item, crosshairState);
377        }
378        else if (pass == 1) {
379            drawItemPass1(g2, dataArea, info, plot, domainAxis, rangeAxis,
380                    dataset, series, item, crosshairState);
381        }
382
383    }
384
385    /**
386     * Draws the visual representation of a single data item, first pass.
387     *
388     * @param x_graphics  the graphics device.
389     * @param x_dataArea  the area within which the data is being drawn.
390     * @param x_info  collects information about the drawing.
391     * @param x_plot  the plot (can be used to obtain standard color
392     *                information etc).
393     * @param x_domainAxis  the domain (horizontal) axis.
394     * @param x_rangeAxis  the range (vertical) axis.
395     * @param x_dataset  the dataset.
396     * @param x_series  the series index (zero-based).
397     * @param x_item  the item index (zero-based).
398     * @param x_crosshairState  crosshair information for the plot
399     *                          ({@code null} permitted).
400     */
401    protected void drawItemPass0(Graphics2D x_graphics,
402                                 Rectangle2D x_dataArea,
403                                 PlotRenderingInfo x_info,
404                                 XYPlot x_plot,
405                                 ValueAxis x_domainAxis,
406                                 ValueAxis x_rangeAxis,
407                                 XYDataset x_dataset,
408                                 int x_series,
409                                 int x_item,
410                                 CrosshairState x_crosshairState) {
411
412        if (!((0 == x_series) && (0 == x_item))) {
413            return;
414        }
415
416        boolean b_impliedZeroSubtrahend = (1 == x_dataset.getSeriesCount());
417
418        // check if either series is a degenerate case (i.e. less than 2 points)
419        if (isEitherSeriesDegenerate(x_dataset, b_impliedZeroSubtrahend)) {
420            return;
421        }
422
423        // check if series are disjoint (i.e. domain-spans do not overlap)
424        if (!b_impliedZeroSubtrahend && areSeriesDisjoint(x_dataset)) {
425            return;
426        }
427
428        // polygon definitions
429        LinkedList l_minuendXs    = new LinkedList();
430        LinkedList l_minuendYs    = new LinkedList();
431        LinkedList l_subtrahendXs = new LinkedList();
432        LinkedList l_subtrahendYs = new LinkedList();
433        LinkedList l_polygonXs    = new LinkedList();
434        LinkedList l_polygonYs    = new LinkedList();
435
436        // state
437        int l_minuendItem      = 0;
438        int l_minuendItemCount = x_dataset.getItemCount(0);
439        Double l_minuendCurX   = null;
440        Double l_minuendNextX  = null;
441        Double l_minuendCurY   = null;
442        Double l_minuendNextY  = null;
443        double l_minuendMaxY   = Double.NEGATIVE_INFINITY;
444        double l_minuendMinY   = Double.POSITIVE_INFINITY;
445
446        int l_subtrahendItem      = 0;
447        int l_subtrahendItemCount = 0; // actual value set below
448        Double l_subtrahendCurX   = null;
449        Double l_subtrahendNextX  = null;
450        Double l_subtrahendCurY   = null;
451        Double l_subtrahendNextY  = null;
452        double l_subtrahendMaxY   = Double.NEGATIVE_INFINITY;
453        double l_subtrahendMinY   = Double.POSITIVE_INFINITY;
454
455        // if a subtrahend is not specified, assume it is zero
456        if (b_impliedZeroSubtrahend) {
457            l_subtrahendItem      = 0;
458            l_subtrahendItemCount = 2;
459            l_subtrahendCurX      = x_dataset.getXValue(0, 0);
460            l_subtrahendNextX     = x_dataset.getXValue(0,
461                    (l_minuendItemCount - 1));
462            l_subtrahendCurY      = 0.0;
463            l_subtrahendNextY     = 0.0;
464            l_subtrahendMaxY      = 0.0;
465            l_subtrahendMinY      = 0.0;
466
467            l_subtrahendXs.add(l_subtrahendCurX);
468            l_subtrahendYs.add(l_subtrahendCurY);
469        }
470        else {
471            l_subtrahendItemCount = x_dataset.getItemCount(1);
472        }
473
474        boolean b_minuendDone           = false;
475        boolean b_minuendAdvanced       = true;
476        boolean b_minuendAtIntersect    = false;
477        boolean b_minuendFastForward    = false;
478        boolean b_subtrahendDone        = false;
479        boolean b_subtrahendAdvanced    = true;
480        boolean b_subtrahendAtIntersect = false;
481        boolean b_subtrahendFastForward = false;
482        boolean b_colinear              = false;
483
484        boolean b_positive;
485
486        // coordinate pairs
487        double l_x1 = 0.0, l_y1 = 0.0; // current minuend point
488        double l_x2 = 0.0, l_y2 = 0.0; // next minuend point
489        double l_x3 = 0.0, l_y3 = 0.0; // current subtrahend point
490        double l_x4 = 0.0, l_y4 = 0.0; // next subtrahend point
491
492        // fast-forward through leading tails
493        boolean b_fastForwardDone = false;
494        while (!b_fastForwardDone) {
495            // get the x and y coordinates
496            l_x1 = x_dataset.getXValue(0, l_minuendItem);
497            l_y1 = x_dataset.getYValue(0, l_minuendItem);
498            l_x2 = x_dataset.getXValue(0, l_minuendItem + 1);
499            l_y2 = x_dataset.getYValue(0, l_minuendItem + 1);
500
501            l_minuendCurX  = l_x1;
502            l_minuendCurY  = l_y1;
503            l_minuendNextX = l_x2;
504            l_minuendNextY = l_y2;
505
506            if (b_impliedZeroSubtrahend) {
507                l_x3 = l_subtrahendCurX;
508                l_y3 = l_subtrahendCurY;
509                l_x4 = l_subtrahendNextX;
510                l_y4 = l_subtrahendNextY;
511            }
512            else {
513                l_x3 = x_dataset.getXValue(1, l_subtrahendItem);
514                l_y3 = x_dataset.getYValue(1, l_subtrahendItem);
515                l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1);
516                l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1);
517
518                l_subtrahendCurX  = l_x3;
519                l_subtrahendCurY  = l_y3;
520                l_subtrahendNextX = l_x4;
521                l_subtrahendNextY = l_y4;
522            }
523
524            if (l_x2 <= l_x3) {
525                // minuend needs to be fast forwarded
526                l_minuendItem++;
527                b_minuendFastForward = true;
528                continue;
529            }
530
531            if (l_x4 <= l_x1) {
532                // subtrahend needs to be fast forwarded
533                l_subtrahendItem++;
534                b_subtrahendFastForward = true;
535                continue;
536            }
537
538            // check if initial polygon needs to be clipped
539            if ((l_x3 < l_x1) && (l_x1 < l_x4)) {
540                // project onto subtrahend
541                double l_slope   = (l_y4 - l_y3) / (l_x4 - l_x3);
542                l_subtrahendCurX = l_minuendCurX;
543                l_subtrahendCurY = (l_slope * l_x1)
544                        + (l_y3 - (l_slope * l_x3));
545
546                l_subtrahendXs.add(l_subtrahendCurX);
547                l_subtrahendYs.add(l_subtrahendCurY);
548            }
549
550            if ((l_x1 < l_x3) && (l_x3 < l_x2)) {
551                // project onto minuend
552                double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1);
553                l_minuendCurX  = l_subtrahendCurX;
554                l_minuendCurY  = (l_slope * l_x3)
555                        + (l_y1 - (l_slope * l_x1));
556
557                l_minuendXs.add(l_minuendCurX);
558                l_minuendYs.add(l_minuendCurY);
559            }
560
561            l_minuendMaxY    = l_minuendCurY;
562            l_minuendMinY    = l_minuendCurY;
563            l_subtrahendMaxY = l_subtrahendCurY;
564            l_subtrahendMinY = l_subtrahendCurY;
565
566            b_fastForwardDone = true;
567        }
568
569        // start of algorithm
570        while (!b_minuendDone && !b_subtrahendDone) {
571            if (!b_minuendDone && !b_minuendFastForward && b_minuendAdvanced) {
572                l_x1 = x_dataset.getXValue(0, l_minuendItem);
573                l_y1 = x_dataset.getYValue(0, l_minuendItem);
574                l_minuendCurX = l_x1;
575                l_minuendCurY = l_y1;
576
577                if (!b_minuendAtIntersect) {
578                    l_minuendXs.add(l_minuendCurX);
579                    l_minuendYs.add(l_minuendCurY);
580                }
581
582                l_minuendMaxY = Math.max(l_minuendMaxY, l_y1);
583                l_minuendMinY = Math.min(l_minuendMinY, l_y1);
584
585                l_x2 = x_dataset.getXValue(0, l_minuendItem + 1);
586                l_y2 = x_dataset.getYValue(0, l_minuendItem + 1);
587                l_minuendNextX = l_x2;
588                l_minuendNextY = l_y2;
589            }
590
591            // never updated the subtrahend if it is implied to be zero
592            if (!b_impliedZeroSubtrahend && !b_subtrahendDone
593                    && !b_subtrahendFastForward && b_subtrahendAdvanced) {
594                l_x3 = x_dataset.getXValue(1, l_subtrahendItem);
595                l_y3 = x_dataset.getYValue(1, l_subtrahendItem);
596                l_subtrahendCurX = l_x3;
597                l_subtrahendCurY = l_y3;
598
599                if (!b_subtrahendAtIntersect) {
600                    l_subtrahendXs.add(l_subtrahendCurX);
601                    l_subtrahendYs.add(l_subtrahendCurY);
602                }
603
604                l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_y3);
605                l_subtrahendMinY = Math.min(l_subtrahendMinY, l_y3);
606
607                l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1);
608                l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1);
609                l_subtrahendNextX = l_x4;
610                l_subtrahendNextY = l_y4;
611            }
612
613            // deassert b_*FastForward (only matters for 1st time through loop)
614            b_minuendFastForward    = false;
615            b_subtrahendFastForward = false;
616
617            Double l_intersectX = null;
618            Double l_intersectY = null;
619            boolean b_intersect = false;
620
621            b_minuendAtIntersect    = false;
622            b_subtrahendAtIntersect = false;
623
624            // check for intersect
625            if ((l_x2 == l_x4) && (l_y2 == l_y4)) {
626                // check if line segments are colinear
627                if ((l_x1 == l_x3) && (l_y1 == l_y3)) {
628                    b_colinear = true;
629                }
630                else {
631                    // the intersect is at the next point for both the minuend
632                    // and subtrahend
633                    l_intersectX = l_x2;
634                    l_intersectY = l_y2;
635
636                    b_intersect             = true;
637                    b_minuendAtIntersect    = true;
638                    b_subtrahendAtIntersect = true;
639                 }
640            }
641            else {
642                // compute common denominator
643                double l_denominator = ((l_y4 - l_y3) * (l_x2 - l_x1))
644                        - ((l_x4 - l_x3) * (l_y2 - l_y1));
645
646                // compute common deltas
647                double l_deltaY = l_y1 - l_y3;
648                double l_deltaX = l_x1 - l_x3;
649
650                // compute numerators
651                double l_numeratorA = ((l_x4 - l_x3) * l_deltaY)
652                        - ((l_y4 - l_y3) * l_deltaX);
653                double l_numeratorB = ((l_x2 - l_x1) * l_deltaY)
654                        - ((l_y2 - l_y1) * l_deltaX);
655
656                // check if line segments are colinear
657                if ((0 == l_numeratorA) && (0 == l_numeratorB)
658                        && (0 == l_denominator)) {
659                    b_colinear = true;
660                }
661                else {
662                    // check if previously colinear
663                    if (b_colinear) {
664                        // clear colinear points and flag
665                        l_minuendXs.clear();
666                        l_minuendYs.clear();
667                        l_subtrahendXs.clear();
668                        l_subtrahendYs.clear();
669                        l_polygonXs.clear();
670                        l_polygonYs.clear();
671
672                        b_colinear = false;
673
674                        // set new starting point for the polygon
675                        boolean b_useMinuend = ((l_x3 <= l_x1)
676                                && (l_x1 <= l_x4));
677                        l_polygonXs.add(b_useMinuend ? l_minuendCurX
678                                : l_subtrahendCurX);
679                        l_polygonYs.add(b_useMinuend ? l_minuendCurY
680                                : l_subtrahendCurY);
681                    }
682                }
683
684                // compute slope components
685                double l_slopeA = l_numeratorA / l_denominator;
686                double l_slopeB = l_numeratorB / l_denominator;
687
688                // test if both grahphs have a vertical rise at the same x-value
689                boolean b_vertical = (l_x1 == l_x2) && (l_x3 == l_x4) && (l_x2 == l_x4);
690
691                // check if the line segments intersect
692                if (((0 < l_slopeA) && (l_slopeA <= 1) && (0 < l_slopeB)
693                        && (l_slopeB <= 1))|| b_vertical) {
694
695                    // compute the point of intersection
696                    double l_xi;
697                    double l_yi;
698                    if(b_vertical){
699                        b_colinear = false;
700                        l_xi = l_x2;
701                        l_yi = l_x4;
702                    }
703                    else{
704                        l_xi = l_x1 + (l_slopeA * (l_x2 - l_x1));
705                        l_yi = l_y1 + (l_slopeA * (l_y2 - l_y1));
706                    }
707
708                    l_intersectX            = l_xi;
709                    l_intersectY            = l_yi;
710                    b_intersect             = true;
711                    b_minuendAtIntersect    = ((l_xi == l_x2)
712                            && (l_yi == l_y2));
713                    b_subtrahendAtIntersect = ((l_xi == l_x4)
714                            && (l_yi == l_y4));
715
716                    // advance minuend and subtrahend to intesect
717                    l_minuendCurX    = l_intersectX;
718                    l_minuendCurY    = l_intersectY;
719                    l_subtrahendCurX = l_intersectX;
720                    l_subtrahendCurY = l_intersectY;
721                }
722            }
723
724            if (b_intersect) {
725                // create the polygon
726                // add the minuend's points to polygon
727                l_polygonXs.addAll(l_minuendXs);
728                l_polygonYs.addAll(l_minuendYs);
729
730                // add intersection point to the polygon
731                l_polygonXs.add(l_intersectX);
732                l_polygonYs.add(l_intersectY);
733
734                // add the subtrahend's points to the polygon in reverse
735                Collections.reverse(l_subtrahendXs);
736                Collections.reverse(l_subtrahendYs);
737                l_polygonXs.addAll(l_subtrahendXs);
738                l_polygonYs.addAll(l_subtrahendYs);
739
740                // create an actual polygon
741                b_positive = (l_subtrahendMaxY <= l_minuendMaxY)
742                        && (l_subtrahendMinY <= l_minuendMinY);
743                createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis,
744                        x_rangeAxis, b_positive, l_polygonXs, l_polygonYs);
745
746                // clear the point vectors
747                l_minuendXs.clear();
748                l_minuendYs.clear();
749                l_subtrahendXs.clear();
750                l_subtrahendYs.clear();
751                l_polygonXs.clear();
752                l_polygonYs.clear();
753
754                // set the maxY and minY values to intersect y-value
755                double l_y       = l_intersectY;
756                l_minuendMaxY    = l_y;
757                l_subtrahendMaxY = l_y;
758                l_minuendMinY    = l_y;
759                l_subtrahendMinY = l_y;
760
761                // add interection point to new polygon
762                l_polygonXs.add(l_intersectX);
763                l_polygonYs.add(l_intersectY);
764            }
765
766            // advance the minuend if needed
767            if (l_x2 <= l_x4) {
768                l_minuendItem++;
769                b_minuendAdvanced = true;
770            }
771            else {
772                b_minuendAdvanced = false;
773            }
774
775            // advance the subtrahend if needed
776            if (l_x4 <= l_x2) {
777                l_subtrahendItem++;
778                b_subtrahendAdvanced = true;
779            }
780            else {
781                b_subtrahendAdvanced = false;
782            }
783
784            b_minuendDone    = (l_minuendItem == (l_minuendItemCount - 1));
785            b_subtrahendDone = (l_subtrahendItem == (l_subtrahendItemCount
786                    - 1));
787        }
788
789        // check if the final polygon needs to be clipped
790        if (b_minuendDone && (l_x3 < l_x2) && (l_x2 < l_x4)) {
791            // project onto subtrahend
792            double l_slope    = (l_y4 - l_y3) / (l_x4 - l_x3);
793            l_subtrahendNextX = l_minuendNextX;
794            l_subtrahendNextY = (l_slope * l_x2)
795                    + (l_y3 - (l_slope * l_x3));
796        }
797
798        if (b_subtrahendDone && (l_x1 < l_x4) && (l_x4 < l_x2)) {
799            // project onto minuend
800            double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1);
801            l_minuendNextX = l_subtrahendNextX;
802            l_minuendNextY = (l_slope * l_x4)
803                    + (l_y1 - (l_slope * l_x1));
804        }
805
806        // consider last point of minuend and subtrahend for determining
807        // positivity
808        l_minuendMaxY    = Math.max(l_minuendMaxY, l_minuendNextY);
809        l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_subtrahendNextY);
810        l_minuendMinY    = Math.min(l_minuendMinY, l_minuendNextY);
811        l_subtrahendMinY = Math.min(l_subtrahendMinY, l_subtrahendNextY);
812
813        // add the last point of the minuned and subtrahend
814        l_minuendXs.add(l_minuendNextX);
815        l_minuendYs.add(l_minuendNextY);
816        l_subtrahendXs.add(l_subtrahendNextX);
817        l_subtrahendYs.add(l_subtrahendNextY);
818
819        // create the polygon
820        // add the minuend's points to polygon
821        l_polygonXs.addAll(l_minuendXs);
822        l_polygonYs.addAll(l_minuendYs);
823
824        // add the subtrahend's points to the polygon in reverse
825        Collections.reverse(l_subtrahendXs);
826        Collections.reverse(l_subtrahendYs);
827        l_polygonXs.addAll(l_subtrahendXs);
828        l_polygonYs.addAll(l_subtrahendYs);
829
830        // create an actual polygon
831        b_positive = (l_subtrahendMaxY <= l_minuendMaxY)
832                && (l_subtrahendMinY <= l_minuendMinY);
833        createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis,
834                x_rangeAxis, b_positive, l_polygonXs, l_polygonYs);
835    }
836
837    /**
838     * Draws the visual representation of a single data item, second pass.  In
839     * the second pass, the renderer draws the lines and shapes for the
840     * individual points in the two series.
841     *
842     * @param x_graphics  the graphics device.
843     * @param x_dataArea  the area within which the data is being drawn.
844     * @param x_info  collects information about the drawing.
845     * @param x_plot  the plot (can be used to obtain standard color
846     *         information etc).
847     * @param x_domainAxis  the domain (horizontal) axis.
848     * @param x_rangeAxis  the range (vertical) axis.
849     * @param x_dataset  the dataset.
850     * @param x_series  the series index (zero-based).
851     * @param x_item  the item index (zero-based).
852     * @param x_crosshairState  crosshair information for the plot
853     *                          ({@code null} permitted).
854     */
855    protected void drawItemPass1(Graphics2D x_graphics,
856                                 Rectangle2D x_dataArea,
857                                 PlotRenderingInfo x_info,
858                                 XYPlot x_plot,
859                                 ValueAxis x_domainAxis,
860                                 ValueAxis x_rangeAxis,
861                                 XYDataset x_dataset,
862                                 int x_series,
863                                 int x_item,
864                                 CrosshairState x_crosshairState) {
865
866        Shape l_entityArea = null;
867        EntityCollection l_entities = null;
868        if (null != x_info) {
869            l_entities = x_info.getOwner().getEntityCollection();
870        }
871
872        Paint l_seriesPaint   = getItemPaint(x_series, x_item);
873        Stroke l_seriesStroke = getItemStroke(x_series, x_item);
874        x_graphics.setPaint(l_seriesPaint);
875        x_graphics.setStroke(l_seriesStroke);
876
877        PlotOrientation l_orientation      = x_plot.getOrientation();
878        RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge();
879        RectangleEdge l_rangeAxisLocation  = x_plot.getRangeAxisEdge();
880
881        double l_x0 = x_dataset.getXValue(x_series, x_item);
882        double l_y0 = x_dataset.getYValue(x_series, x_item);
883        double l_x1 = x_domainAxis.valueToJava2D(l_x0, x_dataArea,
884                l_domainAxisLocation);
885        double l_y1 = x_rangeAxis.valueToJava2D(l_y0, x_dataArea,
886                l_rangeAxisLocation);
887
888        if (getShapesVisible()) {
889            Shape l_shape = getItemShape(x_series, x_item);
890            if (l_orientation == PlotOrientation.HORIZONTAL) {
891                l_shape = ShapeUtils.createTranslatedShape(l_shape,
892                        l_y1, l_x1);
893            }
894            else {
895                l_shape = ShapeUtils.createTranslatedShape(l_shape,
896                        l_x1, l_y1);
897            }
898            if (l_shape.intersects(x_dataArea)) {
899                x_graphics.setPaint(getItemPaint(x_series, x_item));
900                x_graphics.fill(l_shape);
901            }
902            l_entityArea = l_shape;
903        }
904
905        // add an entity for the item...
906        if (null != l_entities) {
907            if (null == l_entityArea) {
908                l_entityArea = new Rectangle2D.Double((l_x1 - 2), (l_y1 - 2),
909                        4, 4);
910            }
911            String l_tip = null;
912            XYToolTipGenerator l_tipGenerator = getToolTipGenerator(x_series,
913                    x_item);
914            if (null != l_tipGenerator) {
915                l_tip = l_tipGenerator.generateToolTip(x_dataset, x_series,
916                        x_item);
917            }
918            String l_url = null;
919            XYURLGenerator l_urlGenerator = getURLGenerator();
920            if (null != l_urlGenerator) {
921                l_url = l_urlGenerator.generateURL(x_dataset, x_series,
922                        x_item);
923            }
924            XYItemEntity l_entity = new XYItemEntity(l_entityArea, x_dataset,
925                    x_series, x_item, l_tip, l_url);
926            l_entities.add(l_entity);
927        }
928
929        // draw the item label if there is one...
930        if (isItemLabelVisible(x_series, x_item)) {
931            drawItemLabel(x_graphics, l_orientation, x_dataset, x_series,
932                          x_item, l_x1, l_y1, (l_y1 < 0.0));
933        }
934
935        int datasetIndex = x_plot.indexOf(x_dataset);
936        updateCrosshairValues(x_crosshairState, l_x0, l_y0, datasetIndex,
937                              l_x1, l_y1, l_orientation);
938
939        if (0 == x_item) {
940            return;
941        }
942
943        double l_x2 = x_domainAxis.valueToJava2D(x_dataset.getXValue(x_series,
944                (x_item - 1)), x_dataArea, l_domainAxisLocation);
945        double l_y2 = x_rangeAxis.valueToJava2D(x_dataset.getYValue(x_series,
946                (x_item - 1)), x_dataArea, l_rangeAxisLocation);
947
948        Line2D l_line = null;
949        if (PlotOrientation.HORIZONTAL == l_orientation) {
950            l_line = new Line2D.Double(l_y1, l_x1, l_y2, l_x2);
951        }
952        else if (PlotOrientation.VERTICAL == l_orientation) {
953            l_line = new Line2D.Double(l_x1, l_y1, l_x2, l_y2);
954        }
955
956        if ((null != l_line) && l_line.intersects(x_dataArea)) {
957            x_graphics.setPaint(getItemPaint(x_series, x_item));
958            x_graphics.setStroke(getItemStroke(x_series, x_item));
959            x_graphics.draw(l_line);
960        }
961    }
962
963    /**
964     * Determines if a dataset is degenerate.  A degenerate dataset is a
965     * dataset where either series has less than two (2) points.
966     *
967     * @param x_dataset  the dataset.
968     * @param x_impliedZeroSubtrahend  if false, do not check the subtrahend
969     *
970     * @return true if the dataset is degenerate.
971     */
972    private boolean isEitherSeriesDegenerate(XYDataset x_dataset,
973            boolean x_impliedZeroSubtrahend) {
974
975        if (x_impliedZeroSubtrahend) {
976            return (x_dataset.getItemCount(0) < 2);
977        }
978
979        return ((x_dataset.getItemCount(0) < 2)
980                || (x_dataset.getItemCount(1) < 2));
981    }
982
983    /**
984     * Determines if the two (2) series are disjoint.
985     * Disjoint series do not overlap in the domain space.
986     *
987     * @param x_dataset  the dataset.
988     *
989     * @return true if the dataset is degenerate.
990     */
991    private boolean areSeriesDisjoint(XYDataset x_dataset) {
992
993        int l_minuendItemCount = x_dataset.getItemCount(0);
994        double l_minuendFirst  = x_dataset.getXValue(0, 0);
995        double l_minuendLast   = x_dataset.getXValue(0, l_minuendItemCount - 1);
996
997        int l_subtrahendItemCount = x_dataset.getItemCount(1);
998        double l_subtrahendFirst  = x_dataset.getXValue(1, 0);
999        double l_subtrahendLast   = x_dataset.getXValue(1,
1000                l_subtrahendItemCount - 1);
1001
1002        return ((l_minuendLast < l_subtrahendFirst)
1003                || (l_subtrahendLast < l_minuendFirst));
1004    }
1005
1006    /**
1007     * Draws the visual representation of a polygon
1008     *
1009     * @param x_graphics  the graphics device.
1010     * @param x_dataArea  the area within which the data is being drawn.
1011     * @param x_plot  the plot (can be used to obtain standard color
1012     *                information etc).
1013     * @param x_domainAxis  the domain (horizontal) axis.
1014     * @param x_rangeAxis  the range (vertical) axis.
1015     * @param x_positive  indicates if the polygon is positive (true) or
1016     *                    negative (false).
1017     * @param x_xValues  a linked list of the x values (expects values to be
1018     *                   of type Double).
1019     * @param x_yValues  a linked list of the y values (expects values to be
1020     *                   of type Double).
1021     */
1022    private void createPolygon (Graphics2D x_graphics,
1023                                Rectangle2D x_dataArea,
1024                                XYPlot x_plot,
1025                                ValueAxis x_domainAxis,
1026                                ValueAxis x_rangeAxis,
1027                                boolean x_positive,
1028                                LinkedList x_xValues,
1029                                LinkedList x_yValues) {
1030
1031        PlotOrientation l_orientation      = x_plot.getOrientation();
1032        RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge();
1033        RectangleEdge l_rangeAxisLocation  = x_plot.getRangeAxisEdge();
1034
1035        Object[] l_xValues = x_xValues.toArray();
1036        Object[] l_yValues = x_yValues.toArray();
1037
1038        GeneralPath l_path = new GeneralPath();
1039
1040        if (PlotOrientation.VERTICAL == l_orientation) {
1041            double l_x = x_domainAxis.valueToJava2D((
1042                    (Double) l_xValues[0]), x_dataArea,
1043                    l_domainAxisLocation);
1044            if (this.roundXCoordinates) {
1045                l_x = Math.rint(l_x);
1046            }
1047
1048            double l_y = x_rangeAxis.valueToJava2D((
1049                    (Double) l_yValues[0]), x_dataArea,
1050                    l_rangeAxisLocation);
1051
1052            l_path.moveTo((float) l_x, (float) l_y);
1053            for (int i = 1; i < l_xValues.length; i++) {
1054                l_x = x_domainAxis.valueToJava2D((
1055                        (Double) l_xValues[i]), x_dataArea,
1056                        l_domainAxisLocation);
1057                if (this.roundXCoordinates) {
1058                    l_x = Math.rint(l_x);
1059                }
1060
1061                l_y = x_rangeAxis.valueToJava2D((
1062                        (Double) l_yValues[i]), x_dataArea,
1063                        l_rangeAxisLocation);
1064                l_path.lineTo((float) l_x, (float) l_y);
1065            }
1066            l_path.closePath();
1067        }
1068        else {
1069            double l_x = x_domainAxis.valueToJava2D((
1070                    (Double) l_xValues[0]), x_dataArea,
1071                    l_domainAxisLocation);
1072            if (this.roundXCoordinates) {
1073                l_x = Math.rint(l_x);
1074            }
1075
1076            double l_y = x_rangeAxis.valueToJava2D((
1077                    (Double) l_yValues[0]), x_dataArea,
1078                    l_rangeAxisLocation);
1079
1080            l_path.moveTo((float) l_y, (float) l_x);
1081            for (int i = 1; i < l_xValues.length; i++) {
1082                l_x = x_domainAxis.valueToJava2D((
1083                        (Double) l_xValues[i]), x_dataArea,
1084                        l_domainAxisLocation);
1085                if (this.roundXCoordinates) {
1086                    l_x = Math.rint(l_x);
1087                }
1088
1089                l_y = x_rangeAxis.valueToJava2D((
1090                        (Double) l_yValues[i]), x_dataArea,
1091                        l_rangeAxisLocation);
1092                l_path.lineTo((float) l_y, (float) l_x);
1093            }
1094            l_path.closePath();
1095        }
1096
1097        if (l_path.intersects(x_dataArea)) {
1098            x_graphics.setPaint(x_positive ? getPositivePaint()
1099                    : getNegativePaint());
1100            x_graphics.fill(l_path);
1101        }
1102    }
1103
1104    /**
1105     * Returns a default legend item for the specified series.  Subclasses
1106     * should override this method to generate customised items.
1107     *
1108     * @param datasetIndex  the dataset index (zero-based).
1109     * @param series  the series index (zero-based).
1110     *
1111     * @return A legend item for the series.
1112     */
1113    @Override
1114    public LegendItem getLegendItem(int datasetIndex, int series) {
1115        LegendItem result = null;
1116        XYPlot p = getPlot();
1117        if (p != null) {
1118            XYDataset dataset = p.getDataset(datasetIndex);
1119            if (dataset != null) {
1120                if (getItemVisible(series, 0)) {
1121                    String label = getLegendItemLabelGenerator().generateLabel(
1122                            dataset, series);
1123                    String description = label;
1124                    String toolTipText = null;
1125                    if (getLegendItemToolTipGenerator() != null) {
1126                        toolTipText
1127                            = getLegendItemToolTipGenerator().generateLabel(
1128                                    dataset, series);
1129                    }
1130                    String urlText = null;
1131                    if (getLegendItemURLGenerator() != null) {
1132                        urlText = getLegendItemURLGenerator().generateLabel(
1133                                dataset, series);
1134                    }
1135                    Paint paint = lookupSeriesPaint(series);
1136                    Stroke stroke = lookupSeriesStroke(series);
1137                    Shape line = getLegendLine();
1138                    result = new LegendItem(label, description,
1139                            toolTipText, urlText, line, stroke, paint);
1140                    result.setLabelFont(lookupLegendTextFont(series));
1141                    Paint labelPaint = lookupLegendTextPaint(series);
1142                    if (labelPaint != null) {
1143                        result.setLabelPaint(labelPaint);
1144                    }
1145                    result.setDataset(dataset);
1146                    result.setDatasetIndex(datasetIndex);
1147                    result.setSeriesKey(dataset.getSeriesKey(series));
1148                    result.setSeriesIndex(series);
1149                }
1150            }
1151
1152        }
1153
1154        return result;
1155
1156    }
1157
1158    /**
1159     * Tests this renderer for equality with an arbitrary object.
1160     *
1161     * @param obj  the object ({@code null} permitted).
1162     *
1163     * @return A boolean.
1164     */
1165    @Override
1166    public boolean equals(Object obj) {
1167        if (obj == this) {
1168            return true;
1169        }
1170        if (!(obj instanceof XYDifferenceRenderer)) {
1171            return false;
1172        }
1173        if (!super.equals(obj)) {
1174            return false;
1175        }
1176        XYDifferenceRenderer that = (XYDifferenceRenderer) obj;
1177        if (!PaintUtils.equal(this.positivePaint, that.positivePaint)) {
1178            return false;
1179        }
1180        if (!PaintUtils.equal(this.negativePaint, that.negativePaint)) {
1181            return false;
1182        }
1183        if (this.shapesVisible != that.shapesVisible) {
1184            return false;
1185        }
1186        if (!ShapeUtils.equal(this.legendLine, that.legendLine)) {
1187            return false;
1188        }
1189        if (this.roundXCoordinates != that.roundXCoordinates) {
1190            return false;
1191        }
1192        return true;
1193    }
1194
1195    /**
1196     * Returns a clone of the renderer.
1197     *
1198     * @return A clone.
1199     *
1200     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
1201     */
1202    @Override
1203    public Object clone() throws CloneNotSupportedException {
1204        XYDifferenceRenderer clone = (XYDifferenceRenderer) super.clone();
1205        clone.legendLine = ShapeUtils.clone(this.legendLine);
1206        return clone;
1207    }
1208
1209    /**
1210     * Provides serialization support.
1211     *
1212     * @param stream  the output stream.
1213     *
1214     * @throws IOException  if there is an I/O error.
1215     */
1216    private void writeObject(ObjectOutputStream stream) throws IOException {
1217        stream.defaultWriteObject();
1218        SerialUtils.writePaint(this.positivePaint, stream);
1219        SerialUtils.writePaint(this.negativePaint, stream);
1220        SerialUtils.writeShape(this.legendLine, stream);
1221    }
1222
1223    /**
1224     * Provides serialization support.
1225     *
1226     * @param stream  the input stream.
1227     *
1228     * @throws IOException  if there is an I/O error.
1229     * @throws ClassNotFoundException  if there is a classpath problem.
1230     */
1231    private void readObject(ObjectInputStream stream)
1232        throws IOException, ClassNotFoundException {
1233        stream.defaultReadObject();
1234        this.positivePaint = SerialUtils.readPaint(stream);
1235        this.negativePaint = SerialUtils.readPaint(stream);
1236        this.legendLine = SerialUtils.readShape(stream);
1237    }
1238
1239}