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

Last change on this file since 14273 was 14273, checked in by stoecker, 6 years ago

fix typos - patch by naoliv - fix #16781 - Thanks a lot

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