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

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

Remove orderFont preference - Fonts are stored locally with text labels now.

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