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

Last change on this file was 18871, checked in by taylor.smock, 6 months ago

See #23218: Use newer error_prone versions when compiling on Java 11+

error_prone 2.11 dropped support for compiling with Java 8, although it still
supports compiling for Java 8. The "major" new check for us is NotJavadoc since
we used /** in quite a few places which were not javadoc.

Other "new" checks that are of interest:

  • AlreadyChecked: if (foo) { doFoo(); } else if (!foo) { doBar(); }
  • UnnecessaryStringBuilder: Avoid StringBuilder (Java converts + to StringBuilder behind-the-scenes, but may also do something else if it performs better)
  • NonApiType: Avoid specific interface types in function definitions
  • NamedLikeContextualKeyword: Avoid using restricted names for classes and methods
  • UnusedMethod: Unused private methods should be removed

This fixes most of the new error_prone issues and some SonarLint issues.

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