]> Pileus Git - aweather/blob - src/plugins/radar.c
Determine site based on lat-lon location
[aweather] / src / plugins / 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 <gio/gio.h>
22 #include <GL/gl.h>
23 #include <math.h>
24 #include <rsl.h>
25
26 #include <gis/gis.h>
27
28 #include "radar.h"
29 #include "marching.h"
30 #include "../aweather-location.h"
31
32
33 /**************************
34  * Data loading functions *
35  **************************/
36 /* Convert a sweep to an 2d array of data points */
37 static void _bscan_sweep(GisPluginRadar *self, Sweep *sweep, colormap_t *colormap,
38                 guint8 **data, int *width, int *height)
39 {
40         /* Calculate max number of bins */
41         int max_bins = 0;
42         for (int i = 0; i < sweep->h.nrays; i++)
43                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
44
45         /* Allocate buffer using max number of bins for each ray */
46         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
47
48         /* Fill the data */
49         for (int ri = 0; ri < sweep->h.nrays; ri++) {
50                 Ray *ray  = sweep->ray[ri];
51                 for (int bi = 0; bi < ray->h.nbins; bi++) {
52                         /* copy RGBA into buffer */
53                         //guint val   = dz_f(ray->range[bi]);
54                         guint8 val   = (guint8)ray->h.f(ray->range[bi]);
55                         guint  buf_i = (ri*max_bins+bi)*4;
56                         buf[buf_i+0] = colormap->data[val][0];
57                         buf[buf_i+1] = colormap->data[val][1];
58                         buf[buf_i+2] = colormap->data[val][2];
59                         buf[buf_i+3] = colormap->data[val][3]; // TESTING
60                         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
61                             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO) {
62                                 buf[buf_i+3] = 0x00; // transparent
63                         }
64                 }
65         }
66
67         /* set output */
68         *width  = max_bins;
69         *height = sweep->h.nrays;
70         *data   = buf;
71 }
72
73 /* Load a sweep as the active texture */
74 static void _load_sweep(GisPluginRadar *self, Sweep *sweep)
75 {
76         GisViewer *viewer = self->viewer;
77         gis_viewer_begin(viewer);
78         self->cur_sweep = sweep;
79         int height, width;
80         guint8 *data;
81         _bscan_sweep(self, sweep, self->cur_colormap, &data, &width, &height);
82         glDeleteTextures(1, &self->cur_sweep_tex);
83         glGenTextures(1, &self->cur_sweep_tex);
84         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
85         glPixelStorei(GL_PACK_ALIGNMENT, 1);
86         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
87         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
88         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
89         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
90                         GL_RGBA, GL_UNSIGNED_BYTE, data);
91         g_free(data);
92         gtk_widget_queue_draw(GTK_WIDGET(viewer));
93         gis_viewer_end(viewer);
94 }
95
96 static void _load_colormap(GisPluginRadar *self, gchar *table)
97 {
98         /* Set colormap so we can draw it on expose */
99         for (int i = 0; colormaps[i].name; i++)
100                 if (g_str_equal(colormaps[i].name, table))
101                         self->cur_colormap = &colormaps[i];
102 }
103
104 /* Add selectors to the config area for the sweeps */
105 static void _on_sweep_clicked(GtkRadioButton *button, gpointer _self);
106 static void _load_radar_gui(GisPluginRadar *self, Radar *radar)
107 {
108         /* Clear existing items */
109         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
110         if (child)
111                 gtk_widget_destroy(child);
112
113         gdouble elev;
114         guint rows = 1, cols = 1, cur_cols;
115         gchar row_label_str[64], col_label_str[64], button_str[64];
116         GtkWidget *row_label, *col_label, *button = NULL, *elev_box = NULL;
117         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
118
119         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
120                 Volume *vol = radar->v[vi];
121                 if (vol == NULL) continue;
122                 rows++; cols = 1; elev = 0;
123
124                 /* Row label */
125                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
126                 row_label = gtk_label_new(row_label_str);
127                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
128                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
129                 gtk_table_attach(GTK_TABLE(table), row_label,
130                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
131
132                 for (guint si = 0; si < vol->h.nsweeps; si++) {
133                         Sweep *sweep = vol->sweep[si];
134                         if (sweep == NULL || sweep->h.elev == 0) continue;
135                         if (sweep->h.elev != elev) {
136                                 cols++;
137                                 elev = sweep->h.elev;
138
139                                 /* Column label */
140                                 g_object_get(table, "n-columns", &cur_cols, NULL);
141                                 if (cols >  cur_cols) {
142                                         g_snprintf(col_label_str, 64, "<b>%.2f°</b>", elev);
143                                         col_label = gtk_label_new(col_label_str);
144                                         gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
145                                         gtk_widget_set_size_request(col_label, 50, -1);
146                                         gtk_table_attach(GTK_TABLE(table), col_label,
147                                                         cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
148                                 }
149
150                                 elev_box = gtk_hbox_new(TRUE, 0);
151                                 gtk_table_attach(GTK_TABLE(table), elev_box,
152                                                 cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
153                         }
154
155
156                         /* Button */
157                         g_snprintf(button_str, 64, "%3.2f", elev);
158                         button = gtk_radio_button_new_with_label_from_widget(
159                                         GTK_RADIO_BUTTON(button), button_str);
160                         gtk_widget_set_size_request(button, -1, 26);
161                         //button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
162                         //gtk_widget_set_size_request(button, -1, 22);
163                         g_object_set(button, "draw-indicator", FALSE, NULL);
164                         gtk_box_pack_end(GTK_BOX(elev_box), button, TRUE, TRUE, 0);
165
166                         g_object_set_data(G_OBJECT(button), "type",  vol->h.type_str);
167                         g_object_set_data(G_OBJECT(button), "sweep", sweep);
168                         g_signal_connect(button, "clicked", G_CALLBACK(_on_sweep_clicked), self);
169                 }
170         }
171         gtk_container_add(GTK_CONTAINER(self->config_body), table);
172         gtk_widget_show_all(table);
173 }
174
175 static void _gis_plugin_radar_grid_set(GRIDCELL *grid, int gi, Ray *ray, int bi)
176 {
177         Range range = ray->range[bi];
178
179         double angle = deg2rad(ray->h.azimuth);
180         double tilt  = deg2rad(ray->h.elev);
181
182         double lx    = sin(angle);
183         double ly    = cos(angle);
184         double lz    = sin(tilt);
185
186         double dist   = bi*ray->h.gate_size + ray->h.range_bin1;
187
188         grid->p[gi].x = lx*dist;
189         grid->p[gi].y = ly*dist;
190         grid->p[gi].z = lz*dist;
191
192         guint8 val = (guint8)ray->h.f(ray->range[bi]);
193         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
194             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO ||
195             val > 80)
196                 val = 0;
197         grid->val[gi] = (float)val;
198         //g_debug("(%.2f,%.2f,%.2f) - (%.0f,%.0f,%.0f) = %d",
199         //      angle, tilt, dist,
200         //      grid->p[gi].x,
201         //      grid->p[gi].y,
202         //      grid->p[gi].z,
203         //      val);
204 }
205
206 /* Load a radar from a decompressed file */
207 static void _load_radar(GisPluginRadar *self, gchar *radar_file)
208 {
209         char *dir  = g_path_get_dirname(radar_file);
210         char *site = g_path_get_basename(dir);
211         g_free(dir);
212         g_debug("GisPluginRadar: load_radar - Loading new radar");
213         RSL_read_these_sweeps("all", NULL);
214         Radar *radar = self->cur_radar = RSL_wsr88d_to_radar(radar_file, site);
215         if (radar == NULL) {
216                 g_warning("fail to load radar: path=%s, site=%s", radar_file, site);
217                 g_free(site);
218                 return;
219         }
220         g_free(site);
221
222 #ifdef MARCHING
223         /* Load the surface */
224         if (self->cur_triangles) {
225                 g_free(self->cur_triangles);
226                 self->cur_triangles = NULL;
227         }
228         self->cur_num_triangles = 0;
229         int x = 1;
230         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
231                 if (radar->v[vi] == NULL) continue;
232
233                 for (guint si = 0; si+1 < radar->v[vi]->h.nsweeps; si++) {
234                         Sweep *sweep0 = radar->v[vi]->sweep[si+0];
235                         Sweep *sweep1 = radar->v[vi]->sweep[si+1];
236
237                         //g_debug("GisPluginRadar: load_radar: sweep[%3d-%3d] -- nrays = %d, %d",
238                         //      si, si+1,sweep0->h.nrays, sweep1->h.nrays);
239
240                         /* Skip super->regular resolution switch for now */
241                         if (sweep0 == NULL || sweep0->h.elev == 0 ||
242                             sweep1 == NULL || sweep1->h.elev == 0 ||
243                             sweep0->h.nrays != sweep1->h.nrays)
244                                 continue;
245
246                         /* We repack the arrays so that raysX[0] is always north, etc */
247                         Ray **rays0 = g_malloc0(sizeof(Ray*)*sweep0->h.nrays);
248                         Ray **rays1 = g_malloc0(sizeof(Ray*)*sweep1->h.nrays);
249
250                         for (guint ri = 0; ri < sweep0->h.nrays; ri++)
251                                 rays0[(guint)(sweep0->ray[ri]->h.azimuth * sweep0->h.nrays / 360)] =
252                                         sweep0->ray[ri];
253                         for (guint ri = 0; ri < sweep1->h.nrays; ri++)
254                                 rays1[(guint)(sweep1->ray[ri]->h.azimuth * sweep1->h.nrays / 360)] =
255                                         sweep1->ray[ri];
256
257                         for (guint ri = 0; ri+x < sweep0->h.nrays; ri+=x) {
258                                 //g_debug("GisPluginRadar: load_radar - ray[%3d-%3d] -- nbins = %d, %d, %d, %d",
259                                 //      ri, ri+x,
260                                 //      rays0[ri  ]->h.nbins,
261                                 //      rays0[ri+1]->h.nbins,
262                                 //      rays1[ri  ]->h.nbins,
263                                 //      rays1[ri+1]->h.nbins);
264
265                                 for (guint bi = 0; bi+x < rays1[ri]->h.nbins; bi+=x) {
266                                         GRIDCELL grid = {};
267                                         _gis_plugin_radar_grid_set(&grid, 7, rays0[(ri  )%sweep0->h.nrays], bi+x);
268                                         _gis_plugin_radar_grid_set(&grid, 6, rays0[(ri+x)%sweep0->h.nrays], bi+x);
269                                         _gis_plugin_radar_grid_set(&grid, 5, rays0[(ri+x)%sweep0->h.nrays], bi  );
270                                         _gis_plugin_radar_grid_set(&grid, 4, rays0[(ri  )%sweep0->h.nrays], bi  );
271                                         _gis_plugin_radar_grid_set(&grid, 3, rays1[(ri  )%sweep0->h.nrays], bi+x);
272                                         _gis_plugin_radar_grid_set(&grid, 2, rays1[(ri+x)%sweep0->h.nrays], bi+x);
273                                         _gis_plugin_radar_grid_set(&grid, 1, rays1[(ri+x)%sweep0->h.nrays], bi  );
274                                         _gis_plugin_radar_grid_set(&grid, 0, rays1[(ri  )%sweep0->h.nrays], bi  );
275                                         
276                                         TRIANGLE tris[10];
277                                         int n = march_one_cube(grid, 40, tris);
278
279                                         self->cur_triangles = g_realloc(self->cur_triangles,
280                                                 (self->cur_num_triangles+n)*sizeof(TRIANGLE));
281                                         for (int i = 0; i < n; i++) {
282                                                 //g_debug("triangle: ");
283                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[0].x, tris[i].p[0].y, tris[i].p[0].z);
284                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[1].x, tris[i].p[1].y, tris[i].p[1].z);
285                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[2].x, tris[i].p[2].y, tris[i].p[2].z);
286                                                 self->cur_triangles[self->cur_num_triangles+i] = tris[i];
287                                         }
288                                         self->cur_num_triangles += n;
289                                         //g_debug(" ");
290                                 }
291                         }
292                 }
293                 break; // Exit after first volume (reflectivity)
294         }
295 #endif
296
297         /* Load the first sweep by default */
298         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
299                 g_warning("No sweeps found\n");
300         } else {
301                 /* load first available sweep */
302                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
303                         if (radar->v[vi]== NULL) continue;
304                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
305                                 if (radar->v[vi]->sweep[si]== NULL) continue;
306                                 _load_colormap(self, radar->v[vi]->h.type_str);
307                                 _load_sweep(self, radar->v[vi]->sweep[si]);
308                                 break;
309                         }
310                         break;
311                 }
312         }
313
314         _load_radar_gui(self, radar);
315 }
316
317
318 /*****************
319  * ASync helpers *
320  *****************/
321 typedef struct {
322         GisPluginRadar *self;
323         gchar *radar_file;
324 } decompressed_t;
325
326 static void _decompressed_cb(GPid pid, gint status, gpointer _udata)
327 {
328         g_debug("GisPluginRadar: decompressed_cb");
329         decompressed_t *udata = _udata;
330         if (status != 0) {
331                 g_warning("wsr88ddec exited with status %d", status);
332                 return;
333         }
334         _load_radar(udata->self, udata->radar_file);
335         g_spawn_close_pid(pid);
336         g_free(udata->radar_file);
337         g_free(udata);
338 }
339
340 static void _cache_chunk_cb(char *path, goffset cur, goffset total, gpointer _self)
341 {
342         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
343         double percent = (double)cur/total;
344
345         //g_debug("GisPluginRadar: cache_chunk_cb - %lld/%lld = %.2f%%",
346         //              cur, total, percent*100);
347
348         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(self->progress_bar), MIN(percent, 1.0));
349
350         gchar *msg = g_strdup_printf("Loading radar... %5.1f%% (%.2f/%.2f MB)",
351                         percent*100, (double)cur/1000000, (double)total/1000000);
352         gtk_label_set_text(GTK_LABEL(self->progress_label), msg);
353         g_free(msg);
354 }
355
356 static void _cache_done_cb(char *path, gboolean updated, gpointer _self)
357 {
358         g_debug("GisPluginRadar: cache_done_cb - updated = %d", updated);
359         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
360         char *decompressed = g_strconcat(path, ".raw", NULL);
361         if (!updated && g_file_test(decompressed, G_FILE_TEST_EXISTS)) {
362                 _load_radar(self, decompressed);
363                 return;
364         }
365
366         decompressed_t *udata = g_malloc(sizeof(decompressed_t));
367         udata->self       = self;
368         udata->radar_file = decompressed;
369         g_debug("GisPluginRadar: cache_done_cb - File updated, decompressing..");
370         char *argv[] = {"wsr88ddec", path, decompressed, NULL};
371         GPid pid;
372         GError *error = NULL;
373         g_spawn_async(
374                 NULL,    // const gchar *working_directory,
375                 argv,    // gchar **argv,
376                 NULL,    // gchar **envp,
377                 G_SPAWN_SEARCH_PATH|
378                 G_SPAWN_DO_NOT_REAP_CHILD,
379                          // GSpawnFlags flags,
380                 NULL,    // GSpawnChildSetupFunc child_setup,
381                 NULL,    // gpointer user_data,
382                 &pid,    // GPid *child_pid,
383                 &error); // GError **error
384         if (error) {
385                 gchar *message = g_strdup_printf("Unable to decompress WSR88D data: %s",
386                                 error->message);
387                 g_warning("%s", message);
388                 GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
389                 if (child)
390                         gtk_widget_destroy(child);
391                 gtk_container_add(GTK_CONTAINER(self->config_body), gtk_label_new(message));
392                 gtk_widget_show_all(self->config_body);
393                 g_error_free(error);
394                 g_free(message);
395         }
396         g_child_watch_add(pid, _decompressed_cb, udata);
397         self->soup = NULL;
398 }
399
400 static void _set_radar(GisPluginRadar *self, const char *site, const char *time)
401 {
402         if (!site || !time)
403                 return;
404         g_debug("GisPluginRadar: set_radar - %s - %s", site, time);
405
406         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
407         char *path = g_strdup_printf("nexrd2/raw/%s/%s_%s", site, site, time);
408
409         /* Set up progress bar */
410         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
411         if (child) gtk_widget_destroy(child);
412
413         GtkWidget *vbox = gtk_vbox_new(FALSE, 10);
414         gtk_container_set_border_width(GTK_CONTAINER(vbox), 10);
415         self->progress_bar   = gtk_progress_bar_new();
416         self->progress_label = gtk_label_new("Loading radar...");
417         gtk_box_pack_start(GTK_BOX(vbox), self->progress_bar,   FALSE, FALSE, 0);
418         gtk_box_pack_start(GTK_BOX(vbox), self->progress_label, FALSE, FALSE, 0);
419         gtk_container_add(GTK_CONTAINER(self->config_body), vbox);
420         gtk_widget_show_all(self->config_body);
421
422         /* Clear radar */
423         if (self->cur_radar)
424                 RSL_free_radar(self->cur_radar);
425         self->cur_radar = NULL;
426         self->cur_sweep = NULL;
427         gtk_widget_queue_draw(GTK_WIDGET(self->viewer));
428
429         /* Start loading the new radar */
430         if (self->soup) {
431                 soup_session_abort(self->soup);
432                 self->soup = NULL;
433         }
434         gchar *base = gis_prefs_get_string(self->prefs, "aweather/nexrad_url", NULL);
435         if (gis_viewer_get_offline(self->viewer))
436                 self->soup = cache_file(base, path, GIS_NEVER,
437                                 NULL, _cache_done_cb, self);
438         else
439                 self->soup = cache_file(base, path, GIS_UPDATE,
440                                 _cache_chunk_cb, _cache_done_cb, self);
441         g_free(path);
442 }
443
444
445 /*************
446  * Callbacks *
447  *************/
448 static void _on_sweep_clicked(GtkRadioButton *button, gpointer _self)
449 {
450         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
451         _load_colormap(self, g_object_get_data(G_OBJECT(button), "type" ));
452         _load_sweep   (self, g_object_get_data(G_OBJECT(button), "sweep"));
453 }
454
455 static void _on_time_changed(GisViewer *viewer, const char *time, gpointer _self)
456 {
457         g_debug("GisPluginRadar: _on_time_changed");
458         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
459         g_free(self->cur_time);
460         self->cur_time = g_strdup(time);
461         _set_radar(self, self->cur_site, self->cur_time);
462 }
463
464 static void _on_location_changed(GisViewer *viewer,
465                 gdouble lat, gdouble lon, gdouble elev,
466                 gpointer _self)
467 {
468         g_debug("GisPluginRadar: _on_location_changed");
469         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
470         gdouble min_dist = EARTH_R / 5;
471         city_t *city, *min_city = NULL;
472         for (city = cities; city->type; city++) {
473                 if (city->type != LOCATION_CITY)
474                         continue;
475                 gdouble city_loc[3] = {};
476                 gdouble eye_loc[3]  = {lat, lon, elev};
477                 lle2xyz(city->lat, city->lon, city->elev,
478                                 &city_loc[0], &city_loc[1], &city_loc[2]);
479                 lle2xyz(lat, lon, elev,
480                                 &eye_loc[0], &eye_loc[1], &eye_loc[2]);
481                 gdouble dist = distd(city_loc, eye_loc);
482                 if (dist < min_dist) {
483                         min_dist = dist;
484                         min_city = city;
485                 }
486         }
487         static city_t *last_city = NULL;
488         if (min_city && min_city != last_city) {
489                 self->cur_site = min_city->code;
490                 _set_radar(self, self->cur_site, self->cur_time);
491         }
492         last_city = min_city;
493 }
494
495 static gpointer _draw_radar(GisCallback *callback, gpointer _self)
496 {
497         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
498         if (self->cur_sweep == NULL)
499                 return NULL;
500         g_debug("GisPluginRadar: _draw_radar");
501         Sweep *sweep = self->cur_sweep;
502
503 #ifdef MARCHING
504         /* Draw the surface */
505         glMatrixMode(GL_MODELVIEW);
506         glPushMatrix();
507         glDisable(GL_TEXTURE_2D);
508         float light_ambient[]  = {0.1f, 0.1f, 0.0f};
509         float light_diffuse[]  = {0.9f, 0.9f, 0.9f};
510         float light_position[] = {-300000.0f, 500000.0f, 400000.0f, 1.0f};
511         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
512         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
513         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
514         glEnable(GL_LIGHT0);
515         glEnable(GL_LIGHTING);
516         glEnable(GL_COLOR_MATERIAL);
517         glColor4f(1,1,1,0.75);
518         g_debug("ntri=%d", self->cur_num_triangles);
519         glBegin(GL_TRIANGLES);
520         for (int i = 0; i < self->cur_num_triangles; i++) {
521                 TRIANGLE t = self->cur_triangles[i];
522                 do_normal(t.p[0].x, t.p[0].y, t.p[0].z,
523                           t.p[1].x, t.p[1].y, t.p[1].z,
524                           t.p[2].x, t.p[2].y, t.p[2].z);
525                 glVertex3f(t.p[0].x, t.p[0].y, t.p[0].z);
526                 glVertex3f(t.p[1].x, t.p[1].y, t.p[1].z);
527                 glVertex3f(t.p[2].x, t.p[2].y, t.p[2].z);
528         }
529         glEnd();
530         glPopMatrix();
531 #endif
532
533         g_debug("GisPluginRadar: _draw_radar - setting camera");
534         Radar_header *h = &self->cur_radar->h;
535         gdouble lat  = (double)h->latd + (double)h->latm/60 + (double)h->lats/(60*60);
536         gdouble lon  = (double)h->lond + (double)h->lonm/60 + (double)h->lons/(60*60);
537         gdouble elev = h->height;
538         gis_viewer_center_position(self->viewer, lat, lon, elev);
539
540         glDisable(GL_ALPHA_TEST);
541         glDisable(GL_CULL_FACE);
542         glDisable(GL_DEPTH_TEST);
543         glDisable(GL_LIGHTING);
544         glEnable(GL_TEXTURE_2D);
545         glColor4f(1,1,1,1);
546
547         /* Draw the rays */
548         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
549         glBegin(GL_QUAD_STRIP);
550         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
551                 Ray  *ray = NULL;
552                 double angle = 0;
553                 if (ri < sweep->h.nrays) {
554                         ray = sweep->ray[ri];
555                         angle = deg2rad(ray->h.azimuth - ((double)ray->h.beam_width/2.));
556                 } else {
557                         /* Do the right side of the last sweep */
558                         ray = sweep->ray[ri-1];
559                         angle = deg2rad(ray->h.azimuth + ((double)ray->h.beam_width/2.));
560                 }
561
562                 double lx = sin(angle);
563                 double ly = cos(angle);
564
565                 double near_dist = ray->h.range_bin1;
566                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
567
568                 /* (find middle of bin) / scale for opengl */
569                 // near left
570                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays-0.01);
571                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
572
573                 // far  left
574                 // todo: correct range-height function
575                 double height = sin(deg2rad(ray->h.elev)) * far_dist;
576                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays-0.01);
577                 glVertex3f(lx*far_dist,  ly*far_dist, height);
578         }
579         glEnd();
580         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
581
582         /* Texture debug */
583         //glBegin(GL_QUADS);
584         //glTexCoord2d( 0.,  0.); glVertex3f(-500.,   0., 0.); // bot left
585         //glTexCoord2d( 0.,  1.); glVertex3f(-500., 500., 0.); // top left
586         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,   500., 3.); // top right
587         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,     0., 3.); // bot right
588         //glEnd();
589
590         return NULL;
591 }
592
593 static gpointer _draw_hud(GisCallback *callback, gpointer _self)
594 {
595         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
596         if (self->cur_sweep == NULL)
597                 return NULL;
598         g_debug("GisPluginRadar: _draw_hud");
599
600         /* Print the color table */
601         glMatrixMode(GL_MODELVIEW ); glLoadIdentity();
602         glMatrixMode(GL_PROJECTION); glLoadIdentity();
603         glDisable(GL_TEXTURE_2D);
604         glDisable(GL_ALPHA_TEST);
605         glDisable(GL_CULL_FACE);
606         glDisable(GL_LIGHTING);
607         glEnable(GL_COLOR_MATERIAL);
608         glBegin(GL_QUADS);
609         int i;
610         for (i = 0; i < 256; i++) {
611                 glColor4ubv(self->cur_colormap->data[i]);
612                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
613                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
614                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
615                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
616         }
617         glEnd();
618
619         return NULL;
620 }
621
622
623 /***********
624  * Methods *
625  ***********/
626 GisPluginRadar *gis_plugin_radar_new(GisViewer *viewer, GisPrefs *prefs)
627 {
628         /* TODO: move to constructor if possible */
629         g_debug("GisPluginRadar: new");
630         GisPluginRadar *self = g_object_new(GIS_TYPE_PLUGIN_RADAR, NULL);
631         self->viewer = viewer;
632         self->prefs  = prefs;
633         self->time_changed_id = g_signal_connect(viewer, "time-changed",
634                         G_CALLBACK(_on_time_changed), self);
635         self->location_changed_id = g_signal_connect(viewer, "location-changed",
636                         G_CALLBACK(_on_location_changed), self);
637
638         /* Add renderers */
639         GisCallback *callback;
640
641         callback = gis_callback_new(_draw_radar, self);
642         gis_viewer_add(viewer, GIS_OBJECT(callback), GIS_LEVEL_WORLD, TRUE);
643
644         callback = gis_callback_new(_draw_hud, self);
645         gis_viewer_add(viewer, GIS_OBJECT(callback), GIS_LEVEL_HUD, FALSE);
646
647         return self;
648 }
649
650 static GtkWidget *gis_plugin_radar_get_config(GisPlugin *_self)
651 {
652         GisPluginRadar *self = GIS_PLUGIN_RADAR(_self);
653         return self->config_body;
654 }
655
656
657 /****************
658  * GObject code *
659  ****************/
660 /* Plugin init */
661 static void gis_plugin_radar_plugin_init(GisPluginInterface *iface);
662 G_DEFINE_TYPE_WITH_CODE(GisPluginRadar, gis_plugin_radar, G_TYPE_OBJECT,
663                 G_IMPLEMENT_INTERFACE(GIS_TYPE_PLUGIN,
664                         gis_plugin_radar_plugin_init));
665 static void gis_plugin_radar_plugin_init(GisPluginInterface *iface)
666 {
667         g_debug("GisPluginRadar: plugin_init");
668         /* Add methods to the interface */
669         iface->get_config = gis_plugin_radar_get_config;
670 }
671 /* Class/Object init */
672 static void gis_plugin_radar_init(GisPluginRadar *self)
673 {
674         g_debug("GisPluginRadar: class_init");
675         /* Set defaults */
676         self->soup          = NULL;
677         self->cur_triangles = NULL;
678         self->cur_num_triangles = 0;
679
680         self->config_body = gtk_alignment_new(0, 0, 1, 1);
681         gtk_container_set_border_width(GTK_CONTAINER(self->config_body), 5);
682         gtk_container_add(GTK_CONTAINER(self->config_body), gtk_label_new("No radar loaded"));
683 }
684 static void gis_plugin_radar_dispose(GObject *gobject)
685 {
686         g_debug("GisPluginRadar: dispose");
687         GisPluginRadar *self = GIS_PLUGIN_RADAR(gobject);
688         g_signal_handler_disconnect(self->viewer, self->time_changed_id);
689         /* Drop references */
690         G_OBJECT_CLASS(gis_plugin_radar_parent_class)->dispose(gobject);
691 }
692 static void gis_plugin_radar_finalize(GObject *gobject)
693 {
694         g_debug("GisPluginRadar: finalize");
695         GisPluginRadar *self = GIS_PLUGIN_RADAR(gobject);
696         /* Free data */
697         G_OBJECT_CLASS(gis_plugin_radar_parent_class)->finalize(gobject);
698
699 }
700 static void gis_plugin_radar_class_init(GisPluginRadarClass *klass)
701 {
702         g_debug("GisPluginRadar: class_init");
703         GObjectClass *gobject_class = (GObjectClass*)klass;
704         gobject_class->dispose  = gis_plugin_radar_dispose;
705         gobject_class->finalize = gis_plugin_radar_finalize;
706 }
707