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