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