2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4 * Copyright (C) 2003-2008, Evan Battaglia <gtoevan@gmx.net>
5 * Copyright (C) 2007, Quy Tonthat <qtonthat@gmail.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39 #include <sys/types.h>
45 #include <glib/gstdio.h>
46 #include <glib/gi18n.h>
51 #define DEM_BLOCK_SIZE 1024
52 #define GET_COLUMN(dem,n) ((VikDEMColumn *)g_ptr_array_index( (dem)->columns, (n) ))
54 static gboolean get_double_and_continue ( gchar **buffer, gdouble *tmp, gboolean warn )
57 *tmp = g_strtod(*buffer, &endptr);
58 if ( endptr == NULL|| endptr == *buffer ) {
60 g_warning(_("Invalid DEM"));
68 static gboolean get_int_and_continue ( gchar **buffer, gint *tmp, gboolean warn )
71 *tmp = strtol(*buffer, &endptr, 10);
72 if ( endptr == NULL|| endptr == *buffer ) {
74 g_warning(_("Invalid DEM"));
81 static gboolean dem_parse_header ( gchar *buffer, VikDEM *dem )
88 /* incomplete header */
89 if ( strlen(buffer) != 1024 )
92 /* fix Fortran-style exponentiation 1.0D5 -> 1.0E5 */
102 /* "DEM level code, pattern code, palaimetric reference system code" -- skip */
103 get_int_and_continue(&buffer, &int_val, TRUE);
104 get_int_and_continue(&buffer, &int_val, TRUE);
105 get_int_and_continue(&buffer, &int_val, TRUE);
108 get_int_and_continue(&buffer, &int_val, TRUE);
109 dem->utm_zone = int_val;
110 /* TODO -- southern or northern hemisphere?! */
111 dem->utm_letter = 'N';
113 /* skip numbers 5-19 */
114 for ( i = 0; i < 15; i++ ) {
115 if ( ! get_double_and_continue(&buffer, &val, FALSE) ) {
116 g_warning (_("Invalid DEM header"));
121 /* number 20 -- horizontal unit code (utm/ll) */
122 get_double_and_continue(&buffer, &val, TRUE);
123 dem->horiz_units = val;
124 get_double_and_continue(&buffer, &val, TRUE);
125 /* dem->orig_vert_units = val; now done below */
127 /* TODO: do this for real. these are only for 1:24k and 1:250k USGS */
128 if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
129 dem->east_scale = 10.0; /* meters */
130 dem->north_scale = 10.0;
131 dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
133 dem->east_scale = 3.0; /* arcseconds */
134 dem->north_scale = 3.0;
135 dem->orig_vert_units = VIK_DEM_VERT_METERS;
139 get_double_and_continue(&buffer, &val, TRUE);
141 /* now we get the four corner points. record the min and max. */
142 get_double_and_continue(&buffer, &val, TRUE);
143 dem->min_east = dem->max_east = val;
144 get_double_and_continue(&buffer, &val, TRUE);
145 dem->min_north = dem->max_north = val;
147 for ( i = 0; i < 3; i++ ) {
148 get_double_and_continue(&buffer, &val, TRUE);
149 if ( val < dem->min_east ) dem->min_east = val;
150 if ( val > dem->max_east ) dem->max_east = val;
151 get_double_and_continue(&buffer, &val, TRUE);
152 if ( val < dem->min_north ) dem->min_north = val;
153 if ( val > dem->max_north ) dem->max_north = val;
159 static void dem_parse_block_as_cont ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
162 while ( *cur_row < GET_COLUMN(dem, *cur_column)->n_points ) {
163 if ( get_int_and_continue(&buffer, &tmp,FALSE) ) {
164 if ( dem->orig_vert_units == VIK_DEM_VERT_DECIMETERS )
165 GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) (tmp / 10);
167 GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) tmp;
172 *cur_row = -1; /* expecting new column */
175 static void dem_parse_block_as_header ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
179 gdouble east_west, south;
182 /* 1 x n_rows 1 east_west south x x x DATA */
184 if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
185 g_warning(_("Incorrect DEM Class B record: expected 1"));
189 /* don't need this */
190 if ( !get_double_and_continue(&buffer, &tmp, TRUE ) ) return;
193 if ( !get_double_and_continue(&buffer, &tmp, TRUE ) )
195 n_rows = (guint) tmp;
197 if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
198 g_warning(_("Incorrect DEM Class B record: expected 1"));
202 if ( !get_double_and_continue(&buffer, &east_west, TRUE) )
204 if ( !get_double_and_continue(&buffer, &south, TRUE) )
207 /* next three things we don't need */
208 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
209 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
210 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
216 /* empty spaces for things before that were skipped */
217 (*cur_row) = (south - dem->min_north) / dem->north_scale;
218 if ( south > dem->max_north || (*cur_row) < 0 )
223 g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
224 GET_COLUMN(dem,*cur_column)->east_west = east_west;
225 GET_COLUMN(dem,*cur_column)->south = south;
226 GET_COLUMN(dem,*cur_column)->n_points = n_rows;
227 GET_COLUMN(dem,*cur_column)->points = g_malloc(sizeof(gint16)*n_rows);
229 /* no information for things before that */
230 for ( i = 0; i < (*cur_row); i++ )
231 GET_COLUMN(dem,*cur_column)->points[i] = VIK_DEM_INVALID_ELEVATION;
233 /* now just continue */
234 dem_parse_block_as_cont ( buffer, dem, cur_column, cur_row );
239 static void dem_parse_block ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
241 /* if haven't read anything or have read all items in a columns and are expecting a new column */
242 if ( *cur_column == -1 || *cur_row == -1 ) {
243 dem_parse_block_as_header(buffer, dem, cur_column, cur_row);
245 dem_parse_block_as_cont(buffer, dem, cur_column, cur_row);
249 /* return size of unzip data or 0 if failed */
250 /* can be made generic to uncompress zip, gzip, bzip2 data */
251 static guint uncompress_data(void *uncompressed_buffer, guint uncompressed_size, void *compressed_data, guint compressed_size)
256 stream.next_in = compressed_data;
257 stream.avail_in = compressed_size;
258 stream.next_out = uncompressed_buffer;
259 stream.avail_out = uncompressed_size;
260 stream.zalloc = (alloc_func)0;
261 stream.zfree = (free_func)0;
262 stream.opaque = (voidpf)0;
264 /* negative windowBits to inflateInit2 means "no header" */
265 if ((err = inflateInit2(&stream, -MAX_WBITS)) != Z_OK) {
266 g_warning("%s(): inflateInit2 failed", __PRETTY_FUNCTION__);
270 err = inflate(&stream, Z_FINISH);
271 if ((err != Z_OK) && (err != Z_STREAM_END) && stream.msg) {
272 g_warning("%s() inflate failed err=%d \"%s\"", __PRETTY_FUNCTION__, err, stream.msg == NULL ? "unknown" : stream.msg);
278 return(stream.total_out);
281 static void *unzip_hgt_file(gchar *zip_file, gulong *unzip_size)
283 void *unzip_data = NULL;
287 guint16 extract_version;
293 guint32 compressed_size;
294 guint32 uncompressed_size;
295 guint16 filename_len;
296 guint16 extra_field_len;
297 } __attribute__ ((__packed__)) *local_file_header = NULL;
300 local_file_header = (struct _lfh *) zip_file;
301 if (local_file_header->sig != 0x04034b50) {
302 g_warning("%s(): wrong format", __PRETTY_FUNCTION__);
307 zip_data = zip_file + sizeof(struct _lfh) + local_file_header->filename_len + local_file_header->extra_field_len;
308 unzip_data = g_malloc(local_file_header->uncompressed_size);
309 gulong uncompressed_size = local_file_header->uncompressed_size;
311 if (!(*unzip_size = uncompress_data(unzip_data, uncompressed_size, zip_data, local_file_header->compressed_size))) {
321 static VikDEM *vik_dem_read_srtm_hgt(const gchar *file_name, const gchar *basename, gboolean zip)
326 gint16 *dem_mem = NULL;
327 gchar *dem_file = NULL;
328 const gint num_rows_3sec = 1201;
329 const gint num_rows_1sec = 3601;
333 GError *error = NULL;
335 dem = g_malloc(sizeof(VikDEM));
337 dem->horiz_units = VIK_DEM_HORIZ_LL_ARCSECONDS;
338 dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
341 dem->min_north = atoi(basename+1) * 3600;
342 dem->min_east = atoi(basename+4) * 3600;
343 if ( basename[0] == 'S' )
344 dem->min_north = - dem->min_north;
345 if ( basename[3] == 'W' )
346 dem->min_east = - dem->min_east;
348 dem->max_north = 3600 + dem->min_north;
349 dem->max_east = 3600 + dem->min_east;
351 dem->columns = g_ptr_array_new();
354 if ((mf = g_mapped_file_new(file_name, FALSE, &error)) == NULL) {
355 g_error(_("Couldn't map file %s: %s"), file_name, error->message);
360 file_size = g_mapped_file_get_length(mf);
361 dem_file = g_mapped_file_get_contents(mf);
364 void *unzip_mem = NULL;
367 if ((unzip_mem = unzip_hgt_file(dem_file, &ucsize)) == NULL) {
368 g_mapped_file_free(mf);
369 g_ptr_array_free(dem->columns, TRUE);
378 if (file_size == (num_rows_3sec * num_rows_3sec * sizeof(gint16)))
380 else if (file_size == (num_rows_1sec * num_rows_1sec * sizeof(gint16)))
383 g_warning("%s(): file %s does not have right size", __PRETTY_FUNCTION__, basename);
384 g_mapped_file_free(mf);
389 num_rows = (arcsec == 3) ? num_rows_3sec : num_rows_1sec;
390 dem->east_scale = dem->north_scale = arcsec;
392 for ( i = 0; i < num_rows; i++ ) {
394 g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
395 GET_COLUMN(dem,i)->east_west = dem->min_east + arcsec*i;
396 GET_COLUMN(dem,i)->south = dem->min_north;
397 GET_COLUMN(dem,i)->n_points = num_rows;
398 GET_COLUMN(dem,i)->points = g_malloc(sizeof(gint16)*num_rows);
402 for ( i = (num_rows - 1); i >= 0; i-- ) {
403 for ( j = 0; j < num_rows; j++ ) {
404 GET_COLUMN(dem,j)->points[i] = GINT16_FROM_BE(dem_mem[ent]);
412 g_mapped_file_free(mf);
416 #define IS_SRTM_HGT(fn) (strlen((fn))==11 && (fn)[7]=='.' && (fn)[8]=='h' && (fn)[9]=='g' && (fn)[10]=='t' && ((fn)[0]=='N' || (fn)[0]=='S') && ((fn)[3]=='E' || (fn)[3]=='W'))
418 VikDEM *vik_dem_new_from_file(const gchar *file)
422 gchar buffer[DEM_BLOCK_SIZE+1];
424 /* use to record state for dem_parse_block */
425 gint cur_column = -1;
427 const gchar *basename = a_file_basename(file);
429 if ( g_access ( file, R_OK ) != 0 )
432 if ( (strlen(basename)==11 || ((strlen(basename) == 15) && (basename[11] == '.' && basename[12] == 'z' && basename[13] == 'i' && basename[14] == 'p'))) &&
433 basename[7]=='.' && basename[8]=='h' && basename[9]=='g' && basename[10]=='t' &&
434 (basename[0] == 'N' || basename[0] == 'S') && (basename[3] == 'E' || basename[3] =='W')) {
435 gboolean is_zip_file = (strlen(basename) == 15);
436 rv = vik_dem_read_srtm_hgt(file, basename, is_zip_file);
440 /* Create Structure */
441 rv = g_malloc(sizeof(VikDEM));
444 f = g_fopen(file, "r");
449 buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
450 if ( ! dem_parse_header ( buffer, rv ) ) {
455 /* TODO: actually use header -- i.e. GET # OF COLUMNS EXPECTED */
457 rv->columns = g_ptr_array_new();
465 buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
467 /* Fix Fortran-style exponentiation */
475 dem_parse_block(buffer, rv, &cur_column, &cur_row);
478 /* TODO - class C records (right now says 'Invalid' and dies) */
484 if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->n_columns >= 2 )
485 rv->north_scale = rv->east_scale = GET_COLUMN(rv, 1)->east_west - GET_COLUMN(rv,0)->east_west;
487 /* FIXME bug in 10m DEM's */
488 if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->north_scale == 10 ) {
490 rv->min_north += 200;
497 void vik_dem_free ( VikDEM *dem )
500 for ( i = 0; i < dem->n_columns; i++)
501 g_free ( GET_COLUMN(dem, i)->points );
502 g_ptr_array_free ( dem->columns, TRUE );
506 gint16 vik_dem_get_xy ( VikDEM *dem, guint col, guint row )
508 if ( col < dem->n_columns )
509 if ( row < GET_COLUMN(dem, col)->n_points )
510 return GET_COLUMN(dem, col)->points[row];
511 return VIK_DEM_INVALID_ELEVATION;
514 gint16 vik_dem_get_east_north ( VikDEM *dem, gdouble east, gdouble north )
518 if ( east > dem->max_east || east < dem->min_east ||
519 north > dem->max_north || north < dem->min_north )
520 return VIK_DEM_INVALID_ELEVATION;
522 col = (gint) floor((east - dem->min_east) / dem->east_scale);
523 row = (gint) floor((north - dem->min_north) / dem->north_scale);
525 return vik_dem_get_xy ( dem, col, row );
528 static gboolean dem_get_ref_points_elev_dist(VikDEM *dem,
529 gdouble east, gdouble north, /* in seconds */
530 gint16 *elevs, gint16 *dists)
533 int cols[4], rows[4];
537 if ( east > dem->max_east || east < dem->min_east ||
538 north > dem->max_north || north < dem->min_north )
539 return FALSE; /* got nothing */
542 pos.lat = north/3600;
544 /* order of the data: sw, nw, ne, se */
546 cols[0] = (gint) floor((east - dem->min_east) / dem->east_scale);
547 rows[0] = (gint) floor((north - dem->min_north) / dem->north_scale);
548 ll[0].lon = (dem->min_east + dem->east_scale*cols[0])/3600;
549 ll[0].lat = (dem->min_north + dem->north_scale*rows[0])/3600;
552 rows[1] = rows[0] + 1;
553 ll[1].lon = ll[0].lon;
554 ll[1].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
556 cols[2] = cols[0] + 1;
557 rows[2] = rows[0] + 1;
558 ll[2].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
559 ll[2].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
561 cols[3] = cols[0] + 1;
563 ll[3].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
564 ll[3].lat = ll[0].lat;
566 for (i = 0; i < 4; i++) {
567 if ((elevs[i] = vik_dem_get_xy(dem, cols[i], rows[i])) == VIK_DEM_INVALID_ELEVATION)
569 dists[i] = a_coords_latlon_diff(&pos, &ll[i]);
573 for (i = 0; i < 4; i++)
574 fprintf(stderr, "%f:%f:%d:%d ", ll[i].lat, ll[i].lon, dists[i], elevs[i]);
575 fprintf(stderr, " north_scale=%f\n", dem->north_scale);
578 return TRUE; /* all OK */
581 gint16 vik_dem_get_simple_interpol ( VikDEM *dem, gdouble east, gdouble north )
584 gint16 elevs[4], dists[4];
586 if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
587 return VIK_DEM_INVALID_ELEVATION;
589 for (i = 0; i < 4; i++) {
595 gdouble t = (gdouble)elevs[0]/dists[0] + (gdouble)elevs[1]/dists[1] + (gdouble)elevs[2]/dists[2] + (gdouble)elevs[3]/dists[3];
596 gdouble b = 1.0/dists[0] + 1.0/dists[1] + 1.0/dists[2] + 1.0/dists[3];
601 gint16 vik_dem_get_shepard_interpol ( VikDEM *dem, gdouble east, gdouble north )
604 gint16 elevs[4], dists[4];
609 if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
610 return VIK_DEM_INVALID_ELEVATION;
613 for (i = 0; i < 4; i++) {
617 if (dists[i] > max_dist)
622 #if 0 /* derived method by Franke & Nielson. Does not seem to work too well here */
623 for (i = 0; i < 4; i++) {
624 tmp = pow((1.0*(max_dist - dists[i])/max_dist*dists[i]), 2);
630 for (i = 0; i < 4; i++) {
631 tmp = pow((1.0/dists[i]), 2);
636 // fprintf(stderr, "DEBUG: tmp=%f t=%f b=%f %f\n", tmp, t, b, t/b);
642 void vik_dem_east_north_to_xy ( VikDEM *dem, gdouble east, gdouble north, guint *col, guint *row )
644 *col = (gint) floor((east - dem->min_east) / dem->east_scale);
645 *row = (gint) floor((north - dem->min_north) / dem->north_scale);
646 if ( *col < 0 ) *col = 0;
647 if ( *row < 0 ) *row = 0;