001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.io.File;
005import java.io.IOException;
006import java.io.InputStream;
007import java.io.OutputStreamWriter;
008import java.io.PrintWriter;
009import java.io.Writer;
010import java.nio.charset.StandardCharsets;
011import java.nio.file.Files;
012import java.nio.file.InvalidPathException;
013import java.nio.file.Paths;
014import java.util.ArrayList;
015import java.util.Collection;
016import java.util.Collections;
017import java.util.List;
018import java.util.Set;
019
020import org.openstreetmap.josm.actions.JoinAreasAction;
021import org.openstreetmap.josm.actions.JoinAreasAction.JoinAreasResult;
022import org.openstreetmap.josm.actions.JoinAreasAction.Multipolygon;
023import org.openstreetmap.josm.command.PurgeCommand;
024import org.openstreetmap.josm.data.coor.LatLon;
025import org.openstreetmap.josm.data.osm.DataSet;
026import org.openstreetmap.josm.data.osm.DownloadPolicy;
027import org.openstreetmap.josm.data.osm.OsmPrimitive;
028import org.openstreetmap.josm.data.osm.Relation;
029import org.openstreetmap.josm.data.osm.RelationMember;
030import org.openstreetmap.josm.data.osm.UploadPolicy;
031import org.openstreetmap.josm.data.osm.Way;
032import org.openstreetmap.josm.io.IllegalDataException;
033import org.openstreetmap.josm.io.OsmReader;
034import org.openstreetmap.josm.io.OsmWriter;
035import org.openstreetmap.josm.io.OsmWriterFactory;
036import org.openstreetmap.josm.spi.preferences.Config;
037
038/**
039 * Look up, if there is right- or left-hand traffic at a certain place.
040 * See <a href="https://en.wikipedia.org/wiki/Left-_and_right-hand_traffic">Left- and right-hand traffic</a>
041 */
042public final class RightAndLefthandTraffic {
043
044    private static final String DRIVING_SIDE = "driving_side";
045    private static final String LEFT = "left";
046    private static final String RIGHT = "right";
047
048    private static volatile GeoPropertyIndex<Boolean> rlCache;
049
050    private RightAndLefthandTraffic() {
051        // Hide implicit public constructor for utility classes
052    }
053
054    /**
055     * Check if there is right-hand traffic at a certain location.
056     *
057     * @param ll the coordinates of the point
058     * @return true if there is right-hand traffic, false if there is left-hand traffic
059     */
060    public static synchronized boolean isRightHandTraffic(LatLon ll) {
061        Boolean value = rlCache.get(ll);
062        return value == null || !value;
063    }
064
065    /**
066     * Initializes Right and lefthand traffic data.
067     * TODO: Synchronization can be refined inside the {@link GeoPropertyIndex} as most look-ups are read-only.
068     */
069    public static synchronized void initialize() {
070        Collection<Way> optimizedWays = loadOptimizedBoundaries();
071        if (optimizedWays.isEmpty()) {
072            optimizedWays = computeOptimizedBoundaries();
073            try {
074                saveOptimizedBoundaries(optimizedWays);
075            } catch (IOException | SecurityException e) {
076                Logging.log(Logging.LEVEL_ERROR, "Unable to save optimized boundaries", e);
077            }
078        }
079        rlCache = new GeoPropertyIndex<>(new DefaultGeoProperty(optimizedWays), 24);
080    }
081
082    private static Collection<Way> computeOptimizedBoundaries() {
083        Collection<Way> ways = new ArrayList<>();
084        Collection<OsmPrimitive> toPurge = new ArrayList<>();
085        // Find all outer ways of left-driving countries. Many of them are adjacent (African and Asian states)
086        DataSet data = Territories.getDataSet();
087        Collection<Relation> allRelations = data.getRelations();
088        Collection<Way> allWays = data.getWays();
089        for (Way w : allWays) {
090            if (LEFT.equals(w.get(DRIVING_SIDE))) {
091                addWayIfNotInner(ways, w);
092            }
093        }
094        for (Relation r : allRelations) {
095            if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE))) {
096                for (RelationMember rm : r.getMembers()) {
097                    if (rm.isWay() && "outer".equals(rm.getRole()) && !RIGHT.equals(rm.getMember().get(DRIVING_SIDE))) {
098                        addWayIfNotInner(ways, (Way) rm.getMember());
099                    }
100                }
101            }
102        }
103        toPurge.addAll(allRelations);
104        toPurge.addAll(allWays);
105        toPurge.removeAll(ways);
106        // Remove ways from parent relations for following optimizations
107        for (Relation r : OsmPrimitive.getParentRelations(ways)) {
108            r.setMembers(null);
109        }
110        // Remove all tags to avoid any conflict
111        for (Way w : ways) {
112            w.removeAll();
113        }
114        // Purge all other ways and relations so dataset only contains lefthand traffic data
115        PurgeCommand.build(toPurge, null).executeCommand();
116        // Combine adjacent countries into a single polygon
117        Collection<Way> optimizedWays = new ArrayList<>();
118        List<Multipolygon> areas = JoinAreasAction.collectMultipolygons(ways);
119        if (areas != null) {
120            try {
121                JoinAreasResult result = new JoinAreasAction(false).joinAreas(areas);
122                if (result.hasChanges()) {
123                    for (Multipolygon mp : result.getPolygons()) {
124                        optimizedWays.add(mp.getOuterWay());
125                    }
126                }
127            } catch (UserCancelException ex) {
128                Logging.warn(ex);
129            } catch (JosmRuntimeException ex) {
130                // Workaround to #10511 / #14185. To remove when #10511 is solved
131                Logging.error(ex);
132            }
133        }
134        if (optimizedWays.isEmpty()) {
135            // Problem: don't optimize
136            Logging.warn("Unable to join left-driving countries polygons");
137            optimizedWays.addAll(ways);
138        }
139        return optimizedWays;
140    }
141
142    /**
143     * Adds w to ways, except if it is an inner way of another lefthand driving multipolygon,
144     * as Lesotho in South Africa and Cyprus village in British Cyprus base.
145     * @param ways ways
146     * @param w way
147     */
148    private static void addWayIfNotInner(Collection<Way> ways, Way w) {
149        Set<Way> s = Collections.singleton(w);
150        for (Relation r : OsmPrimitive.getParentRelations(s)) {
151            if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE)) &&
152                "inner".equals(r.getMembersFor(s).iterator().next().getRole())) {
153                if (Logging.isDebugEnabled()) {
154                    Logging.debug("Skipping {0} because inner part of {1}", w.get("name:en"), r.get("name:en"));
155                }
156                return;
157            }
158        }
159        ways.add(w);
160    }
161
162    private static void saveOptimizedBoundaries(Collection<Way> optimizedWays) throws IOException {
163        DataSet ds = optimizedWays.iterator().next().getDataSet();
164        File file = new File(Config.getDirs().getCacheDirectory(true), "left-right-hand-traffic.osm");
165        try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8);
166             OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, ds.getVersion())
167            ) {
168            w.header(DownloadPolicy.NORMAL, UploadPolicy.DISCOURAGED);
169            w.writeContent(ds);
170            w.footer();
171        }
172    }
173
174    private static Collection<Way> loadOptimizedBoundaries() {
175        try (InputStream is = Files.newInputStream(Paths.get(
176                Config.getDirs().getCacheDirectory(false).getPath(), "left-right-hand-traffic.osm"))) {
177           return OsmReader.parseDataSet(is, null).getWays();
178        } catch (IllegalDataException | IOException | InvalidPathException | SecurityException ex) {
179            Logging.trace(ex);
180            return Collections.emptyList();
181        }
182    }
183}