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