Debian Codegraph @

src/uk/me/parabola/imgfmt/Utils.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 03-Dec-2006
16 */
17 package uk.me.parabola.imgfmt;
18
19 import java.awt.geom.Line2D;
20 import java.io.Closeable;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.nio.ByteBuffer;
27 import java.nio.ByteOrder;
28 import java.util.Calendar;
29 import java.util.Date;
30 import java.util.zip.GZIPInputStream;
31
32 import uk.me.parabola.imgfmt.app.Coord;
33 import uk.me.parabola.imgfmt.app.ImgFileWriter;
34 import uk.me.parabola.log.Logger;
35 /**
36 * Some miscellaneous functions that are used within the .img code.
37 *
38 * @author Steve Ratcliffe
39 */
40 public class Utils {
41 public static final int MIN_LAT_MAP_UNITS = toMapUnit(-90);
42 public static final int MAX_LAT_MAP_UNITS = toMapUnit(90);
43 public static final int MIN_LON_MAP_UNITS = toMapUnit(-180);
44 public static final int MAX_LON_MAP_UNITS = toMapUnit(180);
45
46 /**
47 * Routine to convert a string to bytes and pad with a character up
48 * to a given length.
49 * Only to be used for strings that are expressible in latin1.
50 *
51 * @param s The original string.
52 * @param len The length to pad to.
53 * @param pad The byte used to pad.
54 * @return An array created from the string.
55 */
56 public static byte[] toBytes(String s, int len, byte pad) {
57 if (s == null)
58 throw new IllegalArgumentException("null string provided");
59
60 byte[] out = new byte[len];
61 for (int i = 0; i < len; i++) {
62 if (i > s.length()) {
63 out[i] = pad;
64 } else {
65 out[i] = (byte) s.charAt(i);
66 }
67 }
68 return out;
69 }
70
71 public static byte[] toBytes(String s) {
72 return toBytes(s, s.length(), (byte) 0);
73 }
74
75 /**
76 * Convert from bytes to a string. Only to be used when the character set
77 * is ascii or latin1.
78 *
79 * @param buf A byte buffer to get the bytes from. Should be ascii or latin1.
80 * @param off The offset into buf.
81 * @param len The length to get.
82 * @return A string.
83 */
84 public static String bytesToString(ByteBuffer buf, int off, int len) {
85 if (buf == null)
86 throw new IllegalArgumentException("null byte buffer provided");
87
88 byte[] bbuf = new byte[len];
89 buf.position(off);
90 buf.get(bbuf);
91 char[] cbuf = new char[len];
92 for (int i = 0; i < bbuf.length; i++) {
93 cbuf[i] = (char) bbuf[i];
94 }
95
96 return new String(cbuf);
97 }
98
99 /**
100 * Set the creation date. Note that the year is encoded specially.
101 *
102 * @param buf The buffer to write into. It must have been properly positioned
103 * beforehand.
104 * @param date The date to set.
105 */
106 public static void setCreationTime(ByteBuffer buf, Date date) {
107 Calendar cal = Calendar.getInstance();
108
109 if (date != null)
110 cal.setTime(date);
111
112 fillBufFromTime(buf, cal);
113 }
114
115 /**
116 * A map unit is an integer value that is 1/(2^24) degrees of latitude or
117 * longitude.
118 *
119 * @param degrees The latitude or longitude as decimal degrees.
120 * @return An integer value in map units.
121 */
122 public static int toMapUnit(double degrees) {
123 // do Round rather than Trunc: add a half and a lot extra so that the (int)op
124 // is always positive to avoid negative truncation to zero and give uniform
125 // boundary behaviour
126 final double DELTA = 360.0D / (1 << 24) / 2 + 360.0D;
127 final double RESCALE = (1 << 24) / 360.0D;
128 final int UNDO360 = 1 << 24;
129 return (int)((degrees + DELTA) * RESCALE) - UNDO360;
130 }
131
132 /**
133 * Convert a date into the in-file representation of a date.
134 *
135 * @param date The date.
136 * @return A byte stream in .img format.
137 */
138 public static byte[] makeCreationTime(Date date) {
139 Calendar cal = Calendar.getInstance();
140
141 if (date != null)
142 cal.setTime(date);
143
144 byte[] ret = new byte[7];
145
146 ByteBuffer buf = ByteBuffer.wrap(ret);
147 buf.order(ByteOrder.LITTLE_ENDIAN);
148 fillBufFromTime(buf, cal);
149
150 return ret;
151 }
152
153 private static void fillBufFromTime(ByteBuffer buf, Calendar cal) {
154 buf.putChar((char) cal.get(Calendar.YEAR));
155 buf.put((byte) (cal.get(Calendar.MONTH)+1));
156 buf.put((byte) cal.get(Calendar.DAY_OF_MONTH));
157 buf.put((byte) cal.get(Calendar.HOUR_OF_DAY));
158 buf.put((byte) cal.get(Calendar.MINUTE));
159 buf.put((byte) cal.get(Calendar.SECOND));
160 }
161
162 /**
163 * Make a date from the garmin representation.
164 * @param date The bytes representing the date.
165 * @return A java date.
166 */
167 public static Date makeCreationTime(byte[] date) {
168 Calendar cal = Calendar.getInstance();
169
170 int y = ((date[1] & 0xff) << 8) + (date[0] & 0xff);
171 cal.set(y, date[2]-1, date[3], date[4], date[5], date[6]);
172
173 return cal.getTime();
174 }
175
176 /**
177 * Convert an angle in map units to degrees.
178 */
179 public static double toDegrees(int val) {
180 return (double) val * (360.0 / (1 << 24));
181 }
182
183 /**
184 * Convert an angle in map units to radians.
185 */
186 public static double toRadians(int mapunits) {
187 return toDegrees(mapunits) * (Math.PI / 180);
188 }
189
190 public static void closeFile(Closeable f) {
191 if (f != null) {
192 try {
193 f.close();
194 } catch (IOException e) {
195 Logger.defaultLogger.error("Error closing file", e);
196 }
197 }
198 }
199
200 /**
201 * Open a file and apply filters necessary for reading it such as
202 * decompression.
203 *
204 * @param name The file to open.
205 * @return A stream that will read the file, positioned at the beginning.
206 * @throws FileNotFoundException If the file cannot be opened for any reason.
207 */
208 public static InputStream openFile(String name) throws FileNotFoundException {
209 InputStream is = new FileInputStream(name);
210 if (name.endsWith(".gz")) {
211 try {
212 is = new GZIPInputStream(is);
213 } catch (IOException e) {
214 throw new FileNotFoundException( "Could not read as compressed file");
215 }
216 }
217 return is;
218 }
219
220 public static String joinPath(String dir, String basename, String ext) {
221 return joinPath(dir, basename + "." + ext);
222 }
223 public static String joinPath(String dir, String basename) {
224 File file = new File(dir, basename);
225 return file.getAbsolutePath();
226 }
227
228 /**
229 * Rounds an integer up to the nearest multiple of {@code 2^shift}.
230 * Works with both positive and negative integers.
231 * @param val the integer to round up.
232 * @param shift the power of two to round up to.
233 * @return the rounded integer.
234 */
235 public static int roundUp(int val, int shift) {
236 return (val + (1 << shift) - 1) >>> shift << shift;
237 }
238
239 /**
240 * Calculates the angle between the two segments (c1,c2),(c2,c3).
241 * It is assumed that the segments are rhumb lines, not great circle paths.
242 * @param c1 first point
243 * @param c2 second point
244 * @param c3 third point
245 * @return angle between the two segments in degree [-180;180]
246 */
247 public static double getAngle(Coord c1, Coord c2, Coord c3) {
248 double a = c2.bearingTo(c1);
249 double b = c2.bearingTo(c3);
250 double angle = b - (a - 180);
251 while(angle > 180)
252 angle -= 360;
253 while(angle < -180)
254 angle += 360;
255
256 return angle;
257 }
258
259 /**
260 * Calculates the angle between the two segments (c1,c2),(c2,c3)
261 * using the coords in map units.
262 * @param c1 first point
263 * @param c2 second point
264 * @param c3 third point
265 * @return angle between the two segments in degree [-180;180]
266 */
267 public static double getDisplayedAngle(Coord c1, Coord c2, Coord c3) {
268 return getAngle(c1.getDisplayedCoord(), c2.getDisplayedCoord(), c3.getDisplayedCoord());
269 }
270
271 public final static int NOT_STRAIGHT = 0;
272 public final static int STRAIGHT_SPIKE = 1;
273 public final static int STRICTLY_STRAIGHT = 2;
274 /**
275 * Checks if the two segments (c1,c2),(c2,c3) form a straight line.
276 * @param c1 first point
277 * @param c2 second point
278 * @param c3 third point
279 * @return NOT_STRAIGHT, STRAIGHT_SPIKE or STRICTLY_STRAIGHT
280 */
281 public static int isStraight(Coord c1, Coord c2, Coord c3) {
282 if (c1.equals(c3))
283 return STRAIGHT_SPIKE;
284 long area;
285 // calculate the area that is enclosed by the three points
286 // (as if a closing line is drawn from c3 back to c1)
287 area = ((long)c1.getLongitude() * c2.getLatitude() -
288 (long)c2.getLongitude() * c1.getLatitude());
289 area += ((long)c2.getLongitude() * c3.getLatitude() -
290 (long)c3.getLongitude() * c2.getLatitude());
291 area += ((long)c3.getLongitude() * c1.getLatitude() -
292 (long)c1.getLongitude() * c3.getLatitude());
293 if (area == 0){
294 // area is empty-> points lie on a straight line
295 int delta1 = c1.getLatitude() - c2.getLatitude();
296 int delta2 = c2.getLatitude() - c3.getLatitude();
297 if (delta1 < 0 && delta2 > 0 || delta1 > 0 && delta2 < 0)
298 return STRAIGHT_SPIKE;
299 delta1 = c1.getLongitude() - c2.getLongitude();
300 delta2 = c2.getLongitude() - c3.getLongitude();
301 if (delta1 < 0 && delta2 > 0 || delta1 > 0 && delta2 < 0)
302 return STRAIGHT_SPIKE;
303 return STRICTLY_STRAIGHT;
304 }
305 // line is not straight
306 return NOT_STRAIGHT;
307
308 }
309
310 /**
311 * Checks if the two segments (c1,c2),(c2,c3) form a straight line
312 * using high precision coordinates.
313 * @param c1 first point
314 * @param c2 second point
315 * @param c3 third point
316 * @return NOT_STRAIGHT, STRAIGHT_SPIKE or STRICTLY_STRAIGHT
317 */
318 public static int isHighPrecStraight(Coord c1, Coord c2, Coord c3) {
319 if (c1.highPrecEquals(c3))
320 return STRAIGHT_SPIKE;
321 long area;
322 long c1Lat = c1.getHighPrecLat();
323 long c2Lat = c2.getHighPrecLat();
324 long c3Lat = c3.getHighPrecLat();
325 long c1Lon = c1.getHighPrecLon();
326 long c2Lon = c2.getHighPrecLon();
327 long c3Lon = c3.getHighPrecLon();
328 // calculate the area that is enclosed by the three points
329 // (as if a closing line is drawn from c3 back to c1)
330 area = c1Lon * c2Lat - c2Lon * c1Lat;
331 area += c2Lon * c3Lat - c3Lon * c2Lat;
332 area += c3Lon * c1Lat - c1Lon * c3Lat;
333 if (area == 0){
334 // area is empty-> points lie on a straight line
335 long delta1 = c1Lat - c2Lat;
336 long delta2 = c2Lat - c3Lat;
337 if (delta1 < 0 && delta2 > 0 || delta1 > 0 && delta2 < 0)
338 return STRAIGHT_SPIKE;
339 delta1 = c1Lon - c2Lon;
340 delta2 = c2Lon - c3Lon;
341 if (delta1 < 0 && delta2 > 0 || delta1 > 0 && delta2 < 0)
342 return STRAIGHT_SPIKE;
343 return STRICTLY_STRAIGHT;
344 }
345 // line is not straight
346 return NOT_STRAIGHT;
347
348 }
349
350 /**
351 * approximate atan2, much faster than Math.atan2()
352 * Based on a 50-year old arctan approximation due to Hastings
353 */
354 private final static double PI_BY_2 = Math.PI / 2;
355 // |error| < 0.005
356 public static double atan2_approximation( double y, double x )
357 {
358 if ( x == 0.0f )
359 {
360 if ( y > 0.0f ) return PI_BY_2 ;
361 if ( y == 0.0f ) return 0.0f;
362 return -PI_BY_2 ;
363 }
364 double atan;
365 double z = y/x;
366 if ( Math.abs( z ) < 1.0f )
367 {
368 atan = z/(1.0f + 0.28f*z*z);
369 if ( x < 0.0f )
370 {
371 if ( y < 0.0f ) return atan - Math.PI;
372 return atan + Math.PI;
373 }
374 }
375 else
376 {
377 atan = PI_BY_2 - z/(z*z + 0.28f);
378 if ( y < 0.0f ) return atan - Math.PI;
379 }
380 return atan;
381 }
382
383 /**
384 * calculate a long value for the latitude and longitude of a coord
385 * in high precision.
386 * @param co
387 * @return a long that can be used as a key in HashMaps
388 */
389 public static long coord2Long(Coord co){
390 int latHp = co.getHighPrecLat();
391 int lonHp = co.getHighPrecLon();
392
393 return (latHp & 0xffffffffL) << 32 | (lonHp & 0xffffffffL);
394 }
395
396 public static int numberToPointerSize(int n) {
397 // moved from imgfmt/app/mdr/MdrSection.java and app/typ/TYPFile.java
398 if (n <= 0xff)
399 return 1;
400 else if (n <= 0xffff)
401 return 2;
402 else if (n <= 0xffffff)
403 return 3;
404 else
405 return 4;
406 }
407
408 public static void put3sLongitude(ImgFileWriter writer, int longitude) {
409 // handle special case, write -180/-8388608 instead of 180/8388608 to avoid assertion
410 if (longitude == Utils.MAX_LON_MAP_UNITS)
411 writer.put3s(Utils.MIN_LON_MAP_UNITS);
412 else
413 writer.put3s(longitude);
414 }
415
416 /**
417 * Finds the intersection of two line segments, also if one ends on the other
418 * See https://de.wikipedia.org/wiki/Geod%C3%A4tisches_Rechnen#Geradenschnitt
419 * @param p1_1 the coordinates of the start point of the first specified line segment
420 * @param p1_2 the coordinates of the end point of the first specified line segment
421 * @param p2_1 the coordinates of the start point of the second specified line segment
422 * @param p2_2 the coordinates of the end point of the second specified line segment
423 * @return null if no intersection was found, else a new Coord instance with the coordinates of the intersection
424 */
425 public static Coord getSegmentSegmentIntersection (Coord p1_1, Coord p1_2, Coord p2_1, Coord p2_2) {
426 long x1 = p1_1.getHighPrecLon();
427 long y1 = p1_1.getHighPrecLat();
428 long x2 = p1_2.getHighPrecLon();
429 long y2 = p1_2.getHighPrecLat();
430 long x3 = p2_1.getHighPrecLon();
431 long y3 = p2_1.getHighPrecLat();
432 long x4 = p2_2.getHighPrecLon();
433 long y4 = p2_2.getHighPrecLat();
434
435 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4))
436 return null;
437
438 long divider = (y2 - y1) * (x4 - x3) - (y4 - y3) * (x2 - x1);
439 if (divider == 0)
440 return null; // parallel
441 double h = ((y4 - y3) * (x1 - x4) - (y1 - y4) * (x4 - x3)) / (double) divider;
442
443 if (h < 0 || h > 1) {
444 return null; // intersection of lines is not on given segment
445 }
446 double xs = x1 + h * (x2 - x1);
447 double ys = y1 + h * (y2 - y1);
448 return Coord.makeHighPrecCoord((int)Math.round(ys), (int) Math.round(xs));
449 }
450
451 }
452