c4c7dacb4039fd8e3dbf7257e4e64f618aacbfc4
[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         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
451
452         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
453
454         g_signal_connect(opengl, "location-changed", G_CALLBACK(_set_projection), NULL);
455         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(_set_projection), NULL);
456
457         g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
458         g_signal_connect_after(opengl, "key-press-event",      G_CALLBACK(on_chained_event), NULL);
459         g_signal_connect_after(opengl, "key-release-event",    G_CALLBACK(on_chained_event), NULL);
460         g_signal_connect_after(opengl, "button-press-event",   G_CALLBACK(on_chained_event), NULL);
461         g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
462         g_signal_connect_after(opengl, "motion-notify-event",  G_CALLBACK(on_chained_event), NULL);
463
464         /* Re-queue resize incase configure was triggered before realize */
465         gtk_widget_queue_resize(GTK_WIDGET(opengl));
466 }
467
468 /*********************
469  * GritsViewer methods *
470  *********************/
471 /**
472  * grits_opengl_new:
473  * @plugins: the plugins store to use
474  * @prefs:   the preferences object to use
475  *
476  * Create a new OpenGL renderer.
477  *
478  * Returns: the new #GritsOpenGL
479  */
480 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
481 {
482         g_debug("GritsOpenGL: new");
483         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
484         grits_viewer_setup(opengl, plugins, prefs);
485         return opengl;
486 }
487
488 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
489 {
490         glRotatef(lon, 0, 1, 0);
491         glRotatef(-lat, 1, 0, 0);
492         glTranslatef(0, 0, elev2rad(elev));
493 }
494
495 static void grits_opengl_project(GritsViewer *_opengl,
496                 gdouble lat, gdouble lon, gdouble elev,
497                 gdouble *px, gdouble *py, gdouble *pz)
498 {
499         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
500         gdouble x, y, z;
501         lle2xyz(lat, lon, elev, &x, &y, &z);
502         gluProject(x, y, z,
503                 opengl->sphere->view->model,
504                 opengl->sphere->view->proj,
505                 opengl->sphere->view->view,
506                 px, py, pz);
507 }
508
509 static void grits_opengl_unproject(GritsViewer *_opengl,
510                 gdouble px, gdouble py, gdouble pz,
511                 gdouble *lat, gdouble *lon, gdouble *elev)
512 {
513         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
514         if (!opengl->sphere->view)
515                 return;
516         gdouble x, y, z;
517         if (pz < 0) {
518                 gfloat tmp = 0;
519                 glReadPixels(px, py, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tmp);
520                 pz = tmp;
521         }
522         pz = (pz-OVERLAY_SLICE) * (1.0/(1-OVERLAY_SLICE));
523         gluUnProject(px, py, pz,
524                 opengl->sphere->view->model,
525                 opengl->sphere->view->proj,
526                 opengl->sphere->view->view,
527                 &x, &y, &z);
528         xyz2lle(x, y, z, lat, lon, elev);
529         //g_message("GritsOpenGL: unproject - "
530         //              "%4.0lf,%4.0lf,(%5.3lf) -> "
531         //              "%8.0lf,%8.0lf,%8.0lf -> "
532         //              "%6.2lf,%7.2lf,%4.0lf",
533         //      px, py, pz, x, y, z, *lat, *lon, *elev);
534 }
535
536 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
537                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
538 {
539         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
540         /* TODO: get points? */
541         g_mutex_lock(&opengl->sphere_lock);
542         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
543                         bounds->n, bounds->s, bounds->e, bounds->w);
544         for (GList *cur = triangles; cur; cur = cur->next) {
545                 RoamTriangle *tri = cur->data;
546                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
547                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
548                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
549                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
550                                 points[i]->height_func = height_func;
551                                 points[i]->height_data = user_data;
552                                 roam_point_update_height(points[i]);
553                         }
554                 }
555         }
556         g_list_free(triangles);
557         g_mutex_unlock(&opengl->sphere_lock);
558 }
559
560 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
561 {
562         if (!root)
563                 return;
564         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
565         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
566                 points[i]->height_func = NULL;
567                 points[i]->height_data = NULL;
568                 roam_point_update_height(points[i]);
569         }
570         _grits_opengl_clear_height_func_rec(root->kids[0]);
571         _grits_opengl_clear_height_func_rec(root->kids[1]);
572 }
573
574 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
575 {
576         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
577         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
578                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
579 }
580
581 static gint _objects_find(gconstpointer a, gconstpointer b)
582 {
583         const struct RenderLevel *level = a;
584         const gint *key = b;
585         return level->num == *key ? 0 : 1;
586 }
587
588 static gint _objects_sort(gconstpointer _a, gconstpointer _b, gpointer _)
589 {
590         const struct RenderLevel *a = _a;
591         const struct RenderLevel *b = _b;
592         return a->num < b->num ? -1 :
593                a->num > b->num ?  1 : 0;
594 }
595
596 static void _objects_free(gpointer value, gpointer _)
597 {
598         struct RenderLevel *level = value;
599         if (level->sorted.next)
600                 g_list_free_full(level->sorted.next, g_object_unref);
601         if (level->unsorted.next)
602                 g_list_free_full(level->unsorted.next, g_object_unref);
603         g_free(level);
604 }
605
606 static void grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
607                 gint num, gboolean sort)
608 {
609         g_assert(GRITS_IS_OPENGL(_opengl));
610         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
611         g_mutex_lock(&opengl->objects_lock);
612         struct RenderLevel *level = NULL;
613         GList *tmp = g_queue_find_custom(opengl->objects, &num, _objects_find);
614         if (tmp) {
615                 level = tmp->data;
616         } else {
617                 level = g_new0(struct RenderLevel, 1);
618                 level->num = num;
619                 g_queue_insert_sorted(opengl->objects, level, _objects_sort, NULL);
620         }
621         GList *list = sort ? &level->sorted : &level->unsorted;
622         /* Put the link in the list */
623         GList *link = g_new0(GList, 1);
624         link->data = object;
625         link->prev = list;
626         link->next = list->next;
627         if (list->next)
628                 list->next->prev = link;
629         list->next = link;
630         object->ref = link;
631         g_object_ref(object);
632         g_mutex_unlock(&opengl->objects_lock);
633 }
634
635 void grits_opengl_remove(GritsViewer *_opengl, GritsObject *object)
636 {
637         g_assert(GRITS_IS_OPENGL(_opengl));
638         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
639         if (!object->ref)
640                 return;
641         g_mutex_lock(&opengl->objects_lock);
642         GList *link = object->ref;
643         /* Just unlink and free it, link->prev is assured */
644         link->prev->next = link->next;
645         if (link->next)
646                 link->next->prev = link->prev;
647         g_free(link);
648         object->ref = NULL;
649         g_object_unref(object);
650         g_mutex_unlock(&opengl->objects_lock);
651 }
652
653 /****************
654  * GObject code *
655  ****************/
656 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
657 static void grits_opengl_init(GritsOpenGL *opengl)
658 {
659         g_debug("GritsOpenGL: init");
660         opengl->objects = g_queue_new();
661         opengl->sphere  = roam_sphere_new(opengl);
662         g_mutex_init(&opengl->objects_lock);
663         g_mutex_init(&opengl->sphere_lock);
664         gtk_gl_enable(GTK_WIDGET(opengl));
665         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
666         g_signal_connect(opengl, "map", G_CALLBACK(on_realize), NULL);
667 }
668 static void grits_opengl_dispose(GObject *_opengl)
669 {
670         g_debug("GritsOpenGL: dispose");
671         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
672         if (opengl->objects) {
673                 GQueue *objects = opengl->objects;;
674                 opengl->objects = NULL;
675                 g_mutex_lock(&opengl->objects_lock);
676                 g_queue_foreach(objects, _objects_free, NULL);
677                 g_queue_free(objects);
678                 g_mutex_unlock(&opengl->objects_lock);
679         }
680         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
681 }
682 static void grits_opengl_finalize(GObject *_opengl)
683 {
684         g_debug("GritsOpenGL: finalize");
685         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
686         roam_sphere_free(opengl->sphere);
687         g_mutex_clear(&opengl->objects_lock);
688         g_mutex_clear(&opengl->sphere_lock);
689         gtk_gl_disable(GTK_WIDGET(opengl));
690         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
691 }
692 static void grits_opengl_class_init(GritsOpenGLClass *klass)
693 {
694         g_debug("GritsOpenGL: class_init");
695         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
696         gobject_class->finalize = grits_opengl_finalize;
697         gobject_class->dispose = grits_opengl_dispose;
698
699         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
700         viewer_class->center_position   = grits_opengl_center_position;
701         viewer_class->project           = grits_opengl_project;
702         viewer_class->unproject         = grits_opengl_unproject;
703         viewer_class->clear_height_func = grits_opengl_clear_height_func;
704         viewer_class->set_height_func   = grits_opengl_set_height_func;
705         viewer_class->add               = grits_opengl_add;
706         viewer_class->remove            = grits_opengl_remove;
707 }