001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.validation.tests;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.geom.Point2D;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collection;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.List;
013import java.util.Map;
014import java.util.Objects;
015import java.util.Set;
016import java.util.stream.Collectors;
017
018import org.openstreetmap.josm.data.coor.EastNorth;
019import org.openstreetmap.josm.data.coor.ILatLon;
020import org.openstreetmap.josm.data.osm.DataSet;
021import org.openstreetmap.josm.data.osm.OsmDataManager;
022import org.openstreetmap.josm.data.osm.OsmPrimitive;
023import org.openstreetmap.josm.data.osm.OsmUtils;
024import org.openstreetmap.josm.data.osm.Relation;
025import org.openstreetmap.josm.data.osm.Way;
026import org.openstreetmap.josm.data.osm.WaySegment;
027import org.openstreetmap.josm.data.validation.OsmValidator;
028import org.openstreetmap.josm.data.validation.Severity;
029import org.openstreetmap.josm.data.validation.Test;
030import org.openstreetmap.josm.data.validation.TestError;
031import org.openstreetmap.josm.data.validation.util.ValUtil;
032import org.openstreetmap.josm.gui.progress.ProgressMonitor;
033import org.openstreetmap.josm.tools.CheckParameterUtil;
034import org.openstreetmap.josm.tools.Logging;
035
036/**
037 * Tests if there are segments that crosses in the same layer/level
038 *
039 * @author frsantos
040 */
041public abstract class CrossingWays extends Test {
042
043    static final String BARRIER = "barrier";
044    static final String HIGHWAY = "highway";
045    static final String RAILWAY = "railway";
046    static final String WATERWAY = "waterway";
047    static final String LANDUSE = "landuse";
048
049    static final class MessageHelper {
050        final String message;
051        final int code;
052
053        MessageHelper(String message, int code) {
054            this.message = message;
055            this.code = code;
056        }
057    }
058
059    /**
060     * Type of way. Entries have to be declared in alphabetical order, see sort below.
061     */
062    private enum WayType {
063        BARRIER, BUILDING, HIGHWAY, RAILWAY, RESIDENTIAL_AREA, WATERWAY, WAY;
064
065        static WayType of(Way w) {
066            if (w.hasKey(CrossingWays.BARRIER))
067                return BARRIER;
068            if (isBuilding(w))
069                return BUILDING;
070            else if (w.hasKey(CrossingWays.HIGHWAY))
071                return HIGHWAY;
072            else if (isRailway(w))
073                return RAILWAY;
074            else if (isResidentialArea(w))
075                return RESIDENTIAL_AREA;
076            else if (w.hasKey(CrossingWays.WATERWAY))
077                return WATERWAY;
078            else
079                return WAY;
080        }
081    }
082
083    /** All way segments, grouped by cells */
084    private final Map<Point2D, List<WaySegment>> cellSegments = new HashMap<>(1000);
085    /** The already detected ways in error */
086    private final Map<List<Way>, List<WaySegment>> seenWays = new HashMap<>(50);
087    private final Set<Way> waysToTest = new HashSet<>();
088
089    protected final int code;
090
091    /**
092     * General crossing ways test.
093     */
094    public static class Ways extends CrossingWays {
095
096        protected static final int CROSSING_WAYS = 601;
097
098        /**
099         * Constructs a new crossing {@code Ways} test.
100         */
101        public Ways() {
102            super(tr("Crossing ways"), CROSSING_WAYS);
103        }
104
105        @Override
106        public boolean isPrimitiveUsable(OsmPrimitive w) {
107            return super.isPrimitiveUsable(w)
108                    && !isProposedOrAbandoned(w)
109                    && (isHighway(w)
110                    || w.hasKey(WATERWAY)
111                    || isRailway(w)
112                    || isCoastline(w)
113                    || isBuilding(w)
114                    || w.hasKey(BARRIER)
115                    || isResidentialArea(w));
116        }
117
118        @Override
119        boolean ignoreWaySegmentCombination(Way w1, Way w2) {
120            if (w1 == w2)
121                return true;
122            if (areLayerOrLevelDifferent(w1, w2))
123                return true;
124            if (isBuilding(w1) && isBuilding(w2))
125                return true; // handled by mapcss tests
126            if (((isResidentialArea(w1) || w1.hasKey(BARRIER, HIGHWAY, RAILWAY, WATERWAY) || isWaterArea(w1))
127                    && isResidentialArea(w2))
128                    || ((isResidentialArea(w2) || w2.hasKey(BARRIER, HIGHWAY, RAILWAY, WATERWAY) || isWaterArea(w2))
129                            && isResidentialArea(w1)))
130                return true;
131            if (isWaterArea(w1) && isWaterArea(w2))
132                return true; // handled by mapcss tests
133            if (w1.hasKey(RAILWAY) && w2.hasKey(RAILWAY) && (w1.hasTag(RAILWAY, "yard") != w2.hasTag(RAILWAY, "yard")
134                    || w1.hasTag(RAILWAY, "halt") != w2.hasTag(RAILWAY, "halt")))
135                return true;  // see #20089, #21541
136            if (w1.hasTag(WATERWAY, "fairway") && w2.hasTag(WATERWAY, "fairway"))
137                return true; // see #24572
138            return (w1.hasTag(WATERWAY, "river", "stream", "canal", "drain", "ditch") && isWaterAreaOrFairway(w2))
139                    || (w2.hasTag(WATERWAY, "river", "stream", "canal", "drain", "ditch") && isWaterAreaOrFairway(w1));
140        }
141
142        @Override
143        MessageHelper createMessage(Way w1, Way w2) {
144            WayType[] types = {WayType.of(w1), WayType.of(w2)};
145            Arrays.sort(types);
146
147            if (types[0] == types[1]) {
148                switch (types[0]) {
149                // 610 and 640 where removed for #16707
150                case BARRIER:
151                    return new MessageHelper(tr("Crossing barriers"), 603);
152                case HIGHWAY:
153                    return new MessageHelper(tr("Crossing highways"), 620);
154                case RAILWAY:
155                    return new MessageHelper(tr("Crossing railways"), 630);
156                case WATERWAY:
157                    return new MessageHelper(tr("Crossing waterways"), 650);
158                case WAY:
159                default:
160                    return new MessageHelper(tr("Crossing ways"), CROSSING_WAYS);
161                }
162            } else {
163                switch (types[0]) {
164                case BARRIER:
165                    switch (types[1]) {
166                    case BUILDING:
167                        return new MessageHelper(tr("Crossing barrier/building"), 661);
168                    case HIGHWAY:
169                        return new MessageHelper(tr("Crossing barrier/highway"), 662);
170                    case RAILWAY:
171                        return new MessageHelper(tr("Crossing barrier/railway"), 663);
172                    case WATERWAY:
173                        return new MessageHelper(tr("Crossing barrier/waterway"), 664);
174                    case WAY:
175                    default:
176                        return new MessageHelper(tr("Crossing barrier/way"), 665);
177                    }
178                case BUILDING:
179                    switch (types[1]) {
180                    case HIGHWAY:
181                        return new MessageHelper(tr("Crossing building/highway"), 612);
182                    case RAILWAY:
183                        return new MessageHelper(tr("Crossing building/railway"), 613);
184                    case RESIDENTIAL_AREA:
185                        return new MessageHelper(tr("Crossing building/residential area"), 614);
186                    case WATERWAY:
187                        return new MessageHelper(tr("Crossing building/waterway"), 615);
188                    case WAY:
189                    default:
190                        return new MessageHelper(tr("Crossing building/way"), 611);
191                    }
192                case HIGHWAY:
193                    switch (types[1]) {
194                    case RAILWAY:
195                        return new MessageHelper(tr("Crossing highway/railway"), 622);
196                    case WATERWAY:
197                        return new MessageHelper(tr("Crossing highway/waterway"), 623);
198                    case WAY:
199                    default:
200                        return new MessageHelper(tr("Crossing highway/way"), 621);
201                    }
202                case RAILWAY:
203                    switch (types[1]) {
204                    case WATERWAY:
205                        return new MessageHelper(tr("Crossing railway/waterway"), 632);
206                    case WAY:
207                    default:
208                        return new MessageHelper(tr("Crossing railway/way"), 631);
209                    }
210                case RESIDENTIAL_AREA:
211                    return new MessageHelper(tr("Crossing residential area/way"), 641);
212                case WATERWAY:
213                default:
214                    return new MessageHelper(tr("Crossing waterway/way"), 651);
215                }
216            }
217        }
218    }
219
220    /**
221     * Crossing boundaries ways test.
222     */
223    public static class Boundaries extends CrossingWays {
224
225        protected static final int CROSSING_BOUNDARIES = 602;
226
227        /**
228         * Constructs a new crossing {@code Boundaries} test.
229         */
230        public Boundaries() {
231            super(tr("Crossing boundaries"), CROSSING_BOUNDARIES);
232        }
233
234        @Override
235        public boolean isPrimitiveUsable(OsmPrimitive p) {
236            return super.isPrimitiveUsable(p) && p.hasKey("boundary") && !p.hasTag("boundary", "protected_area")
237                    && (!(p instanceof Relation) || p.isMultipolygon());
238        }
239
240        @Override
241        boolean ignoreWaySegmentCombination(Way w1, Way w2) {
242            // ignore ways which have no common boundary tag value
243            Set<String> s1 = getBoundaryTags(w1);
244            Set<String> s2 = getBoundaryTags(w2);
245            return s1.stream().noneMatch(s2::contains);
246        }
247
248        /**
249         * Collect all boundary tag values of the way and its parent relations
250         * @param w the way to check
251         * @return set with the found boundary tag values
252         */
253        private static Set<String> getBoundaryTags(Way w) {
254            final Set<String> types = new HashSet<>();
255            String type = w.get("boundary");
256            if (type != null)
257                types.add(type);
258            w.referrers(Relation.class).filter(Relation::isMultipolygon).map(r -> r.get("boundary"))
259                    .filter(Objects::nonNull).forEach(types::add);
260            types.remove("protected_area");
261            return types;
262        }
263
264        @Override
265        public void visit(Relation r) {
266            for (Way w : r.getMemberPrimitives(Way.class)) {
267                if (!w.isIncomplete())
268                    visit(w);
269            }
270        }
271    }
272
273    /**
274     * Self crossing ways test (for all ways)
275     */
276    public static class SelfCrossing extends CrossingWays {
277
278        protected static final int CROSSING_SELF = 604;
279
280        /**
281         * Constructs a new SelfIntersection test.
282         */
283        public SelfCrossing() {
284            super(tr("Self crossing ways"), CROSSING_SELF);
285        }
286
287        @Override
288        boolean ignoreWaySegmentCombination(Way w1, Way w2) {
289            return false; // we should not get here
290        }
291    }
292
293    /**
294     * Constructs a new {@code CrossingWays} test.
295     * @param title The test title
296     * @param code The test code
297     * @since 12958
298     */
299    protected CrossingWays(String title, int code) {
300        super(title, tr("This test checks if two roads, railways, waterways or buildings crosses in the same layer, " +
301                "but are not connected by a node."));
302        this.code = code;
303    }
304
305    @Override
306    public void startTest(ProgressMonitor monitor) {
307        super.startTest(monitor);
308        cellSegments.clear();
309        seenWays.clear();
310    }
311
312    @Override
313    public void endTest() {
314        runTest();
315        // free storage
316        cellSegments.clear();
317        seenWays.clear();
318        if (partialSelection)
319            removeIrrelevantErrors(waysToTest);
320        waysToTest.clear();
321        super.endTest();
322    }
323
324    protected void runTest() {
325        final Collection<Way> selection;
326        if (this instanceof SelfCrossing || !partialSelection) {
327            selection = waysToTest;
328        } else {
329            selection = addNearbyObjects();
330        }
331        for (Way w : selection) {
332            testWay(w);
333        }
334
335    }
336
337    private Collection<Way> addNearbyObjects() {
338        final Collection<Way> selection = new HashSet<>();
339        DataSet ds = OsmDataManager.getInstance().getActiveDataSet();
340        if (ds != null) {
341            for (Way wt : waysToTest) {
342                selection.addAll(ds.searchWays(wt.getBBox()).stream()
343                        .filter(w -> !w.isDeleted() && isPrimitiveUsable(w)).collect(Collectors.toList()));
344                if (this instanceof CrossingWays.Boundaries) {
345                    List<Relation> relations = ds.searchRelations(wt.getBBox()).stream()
346                            .filter(this::isPrimitiveUsable).collect(Collectors.toList());
347                    for (Relation r: relations) {
348                        for (Way w : r.getMemberPrimitives(Way.class)) {
349                            if (!w.isIncomplete())
350                                selection.add(w);
351                        }
352                    }
353                }
354            }
355        }
356        return selection;
357    }
358
359    static boolean isCoastline(OsmPrimitive w) {
360        return w.hasTag("natural", "water", "coastline") || w.hasTag(LANDUSE, "reservoir");
361    }
362
363    static boolean isWaterArea(OsmPrimitive w) {
364        return w.hasTag("natural", "water") || w.hasTag(WATERWAY, "riverbank") || w.hasTag(LANDUSE, "reservoir");
365    }
366
367    static boolean isWaterAreaOrFairway(OsmPrimitive w) {
368        return isWaterArea(w) || w.hasTag(WATERWAY, "fairway");
369    }
370
371    static boolean isHighway(OsmPrimitive w) {
372        return w.hasTagDifferent(HIGHWAY, "rest_area", "services", "bus_stop", "platform");
373    }
374
375    static boolean isRailway(OsmPrimitive w) {
376        return w.hasKey(RAILWAY) && !isSubwayOrTramOrRazed(w);
377    }
378
379    static boolean isSubwayOrTramOrRazed(OsmPrimitive w) {
380        return w.hasTag(RAILWAY, "subway", "tram", "razed") ||
381              (w.hasTag(RAILWAY, "construction") && w.hasTag("construction", "tram")) ||
382              (w.hasTag(RAILWAY, "disused") && w.hasTag("disused", "tram"));
383    }
384
385    static boolean isProposedOrAbandoned(OsmPrimitive w) {
386        return w.hasTag(HIGHWAY, "proposed") || w.hasTag(RAILWAY, "proposed", "abandoned");
387    }
388
389    abstract boolean ignoreWaySegmentCombination(Way w1, Way w2);
390
391    MessageHelper createMessage(Way w1, Way w2) {
392        return new MessageHelper(this.name, this.code);
393    }
394
395    @Override
396    public void visit(Way w) {
397        waysToTest.add(w);
398    }
399
400    private void testWay(Way w) {
401        boolean findSelfCrossingOnly = this instanceof SelfCrossing;
402        if (findSelfCrossingOnly) {
403            // free memory, we are not interested in previous ways
404            cellSegments.clear();
405            seenWays.clear();
406        }
407
408        int nodesSize = w.getNodesCount();
409        for (int i = 0; i < nodesSize - 1; i++) {
410            final WaySegment es1 = new WaySegment(w, i);
411            if (!es1.getFirstNode().isLatLonKnown() || !es1.getSecondNode().isLatLonKnown()) {
412                Logging.warn("Crossing ways test skipped " + es1);
413                continue;
414            }
415            for (List<WaySegment> segments : getSegments(cellSegments, es1.getFirstNode(), es1.getSecondNode())) {
416                for (WaySegment es2 : segments) {
417                    List<Way> prims;
418                    List<WaySegment> highlight;
419
420                    if (!es1.intersects(es2)
421                            || (!findSelfCrossingOnly && ignoreWaySegmentCombination(es1.getWay(), es2.getWay()))) {
422                        continue;
423                    }
424
425                    prims = new ArrayList<>();
426                    prims.add(es1.getWay());
427                    if (es1.getWay() != es2.getWay())
428                        prims.add(es2.getWay());
429                    if ((highlight = seenWays.get(prims)) == null) {
430                        highlight = new ArrayList<>();
431                        highlight.add(es1);
432                        highlight.add(es2);
433
434                        final MessageHelper message = createMessage(es1.getWay(), es2.getWay());
435                        errors.add(TestError.builder(this, Severity.WARNING, message.code)
436                                .message(message.message)
437                                .primitives(prims)
438                                .highlightWaySegments(highlight)
439                                .build());
440                        seenWays.put(prims, highlight);
441                    } else {
442                        highlight.add(es1);
443                        highlight.add(es2);
444                    }
445                }
446                segments.add(es1);
447            }
448        }
449    }
450
451    private static boolean areLayerOrLevelDifferent(Way w1, Way w2) {
452        return !Objects.equals(OsmUtils.getLayer(w1), OsmUtils.getLayer(w2))
453            || !Objects.equals(w1.get("level"), w2.get("level"));
454    }
455
456    /**
457     * Returns all the cells this segment crosses.  Each cell contains the list
458     * of segments already processed
459     * @param cellSegments map with already collected way segments
460     * @param n1 The first EastNorth
461     * @param n2 The second EastNorth
462     * @return A list with all the cells the segment crosses
463     */
464    public static List<List<WaySegment>> getSegments(Map<Point2D, List<WaySegment>> cellSegments, EastNorth n1, EastNorth n2) {
465        return ValUtil.getSegmentCells(n1, n2, OsmValidator.getGridDetail()).stream()
466                .map(cell -> cellSegments.computeIfAbsent(cell, k -> new ArrayList<>()))
467                .collect(Collectors.toList());
468    }
469
470    /**
471     * Returns all the cells this segment crosses.  Each cell contains the list
472     * of segments already processed
473     * @param cellSegments map with already collected way segments
474     * @param n1 The first EastNorth
475     * @param n2 The second EastNorth
476     * @return A list with all the cells the segment crosses
477     * @since 18553
478     */
479    public static List<List<WaySegment>> getSegments(Map<Point2D, List<WaySegment>> cellSegments, ILatLon n1, ILatLon n2) {
480        return ValUtil.getSegmentCells(n1, n2, OsmValidator.getGridDetail()).stream()
481                .map(cell -> cellSegments.computeIfAbsent(cell, k -> new ArrayList<>()))
482                .collect(Collectors.toList());
483    }
484
485    /**
486     * Find ways which are crossing without sharing a node.
487     * @param w way that is to be checked
488     * @param cellSegments map with already collected way segments
489     * @param crossingWays map to collect crossing ways and related segments
490     * @param findSharedWaySegments true: find shared way segments instead of crossings
491     */
492    public static void findIntersectingWay(Way w, Map<Point2D, List<WaySegment>> cellSegments,
493            Map<List<Way>, List<WaySegment>> crossingWays, boolean findSharedWaySegments) {
494        int nodesSize = w.getNodesCount();
495        for (int i = 0; i < nodesSize - 1; i++) {
496            final WaySegment es1 = new WaySegment(w, i);
497            final EastNorth en1 = es1.getFirstNode().getEastNorth();
498            final EastNorth en2 = es1.getSecondNode().getEastNorth();
499            if (en1 == null || en2 == null) {
500                Logging.warn("Crossing ways test skipped " + es1);
501                continue;
502            }
503            for (List<WaySegment> segments : CrossingWays.getSegments(cellSegments, en1, en2)) {
504                for (WaySegment es2 : segments) {
505
506                    List<WaySegment> highlight;
507                    if (es2.getWay() == w // reported by CrossingWays.SelfIntersection
508                            || (findSharedWaySegments && !es1.isSimilar(es2))
509                            || (!findSharedWaySegments && !es1.intersects(es2)))
510                        continue;
511
512                    List<Way> prims = Arrays.asList(es1.getWay(), es2.getWay());
513                    if ((highlight = crossingWays.get(prims)) == null) {
514                        highlight = new ArrayList<>(2);
515                        highlight.add(es1);
516                        highlight.add(es2);
517                        crossingWays.put(prims, highlight);
518                    } else {
519                        highlight.add(es1);
520                        highlight.add(es2);
521                    }
522                }
523                segments.add(es1);
524            }
525        }
526    }
527
528    /**
529     * Check if the given way is self crossing
530     * @param way the way to check
531     * @return {@code true} if one or more segments of the way are crossing
532     * @see SelfIntersectingWay
533     * @since 17393
534     */
535    public static boolean isSelfCrossing(Way way) {
536        CheckParameterUtil.ensureParameterNotNull(way, "way");
537        SelfCrossing test = new SelfCrossing();
538        test.visit(way);
539        test.runTest();
540        return !test.getErrors().isEmpty();
541    }
542}