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