]> git.street.me.uk Git - andy/viking.git/blob - src/vikdemlayer.c
Remove OpenAerial
[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/OLD/"
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
356 static void vik_dem_layer_draw_dem ( VikDEMLayer *vdl, VikViewport *vp, VikDEM *dem )
357 {
358   VikDEMColumn *column;
359   VikDEMColumn *nextcolumn;
360
361   struct LatLon dem_northeast, dem_southwest;
362   gdouble max_lat, max_lon, min_lat, min_lon;  
363
364   /**** Check if viewport and DEM data overlap ****/
365
366   /* get min, max lat/lon of viewport */
367   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
368
369   /* get min, max lat/lon of DEM data */
370   if ( dem->horiz_units == VIK_DEM_HORIZ_LL_ARCSECONDS ) {
371     dem_northeast.lat = dem->max_north / 3600.0;
372     dem_northeast.lon = dem->max_east / 3600.0;
373     dem_southwest.lat = dem->min_north / 3600.0;
374     dem_southwest.lon = dem->min_east / 3600.0;
375   } else if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
376     struct UTM dem_northeast_utm, dem_southwest_utm;
377     dem_northeast_utm.northing = dem->max_north;
378     dem_northeast_utm.easting = dem->max_east;
379     dem_southwest_utm.northing = dem->min_north;
380     dem_southwest_utm.easting = dem->min_east;
381     dem_northeast_utm.zone = dem_southwest_utm.zone = dem->utm_zone;
382     dem_northeast_utm.letter = dem_southwest_utm.letter = dem->utm_letter;
383
384     a_coords_utm_to_latlon(&dem_northeast_utm, &dem_northeast);
385     a_coords_utm_to_latlon(&dem_southwest_utm, &dem_southwest);
386   }
387
388   if ( (max_lat > dem_northeast.lat && min_lat > dem_northeast.lat) ||
389        (max_lat < dem_southwest.lat && min_lat < dem_southwest.lat) )
390     return;
391   else if ( (max_lon > dem_northeast.lon && min_lon > dem_northeast.lon) ||
392             (max_lon < dem_southwest.lon && min_lon < dem_southwest.lon) )
393     return;
394   /* else they overlap */
395
396   /**** End Overlap Check ****/
397   /* boxes to show where we have DEM instead of actually drawing the DEM.
398    * useful if we want to see what areas we have coverage for (if we want
399    * to get elevation data for a track) but don't want to cover the map.
400    */
401
402   #if 0
403   /* draw a box if a DEM is loaded. in future I'd like to add an option for this
404    * this is useful if we want to see what areas we have dem for but don't want to
405    * cover the map (or maybe we just need translucent DEM?) */
406   {
407     VikCoord demne, demsw;
408     gint x1, y1, x2, y2;
409     vik_coord_load_from_latlon(&demne, vik_viewport_get_coord_mode(vp), &dem_northeast);
410     vik_coord_load_from_latlon(&demsw, vik_viewport_get_coord_mode(vp), &dem_southwest);
411
412     vik_viewport_coord_to_screen ( vp, &demne, &x1, &y1 );
413     vik_viewport_coord_to_screen ( vp, &demsw, &x2, &y2 );
414
415     if ( x1 > vik_viewport_get_width(vp) ) x1=vik_viewport_get_width(vp);
416     if ( y2 > vik_viewport_get_height(vp) ) y2=vik_viewport_get_height(vp);
417     if ( x2 < 0 ) x2 = 0;
418     if ( y1 < 0 ) y1 = 0;
419     vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
420         FALSE, x2, y1, x1-x2, y2-y1 );
421     return;
422   }
423   #endif
424
425   if ( dem->horiz_units == VIK_DEM_HORIZ_LL_ARCSECONDS ) {
426     VikCoord tmp; /* TODO: don't use coord_load_from_latlon, especially if in latlon drawing mode */
427
428     gdouble max_lat_as, max_lon_as, min_lat_as, min_lon_as;  
429     gdouble start_lat_as, end_lat_as, start_lon_as, end_lon_as;
430
431     gdouble start_lat, end_lat, start_lon, end_lon;
432
433     struct LatLon counter;
434
435     guint x, y, start_x, start_y;
436
437     gint16 elev;
438
439     guint skip_factor = ceil ( vik_viewport_get_xmpp(vp) / 40 ); /* todo: smarter calculation. */
440
441     gdouble nscale_deg = dem->north_scale / ((gdouble) 3600);
442     gdouble escale_deg = dem->east_scale / ((gdouble) 3600);
443
444     max_lat_as = max_lat * 3600;
445     min_lat_as = min_lat * 3600;
446     max_lon_as = max_lon * 3600;
447     min_lon_as = min_lon * 3600;
448
449     start_lat_as = MAX(min_lat_as, dem->min_north);
450     end_lat_as   = MIN(max_lat_as, dem->max_north);
451     start_lon_as = MAX(min_lon_as, dem->min_east);
452     end_lon_as   = MIN(max_lon_as, dem->max_east);
453
454     start_lat = floor(start_lat_as / dem->north_scale) * nscale_deg;
455     end_lat   = ceil (end_lat_as / dem->north_scale) * nscale_deg;
456     start_lon = floor(start_lon_as / dem->east_scale) * escale_deg;
457     end_lon   = ceil (end_lon_as / dem->east_scale) * escale_deg;
458
459     vik_dem_east_north_to_xy ( dem, start_lon_as, start_lat_as, &start_x, &start_y );
460
461     /* verify sane elev interval */
462     if ( vdl->max_elev <= vdl->min_elev )
463       vdl->max_elev = vdl->min_elev + 1;
464
465     for ( x=start_x, counter.lon = start_lon; counter.lon <= end_lon; counter.lon += escale_deg * skip_factor, x += skip_factor ) {
466       if ( x > 0 && x < dem->n_columns ) {
467         column = g_ptr_array_index ( dem->columns, x );
468         if(x+1 == dem->n_columns) {
469           nextcolumn = g_ptr_array_index ( dem->columns, x-1);
470         } else {
471           nextcolumn = g_ptr_array_index ( dem->columns, x+1);
472         }
473
474         for ( y=start_y, counter.lat = start_lat; counter.lat <= end_lat; counter.lat += nscale_deg * skip_factor, y += skip_factor ) {
475           if ( y > column->n_points )
476             break;
477           elev = column->points[y];
478
479           if(vdl->type == DEM_TYPE_HEIGHT) {
480                   if ( elev != VIK_DEM_INVALID_ELEVATION && elev < vdl->min_elev )
481                     elev=vdl->min_elev;
482                   if ( elev != VIK_DEM_INVALID_ELEVATION && elev > vdl->max_elev )
483                     elev=vdl->max_elev;
484           }
485
486           {
487             gint a, b;
488
489             vik_coord_load_from_latlon(&tmp, vik_viewport_get_coord_mode(vp), &counter);
490             vik_viewport_coord_to_screen(vp, &tmp, &a, &b);
491             if(vdl->type == DEM_TYPE_GRADIENT) {
492                     if( elev == VIK_DEM_INVALID_ELEVATION ) {
493                             /* don't draw it */
494                     } else {
495                             // calculate gradient, but only in two orthogonal directions.
496                             gint16 change = 0;
497                             gint16 newelev;
498
499                             // down
500                             if(y+1 == column->n_points)
501                                     newelev = column->points[y-1];
502                             else
503                                     newelev = column->points[y+1];
504                             if(newelev != VIK_DEM_INVALID_ELEVATION)
505                                     change += abs(newelev - elev);
506
507                             // down + right
508                             if(y+1 == nextcolumn->n_points)
509                                     newelev = nextcolumn->points[y-1];
510                             else
511                                     newelev = nextcolumn->points[y+1];
512                             if(newelev != VIK_DEM_INVALID_ELEVATION)
513                                     change += abs(newelev - elev);
514
515                             // right
516                             newelev = nextcolumn->points[y];
517                             if(newelev != VIK_DEM_INVALID_ELEVATION)
518                                     change += abs(newelev - elev);
519
520                             // up + right
521                             if(y <= 1)
522                                     newelev = nextcolumn->points[y+1];
523                             else
524                                     newelev = nextcolumn->points[y-1];
525                             if(newelev != VIK_DEM_INVALID_ELEVATION)
526                                     change += abs(newelev - elev);
527
528                             change = log(change) * log(change) * log(change);
529
530                             if(change < vdl->min_elev)
531                                     change = vdl->min_elev;
532
533                             if(change > vdl->max_elev)
534                                     change = vdl->max_elev;
535
536                             // void vik_viewport_draw_rectangle ( VikViewport *vvp, GdkGC *gc, gboolean filled, gint x1, gint y1, gint x2, gint y2 );
537                             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, a-2, b-2, 4, 4 );
538                     }
539             } else {
540                     if(vdl->type == DEM_TYPE_HEIGHT) {
541                             if ( elev == VIK_DEM_INVALID_ELEVATION )
542                               ; /* don't draw it */
543                             else if ( elev <= 0 )
544                               vik_viewport_draw_rectangle(vp, vdl->gcs[0], TRUE, a-2, b-2, 4, 4 );
545                             else
546                               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-2, b-2, 4, 4 );
547                     }
548             }
549
550           }
551         } /* for y= */
552       }
553     } /* for x= */
554   } else if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
555     gdouble max_nor, max_eas, min_nor, min_eas;
556     gdouble start_nor, start_eas, end_nor, end_eas;
557
558     gint16 elev;
559
560     guint x, y, start_x, start_y;
561
562     VikCoord tmp; /* TODO: don't use coord_load_from_latlon, especially if in latlon drawing mode */
563     struct UTM counter;
564
565     guint skip_factor = ceil ( vik_viewport_get_xmpp(vp) / 10 ); /* todo: smarter calculation. */
566
567     VikCoord tleft, tright, bleft, bright;
568
569     vik_viewport_screen_to_coord ( vp, 0, 0, &tleft );
570     vik_viewport_screen_to_coord ( vp, vik_viewport_get_width(vp), 0, &tright );
571     vik_viewport_screen_to_coord ( vp, 0, vik_viewport_get_height(vp), &bleft );
572     vik_viewport_screen_to_coord ( vp, vik_viewport_get_width(vp), vik_viewport_get_height(vp), &bright );
573
574
575     vik_coord_convert(&tleft, VIK_COORD_UTM);
576     vik_coord_convert(&tright, VIK_COORD_UTM);
577     vik_coord_convert(&bleft, VIK_COORD_UTM);
578     vik_coord_convert(&bright, VIK_COORD_UTM);
579
580     max_nor = MAX(tleft.north_south, tright.north_south);
581     min_nor = MIN(bleft.north_south, bright.north_south);
582     max_eas = MAX(bright.east_west, tright.east_west);
583     min_eas = MIN(bleft.east_west, tleft.east_west);
584
585     start_nor = MAX(min_nor, dem->min_north);
586     end_nor   = MIN(max_nor, dem->max_north);
587     if ( tleft.utm_zone == dem->utm_zone && bleft.utm_zone == dem->utm_zone
588          && (tleft.utm_letter >= 'N') == (dem->utm_letter >= 'N')
589          && (bleft.utm_letter >= 'N') == (dem->utm_letter >= 'N') ) /* if the utm zones/hemispheres are different, min_eas will be bogus */
590       start_eas = MAX(min_eas, dem->min_east);
591     else
592       start_eas = dem->min_east;
593     if ( tright.utm_zone == dem->utm_zone && bright.utm_zone == dem->utm_zone
594          && (tright.utm_letter >= 'N') == (dem->utm_letter >= 'N')
595          && (bright.utm_letter >= 'N') == (dem->utm_letter >= 'N') ) /* if the utm zones/hemispheres are different, min_eas will be bogus */
596       end_eas = MIN(max_eas, dem->max_east);
597     else
598       end_eas = dem->max_east;
599
600     start_nor = floor(start_nor / dem->north_scale) * dem->north_scale;
601     end_nor   = ceil (end_nor / dem->north_scale) * dem->north_scale;
602     start_eas = floor(start_eas / dem->east_scale) * dem->east_scale;
603     end_eas   = ceil (end_eas / dem->east_scale) * dem->east_scale;
604
605     vik_dem_east_north_to_xy ( dem, start_eas, start_nor, &start_x, &start_y );
606
607     /* TODO: why start_x and start_y are -1 -- rounding error from above? */
608
609     counter.zone = dem->utm_zone;
610     counter.letter = dem->utm_letter;
611
612     for ( x=start_x, counter.easting = start_eas; counter.easting <= end_eas; counter.easting += dem->east_scale * skip_factor, x += skip_factor ) {
613       if ( x > 0 && x < dem->n_columns ) {
614         column = g_ptr_array_index ( dem->columns, x );
615         for ( y=start_y, counter.northing = start_nor; counter.northing <= end_nor; counter.northing += dem->north_scale * skip_factor, y += skip_factor ) {
616           if ( y > column->n_points )
617             continue;
618           elev = column->points[y];
619           if ( elev != VIK_DEM_INVALID_ELEVATION && elev < vdl->min_elev )
620             elev=vdl->min_elev;
621           if ( elev != VIK_DEM_INVALID_ELEVATION && elev > vdl->max_elev )
622             elev=vdl->max_elev;
623
624           {
625             gint a, b;
626             vik_coord_load_from_utm(&tmp, vik_viewport_get_coord_mode(vp), &counter);
627                     vik_viewport_coord_to_screen(vp, &tmp, &a, &b);
628             if ( elev == VIK_DEM_INVALID_ELEVATION )
629               ; /* don't draw it */
630             else if ( elev <= 0 )
631               vik_viewport_draw_rectangle(vp, vdl->gcs[0], TRUE, a-2, b-2, 4, 4 );
632             else
633               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-2, b-2, 4, 4 );
634           }
635         } /* for y= */
636       }
637     } /* for x= */
638   }
639 }
640
641 /* return the continent for the specified lat, lon */
642 /* TODO */
643 static const gchar *srtm_continent_dir ( gint lat, gint lon )
644 {
645   extern const char *_srtm_continent_data[];
646   static GHashTable *srtm_continent = NULL;
647   const gchar *continent;
648   gchar name[16];
649
650   if (!srtm_continent) {
651     const gchar **s;
652
653     srtm_continent = g_hash_table_new(g_str_hash, g_str_equal);
654     s = _srtm_continent_data;
655     while (*s != (gchar *)-1) {
656       continent = *s++;
657       while (*s) {
658         g_hash_table_insert(srtm_continent, (gpointer) *s, (gpointer) continent);
659         s++;
660       }
661       s++;
662     }
663   }
664   g_snprintf(name, sizeof(name), "%c%02d%c%03d",
665                   (lat >= 0) ? 'N' : 'S', ABS(lat),
666                   (lon >= 0) ? 'E' : 'W', ABS(lon));
667
668   return(g_hash_table_lookup(srtm_continent, name));
669 }
670
671 void vik_dem_layer_draw ( VikDEMLayer *vdl, gpointer data )
672 {
673   VikViewport *vp = (VikViewport *) data;
674   GList *dems_iter = vdl->files;
675   VikDEM *dem;
676
677
678   /* search for SRTM3 90m */
679
680   if ( vdl->source == DEM_SOURCE_SRTM )
681     srtm_draw_existence ( vp );
682 #ifdef VIK_CONFIG_DEM24K
683   else if ( vdl->source == DEM_SOURCE_DEM24K )
684     dem24k_draw_existence ( vp );
685 #endif
686
687   while ( dems_iter ) {
688     dem = a_dems_get ( (const char *) (dems_iter->data) );
689     if ( dem )
690       vik_dem_layer_draw_dem ( vdl, vp, dem );
691     dems_iter = dems_iter->next;
692   }
693 }
694
695 void vik_dem_layer_free ( VikDEMLayer *vdl )
696 {
697   gint i;
698   if ( vdl->gc != NULL )
699     g_object_unref ( G_OBJECT(vdl->gc) );
700
701   if ( vdl->color != NULL )
702     g_free ( vdl->color );
703
704   if ( vdl->gcs )
705     for ( i = 0; i < DEM_N_HEIGHT_COLORS; i++ )
706       g_object_unref ( vdl->gcs[i] );
707   g_free ( vdl->gcs );
708
709   if ( vdl->gcsgradient )
710     for ( i = 0; i < DEM_N_GRADIENT_COLORS; i++ )
711       g_object_unref ( vdl->gcsgradient[i] );
712   g_free ( vdl->gcsgradient );
713
714   a_dems_list_free ( vdl->files );
715 }
716
717 static void dem_layer_update_gc ( VikDEMLayer *vdl, VikViewport *vp, const gchar *color )
718 {
719   if ( vdl->color )
720     g_free ( vdl->color );
721
722   vdl->color = g_strdup ( color );
723
724   if ( vdl->gc )
725     g_object_unref ( G_OBJECT(vdl->gc) );
726
727   vdl->gc = vik_viewport_new_gc ( vp, vdl->color, vdl->line_thickness );
728 }
729
730 VikDEMLayer *vik_dem_layer_create ( VikViewport *vp )
731 {
732   VikDEMLayer *vdl = vik_dem_layer_new ();
733   gint i;
734
735   /* TODO: share GCS between layers */
736   for ( i = 0; i < DEM_N_HEIGHT_COLORS; i++ )
737     vdl->gcs[i] = vik_viewport_new_gc ( vp, dem_height_colors[i], vdl->line_thickness );
738
739   for ( i = 0; i < DEM_N_GRADIENT_COLORS; i++ )
740     vdl->gcsgradient[i] = vik_viewport_new_gc ( vp, dem_gradient_colors[i], vdl->line_thickness );
741
742   dem_layer_update_gc ( vdl, vp, "red" );
743   return vdl;
744 }
745 /**************************************************************
746  **** SOURCES & DOWNLOADING
747  **************************************************************/
748 typedef struct {
749   gchar *dest;
750   gdouble lat, lon;
751
752   GMutex *mutex;
753   VikDEMLayer *vdl; /* NULL if not alive */
754
755   guint source;
756 } DEMDownloadParams;
757
758
759 /**************************************************
760  *  SOURCE: SRTM                                  *
761  **************************************************/
762
763 static void srtm_dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
764 {
765   gint intlat, intlon;
766   const gchar *continent_dir;
767
768   intlat = (int)floor(p->lat);
769   intlon = (int)floor(p->lon);
770   continent_dir = srtm_continent_dir(intlat, intlon);
771
772   if (!continent_dir) {
773     g_warning(N_("No SRTM data available for %f, %f"), p->lat, p->lon);
774     return;
775   }
776
777   gchar *src_fn = g_strdup_printf("%s%s/%c%02d%c%03d.hgt.zip",
778                 SRTM_HTTP_URI,
779                 continent_dir,
780                 (intlat >= 0) ? 'N' : 'S',
781                 ABS(intlat),
782                 (intlon >= 0) ? 'E' : 'W',
783                 ABS(intlon) );
784
785   static DownloadOptions options = { 0, NULL, 0, a_check_map_file };
786   a_http_download_get_url ( SRTM_HTTP_SITE, src_fn, p->dest, &options, NULL );
787   g_free ( src_fn );
788 }
789
790 static gchar *srtm_lat_lon_to_dest_fn ( gdouble lat, gdouble lon )
791 {
792   gint intlat, intlon;
793   const gchar *continent_dir;
794
795   intlat = (int)floor(lat);
796   intlon = (int)floor(lon);
797   continent_dir = srtm_continent_dir(intlat, intlon);
798
799   if (!continent_dir)
800     continent_dir = "nowhere";
801
802   return g_strdup_printf("srtm3-%s%s%c%02d%c%03d.hgt.zip",
803                 continent_dir,
804                 G_DIR_SEPARATOR_S,
805                 (intlat >= 0) ? 'N' : 'S',
806                 ABS(intlat),
807                 (intlon >= 0) ? 'E' : 'W',
808                 ABS(intlon) );
809
810 }
811
812 /* TODO: generalize */
813 static void srtm_draw_existence ( VikViewport *vp )
814 {
815   gdouble max_lat, max_lon, min_lat, min_lon;  
816   gchar buf[strlen(MAPS_CACHE_DIR)+strlen(SRTM_CACHE_TEMPLATE)+30];
817   gint i, j;
818
819   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
820
821   for (i = floor(min_lat); i <= floor(max_lat); i++) {
822     for (j = floor(min_lon); j <= floor(max_lon); j++) {
823       const gchar *continent_dir;
824       if ((continent_dir = srtm_continent_dir(i, j)) == NULL)
825         continue;
826       g_snprintf(buf, sizeof(buf), SRTM_CACHE_TEMPLATE,
827                 MAPS_CACHE_DIR,
828                 continent_dir,
829                 G_DIR_SEPARATOR_S,
830                 (i >= 0) ? 'N' : 'S',
831                 ABS(i),
832                 (j >= 0) ? 'E' : 'W',
833                 ABS(j) );
834       if ( g_file_test(buf, G_FILE_TEST_EXISTS ) == TRUE ) {
835         VikCoord ne, sw;
836         gint x1, y1, x2, y2;
837         sw.north_south = i;
838         sw.east_west = j;
839         sw.mode = VIK_COORD_LATLON;
840         ne.north_south = i+1;
841         ne.east_west = j+1;
842         ne.mode = VIK_COORD_LATLON;
843         vik_viewport_coord_to_screen ( vp, &sw, &x1, &y1 );
844         vik_viewport_coord_to_screen ( vp, &ne, &x2, &y2 );
845         if ( x1 < 0 ) x1 = 0;
846         if ( y2 < 0 ) y2 = 0;
847         vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
848                 FALSE, x1, y2, x2-x1, y1-y2 );
849       }
850     }
851   }
852 }
853
854
855 /**************************************************
856  *  SOURCE: USGS 24K                              *
857  **************************************************/
858
859 #ifdef VIK_CONFIG_DEM24K
860
861 static void dem24k_dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
862 {
863   /* TODO: dest dir */
864   gchar *cmdline = g_strdup_printf("%s %.03f %.03f",
865         DEM24K_DOWNLOAD_SCRIPT,
866         floor(p->lat*8)/8,
867         ceil(p->lon*8)/8 );
868   /* FIX: don't use system, use execv or something. check for existence */
869   system(cmdline);
870 }
871
872 static gchar *dem24k_lat_lon_to_dest_fn ( gdouble lat, gdouble lon )
873 {
874   return g_strdup_printf("dem24k/%d/%d/%.03f,%.03f.dem",
875         (gint) lat,
876         (gint) lon,
877         floor(lat*8)/8,
878         ceil(lon*8)/8);
879 }
880
881 /* TODO: generalize */
882 static void dem24k_draw_existence ( VikViewport *vp )
883 {
884   gdouble max_lat, max_lon, min_lat, min_lon;  
885   gchar buf[strlen(MAPS_CACHE_DIR)+40];
886   gdouble i, j;
887
888   vik_viewport_get_min_max_lat_lon ( vp, &min_lat, &max_lat, &min_lon, &max_lon );
889
890   for (i = floor(min_lat*8)/8; i <= floor(max_lat*8)/8; i+=0.125) {
891     /* check lat dir first -- faster */
892     g_snprintf(buf, sizeof(buf), "%sdem24k/%d/",
893         MAPS_CACHE_DIR,
894         (gint) i );
895     if ( g_file_test(buf, G_FILE_TEST_EXISTS) == FALSE )
896       continue;
897     for (j = floor(min_lon*8)/8; j <= floor(max_lon*8)/8; j+=0.125) {
898       /* check lon dir first -- faster */
899       g_snprintf(buf, sizeof(buf), "%sdem24k/%d/%d/",
900         MAPS_CACHE_DIR,
901         (gint) i,
902         (gint) j );
903       if ( g_file_test(buf, G_FILE_TEST_EXISTS) == FALSE )
904         continue;
905       g_snprintf(buf, sizeof(buf), "%sdem24k/%d/%d/%.03f,%.03f.dem",
906                 MAPS_CACHE_DIR,
907                 (gint) i,
908                 (gint) j,
909                 floor(i*8)/8,
910                 floor(j*8)/8 );
911       if ( g_file_test(buf, G_FILE_TEST_EXISTS ) == TRUE ) {
912         VikCoord ne, sw;
913         gint x1, y1, x2, y2;
914         sw.north_south = i;
915         sw.east_west = j-0.125;
916         sw.mode = VIK_COORD_LATLON;
917         ne.north_south = i+0.125;
918         ne.east_west = j;
919         ne.mode = VIK_COORD_LATLON;
920         vik_viewport_coord_to_screen ( vp, &sw, &x1, &y1 );
921         vik_viewport_coord_to_screen ( vp, &ne, &x2, &y2 );
922         if ( x1 < 0 ) x1 = 0;
923         if ( y2 < 0 ) y2 = 0;
924         vik_viewport_draw_rectangle ( vp, GTK_WIDGET(vp)->style->black_gc, 
925                 FALSE, x1, y2, x2-x1, y1-y2 );
926       }
927     }
928   }
929 }
930 #endif
931
932 /**************************************************
933  *   SOURCES -- DOWNLOADING & IMPORTING TOOL      *
934  **************************************************
935  */
936
937 static void weak_ref_cb ( gpointer ptr, GObject * dead_vdl )
938 {
939   DEMDownloadParams *p = ptr;
940   g_mutex_lock ( p->mutex );
941   p->vdl = NULL;
942   g_mutex_unlock ( p->mutex );
943 }
944
945 /* Try to add file full_path.
946  * full_path will be copied.
947  * returns FALSE if file does not exists, TRUE otherwise.
948  */
949 static gboolean dem_layer_add_file ( VikDEMLayer *vdl, const gchar *full_path )
950 {
951   if ( g_file_test(full_path, G_FILE_TEST_EXISTS ) == TRUE ) {
952     /* only load if file size is not 0 (not in progress) */
953     struct stat sb;
954     stat (full_path, &sb);
955     if ( sb.st_size ) {
956       gchar *duped_path = g_strdup(full_path);
957       vdl->files = g_list_prepend ( vdl->files, duped_path );
958       a_dems_load ( duped_path );
959       g_debug("%s: %s", __FUNCTION__, duped_path);
960       vik_layer_emit_update ( VIK_LAYER(vdl) );
961     }
962     return TRUE;
963   } else
964     return FALSE;
965 }
966
967 static void dem_download_thread ( DEMDownloadParams *p, gpointer threaddata )
968 {
969   if ( p->source == DEM_SOURCE_SRTM )
970     srtm_dem_download_thread ( p, threaddata );
971 #ifdef VIK_CONFIG_DEM24K
972   else if ( p->source == DEM_SOURCE_DEM24K )
973     dem24k_dem_download_thread ( p, threaddata );
974 #endif
975
976   gdk_threads_enter();
977   g_mutex_lock ( p->mutex );
978   if ( p->vdl ) {
979     g_object_weak_unref ( G_OBJECT(p->vdl), weak_ref_cb, p );
980
981     if ( dem_layer_add_file ( p->vdl, p->dest ) )
982       vik_layer_emit_update ( VIK_LAYER(p->vdl) );
983   }
984   g_mutex_unlock ( p->mutex );
985   gdk_threads_leave();
986 }
987
988
989 static void free_dem_download_params ( DEMDownloadParams *p )
990 {
991   g_mutex_free ( p->mutex );
992   g_free ( p->dest );
993   g_free ( p );
994 }
995
996 static gpointer dem_layer_download_create ( VikWindow *vw, VikViewport *vvp)
997 {
998   return vvp;
999 }
1000
1001
1002 static gboolean dem_layer_download_release ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp )
1003 {
1004   VikCoord coord;
1005   struct LatLon ll;
1006
1007   gchar *full_path;
1008   gchar *dem_file = NULL;
1009
1010   if ( vdl->source == DEM_SOURCE_NONE )
1011     a_dialog_error_msg ( VIK_GTK_WINDOW_FROM_LAYER(vdl), _("No download source selected. Edit layer properties.") );
1012
1013   vik_viewport_screen_to_coord ( vvp, event->x, event->y, &coord );
1014   vik_coord_to_latlon ( &coord, &ll );
1015
1016   
1017   if ( vdl->source == DEM_SOURCE_SRTM )
1018     dem_file = srtm_lat_lon_to_dest_fn ( ll.lat, ll.lon );
1019 #ifdef VIK_CONFIG_DEM24K
1020   else if ( vdl->source == DEM_SOURCE_DEM24K )
1021     dem_file = dem24k_lat_lon_to_dest_fn ( ll.lat, ll.lon );
1022 #endif
1023
1024   if ( ! dem_file )
1025     return TRUE;
1026
1027   full_path = g_strdup_printf("%s%s", MAPS_CACHE_DIR, dem_file );
1028
1029   g_debug("%s: %s", __FUNCTION__, full_path);
1030
1031   // TODO: check if already in filelist
1032
1033   if ( ! dem_layer_add_file(vdl, full_path) ) {
1034     gchar *tmp = g_strdup_printf ( _("Downloading DEM %s"), dem_file );
1035     DEMDownloadParams *p = g_malloc(sizeof(DEMDownloadParams));
1036     p->dest = g_strdup(full_path);
1037     p->lat = ll.lat;
1038     p->lon = ll.lon;
1039     p->vdl = vdl;
1040     p->mutex = g_mutex_new();
1041     p->source = vdl->source;
1042     g_object_weak_ref(G_OBJECT(p->vdl), weak_ref_cb, p );
1043
1044     a_background_thread ( VIK_GTK_WINDOW_FROM_LAYER(vdl), tmp,
1045                 (vik_thr_func) dem_download_thread, p,
1046                 (vik_thr_free_func) free_dem_download_params, NULL, 1 );
1047   }
1048
1049   g_free ( dem_file );
1050   g_free ( full_path );
1051
1052   return TRUE;
1053 }
1054
1055 static gboolean dem_layer_download_click ( VikDEMLayer *vdl, GdkEventButton *event, VikViewport *vvp )
1056 {
1057 /* choose & keep track of cache dir
1058  * download in background thread
1059  * download over area */
1060   return TRUE;
1061 }
1062
1063