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

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

Trigger a GPX layer invalidation on SoM change.

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