]> Pileus Git - grits/blob - src/objects/grits-tile.c
Check for split on all child 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 #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         return tile;
70 }
71
72 /**
73  * grits_tile_get_path:
74  * @child: the tile to generate a path for
75  *
76  * Generate a string representation of a tiles location in a group of nested
77  * tiles. The string returned consists of groups of two digits separated by a
78  * delimiter. Each group of digits the tiles location with respect to it's
79  * parent tile.
80  *
81  * Returns: the path representing the tiles's location
82  */
83 gchar *grits_tile_get_path(GritsTile *child)
84 {
85         /* This could be easily cached if necessary */
86         int x, y;
87         GList *parts = NULL;
88         for (GritsTile *parent = child->parent; parent; child = parent, parent = child->parent)
89                 grits_tile_foreach_index(child, x, y)
90                         if (parent->children[x][y] == child)
91                                 parts = g_list_prepend(parts, grits_tile_path_table[x][y]);
92         GString *path = g_string_new("");
93         for (GList *cur = parts; cur; cur = cur->next)
94                 g_string_append(path, cur->data);
95         g_list_free(parts);
96         return g_string_free(path, FALSE);
97 }
98
99 static gdouble _grits_tile_get_min_dist(GritsPoint *eye, GritsBounds *bounds)
100 {
101         GritsPoint pos = {};
102         pos.lat = eye->lat > bounds->n ? bounds->n :
103                   eye->lat < bounds->s ? bounds->s : eye->lat;
104         pos.lon = eye->lon > bounds->e ? bounds->e :
105                   eye->lon < bounds->w ? bounds->w : eye->lon;
106         //if (eye->lat == pos.lat && eye->lon == pos.lon)
107         //      return elev; /* Shortcut? */
108         gdouble a[3], b[3];
109         lle2xyz(eye->lat, eye->lon, eye->elev, a+0, a+1, a+2);
110         lle2xyz(pos.lat,  pos.lon,  pos.elev,  b+0, b+1, b+2);
111         return distd(a, b);
112 }
113
114 static gboolean _grits_tile_precise(GritsPoint *eye, GritsBounds *bounds,
115                 gdouble max_res, gint width, gint height)
116 {
117         gdouble min_dist  = _grits_tile_get_min_dist(eye, bounds);
118         gdouble view_res  = MPPX(min_dist);
119
120         gdouble lat_point = bounds->n < 0 ? bounds->n :
121                             bounds->s > 0 ? bounds->s : 0;
122         gdouble lon_dist  = bounds->e - bounds->w;
123         gdouble tile_res  = ll2m(lon_dist, lat_point)/width;
124
125         /* This isn't really right, but it helps with memory since we don't
126          * (yet?) test if the tile would be drawn */
127         gdouble scale = eye->elev / min_dist;
128         view_res /= scale;
129         //view_res /= 1.4; /* make it a little nicer, not sure why this is needed */
130         //g_message("tile=(%7.2f %7.2f %7.2f %7.2f) "
131         //          "eye=(%9.1f %9.1f %9.1f) "
132         //          "elev=%9.1f / dist=%9.1f = %f",
133         //              bounds->n, bounds->s, bounds->e, bounds->w,
134         //              eye->lat, eye->lon, eye->elev,
135         //              eye->elev, min_dist, scale);
136
137         return tile_res < max_res ||
138                tile_res < view_res;
139 }
140
141 static void _grits_tile_split_latlon(GritsTile *tile)
142 {
143         const gdouble rows = G_N_ELEMENTS(tile->children);
144         const gdouble cols = G_N_ELEMENTS(tile->children[0]);
145         const gdouble lat_dist = tile->edge.n - tile->edge.s;
146         const gdouble lon_dist = tile->edge.e - tile->edge.w;
147         const gdouble lat_step = lat_dist / rows;
148         const gdouble lon_step = lon_dist / cols;
149
150         int row, col;
151         grits_tile_foreach_index(tile, row, col)
152                 tile->children[row][col] = grits_tile_new(tile,
153                         tile->edge.n - lat_step*(row+0),  // north
154                         tile->edge.n - lat_step*(row+1),  // south
155                         tile->edge.w + lon_step*(col+1),  // east
156                         tile->edge.w + lon_step*(col+0)); // west
157 }
158
159 static void _grits_tile_split_mercator(GritsTile *tile)
160 {
161         GritsTile *child = NULL;
162         GritsBounds tmp = tile->edge;
163
164         /* Project */
165         tile->edge.n = asinh(tan(deg2rad(tile->edge.n)));
166         tile->edge.s = asinh(tan(deg2rad(tile->edge.s)));
167
168         _grits_tile_split_latlon(tile);
169
170         /* Convert back to lat-lon */
171         tile->edge = tmp;
172         grits_tile_foreach(tile, child) {
173                 child->edge.n = rad2deg(atan(sinh(child->edge.n)));
174                 child->edge.s = rad2deg(atan(sinh(child->edge.s)));
175         }
176 }
177
178 /**
179  * grits_tile_update:
180  * @root:      the root tile to split
181  * @eye:       the point the tile is viewed from, for calculating distances
182  * @res:       a maximum resolution in meters per pixel to split tiles to
183  * @width:     width in pixels of the image associated with the tile
184  * @height:    height in pixels of the image associated with the tile
185  * @load_func: function used to load the image when a new tile is created
186  * @user_data: user data to past to the load function
187  *
188  * Recursively split a tile into children of appropriate detail. The resolution
189  * of the tile in pixels per meter is compared to the resolution which the tile
190  * is being drawn at on the screen. If the screen resolution is insufficient
191  * the tile is recursively subdivided until a sufficient resolution is
192  * achieved.
193  */
194 void grits_tile_update(GritsTile *tile, GritsPoint *eye,
195                 gdouble res, gint width, gint height,
196                 GritsTileLoadFunc load_func, gpointer user_data)
197 {
198         //g_debug("GritsTile: update - %p->atime = %u",
199         //              tile, (guint)tile->atime);
200         GritsTile *child;
201
202         if (tile == NULL)
203                 return;
204
205         if (!tile->data)
206                 load_func(tile, user_data);
207
208         tile->atime = time(NULL);
209
210         /* Is this tile high enough resolution? */
211         if (_grits_tile_precise(eye, &tile->edge, res, width, height)) {
212                 grits_tile_foreach(tile, child)
213                         if (child)
214                                 GRITS_OBJECT(child)->hidden = TRUE;
215                 return;
216         }
217
218         /* Split tile if needed */
219         grits_tile_foreach(tile, child) {
220                 if (child == NULL) {
221                         switch (tile->proj) {
222                         case GRITS_PROJ_LATLON:   _grits_tile_split_latlon(tile);   break;
223                         case GRITS_PROJ_MERCATOR: _grits_tile_split_mercator(tile); break;
224                         }
225                 }
226         }
227
228         /* Update recursively */
229         grits_tile_foreach(tile, child) {
230                 GRITS_OBJECT(child)->hidden = FALSE;
231                 grits_tile_update(child, eye, res, width, height,
232                                 load_func, user_data);
233         }
234
235 }
236
237 /**
238  * grits_tile_find:
239  * @root: the root tile to search from
240  * @lat:  target latitude
241  * @lon:  target longitude
242  *
243  * Locate the subtile with the highest resolution which contains the given
244  * lat/lon point.
245  * 
246  * Returns: the child tile
247  */
248 GritsTile *grits_tile_find(GritsTile *root, gdouble lat, gdouble lon)
249 {
250         gint    rows = G_N_ELEMENTS(root->children);
251         gint    cols = G_N_ELEMENTS(root->children[0]);
252
253         gdouble lat_step = (root->edge.n - root->edge.s) / rows;
254         gdouble lon_step = (root->edge.e - root->edge.w) / cols;
255
256         gdouble lat_offset = root->edge.n - lat;;
257         gdouble lon_offset = lon - root->edge.w;
258
259         gint    row = lat_offset / lat_step;
260         gint    col = lon_offset / lon_step;
261
262         if (lon == 180) col--;
263         if (lat == -90) row--;
264
265         //if (lon == 180 || lon == -180)
266         //      g_message("lat=%f,lon=%f step=%f,%f off=%f,%f row=%d/%d,col=%d/%d",
267         //              lat,lon, lat_step,lon_step, lat_offset,lon_offset, row,rows,col,cols);
268
269         if (row < 0 || row >= rows || col < 0 || col >= cols)
270                 return NULL;
271         else if (root->children[row][col] && root->children[row][col]->data)
272                 return grits_tile_find(root->children[row][col], lat, lon);
273         else
274                 return root;
275 }
276
277 /**
278  * grits_tile_gc:
279  * @root:      the root tile to start garbage collection at
280  * @atime:     most recent time at which tiles will be kept
281  * @free_func: function used to free the image when a new tile is collected
282  * @user_data: user data to past to the free function
283  *
284  * Garbage collect old tiles. This removes and deallocate tiles that have not
285  * been used since before @atime.
286  *
287  * Returns: a pointer to the original tile, or NULL if it was garbage collected
288  */
289 GritsTile *grits_tile_gc(GritsTile *root, time_t atime,
290                 GritsTileFreeFunc free_func, gpointer user_data)
291 {
292         if (!root)
293                 return NULL;
294         gboolean has_children = FALSE;
295         int x, y;
296         grits_tile_foreach_index(root, x, y) {
297                 root->children[x][y] = grits_tile_gc(
298                                 root->children[x][y], atime,
299                                 free_func, user_data);
300                 if (root->children[x][y])
301                         has_children = TRUE;
302         }
303         //g_debug("GritsTile: gc - %p->atime=%u < atime=%u",
304         //              root, (guint)root->atime, (guint)atime);
305         if (!has_children && root->atime < atime && root->data) {
306                 free_func(root, user_data);
307                 g_object_unref(root);
308                 return NULL;
309         }
310         return root;
311 }
312
313 /* Use GObject for this */
314 /**
315  * grits_tile_free:
316  * @root:      the root tile to free
317  * @free_func: function used to free the image when a new tile is collected
318  * @user_data: user data to past to the free function
319  *
320  * Recursively free a tile and all it's children.
321  */
322 void grits_tile_free(GritsTile *root, GritsTileFreeFunc free_func, gpointer user_data)
323 {
324         if (!root)
325                 return;
326         GritsTile *child;
327         grits_tile_foreach(root, child)
328                 grits_tile_free(child, free_func, user_data);
329         if (free_func)
330                 free_func(root, user_data);
331         g_object_unref(root);
332 }
333
334 /* Load texture mask so we can draw a texture to just a part of a triangle */
335 static guint _grits_tile_load_mask(void)
336 {
337         guint  tex;
338         guint8 byte = 0xff;
339         glGenTextures(1, &tex);
340         glBindTexture(GL_TEXTURE_2D, tex);
341
342         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1, 1, 0,
343                         GL_ALPHA, GL_UNSIGNED_BYTE, &byte);
344
345         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
346         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
347
348         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
349         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
350         return tex;
351 }
352
353 /* Draw a single tile */
354 static void grits_tile_draw_one(GritsTile *tile, GritsOpenGL *opengl, GList *triangles)
355 {
356         if (!tile || !tile->data)
357                 return;
358         if (!triangles)
359                 g_warning("GritsOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
360                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
361         if (!grits_tile_mask)
362                 grits_tile_mask = _grits_tile_load_mask();
363
364         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
365         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
366         tile->atime = time(NULL);
367
368         gdouble n = tile->edge.n;
369         gdouble s = tile->edge.s;
370         gdouble e = tile->edge.e;
371         gdouble w = tile->edge.w;
372
373         gdouble londist = e - w;
374         gdouble latdist = n - s;
375
376         gdouble xscale = tile->coords.e - tile->coords.w;
377         gdouble yscale = tile->coords.s - tile->coords.n;
378
379         for (GList *cur = triangles; cur; cur = cur->next) {
380                 RoamTriangle *tri = cur->data;
381
382                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
383                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
384
385                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
386                         if (lon[0] > 90) lon[0] -= 360;
387                         if (lon[1] > 90) lon[1] -= 360;
388                         if (lon[2] > 90) lon[2] -= 360;
389                 }
390
391                 gdouble xy[3][2] = {
392                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
393                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
394                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
395                 };
396
397                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
398                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
399                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
400                 //      g_message("w,e=%4.f,%4.f   "
401                 //                "lat,lon,x,y="
402                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
403                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
404                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
405                 //              w,e,
406                 //              lat[0], lon[0], xy[0][0], xy[0][1],
407                 //              lat[1], lon[1], xy[1][0], xy[1][1],
408                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
409
410                 /* Fix poles */
411                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
412                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
413                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
414
415                 /* Scale to tile coords */
416                 for (int i = 0; i < 3; i++) {
417                         xy[i][0] = tile->coords.w + xy[i][0]*xscale;
418                         xy[i][1] = tile->coords.n + xy[i][1]*yscale;
419                 }
420
421                 /* Polygon offset */
422                 glEnable(GL_POLYGON_OFFSET_FILL);
423                 glPolygonOffset(0, -tile->zindex);
424
425                 /* Setup texture */
426                 glActiveTexture(GL_TEXTURE0);
427                 glEnable(GL_TEXTURE_2D);
428                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
429                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
430
431                 /* Enable texture mask */
432                 if (tile->proj == GRITS_PROJ_MERCATOR) {
433                         glActiveTexture(GL_TEXTURE1);
434                         glEnable(GL_TEXTURE_2D);
435                         glBindTexture(GL_TEXTURE_2D, grits_tile_mask);
436                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
437
438                         /* Hack to show maps tiles with better color */
439                         float material_emission[] = {0.5, 0.5, 0.5, 1.0};
440                         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
441
442                         glEnable(GL_BLEND);
443                 }
444
445                 /* Draw triangle */
446                 glBegin(GL_TRIANGLES);
447                 glNormal3dv(tri->p.r->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[0]); glMultiTexCoord2dv(GL_TEXTURE1, xy[0]); glVertex3dv((double*)tri->p.r);
448                 glNormal3dv(tri->p.m->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[1]); glMultiTexCoord2dv(GL_TEXTURE1, xy[1]); glVertex3dv((double*)tri->p.m);
449                 glNormal3dv(tri->p.l->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[2]); glMultiTexCoord2dv(GL_TEXTURE1, xy[2]); glVertex3dv((double*)tri->p.l);
450                 glEnd();
451
452                 /* Disable texture mask */
453                 glDisable(GL_TEXTURE_2D);
454                 glActiveTexture(GL_TEXTURE0);
455         }
456 }
457
458 /* Draw the tile */
459 static gboolean grits_tile_draw_rec(GritsTile *tile, GritsOpenGL *opengl)
460 {
461         if (!tile || !tile->data || GRITS_OBJECT(tile)->hidden)
462                 return FALSE;
463
464         GritsTile *child = NULL;
465         gboolean   done  = FALSE;
466         while (!done) {
467                 /* Only draw children if possible */
468                 gboolean draw_parent = FALSE;
469                 grits_tile_foreach(tile, child)
470                         if (!child || !child->data || GRITS_OBJECT(child)->hidden)
471                                 draw_parent = TRUE;
472
473                 /* Draw parent tile underneath */
474                 if (draw_parent) {
475                         GList *triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
476                                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
477                         grits_tile_draw_one(tile, opengl, triangles);
478                         g_list_free(triangles);
479                 }
480
481                 /* Draw child tiles */
482                 gboolean drew_all_children = TRUE;
483                 grits_tile_foreach(tile, child)
484                         if (!grits_tile_draw_rec(child, opengl))
485                                 drew_all_children = FALSE;
486
487                 /* Check if tiles were hidden by a thread while drawing */
488                 done = draw_parent || drew_all_children;
489         }
490         return TRUE;
491 }
492
493 static void grits_tile_draw(GritsObject *tile, GritsOpenGL *opengl)
494 {
495         glEnable(GL_DEPTH_TEST);
496         glDepthFunc(GL_LESS);
497         glEnable(GL_ALPHA_TEST);
498         glAlphaFunc(GL_GREATER, 0.1);
499         grits_tile_draw_rec(GRITS_TILE(tile), opengl);
500 }
501
502
503 /* GObject code */
504 G_DEFINE_TYPE(GritsTile, grits_tile, GRITS_TYPE_OBJECT);
505 static void grits_tile_init(GritsTile *tile)
506 {
507 }
508
509 static void grits_tile_class_init(GritsTileClass *klass)
510 {
511         g_debug("GritsTile: class_init");
512         GritsObjectClass *object_class = GRITS_OBJECT_CLASS(klass);
513         object_class->draw = grits_tile_draw;
514 }