Changeset 12778 in osm for applications/editors/josm/plugins/lakewalker/src
- Timestamp:
- 2009-01-01T18:28:53+01:00 (17 years ago)
- Location:
- applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker
- Files:
-
- 8 edited
-
Lakewalker.java (modified) (1 diff)
-
LakewalkerAction.java (modified) (6 diffs)
-
LakewalkerApp.java (modified) (1 diff)
-
LakewalkerException.java (modified) (1 diff)
-
LakewalkerPlugin.java (modified) (2 diffs)
-
LakewalkerReader.java (modified) (4 diffs)
-
LakewalkerWMS.java (modified) (1 diff)
-
StringEnumConfigurer.java (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/Lakewalker.java
r11938 r12778 16 16 17 17 public class Lakewalker { 18 protected Collection<Command> commands = new LinkedList<Command>();19 protected Collection<Way> ways = new ArrayList<Way>();20 protected boolean cancel;21 22 private int waylen;23 private int maxnode;24 private int threshold;25 private double epsilon;26 private int resolution;27 private int tilesize;28 private String startdir;29 private String wmslayer;30 31 private File workingdir;32 33 private int[] dirslat = new int[] {0,1,1,1,0,-1,-1,-1};34 private int[] dirslon = new int[] {1,1,0,-1,-1,-1,0,1};35 36 double start_radius_big = 0.001;37 double start_radius_small = 0.0002;38 39 public Lakewalker(int waylen, int maxnode, int threshold, double epsilon, int resolution, int tilesize, String startdir, String wmslayer, File workingdir){40 this.waylen = waylen;41 this.maxnode = maxnode;42 this.threshold = threshold;43 this.epsilon = epsilon;44 this.resolution = resolution;45 this.tilesize = tilesize;46 this.startdir = startdir;47 this.wmslayer = wmslayer;48 49 this.workingdir = workingdir;50 }51 52 /**53 * east = 054 * northeast = 155 * north = 256 * northwest = 357 * west = 458 * southwest = 559 * south = 660 * southeast = 761 */62 private int getDirectionIndex(String direction) throws ArrayIndexOutOfBoundsException{63 int i=0;64 if(direction.equals("East") || direction.equals("east")){65 i = 0;66 } else if(direction.equals("Northeast") || direction.equals("northeast")){67 i = 1;68 } else if(direction.equals("North") || direction.equals("north")){69 i = 2;70 } else if(direction.equals("Northwest") || direction.equals("northwest")){71 i = 3;72 } else if(direction.equals("West") || direction.equals("west")){73 i = 4;74 } else if(direction.equals("Southwest") || direction.equals("southwest")){75 i = 5;76 } else if(direction.equals("South") || direction.equals("south")){77 i = 6;78 } else if(direction.equals("Southeast") || direction.equals("southeast")){79 i = 7;80 } else {81 throw new ArrayIndexOutOfBoundsException(tr("Direction index '{0}' not found",direction));82 }83 return i;84 }85 86 /**87 * Do a trace88 * 89 * @param lat90 * @param lon91 * @param tl_lon92 * @param br_lon93 * @param tl_lat94 * @param br_lat95 */96 public ArrayList<double[]> trace(double lat, double lon, double tl_lon, double br_lon, double tl_lat, double br_lat) throws LakewalkerException {97 98 LakewalkerWMS wms = new LakewalkerWMS(this.resolution, this.tilesize, this.wmslayer, this.workingdir);99 LakewalkerBBox bbox = new LakewalkerBBox(tl_lat,tl_lon,br_lat,br_lon);100 101 Boolean detect_loop = false;102 103 ArrayList<double[]> nodelist = new ArrayList<double[]>();104 105 int[] xy = geo_to_xy(lat,lon,this.resolution);106 107 if(!bbox.contains(lat, lon)){108 throw new LakewalkerException(tr("The starting location was not within the bbox"));109 }110 111 int v;112 113 setStatus(tr("Looking for shoreline..."));114 115 while(true){116 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);117 if(bbox.contains(geo[0],geo[1])==false){118 break;119 }120 121 v = wms.getPixel(xy[0], xy[1]);122 if(v > this.threshold){123 break;124 }125 126 int delta_lat = this.dirslat[getDirectionIndex(this.startdir)];127 int delta_lon = this.dirslon[getDirectionIndex(this.startdir)];128 129 xy[0] = xy[0]+delta_lon;130 xy[1] = xy[1]+delta_lat;131 132 }133 134 int[] startxy = new int[] {xy[0], xy[1]};135 double[] startgeo = xy_to_geo(xy[0],xy[1],this.resolution);136 137 //System.out.printf("Found shore at lat %.4f lon %.4f\n",lat,lon);138 139 int last_dir = this.getDirectionIndex(this.startdir);140 141 for(int i = 0; i < this.maxnode; i++){142 143 // Print a counter144 if(i % 250 == 0){145 setStatus(tr("{0} nodes so far...",i));146 //System.out.println(i+" nodes so far...");147 }148 149 // Some variables we need150 int d;151 int test_x=0;152 int test_y=0;153 int new_dir = 0;154 155 // Loop through all the directions we can go156 for(d = 1; d <= this.dirslat.length; d++){157 158 // Decide which direction we want to look at from this pixel159 new_dir = (last_dir + d + 4) % 8;160 161 test_x = xy[0] + this.dirslon[new_dir];162 test_y = xy[1] + this.dirslat[new_dir];163 164 double[] geo = xy_to_geo(test_x,test_y,this.resolution);165 166 if(!bbox.contains(geo[0], geo[1])){167 System.out.println("Outside bbox");168 break;169 }170 171 v = wms.getPixel(test_x, test_y);172 if(v > this.threshold){173 break;174 }175 176 if(d == this.dirslat.length-1){177 System.out.println("Got stuck");178 break;179 }180 }181 182 // Remember this direction183 last_dir = new_dir;184 185 // Set the pixel we found as current186 xy[0] = test_x;187 xy[1] = test_y;188 189 // Break the loop if we managed to get back to our starting point190 if(xy[0] == startxy[0] && xy[1] == startxy[1]){191 break;192 }193 194 // Store this node195 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);196 nodelist.add(geo);197 //System.out.println("Adding node at "+xy[0]+","+xy[1]+" ("+geo[1]+","+geo[0]+")");198 199 // Check if we got stuck in a loop200 double start_proximity = Math.pow((geo[0] - startgeo[0]),2) + Math.pow((geo[1] - startgeo[1]),2);201 202 if(detect_loop){203 if(start_proximity < Math.pow(start_radius_small,2)){204 System.out.println("Detected loop");205 break;206 }207 }else{208 if(start_proximity > Math.pow(start_radius_big,2)){209 detect_loop = true;210 }211 } 212 }213 214 return nodelist;215 }216 217 /**218 * Remove duplicate nodes from the list219 * 220 * @param nodes221 * @return222 */223 public ArrayList<double[]> duplicateNodeRemove(ArrayList<double[]> nodes){224 225 if(nodes.size() <= 1){226 return nodes;227 }228 229 double lastnode[] = new double[] {nodes.get(0)[0], nodes.get(0)[1]};230 231 for(int i = 1; i < nodes.size(); i++){232 double[] thisnode = new double[] {nodes.get(i)[0], nodes.get(i)[1]};233 234 if(thisnode[0] == lastnode[0] && thisnode[1] == lastnode[1]){235 // Remove the node236 nodes.remove(i);237 238 // Shift back one index239 i = i - 1;240 }241 lastnode = thisnode;242 }243 244 return nodes;245 }246 247 /**248 * Reduce the number of vertices based on their proximity to each other249 * 250 * @param nodes251 * @param proximity252 * @return253 */254 public ArrayList<double[]> vertexReduce(ArrayList<double[]> nodes, double proximity){255 256 // Check if node list is empty257 if(nodes.size()<=1){258 return nodes;259 }260 261 double[] test_v = nodes.get(0);262 ArrayList<double[]> reducednodes = new ArrayList<double[]>();263 264 double prox_sq = Math.pow(proximity, 2);265 266 for(int v = 0; v < nodes.size(); v++){267 if(Math.pow(nodes.get(v)[0] - test_v[0],2) + Math.pow(nodes.get(v)[1] - test_v[1],2) > prox_sq){268 reducednodes.add(nodes.get(v));269 test_v = nodes.get(v);270 }271 }272 273 return reducednodes;274 }275 276 public double pointLineDistance(double[] p1, double[] p2, double[] p3){277 278 double x0 = p1[0];279 double y0 = p1[1];280 double x1 = p2[0];281 double y1 = p2[1];282 double x2 = p3[0];283 double y2 = p3[1];284 285 if(x2 == x1 && y2 == y1){286 return Math.sqrt(Math.pow(x1-x0,2) + Math.pow(y1-y0,2));287 } else {288 return Math.abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));289 }290 }291 292 public ArrayList<double[]> douglasPeuckerNR(ArrayList<double[]> nodes, double epsilon){293 /*294 command_stack = [(0, len(nodes) - 1)]295 296 Vector result_stack = new Vector();18 protected Collection<Command> commands = new LinkedList<Command>(); 19 protected Collection<Way> ways = new ArrayList<Way>(); 20 protected boolean cancel; 21 22 private int waylen; 23 private int maxnode; 24 private int threshold; 25 private double epsilon; 26 private int resolution; 27 private int tilesize; 28 private String startdir; 29 private String wmslayer; 30 31 private File workingdir; 32 33 private int[] dirslat = new int[] {0,1,1,1,0,-1,-1,-1}; 34 private int[] dirslon = new int[] {1,1,0,-1,-1,-1,0,1}; 35 36 double start_radius_big = 0.001; 37 double start_radius_small = 0.0002; 38 39 public Lakewalker(int waylen, int maxnode, int threshold, double epsilon, int resolution, int tilesize, String startdir, String wmslayer, File workingdir){ 40 this.waylen = waylen; 41 this.maxnode = maxnode; 42 this.threshold = threshold; 43 this.epsilon = epsilon; 44 this.resolution = resolution; 45 this.tilesize = tilesize; 46 this.startdir = startdir; 47 this.wmslayer = wmslayer; 48 49 this.workingdir = workingdir; 50 } 51 52 /** 53 * east = 0 54 * northeast = 1 55 * north = 2 56 * northwest = 3 57 * west = 4 58 * southwest = 5 59 * south = 6 60 * southeast = 7 61 */ 62 private int getDirectionIndex(String direction) throws ArrayIndexOutOfBoundsException{ 63 int i=0; 64 if(direction.equals("East") || direction.equals("east")){ 65 i = 0; 66 } else if(direction.equals("Northeast") || direction.equals("northeast")){ 67 i = 1; 68 } else if(direction.equals("North") || direction.equals("north")){ 69 i = 2; 70 } else if(direction.equals("Northwest") || direction.equals("northwest")){ 71 i = 3; 72 } else if(direction.equals("West") || direction.equals("west")){ 73 i = 4; 74 } else if(direction.equals("Southwest") || direction.equals("southwest")){ 75 i = 5; 76 } else if(direction.equals("South") || direction.equals("south")){ 77 i = 6; 78 } else if(direction.equals("Southeast") || direction.equals("southeast")){ 79 i = 7; 80 } else { 81 throw new ArrayIndexOutOfBoundsException(tr("Direction index '{0}' not found",direction)); 82 } 83 return i; 84 } 85 86 /** 87 * Do a trace 88 * 89 * @param lat 90 * @param lon 91 * @param tl_lon 92 * @param br_lon 93 * @param tl_lat 94 * @param br_lat 95 */ 96 public ArrayList<double[]> trace(double lat, double lon, double tl_lon, double br_lon, double tl_lat, double br_lat) throws LakewalkerException { 97 98 LakewalkerWMS wms = new LakewalkerWMS(this.resolution, this.tilesize, this.wmslayer, this.workingdir); 99 LakewalkerBBox bbox = new LakewalkerBBox(tl_lat,tl_lon,br_lat,br_lon); 100 101 Boolean detect_loop = false; 102 103 ArrayList<double[]> nodelist = new ArrayList<double[]>(); 104 105 int[] xy = geo_to_xy(lat,lon,this.resolution); 106 107 if(!bbox.contains(lat, lon)){ 108 throw new LakewalkerException(tr("The starting location was not within the bbox")); 109 } 110 111 int v; 112 113 setStatus(tr("Looking for shoreline...")); 114 115 while(true){ 116 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution); 117 if(bbox.contains(geo[0],geo[1])==false){ 118 break; 119 } 120 121 v = wms.getPixel(xy[0], xy[1]); 122 if(v > this.threshold){ 123 break; 124 } 125 126 int delta_lat = this.dirslat[getDirectionIndex(this.startdir)]; 127 int delta_lon = this.dirslon[getDirectionIndex(this.startdir)]; 128 129 xy[0] = xy[0]+delta_lon; 130 xy[1] = xy[1]+delta_lat; 131 132 } 133 134 int[] startxy = new int[] {xy[0], xy[1]}; 135 double[] startgeo = xy_to_geo(xy[0],xy[1],this.resolution); 136 137 //System.out.printf("Found shore at lat %.4f lon %.4f\n",lat,lon); 138 139 int last_dir = this.getDirectionIndex(this.startdir); 140 141 for(int i = 0; i < this.maxnode; i++){ 142 143 // Print a counter 144 if(i % 250 == 0){ 145 setStatus(tr("{0} nodes so far...",i)); 146 //System.out.println(i+" nodes so far..."); 147 } 148 149 // Some variables we need 150 int d; 151 int test_x=0; 152 int test_y=0; 153 int new_dir = 0; 154 155 // Loop through all the directions we can go 156 for(d = 1; d <= this.dirslat.length; d++){ 157 158 // Decide which direction we want to look at from this pixel 159 new_dir = (last_dir + d + 4) % 8; 160 161 test_x = xy[0] + this.dirslon[new_dir]; 162 test_y = xy[1] + this.dirslat[new_dir]; 163 164 double[] geo = xy_to_geo(test_x,test_y,this.resolution); 165 166 if(!bbox.contains(geo[0], geo[1])){ 167 System.out.println("Outside bbox"); 168 break; 169 } 170 171 v = wms.getPixel(test_x, test_y); 172 if(v > this.threshold){ 173 break; 174 } 175 176 if(d == this.dirslat.length-1){ 177 System.out.println("Got stuck"); 178 break; 179 } 180 } 181 182 // Remember this direction 183 last_dir = new_dir; 184 185 // Set the pixel we found as current 186 xy[0] = test_x; 187 xy[1] = test_y; 188 189 // Break the loop if we managed to get back to our starting point 190 if(xy[0] == startxy[0] && xy[1] == startxy[1]){ 191 break; 192 } 193 194 // Store this node 195 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution); 196 nodelist.add(geo); 197 //System.out.println("Adding node at "+xy[0]+","+xy[1]+" ("+geo[1]+","+geo[0]+")"); 198 199 // Check if we got stuck in a loop 200 double start_proximity = Math.pow((geo[0] - startgeo[0]),2) + Math.pow((geo[1] - startgeo[1]),2); 201 202 if(detect_loop){ 203 if(start_proximity < Math.pow(start_radius_small,2)){ 204 System.out.println("Detected loop"); 205 break; 206 } 207 }else{ 208 if(start_proximity > Math.pow(start_radius_big,2)){ 209 detect_loop = true; 210 } 211 } 212 } 213 214 return nodelist; 215 } 216 217 /** 218 * Remove duplicate nodes from the list 219 * 220 * @param nodes 221 * @return 222 */ 223 public ArrayList<double[]> duplicateNodeRemove(ArrayList<double[]> nodes){ 224 225 if(nodes.size() <= 1){ 226 return nodes; 227 } 228 229 double lastnode[] = new double[] {nodes.get(0)[0], nodes.get(0)[1]}; 230 231 for(int i = 1; i < nodes.size(); i++){ 232 double[] thisnode = new double[] {nodes.get(i)[0], nodes.get(i)[1]}; 233 234 if(thisnode[0] == lastnode[0] && thisnode[1] == lastnode[1]){ 235 // Remove the node 236 nodes.remove(i); 237 238 // Shift back one index 239 i = i - 1; 240 } 241 lastnode = thisnode; 242 } 243 244 return nodes; 245 } 246 247 /** 248 * Reduce the number of vertices based on their proximity to each other 249 * 250 * @param nodes 251 * @param proximity 252 * @return 253 */ 254 public ArrayList<double[]> vertexReduce(ArrayList<double[]> nodes, double proximity){ 255 256 // Check if node list is empty 257 if(nodes.size()<=1){ 258 return nodes; 259 } 260 261 double[] test_v = nodes.get(0); 262 ArrayList<double[]> reducednodes = new ArrayList<double[]>(); 263 264 double prox_sq = Math.pow(proximity, 2); 265 266 for(int v = 0; v < nodes.size(); v++){ 267 if(Math.pow(nodes.get(v)[0] - test_v[0],2) + Math.pow(nodes.get(v)[1] - test_v[1],2) > prox_sq){ 268 reducednodes.add(nodes.get(v)); 269 test_v = nodes.get(v); 270 } 271 } 272 273 return reducednodes; 274 } 275 276 public double pointLineDistance(double[] p1, double[] p2, double[] p3){ 277 278 double x0 = p1[0]; 279 double y0 = p1[1]; 280 double x1 = p2[0]; 281 double y1 = p2[1]; 282 double x2 = p3[0]; 283 double y2 = p3[1]; 284 285 if(x2 == x1 && y2 == y1){ 286 return Math.sqrt(Math.pow(x1-x0,2) + Math.pow(y1-y0,2)); 287 } else { 288 return Math.abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2)); 289 } 290 } 291 292 public ArrayList<double[]> douglasPeuckerNR(ArrayList<double[]> nodes, double epsilon){ 293 /* 294 command_stack = [(0, len(nodes) - 1)] 295 296 Vector result_stack = new Vector(); 297 297 298 298 while(command_stack.size() > 0){ 299 cmd = command_stack.pop();300 if(type(cmd) == tuple){301 (start, end) = cmd302 (node, dist) = dp_findpoint(nodes, start, end)303 if(dist > epsilon){304 command_stack.append("+")305 command_stack.append((start, node))306 command_stack.append((node, end))307 } else {308 result_stack.append((start, end))309 }310 } elseif(cmd == "+"){311 first = result_stack.pop()312 second = result_stack.pop()313 if(first[-1] == second[0]){314 result_stack.append(first + second[1:])315 //print "Added %s and %s; result is %s" % (first, second, result_stack[-1])316 }else {317 error("ERROR: Cannot connect nodestrings!")318 #print first319 #print second320 return;321 }322 } else {323 error("ERROR: Can't understand command \"%s\"" % (cmd,))324 return325 326 if(len(result_stack) == 1){327 return [nodes[x] for x in result_stack[0]];328 } else {329 error("ERROR: Command stack is empty but result stack has %d nodes!" % len(result_stack));330 return;331 }332 333 farthest_node = None334 farthest_dist = 0335 first = nodes[0]336 last = nodes[-1]337 338 for(i in xrange(1, len(nodes) - 1){339 d = point_line_distance(nodes[i], first, last)340 if(d > farthest_dist){341 farthest_dist = d342 farthest_node = i343 }344 }345 if(farthest_dist > epsilon){346 seg_a = douglas_peucker(nodes[0:farthest_node+1], epsilon)347 seg_b = douglas_peucker(nodes[farthest_node:-1], epsilon)348 //print "Minimized %d nodes to %d + %d nodes" % (len(nodes), len(seg_a), len(seg_b))349 nodes = seg_a[:-1] + seg_b350 } else {351 return [nodes[0], nodes[-1]];352 }353 */354 return nodes;355 }356 357 public ArrayList<double[]> douglasPeucker(ArrayList<double[]> nodes, double epsilon){358 359 // Check if node list is empty360 if(nodes.size()<=1){361 return nodes;362 }363 364 int farthest_node = -1;365 double farthest_dist = 0;366 double[] first = nodes.get(0);367 double[] last = nodes.get(nodes.size()-1);368 369 ArrayList<double[]> new_nodes = new ArrayList<double[]>();370 371 double d = 0;372 373 for(int i = 1; i < nodes.size(); i++){374 d = pointLineDistance(nodes.get(i),first,last);375 if(d>farthest_dist){376 farthest_dist = d;377 farthest_node = i;378 }379 }380 381 ArrayList<double[]> seg_a = new ArrayList<double[]>();382 ArrayList<double[]> seg_b = new ArrayList<double[]>();383 384 if(farthest_dist > epsilon){385 seg_a = douglasPeucker(sublist(nodes,0,farthest_node+1),epsilon);386 seg_b = douglasPeucker(sublist(nodes,farthest_node,nodes.size()-1),epsilon);387 388 new_nodes.addAll(seg_a);389 new_nodes.addAll(seg_b);390 } else {391 new_nodes.add(nodes.get(0));392 new_nodes.add(nodes.get(nodes.size()-1));393 }394 return new_nodes;395 }396 397 private ArrayList<double[]> sublist(ArrayList<double[]> l, int i, int f) throws ArrayIndexOutOfBoundsException {398 ArrayList<double[]> sub = new ArrayList<double[]>();399 400 if(f<i || i < 0 || f < 0 || f > l.size()){401 throw new ArrayIndexOutOfBoundsException();402 }403 404 for(int j = i; j < f; j++){405 sub.add(l.get(j));406 }407 return sub;408 }409 410 public double[] xy_to_geo(int x, int y, double resolution){411 double[] geo = new double[2];412 geo[0] = y / resolution;413 geo[1] = x / resolution;414 return geo;415 }416 417 public int[] geo_to_xy(double lat, double lon, double resolution){418 int[] xy = new int[2];419 420 xy[0] = (int)Math.floor(lon * resolution + 0.5);421 xy[1] = (int)Math.floor(lat * resolution + 0.5);422 423 return xy;424 }425 426 /*299 cmd = command_stack.pop(); 300 if(type(cmd) == tuple){ 301 (start, end) = cmd 302 (node, dist) = dp_findpoint(nodes, start, end) 303 if(dist > epsilon){ 304 command_stack.append("+") 305 command_stack.append((start, node)) 306 command_stack.append((node, end)) 307 } else { 308 result_stack.append((start, end)) 309 } 310 } elseif(cmd == "+"){ 311 first = result_stack.pop() 312 second = result_stack.pop() 313 if(first[-1] == second[0]){ 314 result_stack.append(first + second[1:]) 315 //print "Added %s and %s; result is %s" % (first, second, result_stack[-1]) 316 }else { 317 error("ERROR: Cannot connect nodestrings!") 318 #print first 319 #print second 320 return; 321 } 322 } else { 323 error("ERROR: Can't understand command \"%s\"" % (cmd,)) 324 return 325 326 if(len(result_stack) == 1){ 327 return [nodes[x] for x in result_stack[0]]; 328 } else { 329 error("ERROR: Command stack is empty but result stack has %d nodes!" % len(result_stack)); 330 return; 331 } 332 333 farthest_node = None 334 farthest_dist = 0 335 first = nodes[0] 336 last = nodes[-1] 337 338 for(i in xrange(1, len(nodes) - 1){ 339 d = point_line_distance(nodes[i], first, last) 340 if(d > farthest_dist){ 341 farthest_dist = d 342 farthest_node = i 343 } 344 } 345 if(farthest_dist > epsilon){ 346 seg_a = douglas_peucker(nodes[0:farthest_node+1], epsilon) 347 seg_b = douglas_peucker(nodes[farthest_node:-1], epsilon) 348 //print "Minimized %d nodes to %d + %d nodes" % (len(nodes), len(seg_a), len(seg_b)) 349 nodes = seg_a[:-1] + seg_b 350 } else { 351 return [nodes[0], nodes[-1]]; 352 } 353 */ 354 return nodes; 355 } 356 357 public ArrayList<double[]> douglasPeucker(ArrayList<double[]> nodes, double epsilon){ 358 359 // Check if node list is empty 360 if(nodes.size()<=1){ 361 return nodes; 362 } 363 364 int farthest_node = -1; 365 double farthest_dist = 0; 366 double[] first = nodes.get(0); 367 double[] last = nodes.get(nodes.size()-1); 368 369 ArrayList<double[]> new_nodes = new ArrayList<double[]>(); 370 371 double d = 0; 372 373 for(int i = 1; i < nodes.size(); i++){ 374 d = pointLineDistance(nodes.get(i),first,last); 375 if(d>farthest_dist){ 376 farthest_dist = d; 377 farthest_node = i; 378 } 379 } 380 381 ArrayList<double[]> seg_a = new ArrayList<double[]>(); 382 ArrayList<double[]> seg_b = new ArrayList<double[]>(); 383 384 if(farthest_dist > epsilon){ 385 seg_a = douglasPeucker(sublist(nodes,0,farthest_node+1),epsilon); 386 seg_b = douglasPeucker(sublist(nodes,farthest_node,nodes.size()-1),epsilon); 387 388 new_nodes.addAll(seg_a); 389 new_nodes.addAll(seg_b); 390 } else { 391 new_nodes.add(nodes.get(0)); 392 new_nodes.add(nodes.get(nodes.size()-1)); 393 } 394 return new_nodes; 395 } 396 397 private ArrayList<double[]> sublist(ArrayList<double[]> l, int i, int f) throws ArrayIndexOutOfBoundsException { 398 ArrayList<double[]> sub = new ArrayList<double[]>(); 399 400 if(f<i || i < 0 || f < 0 || f > l.size()){ 401 throw new ArrayIndexOutOfBoundsException(); 402 } 403 404 for(int j = i; j < f; j++){ 405 sub.add(l.get(j)); 406 } 407 return sub; 408 } 409 410 public double[] xy_to_geo(int x, int y, double resolution){ 411 double[] geo = new double[2]; 412 geo[0] = y / resolution; 413 geo[1] = x / resolution; 414 return geo; 415 } 416 417 public int[] geo_to_xy(double lat, double lon, double resolution){ 418 int[] xy = new int[2]; 419 420 xy[0] = (int)Math.floor(lon * resolution + 0.5); 421 xy[1] = (int)Math.floor(lat * resolution + 0.5); 422 423 return xy; 424 } 425 426 /* 427 427 * User has hit the cancel button 428 */429 public void cancel() {430 cancel = true;431 }432 433 protected void setStatus(String s) {434 Main.pleaseWaitDlg.currentAction.setText(s);435 Main.pleaseWaitDlg.repaint();436 }437 438 /**439 * Class to do checking of whether the point is within our bbox440 * 441 * @author Jason Reid442 */443 private class LakewalkerBBox {444 445 private double top = 90;446 private double left = -180;447 private double bottom = -90;448 private double right = 180;449 450 protected LakewalkerBBox(double top, double left, double bottom, double right){451 this.left = left;452 this.right = right;453 this.top = top;454 this.bottom = bottom;455 }456 457 protected Boolean contains(double lat, double lon){458 if(lat >= this.top || lat <= this.bottom){459 return false;460 }461 if(lon >= this.right || lon <= this.left){462 return false;463 }464 if((this.right - this.left) % 360 == 0){465 return true;466 }467 return (lon - this.left) % 360 <= (this.right - this.left) % 360;468 }469 }470 private void printarr(int[] a){471 for(int i = 0; i<a.length; i++){472 System.out.println(i+": "+a[i]);473 }474 }428 */ 429 public void cancel() { 430 cancel = true; 431 } 432 433 protected void setStatus(String s) { 434 Main.pleaseWaitDlg.currentAction.setText(s); 435 Main.pleaseWaitDlg.repaint(); 436 } 437 438 /** 439 * Class to do checking of whether the point is within our bbox 440 * 441 * @author Jason Reid 442 */ 443 private class LakewalkerBBox { 444 445 private double top = 90; 446 private double left = -180; 447 private double bottom = -90; 448 private double right = 180; 449 450 protected LakewalkerBBox(double top, double left, double bottom, double right){ 451 this.left = left; 452 this.right = right; 453 this.top = top; 454 this.bottom = bottom; 455 } 456 457 protected Boolean contains(double lat, double lon){ 458 if(lat >= this.top || lat <= this.bottom){ 459 return false; 460 } 461 if(lon >= this.right || lon <= this.left){ 462 return false; 463 } 464 if((this.right - this.left) % 360 == 0){ 465 return true; 466 } 467 return (lon - this.left) % 360 <= (this.right - this.left) % 360; 468 } 469 } 470 private void printarr(int[] a){ 471 for(int i = 0; i<a.length; i++){ 472 System.out.println(i+": "+a[i]); 473 } 474 } 475 475 } 476 476 -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerAction.java
r12479 r12778 35 35 /** 36 36 * Interface to Darryl Shpak's Lakewalker module 37 * 37 * 38 38 * @author Brent Easton 39 39 */ … … 45 45 protected Thread executeThread; 46 46 protected boolean cancel; 47 47 48 48 protected Collection<Command> commands = new LinkedList<Command>(); 49 49 protected Collection<Way> ways = new ArrayList<Way>(); … … 56 56 setEnabled(true); 57 57 } 58 58 59 59 public void actionPerformed(ActionEvent e) { 60 60 if(Main.map == null || Main.map.mapView == null) … … 78 78 */ 79 79 private void cleanupCache() { 80 final long maxCacheAge = System.currentTimeMillis()-Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHEAGE, 100)*24*60*60*1000L;81 final long maxCacheSize = Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHESIZE, 300)*1024*1024;82 83 for (String wmsFolder : LakewalkerPreferences.WMSLAYERS) {84 String wmsCacheDirName = Main.pref.getPreferencesDir()+"plugins/Lakewalker/"+wmsFolder;85 File wmsCacheDir = new File(wmsCacheDirName);86 87 if (wmsCacheDir.exists() && wmsCacheDir.isDirectory()) {88 File wmsCache[] = wmsCacheDir.listFiles();89 90 // sort files by date (most recent first)91 Arrays.sort(wmsCache, new Comparator<File>() {92 public int compare(File f1, File f2) {93 return (int)(f2.lastModified()-f1.lastModified());94 }95 });96 97 // delete aged or oversized, keep newest. Once size/age limit was reached delete all older files98 long folderSize = 0;99 boolean quickdelete = false;100 for (File cacheEntry : wmsCache) {101 if (!cacheEntry.isFile()) continue;102 if (!quickdelete) {103 folderSize += cacheEntry.length();104 if (folderSize > maxCacheSize) {105 quickdelete = true;106 } else if (cacheEntry.lastModified() < maxCacheAge) {107 quickdelete = true;108 }109 }110 111 if (quickdelete) {112 cacheEntry.delete();113 }114 }115 116 } else {117 // create cache directory118 if (!wmsCacheDir.mkdirs()) {119 JOptionPane.showMessageDialog(Main.parent, tr("Error creating cache directory: {0}", wmsCacheDirName));120 }121 }122 }123 } 124 80 final long maxCacheAge = System.currentTimeMillis()-Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHEAGE, 100)*24*60*60*1000L; 81 final long maxCacheSize = Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHESIZE, 300)*1024*1024; 82 83 for (String wmsFolder : LakewalkerPreferences.WMSLAYERS) { 84 String wmsCacheDirName = Main.pref.getPreferencesDir()+"plugins/Lakewalker/"+wmsFolder; 85 File wmsCacheDir = new File(wmsCacheDirName); 86 87 if (wmsCacheDir.exists() && wmsCacheDir.isDirectory()) { 88 File wmsCache[] = wmsCacheDir.listFiles(); 89 90 // sort files by date (most recent first) 91 Arrays.sort(wmsCache, new Comparator<File>() { 92 public int compare(File f1, File f2) { 93 return (int)(f2.lastModified()-f1.lastModified()); 94 } 95 }); 96 97 // delete aged or oversized, keep newest. Once size/age limit was reached delete all older files 98 long folderSize = 0; 99 boolean quickdelete = false; 100 for (File cacheEntry : wmsCache) { 101 if (!cacheEntry.isFile()) continue; 102 if (!quickdelete) { 103 folderSize += cacheEntry.length(); 104 if (folderSize > maxCacheSize) { 105 quickdelete = true; 106 } else if (cacheEntry.lastModified() < maxCacheAge) { 107 quickdelete = true; 108 } 109 } 110 111 if (quickdelete) { 112 cacheEntry.delete(); 113 } 114 } 115 116 } else { 117 // create cache directory 118 if (!wmsCacheDir.mkdirs()) { 119 JOptionPane.showMessageDialog(Main.parent, tr("Error creating cache directory: {0}", wmsCacheDirName)); 120 } 121 } 122 } 123 } 124 125 125 protected void lakewalk(Point clickPoint){ 126 /**127 * Positional data128 */129 final LatLon pos = Main.map.mapView.getLatLon(clickPoint.x, clickPoint.y);130 final LatLon topLeft = Main.map.mapView.getLatLon(0, 0);131 final LatLon botRight = Main.map.mapView.getLatLon(Main.map.mapView.getWidth(), Main.map.mapView132 .getHeight());133 134 /**135 * Cache/working directory location136 */137 final File working_dir = new File(Main.pref.getPreferencesDir(), "plugins/Lakewalker");138 139 /*140 * Collect options141 */142 final int waylen = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500);143 final int maxnode = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_NODES, 50000);144 final int threshold = Main.pref.getInteger(LakewalkerPreferences.PREF_THRESHOLD_VALUE, 90);145 final double epsilon = Main.pref.getDouble(LakewalkerPreferences.PREF_EPSILON, 0.0003);146 final int resolution = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_RES, 4000);147 final int tilesize = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_SIZE, 2000);148 final String startdir = Main.pref.get(LakewalkerPreferences.PREF_START_DIR, "east");149 final String wmslayer = Main.pref.get(LakewalkerPreferences.PREF_WMS, "IR1");150 151 try {126 /** 127 * Positional data 128 */ 129 final LatLon pos = Main.map.mapView.getLatLon(clickPoint.x, clickPoint.y); 130 final LatLon topLeft = Main.map.mapView.getLatLon(0, 0); 131 final LatLon botRight = Main.map.mapView.getLatLon(Main.map.mapView.getWidth(), Main.map.mapView 132 .getHeight()); 133 134 /** 135 * Cache/working directory location 136 */ 137 final File working_dir = new File(Main.pref.getPreferencesDir(), "plugins/Lakewalker"); 138 139 /* 140 * Collect options 141 */ 142 final int waylen = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500); 143 final int maxnode = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_NODES, 50000); 144 final int threshold = Main.pref.getInteger(LakewalkerPreferences.PREF_THRESHOLD_VALUE, 90); 145 final double epsilon = Main.pref.getDouble(LakewalkerPreferences.PREF_EPSILON, 0.0003); 146 final int resolution = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_RES, 4000); 147 final int tilesize = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_SIZE, 2000); 148 final String startdir = Main.pref.get(LakewalkerPreferences.PREF_START_DIR, "east"); 149 final String wmslayer = Main.pref.get(LakewalkerPreferences.PREF_WMS, "IR1"); 150 151 try { 152 152 PleaseWaitRunnable lakewalkerTask = new PleaseWaitRunnable(tr("Tracing")){ 153 153 @Override protected void realRun() throws SAXException { 154 setStatus(tr("checking cache..."));155 cleanupCache();156 processnodelist(pos, topLeft, botRight, waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,working_dir);154 setStatus(tr("checking cache...")); 155 cleanupCache(); 156 processnodelist(pos, topLeft, botRight, waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,working_dir); 157 157 } 158 158 @Override protected void finish() { 159 159 160 160 } 161 161 @Override protected void cancel() { … … 168 168 catch (Exception ex) { 169 169 System.out.println("Exception caught: " + ex.getMessage()); 170 } 171 } 172 170 } 171 } 172 173 173 private void processnodelist(LatLon pos, LatLon topLeft, LatLon botRight, int waylen, int maxnode, int threshold, double epsilon, int resolution, int tilesize, String startdir, String wmslayer, File workingdir){ 174 175 ArrayList<double[]> nodelist = new ArrayList<double[]>();176 177 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,workingdir);178 try {179 nodelist = lw.trace(pos.lat(),pos.lon(),topLeft.lon(),botRight.lon(),topLeft.lat(),botRight.lat());180 } catch(LakewalkerException e){181 System.out.println(e.getError());182 }183 184 System.out.println(nodelist.size()+" nodes generated");185 186 /**187 * Run the nodelist through a vertex reduction algorithm188 */189 190 setStatus(tr("Running vertex reduction..."));191 192 nodelist = lw.vertexReduce(nodelist, epsilon);193 194 //System.out.println("After vertex reduction "+nodelist.size()+" nodes remain.");195 196 /**197 * And then through douglas-peucker approximation198 */199 200 setStatus(tr("Running Douglas-Peucker approximation..."));201 202 nodelist = lw.douglasPeucker(nodelist, epsilon);203 204 //System.out.println("After Douglas-Peucker approximation "+nodelist.size()+" nodes remain.");205 206 /**207 * And then through a duplicate node remover208 */209 210 setStatus(tr("Removing duplicate nodes..."));211 212 nodelist = lw.duplicateNodeRemove(nodelist);213 214 //System.out.println("After removing duplicate nodes, "+nodelist.size()+" nodes remain.");215 216 217 // if for some reason (image loading failed, ...) nodelist is empty, no more processing required.218 if (nodelist.size() == 0) {219 return;220 }221 222 /**223 * Turn the arraylist into osm nodes224 */225 226 Way way = new Way();227 Node n = null;228 Node fn = null;229 230 double eastOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_EAST_OFFSET, 0.0);231 double northOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_NORTH_OFFSET, 0.0);232 233 int nodesinway = 0;234 235 for(int i = 0; i< nodelist.size(); i++){236 if (cancel) {237 return;238 }239 240 try {241 LatLon ll = new LatLon(nodelist.get(i)[0]+northOffset, nodelist.get(i)[1]+eastOffset);242 n = new Node(ll);243 if(fn==null){244 fn = n;245 }246 commands.add(new AddCommand(n));247 248 } catch (Exception ex) {249 } 250 251 way.nodes.add(n);252 253 if(nodesinway > Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500)){254 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water");255 256 if(!waytype.equals("none")){257 way.put("natural",waytype);258 }259 260 way.put("created_by", "Dshpak_landsat_lakes");261 commands.add(new AddCommand(way));262 263 way = new Way();264 265 way.nodes.add(n);266 267 nodesinway = 0;268 }269 nodesinway++;270 }271 272 273 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water");274 174 175 ArrayList<double[]> nodelist = new ArrayList<double[]>(); 176 177 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,workingdir); 178 try { 179 nodelist = lw.trace(pos.lat(),pos.lon(),topLeft.lon(),botRight.lon(),topLeft.lat(),botRight.lat()); 180 } catch(LakewalkerException e){ 181 System.out.println(e.getError()); 182 } 183 184 System.out.println(nodelist.size()+" nodes generated"); 185 186 /** 187 * Run the nodelist through a vertex reduction algorithm 188 */ 189 190 setStatus(tr("Running vertex reduction...")); 191 192 nodelist = lw.vertexReduce(nodelist, epsilon); 193 194 //System.out.println("After vertex reduction "+nodelist.size()+" nodes remain."); 195 196 /** 197 * And then through douglas-peucker approximation 198 */ 199 200 setStatus(tr("Running Douglas-Peucker approximation...")); 201 202 nodelist = lw.douglasPeucker(nodelist, epsilon); 203 204 //System.out.println("After Douglas-Peucker approximation "+nodelist.size()+" nodes remain."); 205 206 /** 207 * And then through a duplicate node remover 208 */ 209 210 setStatus(tr("Removing duplicate nodes...")); 211 212 nodelist = lw.duplicateNodeRemove(nodelist); 213 214 //System.out.println("After removing duplicate nodes, "+nodelist.size()+" nodes remain."); 215 216 217 // if for some reason (image loading failed, ...) nodelist is empty, no more processing required. 218 if (nodelist.size() == 0) { 219 return; 220 } 221 222 /** 223 * Turn the arraylist into osm nodes 224 */ 225 226 Way way = new Way(); 227 Node n = null; 228 Node fn = null; 229 230 double eastOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_EAST_OFFSET, 0.0); 231 double northOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_NORTH_OFFSET, 0.0); 232 233 int nodesinway = 0; 234 235 for(int i = 0; i< nodelist.size(); i++){ 236 if (cancel) { 237 return; 238 } 239 240 try { 241 LatLon ll = new LatLon(nodelist.get(i)[0]+northOffset, nodelist.get(i)[1]+eastOffset); 242 n = new Node(ll); 243 if(fn==null){ 244 fn = n; 245 } 246 commands.add(new AddCommand(n)); 247 248 } catch (Exception ex) { 249 } 250 251 way.nodes.add(n); 252 253 if(nodesinway > Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500)){ 254 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water"); 255 256 if(!waytype.equals("none")){ 257 way.put("natural",waytype); 258 } 259 260 way.put("created_by", "Dshpak_landsat_lakes"); 261 commands.add(new AddCommand(way)); 262 263 way = new Way(); 264 265 way.nodes.add(n); 266 267 nodesinway = 0; 268 } 269 nodesinway++; 270 } 271 272 273 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water"); 274 275 275 if(!waytype.equals("none")){ 276 way.put("natural",waytype);277 } 278 276 way.put("natural",waytype); 277 } 278 279 279 way.put("created_by", "Dshpak_landsat_lakes"); 280 281 way.nodes.add(fn);282 283 commands.add(new AddCommand(way));284 285 if (!commands.isEmpty()) {280 281 way.nodes.add(fn); 282 283 commands.add(new AddCommand(way)); 284 285 if (!commands.isEmpty()) { 286 286 Main.main.undoRedo.add(new SequenceCommand(tr("Lakewalker trace"), commands)); 287 287 Main.ds.setSelected(ways); 288 288 } else { 289 System.out.println("Failed");290 } 291 292 commands = new LinkedList<Command>();293 ways = new ArrayList<Way>();294 295 } 296 289 System.out.println("Failed"); 290 } 291 292 commands = new LinkedList<Command>(); 293 ways = new ArrayList<Way>(); 294 295 } 296 297 297 public void cancel() { 298 cancel = true;298 cancel = true; 299 299 } 300 300 … … 317 317 } 318 318 protected void setStatus(String s) { 319 Main.pleaseWaitDlg.currentAction.setText(s);320 Main.pleaseWaitDlg.repaint();319 Main.pleaseWaitDlg.currentAction.setText(s); 320 Main.pleaseWaitDlg.repaint(); 321 321 } 322 322 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerApp.java
r9273 r12778 5 5 6 6 public class LakewalkerApp { 7 public static void main(String[] args){8 double lat = 52.31384;9 double lon = -79.135;10 double toplat = 52.3165;11 double botlat = 52.3041;12 double leftlon = -79.1442;13 double rightlon = -79.1093;14 15 // ?lat=39.15579999999999&lon=2.9411&zoom=12&layers=B000F000F16 lat = 39.1422;17 lon = 2.9102;18 19 toplat = 39.2229;20 botlat = 39.0977;21 leftlon = 2.8560;22 rightlon = 3.0462;23 24 int waylen = 250;25 int maxnode = 5000;26 int threshold = 100;27 double dp = 0.0003;28 int tilesize = 2000;29 int resolution = 4000;30 String startdir = "East";31 String wmslayer = "IR2";32 33 File working_dir = new File("Lakewalker");34 35 ArrayList<double[]> nodelist = null;36 37 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,dp,resolution,tilesize,startdir,wmslayer,working_dir);38 try {39 nodelist = lw.trace(lat,lon,leftlon,rightlon,toplat,botlat);40 } catch(LakewalkerException e){41 System.out.println(e.getError());42 }43 44 System.out.println(nodelist.size()+" nodes generated");45 46 nodelist = lw.vertexReduce(nodelist, dp);47 48 System.out.println("After vertex reduction, "+nodelist.size()+" nodes remain.");49 50 nodelist = lw.douglasPeucker(nodelist, dp);51 52 System.out.println("After dp approximation, "+nodelist.size()+" nodes remain.");53 54 55 56 }7 public static void main(String[] args){ 8 double lat = 52.31384; 9 double lon = -79.135; 10 double toplat = 52.3165; 11 double botlat = 52.3041; 12 double leftlon = -79.1442; 13 double rightlon = -79.1093; 14 15 // ?lat=39.15579999999999&lon=2.9411&zoom=12&layers=B000F000F 16 lat = 39.1422; 17 lon = 2.9102; 18 19 toplat = 39.2229; 20 botlat = 39.0977; 21 leftlon = 2.8560; 22 rightlon = 3.0462; 23 24 int waylen = 250; 25 int maxnode = 5000; 26 int threshold = 100; 27 double dp = 0.0003; 28 int tilesize = 2000; 29 int resolution = 4000; 30 String startdir = "East"; 31 String wmslayer = "IR2"; 32 33 File working_dir = new File("Lakewalker"); 34 35 ArrayList<double[]> nodelist = null; 36 37 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,dp,resolution,tilesize,startdir,wmslayer,working_dir); 38 try { 39 nodelist = lw.trace(lat,lon,leftlon,rightlon,toplat,botlat); 40 } catch(LakewalkerException e){ 41 System.out.println(e.getError()); 42 } 43 44 System.out.println(nodelist.size()+" nodes generated"); 45 46 nodelist = lw.vertexReduce(nodelist, dp); 47 48 System.out.println("After vertex reduction, "+nodelist.size()+" nodes remain."); 49 50 nodelist = lw.douglasPeucker(nodelist, dp); 51 52 System.out.println("After dp approximation, "+nodelist.size()+" nodes remain."); 53 54 55 56 } 57 57 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerException.java
r6910 r12778 2 2 3 3 class LakewalkerException extends Exception { 4 String error;5 6 public LakewalkerException(){7 super();8 this.error = "An unknown error has occured";9 }10 11 public LakewalkerException(String err){12 super();13 this.error = err;14 }15 16 public String getError(){17 return this.error;18 }4 String error; 5 6 public LakewalkerException(){ 7 super(); 8 this.error = "An unknown error has occured"; 9 } 10 11 public LakewalkerException(String err){ 12 super(); 13 this.error = err; 14 } 15 16 public String getError(){ 17 return this.error; 18 } 19 19 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerPlugin.java
r12255 r12778 10 10 /** 11 11 * Interface to Darryl Shpak's Lakewalker python module 12 * 12 * 13 13 * @author Brent Easton 14 14 */ … … 18 18 } 19 19 20 public PreferenceSetting getPreferenceSetting() 20 public PreferenceSetting getPreferenceSetting() 21 21 { 22 22 return new LakewalkerPreferences(); -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerReader.java
r10920 r12778 51 51 52 52 try { 53 54 Node n = null; // The current node being created55 Node tn = null; // The last node of the previous way53 54 Node n = null; // The current node being created 55 Node tn = null; // The last node of the previous way 56 56 Node fn = null; // Node to hold the first node in the trace 57 57 58 58 while ((line = input.readLine()) != null) { 59 59 if (cancel) { … … 67 67 68 68 if(tn==null){ 69 try {70 LatLon ll = new LatLon(Double.parseDouble(tokens[1])+northOffset, Double.parseDouble(tokens[2])+eastOffset);71 n = new Node(ll);72 if(fn==null){73 fn = n;74 }75 commands.add(new AddCommand(n));76 }77 catch (Exception ex) {78 79 }69 try { 70 LatLon ll = new LatLon(Double.parseDouble(tokens[1])+northOffset, Double.parseDouble(tokens[2])+eastOffset); 71 n = new Node(ll); 72 if(fn==null){ 73 fn = n; 74 } 75 commands.add(new AddCommand(n)); 76 } 77 catch (Exception ex) { 78 79 } 80 80 81 81 } else { 82 82 // If there is a last node, and this node has the same coordinates 83 83 // then we substitute for the previous node 84 n = tn;85 tn = null;84 n = tn; 85 tn = null; 86 86 } 87 88 way.nodes.add(n);87 88 way.nodes.add(n); 89 89 90 90 break; … … 98 98 99 99 if(!waytype.equals("none")){ 100 way.put("natural",waytype);100 way.put("natural",waytype); 101 101 } 102 102 … … 106 106 break; 107 107 108 case 't': 109 way = new Way();110 tn = n;111 break;108 case 't': 109 way = new Way(); 110 tn = n; 111 break; 112 112 113 113 case 'e': -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerWMS.java
r11924 r12778 17 17 18 18 public class LakewalkerWMS { 19 20 private BufferedImage image;21 private int imagex;22 private int imagey;23 24 // Vector to cache images in memory25 private Vector<BufferedImage> images = new Vector<BufferedImage>();26 // Hashmap to hold the mapping of cached images27 private HashMap<String,Integer> imageindex = new HashMap<String,Integer>();28 29 private int resolution;30 private int tilesize;31 32 private String wmslayer;33 34 private File working_dir;35 36 public LakewalkerWMS(int resolution, int tilesize, String wmslayer, File workdir){37 this.resolution = resolution;38 this.tilesize = tilesize;39 this.working_dir = workdir;40 this.wmslayer = wmslayer;41 }42 43 public BufferedImage getTile(int x, int y) throws LakewalkerException {44 String status = getStatus();45 setStatus(tr("Downloading image tile..."));46 47 String layer = "global_mosaic_base";48 49 int[] bottom_left_xy = new int[2];50 bottom_left_xy[0] = floor(x,this.tilesize);51 bottom_left_xy[1] = floor(y,this.tilesize);52 53 int[] top_right_xy = new int[2]; 19 20 private BufferedImage image; 21 private int imagex; 22 private int imagey; 23 24 // Vector to cache images in memory 25 private Vector<BufferedImage> images = new Vector<BufferedImage>(); 26 // Hashmap to hold the mapping of cached images 27 private HashMap<String,Integer> imageindex = new HashMap<String,Integer>(); 28 29 private int resolution; 30 private int tilesize; 31 32 private String wmslayer; 33 34 private File working_dir; 35 36 public LakewalkerWMS(int resolution, int tilesize, String wmslayer, File workdir){ 37 this.resolution = resolution; 38 this.tilesize = tilesize; 39 this.working_dir = workdir; 40 this.wmslayer = wmslayer; 41 } 42 43 public BufferedImage getTile(int x, int y) throws LakewalkerException { 44 String status = getStatus(); 45 setStatus(tr("Downloading image tile...")); 46 47 String layer = "global_mosaic_base"; 48 49 int[] bottom_left_xy = new int[2]; 50 bottom_left_xy[0] = floor(x,this.tilesize); 51 bottom_left_xy[1] = floor(y,this.tilesize); 52 53 int[] top_right_xy = new int[2]; 54 54 top_right_xy[0] = (int)bottom_left_xy[0] + this.tilesize; 55 55 top_right_xy[1] = (int)bottom_left_xy[1] + this.tilesize; 56 56 57 57 double[] topright_geo = xy_to_geo(top_right_xy[0],top_right_xy[1],this.resolution); 58 58 double[] bottomleft_geo = xy_to_geo(bottom_left_xy[0],bottom_left_xy[1],this.resolution); 59 60 String filename = this.wmslayer+"/landsat_"+this.resolution+"_"+this.tilesize+61 "_xy_"+bottom_left_xy[0]+"_"+bottom_left_xy[1]+".png";62 63 // The WMS server only understands decimal points using periods, so we need64 // to convert to a locale that uses that to build the proper URL59 60 String filename = this.wmslayer+"/landsat_"+this.resolution+"_"+this.tilesize+ 61 "_xy_"+bottom_left_xy[0]+"_"+bottom_left_xy[1]+".png"; 62 63 // The WMS server only understands decimal points using periods, so we need 64 // to convert to a locale that uses that to build the proper URL 65 65 NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH); 66 DecimalFormat df = (DecimalFormat)nf;67 df.applyLocalizedPattern("0.000000");68 69 String urlloc = "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&layers="+layer+70 "&styles="+wmslayer+"&srs=EPSG:4326&format=image/png"+71 "&bbox="+df.format(bottomleft_geo[1])+","+df.format(bottomleft_geo[0])+72 ","+df.format(topright_geo[1])+","+df.format(topright_geo[0])+73 "&width="+this.tilesize+"&height="+this.tilesize;74 66 DecimalFormat df = (DecimalFormat)nf; 67 df.applyLocalizedPattern("0.000000"); 68 69 String urlloc = "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&layers="+layer+ 70 "&styles="+wmslayer+"&srs=EPSG:4326&format=image/png"+ 71 "&bbox="+df.format(bottomleft_geo[1])+","+df.format(bottomleft_geo[0])+ 72 ","+df.format(topright_geo[1])+","+df.format(topright_geo[0])+ 73 "&width="+this.tilesize+"&height="+this.tilesize; 74 75 75 File file = new File(this.working_dir,filename); 76 76 77 77 // Calculate the hashmap key 78 String hashkey = Integer.toString(bottom_left_xy[0])+":"+Integer.toString(bottom_left_xy[1]);79 78 String hashkey = Integer.toString(bottom_left_xy[0])+":"+Integer.toString(bottom_left_xy[1]); 79 80 80 // See if this image is already loaded 81 if(this.image != null){ 82 if(this.imagex != bottom_left_xy[0] || this.imagey != bottom_left_xy[1]){83 84 // Check if this image exists in the hashmap85 if(this.imageindex.containsKey(hashkey)){86 // Store which image we have87 this.imagex = bottom_left_xy[0];88 this.imagey = bottom_left_xy[1];89 90 // Retrieve from cache91 this.image = this.images.get(this.imageindex.get(hashkey));92 return this.image;93 } else {94 this.image = null;95 }96 } else {97 return this.image;98 }99 } 100 101 try {102 System.out.println("Looking for image in disk cache: "+filename);103 104 // Read from a file105 this.image = ImageIO.read(file);106 107 this.images.add(this.image);108 this.imageindex.put(hashkey,this.images.size()-1);109 110 } catch(FileNotFoundException e){111 System.out.println("Could not find cached image, downloading.");112 } catch(IOException e){113 System.out.println(e.getMessage());114 } catch(Exception e){115 System.out.println(e.getMessage());116 }117 118 if(this.image == null){119 /**120 * Try downloading the image121 */122 try {123 System.out.println("Downloading from "+urlloc);124 125 // Read from a URL126 URL url = new URL(urlloc);127 this.image = ImageIO.read(url); // this can return null!128 } catch(MalformedURLException e){129 System.out.println(e.getMessage());130 } catch(IOException e){131 System.out.println(e.getMessage());132 } catch(Exception e){133 System.out.println(e.getMessage());134 }135 136 if (this.image != null) {137 this.images.add(this.image);138 this.imageindex.put(hashkey,this.images.size()-1);139 140 this.saveimage(file,this.image);141 }142 }143 144 this.imagex = bottom_left_xy[0];145 this.imagey = bottom_left_xy[1];146 147 if(this.image == null){148 throw new LakewalkerException(tr("Could not acquire image"));149 }150 151 setStatus(status);152 153 return this.image;154 }155 156 public void saveimage(File file, BufferedImage image){81 if(this.image != null){ 82 if(this.imagex != bottom_left_xy[0] || this.imagey != bottom_left_xy[1]){ 83 84 // Check if this image exists in the hashmap 85 if(this.imageindex.containsKey(hashkey)){ 86 // Store which image we have 87 this.imagex = bottom_left_xy[0]; 88 this.imagey = bottom_left_xy[1]; 89 90 // Retrieve from cache 91 this.image = this.images.get(this.imageindex.get(hashkey)); 92 return this.image; 93 } else { 94 this.image = null; 95 } 96 } else { 97 return this.image; 98 } 99 } 100 101 try { 102 System.out.println("Looking for image in disk cache: "+filename); 103 104 // Read from a file 105 this.image = ImageIO.read(file); 106 107 this.images.add(this.image); 108 this.imageindex.put(hashkey,this.images.size()-1); 109 110 } catch(FileNotFoundException e){ 111 System.out.println("Could not find cached image, downloading."); 112 } catch(IOException e){ 113 System.out.println(e.getMessage()); 114 } catch(Exception e){ 115 System.out.println(e.getMessage()); 116 } 117 118 if(this.image == null){ 119 /** 120 * Try downloading the image 121 */ 122 try { 123 System.out.println("Downloading from "+urlloc); 124 125 // Read from a URL 126 URL url = new URL(urlloc); 127 this.image = ImageIO.read(url); // this can return null! 128 } catch(MalformedURLException e){ 129 System.out.println(e.getMessage()); 130 } catch(IOException e){ 131 System.out.println(e.getMessage()); 132 } catch(Exception e){ 133 System.out.println(e.getMessage()); 134 } 135 136 if (this.image != null) { 137 this.images.add(this.image); 138 this.imageindex.put(hashkey,this.images.size()-1); 139 140 this.saveimage(file,this.image); 141 } 142 } 143 144 this.imagex = bottom_left_xy[0]; 145 this.imagey = bottom_left_xy[1]; 146 147 if(this.image == null){ 148 throw new LakewalkerException(tr("Could not acquire image")); 149 } 150 151 setStatus(status); 152 153 return this.image; 154 } 155 156 public void saveimage(File file, BufferedImage image){ 157 157 /** 158 158 * Save the image to the cache 159 159 */ 160 160 try { 161 ImageIO.write(image, "png", file);162 System.out.println("Saved image to cache");161 ImageIO.write(image, "png", file); 162 System.out.println("Saved image to cache"); 163 163 } catch(Exception e){ 164 System.out.println(e.getMessage());165 } 166 }167 168 public int getPixel(int x, int y) throws LakewalkerException{169 170 // Get the previously shown text171 172 173 BufferedImage image = null;174 175 try {176 image = this.getTile(x,y);177 } catch(LakewalkerException e){178 System.out.println(e.getError());179 throw new LakewalkerException(e.getMessage());180 }181 182 int tx = floor(x,this.tilesize);183 int ty = floor(y,this.tilesize);184 185 int pixel_x = (x-tx);186 int pixel_y = (this.tilesize-1)-(y-ty);187 188 //System.out.println("("+x+","+y+") maps to ("+pixel_x+","+pixel_y+") by ("+tx+", "+ty+")");189 190 int rgb = image.getRGB(pixel_x,pixel_y);191 192 int pixel;193 194 int r = (rgb >> 16) & 0xff;164 System.out.println(e.getMessage()); 165 } 166 } 167 168 public int getPixel(int x, int y) throws LakewalkerException{ 169 170 // Get the previously shown text 171 172 173 BufferedImage image = null; 174 175 try { 176 image = this.getTile(x,y); 177 } catch(LakewalkerException e){ 178 System.out.println(e.getError()); 179 throw new LakewalkerException(e.getMessage()); 180 } 181 182 int tx = floor(x,this.tilesize); 183 int ty = floor(y,this.tilesize); 184 185 int pixel_x = (x-tx); 186 int pixel_y = (this.tilesize-1)-(y-ty); 187 188 //System.out.println("("+x+","+y+") maps to ("+pixel_x+","+pixel_y+") by ("+tx+", "+ty+")"); 189 190 int rgb = image.getRGB(pixel_x,pixel_y); 191 192 int pixel; 193 194 int r = (rgb >> 16) & 0xff; 195 195 int g = (rgb >> 8) & 0xff; 196 196 int b = (rgb >> 0) & 0xff; 197 197 198 198 pixel = (int)((0.30 * r) + (0.59 * b) + (0.11 * g)); 199 200 return pixel;201 }202 203 public int floor(int num, int precision){204 double dnum = num/(double)precision;205 BigDecimal val = new BigDecimal(dnum) ;206 val = val.setScale(0, BigDecimal.ROUND_FLOOR);207 return val.intValue()*precision;208 }209 210 public double floor(double num) {211 BigDecimal val = new BigDecimal(num) ;212 val = val.setScale(0, BigDecimal.ROUND_FLOOR);213 return val.doubleValue() ;214 }215 216 public double[] xy_to_geo(int x, int y, double resolution){217 double[] geo = new double[2];218 geo[0] = y / resolution;219 geo[1] = x / resolution;220 return geo;221 }222 223 public int[] geo_to_xy(double lat, double lon, double resolution){224 int[] xy = new int[2];225 226 xy[0] = (int)Math.floor(lon * resolution + 0.5);227 xy[1] = (int)Math.floor(lat * resolution + 0.5);228 229 return xy;230 }231 232 private void printarr(int[] a){233 for(int i = 0; i<a.length; i++){234 System.out.println(i+": "+a[i]);235 }236 }237 protected void setStatus(String s) {238 Main.pleaseWaitDlg.currentAction.setText(s);239 Main.pleaseWaitDlg.repaint();240 }241 protected String getStatus(){242 return Main.pleaseWaitDlg.currentAction.getText();243 }199 200 return pixel; 201 } 202 203 public int floor(int num, int precision){ 204 double dnum = num/(double)precision; 205 BigDecimal val = new BigDecimal(dnum) ; 206 val = val.setScale(0, BigDecimal.ROUND_FLOOR); 207 return val.intValue()*precision; 208 } 209 210 public double floor(double num) { 211 BigDecimal val = new BigDecimal(num) ; 212 val = val.setScale(0, BigDecimal.ROUND_FLOOR); 213 return val.doubleValue() ; 214 } 215 216 public double[] xy_to_geo(int x, int y, double resolution){ 217 double[] geo = new double[2]; 218 geo[0] = y / resolution; 219 geo[1] = x / resolution; 220 return geo; 221 } 222 223 public int[] geo_to_xy(double lat, double lon, double resolution){ 224 int[] xy = new int[2]; 225 226 xy[0] = (int)Math.floor(lon * resolution + 0.5); 227 xy[1] = (int)Math.floor(lat * resolution + 0.5); 228 229 return xy; 230 } 231 232 private void printarr(int[] a){ 233 for(int i = 0; i<a.length; i++){ 234 System.out.println(i+": "+a[i]); 235 } 236 } 237 protected void setStatus(String s) { 238 Main.pleaseWaitDlg.currentAction.setText(s); 239 Main.pleaseWaitDlg.repaint(); 240 } 241 protected String getStatus(){ 242 return Main.pleaseWaitDlg.currentAction.getText(); 243 } 244 244 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/StringEnumConfigurer.java
r5979 r12778 96 96 97 97 public void setValidValues(String[] s) { 98 validValues = s;99 if (box == null) {100 getControls();101 }102 box.setModel(new DefaultComboBoxModel(validValues));98 validValues = s; 99 if (box == null) { 100 getControls(); 101 } 102 box.setModel(new DefaultComboBoxModel(validValues)); 103 103 } 104 104
Note:
See TracChangeset
for help on using the changeset viewer.
