]> Pileus Git - grits/blob - src/gis-opengl.c
08babe50b8617e77365cf45df64e91d5a42160b5
[grits] / src / gis-opengl.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /* Tessellation, "finding intersecting triangles" */
19 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
20 /* http://www.opengl.org/wiki/Alpha_Blending */
21
22 #include <config.h>
23 #include <math.h>
24 #include <string.h>
25 #include <gdk/gdkkeysyms.h>
26 #include <gtk/gtk.h>
27 #include <gtk/gtkgl.h>
28 #include <GL/gl.h>
29 #include <GL/glu.h>
30
31 #include "gis-opengl.h"
32 #include "gis-util.h"
33 #include "roam.h"
34
35 #include "objects/gis-object.h"
36 #include "objects/gis-marker.h"
37 #include "objects/gis-callback.h"
38
39 #define FOV_DIST   2000.0
40 #define MPPX(dist) (4*dist/FOV_DIST)
41
42 // #define ROAM_DEBUG
43
44 /***********
45  * Helpers *
46  ***********/
47 static void _set_visuals(GisOpenGL *opengl)
48 {
49         glMatrixMode(GL_MODELVIEW);
50         glLoadIdentity();
51
52         /* Camera 1 */
53         double lat, lon, elev, rx, ry, rz;
54         gis_viewer_get_location(GIS_VIEWER(opengl), &lat, &lon, &elev);
55         gis_viewer_get_rotation(GIS_VIEWER(opengl), &rx, &ry, &rz);
56         glRotatef(rx, 1, 0, 0);
57         glRotatef(rz, 0, 0, 1);
58
59         /* Lighting */
60 #ifdef ROAM_DEBUG
61         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
62         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
63 #else
64         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
65         float light_diffuse[]  = {5.0f, 5.0f, 5.0f, 1.0f};
66 #endif
67         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
68         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
69         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
70         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
71         glEnable(GL_LIGHT0);
72         glEnable(GL_LIGHTING);
73
74         float material_ambient[]  = {0.2, 0.2, 0.2, 1.0};
75         float material_diffuse[]  = {0.8, 0.8, 0.8, 1.0};
76         float material_specular[] = {0.1, 0.1, 0.1, 1.0};
77         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
78         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
79         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
80         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
81         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
82         glDisable(GL_TEXTURE_2D);
83         glDisable(GL_COLOR_MATERIAL);
84
85         /* Camera 2 */
86         glTranslatef(0, 0, -elev2rad(elev));
87         glRotatef(lat, 1, 0, 0);
88         glRotatef(-lon, 0, 1, 0);
89
90         glDisable(GL_ALPHA_TEST);
91
92         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
93         glEnable(GL_BLEND);
94
95 #ifndef ROAM_DEBUG
96         glCullFace(GL_BACK);
97         glEnable(GL_CULL_FACE);
98 #endif
99
100         glClearDepth(1.0);
101         glDepthFunc(GL_LEQUAL);
102         glEnable(GL_DEPTH_TEST);
103
104         glEnable(GL_LINE_SMOOTH);
105
106         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
107         //glShadeModel(GL_FLAT);
108
109         roam_sphere_update_view(opengl->sphere);
110 }
111
112
113 /********************
114  * Object handleing *
115  ********************/
116 static void _draw_tile(GisOpenGL *opengl, GisTile *tile)
117 {
118         if (!tile || !tile->data)
119                 return;
120         GList *triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
121                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
122         if (!triangles)
123                 g_warning("GisOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
124                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
125         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
126         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
127         for (GList *cur = triangles; cur; cur = cur->next) {
128                 RoamTriangle *tri = cur->data;
129
130                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
131                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
132
133                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
134                         if (lon[0] > 90) lon[0] -= 360;
135                         if (lon[1] > 90) lon[1] -= 360;
136                         if (lon[2] > 90) lon[2] -= 360;
137                 }
138
139                 gdouble n = tile->edge.n;
140                 gdouble s = tile->edge.s;
141                 gdouble e = tile->edge.e;
142                 gdouble w = tile->edge.w;
143
144                 gdouble londist = e - w;
145                 gdouble latdist = n - s;
146
147                 gdouble xy[3][2] = {
148                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
149                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
150                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
151                 };
152
153                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
154                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
155                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
156                 //      g_message("w,e=%4.f,%4.f   "
157                 //                "lat,lon,x,y="
158                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
159                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
160                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
161                 //              w,e,
162                 //              lat[0], lon[0], xy[0][0], xy[0][1],
163                 //              lat[1], lon[1], xy[1][0], xy[1][1],
164                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
165
166                 /* Fix poles */
167                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
168                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
169                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
170
171                 glEnable(GL_TEXTURE_2D);
172                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
173                 glBegin(GL_TRIANGLES);
174                 glNormal3dv(tri->p.r->norm); glTexCoord2dv(xy[0]); glVertex3dv((double*)tri->p.r);
175                 glNormal3dv(tri->p.m->norm); glTexCoord2dv(xy[1]); glVertex3dv((double*)tri->p.m);
176                 glNormal3dv(tri->p.l->norm); glTexCoord2dv(xy[2]); glVertex3dv((double*)tri->p.l);
177                 glEnd();
178         }
179         g_list_free(triangles);
180 }
181
182 static void _draw_tiles(GisOpenGL *opengl, GisTile *tile)
183 {
184         /* Only draw children if possible */
185         gboolean has_children = TRUE;
186         GisTile *child;
187         gis_tile_foreach(tile, child)
188                 if (!child || !child->data)
189                         has_children = FALSE;
190         if (has_children)
191                 /* Only draw children */
192                 gis_tile_foreach(tile, child)
193                         _draw_tiles(opengl, child);
194         else
195                 /* No children, draw this tile */
196                 _draw_tile(opengl, tile);
197 }
198
199 static void _draw_marker(GisOpenGL *opengl, GisMarker *marker)
200 {
201         GisPoint *point = gis_object_center(GIS_OBJECT(marker));
202         gdouble px, py, pz;
203         gis_viewer_project(GIS_VIEWER(opengl),
204                         point->lat, point->lon, point->elev,
205                         &px, &py, &pz);
206         if (pz > 1)
207                 return;
208
209         //g_debug("GisOpenGL: draw_marker - %s pz=%f ", marker->label, pz);
210
211         cairo_surface_t *surface = cairo_get_target(marker->cairo);
212         gdouble width  = cairo_image_surface_get_width(surface);
213         gdouble height = cairo_image_surface_get_height(surface);
214
215         glMatrixMode(GL_PROJECTION); glLoadIdentity();
216         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
217         glOrtho(0, GTK_WIDGET(opengl)->allocation.width,
218                 0, GTK_WIDGET(opengl)->allocation.height, -1, 1);
219         glTranslated(px - marker->xoff,
220                      py - marker->yoff, 0);
221
222         glDisable(GL_LIGHTING);
223         glDisable(GL_COLOR_MATERIAL);
224         glDisable(GL_DEPTH_TEST);
225         glEnable(GL_TEXTURE_2D);
226         glBindTexture(GL_TEXTURE_2D, marker->tex);
227         glBegin(GL_QUADS);
228         glTexCoord2f(1, 1); glVertex3f(width, 0     , 0);
229         glTexCoord2f(1, 0); glVertex3f(width, height, 0);
230         glTexCoord2f(0, 0); glVertex3f(0    , height, 0);
231         glTexCoord2f(0, 1); glVertex3f(0    , 0     , 0);
232         glEnd();
233 }
234
235 static void _draw_callback(GisOpenGL *opengl, GisCallback *callback)
236 {
237         callback->callback(callback, callback->user_data);
238 }
239
240 static void _draw_object(GisOpenGL *opengl, GisObject *object)
241 {
242         //g_debug("GisOpenGL: draw_object");
243         /* Skip out of range objects */
244         if (object->lod > 0) {
245                 gdouble eye[3], obj[3];
246                 gis_viewer_get_location(GIS_VIEWER(opengl), &eye[0], &eye[1], &eye[2]);
247                 lle2xyz(eye[0], eye[1], eye[2], &eye[0], &eye[1], &eye[2]);
248                 lle2xyz(object->center.lat, object->center.lon, object->center.elev,
249                         &obj[0], &obj[1], &obj[2]);
250                 gdouble dist = distd(obj, eye);
251                 if (object->lod < dist)
252                         return;
253         }
254
255         /* Draw */
256         glMatrixMode(GL_PROJECTION); glPushMatrix();
257         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
258         glPushAttrib(GL_ALL_ATTRIB_BITS);
259         if (GIS_IS_MARKER(object)) {
260                 _draw_marker(opengl, GIS_MARKER(object));
261         } else if (GIS_IS_CALLBACK(object)) {
262                 _draw_callback(opengl, GIS_CALLBACK(object));
263         } else if (GIS_IS_TILE(object)) {
264                 _draw_tiles(opengl, GIS_TILE(object));
265         }
266         glPopAttrib();
267         glMatrixMode(GL_PROJECTION); glPopMatrix();
268         glMatrixMode(GL_MODELVIEW);  glPopMatrix();
269 }
270
271 static void _load_object(GisOpenGL *opengl, GisObject *object)
272 {
273         g_debug("GisOpenGL: load_object");
274         if (GIS_IS_MARKER(object)) {
275                 GisMarker *marker = GIS_MARKER(object);
276                 cairo_surface_t *surface = cairo_get_target(marker->cairo);
277                 gdouble width  = cairo_image_surface_get_width(surface);
278                 gdouble height = cairo_image_surface_get_height(surface);
279
280                 glEnable(GL_TEXTURE_2D);
281                 glGenTextures(1, &marker->tex);
282                 glBindTexture(GL_TEXTURE_2D, marker->tex);
283
284                 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
285                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
286                 glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
287                                 cairo_image_surface_get_data(surface));
288                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
289                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
290                 g_debug("load_texture: %d", marker->tex);
291         }
292 }
293
294 static void _unload_object(GisOpenGL *opengl, GisObject *object)
295 {
296         g_debug("GisOpenGL: unload_object");
297         if (GIS_IS_MARKER(object)) {
298                 GisMarker *marker = GIS_MARKER(object);
299                 glDeleteTextures(1, &marker->tex);
300         }
301 }
302
303
304 /*************
305  * Callbacks *
306  *************/
307 /* The unsorted/sroted GLists are blank head nodes,
308  * This way us we can remove objects from the level just by fixing up links
309  * I.e. we don't need to do a lookup to remove an object if we have its GList */
310 struct RenderLevel {
311         GList unsorted;
312         GList sorted;
313 };
314
315 static void on_realize(GisOpenGL *opengl, gpointer _)
316 {
317         g_debug("GisOpenGL: on_realize");
318
319         GdkGLContext   *glcontext  = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
320         GdkGLDrawable  *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
321         if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
322                 g_assert_not_reached();
323
324         _set_visuals(opengl);
325         g_mutex_lock(opengl->sphere_lock);
326         roam_sphere_update_errors(opengl->sphere);
327         g_mutex_unlock(opengl->sphere_lock);
328 }
329
330 static gboolean on_configure(GisOpenGL *opengl, GdkEventConfigure *event, gpointer _)
331 {
332         g_debug("GisOpenGL: on_configure");
333
334         double width  = GTK_WIDGET(opengl)->allocation.width;
335         double height = GTK_WIDGET(opengl)->allocation.height;
336
337         /* Setup OpenGL Window */
338         glViewport(0, 0, width, height);
339         glMatrixMode(GL_PROJECTION);
340         glLoadIdentity();
341         double ang = atan(height/FOV_DIST);
342         gluPerspective(rad2deg(ang)*2, width/height, 1, 10*EARTH_R);
343
344 #ifndef ROAM_DEBUG
345         g_mutex_lock(opengl->sphere_lock);
346         roam_sphere_update_errors(opengl->sphere);
347         g_mutex_unlock(opengl->sphere_lock);
348 #endif
349
350         return FALSE;
351 }
352
353 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
354 {
355         g_debug("GisOpenGL: _draw_level - level=%-4d", (int)key);
356         GisOpenGL *opengl = user_data;
357         struct RenderLevel *level = value;
358         int nsorted = 0, nunsorted = 0;
359         GList *cur = NULL;
360
361         /* Draw opaque objects without sorting */
362         glDepthMask(TRUE);
363         glClear(GL_DEPTH_BUFFER_BIT);
364         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
365                 _draw_object(opengl, GIS_OBJECT(cur->data));
366
367         /* Freeze depth buffer and draw transparent objects sorted */
368         /* TODO: sorting */
369         //glDepthMask(FALSE);
370         glAlphaFunc(GL_GREATER, 0.1);
371         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
372                 _draw_object(opengl, GIS_OBJECT(cur->data));
373
374         /* TODO: Prune empty levels */
375
376         g_debug("GisOpenGL: _draw_level - drew %d,%d objects",
377                         nunsorted, nsorted);
378         return FALSE;
379 }
380
381 static gboolean on_expose(GisOpenGL *opengl, GdkEventExpose *event, gpointer _)
382 {
383         g_debug("GisOpenGL: on_expose - begin");
384
385         glClear(GL_COLOR_BUFFER_BIT);
386
387         _set_visuals(opengl);
388 #ifdef ROAM_DEBUG
389         glColor4f(0.0, 0.0, 9.0, 0.6);
390         glDisable(GL_TEXTURE_2D);
391         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
392         roam_sphere_draw(opengl->sphere);
393         //roam_sphere_draw_normals(opengl->sphere);
394 #else
395         g_tree_foreach(opengl->objects, _draw_level, opengl);
396         if (opengl->wireframe) {
397                 glClear(GL_DEPTH_BUFFER_BIT);
398                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
399                 roam_sphere_draw(opengl->sphere);
400         }
401 #endif
402
403         GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
404         gdk_gl_drawable_swap_buffers(gldrawable);
405
406         g_debug("GisOpenGL: on_expose - end\n");
407         return FALSE;
408 }
409
410 static gboolean on_key_press(GisOpenGL *opengl, GdkEventKey *event, gpointer _)
411 {
412         g_debug("GisOpenGL: on_key_press - key=%x, state=%x, plus=%x",
413                         event->keyval, event->state, GDK_plus);
414
415         guint kv = event->keyval;
416         gdk_threads_leave();
417         /* Testing */
418         if (kv == GDK_w) {
419                 opengl->wireframe = !opengl->wireframe;
420                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
421         }
422 #ifdef ROAM_DEBUG
423         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
424         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
425         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
426         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
427         gdk_threads_enter();
428         gtk_widget_queue_draw(GTK_WIDGET(opengl));
429 #else
430         gdk_threads_enter();
431 #endif
432         return FALSE;
433 }
434
435 static gboolean _update_errors_cb(gpointer sphere)
436 {
437         roam_sphere_update_errors(sphere);
438         return FALSE;
439 }
440 static void on_view_changed(GisOpenGL *opengl,
441                 gdouble _1, gdouble _2, gdouble _3)
442 {
443         g_debug("GisOpenGL: on_view_changed");
444         _set_visuals(opengl);
445 #ifndef ROAM_DEBUG
446         opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
447                         _update_errors_cb, opengl->sphere, NULL);
448         //roam_sphere_update_errors(opengl->sphere);
449 #endif
450 }
451
452 static gboolean on_idle(GisOpenGL *opengl)
453 {
454         //g_debug("GisOpenGL: on_idle");
455         gdk_threads_enter();
456         g_mutex_lock(opengl->sphere_lock);
457         if (roam_sphere_split_merge(opengl->sphere))
458                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
459         g_mutex_unlock(opengl->sphere_lock);
460         gdk_threads_leave();
461         return TRUE;
462 }
463
464
465 /*********************
466  * GisViewer methods *
467  *********************/
468 GisViewer *gis_opengl_new(GisPlugins *plugins, GisPrefs *prefs)
469 {
470         g_debug("GisOpenGL: new");
471         GisViewer *opengl = g_object_new(GIS_TYPE_OPENGL, NULL);
472         gis_viewer_setup(opengl, plugins, prefs);
473         return opengl;
474 }
475
476 static void gis_opengl_center_position(GisViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
477 {
478         GisOpenGL *opengl = GIS_OPENGL(_opengl);
479         glRotatef(lon, 0, 1, 0);
480         glRotatef(-lat, 1, 0, 0);
481         glTranslatef(0, 0, elev2rad(elev));
482 }
483
484 static void gis_opengl_project(GisViewer *_opengl,
485                 gdouble lat, gdouble lon, gdouble elev,
486                 gdouble *px, gdouble *py, gdouble *pz)
487 {
488         GisOpenGL *opengl = GIS_OPENGL(_opengl);
489         gdouble x, y, z;
490         lle2xyz(lat, lon, elev, &x, &y, &z);
491         gluProject(x, y, z,
492                 opengl->sphere->view->model,
493                 opengl->sphere->view->proj,
494                 opengl->sphere->view->view,
495                 px, py, pz);
496 }
497
498 static void gis_opengl_set_height_func(GisViewer *_opengl, GisTile *tile,
499                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
500 {
501         GisOpenGL *opengl = GIS_OPENGL(_opengl);
502         if (!tile)
503                 return;
504         /* TODO: get points? */
505         g_mutex_lock(opengl->sphere_lock);
506         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
507                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
508         for (GList *cur = triangles; cur; cur = cur->next) {
509                 RoamTriangle *tri = cur->data;
510                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
511                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
512                         if (tile->edge.n >= points[i]->lat && points[i]->lat >= tile->edge.s &&
513                             tile->edge.e >= points[i]->lon && points[i]->lon >= tile->edge.w) {
514                                 points[i]->height_func = height_func;
515                                 points[i]->height_data = user_data;
516                                 roam_point_update_height(points[i]);
517                         }
518                 }
519         }
520         g_list_free(triangles);
521         g_mutex_unlock(opengl->sphere_lock);
522 }
523
524 static void _gis_opengl_clear_height_func_rec(RoamTriangle *root)
525 {
526         if (!root)
527                 return;
528         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
529         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
530                 points[i]->height_func = NULL;
531                 points[i]->height_data = NULL;
532                 roam_point_update_height(points[i]);
533         }
534         _gis_opengl_clear_height_func_rec(root->kids[0]);
535         _gis_opengl_clear_height_func_rec(root->kids[1]);
536 }
537
538 static void gis_opengl_clear_height_func(GisViewer *_opengl)
539 {
540         GisOpenGL *opengl = GIS_OPENGL(_opengl);
541         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
542                 _gis_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
543 }
544
545 static gpointer gis_opengl_add(GisViewer *_opengl, GisObject *object,
546                 gint key, gboolean sort)
547 {
548         g_assert(GIS_IS_OPENGL(_opengl));
549         GisOpenGL *opengl = GIS_OPENGL(_opengl);
550         _load_object(opengl, object);
551         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
552         if (!level) {
553                 level = g_new0(struct RenderLevel, 1);
554                 g_tree_insert(opengl->objects, (gpointer)key, level);
555         }
556         GList *list = sort ? &level->sorted : &level->unsorted;
557         /* Put the link in the list */
558         GList *next = g_new0(GList, 1);
559         next->data = object;
560         next->prev = list;
561         next->next = list->next;
562         list->next = next;
563         return next;
564 }
565
566 static GisObject *gis_opengl_remove(GisViewer *_opengl, gpointer _link)
567 {
568         g_assert(GIS_IS_OPENGL(_opengl));
569         GisOpenGL *opengl = GIS_OPENGL(_opengl);
570         GList *link = _link;
571         GisObject *object = link->data;
572         _unload_object(opengl, object);
573         /* Just unlink and free it, link->prev is assured */
574         link->prev->next = link->next;
575         if (link->next)
576                 link->next->prev = link->prev;
577         g_free(link);
578         g_object_unref(object);
579         return object;
580 }
581
582 /****************
583  * GObject code *
584  ****************/
585 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
586 {
587         gint a = (int)_a, b = (int)_b;
588         return a < b ? -1 :
589                a > b ?  1 : 0;
590 }
591 static void _objects_free(gpointer value)
592 {
593         struct RenderLevel *level = value;
594         if (level->sorted.next)
595                 g_list_free(level->sorted.next);
596         if (level->unsorted.next)
597                 g_list_free(level->unsorted.next);
598         g_free(level);
599 }
600
601 G_DEFINE_TYPE(GisOpenGL, gis_opengl, GIS_TYPE_VIEWER);
602 static void gis_opengl_init(GisOpenGL *opengl)
603 {
604         g_debug("GisOpenGL: init");
605         /* OpenGL setup */
606         GdkGLConfig *glconfig = gdk_gl_config_new_by_mode(
607                         GDK_GL_MODE_RGBA   | GDK_GL_MODE_DEPTH |
608                         GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
609         if (!glconfig)
610                 g_error("Failed to create glconfig");
611         if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
612                                 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
613                 g_error("GL lacks required capabilities");
614         g_object_unref(glconfig);
615
616         opengl->objects = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
617         opengl->sphere = roam_sphere_new(opengl);
618         opengl->sphere_lock = g_mutex_new();
619
620 #ifndef ROAM_DEBUG
621         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
622         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
623 #endif
624
625         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
626         g_signal_connect(opengl, "realize",          G_CALLBACK(on_realize),      NULL);
627         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
628         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
629
630         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
631
632         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
633         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
634 }
635 static void gis_opengl_dispose(GObject *_opengl)
636 {
637         g_debug("GisOpenGL: dispose");
638         GisOpenGL *opengl = GIS_OPENGL(_opengl);
639         if (opengl->sm_source[0]) {
640                 g_source_remove(opengl->sm_source[0]);
641                 opengl->sm_source[0] = 0;
642         }
643         if (opengl->sm_source[1]) {
644                 g_source_remove(opengl->sm_source[1]);
645                 opengl->sm_source[1] = 0;
646         }
647         if (opengl->ue_source) {
648                 g_source_remove(opengl->ue_source);
649                 opengl->ue_source = 0;
650         }
651         G_OBJECT_CLASS(gis_opengl_parent_class)->dispose(_opengl);
652 }
653 static void gis_opengl_finalize(GObject *_opengl)
654 {
655         g_debug("GisOpenGL: finalize");
656         GisOpenGL *opengl = GIS_OPENGL(_opengl);
657         roam_sphere_free(opengl->sphere);
658         g_tree_destroy(opengl->objects);
659         g_mutex_free(opengl->sphere_lock);
660         G_OBJECT_CLASS(gis_opengl_parent_class)->finalize(_opengl);
661 }
662 static void gis_opengl_class_init(GisOpenGLClass *klass)
663 {
664         g_debug("GisOpenGL: class_init");
665         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
666         gobject_class->finalize = gis_opengl_finalize;
667         gobject_class->dispose = gis_opengl_dispose;
668
669         GisViewerClass *viewer_class = GIS_VIEWER_CLASS(klass);
670         viewer_class->center_position   = gis_opengl_center_position;
671         viewer_class->project           = gis_opengl_project;
672         viewer_class->clear_height_func = gis_opengl_clear_height_func;
673         viewer_class->set_height_func   = gis_opengl_set_height_func;
674         viewer_class->add               = gis_opengl_add;
675         viewer_class->remove            = gis_opengl_remove;
676 }