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