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