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

Last change on this file since 11914 was 11914, checked in by Don-vip, 7 years ago

sonar - squid:S2972 - Inner classes should not have too many lines of code

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