]> Pileus Git - grits/blob - src/grits-opengl.c
90e830b1e30f3c1923f9a1a52758f34834f60b0b
[grits] / src / grits-opengl.c
1 /*
2  * Copyright (C) 2009-2011 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 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
36 #include "grits-opengl.h"
37 #include "grits-util.h"
38 #include "gtkgl.h"
39 #include "roam.h"
40
41 // #define ROAM_DEBUG
42
43 /* Tessellation, "finding intersecting triangles" */
44 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
45 /* http://www.opengl.org/wiki/Alpha_Blending */
46
47 /* The unsorted/sroted GLists are blank head nodes,
48  * This way us we can remove objects from the level just by fixing up links
49  * I.e. we don't need to do a lookup to remove an object if we have its GList */
50 struct RenderLevel {
51         gint  num;
52         GList unsorted;
53         GList sorted;
54 };
55
56 /***********
57  * Helpers *
58  ***********/
59 static void _set_projection(GritsOpenGL *opengl)
60 {
61         double lat, lon, elev, rx, ry, rz;
62         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
63         grits_viewer_get_rotation(GRITS_VIEWER(opengl), &rx, &ry, &rz);
64
65         /* Set projection and clipping planes */
66         glMatrixMode(GL_PROJECTION);
67         glLoadIdentity();
68
69         double width  = GTK_WIDGET(opengl)->allocation.width;
70         double height = GTK_WIDGET(opengl)->allocation.height;
71         double ang    = atan((height/2)/FOV_DIST)*2;
72         double atmos  = 100000;
73         double near   = MAX(elev*0.75 - atmos, 50); // View 100km of atmosphere
74         double far    = elev + 2*EARTH_R + atmos;   // on both sides of the earth
75
76         glViewport(0, 0, width, height);
77         gluPerspective(rad2deg(ang), width/height, near, far);
78
79         /* Setup camera and lighting */
80         glMatrixMode(GL_MODELVIEW);
81         glLoadIdentity();
82
83         /* Camera 1 */
84         glRotatef(rx, 1, 0, 0);
85         glRotatef(rz, 0, 0, 1);
86
87         /* Lighting */
88         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
89         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
90
91         /* Camera 2 */
92         glTranslatef(0, 0, -elev2rad(elev));
93         glRotatef(lat, 1, 0, 0);
94         glRotatef(-lon, 0, 1, 0);
95
96         /* Update roam view */
97         g_mutex_lock(&opengl->sphere_lock);
98         roam_sphere_update_view(opengl->sphere);
99         g_mutex_unlock(&opengl->sphere_lock);
100 }
101
102 static void _set_settings(GritsOpenGL *opengl)
103 {
104         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
105         glEnable(GL_BLEND);
106         glDisable(GL_ALPHA_TEST);
107
108         glEnable(GL_LIGHT0);
109         glEnable(GL_LIGHTING);
110
111         glEnable(GL_LINE_SMOOTH);
112
113         glDisable(GL_TEXTURE_2D);
114         glDisable(GL_COLOR_MATERIAL);
115
116         if (opengl->wireframe)
117                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
118         else
119                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
120
121         /* Lighting */
122 #ifdef ROAM_DEBUG
123         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
124         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
125 #else
126         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
127         float light_diffuse[]  = {0.8f, 0.8f, 0.8f, 1.0f};
128 #endif
129         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
130         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
131
132         /* Materials */
133         float material_ambient[]  = {1.0, 1.0, 1.0, 1.0};
134         float material_diffuse[]  = {1.0, 1.0, 1.0, 1.0};
135         float material_specular[] = {0.0, 0.0, 0.0, 1.0};
136         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
137         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
138         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
139         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
140         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
141
142 #ifdef ROAM_DEBUG
143         glColor4f(1.0, 1.0, 1.0, 1.0);
144         glLineWidth(2);
145 #else
146         glCullFace(GL_BACK);
147         glEnable(GL_CULL_FACE);
148
149         glClearDepth(1.0);
150         glDepthFunc(GL_LEQUAL);
151         glEnable(GL_DEPTH_TEST);
152 #endif
153 }
154
155 static GPtrArray *_objects_to_array(GritsOpenGL *opengl, gboolean ortho)
156 {
157         GPtrArray *array = g_ptr_array_new();
158         for (GList *i = opengl->objects->head; i; i = i->next) {
159                 struct RenderLevel *level = i->data;
160                 if ((ortho == TRUE  && level->num <  GRITS_LEVEL_HUD) ||
161                     (ortho == FALSE && level->num >= GRITS_LEVEL_HUD))
162                         continue;
163                 for (GList *j = level->unsorted.next; j; j = j->next)
164                         g_ptr_array_add(array, j->data);
165                 for (GList *j = level->sorted.next;   j; j = j->next)
166                         g_ptr_array_add(array, j->data);
167         }
168         return array;
169 }
170
171 /*************
172  * Callbacks *
173  *************/
174
175 static gint run_picking(GritsOpenGL *opengl, GdkEvent *event,
176                 GPtrArray *objects, GritsObject **top)
177 {
178         /* Setup picking buffers */
179         guint buffer[100][4] = {};
180         glSelectBuffer(G_N_ELEMENTS(buffer), (guint*)buffer);
181         if (!opengl->pickmode)
182                 glRenderMode(GL_SELECT);
183         glInitNames();
184
185         /* Render/pick objects */
186         for (guint i = 0; i < objects->len; i++) {
187                 glPushName(i);
188                 GritsObject *object = objects->pdata[i];
189                 object->state.picked = FALSE;
190                 grits_object_pick(object, opengl);
191                 glPopName();
192         }
193
194         int hits = glRenderMode(GL_RENDER);
195
196         /* Process hits */
197         for (int i = 0; i < hits; i++) {
198                 //g_debug("\tHit: %d",     i);
199                 //g_debug("\t\tcount: %d", buffer[i][0]);
200                 //g_debug("\t\tz1:    %f", (float)buffer[i][1]/0x7fffffff);
201                 //g_debug("\t\tz2:    %f", (float)buffer[i][2]/0x7fffffff);
202                 //g_debug("\t\tname:  %p", (gpointer)buffer[i][3]);
203                 guint        index  = buffer[i][3];
204                 GritsObject *object = objects->pdata[index];
205                 object->state.picked = TRUE;
206                 *top = object;
207         }
208
209         /* Notify objects of pointer movements */
210         for (guint i = 0; i < objects->len; i++) {
211                 GritsObject *object = objects->pdata[i];
212                 grits_object_set_pointer(object, event, object->state.picked);
213         }
214
215         return hits;
216 }
217
218 static gboolean run_mouse_move(GritsOpenGL *opengl, GdkEventMotion *event)
219 {
220         gdouble height = GTK_WIDGET(opengl)->allocation.height;
221         gdouble gl_x   = event->x;
222         gdouble gl_y   = height - event->y;
223         gdouble delta  = opengl->pickmode ? 200 : 2;
224
225         if (opengl->pickmode) {
226                 gtk_gl_begin(GTK_WIDGET(opengl));
227                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
228         }
229
230         /* Save matricies */
231         gdouble projection[16];
232         gint    viewport[4]; // x=0,y=0,w,h
233         glGetDoublev(GL_PROJECTION_MATRIX, projection);
234         glGetIntegerv(GL_VIEWPORT, viewport);
235         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
236         glMatrixMode(GL_PROJECTION); glPushMatrix();
237
238         g_mutex_lock(&opengl->objects_lock);
239
240         GritsObject *top = NULL;
241         GPtrArray *ortho = _objects_to_array(opengl, TRUE);
242         GPtrArray *world = _objects_to_array(opengl, FALSE);
243
244         /* Run perspective picking */
245         glMatrixMode(GL_PROJECTION); glLoadIdentity();
246         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
247         glMultMatrixd(projection);
248         gint world_hits = run_picking(opengl, (GdkEvent*)event, world, &top);
249
250         /* Run ortho picking */
251         glMatrixMode(GL_PROJECTION); glLoadIdentity();
252         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
253         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
254         glOrtho(0, viewport[2], viewport[3], 0, 1000, -1000);
255         gint ortho_hits = run_picking(opengl, (GdkEvent*)event, ortho, &top);
256
257         /* Update cursor */
258         static GdkCursor *cursor = NULL;
259         static GdkWindow *window = NULL;
260         if (!window || !cursor) {
261                 cursor = gdk_cursor_new(GDK_FLEUR);
262                 window = gtk_widget_get_window(GTK_WIDGET(opengl));
263         }
264         GdkCursor *topcursor = top && top->cursor ? top->cursor : cursor;
265         gdk_window_set_cursor(window, topcursor);
266
267         g_debug("GritsOpenGL: run_mouse_move - hits=%d/%d,%d/%d ev=%.0lf,%.0lf",
268                         world_hits, world->len, ortho_hits, ortho->len, gl_x, gl_y);
269
270         g_ptr_array_free(world, TRUE);
271         g_ptr_array_free(ortho, TRUE);
272
273         g_mutex_unlock(&opengl->objects_lock);
274
275         /* Test unproject */
276         //gdouble lat, lon, elev;
277         //grits_viewer_unproject(GRITS_VIEWER(opengl),
278         //              gl_x, gl_y, -1, &lat, &lon, &elev);
279
280         /* Cleanup */
281         glMatrixMode(GL_PROJECTION); glPopMatrix();
282         glMatrixMode(GL_MODELVIEW);  glPopMatrix();
283
284         if (opengl->pickmode)
285                 gtk_gl_end(GTK_WIDGET(opengl));
286
287         return FALSE;
288 }
289
290 static gboolean on_motion_notify(GritsOpenGL *opengl, GdkEventMotion *event, gpointer _)
291 {
292         opengl->mouse_queue = *event;
293         gtk_widget_queue_draw(GTK_WIDGET(opengl));
294         return FALSE;
295 }
296
297 static void _draw_level(gpointer _level, gpointer _opengl)
298 {
299         GritsOpenGL *opengl = _opengl;
300         struct RenderLevel *level = _level;
301
302         g_debug("GritsOpenGL: _draw_level - level=%-4d", level->num);
303         int nsorted = 0, nunsorted = 0;
304         GList *cur = NULL;
305
306         /* Configure individual levels */
307         if (level->num < GRITS_LEVEL_WORLD) {
308                 /* Disable depth for background levels */
309                 glDepthMask(FALSE);
310                 glDisable(GL_ALPHA_TEST);
311         } else if (level->num < GRITS_LEVEL_OVERLAY) {
312                 /* Enable depth and alpha for world levels */
313                 glEnable(GL_ALPHA_TEST);
314                 glAlphaFunc(GL_GREATER, 0.1);
315         } else {
316                 /* Disable depth for Overlay/HUD levels */
317                 glDepthMask(FALSE);
318         }
319
320         /* Start ortho */
321         if (level->num >= GRITS_LEVEL_HUD) {
322                 glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
323                 glMatrixMode(GL_MODELVIEW);  glPushMatrix(); glLoadIdentity();
324                 gint win_width  = GTK_WIDGET(opengl)->allocation.width;
325                 gint win_height = GTK_WIDGET(opengl)->allocation.height;
326                 glOrtho(0, win_width, win_height, 0, 1000, -1000);
327         }
328
329         /* Draw unsorted objects without depth testing,
330          * these are polygons, etc, rather than physical objects */
331         glDisable(GL_DEPTH_TEST);
332         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
333                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
334
335         /* Draw sorted objects using depth testing
336          * These are things that are actually part of the world */
337         glEnable(GL_DEPTH_TEST);
338         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
339                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
340
341         /* End ortho */
342         if (level->num >= GRITS_LEVEL_HUD) {
343                 glMatrixMode(GL_PROJECTION); glPopMatrix();
344                 glMatrixMode(GL_MODELVIEW);  glPopMatrix();
345         }
346
347         /* Leave depth buffer write enabled */
348         glDepthMask(TRUE);
349
350         /* TODO: Prune empty levels */
351
352         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
353                         nunsorted, nsorted);
354 }
355
356 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
357 {
358         g_debug("GritsOpenGL: on_expose - begin");
359
360         if (opengl->pickmode)
361                 return run_mouse_move(opengl, (GdkEventMotion*)event);
362
363         if (opengl->mouse_queue.type != GDK_NOTHING) {
364                 run_mouse_move(opengl, &opengl->mouse_queue);
365                 opengl->mouse_queue.type = GDK_NOTHING;
366         }
367
368         gtk_gl_begin(GTK_WIDGET(opengl));
369
370         _set_settings(opengl);
371         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
372
373 #ifndef ROAM_DEBUG
374         g_mutex_lock(&opengl->sphere_lock);
375         roam_sphere_update_errors(opengl->sphere);
376         roam_sphere_split_merge(opengl->sphere);
377         g_mutex_unlock(&opengl->sphere_lock);
378 #endif
379
380 #ifdef ROAM_DEBUG
381         roam_sphere_draw(opengl->sphere);
382         roam_sphere_draw_normals(opengl->sphere);
383         (void)_draw_level;
384 #else
385         g_mutex_lock(&opengl->objects_lock);
386         g_queue_foreach(opengl->objects, _draw_level, opengl);
387         g_mutex_unlock(&opengl->objects_lock);
388 #endif
389
390         gtk_gl_end(GTK_WIDGET(opengl));
391
392         g_debug("GritsOpenGL: on_expose - end\n");
393         return FALSE;
394 }
395
396 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
397 {
398         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
399                         event->keyval, event->state, GDK_plus);
400
401         guint kv = event->keyval;
402         /* Testing */
403         if (kv == GDK_w) {
404                 opengl->wireframe = !opengl->wireframe;
405                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
406         }
407         if (kv == GDK_p) {
408                 opengl->pickmode = !opengl->pickmode;
409                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
410         }
411 #ifdef ROAM_DEBUG
412         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
413         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
414         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
415         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
416         gtk_widget_queue_draw(GTK_WIDGET(opengl));
417 #endif
418         return FALSE;
419 }
420
421 static gboolean on_chained_event(GritsOpenGL *opengl, GdkEvent *event, gpointer _)
422 {
423         for (GList *i = opengl->objects->tail; i; i = i->prev) {
424                 struct RenderLevel *level = i->data;
425                 for (GList *j = level->unsorted.next; j; j = j->next)
426                         if (grits_object_event(j->data, event))
427                                 return TRUE;
428                 for (GList *j = level->sorted.next;   j; j = j->next)
429                         if (grits_object_event(j->data, event))
430                                 return TRUE;
431         }
432         return FALSE;
433 }
434
435 static void on_realize(GritsOpenGL *opengl, gpointer _)
436 {
437         g_debug("GritsOpenGL: on_realize");
438         gtk_gl_begin(GTK_WIDGET(opengl));
439
440         /* Connect signals and idle functions now that opengl is fully initialized */
441         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
442         g_signal_connect(opengl, "configure-event",  G_CALLBACK(_set_projection), NULL);
443         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
444
445         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
446
447         g_signal_connect(opengl, "location-changed", G_CALLBACK(_set_projection), NULL);
448         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(_set_projection), NULL);
449
450         g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
451         g_signal_connect_after(opengl, "key-press-event",      G_CALLBACK(on_chained_event), NULL);
452         g_signal_connect_after(opengl, "key-release-event",    G_CALLBACK(on_chained_event), NULL);
453         g_signal_connect_after(opengl, "button-press-event",   G_CALLBACK(on_chained_event), NULL);
454         g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
455         g_signal_connect_after(opengl, "motion-notify-event",  G_CALLBACK(on_chained_event), NULL);
456
457         /* Re-queue resize incase configure was triggered before realize */
458         gtk_widget_queue_resize(GTK_WIDGET(opengl));
459 }
460
461 /*********************
462  * GritsViewer methods *
463  *********************/
464 /**
465  * grits_opengl_new:
466  * @plugins: the plugins store to use
467  * @prefs:   the preferences object to use
468  *
469  * Create a new OpenGL renderer.
470  *
471  * Returns: the new #GritsOpenGL
472  */
473 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
474 {
475         g_debug("GritsOpenGL: new");
476         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
477         grits_viewer_setup(opengl, plugins, prefs);
478         return opengl;
479 }
480
481 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
482 {
483         glRotatef(lon, 0, 1, 0);
484         glRotatef(-lat, 1, 0, 0);
485         glTranslatef(0, 0, elev2rad(elev));
486 }
487
488 static void grits_opengl_project(GritsViewer *_opengl,
489                 gdouble lat, gdouble lon, gdouble elev,
490                 gdouble *px, gdouble *py, gdouble *pz)
491 {
492         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
493         gdouble x, y, z;
494         lle2xyz(lat, lon, elev, &x, &y, &z);
495         gluProject(x, y, z,
496                 opengl->sphere->view->model,
497                 opengl->sphere->view->proj,
498                 opengl->sphere->view->view,
499                 px, py, pz);
500 }
501
502 static void grits_opengl_unproject(GritsViewer *_opengl,
503                 gdouble px, gdouble py, gdouble pz,
504                 gdouble *lat, gdouble *lon, gdouble *elev)
505 {
506         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
507         if (!opengl->sphere->view)
508                 return;
509         gdouble x, y, z;
510         if (pz < 0) {
511                 gfloat tmp = 0;
512                 glReadPixels(px, py, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tmp);
513                 pz = tmp;
514         }
515         gluUnProject(px, py, pz,
516                 opengl->sphere->view->model,
517                 opengl->sphere->view->proj,
518                 opengl->sphere->view->view,
519                 &x, &y, &z);
520         xyz2lle(x, y, z, lat, lon, elev);
521         //g_message("GritsOpenGL: unproject - "
522         //              "%4.0lf,%4.0lf,(%5.3lf) -> "
523         //              "%8.0lf,%8.0lf,%8.0lf -> "
524         //              "%6.2lf,%7.2lf,%4.0lf",
525         //      px, py, pz, x, y, z, *lat, *lon, *elev);
526 }
527
528 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
529                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
530 {
531         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
532         /* TODO: get points? */
533         g_mutex_lock(&opengl->sphere_lock);
534         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
535                         bounds->n, bounds->s, bounds->e, bounds->w);
536         for (GList *cur = triangles; cur; cur = cur->next) {
537                 RoamTriangle *tri = cur->data;
538                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
539                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
540                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
541                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
542                                 points[i]->height_func = height_func;
543                                 points[i]->height_data = user_data;
544                                 roam_point_update_height(points[i]);
545                         }
546                 }
547         }
548         g_list_free(triangles);
549         g_mutex_unlock(&opengl->sphere_lock);
550 }
551
552 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
553 {
554         if (!root)
555                 return;
556         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
557         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
558                 points[i]->height_func = NULL;
559                 points[i]->height_data = NULL;
560                 roam_point_update_height(points[i]);
561         }
562         _grits_opengl_clear_height_func_rec(root->kids[0]);
563         _grits_opengl_clear_height_func_rec(root->kids[1]);
564 }
565
566 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
567 {
568         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
569         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
570                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
571 }
572
573 static gint _objects_find(gconstpointer a, gconstpointer b)
574 {
575         const struct RenderLevel *level = a;
576         const gint *key = b;
577         return level->num == *key ? 0 : 1;
578 }
579
580 static gint _objects_sort(gconstpointer _a, gconstpointer _b, gpointer _)
581 {
582         const struct RenderLevel *a = _a;
583         const struct RenderLevel *b = _b;
584         return a->num < b->num ? -1 :
585                a->num > b->num ?  1 : 0;
586 }
587
588 static void _objects_free(gpointer value, gpointer _)
589 {
590         struct RenderLevel *level = value;
591         if (level->sorted.next)
592                 g_list_free_full(level->sorted.next, g_object_unref);
593         if (level->unsorted.next)
594                 g_list_free_full(level->unsorted.next, g_object_unref);
595         g_free(level);
596 }
597
598 static void grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
599                 gint num, gboolean sort)
600 {
601         g_assert(GRITS_IS_OPENGL(_opengl));
602         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
603         g_mutex_lock(&opengl->objects_lock);
604         struct RenderLevel *level = NULL;
605         GList *tmp = g_queue_find_custom(opengl->objects, &num, _objects_find);
606         if (tmp) {
607                 level = tmp->data;
608         } else {
609                 level = g_new0(struct RenderLevel, 1);
610                 level->num = num;
611                 g_queue_insert_sorted(opengl->objects, level, _objects_sort, NULL);
612         }
613         GList *list = sort ? &level->sorted : &level->unsorted;
614         /* Put the link in the list */
615         GList *link = g_new0(GList, 1);
616         link->data = object;
617         link->prev = list;
618         link->next = list->next;
619         if (list->next)
620                 list->next->prev = link;
621         list->next = link;
622         object->ref = link;
623         g_object_ref(object);
624         g_mutex_unlock(&opengl->objects_lock);
625 }
626
627 void grits_opengl_remove(GritsViewer *_opengl, GritsObject *object)
628 {
629         g_assert(GRITS_IS_OPENGL(_opengl));
630         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
631         if (!object->ref)
632                 return;
633         g_mutex_lock(&opengl->objects_lock);
634         GList *link = object->ref;
635         /* Just unlink and free it, link->prev is assured */
636         link->prev->next = link->next;
637         if (link->next)
638                 link->next->prev = link->prev;
639         g_free(link);
640         object->ref = NULL;
641         g_object_unref(object);
642         g_mutex_unlock(&opengl->objects_lock);
643 }
644
645 /****************
646  * GObject code *
647  ****************/
648 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
649 static void grits_opengl_init(GritsOpenGL *opengl)
650 {
651         g_debug("GritsOpenGL: init");
652         opengl->objects = g_queue_new();
653         opengl->sphere  = roam_sphere_new(opengl);
654         g_mutex_init(&opengl->objects_lock);
655         g_mutex_init(&opengl->sphere_lock);
656         gtk_gl_enable(GTK_WIDGET(opengl));
657         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
658         g_signal_connect(opengl, "map", G_CALLBACK(on_realize), NULL);
659 }
660 static void grits_opengl_dispose(GObject *_opengl)
661 {
662         g_debug("GritsOpenGL: dispose");
663         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
664         if (opengl->objects) {
665                 GQueue *objects = opengl->objects;;
666                 opengl->objects = NULL;
667                 g_mutex_lock(&opengl->objects_lock);
668                 g_queue_foreach(objects, _objects_free, NULL);
669                 g_queue_free(objects);
670                 g_mutex_unlock(&opengl->objects_lock);
671         }
672         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
673 }
674 static void grits_opengl_finalize(GObject *_opengl)
675 {
676         g_debug("GritsOpenGL: finalize");
677         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
678         roam_sphere_free(opengl->sphere);
679         g_mutex_clear(&opengl->objects_lock);
680         g_mutex_clear(&opengl->sphere_lock);
681         gtk_gl_disable(GTK_WIDGET(opengl));
682         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
683 }
684 static void grits_opengl_class_init(GritsOpenGLClass *klass)
685 {
686         g_debug("GritsOpenGL: class_init");
687         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
688         gobject_class->finalize = grits_opengl_finalize;
689         gobject_class->dispose = grits_opengl_dispose;
690
691         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
692         viewer_class->center_position   = grits_opengl_center_position;
693         viewer_class->project           = grits_opengl_project;
694         viewer_class->unproject         = grits_opengl_unproject;
695         viewer_class->clear_height_func = grits_opengl_clear_height_func;
696         viewer_class->set_height_func   = grits_opengl_set_height_func;
697         viewer_class->add               = grits_opengl_add;
698         viewer_class->remove            = grits_opengl_remove;
699 }