]> git.street.me.uk Git - andy/viking.git/blob - src/vikdemlayer.c
Fix debug message
[andy/viking.git] / src / vikdemlayer.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #ifdef HAVE_MATH_H
26 #include <math.h>
27 #endif
28 #ifdef HAVE_SYS_TYPES_H
29 #include <sys/types.h>
30 #endif
31 #ifdef HAVE_SYS_STAT_H
32 #include <sys/stat.h>
33 #endif
34 #ifdef HAVE_STRING_H
35 #include <string.h>
36 #endif
37 #include <stdlib.h>
38 #include <glib/gi18n.h>
39
40 #include "config.h"
41 #include "globals.h"
42 #include "coords.h"
43 #include "vikcoord.h"
44 #include "download.h"
45 #include "background.h"
46 #include "vikwaypoint.h"
47 #include "viktrack.h"
48 #include "vikviewport.h"
49 #include "viktreeview.h"
50 #include "viklayer.h"
51 #include "vikaggregatelayer.h"
52 #include "viklayerspanel.h"
53 #include "vikmapslayer.h"
54 #include "vikdemlayer.h"
55 #include "dialog.h"
56
57 #include "dem.h"
58 #include "dems.h"
59
60 #include "icons/icons.h"
61
62 #define MAPS_CACHE_DIR maps_layer_default_dir()
63
64 #define SRTM_CACHE_TEMPLATE "%ssrtm3-%s%s%c%02d%c%03d.hgt.zip"
65 #define SRTM_HTTP_SITE "dds.cr.usgs.gov"
66 #define SRTM_HTTP_URI  "/srtm/version2_1/SRTM3/"
67
68 #ifdef VIK_CONFIG_DEM24K
69 #define DEM24K_DOWNLOAD_SCRIPT "dem24k.pl"
70 #endif
71
72
73 static void dem_layer_marshall( VikDEMLayer *vdl, guint8 **data, gint *len );
74 static VikDEMLayer *dem_layer_unmarshall( guint8 *data, gint len, VikViewport *vvp );
75 static gboolean dem_layer_set_param ( VikDEMLayer *vdl, guint16 id, VikLayerParamData data, VikViewport *vp );
76 static VikLayerParamData dem_layer_get_param ( VikDEMLayer *vdl, guint16 id );
77 static void dem_layer_update_gc ( VikDEMLayer *vdl, VikViewport *vp, const gchar *color );
78 static void dem_layer_post_read ( VikLayer *vl, VikViewport *vp, gboolean from_file );
79 static void srtm_draw_existence ( VikViewport *vp );
80
81 #ifdef VIK_CONFIG_DEM24K
82 static void dem24k_draw_existence ( VikViewport *vp );
83 #endif
84
85 static VikLayerParamScale param_scales[] = {
86   { 1, 10000, 10, 1 },
87   { 1, 10000, 10, 1 },
88   { 1, 10, 1, 0 },
89 };
90
91 static gchar *params_source[] = {
92         "SRTM Global 90m (3 arcsec)",
93 #ifdef VIK_CONFIG_DEM24K
94         "USA 10m (USGS 24k)",
95 #endif
96         "None",
97         NULL
98         };
99
100 static gchar *params_type[] = {
101         N_("Absolute height"),
102         N_("Height gradient"),
103         NULL
104 };
105
106 enum { DEM_SOURCE_SRTM,
107 #ifdef VIK_CONFIG_DEM24K
108        DEM_SOURCE_DEM24K,
109 #endif
110        DEM_SOURCE_NONE,
111      };
112
113 enum { DEM_TYPE_HEIGHT = 0,
114        DEM_TYPE_GRADIENT,
115        DEM_TYPE_NONE,
116 };
117
118 static VikLayerParam dem_layer_params[] = {
119   { "files", VIK_LAYER_PARAM_STRING_LIST, VIK_LAYER_GROUP_NONE, N_("DEM Files:"), VIK_LAYER_WIDGET_FILELIST },
120   { "source", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, N_("Download Source:"), VIK_LAYER_WIDGET_RADIOGROUP_STATIC, params_source, NULL },
121   { "color", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("Color:"), VIK_LAYER_WIDGET_ENTRY },
122   { "type", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, N_("Type:"), VIK_LAYER_WIDGET_RADIOGROUP_STATIC, params_type, NULL },
123   { "min_elev", VIK_LAYER_PARAM_DOUBLE, VIK_LAYER_GROUP_NONE, N_("Min Elev:"), VIK_LAYER_WIDGET_SPINBUTTON, param_scales + 0 },
124   { "max_elev", VIK_LAYER_PARAM_DOUBLE, VIK_LAYER_GROUP_NONE, N_("Max Elev:"), VIK_LAYER_WIDGET_SPINBUTTON, param_scales + 0 },
125   { "line_thickness", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, N_("Line Thickness:"), VIK_LAYER_WIDGET_SPINBUTTON, param_scales + 1 },
126 };
127
128
129 enum { PARAM_FILES=0, PARAM_SOURCE, PARAM_COLOR, PARAM_TYPE, PARAM_MIN_ELEV, PARAM_MAX_ELEV, PARAM_LINE_THICKNESS, NUM_PARAMS };
130
131 static gpointer dem_layer_download_create ( VikWindow *vw, VikViewport *vvp);
132 static gboolean dem_layer_download_release ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp );
133 static gboolean dem_layer_download_click ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp );
134
135 static VikToolInterface dem_tools[] = {
136   { N_("DEM Download/Import"), (VikToolConstructorFunc) dem_layer_download_create, NULL, NULL, NULL,
137     (VikToolMouseFunc) dem_layer_download_click, NULL,  (VikToolMouseFunc) dem_layer_download_release,
138     (VikToolKeyFunc) NULL, GDK_CURSOR_IS_PIXMAP, &cursor_demdl_pixbuf },
139 };
140
141
142 /*
143 */
144
145 static gchar *dem_height_colors[] = {
146 "#0000FF",
147 "#9b793c", "#9c7d40", "#9d8144", "#9e8549", "#9f894d", "#a08d51", "#a29156", "#a3955a", "#a4995e", "#a69d63",
148 "#a89f65", "#aaa267", "#ada569", "#afa76b", "#b1aa6d", "#b4ad6f", "#b6b071", "#b9b373", "#bcb676", "#beb978",
149 "#c0bc7a", "#c2c07d", "#c4c37f", "#c6c681", "#c8ca84", "#cacd86", "#ccd188", "#cfd58b", "#c2ce84", "#b5c87e",
150 "#a9c278", "#9cbb71", "#8fb56b", "#83af65", "#76a95e", "#6aa358", "#5e9d52", "#63a055", "#69a458", "#6fa85c",
151 "#74ac5f", "#7ab063", "#80b467", "#86b86a", "#8cbc6e", "#92c072", "#94c175", "#97c278", "#9ac47c", "#9cc57f",
152 "#9fc682", "#a2c886", "#a4c989", "#a7cb8d", "#aacd91", "#afce99", "#b5d0a1", "#bbd2aa", "#c0d3b2", "#c6d5ba",
153 "#ccd7c3", "#d1d9cb", "#d7dbd4", "#DDDDDD", "#e0e0e0", "#e4e4e4", "#e8e8e8", "#ebebeb", "#efefef", "#f3f3f3",
154 "#f7f7f7", "#fbfbfb", "#ffffff"
155 };
156
157 static const guint DEM_N_HEIGHT_COLORS = sizeof(dem_height_colors)/sizeof(dem_height_colors[0]);
158
159 /*
160 "#9b793c", "#9e8549", "#a29156", "#a69d63", "#ada569", "#b4ad6f", "#bcb676", "#c2c07d", "#c8ca84", "#cfd58b",
161 "#a9c278", "#83af65", "#5e9d52", "#6fa85c", "#80b467", "#92c072", "#9ac47c", "#a2c886", "#aacd91", "#bbd2aa",
162 "#ccd7c3", "#DDDDDD", "#e8e8e8", "#f3f3f3", "#FFFFFF"
163 };
164 */
165
166 static gchar *dem_gradient_colors[] = {
167 "#AAAAAA"
168 "#000000", "#000011", "#000022", "#000033", "#000044", "#00004c", "#000055", "#00005d", "#000066", "#00006e",
169 "#000077", "#00007f", "#000088", "#000090", "#000099", "#0000a1", "#0000aa", "#0000b2", "#0000bb", "#0000c3",
170 "#0000cc", "#0000d4", "#0000dd", "#0000e5", "#0000ee", "#0000f6", "#0000ff", "#0008f7", "#0011ee", "#0019e6",
171 "#0022dd", "#002ad5", "#0033cc", "#003bc4", "#0044bb", "#004cb3", "#0055aa", "#005da2", "#006699", "#006e91",
172 "#007788", "#007f80", "#008877", "#00906f", "#009966", "#00a15e", "#00aa55", "#00b24d", "#00bb44", "#00c33c",
173 "#00cc33", "#00d42b", "#00dd22", "#00e51a", "#00ee11", "#00f609", "#00ff00", "#08f700", "#11ee00", "#19e600",
174 "#22dd00", "#2ad500", "#33cc00", "#3bc400", "#44bb00", "#4cb300", "#55aa00", "#5da200", "#669900", "#6e9100",
175 "#778800", "#7f8000", "#887700", "#906f00", "#996600", "#a15e00", "#aa5500", "#b24d00", "#bb4400", "#c33c00",
176 "#cc3300", "#d42b00", "#dd2200", "#e51a00", "#ee1100", "#f60900", "#ff0000",
177 "#FFFFFF"
178 };
179
180 static const guint DEM_N_GRADIENT_COLORS = sizeof(dem_gradient_colors)/sizeof(dem_gradient_colors[0]);
181
182
183 VikLayerInterface vik_dem_layer_interface = {
184   "DEM",
185   &vikdemlayer_pixbuf,
186
187   dem_tools,
188   sizeof(dem_tools) / sizeof(dem_tools[0]),
189
190   dem_layer_params,
191   NUM_PARAMS,
192   NULL,
193   0,
194
195   VIK_MENU_ITEM_ALL,
196
197   (VikLayerFuncCreate)                  vik_dem_layer_create,
198   (VikLayerFuncRealize)                 NULL,
199   (VikLayerFuncPostRead)                dem_layer_post_read,
200   (VikLayerFuncFree)                    vik_dem_layer_free,
201
202   (VikLayerFuncProperties)              NULL,
203   (VikLayerFuncDraw)                    vik_dem_layer_draw,
204   (VikLayerFuncChangeCoordMode)         NULL,
205
206   (VikLayerFuncSetMenuItemsSelection)   NULL,
207   (VikLayerFuncGetMenuItemsSelection)   NULL,
208
209   (VikLayerFuncAddMenuItems)            NULL,
210   (VikLayerFuncSublayerAddMenuItems)    NULL,
211
212   (VikLayerFuncSublayerRenameRequest)   NULL,
213   (VikLayerFuncSublayerToggleVisible)   NULL,
214
215   (VikLayerFuncMarshall)                dem_layer_marshall,
216   (VikLayerFuncUnmarshall)              dem_layer_unmarshall,
217
218   (VikLayerFuncSetParam)                dem_layer_set_param,
219   (VikLayerFuncGetParam)                dem_layer_get_param,
220
221   (VikLayerFuncReadFileData)            NULL,
222   (VikLayerFuncWriteFileData)           NULL,
223
224   (VikLayerFuncDeleteItem)              NULL,
225   (VikLayerFuncCopyItem)                NULL,
226   (VikLayerFuncPasteItem)               NULL,
227   (VikLayerFuncFreeCopiedItem)          NULL,
228   (VikLayerFuncDragDropRequest)         NULL,
229 };
230
231 struct _VikDEMLayer {
232   VikLayer vl;
233   GdkGC *gc;
234   GdkGC **gcs;
235   GdkGC **gcsgradient;
236   GList *files;
237   gdouble min_elev;
238   gdouble max_elev;
239   guint8 line_thickness;
240   gchar *color;
241   guint source;
242   guint type;
243 };
244
245 GType vik_dem_layer_get_type ()
246 {
247   static GType vdl_type = 0;
248
249   if (!vdl_type)
250   {
251     static const GTypeInfo vdl_info =
252     {
253       sizeof (VikDEMLayerClass),
254       NULL, /* base_init */
255       NULL, /* base_finalize */
256       NULL, /* class init */
257       NULL, /* class_finalize */
258       NULL, /* class_data */
259       sizeof (VikDEMLayer),
260       0,
261       NULL /* instance init */
262     };
263     vdl_type = g_type_register_static ( VIK_LAYER_TYPE, "VikDEMLayer", &vdl_info, 0 );
264   }
265
266   return vdl_type;
267 }
268
269 static void dem_layer_marshall( VikDEMLayer *vdl, guint8 **data, gint *len )
270 {
271   vik_layer_marshall_params ( VIK_LAYER(vdl), data, len );
272 }
273
274 static VikDEMLayer *dem_layer_unmarshall( guint8 *data, gint len, VikViewport *vvp )
275 {
276   VikDEMLayer *rv = vik_dem_layer_new ();
277   gint i;
278
279   /* TODO: share GCS between layers */
280   for ( i = 0; i < DEM_N_HEIGHT_COLORS; i++ )
281     rv->gcs[i] = vik_viewport_new_gc ( vvp, dem_height_colors[i], rv->line_thickness );
282
283   for ( i = 0; i < DEM_N_GRADIENT_COLORS; i++ )
284     rv->gcsgradient[i] = vik_viewport_new_gc ( vvp, dem_gradient_colors[i], rv->line_thickness );
285
286   vik_layer_unmarshall_params ( VIK_LAYER(rv), data, len, vvp );
287   return rv;
288 }
289
290 gboolean dem_layer_set_param ( VikDEMLayer *vdl, guint16 id, VikLayerParamData data, VikViewport *vp )
291 {
292   switch ( id )
293   {
294     case PARAM_COLOR: if ( vdl->color ) g_free ( vdl->color ); vdl->color = g_strdup ( data.s ); break;
295     case PARAM_SOURCE: vdl->source = data.u; break;
296     case PARAM_TYPE: vdl->type = data.u; break;
297     case PARAM_MIN_ELEV: vdl->min_elev = data.d; break;
298     case PARAM_MAX_ELEV: vdl->max_elev = data.d; break;
299     case PARAM_LINE_THICKNESS: if ( data.u >= 1 && data.u <= 15 ) vdl->line_thickness = data.u; break;
300     case PARAM_FILES: a_dems_load_list ( &(data.sl) ); a_dems_list_free ( vdl->files ); vdl->files = data.sl; break;
301   }
302   return TRUE;
303 }
304
305 static VikLayerParamData dem_layer_get_param ( VikDEMLayer *vdl, guint16 id )
306 {
307   VikLayerParamData rv;
308   switch ( id )
309   {
310     case PARAM_FILES: rv.sl = vdl->files; break;
311     case PARAM_SOURCE: rv.u = vdl->source; break;
312     case PARAM_TYPE: rv.u = vdl->type; break;
313     case PARAM_COLOR: rv.s = vdl->color ? vdl->color : ""; break;
314     case PARAM_MIN_ELEV: rv.d = vdl->min_elev; break;
315     case PARAM_MAX_ELEV: rv.d = vdl->max_elev; break;
316     case PARAM_LINE_THICKNESS: rv.i = vdl->line_thickness; break;
317   }
318   return rv;
319 }
320
321 static void dem_layer_post_read ( VikLayer *vl, VikViewport *vp, gboolean from_file )
322 {
323   VikDEMLayer *vdl = VIK_DEM_LAYER(vl);
324   if ( vdl->gc )
325     g_object_unref ( G_OBJECT(vdl->gc) );
326
327   vdl->gc = vik_viewport_new_gc ( vp, vdl->color, vdl->line_thickness );
328 }
329
330 VikDEMLayer *vik_dem_layer_new ( )
331 {
332   VikDEMLayer *vdl = VIK_DEM_LAYER ( g_object_new ( VIK_DEM_LAYER_TYPE, NULL ) );
333
334   vik_layer_init ( VIK_LAYER(vdl), VIK_LAYER_DEM );
335
336   vdl->files = NULL;
337
338
339   vdl->gc = NULL;
340
341   vdl->gcs = g_malloc(sizeof(GdkGC *)*DEM_N_HEIGHT_COLORS);
342   vdl->gcsgradient = g_malloc(sizeof(GdkGC *)*DEM_N_GRADIENT_COLORS);
343   /* make new gcs only if we need it (copy layer -> use old) */
344
345   vdl->min_elev = 0.0;
346   vdl->max_elev = 1000.0;
347   vdl->source = DEM_SOURCE_SRTM;
348   vdl->type = DEM_TYPE_HEIGHT;
349   vdl->line_thickness = 3;
350   vdl->color = NULL;
351   return vdl;
352 }
353
354
355 static inline guint16 get_height_difference(gint16 elev, gint16 new_elev)
356 {
357   if(new_elev == VIK_DEM_INVALID_ELEVATION)
358     return 0;
359   else
360     return abs(new_elev - elev);
361 }
362
363
364 static void vik_dem_layer_draw_dem ( VikDEMLayer *vdl, VikViewport *vp, VikDEM *dem )
365 {
366   VikDEMColumn *column, *prevcolumn, *nextcolumn;
367
368   struct LatLon dem_northeast, dem_southwest;
369   gdouble max_lat, max_lon, min_lat, min_lon;
370
371   /**** Check if viewport and DEM data overlap ****/
372
373   /* get min, max lat/lon of viewport */
374   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
375
376   /* get min, max lat/lon of DEM data */
377   if ( dem->horiz_units == VIK_DEM_HORIZ_LL_ARCSECONDS ) {
378     dem_northeast.lat = dem->max_north / 3600.0;
379     dem_northeast.lon = dem->max_east / 3600.0;
380     dem_southwest.lat = dem->min_north / 3600.0;
381     dem_southwest.lon = dem->min_east / 3600.0;
382   } else if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
383     struct UTM dem_northeast_utm, dem_southwest_utm;
384     dem_northeast_utm.northing = dem->max_north;
385     dem_northeast_utm.easting = dem->max_east;
386     dem_southwest_utm.northing = dem->min_north;
387     dem_southwest_utm.easting = dem->min_east;
388     dem_northeast_utm.zone = dem_southwest_utm.zone = dem->utm_zone;
389     dem_northeast_utm.letter = dem_southwest_utm.letter = dem->utm_letter;
390
391     a_coords_utm_to_latlon(&dem_northeast_utm, &dem_northeast);
392     a_coords_utm_to_latlon(&dem_southwest_utm, &dem_southwest);
393   }
394
395   if ( (max_lat > dem_northeast.lat && min_lat > dem_northeast.lat) ||
396        (max_lat < dem_southwest.lat && min_lat < dem_southwest.lat) )
397     return;
398   else if ( (max_lon > dem_northeast.lon && min_lon > dem_northeast.lon) ||
399             (max_lon < dem_southwest.lon && min_lon < dem_southwest.lon) )
400     return;
401   /* else they overlap */
402
403   /**** End Overlap Check ****/
404   /* boxes to show where we have DEM instead of actually drawing the DEM.
405    * useful if we want to see what areas we have coverage for (if we want
406    * to get elevation data for a track) but don't want to cover the map.
407    */
408
409   #if 0
410   /* draw a box if a DEM is loaded. in future I'd like to add an option for this
411    * this is useful if we want to see what areas we have dem for but don't want to
412    * cover the map (or maybe we just need translucent DEM?) */
413   {
414     VikCoord demne, demsw;
415     gint x1, y1, x2, y2;
416     vik_coord_load_from_latlon(&demne, vik_viewport_get_coord_mode(vp), &dem_northeast);
417     vik_coord_load_from_latlon(&demsw, vik_viewport_get_coord_mode(vp), &dem_southwest);
418
419     vik_viewport_coord_to_screen ( vp, &demne, &x1, &y1 );
420     vik_viewport_coord_to_screen ( vp, &demsw, &x2, &y2 );
421
422     if ( x1 > vik_viewport_get_width(vp) ) x1=vik_viewport_get_width(vp);
423     if ( y2 > vik_viewport_get_height(vp) ) y2=vik_viewport_get_height(vp);
424     if ( x2 < 0 ) x2 = 0;
425     if ( y1 < 0 ) y1 = 0;
426     vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
427         FALSE, x2, y1, x1-x2, y2-y1 );
428     return;
429   }
430   #endif
431
432   if ( dem->horiz_units == VIK_DEM_HORIZ_LL_ARCSECONDS ) {
433     VikCoord tmp; /* TODO: don't use coord_load_from_latlon, especially if in latlon drawing mode */
434
435     gdouble max_lat_as, max_lon_as, min_lat_as, min_lon_as;  
436     gdouble start_lat_as, end_lat_as, start_lon_as, end_lon_as;
437
438     gdouble start_lat, end_lat, start_lon, end_lon;
439
440     struct LatLon counter;
441
442     guint x, y, start_x, start_y;
443
444     gint16 elev;
445
446     guint skip_factor = ceil ( vik_viewport_get_xmpp(vp) / 80 ); /* todo: smarter calculation. */
447
448     gdouble nscale_deg = dem->north_scale / ((gdouble) 3600);
449     gdouble escale_deg = dem->east_scale / ((gdouble) 3600);
450
451     max_lat_as = max_lat * 3600;
452     min_lat_as = min_lat * 3600;
453     max_lon_as = max_lon * 3600;
454     min_lon_as = min_lon * 3600;
455
456     start_lat_as = MAX(min_lat_as, dem->min_north);
457     end_lat_as   = MIN(max_lat_as, dem->max_north);
458     start_lon_as = MAX(min_lon_as, dem->min_east);
459     end_lon_as   = MIN(max_lon_as, dem->max_east);
460
461     start_lat = floor(start_lat_as / dem->north_scale) * nscale_deg;
462     end_lat   = ceil (end_lat_as / dem->north_scale) * nscale_deg;
463     start_lon = floor(start_lon_as / dem->east_scale) * escale_deg;
464     end_lon   = ceil (end_lon_as / dem->east_scale) * escale_deg;
465
466     vik_dem_east_north_to_xy ( dem, start_lon_as, start_lat_as, &start_x, &start_y );
467     guint gradient_skip_factor = 1;
468     if(vdl->type == DEM_TYPE_GRADIENT)
469             gradient_skip_factor = skip_factor;
470
471     /* verify sane elev interval */
472     if ( vdl->max_elev <= vdl->min_elev )
473       vdl->max_elev = vdl->min_elev + 1;
474
475     for ( x=start_x, counter.lon = start_lon; counter.lon <= end_lon+escale_deg*skip_factor; counter.lon += escale_deg * skip_factor, x += skip_factor ) {
476       // NOTE: ( counter.lon <= end_lon + ESCALE_DEG*SKIP_FACTOR ) is neccessary so in high zoom modes,
477       // the leftmost column does also get drawn, if the center point is out of viewport.
478       if ( x >= 0 && x < dem->n_columns ) {
479         column = g_ptr_array_index ( dem->columns, x );
480         // get previous and next column. catch out-of-bound.
481         gint32 new_x = x;
482         new_x -= gradient_skip_factor;
483         if(new_x < 1)
484           prevcolumn = g_ptr_array_index ( dem->columns, x+1);
485         else
486           prevcolumn = g_ptr_array_index ( dem->columns, new_x);
487         new_x = x;
488         new_x += gradient_skip_factor;
489         if(new_x >= dem->n_columns)
490           nextcolumn = g_ptr_array_index ( dem->columns, x-1);
491         else
492           nextcolumn = g_ptr_array_index ( dem->columns, new_x);
493
494         for ( y=start_y, counter.lat = start_lat; counter.lat <= end_lat; counter.lat += nscale_deg * skip_factor, y += skip_factor ) {
495           if ( y > column->n_points )
496             break;
497
498           elev = column->points[y];
499
500           // calculate bounding box for drawing
501           gint box_x, box_y, box_width, box_height;
502           struct LatLon box_c;
503           box_c = counter;
504           box_c.lat += (nscale_deg * skip_factor)/2;
505           box_c.lon -= (escale_deg * skip_factor)/2;
506           vik_coord_load_from_latlon(&tmp, vik_viewport_get_coord_mode(vp), &box_c);
507           vik_viewport_coord_to_screen(vp, &tmp, &box_x, &box_y);
508           // catch box at borders
509           if(box_x < 0)
510                   box_x = 0;
511           if(box_y < 0)
512                   box_y = 0;
513           box_c.lat -= nscale_deg * skip_factor;
514           box_c.lon += escale_deg * skip_factor;
515           vik_coord_load_from_latlon(&tmp, vik_viewport_get_coord_mode(vp), &box_c);
516           vik_viewport_coord_to_screen(vp, &tmp, &box_width, &box_height);
517           box_width -= box_x;
518           box_height -= box_y;
519           // catch box at borders
520           if(box_width < 0 || box_height < 0)
521                   continue; // skip this. this is out of our viewport anyway. FIXME: why?
522
523           if(vdl->type == DEM_TYPE_HEIGHT) {
524             if ( elev != VIK_DEM_INVALID_ELEVATION && elev < vdl->min_elev )
525               elev=vdl->min_elev;
526             if ( elev != VIK_DEM_INVALID_ELEVATION && elev > vdl->max_elev )
527               elev=vdl->max_elev;
528           }
529
530           {
531             if(box_width < 0 || box_height < 0) // FIXME: why does this happen?
532               continue;
533
534             if(vdl->type == DEM_TYPE_GRADIENT) {
535               if( elev == VIK_DEM_INVALID_ELEVATION ) {
536                 /* don't draw it */
537               } else {
538                 // calculate and sum gradient in all directions
539                 gint16 change = 0;
540                 gint32 new_y;
541
542                 // calculate gradient from height points all around the current one
543                 new_y = y - gradient_skip_factor;
544                 if(new_y < 0)
545                         new_y = y;
546                 change += get_height_difference(elev, prevcolumn->points[new_y]);
547                 change += get_height_difference(elev, column->points[new_y]);
548                 change += get_height_difference(elev, nextcolumn->points[new_y]);
549
550                 change += get_height_difference(elev, prevcolumn->points[y]);
551                 change += get_height_difference(elev, nextcolumn->points[y]);
552
553                 new_y = y + gradient_skip_factor;
554                 if(new_y >= column->n_points)
555                         new_y = y;
556                 change += get_height_difference(elev, prevcolumn->points[new_y]);
557                 change += get_height_difference(elev, column->points[new_y]);
558                 change += get_height_difference(elev, nextcolumn->points[new_y]);
559
560                 change = change / ((skip_factor > 1) ? log(skip_factor) : 0.55); // FIXME: better calc.
561
562                 if(change < vdl->min_elev)
563                   change = vdl->min_elev;
564
565                 if(change > vdl->max_elev)
566                   change = vdl->max_elev;
567
568                 // void vik_viewport_draw_rectangle ( VikViewport *vvp, GdkGC *gc, gboolean filled, gint x1, gint y1, gint x2, gint y2 );
569                 vik_viewport_draw_rectangle(vp, vdl->gcsgradient[(gint)floor((change - vdl->min_elev)/(vdl->max_elev - vdl->min_elev)*(DEM_N_GRADIENT_COLORS-2))+1], TRUE, box_x, box_y, box_width, box_height);
570               }
571             } else {
572               if(vdl->type == DEM_TYPE_HEIGHT) {
573                 if ( elev == VIK_DEM_INVALID_ELEVATION )
574                   ; /* don't draw it */
575                 else if ( elev <= 0 )
576                   vik_viewport_draw_rectangle(vp, vdl->gcs[0], TRUE, box_x, box_y, box_width, box_height);
577                 else
578                   vik_viewport_draw_rectangle(vp, vdl->gcs[(gint)floor((elev - vdl->min_elev)/(vdl->max_elev - vdl->min_elev)*(DEM_N_HEIGHT_COLORS-2))+1], TRUE, box_x, box_y, box_width, box_height);
579               }
580             }
581           }
582         } /* for y= */
583       }
584     } /* for x= */
585   } else if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
586     gdouble max_nor, max_eas, min_nor, min_eas;
587     gdouble start_nor, start_eas, end_nor, end_eas;
588
589     gint16 elev;
590
591     guint x, y, start_x, start_y;
592
593     VikCoord tmp; /* TODO: don't use coord_load_from_latlon, especially if in latlon drawing mode */
594     struct UTM counter;
595
596     guint skip_factor = ceil ( vik_viewport_get_xmpp(vp) / 10 ); /* todo: smarter calculation. */
597
598     VikCoord tleft, tright, bleft, bright;
599
600     vik_viewport_screen_to_coord ( vp, 0, 0, &tleft );
601     vik_viewport_screen_to_coord ( vp, vik_viewport_get_width(vp), 0, &tright );
602     vik_viewport_screen_to_coord ( vp, 0, vik_viewport_get_height(vp), &bleft );
603     vik_viewport_screen_to_coord ( vp, vik_viewport_get_width(vp), vik_viewport_get_height(vp), &bright );
604
605
606     vik_coord_convert(&tleft, VIK_COORD_UTM);
607     vik_coord_convert(&tright, VIK_COORD_UTM);
608     vik_coord_convert(&bleft, VIK_COORD_UTM);
609     vik_coord_convert(&bright, VIK_COORD_UTM);
610
611     max_nor = MAX(tleft.north_south, tright.north_south);
612     min_nor = MIN(bleft.north_south, bright.north_south);
613     max_eas = MAX(bright.east_west, tright.east_west);
614     min_eas = MIN(bleft.east_west, tleft.east_west);
615
616     start_nor = MAX(min_nor, dem->min_north);
617     end_nor   = MIN(max_nor, dem->max_north);
618     if ( tleft.utm_zone == dem->utm_zone && bleft.utm_zone == dem->utm_zone
619          && (tleft.utm_letter >= 'N') == (dem->utm_letter >= 'N')
620          && (bleft.utm_letter >= 'N') == (dem->utm_letter >= 'N') ) /* if the utm zones/hemispheres are different, min_eas will be bogus */
621       start_eas = MAX(min_eas, dem->min_east);
622     else
623       start_eas = dem->min_east;
624     if ( tright.utm_zone == dem->utm_zone && bright.utm_zone == dem->utm_zone
625          && (tright.utm_letter >= 'N') == (dem->utm_letter >= 'N')
626          && (bright.utm_letter >= 'N') == (dem->utm_letter >= 'N') ) /* if the utm zones/hemispheres are different, min_eas will be bogus */
627       end_eas = MIN(max_eas, dem->max_east);
628     else
629       end_eas = dem->max_east;
630
631     start_nor = floor(start_nor / dem->north_scale) * dem->north_scale;
632     end_nor   = ceil (end_nor / dem->north_scale) * dem->north_scale;
633     start_eas = floor(start_eas / dem->east_scale) * dem->east_scale;
634     end_eas   = ceil (end_eas / dem->east_scale) * dem->east_scale;
635
636     vik_dem_east_north_to_xy ( dem, start_eas, start_nor, &start_x, &start_y );
637
638     /* TODO: why start_x and start_y are -1 -- rounding error from above? */
639
640     counter.zone = dem->utm_zone;
641     counter.letter = dem->utm_letter;
642
643     for ( x=start_x, counter.easting = start_eas; counter.easting <= end_eas; counter.easting += dem->east_scale * skip_factor, x += skip_factor ) {
644       if ( x > 0 && x < dem->n_columns ) {
645         column = g_ptr_array_index ( dem->columns, x );
646         for ( y=start_y, counter.northing = start_nor; counter.northing <= end_nor; counter.northing += dem->north_scale * skip_factor, y += skip_factor ) {
647           if ( y > column->n_points )
648             continue;
649           elev = column->points[y];
650           if ( elev != VIK_DEM_INVALID_ELEVATION && elev < vdl->min_elev )
651             elev=vdl->min_elev;
652           if ( elev != VIK_DEM_INVALID_ELEVATION && elev > vdl->max_elev )
653             elev=vdl->max_elev;
654
655           {
656             gint a, b;
657             vik_coord_load_from_utm(&tmp, vik_viewport_get_coord_mode(vp), &counter);
658                     vik_viewport_coord_to_screen(vp, &tmp, &a, &b);
659             if ( elev == VIK_DEM_INVALID_ELEVATION )
660               ; /* don't draw it */
661             else if ( elev <= 0 )
662               vik_viewport_draw_rectangle(vp, vdl->gcs[0], TRUE, a-1, b-1, 2, 2 );
663             else
664               vik_viewport_draw_rectangle(vp, vdl->gcs[(gint)floor((elev - vdl->min_elev)/(vdl->max_elev - vdl->min_elev)*(DEM_N_HEIGHT_COLORS-2))+1], TRUE, a-1, b-1, 2, 2 );
665           }
666         } /* for y= */
667       }
668     } /* for x= */
669   }
670 }
671
672 /* return the continent for the specified lat, lon */
673 /* TODO */
674 static const gchar *srtm_continent_dir ( gint lat, gint lon )
675 {
676   extern const char *_srtm_continent_data[];
677   static GHashTable *srtm_continent = NULL;
678   const gchar *continent;
679   gchar name[16];
680
681   if (!srtm_continent) {
682     const gchar **s;
683
684     srtm_continent = g_hash_table_new(g_str_hash, g_str_equal);
685     s = _srtm_continent_data;
686     while (*s != (gchar *)-1) {
687       continent = *s++;
688       while (*s) {
689         g_hash_table_insert(srtm_continent, (gpointer) *s, (gpointer) continent);
690         s++;
691       }
692       s++;
693     }
694   }
695   g_snprintf(name, sizeof(name), "%c%02d%c%03d",
696                   (lat >= 0) ? 'N' : 'S', ABS(lat),
697                   (lon >= 0) ? 'E' : 'W', ABS(lon));
698
699   return(g_hash_table_lookup(srtm_continent, name));
700 }
701
702 void vik_dem_layer_draw ( VikDEMLayer *vdl, gpointer data )
703 {
704   VikViewport *vp = (VikViewport *) data;
705   GList *dems_iter = vdl->files;
706   VikDEM *dem;
707
708
709   /* search for SRTM3 90m */
710
711   if ( vdl->source == DEM_SOURCE_SRTM )
712     srtm_draw_existence ( vp );
713 #ifdef VIK_CONFIG_DEM24K
714   else if ( vdl->source == DEM_SOURCE_DEM24K )
715     dem24k_draw_existence ( vp );
716 #endif
717
718   while ( dems_iter ) {
719     dem = a_dems_get ( (const char *) (dems_iter->data) );
720     if ( dem )
721       vik_dem_layer_draw_dem ( vdl, vp, dem );
722     dems_iter = dems_iter->next;
723   }
724 }
725
726 void vik_dem_layer_free ( VikDEMLayer *vdl )
727 {
728   gint i;
729   if ( vdl->gc != NULL )
730     g_object_unref ( G_OBJECT(vdl->gc) );
731
732   if ( vdl->color != NULL )
733     g_free ( vdl->color );
734
735   if ( vdl->gcs )
736     for ( i = 0; i < DEM_N_HEIGHT_COLORS; i++ )
737       g_object_unref ( vdl->gcs[i] );
738   g_free ( vdl->gcs );
739
740   if ( vdl->gcsgradient )
741     for ( i = 0; i < DEM_N_GRADIENT_COLORS; i++ )
742       g_object_unref ( vdl->gcsgradient[i] );
743   g_free ( vdl->gcsgradient );
744
745   a_dems_list_free ( vdl->files );
746 }
747
748 static void dem_layer_update_gc ( VikDEMLayer *vdl, VikViewport *vp, const gchar *color )
749 {
750   if ( vdl->color )
751     g_free ( vdl->color );
752
753   vdl->color = g_strdup ( color );
754
755   if ( vdl->gc )
756     g_object_unref ( G_OBJECT(vdl->gc) );
757
758   vdl->gc = vik_viewport_new_gc ( vp, vdl->color, vdl->line_thickness );
759 }
760
761 VikDEMLayer *vik_dem_layer_create ( VikViewport *vp )
762 {
763   VikDEMLayer *vdl = vik_dem_layer_new ();
764   gint i;
765
766   /* TODO: share GCS between layers */
767   for ( i = 0; i < DEM_N_HEIGHT_COLORS; i++ )
768     vdl->gcs[i] = vik_viewport_new_gc ( vp, dem_height_colors[i], vdl->line_thickness );
769
770   for ( i = 0; i < DEM_N_GRADIENT_COLORS; i++ )
771     vdl->gcsgradient[i] = vik_viewport_new_gc ( vp, dem_gradient_colors[i], vdl->line_thickness );
772
773   dem_layer_update_gc ( vdl, vp, "red" );
774   return vdl;
775 }
776 /**************************************************************
777  **** SOURCES & DOWNLOADING
778  **************************************************************/
779 typedef struct {
780   gchar *dest;
781   gdouble lat, lon;
782
783   GMutex *mutex;
784   VikDEMLayer *vdl; /* NULL if not alive */
785
786   guint source;
787 } DEMDownloadParams;
788
789
790 /**************************************************
791  *  SOURCE: SRTM                                  *
792  **************************************************/
793
794 static void srtm_dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
795 {
796   gint intlat, intlon;
797   const gchar *continent_dir;
798
799   intlat = (int)floor(p->lat);
800   intlon = (int)floor(p->lon);
801   continent_dir = srtm_continent_dir(intlat, intlon);
802
803   if (!continent_dir) {
804     g_warning(N_("No SRTM data available for %f, %f"), p->lat, p->lon);
805     return;
806   }
807
808   gchar *src_fn = g_strdup_printf("%s%s/%c%02d%c%03d.hgt.zip",
809                 SRTM_HTTP_URI,
810                 continent_dir,
811                 (intlat >= 0) ? 'N' : 'S',
812                 ABS(intlat),
813                 (intlon >= 0) ? 'E' : 'W',
814                 ABS(intlon) );
815
816   static DownloadOptions options = { 0, NULL, 0, a_check_map_file };
817   a_http_download_get_url ( SRTM_HTTP_SITE, src_fn, p->dest, &options, NULL );
818   g_free ( src_fn );
819 }
820
821 static gchar *srtm_lat_lon_to_dest_fn ( gdouble lat, gdouble lon )
822 {
823   gint intlat, intlon;
824   const gchar *continent_dir;
825
826   intlat = (int)floor(lat);
827   intlon = (int)floor(lon);
828   continent_dir = srtm_continent_dir(intlat, intlon);
829
830   if (!continent_dir)
831     continent_dir = "nowhere";
832
833   return g_strdup_printf("srtm3-%s%s%c%02d%c%03d.hgt.zip",
834                 continent_dir,
835                 G_DIR_SEPARATOR_S,
836                 (intlat >= 0) ? 'N' : 'S',
837                 ABS(intlat),
838                 (intlon >= 0) ? 'E' : 'W',
839                 ABS(intlon) );
840
841 }
842
843 /* TODO: generalize */
844 static void srtm_draw_existence ( VikViewport *vp )
845 {
846   gdouble max_lat, max_lon, min_lat, min_lon;  
847   gchar buf[strlen(MAPS_CACHE_DIR)+strlen(SRTM_CACHE_TEMPLATE)+30];
848   gint i, j;
849
850   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
851
852   for (i = floor(min_lat); i <= floor(max_lat); i++) {
853     for (j = floor(min_lon); j <= floor(max_lon); j++) {
854       const gchar *continent_dir;
855       if ((continent_dir = srtm_continent_dir(i, j)) == NULL)
856         continue;
857       g_snprintf(buf, sizeof(buf), SRTM_CACHE_TEMPLATE,
858                 MAPS_CACHE_DIR,
859                 continent_dir,
860                 G_DIR_SEPARATOR_S,
861                 (i >= 0) ? 'N' : 'S',
862                 ABS(i),
863                 (j >= 0) ? 'E' : 'W',
864                 ABS(j) );
865       if ( g_file_test(buf, G_FILE_TEST_EXISTS ) == TRUE ) {
866         VikCoord ne, sw;
867         gint x1, y1, x2, y2;
868         sw.north_south = i;
869         sw.east_west = j;
870         sw.mode = VIK_COORD_LATLON;
871         ne.north_south = i+1;
872         ne.east_west = j+1;
873         ne.mode = VIK_COORD_LATLON;
874         vik_viewport_coord_to_screen ( vp, &sw, &x1, &y1 );
875         vik_viewport_coord_to_screen ( vp, &ne, &x2, &y2 );
876         if ( x1 < 0 ) x1 = 0;
877         if ( y2 < 0 ) y2 = 0;
878         vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
879                 FALSE, x1, y2, x2-x1, y1-y2 );
880       }
881     }
882   }
883 }
884
885
886 /**************************************************
887  *  SOURCE: USGS 24K                              *
888  **************************************************/
889
890 #ifdef VIK_CONFIG_DEM24K
891
892 static void dem24k_dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
893 {
894   /* TODO: dest dir */
895   gchar *cmdline = g_strdup_printf("%s %.03f %.03f",
896         DEM24K_DOWNLOAD_SCRIPT,
897         floor(p->lat*8)/8,
898         ceil(p->lon*8)/8 );
899   /* FIX: don't use system, use execv or something. check for existence */
900   system(cmdline);
901 }
902
903 static gchar *dem24k_lat_lon_to_dest_fn ( gdouble lat, gdouble lon )
904 {
905   return g_strdup_printf("dem24k/%d/%d/%.03f,%.03f.dem",
906         (gint) lat,
907         (gint) lon,
908         floor(lat*8)/8,
909         ceil(lon*8)/8);
910 }
911
912 /* TODO: generalize */
913 static void dem24k_draw_existence ( VikViewport *vp )
914 {
915   gdouble max_lat, max_lon, min_lat, min_lon;  
916   gchar buf[strlen(MAPS_CACHE_DIR)+40];
917   gdouble i, j;
918
919   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
920
921   for (i = floor(min_lat*8)/8; i <= floor(max_lat*8)/8; i+=0.125) {
922     /* check lat dir first -- faster */
923     g_snprintf(buf, sizeof(buf), "%sdem24k/%d/",
924         MAPS_CACHE_DIR,
925         (gint) i );
926     if ( g_file_test(buf, G_FILE_TEST_EXISTS) == FALSE )
927       continue;
928     for (j = floor(min_lon*8)/8; j <= floor(max_lon*8)/8; j+=0.125) {
929       /* check lon dir first -- faster */
930       g_snprintf(buf, sizeof(buf), "%sdem24k/%d/%d/",
931         MAPS_CACHE_DIR,
932         (gint) i,
933         (gint) j );
934       if ( g_file_test(buf, G_FILE_TEST_EXISTS) == FALSE )
935         continue;
936       g_snprintf(buf, sizeof(buf), "%sdem24k/%d/%d/%.03f,%.03f.dem",
937                 MAPS_CACHE_DIR,
938                 (gint) i,
939                 (gint) j,
940                 floor(i*8)/8,
941                 floor(j*8)/8 );
942       if ( g_file_test(buf, G_FILE_TEST_EXISTS ) == TRUE ) {
943         VikCoord ne, sw;
944         gint x1, y1, x2, y2;
945         sw.north_south = i;
946         sw.east_west = j-0.125;
947         sw.mode = VIK_COORD_LATLON;
948         ne.north_south = i+0.125;
949         ne.east_west = j;
950         ne.mode = VIK_COORD_LATLON;
951         vik_viewport_coord_to_screen ( vp, &sw, &x1, &y1 );
952         vik_viewport_coord_to_screen ( vp, &ne, &x2, &y2 );
953         if ( x1 < 0 ) x1 = 0;
954         if ( y2 < 0 ) y2 = 0;
955         vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
956                 FALSE, x1, y2, x2-x1, y1-y2 );
957       }
958     }
959   }
960 }
961 #endif
962
963 /**************************************************
964  *   SOURCES -- DOWNLOADING & IMPORTING TOOL      *
965  **************************************************
966  */
967
968 static void weak_ref_cb ( gpointer ptr, GObject * dead_vdl )
969 {
970   DEMDownloadParams *p = ptr;
971   g_mutex_lock ( p->mutex );
972   p->vdl = NULL;
973   g_mutex_unlock ( p->mutex );
974 }
975
976 /* Try to add file full_path.
977  * full_path will be copied.
978  * returns FALSE if file does not exists, TRUE otherwise.
979  */
980 static gboolean dem_layer_add_file ( VikDEMLayer *vdl, const gchar *full_path )
981 {
982   if ( g_file_test(full_path, G_FILE_TEST_EXISTS ) == TRUE ) {
983     /* only load if file size is not 0 (not in progress) */
984     struct stat sb;
985     stat (full_path, &sb);
986     if ( sb.st_size ) {
987       gchar *duped_path = g_strdup(full_path);
988       vdl->files = g_list_prepend ( vdl->files, duped_path );
989       a_dems_load ( duped_path );
990       g_debug("%s: %s", __FUNCTION__, duped_path);
991       vik_layer_emit_update ( VIK_LAYER(vdl) );
992     }
993     return TRUE;
994   } else
995     return FALSE;
996 }
997
998 static void dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
999 {
1000   if ( p->source == DEM_SOURCE_SRTM )
1001     srtm_dem_download_thread ( p, threaddata );
1002 #ifdef VIK_CONFIG_DEM24K
1003   else if ( p->source == DEM_SOURCE_DEM24K )
1004     dem24k_dem_download_thread ( p, threaddata );
1005 #endif
1006
1007   gdk_threads_enter();
1008   g_mutex_lock ( p->mutex );
1009   if ( p->vdl ) {
1010     g_object_weak_unref ( G_OBJECT(p->vdl), weak_ref_cb, p );
1011
1012     if ( dem_layer_add_file ( p->vdl, p->dest ) )
1013       vik_layer_emit_update ( VIK_LAYER(p->vdl) );
1014   }
1015   g_mutex_unlock ( p->mutex );
1016   gdk_threads_leave();
1017 }
1018
1019
1020 static void free_dem_download_params ( DEMDownloadParams *p )
1021 {
1022   g_mutex_free ( p->mutex );
1023   g_free ( p->dest );
1024   g_free ( p );
1025 }
1026
1027 static gpointer dem_layer_download_create ( VikWindow *vw, VikViewport *vvp)
1028 {
1029   return vvp;
1030 }
1031
1032
1033 static gboolean dem_layer_download_release ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp )
1034 {
1035   VikCoord coord;
1036   struct LatLon ll;
1037
1038   gchar *full_path;
1039   gchar *dem_file = NULL;
1040
1041   if ( vdl->source == DEM_SOURCE_NONE )
1042     a_dialog_error_msg ( VIK_GTK_WINDOW_FROM_LAYER(vdl), _("No download source selected. Edit layer properties.") );
1043
1044   vik_viewport_screen_to_coord ( vvp, event->x, event->y, &coord );
1045   vik_coord_to_latlon ( &coord, &ll );
1046
1047   
1048   if ( vdl->source == DEM_SOURCE_SRTM )
1049     dem_file = srtm_lat_lon_to_dest_fn ( ll.lat, ll.lon );
1050 #ifdef VIK_CONFIG_DEM24K
1051   else if ( vdl->source == DEM_SOURCE_DEM24K )
1052     dem_file = dem24k_lat_lon_to_dest_fn ( ll.lat, ll.lon );
1053 #endif
1054
1055   if ( ! dem_file )
1056     return TRUE;
1057
1058   full_path = g_strdup_printf("%s%s", MAPS_CACHE_DIR, dem_file );
1059
1060   g_debug("%s: %s", __FUNCTION__, full_path);
1061
1062   // TODO: check if already in filelist
1063
1064   if ( ! dem_layer_add_file(vdl, full_path) ) {
1065     gchar *tmp = g_strdup_printf ( _("Downloading DEM %s"), dem_file );
1066     DEMDownloadParams *p = g_malloc(sizeof(DEMDownloadParams));
1067     p->dest = g_strdup(full_path);
1068     p->lat = ll.lat;
1069     p->lon = ll.lon;
1070     p->vdl = vdl;
1071     p->mutex = g_mutex_new();
1072     p->source = vdl->source;
1073     g_object_weak_ref(G_OBJECT(p->vdl), weak_ref_cb, p );
1074
1075     a_background_thread ( VIK_GTK_WINDOW_FROM_LAYER(vdl), tmp,
1076                 (vik_thr_func) dem_download_thread, p,
1077                 (vik_thr_free_func) free_dem_download_params, NULL, 1 );
1078   }
1079
1080   g_free ( dem_file );
1081   g_free ( full_path );
1082
1083   return TRUE;
1084 }
1085
1086 static gboolean dem_layer_download_click ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp )
1087 {
1088 /* choose & keep track of cache dir
1089  * download in background thread
1090  * download over area */
1091   return TRUE;
1092 }
1093
1094