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

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

sonar - squid:S1172 - Unused method parameters should be removed

  • Property svn:eol-style set to native
File size: 69.0 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.Rectangle;
15import java.awt.RenderingHints;
16import java.awt.Shape;
17import java.awt.TexturePaint;
18import java.awt.font.FontRenderContext;
19import java.awt.font.GlyphVector;
20import java.awt.font.LineMetrics;
21import java.awt.font.TextLayout;
22import java.awt.geom.AffineTransform;
23import java.awt.geom.Path2D;
24import java.awt.geom.Point2D;
25import java.awt.geom.Rectangle2D;
26import java.awt.geom.RoundRectangle2D;
27import java.awt.image.BufferedImage;
28import java.util.ArrayList;
29import java.util.Collection;
30import java.util.Collections;
31import java.util.HashMap;
32import java.util.Iterator;
33import java.util.List;
34import java.util.Map;
35import java.util.Optional;
36import java.util.concurrent.ForkJoinPool;
37import java.util.concurrent.ForkJoinTask;
38import java.util.concurrent.RecursiveTask;
39import java.util.function.BiConsumer;
40import java.util.function.Consumer;
41import java.util.function.Supplier;
42
43import javax.swing.AbstractButton;
44import javax.swing.FocusManager;
45
46import org.openstreetmap.josm.Main;
47import org.openstreetmap.josm.data.Bounds;
48import org.openstreetmap.josm.data.coor.EastNorth;
49import org.openstreetmap.josm.data.osm.BBox;
50import org.openstreetmap.josm.data.osm.Changeset;
51import org.openstreetmap.josm.data.osm.DataSet;
52import org.openstreetmap.josm.data.osm.Node;
53import org.openstreetmap.josm.data.osm.OsmPrimitive;
54import org.openstreetmap.josm.data.osm.OsmUtils;
55import org.openstreetmap.josm.data.osm.Relation;
56import org.openstreetmap.josm.data.osm.RelationMember;
57import org.openstreetmap.josm.data.osm.Way;
58import org.openstreetmap.josm.data.osm.WaySegment;
59import org.openstreetmap.josm.data.osm.visitor.Visitor;
60import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
61import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData;
62import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
63import org.openstreetmap.josm.data.preferences.AbstractProperty;
64import org.openstreetmap.josm.data.preferences.BooleanProperty;
65import org.openstreetmap.josm.data.preferences.IntegerProperty;
66import org.openstreetmap.josm.data.preferences.StringProperty;
67import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
68import org.openstreetmap.josm.gui.NavigatableComponent;
69import org.openstreetmap.josm.gui.draw.MapViewPath;
70import org.openstreetmap.josm.gui.draw.MapViewPositionAndRotation;
71import org.openstreetmap.josm.gui.mappaint.ElemStyles;
72import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
73import org.openstreetmap.josm.gui.mappaint.StyleElementList;
74import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
75import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement;
76import org.openstreetmap.josm.gui.mappaint.styleelement.AreaIconElement;
77import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement;
78import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.HorizontalTextAlignment;
79import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.VerticalTextAlignment;
80import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
81import org.openstreetmap.josm.gui.mappaint.styleelement.NodeElement;
82import org.openstreetmap.josm.gui.mappaint.styleelement.RepeatImageElement.LineImageAlignment;
83import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
84import org.openstreetmap.josm.gui.mappaint.styleelement.Symbol;
85import org.openstreetmap.josm.gui.mappaint.styleelement.TextElement;
86import org.openstreetmap.josm.gui.mappaint.styleelement.TextLabel;
87import org.openstreetmap.josm.gui.mappaint.styleelement.placement.PositionForAreaStrategy;
88import org.openstreetmap.josm.tools.CompositeList;
89import org.openstreetmap.josm.tools.Geometry;
90import org.openstreetmap.josm.tools.Geometry.AreaAndPerimeter;
91import org.openstreetmap.josm.tools.ImageProvider;
92import org.openstreetmap.josm.tools.JosmRuntimeException;
93import org.openstreetmap.josm.tools.Utils;
94import org.openstreetmap.josm.tools.bugreport.BugReport;
95
96/**
97 * A map renderer which renders a map according to style rules in a set of style sheets.
98 * @since 486
99 */
100public class StyledMapRenderer extends AbstractMapRenderer {
101
102 private static final ForkJoinPool THREAD_POOL =
103 Utils.newForkJoinPool("mappaint.StyledMapRenderer.style_creation.numberOfThreads", "styled-map-renderer-%d", Thread.NORM_PRIORITY);
104
105 /**
106 * This stores a style and a primitive that should be painted with that style.
107 */
108 public static class StyleRecord implements Comparable<StyleRecord> {
109 private final StyleElement style;
110 private final OsmPrimitive osm;
111 private final int flags;
112
113 StyleRecord(StyleElement style, OsmPrimitive osm, int flags) {
114 this.style = style;
115 this.osm = osm;
116 this.flags = flags;
117 }
118
119 @Override
120 public int compareTo(StyleRecord other) {
121 if ((this.flags & FLAG_DISABLED) != 0 && (other.flags & FLAG_DISABLED) == 0)
122 return -1;
123 if ((this.flags & FLAG_DISABLED) == 0 && (other.flags & FLAG_DISABLED) != 0)
124 return 1;
125
126 int d0 = Float.compare(this.style.majorZIndex, other.style.majorZIndex);
127 if (d0 != 0)
128 return d0;
129
130 // selected on top of member of selected on top of unselected
131 // FLAG_DISABLED bit is the same at this point
132 if (this.flags > other.flags)
133 return 1;
134 if (this.flags < other.flags)
135 return -1;
136
137 int dz = Float.compare(this.style.zIndex, other.style.zIndex);
138 if (dz != 0)
139 return dz;
140
141 // simple node on top of icons and shapes
142 if (NodeElement.SIMPLE_NODE_ELEMSTYLE.equals(this.style) && !NodeElement.SIMPLE_NODE_ELEMSTYLE.equals(other.style))
143 return 1;
144 if (!NodeElement.SIMPLE_NODE_ELEMSTYLE.equals(this.style) && NodeElement.SIMPLE_NODE_ELEMSTYLE.equals(other.style))
145 return -1;
146
147 // newer primitives to the front
148 long id = this.osm.getUniqueId() - other.osm.getUniqueId();
149 if (id > 0)
150 return 1;
151 if (id < 0)
152 return -1;
153
154 return Float.compare(this.style.objectZIndex, other.style.objectZIndex);
155 }
156
157 /**
158 * Get the style for this style element.
159 * @return The style
160 */
161 public StyleElement getStyle() {
162 return style;
163 }
164
165 /**
166 * Paints the primitive with the style.
167 * @param paintSettings The settings to use.
168 * @param painter The painter to paint the style.
169 */
170 public void paintPrimitive(MapPaintSettings paintSettings, StyledMapRenderer painter) {
171 style.paintPrimitive(
172 osm,
173 paintSettings,
174 painter,
175 (flags & FLAG_SELECTED) != 0,
176 (flags & FLAG_OUTERMEMBER_OF_SELECTED) != 0,
177 (flags & FLAG_MEMBER_OF_SELECTED) != 0
178 );
179 }
180
181 @Override
182 public String toString() {
183 return "StyleRecord [style=" + style + ", osm=" + osm + ", flags=" + flags + "]";
184 }
185 }
186
187 private static Map<Font, Boolean> IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG = new HashMap<>();
188
189 /**
190 * Check, if this System has the GlyphVector double translation bug.
191 *
192 * With this bug, <code>gv.setGlyphTransform(i, trfm)</code> has a different
193 * effect than on most other systems, namely the translation components
194 * ("m02" &amp; "m12", {@link AffineTransform}) appear to be twice as large, as
195 * they actually are. The rotation is unaffected (scale &amp; shear not tested
196 * so far).
197 *
198 * This bug has only been observed on Mac OS X, see #7841.
199 *
200 * After switch to Java 7, this test is a false positive on Mac OS X (see #10446),
201 * i.e. it returns true, but the real rendering code does not require any special
202 * handling.
203 * It hasn't been further investigated why the test reports a wrong result in
204 * this case, but the method has been changed to simply return false by default.
205 * (This can be changed with a setting in the advanced preferences.)
206 *
207 * @param font The font to check.
208 * @return false by default, but depends on the value of the advanced
209 * preference glyph-bug=false|true|auto, where auto is the automatic detection
210 * method which apparently no longer gives a useful result for Java 7.
211 */
212 public static boolean isGlyphVectorDoubleTranslationBug(Font font) {
213 Boolean cached = IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.get(font);
214 if (cached != null)
215 return cached;
216 String overridePref = Main.pref.get("glyph-bug", "auto");
217 if ("auto".equals(overridePref)) {
218 FontRenderContext frc = new FontRenderContext(null, false, false);
219 GlyphVector gv = font.createGlyphVector(frc, "x");
220 gv.setGlyphTransform(0, AffineTransform.getTranslateInstance(1000, 1000));
221 Shape shape = gv.getGlyphOutline(0);
222 if (Main.isTraceEnabled()) {
223 Main.trace("#10446: shape: "+shape.getBounds());
224 }
225 // x is about 1000 on normal stystems and about 2000 when the bug occurs
226 int x = shape.getBounds().x;
227 boolean isBug = x > 1500;
228 IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.put(font, isBug);
229 return isBug;
230 } else {
231 boolean override = Boolean.parseBoolean(overridePref);
232 IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.put(font, override);
233 return override;
234 }
235 }
236
237 private double circum;
238 private double scale;
239
240 private MapPaintSettings paintSettings;
241
242 private Color highlightColorTransparent;
243
244 /**
245 * Flags used to store the primitive state along with the style. This is the normal style.
246 * <p>
247 * Not used in any public interfaces.
248 */
249 private static final int FLAG_NORMAL = 0;
250 /**
251 * A primitive with {@link OsmPrimitive#isDisabled()}
252 */
253 private static final int FLAG_DISABLED = 1;
254 /**
255 * A primitive with {@link OsmPrimitive#isMemberOfSelected()}
256 */
257 private static final int FLAG_MEMBER_OF_SELECTED = 2;
258 /**
259 * A primitive with {@link OsmPrimitive#isSelected()}
260 */
261 private static final int FLAG_SELECTED = 4;
262 /**
263 * A primitive with {@link OsmPrimitive#isOuterMemberOfSelected()}
264 */
265 private static final int FLAG_OUTERMEMBER_OF_SELECTED = 8;
266
267 private static final double PHI = Math.toRadians(20);
268 private static final double cosPHI = Math.cos(PHI);
269 private static final double sinPHI = Math.sin(PHI);
270 /**
271 * If we should use left hand traffic.
272 */
273 private static final AbstractProperty<Boolean> PREFERENCE_LEFT_HAND_TRAFFIC
274 = new BooleanProperty("mappaint.lefthandtraffic", false).cached();
275 /**
276 * Indicates that the renderer should enable anti-aliasing
277 * @since 11758
278 */
279 public static final AbstractProperty<Boolean> PREFERENCE_ANTIALIASING_USE
280 = new BooleanProperty("mappaint.use-antialiasing", true).cached();
281 /**
282 * The mode that is used for anti-aliasing
283 * @since 11758
284 */
285 public static final AbstractProperty<String> PREFERENCE_TEXT_ANTIALIASING
286 = new StringProperty("mappaint.text-antialiasing", "default").cached();
287
288 /**
289 * The line with to use for highlighting
290 */
291 private static final AbstractProperty<Integer> HIGHLIGHT_LINE_WIDTH = new IntegerProperty("mappaint.highlight.width", 4).cached();
292 private static final AbstractProperty<Integer> HIGHLIGHT_POINT_RADIUS = new IntegerProperty("mappaint.highlight.radius", 7).cached();
293 private static final AbstractProperty<Integer> WIDER_HIGHLIGHT = new IntegerProperty("mappaint.highlight.bigger-increment", 5).cached();
294 private static final AbstractProperty<Integer> HIGHLIGHT_STEP = new IntegerProperty("mappaint.highlight.step", 4).cached();
295
296 private Collection<WaySegment> highlightWaySegments;
297
298 //flag that activate wider highlight mode
299 private boolean useWiderHighlight;
300
301 private boolean useStrokes;
302 private boolean showNames;
303 private boolean showIcons;
304 private boolean isOutlineOnly;
305
306 private boolean leftHandTraffic;
307 private Object antialiasing;
308
309 private Supplier<RenderBenchmarkCollector> benchmarkFactory = RenderBenchmarkCollector.defaultBenchmarkSupplier();
310
311 /**
312 * Constructs a new {@code StyledMapRenderer}.
313 *
314 * @param g the graphics context. Must not be null.
315 * @param nc the map viewport. Must not be null.
316 * @param isInactiveMode if true, the paint visitor shall render OSM objects such that they
317 * look inactive. Example: rendering of data in an inactive layer using light gray as color only.
318 * @throws IllegalArgumentException if {@code g} is null
319 * @throws IllegalArgumentException if {@code nc} is null
320 */
321 public StyledMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
322 super(g, nc, isInactiveMode);
323
324 if (nc != null) {
325 Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
326 useWiderHighlight = !(focusOwner instanceof AbstractButton || focusOwner == nc);
327 }
328 }
329
330 private void displaySegments(MapViewPath path, Path2D orientationArrows, Path2D onewayArrows, Path2D onewayArrowsCasing,
331 Color color, BasicStroke line, BasicStroke dashes, Color dashedColor) {
332 g.setColor(isInactiveMode ? inactiveColor : color);
333 if (useStrokes) {
334 g.setStroke(line);
335 }
336 g.draw(path.computeClippedLine(g.getStroke()));
337
338 if (!isInactiveMode && useStrokes && dashes != null) {
339 g.setColor(dashedColor);
340 g.setStroke(dashes);
341 g.draw(path.computeClippedLine(dashes));
342 }
343
344 if (orientationArrows != null) {
345 g.setColor(isInactiveMode ? inactiveColor : color);
346 g.setStroke(new BasicStroke(line.getLineWidth(), line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
347 g.draw(orientationArrows);
348 }
349
350 if (onewayArrows != null) {
351 g.setStroke(new BasicStroke(1, line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
352 g.fill(onewayArrowsCasing);
353 g.setColor(isInactiveMode ? inactiveColor : backgroundColor);
354 g.fill(onewayArrows);
355 }
356
357 if (useStrokes) {
358 g.setStroke(new BasicStroke());
359 }
360 }
361
362 /**
363 * Worker function for drawing areas.
364 *
365 * @param path the path object for the area that should be drawn; in case
366 * of multipolygons, this can path can be a complex shape with one outer
367 * polygon and one or more inner polygons
368 * @param color The color to fill the area with.
369 * @param fillImage The image to fill the area with. Overrides color.
370 * @param extent if not null, area will be filled partially; specifies, how
371 * far to fill from the boundary towards the center of the area;
372 * if null, area will be filled completely
373 * @param pfClip clipping area for partial fill (only needed for unclosed
374 * polygons)
375 * @param disabled If this should be drawn with a special disabled style.
376 * @param text Ignored. Use {@link #drawText(OsmPrimitive, TextLabel)} instead.
377 */
378 protected void drawArea(MapViewPath path, Color color,
379 MapImage fillImage, Float extent, Path2D.Double pfClip, boolean disabled, TextLabel text) {
380 if (!isOutlineOnly && color.getAlpha() != 0) {
381 Shape area = path;
382 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
383 if (fillImage == null) {
384 if (isInactiveMode) {
385 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.33f));
386 }
387 g.setColor(color);
388 if (extent == null) {
389 g.fill(area);
390 } else {
391 Shape oldClip = g.getClip();
392 Shape clip = area;
393 if (pfClip != null) {
394 clip = pfClip.createTransformedShape(mapState.getAffineTransform());
395 }
396 g.clip(clip);
397 g.setStroke(new BasicStroke(2 * extent, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 4));
398 g.draw(area);
399 g.setClip(oldClip);
400 }
401 } else {
402 TexturePaint texture = new TexturePaint(fillImage.getImage(disabled),
403 new Rectangle(0, 0, fillImage.getWidth(), fillImage.getHeight()));
404 g.setPaint(texture);
405 Float alpha = fillImage.getAlphaFloat();
406 if (!Utils.equalsEpsilon(alpha, 1f)) {
407 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
408 }
409 if (extent == null) {
410 g.fill(area);
411 } else {
412 Shape oldClip = g.getClip();
413 BasicStroke stroke = new BasicStroke(2 * extent, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
414 g.clip(stroke.createStrokedShape(area));
415 Shape fill = area;
416 if (pfClip != null) {
417 fill = pfClip.createTransformedShape(mapState.getAffineTransform());
418 }
419 g.fill(fill);
420 g.setClip(oldClip);
421 }
422 g.setPaintMode();
423 }
424 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
425 }
426 }
427
428 /**
429 * Draws a multipolygon area.
430 * @param r The multipolygon relation
431 * @param color The color to fill the area with.
432 * @param fillImage The image to fill the area with. Overrides color.
433 * @param extent if not null, area will be filled partially; specifies, how
434 * far to fill from the boundary towards the center of the area;
435 * if null, area will be filled completely
436 * @param extentThreshold if not null, determines if the partial filled should
437 * be replaced by plain fill, when it covers a certain fraction of the total area
438 * @param disabled If this should be drawn with a special disabled style.
439 * @param text The text to write on the area.
440 */
441 public void drawArea(Relation r, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled, TextLabel text) {
442 Multipolygon multipolygon = MultipolygonCache.getInstance().get(r);
443 if (!r.isDisabled() && !multipolygon.getOuterWays().isEmpty()) {
444 for (PolyData pd : multipolygon.getCombinedPolygons()) {
445 if (!isAreaVisible(pd.get())) {
446 continue;
447 }
448 MapViewPath p = new MapViewPath(mapState);
449 p.appendFromEastNorth(pd.get());
450 p.setWindingRule(Path2D.WIND_EVEN_ODD);
451 Path2D.Double pfClip = null;
452 if (extent != null) {
453 if (!usePartialFill(pd.getAreaAndPerimeter(null), extent, extentThreshold)) {
454 extent = null;
455 } else if (!pd.isClosed()) {
456 pfClip = getPFClip(pd, extent * scale);
457 }
458 }
459 drawArea(p,
460 pd.isSelected() ? paintSettings.getRelationSelectedColor(color.getAlpha()) : color,
461 fillImage, extent, pfClip, disabled, text);
462 }
463 }
464 }
465
466 /**
467 * Draws an area defined by a way. They way does not need to be closed, but it should.
468 * @param w The way.
469 * @param color The color to fill the area with.
470 * @param fillImage The image to fill the area with. Overrides color.
471 * @param extent if not null, area will be filled partially; specifies, how
472 * far to fill from the boundary towards the center of the area;
473 * if null, area will be filled completely
474 * @param extentThreshold if not null, determines if the partial filled should
475 * be replaced by plain fill, when it covers a certain fraction of the total area
476 * @param disabled If this should be drawn with a special disabled style.
477 * @param text The text to write on the area.
478 */
479 public void drawArea(Way w, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled, TextLabel text) {
480 Path2D.Double pfClip = null;
481 if (extent != null) {
482 if (!usePartialFill(Geometry.getAreaAndPerimeter(w.getNodes()), extent, extentThreshold)) {
483 extent = null;
484 } else if (!w.isClosed()) {
485 pfClip = getPFClip(w, extent * scale);
486 }
487 }
488 drawArea(getPath(w), color, fillImage, extent, pfClip, disabled, text);
489 }
490
491 /**
492 * Determine, if partial fill should be turned off for this object, because
493 * only a small unfilled gap in the center of the area would be left.
494 *
495 * This is used to get a cleaner look for urban regions with many small
496 * areas like buildings, etc.
497 * @param ap the area and the perimeter of the object
498 * @param extent the "width" of partial fill
499 * @param threshold when the partial fill covers that much of the total
500 * area, the partial fill is turned off; can be greater than 100% as the
501 * covered area is estimated as <code>perimeter * extent</code>
502 * @return true, if the partial fill should be used, false otherwise
503 */
504 private boolean usePartialFill(AreaAndPerimeter ap, float extent, Float threshold) {
505 if (threshold == null) return true;
506 return ap.getPerimeter() * extent * scale < threshold * ap.getArea();
507 }
508
509 /**
510 * Draw a text onto a node
511 * @param n The node to draw the text on
512 * @param bs The text and it's alignment.
513 */
514 public void drawBoxText(Node n, BoxTextElement bs) {
515 if (!isShowNames() || bs == null)
516 return;
517
518 MapViewPoint p = mapState.getPointFor(n);
519 TextLabel text = bs.text;
520 String s = text.labelCompositionStrategy.compose(n);
521 if (s == null || s.isEmpty()) return;
522
523 Font defaultFont = g.getFont();
524 g.setFont(text.font);
525
526 FontRenderContext frc = g.getFontRenderContext();
527 Rectangle2D bounds = text.font.getStringBounds(s, frc);
528
529 double x = Math.round(p.getInViewX()) + text.xOffset + bounds.getCenterX();
530 double y = Math.round(p.getInViewY()) + text.yOffset + bounds.getCenterY();
531 /**
532 *
533 * left-above __center-above___ right-above
534 * left-top| |right-top
535 * | |
536 * left-center| center-center |right-center
537 * | |
538 * left-bottom|_________________|right-bottom
539 * left-below center-below right-below
540 *
541 */
542 Rectangle box = bs.getBox();
543 if (bs.hAlign == HorizontalTextAlignment.RIGHT) {
544 x += box.x + box.width + 2;
545 } else {
546 int textWidth = (int) bounds.getWidth();
547 if (bs.hAlign == HorizontalTextAlignment.CENTER) {
548 x -= textWidth / 2;
549 } else if (bs.hAlign == HorizontalTextAlignment.LEFT) {
550 x -= -box.x + 4 + textWidth;
551 } else throw new AssertionError();
552 }
553
554 if (bs.vAlign == VerticalTextAlignment.BOTTOM) {
555 y += box.y + box.height;
556 } else {
557 LineMetrics metrics = text.font.getLineMetrics(s, frc);
558 if (bs.vAlign == VerticalTextAlignment.ABOVE) {
559 y -= -box.y + (int) metrics.getDescent();
560 } else if (bs.vAlign == VerticalTextAlignment.TOP) {
561 y -= -box.y - (int) metrics.getAscent();
562 } else if (bs.vAlign == VerticalTextAlignment.CENTER) {
563 y += (int) ((metrics.getAscent() - metrics.getDescent()) / 2);
564 } else if (bs.vAlign == VerticalTextAlignment.BELOW) {
565 y += box.y + box.height + (int) metrics.getAscent() + 2;
566 } else throw new AssertionError();
567 }
568
569 displayText(n, text, s, bounds, new MapViewPositionAndRotation(mapState.getForView(x, y), 0));
570 g.setFont(defaultFont);
571 }
572
573 /**
574 * Draw an image along a way repeatedly.
575 *
576 * @param way the way
577 * @param pattern the image
578 * @param disabled If this should be drawn with a special disabled style.
579 * @param offset offset from the way
580 * @param spacing spacing between two images
581 * @param phase initial spacing
582 * @param align alignment of the image. The top, center or bottom edge can be aligned with the way.
583 */
584 public void drawRepeatImage(Way way, MapImage pattern, boolean disabled, double offset, double spacing, double phase,
585 LineImageAlignment align) {
586 final int imgWidth = pattern.getWidth();
587 final double repeat = imgWidth + spacing;
588 final int imgHeight = pattern.getHeight();
589
590 int dy1 = (int) ((align.getAlignmentOffset() - .5) * imgHeight);
591 int dy2 = dy1 + imgHeight;
592
593 OffsetIterator it = new OffsetIterator(mapState, way.getNodes(), offset);
594 MapViewPath path = new MapViewPath(mapState);
595 if (it.hasNext()) {
596 path.moveTo(it.next());
597 }
598 while (it.hasNext()) {
599 path.lineTo(it.next());
600 }
601
602 double startOffset = phase % repeat;
603 if (startOffset < 0) {
604 startOffset += repeat;
605 }
606
607 BufferedImage image = pattern.getImage(disabled);
608
609 path.visitClippedLine(startOffset, repeat, (inLineOffset, start, end, startIsOldEnd) -> {
610 final double segmentLength = start.distanceToInView(end);
611 if (segmentLength < 0.1) {
612 // avoid odd patterns when zoomed out.
613 return;
614 }
615 if (segmentLength > repeat * 500) {
616 // simply skip drawing so many images - something must be wrong.
617 return;
618 }
619 AffineTransform saveTransform = g.getTransform();
620 g.translate(start.getInViewX(), start.getInViewY());
621 double dx = end.getInViewX() - start.getInViewX();
622 double dy = end.getInViewY() - start.getInViewY();
623 g.rotate(Math.atan2(dy, dx));
624
625 // The start of the next image
626 double imageStart = -(inLineOffset % repeat);
627
628 while (imageStart < segmentLength) {
629 int x = (int) imageStart;
630 int sx1 = Math.max(0, -x);
631 int sx2 = imgWidth - Math.max(0, x + imgWidth - (int) Math.ceil(segmentLength));
632 g.drawImage(image, x + sx1, dy1, x + sx2, dy2, sx1, 0, sx2, imgHeight, null);
633 imageStart += repeat;
634 }
635
636 g.setTransform(saveTransform);
637 });
638 }
639
640 @Override
641 public void drawNode(Node n, Color color, int size, boolean fill) {
642 if (size <= 0 && !n.isHighlighted())
643 return;
644
645 MapViewPoint p = mapState.getPointFor(n);
646
647 if (n.isHighlighted()) {
648 drawPointHighlight(p.getInView(), size);
649 }
650
651 if (size > 1 && p.isInView()) {
652 int radius = size / 2;
653
654 if (isInactiveMode || n.isDisabled()) {
655 g.setColor(inactiveColor);
656 } else {
657 g.setColor(color);
658 }
659 Rectangle2D rect = new Rectangle2D.Double(p.getInViewX()-radius-1, p.getInViewY()-radius-1, size + 1, size + 1);
660 if (fill) {
661 g.fill(rect);
662 } else {
663 g.draw(rect);
664 }
665 }
666 }
667
668 /**
669 * Draw the icon for a given node.
670 * @param n The node
671 * @param img The icon to draw at the node position
672 * @param disabled {@code} true to render disabled version, {@code false} for the standard version
673 * @param selected {@code} true to render it as selected, {@code false} otherwise
674 * @param member {@code} true to render it as a relation member, {@code false} otherwise
675 * @param theta the angle of rotation in radians
676 */
677 public void drawNodeIcon(Node n, MapImage img, boolean disabled, boolean selected, boolean member, double theta) {
678 MapViewPoint p = mapState.getPointFor(n);
679
680 int w = img.getWidth();
681 int h = img.getHeight();
682 if (n.isHighlighted()) {
683 drawPointHighlight(p.getInView(), Math.max(w, h));
684 }
685
686 drawIcon(p, img, disabled, selected, member, theta, (g, r) -> {
687 Color color = getSelectionHintColor(disabled, selected);
688 g.setColor(color);
689 g.draw(r);
690 });
691 }
692
693
694 /**
695 * Draw the icon for a given area. Normally, the icon is drawn around the center of the area.
696 * @param osm The primitive to draw the icon for
697 * @param img The icon to draw
698 * @param disabled {@code} true to render disabled version, {@code false} for the standard version
699 * @param selected {@code} true to render it as selected, {@code false} otherwise
700 * @param member {@code} true to render it as a relation member, {@code false} otherwise
701 * @param theta the angle of rotation in radians
702 * @param iconPosition Where to place the icon.
703 * @since 11670
704 */
705 public void drawAreaIcon(OsmPrimitive osm, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
706 PositionForAreaStrategy iconPosition) {
707 Rectangle2D.Double iconRect = new Rectangle2D.Double(-img.getWidth() / 2.0, -img.getHeight() / 2.0, img.getWidth(), img.getHeight());
708
709 forEachPolygon(osm, path -> {
710 MapViewPositionAndRotation placement = iconPosition.findLabelPlacement(path, iconRect);
711 if (placement == null) {
712 return;
713 }
714 MapViewPoint p = placement.getPoint();
715 drawIcon(p, img, disabled, selected, member, theta + placement.getRotation(), (g, r) -> {
716 if (useStrokes) {
717 g.setStroke(new BasicStroke(2));
718 }
719 // only draw a minor highlighting, so that users do not confuse this for a point.
720 Color color = getSelectionHintColor(disabled, selected);
721 color = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (color.getAlpha() * .2));
722 g.setColor(color);
723 g.draw(r);
724 });
725 });
726 }
727
728 private void drawIcon(MapViewPoint p, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
729 BiConsumer<Graphics2D, Rectangle2D> selectionDrawer) {
730 float alpha = img.getAlphaFloat();
731
732 Graphics2D temporaryGraphics = (Graphics2D) g.create();
733 if (!Utils.equalsEpsilon(alpha, 1f)) {
734 temporaryGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
735 }
736
737 double x = Math.round(p.getInViewX());
738 double y = Math.round(p.getInViewY());
739 temporaryGraphics.translate(x, y);
740 temporaryGraphics.rotate(theta);
741 int drawX = -img.getWidth() / 2 + img.offsetX;
742 int drawY = -img.getHeight() / 2 + img.offsetY;
743 temporaryGraphics.drawImage(img.getImage(disabled), drawX, drawY, nc);
744 if (selected || member) {
745 selectionDrawer.accept(temporaryGraphics, new Rectangle2D.Double(drawX - 2, drawY - 2, img.getWidth() + 4, img.getHeight() + 4));
746 }
747 }
748
749 private Color getSelectionHintColor(boolean disabled, boolean selected) {
750 Color color;
751 if (disabled) {
752 color = inactiveColor;
753 } else if (selected) {
754 color = selectedColor;
755 } else {
756 color = relationSelectedColor;
757 }
758 return color;
759 }
760
761 /**
762 * Draw the symbol and possibly a highlight marking on a given node.
763 * @param n The position to draw the symbol on
764 * @param s The symbol to draw
765 * @param fillColor The color to fill the symbol with
766 * @param strokeColor The color to use for the outer corner of the symbol
767 */
768 public void drawNodeSymbol(Node n, Symbol s, Color fillColor, Color strokeColor) {
769 MapViewPoint p = mapState.getPointFor(n);
770
771 if (n.isHighlighted()) {
772 drawPointHighlight(p.getInView(), s.size);
773 }
774
775 if (fillColor != null || strokeColor != null) {
776 Shape shape = s.buildShapeAround(p.getInViewX(), p.getInViewY());
777
778 if (fillColor != null) {
779 g.setColor(fillColor);
780 g.fill(shape);
781 }
782 if (s.stroke != null) {
783 g.setStroke(s.stroke);
784 g.setColor(strokeColor);
785 g.draw(shape);
786 g.setStroke(new BasicStroke());
787 }
788 }
789 }
790
791 /**
792 * Draw a number of the order of the two consecutive nodes within the
793 * parents way
794 *
795 * @param n1 First node of the way segment.
796 * @param n2 Second node of the way segment.
797 * @param orderNumber The number of the segment in the way.
798 * @param clr The color to use for drawing the text.
799 */
800 public void drawOrderNumber(Node n1, Node n2, int orderNumber, Color clr) {
801 MapViewPoint p1 = mapState.getPointFor(n1);
802 MapViewPoint p2 = mapState.getPointFor(n2);
803 drawOrderNumber(p1, p2, orderNumber, clr);
804 }
805
806 /**
807 * highlights a given GeneralPath using the settings from BasicStroke to match the line's
808 * style. Width of the highlight can be changed by user preferences
809 * @param path path to draw
810 * @param line line style
811 */
812 private void drawPathHighlight(MapViewPath path, BasicStroke line) {
813 if (path == null)
814 return;
815 g.setColor(highlightColorTransparent);
816 float w = line.getLineWidth() + HIGHLIGHT_LINE_WIDTH.get();
817 if (useWiderHighlight) {
818 w += WIDER_HIGHLIGHT.get();
819 }
820 int step = Math.max(HIGHLIGHT_STEP.get(), 1);
821 while (w >= line.getLineWidth()) {
822 g.setStroke(new BasicStroke(w, line.getEndCap(), line.getLineJoin(), line.getMiterLimit()));
823 g.draw(path);
824 w -= step;
825 }
826 }
827
828 /**
829 * highlights a given point by drawing a rounded rectangle around it. Give the
830 * size of the object you want to be highlighted, width is added automatically.
831 * @param p point
832 * @param size highlight size
833 */
834 private void drawPointHighlight(Point2D p, int size) {
835 g.setColor(highlightColorTransparent);
836 int s = size + HIGHLIGHT_POINT_RADIUS.get();
837 if (useWiderHighlight) {
838 s += WIDER_HIGHLIGHT.get();
839 }
840 int step = Math.max(HIGHLIGHT_STEP.get(), 1);
841 while (s >= size) {
842 int r = (int) Math.floor(s/2d);
843 g.fill(new RoundRectangle2D.Double(p.getX()-r, p.getY()-r, s, s, r, r));
844 s -= step;
845 }
846 }
847
848 public void drawRestriction(Image img, Point pVia, double vx, double vx2, double vy, double vy2, double angle, boolean selected) {
849 // rotate image with direction last node in from to, and scale down image to 16*16 pixels
850 Image smallImg = ImageProvider.createRotatedImage(img, angle, new Dimension(16, 16));
851 int w = smallImg.getWidth(null), h = smallImg.getHeight(null);
852 g.drawImage(smallImg, (int) (pVia.x+vx+vx2)-w/2, (int) (pVia.y+vy+vy2)-h/2, nc);
853
854 if (selected) {
855 g.setColor(isInactiveMode ? inactiveColor : relationSelectedColor);
856 g.drawRect((int) (pVia.x+vx+vx2)-w/2-2, (int) (pVia.y+vy+vy2)-h/2-2, w+4, h+4);
857 }
858 }
859
860 public void drawRestriction(Relation r, MapImage icon, boolean disabled) {
861 Way fromWay = null;
862 Way toWay = null;
863 OsmPrimitive via = null;
864
865 /* find the "from", "via" and "to" elements */
866 for (RelationMember m : r.getMembers()) {
867 if (m.getMember().isIncomplete())
868 return;
869 else {
870 if (m.isWay()) {
871 Way w = m.getWay();
872 if (w.getNodesCount() < 2) {
873 continue;
874 }
875
876 switch(m.getRole()) {
877 case "from":
878 if (fromWay == null) {
879 fromWay = w;
880 }
881 break;
882 case "to":
883 if (toWay == null) {
884 toWay = w;
885 }
886 break;
887 case "via":
888 if (via == null) {
889 via = w;
890 }
891 break;
892 default: // Do nothing
893 }
894 } else if (m.isNode()) {
895 Node n = m.getNode();
896 if (via == null && "via".equals(m.getRole())) {
897 via = n;
898 }
899 }
900 }
901 }
902
903 if (fromWay == null || toWay == null || via == null)
904 return;
905
906 Node viaNode;
907 if (via instanceof Node) {
908 viaNode = (Node) via;
909 if (!fromWay.isFirstLastNode(viaNode))
910 return;
911 } else {
912 Way viaWay = (Way) via;
913 Node firstNode = viaWay.firstNode();
914 Node lastNode = viaWay.lastNode();
915 Boolean onewayvia = Boolean.FALSE;
916
917 String onewayviastr = viaWay.get("oneway");
918 if (onewayviastr != null) {
919 if ("-1".equals(onewayviastr)) {
920 onewayvia = Boolean.TRUE;
921 Node tmp = firstNode;
922 firstNode = lastNode;
923 lastNode = tmp;
924 } else {
925 onewayvia = Optional.ofNullable(OsmUtils.getOsmBoolean(onewayviastr)).orElse(Boolean.FALSE);
926 }
927 }
928
929 if (fromWay.isFirstLastNode(firstNode)) {
930 viaNode = firstNode;
931 } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
932 viaNode = lastNode;
933 } else
934 return;
935 }
936
937 /* find the "direct" nodes before the via node */
938 Node fromNode;
939 if (fromWay.firstNode() == via) {
940 fromNode = fromWay.getNode(1);
941 } else {
942 fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
943 }
944
945 Point pFrom = nc.getPoint(fromNode);
946 Point pVia = nc.getPoint(viaNode);
947
948 /* starting from via, go back the "from" way a few pixels
949 (calculate the vector vx/vy with the specified length and the direction
950 away from the "via" node along the first segment of the "from" way)
951 */
952 double distanceFromVia = 14;
953 double dx = pFrom.x >= pVia.x ? pFrom.x - pVia.x : pVia.x - pFrom.x;
954 double dy = pFrom.y >= pVia.y ? pFrom.y - pVia.y : pVia.y - pFrom.y;
955
956 double fromAngle;
957 if (dx == 0) {
958 fromAngle = Math.PI/2;
959 } else {
960 fromAngle = Math.atan(dy / dx);
961 }
962 double fromAngleDeg = Math.toDegrees(fromAngle);
963
964 double vx = distanceFromVia * Math.cos(fromAngle);
965 double vy = distanceFromVia * Math.sin(fromAngle);
966
967 if (pFrom.x < pVia.x) {
968 vx = -vx;
969 }
970 if (pFrom.y < pVia.y) {
971 vy = -vy;
972 }
973
974 /* go a few pixels away from the way (in a right angle)
975 (calculate the vx2/vy2 vector with the specified length and the direction
976 90degrees away from the first segment of the "from" way)
977 */
978 double distanceFromWay = 10;
979 double vx2 = 0;
980 double vy2 = 0;
981 double iconAngle = 0;
982
983 if (pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
984 if (!leftHandTraffic) {
985 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
986 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
987 } else {
988 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
989 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
990 }
991 iconAngle = 270+fromAngleDeg;
992 }
993 if (pFrom.x < pVia.x && pFrom.y >= pVia.y) {
994 if (!leftHandTraffic) {
995 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
996 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
997 } else {
998 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
999 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
1000 }
1001 iconAngle = 90-fromAngleDeg;
1002 }
1003 if (pFrom.x < pVia.x && pFrom.y < pVia.y) {
1004 if (!leftHandTraffic) {
1005 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
1006 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
1007 } else {
1008 vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
1009 vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
1010 }
1011 iconAngle = 90+fromAngleDeg;
1012 }
1013 if (pFrom.x >= pVia.x && pFrom.y < pVia.y) {
1014 if (!leftHandTraffic) {
1015 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
1016 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
1017 } else {
1018 vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
1019 vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
1020 }
1021 iconAngle = 270-fromAngleDeg;
1022 }
1023
1024 drawRestriction(icon.getImage(disabled),
1025 pVia, vx, vx2, vy, vy2, iconAngle, r.isSelected());
1026 }
1027
1028 /**
1029 * Draws a text for the given primitive
1030 * @param osm The primitive to draw the text for
1031 * @param text The text definition (font/position/.../text content) to draw.
1032 * @since 11722
1033 */
1034 public void drawText(OsmPrimitive osm, TextLabel text) {
1035 if (!isShowNames()) {
1036 return;
1037 }
1038 String name = text.getString(osm);
1039 if (name == null || name.isEmpty()) {
1040 return;
1041 }
1042
1043 FontMetrics fontMetrics = g.getFontMetrics(text.font); // if slow, use cache
1044 Rectangle2D nb = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
1045
1046 Font defaultFont = g.getFont();
1047 forEachPolygon(osm, path -> {
1048 //TODO: Ignore areas that are out of bounds.
1049 PositionForAreaStrategy position = text.getLabelPositionStrategy();
1050 MapViewPositionAndRotation center = position.findLabelPlacement(path, nb);
1051 if (center != null) {
1052 displayText(osm, text, name, nb, center);
1053 } else if (position.supportsGlyphVector()) {
1054 List<GlyphVector> gvs = Utils.getGlyphVectorsBidi(name, text.font, g.getFontRenderContext());
1055
1056 List<GlyphVector> translatedGvs = position.generateGlyphVectors(path, nb, gvs, isGlyphVectorDoubleTranslationBug(text.font));
1057 displayText(() -> translatedGvs.forEach(gv -> g.drawGlyphVector(gv, 0, 0)),
1058 () -> translatedGvs.stream().collect(
1059 Path2D.Double::new,
1060 (p, gv) -> p.append(gv.getOutline(0, 0), false),
1061 (p1, p2) -> p1.append(p2, false)),
1062 osm.isDisabled(), text);
1063 } else if (Main.isTraceEnabled()) {
1064 Main.trace("Couldn't find a correct label placement for " + osm + " / " + name);
1065 }
1066 });
1067 g.setFont(defaultFont);
1068 }
1069
1070 private void displayText(OsmPrimitive osm, TextLabel text, String name, Rectangle2D nb,
1071 MapViewPositionAndRotation center) {
1072 AffineTransform at = new AffineTransform();
1073 if (Math.abs(center.getRotation()) < .01) {
1074 // Explicitly no rotation: move to full pixels.
1075 at.setToTranslation(Math.round(center.getPoint().getInViewX() - nb.getCenterX()),
1076 Math.round(center.getPoint().getInViewY() - nb.getCenterY()));
1077 } else {
1078 at.setToTranslation(center.getPoint().getInViewX(), center.getPoint().getInViewY());
1079 at.rotate(center.getRotation());
1080 at.translate(-nb.getCenterX(), -nb.getCenterY());
1081 }
1082 displayText(() -> {
1083 AffineTransform defaultTransform = g.getTransform();
1084 g.setTransform(at);
1085 g.setFont(text.font);
1086 g.drawString(name, 0, 0);
1087 g.setTransform(defaultTransform);
1088 }, () -> {
1089 FontRenderContext frc = g.getFontRenderContext();
1090 TextLayout tl = new TextLayout(name, text.font, frc);
1091 return tl.getOutline(at);
1092 }, osm.isDisabled(), text);
1093 }
1094
1095 /**
1096 * Displays text at specified position including its halo, if applicable.
1097 *
1098 * @param fill The function that fills the text
1099 * @param outline The function to draw the outline
1100 * @param disabled {@code true} if element is disabled (filtered out)
1101 * @param text text style to use
1102 */
1103 private void displayText(Runnable fill, Supplier<Shape> outline, boolean disabled, TextLabel text) {
1104 if (isInactiveMode || disabled) {
1105 g.setColor(inactiveColor);
1106 fill.run();
1107 } else if (text.haloRadius != null) {
1108 g.setStroke(new BasicStroke(2*text.haloRadius, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
1109 g.setColor(text.haloColor);
1110 Shape textOutline = outline.get();
1111 g.draw(textOutline);
1112 g.setStroke(new BasicStroke());
1113 g.setColor(text.color);
1114 g.fill(textOutline);
1115 } else {
1116 g.setColor(text.color);
1117 fill.run();
1118 }
1119 }
1120
1121 /**
1122 * Calls a consumer for each path of the area shape-
1123 * @param osm A way or a multipolygon
1124 * @param consumer The consumer to call.
1125 */
1126 private void forEachPolygon(OsmPrimitive osm, Consumer<MapViewPath> consumer) {
1127 if (osm instanceof Way) {
1128 consumer.accept(getPath((Way) osm));
1129 } else if (osm instanceof Relation) {
1130 Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) osm);
1131 if (!multipolygon.getOuterWays().isEmpty()) {
1132 for (PolyData pd : multipolygon.getCombinedPolygons()) {
1133 MapViewPath path = new MapViewPath(mapState);
1134 path.appendFromEastNorth(pd.get());
1135 path.setWindingRule(MapViewPath.WIND_EVEN_ODD);
1136 consumer.accept(path);
1137 }
1138 }
1139 }
1140 }
1141
1142 /**
1143 * Draws a text along a given way.
1144 * @param way The way to draw the text on.
1145 * @param text The text definition (font/.../text content) to draw.
1146 * @deprecated Use {@link #drawText(OsmPrimitive, TextLabel)} instead.
1147 */
1148 @Deprecated
1149 public void drawTextOnPath(Way way, TextLabel text) {
1150 // NOP.
1151 }
1152
1153 /**
1154 * draw way. This method allows for two draw styles (line using color, dashes using dashedColor) to be passed.
1155 * @param way The way to draw
1156 * @param color The base color to draw the way in
1157 * @param line The line style to use. This is drawn using color.
1158 * @param dashes The dash style to use. This is drawn using dashedColor. <code>null</code> if unused.
1159 * @param dashedColor The color of the dashes.
1160 * @param offset The offset
1161 * @param showOrientation show arrows that indicate the technical orientation of
1162 * the way (defined by order of nodes)
1163 * @param showHeadArrowOnly True if only the arrow at the end of the line but not those on the segments should be displayed.
1164 * @param showOneway show symbols that indicate the direction of the feature,
1165 * e.g. oneway street or waterway
1166 * @param onewayReversed for oneway=-1 and similar
1167 */
1168 public void drawWay(Way way, Color color, BasicStroke line, BasicStroke dashes, Color dashedColor, float offset,
1169 boolean showOrientation, boolean showHeadArrowOnly,
1170 boolean showOneway, boolean onewayReversed) {
1171
1172 MapViewPath path = new MapViewPath(mapState);
1173 MapViewPath orientationArrows = showOrientation ? new MapViewPath(mapState) : null;
1174 MapViewPath onewayArrows;
1175 MapViewPath onewayArrowsCasing;
1176 Rectangle bounds = g.getClipBounds();
1177 if (bounds != null) {
1178 // avoid arrow heads at the border
1179 bounds.grow(100, 100);
1180 }
1181
1182 List<Node> wayNodes = way.getNodes();
1183 if (wayNodes.size() < 2) return;
1184
1185 // only highlight the segment if the way itself is not highlighted
1186 if (!way.isHighlighted() && highlightWaySegments != null) {
1187 MapViewPath highlightSegs = null;
1188 for (WaySegment ws : highlightWaySegments) {
1189 if (ws.way != way || ws.lowerIndex < offset) {
1190 continue;
1191 }
1192 if (highlightSegs == null) {
1193 highlightSegs = new MapViewPath(mapState);
1194 }
1195
1196 highlightSegs.moveTo(ws.getFirstNode());
1197 highlightSegs.lineTo(ws.getSecondNode());
1198 }
1199
1200 drawPathHighlight(highlightSegs, line);
1201 }
1202
1203 MapViewPoint lastPoint = null;
1204 Iterator<MapViewPoint> it = new OffsetIterator(mapState, wayNodes, offset);
1205 boolean initialMoveToNeeded = true;
1206 while (it.hasNext()) {
1207 MapViewPoint p = it.next();
1208 if (lastPoint != null) {
1209 MapViewPoint p1 = lastPoint;
1210 MapViewPoint p2 = p;
1211
1212 if (initialMoveToNeeded) {
1213 initialMoveToNeeded = false;
1214 path.moveTo(p1);
1215 }
1216 path.lineTo(p2);
1217
1218 /* draw arrow */
1219 if (showHeadArrowOnly ? !it.hasNext() : showOrientation) {
1220 //TODO: Cache
1221 ArrowPaintHelper drawHelper = new ArrowPaintHelper(PHI, 10 + line.getLineWidth());
1222 drawHelper.paintArrowAt(orientationArrows, p2, p1);
1223 }
1224 }
1225 lastPoint = p;
1226 }
1227 if (showOneway) {
1228 onewayArrows = new MapViewPath(mapState);
1229 onewayArrowsCasing = new MapViewPath(mapState);
1230 double interval = 60;
1231
1232 path.visitClippedLine(0, 60, (inLineOffset, start, end, startIsOldEnd) -> {
1233 double segmentLength = start.distanceToInView(end);
1234 if (segmentLength > 0.001) {
1235 final double nx = (end.getInViewX() - start.getInViewX()) / segmentLength;
1236 final double ny = (end.getInViewY() - start.getInViewY()) / segmentLength;
1237
1238 // distance from p1
1239 double dist = interval - (inLineOffset % interval);
1240
1241 while (dist < segmentLength) {
1242 appenOnewayPath(onewayReversed, start, nx, ny, dist, 3d, onewayArrowsCasing);
1243 appenOnewayPath(onewayReversed, start, nx, ny, dist, 2d, onewayArrows);
1244 dist += interval;
1245 }
1246 }
1247 });
1248 } else {
1249 onewayArrows = null;
1250 onewayArrowsCasing = null;
1251 }
1252
1253 if (way.isHighlighted()) {
1254 drawPathHighlight(path, line);
1255 }
1256 displaySegments(path, orientationArrows, onewayArrows, onewayArrowsCasing, color, line, dashes, dashedColor);
1257 }
1258
1259 private static void appenOnewayPath(boolean onewayReversed, MapViewPoint p1, double nx, double ny, double dist,
1260 double onewaySize, Path2D onewayPath) {
1261 // scale such that border is 1 px
1262 final double fac = -(onewayReversed ? -1 : 1) * onewaySize * (1 + sinPHI) / (sinPHI * cosPHI);
1263 final double sx = nx * fac;
1264 final double sy = ny * fac;
1265
1266 // Attach the triangle at the incenter and not at the tip.
1267 // Makes the border even at all sides.
1268 final double x = p1.getInViewX() + nx * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1269 final double y = p1.getInViewY() + ny * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1270
1271 onewayPath.moveTo(x, y);
1272 onewayPath.lineTo(x + cosPHI * sx - sinPHI * sy, y + sinPHI * sx + cosPHI * sy);
1273 onewayPath.lineTo(x + cosPHI * sx + sinPHI * sy, y - sinPHI * sx + cosPHI * sy);
1274 onewayPath.lineTo(x, y);
1275 }
1276
1277 /**
1278 * Gets the "circum". This is the distance on the map in meters that 100 screen pixels represent.
1279 * @return The "circum"
1280 */
1281 public double getCircum() {
1282 return circum;
1283 }
1284
1285 @Override
1286 public void getColors() {
1287 super.getColors();
1288 this.highlightColorTransparent = new Color(highlightColor.getRed(), highlightColor.getGreen(), highlightColor.getBlue(), 100);
1289 this.backgroundColor = PaintColors.getBackgroundColor();
1290 }
1291
1292 @Override
1293 public void getSettings(boolean virtual) {
1294 super.getSettings(virtual);
1295 paintSettings = MapPaintSettings.INSTANCE;
1296
1297 circum = nc.getDist100Pixel();
1298 scale = nc.getScale();
1299
1300 leftHandTraffic = PREFERENCE_LEFT_HAND_TRAFFIC.get();
1301
1302 useStrokes = paintSettings.getUseStrokesDistance() > circum;
1303 showNames = paintSettings.getShowNamesDistance() > circum;
1304 showIcons = paintSettings.getShowIconsDistance() > circum;
1305 isOutlineOnly = paintSettings.isOutlineOnly();
1306
1307 antialiasing = PREFERENCE_ANTIALIASING_USE.get() ?
1308 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF;
1309 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
1310
1311 Object textAntialiasing;
1312 switch (PREFERENCE_TEXT_ANTIALIASING.get()) {
1313 case "on":
1314 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
1315 break;
1316 case "off":
1317 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
1318 break;
1319 case "gasp":
1320 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_GASP;
1321 break;
1322 case "lcd-hrgb":
1323 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
1324 break;
1325 case "lcd-hbgr":
1326 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR;
1327 break;
1328 case "lcd-vrgb":
1329 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB;
1330 break;
1331 case "lcd-vbgr":
1332 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR;
1333 break;
1334 default:
1335 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT;
1336 }
1337 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing);
1338 }
1339
1340 private MapViewPath getPath(Way w) {
1341 MapViewPath path = new MapViewPath(mapState);
1342 if (w.isClosed()) {
1343 path.appendClosed(w.getNodes(), false);
1344 } else {
1345 path.append(w.getNodes(), false);
1346 }
1347 return path;
1348 }
1349
1350 private static Path2D.Double getPFClip(Way w, double extent) {
1351 Path2D.Double clip = new Path2D.Double();
1352 buildPFClip(clip, w.getNodes(), extent);
1353 return clip;
1354 }
1355
1356 private static Path2D.Double getPFClip(PolyData pd, double extent) {
1357 Path2D.Double clip = new Path2D.Double();
1358 clip.setWindingRule(Path2D.WIND_EVEN_ODD);
1359 buildPFClip(clip, pd.getNodes(), extent);
1360 for (PolyData pdInner : pd.getInners()) {
1361 buildPFClip(clip, pdInner.getNodes(), extent);
1362 }
1363 return clip;
1364 }
1365
1366 /**
1367 * Fix the clipping area of unclosed polygons for partial fill.
1368 *
1369 * The current algorithm for partial fill simply strokes the polygon with a
1370 * large stroke width after masking the outside with a clipping area.
1371 * This works, but for unclosed polygons, the mask can crop the corners at
1372 * both ends (see #12104).
1373 *
1374 * This method fixes the clipping area by sort of adding the corners to the
1375 * clip outline.
1376 *
1377 * @param clip the clipping area to modify (initially empty)
1378 * @param nodes nodes of the polygon
1379 * @param extent the extent
1380 */
1381 private static void buildPFClip(Path2D.Double clip, List<Node> nodes, double extent) {
1382 boolean initial = true;
1383 for (Node n : nodes) {
1384 EastNorth p = n.getEastNorth();
1385 if (p != null) {
1386 if (initial) {
1387 clip.moveTo(p.getX(), p.getY());
1388 initial = false;
1389 } else {
1390 clip.lineTo(p.getX(), p.getY());
1391 }
1392 }
1393 }
1394 if (nodes.size() >= 3) {
1395 EastNorth fst = nodes.get(0).getEastNorth();
1396 EastNorth snd = nodes.get(1).getEastNorth();
1397 EastNorth lst = nodes.get(nodes.size() - 1).getEastNorth();
1398 EastNorth lbo = nodes.get(nodes.size() - 2).getEastNorth();
1399
1400 EastNorth cLst = getPFDisplacedEndPoint(lbo, lst, fst, extent);
1401 EastNorth cFst = getPFDisplacedEndPoint(snd, fst, cLst != null ? cLst : lst, extent);
1402 if (cLst == null && cFst != null) {
1403 cLst = getPFDisplacedEndPoint(lbo, lst, cFst, extent);
1404 }
1405 if (cLst != null) {
1406 clip.lineTo(cLst.getX(), cLst.getY());
1407 }
1408 if (cFst != null) {
1409 clip.lineTo(cFst.getX(), cFst.getY());
1410 }
1411 }
1412 }
1413
1414 /**
1415 * Get the point to add to the clipping area for partial fill of unclosed polygons.
1416 *
1417 * <code>(p1,p2)</code> is the first or last way segment and <code>p3</code> the
1418 * opposite endpoint.
1419 *
1420 * @param p1 1st point
1421 * @param p2 2nd point
1422 * @param p3 3rd point
1423 * @param extent the extent
1424 * @return a point q, such that p1,p2,q form a right angle
1425 * and the distance of q to p2 is <code>extent</code>. The point q lies on
1426 * the same side of the line p1,p2 as the point p3.
1427 * Returns null if p1,p2,p3 forms an angle greater 90 degrees. (In this case
1428 * the corner of the partial fill would not be cut off by the mask, so an
1429 * additional point is not necessary.)
1430 */
1431 private static EastNorth getPFDisplacedEndPoint(EastNorth p1, EastNorth p2, EastNorth p3, double extent) {
1432 double dx1 = p2.getX() - p1.getX();
1433 double dy1 = p2.getY() - p1.getY();
1434 double dx2 = p3.getX() - p2.getX();
1435 double dy2 = p3.getY() - p2.getY();
1436 if (dx1 * dx2 + dy1 * dy2 < 0) {
1437 double len = Math.sqrt(dx1 * dx1 + dy1 * dy1);
1438 if (len == 0) return null;
1439 double dxm = -dy1 * extent / len;
1440 double dym = dx1 * extent / len;
1441 if (dx1 * dy2 - dx2 * dy1 < 0) {
1442 dxm = -dxm;
1443 dym = -dym;
1444 }
1445 return new EastNorth(p2.getX() + dxm, p2.getY() + dym);
1446 }
1447 return null;
1448 }
1449
1450 /**
1451 * Test if the area is visible
1452 * @param area The area, interpreted in east/north space.
1453 * @return true if it is visible.
1454 */
1455 private boolean isAreaVisible(Path2D.Double area) {
1456 Rectangle2D bounds = area.getBounds2D();
1457 if (bounds.isEmpty()) return false;
1458 MapViewPoint p = mapState.getPointFor(new EastNorth(bounds.getX(), bounds.getY()));
1459 if (p.getInViewX() > mapState.getViewWidth()) return false;
1460 if (p.getInViewY() < 0) return false;
1461 p = mapState.getPointFor(new EastNorth(bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()));
1462 if (p.getInViewX() < 0) return false;
1463 if (p.getInViewY() > mapState.getViewHeight()) return false;
1464 return true;
1465 }
1466
1467 public boolean isInactiveMode() {
1468 return isInactiveMode;
1469 }
1470
1471 public boolean isShowIcons() {
1472 return showIcons;
1473 }
1474
1475 public boolean isShowNames() {
1476 return showNames;
1477 }
1478
1479 /**
1480 * Computes the flags for a given OSM primitive.
1481 * @param primitive The primititve to compute the flags for.
1482 * @param checkOuterMember <code>true</code> if we should also add {@link #FLAG_OUTERMEMBER_OF_SELECTED}
1483 * @return The flag.
1484 */
1485 public static int computeFlags(OsmPrimitive primitive, boolean checkOuterMember) {
1486 if (primitive.isDisabled()) {
1487 return FLAG_DISABLED;
1488 } else if (primitive.isSelected()) {
1489 return FLAG_SELECTED;
1490 } else if (checkOuterMember && primitive.isOuterMemberOfSelected()) {
1491 return FLAG_OUTERMEMBER_OF_SELECTED;
1492 } else if (primitive.isMemberOfSelected()) {
1493 return FLAG_MEMBER_OF_SELECTED;
1494 } else {
1495 return FLAG_NORMAL;
1496 }
1497 }
1498
1499 private static class ComputeStyleListWorker extends RecursiveTask<List<StyleRecord>> implements Visitor {
1500 private final transient List<? extends OsmPrimitive> input;
1501 private final transient List<StyleRecord> output;
1502
1503 private final transient ElemStyles styles = MapPaintStyles.getStyles();
1504 private final int directExecutionTaskSize;
1505 private final double circum;
1506 private final NavigatableComponent nc;
1507
1508 private final boolean drawArea;
1509 private final boolean drawMultipolygon;
1510 private final boolean drawRestriction;
1511
1512 /**
1513 * Constructs a new {@code ComputeStyleListWorker}.
1514 * @param circum distance on the map in meters that 100 screen pixels represent
1515 * @param nc navigatable component
1516 * @param input the primitives to process
1517 * @param output the list of styles to which styles will be added
1518 * @param directExecutionTaskSize the threshold deciding whether to subdivide the tasks
1519 */
1520 ComputeStyleListWorker(double circum, NavigatableComponent nc,
1521 final List<? extends OsmPrimitive> input, List<StyleRecord> output, int directExecutionTaskSize) {
1522 this.circum = circum;
1523 this.nc = nc;
1524 this.input = input;
1525 this.output = output;
1526 this.directExecutionTaskSize = directExecutionTaskSize;
1527 this.drawArea = circum <= Main.pref.getInteger("mappaint.fillareas", 10_000_000);
1528 this.drawMultipolygon = drawArea && Main.pref.getBoolean("mappaint.multipolygon", true);
1529 this.drawRestriction = Main.pref.getBoolean("mappaint.restriction", true);
1530 this.styles.setDrawMultipolygon(drawMultipolygon);
1531 }
1532
1533 @Override
1534 protected List<StyleRecord> compute() {
1535 if (input.size() <= directExecutionTaskSize) {
1536 return computeDirectly();
1537 } else {
1538 final Collection<ForkJoinTask<List<StyleRecord>>> tasks = new ArrayList<>();
1539 for (int fromIndex = 0; fromIndex < input.size(); fromIndex += directExecutionTaskSize) {
1540 final int toIndex = Math.min(fromIndex + directExecutionTaskSize, input.size());
1541 final List<StyleRecord> output = new ArrayList<>(directExecutionTaskSize);
1542 tasks.add(new ComputeStyleListWorker(circum, nc, input.subList(fromIndex, toIndex), output, directExecutionTaskSize).fork());
1543 }
1544 for (ForkJoinTask<List<StyleRecord>> task : tasks) {
1545 output.addAll(task.join());
1546 }
1547 return output;
1548 }
1549 }
1550
1551 public List<StyleRecord> computeDirectly() {
1552 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().lock();
1553 try {
1554 for (final OsmPrimitive osm : input) {
1555 acceptDrawable(osm);
1556 }
1557 return output;
1558 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1559 throw BugReport.intercept(e).put("input-size", input.size()).put("output-size", output.size());
1560 } finally {
1561 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().unlock();
1562 }
1563 }
1564
1565 private void acceptDrawable(final OsmPrimitive osm) {
1566 try {
1567 if (osm.isDrawable()) {
1568 osm.accept(this);
1569 }
1570 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1571 throw BugReport.intercept(e).put("osm", osm);
1572 }
1573 }
1574
1575 @Override
1576 public void visit(Node n) {
1577 add(n, computeFlags(n, false));
1578 }
1579
1580 @Override
1581 public void visit(Way w) {
1582 add(w, computeFlags(w, true));
1583 }
1584
1585 @Override
1586 public void visit(Relation r) {
1587 add(r, computeFlags(r, true));
1588 }
1589
1590 @Override
1591 public void visit(Changeset cs) {
1592 throw new UnsupportedOperationException();
1593 }
1594
1595 public void add(Node osm, int flags) {
1596 StyleElementList sl = styles.get(osm, circum, nc);
1597 for (StyleElement s : sl) {
1598 output.add(new StyleRecord(s, osm, flags));
1599 }
1600 }
1601
1602 public void add(Relation osm, int flags) {
1603 StyleElementList sl = styles.get(osm, circum, nc);
1604 for (StyleElement s : sl) {
1605 if (drawMultipolygon && drawArea && (s instanceof AreaElement || s instanceof AreaIconElement) && (flags & FLAG_DISABLED) == 0) {
1606 output.add(new StyleRecord(s, osm, flags));
1607 } else if (drawMultipolygon && drawArea && s instanceof TextElement) {
1608 output.add(new StyleRecord(s, osm, flags));
1609 } else if (drawRestriction && s instanceof NodeElement) {
1610 output.add(new StyleRecord(s, osm, flags));
1611 }
1612 }
1613 }
1614
1615 public void add(Way osm, int flags) {
1616 StyleElementList sl = styles.get(osm, circum, nc);
1617 for (StyleElement s : sl) {
1618 if ((drawArea && (flags & FLAG_DISABLED) == 0) || !(s instanceof AreaElement)) {
1619 output.add(new StyleRecord(s, osm, flags));
1620 }
1621 }
1622 }
1623 }
1624
1625 /**
1626 * Sets the factory that creates the benchmark data receivers.
1627 * @param benchmarkFactory The factory.
1628 * @since 10697
1629 */
1630 public void setBenchmarkFactory(Supplier<RenderBenchmarkCollector> benchmarkFactory) {
1631 this.benchmarkFactory = benchmarkFactory;
1632 }
1633
1634 @Override
1635 public void render(final DataSet data, boolean renderVirtualNodes, Bounds bounds) {
1636 RenderBenchmarkCollector benchmark = benchmarkFactory.get();
1637 BBox bbox = bounds.toBBox();
1638 getSettings(renderVirtualNodes);
1639
1640 data.getReadLock().lock();
1641 try {
1642 highlightWaySegments = data.getHighlightedWaySegments();
1643
1644 benchmark.renderStart(circum);
1645
1646 List<Node> nodes = data.searchNodes(bbox);
1647 List<Way> ways = data.searchWays(bbox);
1648 List<Relation> relations = data.searchRelations(bbox);
1649
1650 final List<StyleRecord> allStyleElems = new ArrayList<>(nodes.size()+ways.size()+relations.size());
1651
1652 // Need to process all relations first.
1653 // Reason: Make sure, ElemStyles.getStyleCacheWithRange is not called for the same primitive in parallel threads.
1654 // (Could be synchronized, but try to avoid this for performance reasons.)
1655 THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, relations, allStyleElems,
1656 Math.max(20, relations.size() / THREAD_POOL.getParallelism() / 3)));
1657 THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, new CompositeList<>(nodes, ways), allStyleElems,
1658 Math.max(100, (nodes.size() + ways.size()) / THREAD_POOL.getParallelism() / 3)));
1659
1660 if (!benchmark.renderSort()) {
1661 return;
1662 }
1663
1664 Collections.sort(allStyleElems); // TODO: try parallel sort when switching to Java 8
1665
1666 if (!benchmark.renderDraw(allStyleElems)) {
1667 return;
1668 }
1669
1670 for (StyleRecord record : allStyleElems) {
1671 paintRecord(record);
1672 }
1673
1674 drawVirtualNodes(data, bbox);
1675
1676 benchmark.renderDone();
1677 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1678 throw BugReport.intercept(e)
1679 .put("data", data)
1680 .put("circum", circum)
1681 .put("scale", scale)
1682 .put("paintSettings", paintSettings)
1683 .put("renderVirtualNodes", renderVirtualNodes);
1684 } finally {
1685 data.getReadLock().unlock();
1686 }
1687 }
1688
1689 private void paintRecord(StyleRecord record) {
1690 try {
1691 record.paintPrimitive(paintSettings, this);
1692 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1693 throw BugReport.intercept(e).put("record", record);
1694 }
1695 }
1696}
Note: See TracBrowser for help on using the repository browser.