]> Pileus Git - grits/blob - src/roam.c
21b1393c6c902b0202d045ffed0821826840934c
[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 /* (neight->t.? == old) = new */
317 static void roam_triangle_sync_neighbors(RoamTriangle *neigh, RoamTriangle *old, RoamTriangle *new)
318 {
319         if      (neigh->t.l == old) neigh->t.l = new;
320         else if (neigh->t.b == old) neigh->t.b = new;
321         else if (neigh->t.r == old) neigh->t.r = new;
322         else g_assert_not_reached();
323 }
324
325 static gboolean roam_triangle_visible(RoamTriangle *triangle, RoamSphere *sphere)
326 {
327         RoamPoint *l = triangle->p.l;
328         RoamPoint *m = triangle->p.m;
329         RoamPoint *r = triangle->p.r;
330         gdouble min_x = MIN(MIN(l->px, m->px), r->px);
331         gdouble max_x = MAX(MAX(l->px, m->px), r->px);
332         gdouble min_y = MIN(MIN(l->py, m->py), r->py);
333         gdouble max_y = MAX(MAX(l->py, m->py), r->py);
334         gint *view = sphere->view->view;
335         return !(max_x < view[0] || min_x > view[2] ||
336                  max_y < view[1] || min_y > view[3]) &&
337                  l->pz > 0 && m->pz > 0 && r->pz > 0 &&
338                  l->pz < 1 && m->pz < 1 && r->pz < 1;
339 }
340
341 /**
342  * roam_triangle_update_errors:
343  * @triangle: the triangle
344  * @sphere:   the sphere to use when updating errors
345  *
346  * Update the error value associated with a triangle. Called when the view
347  * changes.
348  */
349 void roam_triangle_update_errors(RoamTriangle *triangle, RoamSphere *sphere)
350 {
351         /* Update points */
352         roam_point_update_projection(triangle->p.l, sphere->view);
353         roam_point_update_projection(triangle->p.m, sphere->view);
354         roam_point_update_projection(triangle->p.r, sphere->view);
355
356         if (!roam_triangle_visible(triangle, sphere)) {
357                 triangle->error = -1;
358         } else {
359                 roam_point_update_projection(triangle->split, sphere->view);
360                 RoamPoint *l     = triangle->p.l;
361                 RoamPoint *m     = triangle->p.m;
362                 RoamPoint *r     = triangle->p.r;
363                 RoamPoint *split = triangle->split;
364
365                 /*               l-r midpoint        projected l-r midpoint */
366                 gdouble pxdist = (l->px + r->px)/2 - split->px;
367                 gdouble pydist = (l->py + r->py)/2 - split->py;
368
369                 triangle->error = sqrt(pxdist*pxdist + pydist*pydist);
370
371                 /* Multiply by size of triangle */
372                 double size = -( l->px * (m->py - r->py) +
373                                  m->px * (r->py - l->py) +
374                                  r->px * (l->py - m->py) ) / 2.0;
375
376                 /* Size < 0 == backface */
377                 triangle->error *= size;
378         }
379 }
380
381 /**
382  * roam_triangle_split:
383  * @triangle: the triangle
384  * @sphere:   the sphere
385  *
386  * Split a triangle into two child triangles and update the sphere.
387  * triangle
388  */
389 void roam_triangle_split(RoamTriangle *triangle, RoamSphere *sphere)
390 {
391         //g_message("roam_triangle_split: %p, e=%f\n", triangle, triangle->error);
392
393         sphere->polys += 2;
394
395         if (triangle != triangle->t.b->t.b)
396                 roam_triangle_split(triangle->t.b, sphere);
397         if (triangle != triangle->t.b->t.b)
398                 g_assert_not_reached();
399
400         RoamTriangle *s = triangle;      // Self
401         RoamTriangle *b = triangle->t.b; // Base
402
403         RoamDiamond *dia = roam_diamond_new(s, b);
404
405         /* Add new triangles */
406         RoamPoint *mid = triangle->split;
407         RoamTriangle *sl = s->kids[0] = roam_triangle_new(s->p.m, mid, s->p.l, dia); // Self Left
408         RoamTriangle *sr = s->kids[1] = roam_triangle_new(s->p.r, mid, s->p.m, dia); // Self Right
409         RoamTriangle *bl = b->kids[0] = roam_triangle_new(b->p.m, mid, b->p.l, dia); // Base Left
410         RoamTriangle *br = b->kids[1] = roam_triangle_new(b->p.r, mid, b->p.m, dia); // Base Right
411
412         /*                triangle,l,  base,      r,  sphere */
413         roam_triangle_add(sl, sr, s->t.l, br, sphere);
414         roam_triangle_add(sr, bl, s->t.r, sl, sphere);
415         roam_triangle_add(bl, br, b->t.l, sr, sphere);
416         roam_triangle_add(br, sl, b->t.r, bl, sphere);
417
418         roam_triangle_sync_neighbors(s->t.l, s, sl);
419         roam_triangle_sync_neighbors(s->t.r, s, sr);
420         roam_triangle_sync_neighbors(b->t.l, b, bl);
421         roam_triangle_sync_neighbors(b->t.r, b, br);
422
423         /* Remove old triangles */
424         roam_triangle_remove(s, sphere);
425         roam_triangle_remove(b, sphere);
426
427         /* Add/Remove diamonds */
428         roam_diamond_update_errors(dia, sphere);
429         roam_diamond_add(dia, sphere);
430         roam_diamond_remove(s->parent, sphere);
431         roam_diamond_remove(b->parent, sphere);
432 }
433
434 /**
435  * roam_triangle_draw:
436  * @triangle: the triangle
437  *
438  * Draw the triangle. Use for debugging.
439  */
440 void roam_triangle_draw(RoamTriangle *triangle)
441 {
442         glBegin(GL_TRIANGLES);
443         glNormal3dv(triangle->p.r->norm); glVertex3dv((double*)triangle->p.r);
444         glNormal3dv(triangle->p.m->norm); glVertex3dv((double*)triangle->p.m);
445         glNormal3dv(triangle->p.l->norm); glVertex3dv((double*)triangle->p.l);
446         glEnd();
447         return;
448 }
449
450 /**
451  * roam_triangle_draw_normal:
452  * @triangle: the triangle
453  *
454  * Draw a normal vector for the triangle. Used while debugging.
455  */
456 void roam_triangle_draw_normal(RoamTriangle *triangle)
457 {
458         double center[] = {
459                 (triangle->p.l->x + triangle->p.m->x + triangle->p.r->x)/3.0,
460                 (triangle->p.l->y + triangle->p.m->y + triangle->p.r->y)/3.0,
461                 (triangle->p.l->z + triangle->p.m->z + triangle->p.r->z)/3.0,
462         };
463         double end[] = {
464                 center[0]+triangle->norm[0]*2000000,
465                 center[1]+triangle->norm[1]*2000000,
466                 center[2]+triangle->norm[2]*2000000,
467         };
468         glBegin(GL_LINES);
469         glVertex3dv(center);
470         glVertex3dv(end);
471         glEnd();
472 }
473
474 /***************
475  * RoamDiamond *
476  ***************/
477 /**
478  * roam_diamond_new:
479  * @parent0: a parent triangle
480  * @parent1: a parent triangle
481  * @kid0:    a child triangle
482  * @kid1:    a child triangle
483  * @kid2:    a child triangle
484  * @kid3:    a child triangle
485  *
486  * Create a diamond to store information about two split triangles.
487  *
488  * Returns: the new diamond
489  */
490 RoamDiamond *roam_diamond_new(RoamTriangle *parent0, RoamTriangle *parent1)
491 {
492         RoamDiamond *diamond = g_new0(RoamDiamond, 1);
493         diamond->parents[0] = parent0;
494         diamond->parents[1] = parent1;
495         return diamond;
496 }
497
498 /**
499  * roam_diamond_add:
500  * @diamond: the diamond
501  * @sphere:  the sphere to add the diamond to
502  *
503  * Add a diamond into the sphere's pool of diamonds. It will be check for
504  * possible merges.
505  */
506 void roam_diamond_add(RoamDiamond *diamond, RoamSphere *sphere)
507 {
508         diamond->active = TRUE;
509         diamond->error  = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
510         diamond->handle = g_pqueue_push(sphere->diamonds, diamond);
511 }
512
513 /**
514  * roam_diamond_remove:
515  * @diamond: the diamond
516  * @sphere:  the sphere to remove the diamond from
517  *
518  * Remove a diamond from the sphere's pool of diamonds.
519  */
520 void roam_diamond_remove(RoamDiamond *diamond, RoamSphere *sphere)
521 {
522         if (diamond && diamond->active) {
523                 diamond->active = FALSE;
524                 g_pqueue_remove(sphere->diamonds, diamond->handle);
525         }
526 }
527
528 /**
529  * roam_diamond_merge:
530  * @diamond: the diamond
531  * @sphere:  the sphere
532  *
533  * "Merge" a diamond back into two parent triangles. The original two triangles
534  * are added back into the sphere and the four child triangles as well as the
535  * diamond are removed.
536  */
537 void roam_diamond_merge(RoamDiamond *diamond, RoamSphere *sphere)
538 {
539         //g_message("roam_diamond_merge: %p, e=%f\n", diamond, diamond->error);
540
541         /* TODO: pick the best split */
542         sphere->polys -= 2;
543
544         /* Use nicer temp names */
545         RoamTriangle *s = diamond->parents[0]; // Self
546         RoamTriangle *b = diamond->parents[1]; // Base
547
548         RoamTriangle *sl = s->kids[0];
549         RoamTriangle *sr = s->kids[1];
550         RoamTriangle *bl = b->kids[0];
551         RoamTriangle *br = b->kids[1];
552
553         s->kids[0] = s->kids[1] = NULL;
554         b->kids[0] = b->kids[1] = NULL;
555
556         /* Add original triangles */
557         roam_triangle_add(s, sl->t.b, b, sr->t.b, sphere);
558         roam_triangle_add(b, bl->t.b, s, br->t.b, sphere);
559
560         roam_triangle_sync_neighbors(sl->t.b, sl, s);
561         roam_triangle_sync_neighbors(sr->t.b, sr, s);
562         roam_triangle_sync_neighbors(bl->t.b, bl, b);
563         roam_triangle_sync_neighbors(br->t.b, br, b);
564
565         /* Remove child triangles */
566         roam_triangle_remove(sl, sphere);
567         roam_triangle_remove(sr, sphere);
568         roam_triangle_remove(bl, sphere);
569         roam_triangle_remove(br, sphere);
570
571         /* Add/Remove triangles */
572         if (s->t.l->t.l == s->t.r->t.r &&
573             s->t.l->t.l != s && s->parent) {
574                 roam_diamond_update_errors(s->parent, sphere);
575                 roam_diamond_add(s->parent, sphere);
576         }
577
578         if (b->t.l->t.l == b->t.r->t.r &&
579             b->t.l->t.l != b && b->parent) {
580                 roam_diamond_update_errors(b->parent, sphere);
581                 roam_diamond_add(b->parent, sphere);
582         }
583
584         /* Remove and free diamond and child triangles */
585         roam_diamond_remove(diamond, sphere);
586         g_assert(sl->p.m == sr->p.m &&
587                  sr->p.m == bl->p.m &&
588                  bl->p.m == br->p.m);
589         g_assert(sl->p.m->tris == 0);
590         roam_triangle_free(sl);
591         roam_triangle_free(sr);
592         roam_triangle_free(bl);
593         roam_triangle_free(br);
594         g_free(diamond);
595 }
596
597 /**
598  * roam_diamond_update_errors:
599  * @diamond: the diamond
600  * @sphere:  the sphere to use when updating errors
601  *
602  * Update the error value associated with a diamond. Called when the view
603  * changes.
604  */
605 void roam_diamond_update_errors(RoamDiamond *diamond, RoamSphere *sphere)
606 {
607         roam_triangle_update_errors(diamond->parents[0], sphere);
608         roam_triangle_update_errors(diamond->parents[1], sphere);
609         diamond->error = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
610 }
611
612 /**************
613  * RoamSphere *
614  **************/
615 /**
616  * roam_sphere_new:
617  *
618  * Create a new sphere
619  *
620  * Returns: the sphere
621  */
622 RoamSphere *roam_sphere_new()
623 {
624         RoamSphere *sphere = g_new0(RoamSphere, 1);
625         sphere->polys       = 8;
626         sphere->triangles   = g_pqueue_new((GCompareDataFunc)tri_cmp, NULL);
627         sphere->diamonds    = g_pqueue_new((GCompareDataFunc)dia_cmp, NULL);
628
629         RoamPoint *vertexes[] = {
630                 roam_point_new( 90,   0,  0), // 0 (North)
631                 roam_point_new(-90,   0,  0), // 1 (South)
632                 roam_point_new(  0,   0,  0), // 2 (Europe/Africa)
633                 roam_point_new(  0,  90,  0), // 3 (Asia,East)
634                 roam_point_new(  0, 180,  0), // 4 (Pacific)
635                 roam_point_new(  0, -90,  0), // 5 (Americas,West)
636         };
637         int _triangles[][2][3] = {
638                 /*lv mv rv   ln, bn, rn */
639                 {{2,0,3}, {3, 4, 1}}, // 0
640                 {{3,0,4}, {0, 5, 2}}, // 1
641                 {{4,0,5}, {1, 6, 3}}, // 2
642                 {{5,0,2}, {2, 7, 0}}, // 3
643                 {{3,1,2}, {5, 0, 7}}, // 4
644                 {{4,1,3}, {6, 1, 4}}, // 5
645                 {{5,1,4}, {7, 2, 5}}, // 6
646                 {{2,1,5}, {4, 3, 6}}, // 7
647         };
648
649         for (int i = 0; i < 6; i++)
650                 roam_point_update_height(vertexes[i]);
651         for (int i = 0; i < 8; i++)
652                 sphere->roots[i] = roam_triangle_new(
653                         vertexes[_triangles[i][0][0]],
654                         vertexes[_triangles[i][0][1]],
655                         vertexes[_triangles[i][0][2]],
656                         NULL);
657         for (int i = 0; i < 8; i++)
658                 roam_triangle_add(sphere->roots[i],
659                         sphere->roots[_triangles[i][1][0]],
660                         sphere->roots[_triangles[i][1][1]],
661                         sphere->roots[_triangles[i][1][2]],
662                         sphere);
663         for (int i = 0; i < 8; i++)
664                 g_debug("RoamSphere: new - %p edge=%f,%f,%f,%f", sphere->roots[i],
665                                 sphere->roots[i]->edge.n,
666                                 sphere->roots[i]->edge.s,
667                                 sphere->roots[i]->edge.e,
668                                 sphere->roots[i]->edge.w);
669
670         return sphere;
671 }
672
673 /**
674  * roam_sphere_update_view
675  * @sphere: the sphere
676  *
677  * Recreate the sphere's view matrices based on the current OpenGL state.
678  */
679 void roam_sphere_update_view(RoamSphere *sphere)
680 {
681         if (!sphere->view)
682                 sphere->view = g_new0(RoamView, 1);
683         glGetDoublev (GL_MODELVIEW_MATRIX,  sphere->view->model);
684         glGetDoublev (GL_PROJECTION_MATRIX, sphere->view->proj);
685         glGetIntegerv(GL_VIEWPORT,          sphere->view->view);
686         sphere->view->version++;
687 }
688
689 /**
690  * roam_sphere_update_errors
691  * @sphere: the sphere
692  *
693  * Update triangle and diamond errors in the sphere.
694  */
695 void roam_sphere_update_errors(RoamSphere *sphere)
696 {
697         g_debug("RoamSphere: update_errors - polys=%d", sphere->polys);
698         GPtrArray *tris = g_pqueue_get_array(sphere->triangles);
699         GPtrArray *dias = g_pqueue_get_array(sphere->diamonds);
700
701         roam_sphere_update_view(sphere);
702
703         for (int i = 0; i < tris->len; i++) {
704                 RoamTriangle *triangle = tris->pdata[i];
705                 roam_triangle_update_errors(triangle, sphere);
706                 g_pqueue_priority_changed(sphere->triangles, triangle->handle);
707         }
708
709         for (int i = 0; i < dias->len; i++) {
710                 RoamDiamond *diamond = dias->pdata[i];
711                 roam_diamond_update_errors(diamond, sphere);
712                 g_pqueue_priority_changed(sphere->diamonds, diamond->handle);
713         }
714
715         g_ptr_array_free(tris, TRUE);
716         g_ptr_array_free(dias, TRUE);
717 }
718
719 /**
720  * roam_sphere_split_one
721  * @sphere: the sphere
722  *
723  * Split the triangle with the greatest error.
724  */
725 void roam_sphere_split_one(RoamSphere *sphere)
726 {
727         RoamTriangle *to_split = g_pqueue_peek(sphere->triangles);
728         if (!to_split) return;
729         roam_triangle_split(to_split, sphere);
730 }
731
732 /**
733  * roam_sphere_merge_one
734  * @sphere: the sphere
735  *
736  * Merge the diamond with the lowest error.
737  */
738 void roam_sphere_merge_one(RoamSphere *sphere)
739 {
740         RoamDiamond *to_merge = g_pqueue_peek(sphere->diamonds);
741         if (!to_merge) return;
742         roam_diamond_merge(to_merge, sphere);
743 }
744
745 /**
746  * roam_sphere_split_merge
747  * @sphere: the sphere
748  *
749  * Perform a predetermined number split-merge iterations.
750  *
751  * Returns: the number splits and merges done
752  */
753 gint roam_sphere_split_merge(RoamSphere *sphere)
754 {
755         gint iters = 0, max_iters = 500;
756         //gint target = 4000;
757         gint target = 2000;
758         //gint target = 500;
759
760         if (!sphere->view)
761                 return 0;
762
763         if (target - sphere->polys > 100) {
764                 //g_debug("RoamSphere: split_merge - Splitting %d - %d > 100", target, sphere->polys);
765                 while (sphere->polys < target && iters++ < max_iters)
766                         roam_sphere_split_one(sphere);
767         }
768
769         if (sphere->polys - target > 100) {
770                 //g_debug("RoamSphere: split_merge - Merging %d - %d > 100", sphere->polys, target);
771                 while (sphere->polys > target && iters++ < max_iters)
772                         roam_sphere_merge_one(sphere);
773         }
774
775         while (((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error >
776                ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error &&
777                iters++ < max_iters) {
778                 //g_debug("RoamSphere: split_merge - Fixing 1 %f > %f && %d < %d",
779                 //              ((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error,
780                 //              ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error,
781                 //              iters-1, max_iters);
782                 roam_sphere_merge_one(sphere);
783                 roam_sphere_split_one(sphere);
784         }
785
786         return iters;
787 }
788
789 /**
790  * roam_sphere_draw:
791  * @sphere: the sphere
792  *
793  * Draw the sphere. Use for debugging.
794  */
795 void roam_sphere_draw(RoamSphere *sphere)
796 {
797         g_debug("RoamSphere: draw");
798         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw, NULL);
799 }
800
801 /**
802  * roam_sphere_draw_normals
803  * @sphere: the sphere
804  *
805  * Draw all the surface normal vectors for the sphere. Used while debugging.
806  */
807 void roam_sphere_draw_normals(RoamSphere *sphere)
808 {
809         g_debug("RoamSphere: draw_normal");
810         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw_normal, NULL);
811 }
812
813 static GList *_roam_sphere_get_leaves(RoamTriangle *triangle, GList *list, gboolean all)
814 {
815         if (triangle->kids[0] && triangle->kids[1]) {
816                 if (all) list = g_list_prepend(list, triangle);
817                 list = _roam_sphere_get_leaves(triangle->kids[0], list, all);
818                 list = _roam_sphere_get_leaves(triangle->kids[1], list, all);
819                 return list;
820         } else {
821                 return g_list_prepend(list, triangle);
822         }
823 }
824
825 static GList *_roam_sphere_get_intersect_rec(RoamTriangle *triangle, GList *list,
826                 gboolean all, gdouble n, gdouble s, gdouble e, gdouble w)
827 {
828         gdouble tn = triangle->edge.n;
829         gdouble ts = triangle->edge.s;
830         gdouble te = triangle->edge.e;
831         gdouble tw = triangle->edge.w;
832
833         gboolean debug = FALSE  &&
834                 n==90 && s==45 && e==-90 && w==-180 &&
835                 ts > 44 && ts < 46;
836
837         if (debug)
838                 g_message("t=%p: %f < %f || %f > %f || %f < %f || %f > %f",
839                             triangle, tn,   s,   ts,   n,   te,   w,   tw,   e);
840         if (tn <= s || ts >= n || te <= w || tw >= e) {
841                 /* No intersect */
842                 if (debug) g_message("no intersect");
843                 return list;
844         } else if (tn <= n && ts >= s && te <= e && tw >= w) {
845                 /* Triangle is completely contained */
846                 if (debug) g_message("contained");
847                 if (all) list = g_list_prepend(list, triangle);
848                 return _roam_sphere_get_leaves(triangle, list, all);
849         } else if (triangle->kids[0] && triangle->kids[1]) {
850                 /* Paritial intersect with children */
851                 if (debug) g_message("edge w/ child");
852                 if (all) list = g_list_prepend(list, triangle);
853                 list = _roam_sphere_get_intersect_rec(triangle->kids[0], list, all, n, s, e, w);
854                 list = _roam_sphere_get_intersect_rec(triangle->kids[1], list, all, n, s, e, w);
855                 return list;
856         } else {
857                 /* This triangle is an edge case */
858                 if (debug) g_message("edge");
859                 return g_list_prepend(list, triangle);
860         }
861 }
862
863 /**
864  * roam_sphere_get_intersect
865  * @sphere: the sphere
866  * @all: TRUE if non-leaf triangle should be returned as well
867  * @n: the northern edge 
868  * @s: the southern edge 
869  * @e: the eastern edge 
870  * @w: the western edge 
871  *
872  * Lookup triangles withing the sphere that intersect a given lat-lon box.
873  *
874  * Returns: the list of intersecting triangles.
875  */
876 /* Warning: This grabs pointers to triangles which can be changed by other
877  * calls, e.g. split_merge. If you use this, you need to do some locking to
878  * prevent the returned list from becomming stale. */
879 GList *roam_sphere_get_intersect(RoamSphere *sphere, gboolean all,
880                 gdouble n, gdouble s, gdouble e, gdouble w)
881 {
882         /* I think this is correct..
883          * i_cost = cost for triangle-rectagnle intersect test
884          * time = n_tiles * 2*tris_per_tile * i_cost
885          * time = 30      * 2*333           * i_cost = 20000 * i_cost */
886         GList *list = NULL;
887         for (int i = 0; i < G_N_ELEMENTS(sphere->roots); i++)
888                 list = _roam_sphere_get_intersect_rec(sphere->roots[i],
889                                 list, all, n, s, e, w);
890         return list;
891 }
892
893 static void roam_sphere_free_tri(RoamTriangle *triangle)
894 {
895         if (--triangle->p.l->tris == 0) g_free(triangle->p.l);
896         if (--triangle->p.m->tris == 0) g_free(triangle->p.m);
897         if (--triangle->p.r->tris == 0) g_free(triangle->p.r);
898         roam_triangle_free(triangle);
899 }
900
901 /**
902  * roam_sphere_free
903  * @sphere: the sphere
904  *
905  * Free data associated with a sphere
906  */
907 void roam_sphere_free(RoamSphere *sphere)
908 {
909         g_debug("RoamSphere: free");
910         /* Slow method, but it should work */
911         while (sphere->polys > 8)
912                 roam_sphere_merge_one(sphere);
913         /* TODO: free points */
914         g_pqueue_foreach(sphere->triangles, (GFunc)roam_sphere_free_tri, NULL);
915         g_pqueue_free(sphere->triangles);
916         g_pqueue_free(sphere->diamonds);
917         g_free(sphere->view);
918         g_free(sphere);
919 }