]> Pileus Git - aweather/blob - src/plugins/radar.c
Add dual-pole support and improve colormap handling
[aweather] / src / plugins / radar.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #define _XOPEN_SOURCE
19 #include <sys/time.h>
20 #include <config.h>
21 #include <glib/gstdio.h>
22 #include <gtk/gtk.h>
23 #include <gtk/gtkgl.h>
24 #include <gio/gio.h>
25 #include <GL/gl.h>
26 #include <math.h>
27 #include <rsl.h>
28
29 #include <grits.h>
30
31 #include "radar.h"
32 #include "level2.h"
33 #include "../aweather-location.h"
34
35 GtkWidget *_gtk_check_label_new(const gchar *text, gboolean state,
36                 GCallback on_clicked, gpointer user_data)
37 {
38         GtkWidget *hbox  = gtk_hbox_new(FALSE, 0);
39         GtkWidget *check = gtk_check_button_new();
40         GtkWidget *label = gtk_label_new(text);
41         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), state);
42         g_signal_connect_swapped(check , "clicked",
43                         G_CALLBACK(on_clicked), user_data);
44         gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
45         gtk_box_pack_end(GTK_BOX(hbox), check , FALSE, FALSE, 0);
46         gtk_widget_show_all(hbox);
47         return hbox;
48 }
49
50 void _gtk_bin_set_child(GtkBin *bin, GtkWidget *new)
51 {
52         GtkWidget *old = gtk_bin_get_child(bin);
53         if (old)
54                 gtk_widget_destroy(old);
55         gtk_container_add(GTK_CONTAINER(bin), new);
56         gtk_widget_show_all(new);
57 }
58
59 static gchar *_find_nearest(time_t time, GList *files,
60                 gsize offset, gchar *format)
61 {
62         g_debug("RadarSite: find_nearest ...");
63         time_t  nearest_time = 0;
64         char   *nearest_file = NULL;
65
66         struct tm tm = {};
67         for (GList *cur = files; cur; cur = cur->next) {
68                 gchar *file = cur->data;
69                 strptime(file+offset, format, &tm);
70                 if (ABS(time - mktime(&tm)) <
71                     ABS(time - nearest_time)) {
72                         nearest_file = file;
73                         nearest_time = mktime(&tm);
74                 }
75         }
76
77         g_debug("RadarSite: find_nearest = %s", nearest_file);
78         if (nearest_file)
79                 return g_strdup(nearest_file);
80         else
81                 return NULL;
82 }
83
84
85 /**************
86  * RadarSites *
87  **************/
88 typedef enum {
89         STATUS_UNLOADED,
90         STATUS_LOADING,
91         STATUS_LOADED,
92 } RadarSiteStatus;
93 struct _RadarSite {
94         /* Information */
95         city_t         *city;
96         GritsMarker    *marker;      // Map marker for grits
97         gpointer       *marker_ref;  // Reference to maker
98
99         /* Stuff from the parents */
100         GritsViewer    *viewer;
101         GritsHttp      *http;
102         GritsPrefs     *prefs;
103         GtkWidget      *pconfig;
104
105         /* When loaded */
106         gboolean        hidden;
107         RadarSiteStatus status;      // Loading status for the site
108         GtkWidget      *config;
109         AWeatherLevel2 *level2;      // The Level2 structure for the current volume
110         gpointer        level2_ref;  // GritsViewer reference to the added radar
111
112         /* Internal data */
113         time_t          time;        // Current timestamp of the level2
114         gchar          *message;     // Error message set while updating
115         guint           time_id;     // "time-changed"     callback ID
116         guint           refresh_id;  // "refresh"          callback ID
117         guint           location_id; // "locaiton-changed" callback ID
118 };
119
120 /* format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323 */
121 void _site_update_loading(gchar *file, goffset cur,
122                 goffset total, gpointer _site)
123 {
124         RadarSite *site = _site;
125         GtkWidget *progress_bar = gtk_bin_get_child(GTK_BIN(site->config));
126         double percent = (double)cur/total;
127         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar), MIN(percent, 1.0));
128         gchar *msg = g_strdup_printf("Loading... %5.1f%% (%.2f/%.2f MB)",
129                         percent*100, (double)cur/1000000, (double)total/1000000);
130         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar), msg);
131         g_free(msg);
132 }
133 gboolean _site_update_end(gpointer _site)
134 {
135         RadarSite *site = _site;
136         if (site->message) {
137                 g_warning("RadarSite: update_end - %s", site->message);
138                 _gtk_bin_set_child(GTK_BIN(site->config),
139                                 gtk_label_new(site->message));
140         } else {
141                 _gtk_bin_set_child(GTK_BIN(site->config),
142                                 aweather_level2_get_config(site->level2));
143         }
144         site->status = STATUS_LOADED;
145         return FALSE;
146 }
147 gpointer _site_update_thread(gpointer _site)
148 {
149         RadarSite *site = _site;
150         g_debug("RadarSite: update_thread - %s", site->city->code);
151         site->message = NULL;
152
153         gboolean offline = grits_viewer_get_offline(site->viewer);
154         gchar *nexrad_url = grits_prefs_get_string(site->prefs,
155                         "aweather/nexrad_url", NULL);
156
157         /* Find nearest volume (temporally) */
158         g_debug("RadarSite: update_thread - find nearest - %s", site->city->code);
159         gchar *dir_list = g_strconcat(nexrad_url, "/", site->city->code,
160                         "/", "dir.list", NULL);
161         GList *files = grits_http_available(site->http,
162                         "^K\\w{3}_\\d{8}_\\d{4}$", site->city->code,
163                         "\\d+ (.*)", (offline ? NULL : dir_list));
164         g_free(dir_list);
165         gchar *nearest = _find_nearest(site->time, files, 5, "%Y%m%d_%H%M");
166         g_list_foreach(files, (GFunc)g_free, NULL);
167         g_list_free(files);
168         if (!nearest) {
169                 site->message = "No suitable files found";
170                 goto out;
171         }
172
173         /* Fetch new volume */
174         g_debug("RadarSite: update_thread - fetch");
175         gchar *local = g_strconcat(site->city->code, "/", nearest, NULL);
176         gchar *uri   = g_strconcat(nexrad_url, "/", local,   NULL);
177         gchar *file  = grits_http_fetch(site->http, uri, local,
178                         offline ? GRITS_LOCAL : GRITS_UPDATE,
179                         _site_update_loading, site);
180         g_free(nexrad_url);
181         g_free(nearest);
182         g_free(local);
183         g_free(uri);
184         if (!file) {
185                 site->message = "Fetch failed";
186                 goto out;
187         }
188
189         /* Load and add new volume */
190         g_debug("RadarSite: update_thread - load - %s", site->city->code);
191         site->level2 = aweather_level2_new_from_file(
192                         file, site->city->code, colormaps);
193         g_free(file);
194         if (!site->level2) {
195                 site->message = "Load failed";
196                 goto out;
197         }
198         GRITS_OBJECT(site->level2)->hidden = site->hidden;
199         site->level2_ref = grits_viewer_add(site->viewer,
200                         GRITS_OBJECT(site->level2), GRITS_LEVEL_WORLD, TRUE);
201
202 out:
203         g_idle_add(_site_update_end, site);
204         return NULL;
205 }
206 void _site_update(RadarSite *site)
207 {
208         if (site->status == STATUS_LOADING)
209                 return;
210         site->status = STATUS_LOADING;
211
212         site->time = grits_viewer_get_time(site->viewer);
213         g_debug("RadarSite: update %s - %d",
214                         site->city->code, (gint)site->time);
215
216         /* Add a progress bar */
217         GtkWidget *progress = gtk_progress_bar_new();
218         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), "Loading...");
219         _gtk_bin_set_child(GTK_BIN(site->config), progress);
220
221         /* Remove old volume */
222         g_debug("RadarSite: update - remove - %s", site->city->code);
223         if (site->level2_ref) {
224                 site->level2     = NULL;
225                 grits_viewer_remove(site->viewer, site->level2_ref);
226                 site->level2_ref = NULL;
227         }
228
229         /* Fork loading right away so updating the
230          * list of times doesn't take too long */
231         g_thread_create(_site_update_thread, site, FALSE, NULL);
232 }
233
234 /* RadarSite methods */
235 void radar_site_unload(RadarSite *site)
236 {
237         if (site->status != STATUS_LOADED)
238                 return; // Abort if it's still loading
239
240         g_debug("RadarSite: unload %s", site->city->code);
241
242         if (site->time_id)
243                 g_signal_handler_disconnect(site->viewer, site->time_id);
244         if (site->refresh_id)
245                 g_signal_handler_disconnect(site->viewer, site->refresh_id);
246
247         /* Remove tab */
248         if (site->config)
249                 gtk_widget_destroy(site->config);
250
251         /* Remove radar */
252         if (site->level2_ref) {
253                 site->level2     = NULL;
254                 grits_viewer_remove(site->viewer, site->level2_ref);
255                 site->level2_ref = NULL;
256         }
257
258         site->status = STATUS_UNLOADED;
259 }
260
261 void radar_site_toggle(RadarSite *site)
262 {
263         site->hidden = !site->hidden;
264         if (site->level2) {
265                 GRITS_OBJECT(site->level2)->hidden = site->hidden;
266                 gtk_widget_queue_draw(GTK_WIDGET(site->viewer));
267         }
268 }
269
270 void radar_site_load(RadarSite *site)
271 {
272         g_debug("RadarSite: load %s", site->city->code);
273
274         /* Add tab page */
275         site->config = gtk_alignment_new(0, 0, 1, 1);
276         gtk_notebook_append_page(GTK_NOTEBOOK(site->pconfig), site->config,
277                         _gtk_check_label_new(site->city->name, !site->hidden,
278                                 G_CALLBACK(radar_site_toggle), site));
279         gtk_widget_show_all(site->config);
280
281         /* Set up radar loading */
282         site->time_id = g_signal_connect_swapped(site->viewer, "time-changed",
283                         G_CALLBACK(_site_update), site);
284         site->refresh_id = g_signal_connect_swapped(site->viewer, "refresh",
285                         G_CALLBACK(_site_update), site);
286         _site_update(site);
287 }
288
289 void _site_on_location_changed(GritsViewer *viewer,
290                 gdouble lat, gdouble lon, gdouble elev,
291                 gpointer _site)
292 {
293         static gdouble min_dist = EARTH_R / 30;
294         RadarSite *site = _site;
295
296         /* Calculate distance, could cache xyz values */
297         gdouble eye_xyz[3], site_xyz[3];
298         lle2xyz(lat, lon, elev, &eye_xyz[0], &eye_xyz[1], &eye_xyz[2]);
299         lle2xyz(site->city->pos.lat, site->city->pos.lon, site->city->pos.elev,
300                         &site_xyz[0], &site_xyz[1], &site_xyz[2]);
301         gdouble dist = distd(site_xyz, eye_xyz);
302
303         /* Load or unload the site if necessasairy */
304         if (dist <= min_dist && dist < elev*1.25 && site->status == STATUS_UNLOADED)
305                 radar_site_load(site);
306         else if (dist > 2*min_dist &&  site->status != STATUS_UNLOADED)
307                 radar_site_unload(site);
308 }
309
310 gboolean _site_add_marker(gpointer _site)
311 {
312         RadarSite *site = _site;
313         site->marker = grits_marker_new(site->city->name);
314         GRITS_OBJECT(site->marker)->center = site->city->pos;
315         GRITS_OBJECT(site->marker)->lod    = EARTH_R*site->city->lod;
316         site->marker_ref = grits_viewer_add(site->viewer,
317                         GRITS_OBJECT(site->marker), GRITS_LEVEL_OVERLAY, FALSE);
318         return FALSE;
319 }
320 RadarSite *radar_site_new(city_t *city, GtkWidget *pconfig,
321                 GritsViewer *viewer, GritsPrefs *prefs, GritsHttp *http)
322 {
323         RadarSite *site = g_new0(RadarSite, 1);
324         site->viewer  = g_object_ref(viewer);
325         site->prefs   = g_object_ref(prefs);
326         //site->http    = http;
327         site->http    = grits_http_new(G_DIR_SEPARATOR_S
328                         "nexrad" G_DIR_SEPARATOR_S
329                         "level2" G_DIR_SEPARATOR_S);
330         site->city    = city;
331         site->pconfig = pconfig;
332
333         /* Add marker */
334         g_idle_add_full(G_PRIORITY_LOW, _site_add_marker, site, NULL);
335
336         /* Connect signals */
337         site->location_id  = g_signal_connect(viewer, "location-changed",
338                         G_CALLBACK(_site_on_location_changed), site);
339         return site;
340 }
341
342 void radar_site_free(RadarSite *site)
343 {
344         radar_site_unload(site);
345         grits_viewer_remove(site->viewer, site->marker_ref);
346         if (site->location_id)
347                 g_signal_handler_disconnect(site->viewer, site->location_id);
348         grits_http_free(site->http);
349         g_object_unref(site->viewer);
350         g_object_unref(site->prefs);
351         g_free(site);
352 }
353
354
355 /**************
356  * RadarConus *
357  **************/
358 #define CONUS_NORTH       50.406626367301044
359 #define CONUS_WEST       -127.620375523875420
360 #define CONUS_WIDTH       3400.0
361 #define CONUS_HEIGHT      1600.0
362 #define CONUS_DEG_PER_PX  0.017971305190311
363
364 struct _RadarConus {
365         GritsViewer *viewer;
366         GritsHttp   *http;
367         GtkWidget   *config;
368         time_t       time;
369         const gchar *message;
370         GStaticMutex loading;
371
372         gchar       *path;
373         GritsTile   *tile[2];
374         gpointer    *tile_ref[2];
375
376         guint        time_id;     // "time-changed"     callback ID
377         guint        refresh_id;  // "refresh"          callback ID
378 };
379
380 void _conus_update_loading(gchar *file, goffset cur,
381                 goffset total, gpointer _conus)
382 {
383         RadarConus *conus = _conus;
384         GtkWidget *progress_bar = gtk_bin_get_child(GTK_BIN(conus->config));
385         double percent = (double)cur/total;
386         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar), MIN(percent, 1.0));
387         gchar *msg = g_strdup_printf("Loading... %5.1f%% (%.2f/%.2f MB)",
388                         percent*100, (double)cur/1000000, (double)total/1000000);
389         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar), msg);
390         g_free(msg);
391 }
392
393 /* Copy images to graphics memory */
394 static void _conus_update_end_copy(GritsTile *tile, guchar *pixels)
395 {
396         if (!tile->data) {
397                 tile->data = g_new0(guint, 1);
398                 glGenTextures(1, tile->data);
399         }
400
401         guint *tex = tile->data;
402         glBindTexture(GL_TEXTURE_2D, *tex);
403
404         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
405         glPixelStorei(GL_PACK_ALIGNMENT, 1);
406         glTexImage2D(GL_TEXTURE_2D, 0, 4, 2048, 2048, 0,
407                         GL_RGBA, GL_UNSIGNED_BYTE, NULL);
408         glTexSubImage2D(GL_TEXTURE_2D, 0, 1,1, CONUS_WIDTH/2,CONUS_HEIGHT,
409                         GL_RGBA, GL_UNSIGNED_BYTE, pixels);
410         tile->coords.n = 1.0/(CONUS_WIDTH/2);
411         tile->coords.w = 1.0/ CONUS_HEIGHT;
412         tile->coords.s = tile->coords.n +  CONUS_HEIGHT   / 2048.0;
413         tile->coords.e = tile->coords.w + (CONUS_WIDTH/2) / 2048.0;
414         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
415         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
416         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
417         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
418         glFlush();
419 }
420
421 /* Split the pixbuf into east and west halves (with 2K sides)
422  * Also map the pixbuf's alpha values */
423 static void _conus_update_end_split(guchar *pixels, guchar *west, guchar *east,
424                 gint width, gint height, gint pxsize)
425 {
426         g_debug("Conus: update_end_split");
427         guchar *out[] = {west,east};
428         const guchar alphamap[][4] = {
429                 {0x04, 0xe9, 0xe7, 0x30},
430                 {0x01, 0x9f, 0xf4, 0x60},
431                 {0x03, 0x00, 0xf4, 0x90},
432         };
433         for (int y = 0; y < height; y++)
434         for (int x = 0; x < width;  x++) {
435                 gint subx = x % (width/2);
436                 gint idx  = x / (width/2);
437                 guchar *src = &pixels[(y*width+x)*pxsize];
438                 guchar *dst = &out[idx][(y*(width/2)+subx)*4];
439                 if (src[0] > 0xe0 &&
440                     src[1] > 0xe0 &&
441                     src[2] > 0xe0) {
442                         dst[3] = 0x00;
443                 } else {
444                         dst[0] = src[0];
445                         dst[1] = src[1];
446                         dst[2] = src[2];
447                         dst[3] = 0xff;
448                         for (int j = 0; j < G_N_ELEMENTS(alphamap); j++)
449                                 if (src[0] == alphamap[j][0] &&
450                                     src[1] == alphamap[j][1] &&
451                                     src[2] == alphamap[j][2])
452                                         dst[3] = alphamap[j][3];
453                 }
454         }
455 }
456
457 gboolean _conus_update_end(gpointer _conus)
458 {
459         RadarConus *conus = _conus;
460         g_debug("Conus: update_end");
461
462         /* Check error status */
463         if (conus->message) {
464                 g_warning("Conus: update_end - %s", conus->message);
465                 _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new(conus->message));
466                 goto out;
467         }
468
469         /* Load and pixbuf */
470         GError *error = NULL;
471         GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(conus->path, &error);
472         if (!pixbuf || error) {
473                 g_warning("Conus: update_end - error loading pixbuf");
474                 _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new("Error loading pixbuf"));
475                 g_remove(conus->path);
476                 goto out;
477         }
478
479         /* Split pixels into east/west parts */
480         guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);
481         gint    width  = gdk_pixbuf_get_width(pixbuf);
482         gint    height = gdk_pixbuf_get_height(pixbuf);
483         gint    pxsize = gdk_pixbuf_get_has_alpha(pixbuf) ? 4 : 3;
484         guchar *pixels_west = g_malloc(4*(width/2)*height);
485         guchar *pixels_east = g_malloc(4*(width/2)*height);
486         _conus_update_end_split(pixels, pixels_west, pixels_east,
487                         width, height, pxsize);
488         g_object_unref(pixbuf);
489
490         /* Copy pixels to graphics memory */
491         _conus_update_end_copy(conus->tile[0], pixels_west);
492         _conus_update_end_copy(conus->tile[1], pixels_east);
493         g_free(pixels_west);
494         g_free(pixels_east);
495
496         /* Update GUI */
497         gchar *label = g_path_get_basename(conus->path);
498         _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new(label));
499         gtk_widget_queue_draw(GTK_WIDGET(conus->viewer));
500         g_free(label);
501
502 out:
503         g_free(conus->path);
504         g_static_mutex_unlock(&conus->loading);
505         return FALSE;
506 }
507
508 gpointer _conus_update_thread(gpointer _conus)
509 {
510         RadarConus *conus = _conus;
511         conus->message = NULL;
512
513         /* Find nearest */
514         g_debug("Conus: update_thread - nearest");
515         gboolean offline = grits_viewer_get_offline(conus->viewer);
516         gchar *conus_url = "http://radar.weather.gov/Conus/RadarImg/";
517         GList *files = grits_http_available(conus->http,
518                         "^Conus_[^\"]*_N0Ronly.gif$", "",
519                         NULL, (offline ? NULL : conus_url));
520         gchar *nearest = _find_nearest(conus->time, files, 6, "%Y%m%d_%H%M");
521         g_list_foreach(files, (GFunc)g_free, NULL);
522         g_list_free(files);
523         if (!nearest) {
524                 conus->message = "No suitable files";
525                 goto out;
526         }
527
528         /* Fetch the image */
529         g_debug("Conus: update_thread - fetch");
530         gchar *uri  = g_strconcat(conus_url, nearest, NULL);
531         conus->path = grits_http_fetch(conus->http, uri, nearest, GRITS_ONCE,
532                         _conus_update_loading, conus);
533         g_free(nearest);
534         g_free(uri);
535         if (!conus->path) {
536                 conus->message = "Fetch failed";
537                 goto out;
538         }
539
540 out:
541         g_debug("Conus: update_thread - done");
542         g_idle_add(_conus_update_end, conus);
543         return NULL;
544 }
545
546 void _conus_update(RadarConus *conus)
547 {
548         if (!g_static_mutex_trylock(&conus->loading))
549                 return;
550         conus->time = grits_viewer_get_time(conus->viewer);
551         g_debug("Conus: update - %d",
552                         (gint)conus->time);
553
554         /* Add a progress bar */
555         GtkWidget *progress = gtk_progress_bar_new();
556         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), "Loading...");
557         _gtk_bin_set_child(GTK_BIN(conus->config), progress);
558
559         g_thread_create(_conus_update_thread, conus, FALSE, NULL);
560 }
561
562 void radar_conus_toggle(RadarConus *conus)
563 {
564         GRITS_OBJECT(conus->tile[0])->hidden =
565                 !GRITS_OBJECT(conus->tile[0])->hidden;
566         GRITS_OBJECT(conus->tile[1])->hidden =
567                 !GRITS_OBJECT(conus->tile[1])->hidden;
568         gtk_widget_queue_draw(GTK_WIDGET(conus->viewer));
569 }
570
571 RadarConus *radar_conus_new(GtkWidget *pconfig,
572                 GritsViewer *viewer, GritsHttp *http)
573 {
574         RadarConus *conus = g_new0(RadarConus, 1);
575         conus->viewer  = g_object_ref(viewer);
576         conus->http    = http;
577         conus->config  = gtk_alignment_new(0, 0, 1, 1);
578         g_static_mutex_init(&conus->loading);
579
580         gdouble south =  CONUS_NORTH - CONUS_DEG_PER_PX*CONUS_HEIGHT;
581         gdouble east  =  CONUS_WEST  + CONUS_DEG_PER_PX*CONUS_WIDTH;
582         gdouble mid   =  CONUS_WEST  + CONUS_DEG_PER_PX*CONUS_WIDTH/2;
583         conus->tile[0] = grits_tile_new(NULL, CONUS_NORTH, south, mid, CONUS_WEST);
584         conus->tile[1] = grits_tile_new(NULL, CONUS_NORTH, south, east, mid);
585         conus->tile[0]->zindex = 2;
586         conus->tile[1]->zindex = 1;
587         conus->tile_ref[0] = grits_viewer_add(viewer,
588                         GRITS_OBJECT(conus->tile[0]), GRITS_LEVEL_WORLD, TRUE);
589         conus->tile_ref[1] = grits_viewer_add(viewer,
590                         GRITS_OBJECT(conus->tile[1]), GRITS_LEVEL_WORLD, TRUE);
591
592         conus->time_id = g_signal_connect_swapped(viewer, "time-changed",
593                         G_CALLBACK(_conus_update), conus);
594         conus->refresh_id = g_signal_connect_swapped(viewer, "refresh",
595                         G_CALLBACK(_conus_update), conus);
596
597         gtk_notebook_append_page(GTK_NOTEBOOK(pconfig), conus->config,
598                         _gtk_check_label_new("Conus", TRUE,
599                                 G_CALLBACK(radar_conus_toggle), conus));
600         _conus_update(conus);
601         return conus;
602 }
603
604 void radar_conus_free(RadarConus *conus)
605 {
606         g_signal_handler_disconnect(conus->viewer, conus->time_id);
607         g_signal_handler_disconnect(conus->viewer, conus->refresh_id);
608
609         for (int i = 0; i < 2; i++) {
610                 GritsTile *tile = conus->tile[i];
611                 gpointer   ref  = conus->tile_ref[i];
612                 if (tile->data) {
613                         glDeleteTextures(1, tile->data);
614                         g_free(tile->data);
615                 }
616                 grits_viewer_remove(conus->viewer, ref);
617         }
618
619         g_object_unref(conus->viewer);
620         g_free(conus);
621 }
622
623
624 /********************
625  * GritsPluginRadar *
626  ********************/
627 static void _draw_hud(GritsCallback *callback, GritsOpenGL *opengl, gpointer _self)
628 {
629         g_debug("GritsPluginRadar: _draw_hud");
630         /* Setup OpenGL */
631         glMatrixMode(GL_MODELVIEW ); glLoadIdentity();
632         glMatrixMode(GL_PROJECTION); glLoadIdentity();
633         glDisable(GL_TEXTURE_2D);
634         glDisable(GL_ALPHA_TEST);
635         glDisable(GL_CULL_FACE);
636         glDisable(GL_LIGHTING);
637         glEnable(GL_COLOR_MATERIAL);
638
639         GHashTableIter iter;
640         gpointer name, _site;
641         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(_self);
642         g_hash_table_iter_init(&iter, self->sites);
643         while (g_hash_table_iter_next(&iter, &name, &_site)) {
644                 /* Pick correct colormaps */
645                 RadarSite *site = _site;
646                 if (site->hidden || !site->level2)
647                         continue;
648                 AWeatherColormap *colormap = site->level2->sweep_colors;
649
650                 /* Print the color table */
651                 glBegin(GL_QUADS);
652                 int len = colormap->len;
653                 for (int i = 0; i < len; i++) {
654                         glColor4ubv(colormap->data[i]);
655                         glVertex3f(-1.0, (float)((i  ) - len/2)/(len/2), 0.0); // bot left
656                         glVertex3f(-1.0, (float)((i+1) - len/2)/(len/2), 0.0); // top left
657                         glVertex3f(-0.9, (float)((i+1) - len/2)/(len/2), 0.0); // top right
658                         glVertex3f(-0.9, (float)((i  ) - len/2)/(len/2), 0.0); // bot right
659                 }
660                 glEnd();
661         }
662 }
663
664 static void _load_colormap(gchar *filename, AWeatherColormap *cm)
665 {
666         g_debug("GritsPluginRadar: _load_colormap - %s", filename);
667         FILE *file = g_fopen(filename, "r");
668         if (!file)
669                 g_error("GritsPluginRadar: open failed");
670         guint8 color[4];
671         GArray *array = g_array_sized_new(FALSE, TRUE, sizeof(color), 256);
672         fgets(cm->name, sizeof(cm->name), file);
673         fscanf(file, "%f\n", &cm->scale);
674         fscanf(file, "%f\n", &cm->shift);
675         while (fscanf(file, "%hhd %hhd %hhd %hhd\n",
676                         &color[0], &color[1], &color[2], &color[3]) == 4)
677                 g_array_append_val(array, color);
678         cm->len  = (gint )array->len;
679         cm->data = (void*)array->data;
680         g_array_free(array, FALSE);
681 }
682
683 /* Methods */
684 GritsPluginRadar *grits_plugin_radar_new(GritsViewer *viewer, GritsPrefs *prefs)
685 {
686         /* TODO: move to constructor if possible */
687         g_debug("GritsPluginRadar: new");
688         GritsPluginRadar *self = g_object_new(GRITS_TYPE_PLUGIN_RADAR, NULL);
689         self->viewer = viewer;
690         self->prefs  = prefs;
691
692         /* Load HUD */
693         GritsCallback *hud_cb = grits_callback_new(_draw_hud, self);
694         self->hud_ref = grits_viewer_add(viewer, GRITS_OBJECT(hud_cb), GRITS_LEVEL_HUD, FALSE);
695
696         /* Load Conus */
697         self->conus = radar_conus_new(self->config, self->viewer, self->conus_http);
698
699         /* Load radar sites */
700         for (city_t *city = cities; city->type; city++) {
701                 if (city->type != LOCATION_CITY)
702                         continue;
703                 RadarSite *site = radar_site_new(city, self->config,
704                                 self->viewer, self->prefs, self->sites_http);
705                 g_hash_table_insert(self->sites, city->code, site);
706         }
707
708         return self;
709 }
710
711 static GtkWidget *grits_plugin_radar_get_config(GritsPlugin *_self)
712 {
713         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(_self);
714         return self->config;
715 }
716
717 /* GObject code */
718 static void grits_plugin_radar_plugin_init(GritsPluginInterface *iface);
719 G_DEFINE_TYPE_WITH_CODE(GritsPluginRadar, grits_plugin_radar, G_TYPE_OBJECT,
720                 G_IMPLEMENT_INTERFACE(GRITS_TYPE_PLUGIN,
721                         grits_plugin_radar_plugin_init));
722 static void grits_plugin_radar_plugin_init(GritsPluginInterface *iface)
723 {
724         g_debug("GritsPluginRadar: plugin_init");
725         /* Add methods to the interface */
726         iface->get_config = grits_plugin_radar_get_config;
727 }
728 static void grits_plugin_radar_init(GritsPluginRadar *self)
729 {
730         g_debug("GritsPluginRadar: class_init");
731         /* Set defaults */
732         self->sites_http = grits_http_new(G_DIR_SEPARATOR_S
733                         "nexrad" G_DIR_SEPARATOR_S
734                         "level2" G_DIR_SEPARATOR_S);
735         self->conus_http = grits_http_new(G_DIR_SEPARATOR_S
736                         "nexrad" G_DIR_SEPARATOR_S
737                         "conus"  G_DIR_SEPARATOR_S);
738         self->sites      = g_hash_table_new_full(g_str_hash, g_str_equal,
739                                 NULL, (GDestroyNotify)radar_site_free);
740         self->config     = gtk_notebook_new();
741
742         /* Load colormaps */
743         for (int i = 0; colormaps[i].file; i++) {
744                 gchar *file = g_build_filename(PKGDATADIR,
745                                 "colors", colormaps[i].file, NULL);
746                 _load_colormap(file, &colormaps[i]);
747                 g_free(file);
748         }
749
750         /* Need to position on the top because of Win32 bug */
751         gtk_notebook_set_tab_pos(GTK_NOTEBOOK(self->config), GTK_POS_BOTTOM);
752 }
753 static void grits_plugin_radar_dispose(GObject *gobject)
754 {
755         g_debug("GritsPluginRadar: dispose");
756         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(gobject);
757         grits_viewer_remove(self->viewer, self->hud_ref);
758         radar_conus_free(self->conus);
759         /* Drop references */
760         G_OBJECT_CLASS(grits_plugin_radar_parent_class)->dispose(gobject);
761 }
762 static void grits_plugin_radar_finalize(GObject *gobject)
763 {
764         g_debug("GritsPluginRadar: finalize");
765         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(gobject);
766         /* Free data */
767         grits_http_free(self->conus_http);
768         grits_http_free(self->sites_http);
769         g_hash_table_destroy(self->sites);
770         gtk_widget_destroy(self->config);
771         G_OBJECT_CLASS(grits_plugin_radar_parent_class)->finalize(gobject);
772
773 }
774 static void grits_plugin_radar_class_init(GritsPluginRadarClass *klass)
775 {
776         g_debug("GritsPluginRadar: class_init");
777         GObjectClass *gobject_class = (GObjectClass*)klass;
778         gobject_class->dispose  = grits_plugin_radar_dispose;
779         gobject_class->finalize = grits_plugin_radar_finalize;
780 }