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