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