]> Pileus Git - grits/blob - src/gis-opengl.c
Keep the sphere locked while drawing the wireframe
[grits] / src / gis-opengl.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
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 /**
19  * SECTION:gis-opengl
20  * @short_description: OpenGL based virtual globe
21  *
22  * #GisOpenGL is the core rendering engine used by libgis. Theoretically other
23  * renderers could be writte, but they have not been. GisOpenGL uses the ROAM
24  * algorithm for updating surface mesh the planet. The only thing GisOpenGL can
25  * actually render on it's own is a wireframe of a sphere.
26  *
27  * GisOpenGL relies on #GtkGlExt and requires (at least) OpenGL 2.0.
28  */
29
30 #include <config.h>
31 #include <math.h>
32 #include <string.h>
33 #include <gdk/gdkkeysyms.h>
34 #include <gtk/gtk.h>
35 #include <gtk/gtkgl.h>
36 #include <GL/gl.h>
37 #include <GL/glu.h>
38
39 #include "gis-opengl.h"
40 #include "gis-util.h"
41 #include "roam.h"
42
43 // #define ROAM_DEBUG
44
45 /* Tessellation, "finding intersecting triangles" */
46 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
47 /* http://www.opengl.org/wiki/Alpha_Blending */
48
49 /***********
50  * Helpers *
51  ***********/
52 static void _set_visuals(GisOpenGL *opengl)
53 {
54         glMatrixMode(GL_MODELVIEW);
55         glLoadIdentity();
56
57         /* Camera 1 */
58         double lat, lon, elev, rx, ry, rz;
59         gis_viewer_get_location(GIS_VIEWER(opengl), &lat, &lon, &elev);
60         gis_viewer_get_rotation(GIS_VIEWER(opengl), &rx, &ry, &rz);
61         glRotatef(rx, 1, 0, 0);
62         glRotatef(rz, 0, 0, 1);
63
64         /* Lighting */
65 #ifdef ROAM_DEBUG
66         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
67         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
68 #else
69         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
70         float light_diffuse[]  = {5.0f, 5.0f, 5.0f, 1.0f};
71 #endif
72         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
73         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
74         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
75         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
76         glEnable(GL_LIGHT0);
77         glEnable(GL_LIGHTING);
78
79         float material_ambient[]  = {0.2, 0.2, 0.2, 1.0};
80         float material_diffuse[]  = {0.8, 0.8, 0.8, 1.0};
81         float material_specular[] = {0.1, 0.1, 0.1, 1.0};
82         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
83         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
84         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
85         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
86         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
87         glDisable(GL_TEXTURE_2D);
88         glDisable(GL_COLOR_MATERIAL);
89
90         /* Camera 2 */
91         glTranslatef(0, 0, -elev2rad(elev));
92         glRotatef(lat, 1, 0, 0);
93         glRotatef(-lon, 0, 1, 0);
94
95         glDisable(GL_ALPHA_TEST);
96
97         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
98         glEnable(GL_BLEND);
99
100 #ifndef ROAM_DEBUG
101         glCullFace(GL_BACK);
102         glEnable(GL_CULL_FACE);
103
104         glClearDepth(1.0);
105         glDepthFunc(GL_LEQUAL);
106         glEnable(GL_DEPTH_TEST);
107 #endif
108
109         glEnable(GL_LINE_SMOOTH);
110
111         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
112         //glShadeModel(GL_FLAT);
113
114         g_mutex_lock(opengl->sphere_lock);
115         roam_sphere_update_view(opengl->sphere);
116         g_mutex_unlock(opengl->sphere_lock);
117 }
118
119
120 /*************
121  * Callbacks *
122  *************/
123 /* The unsorted/sroted GLists are blank head nodes,
124  * This way us we can remove objects from the level just by fixing up links
125  * I.e. we don't need to do a lookup to remove an object if we have its GList */
126 struct RenderLevel {
127         GList unsorted;
128         GList sorted;
129 };
130
131 static gboolean on_configure(GisOpenGL *opengl, GdkEventConfigure *event, gpointer _)
132 {
133         g_debug("GisOpenGL: on_configure");
134
135         double width  = GTK_WIDGET(opengl)->allocation.width;
136         double height = GTK_WIDGET(opengl)->allocation.height;
137
138         /* Setup OpenGL Window */
139         glViewport(0, 0, width, height);
140         glMatrixMode(GL_PROJECTION);
141         glLoadIdentity();
142         double ang = atan(height/FOV_DIST);
143         gluPerspective(rad2deg(ang)*2, width/height, 1000, 10*EARTH_R);
144
145 #ifndef ROAM_DEBUG
146         g_mutex_lock(opengl->sphere_lock);
147         roam_sphere_update_errors(opengl->sphere);
148         g_mutex_unlock(opengl->sphere_lock);
149 #endif
150
151         return FALSE;
152 }
153
154 static void on_realize(GisOpenGL *opengl, gpointer _)
155 {
156         g_debug("GisOpenGL: on_realize");
157
158         GdkGLContext   *glcontext  = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
159         GdkGLDrawable  *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
160         if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
161                 g_assert_not_reached();
162
163         _set_visuals(opengl);
164         on_configure(opengl, NULL, NULL);
165 }
166
167 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
168 {
169         g_debug("GisOpenGL: _draw_level - level=%-4d", (int)key);
170         GisOpenGL *opengl = user_data;
171         struct RenderLevel *level = value;
172         int nsorted = 0, nunsorted = 0;
173         GList *cur = NULL;
174
175         /* Draw opaque objects without sorting */
176         glDepthMask(TRUE);
177         glClear(GL_DEPTH_BUFFER_BIT);
178         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
179                 gis_object_draw( GIS_OBJECT(cur->data), opengl);
180
181         /* Freeze depth buffer and draw transparent objects sorted */
182         /* TODO: sorting */
183         //glDepthMask(FALSE);
184         glAlphaFunc(GL_GREATER, 0.1);
185         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
186                 gis_object_draw(GIS_OBJECT(cur->data), opengl);
187
188         /* TODO: Prune empty levels */
189
190         g_debug("GisOpenGL: _draw_level - drew %d,%d objects",
191                         nunsorted, nsorted);
192         return FALSE;
193 }
194
195 static gboolean on_expose(GisOpenGL *opengl, GdkEventExpose *event, gpointer _)
196 {
197         g_debug("GisOpenGL: on_expose - begin");
198
199         glClear(GL_COLOR_BUFFER_BIT);
200
201         _set_visuals(opengl);
202 #ifdef ROAM_DEBUG
203         glColor4f(1.0, 1.0, 1.0, 1.0);
204         glLineWidth(2);
205         glDisable(GL_TEXTURE_2D);
206         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
207         roam_sphere_draw(opengl->sphere);
208         (void)_draw_level;
209         //roam_sphere_draw_normals(opengl->sphere);
210 #else
211         g_mutex_lock(opengl->objects_lock);
212         g_tree_foreach(opengl->objects, _draw_level, opengl);
213         if (opengl->wireframe) {
214                 glClear(GL_DEPTH_BUFFER_BIT);
215                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
216                 roam_sphere_draw(opengl->sphere);
217         }
218         g_mutex_unlock(opengl->objects_lock);
219 #endif
220
221         GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
222         gdk_gl_drawable_swap_buffers(gldrawable);
223
224         g_debug("GisOpenGL: on_expose - end\n");
225         return FALSE;
226 }
227
228 static gboolean on_key_press(GisOpenGL *opengl, GdkEventKey *event, gpointer _)
229 {
230         g_debug("GisOpenGL: on_key_press - key=%x, state=%x, plus=%x",
231                         event->keyval, event->state, GDK_plus);
232
233         guint kv = event->keyval;
234         /* Testing */
235         if (kv == GDK_w) {
236                 opengl->wireframe = !opengl->wireframe;
237                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
238         }
239 #ifdef ROAM_DEBUG
240         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
241         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
242         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
243         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
244         gtk_widget_queue_draw(GTK_WIDGET(opengl));
245 #endif
246         return FALSE;
247 }
248
249 static gboolean _update_errors_cb(gpointer _opengl)
250 {
251         GisOpenGL *opengl = _opengl;
252         g_mutex_lock(opengl->sphere_lock);
253         roam_sphere_update_errors(opengl->sphere);
254         g_mutex_unlock(opengl->sphere_lock);
255         opengl->ue_source = 0;
256         return FALSE;
257 }
258 static void on_view_changed(GisOpenGL *opengl,
259                 gdouble _1, gdouble _2, gdouble _3)
260 {
261         g_debug("GisOpenGL: on_view_changed");
262         _set_visuals(opengl);
263 #ifndef ROAM_DEBUG
264         if (!opengl->ue_source)
265                 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
266                                 _update_errors_cb, opengl, NULL);
267         //roam_sphere_update_errors(opengl->sphere);
268 #else
269         (void)_update_errors_cb;
270 #endif
271 }
272
273 static gboolean on_idle(GisOpenGL *opengl)
274 {
275         //g_debug("GisOpenGL: on_idle");
276         g_mutex_lock(opengl->sphere_lock);
277         if (roam_sphere_split_merge(opengl->sphere))
278                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
279         g_mutex_unlock(opengl->sphere_lock);
280         return TRUE;
281 }
282
283
284 /*********************
285  * GisViewer methods *
286  *********************/
287 /**
288  * gis_opengl_new:
289  * @plugins: the plugins store to use
290  * @prefs:   the preferences object to use
291  *
292  * Create a new OpenGL renderer.
293  *
294  * Returns: the new #GisOpenGL
295  */
296 GisViewer *gis_opengl_new(GisPlugins *plugins, GisPrefs *prefs)
297 {
298         g_debug("GisOpenGL: new");
299         GisViewer *opengl = g_object_new(GIS_TYPE_OPENGL, NULL);
300         gis_viewer_setup(opengl, plugins, prefs);
301         return opengl;
302 }
303
304 static void gis_opengl_center_position(GisViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
305 {
306         glRotatef(lon, 0, 1, 0);
307         glRotatef(-lat, 1, 0, 0);
308         glTranslatef(0, 0, elev2rad(elev));
309 }
310
311 static void gis_opengl_project(GisViewer *_opengl,
312                 gdouble lat, gdouble lon, gdouble elev,
313                 gdouble *px, gdouble *py, gdouble *pz)
314 {
315         GisOpenGL *opengl = GIS_OPENGL(_opengl);
316         gdouble x, y, z;
317         lle2xyz(lat, lon, elev, &x, &y, &z);
318         gluProject(x, y, z,
319                 opengl->sphere->view->model,
320                 opengl->sphere->view->proj,
321                 opengl->sphere->view->view,
322                 px, py, pz);
323 }
324
325 static void gis_opengl_set_height_func(GisViewer *_opengl, GisBounds *bounds,
326                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
327 {
328         GisOpenGL *opengl = GIS_OPENGL(_opengl);
329         /* TODO: get points? */
330         g_mutex_lock(opengl->sphere_lock);
331         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
332                         bounds->n, bounds->s, bounds->e, bounds->w);
333         for (GList *cur = triangles; cur; cur = cur->next) {
334                 RoamTriangle *tri = cur->data;
335                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
336                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
337                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
338                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
339                                 points[i]->height_func = height_func;
340                                 points[i]->height_data = user_data;
341                                 roam_point_update_height(points[i]);
342                         }
343                 }
344         }
345         g_list_free(triangles);
346         g_mutex_unlock(opengl->sphere_lock);
347 }
348
349 static void _gis_opengl_clear_height_func_rec(RoamTriangle *root)
350 {
351         if (!root)
352                 return;
353         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
354         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
355                 points[i]->height_func = NULL;
356                 points[i]->height_data = NULL;
357                 roam_point_update_height(points[i]);
358         }
359         _gis_opengl_clear_height_func_rec(root->kids[0]);
360         _gis_opengl_clear_height_func_rec(root->kids[1]);
361 }
362
363 static void gis_opengl_clear_height_func(GisViewer *_opengl)
364 {
365         GisOpenGL *opengl = GIS_OPENGL(_opengl);
366         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
367                 _gis_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
368 }
369
370 static gpointer gis_opengl_add(GisViewer *_opengl, GisObject *object,
371                 gint key, gboolean sort)
372 {
373         g_assert(GIS_IS_OPENGL(_opengl));
374         GisOpenGL *opengl = GIS_OPENGL(_opengl);
375         g_mutex_lock(opengl->objects_lock);
376         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
377         if (!level) {
378                 level = g_new0(struct RenderLevel, 1);
379                 g_tree_insert(opengl->objects, (gpointer)key, level);
380         }
381         GList *list = sort ? &level->sorted : &level->unsorted;
382         /* Put the link in the list */
383         GList *link = g_new0(GList, 1);
384         link->data = object;
385         link->prev = list;
386         link->next = list->next;
387         if (list->next)
388                 list->next->prev = link;
389         list->next = link;
390         g_mutex_unlock(opengl->objects_lock);
391         return link;
392 }
393
394 static GisObject *gis_opengl_remove(GisViewer *_opengl, gpointer _link)
395 {
396         g_assert(GIS_IS_OPENGL(_opengl));
397         GisOpenGL *opengl = GIS_OPENGL(_opengl);
398         g_mutex_lock(opengl->objects_lock);
399         GList *link = _link;
400         GisObject *object = link->data;
401         /* Just unlink and free it, link->prev is assured */
402         link->prev->next = link->next;
403         if (link->next)
404                 link->next->prev = link->prev;
405         g_free(link);
406         g_object_unref(object);
407         g_mutex_unlock(opengl->objects_lock);
408         return object;
409 }
410
411 /****************
412  * GObject code *
413  ****************/
414 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
415 {
416         gint a = (int)_a, b = (int)_b;
417         return a < b ? -1 :
418                a > b ?  1 : 0;
419 }
420 static void _objects_free(gpointer value)
421 {
422         struct RenderLevel *level = value;
423         if (level->sorted.next)
424                 g_list_free(level->sorted.next);
425         if (level->unsorted.next)
426                 g_list_free(level->unsorted.next);
427         g_free(level);
428 }
429
430 G_DEFINE_TYPE(GisOpenGL, gis_opengl, GIS_TYPE_VIEWER);
431 static void gis_opengl_init(GisOpenGL *opengl)
432 {
433         g_debug("GisOpenGL: init");
434         /* OpenGL setup */
435         GdkGLConfig *glconfig = gdk_gl_config_new_by_mode(
436                         GDK_GL_MODE_RGBA   | GDK_GL_MODE_DEPTH |
437                         GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
438         if (!glconfig)
439                 g_error("Failed to create glconfig");
440         if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
441                                 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
442                 g_error("GL lacks required capabilities");
443         g_object_unref(glconfig);
444
445         opengl->objects = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
446         opengl->objects_lock = g_mutex_new();
447         opengl->sphere = roam_sphere_new(opengl);
448         opengl->sphere_lock = g_mutex_new();
449
450 #ifndef ROAM_DEBUG
451         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
452         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
453 #else
454         (void)on_idle;
455         (void)_update_errors_cb;
456 #endif
457
458         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
459         g_signal_connect(opengl, "realize",          G_CALLBACK(on_realize),      NULL);
460         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
461         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
462
463         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
464
465         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
466         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
467 }
468 static void gis_opengl_dispose(GObject *_opengl)
469 {
470         g_debug("GisOpenGL: dispose");
471         GisOpenGL *opengl = GIS_OPENGL(_opengl);
472         if (opengl->sm_source[0]) {
473                 g_source_remove(opengl->sm_source[0]);
474                 opengl->sm_source[0] = 0;
475         }
476         if (opengl->sm_source[1]) {
477                 g_source_remove(opengl->sm_source[1]);
478                 opengl->sm_source[1] = 0;
479         }
480         if (opengl->ue_source) {
481                 g_source_remove(opengl->ue_source);
482                 opengl->ue_source = 0;
483         }
484         G_OBJECT_CLASS(gis_opengl_parent_class)->dispose(_opengl);
485 }
486 static void gis_opengl_finalize(GObject *_opengl)
487 {
488         g_debug("GisOpenGL: finalize");
489         GisOpenGL *opengl = GIS_OPENGL(_opengl);
490         roam_sphere_free(opengl->sphere);
491         g_tree_destroy(opengl->objects);
492         g_mutex_free(opengl->objects_lock);
493         g_mutex_free(opengl->sphere_lock);
494         G_OBJECT_CLASS(gis_opengl_parent_class)->finalize(_opengl);
495 }
496 static void gis_opengl_class_init(GisOpenGLClass *klass)
497 {
498         g_debug("GisOpenGL: class_init");
499         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
500         gobject_class->finalize = gis_opengl_finalize;
501         gobject_class->dispose = gis_opengl_dispose;
502
503         GisViewerClass *viewer_class = GIS_VIEWER_CLASS(klass);
504         viewer_class->center_position   = gis_opengl_center_position;
505         viewer_class->project           = gis_opengl_project;
506         viewer_class->clear_height_func = gis_opengl_clear_height_func;
507         viewer_class->set_height_func   = gis_opengl_set_height_func;
508         viewer_class->add               = gis_opengl_add;
509         viewer_class->remove            = gis_opengl_remove;
510 }