]> Pileus Git - grits/blob - src/plugin-radar.c
adding some RSL patches, and support for velocity/spectum width color maps
[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
24 #include "rsl.h"
25
26 #include "aweather-gui.h"
27 #include "plugin-radar.h"
28 #include "data.h"
29
30 GtkWidget *drawing;
31 GtkWidget *config_body;
32 static Sweep *cur_sweep = NULL;  // make this not global
33 static int nred, ngreen, nblue;
34 static char red[256], green[256], blue[256];
35 static guint sweep_tex = 0;
36
37 static AWeatherGui *gui = NULL;
38 static Radar *radar = NULL;
39
40 /**************************
41  * Data loading functions *
42  **************************/
43 /* return a GL alpha value for a radar pixle */
44 static guint8 get_alpha(guint8 db)
45 {
46         if (db == BADVAL) return 0;
47         if (db == RFVAL ) return 0;
48         if (db == APFLAG) return 0;
49         if (db == NOECHO) return 0;
50         if (db == 0     ) return 0;
51         //if      (db > 60) return 0;
52         //else if (db < 10) return 0;
53         //else if (db < 25) return (db-10)*(255.0/15);
54         else              return 255;
55 }
56
57 /* Convert a sweep to an 2d array of data points */
58 static void bscan_sweep(Sweep *sweep, guint8 **data, int *width, int *height)
59 {
60         /* Calculate max number of bins */
61         int i, max_bins = 0;
62         for (i = 0; i < sweep->h.nrays; i++)
63                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
64
65         /* Allocate buffer using max number of bins for each ray */
66         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
67
68         /* Fill the data */
69         int ri, bi;
70         for (ri = 0; ri < sweep->h.nrays; ri++) {
71                 Ray *ray  = sweep->ray[ri];
72                 for (bi = 0; bi < ray->h.nbins; bi++) {
73                         /* copy RGBA into buffer */
74                         //guint val   = dz_f(ray->range[bi]);
75                         guint val   = ray->h.f(ray->range[bi]);
76                         guint buf_i = (ri*max_bins+bi)*4;
77                         buf[buf_i+0] =   red[val];
78                         buf[buf_i+1] = green[val];
79                         buf[buf_i+2] =  blue[val];
80                         buf[buf_i+3] = get_alpha(val);
81                 }
82         }
83
84         /* set output */
85         *width  = max_bins;
86         *height = sweep->h.nrays;
87         *data   = buf;
88 }
89
90 static void load_color_table(char *table)
91 {
92         /* TODO: replace this with a better color table */
93         g_message("loading color table");
94         if (g_str_equal(table, "Velocity"))
95                 RSL_load_vel_color_table();
96         else if (g_str_equal(table, "Spectrum width"))
97                 RSL_load_sw_color_table();
98         else
99                 RSL_load_refl_color_table();
100         RSL_get_color_table(RSL_RED_TABLE,   red,   &nred);
101         RSL_get_color_table(RSL_GREEN_TABLE, green, &ngreen);
102         RSL_get_color_table(RSL_BLUE_TABLE,  blue,  &nblue);
103 }
104
105 /* Load a sweep as the active texture */
106 static void load_sweep(Sweep *sweep)
107 {
108         aweather_gui_gl_begin(gui);
109         cur_sweep = sweep;
110         int height, width;
111         guint8 *data;
112         bscan_sweep(sweep, &data, &width, &height);
113         glGenTextures(1, &sweep_tex);
114         glBindTexture(GL_TEXTURE_2D, sweep_tex);
115         glPixelStorei(GL_PACK_ALIGNMENT, 1);
116         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
117         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
118         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
119         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
120         g_free(data);
121         gdk_window_invalidate_rect(drawing->window, &drawing->allocation, FALSE);
122         gdk_window_process_updates(drawing->window, FALSE);
123         aweather_gui_gl_end(gui);
124 }
125
126 /* Add selectors to the config area for the sweeps */
127 static void load_radar_gui(Radar *radar)
128 {
129         /* Clear existing items */
130         GtkWidget *child = gtk_bin_get_child(GTK_BIN(config_body));
131         if (child)
132                 gtk_widget_destroy(child);
133
134         GtkWidget *hbox = gtk_hbox_new(TRUE, 0);
135         GtkWidget *button = NULL;
136         int vi = 0, si = 0;
137         for (vi = 0; vi < radar->h.nvolumes; vi++) {
138                 Volume *vol = radar->v[vi];
139                 if (vol == NULL) continue;
140                 GtkWidget *vbox = gtk_vbox_new(TRUE, 0);
141                 for (si = vol->h.nsweeps-1; si >= 0; si--) {
142                         Sweep *sweep = vol->sweep[si];
143                         if (sweep == NULL) continue;
144                         char *label = g_strdup_printf("Tilt: %.2f (%s)", sweep->h.elev, vol->h.type_str);
145                         button = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(button), label);
146                         g_object_set(button, "draw-indicator", FALSE, NULL);
147                         g_signal_connect_swapped(button, "clicked", G_CALLBACK(load_color_table), vol->h.type_str);
148                         g_signal_connect_swapped(button, "clicked", G_CALLBACK(load_sweep), sweep);
149                         gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, TRUE, 0);
150                         g_free(label);
151                 }
152                 gtk_box_set_homogeneous(GTK_BOX(vbox), FALSE);
153                 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
154         }
155         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(config_body), hbox);
156         gtk_widget_show_all(hbox);
157 }
158
159 /* Load a radar from a file */
160 static void load_radar_rsl(GPid pid, gint status, gpointer _path)
161 {
162         gchar *path = _path;
163         if (status != 0) {
164                 g_warning("wsr88ddec exited with status %d", status);
165                 return;
166         }
167         char *site = g_path_get_basename(g_path_get_dirname(path));
168         if (radar) RSL_free_radar(radar);
169         RSL_read_these_sweeps("all", NULL);
170         radar = RSL_wsr88d_to_radar(path, site);
171         if (radar == NULL) {
172                 g_warning("fail to load radar: path=%s, site=%s", path, site);
173                 return;
174         }
175
176         /* Load the first sweep by default */
177         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
178                 g_warning("No sweeps found\n");
179         } else {
180                 /* load first available sweep */
181                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
182                         if (radar->v[vi]== NULL) continue;
183                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
184                                 if (radar->v[vi]->sweep[si]== NULL) continue;
185                                 load_color_table(radar->v[vi]->h.type_str);
186                                 load_sweep(radar->v[vi]->sweep[si]);
187                                 break;
188                         }
189                         break;
190                 }
191         }
192
193         load_radar_gui(radar);
194 }
195
196 /* decompress a radar file, then chain to the actuall loading function */
197 static void load_radar(char *path, gpointer user_data)
198 {
199         char *raw  = g_strconcat(path, ".raw", NULL);
200         if (g_file_test(raw, G_FILE_TEST_EXISTS)) {
201                 load_radar_rsl(0, 0, raw);
202         } else {
203                 char *argv[] = {"wsr88ddec", path, raw, NULL};
204                 GPid pid;
205                 GError *error = NULL;
206                 g_spawn_async(
207                         NULL,    // const gchar *working_directory,
208                         argv,    // gchar **argv,
209                         NULL,    // gchar **envp,
210                         G_SPAWN_SEARCH_PATH|
211                         G_SPAWN_DO_NOT_REAP_CHILD, 
212                                  // GSpawnFlags flags,
213                         NULL,    // GSpawnChildSetupFunc child_setup,
214                         NULL,    // gpointer user_data,
215                         &pid,    // GPid *child_pid,
216                         &error); // GError **error
217                 if (error)
218                         g_warning("failed to decompress WSR88D data: %s", error->message);
219                 g_child_watch_add(pid, load_radar_rsl, raw);
220         }
221 }
222
223 /*************
224  * Callbacks *
225  *************/
226 static gboolean expose(GtkWidget *da, GdkEventExpose *event, gpointer user_data)
227 {
228         g_message("radar:expose");
229         if (cur_sweep == NULL)
230                 return FALSE;
231         Sweep *sweep = cur_sweep;
232
233         /* Draw the rays */
234
235         glMatrixMode(GL_MODELVIEW);
236         glPushMatrix();
237         glBindTexture(GL_TEXTURE_2D, sweep_tex);
238         glEnable(GL_TEXTURE_2D);
239         glDisable(GL_ALPHA_TEST);
240         glColor4f(1,1,1,1);
241         glBegin(GL_QUAD_STRIP);
242         for (int ri = 0; ri <= sweep->h.nrays+1; ri++) {
243                 /* Do the first sweep twice to complete the last Quad */
244                 Ray *ray = sweep->ray[ri % sweep->h.nrays];
245
246                 /* right and left looking out from radar */
247                 double left  = ((ray->h.azimuth - ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
248                 //double right = ((ray->h.azimuth + ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
249
250                 double lx = sin(left);
251                 double ly = cos(left);
252
253                 double near_dist = ray->h.range_bin1;
254                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
255
256                 /* (find middle of bin) / scale for opengl */
257                 // near left
258                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays);
259                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
260
261                 // far  left
262                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays);
263                 glVertex3f(lx*far_dist,  ly*far_dist,  2.0);
264         }
265         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
266         glEnd();
267         glPopMatrix();
268
269         /* Texture debug */
270         //glBegin(GL_QUADS);
271         //glTexCoord2d( 0.,  0.); glVertex3f(-1.,  0., 0.); // bot left
272         //glTexCoord2d( 0.,  1.); glVertex3f(-1.,  1., 0.); // top left
273         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,  1., 0.); // top right
274         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,  0., 0.); // bot right
275         //glEnd();
276
277         /* Print the color table */
278         glDisable(GL_TEXTURE_2D);
279         glDisable(GL_DEPTH_TEST);
280         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
281         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
282         glBegin(GL_QUADS);
283         int i;
284         for (i = 0; i < nred; i++) {
285                 glColor4ub(red[i], green[i], blue[i], get_alpha(i));
286                 glVertex3f(-1.0, (float)((i  ) - nred/2)/(nred/2), 0.0); // bot left
287                 glVertex3f(-1.0, (float)((i+1) - nred/2)/(nred/2), 0.0); // top left
288                 glVertex3f(-0.9, (float)((i+1) - nred/2)/(nred/2), 0.0); // top right
289                 glVertex3f(-0.9, (float)((i  ) - nred/2)/(nred/2), 0.0); // bot right
290         }
291         glEnd();
292         glEnable(GL_DEPTH_TEST);
293         glEnable(GL_ALPHA_TEST);
294         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
295         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
296         return FALSE;
297 }
298
299 static void set_time(AWeatherView *view, char *time, gpointer user_data)
300 {
301         g_message("radar:setting time");
302         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
303         char *site = aweather_view_get_location(view);
304         char *base = "http://mesonet.agron.iastate.edu/data/";
305         char *path = g_strdup_printf("nexrd2/raw/K%s/K%s_%s", site, site, time);
306         //g_message("caching %s/%s", base, path);
307         cache_file(base, path, load_radar, NULL);
308 }
309
310 static void set_site(AWeatherView *view, char *site, gpointer user_data)
311 {
312         g_message("Loading wsr88d list for %s", site);
313         gchar *data;
314         gsize length;
315         GError *error = NULL;
316         char *list_uri = g_strdup_printf("http://mesonet.agron.iastate.edu/data/nexrd2/raw/K%s/dir.list", site);
317         GFile *list    = g_file_new_for_uri(list_uri);
318         g_file_load_contents(list, NULL, &data, &length, NULL, &error);
319         if (error) {
320                 g_warning("Error loading list for %s: %s", site, error->message);
321                 return;
322         }
323         gchar **lines = g_strsplit(data, "\n", -1);
324         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(gui, "time"));
325         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
326         gtk_list_store_clear(lstore);
327         radar = NULL;
328         char *time = NULL;
329         for (int i = 0; lines[i] && lines[i][0]; i++) {
330                 // format: `841907 KABR_20090510_0159'
331                 //g_message("\tadding %p [%s]", lines[i], lines[i]);
332                 char **parts = g_strsplit(lines[i], " ", 2);
333                 time = parts[1]+5;
334                 GtkTreeIter iter;
335                 gtk_list_store_insert(lstore, &iter, 0);
336                 gtk_list_store_set(lstore, &iter, 0, time, -1);
337         }
338         if (time != NULL) 
339                 aweather_view_set_time(view, time);
340 }
341
342 /* Init */
343 gboolean radar_init(AWeatherGui *_gui)
344 {
345         gui = _gui;
346         drawing = aweather_gui_get_widget(gui, "drawing");
347         GtkNotebook    *config  = GTK_NOTEBOOK(aweather_gui_get_widget(gui, "tabs"));
348         AWeatherView   *view    = aweather_gui_get_view(gui);
349
350         /* Add configuration tab */
351         config_body = gtk_scrolled_window_new(NULL, NULL);
352         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(config_body), gtk_label_new("No radar loaded"));
353         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(config_body), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
354         gtk_notebook_append_page(GTK_NOTEBOOK(config), config_body, gtk_label_new("Radar"));
355
356         /* Set up OpenGL Stuff */
357         g_signal_connect(drawing, "expose-event",     G_CALLBACK(expose),   NULL);
358         g_signal_connect(view,    "location-changed", G_CALLBACK(set_site), NULL);
359         g_signal_connect(view,    "time-changed",     G_CALLBACK(set_time), NULL);
360
361         return TRUE;
362 }