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