source: josm/trunk/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java@ 12891

Last change on this file since 12891 was 12891, checked in by bastiK, 7 years ago

see #15229 - move non-essential helper methods from Preferences to PreferencesUtils

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