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