]> Pileus Git - grits/blob - src/grits-opengl.c
Switch from GtkGLExt to internal OpenGL handling
[grits] / src / grits-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:grits-opengl
20  * @short_description: OpenGL based virtual globe
21  *
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.
26  *
27  * GritsOpenGL 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 <GL/gl.h>
36 #include <GL/glu.h>
37
38 #include "grits-opengl.h"
39 #include "grits-util.h"
40 #include "gtkgl.h"
41 #include "roam.h"
42
43 // #define ROAM_DEBUG
44
45 /* Tessellation, "finding intersecting triangles" */
46 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
47 /* http://www.opengl.org/wiki/Alpha_Blending */
48
49 /***********
50  * Helpers *
51  ***********/
52 static void _set_visuals(GritsOpenGL *opengl)
53 {
54         glMatrixMode(GL_MODELVIEW);
55         glLoadIdentity();
56
57         /* Camera 1 */
58         double lat, lon, elev, rx, ry, rz;
59         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
60         grits_viewer_get_rotation(GRITS_VIEWER(opengl), &rx, &ry, &rz);
61         glRotatef(rx, 1, 0, 0);
62         glRotatef(rz, 0, 0, 1);
63
64         /* Lighting */
65 #ifdef ROAM_DEBUG
66         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
67         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
68 #else
69         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
70         float light_diffuse[]  = {0.8f, 0.8f, 0.8f, 1.0f};
71 #endif
72         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
73         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
74         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
75         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
76         glEnable(GL_LIGHT0);
77         glEnable(GL_LIGHTING);
78
79         float material_ambient[]  = {1.0, 1.0, 1.0, 1.0};
80         float material_diffuse[]  = {1.0, 1.0, 1.0, 1.0};
81         float material_specular[] = {0.0, 0.0, 0.0, 1.0};
82         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
83         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
84         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
85         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
86         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
87         glDisable(GL_TEXTURE_2D);
88         glDisable(GL_COLOR_MATERIAL);
89
90         /* Camera 2 */
91         glTranslatef(0, 0, -elev2rad(elev));
92         glRotatef(lat, 1, 0, 0);
93         glRotatef(-lon, 0, 1, 0);
94
95         glDisable(GL_ALPHA_TEST);
96
97         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
98         glEnable(GL_BLEND);
99
100 #ifndef ROAM_DEBUG
101         glCullFace(GL_BACK);
102         glEnable(GL_CULL_FACE);
103
104         glClearDepth(1.0);
105         glDepthFunc(GL_LEQUAL);
106         glEnable(GL_DEPTH_TEST);
107 #endif
108
109         glEnable(GL_LINE_SMOOTH);
110
111         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
112         //glShadeModel(GL_FLAT);
113
114         g_mutex_lock(opengl->sphere_lock);
115         roam_sphere_update_view(opengl->sphere);
116         g_mutex_unlock(opengl->sphere_lock);
117 }
118
119
120 /*************
121  * Callbacks *
122  *************/
123 /* The unsorted/sroted GLists are blank head nodes,
124  * This way us we can remove objects from the level just by fixing up links
125  * I.e. we don't need to do a lookup to remove an object if we have its GList */
126 struct RenderLevel {
127         GList unsorted;
128         GList sorted;
129 };
130
131 static gboolean on_configure(GritsOpenGL *opengl, GdkEventConfigure *event, gpointer _)
132 {
133         g_debug("GritsOpenGL: on_configure");
134
135         double width  = GTK_WIDGET(opengl)->allocation.width;
136         double height = GTK_WIDGET(opengl)->allocation.height;
137
138         /* Setup OpenGL Window */
139         glViewport(0, 0, width, height);
140         glMatrixMode(GL_PROJECTION);
141         glLoadIdentity();
142         double ang = atan(height/FOV_DIST);
143         gluPerspective(rad2deg(ang)*2, width/height, 1000, 10*EARTH_R);
144
145 #ifndef ROAM_DEBUG
146         g_mutex_lock(opengl->sphere_lock);
147         roam_sphere_update_errors(opengl->sphere);
148         g_mutex_unlock(opengl->sphere_lock);
149 #endif
150
151         return FALSE;
152 }
153
154 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
155 {
156         g_debug("GritsOpenGL: _draw_level - level=%-4d", (int)key);
157         GritsOpenGL *opengl = user_data;
158         struct RenderLevel *level = value;
159         int nsorted = 0, nunsorted = 0;
160         GList *cur = NULL;
161
162         /* Draw opaque objects without sorting */
163         glDepthMask(TRUE);
164         glClear(GL_DEPTH_BUFFER_BIT);
165         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
166                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
167
168         /* Freeze depth buffer and draw transparent objects sorted */
169         /* TODO: sorting */
170         //glDepthMask(FALSE);
171         glAlphaFunc(GL_GREATER, 0.1);
172         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
173                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
174
175         /* TODO: Prune empty levels */
176
177         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
178                         nunsorted, nsorted);
179         return FALSE;
180 }
181
182 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
183 {
184         g_debug("GritsOpenGL: on_expose - begin");
185
186         glClear(GL_COLOR_BUFFER_BIT);
187
188         _set_visuals(opengl);
189 #ifdef ROAM_DEBUG
190         glColor4f(1.0, 1.0, 1.0, 1.0);
191         glLineWidth(2);
192         glDisable(GL_TEXTURE_2D);
193         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
194         roam_sphere_draw(opengl->sphere);
195         (void)_draw_level;
196         //roam_sphere_draw_normals(opengl->sphere);
197 #else
198         g_mutex_lock(opengl->objects_lock);
199         g_tree_foreach(opengl->objects, _draw_level, opengl);
200         if (opengl->wireframe) {
201                 glClear(GL_DEPTH_BUFFER_BIT);
202                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
203                 roam_sphere_draw(opengl->sphere);
204                 g_tree_foreach(opengl->objects, _draw_level, opengl);
205         }
206         g_mutex_unlock(opengl->objects_lock);
207 #endif
208
209         gtk_gl_end(GTK_WIDGET(opengl));
210
211         g_debug("GritsOpenGL: on_expose - end\n");
212         return FALSE;
213 }
214
215 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
216 {
217         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
218                         event->keyval, event->state, GDK_plus);
219
220         guint kv = event->keyval;
221         /* Testing */
222         if (kv == GDK_w) {
223                 opengl->wireframe = !opengl->wireframe;
224                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
225         }
226 #ifdef ROAM_DEBUG
227         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
228         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
229         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
230         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
231         gtk_widget_queue_draw(GTK_WIDGET(opengl));
232 #endif
233         return FALSE;
234 }
235
236 static gboolean _update_errors_cb(gpointer _opengl)
237 {
238         GritsOpenGL *opengl = _opengl;
239         g_mutex_lock(opengl->sphere_lock);
240         roam_sphere_update_errors(opengl->sphere);
241         g_mutex_unlock(opengl->sphere_lock);
242         opengl->ue_source = 0;
243         return FALSE;
244 }
245 static void on_view_changed(GritsOpenGL *opengl,
246                 gdouble _1, gdouble _2, gdouble _3)
247 {
248         g_debug("GritsOpenGL: on_view_changed");
249         _set_visuals(opengl);
250 #ifndef ROAM_DEBUG
251         if (!opengl->ue_source)
252                 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
253                                 _update_errors_cb, opengl, NULL);
254         //roam_sphere_update_errors(opengl->sphere);
255 #else
256         (void)_update_errors_cb;
257 #endif
258 }
259
260 static gboolean on_idle(GritsOpenGL *opengl)
261 {
262         //g_debug("GritsOpenGL: on_idle");
263         g_mutex_lock(opengl->sphere_lock);
264         if (roam_sphere_split_merge(opengl->sphere))
265                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
266         g_mutex_unlock(opengl->sphere_lock);
267         return TRUE;
268 }
269
270 static void on_realize(GritsOpenGL *opengl, gpointer _)
271 {
272         g_debug("GritsOpenGL: on_realize");
273         gtk_gl_begin(GTK_WIDGET(opengl));
274
275         /* Connect signals and idle functions now that opengl is fully initialized */
276         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
277         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
278         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
279
280         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
281
282         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
283         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
284
285 #ifndef ROAM_DEBUG
286         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
287         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
288 #else
289         (void)on_idle;
290         (void)_update_errors_cb;
291 #endif
292
293         /* Re-queue resize incase configure was triggered before realize */
294         gtk_widget_queue_resize(GTK_WIDGET(opengl));
295 }
296
297 /*********************
298  * GritsViewer methods *
299  *********************/
300 /**
301  * grits_opengl_new:
302  * @plugins: the plugins store to use
303  * @prefs:   the preferences object to use
304  *
305  * Create a new OpenGL renderer.
306  *
307  * Returns: the new #GritsOpenGL
308  */
309 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
310 {
311         g_debug("GritsOpenGL: new");
312         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
313         grits_viewer_setup(opengl, plugins, prefs);
314         return opengl;
315 }
316
317 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
318 {
319         glRotatef(lon, 0, 1, 0);
320         glRotatef(-lat, 1, 0, 0);
321         glTranslatef(0, 0, elev2rad(elev));
322 }
323
324 static void grits_opengl_project(GritsViewer *_opengl,
325                 gdouble lat, gdouble lon, gdouble elev,
326                 gdouble *px, gdouble *py, gdouble *pz)
327 {
328         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
329         gdouble x, y, z;
330         lle2xyz(lat, lon, elev, &x, &y, &z);
331         gluProject(x, y, z,
332                 opengl->sphere->view->model,
333                 opengl->sphere->view->proj,
334                 opengl->sphere->view->view,
335                 px, py, pz);
336 }
337
338 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
339                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
340 {
341         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
342         /* TODO: get points? */
343         g_mutex_lock(opengl->sphere_lock);
344         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
345                         bounds->n, bounds->s, bounds->e, bounds->w);
346         for (GList *cur = triangles; cur; cur = cur->next) {
347                 RoamTriangle *tri = cur->data;
348                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
349                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
350                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
351                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
352                                 points[i]->height_func = height_func;
353                                 points[i]->height_data = user_data;
354                                 roam_point_update_height(points[i]);
355                         }
356                 }
357         }
358         g_list_free(triangles);
359         g_mutex_unlock(opengl->sphere_lock);
360 }
361
362 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
363 {
364         if (!root)
365                 return;
366         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
367         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
368                 points[i]->height_func = NULL;
369                 points[i]->height_data = NULL;
370                 roam_point_update_height(points[i]);
371         }
372         _grits_opengl_clear_height_func_rec(root->kids[0]);
373         _grits_opengl_clear_height_func_rec(root->kids[1]);
374 }
375
376 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
377 {
378         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
379         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
380                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
381 }
382
383 static gpointer grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
384                 gint key, gboolean sort)
385 {
386         g_assert(GRITS_IS_OPENGL(_opengl));
387         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
388         g_mutex_lock(opengl->objects_lock);
389         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
390         if (!level) {
391                 level = g_new0(struct RenderLevel, 1);
392                 g_tree_insert(opengl->objects, (gpointer)key, level);
393         }
394         GList *list = sort ? &level->sorted : &level->unsorted;
395         /* Put the link in the list */
396         GList *link = g_new0(GList, 1);
397         link->data = object;
398         link->prev = list;
399         link->next = list->next;
400         if (list->next)
401                 list->next->prev = link;
402         list->next = link;
403         g_mutex_unlock(opengl->objects_lock);
404         return link;
405 }
406
407 static GritsObject *grits_opengl_remove(GritsViewer *_opengl, gpointer _link)
408 {
409         g_assert(GRITS_IS_OPENGL(_opengl));
410         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
411         GList *link = _link;
412         g_mutex_lock(opengl->objects_lock);
413         GritsObject *object = link->data;
414         /* Just unlink and free it, link->prev is assured */
415         link->prev->next = link->next;
416         if (link->next)
417                 link->next->prev = link->prev;
418         g_mutex_unlock(opengl->objects_lock);
419         g_free(link);
420         g_object_unref(object);
421         return object;
422 }
423
424 /****************
425  * GObject code *
426  ****************/
427 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
428 {
429         gint a = (int)_a, b = (int)_b;
430         return a < b ? -1 :
431                a > b ?  1 : 0;
432 }
433 static void _objects_free(gpointer value)
434 {
435         struct RenderLevel *level = value;
436         if (level->sorted.next)
437                 g_list_free(level->sorted.next);
438         if (level->unsorted.next)
439                 g_list_free(level->unsorted.next);
440         g_free(level);
441 }
442
443 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
444 static void grits_opengl_init(GritsOpenGL *opengl)
445 {
446         g_debug("GritsOpenGL: init");
447         opengl->objects      = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
448         opengl->objects_lock = g_mutex_new();
449         opengl->sphere       = roam_sphere_new(opengl);
450         opengl->sphere_lock  = g_mutex_new();
451         gtk_gl_enable(GTK_WIDGET(opengl));
452         g_signal_connect(opengl, "realize", G_CALLBACK(on_realize), NULL);
453 }
454 static void grits_opengl_dispose(GObject *_opengl)
455 {
456         g_debug("GritsOpenGL: dispose");
457         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
458         if (opengl->sm_source[0]) {
459                 g_source_remove(opengl->sm_source[0]);
460                 opengl->sm_source[0] = 0;
461         }
462         if (opengl->sm_source[1]) {
463                 g_source_remove(opengl->sm_source[1]);
464                 opengl->sm_source[1] = 0;
465         }
466         if (opengl->ue_source) {
467                 g_source_remove(opengl->ue_source);
468                 opengl->ue_source = 0;
469         }
470         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
471 }
472 static void grits_opengl_finalize(GObject *_opengl)
473 {
474         g_debug("GritsOpenGL: finalize");
475         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
476         roam_sphere_free(opengl->sphere);
477         g_tree_destroy(opengl->objects);
478         g_mutex_free(opengl->objects_lock);
479         g_mutex_free(opengl->sphere_lock);
480         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
481 }
482 static void grits_opengl_class_init(GritsOpenGLClass *klass)
483 {
484         g_debug("GritsOpenGL: class_init");
485         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
486         gobject_class->finalize = grits_opengl_finalize;
487         gobject_class->dispose = grits_opengl_dispose;
488
489         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
490         viewer_class->center_position   = grits_opengl_center_position;
491         viewer_class->project           = grits_opengl_project;
492         viewer_class->clear_height_func = grits_opengl_clear_height_func;
493         viewer_class->set_height_func   = grits_opengl_set_height_func;
494         viewer_class->add               = grits_opengl_add;
495         viewer_class->remove            = grits_opengl_remove;
496 }