]> Pileus Git - grits/blob - src/gis-opengl.c
dc32fa8de4e4f188e77d19399ce0b7dd342a84e2
[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                 glEnable(GL_POLYGON_OFFSET_FILL);
182                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
183                 glPolygonOffset(0, -tile->zindex);
184                 glBegin(GL_TRIANGLES);
185                 glNormal3dv(tri->p.r->norm); glTexCoord2dv(xy[0]); glVertex3dv((double*)tri->p.r);
186                 glNormal3dv(tri->p.m->norm); glTexCoord2dv(xy[1]); glVertex3dv((double*)tri->p.m);
187                 glNormal3dv(tri->p.l->norm); glTexCoord2dv(xy[2]); glVertex3dv((double*)tri->p.l);
188                 glEnd();
189         }
190         g_list_free(triangles);
191 }
192
193 static void _draw_tiles(GisOpenGL *opengl, GisTile *tile)
194 {
195         /* Only draw children if possible */
196         gboolean has_children = FALSE;
197         GisTile *child;
198         gis_tile_foreach(tile, child)
199                 if (child && child->data)
200                         has_children = TRUE;
201
202         GList *triangles = NULL;
203         if (has_children) {
204                 /* TODO: simplify this */
205                 const gdouble rows = G_N_ELEMENTS(tile->children);
206                 const gdouble cols = G_N_ELEMENTS(tile->children[0]);
207                 const gdouble lat_dist = tile->edge.n - tile->edge.s;
208                 const gdouble lon_dist = tile->edge.e - tile->edge.w;
209                 const gdouble lat_step = lat_dist / rows;
210                 const gdouble lon_step = lon_dist / cols;
211                 int row, col;
212                 gis_tile_foreach_index(tile, row, col) {
213                         GisTile *child = tile->children[row][col];
214                         if (child && child->data) {
215                                 _draw_tiles(opengl, child);
216                         } else {
217                                 const gdouble n = tile->edge.n-(lat_step*(row+0));
218                                 const gdouble s = tile->edge.n-(lat_step*(row+1));
219                                 const gdouble e = tile->edge.w+(lon_step*(col+1));
220                                 const gdouble w = tile->edge.w+(lon_step*(col+0));
221                                 GList *these = roam_sphere_get_intersect(opengl->sphere, FALSE, n, s, e, w);
222                                 triangles = g_list_concat(triangles, these);
223                         }
224                 }
225         } else {
226                 triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
227                                 tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
228         }
229         if (triangles)
230                 _draw_tile(opengl, tile, triangles);
231 }
232
233 static void _draw_marker(GisOpenGL *opengl, GisMarker *marker)
234 {
235         GisPoint *point = gis_object_center(marker);
236         gdouble px, py, pz;
237         gis_viewer_project(GIS_VIEWER(opengl),
238                         point->lat, point->lon, point->elev,
239                         &px, &py, &pz);
240
241         gint win_width  = GTK_WIDGET(opengl)->allocation.width;
242         gint win_height = GTK_WIDGET(opengl)->allocation.height;
243         py = win_height - py;
244         if (pz > 1)
245                 return;
246
247         //g_debug("GisOpenGL: draw_marker - %s pz=%f ", marker->label, pz);
248
249         cairo_surface_t *surface = cairo_get_target(marker->cairo);
250         gdouble width  = cairo_image_surface_get_width(surface);
251         gdouble height = cairo_image_surface_get_height(surface);
252
253         glMatrixMode(GL_PROJECTION); glLoadIdentity();
254         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
255         glOrtho(0, win_width, win_height, 0, -1, 1);
256         glTranslated(px - marker->xoff,
257                      py - marker->yoff, 0);
258
259         glDisable(GL_LIGHTING);
260         glDisable(GL_COLOR_MATERIAL);
261         glDisable(GL_DEPTH_TEST);
262         glEnable(GL_TEXTURE_2D);
263         glBindTexture(GL_TEXTURE_2D, marker->tex);
264         glDisable(GL_CULL_FACE);
265         glBegin(GL_QUADS);
266         glTexCoord2f(1, 0); glVertex3f(width, 0     , 0);
267         glTexCoord2f(1, 1); glVertex3f(width, height, 0);
268         glTexCoord2f(0, 1); glVertex3f(0    , height, 0);
269         glTexCoord2f(0, 0); glVertex3f(0    , 0     , 0);
270         glEnd();
271 }
272
273 static void _draw_callback(GisOpenGL *opengl, GisCallback *callback)
274 {
275         callback->callback(callback, callback->user_data);
276 }
277
278 static void _draw_object(GisOpenGL *opengl, GisObject *object)
279 {
280         //g_debug("GisOpenGL: draw_object");
281         /* Skip out of range objects */
282         if (object->lod > 0) {
283                 /* LOD test */
284                 gdouble eye[3], obj[3];
285                 gis_viewer_get_location(GIS_VIEWER(opengl), &eye[0], &eye[1], &eye[2]);
286                 gdouble elev = eye[2];
287                 lle2xyz(eye[0], eye[1], eye[2], &eye[0], &eye[1], &eye[2]);
288                 lle2xyz(object->center.lat, object->center.lon, object->center.elev,
289                         &obj[0], &obj[1], &obj[2]);
290                 gdouble dist = distd(obj, eye);
291                 if (object->lod < dist)
292                         return;
293
294                 /* Horizon testing */
295                 gdouble c = EARTH_R+elev;
296                 gdouble a = EARTH_R;
297                 gdouble horizon = sqrt(c*c - a*a);
298                 if (dist > horizon)
299                         return;
300         }
301
302         /* Draw */
303         glMatrixMode(GL_PROJECTION); glPushMatrix();
304         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
305         glPushAttrib(GL_ALL_ATTRIB_BITS);
306         if (GIS_IS_MARKER(object)) {
307                 _draw_marker(opengl, GIS_MARKER(object));
308         } else if (GIS_IS_CALLBACK(object)) {
309                 _draw_callback(opengl, GIS_CALLBACK(object));
310         } else if (GIS_IS_TILE(object)) {
311                 glEnable(GL_DEPTH_TEST);
312                 glDepthFunc(GL_LESS);
313                 g_mutex_lock(opengl->sphere_lock);
314                 _draw_tiles(opengl, GIS_TILE(object));
315                 g_mutex_unlock(opengl->sphere_lock);
316         }
317         glPopAttrib();
318         glMatrixMode(GL_PROJECTION); glPopMatrix();
319         glMatrixMode(GL_MODELVIEW);  glPopMatrix();
320 }
321
322 static void _load_object(GisOpenGL *opengl, GisObject *object)
323 {
324         g_debug("GisOpenGL: load_object");
325         if (GIS_IS_MARKER(object)) {
326                 GisMarker *marker = GIS_MARKER(object);
327                 cairo_surface_t *surface = cairo_get_target(marker->cairo);
328                 gdouble width  = cairo_image_surface_get_width(surface);
329                 gdouble height = cairo_image_surface_get_height(surface);
330
331                 glEnable(GL_TEXTURE_2D);
332                 glGenTextures(1, &marker->tex);
333                 glBindTexture(GL_TEXTURE_2D, marker->tex);
334
335                 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
336                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
337                 glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
338                                 cairo_image_surface_get_data(surface));
339                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
340                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
341                 g_debug("load_texture: %d", marker->tex);
342         }
343 }
344
345 static void _unload_object(GisOpenGL *opengl, GisObject *object)
346 {
347         g_debug("GisOpenGL: unload_object");
348         if (GIS_IS_MARKER(object)) {
349                 GisMarker *marker = GIS_MARKER(object);
350                 glDeleteTextures(1, &marker->tex);
351         }
352 }
353
354
355 /*************
356  * Callbacks *
357  *************/
358 /* The unsorted/sroted GLists are blank head nodes,
359  * This way us we can remove objects from the level just by fixing up links
360  * I.e. we don't need to do a lookup to remove an object if we have its GList */
361 struct RenderLevel {
362         GList unsorted;
363         GList sorted;
364 };
365
366 static gboolean on_configure(GisOpenGL *opengl, GdkEventConfigure *event, gpointer _)
367 {
368         g_debug("GisOpenGL: on_configure");
369
370         double width  = GTK_WIDGET(opengl)->allocation.width;
371         double height = GTK_WIDGET(opengl)->allocation.height;
372
373         /* Setup OpenGL Window */
374         glViewport(0, 0, width, height);
375         glMatrixMode(GL_PROJECTION);
376         glLoadIdentity();
377         double ang = atan(height/FOV_DIST);
378         gluPerspective(rad2deg(ang)*2, width/height, 1000, 10*EARTH_R);
379
380 #ifndef ROAM_DEBUG
381         g_mutex_lock(opengl->sphere_lock);
382         roam_sphere_update_errors(opengl->sphere);
383         g_mutex_unlock(opengl->sphere_lock);
384 #endif
385
386         return FALSE;
387 }
388
389 static void on_realize(GisOpenGL *opengl, gpointer _)
390 {
391         g_debug("GisOpenGL: on_realize");
392
393         GdkGLContext   *glcontext  = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
394         GdkGLDrawable  *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
395         if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
396                 g_assert_not_reached();
397
398         _set_visuals(opengl);
399         on_configure(opengl, NULL, NULL);
400 }
401
402 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
403 {
404         g_debug("GisOpenGL: _draw_level - level=%-4d", (int)key);
405         GisOpenGL *opengl = user_data;
406         struct RenderLevel *level = value;
407         int nsorted = 0, nunsorted = 0;
408         GList *cur = NULL;
409
410         /* Draw opaque objects without sorting */
411         glDepthMask(TRUE);
412         glClear(GL_DEPTH_BUFFER_BIT);
413         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
414                 _draw_object(opengl, GIS_OBJECT(cur->data));
415
416         /* Freeze depth buffer and draw transparent objects sorted */
417         /* TODO: sorting */
418         //glDepthMask(FALSE);
419         glAlphaFunc(GL_GREATER, 0.1);
420         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
421                 _draw_object(opengl, GIS_OBJECT(cur->data));
422
423         /* TODO: Prune empty levels */
424
425         g_debug("GisOpenGL: _draw_level - drew %d,%d objects",
426                         nunsorted, nsorted);
427         return FALSE;
428 }
429
430 static gboolean on_expose(GisOpenGL *opengl, GdkEventExpose *event, gpointer _)
431 {
432         g_debug("GisOpenGL: on_expose - begin");
433
434         glClear(GL_COLOR_BUFFER_BIT);
435
436         _set_visuals(opengl);
437 #ifdef ROAM_DEBUG
438         glColor4f(0.0, 0.0, 9.0, 0.6);
439         glDisable(GL_TEXTURE_2D);
440         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
441         roam_sphere_draw(opengl->sphere);
442         //roam_sphere_draw_normals(opengl->sphere);
443 #else
444         g_mutex_lock(opengl->objects_lock);
445         g_tree_foreach(opengl->objects, _draw_level, opengl);
446         g_mutex_unlock(opengl->objects_lock);
447         if (opengl->wireframe) {
448                 glClear(GL_DEPTH_BUFFER_BIT);
449                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
450                 roam_sphere_draw(opengl->sphere);
451         }
452 #endif
453
454         GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
455         gdk_gl_drawable_swap_buffers(gldrawable);
456
457         g_debug("GisOpenGL: on_expose - end\n");
458         return FALSE;
459 }
460
461 static gboolean on_key_press(GisOpenGL *opengl, GdkEventKey *event, gpointer _)
462 {
463         g_debug("GisOpenGL: on_key_press - key=%x, state=%x, plus=%x",
464                         event->keyval, event->state, GDK_plus);
465
466         guint kv = event->keyval;
467         /* Testing */
468         if (kv == GDK_w) {
469                 opengl->wireframe = !opengl->wireframe;
470                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
471         }
472 #ifdef ROAM_DEBUG
473         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
474         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
475         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
476         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
477         gtk_widget_queue_draw(GTK_WIDGET(opengl));
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         g_mutex_lock(opengl->sphere_lock);
508         if (roam_sphere_split_merge(opengl->sphere))
509                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
510         g_mutex_unlock(opengl->sphere_lock);
511         return TRUE;
512 }
513
514
515 /*********************
516  * GisViewer methods *
517  *********************/
518 /**
519  * gis_opengl_new:
520  * @plugins: the plugins store to use
521  * @prefs:   the preferences object to use
522  *
523  * Create a new OpenGL renderer.
524  *
525  * Returns: the new #GisOpenGL
526  */
527 GisViewer *gis_opengl_new(GisPlugins *plugins, GisPrefs *prefs)
528 {
529         g_debug("GisOpenGL: new");
530         GisViewer *opengl = g_object_new(GIS_TYPE_OPENGL, NULL);
531         gis_viewer_setup(opengl, plugins, prefs);
532         return opengl;
533 }
534
535 static void gis_opengl_center_position(GisViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
536 {
537         GisOpenGL *opengl = GIS_OPENGL(_opengl);
538         glRotatef(lon, 0, 1, 0);
539         glRotatef(-lat, 1, 0, 0);
540         glTranslatef(0, 0, elev2rad(elev));
541 }
542
543 static void gis_opengl_project(GisViewer *_opengl,
544                 gdouble lat, gdouble lon, gdouble elev,
545                 gdouble *px, gdouble *py, gdouble *pz)
546 {
547         GisOpenGL *opengl = GIS_OPENGL(_opengl);
548         gdouble x, y, z;
549         lle2xyz(lat, lon, elev, &x, &y, &z);
550         gluProject(x, y, z,
551                 opengl->sphere->view->model,
552                 opengl->sphere->view->proj,
553                 opengl->sphere->view->view,
554                 px, py, pz);
555 }
556
557 static void gis_opengl_set_height_func(GisViewer *_opengl, GisTile *tile,
558                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
559 {
560         GisOpenGL *opengl = GIS_OPENGL(_opengl);
561         if (!tile)
562                 return;
563         /* TODO: get points? */
564         g_mutex_lock(opengl->sphere_lock);
565         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
566                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
567         for (GList *cur = triangles; cur; cur = cur->next) {
568                 RoamTriangle *tri = cur->data;
569                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
570                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
571                         if (tile->edge.n >= points[i]->lat && points[i]->lat >= tile->edge.s &&
572                             tile->edge.e >= points[i]->lon && points[i]->lon >= tile->edge.w) {
573                                 points[i]->height_func = height_func;
574                                 points[i]->height_data = user_data;
575                                 roam_point_update_height(points[i]);
576                         }
577                 }
578         }
579         g_list_free(triangles);
580         g_mutex_unlock(opengl->sphere_lock);
581 }
582
583 static void _gis_opengl_clear_height_func_rec(RoamTriangle *root)
584 {
585         if (!root)
586                 return;
587         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
588         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
589                 points[i]->height_func = NULL;
590                 points[i]->height_data = NULL;
591                 roam_point_update_height(points[i]);
592         }
593         _gis_opengl_clear_height_func_rec(root->kids[0]);
594         _gis_opengl_clear_height_func_rec(root->kids[1]);
595 }
596
597 static void gis_opengl_clear_height_func(GisViewer *_opengl)
598 {
599         GisOpenGL *opengl = GIS_OPENGL(_opengl);
600         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
601                 _gis_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
602 }
603
604 static gpointer gis_opengl_add(GisViewer *_opengl, GisObject *object,
605                 gint key, gboolean sort)
606 {
607         g_assert(GIS_IS_OPENGL(_opengl));
608         GisOpenGL *opengl = GIS_OPENGL(_opengl);
609         g_mutex_lock(opengl->objects_lock);
610         _load_object(opengl, object);
611         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
612         if (!level) {
613                 level = g_new0(struct RenderLevel, 1);
614                 g_tree_insert(opengl->objects, (gpointer)key, level);
615         }
616         GList *list = sort ? &level->sorted : &level->unsorted;
617         /* Put the link in the list */
618         GList *link = g_new0(GList, 1);
619         link->data = object;
620         link->prev = list;
621         link->next = list->next;
622         if (list->next)
623                 list->next->prev = link;
624         list->next = link;
625         g_mutex_unlock(opengl->objects_lock);
626         return link;
627 }
628
629 static GisObject *gis_opengl_remove(GisViewer *_opengl, gpointer _link)
630 {
631         g_assert(GIS_IS_OPENGL(_opengl));
632         GisOpenGL *opengl = GIS_OPENGL(_opengl);
633         g_mutex_lock(opengl->objects_lock);
634         GList *link = _link;
635         GisObject *object = link->data;
636         _unload_object(opengl, object);
637         /* Just unlink and free it, link->prev is assured */
638         link->prev->next = link->next;
639         if (link->next)
640                 link->next->prev = link->prev;
641         g_free(link);
642         g_object_unref(object);
643         g_mutex_unlock(opengl->objects_lock);
644         return object;
645 }
646
647 /****************
648  * GObject code *
649  ****************/
650 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
651 {
652         gint a = (int)_a, b = (int)_b;
653         return a < b ? -1 :
654                a > b ?  1 : 0;
655 }
656 static void _objects_free(gpointer value)
657 {
658         struct RenderLevel *level = value;
659         if (level->sorted.next)
660                 g_list_free(level->sorted.next);
661         if (level->unsorted.next)
662                 g_list_free(level->unsorted.next);
663         g_free(level);
664 }
665
666 G_DEFINE_TYPE(GisOpenGL, gis_opengl, GIS_TYPE_VIEWER);
667 static void gis_opengl_init(GisOpenGL *opengl)
668 {
669         g_debug("GisOpenGL: init");
670         /* OpenGL setup */
671         GdkGLConfig *glconfig = gdk_gl_config_new_by_mode(
672                         GDK_GL_MODE_RGBA   | GDK_GL_MODE_DEPTH |
673                         GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
674         if (!glconfig)
675                 g_error("Failed to create glconfig");
676         if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
677                                 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
678                 g_error("GL lacks required capabilities");
679         g_object_unref(glconfig);
680
681         opengl->objects = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
682         opengl->objects_lock = g_mutex_new();
683         opengl->sphere = roam_sphere_new(opengl);
684         opengl->sphere_lock = g_mutex_new();
685
686 #ifndef ROAM_DEBUG
687         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
688         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
689 #endif
690
691         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
692         g_signal_connect(opengl, "realize",          G_CALLBACK(on_realize),      NULL);
693         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
694         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
695
696         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
697
698         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
699         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
700 }
701 static void gis_opengl_dispose(GObject *_opengl)
702 {
703         g_debug("GisOpenGL: dispose");
704         GisOpenGL *opengl = GIS_OPENGL(_opengl);
705         if (opengl->sm_source[0]) {
706                 g_source_remove(opengl->sm_source[0]);
707                 opengl->sm_source[0] = 0;
708         }
709         if (opengl->sm_source[1]) {
710                 g_source_remove(opengl->sm_source[1]);
711                 opengl->sm_source[1] = 0;
712         }
713         if (opengl->ue_source) {
714                 g_source_remove(opengl->ue_source);
715                 opengl->ue_source = 0;
716         }
717         G_OBJECT_CLASS(gis_opengl_parent_class)->dispose(_opengl);
718 }
719 static void gis_opengl_finalize(GObject *_opengl)
720 {
721         g_debug("GisOpenGL: finalize");
722         GisOpenGL *opengl = GIS_OPENGL(_opengl);
723         roam_sphere_free(opengl->sphere);
724         g_tree_destroy(opengl->objects);
725         g_mutex_free(opengl->objects_lock);
726         g_mutex_free(opengl->sphere_lock);
727         G_OBJECT_CLASS(gis_opengl_parent_class)->finalize(_opengl);
728 }
729 static void gis_opengl_class_init(GisOpenGLClass *klass)
730 {
731         g_debug("GisOpenGL: class_init");
732         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
733         gobject_class->finalize = gis_opengl_finalize;
734         gobject_class->dispose = gis_opengl_dispose;
735
736         GisViewerClass *viewer_class = GIS_VIEWER_CLASS(klass);
737         viewer_class->center_position   = gis_opengl_center_position;
738         viewer_class->project           = gis_opengl_project;
739         viewer_class->clear_height_func = gis_opengl_clear_height_func;
740         viewer_class->set_height_func   = gis_opengl_set_height_func;
741         viewer_class->add               = gis_opengl_add;
742         viewer_class->remove            = gis_opengl_remove;
743 }