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

Last change on this file since 18396 was 18396, checked in by stoecker, 3 years ago

fix #20600 - add Fix coloring for NMEA, patch by Bjoeni

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