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

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

see #15229 - deprecate ILatLon#getEastNorth() so ILatLon has no dependency on Main.proj

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