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