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

Last change on this file since 16864 was 16864, checked in by simon04, 4 years ago

fix #15441 - Separate GpxRouteLayer

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