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

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

Fix #14485: Increase sorting speed by removing compareTo complexity.

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