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

Last change on this file since 12171 was 12171, checked in by michael2402, 7 years ago

Fixed checkstyle warnings.

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