source: josm/trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java@ 7080

Last change on this file since 7080 was 7080, checked in by bastiK, 10 years ago

see #9691 - on single core machine do nothing fancy and stay in EDT - this saves some array copying; provide initial capacities for ArrayLists

  • Property svn:eol-style set to native
File size: 57.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm.visitor.paint;
3
4import java.awt.AlphaComposite;
5import java.awt.BasicStroke;
6import java.awt.Color;
7import java.awt.Component;
8import java.awt.Dimension;
9import java.awt.Font;
10import java.awt.FontMetrics;
11import java.awt.Graphics2D;
12import java.awt.Image;
13import java.awt.Point;
14import java.awt.Polygon;
15import java.awt.Rectangle;
16import java.awt.RenderingHints;
17import java.awt.Shape;
18import java.awt.TexturePaint;
19import java.awt.font.FontRenderContext;
20import java.awt.font.GlyphVector;
21import java.awt.font.LineMetrics;
22import java.awt.geom.AffineTransform;
23import java.awt.geom.GeneralPath;
24import java.awt.geom.Path2D;
25import java.awt.geom.Point2D;
26import java.awt.geom.Rectangle2D;
27import java.util.AbstractList;
28import java.util.ArrayList;
29import java.util.Collection;
30import java.util.Collections;
31import java.util.Iterator;
32import java.util.List;
33import java.util.concurrent.Callable;
34import java.util.concurrent.ExecutionException;
35import java.util.concurrent.ExecutorService;
36import java.util.concurrent.Executors;
37import java.util.concurrent.Future;
38import javax.swing.AbstractButton;
39import javax.swing.FocusManager;
40import org.openstreetmap.josm.Main;
41import org.openstreetmap.josm.data.Bounds;
42import org.openstreetmap.josm.data.coor.EastNorth;
43import org.openstreetmap.josm.data.osm.BBox;
44import org.openstreetmap.josm.data.osm.Changeset;
45import org.openstreetmap.josm.data.osm.DataSet;
46import org.openstreetmap.josm.data.osm.Node;
47import org.openstreetmap.josm.data.osm.OsmPrimitive;
48import org.openstreetmap.josm.data.osm.OsmUtils;
49import org.openstreetmap.josm.data.osm.Relation;
50import org.openstreetmap.josm.data.osm.RelationMember;
51import org.openstreetmap.josm.data.osm.Way;
52import org.openstreetmap.josm.data.osm.WaySegment;
53import org.openstreetmap.josm.data.osm.visitor.Visitor;
54import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
55import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData;
56import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
57import org.openstreetmap.josm.gui.NavigatableComponent;
58import org.openstreetmap.josm.gui.mappaint.AreaElemStyle;
59import org.openstreetmap.josm.gui.mappaint.BoxTextElemStyle;
60import org.openstreetmap.josm.gui.mappaint.BoxTextElemStyle.HorizontalTextAlignment;
61import org.openstreetmap.josm.gui.mappaint.BoxTextElemStyle.VerticalTextAlignment;
62import org.openstreetmap.josm.gui.mappaint.ElemStyle;
63import org.openstreetmap.josm.gui.mappaint.ElemStyles;
64import org.openstreetmap.josm.gui.mappaint.MapImage;
65import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
66import org.openstreetmap.josm.gui.mappaint.NodeElemStyle;
67import org.openstreetmap.josm.gui.mappaint.NodeElemStyle.Symbol;
68import org.openstreetmap.josm.gui.mappaint.RepeatImageElemStyle.LineImageAlignment;
69import org.openstreetmap.josm.gui.mappaint.StyleCache.StyleList;
70import org.openstreetmap.josm.gui.mappaint.TextElement;
71import org.openstreetmap.josm.tools.ImageProvider;
72import org.openstreetmap.josm.tools.Utils;
73
74/**
75 * <p>A map renderer which renders a map according to style rules in a set of style sheets.</p>
76 *
77 */
78public class StyledMapRenderer extends AbstractMapRenderer {
79
80 final public static int noThreads;
81 final public static ExecutorService styleCreatorPool;
82
83 static {
84 noThreads = Main.pref.getInteger(
85 "mappaint.StyledMapRenderer.style_creation.numberOfThreads",
86 Runtime.getRuntime().availableProcessors());
87 styleCreatorPool = noThreads <= 1 ? null : Executors.newFixedThreadPool(noThreads);
88 }
89
90 /**
91 * Iterates over a list of Way Nodes and returns screen coordinates that
92 * represent a line that is shifted by a certain offset perpendicular
93 * to the way direction.
94 *
95 * There is no intention, to handle consecutive duplicate Nodes in a
96 * perfect way, but it is should not throw an exception.
97 */
98 private class OffsetIterator implements Iterator<Point> {
99
100 private List<Node> nodes;
101 private float offset;
102 private int idx;
103
104 private Point prev = null;
105 /* 'prev0' is a point that has distance 'offset' from 'prev' and the
106 * line from 'prev' to 'prev0' is perpendicular to the way segment from
107 * 'prev' to the next point.
108 */
109 private int x_prev0, y_prev0;
110
111 public OffsetIterator(List<Node> nodes, float offset) {
112 this.nodes = nodes;
113 this.offset = offset;
114 idx = 0;
115 }
116
117 @Override
118 public boolean hasNext() {
119 return idx < nodes.size();
120 }
121
122 @Override
123 public Point next() {
124 if (Math.abs(offset) < 0.1f) return nc.getPoint(nodes.get(idx++));
125
126 Point current = nc.getPoint(nodes.get(idx));
127
128 if (idx == nodes.size() - 1) {
129 ++idx;
130 if (prev != null) {
131 return new Point(x_prev0 + current.x - prev.x, y_prev0 + current.y - prev.y);
132 } else {
133 return current;
134 }
135 }
136
137 Point next = nc.getPoint(nodes.get(idx+1));
138
139 int dx_next = next.x - current.x;
140 int dy_next = next.y - current.y;
141 double len_next = Math.sqrt(dx_next*dx_next + dy_next*dy_next);
142
143 if (len_next == 0) {
144 len_next = 1; // value does not matter, because dy_next and dx_next is 0
145 }
146
147 int x_current0 = current.x + (int) Math.round(offset * dy_next / len_next);
148 int y_current0 = current.y - (int) Math.round(offset * dx_next / len_next);
149
150 if (idx==0) {
151 ++idx;
152 prev = current;
153 x_prev0 = x_current0;
154 y_prev0 = y_current0;
155 return new Point(x_current0, y_current0);
156 } else {
157 int dx_prev = current.x - prev.x;
158 int dy_prev = current.y - prev.y;
159
160 // determine intersection of the lines parallel to the two
161 // segments
162 int det = dx_next*dy_prev - dx_prev*dy_next;
163
164 if (det == 0) {
165 ++idx;
166 prev = current;
167 x_prev0 = x_current0;
168 y_prev0 = y_current0;
169 return new Point(x_current0, y_current0);
170 }
171
172 int m = dx_next*(y_current0 - y_prev0) - dy_next*(x_current0 - x_prev0);
173
174 int cx_ = x_prev0 + Math.round((float)m * dx_prev / det);
175 int cy_ = y_prev0 + Math.round((float)m * dy_prev / det);
176 ++idx;
177 prev = current;
178 x_prev0 = x_current0;
179 y_prev0 = y_current0;
180 return new Point(cx_, cy_);
181 }
182 }
183
184 @Override
185 public void remove() {
186 throw new UnsupportedOperationException();
187 }
188 }
189
190 private static class StyleRecord implements Comparable<StyleRecord> {
191 final ElemStyle style;
192 final OsmPrimitive osm;
193 final int flags;
194
195 public StyleRecord(ElemStyle style, OsmPrimitive osm, int flags) {
196 this.style = style;
197 this.osm = osm;
198 this.flags = flags;
199 }
200
201 @Override
202 public int compareTo(StyleRecord other) {
203 if ((this.flags & FLAG_DISABLED) != 0 && (other.flags & FLAG_DISABLED) == 0)
204 return -1;
205 if ((this.flags & FLAG_DISABLED) == 0 && (other.flags & FLAG_DISABLED) != 0)
206 return 1;
207
208 int d0 = Float.compare(this.style.major_z_index, other.style.major_z_index);
209 if (d0 != 0)
210 return d0;
211
212 // selected on top of member of selected on top of unselected
213 // FLAG_DISABLED bit is the same at this point
214 if (this.flags > other.flags)
215 return 1;
216 if (this.flags < other.flags)
217 return -1;
218
219 int dz = Float.compare(this.style.z_index, other.style.z_index);
220 if (dz != 0)
221 return dz;
222
223 // simple node on top of icons and shapes
224 if (this.style == NodeElemStyle.SIMPLE_NODE_ELEMSTYLE && other.style != NodeElemStyle.SIMPLE_NODE_ELEMSTYLE)
225 return 1;
226 if (this.style != NodeElemStyle.SIMPLE_NODE_ELEMSTYLE && other.style == NodeElemStyle.SIMPLE_NODE_ELEMSTYLE)
227 return -1;
228
229 // newer primitives to the front
230 long id = this.osm.getUniqueId() - other.osm.getUniqueId();
231 if (id > 0)
232 return 1;
233 if (id < 0)
234 return -1;
235
236 return Float.compare(this.style.object_z_index, other.style.object_z_index);
237 }
238 }
239
240 /**
241 * Joined List build from two Lists (read-only).
242 *
243 * Extremely simple single-purpose implementation.
244 * @param <T>
245 */
246 public static class CompositeList<T> extends AbstractList<T> {
247 List<T> a,b;
248
249 public CompositeList(List<T> a, List<T> b) {
250 this.a = a;
251 this.b = b;
252 }
253
254 @Override
255 public T get(int index) {
256 return index < a.size() ? a.get(index) : b.get(index - a.size());
257 }
258
259 @Override
260 public int size() {
261 return a.size() + b.size();
262 }
263 }
264
265 private static Boolean IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG = null;
266
267 /**
268 * Check, if this System has the GlyphVector double translation bug.
269 *
270 * With this bug, <code>gv.setGlyphTransform(i, trfm)</code> has a different
271 * effect than on most other systems, namely the translation components
272 * ("m02" &amp; "m12", {@link AffineTransform}) appear to be twice as large, as
273 * they actually are. The rotation is unaffected (scale &amp; shear not tested
274 * so far).
275 *
276 * This bug has only been observed on Mac OS X, see #7841.
277 *
278 * @return true, if the GlyphVector double translation bug is present on
279 * this System
280 */
281 public static boolean isGlyphVectorDoubleTranslationBug() {
282 if (IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG != null)
283 return IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG;
284 FontRenderContext frc = new FontRenderContext(null, false, false);
285 Font font = new Font("Dialog", Font.PLAIN, 12);
286 GlyphVector gv = font.createGlyphVector(frc, "x");
287 gv.setGlyphTransform(0, AffineTransform.getTranslateInstance(1000, 1000));
288 Shape shape = gv.getGlyphOutline(0);
289 // x is about 1000 on normal stystems and about 2000 when the bug occurs
290 int x = shape.getBounds().x;
291 IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG = x > 1500;
292 return IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG;
293 }
294
295 private ElemStyles styles;
296 private double circum;
297
298 private MapPaintSettings paintSettings;
299
300 private Color relationSelectedColor;
301 private Color highlightColorTransparent;
302
303 private static final int FLAG_NORMAL = 0;
304 private static final int FLAG_DISABLED = 1;
305 private static final int FLAG_MEMBER_OF_SELECTED = 2;
306 private static final int FLAG_SELECTED = 4;
307
308 private static final double PHI = Math.toRadians(20);
309 private static final double cosPHI = Math.cos(PHI);
310 private static final double sinPHI = Math.sin(PHI);
311
312 private Collection<WaySegment> highlightWaySegments;
313
314 // highlight customization fields
315 private int highlightLineWidth;
316 private int highlightPointRadius;
317 private int widerHighlight;
318 private int highlightStep;
319
320 //flag that activate wider highlight mode
321 private boolean useWiderHighlight;
322
323 private boolean useStrokes;
324 private boolean showNames;
325 private boolean showIcons;
326 private boolean isOutlineOnly;
327
328 private Font orderFont;
329
330 private boolean leftHandTraffic;
331
332 public StyledMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
333 super(g, nc, isInactiveMode);
334
335 if (nc!=null) {
336 Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
337 useWiderHighlight = !(focusOwner instanceof AbstractButton || focusOwner == nc);
338 }
339 }
340
341 private Polygon buildPolygon(Point center, int radius, int sides) {
342 return buildPolygon(center, radius, sides, 0.0);
343 }
344
345 private Polygon buildPolygon(Point center, int radius, int sides, double rotation) {
346 Polygon polygon = new Polygon();
347 for (int i = 0; i < sides; i++) {
348 double angle = ((2 * Math.PI / sides) * i) - rotation;
349 int x = (int) Math.round(center.x + radius * Math.cos(angle));
350 int y = (int) Math.round(center.y + radius * Math.sin(angle));
351 polygon.addPoint(x, y);
352 }
353 return polygon;
354 }
355
356 private void displaySegments(GeneralPath path, GeneralPath orientationArrows, GeneralPath onewayArrows, GeneralPath onewayArrowsCasing,
357 Color color, BasicStroke line, BasicStroke dashes, Color dashedColor) {
358 g.setColor(isInactiveMode ? inactiveColor : color);
359 if (useStrokes) {
360 g.setStroke(line);
361 }
362 g.draw(path);
363
364 if(!isInactiveMode && useStrokes && dashes != null) {
365 g.setColor(dashedColor);
366 g.setStroke(dashes);
367 g.draw(path);
368 }
369
370 if (orientationArrows != null) {
371 g.setColor(isInactiveMode ? inactiveColor : color);
372 g.setStroke(new BasicStroke(line.getLineWidth(), line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
373 g.draw(orientationArrows);
374 }
375
376 if (onewayArrows != null) {
377 g.setStroke(new BasicStroke(1, line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
378 g.fill(onewayArrowsCasing);
379 g.setColor(isInactiveMode ? inactiveColor : backgroundColor);
380 g.fill(onewayArrows);
381 }
382
383 if (useStrokes) {
384 g.setStroke(new BasicStroke());
385 }
386 }
387
388 /**
389 * Displays text at specified position including its halo, if applicable.
390 *
391 * @param gv Text's glyphs to display. If {@code null}, use text from {@code s} instead.
392 * @param s text to display if {@code gv} is {@code null}
393 * @param x X position
394 * @param y Y position
395 * @param disabled {@code true} if element is disabled (filtered out)
396 * @param text text style to use
397 */
398 private void displayText(GlyphVector gv, String s, int x, int y, boolean disabled, TextElement text) {
399 if (isInactiveMode || disabled) {
400 g.setColor(inactiveColor);
401 if (gv != null) {
402 g.drawGlyphVector(gv, x, y);
403 } else {
404 g.setFont(text.font);
405 g.drawString(s, x, y);
406 }
407 } else if (text.haloRadius != null) {
408 g.setStroke(new BasicStroke(2*text.haloRadius, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
409 g.setColor(text.haloColor);
410 if (gv == null) {
411 FontRenderContext frc = g.getFontRenderContext();
412 gv = text.font.createGlyphVector(frc, s);
413 }
414 Shape textOutline = gv.getOutline(x, y);
415 g.draw(textOutline);
416 g.setStroke(new BasicStroke());
417 g.setColor(text.color);
418 g.fill(textOutline);
419 } else {
420 g.setColor(text.color);
421 if (gv != null) {
422 g.drawGlyphVector(gv, x, y);
423 } else {
424 g.setFont(text.font);
425 g.drawString(s, x, y);
426 }
427 }
428 }
429
430 protected void drawArea(OsmPrimitive osm, Path2D.Double path, Color color, MapImage fillImage, TextElement text) {
431
432 Shape area = path.createTransformedShape(nc.getAffineTransform());
433
434 if (!isOutlineOnly) {
435 if (fillImage == null) {
436 if (isInactiveMode) {
437 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.33f));
438 }
439 g.setColor(color);
440 g.fill(area);
441 } else {
442 TexturePaint texture = new TexturePaint(fillImage.getImage(),
443 new Rectangle(0, 0, fillImage.getWidth(), fillImage.getHeight()));
444 g.setPaint(texture);
445 Float alpha = Utils.color_int2float(fillImage.alpha);
446 if (alpha != 1f) {
447 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
448 }
449 g.fill(area);
450 g.setPaintMode();
451 }
452 }
453
454 if (text != null && isShowNames()) {
455 // abort if we can't compose the label to be rendered
456 if (text.labelCompositionStrategy == null) return;
457 String name = text.labelCompositionStrategy.compose(osm);
458 if (name == null) return;
459
460 Rectangle pb = area.getBounds();
461 FontMetrics fontMetrics = g.getFontMetrics(orderFont); // if slow, use cache
462 Rectangle2D nb = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
463
464 // Using the Centroid is Nicer for buildings like: +--------+
465 // but this needs to be fast. As most houses are | 42 |
466 // boxes anyway, the center of the bounding box +---++---+
467 // will have to do. ++
468 // Centroids are not optimal either, just imagine a U-shaped house.
469
470 Rectangle centeredNBounds = new Rectangle(pb.x + (int)((pb.width - nb.getWidth())/2.0),
471 pb.y + (int)((pb.height - nb.getHeight())/2.0),
472 (int)nb.getWidth(),
473 (int)nb.getHeight());
474
475 if ((pb.width >= nb.getWidth() && pb.height >= nb.getHeight()) && // quick check
476 area.contains(centeredNBounds) // slow but nice
477 ) {
478 Font defaultFont = g.getFont();
479 int x = (int)(centeredNBounds.getMinX() - nb.getMinX());
480 int y = (int)(centeredNBounds.getMinY() - nb.getMinY());
481 displayText(null, name, x, y, osm.isDisabled(), text);
482 g.setFont(defaultFont);
483 }
484 }
485 }
486
487 public void drawArea(Relation r, Color color, MapImage fillImage, TextElement text) {
488 Multipolygon multipolygon = MultipolygonCache.getInstance().get(nc, r);
489 if (!r.isDisabled() && !multipolygon.getOuterWays().isEmpty()) {
490 for (PolyData pd : multipolygon.getCombinedPolygons()) {
491 Path2D.Double p = pd.get();
492 if (!isAreaVisible(p)) {
493 continue;
494 }
495 drawArea(r, p,
496 pd.selected ? paintSettings.getRelationSelectedColor(color.getAlpha()) : color,
497 fillImage, text);
498 }
499 }
500 }
501
502 public void drawArea(Way w, Color color, MapImage fillImage, TextElement text) {
503 drawArea(w, getPath(w), color, fillImage, text);
504 }
505
506 public void drawBoxText(Node n, BoxTextElemStyle bs) {
507 if (!isShowNames() || bs == null)
508 return;
509
510 Point p = nc.getPoint(n);
511 TextElement text = bs.text;
512 String s = text.labelCompositionStrategy.compose(n);
513 if (s == null) return;
514
515 Font defaultFont = g.getFont();
516 g.setFont(text.font);
517
518 int x = p.x + text.xOffset;
519 int y = p.y + text.yOffset;
520 /**
521 *
522 * left-above __center-above___ right-above
523 * left-top| |right-top
524 * | |
525 * left-center| center-center |right-center
526 * | |
527 * left-bottom|_________________|right-bottom
528 * left-below center-below right-below
529 *
530 */
531 Rectangle box = bs.getBox();
532 if (bs.hAlign == HorizontalTextAlignment.RIGHT) {
533 x += box.x + box.width + 2;
534 } else {
535 FontRenderContext frc = g.getFontRenderContext();
536 Rectangle2D bounds = text.font.getStringBounds(s, frc);
537 int textWidth = (int) bounds.getWidth();
538 if (bs.hAlign == HorizontalTextAlignment.CENTER) {
539 x -= textWidth / 2;
540 } else if (bs.hAlign == HorizontalTextAlignment.LEFT) {
541 x -= - box.x + 4 + textWidth;
542 } else throw new AssertionError();
543 }
544
545 if (bs.vAlign == VerticalTextAlignment.BOTTOM) {
546 y += box.y + box.height;
547 } else {
548 FontRenderContext frc = g.getFontRenderContext();
549 LineMetrics metrics = text.font.getLineMetrics(s, frc);
550 if (bs.vAlign == VerticalTextAlignment.ABOVE) {
551 y -= - box.y + metrics.getDescent();
552 } else if (bs.vAlign == VerticalTextAlignment.TOP) {
553 y -= - box.y - metrics.getAscent();
554 } else if (bs.vAlign == VerticalTextAlignment.CENTER) {
555 y += (metrics.getAscent() - metrics.getDescent()) / 2;
556 } else if (bs.vAlign == VerticalTextAlignment.BELOW) {
557 y += box.y + box.height + metrics.getAscent() + 2;
558 } else throw new AssertionError();
559 }
560 displayText(null, s, x, y, n.isDisabled(), text);
561 g.setFont(defaultFont);
562 }
563
564 /**
565 * Draw an image along a way repeatedly.
566 *
567 * @param way the way
568 * @param pattern the image
569 * @param offset offset from the way
570 * @param spacing spacing between two images
571 * @param phase initial spacing
572 * @param align alignment of the image. The top, center or bottom edge
573 * can be aligned with the way.
574 */
575 public void drawRepeatImage(Way way, Image pattern, float offset, float spacing, float phase, LineImageAlignment align) {
576 final int imgWidth = pattern.getWidth(null);
577 final double repeat = imgWidth + spacing;
578 final int imgHeight = pattern.getHeight(null);
579
580 Point lastP = null;
581 double currentWayLength = phase % repeat;
582 if (currentWayLength < 0) {
583 currentWayLength += repeat;
584 }
585
586 int dy1, dy2;
587 switch (align) {
588 case TOP:
589 dy1 = 0;
590 dy2 = imgHeight;
591 break;
592 case CENTER:
593 dy1 = - imgHeight / 2;
594 dy2 = imgHeight + dy1;
595 break;
596 case BOTTOM:
597 dy1 = -imgHeight;
598 dy2 = 0;
599 break;
600 default:
601 throw new AssertionError();
602 }
603
604 OffsetIterator it = new OffsetIterator(way.getNodes(), offset);
605 while (it.hasNext()) {
606 Point thisP = it.next();
607
608 if (lastP != null) {
609 final double segmentLength = thisP.distance(lastP);
610
611 final double dx = thisP.x - lastP.x;
612 final double dy = thisP.y - lastP.y;
613
614 // pos is the position from the beginning of the current segment
615 // where an image should be painted
616 double pos = repeat - (currentWayLength % repeat);
617
618 AffineTransform saveTransform = g.getTransform();
619 g.translate(lastP.x, lastP.y);
620 g.rotate(Math.atan2(dy, dx));
621
622 // draw the rest of the image from the last segment in case it
623 // is cut off
624 if (pos > spacing) {
625 // segment is too short for a complete image
626 if (pos > segmentLength + spacing) {
627 g.drawImage(pattern, 0, dy1, (int) segmentLength, dy2,
628 (int) (repeat - pos), 0,
629 (int) (repeat - pos + segmentLength), imgHeight, null);
630 // rest of the image fits fully on the current segment
631 } else {
632 g.drawImage(pattern, 0, dy1, (int) (pos - spacing), dy2,
633 (int) (repeat - pos), 0, imgWidth, imgHeight, null);
634 }
635 }
636 // draw remaining images for this segment
637 while (pos < segmentLength) {
638 // cut off at the end?
639 if (pos + imgWidth > segmentLength) {
640 g.drawImage(pattern, (int) pos, dy1, (int) segmentLength, dy2,
641 0, 0, (int) segmentLength - (int) pos, imgHeight, null);
642 } else {
643 g.drawImage(pattern, (int) pos, dy1, nc);
644 }
645 pos += repeat;
646 }
647 g.setTransform(saveTransform);
648
649 currentWayLength += segmentLength;
650 }
651 lastP = thisP;
652 }
653 }
654
655 @Override
656 public void drawNode(Node n, Color color, int size, boolean fill) {
657 if(size <= 0 && !n.isHighlighted())
658 return;
659
660 Point p = nc.getPoint(n);
661
662 if(n.isHighlighted()) {
663 drawPointHighlight(p, size);
664 }
665
666 if (size > 1) {
667 if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth()) || (p.y > nc.getHeight())) return;
668 int radius = size / 2;
669
670 if (isInactiveMode || n.isDisabled()) {
671 g.setColor(inactiveColor);
672 } else {
673 g.setColor(color);
674 }
675 if (fill) {
676 g.fillRect(p.x-radius-1, p.y-radius-1, size + 1, size + 1);
677 } else {
678 g.drawRect(p.x-radius-1, p.y-radius-1, size, size);
679 }
680 }
681 }
682
683 public void drawNodeIcon(Node n, Image img, float alpha, boolean selected, boolean member) {
684 Point p = nc.getPoint(n);
685
686 final int w = img.getWidth(null), h=img.getHeight(null);
687 if(n.isHighlighted()) {
688 drawPointHighlight(p, Math.max(w, h));
689 }
690
691 if (alpha != 1f) {
692 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
693 }
694 g.drawImage(img, p.x-w/2, p.y-h/2, nc);
695 g.setPaintMode();
696 if (selected || member)
697 {
698 Color color;
699 if (isInactiveMode || n.isDisabled()) {
700 color = inactiveColor;
701 } else if (selected) {
702 color = selectedColor;
703 } else {
704 color = relationSelectedColor;
705 }
706 g.setColor(color);
707 g.drawRect(p.x-w/2-2, p.y-h/2-2, w+4, h+4);
708 }
709 }
710
711 public void drawNodeSymbol(Node n, Symbol s, Color fillColor, Color strokeColor) {
712 Point p = nc.getPoint(n);
713 int radius = s.size / 2;
714
715 if(n.isHighlighted()) {
716 drawPointHighlight(p, s.size);
717 }
718
719 if (fillColor != null) {
720 g.setColor(fillColor);
721 switch (s.symbol) {
722 case SQUARE:
723 g.fillRect(p.x - radius, p.y - radius, s.size, s.size);
724 break;
725 case CIRCLE:
726 g.fillOval(p.x - radius, p.y - radius, s.size, s.size);
727 break;
728 case TRIANGLE:
729 g.fillPolygon(buildPolygon(p, radius, 3, Math.PI / 2));
730 break;
731 case PENTAGON:
732 g.fillPolygon(buildPolygon(p, radius, 5, Math.PI / 2));
733 break;
734 case HEXAGON:
735 g.fillPolygon(buildPolygon(p, radius, 6));
736 break;
737 case HEPTAGON:
738 g.fillPolygon(buildPolygon(p, radius, 7, Math.PI / 2));
739 break;
740 case OCTAGON:
741 g.fillPolygon(buildPolygon(p, radius, 8, Math.PI / 8));
742 break;
743 case NONAGON:
744 g.fillPolygon(buildPolygon(p, radius, 9, Math.PI / 2));
745 break;
746 case DECAGON:
747 g.fillPolygon(buildPolygon(p, radius, 10));
748 break;
749 default:
750 throw new AssertionError();
751 }
752 }
753 if (s.stroke != null) {
754 g.setStroke(s.stroke);
755 g.setColor(strokeColor);
756 switch (s.symbol) {
757 case SQUARE:
758 g.drawRect(p.x - radius, p.y - radius, s.size - 1, s.size - 1);
759 break;
760 case CIRCLE:
761 g.drawOval(p.x - radius, p.y - radius, s.size - 1, s.size - 1);
762 break;
763 case TRIANGLE:
764 g.drawPolygon(buildPolygon(p, radius, 3, Math.PI / 2));
765 break;
766 case PENTAGON:
767 g.drawPolygon(buildPolygon(p, radius, 5, Math.PI / 2));
768 break;
769 case HEXAGON:
770 g.drawPolygon(buildPolygon(p, radius, 6));
771 break;
772 case HEPTAGON:
773 g.drawPolygon(buildPolygon(p, radius, 7, Math.PI / 2));
774 break;
775 case OCTAGON:
776 g.drawPolygon(buildPolygon(p, radius, 8, Math.PI / 8));
777 break;
778 case NONAGON:
779 g.drawPolygon(buildPolygon(p, radius, 9, Math.PI / 2));
780 break;
781 case DECAGON:
782 g.drawPolygon(buildPolygon(p, radius, 10));
783 break;
784 default:
785 throw new AssertionError();
786 }
787 g.setStroke(new BasicStroke());
788 }
789 }
790
791 /**
792 * Draw a number of the order of the two consecutive nodes within the
793 * parents way
794 */
795 public void drawOrderNumber(Node n1, Node n2, int orderNumber, Color clr) {
796 Point p1 = nc.getPoint(n1);
797 Point p2 = nc.getPoint(n2);
798 StyledMapRenderer.this.drawOrderNumber(p1, p2, orderNumber, clr);
799 }
800
801 /**
802 * highlights a given GeneralPath using the settings from BasicStroke to match the line's
803 * style. Width of the highlight is hard coded.
804 * @param path
805 * @param line
806 */
807 private void drawPathHighlight(GeneralPath path, BasicStroke line) {
808 if(path == null)
809 return;
810 g.setColor(highlightColorTransparent);
811 float w = (line.getLineWidth() + highlightLineWidth);
812 if (useWiderHighlight) w+=widerHighlight;
813 while(w >= line.getLineWidth()) {
814 g.setStroke(new BasicStroke(w, line.getEndCap(), line.getLineJoin(), line.getMiterLimit()));
815 g.draw(path);
816 w -= highlightStep;
817 }
818 }
819 /**
820 * highlights a given point by drawing a rounded rectangle around it. Give the
821 * size of the object you want to be highlighted, width is added automatically.
822 */
823 private void drawPointHighlight(Point p, int size) {
824 g.setColor(highlightColorTransparent);
825 int s = size + highlightPointRadius;
826 if (useWiderHighlight) s+=widerHighlight;
827 while(s >= size) {
828 int r = (int) Math.floor(s/2);
829 g.fillRoundRect(p.x-r, p.y-r, s, s, r, r);
830 s -= highlightStep;
831 }
832 }
833
834 public void drawRestriction(Image img, Point pVia, double vx, double vx2, double vy, double vy2, double angle, boolean selected) {
835 // rotate image with direction last node in from to, and scale down image to 16*16 pixels
836 Image smallImg = ImageProvider.createRotatedImage(img, angle, new Dimension(16, 16));
837 int w = smallImg.getWidth(null), h=smallImg.getHeight(null);
838 g.drawImage(smallImg, (int)(pVia.x+vx+vx2)-w/2, (int)(pVia.y+vy+vy2)-h/2, nc);
839
840 if (selected) {
841 g.setColor(isInactiveMode ? inactiveColor : relationSelectedColor);
842 g.drawRect((int)(pVia.x+vx+vx2)-w/2-2,(int)(pVia.y+vy+vy2)-h/2-2, w+4, h+4);
843 }
844 }
845
846 public void drawRestriction(Relation r, MapImage icon) {
847 Way fromWay = null;
848 Way toWay = null;
849 OsmPrimitive via = null;
850
851 /* find the "from", "via" and "to" elements */
852 for (RelationMember m : r.getMembers()) {
853 if(m.getMember().isIncomplete())
854 return;
855 else {
856 if(m.isWay()) {
857 Way w = m.getWay();
858 if(w.getNodesCount() < 2) {
859 continue;
860 }
861
862 switch(m.getRole()) {
863 case "from":
864 if(fromWay == null) {
865 fromWay = w;
866 }
867 break;
868 case "to":
869 if(toWay == null) {
870 toWay = w;
871 }
872 break;
873 case "via":
874 if(via == null) {
875 via = w;
876 }
877 }
878 } else if(m.isNode()) {
879 Node n = m.getNode();
880 if("via".equals(m.getRole()) && via == null) {
881 via = n;
882 }
883 }
884 }
885 }
886
887 if (fromWay == null || toWay == null || via == null)
888 return;
889
890 Node viaNode;
891 if(via instanceof Node)
892 {
893 viaNode = (Node) via;
894 if(!fromWay.isFirstLastNode(viaNode))
895 return;
896 }
897 else
898 {
899 Way viaWay = (Way) via;
900 Node firstNode = viaWay.firstNode();
901 Node lastNode = viaWay.lastNode();
902 Boolean onewayvia = false;
903
904 String onewayviastr = viaWay.get("oneway");
905 if(onewayviastr != null)
906 {
907 if("-1".equals(onewayviastr)) {
908 onewayvia = true;
909 Node tmp = firstNode;
910 firstNode = lastNode;
911 lastNode = tmp;
912 } else {
913 onewayvia = OsmUtils.getOsmBoolean(onewayviastr);
914 if (onewayvia == null) {
915 onewayvia = false;
916 }
917 }
918 }
919
920 if(fromWay.isFirstLastNode(firstNode)) {
921 viaNode = firstNode;
922 } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
923 viaNode = lastNode;
924 } else
925 return;
926 }
927
928 /* find the "direct" nodes before the via node */
929 Node fromNode;
930 if(fromWay.firstNode() == via) {
931 fromNode = fromWay.getNode(1);
932 } else {
933 fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
934 }
935
936 Point pFrom = nc.getPoint(fromNode);
937 Point pVia = nc.getPoint(viaNode);
938
939 /* starting from via, go back the "from" way a few pixels
940 (calculate the vector vx/vy with the specified length and the direction
941 away from the "via" node along the first segment of the "from" way)
942 */
943 double distanceFromVia=14;
944 double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x);
945 double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y);
946
947 double fromAngle;
948 if(dx == 0.0) {
949 fromAngle = Math.PI/2;
950 } else {
951 fromAngle = Math.atan(dy / dx);
952 }
953 double fromAngleDeg = Math.toDegrees(fromAngle);
954
955 double vx = distanceFromVia * Math.cos(fromAngle);
956 double vy = distanceFromVia * Math.sin(fromAngle);
957
958 if(pFrom.x < pVia.x) {
959 vx = -vx;
960 }
961 if(pFrom.y < pVia.y) {
962 vy = -vy;
963 }
964
965 /* go a few pixels away from the way (in a right angle)
966 (calculate the vx2/vy2 vector with the specified length and the direction
967 90degrees away from the first segment of the "from" way)
968 */
969 double distanceFromWay=10;
970 double vx2 = 0;
971 double vy2 = 0;
972 double iconAngle = 0;
973
974 if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
975 if(!leftHandTraffic) {
976 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
977 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
978 } else {
979 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
980 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
981 }
982 iconAngle = 270+fromAngleDeg;
983 }
984 if(pFrom.x < pVia.x && pFrom.y >= pVia.y) {
985 if(!leftHandTraffic) {
986 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
987 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
988 } else {
989 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
990 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
991 }
992 iconAngle = 90-fromAngleDeg;
993 }
994 if(pFrom.x < pVia.x && pFrom.y < pVia.y) {
995 if(!leftHandTraffic) {
996 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
997 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
998 } else {
999 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
1000 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
1001 }
1002 iconAngle = 90+fromAngleDeg;
1003 }
1004 if(pFrom.x >= pVia.x && pFrom.y < pVia.y) {
1005 if(!leftHandTraffic) {
1006 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
1007 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
1008 } else {
1009 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
1010 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
1011 }
1012 iconAngle = 270-fromAngleDeg;
1013 }
1014
1015 drawRestriction(isInactiveMode || r.isDisabled() ? icon.getDisabled() : icon.getImage(),
1016 pVia, vx, vx2, vy, vy2, iconAngle, r.isSelected());
1017 }
1018
1019 public void drawTextOnPath(Way way, TextElement text) {
1020 if (way == null || text == null)
1021 return;
1022 String name = text.getString(way);
1023 if (name == null || name.isEmpty())
1024 return;
1025
1026 Polygon poly = new Polygon();
1027 Point lastPoint = null;
1028 Iterator<Node> it = way.getNodes().iterator();
1029 double pathLength = 0;
1030 long dx, dy;
1031 while (it.hasNext()) {
1032 Node n = it.next();
1033 Point p = nc.getPoint(n);
1034 poly.addPoint(p.x, p.y);
1035
1036 if(lastPoint != null) {
1037 dx = p.x - lastPoint.x;
1038 dy = p.y - lastPoint.y;
1039 pathLength += Math.sqrt(dx*dx + dy*dy);
1040 }
1041 lastPoint = p;
1042 }
1043
1044 FontMetrics fontMetrics = g.getFontMetrics(text.font); // if slow, use cache
1045 Rectangle2D rec = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
1046
1047 if (rec.getWidth() > pathLength)
1048 return;
1049
1050 double t1 = (pathLength/2 - rec.getWidth()/2) / pathLength;
1051 double t2 = (pathLength/2 + rec.getWidth()/2) / pathLength;
1052
1053 double[] p1 = pointAt(t1, poly, pathLength);
1054 double[] p2 = pointAt(t2, poly, pathLength);
1055
1056 if (p1 == null || p2 == null)
1057 return;
1058
1059 double angleOffset;
1060 double offsetSign;
1061 double tStart;
1062
1063 if (p1[0] < p2[0] &&
1064 p1[2] < Math.PI/2 &&
1065 p1[2] > -Math.PI/2) {
1066 angleOffset = 0;
1067 offsetSign = 1;
1068 tStart = t1;
1069 } else {
1070 angleOffset = Math.PI;
1071 offsetSign = -1;
1072 tStart = t2;
1073 }
1074
1075 FontRenderContext frc = g.getFontRenderContext();
1076 GlyphVector gv = text.font.createGlyphVector(frc, name);
1077
1078 for (int i=0; i<gv.getNumGlyphs(); ++i) {
1079 Rectangle2D rect = gv.getGlyphLogicalBounds(i).getBounds2D();
1080 double t = tStart + offsetSign * (rect.getX() + rect.getWidth()/2) / pathLength;
1081 double[] p = pointAt(t, poly, pathLength);
1082 if (p != null) {
1083 AffineTransform trfm = AffineTransform.getTranslateInstance(p[0] - rect.getX(), p[1]);
1084 trfm.rotate(p[2]+angleOffset);
1085 double off = -rect.getY() - rect.getHeight()/2 + text.yOffset;
1086 trfm.translate(-rect.getWidth()/2, off);
1087 if (isGlyphVectorDoubleTranslationBug()) {
1088 // scale the translation components by one half
1089 AffineTransform tmp = AffineTransform.getTranslateInstance(-0.5 * trfm.getTranslateX(), -0.5 * trfm.getTranslateY());
1090 tmp.concatenate(trfm);
1091 trfm = tmp;
1092 }
1093 gv.setGlyphTransform(i, trfm);
1094 }
1095 }
1096 displayText(gv, null, 0, 0, way.isDisabled(), text);
1097 }
1098
1099 /**
1100 * draw way
1101 * @param showOrientation show arrows that indicate the technical orientation of
1102 * the way (defined by order of nodes)
1103 * @param showOneway show symbols that indicate the direction of the feature,
1104 * e.g. oneway street or waterway
1105 * @param onewayReversed for oneway=-1 and similar
1106 */
1107 public void drawWay(Way way, Color color, BasicStroke line, BasicStroke dashes, Color dashedColor, float offset,
1108 boolean showOrientation, boolean showHeadArrowOnly,
1109 boolean showOneway, boolean onewayReversed) {
1110
1111 GeneralPath path = new GeneralPath();
1112 GeneralPath orientationArrows = showOrientation ? new GeneralPath() : null;
1113 GeneralPath onewayArrows = showOneway ? new GeneralPath() : null;
1114 GeneralPath onewayArrowsCasing = showOneway ? new GeneralPath() : null;
1115 Rectangle bounds = g.getClipBounds();
1116 if (bounds != null) {
1117 // avoid arrow heads at the border
1118 bounds.grow(100, 100);
1119 }
1120
1121 double wayLength = 0;
1122 Point lastPoint = null;
1123 boolean initialMoveToNeeded = true;
1124 List<Node> wayNodes = way.getNodes();
1125 if (wayNodes.size() < 2) return;
1126
1127 // only highlight the segment if the way itself is not highlighted
1128 if (!way.isHighlighted()) {
1129 GeneralPath highlightSegs = null;
1130 for (WaySegment ws : highlightWaySegments) {
1131 if (ws.way != way || ws.lowerIndex < offset) {
1132 continue;
1133 }
1134 if(highlightSegs == null) {
1135 highlightSegs = new GeneralPath();
1136 }
1137
1138 Point p1 = nc.getPoint(ws.getFirstNode());
1139 Point p2 = nc.getPoint(ws.getSecondNode());
1140 highlightSegs.moveTo(p1.x, p1.y);
1141 highlightSegs.lineTo(p2.x, p2.y);
1142 }
1143
1144 drawPathHighlight(highlightSegs, line);
1145 }
1146
1147 Iterator<Point> it = new OffsetIterator(wayNodes, offset);
1148 while (it.hasNext()) {
1149 Point p = it.next();
1150 if (lastPoint != null) {
1151 Point p1 = lastPoint;
1152 Point p2 = p;
1153
1154 /**
1155 * Do custom clipping to work around openjdk bug. It leads to
1156 * drawing artefacts when zooming in a lot. (#4289, #4424)
1157 * (Looks like int overflow.)
1158 */
1159 LineClip clip = new LineClip(p1, p2, bounds);
1160 if (clip.execute()) {
1161 if (!p1.equals(clip.getP1())) {
1162 p1 = clip.getP1();
1163 path.moveTo(p1.x, p1.y);
1164 } else if (initialMoveToNeeded) {
1165 initialMoveToNeeded = false;
1166 path.moveTo(p1.x, p1.y);
1167 }
1168 p2 = clip.getP2();
1169 path.lineTo(p2.x, p2.y);
1170
1171 /* draw arrow */
1172 if (showHeadArrowOnly ? !it.hasNext() : showOrientation) {
1173 final double segmentLength = p1.distance(p2);
1174 if (segmentLength != 0.0) {
1175 final double l = (10. + line.getLineWidth()) / segmentLength;
1176
1177 final double sx = l * (p1.x - p2.x);
1178 final double sy = l * (p1.y - p2.y);
1179
1180 orientationArrows.moveTo (p2.x + cosPHI * sx - sinPHI * sy, p2.y + sinPHI * sx + cosPHI * sy);
1181 orientationArrows.lineTo(p2.x, p2.y);
1182 orientationArrows.lineTo (p2.x + cosPHI * sx + sinPHI * sy, p2.y - sinPHI * sx + cosPHI * sy);
1183 }
1184 }
1185 if (showOneway) {
1186 final double segmentLength = p1.distance(p2);
1187 if (segmentLength != 0.0) {
1188 final double nx = (p2.x - p1.x) / segmentLength;
1189 final double ny = (p2.y - p1.y) / segmentLength;
1190
1191 final double interval = 60;
1192 // distance from p1
1193 double dist = interval - (wayLength % interval);
1194
1195 while (dist < segmentLength) {
1196 for (int i=0; i<2; ++i) {
1197 float onewaySize = i == 0 ? 3f : 2f;
1198 GeneralPath onewayPath = i == 0 ? onewayArrowsCasing : onewayArrows;
1199
1200 // scale such that border is 1 px
1201 final double fac = - (onewayReversed ? -1 : 1) * onewaySize * (1 + sinPHI) / (sinPHI * cosPHI);
1202 final double sx = nx * fac;
1203 final double sy = ny * fac;
1204
1205 // Attach the triangle at the incenter and not at the tip.
1206 // Makes the border even at all sides.
1207 final double x = p1.x + nx * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1208 final double y = p1.y + ny * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1209
1210 onewayPath.moveTo(x, y);
1211 onewayPath.lineTo (x + cosPHI * sx - sinPHI * sy, y + sinPHI * sx + cosPHI * sy);
1212 onewayPath.lineTo (x + cosPHI * sx + sinPHI * sy, y - sinPHI * sx + cosPHI * sy);
1213 onewayPath.lineTo(x, y);
1214 }
1215 dist += interval;
1216 }
1217 }
1218 wayLength += segmentLength;
1219 }
1220 }
1221 }
1222 lastPoint = p;
1223 }
1224 if(way.isHighlighted()) {
1225 drawPathHighlight(path, line);
1226 }
1227 displaySegments(path, orientationArrows, onewayArrows, onewayArrowsCasing, color, line, dashes, dashedColor);
1228 }
1229
1230 public double getCircum() {
1231 return circum;
1232 }
1233
1234 @Override
1235 public void getColors() {
1236 super.getColors();
1237 this.relationSelectedColor = PaintColors.RELATIONSELECTED.get();
1238 this.highlightColorTransparent = new Color(highlightColor.getRed(), highlightColor.getGreen(), highlightColor.getBlue(), 100);
1239 this.backgroundColor = PaintColors.getBackgroundColor();
1240 }
1241
1242 @Override
1243 protected void getSettings(boolean virtual) {
1244 super.getSettings(virtual);
1245 paintSettings = MapPaintSettings.INSTANCE;
1246
1247 circum = nc.getDist100Pixel();
1248
1249 leftHandTraffic = Main.pref.getBoolean("mappaint.lefthandtraffic", false);
1250
1251 useStrokes = paintSettings.getUseStrokesDistance() > circum;
1252 showNames = paintSettings.getShowNamesDistance() > circum;
1253 showIcons = paintSettings.getShowIconsDistance() > circum;
1254 isOutlineOnly = paintSettings.isOutlineOnly();
1255 orderFont = new Font(Main.pref.get("mappaint.font", "Helvetica"), Font.PLAIN, Main.pref.getInteger("mappaint.fontsize", 8));
1256
1257 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1258 Main.pref.getBoolean("mappaint.use-antialiasing", true) ?
1259 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
1260
1261 highlightLineWidth = Main.pref.getInteger("mappaint.highlight.width", 4);
1262 highlightPointRadius = Main.pref.getInteger("mappaint.highlight.radius", 7);
1263 widerHighlight = Main.pref.getInteger("mappaint.highlight.bigger-increment", 5);
1264 highlightStep = Main.pref.getInteger("mappaint.highlight.step", 4);
1265 }
1266
1267 private Path2D.Double getPath(Way w) {
1268 Path2D.Double path = new Path2D.Double();
1269 boolean initial = true;
1270 for (Node n : w.getNodes()) {
1271 EastNorth p = n.getEastNorth();
1272 if (p != null) {
1273 if (initial) {
1274 path.moveTo(p.getX(), p.getY());
1275 initial = false;
1276 } else {
1277 path.lineTo(p.getX(), p.getY());
1278 }
1279 }
1280 }
1281 return path;
1282 }
1283
1284 private boolean isAreaVisible(Path2D.Double area) {
1285 Rectangle2D bounds = area.getBounds2D();
1286 if (bounds.isEmpty()) return false;
1287 Point2D p = nc.getPoint2D(new EastNorth(bounds.getX(), bounds.getY()));
1288 if (p.getX() > nc.getWidth()) return false;
1289 if (p.getY() < 0) return false;
1290 p = nc.getPoint2D(new EastNorth(bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()));
1291 if (p.getX() < 0) return false;
1292 if (p.getY() > nc.getHeight()) return false;
1293 return true;
1294 }
1295
1296 public boolean isInactiveMode() {
1297 return isInactiveMode;
1298 }
1299
1300 public boolean isShowIcons() {
1301 return showIcons;
1302 }
1303
1304 public boolean isShowNames() {
1305 return showNames;
1306 }
1307
1308 private double[] pointAt(double t, Polygon poly, double pathLength) {
1309 double totalLen = t * pathLength;
1310 double curLen = 0;
1311 long dx, dy;
1312 double segLen;
1313
1314 // Yes, it is inefficient to iterate from the beginning for each glyph.
1315 // Can be optimized if it turns out to be slow.
1316 for (int i = 1; i < poly.npoints; ++i) {
1317 dx = poly.xpoints[i] - poly.xpoints[i-1];
1318 dy = poly.ypoints[i] - poly.ypoints[i-1];
1319 segLen = Math.sqrt(dx*dx + dy*dy);
1320 if (totalLen > curLen + segLen) {
1321 curLen += segLen;
1322 continue;
1323 }
1324 return new double[] {
1325 poly.xpoints[i-1]+(totalLen - curLen)/segLen*dx,
1326 poly.ypoints[i-1]+(totalLen - curLen)/segLen*dy,
1327 Math.atan2(dy, dx)};
1328 }
1329 return null;
1330 }
1331
1332 @Override
1333 public void render(final DataSet data, boolean renderVirtualNodes, Bounds bounds) {
1334 BBox bbox = bounds.toBBox();
1335 getSettings(renderVirtualNodes);
1336
1337 final boolean drawArea = circum <= Main.pref.getInteger("mappaint.fillareas", 10000000);
1338 final boolean drawMultipolygon = drawArea && Main.pref.getBoolean("mappaint.multipolygon", true);
1339 final boolean drawRestriction = Main.pref.getBoolean("mappaint.restriction", true);
1340
1341 styles = MapPaintStyles.getStyles();
1342 styles.setDrawMultipolygon(drawMultipolygon);
1343
1344 highlightWaySegments = data.getHighlightedWaySegments();
1345
1346 long timeStart=0, timePhase1=0, timeFinished;
1347 if (Main.isTraceEnabled()) {
1348 timeStart = System.currentTimeMillis();
1349 System.err.print("BENCHMARK: rendering ");
1350 Main.debug(null);
1351 }
1352
1353 class ComputeStyleListWorker implements Callable<List<StyleRecord>>, Visitor {
1354 private final List<? extends OsmPrimitive> input;
1355 private final int from;
1356 private final int to;
1357 private final List<StyleRecord> output;
1358
1359 /**
1360 * Constructor for CreateStyleRecordsWorker.
1361 * @param input the primitives to process
1362 * @param from first index of <code>input</code> to use
1363 * @param to last index + 1
1364 */
1365 public ComputeStyleListWorker(final List<? extends OsmPrimitive> input, int from, int to, List<StyleRecord> output) {
1366 this.input = input;
1367 this.from = from;
1368 this.to = to;
1369 this.output = output;
1370 }
1371
1372 @Override
1373 public List<StyleRecord> call() throws Exception {
1374 for (int i = from; i<to; i++) {
1375 OsmPrimitive osm = input.get(i);
1376 if (osm.isDrawable()) {
1377 osm.accept(this);
1378 }
1379 }
1380 return output;
1381 }
1382
1383 @Override
1384 public void visit(Node n) {
1385 if (n.isDisabled()) {
1386 add(n, FLAG_DISABLED);
1387 } else if (data.isSelected(n)) {
1388 add(n, FLAG_SELECTED);
1389 } else if (n.isMemberOfSelected()) {
1390 add(n, FLAG_MEMBER_OF_SELECTED);
1391 } else {
1392 add(n, FLAG_NORMAL);
1393 }
1394 }
1395
1396 @Override
1397 public void visit(Way w) {
1398 if (w.isDisabled()) {
1399 add(w, FLAG_DISABLED);
1400 } else if (data.isSelected(w)) {
1401 add(w, FLAG_SELECTED);
1402 } else if (w.isMemberOfSelected()) {
1403 add(w, FLAG_MEMBER_OF_SELECTED);
1404 } else {
1405 add(w, FLAG_NORMAL);
1406 }
1407 }
1408
1409 @Override
1410 public void visit(Relation r) {
1411 if (r.isDisabled()) {
1412 add(r, FLAG_DISABLED);
1413 } else if (data.isSelected(r)) {
1414 add(r, FLAG_SELECTED);
1415 } else {
1416 add(r, FLAG_NORMAL);
1417 }
1418 }
1419
1420 @Override
1421 public void visit(Changeset cs) {
1422 throw new UnsupportedOperationException();
1423 }
1424
1425 public void add(Node osm, int flags) {
1426 StyleList sl = styles.get(osm, circum, nc);
1427 for (ElemStyle s : sl) {
1428 output.add(new StyleRecord(s, osm, flags));
1429 }
1430 }
1431
1432 public void add(Relation osm, int flags) {
1433 StyleList sl = styles.get(osm, circum, nc);
1434 for (ElemStyle s : sl) {
1435 if (drawMultipolygon && drawArea && s instanceof AreaElemStyle && (flags & FLAG_DISABLED) == 0) {
1436 output.add(new StyleRecord(s, osm, flags));
1437 } else if (drawRestriction && s instanceof NodeElemStyle) {
1438 output.add(new StyleRecord(s, osm, flags));
1439 }
1440 }
1441 }
1442
1443 public void add(Way osm, int flags) {
1444 StyleList sl = styles.get(osm, circum, nc);
1445 for (ElemStyle s : sl) {
1446 if (!(drawArea && (flags & FLAG_DISABLED) == 0) && s instanceof AreaElemStyle) {
1447 continue;
1448 }
1449 output.add(new StyleRecord(s, osm, flags));
1450 }
1451 }
1452 }
1453 List<Node> nodes = data.searchNodes(bbox);
1454 List<Way> ways = data.searchWays(bbox);
1455 List<Relation> relations = data.searchRelations(bbox);
1456
1457 final List<StyleRecord> allStyleElems = new ArrayList<>(nodes.size()+ways.size()+relations.size());
1458
1459 class ConcurrentTasksHelper {
1460
1461 void process(List<? extends OsmPrimitive> prims) {
1462 final List<ComputeStyleListWorker> tasks = new ArrayList<>();
1463 final int bucketsize = Math.max(100, prims.size()/noThreads/3);
1464 final int noBuckets = (prims.size() + bucketsize - 1) / bucketsize;
1465 final boolean singleThread = noThreads == 1 || noBuckets == 1;
1466 for (int i=0; i<noBuckets; i++) {
1467 int from = i*bucketsize;
1468 int to = Math.min((i+1)*bucketsize, prims.size());
1469 List<StyleRecord> target = singleThread ? allStyleElems : new ArrayList<StyleRecord>(to - from);
1470 tasks.add(new ComputeStyleListWorker(prims, from, to, target));
1471 }
1472 if (singleThread) {
1473 try {
1474 for (ComputeStyleListWorker task : tasks) {
1475 task.call();
1476 }
1477 } catch (Exception ex) {
1478 throw new RuntimeException(ex);
1479 }
1480 } else if (tasks.size() > 1) {
1481 try {
1482 for (Future<List<StyleRecord>> future : styleCreatorPool.invokeAll(tasks)) {
1483 allStyleElems.addAll(future.get());
1484 }
1485 } catch (InterruptedException | ExecutionException ex) {
1486 throw new RuntimeException(ex);
1487 }
1488 }
1489 }
1490 }
1491 ConcurrentTasksHelper helper = new ConcurrentTasksHelper();
1492
1493 // Need to process all relations first.
1494 // Reason: Make sure, ElemStyles.getStyleCacheWithRange is
1495 // not called for the same primtive in parallel threads.
1496 // (Could be synchronized, but try to avoid this for
1497 // performance reasons.)
1498 helper.process(relations);
1499 @SuppressWarnings("unchecked")
1500 List<OsmPrimitive> nodesAndWays = (List) new CompositeList(nodes, ways);
1501 helper.process(nodesAndWays);
1502
1503 if (Main.isTraceEnabled()) {
1504 timePhase1 = System.currentTimeMillis();
1505 System.err.print("phase 1 (calculate styles): " + (timePhase1 - timeStart) + " ms");
1506 }
1507
1508 Collections.sort(allStyleElems);
1509
1510 for (StyleRecord r : allStyleElems) {
1511 r.style.paintPrimitive(
1512 r.osm,
1513 paintSettings,
1514 StyledMapRenderer.this,
1515 (r.flags & FLAG_SELECTED) != 0,
1516 (r.flags & FLAG_MEMBER_OF_SELECTED) != 0
1517 );
1518 }
1519
1520 if (Main.isTraceEnabled()) {
1521 timeFinished = System.currentTimeMillis();
1522 System.err.println("; phase 2 (draw): " + (timeFinished - timePhase1) + " ms; total: " + (timeFinished - timeStart) + " ms");
1523 }
1524
1525 drawVirtualNodes(data, bbox);
1526 }
1527}
Note: See TracBrowser for help on using the repository browser.