]> Pileus Git - grits/blob - src/roam.c
Store "kids" in RoamTriangle only
[grits] / src / roam.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:roam
20  * @short_description: Realtime Optimally-Adapting Meshes
21  *
22  * A spherical version of the Realtime Optimally-Adapting Meshes (ROAM)
23  * algorithm is use for drawing the surface of the planet. ROAM provide a
24  * continuous level-of-detail mesh of the planet which is used by #GisOpenGL
25  * when drawing surface textures for GisTiles.
26  *
27  * This implementation of the ROAM algorithm is based on an octahedron as the
28  * base model.
29  */
30
31 #include <glib.h>
32 #include <math.h>
33 #include <string.h>
34 #include <GL/gl.h>
35 #include <GL/glu.h>
36
37 #include "gpqueue.h"
38 #include "gis-util.h"
39 #include "roam.h"
40
41 /*
42  * TODO:
43  *   - Optimize for memory consumption
44  *   - Profile for computation speed
45  *   - Target polygon count/detail
46  */
47
48 /* For GPQueue comparators */
49 static gint tri_cmp(RoamTriangle *a, RoamTriangle *b, gpointer data)
50 {
51         if      (a->error < b->error) return  1;
52         else if (a->error > b->error) return -1;
53         else                          return  0;
54 }
55 static gint dia_cmp(RoamDiamond *a, RoamDiamond *b, gpointer data)
56 {
57         if      (a->error < b->error) return -1;
58         else if (a->error > b->error) return  1;
59         else                          return  0;
60 }
61
62
63 /*************
64  * RoamPoint *
65  *************/
66 /**
67  * roam_point_new:
68  * @lat:  the latitude for the point
69  * @lon:  the longitude for the point
70  * @elev: the elevation for the point
71  *
72  * Create a new point at the given locaiton
73  *
74  * Returns: the new point
75  */
76 RoamPoint *roam_point_new(gdouble lat, gdouble lon, gdouble elev)
77 {
78         RoamPoint *point = g_new0(RoamPoint, 1);
79         point->lat  = lat;
80         point->lon  = lon;
81         point->elev = elev;
82         /* For get_intersect */
83         lle2xyz(lat, lon, elev, &point->x, &point->y, &point->z);
84         return point;
85 }
86
87 /**
88  * roam_point_add_triangle:
89  * @point:    the point
90  * @triangle: the to add
91  *
92  * Associating a triangle with a point and update it's vertex normal.
93  */
94 void roam_point_add_triangle(RoamPoint *point, RoamTriangle *triangle)
95 {
96         for (int i = 0; i < 3; i++) {
97                 point->norm[i] *= point->tris;
98                 point->norm[i] += triangle->norm[i];
99         }
100         point->tris++;
101         for (int i = 0; i < 3; i++)
102                 point->norm[i] /= point->tris;
103 }
104
105 /**
106  * roam_point_remove_triangle:
107  * @point:    the point
108  * @triangle: the to add
109  *
110  * Un-associating a triangle with a point and update it's vertex normal.
111  */
112 void roam_point_remove_triangle(RoamPoint *point, RoamTriangle *triangle)
113 {
114         for (int i = 0; i < 3; i++) {
115                 point->norm[i] *= point->tris;
116                 point->norm[i] -= triangle->norm[i];
117         }
118         point->tris--;
119         if (point->tris)
120                 for (int i = 0; i < 3; i++)
121                         point->norm[i] /= point->tris;
122 }
123
124 /**
125  * roam_point_update_height:
126  * @point: the point
127  *
128  * Update the height (elevation) of a point based on the current height function
129  */
130 void roam_point_update_height(RoamPoint *point)
131 {
132         if (point->height_func) {
133                 gdouble elev = point->height_func(
134                                 point->lat, point->lon, point->height_data);
135                 lle2xyz(point->lat, point->lon, elev,
136                                 &point->x, &point->y, &point->z);
137         }
138 }
139
140 /**
141  * roam_point_update_projection:
142  * @point: the point
143  * @view:  the view to use when projecting the point
144  *
145  * Updated the screen-space projection of a point.
146  */
147 void roam_point_update_projection(RoamPoint *point, RoamView *view)
148 {
149         static int count   = 0;
150         static int version = 0;
151         if (version != view->version) {
152                 g_debug("RoamPoint: Projected %d points", count);
153                 count   = 0;
154                 version = view->version;
155         }
156
157         if (point->pversion != view->version) {
158                 /* Cache projection */
159                 gluProject(point->x, point->y, point->z,
160                         view->model, view->proj, view->view,
161                         &point->px, &point->py, &point->pz);
162                 point->pversion = view->version;
163                 count++;
164         }
165 }
166
167 /****************
168  * RoamTriangle *
169  ****************/
170 /**
171  * roam_triangle_new:
172  * @l: the left point
173  * @m: the middle point
174  * @r: the right point
175  *
176  * Create a new triangle consisting of three points. 
177  *
178  * Returns: the new triangle
179  */
180 RoamTriangle *roam_triangle_new(RoamPoint *l, RoamPoint *m, RoamPoint *r,
181                 RoamDiamond *parent)
182 {
183         RoamTriangle *triangle = g_new0(RoamTriangle, 1);
184
185         triangle->error  = 0;
186         triangle->p.l    = l;
187         triangle->p.m    = m;
188         triangle->p.r    = r;
189         triangle->parent = parent;
190         triangle->split  = roam_point_new(
191                 (l->lat + r->lat)/2,
192                 (ABS(l->lat) == 90 ? r->lon :
193                  ABS(r->lat) == 90 ? l->lon :
194                  lon_avg(l->lon, r->lon)),
195                 (l->elev + r->elev)/2);
196         /* TODO: Move this back to sphere, or actually use the nesting */
197         triangle->split->height_func = m->height_func;
198         triangle->split->height_data = m->height_data;
199         roam_point_update_height(triangle->split);
200         //if ((float)triangle->split->lat > 44 && (float)triangle->split->lat < 46)
201         //      g_debug("RoamTriangle: new - (l,m,r,split).lats = %7.2f %7.2f %7.2f %7.2f",
202         //                      l->lat, m->lat, r->lat, triangle->split->lat);
203         //if ((float)l->lat == (float)r->lat &&
204         //    (float)triangle->split->lat != (float)l->lat)
205         //      g_warning("RoamTriangle: new - split.lat=%f != (l=r).lat=%f",
206         //              triangle->split->lat, l->lat);
207
208         /* Update normal */
209         double pa[3];
210         double pb[3];
211         pa[0] = triangle->p.l->x - triangle->p.m->x;
212         pa[1] = triangle->p.l->y - triangle->p.m->y;
213         pa[2] = triangle->p.l->z - triangle->p.m->z;
214
215         pb[0] = triangle->p.r->x - triangle->p.m->x;
216         pb[1] = triangle->p.r->y - triangle->p.m->y;
217         pb[2] = triangle->p.r->z - triangle->p.m->z;
218
219         triangle->norm[0] = pa[1] * pb[2] - pa[2] * pb[1];
220         triangle->norm[1] = pa[2] * pb[0] - pa[0] * pb[2];
221         triangle->norm[2] = pa[0] * pb[1] - pa[1] * pb[0];
222
223         double total = sqrt(triangle->norm[0] * triangle->norm[0] +
224                             triangle->norm[1] * triangle->norm[1] +
225                             triangle->norm[2] * triangle->norm[2]);
226
227         triangle->norm[0] /= total;
228         triangle->norm[1] /= total;
229         triangle->norm[2] /= total;
230
231         /* Store bounding box, for get_intersect */
232         RoamPoint *p[] = {l,m,r};
233         triangle->edge.n =  -90; triangle->edge.s =  90;
234         triangle->edge.e = -180; triangle->edge.w = 180;
235         gboolean maxed = FALSE;
236         for (int i = 0; i < G_N_ELEMENTS(p); i++) {
237                 triangle->edge.n = MAX(triangle->edge.n, p[i]->lat);
238                 triangle->edge.s = MIN(triangle->edge.s, p[i]->lat);
239                 if (p[i]->lat == 90 || p[i]->lat == -90)
240                         continue;
241                 if (p[i]->lon == 180) {
242                         maxed = TRUE;
243                         continue;
244                 }
245                 triangle->edge.e = MAX(triangle->edge.e, p[i]->lon);
246                 triangle->edge.w = MIN(triangle->edge.w, p[i]->lon);
247         }
248         if (maxed) {
249                 if (triangle->edge.e < 0)
250                         triangle->edge.w = -180;
251                 else
252                         triangle->edge.e =  180;
253         }
254
255         //g_message("roam_triangle_new: %p", triangle);
256         return triangle;
257 }
258
259 /**
260  * roam_triangle_free:
261  * @triangle: the triangle
262  *
263  * Free data associated with a triangle
264  */
265 void roam_triangle_free(RoamTriangle *triangle)
266 {
267         g_free(triangle->split);
268         g_free(triangle);
269 }
270
271 /**
272  * roam_triangle_add:
273  * @triangle: the triangle
274  * @left:     the left neighbor
275  * @base:     the base neighbor
276  * @right:    the right neighbor
277  * @sphere:   the sphere to add the triangle to
278  *
279  * Add a triangle into the sphere's mesh using the given neighbors.
280  */
281 void roam_triangle_add(RoamTriangle *triangle,
282                 RoamTriangle *left, RoamTriangle *base, RoamTriangle *right,
283                 RoamSphere *sphere)
284 {
285         triangle->t.l = left;
286         triangle->t.b = base;
287         triangle->t.r = right;
288
289         roam_point_add_triangle(triangle->p.l, triangle);
290         roam_point_add_triangle(triangle->p.m, triangle);
291         roam_point_add_triangle(triangle->p.r, triangle);
292
293         if (sphere->view)
294                 roam_triangle_update_errors(triangle, sphere);
295
296         triangle->handle = g_pqueue_push(sphere->triangles, triangle);
297 }
298
299 /**
300  * roam_triangle_remove:
301  * @triangle: the triangle
302  * @sphere:   the sphere to remove the triangle from
303  *
304  * Remove a triangle from a sphere's mesh.
305  */
306 void roam_triangle_remove(RoamTriangle *triangle, RoamSphere *sphere)
307 {
308         /* Update vertex normals */
309         roam_point_remove_triangle(triangle->p.l, triangle);
310         roam_point_remove_triangle(triangle->p.m, triangle);
311         roam_point_remove_triangle(triangle->p.r, triangle);
312
313         g_pqueue_remove(sphere->triangles, triangle->handle);
314 }
315
316 static void roam_triangle_sync_neighbors(RoamTriangle *new, RoamTriangle *old, RoamTriangle *neigh)
317 {
318         if      (neigh->t.l == old) neigh->t.l = new;
319         else if (neigh->t.b == old) neigh->t.b = new;
320         else if (neigh->t.r == old) neigh->t.r = new;
321         else g_assert_not_reached();
322 }
323
324 static gboolean roam_triangle_visible(RoamTriangle *triangle, RoamSphere *sphere)
325 {
326         RoamPoint *l = triangle->p.l;
327         RoamPoint *m = triangle->p.m;
328         RoamPoint *r = triangle->p.r;
329         gdouble min_x = MIN(MIN(l->px, m->px), r->px);
330         gdouble max_x = MAX(MAX(l->px, m->px), r->px);
331         gdouble min_y = MIN(MIN(l->py, m->py), r->py);
332         gdouble max_y = MAX(MAX(l->py, m->py), r->py);
333         gint *view = sphere->view->view;
334         return !(max_x < view[0] || min_x > view[2] ||
335                  max_y < view[1] || min_y > view[3]) &&
336                  l->pz > 0 && m->pz > 0 && r->pz > 0 &&
337                  l->pz < 1 && m->pz < 1 && r->pz < 1;
338 }
339
340 /**
341  * roam_triangle_update_errors:
342  * @triangle: the triangle
343  * @sphere:   the sphere to use when updating errors
344  *
345  * Update the error value associated with a triangle. Called when the view
346  * changes.
347  */
348 void roam_triangle_update_errors(RoamTriangle *triangle, RoamSphere *sphere)
349 {
350         /* Update points */
351         roam_point_update_projection(triangle->p.l, sphere->view);
352         roam_point_update_projection(triangle->p.m, sphere->view);
353         roam_point_update_projection(triangle->p.r, sphere->view);
354
355         if (!roam_triangle_visible(triangle, sphere)) {
356                 triangle->error = -1;
357         } else {
358                 roam_point_update_projection(triangle->split, sphere->view);
359                 RoamPoint *l     = triangle->p.l;
360                 RoamPoint *m     = triangle->p.m;
361                 RoamPoint *r     = triangle->p.r;
362                 RoamPoint *split = triangle->split;
363
364                 /*               l-r midpoint        projected l-r midpoint */
365                 gdouble pxdist = (l->px + r->px)/2 - split->px;
366                 gdouble pydist = (l->py + r->py)/2 - split->py;
367
368                 triangle->error = sqrt(pxdist*pxdist + pydist*pydist);
369
370                 /* Multiply by size of triangle */
371                 double size = -( l->px * (m->py - r->py) +
372                                  m->px * (r->py - l->py) +
373                                  r->px * (l->py - m->py) ) / 2.0;
374
375                 /* Size < 0 == backface */
376                 triangle->error *= size;
377         }
378 }
379
380 /**
381  * roam_triangle_split:
382  * @triangle: the triangle
383  * @sphere:   the sphere
384  *
385  * Split a triangle into two child triangles and update the sphere.
386  * triangle
387  */
388 void roam_triangle_split(RoamTriangle *triangle, RoamSphere *sphere)
389 {
390         //g_message("roam_triangle_split: %p, e=%f\n", triangle, triangle->error);
391
392         sphere->polys += 2;
393
394         if (triangle != triangle->t.b->t.b)
395                 roam_triangle_split(triangle->t.b, sphere);
396         if (triangle != triangle->t.b->t.b)
397                 g_assert_not_reached();
398
399         RoamTriangle *s = triangle;      // Self
400         RoamTriangle *b = triangle->t.b; // Base
401
402         RoamDiamond *dia = roam_diamond_new(s, b);
403
404         /* Add new triangles */
405         RoamPoint *mid = triangle->split;
406         RoamTriangle *sl = s->kids[0] = roam_triangle_new(s->p.m, mid, s->p.l, dia); // Self Left
407         RoamTriangle *sr = s->kids[1] = roam_triangle_new(s->p.r, mid, s->p.m, dia); // Self Right
408         RoamTriangle *bl = b->kids[0] = roam_triangle_new(b->p.m, mid, b->p.l, dia); // Base Left
409         RoamTriangle *br = b->kids[1] = roam_triangle_new(b->p.r, mid, b->p.m, dia); // Base Right
410
411         /*                triangle,l,  base,      r,  sphere */
412         roam_triangle_add(sl, sr, s->t.l, br, sphere);
413         roam_triangle_add(sr, bl, s->t.r, sl, sphere);
414         roam_triangle_add(bl, br, b->t.l, sr, sphere);
415         roam_triangle_add(br, sl, b->t.r, bl, sphere);
416
417         roam_triangle_sync_neighbors(sl, s, s->t.l);
418         roam_triangle_sync_neighbors(sr, s, s->t.r);
419         roam_triangle_sync_neighbors(bl, b, b->t.l);
420         roam_triangle_sync_neighbors(br, b, b->t.r);
421
422         /* Remove old triangles */
423         roam_triangle_remove(s, sphere);
424         roam_triangle_remove(b, sphere);
425
426         /* Add/Remove diamonds */
427         roam_diamond_update_errors(dia, sphere);
428         roam_diamond_add(dia, sphere);
429         roam_diamond_remove(s->parent, sphere);
430         roam_diamond_remove(b->parent, sphere);
431 }
432
433 /**
434  * roam_triangle_draw:
435  * @triangle: the triangle
436  *
437  * Draw the triangle. Use for debugging.
438  */
439 void roam_triangle_draw(RoamTriangle *triangle)
440 {
441         glBegin(GL_TRIANGLES);
442         glNormal3dv(triangle->p.r->norm); glVertex3dv((double*)triangle->p.r);
443         glNormal3dv(triangle->p.m->norm); glVertex3dv((double*)triangle->p.m);
444         glNormal3dv(triangle->p.l->norm); glVertex3dv((double*)triangle->p.l);
445         glEnd();
446         return;
447 }
448
449 /**
450  * roam_triangle_draw_normal:
451  * @triangle: the triangle
452  *
453  * Draw a normal vector for the triangle. Used while debugging.
454  */
455 void roam_triangle_draw_normal(RoamTriangle *triangle)
456 {
457         double center[] = {
458                 (triangle->p.l->x + triangle->p.m->x + triangle->p.r->x)/3.0,
459                 (triangle->p.l->y + triangle->p.m->y + triangle->p.r->y)/3.0,
460                 (triangle->p.l->z + triangle->p.m->z + triangle->p.r->z)/3.0,
461         };
462         double end[] = {
463                 center[0]+triangle->norm[0]*2000000,
464                 center[1]+triangle->norm[1]*2000000,
465                 center[2]+triangle->norm[2]*2000000,
466         };
467         glBegin(GL_LINES);
468         glVertex3dv(center);
469         glVertex3dv(end);
470         glEnd();
471 }
472
473 /***************
474  * RoamDiamond *
475  ***************/
476 /**
477  * roam_diamond_new:
478  * @parent0: a parent triangle
479  * @parent1: a parent triangle
480  * @kid0:    a child triangle
481  * @kid1:    a child triangle
482  * @kid2:    a child triangle
483  * @kid3:    a child triangle
484  *
485  * Create a diamond to store information about two split triangles.
486  *
487  * Returns: the new diamond
488  */
489 RoamDiamond *roam_diamond_new(RoamTriangle *parent0, RoamTriangle *parent1)
490 {
491         RoamDiamond *diamond = g_new0(RoamDiamond, 1);
492         diamond->parents[0] = parent0;
493         diamond->parents[1] = parent1;
494         return diamond;
495 }
496
497 /**
498  * roam_diamond_add:
499  * @diamond: the diamond
500  * @sphere:  the sphere to add the diamond to
501  *
502  * Add a diamond into the sphere's pool of diamonds. It will be check for
503  * possible merges.
504  */
505 void roam_diamond_add(RoamDiamond *diamond, RoamSphere *sphere)
506 {
507         diamond->active = TRUE;
508         diamond->error  = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
509         diamond->handle = g_pqueue_push(sphere->diamonds, diamond);
510 }
511
512 /**
513  * roam_diamond_remove:
514  * @diamond: the diamond
515  * @sphere:  the sphere to remove the diamond from
516  *
517  * Remove a diamond from the sphere's pool of diamonds.
518  */
519 void roam_diamond_remove(RoamDiamond *diamond, RoamSphere *sphere)
520 {
521         if (diamond && diamond->active) {
522                 diamond->active = FALSE;
523                 g_pqueue_remove(sphere->diamonds, diamond->handle);
524         }
525 }
526
527 /**
528  * roam_diamond_merge:
529  * @diamond: the diamond
530  * @sphere:  the sphere
531  *
532  * "Merge" a diamond back into two parent triangles. The original two triangles
533  * are added back into the sphere and the four child triangles as well as the
534  * diamond are removed.
535  */
536 void roam_diamond_merge(RoamDiamond *diamond, RoamSphere *sphere)
537 {
538         //g_message("roam_diamond_merge: %p, e=%f\n", diamond, diamond->error);
539
540         /* TODO: pick the best split */
541         sphere->polys -= 2;
542
543         /* Use nicer temp names */
544         RoamTriangle *s = diamond->parents[0]; // Self
545         RoamTriangle *b = diamond->parents[1]; // Base
546
547         RoamTriangle *sl = s->kids[0];
548         RoamTriangle *sr = s->kids[1];
549         RoamTriangle *bl = b->kids[0];
550         RoamTriangle *br = b->kids[1];
551
552         s->kids[0] = s->kids[1] = NULL;
553         b->kids[0] = b->kids[1] = NULL;
554
555         /* Add original triangles */
556         roam_triangle_add(s, sl->t.b, b, sr->t.b, sphere);
557         roam_triangle_add(b, bl->t.b, s, br->t.b, sphere);
558
559         roam_triangle_sync_neighbors(s, sl, sl->t.b);
560         roam_triangle_sync_neighbors(s, sr, sr->t.b);
561         roam_triangle_sync_neighbors(b, bl, bl->t.b);
562         roam_triangle_sync_neighbors(b, br, br->t.b);
563
564         /* Remove child triangles */
565         roam_triangle_remove(sl, sphere);
566         roam_triangle_remove(sr, sphere);
567         roam_triangle_remove(bl, sphere);
568         roam_triangle_remove(br, sphere);
569
570         /* Add/Remove triangles */
571         if (s->t.l->t.l == s->t.r->t.r &&
572             s->t.l->t.l != s && s->parent) {
573                 roam_diamond_update_errors(s->parent, sphere);
574                 roam_diamond_add(s->parent, sphere);
575         }
576
577         if (b->t.l->t.l == b->t.r->t.r &&
578             b->t.l->t.l != b && b->parent) {
579                 roam_diamond_update_errors(b->parent, sphere);
580                 roam_diamond_add(b->parent, sphere);
581         }
582
583         /* Remove and free diamond and child triangles */
584         roam_diamond_remove(diamond, sphere);
585         g_assert(sl->p.m == sr->p.m &&
586                  sr->p.m == bl->p.m &&
587                  bl->p.m == br->p.m);
588         g_assert(sl->p.m->tris == 0);
589         roam_triangle_free(sl);
590         roam_triangle_free(sr);
591         roam_triangle_free(bl);
592         roam_triangle_free(br);
593         g_free(diamond);
594 }
595
596 /**
597  * roam_diamond_update_errors:
598  * @diamond: the diamond
599  * @sphere:  the sphere to use when updating errors
600  *
601  * Update the error value associated with a diamond. Called when the view
602  * changes.
603  */
604 void roam_diamond_update_errors(RoamDiamond *diamond, RoamSphere *sphere)
605 {
606         roam_triangle_update_errors(diamond->parents[0], sphere);
607         roam_triangle_update_errors(diamond->parents[1], sphere);
608         diamond->error = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
609 }
610
611 /**************
612  * RoamSphere *
613  **************/
614 /**
615  * roam_sphere_new:
616  *
617  * Create a new sphere
618  *
619  * Returns: the sphere
620  */
621 RoamSphere *roam_sphere_new()
622 {
623         RoamSphere *sphere = g_new0(RoamSphere, 1);
624         sphere->polys       = 8;
625         sphere->triangles   = g_pqueue_new((GCompareDataFunc)tri_cmp, NULL);
626         sphere->diamonds    = g_pqueue_new((GCompareDataFunc)dia_cmp, NULL);
627
628         RoamPoint *vertexes[] = {
629                 roam_point_new( 90,   0,  0), // 0 (North)
630                 roam_point_new(-90,   0,  0), // 1 (South)
631                 roam_point_new(  0,   0,  0), // 2 (Europe/Africa)
632                 roam_point_new(  0,  90,  0), // 3 (Asia,East)
633                 roam_point_new(  0, 180,  0), // 4 (Pacific)
634                 roam_point_new(  0, -90,  0), // 5 (Americas,West)
635         };
636         int _triangles[][2][3] = {
637                 /*lv mv rv   ln, bn, rn */
638                 {{2,0,3}, {3, 4, 1}}, // 0
639                 {{3,0,4}, {0, 5, 2}}, // 1
640                 {{4,0,5}, {1, 6, 3}}, // 2
641                 {{5,0,2}, {2, 7, 0}}, // 3
642                 {{3,1,2}, {5, 0, 7}}, // 4
643                 {{4,1,3}, {6, 1, 4}}, // 5
644                 {{5,1,4}, {7, 2, 5}}, // 6
645                 {{2,1,5}, {4, 3, 6}}, // 7
646         };
647
648         for (int i = 0; i < 6; i++)
649                 roam_point_update_height(vertexes[i]);
650         for (int i = 0; i < 8; i++)
651                 sphere->roots[i] = roam_triangle_new(
652                         vertexes[_triangles[i][0][0]],
653                         vertexes[_triangles[i][0][1]],
654                         vertexes[_triangles[i][0][2]],
655                         NULL);
656         for (int i = 0; i < 8; i++)
657                 roam_triangle_add(sphere->roots[i],
658                         sphere->roots[_triangles[i][1][0]],
659                         sphere->roots[_triangles[i][1][1]],
660                         sphere->roots[_triangles[i][1][2]],
661                         sphere);
662         for (int i = 0; i < 8; i++)
663                 g_debug("RoamSphere: new - %p edge=%f,%f,%f,%f", sphere->roots[i],
664                                 sphere->roots[i]->edge.n,
665                                 sphere->roots[i]->edge.s,
666                                 sphere->roots[i]->edge.e,
667                                 sphere->roots[i]->edge.w);
668
669         return sphere;
670 }
671
672 /**
673  * roam_sphere_update_view
674  * @sphere: the sphere
675  *
676  * Recreate the sphere's view matrices based on the current OpenGL state.
677  */
678 void roam_sphere_update_view(RoamSphere *sphere)
679 {
680         if (!sphere->view)
681                 sphere->view = g_new0(RoamView, 1);
682         glGetDoublev (GL_MODELVIEW_MATRIX,  sphere->view->model);
683         glGetDoublev (GL_PROJECTION_MATRIX, sphere->view->proj);
684         glGetIntegerv(GL_VIEWPORT,          sphere->view->view);
685         sphere->view->version++;
686 }
687
688 /**
689  * roam_sphere_update_errors
690  * @sphere: the sphere
691  *
692  * Update triangle and diamond errors in the sphere.
693  */
694 void roam_sphere_update_errors(RoamSphere *sphere)
695 {
696         g_debug("RoamSphere: update_errors - polys=%d", sphere->polys);
697         GPtrArray *tris = g_pqueue_get_array(sphere->triangles);
698         GPtrArray *dias = g_pqueue_get_array(sphere->diamonds);
699
700         roam_sphere_update_view(sphere);
701
702         for (int i = 0; i < tris->len; i++) {
703                 RoamTriangle *triangle = tris->pdata[i];
704                 roam_triangle_update_errors(triangle, sphere);
705                 g_pqueue_priority_changed(sphere->triangles, triangle->handle);
706         }
707
708         for (int i = 0; i < dias->len; i++) {
709                 RoamDiamond *diamond = dias->pdata[i];
710                 roam_diamond_update_errors(diamond, sphere);
711                 g_pqueue_priority_changed(sphere->diamonds, diamond->handle);
712         }
713
714         g_ptr_array_free(tris, TRUE);
715         g_ptr_array_free(dias, TRUE);
716 }
717
718 /**
719  * roam_sphere_split_one
720  * @sphere: the sphere
721  *
722  * Split the triangle with the greatest error.
723  */
724 void roam_sphere_split_one(RoamSphere *sphere)
725 {
726         RoamTriangle *to_split = g_pqueue_peek(sphere->triangles);
727         if (!to_split) return;
728         roam_triangle_split(to_split, sphere);
729 }
730
731 /**
732  * roam_sphere_merge_one
733  * @sphere: the sphere
734  *
735  * Merge the diamond with the lowest error.
736  */
737 void roam_sphere_merge_one(RoamSphere *sphere)
738 {
739         RoamDiamond *to_merge = g_pqueue_peek(sphere->diamonds);
740         if (!to_merge) return;
741         roam_diamond_merge(to_merge, sphere);
742 }
743
744 /**
745  * roam_sphere_split_merge
746  * @sphere: the sphere
747  *
748  * Perform a predetermined number split-merge iterations.
749  *
750  * Returns: the number splits and merges done
751  */
752 gint roam_sphere_split_merge(RoamSphere *sphere)
753 {
754         gint iters = 0, max_iters = 500;
755         //gint target = 4000;
756         gint target = 2000;
757         //gint target = 500;
758
759         if (!sphere->view)
760                 return 0;
761
762         if (target - sphere->polys > 100) {
763                 //g_debug("RoamSphere: split_merge - Splitting %d - %d > 100", target, sphere->polys);
764                 while (sphere->polys < target && iters++ < max_iters)
765                         roam_sphere_split_one(sphere);
766         }
767
768         if (sphere->polys - target > 100) {
769                 //g_debug("RoamSphere: split_merge - Merging %d - %d > 100", sphere->polys, target);
770                 while (sphere->polys > target && iters++ < max_iters)
771                         roam_sphere_merge_one(sphere);
772         }
773
774         while (((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error >
775                ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error &&
776                iters++ < max_iters) {
777                 //g_debug("RoamSphere: split_merge - Fixing 1 %f > %f && %d < %d",
778                 //              ((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error,
779                 //              ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error,
780                 //              iters-1, max_iters);
781                 roam_sphere_merge_one(sphere);
782                 roam_sphere_split_one(sphere);
783         }
784
785         return iters;
786 }
787
788 /**
789  * roam_sphere_draw:
790  * @sphere: the sphere
791  *
792  * Draw the sphere. Use for debugging.
793  */
794 void roam_sphere_draw(RoamSphere *sphere)
795 {
796         g_debug("RoamSphere: draw");
797         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw, NULL);
798 }
799
800 /**
801  * roam_sphere_draw_normals
802  * @sphere: the sphere
803  *
804  * Draw all the surface normal vectors for the sphere. Used while debugging.
805  */
806 void roam_sphere_draw_normals(RoamSphere *sphere)
807 {
808         g_debug("RoamSphere: draw_normal");
809         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw_normal, NULL);
810 }
811
812 static GList *_roam_sphere_get_leaves(RoamTriangle *triangle, GList *list, gboolean all)
813 {
814         if (triangle->kids[0] && triangle->kids[1]) {
815                 if (all) list = g_list_prepend(list, triangle);
816                 list = _roam_sphere_get_leaves(triangle->kids[0], list, all);
817                 list = _roam_sphere_get_leaves(triangle->kids[1], list, all);
818                 return list;
819         } else {
820                 return g_list_prepend(list, triangle);
821         }
822 }
823
824 static GList *_roam_sphere_get_intersect_rec(RoamTriangle *triangle, GList *list,
825                 gboolean all, gdouble n, gdouble s, gdouble e, gdouble w)
826 {
827         gdouble tn = triangle->edge.n;
828         gdouble ts = triangle->edge.s;
829         gdouble te = triangle->edge.e;
830         gdouble tw = triangle->edge.w;
831
832         gboolean debug = FALSE  &&
833                 n==90 && s==45 && e==-90 && w==-180 &&
834                 ts > 44 && ts < 46;
835
836         if (debug)
837                 g_message("t=%p: %f < %f || %f > %f || %f < %f || %f > %f",
838                             triangle, tn,   s,   ts,   n,   te,   w,   tw,   e);
839         if (tn <= s || ts >= n || te <= w || tw >= e) {
840                 /* No intersect */
841                 if (debug) g_message("no intersect");
842                 return list;
843         } else if (tn <= n && ts >= s && te <= e && tw >= w) {
844                 /* Triangle is completely contained */
845                 if (debug) g_message("contained");
846                 if (all) list = g_list_prepend(list, triangle);
847                 return _roam_sphere_get_leaves(triangle, list, all);
848         } else if (triangle->kids[0] && triangle->kids[1]) {
849                 /* Paritial intersect with children */
850                 if (debug) g_message("edge w/ child");
851                 if (all) list = g_list_prepend(list, triangle);
852                 list = _roam_sphere_get_intersect_rec(triangle->kids[0], list, all, n, s, e, w);
853                 list = _roam_sphere_get_intersect_rec(triangle->kids[1], list, all, n, s, e, w);
854                 return list;
855         } else {
856                 /* This triangle is an edge case */
857                 if (debug) g_message("edge");
858                 return g_list_prepend(list, triangle);
859         }
860 }
861
862 /**
863  * roam_sphere_get_intersect
864  * @sphere: the sphere
865  * @all: TRUE if non-leaf triangle should be returned as well
866  * @n: the northern edge 
867  * @s: the southern edge 
868  * @e: the eastern edge 
869  * @w: the western edge 
870  *
871  * Lookup triangles withing the sphere that intersect a given lat-lon box.
872  *
873  * Returns: the list of intersecting triangles.
874  */
875 /* Warning: This grabs pointers to triangles which can be changed by other
876  * calls, e.g. split_merge. If you use this, you need to do some locking to
877  * prevent the returned list from becomming stale. */
878 GList *roam_sphere_get_intersect(RoamSphere *sphere, gboolean all,
879                 gdouble n, gdouble s, gdouble e, gdouble w)
880 {
881         /* I think this is correct..
882          * i_cost = cost for triangle-rectagnle intersect test
883          * time = n_tiles * 2*tris_per_tile * i_cost
884          * time = 30      * 2*333           * i_cost = 20000 * i_cost */
885         GList *list = NULL;
886         for (int i = 0; i < G_N_ELEMENTS(sphere->roots); i++)
887                 list = _roam_sphere_get_intersect_rec(sphere->roots[i],
888                                 list, all, n, s, e, w);
889         return list;
890 }
891
892 static void roam_sphere_free_tri(RoamTriangle *triangle)
893 {
894         if (--triangle->p.l->tris == 0) g_free(triangle->p.l);
895         if (--triangle->p.m->tris == 0) g_free(triangle->p.m);
896         if (--triangle->p.r->tris == 0) g_free(triangle->p.r);
897         roam_triangle_free(triangle);
898 }
899
900 /**
901  * roam_sphere_free
902  * @sphere: the sphere
903  *
904  * Free data associated with a sphere
905  */
906 void roam_sphere_free(RoamSphere *sphere)
907 {
908         g_debug("RoamSphere: free");
909         /* Slow method, but it should work */
910         while (sphere->polys > 8)
911                 roam_sphere_merge_one(sphere);
912         /* TODO: free points */
913         g_pqueue_foreach(sphere->triangles, (GFunc)roam_sphere_free_tri, NULL);
914         g_pqueue_free(sphere->triangles);
915         g_pqueue_free(sphere->diamonds);
916         g_free(sphere->view);
917         g_free(sphere);
918 }