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