]> Pileus Git - grits/blob - src/objects/grits-tile.c
Fix queue_draw on grits_tiles
[grits] / src / objects / grits-tile.c
1 /*
2  * Copyright (C) 2009-2010, 2012 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-tile
20  * @short_description: Latitude/longitude overlays
21  *
22  * Each #GritsTile corresponds to a latitude/longitude box on the surface of
23  * the earth. When drawn, the #GritsTile renders an images associated with it
24  * to the surface of the earth. This is primarily used to draw ground overlays.
25  *
26  * Each GritsTile can be split into subtiles in order to draw higher resolution
27  * overlays. Pointers to subtitles are stored in the parent tile and a parent
28  * pointer is stored in each child.
29  *
30  * Each #GritsTile has a data filed which must be set by the user in order for
31  * the tile to be drawn. When used with GritsOpenGL the data must be an integer
32  * representing the OpenGL texture to use when drawing the tile.
33  */
34
35 #define GL_GLEXT_PROTOTYPES
36 #include <config.h>
37 #include <math.h>
38 #include <string.h>
39 #include "gtkgl.h"
40 #include "grits-tile.h"
41
42 static guint  grits_tile_mask = 0;
43
44 gchar *grits_tile_path_table[2][2] = {
45         {"00.", "01."},
46         {"10.", "11."},
47 };
48
49 /**
50  * grits_tile_new:
51  * @parent: the parent for the tile, or NULL
52  * @n:      the northern border of the tile
53  * @s:      the southern border of the tile
54  * @e:      the eastern border of the tile
55  * @w:      the western border of the tile
56  *
57  * Create a tile associated with a particular latitude/longitude box.
58  *
59  * Returns: the new #GritsTile
60  */
61 GritsTile *grits_tile_new(GritsTile *parent,
62         gdouble n, gdouble s, gdouble e, gdouble w)
63 {
64         GritsTile *tile = g_object_new(GRITS_TYPE_TILE, NULL);
65         tile->parent = parent;
66         tile->atime  = time(NULL);
67         grits_bounds_set_bounds(&tile->coords, 0, 1, 1, 0);
68         grits_bounds_set_bounds(&tile->edge, n, s, e, w);
69         if (parent)
70                 tile->proj   = parent->proj;
71         return tile;
72 }
73
74 /**
75  * grits_tile_get_path:
76  * @child: the tile to generate a path for
77  *
78  * Generate a string representation of a tiles location in a group of nested
79  * tiles. The string returned consists of groups of two digits separated by a
80  * delimiter. Each group of digits the tiles location with respect to it's
81  * parent tile.
82  *
83  * Returns: the path representing the tiles's location
84  */
85 gchar *grits_tile_get_path(GritsTile *child)
86 {
87         /* This could be easily cached if necessary */
88         int x, y;
89         GList *parts = NULL;
90         for (GritsTile *parent = child->parent; parent; child = parent, parent = child->parent)
91                 grits_tile_foreach_index(child, x, y)
92                         if (parent->children[x][y] == child)
93                                 parts = g_list_prepend(parts, grits_tile_path_table[x][y]);
94         GString *path = g_string_new("");
95         for (GList *cur = parts; cur; cur = cur->next)
96                 g_string_append(path, cur->data);
97         g_list_free(parts);
98         return g_string_free(path, FALSE);
99 }
100
101 static gdouble _grits_tile_get_min_dist(GritsPoint *eye, GritsBounds *bounds)
102 {
103         GritsPoint pos = {};
104         pos.lat = eye->lat > bounds->n ? bounds->n :
105                   eye->lat < bounds->s ? bounds->s : eye->lat;
106         pos.lon = eye->lon > bounds->e ? bounds->e :
107                   eye->lon < bounds->w ? bounds->w : eye->lon;
108         //if (eye->lat == pos.lat && eye->lon == pos.lon)
109         //      return elev; /* Shortcut? */
110         gdouble a[3], b[3];
111         lle2xyz(eye->lat, eye->lon, eye->elev, a+0, a+1, a+2);
112         lle2xyz(pos.lat,  pos.lon,  pos.elev,  b+0, b+1, b+2);
113         return distd(a, b);
114 }
115
116 static gboolean _grits_tile_precise(GritsPoint *eye, GritsBounds *bounds,
117                 gdouble max_res, gint width, gint height)
118 {
119         gdouble min_dist  = _grits_tile_get_min_dist(eye, bounds);
120         gdouble view_res  = MPPX(min_dist);
121
122         gdouble lat_point = bounds->n < 0 ? bounds->n :
123                             bounds->s > 0 ? bounds->s : 0;
124         gdouble lon_dist  = bounds->e - bounds->w;
125         gdouble tile_res  = ll2m(lon_dist, lat_point)/width;
126
127         /* This isn't really right, but it helps with memory since we don't
128          * (yet?) test if the tile would be drawn */
129         gdouble scale = eye->elev / min_dist;
130         view_res /= scale;
131         view_res *= 1.8;
132         //view_res /= 1.4; /* make it a little nicer, not sure why this is needed */
133         //g_message("tile=(%7.2f %7.2f %7.2f %7.2f) "
134         //          "eye=(%9.1f %9.1f %9.1f) "
135         //          "elev=%9.1f / dist=%9.1f = %f",
136         //              bounds->n, bounds->s, bounds->e, bounds->w,
137         //              eye->lat, eye->lon, eye->elev,
138         //              eye->elev, min_dist, scale);
139
140         return tile_res < max_res ||
141                tile_res < view_res;
142 }
143
144 static void _grits_tile_split_latlon(GritsTile *tile)
145 {
146         //g_debug("GritsTile: split - %p", tile);
147         const gdouble rows = G_N_ELEMENTS(tile->children);
148         const gdouble cols = G_N_ELEMENTS(tile->children[0]);
149         const gdouble lat_dist = tile->edge.n - tile->edge.s;
150         const gdouble lon_dist = tile->edge.e - tile->edge.w;
151         const gdouble lat_step = lat_dist / rows;
152         const gdouble lon_step = lon_dist / cols;
153
154         int row, col;
155         grits_tile_foreach_index(tile, row, col) {
156                 if (!tile->children[row][col])
157                         tile->children[row][col] =
158                                 grits_tile_new(tile, 0, 0, 0, 0);
159                 /* Set edges aferwards so that north and south
160                  * get reset for mercator projections */
161                 GritsTile *child = tile->children[row][col];
162                 child->edge.n = tile->edge.n - lat_step*(row+0);
163                 child->edge.s = tile->edge.n - lat_step*(row+1);
164                 child->edge.e = tile->edge.w + lon_step*(col+1);
165                 child->edge.w = tile->edge.w + lon_step*(col+0);
166         }
167 }
168
169 static void _grits_tile_split_mercator(GritsTile *tile)
170 {
171         GritsTile *child = NULL;
172         GritsBounds tmp = tile->edge;
173
174         /* Project */
175         tile->edge.n = asinh(tan(deg2rad(tile->edge.n)));
176         tile->edge.s = asinh(tan(deg2rad(tile->edge.s)));
177
178         _grits_tile_split_latlon(tile);
179
180         /* Convert back to lat-lon */
181         tile->edge = tmp;
182         grits_tile_foreach(tile, child) {
183                 child->edge.n = rad2deg(atan(sinh(child->edge.n)));
184                 child->edge.s = rad2deg(atan(sinh(child->edge.s)));
185         }
186 }
187
188 /**
189  * grits_tile_update:
190  * @root:      the root tile to split
191  * @eye:       the point the tile is viewed from, for calculating distances
192  * @res:       a maximum resolution in meters per pixel to split tiles to
193  * @width:     width in pixels of the image associated with the tile
194  * @height:    height in pixels of the image associated with the tile
195  * @load_func: function used to load the image when a new tile is created
196  * @user_data: user data to past to the load function
197  *
198  * Recursively split a tile into children of appropriate detail. The resolution
199  * of the tile in pixels per meter is compared to the resolution which the tile
200  * is being drawn at on the screen. If the screen resolution is insufficient
201  * the tile is recursively subdivided until a sufficient resolution is
202  * achieved.
203  */
204 void grits_tile_update(GritsTile *tile, GritsPoint *eye,
205                 gdouble res, gint width, gint height,
206                 GritsTileLoadFunc load_func, gpointer user_data)
207 {
208         GritsTile *child;
209
210         if (tile == NULL)
211                 return;
212
213         //g_debug("GritsTile: update - %p->atime = %u",
214         //              tile, (guint)tile->atime);
215
216         /* Is the parent tile's texture high enough
217          * resolution for this part? */
218         gint xs = G_N_ELEMENTS(tile->children);
219         gint ys = G_N_ELEMENTS(tile->children[0]);
220         if (tile->parent && _grits_tile_precise(eye, &tile->edge,
221                                 res, width/xs, height/ys)) {
222                 GRITS_OBJECT(tile)->hidden = TRUE;
223                 return;
224         }
225
226         /* Load the tile */
227         if (!tile->load && !tile->data && !tile->tex && !tile->pixels && !tile->pixbuf)
228                 load_func(tile, user_data);
229         tile->atime = time(NULL);
230         tile->load  = TRUE;
231         GRITS_OBJECT(tile)->hidden = FALSE;
232
233         /* Split tile if needed */
234         grits_tile_foreach(tile, child) {
235                 if (child == NULL) {
236                         switch (tile->proj) {
237                         case GRITS_PROJ_LATLON:   _grits_tile_split_latlon(tile);   break;
238                         case GRITS_PROJ_MERCATOR: _grits_tile_split_mercator(tile); break;
239                         }
240                 }
241         }
242
243         /* Update recursively */
244         grits_tile_foreach(tile, child)
245                 grits_tile_update(child, eye, res, width, height,
246                                 load_func, user_data);
247 }
248
249 static void _grits_tile_queue_draw(GritsTile *tile)
250 {
251         while (!GRITS_OBJECT(tile)->viewer && tile->parent)
252                 tile = tile->parent;
253         grits_object_queue_draw(GRITS_OBJECT(tile));
254 }
255
256 /**
257  * grits_tile_load_pixels:
258  * @tile:   the tile to load data into
259  * @pixels: buffered pixel data
260  * @width:  width of the pixel buffer (in pixels)
261  * @height: height of the pixel buffer (in pixels)
262  * @alpha:  TRUE if the pixel data contains an alpha channel
263  *
264  * Load tile data from an in memory pixel buffer.
265  *
266  * This function is thread safe and my be called from outside the main thread.
267  *
268  * Ownership of the pixel buffer is passed to the tile, it should not be freed
269  * or modified after calling this function.
270  *
271  * Returns: TRUE if the image was loaded successfully
272  */
273 gboolean grits_tile_load_pixels(GritsTile *tile, guchar *pixels,
274                 gint width, gint height, gint alpha)
275 {
276         g_debug("GritsTile: load_pixels - %p -> %p (%dx%d:%d)",
277                         tile, pixels, width, height, alpha);
278
279         /* Copy pixbuf data for callback */
280         tile->width  = width;
281         tile->height = height;
282         tile->alpha  = alpha;
283         tile->pixels = pixels;
284
285         /* Queue OpenGL texture load/draw */
286         _grits_tile_queue_draw(tile);
287
288         return TRUE;
289 }
290
291 /**
292  * grits_tile_load_file:
293  * @tile: the tile to load data into
294  * @file: path to an image file to load
295  *
296  * Load tile data from a GdkPixbuf
297  * This function is thread safe and my be called from outside the main thread.
298  *
299  * Returns: TRUE if the image was loaded successfully
300  */
301 gboolean grits_tile_load_pixbuf(GritsTile *tile, GdkPixbuf *pixbuf)
302 {
303         g_debug("GritsTile: load_pixbuf %p -> %p", tile, pixbuf);
304
305         /* Copy pixbuf data for callback */
306         tile->pixbuf = g_object_ref(pixbuf);
307         tile->width  = gdk_pixbuf_get_width(pixbuf);
308         tile->height = gdk_pixbuf_get_height(pixbuf);
309         tile->alpha  = gdk_pixbuf_get_has_alpha(pixbuf);
310
311         /* Queue OpenGL texture load/draw */
312         _grits_tile_queue_draw(tile);
313
314         return TRUE;
315 }
316
317 /**
318  * grits_tile_load_file:
319  * @tile: the tile to load data into
320  * @file: path to an image file to load
321  *
322  * Load tile data from an image file
323  * This function is thread safe and my be called from outside the main thread.
324  *
325  * Returns: TRUE if the image was loaded successfully
326  */
327 gboolean grits_tile_load_file(GritsTile *tile, const gchar *file)
328 {
329         g_debug("GritsTile: load_file %p -> %s", tile, file);
330
331         /* Copy pixbuf data for callback */
332         tile->pixbuf = gdk_pixbuf_new_from_file(file, NULL);
333         if (!tile->pixbuf)
334                 return FALSE;
335         tile->width  = gdk_pixbuf_get_width(tile->pixbuf);
336         tile->height = gdk_pixbuf_get_height(tile->pixbuf);
337         tile->alpha  = gdk_pixbuf_get_has_alpha(tile->pixbuf);
338
339         /* Queue OpenGL texture load/draw */
340         _grits_tile_queue_draw(tile);
341
342         return TRUE;
343 }
344
345 /**
346  * grits_tile_find:
347  * @root: the root tile to search from
348  * @lat:  target latitude
349  * @lon:  target longitude
350  *
351  * Locate the subtile with the highest resolution which contains the given
352  * lat/lon point.
353  *
354  * Returns: the child tile
355  */
356 GritsTile *grits_tile_find(GritsTile *root, gdouble lat, gdouble lon)
357 {
358         gint    rows = G_N_ELEMENTS(root->children);
359         gint    cols = G_N_ELEMENTS(root->children[0]);
360
361         gdouble lat_step = (root->edge.n - root->edge.s) / rows;
362         gdouble lon_step = (root->edge.e - root->edge.w) / cols;
363
364         gdouble lat_offset = root->edge.n - lat;;
365         gdouble lon_offset = lon - root->edge.w;
366
367         gint    row = lat_offset / lat_step;
368         gint    col = lon_offset / lon_step;
369
370         if (lon == 180) col--;
371         if (lat == -90) row--;
372
373         //if (lon == 180 || lon == -180)
374         //      g_message("lat=%f,lon=%f step=%f,%f off=%f,%f row=%d/%d,col=%d/%d",
375         //              lat,lon, lat_step,lon_step, lat_offset,lon_offset, row,rows,col,cols);
376
377         if (row < 0 || row >= rows || col < 0 || col >= cols)
378                 return NULL;
379         else if (root->children[row][col] && root->children[row][col]->data)
380                 return grits_tile_find(root->children[row][col], lat, lon);
381         else
382                 return root;
383 }
384
385 /**
386  * grits_tile_gc:
387  * @root:      the root tile to start garbage collection at
388  * @atime:     most recent time at which tiles will be kept
389  * @free_func: function used to free the image when a new tile is collected
390  * @user_data: user data to past to the free function
391  *
392  * Garbage collect old tiles. This removes and deallocate tiles that have not
393  * been used since before @atime.
394  *
395  * Returns: a pointer to the original tile, or NULL if it was garbage collected
396  */
397 GritsTile *grits_tile_gc(GritsTile *root, time_t atime,
398                 GritsTileFreeFunc free_func, gpointer user_data)
399 {
400         if (!root)
401                 return NULL;
402         gboolean has_children = FALSE;
403         int x, y;
404         grits_tile_foreach_index(root, x, y) {
405                 root->children[x][y] = grits_tile_gc(
406                                 root->children[x][y], atime,
407                                 free_func, user_data);
408                 if (root->children[x][y])
409                         has_children = TRUE;
410         }
411         //g_debug("GritsTile: gc - %p kids=%d time=%d data=%d load=%d",
412         //      root, !!has_children, root->atime < atime, !!root->data, !!root->load);
413         int thread_safe = !root->load || root->data || root->tex || root->pixels || root->pixbuf;
414         if (root->parent && !has_children && root->atime < atime && thread_safe) {
415                 //g_debug("GritsTile: gc/free - %p", root);
416                 if (root->pixbuf)
417                         g_object_unref(root->pixbuf);
418                 if (root->pixels)
419                         g_free(root->pixels);
420                 if (root->tex)
421                         glDeleteTextures(1, &root->tex);
422                 if (root->data) {
423                         if (free_func)
424                                 free_func(root, user_data);
425                         else
426                                 g_free(root->data);
427                 }
428                 g_object_unref(root);
429                 return NULL;
430         }
431         return root;
432 }
433
434 /* Use GObject for this */
435 /**
436  * grits_tile_free:
437  * @root:      the root tile to free
438  * @free_func: function used to free the image when a new tile is collected
439  * @user_data: user data to past to the free function
440  *
441  * Recursively free a tile and all it's children.
442  */
443 void grits_tile_free(GritsTile *root, GritsTileFreeFunc free_func, gpointer user_data)
444 {
445         if (!root)
446                 return;
447         GritsTile *child;
448         grits_tile_foreach(root, child)
449                 grits_tile_free(child, free_func, user_data);
450         if (free_func)
451                 free_func(root, user_data);
452         g_object_unref(root);
453 }
454
455 /* Load texture mask so we can draw a texture to just a part of a triangle */
456 static guint _grits_tile_load_mask(void)
457 {
458         guint tex;
459         const int width = 256, height = 256;
460         guint8 *bytes = g_malloc(width*height);
461         memset(bytes, 0xff, width*height);
462         glGenTextures(1, &tex);
463         glBindTexture(GL_TEXTURE_2D, tex);
464
465         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0,
466                         GL_ALPHA, GL_UNSIGNED_BYTE, bytes);
467
468         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
469         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
470
471         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
472         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
473         g_free(bytes);
474         return tex;
475 }
476
477 /* Load the texture from saved pixel data */
478 static gboolean _grits_tile_load_tex(GritsTile *tile)
479 {
480         /* Abort for null tiles */
481         if (!tile)
482                 return FALSE;
483
484         /* Defer loading of hidden tiles */
485         if (GRITS_OBJECT(tile)->hidden)
486                 return FALSE;
487
488         /* If we're already done loading the text stop */
489         if (tile->tex)
490                 return TRUE;
491
492         /* Check if the tile has data yet */
493         if (!tile->pixels && !tile->pixbuf)
494                 return FALSE;
495
496         /* Get correct pixel buffer */
497         guchar *pixels = tile->pixels ?:
498                 gdk_pixbuf_get_pixels(tile->pixbuf);
499
500         /* Create texture */
501         g_debug("GritsTile: load_tex");
502         glGenTextures(1, &tile->tex);
503         glBindTexture(GL_TEXTURE_2D, tile->tex);
504
505         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
506         glPixelStorei(GL_PACK_ALIGNMENT, 1);
507         glTexImage2D(GL_TEXTURE_2D, 0, 4, tile->width, tile->height, 0,
508                         (tile->alpha ? GL_RGBA : GL_RGB), GL_UNSIGNED_BYTE, pixels);
509         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
510         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
511         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
512         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
513
514         /* Free data */
515         if (tile->pixbuf) {
516                 g_object_unref(tile->pixbuf);
517                 tile->pixbuf = NULL;
518         }
519         if (tile->pixels) {
520                 g_free(tile->pixels);
521                 tile->pixels = NULL;
522         }
523
524         return TRUE;
525
526 }
527
528 /* Draw a single tile */
529 static void grits_tile_draw_one(GritsTile *tile, GritsOpenGL *opengl, GList *triangles)
530 {
531         if (!tile || !tile->tex)
532                 return;
533         if (!triangles)
534                 g_warning("GritsOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
535                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
536
537         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
538         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
539         tile->atime = time(NULL);
540
541         gdouble n = tile->edge.n;
542         gdouble s = tile->edge.s;
543         gdouble e = tile->edge.e;
544         gdouble w = tile->edge.w;
545
546         gdouble londist = e - w;
547         gdouble latdist = n - s;
548
549         gdouble xscale = tile->coords.e - tile->coords.w;
550         gdouble yscale = tile->coords.s - tile->coords.n;
551
552         glPolygonOffset(0, -tile->zindex);
553
554         for (GList *cur = triangles; cur; cur = cur->next) {
555                 RoamTriangle *tri = cur->data;
556
557                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
558                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
559
560                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
561                         if (lon[0] > 90) lon[0] -= 360;
562                         if (lon[1] > 90) lon[1] -= 360;
563                         if (lon[2] > 90) lon[2] -= 360;
564                 }
565
566                 gdouble xy[3][2] = {
567                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
568                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
569                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
570                 };
571
572                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
573                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
574                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
575                 //      g_message("w,e=%4.f,%4.f   "
576                 //                "lat,lon,x,y="
577                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
578                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
579                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
580                 //              w,e,
581                 //              lat[0], lon[0], xy[0][0], xy[0][1],
582                 //              lat[1], lon[1], xy[1][0], xy[1][1],
583                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
584
585                 /* Fix poles */
586                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
587                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
588                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
589
590                 /* Scale to tile coords */
591                 for (int i = 0; i < 3; i++) {
592                         xy[i][0] = tile->coords.w + xy[i][0]*xscale;
593                         xy[i][1] = tile->coords.n + xy[i][1]*yscale;
594                 }
595
596                 /* Draw triangle */
597                 glBindTexture(GL_TEXTURE_2D, tile->tex);
598                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
599                 glBegin(GL_TRIANGLES);
600                 glNormal3dv(tri->p.r->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[0]); glMultiTexCoord2dv(GL_TEXTURE1, xy[0]); glVertex3dv((double*)tri->p.r);
601                 glNormal3dv(tri->p.m->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[1]); glMultiTexCoord2dv(GL_TEXTURE1, xy[1]); glVertex3dv((double*)tri->p.m);
602                 glNormal3dv(tri->p.l->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[2]); glMultiTexCoord2dv(GL_TEXTURE1, xy[2]); glVertex3dv((double*)tri->p.l);
603                 glEnd();
604         }
605 }
606
607 /* Draw the tile */
608 static gboolean grits_tile_draw_rec(GritsTile *tile, GritsOpenGL *opengl)
609 {
610         //g_debug("GritsTile: draw_rec - tile=%p, data=%d, load=%d, hide=%d", tile,
611         //              tile ? !!tile->data : 0,
612         //              tile ? !!tile->load : 0,
613         //              tile ? !!GRITS_OBJECT(tile)->hidden : 0);
614
615         if (!_grits_tile_load_tex(tile))
616                 return FALSE;
617
618         GritsTile *child = NULL;
619
620         /* Draw child tiles */
621         gboolean draw_parent = FALSE;
622         grits_tile_foreach(tile, child)
623                 if (!grits_tile_draw_rec(child, opengl))
624                         draw_parent = TRUE;
625
626         /* Draw parent tile underneath using depth test */
627         if (draw_parent) {
628                 GList *triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
629                                 tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
630                 grits_tile_draw_one(tile, opengl, triangles);
631                 g_list_free(triangles);
632         }
633
634         return TRUE;
635 }
636
637 static void grits_tile_draw(GritsObject *tile, GritsOpenGL *opengl)
638 {
639         glEnable(GL_DEPTH_TEST);
640         glDepthFunc(GL_LESS);
641         glEnable(GL_ALPHA_TEST);
642         glAlphaFunc(GL_GREATER, 0.1);
643         glEnable(GL_POLYGON_OFFSET_FILL);
644         glEnable(GL_BLEND);
645
646         /* Setup texture mask */
647         if (!grits_tile_mask)
648                 grits_tile_mask = _grits_tile_load_mask();
649         glActiveTexture(GL_TEXTURE1);
650         glEnable(GL_TEXTURE_2D);
651         glBindTexture(GL_TEXTURE_2D, grits_tile_mask);
652         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
653
654         /* Setup texture */
655         glActiveTexture(GL_TEXTURE0);
656         glEnable(GL_TEXTURE_2D);
657
658         /* Hack to show maps tiles with better color */
659         if (GRITS_TILE(tile)->proj == GRITS_PROJ_MERCATOR) {
660                 float material_emission[] = {0.5, 0.5, 0.5, 1.0};
661                 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
662         }
663
664         /* Draw all tiles */
665         grits_tile_draw_rec(GRITS_TILE(tile), opengl);
666
667         /* Disable texture mask */
668         glActiveTexture(GL_TEXTURE1);
669         glDisable(GL_TEXTURE_2D);
670         glActiveTexture(GL_TEXTURE0);
671 }
672
673
674 /* GObject code */
675 G_DEFINE_TYPE(GritsTile, grits_tile, GRITS_TYPE_OBJECT);
676 static void grits_tile_init(GritsTile *tile)
677 {
678 }
679
680 static void grits_tile_class_init(GritsTileClass *klass)
681 {
682         g_debug("GritsTile: class_init");
683         GritsObjectClass *object_class = GRITS_OBJECT_CLASS(klass);
684         object_class->draw = grits_tile_draw;
685 }