001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.mapmode;
003
004import java.util.ArrayList;
005import java.util.Collection;
006import java.util.Collections;
007import java.util.HashMap;
008import java.util.HashSet;
009import java.util.List;
010import java.util.Map;
011import java.util.Set;
012
013import org.openstreetmap.josm.Main;
014import org.openstreetmap.josm.actions.CombineWayAction;
015import org.openstreetmap.josm.command.AddCommand;
016import org.openstreetmap.josm.command.Command;
017import org.openstreetmap.josm.command.SequenceCommand;
018import org.openstreetmap.josm.data.coor.EastNorth;
019import org.openstreetmap.josm.data.osm.Node;
020import org.openstreetmap.josm.data.osm.Way;
021import org.openstreetmap.josm.tools.Geometry;
022
023/**
024 * Helper for ParallelWayAction
025 *
026 * @author Ole Jørgen Brønner (olejorgenb)
027 */
028public class ParallelWays {
029    private final List<Way> ways;
030    private final List<Node> sortedNodes;
031
032    private final int nodeCount;
033
034    private final EastNorth[] pts;
035    private final EastNorth[] normals;
036
037    // Need a reference way to determine the direction of the offset when we manage multiple ways
038    public ParallelWays(Collection<Way> sourceWays, boolean copyTags, int refWayIndex) {
039        // Possible/sensible to use PrimetiveDeepCopy here?
040
041        // Make a deep copy of the ways, keeping the copied ways connected
042        // TODO: This assumes the first/last nodes of the ways are the only possible shared nodes.
043        Map<Node, Node> splitNodeMap = new HashMap<>(sourceWays.size());
044        for (Way w : sourceWays) {
045            if (!splitNodeMap.containsKey(w.firstNode())) {
046                splitNodeMap.put(w.firstNode(), copyNode(w.firstNode(), copyTags));
047            }
048            if (!splitNodeMap.containsKey(w.lastNode())) {
049                splitNodeMap.put(w.lastNode(), copyNode(w.lastNode(), copyTags));
050            }
051        }
052        ways = new ArrayList<>(sourceWays.size());
053        for (Way w : sourceWays) {
054            Way wCopy = new Way();
055            wCopy.addNode(splitNodeMap.get(w.firstNode()));
056            for (int i = 1; i < w.getNodesCount() - 1; i++) {
057                wCopy.addNode(copyNode(w.getNode(i), copyTags));
058            }
059            wCopy.addNode(splitNodeMap.get(w.lastNode()));
060            if (copyTags) {
061                wCopy.setKeys(w.getKeys());
062            }
063            ways.add(wCopy);
064        }
065
066        // Find a linear ordering of the nodes. Fail if there isn't one.
067        CombineWayAction.NodeGraph nodeGraph = CombineWayAction.NodeGraph.createUndirectedGraphFromNodeWays(ways);
068        List<Node> sortedNodesPath = nodeGraph.buildSpanningPath();
069        if (sortedNodesPath == null)
070            throw new IllegalArgumentException("Ways must have spanning path"); // Create a dedicated exception?
071
072        // Fix #8631 - Remove duplicated nodes from graph to be robust with self-intersecting ways
073        Set<Node> removedNodes = new HashSet<>();
074        sortedNodes = new ArrayList<>();
075        for (int i = 0; i < sortedNodesPath.size(); i++) {
076            Node n = sortedNodesPath.get(i);
077            if (i < sortedNodesPath.size()-1) {
078                if (sortedNodesPath.get(i+1).getCoor().equals(n.getCoor())) {
079                    removedNodes.add(n);
080                    for (Way w : ways) {
081                        w.removeNode(n);
082                    }
083                    continue;
084                }
085            }
086            if (!removedNodes.contains(n)) {
087                sortedNodes.add(n);
088            }
089        }
090
091        // Ugly method of ensuring that the offset isn't inverted. I'm sure there is a better and more elegant way
092        Way refWay = ways.get(refWayIndex);
093        boolean refWayReversed = true;
094        for (int i = 0; i < sortedNodes.size() - 1; i++) {
095            if (sortedNodes.get(i) == refWay.firstNode() && sortedNodes.get(i + 1) == refWay.getNode(1)) {
096                refWayReversed = false;
097                break;
098            }
099        }
100        if (refWayReversed) {
101            Collections.reverse(sortedNodes); // need to keep the orientation of the reference way.
102        }
103
104        // Initialize the required parameters. (segment normals, etc.)
105        nodeCount = sortedNodes.size();
106        pts = new EastNorth[nodeCount];
107        normals = new EastNorth[nodeCount - 1];
108        int i = 0;
109        for (Node n : sortedNodes) {
110            EastNorth t = n.getEastNorth();
111            pts[i] = t;
112            i++;
113        }
114        for (i = 0; i < nodeCount - 1; i++) {
115            double dx = pts[i + 1].getX() - pts[i].getX();
116            double dy = pts[i + 1].getY() - pts[i].getY();
117            double len = Math.sqrt(dx * dx + dy * dy);
118            normals[i] = new EastNorth(-dy / len, dx / len);
119        }
120    }
121
122    public boolean isClosedPath() {
123        return sortedNodes.get(0) == sortedNodes.get(sortedNodes.size() - 1);
124    }
125
126    /**
127     * Offsets the way(s) d units. Positive d means to the left (relative to the reference way)
128     * @param d offset
129     */
130    public void changeOffset(double d) {
131        // This is the core algorithm:
132        /* 1. Calculate a parallel line, offset by 'd', to each segment in the path
133         * 2. Find the intersection of lines belonging to neighboring segments. These become the new node positions
134         * 3. Do some special casing for closed paths
135         *
136         * Simple and probably not even close to optimal performance wise
137         */
138
139        EastNorth[] ppts = new EastNorth[nodeCount];
140
141        EastNorth prevA = pts[0].add(normals[0].scale(d));
142        EastNorth prevB = pts[1].add(normals[0].scale(d));
143        for (int i = 1; i < nodeCount - 1; i++) {
144            EastNorth a = pts[i].add(normals[i].scale(d));
145            EastNorth b = pts[i + 1].add(normals[i].scale(d));
146            if (Geometry.segmentsParallel(a, b, prevA, prevB)) {
147                ppts[i] = a;
148            } else {
149                ppts[i] = Geometry.getLineLineIntersection(a, b, prevA, prevB);
150            }
151            prevA = a;
152            prevB = b;
153        }
154        if (isClosedPath()) {
155            EastNorth a = pts[0].add(normals[0].scale(d));
156            EastNorth b = pts[1].add(normals[0].scale(d));
157            if (Geometry.segmentsParallel(a, b, prevA, prevB)) {
158                ppts[0] = a;
159            } else {
160                ppts[0] = Geometry.getLineLineIntersection(a, b, prevA, prevB);
161            }
162            ppts[nodeCount - 1] = ppts[0];
163        } else {
164            ppts[0] = pts[0].add(normals[0].scale(d));
165            ppts[nodeCount - 1] = pts[nodeCount - 1].add(normals[nodeCount - 2].scale(d));
166        }
167
168        for (int i = 0; i < nodeCount; i++) {
169            sortedNodes.get(i).setEastNorth(ppts[i]);
170        }
171    }
172
173    public void commit() {
174        SequenceCommand undoCommand = new SequenceCommand("Make parallel way(s)", makeAddWayAndNodesCommandList());
175        Main.main.undoRedo.add(undoCommand);
176    }
177
178    private List<Command> makeAddWayAndNodesCommandList() {
179        List<Command> commands = new ArrayList<>(sortedNodes.size() + ways.size());
180        for (int i = 0; i < sortedNodes.size() - (isClosedPath() ? 1 : 0); i++) {
181            commands.add(new AddCommand(sortedNodes.get(i)));
182        }
183        for (Way w : ways) {
184            commands.add(new AddCommand(w));
185        }
186        return commands;
187    }
188
189    private static Node copyNode(Node source, boolean copyTags) {
190        if (copyTags)
191            return new Node(source, true);
192        else {
193            Node n = new Node();
194            n.setCoor(source.getCoor());
195            return n;
196        }
197    }
198
199    public final List<Way> getWays() {
200        return ways;
201    }
202}