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