]> Pileus Git - grits/blob - src/grits-opengl.c
Tighten up locking to allow for nested objects
[grits] / src / grits-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:grits-opengl
20  * @short_description: OpenGL based virtual globe
21  *
22  * #GritsOpenGL is the core rendering engine used by grits. Theoretically other
23  * renderers could be writte, but they have not been. GritsOpenGL uses the ROAM
24  * algorithm for updating surface mesh the planet. The only thing GritsOpenGL
25  * can actually render on it's own is a wireframe of a sphere.
26  *
27  * GritsOpenGL 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 "grits-opengl.h"
40 #include "grits-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(GritsOpenGL *opengl)
53 {
54         glMatrixMode(GL_MODELVIEW);
55         glLoadIdentity();
56
57         /* Camera 1 */
58         double lat, lon, elev, rx, ry, rz;
59         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
60         grits_viewer_get_rotation(GRITS_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[]  = {0.8f, 0.8f, 0.8f, 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[]  = {1.0, 1.0, 1.0, 1.0};
80         float material_diffuse[]  = {1.0, 1.0, 1.0, 1.0};
81         float material_specular[] = {0.0, 0.0, 0.0, 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(GritsOpenGL *opengl, GdkEventConfigure *event, gpointer _)
132 {
133         g_debug("GritsOpenGL: 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 gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
155 {
156         g_debug("GritsOpenGL: _draw_level - level=%-4d", (int)key);
157         GritsOpenGL *opengl = user_data;
158         struct RenderLevel *level = value;
159         int nsorted = 0, nunsorted = 0;
160         GList *cur = NULL;
161
162         /* Draw opaque objects without sorting */
163         glDepthMask(TRUE);
164         glClear(GL_DEPTH_BUFFER_BIT);
165         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
166                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
167
168         /* Freeze depth buffer and draw transparent objects sorted */
169         /* TODO: sorting */
170         //glDepthMask(FALSE);
171         glAlphaFunc(GL_GREATER, 0.1);
172         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
173                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
174
175         /* TODO: Prune empty levels */
176
177         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
178                         nunsorted, nsorted);
179         return FALSE;
180 }
181
182 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
183 {
184         g_debug("GritsOpenGL: on_expose - begin");
185
186         glClear(GL_COLOR_BUFFER_BIT);
187
188         _set_visuals(opengl);
189 #ifdef ROAM_DEBUG
190         glColor4f(1.0, 1.0, 1.0, 1.0);
191         glLineWidth(2);
192         glDisable(GL_TEXTURE_2D);
193         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
194         roam_sphere_draw(opengl->sphere);
195         (void)_draw_level;
196         //roam_sphere_draw_normals(opengl->sphere);
197 #else
198         g_mutex_lock(opengl->objects_lock);
199         g_tree_foreach(opengl->objects, _draw_level, opengl);
200         if (opengl->wireframe) {
201                 glClear(GL_DEPTH_BUFFER_BIT);
202                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
203                 roam_sphere_draw(opengl->sphere);
204                 g_tree_foreach(opengl->objects, _draw_level, opengl);
205         }
206         g_mutex_unlock(opengl->objects_lock);
207 #endif
208
209         GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
210         gdk_gl_drawable_swap_buffers(gldrawable);
211
212         g_debug("GritsOpenGL: on_expose - end\n");
213         return FALSE;
214 }
215
216 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
217 {
218         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
219                         event->keyval, event->state, GDK_plus);
220
221         guint kv = event->keyval;
222         /* Testing */
223         if (kv == GDK_w) {
224                 opengl->wireframe = !opengl->wireframe;
225                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
226         }
227 #ifdef ROAM_DEBUG
228         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
229         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
230         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
231         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
232         gtk_widget_queue_draw(GTK_WIDGET(opengl));
233 #endif
234         return FALSE;
235 }
236
237 static gboolean _update_errors_cb(gpointer _opengl)
238 {
239         GritsOpenGL *opengl = _opengl;
240         g_mutex_lock(opengl->sphere_lock);
241         roam_sphere_update_errors(opengl->sphere);
242         g_mutex_unlock(opengl->sphere_lock);
243         opengl->ue_source = 0;
244         return FALSE;
245 }
246 static void on_view_changed(GritsOpenGL *opengl,
247                 gdouble _1, gdouble _2, gdouble _3)
248 {
249         g_debug("GritsOpenGL: on_view_changed");
250         _set_visuals(opengl);
251 #ifndef ROAM_DEBUG
252         if (!opengl->ue_source)
253                 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
254                                 _update_errors_cb, opengl, NULL);
255         //roam_sphere_update_errors(opengl->sphere);
256 #else
257         (void)_update_errors_cb;
258 #endif
259 }
260
261 static gboolean on_idle(GritsOpenGL *opengl)
262 {
263         //g_debug("GritsOpenGL: on_idle");
264         g_mutex_lock(opengl->sphere_lock);
265         if (roam_sphere_split_merge(opengl->sphere))
266                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
267         g_mutex_unlock(opengl->sphere_lock);
268         return TRUE;
269 }
270
271 static void on_realize(GritsOpenGL *opengl, gpointer _)
272 {
273         g_debug("GritsOpenGL: on_realize");
274
275         /* Start OpenGL */
276         GdkGLContext   *glcontext  = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
277         GdkGLDrawable  *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
278         if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
279                 g_assert_not_reached();
280
281         /* Connect signals and idle functions now that opengl is fully initialized */
282         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
283         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
284         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
285
286         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
287
288         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
289         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
290
291 #ifndef ROAM_DEBUG
292         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
293         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
294 #else
295         (void)on_idle;
296         (void)_update_errors_cb;
297 #endif
298
299         /* Re-queue resize incase configure was triggered before realize */
300         gtk_widget_queue_resize(GTK_WIDGET(opengl));
301 }
302
303 /*********************
304  * GritsViewer methods *
305  *********************/
306 /**
307  * grits_opengl_new:
308  * @plugins: the plugins store to use
309  * @prefs:   the preferences object to use
310  *
311  * Create a new OpenGL renderer.
312  *
313  * Returns: the new #GritsOpenGL
314  */
315 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
316 {
317         g_debug("GritsOpenGL: new");
318         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
319         grits_viewer_setup(opengl, plugins, prefs);
320         return opengl;
321 }
322
323 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
324 {
325         glRotatef(lon, 0, 1, 0);
326         glRotatef(-lat, 1, 0, 0);
327         glTranslatef(0, 0, elev2rad(elev));
328 }
329
330 static void grits_opengl_project(GritsViewer *_opengl,
331                 gdouble lat, gdouble lon, gdouble elev,
332                 gdouble *px, gdouble *py, gdouble *pz)
333 {
334         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
335         gdouble x, y, z;
336         lle2xyz(lat, lon, elev, &x, &y, &z);
337         gluProject(x, y, z,
338                 opengl->sphere->view->model,
339                 opengl->sphere->view->proj,
340                 opengl->sphere->view->view,
341                 px, py, pz);
342 }
343
344 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
345                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
346 {
347         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
348         /* TODO: get points? */
349         g_mutex_lock(opengl->sphere_lock);
350         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
351                         bounds->n, bounds->s, bounds->e, bounds->w);
352         for (GList *cur = triangles; cur; cur = cur->next) {
353                 RoamTriangle *tri = cur->data;
354                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
355                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
356                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
357                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
358                                 points[i]->height_func = height_func;
359                                 points[i]->height_data = user_data;
360                                 roam_point_update_height(points[i]);
361                         }
362                 }
363         }
364         g_list_free(triangles);
365         g_mutex_unlock(opengl->sphere_lock);
366 }
367
368 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
369 {
370         if (!root)
371                 return;
372         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
373         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
374                 points[i]->height_func = NULL;
375                 points[i]->height_data = NULL;
376                 roam_point_update_height(points[i]);
377         }
378         _grits_opengl_clear_height_func_rec(root->kids[0]);
379         _grits_opengl_clear_height_func_rec(root->kids[1]);
380 }
381
382 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
383 {
384         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
385         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
386                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
387 }
388
389 static gpointer grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
390                 gint key, gboolean sort)
391 {
392         g_assert(GRITS_IS_OPENGL(_opengl));
393         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
394         g_mutex_lock(opengl->objects_lock);
395         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
396         if (!level) {
397                 level = g_new0(struct RenderLevel, 1);
398                 g_tree_insert(opengl->objects, (gpointer)key, level);
399         }
400         GList *list = sort ? &level->sorted : &level->unsorted;
401         /* Put the link in the list */
402         GList *link = g_new0(GList, 1);
403         link->data = object;
404         link->prev = list;
405         link->next = list->next;
406         if (list->next)
407                 list->next->prev = link;
408         list->next = link;
409         g_mutex_unlock(opengl->objects_lock);
410         return link;
411 }
412
413 static GritsObject *grits_opengl_remove(GritsViewer *_opengl, gpointer _link)
414 {
415         g_assert(GRITS_IS_OPENGL(_opengl));
416         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
417         GList *link = _link;
418         g_mutex_lock(opengl->objects_lock);
419         GritsObject *object = link->data;
420         /* Just unlink and free it, link->prev is assured */
421         link->prev->next = link->next;
422         if (link->next)
423                 link->next->prev = link->prev;
424         g_mutex_unlock(opengl->objects_lock);
425         g_free(link);
426         g_object_unref(object);
427         return object;
428 }
429
430 /****************
431  * GObject code *
432  ****************/
433 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
434 {
435         gint a = (int)_a, b = (int)_b;
436         return a < b ? -1 :
437                a > b ?  1 : 0;
438 }
439 static void _objects_free(gpointer value)
440 {
441         struct RenderLevel *level = value;
442         if (level->sorted.next)
443                 g_list_free(level->sorted.next);
444         if (level->unsorted.next)
445                 g_list_free(level->unsorted.next);
446         g_free(level);
447 }
448
449 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
450 static void grits_opengl_init(GritsOpenGL *opengl)
451 {
452         g_debug("GritsOpenGL: init");
453         opengl->objects      = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
454         opengl->objects_lock = g_mutex_new();
455         opengl->sphere       = roam_sphere_new(opengl);
456         opengl->sphere_lock  = g_mutex_new();
457
458         /* Set OpenGL before "realize" */
459         GdkGLConfig *glconfig = gdk_gl_config_new_by_mode(
460                         GDK_GL_MODE_RGBA   | GDK_GL_MODE_DEPTH |
461                         GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
462         if (!glconfig)
463                 g_error("Failed to create glconfig");
464         if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
465                                 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
466                 g_error("GL lacks required capabilities");
467         g_object_unref(glconfig);
468
469         /* Finish OpenGL init after it's realized */
470         g_signal_connect(opengl, "realize", G_CALLBACK(on_realize), NULL);
471 }
472 static void grits_opengl_dispose(GObject *_opengl)
473 {
474         g_debug("GritsOpenGL: dispose");
475         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
476         if (opengl->sm_source[0]) {
477                 g_source_remove(opengl->sm_source[0]);
478                 opengl->sm_source[0] = 0;
479         }
480         if (opengl->sm_source[1]) {
481                 g_source_remove(opengl->sm_source[1]);
482                 opengl->sm_source[1] = 0;
483         }
484         if (opengl->ue_source) {
485                 g_source_remove(opengl->ue_source);
486                 opengl->ue_source = 0;
487         }
488         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
489 }
490 static void grits_opengl_finalize(GObject *_opengl)
491 {
492         g_debug("GritsOpenGL: finalize");
493         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
494         roam_sphere_free(opengl->sphere);
495         g_tree_destroy(opengl->objects);
496         g_mutex_free(opengl->objects_lock);
497         g_mutex_free(opengl->sphere_lock);
498         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
499 }
500 static void grits_opengl_class_init(GritsOpenGLClass *klass)
501 {
502         g_debug("GritsOpenGL: class_init");
503         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
504         gobject_class->finalize = grits_opengl_finalize;
505         gobject_class->dispose = grits_opengl_dispose;
506
507         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
508         viewer_class->center_position   = grits_opengl_center_position;
509         viewer_class->project           = grits_opengl_project;
510         viewer_class->clear_height_func = grits_opengl_clear_height_func;
511         viewer_class->set_height_func   = grits_opengl_set_height_func;
512         viewer_class->add               = grits_opengl_add;
513         viewer_class->remove            = grits_opengl_remove;
514 }