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

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

Encalupse OsmPrimitive.incomplete

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