XyInterpolatedBlockRenderer.java

  1. package org.opentrafficsim.draw.graphs;

  2. import java.awt.BasicStroke;
  3. import java.awt.Color;
  4. import java.awt.Graphics2D;
  5. import java.awt.Paint;
  6. import java.awt.PaintContext;
  7. import java.awt.Rectangle;
  8. import java.awt.RenderingHints;
  9. import java.awt.geom.AffineTransform;
  10. import java.awt.geom.Rectangle2D;
  11. import java.awt.image.ColorModel;
  12. import java.awt.image.Raster;
  13. import java.awt.image.WritableRaster;

  14. import org.djutils.exceptions.Throw;
  15. import org.jfree.chart.axis.ValueAxis;
  16. import org.jfree.chart.entity.EntityCollection;
  17. import org.jfree.chart.plot.CrosshairState;
  18. import org.jfree.chart.plot.PlotOrientation;
  19. import org.jfree.chart.plot.PlotRenderingInfo;
  20. import org.jfree.chart.plot.XYPlot;
  21. import org.jfree.chart.renderer.PaintScale;
  22. import org.jfree.chart.renderer.xy.XYBlockRenderer;
  23. import org.jfree.chart.renderer.xy.XYItemRendererState;
  24. import org.jfree.chart.ui.RectangleAnchor;
  25. import org.jfree.chart.ui.Size2D;
  26. import org.jfree.data.xy.XYDataset;
  27. import org.opentrafficsim.draw.ColorPaintScale;

  28. /**
  29.  * Renderer for blocks that are filled with bidirectionally interpolated colors. It extends a {@code XYBlockRenderer} and
  30.  * requires a small extension of the underlying dataset ({@code XyInterpolatedDataset}). The interpolation is performed in the
  31.  * {@code drawItem} method. This class imposes two constraints on the functionality of the super class: i) no BlockAnchor may be
  32.  * set as this is tightly related to the interpolation, and ii) only paint scales of type {@code ColorPaintScale} can be used,
  33.  * as the interpolation obtains pixel colors from it.
  34.  * <p>
  35.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  36.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  37.  * </p>
  38.  * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  39.  * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
  40.  * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  41.  */
  42. public class XyInterpolatedBlockRenderer extends XYBlockRenderer
  43. {

  44.     /** */
  45.     private static final long serialVersionUID = 20181008L;

  46.     /** Whether to use the interpolation. */
  47.     private boolean interpolate = true;

  48.     /** Dataset that allows retrieving surrounding value for interpolation. */
  49.     private final XyInterpolatedDataset xyInterpolatedDataset;

  50.     /**
  51.      * @param xyInterpolatedDataset XYInterpolatedDataset; dataset that allows retrieving surrounding value for interpolation
  52.      */
  53.     public XyInterpolatedBlockRenderer(final XyInterpolatedDataset xyInterpolatedDataset)
  54.     {
  55.         this.xyInterpolatedDataset = xyInterpolatedDataset;
  56.     }

  57.     /**
  58.      * {@inheritDoc} throws UnsupportedOperationException if the paint scale is not of type ColorPaintScale
  59.      */
  60.     @Override
  61.     public void setPaintScale(final PaintScale scale)
  62.     {
  63.         Throw.when(!(scale instanceof ColorPaintScale), UnsupportedOperationException.class,
  64.                 "Class XYInterpolatedBlockRenderer requires a ColorPaintScale.");
  65.         super.setPaintScale(scale);
  66.     }

  67.     /**
  68.      * {@inheritDoc} throws UnsupportedOperationException block anchor is governed based on interpolation
  69.      */
  70.     @Override
  71.     public void setBlockAnchor(final RectangleAnchor anchor)
  72.     {
  73.         throw new UnsupportedOperationException(
  74.                 "Class XYInterpolatedBlockRenderer does not support setting the anchor, it's coupled to interpolation.");
  75.     }

  76.     /**
  77.      * Enables interpolation or not. Interpolation occurs between cell centers. Therefore the painted blocks are shifted right
  78.      * and up. The user of this class must provide an additional row and column of data to fill up the gaps. These values may be
  79.      * NaN.
  80.      * @param interpolate boolean; interpolate or not
  81.      */
  82.     public final void setInterpolate(final boolean interpolate)
  83.     {
  84.         this.interpolate = interpolate;
  85.         if (interpolate)
  86.         {
  87.             super.setBlockAnchor(RectangleAnchor.TOP_LEFT); // reversed y axis
  88.         }
  89.         else
  90.         {
  91.             super.setBlockAnchor(RectangleAnchor.CENTER);
  92.         }
  93.     }

  94.     /**
  95.      * {@inheritDoc} This code is partially based on the parent implementation.
  96.      */
  97.     @Override
  98.     @SuppressWarnings("parameternumber")
  99.     public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea,
  100.             final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis,
  101.             final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState, final int pass)
  102.     {

  103.         double z00 = this.xyInterpolatedDataset.getZValue(series, item);
  104.         Paint p;

  105.         if (!this.interpolate)
  106.         {
  107.             // regular non interpolated case
  108.             p = getPaintScale().getPaint(z00);
  109.         }
  110.         else
  111.         {
  112.             // obtain data values in surrounding cells (up, right, and up-right)
  113.             double z10 = getAdjacentZ(series, item, true, false);
  114.             double z01 = getAdjacentZ(series, item, false, true);
  115.             double z11 = getAdjacentZ(series, item, true, true);

  116.             // fix NaN values
  117.             double z00f = fixNaN(z00, z01, z10, z11);
  118.             double z10f = fixNaN(z10, z00, z11, z01);
  119.             double z01f = fixNaN(z01, z00, z11, z10);
  120.             double z11f = fixNaN(z11, z10, z01, z00);

  121.             // use these values to derive an interpolated color raster
  122.             p = new Paint()
  123.             {
  124.                 /** {@inheritDoc} */
  125.                 @Override
  126.                 public int getTransparency()
  127.                 {
  128.                     return TRANSLUCENT;
  129.                 }

  130.                 /** {@inheritDoc} */
  131.                 @Override
  132.                 public PaintContext createContext(final ColorModel cm, final Rectangle deviceBounds,
  133.                         final Rectangle2D userBounds, final AffineTransform xform, final RenderingHints hints)
  134.                 {
  135.                     return new PaintContext()
  136.                     {
  137.                         /** {@inheritDoc} */
  138.                         @Override
  139.                         public void dispose()
  140.                         {
  141.                             //
  142.                         }

  143.                         /** {@inheritDoc} */
  144.                         @Override
  145.                         public ColorModel getColorModel()
  146.                         {
  147.                             return ColorModel.getRGBdefault();
  148.                         }

  149.                         /** {@inheritDoc} */
  150.                         @Override
  151.                         public Raster getRaster(final int x, final int y, final int w, final int h)
  152.                         {
  153.                             // a raster can be obtained for any square subset of 1 cell, obtain the offset
  154.                             double wOffset = x - deviceBounds.getX();
  155.                             double hOffset = y - deviceBounds.getY();

  156.                             // initialize a writable raster
  157.                             WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h);

  158.                             // loop pixels in data buffer (raster.setPixel(i, j, float[]) doesn't work...)
  159.                             for (int k = 0; k < raster.getDataBuffer().getSize(); k++)
  160.                             {
  161.                                 // coordinate (i, j) is where pixel k is within the bounds
  162.                                 double i = hOffset + k / w;
  163.                                 double j = wOffset + k % w;

  164.                                 // get weights relative to the edges
  165.                                 double bot = i / deviceBounds.getHeight();
  166.                                 double top = 1.0 - bot;
  167.                                 double rig = j / deviceBounds.getWidth();
  168.                                 double lef = 1.0 - rig;

  169.                                 // bilinear interpolation of the value
  170.                                 double z = z00f * lef * bot + z10f * top * lef + z01f * bot * rig + z11f * top * rig;

  171.                                 // with the interpolated value, obtain a color the simple way
  172.                                 Color c = (Color) getPaintScale().getPaint(z); // paint scale forced of type ColorPaintScale

  173.                                 // write
  174.                                 raster.getDataBuffer().setElem(k, c.getRGB());
  175.                             }
  176.                             return raster;
  177.                         }
  178.                     };
  179.                 }
  180.             };

  181.         }

  182.         // use rect to obtain x and y range, accounting for offset (direct information is private in super class)
  183.         double x = dataset.getXValue(series, item);
  184.         double y = dataset.getYValue(series, item);
  185.         Rectangle2D rect =
  186.                 RectangleAnchor.createRectangle(new Size2D(getBlockWidth(), getBlockHeight()), x, y, getBlockAnchor());
  187.         double xx0 = domainAxis.valueToJava2D(rect.getMinX(), dataArea, plot.getDomainAxisEdge());
  188.         double yy0 = rangeAxis.valueToJava2D(rect.getMinY(), dataArea, plot.getRangeAxisEdge());
  189.         double xx1 = domainAxis.valueToJava2D(rect.getMaxX(), dataArea, plot.getDomainAxisEdge());
  190.         double yy1 = rangeAxis.valueToJava2D(rect.getMaxY(), dataArea, plot.getRangeAxisEdge());

  191.         // code below this is equal to the super implementation
  192.         Rectangle2D block;
  193.         PlotOrientation orientation = plot.getOrientation();
  194.         if (orientation.equals(PlotOrientation.HORIZONTAL))
  195.         {
  196.             block = new Rectangle2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0), Math.abs(xx0 - xx1));
  197.         }
  198.         else
  199.         {
  200.             block = new Rectangle2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0), Math.abs(yy1 - yy0));
  201.         }
  202.         g2.setPaint(p);
  203.         g2.fill(block);
  204.         g2.setStroke(new BasicStroke(1.0f));
  205.         g2.draw(block);

  206.         if (isItemLabelVisible(series, item))
  207.         {
  208.             drawItemLabel(g2, orientation, dataset, series, item, block.getCenterX(), block.getCenterY(), y < 0.0);
  209.         }

  210.         int datasetIndex = plot.indexOf(dataset);
  211.         double transX = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge());
  212.         double transY = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge());
  213.         updateCrosshairValues(crosshairState, x, y, datasetIndex, transX, transY, orientation);

  214.         EntityCollection entities = state.getEntityCollection();
  215.         if (entities != null)
  216.         {
  217.             addEntity(entities, block, dataset, series, item, block.getCenterX(), block.getCenterY());
  218.         }
  219.     }

  220.     /**
  221.      * Returns the value of an adjacent cell.
  222.      * @param series int; the series index
  223.      * @param item int; item
  224.      * @param up boolean; whether to get the upper cell (can be combined with right)
  225.      * @param right boolean; whether to get the right cell (can be combined with up)
  226.      * @return double; value in adjacent cell, or {@code Double.NaN} if no such cell.
  227.      */
  228.     private double getAdjacentZ(final int series, final int item, final boolean up, final boolean right)
  229.     {
  230.         if (up && (item + 1) % this.xyInterpolatedDataset.getRangeBinCount() == 0)
  231.         {
  232.             // we cannot interpolate beyond the range extent
  233.             return Double.NaN;
  234.         }
  235.         int adjacentItem = item + (up ? 1 : 0) + (right ? this.xyInterpolatedDataset.getRangeBinCount() : 0);
  236.         if (adjacentItem >= this.xyInterpolatedDataset.getItemCount(series))
  237.         {
  238.             // we cannot interpolate beyond the domain extent
  239.             return Double.NaN;
  240.         }
  241.         return this.xyInterpolatedDataset.getZValue(series, adjacentItem);
  242.     }

  243.     /**
  244.      * Restores a corner value if it's NaN using surrounding values. If both adjacent corner points are not NaN, the mean of
  245.      * those is used. If either is not NaN, that value is used. Otherwise the opposite corner point is used (which may be NaN).
  246.      * This method's main purpose is to fill the left side of the first column of cells and the bottom of the first row of cells
  247.      * in case of interpolation. Coincidentally it can also fill small data gaps visually.
  248.      * @param value double; value to fix (if needed)
  249.      * @param adjacentCorner1 double; adjacent corner value
  250.      * @param adjacentCorner2 double; other adjacent corner value
  251.      * @param oppositeCorner double; opposite corner value
  252.      * @return double; fixed value (if possible, i.e. not all corners are NaN)
  253.      */
  254.     private double fixNaN(final double value, final double adjacentCorner1, final double adjacentCorner2,
  255.             final double oppositeCorner)
  256.     {
  257.         if (!Double.isNaN(value))
  258.         {
  259.             return value;
  260.         }
  261.         if (Double.isNaN(adjacentCorner1))
  262.         {
  263.             if (Double.isNaN(adjacentCorner2))
  264.             {
  265.                 return oppositeCorner;
  266.             }
  267.             else
  268.             {
  269.                 return adjacentCorner2;
  270.             }
  271.         }
  272.         else if (Double.isNaN(adjacentCorner2))
  273.         {
  274.             return adjacentCorner1;
  275.         }
  276.         return 0.5 * (adjacentCorner1 + adjacentCorner2);
  277.     }

  278.     /** {@inheritDoc} */
  279.     @Override
  280.     public String toString()
  281.     {
  282.         return "XYInterpolatedBlockRenderer [interpolate=" + this.interpolate + ", xyInterpolatedDataset="
  283.                 + this.xyInterpolatedDataset + "]";
  284.     }

  285. }