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

Last change on this file since 12208 was 12208, checked in by michael2402, 7 years ago

See #14485: Fix order of disabled style elements

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