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