2 * Copyright (C) 2009-2011 Andy Spencer <andy753421@gmail.com>
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.
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.
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/>.
19 * SECTION:grits-opengl
20 * @short_description: OpenGL based virtual globe
22 * #GritsOpenGL is the core rendering engine used by grits. Theoretically other
23 * renderers could be writte, but they have not been. GritsOpenGL uses the ROAM
24 * algorithm for updating surface mesh the planet. The only thing GritsOpenGL
25 * can actually render on it's own is a wireframe of a sphere.
27 * GritsOpenGL relies on #GtkGlExt and requires (at least) OpenGL 2.0.
33 #include <gdk/gdkkeysyms.h>
35 #include <gtk/gtkgl.h>
39 #include "grits-opengl.h"
40 #include "grits-util.h"
43 static GdkGLConfig *glconfig;
47 /* Tessellation, "finding intersecting triangles" */
48 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
49 /* http://www.opengl.org/wiki/Alpha_Blending */
51 /* The unsorted/sroted GLists are blank head nodes,
52 * This way us we can remove objects from the level just by fixing up links
53 * I.e. we don't need to do a lookup to remove an object if we have its GList */
62 static void _set_visuals(GritsOpenGL *opengl)
64 glMatrixMode(GL_MODELVIEW);
68 double lat, lon, elev, rx, ry, rz;
69 grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
70 grits_viewer_get_rotation(GRITS_VIEWER(opengl), &rx, &ry, &rz);
71 glRotatef(rx, 1, 0, 0);
72 glRotatef(rz, 0, 0, 1);
76 float light_ambient[] = {0.7f, 0.7f, 0.7f, 1.0f};
77 float light_diffuse[] = {2.0f, 2.0f, 2.0f, 1.0f};
79 float light_ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
80 float light_diffuse[] = {0.8f, 0.8f, 0.8f, 1.0f};
82 float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
83 glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
84 glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
85 glLightfv(GL_LIGHT0, GL_POSITION, light_position);
87 glEnable(GL_LIGHTING);
89 float material_ambient[] = {1.0, 1.0, 1.0, 1.0};
90 float material_diffuse[] = {1.0, 1.0, 1.0, 1.0};
91 float material_specular[] = {0.0, 0.0, 0.0, 1.0};
92 float material_emission[] = {0.0, 0.0, 0.0, 1.0};
93 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_ambient);
94 glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse);
95 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
96 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
97 glDisable(GL_TEXTURE_2D);
98 glDisable(GL_COLOR_MATERIAL);
101 glTranslatef(0, 0, -elev2rad(elev));
102 glRotatef(lat, 1, 0, 0);
103 glRotatef(-lon, 0, 1, 0);
105 glDisable(GL_ALPHA_TEST);
107 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
112 glEnable(GL_CULL_FACE);
115 glDepthFunc(GL_LEQUAL);
116 glEnable(GL_DEPTH_TEST);
119 glEnable(GL_LINE_SMOOTH);
121 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
122 //glShadeModel(GL_FLAT);
124 g_mutex_lock(opengl->sphere_lock);
125 roam_sphere_update_view(opengl->sphere);
126 g_mutex_unlock(opengl->sphere_lock);
129 static gboolean _foreach_object_cb(gpointer key, gpointer value, gpointer pointers)
131 struct RenderLevel *level = value;
132 GFunc user_func = ((gpointer*)pointers)[0];
133 gpointer user_data = ((gpointer*)pointers)[1];
134 for (GList *cur = level->unsorted.next; cur; cur = cur->next)
135 user_func(cur->data, user_data);
136 for (GList *cur = level->sorted.next; cur; cur = cur->next)
137 user_func(cur->data, user_data);
141 static void _foreach_object(GritsOpenGL *opengl, GFunc func, gpointer user_data)
143 gpointer pointers[2] = {func, user_data};
144 g_tree_foreach(opengl->objects, _foreach_object_cb, pointers);
150 static gboolean on_configure(GritsOpenGL *opengl, GdkEventConfigure *event, gpointer _)
152 g_debug("GritsOpenGL: on_configure");
154 double width = GTK_WIDGET(opengl)->allocation.width;
155 double height = GTK_WIDGET(opengl)->allocation.height;
157 /* Setup OpenGL Window */
158 glViewport(0, 0, width, height);
159 glMatrixMode(GL_PROJECTION);
161 double ang = atan(height/FOV_DIST);
162 gluPerspective(rad2deg(ang)*2, width/height, 10, 100*EARTH_R);
165 g_mutex_lock(opengl->sphere_lock);
166 roam_sphere_update_errors(opengl->sphere);
167 g_mutex_unlock(opengl->sphere_lock);
173 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
175 g_debug("GritsOpenGL: _draw_level - level=%-4d", (int)key);
176 GritsOpenGL *opengl = user_data;
177 struct RenderLevel *level = value;
178 int nsorted = 0, nunsorted = 0;
181 /* Draw opaque objects without sorting */
183 glClear(GL_DEPTH_BUFFER_BIT);
184 for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
185 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
187 /* Freeze depth buffer and draw transparent objects sorted */
189 //glDepthMask(FALSE);
190 glAlphaFunc(GL_GREATER, 0.1);
191 for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
192 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
194 /* TODO: Prune empty levels */
196 g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
201 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
203 g_debug("GritsOpenGL: on_expose - begin");
205 glClear(GL_COLOR_BUFFER_BIT);
207 _set_visuals(opengl);
209 glColor4f(1.0, 1.0, 1.0, 1.0);
211 glDisable(GL_TEXTURE_2D);
212 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
213 roam_sphere_draw(opengl->sphere);
215 //roam_sphere_draw_normals(opengl->sphere);
217 g_mutex_lock(opengl->objects_lock);
218 g_tree_foreach(opengl->objects, _draw_level, opengl);
219 if (opengl->wireframe) {
220 glClear(GL_DEPTH_BUFFER_BIT);
221 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
222 roam_sphere_draw(opengl->sphere);
223 g_tree_foreach(opengl->objects, _draw_level, opengl);
225 g_mutex_unlock(opengl->objects_lock);
228 GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
229 gdk_gl_drawable_swap_buffers(gldrawable);
231 g_debug("GritsOpenGL: on_expose - end\n");
235 static gboolean on_motion_notify(GritsOpenGL *opengl, GdkEventMotion *event, gpointer _)
237 gdouble height = GTK_WIDGET(opengl)->allocation.height;
238 gdouble gl_x = event->x;
239 gdouble gl_y = height - event->y;
243 gdouble projection[16];
244 glGetIntegerv(GL_VIEWPORT, viewport);
245 glGetDoublev(GL_PROJECTION_MATRIX, projection);
247 glMatrixMode(GL_PROJECTION);
250 gluPickMatrix(gl_x, gl_y, 2, 2, viewport);
251 glMultMatrixd(projection);
253 /* Prepare for picking */
254 guint buffer[100][4] = {};
255 glSelectBuffer(G_N_ELEMENTS(buffer), (guint*)buffer);
256 glRenderMode(GL_SELECT);
260 g_mutex_lock(opengl->objects_lock);
261 _foreach_object(opengl, (GFunc)grits_object_pick_begin, opengl);
262 int hits = glRenderMode(GL_RENDER);
263 g_debug("GritsOpenGL: on_motion_notify - hits=%d ev=%.0lf,%.0lf",
265 for (int i = 0; i < hits; i++) {
266 //g_debug("\tHit: %d", i);
267 //g_debug("\t\tcount: %d", buffer[i][0]);
268 //g_debug("\t\tz1: %f", (float)buffer[i][1]/0x7fffffff);
269 //g_debug("\t\tz2: %f", (float)buffer[i][2]/0x7fffffff);
270 //g_debug("\t\tname: %p", (gpointer)buffer[i][3]);
271 GritsObject *object = GRITS_OBJECT(buffer[i][3]);
272 grits_object_pick_pointer(object, gl_x, gl_y);
274 _foreach_object(opengl, (GFunc)grits_object_pick_end, NULL);
275 g_mutex_unlock(opengl->objects_lock);
278 glMatrixMode(GL_PROJECTION);
284 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
286 g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
287 event->keyval, event->state, GDK_plus);
289 guint kv = event->keyval;
292 opengl->wireframe = !opengl->wireframe;
293 gtk_widget_queue_draw(GTK_WIDGET(opengl));
296 else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
297 else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
298 else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
299 else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
300 gtk_widget_queue_draw(GTK_WIDGET(opengl));
305 static gboolean on_chained_event(GritsOpenGL *opengl, GdkEvent *event, gpointer _)
307 _foreach_object(opengl, (GFunc)grits_object_event, event);
311 static gboolean _update_errors_cb(gpointer _opengl)
313 GritsOpenGL *opengl = _opengl;
314 g_mutex_lock(opengl->sphere_lock);
315 roam_sphere_update_errors(opengl->sphere);
316 g_mutex_unlock(opengl->sphere_lock);
317 opengl->ue_source = 0;
320 static void on_view_changed(GritsOpenGL *opengl,
321 gdouble _1, gdouble _2, gdouble _3)
323 g_debug("GritsOpenGL: on_view_changed");
324 _set_visuals(opengl);
326 if (!opengl->ue_source)
327 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
328 _update_errors_cb, opengl, NULL);
329 //roam_sphere_update_errors(opengl->sphere);
331 (void)_update_errors_cb;
335 static gboolean on_idle(GritsOpenGL *opengl)
337 //g_debug("GritsOpenGL: on_idle");
338 g_mutex_lock(opengl->sphere_lock);
339 if (roam_sphere_split_merge(opengl->sphere))
340 gtk_widget_queue_draw(GTK_WIDGET(opengl));
341 g_mutex_unlock(opengl->sphere_lock);
345 static void on_realize(GritsOpenGL *opengl, gpointer _)
347 g_debug("GritsOpenGL: on_realize");
350 GdkGLContext *glcontext = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
351 GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
352 if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
353 g_assert_not_reached();
355 /* Connect signals and idle functions now that opengl is fully initialized */
356 gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
357 g_signal_connect(opengl, "configure-event", G_CALLBACK(on_configure), NULL);
358 g_signal_connect(opengl, "expose-event", G_CALLBACK(on_expose), NULL);
360 g_signal_connect(opengl, "key-press-event", G_CALLBACK(on_key_press), NULL);
362 g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
363 g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
365 g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
366 g_signal_connect_after(opengl, "key-press-event", G_CALLBACK(on_chained_event), NULL);
367 g_signal_connect_after(opengl, "key-release-event", G_CALLBACK(on_chained_event), NULL);
368 g_signal_connect_after(opengl, "button-press-event", G_CALLBACK(on_chained_event), NULL);
369 g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
370 g_signal_connect_after(opengl, "motion-notify-event", G_CALLBACK(on_chained_event), NULL);
373 opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33, (GSourceFunc)on_idle, opengl, NULL);
374 opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
377 (void)_update_errors_cb;
380 /* Re-queue resize incase configure was triggered before realize */
381 gtk_widget_queue_resize(GTK_WIDGET(opengl));
384 /*********************
385 * GritsViewer methods *
386 *********************/
389 * @plugins: the plugins store to use
390 * @prefs: the preferences object to use
392 * Create a new OpenGL renderer.
394 * Returns: the new #GritsOpenGL
396 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
398 g_debug("GritsOpenGL: new");
399 GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
400 grits_viewer_setup(opengl, plugins, prefs);
404 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
406 glRotatef(lon, 0, 1, 0);
407 glRotatef(-lat, 1, 0, 0);
408 glTranslatef(0, 0, elev2rad(elev));
411 static void grits_opengl_project(GritsViewer *_opengl,
412 gdouble lat, gdouble lon, gdouble elev,
413 gdouble *px, gdouble *py, gdouble *pz)
415 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
417 lle2xyz(lat, lon, elev, &x, &y, &z);
419 opengl->sphere->view->model,
420 opengl->sphere->view->proj,
421 opengl->sphere->view->view,
425 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
426 RoamHeightFunc height_func, gpointer user_data, gboolean update)
428 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
429 /* TODO: get points? */
430 g_mutex_lock(opengl->sphere_lock);
431 GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
432 bounds->n, bounds->s, bounds->e, bounds->w);
433 for (GList *cur = triangles; cur; cur = cur->next) {
434 RoamTriangle *tri = cur->data;
435 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
436 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
437 if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
438 bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
439 points[i]->height_func = height_func;
440 points[i]->height_data = user_data;
441 roam_point_update_height(points[i]);
445 g_list_free(triangles);
446 g_mutex_unlock(opengl->sphere_lock);
449 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
453 RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
454 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
455 points[i]->height_func = NULL;
456 points[i]->height_data = NULL;
457 roam_point_update_height(points[i]);
459 _grits_opengl_clear_height_func_rec(root->kids[0]);
460 _grits_opengl_clear_height_func_rec(root->kids[1]);
463 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
465 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
466 for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
467 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
470 static gpointer grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
471 gint key, gboolean sort)
473 g_assert(GRITS_IS_OPENGL(_opengl));
474 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
475 g_mutex_lock(opengl->objects_lock);
476 struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
478 level = g_new0(struct RenderLevel, 1);
479 g_tree_insert(opengl->objects, (gpointer)key, level);
481 GList *list = sort ? &level->sorted : &level->unsorted;
482 /* Put the link in the list */
483 GList *link = g_new0(GList, 1);
486 link->next = list->next;
488 list->next->prev = link;
490 g_mutex_unlock(opengl->objects_lock);
494 static GritsObject *grits_opengl_remove(GritsViewer *_opengl, GritsObject *object)
496 g_assert(GRITS_IS_OPENGL(_opengl));
497 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
498 GList *link = object->ref;
499 g_mutex_lock(opengl->objects_lock);
500 /* Just unlink and free it, link->prev is assured */
501 link->prev->next = link->next;
503 link->next->prev = link->prev;
504 g_mutex_unlock(opengl->objects_lock);
506 object->viewer = NULL;
508 g_object_unref(object);
515 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
517 gint a = (int)_a, b = (int)_b;
521 static void _objects_free(gpointer value)
523 struct RenderLevel *level = value;
524 if (level->sorted.next)
525 g_list_free(level->sorted.next);
526 if (level->unsorted.next)
527 g_list_free(level->unsorted.next);
531 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
532 void grits_init(int *argc, char ***argv)
534 glconfig = gdk_gl_config_new_by_mode(
535 GDK_GL_MODE_RGBA | GDK_GL_MODE_DEPTH |
536 GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
538 g_warning("Failed to create glconfig, unsupported:%s%s%s%s.",
539 gdk_gl_config_new_by_mode(GDK_GL_MODE_RGBA) ? "" : " RGBA",
540 gdk_gl_config_new_by_mode(GDK_GL_MODE_DEPTH) ? "" : " DEPTH",
541 gdk_gl_config_new_by_mode(GDK_GL_MODE_DOUBLE) ? "" : " DOUBLE",
542 gdk_gl_config_new_by_mode(GDK_GL_MODE_ALPHA) ? "" : " ALPHA");
545 static void grits_opengl_init(GritsOpenGL *opengl)
547 g_debug("GritsOpenGL: init");
548 opengl->objects = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
549 opengl->objects_lock = g_mutex_new();
550 opengl->sphere = roam_sphere_new(opengl);
551 opengl->sphere_lock = g_mutex_new();
553 /* Set OpenGL before "realize" */
555 g_warning("recreating glconfig");
556 glconfig = gdk_gl_config_new_by_mode(
557 GDK_GL_MODE_RGBA | GDK_GL_MODE_DEPTH |
558 GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
561 g_error("Failed to create glconfig, unsupported:%s%s%s%s.",
562 gdk_gl_config_new_by_mode(GDK_GL_MODE_RGBA) ? "" : " RGBA",
563 gdk_gl_config_new_by_mode(GDK_GL_MODE_DEPTH) ? "" : " DEPTH",
564 gdk_gl_config_new_by_mode(GDK_GL_MODE_DOUBLE) ? "" : " DEPTH",
565 gdk_gl_config_new_by_mode(GDK_GL_MODE_ALPHA) ? "" : " ALPHA");
566 if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
567 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
568 g_error("GL lacks required capabilities");
570 /* Finish OpenGL init after it's realized */
571 g_signal_connect(opengl, "realize", G_CALLBACK(on_realize), NULL);
573 static void grits_opengl_dispose(GObject *_opengl)
575 g_debug("GritsOpenGL: dispose");
576 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
577 if (opengl->sm_source[0]) {
578 g_source_remove(opengl->sm_source[0]);
579 opengl->sm_source[0] = 0;
581 if (opengl->sm_source[1]) {
582 g_source_remove(opengl->sm_source[1]);
583 opengl->sm_source[1] = 0;
585 if (opengl->ue_source) {
586 g_source_remove(opengl->ue_source);
587 opengl->ue_source = 0;
589 G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
591 static void grits_opengl_finalize(GObject *_opengl)
593 g_debug("GritsOpenGL: finalize");
594 GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
595 roam_sphere_free(opengl->sphere);
596 g_tree_destroy(opengl->objects);
597 g_mutex_free(opengl->objects_lock);
598 g_mutex_free(opengl->sphere_lock);
599 G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
601 static void grits_opengl_class_init(GritsOpenGLClass *klass)
603 g_debug("GritsOpenGL: class_init");
604 GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
605 gobject_class->finalize = grits_opengl_finalize;
606 gobject_class->dispose = grits_opengl_dispose;
608 GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
609 viewer_class->center_position = grits_opengl_center_position;
610 viewer_class->project = grits_opengl_project;
611 viewer_class->clear_height_func = grits_opengl_clear_height_func;
612 viewer_class->set_height_func = grits_opengl_set_height_func;
613 viewer_class->add = grits_opengl_add;
614 viewer_class->remove = grits_opengl_remove;