source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java@ 16160

Last change on this file since 16160 was 16160, checked in by jttt, 15 years ago

Use getter for Node.coor and Node.eastNort

File size: 10.7 KB
Line 
1package cadastre_fr;
2
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.io.BufferedOutputStream;
6import java.io.BufferedReader;
7import java.io.File;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.net.HttpURLConnection;
13import java.net.MalformedURLException;
14import java.net.URL;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.LinkedList;
18
19import javax.swing.JOptionPane;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.command.AddCommand;
23import org.openstreetmap.josm.command.Command;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.data.coor.EastNorth;
26import org.openstreetmap.josm.data.osm.DataSet;
27import org.openstreetmap.josm.data.osm.Node;
28import org.openstreetmap.josm.data.osm.Way;
29import org.openstreetmap.josm.gui.MapView;
30import org.openstreetmap.josm.gui.PleaseWaitRunnable;
31import org.openstreetmap.josm.io.OsmTransferException;
32import org.openstreetmap.josm.io.ProgressInputStream;
33
34public class DownloadSVGBuilding extends PleaseWaitRunnable {
35
36 private WMSLayer wmsLayer;
37 private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;
38 private CadastreInterface wmsInterface;
39 private String svg = null;
40 private static EastNorthBound currentView = null;
41 private EastNorthBound viewBox = null;
42
43 public DownloadSVGBuilding(WMSLayer wmsLayer) {
44 super(tr("Downloading {0}", wmsLayer.name));
45
46 this.wmsLayer = wmsLayer;
47 this.wmsInterface = grabber.getWmsInterface();
48 }
49
50 @Override
51 public void realRun() throws IOException, OsmTransferException {
52 Main.pleaseWaitDlg.currentAction.setText(tr("Contacting WMS Server..."));
53 try {
54 if (wmsInterface.retrieveInterface(wmsLayer)) {
55 svg = grabBoundary(currentView);
56 if (svg == null)
57 return;
58 getViewBox(svg);
59 if (viewBox == null)
60 return;
61 createBuildings(svg);
62 }
63 } catch (DuplicateLayerException e) {
64 System.err.println("removed a duplicated layer");
65 }
66 }
67
68 @Override
69 protected void cancel() {
70 grabber.getWmsInterface().cancel();
71 }
72
73 @Override
74 protected void finish() {
75 }
76
77 private boolean getViewBox(String svg) {
78 double[] box = new SVGParser().getViewBox(svg);
79 if (box != null) {
80 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
81 new EastNorth(box[0]+box[2], box[1]+box[3]));
82 return true;
83 }
84 System.out.println("Unable to parse SVG data (viewBox)");
85 return false;
86 }
87
88 /**
89 * The svg contains more than one commune boundary defined by path elements. So detect
90 * which path element is the best fitting to the viewBox and convert it to OSM objects
91 */
92 private void createBuildings(String svg) {
93 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
94 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<ArrayList<EastNorth>>();
95
96 // convert SVG nodes to eastNorth coordinates
97 for (int i=0; i< SVGpaths.length; i++) {
98 ArrayList<EastNorth> eastNorth = new ArrayList<EastNorth>();
99 createNodes(SVGpaths[i], eastNorth);
100 if (eastNorth.size() > 2)
101 eastNorths.add(eastNorth);
102 }
103
104 // create nodes and closed ways
105 DataSet svgDataSet = new DataSet();
106 for (ArrayList<EastNorth> path : eastNorths) {
107 Way wayToAdd = new Way();
108 for (EastNorth eastNorth : path) {
109 Node nodeToAdd = new Node(Main.proj.eastNorth2latlon(eastNorth));
110 // check if new node is not already created by another new path
111 Node nearestNewNode = checkNearestNode(nodeToAdd, svgDataSet.nodes);
112 if (nearestNewNode == nodeToAdd)
113 svgDataSet.addPrimitive(nearestNewNode);
114 wayToAdd.nodes.add(nearestNewNode); // either a new node or an existing one
115 }
116 wayToAdd.nodes.add(wayToAdd.nodes.get(0)); // close the way
117 svgDataSet.addPrimitive(wayToAdd);
118 }
119
120 // TODO remove small boxes (4 nodes with less than 1 meter distance)
121 /*
122 for (Way w : svgDataSet.ways)
123 if (w.nodes.size() == 5)
124 for (int i = 0; i < w.nodes.size()-2; i++) {
125 if (w.nodes.get(i).eastNorth.distance(w.nodes.get(i+1).eastNorth))
126 }*/
127
128 // simplify ways and check if we can reuse existing OSM nodes
129 for (Way wayToAdd : svgDataSet.ways)
130 new SimplifyWay().simplifyWay(wayToAdd, svgDataSet, 0.5);
131 // check if the new way or its nodes is already in OSM layer
132 for (Node n : svgDataSet.nodes) {
133 Node nearestNewNode = checkNearestNode(n, Main.ds.nodes);
134 if (nearestNewNode != n) {
135 // replace the SVG node by the OSM node
136 for (Way w : svgDataSet.ways) {
137 int replaced = 0;
138 for (Node node : w.nodes)
139 if (node == n) {
140 node = nearestNewNode;
141 replaced++;
142 }
143 if (w.nodes.size() == replaced)
144 w.delete(true);
145 }
146 n.delete(true);
147 }
148
149 }
150
151 Collection<Command> cmds = new LinkedList<Command>();
152 for (Node node : svgDataSet.nodes)
153 if (!node.deleted)
154 cmds.add(new AddCommand(node));
155 for (Way way : svgDataSet.ways)
156 if (!way.deleted)
157 cmds.add(new AddCommand(way));
158 Main.main.undoRedo.add(new SequenceCommand(tr("Create buildings"), cmds));
159 Main.map.repaint();
160 }
161
162 private void createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
163 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
164 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
165 double dx = Double.parseDouble(coor[1]);
166 double dy = Double.parseDouble(coor[2]);
167 for (int i=3; i<coor.length; i+=2){
168 if (coor[i].equals("")) {
169 eastNorth.clear(); // some paths are just artifacts
170 return;
171 }
172 double east = dx+=Double.parseDouble(coor[i]);
173 double north = dy+=Double.parseDouble(coor[i+1]);
174 eastNorth.add(new EastNorth(east,north));
175 }
176 // flip the image (svg using a reversed Y coordinate system)
177 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
178 for (EastNorth en : eastNorth) {
179 en.setLocation(en.east(), 2 * pivot - en.north());
180 }
181 return;
182 }
183
184 /**
185 * Check if node can be reused.
186 * @param nodeToAdd the candidate as new node
187 * @return the already existing node (if any), otherwise the new node candidate.
188 */
189 private Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
190 double epsilon = 0.05; // smallest distance considering duplicate node
191 for (Node n : nodes) {
192 if (!n.deleted && !n.incomplete) {
193 double dist = n.getEastNorth().distance(nodeToAdd.getEastNorth());
194 if (dist < epsilon) {
195 return n;
196 }
197 }
198 }
199 return nodeToAdd;
200 }
201
202 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
203 try {
204 URL url = null;
205 url = getURLsvg(bbox);
206 System.out.println("grab:"+url);
207 return grabSVG(url);
208 } catch (MalformedURLException e) {
209 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
210 }
211 }
212
213 private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
214 String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
215 str += "&layers=";
216 str += "CDIF:LS2";
217 str += "&format=image/svg";
218 str += "&bbox="+bbox.min.east()+",";
219 str += bbox.min.north() + ",";
220 str += bbox.max.east() + ",";
221 str += bbox.max.north();
222 str += "&width=800&height=600"; // maximum allowed by wms server
223 str += "&exception=application/vnd.ogc.se_inimage";
224 str += "&styles=";
225 str += "LS2_90";
226 System.out.println("URL="+str);
227 return new URL(str.replace(" ", "%20"));
228 }
229
230 private String grabSVG(URL url) throws IOException, OsmTransferException {
231 wmsInterface.urlConn = (HttpURLConnection)url.openConnection();
232 wmsInterface.urlConn.setRequestMethod("GET");
233 wmsInterface.setCookie();
234 InputStream is = new ProgressInputStream(wmsInterface.urlConn, Main.pleaseWaitDlg);
235 File file = new File(CadastrePlugin.cacheDir + "building.svg");
236 String svg = new String();
237 try {
238 if (file.exists())
239 file.delete();
240 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
241 InputStreamReader isr =new InputStreamReader(is);
242 BufferedReader br = new BufferedReader(isr);
243 String line="";
244 while ( null!=(line=br.readLine())){
245 line += "\n";
246 bos.write(line.getBytes());
247 svg += line;
248 }
249 bos.close();
250 } catch (IOException e) {
251 e.printStackTrace(System.out);
252 }
253 is.close();
254 return svg;
255 }
256
257 public static void download(WMSLayer wmsLayer) {
258 MapView mv = Main.map.mapView;
259 currentView = new EastNorthBound(mv.getEastNorth(0, mv.getHeight()),
260 mv.getEastNorth(mv.getWidth(), 0));
261 if ((currentView.max.east() - currentView.min.east()) > 1000 ||
262 (currentView.max.north() - currentView.min.north() > 1000)) {
263 JOptionPane.showMessageDialog(Main.parent,
264 tr("To avoid cadastre WMS overload,\nbuilding import size is limited to 1 km2 max."));
265 return;
266 }
267 if (CadastrePlugin.autoSourcing == false) {
268 JOptionPane.showMessageDialog(Main.parent,
269 tr("Please, enable auto-sourcing and check cadastre millesime."));
270 return;
271 }
272 Main.worker.execute(new DownloadSVGBuilding(wmsLayer));
273 }
274
275}
Note: See TracBrowser for help on using the repository browser.