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

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

see #10269 - fix NPE (robustness. trkPnt.customColoring should probably not be null)

File size: 22.8 KB
Line 
1// License: GPL. See LICENSE file for details.
2
3package org.openstreetmap.josm.gui.layer.gpx;
4
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7
8import java.awt.BasicStroke;
9import java.awt.Color;
10import java.awt.Graphics2D;
11import java.awt.Point;
12import java.awt.RenderingHints;
13import java.awt.Stroke;
14import java.util.Collection;
15import java.util.Date;
16import java.util.List;
17
18import org.openstreetmap.josm.Main;
19import org.openstreetmap.josm.data.coor.LatLon;
20import org.openstreetmap.josm.data.gpx.GpxData;
21import org.openstreetmap.josm.data.gpx.WayPoint;
22import org.openstreetmap.josm.gui.MapView;
23import org.openstreetmap.josm.tools.ColorScale;
24
25
26/**
27 * Class that helps to draw large set of GPS tracks with different colors and options
28 * @since 7319
29 */
30public class GpxDrawHelper {
31 private GpxData data;
32
33 // draw lines between points belonging to different segments
34 private boolean forceLines;
35 // draw direction arrows on the lines
36 private boolean direction;
37 /** don't draw lines if longer than x meters **/
38 private int lineWidth;
39 private int maxLineLength;
40 private boolean lines;
41 /** paint large dots for points **/
42 private boolean large;
43 private int largesize;
44 private boolean hdopCircle;
45 /** paint direction arrow with alternate math. may be faster **/
46 private boolean alternateDirection;
47 /** don't draw arrows nearer to each other than this **/
48 private int delta;
49 private double minTrackDurationForTimeColoring;
50
51 private int hdopfactor;
52
53 private static final double PHI = Math.toRadians(15);
54
55 //// Variables used only to check cache validity
56 private boolean computeCacheInSync = false;
57 private int computeCacheMaxLineLengthUsed;
58 private Color computeCacheColorUsed;
59 private boolean computeCacheColorDynamic;
60 private ColorMode computeCacheColored;
61 private int computeCacheColorTracksTune;
62
63 //// Color-related fields
64 /** Mode of the line coloring **/
65 private ColorMode colored;
66 /** max speed for coloring - allows to tweak line coloring for different speed levels. **/
67 private int colorTracksTune;
68 private boolean colorModeDynamic;
69 private Color neutralColor;
70 private int largePointAlpha;
71
72 // default access is used to allow changing from plugins
73 ColorScale velocityScale;
74 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
75 ColorScale hdopScale;
76 ColorScale dateScale;
77 ColorScale directionScale;
78
79 /** Opacity for hdop points **/
80 private int hdopAlpha;
81
82
83 // lookup array to draw arrows without doing any math
84 private static final int ll0 = 9;
85 private static final int sl4 = 5;
86 private static final int sl9 = 3;
87 private static final int[][] dir = { { +sl4, +ll0, +ll0, +sl4 }, { -sl9, +ll0, +sl9, +ll0 }, { -ll0, +sl4, -sl4, +ll0 },
88 { -ll0, -sl9, -ll0, +sl9 }, { -sl4, -ll0, -ll0, -sl4 }, { +sl9, -ll0, -sl9, -ll0 },
89 { +ll0, -sl4, +sl4, -ll0 }, { +ll0, +sl9, +ll0, -sl9 }, { +sl4, +ll0, +ll0, +sl4 },
90 { -sl9, +ll0, +sl9, +ll0 }, { -ll0, +sl4, -sl4, +ll0 }, { -ll0, -sl9, -ll0, +sl9 } };
91
92 private void setupColors() {
93 hdopAlpha = Main.pref.getInteger("hdop.color.alpha", -1);
94 velocityScale = ColorScale.createHSBScale(256).addTitle(tr("Velocity, km/h"));
95 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
96 hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP, m"));
97 dateScale = ColorScale.createHSBScale(256).addTitle(tr("Time"));
98 directionScale = ColorScale.createCyclicScale(256).setIntervalCount(4).addTitle(tr("Direction"));
99 }
100
101 /**
102 * Different color modes
103 */
104 public enum ColorMode {
105 NONE, VELOCITY, HDOP, DIRECTION, TIME
106 }
107
108 public GpxDrawHelper(GpxData gpxData) {
109 data = gpxData;
110 setupColors();
111 }
112
113 /**
114 * Get the default color for gps tracks for specified layer
115 * @param layerName name of the GpxLayer
116 * @param ignoreCustom do not use preferences
117 * @return the color or null if the color is not constant
118 */
119 public Color getColor(String layerName, boolean ignoreCustom) {
120 Color c = Main.pref.getColor(marktr("gps point"), "layer " + layerName, Color.gray);
121 return ignoreCustom || getColorMode(layerName) == ColorMode.NONE ? c : null;
122 }
123
124 /**
125 * Read coloring mode for specified layer from preferences
126 * @param layerName name of the GpxLayer
127 * @return coloting mode
128 */
129 public ColorMode getColorMode(String layerName) {
130 try {
131 int i=Main.pref.getInteger("draw.rawgps.colors", "layer " + layerName, 0);
132 return ColorMode.values()[i];
133 } catch (Exception e) {
134 Main.warn(e);
135 }
136 return ColorMode.NONE;
137 }
138
139 /** Reads generic color from preferences (usually gray)
140 * @return the color
141 **/
142 public static Color getGenericColor() {
143 return Main.pref.getColor(marktr("gps point"), Color.gray);
144 }
145
146 /**
147 * Read all drawing-related settings from preferences
148 * @param layerName layer name used to access its specific preferences
149 **/
150 public void readPreferences(String layerName) {
151 String spec = "layer " + layerName;
152 forceLines = Main.pref.getBoolean("draw.rawgps.lines.force", spec, false);
153 direction = Main.pref.getBoolean("draw.rawgps.direction", spec, false);
154 lineWidth = Main.pref.getInteger("draw.rawgps.linewidth", spec, 0);
155
156 if (!data.fromServer) {
157 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length.local", spec, -1);
158 lines = Main.pref.getBoolean("draw.rawgps.lines.local", spec, true);
159 } else {
160 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length", spec, 200);
161 lines = Main.pref.getBoolean("draw.rawgps.lines", spec, true);
162 }
163 large = Main.pref.getBoolean("draw.rawgps.large", spec, false);
164 largesize = Main.pref.getInteger("draw.rawgps.large.size", spec, 3);
165 hdopCircle = Main.pref.getBoolean("draw.rawgps.hdopcircle", spec, false);
166 colored = getColorMode(layerName);
167 alternateDirection = Main.pref.getBoolean("draw.rawgps.alternatedirection", spec, false);
168 delta = Main.pref.getInteger("draw.rawgps.min-arrow-distance", spec, 40);
169 colorTracksTune = Main.pref.getInteger("draw.rawgps.colorTracksTune", spec, 45);
170 colorModeDynamic = Main.pref.getBoolean("draw.rawgps.colors.dynamic", spec, false);
171 hdopfactor = Main.pref.getInteger("hdop.factor", 25);
172 minTrackDurationForTimeColoring = Main.pref.getInteger("draw.rawgps.date-coloring-min-dt", 60);
173 largePointAlpha = Main.pref.getInteger("draw.rawgps.large.alpha", -1) & 0xFF;
174
175 neutralColor = getColor(layerName, true);
176 velocityScale.setNoDataColor(neutralColor);
177 dateScale.setNoDataColor(neutralColor);
178 hdopScale.setNoDataColor(neutralColor);
179 directionScale.setNoDataColor(neutralColor);
180
181 largesize += lineWidth;
182 }
183
184
185 public void drawAll(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
186
187 checkCache();
188
189 // STEP 2b - RE-COMPUTE CACHE DATA *********************
190 if (!computeCacheInSync) { // don't compute if the cache is good
191 calculateColors();
192 }
193
194 Stroke storedStroke = g.getStroke();
195
196 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
197 Main.pref.getBoolean("mappaint.gpx.use-antialiasing", false) ?
198 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
199
200 if(lineWidth != 0) {
201 g.setStroke(new BasicStroke(lineWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
202 }
203 drawLines(g, mv, visibleSegments);
204 drawArrows(g, mv, visibleSegments);
205 drawPoints(g, mv, visibleSegments);
206 if(lineWidth != 0) {
207 g.setStroke(storedStroke);
208 }
209 }
210
211 public void calculateColors() {
212 double minval = +1e10;
213 double maxval = -1e10;
214 WayPoint oldWp = null;
215
216 if (colorModeDynamic) {
217 if (colored == ColorMode.VELOCITY) {
218 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
219 if(!forceLines) {
220 oldWp = null;
221 }
222 for (WayPoint trkPnt : segment) {
223 LatLon c = trkPnt.getCoor();
224 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
225 continue;
226 }
227 if (oldWp != null && trkPnt.time > oldWp.time) {
228 double vel = c.greatCircleDistance(oldWp.getCoor())
229 / (trkPnt.time - oldWp.time);
230 if(vel > maxval) {
231 maxval = vel;
232 }
233 if(vel < minval) {
234 minval = vel;
235 }
236 }
237 oldWp = trkPnt;
238 }
239 }
240 if (minval >= maxval) {
241 velocityScale.setRange(0, 120/3.6);
242 } else {
243 velocityScale.setRange(minval, maxval);
244 }
245 } else if (colored == ColorMode.HDOP) {
246 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
247 for (WayPoint trkPnt : segment) {
248 Object val = trkPnt.attr.get("hdop");
249 if (val != null) {
250 double hdop = ((Float) val).doubleValue();
251 if(hdop > maxval) {
252 maxval = hdop;
253 }
254 if(hdop < minval) {
255 minval = hdop;
256 }
257 }
258 }
259 }
260 if (minval >= maxval) {
261 hdopScale.setRange(0, 100);
262 } else {
263 hdopScale.setRange(minval, maxval);
264 }
265 }
266 oldWp = null;
267 } else { // color mode not dynamic
268 velocityScale.setRange(0, colorTracksTune);
269 hdopScale.setRange(0, 1.0/hdopfactor);
270 }
271 double now = System.currentTimeMillis()/1000.0;
272 if (colored == ColorMode.TIME) {
273 Date[] bounds = data.getMinMaxTimeForAllTracks();
274 if (bounds!=null) {
275 minval = bounds[0].getTime()/1000.0;
276 maxval = bounds[1].getTime()/1000.0;
277 } else {
278 minval = 0; maxval=now;
279 }
280 dateScale.setRange(minval, maxval);
281 }
282
283
284 // Now the colors for all the points will be assigned
285 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
286 if (!forceLines) { // don't draw lines between segments, unless forced to
287 oldWp = null;
288 }
289 for (WayPoint trkPnt : segment) {
290 LatLon c = trkPnt.getCoor();
291 trkPnt.customColoring = neutralColor;
292 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
293 continue;
294 }
295 // now we are sure some color will be assigned
296 Color color = null;
297
298 if (colored == ColorMode.HDOP) {
299 Float hdop = ((Float) trkPnt.attr.get("hdop"));
300 color = hdopScale.getColor(hdop);
301 }
302 if (oldWp != null) { // other coloring modes need segment for calcuation
303 double dist = c.greatCircleDistance(oldWp.getCoor());
304 boolean noDraw=false;
305 switch (colored) {
306 case VELOCITY:
307 double dtime = trkPnt.time - oldWp.time;
308 if(dtime > 0) {
309 color = velocityScale.getColor(dist / dtime);
310 } else {
311 color = velocityScale.getNoDataColor();
312 }
313 break;
314 case DIRECTION:
315 double dirColor = oldWp.getCoor().heading(trkPnt.getCoor());
316 color = directionScale.getColor(dirColor);
317 break;
318 case TIME:
319 double t=trkPnt.time;
320 if (t > 0 && t <= now && maxval - minval > minTrackDurationForTimeColoring) { // skip bad timestamps and very short tracks
321 color = dateScale.getColor(t);
322 } else {
323 color = dateScale.getNoDataColor();
324 }
325 break;
326 }
327 if (!noDraw && (maxLineLength == -1 || dist <= maxLineLength)) {
328 trkPnt.drawLine = true;
329 trkPnt.dir = (int) oldWp.getCoor().heading(trkPnt.getCoor());
330 } else {
331 trkPnt.drawLine = false;
332 }
333 } else { // make sure we reset outdated data
334 trkPnt.drawLine = false;
335 color = neutralColor;
336 }
337 if (color!=null) {
338 trkPnt.customColoring = color;
339 }
340 oldWp = trkPnt;
341 }
342 }
343
344 computeCacheInSync = true;
345 }
346
347
348
349 private void drawLines(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
350 if (lines) {
351 Point old = null;
352 for (WayPoint trkPnt : visibleSegments) {
353 LatLon c = trkPnt.getCoor();
354 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
355 continue;
356 }
357 Point screen = mv.getPoint(trkPnt.getEastNorth());
358 if (trkPnt.drawLine) {
359 // skip points that are on the same screenposition
360 if (old != null && ((old.x != screen.x) || (old.y != screen.y))) {
361 g.setColor(trkPnt.customColoring);
362 g.drawLine(old.x, old.y, screen.x, screen.y);
363 }
364 }
365 old = screen;
366 }
367 }
368 }
369
370 private void drawArrows(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
371 /****************************************************************
372 ********** STEP 3b - DRAW NICE ARROWS **************************
373 ****************************************************************/
374 if (lines && direction && !alternateDirection) {
375 Point old = null;
376 Point oldA = null; // last arrow painted
377 for (WayPoint trkPnt : visibleSegments) {
378 LatLon c = trkPnt.getCoor();
379 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
380 continue;
381 }
382 if (trkPnt.drawLine) {
383 Point screen = mv.getPoint(trkPnt.getEastNorth());
384 // skip points that are on the same screenposition
385 if (old != null
386 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
387 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
388 g.setColor(trkPnt.customColoring);
389 double t = Math.atan2(screen.y - old.y, screen.x - old.x) + Math.PI;
390 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t - PHI)),
391 (int) (screen.y + 10 * Math.sin(t - PHI)));
392 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t + PHI)),
393 (int) (screen.y + 10 * Math.sin(t + PHI)));
394 oldA = screen;
395 }
396 old = screen;
397 }
398 } // end for trkpnt
399 }
400
401 /****************************************************************
402 ********** STEP 3c - DRAW FAST ARROWS **************************
403 ****************************************************************/
404 if (lines && direction && alternateDirection) {
405 Point old = null;
406 Point oldA = null; // last arrow painted
407 for (WayPoint trkPnt : visibleSegments) {
408 LatLon c = trkPnt.getCoor();
409 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
410 continue;
411 }
412 if (trkPnt.drawLine) {
413 Point screen = mv.getPoint(trkPnt.getEastNorth());
414 // skip points that are on the same screenposition
415 if (old != null
416 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
417 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
418 g.setColor(trkPnt.customColoring);
419 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][0], screen.y
420 + dir[trkPnt.dir][1]);
421 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][2], screen.y
422 + dir[trkPnt.dir][3]);
423 oldA = screen;
424 }
425 old = screen;
426 }
427 } // end for trkpnt
428 }
429 }
430
431 private void drawPoints(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
432 /****************************************************************
433 ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE *********
434 ****************************************************************/
435 if (large || hdopCircle) {
436 final int halfSize = largesize/2;
437 for (WayPoint trkPnt : visibleSegments) {
438 LatLon c = trkPnt.getCoor();
439 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
440 continue;
441 }
442 Point screen = mv.getPoint(trkPnt.getEastNorth());
443
444
445 if (hdopCircle && trkPnt.attr.get("hdop") != null) {
446 // hdop value
447 float hdop = ((Float)trkPnt.attr.get("hdop"));
448 if (hdop < 0) {
449 hdop = 0;
450 }
451 Color customColoringTransparent = hdopAlpha<0 ? trkPnt.customColoring:
452 new Color(trkPnt.customColoring.getRGB() & 0x00ffffff | hdopAlpha<<24, true);
453 g.setColor(customColoringTransparent);
454 // hdop cirles
455 int hdopp = mv.getPoint(new LatLon(trkPnt.getCoor().lat(), trkPnt.getCoor().lon() + 2*6*hdop*360/40000000)).x - screen.x;
456 g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
457 }
458 if (large) {
459 // color the large GPS points like the gps lines
460 if (trkPnt.customColoring != null) {
461 Color customColoringTransparent = largePointAlpha<0 ? trkPnt.customColoring:
462 new Color(trkPnt.customColoring.getRGB() & 0x00ffffff | largePointAlpha<<24, true);
463
464 g.setColor(customColoringTransparent);
465 }
466 g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
467 }
468 } // end for trkpnt
469 } // end if large || hdopcircle
470
471 /****************************************************************
472 ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
473 ****************************************************************/
474 if (!large && lines) {
475 g.setColor(neutralColor);
476 for (WayPoint trkPnt : visibleSegments) {
477 LatLon c = trkPnt.getCoor();
478 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
479 continue;
480 }
481 if (!trkPnt.drawLine) {
482 Point screen = mv.getPoint(trkPnt.getEastNorth());
483 g.drawRect(screen.x, screen.y, 0, 0);
484 }
485 } // end for trkpnt
486 } // end if large
487
488 /****************************************************************
489 ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
490 ****************************************************************/
491 if (!large && !lines) {
492 g.setColor(neutralColor);
493 for (WayPoint trkPnt : visibleSegments) {
494 LatLon c = trkPnt.getCoor();
495 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
496 continue;
497 }
498 Point screen = mv.getPoint(trkPnt.getEastNorth());
499 g.setColor(trkPnt.customColoring);
500 g.drawRect(screen.x, screen.y, 0, 0);
501 } // end for trkpnt
502 } // end if large
503 }
504
505 /**
506 * Check cache validity set necessary flags
507 */
508 private void checkCache() {
509 if ((computeCacheMaxLineLengthUsed != maxLineLength) || (!neutralColor.equals(computeCacheColorUsed))
510 || (computeCacheColored != colored) || (computeCacheColorTracksTune != colorTracksTune)
511 || (computeCacheColorDynamic != colorModeDynamic)) {
512 computeCacheMaxLineLengthUsed = maxLineLength;
513 computeCacheInSync = false;
514 computeCacheColorUsed = neutralColor;
515 computeCacheColored = colored;
516 computeCacheColorTracksTune = colorTracksTune;
517 computeCacheColorDynamic = colorModeDynamic;
518 }
519 }
520
521 public void dataChanged() {
522 computeCacheInSync = false;
523 }
524
525 public void drawColorBar(Graphics2D g, MapView mv) {
526 int w = mv.getWidth();
527 int h = mv.getHeight();
528 if (colored == ColorMode.HDOP) {
529 hdopScale.drawColorBar(g, w-30, 50, 20, 100, 1.0);
530 } else if (colored == ColorMode.VELOCITY) {
531 velocityScale.drawColorBar(g, w-30, 50, 20, 100, 3.6);
532 } else if (colored == ColorMode.DIRECTION) {
533 directionScale.drawColorBar(g, w-30, 50, 20, 100, 180.0/Math.PI);
534 }
535 }
536
537}
Note: See TracBrowser for help on using the repository browser.