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

Last change on this file since 15282 was 15282, checked in by Don-vip, 5 years ago

fix #18002 - ignore negative width in GpxDrawHelper

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