]> Pileus Git - grits/blob - src/objects/grits-tile.c
Fix memory leaks in tile loading
[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 #include <config.h>
36 #include <math.h>
37 #include "gtkgl.h"
38 #include "grits-tile.h"
39
40 guint  grits_tile_mask = 0;
41
42 gchar *grits_tile_path_table[2][2] = {
43         {"00.", "01."},
44         {"10.", "11."},
45 };
46
47 /**
48  * grits_tile_new:
49  * @parent: the parent for the tile, or NULL
50  * @n:      the northern border of the tile
51  * @s:      the southern border of the tile
52  * @e:      the eastern border of the tile
53  * @w:      the western border of the tile
54  *
55  * Create a tile associated with a particular latitude/longitude box.
56  *
57  * Returns: the new #GritsTile
58  */
59 GritsTile *grits_tile_new(GritsTile *parent,
60         gdouble n, gdouble s, gdouble e, gdouble w)
61 {
62         GritsTile *tile = g_object_new(GRITS_TYPE_TILE, NULL);
63         tile->parent = parent;
64         tile->atime  = time(NULL);
65         grits_bounds_set_bounds(&tile->coords, 0, 1, 1, 0);
66         grits_bounds_set_bounds(&tile->edge, n, s, e, w);
67         if (parent) {
68                 tile->proj   = parent->proj;
69                 tile->zindex = parent->zindex+1;
70         }
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         const gdouble rows = G_N_ELEMENTS(tile->children);
147         const gdouble cols = G_N_ELEMENTS(tile->children[0]);
148         const gdouble lat_dist = tile->edge.n - tile->edge.s;
149         const gdouble lon_dist = tile->edge.e - tile->edge.w;
150         const gdouble lat_step = lat_dist / rows;
151         const gdouble lon_step = lon_dist / cols;
152
153         int row, col;
154         grits_tile_foreach_index(tile, row, col) {
155                 if (!tile->children[row][col])
156                         tile->children[row][col] =
157                                 grits_tile_new(tile, 0, 0, 0, 0);
158                 /* Set edges aferwards so that north and south
159                  * get reset for mercator projections */
160                 GritsTile *child = tile->children[row][col];
161                 child->edge.n = tile->edge.n - lat_step*(row+0);
162                 child->edge.s = tile->edge.n - lat_step*(row+1);
163                 child->edge.e = tile->edge.w + lon_step*(col+1);
164                 child->edge.w = tile->edge.w + lon_step*(col+0);
165         }
166 }
167
168 static void _grits_tile_split_mercator(GritsTile *tile)
169 {
170         GritsTile *child = NULL;
171         GritsBounds tmp = tile->edge;
172
173         /* Project */
174         tile->edge.n = asinh(tan(deg2rad(tile->edge.n)));
175         tile->edge.s = asinh(tan(deg2rad(tile->edge.s)));
176
177         _grits_tile_split_latlon(tile);
178
179         /* Convert back to lat-lon */
180         tile->edge = tmp;
181         grits_tile_foreach(tile, child) {
182                 child->edge.n = rad2deg(atan(sinh(child->edge.n)));
183                 child->edge.s = rad2deg(atan(sinh(child->edge.s)));
184         }
185 }
186
187 /**
188  * grits_tile_update:
189  * @root:      the root tile to split
190  * @eye:       the point the tile is viewed from, for calculating distances
191  * @res:       a maximum resolution in meters per pixel to split tiles to
192  * @width:     width in pixels of the image associated with the tile
193  * @height:    height in pixels of the image associated with the tile
194  * @load_func: function used to load the image when a new tile is created
195  * @user_data: user data to past to the load function
196  *
197  * Recursively split a tile into children of appropriate detail. The resolution
198  * of the tile in pixels per meter is compared to the resolution which the tile
199  * is being drawn at on the screen. If the screen resolution is insufficient
200  * the tile is recursively subdivided until a sufficient resolution is
201  * achieved.
202  */
203 void grits_tile_update(GritsTile *tile, GritsPoint *eye,
204                 gdouble res, gint width, gint height,
205                 GritsTileLoadFunc load_func, gpointer user_data)
206 {
207         GritsTile *child;
208
209         if (tile == NULL)
210                 return;
211
212         //g_debug("GritsTile: update - %p->atime = %u",
213         //              tile, (guint)tile->atime);
214
215         /* Is the parent tile's texture high enough
216          * resolution for this part? */
217         gint xs = G_N_ELEMENTS(tile->children);
218         gint ys = G_N_ELEMENTS(tile->children[0]);
219         if (_grits_tile_precise(eye, &tile->edge, res, width/xs, height/ys)) {
220                 GRITS_OBJECT(tile)->hidden = TRUE;
221                 return;
222         }
223
224         /* Load the tile */
225         if (!tile->load && !tile->data)
226                 load_func(tile, user_data);
227         tile->atime = time(NULL);
228         tile->load  = TRUE;
229         GRITS_OBJECT(tile)->hidden = FALSE;
230
231         /* Split tile if needed */
232         grits_tile_foreach(tile, child) {
233                 if (child == NULL) {
234                         switch (tile->proj) {
235                         case GRITS_PROJ_LATLON:   _grits_tile_split_latlon(tile);   break;
236                         case GRITS_PROJ_MERCATOR: _grits_tile_split_mercator(tile); break;
237                         }
238                 }
239         }
240
241         /* Update recursively */
242         grits_tile_foreach(tile, child)
243                 grits_tile_update(child, eye, res, width, height,
244                                 load_func, user_data);
245 }
246
247 /**
248  * grits_tile_find:
249  * @root: the root tile to search from
250  * @lat:  target latitude
251  * @lon:  target longitude
252  *
253  * Locate the subtile with the highest resolution which contains the given
254  * lat/lon point.
255  * 
256  * Returns: the child tile
257  */
258 GritsTile *grits_tile_find(GritsTile *root, gdouble lat, gdouble lon)
259 {
260         gint    rows = G_N_ELEMENTS(root->children);
261         gint    cols = G_N_ELEMENTS(root->children[0]);
262
263         gdouble lat_step = (root->edge.n - root->edge.s) / rows;
264         gdouble lon_step = (root->edge.e - root->edge.w) / cols;
265
266         gdouble lat_offset = root->edge.n - lat;;
267         gdouble lon_offset = lon - root->edge.w;
268
269         gint    row = lat_offset / lat_step;
270         gint    col = lon_offset / lon_step;
271
272         if (lon == 180) col--;
273         if (lat == -90) row--;
274
275         //if (lon == 180 || lon == -180)
276         //      g_message("lat=%f,lon=%f step=%f,%f off=%f,%f row=%d/%d,col=%d/%d",
277         //              lat,lon, lat_step,lon_step, lat_offset,lon_offset, row,rows,col,cols);
278
279         if (row < 0 || row >= rows || col < 0 || col >= cols)
280                 return NULL;
281         else if (root->children[row][col] && root->children[row][col]->data)
282                 return grits_tile_find(root->children[row][col], lat, lon);
283         else
284                 return root;
285 }
286
287 /**
288  * grits_tile_gc:
289  * @root:      the root tile to start garbage collection at
290  * @atime:     most recent time at which tiles will be kept
291  * @free_func: function used to free the image when a new tile is collected
292  * @user_data: user data to past to the free function
293  *
294  * Garbage collect old tiles. This removes and deallocate tiles that have not
295  * been used since before @atime.
296  *
297  * Returns: a pointer to the original tile, or NULL if it was garbage collected
298  */
299 GritsTile *grits_tile_gc(GritsTile *root, time_t atime,
300                 GritsTileFreeFunc free_func, gpointer user_data)
301 {
302         if (!root)
303                 return NULL;
304         gboolean has_children = FALSE;
305         int x, y;
306         grits_tile_foreach_index(root, x, y) {
307                 root->children[x][y] = grits_tile_gc(
308                                 root->children[x][y], atime,
309                                 free_func, user_data);
310                 if (root->children[x][y])
311                         has_children = TRUE;
312         }
313         //g_debug("GritsTile: gc - %p->atime=%u < atime=%u",
314         //              root, (guint)root->atime, (guint)atime);
315         if (!has_children && root->atime < atime &&
316                         (root->data || !root->load)) {
317                 if (root->data)
318                         free_func(root, user_data);
319                 g_object_unref(root);
320                 return NULL;
321         }
322         return root;
323 }
324
325 /* Use GObject for this */
326 /**
327  * grits_tile_free:
328  * @root:      the root tile to free
329  * @free_func: function used to free the image when a new tile is collected
330  * @user_data: user data to past to the free function
331  *
332  * Recursively free a tile and all it's children.
333  */
334 void grits_tile_free(GritsTile *root, GritsTileFreeFunc free_func, gpointer user_data)
335 {
336         if (!root)
337                 return;
338         GritsTile *child;
339         grits_tile_foreach(root, child)
340                 grits_tile_free(child, free_func, user_data);
341         if (free_func)
342                 free_func(root, user_data);
343         g_object_unref(root);
344 }
345
346 /* Load texture mask so we can draw a texture to just a part of a triangle */
347 static guint _grits_tile_load_mask(void)
348 {
349         guint  tex;
350         guint8 byte = 0xff;
351         glGenTextures(1, &tex);
352         glBindTexture(GL_TEXTURE_2D, tex);
353
354         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1, 1, 0,
355                         GL_ALPHA, GL_UNSIGNED_BYTE, &byte);
356
357         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
358         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
359
360         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
361         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
362         return tex;
363 }
364
365 /* Draw a single tile */
366 static void grits_tile_draw_one(GritsTile *tile, GritsOpenGL *opengl, GList *triangles)
367 {
368         if (!tile || !tile->data)
369                 return;
370         if (!triangles)
371                 g_warning("GritsOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
372                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
373         if (!grits_tile_mask)
374                 grits_tile_mask = _grits_tile_load_mask();
375
376         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
377         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
378         tile->atime = time(NULL);
379
380         gdouble n = tile->edge.n;
381         gdouble s = tile->edge.s;
382         gdouble e = tile->edge.e;
383         gdouble w = tile->edge.w;
384
385         gdouble londist = e - w;
386         gdouble latdist = n - s;
387
388         gdouble xscale = tile->coords.e - tile->coords.w;
389         gdouble yscale = tile->coords.s - tile->coords.n;
390
391         for (GList *cur = triangles; cur; cur = cur->next) {
392                 RoamTriangle *tri = cur->data;
393
394                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
395                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
396
397                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
398                         if (lon[0] > 90) lon[0] -= 360;
399                         if (lon[1] > 90) lon[1] -= 360;
400                         if (lon[2] > 90) lon[2] -= 360;
401                 }
402
403                 gdouble xy[3][2] = {
404                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
405                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
406                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
407                 };
408
409                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
410                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
411                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
412                 //      g_message("w,e=%4.f,%4.f   "
413                 //                "lat,lon,x,y="
414                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
415                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
416                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
417                 //              w,e,
418                 //              lat[0], lon[0], xy[0][0], xy[0][1],
419                 //              lat[1], lon[1], xy[1][0], xy[1][1],
420                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
421
422                 /* Fix poles */
423                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
424                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
425                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
426
427                 /* Scale to tile coords */
428                 for (int i = 0; i < 3; i++) {
429                         xy[i][0] = tile->coords.w + xy[i][0]*xscale;
430                         xy[i][1] = tile->coords.n + xy[i][1]*yscale;
431                 }
432
433                 /* Polygon offset */
434                 glEnable(GL_POLYGON_OFFSET_FILL);
435                 glPolygonOffset(0, -tile->zindex);
436
437                 /* Setup texture */
438                 glActiveTexture(GL_TEXTURE0);
439                 glEnable(GL_TEXTURE_2D);
440                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
441                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
442
443                 /* Enable texture mask */
444                 if (tile->proj == GRITS_PROJ_MERCATOR) {
445                         glActiveTexture(GL_TEXTURE1);
446                         glEnable(GL_TEXTURE_2D);
447                         glBindTexture(GL_TEXTURE_2D, grits_tile_mask);
448                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
449
450                         /* Hack to show maps tiles with better color */
451                         float material_emission[] = {0.5, 0.5, 0.5, 1.0};
452                         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
453
454                         glEnable(GL_BLEND);
455                 }
456
457                 /* Draw triangle */
458                 glBegin(GL_TRIANGLES);
459                 glNormal3dv(tri->p.r->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[0]); glMultiTexCoord2dv(GL_TEXTURE1, xy[0]); glVertex3dv((double*)tri->p.r);
460                 glNormal3dv(tri->p.m->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[1]); glMultiTexCoord2dv(GL_TEXTURE1, xy[1]); glVertex3dv((double*)tri->p.m);
461                 glNormal3dv(tri->p.l->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[2]); glMultiTexCoord2dv(GL_TEXTURE1, xy[2]); glVertex3dv((double*)tri->p.l);
462                 glEnd();
463
464                 /* Disable texture mask */
465                 glDisable(GL_TEXTURE_2D);
466                 glActiveTexture(GL_TEXTURE0);
467         }
468 }
469
470 /* Draw the tile */
471 static gboolean grits_tile_draw_rec(GritsTile *tile, GritsOpenGL *opengl)
472 {
473         //g_debug("GritsTile: draw_rec - tile=%p, data=%d, load=%d, hide=%d", tile,
474         //              tile ? !!tile->data : 0,
475         //              tile ? !!tile->load : 0,
476         //              tile ? !!GRITS_OBJECT(tile)->hidden : 0);
477
478         if (!tile || !tile->data || GRITS_OBJECT(tile)->hidden)
479                 return FALSE;
480
481         GritsTile *child = NULL;
482         gboolean   done  = FALSE;
483         while (!done) {
484                 /* Only draw children if possible */
485                 gboolean draw_parent = FALSE;
486                 grits_tile_foreach(tile, child)
487                         if (!child || !child->data || GRITS_OBJECT(child)->hidden)
488                                 draw_parent = TRUE;
489
490                 /* Draw parent tile underneath */
491                 if (draw_parent) {
492                         GList *triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
493                                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
494                         grits_tile_draw_one(tile, opengl, triangles);
495                         g_list_free(triangles);
496                 }
497
498                 /* Draw child tiles */
499                 gboolean drew_all_children = TRUE;
500                 grits_tile_foreach(tile, child)
501                         if (!grits_tile_draw_rec(child, opengl))
502                                 drew_all_children = FALSE;
503
504                 /* Check if tiles were hidden by a thread while drawing */
505                 done = draw_parent || drew_all_children;
506         }
507         return TRUE;
508 }
509
510 static void grits_tile_draw(GritsObject *tile, GritsOpenGL *opengl)
511 {
512         glEnable(GL_DEPTH_TEST);
513         glDepthFunc(GL_LESS);
514         glEnable(GL_ALPHA_TEST);
515         glAlphaFunc(GL_GREATER, 0.1);
516         grits_tile_draw_rec(GRITS_TILE(tile), opengl);
517 }
518
519
520 /* GObject code */
521 G_DEFINE_TYPE(GritsTile, grits_tile, GRITS_TYPE_OBJECT);
522 static void grits_tile_init(GritsTile *tile)
523 {
524 }
525
526 static void grits_tile_class_init(GritsTileClass *klass)
527 {
528         g_debug("GritsTile: class_init");
529         GritsObjectClass *object_class = GRITS_OBJECT_CLASS(klass);
530         object_class->draw = grits_tile_draw;
531 }