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