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

Last change on this file since 16922 was 16922, checked in by simon04, 4 years ago

fix #19705 - StyledMapRenderer: render turn restrictions in HiDPI

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