001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer.gpx;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.AlphaComposite;
008import java.awt.BasicStroke;
009import java.awt.Color;
010import java.awt.Composite;
011import java.awt.Graphics2D;
012import java.awt.LinearGradientPaint;
013import java.awt.MultipleGradientPaint;
014import java.awt.Paint;
015import java.awt.Point;
016import java.awt.Rectangle;
017import java.awt.RenderingHints;
018import java.awt.Stroke;
019import java.awt.image.BufferedImage;
020import java.awt.image.DataBufferInt;
021import java.awt.image.Raster;
022import java.io.BufferedReader;
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.Arrays;
026import java.util.Collections;
027import java.util.Date;
028import java.util.LinkedList;
029import java.util.List;
030import java.util.Random;
031
032import javax.swing.ImageIcon;
033
034import org.openstreetmap.josm.data.Bounds;
035import org.openstreetmap.josm.data.PreferencesUtils;
036import org.openstreetmap.josm.data.SystemOfMeasurement;
037import org.openstreetmap.josm.data.SystemOfMeasurement.SoMChangeListener;
038import org.openstreetmap.josm.data.coor.LatLon;
039import org.openstreetmap.josm.data.gpx.GpxConstants;
040import org.openstreetmap.josm.data.gpx.GpxData;
041import org.openstreetmap.josm.data.gpx.GpxData.GpxDataChangeEvent;
042import org.openstreetmap.josm.data.gpx.GpxData.GpxDataChangeListener;
043import org.openstreetmap.josm.data.gpx.Line;
044import org.openstreetmap.josm.data.gpx.WayPoint;
045import org.openstreetmap.josm.data.preferences.NamedColorProperty;
046import org.openstreetmap.josm.gui.MapView;
047import org.openstreetmap.josm.gui.MapViewState;
048import org.openstreetmap.josm.gui.layer.GpxLayer;
049import org.openstreetmap.josm.gui.layer.MapViewGraphics;
050import org.openstreetmap.josm.gui.layer.MapViewPaintable;
051import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent;
052import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent;
053import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener;
054import org.openstreetmap.josm.io.CachedFile;
055import org.openstreetmap.josm.spi.preferences.Config;
056import org.openstreetmap.josm.tools.ColorScale;
057import org.openstreetmap.josm.tools.JosmRuntimeException;
058import org.openstreetmap.josm.tools.Logging;
059import org.openstreetmap.josm.tools.Utils;
060
061/**
062 * Class that helps to draw large set of GPS tracks with different colors and options
063 * @since 7319
064 */
065public class GpxDrawHelper implements SoMChangeListener, MapViewPaintable.LayerPainter, PaintableInvalidationListener, GpxDataChangeListener {
066
067    /**
068     * The color that is used for drawing GPX points.
069     * @since 10824
070     */
071    public static final NamedColorProperty DEFAULT_COLOR = new NamedColorProperty(marktr("gps point"), Color.magenta);
072
073    private final GpxData data;
074    private final GpxLayer layer;
075
076    // draw lines between points belonging to different segments
077    private boolean forceLines;
078    // use alpha blending for line draw
079    private boolean alphaLines;
080    // draw direction arrows on the lines
081    private boolean direction;
082    /** width of line for paint **/
083    private int lineWidth;
084    /** don't draw lines if longer than x meters **/
085    private int maxLineLength;
086    // draw lines
087    private boolean lines;
088    /** paint large dots for points **/
089    private boolean large;
090    private int largesize;
091    private boolean hdopCircle;
092    /** paint direction arrow with alternate math. may be faster **/
093    private boolean alternateDirection;
094    /** don't draw arrows nearer to each other than this **/
095    private int delta;
096    private double minTrackDurationForTimeColoring;
097
098    /** maximum value of displayed HDOP, minimum is 0 */
099    private int hdoprange;
100
101    private static final double PHI = Utils.toRadians(15);
102
103    //// Variables used only to check cache validity
104    private boolean computeCacheInSync;
105    private int computeCacheMaxLineLengthUsed;
106    private Color computeCacheColorUsed;
107    private boolean computeCacheColorDynamic;
108    private ColorMode computeCacheColored;
109    private int computeCacheColorTracksTune;
110    private int computeCacheHeatMapDrawColorTableIdx;
111    private boolean computeCacheHeatMapDrawPointMode;
112    private int computeCacheHeatMapDrawGain;
113    private int computeCacheHeatMapDrawLowerLimit;
114
115    //// Color-related fields
116    /** Mode of the line coloring **/
117    private ColorMode colored;
118    /** max speed for coloring - allows to tweak line coloring for different speed levels. **/
119    private int colorTracksTune;
120    private boolean colorModeDynamic;
121    private Color neutralColor;
122    private int largePointAlpha;
123
124    // default access is used to allow changing from plugins
125    private ColorScale velocityScale;
126    /** Colors (without custom alpha channel, if given) for HDOP painting. **/
127    private ColorScale hdopScale;
128    private ColorScale dateScale;
129    private ColorScale directionScale;
130
131    /** Opacity for hdop points **/
132    private int hdopAlpha;
133
134    // lookup array to draw arrows without doing any math
135    private static final int ll0 = 9;
136    private static final int sl4 = 5;
137    private static final int sl9 = 3;
138    private static final int[][] dir = {
139        {+sl4, +ll0, +ll0, +sl4}, {-sl9, +ll0, +sl9, +ll0},
140        {-ll0, +sl4, -sl4, +ll0}, {-ll0, -sl9, -ll0, +sl9},
141        {-sl4, -ll0, -ll0, -sl4}, {+sl9, -ll0, -sl9, -ll0},
142        {+ll0, -sl4, +sl4, -ll0}, {+ll0, +sl9, +ll0, -sl9}
143    };
144
145    /** heat map parameters **/
146
147    // enabled or not (override by settings)
148    private boolean heatMapEnabled;
149    // draw small extra line
150    private boolean heatMapDrawExtraLine;
151    // used index for color table (parameter)
152    private int heatMapDrawColorTableIdx;
153    // use point or line draw mode
154    private boolean heatMapDrawPointMode;
155    // extra gain > 0 or < 0 attenuation, 0 = default
156    private int heatMapDrawGain;
157    // do not draw elements with value lower than this limit
158    private int heatMapDrawLowerLimit;
159
160    // normal buffered image and draw object (cached)
161    private BufferedImage heatMapImgGray;
162    private Graphics2D heatMapGraph2d;
163
164    // some cached values
165    Rectangle heatMapCacheScreenBounds = new Rectangle();
166    MapViewState heatMapMapViewState;
167    int heatMapCacheLineWith;
168
169    // copied value for line drawing
170    private final List<Integer> heatMapPolyX = new ArrayList<>();
171    private final List<Integer> heatMapPolyY = new ArrayList<>();
172
173    // setup color maps used by heat map
174    private static Color[] heatMapLutColorJosmInferno = createColorFromResource("inferno");
175    private static Color[] heatMapLutColorJosmViridis = createColorFromResource("viridis");
176    private static Color[] heatMapLutColorJosmBrown2Green = createColorFromResource("brown2green");
177    private static Color[] heatMapLutColorJosmRed2Blue = createColorFromResource("red2blue");
178
179    // user defined heatmap color
180    private Color[] heatMapLutColor = createColorLut(0, Color.BLACK, Color.WHITE);
181
182    // The heat map was invalidated since the last draw.
183    private boolean gpxLayerInvalidated;
184
185    private void setupColors() {
186        hdopAlpha = Config.getPref().getInt("hdop.color.alpha", -1);
187        velocityScale = ColorScale.createHSBScale(256);
188        /** Colors (without custom alpha channel, if given) for HDOP painting. **/
189        hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP"));
190        dateScale = ColorScale.createHSBScale(256).addTitle(tr("Time"));
191        directionScale = ColorScale.createCyclicScale(256).setIntervalCount(4).addTitle(tr("Direction"));
192
193        systemOfMeasurementChanged(null, null);
194    }
195
196    @Override
197    public void systemOfMeasurementChanged(String oldSoM, String newSoM) {
198        SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
199        velocityScale.addTitle(tr("Velocity, {0}", som.speedName));
200        layer.invalidate();
201    }
202
203    /**
204     * Different color modes
205     */
206    public enum ColorMode {
207        /**
208         * No special colors
209         */
210        NONE,
211        /**
212         * Color by velocity
213         */
214        VELOCITY,
215        /**
216         * Color by accuracy
217         */
218        HDOP,
219        /**
220         * Color by traveling direction
221         */
222        DIRECTION,
223        /**
224         * Color by time
225         */
226        TIME,
227        /**
228         * Color using a heatmap instead of normal lines
229         */
230        HEATMAP;
231
232        static ColorMode fromIndex(final int index) {
233            return values()[index];
234        }
235
236        int toIndex() {
237            return Arrays.asList(values()).indexOf(this);
238        }
239    }
240
241    /**
242     * Constructs a new {@code GpxDrawHelper}.
243     * @param gpxLayer The layer to draw
244     * @since 12157
245     */
246    public GpxDrawHelper(GpxLayer gpxLayer) {
247        layer = gpxLayer;
248        data = gpxLayer.data;
249        data.addChangeListener(this);
250
251        layer.addInvalidationListener(this);
252        SystemOfMeasurement.addSoMChangeListener(this);
253        setupColors();
254    }
255
256    private static String specName(String layerName) {
257        return "layer " + layerName;
258    }
259
260    /**
261     * Get the default color for gps tracks for specified layer
262     * @param layerName name of the GpxLayer
263     * @param ignoreCustom do not use preferences
264     * @return the color or null if the color is not constant
265     */
266    public Color getColor(String layerName, boolean ignoreCustom) {
267        if (ignoreCustom || getColorMode(layerName) == ColorMode.NONE) {
268            return DEFAULT_COLOR.getChildColor(
269                    NamedColorProperty.COLOR_CATEGORY_LAYER,
270                    layerName,
271                    DEFAULT_COLOR.getName()).get();
272        } else {
273            return null;
274        }
275    }
276
277    /**
278     * Read coloring mode for specified layer from preferences
279     * @param layerName name of the GpxLayer
280     * @return coloring mode
281     */
282    public ColorMode getColorMode(String layerName) {
283        try {
284            int i = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.colors", specName(layerName), 0);
285            return ColorMode.fromIndex(i);
286        } catch (IndexOutOfBoundsException e) {
287            Logging.warn(e);
288        }
289        return ColorMode.NONE;
290    }
291
292    /** Reads generic color from preferences (usually gray)
293     * @return the color
294     **/
295    public static Color getGenericColor() {
296        return DEFAULT_COLOR.get();
297    }
298
299    /**
300     * Read all drawing-related settings from preferences
301     * @param layerName layer name used to access its specific preferences
302     **/
303    public void readPreferences(String layerName) {
304        String spec = specName(layerName);
305        forceLines = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.lines.force", spec, false);
306        direction = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.direction", spec, false);
307        lineWidth = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.linewidth", spec, 0);
308        alphaLines = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.lines.alpha-blend", spec, false);
309
310        if (!data.fromServer) {
311            maxLineLength = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.max-line-length.local", spec, -1);
312            lines = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.lines.local", spec, true);
313        } else {
314            maxLineLength = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.max-line-length", spec, 200);
315            lines = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.lines", spec, true);
316        }
317        large = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.large", spec, false);
318        largesize = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.large.size", spec, 3);
319        hdopCircle = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.hdopcircle", spec, false);
320        colored = getColorMode(layerName);
321        alternateDirection = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.alternatedirection", spec, false);
322        delta = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.min-arrow-distance", spec, 40);
323        colorTracksTune = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.colorTracksTune", spec, 45);
324        colorModeDynamic = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.colors.dynamic", spec, false);
325        /* good HDOP's are between 1 and 3, very bad HDOP's go into 3 digit values */
326        hdoprange = Config.getPref().getInt("hdop.range", 7);
327        minTrackDurationForTimeColoring = Config.getPref().getInt("draw.rawgps.date-coloring-min-dt", 60);
328        largePointAlpha = Config.getPref().getInt("draw.rawgps.large.alpha", -1) & 0xFF;
329
330        // get heatmap parameters
331        heatMapEnabled = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.heatmap.enabled", spec, false);
332        heatMapDrawExtraLine = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.heatmap.line-extra", spec, false);
333        heatMapDrawColorTableIdx = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.heatmap.colormap", spec, 0);
334        heatMapDrawPointMode = PreferencesUtils.getBoolean(Config.getPref(), "draw.rawgps.heatmap.use-points", spec, false);
335        heatMapDrawGain = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.heatmap.gain", spec, 0);
336        heatMapDrawLowerLimit = PreferencesUtils.getInteger(Config.getPref(), "draw.rawgps.heatmap.lower-limit", spec, 0);
337
338        // shrink to range
339        heatMapDrawGain = Utils.clamp(heatMapDrawGain, -10, 10);
340
341        neutralColor = getColor(layerName, true);
342        velocityScale.setNoDataColor(neutralColor);
343        dateScale.setNoDataColor(neutralColor);
344        hdopScale.setNoDataColor(neutralColor);
345        directionScale.setNoDataColor(neutralColor);
346
347        largesize += lineWidth;
348    }
349
350    @Override
351    public void paint(MapViewGraphics graphics) {
352        Bounds clipBounds = graphics.getClipBounds().getLatLonBoundsBox();
353        List<WayPoint> visibleSegments = listVisibleSegments(clipBounds);
354        if (!visibleSegments.isEmpty()) {
355            readPreferences(layer.getName());
356            drawAll(graphics.getDefaultGraphics(), graphics.getMapView(), visibleSegments, clipBounds);
357            if (graphics.getMapView().getLayerManager().getActiveLayer() == layer) {
358                drawColorBar(graphics.getDefaultGraphics(), graphics.getMapView());
359            }
360        }
361    }
362
363    private List<WayPoint> listVisibleSegments(Bounds box) {
364        WayPoint last = null;
365        LinkedList<WayPoint> visibleSegments = new LinkedList<>();
366
367        ensureTrackVisibilityLength();
368        for (Line segment : data.getLinesIterable(layer.trackVisibility)) {
369
370            for (WayPoint pt : segment) {
371                Bounds b = new Bounds(pt.getCoor());
372                if (pt.drawLine && last != null) {
373                    b.extend(last.getCoor());
374                }
375                if (b.intersects(box)) {
376                    if (last != null && (visibleSegments.isEmpty()
377                            || visibleSegments.getLast() != last)) {
378                        if (last.drawLine) {
379                            WayPoint l = new WayPoint(last);
380                            l.drawLine = false;
381                            visibleSegments.add(l);
382                        } else {
383                            visibleSegments.add(last);
384                        }
385                    }
386                    visibleSegments.add(pt);
387                }
388                last = pt;
389            }
390        }
391        return visibleSegments;
392    }
393
394    /** ensures the trackVisibility array has the correct length without losing data.
395     * TODO: Make this nicer by syncing the trackVisibility automatically.
396     * additional entries are initialized to true;
397     */
398    private void ensureTrackVisibilityLength() {
399        final int l = data.getTracks().size();
400        if (l == layer.trackVisibility.length)
401            return;
402        final int m = Math.min(l, layer.trackVisibility.length);
403        layer.trackVisibility = Arrays.copyOf(layer.trackVisibility, l);
404        for (int i = m; i < l; i++) {
405            layer.trackVisibility[i] = true;
406        }
407    }
408
409    /**
410     * Draw all enabled GPX elements of layer.
411     * @param g               the common draw object to use
412     * @param mv              the meta data to current displayed area
413     * @param visibleSegments segments visible in the current scope of mv
414     * @param clipBounds      the clipping rectangle for the current view
415     * @since 14748 : new parameter clipBounds
416     */
417
418    public void drawAll(Graphics2D g, MapView mv, List<WayPoint> visibleSegments, Bounds clipBounds) {
419
420        final long timeStart = System.currentTimeMillis();
421
422        checkCache();
423
424        // STEP 2b - RE-COMPUTE CACHE DATA *********************
425        if (!computeCacheInSync) { // don't compute if the cache is good
426            calculateColors();
427            // update the WaiPoint.drawline attributes
428            visibleSegments.clear();
429            visibleSegments.addAll(listVisibleSegments(clipBounds));
430        }
431
432        fixColors(visibleSegments);
433
434        // backup the environment
435        Composite oldComposite = g.getComposite();
436        Stroke oldStroke = g.getStroke();
437        Paint oldPaint = g.getPaint();
438
439        // set hints for the render
440        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
441            Config.getPref().getBoolean("mappaint.gpx.use-antialiasing", false) ?
442                    RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
443
444        if (lineWidth != 0) {
445            g.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
446        }
447
448        // global enabled or select via color
449        boolean useHeatMap = heatMapEnabled || ColorMode.HEATMAP == colored;
450
451        // default global alpha level
452        float layerAlpha = 1.00f;
453
454        // extract current alpha blending value
455        if (oldComposite instanceof AlphaComposite) {
456            layerAlpha = ((AlphaComposite) oldComposite).getAlpha();
457        }
458
459        // use heatmap background layer
460        if (useHeatMap) {
461            drawHeatMap(g, mv, visibleSegments);
462        } else {
463            // use normal line style or alpha-blending lines
464            if (!alphaLines) {
465                drawLines(g, mv, visibleSegments);
466            } else {
467                drawLinesAlpha(g, mv, visibleSegments, layerAlpha);
468            }
469        }
470
471        // override global alpha settings (smooth overlay)
472        if (alphaLines || useHeatMap) {
473            g.setComposite(AlphaComposite.SrcOver.derive(0.25f * layerAlpha));
474        }
475
476        // normal overlays
477        drawArrows(g, mv, visibleSegments);
478        drawPoints(g, mv, visibleSegments);
479
480        // restore environment
481        g.setPaint(oldPaint);
482        g.setStroke(oldStroke);
483        g.setComposite(oldComposite);
484
485        // show some debug info
486        if (Logging.isDebugEnabled() && !visibleSegments.isEmpty()) {
487            final long timeDiff = System.currentTimeMillis() - timeStart;
488
489            Logging.debug("gpxdraw::draw takes " +
490                         Utils.getDurationString(timeDiff) +
491                         "(" +
492                         "segments= " + visibleSegments.size() +
493                         ", per 10000 = " + Utils.getDurationString(10_000 * timeDiff / visibleSegments.size()) +
494                         ")"
495              );
496        }
497    }
498
499    /**
500     *  Calculate colors of way segments based on latest configuration settings
501     */
502    public void calculateColors() {
503        double minval = +1e10;
504        double maxval = -1e10;
505        WayPoint oldWp = null;
506
507        if (colorModeDynamic) {
508            if (colored == ColorMode.VELOCITY) {
509                final List<Double> velocities = new ArrayList<>();
510                for (Line segment : data.getLinesIterable(null)) {
511                    if (!forceLines) {
512                        oldWp = null;
513                    }
514                    for (WayPoint trkPnt : segment) {
515                        if (!trkPnt.isLatLonKnown()) {
516                            continue;
517                        }
518                        if (oldWp != null && trkPnt.getTimeInMillis() > oldWp.getTimeInMillis()) {
519                            double vel = trkPnt.getCoor().greatCircleDistance(oldWp.getCoor())
520                                    / (trkPnt.getTime() - oldWp.getTime());
521                            velocities.add(vel);
522                        }
523                        oldWp = trkPnt;
524                    }
525                }
526                Collections.sort(velocities);
527                if (velocities.isEmpty()) {
528                    velocityScale.setRange(0, 120/3.6);
529                } else {
530                    minval = velocities.get(velocities.size() / 20); // 5% percentile to remove outliers
531                    maxval = velocities.get(velocities.size() * 19 / 20); // 95% percentile to remove outliers
532                    velocityScale.setRange(minval, maxval);
533                }
534            } else if (colored == ColorMode.HDOP) {
535                for (Line segment : data.getLinesIterable(null)) {
536                    for (WayPoint trkPnt : segment) {
537                        Object val = trkPnt.get(GpxConstants.PT_HDOP);
538                        if (val != null) {
539                            double hdop = ((Float) val).doubleValue();
540                            if (hdop > maxval) {
541                                maxval = hdop;
542                            }
543                            if (hdop < minval) {
544                                minval = hdop;
545                            }
546                        }
547                    }
548                }
549                if (minval >= maxval) {
550                    hdopScale.setRange(0, 100);
551                } else {
552                    hdopScale.setRange(minval, maxval);
553                }
554            }
555            oldWp = null;
556        } else { // color mode not dynamic
557            velocityScale.setRange(0, colorTracksTune);
558            hdopScale.setRange(0, hdoprange);
559        }
560        double now = System.currentTimeMillis()/1000.0;
561        if (colored == ColorMode.TIME) {
562            Date[] bounds = data.getMinMaxTimeForAllTracks();
563            if (bounds.length >= 2) {
564                minval = bounds[0].getTime()/1000.0;
565                maxval = bounds[1].getTime()/1000.0;
566            } else {
567                minval = 0;
568                maxval = now;
569            }
570            dateScale.setRange(minval, maxval);
571        }
572
573        // Now the colors for all the points will be assigned
574        for (Line segment : data.getLinesIterable(null)) {
575            if (!forceLines) { // don't draw lines between segments, unless forced to
576                oldWp = null;
577            }
578            for (WayPoint trkPnt : segment) {
579                LatLon c = trkPnt.getCoor();
580                trkPnt.customColoring = neutralColor;
581                if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
582                    continue;
583                }
584                // now we are sure some color will be assigned
585                Color color = null;
586
587                if (colored == ColorMode.HDOP) {
588                    Float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
589                    color = hdopScale.getColor(hdop);
590                }
591                if (oldWp != null) { // other coloring modes need segment for calcuation
592                    double dist = c.greatCircleDistance(oldWp.getCoor());
593                    boolean noDraw = false;
594                    switch (colored) {
595                    case VELOCITY:
596                        double dtime = trkPnt.getTime() - oldWp.getTime();
597                        if (dtime > 0) {
598                            color = velocityScale.getColor(dist / dtime);
599                        } else {
600                            color = velocityScale.getNoDataColor();
601                        }
602                        break;
603                    case DIRECTION:
604                        double dirColor = oldWp.getCoor().bearing(trkPnt.getCoor());
605                        color = directionScale.getColor(dirColor);
606                        break;
607                    case TIME:
608                        double t = trkPnt.getTime();
609                        // skip bad timestamps and very short tracks
610                        if (t > 0 && t <= now && maxval - minval > minTrackDurationForTimeColoring) {
611                            color = dateScale.getColor(t);
612                        } else {
613                            color = dateScale.getNoDataColor();
614                        }
615                        break;
616                    default: // Do nothing
617                    }
618                    if (!noDraw && !segment.isUnordered() && (maxLineLength == -1 || dist <= maxLineLength)) {
619                        trkPnt.drawLine = true;
620                        double bearing = oldWp.getCoor().bearing(trkPnt.getCoor());
621                        trkPnt.dir = ((int) (bearing / Math.PI * 4 + 1.5)) % 8;
622                    } else {
623                        trkPnt.drawLine = false;
624                    }
625                } else { // make sure we reset outdated data
626                    trkPnt.drawLine = false;
627                    color = neutralColor;
628                }
629                if (color != null) {
630                    trkPnt.customColoring = color;
631                }
632                oldWp = trkPnt;
633            }
634        }
635
636        // heat mode
637        if (ColorMode.HEATMAP == colored) {
638
639            // get new user color map and refresh visibility level
640            heatMapLutColor = createColorLut(heatMapDrawLowerLimit,
641                                             selectColorMap(neutralColor != null ? neutralColor : Color.WHITE, heatMapDrawColorTableIdx));
642
643            // force redraw of image
644            heatMapMapViewState = null;
645        }
646
647        computeCacheInSync = true;
648    }
649
650    /**
651     * Draw all GPX ways segments
652     * @param g               the common draw object to use
653     * @param mv              the meta data to current displayed area
654     * @param visibleSegments segments visible in the current scope of mv
655     */
656    private void drawLines(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
657        if (lines) {
658            Point old = null;
659            for (WayPoint trkPnt : visibleSegments) {
660                if (!trkPnt.isLatLonKnown()) {
661                    old = null;
662                    continue;
663                }
664                Point screen = mv.getPoint(trkPnt);
665                // skip points that are on the same screenposition
666                if (trkPnt.drawLine && old != null && ((old.x != screen.x) || (old.y != screen.y))) {
667                    g.setColor(trkPnt.customColoring);
668                    g.drawLine(old.x, old.y, screen.x, screen.y);
669                }
670                old = screen;
671            }
672        }
673    }
674
675    /**
676     * Draw all GPX arrays
677     * @param g               the common draw object to use
678     * @param mv              the meta data to current displayed area
679     * @param visibleSegments segments visible in the current scope of mv
680     */
681    private void drawArrows(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
682        /****************************************************************
683         ********** STEP 3b - DRAW NICE ARROWS **************************
684         ****************************************************************/
685        if (lines && direction && !alternateDirection) {
686            Point old = null;
687            Point oldA = null; // last arrow painted
688            for (WayPoint trkPnt : visibleSegments) {
689                if (!trkPnt.isLatLonKnown()) {
690                    old = null;
691                    continue;
692                }
693                if (trkPnt.drawLine) {
694                    Point screen = mv.getPoint(trkPnt);
695                    // skip points that are on the same screenposition
696                    if (old != null
697                            && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
698                            || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
699                        g.setColor(trkPnt.customColoring);
700                        double t = Math.atan2((double) screen.y - old.y, (double) screen.x - old.x) + Math.PI;
701                        g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t - PHI)),
702                                (int) (screen.y + 10 * Math.sin(t - PHI)));
703                        g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t + PHI)),
704                                (int) (screen.y + 10 * Math.sin(t + PHI)));
705                        oldA = screen;
706                    }
707                    old = screen;
708                }
709            } // end for trkpnt
710        }
711
712        /****************************************************************
713         ********** STEP 3c - DRAW FAST ARROWS **************************
714         ****************************************************************/
715        if (lines && direction && alternateDirection) {
716            Point old = null;
717            Point oldA = null; // last arrow painted
718            for (WayPoint trkPnt : visibleSegments) {
719                LatLon c = trkPnt.getCoor();
720                if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
721                    continue;
722                }
723                if (trkPnt.drawLine) {
724                    Point screen = mv.getPoint(trkPnt);
725                    // skip points that are on the same screenposition
726                    if (old != null
727                            && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
728                            || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
729                        g.setColor(trkPnt.customColoring);
730                        g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][0], screen.y
731                                + dir[trkPnt.dir][1]);
732                        g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][2], screen.y
733                                + dir[trkPnt.dir][3]);
734                        oldA = screen;
735                    }
736                    old = screen;
737                }
738            } // end for trkpnt
739        }
740    }
741
742    /**
743     * Draw all GPX points
744     * @param g               the common draw object to use
745     * @param mv              the meta data to current displayed area
746     * @param visibleSegments segments visible in the current scope of mv
747     */
748    private void drawPoints(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
749        /****************************************************************
750         ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE *********
751         ****************************************************************/
752        if (large || hdopCircle) {
753            final int halfSize = largesize/2;
754            for (WayPoint trkPnt : visibleSegments) {
755                LatLon c = trkPnt.getCoor();
756                if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
757                    continue;
758                }
759                Point screen = mv.getPoint(trkPnt);
760
761                if (hdopCircle && trkPnt.get(GpxConstants.PT_HDOP) != null) {
762                    // hdop value
763                    float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
764                    if (hdop < 0) {
765                        hdop = 0;
766                    }
767                    Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring :
768                        new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true);
769                    g.setColor(customColoringTransparent);
770                    // hdop circles
771                    int hdopp = mv.getPoint(new LatLon(
772                            trkPnt.getCoor().lat(),
773                            trkPnt.getCoor().lon() + 2d*6*hdop*360/40000000d)).x - screen.x;
774                    g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
775                }
776                if (large) {
777                    // color the large GPS points like the gps lines
778                    if (trkPnt.customColoring != null) {
779                        Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring :
780                            new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true);
781
782                        g.setColor(customColoringTransparent);
783                    }
784                    g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
785                }
786            } // end for trkpnt
787        } // end if large || hdopcircle
788
789        /****************************************************************
790         ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
791         ****************************************************************/
792        if (!large && lines) {
793            g.setColor(neutralColor);
794            for (WayPoint trkPnt : visibleSegments) {
795                LatLon c = trkPnt.getCoor();
796                if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
797                    continue;
798                }
799                if (!trkPnt.drawLine) {
800                    Point screen = mv.getPoint(trkPnt);
801                    g.drawRect(screen.x, screen.y, 0, 0);
802                }
803            } // end for trkpnt
804        } // end if large
805
806        /****************************************************************
807         ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
808         ****************************************************************/
809        if (!large && !lines) {
810            g.setColor(neutralColor);
811            for (WayPoint trkPnt : visibleSegments) {
812                LatLon c = trkPnt.getCoor();
813                if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
814                    continue;
815                }
816                Point screen = mv.getPoint(trkPnt);
817                g.setColor(trkPnt.customColoring);
818                g.drawRect(screen.x, screen.y, 0, 0);
819            } // end for trkpnt
820        } // end if large
821    }
822
823    /**
824     * Draw GPX lines by using alpha blending
825     * @param g               the common draw object to use
826     * @param mv              the meta data to current displayed area
827     * @param visibleSegments segments visible in the current scope of mv
828     * @param layerAlpha      the color alpha value set for that operation
829     */
830    private void drawLinesAlpha(Graphics2D g, MapView mv, List<WayPoint> visibleSegments, float layerAlpha) {
831
832        // 1st. backup the paint environment ----------------------------------
833        Composite oldComposite = g.getComposite();
834        Stroke oldStroke = g.getStroke();
835        Paint oldPaint = g.getPaint();
836
837        // 2nd. determine current scale factors -------------------------------
838
839        // adjust global settings
840        final int globalLineWidth = Utils.clamp(lineWidth, 1, 20);
841
842        // cache scale of view
843        final double zoomScale = mv.getDist100Pixel() / 50.0f;
844
845        // 3rd. determine current paint parameters -----------------------------
846
847        // alpha value is based on zoom and line with combined with global layer alpha
848        float theLineAlpha = (float) Utils.clamp((0.50 / zoomScale) / (globalLineWidth + 1), 0.01, 0.50) * layerAlpha;
849        final int theLineWith = (int) (lineWidth / zoomScale) + 1;
850
851        // 4th setup virtual paint area ----------------------------------------
852
853        // set line format and alpha channel for all overlays (more lines -> few overlap -> more transparency)
854        g.setStroke(new BasicStroke(theLineWith, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
855        g.setComposite(AlphaComposite.SrcOver.derive(theLineAlpha));
856
857        // last used / calculated entries
858        Point lastPaintPnt = null;
859
860        // 5th draw the layer ---------------------------------------------------
861
862        // for all points
863        for (WayPoint trkPnt : visibleSegments) {
864
865            // transform coordinates
866            final Point paintPnt = mv.getPoint(trkPnt);
867
868            // skip single points
869            if (lastPaintPnt != null && trkPnt.drawLine && !lastPaintPnt.equals(paintPnt)) {
870
871                // set different color
872                g.setColor(trkPnt.customColoring);
873
874                // draw it
875                g.drawLine(lastPaintPnt.x, lastPaintPnt.y, paintPnt.x, paintPnt.y);
876            }
877
878            lastPaintPnt = paintPnt;
879        }
880
881        // @last restore modified paint environment -----------------------------
882        g.setPaint(oldPaint);
883        g.setStroke(oldStroke);
884        g.setComposite(oldComposite);
885    }
886
887    /**
888     * Generates a linear gradient map image
889     *
890     * @param width  image width
891     * @param height image height
892     * @param colors 1..n color descriptions
893     * @return image object
894     */
895    protected static BufferedImage createImageGradientMap(int width, int height, Color... colors) {
896
897        // create image an paint object
898        final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
899        final Graphics2D g = img.createGraphics();
900
901        float[] fract = new float[ colors.length ];
902
903        // distribute fractions (define position of color in map)
904        for (int i = 0; i < colors.length; ++i) {
905            fract[i] = i * (1.0f / colors.length);
906        }
907
908        // draw the gradient map
909        LinearGradientPaint gradient = new LinearGradientPaint(0, 0, width, height, fract, colors,
910                                                               MultipleGradientPaint.CycleMethod.NO_CYCLE);
911        g.setPaint(gradient);
912        g.fillRect(0, 0, width, height);
913        g.dispose();
914
915        // access it via raw interface
916        return img;
917    }
918
919    /**
920     * Creates a distributed colormap by linear blending between colors
921     * @param lowerLimit lower limit for first visible color
922     * @param colors 1..n colors
923     * @return array of Color objects
924     */
925    protected static Color[] createColorLut(int lowerLimit, Color... colors) {
926
927        // number of lookup entries
928        final int tableSize = 256;
929
930        // access it via raw interface
931        final Raster imgRaster = createImageGradientMap(tableSize, 1, colors).getData();
932
933        // the pixel storage
934        int[] pixel = new int[1];
935
936        Color[] colorTable = new Color[tableSize];
937
938        // map the range 0..255 to 0..pi/2
939        final double mapTo90Deg = Math.PI / 2.0 / 255.0;
940
941        // create the lookup table
942        for (int i = 0; i < tableSize; i++) {
943
944            // get next single pixel
945            imgRaster.getDataElements(i, 0, pixel);
946
947            // get color and map
948            Color c = new Color(pixel[0]);
949
950            // smooth alpha like sin curve
951            int alpha = (i > lowerLimit) ? (int) (Math.sin((i-lowerLimit) * mapTo90Deg) * 255) : 0;
952
953            // alpha with pre-offset, first color -> full transparent
954            alpha = alpha > 0 ? (20 + alpha) : 0;
955
956            // shrink to maximum bound
957            if (alpha > 255) {
958                alpha = 255;
959            }
960
961            // increase transparency for higher values ( avoid big saturation )
962            if (i > 240 && 255 == alpha) {
963                alpha -= (i - 240);
964            }
965
966            // fill entry in table, assign a alpha value
967            colorTable[i] = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
968        }
969
970        // transform into lookup table
971        return colorTable;
972    }
973
974    /**
975     * Creates a darker color
976     * @param in        Color object
977     * @param adjust    darker adjustment amount
978     * @return          new Color
979     */
980    protected static Color darkerColor(Color in, float adjust) {
981
982        final float r = (float) in.getRed()/255;
983        final float g = (float) in.getGreen()/255;
984        final float b = (float) in.getBlue()/255;
985
986        return new Color(r*adjust, g*adjust, b*adjust);
987    }
988
989    /**
990     * Creates a colormap by using a static color map with 1..n colors (RGB 0.0 ..1.0)
991     * @param str the filename (without extension) to look for into data/gpx
992     * @return the parsed colormap
993     */
994    protected static Color[] createColorFromResource(String str) {
995
996        // create resource string
997        final String colorFile = "resource://data/gpx/" + str + ".txt";
998
999        List<Color> colorList = new ArrayList<>();
1000
1001        // try to load the file
1002        try (CachedFile cf = new CachedFile(colorFile); BufferedReader br = cf.getContentReader()) {
1003
1004            String line;
1005
1006            // process lines
1007            while ((line = br.readLine()) != null) {
1008
1009                // use comma as separator
1010                String[] column = line.split(",");
1011
1012                // empty or comment line
1013                if (column.length < 3 || column[0].startsWith("#")) {
1014                    continue;
1015                }
1016
1017                // extract RGB value
1018                float r = Float.parseFloat(column[0]);
1019                float g = Float.parseFloat(column[1]);
1020                float b = Float.parseFloat(column[2]);
1021
1022                // some color tables are 0..1.0 and some 0.255
1023                float scale = (r < 1 && g < 1 && b < 1) ? 1 : 255;
1024
1025                colorList.add(new Color(r/scale, g/scale, b/scale));
1026            }
1027        } catch (IOException e) {
1028            throw new JosmRuntimeException(e);
1029        }
1030
1031        // fallback if empty or failed
1032        if (colorList.isEmpty()) {
1033            colorList.add(Color.BLACK);
1034            colorList.add(Color.WHITE);
1035        } else {
1036            // add additional darker elements to end of list
1037            final Color lastColor = colorList.get(colorList.size() - 1);
1038            colorList.add(darkerColor(lastColor, 0.975f));
1039            colorList.add(darkerColor(lastColor, 0.950f));
1040        }
1041
1042        return createColorLut(0, colorList.toArray(new Color[0]));
1043    }
1044
1045    /**
1046     * Returns the next user color map
1047     *
1048     * @param userColor - default or fallback user color
1049     * @param tableIdx  - selected user color index
1050     * @return color array
1051     */
1052    protected static Color[] selectColorMap(Color userColor, int tableIdx) {
1053
1054        // generate new user color map ( dark, user color, white )
1055        Color[] userColor1 = createColorLut(0, userColor.darker(), userColor, userColor.brighter(), Color.WHITE);
1056
1057        // generate new user color map ( white -> color )
1058        Color[] userColor2 = createColorLut(0, Color.WHITE, Color.WHITE, userColor);
1059
1060        // generate new user color map
1061        Color[] colorTrafficLights = createColorLut(0, Color.WHITE, Color.GREEN.darker(), Color.YELLOW, Color.RED);
1062
1063        // decide what, keep order is sync with setting on GUI
1064        Color[][] lut = {
1065                userColor1,
1066                userColor2,
1067                colorTrafficLights,
1068                heatMapLutColorJosmInferno,
1069                heatMapLutColorJosmViridis,
1070                heatMapLutColorJosmBrown2Green,
1071                heatMapLutColorJosmRed2Blue
1072        };
1073
1074        // default case
1075        Color[] nextUserColor = userColor1;
1076
1077        // select by index
1078        if (tableIdx < lut.length) {
1079            nextUserColor = lut[ tableIdx ];
1080        }
1081
1082        // adjust color map
1083        return nextUserColor;
1084    }
1085
1086    /**
1087     * Generates a Icon
1088     *
1089     * @param userColor selected user color
1090     * @param tableIdx tabled index
1091     * @param size size of the image
1092     * @return a image icon that shows the
1093     */
1094    public static ImageIcon getColorMapImageIcon(Color userColor, int tableIdx, int size) {
1095        return new ImageIcon(createImageGradientMap(size, size, selectColorMap(userColor, tableIdx)));
1096    }
1097
1098    /**
1099     * Draw gray heat map with current Graphics2D setting
1100     * @param gB              the common draw object to use
1101     * @param mv              the meta data to current displayed area
1102     * @param listSegm        segments visible in the current scope of mv
1103     * @param foreComp        composite use to draw foreground objects
1104     * @param foreStroke      stroke use to draw foreground objects
1105     * @param backComp        composite use to draw background objects
1106     * @param backStroke      stroke use to draw background objects
1107     */
1108    private void drawHeatGrayLineMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm,
1109                                     Composite foreComp, Stroke foreStroke,
1110                                     Composite backComp, Stroke backStroke) {
1111
1112        // draw foreground
1113        boolean drawForeground = foreComp != null && foreStroke != null;
1114
1115        // set initial values
1116        gB.setStroke(backStroke); gB.setComposite(backComp);
1117
1118        // get last point in list
1119        final WayPoint lastPnt = !listSegm.isEmpty() ? listSegm.get(listSegm.size() - 1) : null;
1120
1121        // for all points, draw single lines by using optimized drawing
1122        for (WayPoint trkPnt : listSegm) {
1123
1124            // get transformed coordinates
1125            final Point paintPnt = mv.getPoint(trkPnt);
1126
1127            // end of line segment or end of list reached
1128            if (!trkPnt.drawLine || (lastPnt == trkPnt)) {
1129
1130                // convert to primitive type
1131                final int[] polyXArr = heatMapPolyX.stream().mapToInt(Integer::intValue).toArray();
1132                final int[] polyYArr = heatMapPolyY.stream().mapToInt(Integer::intValue).toArray();
1133
1134                // a.) draw background
1135                gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1136
1137                // b.) draw extra foreground
1138                if (drawForeground && heatMapDrawExtraLine) {
1139
1140                    gB.setStroke(foreStroke); gB.setComposite(foreComp);
1141                    gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1142                    gB.setStroke(backStroke); gB.setComposite(backComp);
1143                }
1144
1145                // drop used points
1146                heatMapPolyX.clear(); heatMapPolyY.clear();
1147            }
1148
1149            // store only the integer part (make sense because pixel is 1:1 here)
1150            heatMapPolyX.add((int) paintPnt.getX());
1151            heatMapPolyY.add((int) paintPnt.getY());
1152        }
1153    }
1154
1155    /**
1156     * Map the gray map to heat map and draw them with current Graphics2D setting
1157     * @param g               the common draw object to use
1158     * @param imgGray         gray scale input image
1159     * @param sampleRaster    the line with for drawing
1160     * @param outlineWidth     line width for outlines
1161     */
1162    private void drawHeatMapGrayMap(Graphics2D g, BufferedImage imgGray, int sampleRaster, int outlineWidth) {
1163
1164        final int[] imgPixels = ((DataBufferInt) imgGray.getRaster().getDataBuffer()).getData();
1165
1166        // samples offset and bounds are scaled with line width derived from zoom level
1167        final int offX = Math.max(1, sampleRaster);
1168        final int offY = Math.max(1, sampleRaster);
1169
1170        final int maxPixelX = imgGray.getWidth();
1171        final int maxPixelY = imgGray.getHeight();
1172
1173        // always full or outlines at big samples rasters
1174        final boolean drawOutlines = (outlineWidth > 0) && ((0 == sampleRaster) || (sampleRaster > 10));
1175
1176        // backup stroke
1177        final Stroke oldStroke = g.getStroke();
1178
1179        // use basic stroke for outlines and default transparency
1180        g.setStroke(new BasicStroke(outlineWidth));
1181
1182        int lastPixelX = 0;
1183        int lastPixelColor = 0;
1184
1185        // resample gray scale image with line linear weight of next sample in line
1186        // process each line and draw pixels / rectangles with same color with one operations
1187        for (int y = 0; y < maxPixelY; y += offY) {
1188
1189            // the lines offsets
1190            final int lastLineOffset = maxPixelX * (y+0);
1191            final int nextLineOffset = maxPixelX * (y+1);
1192
1193            for (int x = 0; x < maxPixelX; x += offX) {
1194
1195                int thePixelColor = 0; int thePixelCount = 0;
1196
1197                // sample the image (it is gray scale)
1198                int offset = lastLineOffset + x;
1199
1200                // merge next pixels of window of line
1201                for (int k = 0; k < offX && (offset + k) < nextLineOffset; k++) {
1202                    thePixelColor += imgPixels[offset+k] & 0xFF;
1203                    thePixelCount++;
1204                }
1205
1206                // mean value
1207                thePixelColor = thePixelCount > 0 ? (thePixelColor / thePixelCount) : 0;
1208
1209                // restart -> use initial sample
1210                if (0 == x) {
1211                    lastPixelX = 0; lastPixelColor = thePixelColor - 1;
1212                }
1213
1214                boolean bDrawIt = false;
1215
1216                // when one of segment is mapped to black
1217                bDrawIt = bDrawIt || (lastPixelColor == 0) || (thePixelColor == 0);
1218
1219                // different color
1220                bDrawIt = bDrawIt || (Math.abs(lastPixelColor-thePixelColor) > 0);
1221
1222                // when line is finished draw always
1223                bDrawIt = bDrawIt || (y >= (maxPixelY-offY));
1224
1225                if (bDrawIt) {
1226
1227                    // draw only foreground pixels
1228                    if (lastPixelColor > 0) {
1229
1230                        // gray to RGB mapping
1231                        g.setColor(heatMapLutColor[ lastPixelColor ]);
1232
1233                        // box from from last Y pixel to current pixel
1234                        if (drawOutlines) {
1235                            g.drawRect(lastPixelX, y, offX + x - lastPixelX, offY);
1236                        } else {
1237                            g.fillRect(lastPixelX, y, offX + x - lastPixelX, offY);
1238                        }
1239                    }
1240
1241                    // restart detection
1242                    lastPixelX = x; lastPixelColor = thePixelColor;
1243                }
1244            }
1245        }
1246
1247        // recover
1248        g.setStroke(oldStroke);
1249    }
1250
1251    /**
1252     * Collect and draw GPS segments and displays a heat-map
1253     * @param g               the common draw object to use
1254     * @param mv              the meta data to current displayed area
1255     * @param visibleSegments segments visible in the current scope of mv
1256     */
1257    private void drawHeatMap(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
1258
1259        // get bounds of screen image and projection, zoom and adjust input parameters
1260        final Rectangle screenBounds = new Rectangle(mv.getWidth(), mv.getHeight());
1261        final MapViewState mapViewState = mv.getState();
1262        final double zoomScale = mv.getDist100Pixel() / 50.0f;
1263
1264        // adjust global settings ( zero = default line width )
1265        final int globalLineWidth = (0 == lineWidth) ? 1 : Utils.clamp(lineWidth, 1, 20);
1266
1267        // 1st setup virtual paint area ----------------------------------------
1268
1269        // new image buffer needed
1270        final boolean imageSetup = null == heatMapImgGray || !heatMapCacheScreenBounds.equals(screenBounds);
1271
1272        // screen bounds changed, need new image buffer ?
1273        if (imageSetup) {
1274            // we would use a "pure" grayscale image, but there is not efficient way to map gray scale values to RGB)
1275            heatMapImgGray = new BufferedImage(screenBounds.width, screenBounds.height, BufferedImage.TYPE_INT_ARGB);
1276            heatMapGraph2d = heatMapImgGray.createGraphics();
1277            heatMapGraph2d.setBackground(new Color(0, 0, 0, 255));
1278            heatMapGraph2d.setColor(Color.WHITE);
1279
1280            // fast draw ( maybe help or not )
1281            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
1282            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
1283            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
1284            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
1285            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1286            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
1287            heatMapGraph2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
1288
1289            // cache it
1290            heatMapCacheScreenBounds = screenBounds;
1291        }
1292
1293        // 2nd. determine current scale factors -------------------------------
1294
1295        // the line width (foreground: draw extra small footprint line of track)
1296        int lineWidthB = (int) Math.max(1.5f * (globalLineWidth / zoomScale) + 1, 2);
1297        int lineWidthF = lineWidthB > 2 ? (globalLineWidth - 1) : 0;
1298
1299        // global alpha adjustment
1300        float lineAlpha = (float) Utils.clamp((0.40 / zoomScale) / (globalLineWidth + 1), 0.01, 0.40);
1301
1302        // adjust 0.15 .. 1.85
1303        float scaleAlpha = 1.0f + ((heatMapDrawGain/10.0f) * 0.85f);
1304
1305        // add to calculated values
1306        float lineAlphaBPoint = (float) Utils.clamp((lineAlpha * 0.65) * scaleAlpha, 0.001, 0.90);
1307        float lineAlphaBLine = (float) Utils.clamp((lineAlpha * 1.00) * scaleAlpha, 0.001, 0.90);
1308        float lineAlphaFLine = (float) Utils.clamp((lineAlpha / 1.50) * scaleAlpha, 0.001, 0.90);
1309
1310        // 3rd Calculate the heat map data by draw GPX traces with alpha value ----------
1311
1312        // recalculation of image needed
1313        final boolean imageRecalc = !mapViewState.equalsInWindow(heatMapMapViewState)
1314                || gpxLayerInvalidated
1315                || heatMapCacheLineWith != globalLineWidth;
1316
1317        // need re-generation of gray image ?
1318        if (imageSetup || imageRecalc) {
1319
1320            // clear background
1321            heatMapGraph2d.clearRect(0, 0, heatMapImgGray.getWidth(), heatMapImgGray.getHeight());
1322
1323            // point or line blending
1324            if (heatMapDrawPointMode) {
1325                heatMapGraph2d.setComposite(AlphaComposite.SrcOver.derive(lineAlphaBPoint));
1326                drawHeatGrayDotMap(heatMapGraph2d, mv, visibleSegments, lineWidthB);
1327
1328            } else {
1329                drawHeatGrayLineMap(heatMapGraph2d, mv, visibleSegments,
1330                                    lineWidthF > 1 ? AlphaComposite.SrcOver.derive(lineAlphaFLine) : null,
1331                                    new BasicStroke(lineWidthF, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND),
1332                                    AlphaComposite.SrcOver.derive(lineAlphaBLine),
1333                                    new BasicStroke(lineWidthB, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
1334            }
1335
1336            // remember draw parameter
1337            heatMapMapViewState = mapViewState;
1338            heatMapCacheLineWith = globalLineWidth;
1339            gpxLayerInvalidated = false;
1340        }
1341
1342        // 4th. Draw data on target layer, map data via color lookup table --------------
1343        drawHeatMapGrayMap(g, heatMapImgGray, lineWidthB > 2 ? (int) (lineWidthB*1.25f) : 1, lineWidth > 2 ? (lineWidth - 2) : 1);
1344    }
1345
1346    /**
1347     * Draw a dotted heat map
1348     *
1349     * @param gB              the common draw object to use
1350     * @param mv              the meta data to current displayed area
1351     * @param listSegm        segments visible in the current scope of mv
1352     * @param drawSize        draw size of draw element
1353     */
1354    private static void drawHeatGrayDotMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm, int drawSize) {
1355
1356        // typical rendering rate -> use realtime preview instead of accurate display
1357        final double maxSegm = 25_000, nrSegms = listSegm.size();
1358
1359        // determine random drop rate
1360        final double randomDrop = Math.min(nrSegms > maxSegm ? (nrSegms - maxSegm) / nrSegms : 0, 0.70f);
1361
1362        // http://www.nstb.tc.faa.gov/reports/PAN94_0716.pdf#page=22
1363        // Global Average Position Domain Accuracy, typical -> not worst case !
1364        // < 4.218 m Vertical
1365        // < 2.168 m Horizontal
1366        final double pixelRmsX = (100 / mv.getDist100Pixel()) * 2.168;
1367        final double pixelRmsY = (100 / mv.getDist100Pixel()) * 4.218;
1368
1369        Point lastPnt = null;
1370
1371        // for all points, draw single lines
1372        for (WayPoint trkPnt : listSegm) {
1373
1374            // get transformed coordinates
1375            final Point paintPnt = mv.getPoint(trkPnt);
1376
1377            // end of line segment or end of list reached
1378            if (trkPnt.drawLine && null != lastPnt) {
1379                drawHeatSurfaceLine(gB, paintPnt, lastPnt, drawSize, pixelRmsX, pixelRmsY, randomDrop);
1380            }
1381
1382            // remember
1383            lastPnt = paintPnt;
1384        }
1385    }
1386
1387    /**
1388     * Draw a dotted surface line
1389     *
1390     * @param g                 the common draw object to use
1391     * @param fromPnt           start point
1392     * @param toPnt             end point
1393     * @param drawSize          size of draw elements
1394     * @param rmsSizeX          RMS size of circle for X (width)
1395     * @param rmsSizeY          RMS size of circle for Y (height)
1396     * @param dropRate          Pixel render drop rate
1397     */
1398    private static void drawHeatSurfaceLine(Graphics2D g,
1399            Point fromPnt, Point toPnt, int drawSize, double rmsSizeX, double rmsSizeY, double dropRate) {
1400
1401        // collect frequently used items
1402        final int fromX = (int) fromPnt.getX(); final int deltaX = (int) (toPnt.getX() - fromX);
1403        final int fromY = (int) fromPnt.getY(); final int deltaY = (int) (toPnt.getY() - fromY);
1404
1405        // use same random values for each point
1406        final Random heatMapRandom = new Random(fromX+fromY+deltaX+deltaY);
1407
1408        // cache distance between start and end point
1409        final int dist = (int) Math.abs(fromPnt.distance(toPnt));
1410
1411        // number of increment ( fill wide distance tracks )
1412        double scaleStep = Math.max(1.0f / dist, dist > 100 ? 0.10f : 0.20f);
1413
1414        // number of additional random points
1415        int rounds = Math.min(drawSize/2, 1)+1;
1416
1417        // decrease random noise at high drop rate ( more accurate draw of fewer points )
1418        rmsSizeX *= (1.0d - dropRate);
1419        rmsSizeY *= (1.0d - dropRate);
1420
1421        double scaleVal = 0;
1422
1423        // interpolate line draw ( needs separate point instead of line )
1424        while (scaleVal < (1.0d-0.0001d)) {
1425
1426            // get position
1427            final double pntX = fromX + scaleVal * deltaX;
1428            final double pntY = fromY + scaleVal * deltaY;
1429
1430            // add random distribution around sampled point
1431            for (int k = 0; k < rounds; k++) {
1432
1433                // add error distribution, first point with less error
1434                int x = (int) (pntX + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeX : rmsSizeX/4));
1435                int y = (int) (pntY + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeY : rmsSizeY/4));
1436
1437                // draw it, even drop is requested
1438                if (heatMapRandom.nextDouble() >= dropRate) {
1439                    g.fillRect(x-drawSize, y-drawSize, drawSize, drawSize);
1440                }
1441            }
1442            scaleVal += scaleStep;
1443        }
1444    }
1445
1446    /**
1447     * Apply default color configuration to way segments
1448     * @param visibleSegments segments visible in the current scope of mv
1449     */
1450    private void fixColors(List<WayPoint> visibleSegments) {
1451        for (WayPoint trkPnt : visibleSegments) {
1452            if (trkPnt.customColoring == null) {
1453                trkPnt.customColoring = neutralColor;
1454            }
1455        }
1456    }
1457
1458    /**
1459     * Check cache validity set necessary flags
1460     */
1461    private void checkCache() {
1462        // CHECKSTYLE.OFF: BooleanExpressionComplexity
1463        if ((computeCacheMaxLineLengthUsed != maxLineLength)
1464                || (computeCacheColored != colored)
1465                || (computeCacheColorTracksTune != colorTracksTune)
1466                || (computeCacheColorDynamic != colorModeDynamic)
1467                || (computeCacheHeatMapDrawColorTableIdx != heatMapDrawColorTableIdx)
1468                || (!neutralColor.equals(computeCacheColorUsed)
1469                || (computeCacheHeatMapDrawPointMode != heatMapDrawPointMode)
1470                || (computeCacheHeatMapDrawGain != heatMapDrawGain))
1471                || (computeCacheHeatMapDrawLowerLimit != heatMapDrawLowerLimit)
1472        ) {
1473            // CHECKSTYLE.ON: BooleanExpressionComplexity
1474            computeCacheMaxLineLengthUsed = maxLineLength;
1475            computeCacheInSync = false;
1476            computeCacheColorUsed = neutralColor;
1477            computeCacheColored = colored;
1478            computeCacheColorTracksTune = colorTracksTune;
1479            computeCacheColorDynamic = colorModeDynamic;
1480            computeCacheHeatMapDrawColorTableIdx = heatMapDrawColorTableIdx;
1481            computeCacheHeatMapDrawPointMode = heatMapDrawPointMode;
1482            computeCacheHeatMapDrawGain = heatMapDrawGain;
1483            computeCacheHeatMapDrawLowerLimit = heatMapDrawLowerLimit;
1484        }
1485    }
1486
1487    /**
1488     *  callback when data is changed, invalidate cached configuration parameters
1489     */
1490    @Override
1491    public void gpxDataChanged(GpxDataChangeEvent e) {
1492        computeCacheInSync = false;
1493    }
1494
1495    /**
1496     * Draw all GPX arrays
1497     * @param g               the common draw object to use
1498     * @param mv              the meta data to current displayed area
1499     */
1500    public void drawColorBar(Graphics2D g, MapView mv) {
1501        int w = mv.getWidth();
1502
1503        // set do default
1504        g.setComposite(AlphaComposite.SrcOver.derive(1.00f));
1505
1506        if (colored == ColorMode.HDOP) {
1507            hdopScale.drawColorBar(g, w-30, 50, 20, 100, 1.0);
1508        } else if (colored == ColorMode.VELOCITY) {
1509            SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
1510            velocityScale.drawColorBar(g, w-30, 50, 20, 100, som.speedValue);
1511        } else if (colored == ColorMode.DIRECTION) {
1512            directionScale.drawColorBar(g, w-30, 50, 20, 100, 180.0/Math.PI);
1513        }
1514    }
1515
1516    @Override
1517    public void paintableInvalidated(PaintableInvalidationEvent event) {
1518        gpxLayerInvalidated = true;
1519    }
1520
1521    @Override
1522    public void detachFromMapView(MapViewEvent event) {
1523        SystemOfMeasurement.removeSoMChangeListener(this);
1524        layer.removeInvalidationListener(this);
1525        data.removeChangeListener(this);
1526    }
1527}