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