001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm.visitor.paint;
003
004import java.awt.BasicStroke;
005import java.awt.Color;
006import java.awt.Graphics2D;
007import java.awt.Rectangle;
008import java.awt.RenderingHints;
009import java.awt.Stroke;
010import java.awt.geom.Ellipse2D;
011import java.awt.geom.GeneralPath;
012import java.awt.geom.Rectangle2D;
013import java.awt.geom.Rectangle2D.Double;
014import java.util.ArrayList;
015import java.util.Iterator;
016import java.util.List;
017
018import org.openstreetmap.josm.data.Bounds;
019import org.openstreetmap.josm.data.osm.BBox;
020import org.openstreetmap.josm.data.osm.INode;
021import org.openstreetmap.josm.data.osm.IPrimitive;
022import org.openstreetmap.josm.data.osm.IRelation;
023import org.openstreetmap.josm.data.osm.IRelationMember;
024import org.openstreetmap.josm.data.osm.IWay;
025import org.openstreetmap.josm.data.osm.OsmData;
026import org.openstreetmap.josm.data.osm.WaySegment;
027import org.openstreetmap.josm.data.osm.visitor.PrimitiveVisitor;
028import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
029import org.openstreetmap.josm.gui.MapViewState.MapViewRectangle;
030import org.openstreetmap.josm.gui.NavigatableComponent;
031import org.openstreetmap.josm.gui.draw.MapPath2D;
032import org.openstreetmap.josm.spi.preferences.Config;
033import org.openstreetmap.josm.tools.Utils;
034
035/**
036 * A map renderer that paints a simple scheme of every primitive it visits to a
037 * previous set graphic environment.
038 * @since 23
039 */
040public class WireframeMapRenderer extends AbstractMapRenderer implements PrimitiveVisitor {
041
042    /** Color Preference for ways not matching any other group */
043    protected Color dfltWayColor;
044    /** Color Preference for relations */
045    protected Color relationColor;
046    /** Color Preference for untagged ways */
047    protected Color untaggedWayColor;
048    /** Color Preference for tagged nodes */
049    protected Color taggedColor;
050    /** Color Preference for multiply connected nodes */
051    protected Color connectionColor;
052    /** Color Preference for tagged and multiply connected nodes */
053    protected Color taggedConnectionColor;
054    /** Preference: should directional arrows be displayed */
055    protected boolean showDirectionArrow;
056    /** Preference: should arrows for oneways be displayed */
057    protected boolean showOnewayArrow;
058    /** Preference: should only the last arrow of a way be displayed */
059    protected boolean showHeadArrowOnly;
060    /** Preference: should the segment numbers of ways be displayed */
061    protected boolean showOrderNumber;
062    /** Preference: should the segment numbers of the selected be displayed */
063    protected boolean showOrderNumberOnSelectedWay;
064    /** Preference: should selected nodes be filled */
065    protected boolean fillSelectedNode;
066    /** Preference: should unselected nodes be filled */
067    protected boolean fillUnselectedNode;
068    /** Preference: should tagged nodes be filled */
069    protected boolean fillTaggedNode;
070    /** Preference: should multiply connected nodes be filled */
071    protected boolean fillConnectionNode;
072    /** Preference: should relation ways be shown with outlines */
073    protected boolean useRelatedWayStroke;
074    /** Preference: size of selected nodes */
075    protected int selectedNodeSize;
076    /** Preference: size of unselected nodes */
077    protected int unselectedNodeSize;
078    /** Preference: size of multiply connected nodes */
079    protected int connectionNodeSize;
080    /** Preference: size of tagged nodes */
081    protected int taggedNodeSize;
082
083    /** Color cache to draw subsequent segments of same color as one <code>Path</code>. */
084    protected Color currentColor;
085    /** Path store to draw subsequent segments of same color as one <code>Path</code>. */
086    protected MapPath2D currentPath = new MapPath2D();
087
088    /** Helper variable for {@link #drawSegment} */
089    private static final ArrowPaintHelper ARROW_PAINT_HELPER = new ArrowPaintHelper(Utils.toRadians(20), 10);
090
091    /** Helper variable for {@link #visit(IRelation)} */
092    private final Stroke relatedWayStroke = new BasicStroke(
093            4, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL);
094    private MapViewRectangle viewClip;
095
096    /**
097     * Creates an wireframe render
098     *
099     * @param g the graphics context. Must not be null.
100     * @param nc the map viewport. Must not be null.
101     * @param isInactiveMode if true, the paint visitor shall render OSM objects such that they
102     * look inactive. Example: rendering of data in an inactive layer using light gray as color only.
103     * @throws IllegalArgumentException if {@code g} is null
104     * @throws IllegalArgumentException if {@code nc} is null
105     */
106    public WireframeMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
107        super(g, nc, isInactiveMode);
108    }
109
110    @Override
111    public void getColors() {
112        super.getColors();
113        dfltWayColor = PaintColors.DEFAULT_WAY.get();
114        relationColor = PaintColors.RELATION.get();
115        untaggedWayColor = PaintColors.UNTAGGED_WAY.get();
116        highlightColor = PaintColors.HIGHLIGHT_WIREFRAME.get();
117        taggedColor = PaintColors.TAGGED.get();
118        connectionColor = PaintColors.CONNECTION.get();
119
120        if (!taggedColor.equals(nodeColor)) {
121            taggedConnectionColor = taggedColor;
122        } else {
123            taggedConnectionColor = connectionColor;
124        }
125    }
126
127    @Override
128    protected void getSettings(boolean virtual) {
129        super.getSettings(virtual);
130        MapPaintSettings settings = MapPaintSettings.INSTANCE;
131        showDirectionArrow = settings.isShowDirectionArrow();
132        showOnewayArrow = settings.isShowOnewayArrow();
133        showHeadArrowOnly = settings.isShowHeadArrowOnly();
134        showOrderNumber = settings.isShowOrderNumber();
135        showOrderNumberOnSelectedWay = settings.isShowOrderNumberOnSelectedWay();
136        selectedNodeSize = settings.getSelectedNodeSize();
137        unselectedNodeSize = settings.getUnselectedNodeSize();
138        connectionNodeSize = settings.getConnectionNodeSize();
139        taggedNodeSize = settings.getTaggedNodeSize();
140        fillSelectedNode = settings.isFillSelectedNode();
141        fillUnselectedNode = settings.isFillUnselectedNode();
142        fillConnectionNode = settings.isFillConnectionNode();
143        fillTaggedNode = settings.isFillTaggedNode();
144        useRelatedWayStroke =
145                Config.getPref().getBoolean("mappaint.wireframe.show-relation-outlines", true);
146
147        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
148                Config.getPref().getBoolean("mappaint.wireframe.use-antialiasing", false) ?
149                        RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
150    }
151
152    @Override
153    public void render(OsmData<?, ?, ?, ?> data, boolean virtual, Bounds bounds) {
154        BBox bbox = bounds.toBBox();
155        Rectangle clip = g.getClipBounds();
156        // handle possible null value, see #24734
157        if (clip == null)
158            return;
159
160        clip.grow(50, 50);
161        viewClip = mapState.getViewArea(clip);
162        getSettings(virtual);
163
164        for (final IRelation<?> rel : data.searchRelations(bbox)) {
165            if (rel.isDrawable() && !rel.isSelected() && !rel.isDisabledAndHidden()) {
166                rel.accept(this);
167            }
168        }
169
170        // draw tagged ways first, then untagged ways, then highlighted ways
171        List<IWay<?>> highlightedWays = new ArrayList<>();
172        List<IWay<?>> untaggedWays = new ArrayList<>();
173
174        for (final IWay<?> way : data.searchWays(bbox)) {
175            if (way.isDrawable() && !way.isSelected() && !way.isDisabledAndHidden()) {
176                if (way.isHighlighted()) {
177                    highlightedWays.add(way);
178                } else if (!way.isTagged()) {
179                    untaggedWays.add(way);
180                } else {
181                    way.accept(this);
182                }
183            }
184            displaySegments();
185        }
186        displaySegments();
187
188        // Display highlighted ways after the other ones (fix #8276)
189        List<IWay<?>> specialWays = new ArrayList<>(untaggedWays);
190        specialWays.addAll(highlightedWays);
191        for (final IWay<?> way : specialWays) {
192            way.accept(this);
193        }
194        specialWays.clear();
195        displaySegments();
196
197        for (final IPrimitive osm : data.getSelected()) {
198            if (osm.isDrawable()) {
199                osm.accept(this);
200            }
201        }
202        displaySegments();
203
204        for (final INode osm: data.searchNodes(bbox)) {
205            if (osm.isDrawable() && !osm.isSelected() && !osm.isDisabledAndHidden()) {
206                osm.accept(this);
207            }
208        }
209        drawVirtualNodes(data, bbox);
210
211        // draw highlighted way segments over the already drawn ways. Otherwise each
212        // way would have to be checked if it contains a way segment to highlight when
213        // in most of the cases there won't be more than one segment. Since the wireframe
214        // renderer does not feature any transparency there should be no visual difference.
215        for (final WaySegment wseg : data.getHighlightedWaySegments()) {
216            drawSegment(mapState.getPointFor(wseg.getFirstNode()), mapState.getPointFor(wseg.getSecondNode()), highlightColor, false);
217        }
218        displaySegments();
219    }
220
221    /**
222     * Helper function to calculate maximum of 4 values.
223     *
224     * @param a First value
225     * @param b Second value
226     * @param c Third value
227     * @param d Fourth value
228     * @return maximumof {@code a}, {@code b}, {@code c}, {@code d}
229     */
230    private static int max(int a, int b, int c, int d) {
231        return Math.max(Math.max(a, b), Math.max(c, d));
232    }
233
234    /**
235     * Draw a small rectangle.
236     * White if selected (as always) or red otherwise.
237     *
238     * @param n The node to draw.
239     */
240    @Override
241    public void visit(INode n) {
242        if (n.isIncomplete()) return;
243
244        if (n.isHighlighted()) {
245            drawNode(n, highlightColor, selectedNodeSize, fillSelectedNode);
246        } else {
247            Color color;
248
249            if (isInactiveMode || n.isDisabled()) {
250                color = inactiveColor;
251            } else if (n.isSelected()) {
252                color = selectedColor;
253            } else if (n.isMemberOfSelected()) {
254                color = relationSelectedColor;
255            } else if (n.isConnectionNode()) {
256                if (isNodeTagged(n)) {
257                    color = taggedConnectionColor;
258                } else {
259                    color = connectionColor;
260                }
261            } else {
262                if (isNodeTagged(n)) {
263                    color = taggedColor;
264                } else {
265                    color = nodeColor;
266                }
267            }
268
269            final int size = max(n.isSelected() ? selectedNodeSize : 0,
270                    isNodeTagged(n) ? taggedNodeSize : 0,
271                    n.isConnectionNode() ? connectionNodeSize : 0,
272                    unselectedNodeSize);
273
274            final boolean fill = (n.isSelected() && fillSelectedNode) ||
275            (isNodeTagged(n) && fillTaggedNode) ||
276            (n.isConnectionNode() && fillConnectionNode) ||
277            fillUnselectedNode;
278
279            drawNode(n, color, size, fill);
280        }
281    }
282
283    private static boolean isNodeTagged(INode n) {
284        return n.isTagged() || n.isAnnotated();
285    }
286
287    /**
288     * Draw a line for all way segments.
289     * @param w The way to draw.
290     */
291    @Override
292    public void visit(IWay<?> w) {
293        if (w.isIncomplete() || w.getNodesCount() < 2)
294            return;
295
296        /* show direction arrows, if draw.segment.relevant_directions_only is not set, the way is tagged with a direction key
297           (even if the tag is negated as in oneway=false) or the way is selected */
298
299        boolean showThisDirectionArrow = w.isSelected() || showDirectionArrow;
300        /* head only takes over control if the option is true,
301           the direction should be shown at all and not only because it's selected */
302        boolean showOnlyHeadArrowOnly = showThisDirectionArrow && showHeadArrowOnly && !w.isSelected();
303        Color wayColor;
304
305        if (isInactiveMode || w.isDisabled()) {
306            wayColor = inactiveColor;
307        } else if (w.isHighlighted()) {
308            wayColor = highlightColor;
309        } else if (w.isSelected()) {
310            wayColor = selectedColor;
311        } else if (w.isMemberOfSelected()) {
312            wayColor = relationSelectedColor;
313        } else if (!w.isTagged()) {
314            wayColor = untaggedWayColor;
315        } else {
316            wayColor = dfltWayColor;
317        }
318
319        Iterator<? extends INode> it = w.getNodes().iterator();
320        if (it.hasNext()) {
321            MapViewPoint lastP = mapState.getPointFor(it.next());
322            int lastPOutside = lastP.getOutsideRectangleFlags(viewClip);
323            for (int orderNumber = 1; it.hasNext(); orderNumber++) {
324                MapViewPoint p = mapState.getPointFor(it.next());
325                int pOutside = p.getOutsideRectangleFlags(viewClip);
326                if ((pOutside & lastPOutside) == 0) {
327                    drawSegment(lastP, p, wayColor,
328                            showOnlyHeadArrowOnly ? !it.hasNext() : showThisDirectionArrow);
329                    if ((showOrderNumber || (showOrderNumberOnSelectedWay && w.isSelected())) && !isInactiveMode) {
330                        drawOrderNumber(lastP, p, orderNumber, g.getColor());
331                    }
332                }
333                lastP = p;
334                lastPOutside = pOutside;
335            }
336        }
337    }
338
339    /**
340     * Draw objects used in relations.
341     * @param r The relation to draw.
342     */
343    @Override
344    public void visit(IRelation<?> r) {
345        if (r.isIncomplete()) return;
346
347        Color col;
348        if (isInactiveMode || r.isDisabled()) {
349            col = inactiveColor;
350        } else if (r.isSelected()) {
351            col = selectedColor;
352        } else if (r.isMultipolygon() && r.isMemberOfSelected()) {
353            col = relationSelectedColor;
354        } else {
355            col = relationColor;
356        }
357        g.setColor(col);
358
359        Bounds viewArea = mapState.getViewArea().getLatLonBoundsBox();
360        for (IRelationMember<?> m : r.getMembers()) {
361            if (m.getMember().isIncomplete() || !m.getMember().isDrawable()) {
362                continue;
363            }
364
365            if (m.isNode() && viewArea.contains((INode) m.getMember())) {
366                MapViewPoint p = mapState.getPointFor((INode) m.getMember());
367                if (p.isInView()) {
368                    g.draw(new Ellipse2D.Double(p.getInViewX()-4, p.getInViewY()-4, 9, 9));
369                }
370
371            } else if (m.isWay() && viewArea.intersects(m.getMember().getBBox())) {
372                GeneralPath path = new GeneralPath();
373
374                boolean first = true;
375                for (INode n : ((IWay<?>) m.getMember()).getNodes()) {
376                    if (!n.isDrawable()) {
377                        continue;
378                    }
379                    MapViewPoint p = mapState.getPointFor(n);
380                    if (first) {
381                        path.moveTo(p.getInViewX(), p.getInViewY());
382                        first = false;
383                    } else {
384                        path.lineTo(p.getInViewX(), p.getInViewY());
385                    }
386                }
387
388                if (useRelatedWayStroke) {
389                    g.draw(relatedWayStroke.createStrokedShape(path));
390                } else {
391                    g.draw(path);
392                }
393            }
394        }
395    }
396
397    @Override
398    public void drawNode(INode n, Color color, int size, boolean fill) {
399        if (size > 1) {
400            MapViewPoint p = mapState.getPointFor(n);
401            if (!p.isInView())
402                return;
403            int radius = size / 2;
404            Double shape = new Rectangle2D.Double(p.getInViewX() - radius, p.getInViewY() - radius, size, size);
405            g.setColor(color);
406            if (fill) {
407                g.fill(shape);
408            }
409            g.draw(shape);
410        }
411    }
412
413    /**
414     * Draw a line with the given color.
415     *
416     * @param path The path to append this segment.
417     * @param mv1 First point of the way segment.
418     * @param mv2 Second point of the way segment.
419     * @param showDirection <code>true</code> if segment direction should be indicated
420     * @since 10827
421     */
422    protected void drawSegment(MapPath2D path, MapViewPoint mv1, MapViewPoint mv2, boolean showDirection) {
423        path.moveTo(mv1);
424        path.lineTo(mv2);
425        if (showDirection) {
426            ARROW_PAINT_HELPER.paintArrowAt(path, mv2, mv1);
427        }
428    }
429
430    /**
431     * Draw a line with the given color.
432     *
433     * @param p1 First point of the way segment.
434     * @param p2 Second point of the way segment.
435     * @param col The color to use for drawing line.
436     * @param showDirection <code>true</code> if segment direction should be indicated.
437     * @since 10827
438     */
439    protected void drawSegment(MapViewPoint p1, MapViewPoint p2, Color col, boolean showDirection) {
440        if (!col.equals(currentColor)) {
441            displaySegments(col);
442        }
443        drawSegment(currentPath, p1, p2, showDirection);
444    }
445
446    /**
447     * Finally display all segments in currect path.
448     */
449    protected void displaySegments() {
450        displaySegments(null);
451    }
452
453    /**
454     * Finally display all segments in currect path.
455     *
456     * @param newColor This color is set after the path is drawn.
457     */
458    protected void displaySegments(Color newColor) {
459        if (currentPath != null) {
460            g.setColor(currentColor);
461            g.draw(currentPath);
462            currentPath = new MapPath2D();
463            currentColor = newColor;
464        }
465    }
466}