]> Pileus Git - grits/blob - src/plugin-radar.c
46e73d4a0ee73b4e1f9ed35235a749be2a85f845
[grits] / src / plugin-radar.c
1 /*
2  * Copyright (C) 2009 Andy Spencer <spenceal@rose-hulman.edu>
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 #include <config.h>
19 #include <gtk/gtk.h>
20 #include <gtk/gtkgl.h>
21 #include <GL/gl.h>
22 #include <math.h>
23 #include <rsl.h>
24
25 #include "aweather-gui.h"
26 #include "plugin-radar.h"
27 #include "data.h"
28
29 /****************
30  * GObject code *
31  ****************/
32 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface);
33 static void aweather_radar_expose(AWeatherPlugin *_radar);
34 G_DEFINE_TYPE_WITH_CODE(AWeatherRadar, aweather_radar, G_TYPE_OBJECT,
35                 G_IMPLEMENT_INTERFACE(AWEATHER_TYPE_PLUGIN,
36                         aweather_radar_plugin_init));
37 static void aweather_radar_class_init(AWeatherRadarClass *klass)
38 {
39         GObjectClass *object_class = (GObjectClass*)klass;
40 }
41 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface)
42 {
43         /* Add methods to the interface */
44         iface->expose = aweather_radar_expose;
45 }
46 static void aweather_radar_init(AWeatherRadar *radar)
47 {
48         /* Set defaults */
49         radar->gui = NULL;
50 }
51
52 /* TODO: User parameters or user data or something */
53 static AWeatherRadar *self = NULL;
54
55 /**************************
56  * Data loading functions *
57  **************************/
58 /* Convert a sweep to an 2d array of data points */
59 static void bscan_sweep(Sweep *sweep, guint8 **data, int *width, int *height)
60 {
61         /* Calculate max number of bins */
62         int i, max_bins = 0;
63         for (i = 0; i < sweep->h.nrays; i++)
64                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
65
66         /* Allocate buffer using max number of bins for each ray */
67         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
68
69         /* Fill the data */
70         int ri, bi;
71         for (ri = 0; ri < sweep->h.nrays; ri++) {
72                 Ray *ray  = sweep->ray[ri];
73                 for (bi = 0; bi < ray->h.nbins; bi++) {
74                         /* copy RGBA into buffer */
75                         //guint val   = dz_f(ray->range[bi]);
76                         guint8 val   = (guint8)ray->h.f(ray->range[bi]);
77                         guint  buf_i = (ri*max_bins+bi)*4;
78                         buf[buf_i+0] = self->cur_colormap->data[val][0];
79                         buf[buf_i+1] = self->cur_colormap->data[val][1];
80                         buf[buf_i+2] = self->cur_colormap->data[val][2];
81                         buf[buf_i+3] = self->cur_colormap->data[val][3];
82                         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
83                             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO) {
84                                 buf[buf_i+3] = 0x00; // transparent
85                         }
86                 }
87         }
88
89         /* set output */
90         *width  = max_bins;
91         *height = sweep->h.nrays;
92         *data   = buf;
93 }
94
95 static void load_color_table(char *table)
96 {
97         for (int i = 0; colormaps[i].name; i++)
98                 if (g_str_equal(colormaps[i].name, table))
99                         self->cur_colormap = &colormaps[i];
100 }
101
102 /* Load a sweep as the active texture */
103 static void load_sweep(Sweep *sweep)
104 {
105         aweather_gui_gl_begin(self->gui);
106         self->cur_sweep = sweep;
107         int height, width;
108         guint8 *data;
109         bscan_sweep(sweep, &data, &width, &height);
110         glDeleteTextures(1, &self->cur_sweep_tex);
111         glGenTextures(1, &self->cur_sweep_tex);
112         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
113         glPixelStorei(GL_PACK_ALIGNMENT, 1);
114         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
115         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
116         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
117         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
118                         GL_RGBA, GL_UNSIGNED_BYTE, data);
119         g_free(data);
120         aweather_gui_gl_redraw(self->gui);
121         aweather_gui_gl_end(self->gui);
122 }
123
124 /* Add selectors to the config area for the sweeps */
125 static void load_radar_gui(Radar *radar)
126 {
127         /* Clear existing items */
128         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
129         if (child)
130                 gtk_widget_destroy(child);
131
132         gdouble elev;
133         guint rows = 1, cols = 1, cur_cols;
134         gchar row_label_str[64], col_label_str[64], button_str[64];
135         GtkWidget *row_label, *col_label, *button = NULL, *elev_box;
136         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
137
138         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
139                 Volume *vol = radar->v[vi];
140                 if (vol == NULL) continue;
141                 rows++; cols = 1; elev = 0;
142
143                 /* Row label */
144                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
145                 row_label = gtk_label_new(row_label_str);
146                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
147                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
148                 gtk_table_attach(GTK_TABLE(table), row_label,
149                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
150
151                 for (guint si = 0; si < vol->h.nsweeps; si++) {
152                         Sweep *sweep = vol->sweep[si];
153                         if (sweep == NULL || sweep->h.elev == 0) continue;
154                         if (sweep->h.elev != elev) {
155                                 g_message("adding elev");
156                                 cols++;
157                                 elev = sweep->h.elev;
158
159                                 /* Column label */
160                                 g_object_get(table, "n-columns", &cur_cols, NULL);
161                                 if (cols >  cur_cols) {
162                                         g_snprintf(col_label_str, 64, "<b>%.2f°</b>", elev);
163                                         col_label = gtk_label_new(col_label_str);
164                                         gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
165                                         gtk_widget_set_size_request(col_label, 40, -1);
166                                         gtk_table_attach(GTK_TABLE(table), col_label,
167                                                         cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
168                                 }
169
170                                 elev_box = gtk_hbox_new(TRUE, 0);
171                                 gtk_table_attach(GTK_TABLE(table), elev_box,
172                                                 cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
173                         }
174
175
176                         /* Button */
177                         g_snprintf(button_str, 64, "%3.2f", elev);
178                         button = gtk_radio_button_new_with_label_from_widget(
179                                         GTK_RADIO_BUTTON(button), button_str);
180                         gtk_widget_set_size_request(button, -1, 26);
181                         //button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
182                         //gtk_widget_set_size_request(button, -1, 22);
183                         g_object_set(button, "draw-indicator", FALSE, NULL);
184                         gtk_box_pack_end(GTK_BOX(elev_box), button, TRUE, TRUE, 0);
185                         g_signal_connect_swapped(button, "clicked",
186                                         G_CALLBACK(load_color_table), vol->h.type_str);
187                         g_signal_connect_swapped(button, "clicked",
188                                         G_CALLBACK(load_sweep), sweep);
189                 }
190         }
191         gtk_container_add(GTK_CONTAINER(self->config_body), table);
192         gtk_widget_show_all(table);
193 }
194
195 /* Load a radar from a file */
196 static void load_radar_rsl(GPid pid, gint status, gpointer _path)
197 {
198         gchar *path = _path;
199         if (status != 0) {
200                 g_warning("wsr88ddec exited with status %d", status);
201                 return;
202         }
203         char *dir  = g_path_get_dirname(path);
204         char *site = g_path_get_basename(dir);
205         g_free(dir);
206         RSL_read_these_sweeps("all", NULL);
207         if (self->cur_radar) {
208                 g_message("Freeing radar");
209                 RSL_free_radar(self->cur_radar);
210         }
211         g_message("Allocating radar");
212         Radar *radar = self->cur_radar = RSL_wsr88d_to_radar(path, site);
213         if (radar == NULL) {
214                 g_warning("fail to load radar: path=%s, site=%s", path, site);
215                 g_free(path);
216                 g_free(site);
217                 return;
218         }
219         g_free(path);
220         g_free(site);
221
222         /* Load the first sweep by default */
223         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
224                 g_warning("No sweeps found\n");
225         } else {
226                 /* load first available sweep */
227                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
228                         if (radar->v[vi]== NULL) continue;
229                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
230                                 if (radar->v[vi]->sweep[si]== NULL) continue;
231                                 load_color_table(radar->v[vi]->h.type_str);
232                                 load_sweep(radar->v[vi]->sweep[si]);
233                                 break;
234                         }
235                         break;
236                 }
237         }
238
239         load_radar_gui(radar);
240 }
241
242 /* decompress a radar file, then chain to the actuall loading function */
243 static void load_radar(char *path, gboolean updated, gpointer user_data)
244 {
245         char *raw  = g_strconcat(path, ".raw", NULL);
246         if (!updated) {
247                 load_radar_rsl(0, 0, raw);
248         } else {
249                 g_message("File updated, decompressing..");
250                 char *argv[] = {"wsr88ddec", path, raw, NULL};
251                 GPid pid;
252                 GError *error = NULL;
253                 g_spawn_async(
254                         NULL,    // const gchar *working_directory,
255                         argv,    // gchar **argv,
256                         NULL,    // gchar **envp,
257                         G_SPAWN_SEARCH_PATH|
258                         G_SPAWN_DO_NOT_REAP_CHILD, 
259                                  // GSpawnFlags flags,
260                         NULL,    // GSpawnChildSetupFunc child_setup,
261                         NULL,    // gpointer user_data,
262                         &pid,    // GPid *child_pid,
263                         &error); // GError **error
264                 if (error) {
265                         g_warning("failed to decompress WSR88D data: %s",
266                                         error->message);
267                         g_error_free(error);
268                 }
269                 g_child_watch_add(pid, load_radar_rsl, raw);
270         }
271 }
272
273 static void update_times(char *site, char **last_time)
274 {
275         char *list_uri = g_strdup_printf(
276                         "http://mesonet.agron.iastate.edu/data/nexrd2/raw/K%s/dir.list",
277                         site);
278         GFile *list    = g_file_new_for_uri(list_uri);
279         g_free(list_uri);
280
281         gchar *data;
282         gsize length;
283         GError *error = NULL;
284         g_file_load_contents(list, NULL, &data, &length, NULL, &error);
285         g_object_unref(list);
286         if (error) {
287                 g_warning("Error loading list for %s: %s", site, error->message);
288                 g_error_free(error);
289                 return;
290         }
291         gchar **lines = g_strsplit(data, "\n", -1);
292         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(self->gui, "time"));
293         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
294         gtk_list_store_clear(lstore);
295         GtkTreeIter iter;
296         for (int i = 0; lines[i] && lines[i][0]; i++) {
297                 // format: `841907 KABR_20090510_0159'
298                 //g_message("\tadding %p [%s]", lines[i], lines[i]);
299                 char **parts = g_strsplit(lines[i], " ", 2);
300                 char *time = parts[1]+5;
301                 gtk_list_store_insert(lstore, &iter, 0);
302                 gtk_list_store_set(lstore, &iter, 0, time, -1);
303                 g_strfreev(parts);
304         }
305
306         if (last_time)
307                 gtk_tree_model_get(GTK_TREE_MODEL(lstore), &iter, 0, last_time, -1);
308
309         g_free(data);
310         g_strfreev(lines);
311 }
312
313 /*************
314  * Callbacks *
315  *************/
316 static void on_time_changed(AWeatherView *view, char *time, gpointer user_data)
317 {
318         g_message("radar:setting time");
319         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
320         char *site = aweather_view_get_site(view);
321         char *base = "http://mesonet.agron.iastate.edu/data/";
322         char *path = g_strdup_printf("nexrd2/raw/K%s/K%s_%s", site, site, time);
323
324         self->cur_radar = NULL;
325         self->cur_sweep = NULL; // Clear radar
326         aweather_gui_gl_redraw(self->gui);
327
328         cache_file(base, path, AWEATHER_AUTOMATIC, load_radar, NULL);
329         g_free(path);
330 }
331
332 static void on_site_changed(AWeatherView *view, char *site, gpointer user_data)
333 {
334         g_message("Loading wsr88d list for %s", site);
335         char *time = NULL;
336         update_times(site, &time);
337         aweather_view_set_time(view, time);
338
339         g_free(time);
340 }
341
342 static void on_refresh(AWeatherView *view, gpointer user_data)
343 {
344         char *site = aweather_view_get_site(view);
345         char *time = NULL;
346         update_times(site, &time);
347         aweather_view_set_time(view, time);
348         g_free(time);
349 }
350
351
352
353 /***********
354  * Methods *
355  ***********/
356 AWeatherRadar *aweather_radar_new(AWeatherGui *gui)
357 {
358         //g_message("aweather_view_new");
359         AWeatherRadar *radar = g_object_new(AWEATHER_TYPE_RADAR, NULL);
360         radar->gui = gui;
361
362         self = radar;
363
364         GtkWidget    *config  = aweather_gui_get_widget(gui, "tabs");
365         AWeatherView *view    = aweather_gui_get_view(gui);
366
367         /* Add configuration tab */
368         self->config_body = gtk_alignment_new(0, 0, 1, 1);
369         gtk_container_set_border_width(GTK_CONTAINER(self->config_body), 5);
370         gtk_container_add(GTK_CONTAINER(self->config_body), gtk_label_new("No radar loaded"));
371         gtk_notebook_prepend_page(GTK_NOTEBOOK(config), self->config_body, gtk_label_new("Radar"));
372
373         /* Set up OpenGL Stuff */
374         g_signal_connect(view,    "site-changed", G_CALLBACK(on_site_changed), NULL);
375         g_signal_connect(view,    "time-changed", G_CALLBACK(on_time_changed), NULL);
376         g_signal_connect(view,    "refresh",      G_CALLBACK(on_refresh),      NULL);
377
378         return radar;
379 }
380
381 static void aweather_radar_expose(AWeatherPlugin *_radar)
382 {
383         AWeatherRadar *radar = AWEATHER_RADAR(_radar);
384         g_message("radar:expose");
385         if (self->cur_sweep == NULL)
386                 return;
387         Sweep *sweep = self->cur_sweep;
388
389         /* Draw the rays */
390
391         glMatrixMode(GL_MODELVIEW);
392         glPushMatrix();
393         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
394         glEnable(GL_TEXTURE_2D);
395         glDisable(GL_ALPHA_TEST);
396         glColor4f(1,1,1,1);
397         glBegin(GL_QUAD_STRIP);
398         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
399                 Ray  *ray = NULL;
400                 double angle = 0;
401                 if (ri < sweep->h.nrays) {
402                         ray = sweep->ray[ri];
403                         angle = ((ray->h.azimuth - ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
404                 } else {
405                         /* Do the right side of the last sweep */
406                         ray = sweep->ray[ri-1];
407                         angle = ((ray->h.azimuth + ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
408                 }
409
410                 double lx = sin(angle);
411                 double ly = cos(angle);
412
413                 double near_dist = ray->h.range_bin1;
414                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
415
416                 /* (find middle of bin) / scale for opengl */
417                 // near left
418                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays-0.01);
419                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
420
421                 // far  left
422                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays-0.01);
423                 glVertex3f(lx*far_dist,  ly*far_dist,  2.0);
424         }
425         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
426         glEnd();
427         glPopMatrix();
428
429         /* Texture debug */
430         //glBegin(GL_QUADS);
431         //glTexCoord2d( 0.,  0.); glVertex3f(-500.,   0., 0.); // bot left
432         //glTexCoord2d( 0.,  1.); glVertex3f(-500., 500., 0.); // top left
433         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,   500., 3.); // top right
434         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,     0., 3.); // bot right
435         //glEnd();
436
437         /* Print the color table */
438         glDisable(GL_TEXTURE_2D);
439         glDisable(GL_DEPTH_TEST);
440         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
441         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
442         glBegin(GL_QUADS);
443         int i;
444         for (i = 0; i < 256; i++) {
445                 glColor4ub(self->cur_colormap->data[i][0],
446                            self->cur_colormap->data[i][1],
447                            self->cur_colormap->data[i][2],
448                            self->cur_colormap->data[i][3]);
449                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
450                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
451                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
452                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
453         }
454         glEnd();
455         glEnable(GL_DEPTH_TEST);
456         glEnable(GL_ALPHA_TEST);
457         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
458         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
459 }