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