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

Last change on this file since 12722 was 12722, checked in by bastiK, 7 years ago

see #9995 - fix blurry GUI-icons and map view for Java 9 HiDPI mode

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