]> Pileus Git - grits/blob - src/roam.c
Use common vector operations for 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 #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 #include <GL/gl.h>
35 #include <GL/glu.h>
36
37 #include "gpqueue.h"
38 #include "grits-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         crossd3((gdouble*)triangle->p.l,
210                 (gdouble*)triangle->p.m,
211                 (gdouble*)triangle->p.r, triangle->norm);
212         normd(triangle->norm);
213
214         /* Store bounding box, for get_intersect */
215         RoamPoint *p[] = {l,m,r};
216         triangle->edge.n =  -90; triangle->edge.s =  90;
217         triangle->edge.e = -180; triangle->edge.w = 180;
218         gboolean maxed = FALSE;
219         for (int i = 0; i < G_N_ELEMENTS(p); i++) {
220                 triangle->edge.n = MAX(triangle->edge.n, p[i]->lat);
221                 triangle->edge.s = MIN(triangle->edge.s, p[i]->lat);
222                 if (p[i]->lat == 90 || p[i]->lat == -90)
223                         continue;
224                 if (p[i]->lon == 180) {
225                         maxed = TRUE;
226                         continue;
227                 }
228                 triangle->edge.e = MAX(triangle->edge.e, p[i]->lon);
229                 triangle->edge.w = MIN(triangle->edge.w, p[i]->lon);
230         }
231         if (maxed) {
232                 if (triangle->edge.e < 0)
233                         triangle->edge.w = -180;
234                 else
235                         triangle->edge.e =  180;
236         }
237
238         //g_message("roam_triangle_new: %p", triangle);
239         return triangle;
240 }
241
242 /**
243  * roam_triangle_free:
244  * @triangle: the triangle
245  *
246  * Free data associated with a triangle
247  */
248 void roam_triangle_free(RoamTriangle *triangle)
249 {
250         g_free(triangle->split);
251         g_free(triangle);
252 }
253
254 /**
255  * roam_triangle_add:
256  * @triangle: the triangle
257  * @left:     the left neighbor
258  * @base:     the base neighbor
259  * @right:    the right neighbor
260  * @sphere:   the sphere to add the triangle to
261  *
262  * Add a triangle into the sphere's mesh using the given neighbors.
263  */
264 void roam_triangle_add(RoamTriangle *triangle,
265                 RoamTriangle *left, RoamTriangle *base, RoamTriangle *right,
266                 RoamSphere *sphere)
267 {
268         triangle->t.l = left;
269         triangle->t.b = base;
270         triangle->t.r = right;
271
272         roam_point_add_triangle(triangle->p.l, triangle);
273         roam_point_add_triangle(triangle->p.m, triangle);
274         roam_point_add_triangle(triangle->p.r, triangle);
275
276         if (sphere->view)
277                 roam_triangle_update_errors(triangle, sphere);
278
279         triangle->handle = g_pqueue_push(sphere->triangles, triangle);
280 }
281
282 /**
283  * roam_triangle_remove:
284  * @triangle: the triangle
285  * @sphere:   the sphere to remove the triangle from
286  *
287  * Remove a triangle from a sphere's mesh.
288  */
289 void roam_triangle_remove(RoamTriangle *triangle, RoamSphere *sphere)
290 {
291         /* Update vertex normals */
292         roam_point_remove_triangle(triangle->p.l, triangle);
293         roam_point_remove_triangle(triangle->p.m, triangle);
294         roam_point_remove_triangle(triangle->p.r, triangle);
295
296         g_pqueue_remove(sphere->triangles, triangle->handle);
297 }
298
299 /* (neight->t.? == old) = new */
300 static void roam_triangle_sync_neighbors(RoamTriangle *neigh, RoamTriangle *old, RoamTriangle *new)
301 {
302         if      (neigh->t.l == old) neigh->t.l = new;
303         else if (neigh->t.b == old) neigh->t.b = new;
304         else if (neigh->t.r == old) neigh->t.r = new;
305 }
306
307 static gboolean roam_triangle_visible(RoamTriangle *triangle, RoamSphere *sphere)
308 {
309         RoamPoint *l = triangle->p.l;
310         RoamPoint *m = triangle->p.m;
311         RoamPoint *r = triangle->p.r;
312         gdouble min_x = MIN(MIN(l->px, m->px), r->px);
313         gdouble max_x = MAX(MAX(l->px, m->px), r->px);
314         gdouble min_y = MIN(MIN(l->py, m->py), r->py);
315         gdouble max_y = MAX(MAX(l->py, m->py), r->py);
316         gint *view = sphere->view->view;
317         return !(max_x < view[0] || min_x > view[2] ||
318                  max_y < view[1] || min_y > view[3]) &&
319                  l->pz > 0 && m->pz > 0 && r->pz > 0 &&
320                  l->pz < 1 && m->pz < 1 && r->pz < 1;
321 }
322
323 static gboolean roam_triangle_backface(RoamTriangle *triangle, RoamSphere *sphere)
324 {
325         RoamPoint *l = triangle->p.l;
326         RoamPoint *m = triangle->p.m;
327         RoamPoint *r = triangle->p.r;
328         roam_point_update_projection(l, sphere->view);
329         roam_point_update_projection(m, sphere->view);
330         roam_point_update_projection(r, sphere->view);
331         double size = -( l->px * (m->py - r->py) +
332                          m->px * (r->py - l->py) +
333                          r->px * (l->py - m->py) ) / 2.0;
334         return size < 0;
335 }
336
337 /**
338  * roam_triangle_update_errors:
339  * @triangle: the triangle
340  * @sphere:   the sphere to use when updating errors
341  *
342  * Update the error value associated with a triangle. Called when the view
343  * changes.
344  */
345 void roam_triangle_update_errors(RoamTriangle *triangle, RoamSphere *sphere)
346 {
347         /* Update points */
348         roam_point_update_projection(triangle->p.l, sphere->view);
349         roam_point_update_projection(triangle->p.m, sphere->view);
350         roam_point_update_projection(triangle->p.r, sphere->view);
351
352         if (!roam_triangle_visible(triangle, sphere)) {
353                 triangle->error = -1;
354         } else {
355                 roam_point_update_projection(triangle->split, sphere->view);
356                 RoamPoint *l     = triangle->p.l;
357                 RoamPoint *m     = triangle->p.m;
358                 RoamPoint *r     = triangle->p.r;
359                 RoamPoint *split = triangle->split;
360
361                 /*               l-r midpoint        projected l-r midpoint */
362                 gdouble pxdist = (l->px + r->px)/2 - split->px;
363                 gdouble pydist = (l->py + r->py)/2 - split->py;
364
365                 triangle->error = sqrt(pxdist*pxdist + pydist*pydist);
366
367                 /* Multiply by size of triangle */
368                 double size = -( l->px * (m->py - r->py) +
369                                  m->px * (r->py - l->py) +
370                                  r->px * (l->py - m->py) ) / 2.0;
371
372                 /* Size < 0 == backface */
373                 triangle->error *= size;
374
375                 /* Give some preference to "edge" faces */
376                 if (roam_triangle_backface(triangle->t.l, sphere) ||
377                     roam_triangle_backface(triangle->t.b, sphere) ||
378                     roam_triangle_backface(triangle->t.r, sphere))
379                         triangle->error *= 500;
380         }
381 }
382
383 /**
384  * roam_triangle_split:
385  * @triangle: the triangle
386  * @sphere:   the sphere
387  *
388  * Split a triangle into two child triangles and update the sphere.
389  * triangle
390  */
391 void roam_triangle_split(RoamTriangle *triangle, RoamSphere *sphere)
392 {
393         //g_message("roam_triangle_split: %p, e=%f\n", triangle, triangle->error);
394
395         sphere->polys += 2;
396
397         if (triangle != triangle->t.b->t.b)
398                 roam_triangle_split(triangle->t.b, sphere);
399         if (triangle != triangle->t.b->t.b)
400                 g_assert_not_reached();
401
402         RoamTriangle *s = triangle;      // Self
403         RoamTriangle *b = triangle->t.b; // Base
404
405         RoamDiamond *dia = roam_diamond_new(s, b);
406
407         /* Add new triangles */
408         RoamPoint *mid = triangle->split;
409         RoamTriangle *sl = s->kids[0] = roam_triangle_new(s->p.m, mid, s->p.l, dia); // Self Left
410         RoamTriangle *sr = s->kids[1] = roam_triangle_new(s->p.r, mid, s->p.m, dia); // Self Right
411         RoamTriangle *bl = b->kids[0] = roam_triangle_new(b->p.m, mid, b->p.l, dia); // Base Left
412         RoamTriangle *br = b->kids[1] = roam_triangle_new(b->p.r, mid, b->p.m, dia); // Base Right
413
414         /*                triangle,l,  base,      r,  sphere */
415         roam_triangle_add(sl, sr, s->t.l, br, sphere);
416         roam_triangle_add(sr, bl, s->t.r, sl, sphere);
417         roam_triangle_add(bl, br, b->t.l, sr, sphere);
418         roam_triangle_add(br, sl, b->t.r, bl, sphere);
419
420         roam_triangle_sync_neighbors(s->t.l, s, sl);
421         roam_triangle_sync_neighbors(s->t.r, s, sr);
422         roam_triangle_sync_neighbors(b->t.l, b, bl);
423         roam_triangle_sync_neighbors(b->t.r, b, br);
424
425         /* Remove old triangles */
426         roam_triangle_remove(s, sphere);
427         roam_triangle_remove(b, sphere);
428
429         /* Add/Remove diamonds */
430         roam_diamond_update_errors(dia, sphere);
431         roam_diamond_add(dia, sphere);
432         roam_diamond_remove(s->parent, sphere);
433         roam_diamond_remove(b->parent, sphere);
434 }
435
436 /**
437  * roam_triangle_draw:
438  * @triangle: the triangle
439  *
440  * Draw the triangle. Use for debugging.
441  */
442 void roam_triangle_draw(RoamTriangle *triangle)
443 {
444         glBegin(GL_TRIANGLES);
445         glNormal3dv(triangle->p.r->norm); glVertex3dv((double*)triangle->p.r);
446         glNormal3dv(triangle->p.m->norm); glVertex3dv((double*)triangle->p.m);
447         glNormal3dv(triangle->p.l->norm); glVertex3dv((double*)triangle->p.l);
448         glEnd();
449         return;
450 }
451
452 /**
453  * roam_triangle_draw_normal:
454  * @triangle: the triangle
455  *
456  * Draw a normal vector for the triangle. Used while debugging.
457  */
458 void roam_triangle_draw_normal(RoamTriangle *triangle)
459 {
460         double center[] = {
461                 (triangle->p.l->x + triangle->p.m->x + triangle->p.r->x)/3.0,
462                 (triangle->p.l->y + triangle->p.m->y + triangle->p.r->y)/3.0,
463                 (triangle->p.l->z + triangle->p.m->z + triangle->p.r->z)/3.0,
464         };
465         double end[] = {
466                 center[0]+triangle->norm[0]*2000000,
467                 center[1]+triangle->norm[1]*2000000,
468                 center[2]+triangle->norm[2]*2000000,
469         };
470         glBegin(GL_LINES);
471         glVertex3dv(center);
472         glVertex3dv(end);
473         glEnd();
474 }
475
476 /***************
477  * RoamDiamond *
478  ***************/
479 /**
480  * roam_diamond_new:
481  * @parent0: a parent triangle
482  * @parent1: a parent triangle
483  * @kid0:    a child triangle
484  * @kid1:    a child triangle
485  * @kid2:    a child triangle
486  * @kid3:    a child triangle
487  *
488  * Create a diamond to store information about two split triangles.
489  *
490  * Returns: the new diamond
491  */
492 RoamDiamond *roam_diamond_new(RoamTriangle *parent0, RoamTriangle *parent1)
493 {
494         RoamDiamond *diamond = g_new0(RoamDiamond, 1);
495         diamond->parents[0] = parent0;
496         diamond->parents[1] = parent1;
497         return diamond;
498 }
499
500 /**
501  * roam_diamond_add:
502  * @diamond: the diamond
503  * @sphere:  the sphere to add the diamond to
504  *
505  * Add a diamond into the sphere's pool of diamonds. It will be check for
506  * possible merges.
507  */
508 void roam_diamond_add(RoamDiamond *diamond, RoamSphere *sphere)
509 {
510         diamond->active = TRUE;
511         diamond->error  = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
512         diamond->handle = g_pqueue_push(sphere->diamonds, diamond);
513 }
514
515 /**
516  * roam_diamond_remove:
517  * @diamond: the diamond
518  * @sphere:  the sphere to remove the diamond from
519  *
520  * Remove a diamond from the sphere's pool of diamonds.
521  */
522 void roam_diamond_remove(RoamDiamond *diamond, RoamSphere *sphere)
523 {
524         if (diamond && diamond->active) {
525                 diamond->active = FALSE;
526                 g_pqueue_remove(sphere->diamonds, diamond->handle);
527         }
528 }
529
530 /**
531  * roam_diamond_merge:
532  * @diamond: the diamond
533  * @sphere:  the sphere
534  *
535  * "Merge" a diamond back into two parent triangles. The original two triangles
536  * are added back into the sphere and the four child triangles as well as the
537  * diamond are removed.
538  */
539 void roam_diamond_merge(RoamDiamond *diamond, RoamSphere *sphere)
540 {
541         //g_message("roam_diamond_merge: %p, e=%f\n", diamond, diamond->error);
542
543         /* TODO: pick the best split */
544         sphere->polys -= 2;
545
546         /* Use nicer temp names */
547         RoamTriangle *s = diamond->parents[0]; // Self
548         RoamTriangle *b = diamond->parents[1]; // Base
549
550         RoamTriangle *sl = s->kids[0];
551         RoamTriangle *sr = s->kids[1];
552         RoamTriangle *bl = b->kids[0];
553         RoamTriangle *br = b->kids[1];
554
555         s->kids[0] = s->kids[1] = NULL;
556         b->kids[0] = b->kids[1] = NULL;
557
558         /* Add original triangles */
559         roam_triangle_sync_neighbors(s->t.l, sl, s);
560         roam_triangle_sync_neighbors(s->t.r, sr, s);
561         roam_triangle_sync_neighbors(b->t.l, bl, b);
562         roam_triangle_sync_neighbors(b->t.r, br, b);
563
564         roam_triangle_add(s, sl->t.b, b, sr->t.b, sphere);
565         roam_triangle_add(b, bl->t.b, s, br->t.b, sphere);
566
567         roam_triangle_sync_neighbors(sl->t.b, sl, s);
568         roam_triangle_sync_neighbors(sr->t.b, sr, s);
569         roam_triangle_sync_neighbors(bl->t.b, bl, b);
570         roam_triangle_sync_neighbors(br->t.b, br, b);
571
572         /* Remove child triangles */
573         roam_triangle_remove(sl, sphere);
574         roam_triangle_remove(sr, sphere);
575         roam_triangle_remove(bl, sphere);
576         roam_triangle_remove(br, sphere);
577
578         /* Add/Remove triangles */
579         if (s->t.l->t.l == s->t.r->t.r &&
580             s->t.l->t.l != s && s->parent) {
581                 roam_diamond_update_errors(s->parent, sphere);
582                 roam_diamond_add(s->parent, sphere);
583         }
584
585         if (b->t.l->t.l == b->t.r->t.r &&
586             b->t.l->t.l != b && b->parent) {
587                 roam_diamond_update_errors(b->parent, sphere);
588                 roam_diamond_add(b->parent, sphere);
589         }
590
591         /* Remove and free diamond and child triangles */
592         roam_diamond_remove(diamond, sphere);
593         g_assert(sl->p.m == sr->p.m &&
594                  sr->p.m == bl->p.m &&
595                  bl->p.m == br->p.m);
596         g_assert(sl->p.m->tris == 0);
597         roam_triangle_free(sl);
598         roam_triangle_free(sr);
599         roam_triangle_free(bl);
600         roam_triangle_free(br);
601         g_free(diamond);
602 }
603
604 /**
605  * roam_diamond_update_errors:
606  * @diamond: the diamond
607  * @sphere:  the sphere to use when updating errors
608  *
609  * Update the error value associated with a diamond. Called when the view
610  * changes.
611  */
612 void roam_diamond_update_errors(RoamDiamond *diamond, RoamSphere *sphere)
613 {
614         roam_triangle_update_errors(diamond->parents[0], sphere);
615         roam_triangle_update_errors(diamond->parents[1], sphere);
616         diamond->error = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
617 }
618
619 /**************
620  * RoamSphere *
621  **************/
622 /**
623  * roam_sphere_new:
624  *
625  * Create a new sphere
626  *
627  * Returns: the sphere
628  */
629 RoamSphere *roam_sphere_new()
630 {
631         RoamSphere *sphere = g_new0(RoamSphere, 1);
632         sphere->polys       = 8;
633         sphere->triangles   = g_pqueue_new((GCompareDataFunc)tri_cmp, NULL);
634         sphere->diamonds    = g_pqueue_new((GCompareDataFunc)dia_cmp, NULL);
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         if (!sphere->view)
689                 sphere->view = g_new0(RoamView, 1);
690         glGetDoublev (GL_MODELVIEW_MATRIX,  sphere->view->model);
691         glGetDoublev (GL_PROJECTION_MATRIX, sphere->view->proj);
692         glGetIntegerv(GL_VIEWPORT,          sphere->view->view);
693         sphere->view->version++;
694 }
695
696 /**
697  * roam_sphere_update_errors
698  * @sphere: the sphere
699  *
700  * Update triangle and diamond errors in the sphere.
701  */
702 void roam_sphere_update_errors(RoamSphere *sphere)
703 {
704         g_debug("RoamSphere: update_errors - polys=%d", sphere->polys);
705         GPtrArray *tris = g_pqueue_get_array(sphere->triangles);
706         GPtrArray *dias = g_pqueue_get_array(sphere->diamonds);
707
708         roam_sphere_update_view(sphere);
709
710         for (int i = 0; i < tris->len; i++) {
711                 RoamTriangle *triangle = tris->pdata[i];
712                 roam_triangle_update_errors(triangle, sphere);
713                 g_pqueue_priority_changed(sphere->triangles, triangle->handle);
714         }
715
716         for (int i = 0; i < dias->len; i++) {
717                 RoamDiamond *diamond = dias->pdata[i];
718                 roam_diamond_update_errors(diamond, sphere);
719                 g_pqueue_priority_changed(sphere->diamonds, diamond->handle);
720         }
721
722         g_ptr_array_free(tris, TRUE);
723         g_ptr_array_free(dias, TRUE);
724 }
725
726 /**
727  * roam_sphere_split_one
728  * @sphere: the sphere
729  *
730  * Split the triangle with the greatest error.
731  */
732 void roam_sphere_split_one(RoamSphere *sphere)
733 {
734         RoamTriangle *to_split = g_pqueue_peek(sphere->triangles);
735         if (!to_split) return;
736         roam_triangle_split(to_split, sphere);
737 }
738
739 /**
740  * roam_sphere_merge_one
741  * @sphere: the sphere
742  *
743  * Merge the diamond with the lowest error.
744  */
745 void roam_sphere_merge_one(RoamSphere *sphere)
746 {
747         RoamDiamond *to_merge = g_pqueue_peek(sphere->diamonds);
748         if (!to_merge) return;
749         roam_diamond_merge(to_merge, sphere);
750 }
751
752 /**
753  * roam_sphere_split_merge
754  * @sphere: the sphere
755  *
756  * Perform a predetermined number split-merge iterations.
757  *
758  * Returns: the number splits and merges done
759  */
760 gint roam_sphere_split_merge(RoamSphere *sphere)
761 {
762         gint iters = 0, max_iters = 500;
763         //gint target = 4000;
764         gint target = 2000;
765         //gint target = 500;
766
767         if (!sphere->view)
768                 return 0;
769
770         if (target - sphere->polys > 100) {
771                 //g_debug("RoamSphere: split_merge - Splitting %d - %d > 100", target, sphere->polys);
772                 while (sphere->polys < target && iters++ < max_iters)
773                         roam_sphere_split_one(sphere);
774         }
775
776         if (sphere->polys - target > 100) {
777                 //g_debug("RoamSphere: split_merge - Merging %d - %d > 100", sphere->polys, target);
778                 while (sphere->polys > target && iters++ < max_iters)
779                         roam_sphere_merge_one(sphere);
780         }
781
782         while (((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error >
783                ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error &&
784                iters++ < max_iters) {
785                 //g_debug("RoamSphere: split_merge - Fixing 1 %f > %f && %d < %d",
786                 //              ((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error,
787                 //              ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error,
788                 //              iters-1, max_iters);
789                 roam_sphere_merge_one(sphere);
790                 roam_sphere_split_one(sphere);
791         }
792
793         return iters;
794 }
795
796 /**
797  * roam_sphere_draw:
798  * @sphere: the sphere
799  *
800  * Draw the sphere. Use for debugging.
801  */
802 void roam_sphere_draw(RoamSphere *sphere)
803 {
804         g_debug("RoamSphere: draw");
805         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw, NULL);
806 }
807
808 /**
809  * roam_sphere_draw_normals
810  * @sphere: the sphere
811  *
812  * Draw all the surface normal vectors for the sphere. Used while debugging.
813  */
814 void roam_sphere_draw_normals(RoamSphere *sphere)
815 {
816         g_debug("RoamSphere: draw_normal");
817         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw_normal, NULL);
818 }
819
820 static GList *_roam_sphere_get_leaves(RoamTriangle *triangle, GList *list, gboolean all)
821 {
822         if (triangle->kids[0] && triangle->kids[1]) {
823                 if (all) list = g_list_prepend(list, triangle);
824                 list = _roam_sphere_get_leaves(triangle->kids[0], list, all);
825                 list = _roam_sphere_get_leaves(triangle->kids[1], list, all);
826                 return list;
827         } else {
828                 return g_list_prepend(list, triangle);
829         }
830 }
831
832 static GList *_roam_sphere_get_intersect_rec(RoamTriangle *triangle, GList *list,
833                 gboolean all, gdouble n, gdouble s, gdouble e, gdouble w)
834 {
835         gdouble tn = triangle->edge.n;
836         gdouble ts = triangle->edge.s;
837         gdouble te = triangle->edge.e;
838         gdouble tw = triangle->edge.w;
839
840         gboolean debug = FALSE  &&
841                 n==90 && s==45 && e==-90 && w==-180 &&
842                 ts > 44 && ts < 46;
843
844         if (debug)
845                 g_message("t=%p: %f < %f || %f > %f || %f < %f || %f > %f",
846                             triangle, tn,   s,   ts,   n,   te,   w,   tw,   e);
847         if (tn <= s || ts >= n || te <= w || tw >= e) {
848                 /* No intersect */
849                 if (debug) g_message("no intersect");
850                 return list;
851         } else if (tn <= n && ts >= s && te <= e && tw >= w) {
852                 /* Triangle is completely contained */
853                 if (debug) g_message("contained");
854                 if (all) list = g_list_prepend(list, triangle);
855                 return _roam_sphere_get_leaves(triangle, list, all);
856         } else if (triangle->kids[0] && triangle->kids[1]) {
857                 /* Paritial intersect with children */
858                 if (debug) g_message("edge w/ child");
859                 if (all) list = g_list_prepend(list, triangle);
860                 list = _roam_sphere_get_intersect_rec(triangle->kids[0], list, all, n, s, e, w);
861                 list = _roam_sphere_get_intersect_rec(triangle->kids[1], list, all, n, s, e, w);
862                 return list;
863         } else {
864                 /* This triangle is an edge case */
865                 if (debug) g_message("edge");
866                 return g_list_prepend(list, triangle);
867         }
868 }
869
870 /**
871  * roam_sphere_get_intersect
872  * @sphere: the sphere
873  * @all: TRUE if non-leaf triangle should be returned as well
874  * @n: the northern edge 
875  * @s: the southern edge 
876  * @e: the eastern edge 
877  * @w: the western edge 
878  *
879  * Lookup triangles withing the sphere that intersect a given lat-lon box.
880  *
881  * Returns: the list of intersecting triangles.
882  */
883 /* Warning: This grabs pointers to triangles which can be changed by other
884  * calls, e.g. split_merge. If you use this, you need to do some locking to
885  * prevent the returned list from becomming stale. */
886 GList *roam_sphere_get_intersect(RoamSphere *sphere, gboolean all,
887                 gdouble n, gdouble s, gdouble e, gdouble w)
888 {
889         /* I think this is correct..
890          * i_cost = cost for triangle-rectagnle intersect test
891          * time = n_tiles * 2*tris_per_tile * i_cost
892          * time = 30      * 2*333           * i_cost = 20000 * i_cost */
893         GList *list = NULL;
894         for (int i = 0; i < G_N_ELEMENTS(sphere->roots); i++)
895                 list = _roam_sphere_get_intersect_rec(sphere->roots[i],
896                                 list, all, n, s, e, w);
897         return list;
898 }
899
900 static void roam_sphere_free_tri(RoamTriangle *triangle)
901 {
902         if (--triangle->p.l->tris == 0) g_free(triangle->p.l);
903         if (--triangle->p.m->tris == 0) g_free(triangle->p.m);
904         if (--triangle->p.r->tris == 0) g_free(triangle->p.r);
905         roam_triangle_free(triangle);
906 }
907
908 /**
909  * roam_sphere_free
910  * @sphere: the sphere
911  *
912  * Free data associated with a sphere
913  */
914 void roam_sphere_free(RoamSphere *sphere)
915 {
916         g_debug("RoamSphere: free");
917         /* Slow method, but it should work */
918         while (sphere->polys > 8)
919                 roam_sphere_merge_one(sphere);
920         /* TODO: free points */
921         g_pqueue_foreach(sphere->triangles, (GFunc)roam_sphere_free_tri, NULL);
922         g_pqueue_free(sphere->triangles);
923         g_pqueue_free(sphere->diamonds);
924         g_free(sphere->view);
925         g_free(sphere);
926 }