]> git.mxchange.org Git - flightgear.git/blob - Simulator/Scenery/tilemgr.cxx
Merge Include as subdirectory
[flightgear.git] / Simulator / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22 // (Log is kept at end of this file)
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #ifdef HAVE_WINDOWS_H
30 #  include <windows.h>
31 #endif
32
33 #include <GL/glut.h>
34 #include <XGL/xgl.h>
35
36 #include <Aircraft/aircraft.hxx>
37
38 #include <Debug/logstream.hxx>
39 // #include <Bucket/bucketutils.hxx>
40 #include <Include/fg_constants.h>
41 #include <Main/options.hxx>
42 #include <Main/views.hxx>
43 #include <Math/fg_geodesy.hxx>
44 #include <Math/mat3.h>
45 #include <Math/point3d.hxx>
46 #include <Math/polar3d.hxx>
47 #include <Math/vector.hxx>
48 #include <Objects/material.hxx>
49 #include <Objects/obj.hxx>
50 #include <Weather/weather.hxx>
51
52 #include "scenery.hxx"
53 #include "tile.hxx"
54 #include "tilecache.hxx"
55 #include "tilemgr.hxx"
56
57
58 // to test clipping speedup in fgTileMgrRender()
59 #if defined ( USE_FAST_FOV_CLIP )
60   // #define TEST_FOV_CLIP
61   // #define TEST_ELEV
62 #endif
63
64
65 #define FG_LOCAL_X_Y         81  // max(o->tile_diameter) ** 2
66
67 #define FG_SQUARE( X ) ( (X) * (X) )
68
69 #if defined(USE_MEM) || defined(WIN32)
70 #  define FG_MEM_COPY(to,from,n)        memcpy(to, from, n)
71 #else
72 #  define FG_MEM_COPY(to,from,n)        bcopy(from, to, n)
73 #endif
74
75 // closest (potentially viewable) tiles, centered on current tile.
76 // This is an array of pointers to cache indexes.
77 int tiles[FG_LOCAL_X_Y];
78
79
80 // Initialize the Tile Manager subsystem
81 int fgTileMgrInit( void ) {
82     FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
83
84     // load default material library
85     material_mgr.load_lib();
86
87     return 1;
88 }
89
90
91 // load a tile
92 void fgTileMgrLoadTile( const FGBucket& p, int *index) {
93     fgTILECACHE *c;
94
95     c = &global_tile_cache;
96
97     FG_LOG( FG_TERRAIN, FG_DEBUG, "Updating for bucket " << p );
98     
99     // if not in cache, load tile into the next available slot
100     *index = c->exists(p);
101     if ( *index < 0 ) {
102         *index = c->next_avail();
103         c->fill_in(*index, p);
104     }
105
106     FG_LOG( FG_TERRAIN, FG_DEBUG, "Selected cache index: " << *index );
107 }
108
109
110 // Calculate shortest distance from point to line
111 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp, 
112                                        MAT3vec d )
113 {
114     MAT3vec p, p0;
115     double dist;
116
117     p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
118     p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
119
120     return fgPointLineSquared(p, p0, d);
121 }
122
123
124 // Determine scenery altitude.  Normally this just happens when we
125 // render the scene, but we'd also like to be able to do this
126 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
127 // Returns result in meters.
128 double
129 fgTileMgrCurElevNEW( const FGBucket& p ) {
130     fgTILE *t;
131     fgFRAGMENT *frag_ptr;
132     Point3D abs_view_pos = current_view.get_abs_view_pos();
133     Point3D earth_center(0.0);
134     Point3D result;
135     MAT3vec local_up;
136     double dist, lat_geod, alt, sea_level_r;
137     int index;
138
139     local_up[0] = abs_view_pos.x();
140     local_up[1] = abs_view_pos.y();
141     local_up[2] = abs_view_pos.z();
142
143     // Find current translation offset
144     // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
145     index = global_tile_cache.exists(p);
146     if ( index < 0 ) {
147         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
148         return 0.0;
149     }
150
151     t = global_tile_cache.get_tile(index);
152
153     scenery.next_center = t->center;
154     
155     FG_LOG( FG_TERRAIN, FG_DEBUG, 
156             "Current bucket = " << p << "  Index = " << p.gen_index_str() );
157     FG_LOG( FG_TERRAIN, FG_DEBUG,
158             "abs_view_pos = " << abs_view_pos );
159
160     // calculate tile offset
161     // x = (t->offset.x = t->center.x - scenery.center.x);
162     // y = (t->offset.y = t->center.y - scenery.center.y);
163     // z = (t->offset.z = t->center.z - scenery.center.z);
164     
165     // calc current terrain elevation calculate distance from
166     // vertical tangent line at current position to center of
167     // tile.
168         
169     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
170        point_line_dist_squared(&(t->offset), &(v->view_pos), 
171        v->local_up), t->bounding_radius); */
172
173     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
174     if ( dist < FG_SQUARE(t->bounding_radius) ) {
175
176         // traverse fragment list for tile
177         fgTILE::FragmentIterator current = t->begin();
178         fgTILE::FragmentIterator last = t->end();
179
180         for ( ; current != last; ++current ) {
181             frag_ptr = &(*current);
182             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
183                point_line_dist_squared( &(frag_ptr->center), 
184                &abs_view_pos), local_up),
185                frag_ptr->bounding_radius); */
186
187             dist = point_line_dist_squared( frag_ptr->center,
188                                             abs_view_pos,
189                                             local_up);
190             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
191                 if ( frag_ptr->intersect( abs_view_pos, 
192                                           earth_center, 0, result ) ) {
193                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
194                             result );
195                     // compute geocentric coordinates of tile center
196                     Point3D pp = fgCartToPolar3d(result);
197                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
198                     // convert to geodetic coordinates
199                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
200                                  &alt, &sea_level_r);
201
202                     // printf("alt = %.2f\n", alt);
203                     // exit since we found an intersection
204                     if ( alt > -9999.0 ) {
205                         // printf("returning alt\n");
206                         return alt;
207                     } else {
208                         // printf("returning 0\n");
209                         return 0.0;
210                     }
211                 }
212             }
213         }
214     }
215
216     FG_LOG( FG_TERRAIN, FG_INFO, "(new) no terrain intersection found" );
217
218     return 0.0;
219 }
220
221
222 // Determine scenery altitude.  Normally this just happens when we
223 // render the scene, but we'd also like to be able to do this
224 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
225 // Returns result in meters.
226 double
227 fgTileMgrCurElev( double lon, double lat, const Point3D& abs_view_pos ) {
228     fgTILECACHE *c;
229     fgTILE *t;
230     fgFRAGMENT *frag_ptr;
231     Point3D earth_center(0.0);
232     Point3D result;
233     MAT3vec local_up;
234     double dist, lat_geod, alt, sea_level_r;
235     int index;
236
237     c = &global_tile_cache;
238
239     local_up[0] = abs_view_pos.x();
240     local_up[1] = abs_view_pos.y();
241     local_up[2] = abs_view_pos.z();
242
243     FG_LOG( FG_TERRAIN, FG_DEBUG, "Absolute view pos = " << abs_view_pos );
244
245     // Find current translation offset
246     FGBucket p( lon * RAD_TO_DEG, lat * RAD_TO_DEG );
247     index = c->exists(p);
248     if ( index < 0 ) {
249         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
250         return 0.0;
251     }
252
253     t = c->get_tile(index);
254
255     scenery.next_center = t->center;
256     
257     FG_LOG( FG_TERRAIN, FG_DEBUG, 
258             "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
259             << ")  Current bucket = " << p 
260             << "  Index = " << p.gen_index_str() );
261
262     FG_LOG( FG_TERRAIN, FG_DEBUG, "Tile center " << t->center 
263             << "  bounding radius = " << t->bounding_radius );
264
265     // calculate tile offset
266     // x = (t->offset.x = t->center.x - scenery.center.x);
267     // y = (t->offset.y = t->center.y - scenery.center.y);
268     // z = (t->offset.z = t->center.z - scenery.center.z);
269     
270     // calc current terrain elevation calculate distance from
271     // vertical tangent line at current position to center of
272     // tile.
273         
274     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
275        point_line_dist_squared(&(t->offset), &(v->view_pos), 
276        v->local_up), t->bounding_radius); */
277
278     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
279     FG_LOG( FG_TERRAIN, FG_DEBUG, "(gross check) dist squared = " << dist );
280
281     if ( dist < FG_SQUARE(t->bounding_radius) ) {
282
283         // traverse fragment list for tile
284         fgTILE::FragmentIterator current = t->begin();
285         fgTILE::FragmentIterator last = t->end();
286
287         for ( ; current != last; ++current ) {
288             frag_ptr = &(*current);
289             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
290                point_line_dist_squared( &(frag_ptr->center), 
291                &abs_view_pos), local_up),
292                frag_ptr->bounding_radius); */
293
294             dist = point_line_dist_squared( frag_ptr->center,
295                                             abs_view_pos,
296                                             local_up);
297             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
298                 if ( frag_ptr->intersect( abs_view_pos, 
299                                           earth_center, 0, result ) ) {
300                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
301                             result );
302                     // compute geocentric coordinates of tile center
303                     Point3D pp = fgCartToPolar3d(result);
304                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
305                     // convert to geodetic coordinates
306                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
307                                  &alt, &sea_level_r);
308
309                     // printf("alt = %.2f\n", alt);
310                     // exit since we found an intersection
311                     if ( alt > -9999.0 ) {
312                         // printf("returning alt\n");
313                         return alt;
314                     } else {
315                         // printf("returning 0\n");
316                         return 0.0;
317                     }
318                 }
319             }
320         }
321     }
322
323     FG_LOG( FG_TERRAIN, FG_INFO, "(old) no terrain intersection found" );
324
325     return 0.0;
326 }
327
328
329 // given the current lon/lat, fill in the array of local chunks.  If
330 // the chunk isn't already in the cache, then read it from disk.
331 int fgTileMgrUpdate( void ) {
332     fgTILECACHE *c;
333     FGInterface *f;
334     FGBucket p2;
335     static FGBucket p_last(false);
336     static double last_lon = -1000.0;  // in degrees
337     static double last_lat = -1000.0;  // in degrees
338     int tile_diameter;
339     int i, j, dw, dh;
340
341     c = &global_tile_cache;
342     f = current_aircraft.fdm_state;
343
344     tile_diameter = current_options.get_tile_diameter();
345
346     FGBucket p1( f->get_Longitude() * RAD_TO_DEG,
347                  f->get_Latitude() * RAD_TO_DEG );
348     dw = tile_diameter / 2;
349     dh = tile_diameter / 2;
350
351     if ( p1 == p_last ) {
352         // same bucket as last time
353         FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
354     } else if ( p_last.get_lon() == -1000 ) {
355         // First time through, initialize the system and load all
356         // relavant tiles
357
358         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
359         FG_LOG( FG_TERRAIN, FG_INFO, "  First time through ... " );
360         FG_LOG( FG_TERRAIN, FG_INFO, "  Updating Tile list for " << p1 );
361         FG_LOG( FG_TERRAIN, FG_INFO, "  Loading " 
362                 << tile_diameter * tile_diameter << " tiles" );
363
364         // wipe/initialize tile cache
365         c->init();
366
367         // build the local area list and update cache
368         for ( j = 0; j < tile_diameter; j++ ) {
369             for ( i = 0; i < tile_diameter; i++ ) {
370                 // fgBucketOffset(&p1, &p2, i - dw, j - dh);
371                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
372                                      f->get_Latitude() * RAD_TO_DEG,
373                                      i - dw, j -dh );
374                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + i]);
375             }
376         }
377     } else {
378         // We've moved to a new bucket, we need to scroll our
379         // structures, and load in the new tiles
380
381         // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
382         // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
383         // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
384
385         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
386
387         if ( (p1.get_lon() > p_last.get_lon()) ||
388              ( (p1.get_lon() == p_last.get_lon()) && (p1.get_x() > p_last.get_x()) ) ) {
389             FG_LOG( FG_TERRAIN, FG_INFO, 
390                     "  Loading " << tile_diameter << "tiles" );
391             for ( j = 0; j < tile_diameter; j++ ) {
392                 // scrolling East
393                 for ( i = 0; i < tile_diameter - 1; i++ ) {
394                     tiles[(j*tile_diameter) + i] = 
395                         tiles[(j*tile_diameter) + i + 1];
396                 }
397                 // load in new column
398                 // fgBucketOffset(&p_last, &p2, dw + 1, j - dh);
399                 p2 = fgBucketOffset( last_lon, last_lat, dw + 1, j - dh );
400                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 
401                                              tile_diameter - 1]);
402             }
403         } else if ( (p1.get_lon() < p_last.get_lon()) ||
404                     ( (p1.get_lon() == p_last.get_lon()) && (p1.get_x() < p_last.get_x()) ) ) {
405             FG_LOG( FG_TERRAIN, FG_INFO, 
406                     "  Loading " << tile_diameter << "tiles" );
407             for ( j = 0; j < tile_diameter; j++ ) {
408                 // scrolling West
409                 for ( i = tile_diameter - 1; i > 0; i-- ) {
410                     tiles[(j*tile_diameter) + i] = 
411                         tiles[(j*tile_diameter) + i - 1];
412                 }
413                 // load in new column
414                 // fgBucketOffset(&p_last, &p2, -dw - 1, j - dh);
415                 p2 = fgBucketOffset( last_lon, last_lat, -dw - 1, j - dh );
416                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 0]);
417             }
418         }
419
420         if ( (p1.get_lat() > p_last.get_lat()) ||
421              ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() > p_last.get_y()) ) ) {
422             FG_LOG( FG_TERRAIN, FG_INFO, 
423                     "  Loading " << tile_diameter << "tiles" );
424             for ( i = 0; i < tile_diameter; i++ ) {
425                 // scrolling North
426                 for ( j = 0; j < tile_diameter - 1; j++ ) {
427                     tiles[(j * tile_diameter) + i] =
428                         tiles[((j+1) * tile_diameter) + i];
429                 }
430                 // load in new column
431                 // fgBucketOffset(&p_last, &p2, i - dw, dh + 1);
432                 p2 = fgBucketOffset( last_lon, last_lat, i - dw, dh + 1);
433                 fgTileMgrLoadTile( p2, &tiles[((tile_diameter-1) * 
434                                                tile_diameter) + i]);
435             }
436         } else if ( (p1.get_lat() < p_last.get_lat()) ||
437                     ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() < p_last.get_y()) ) ) {
438             FG_LOG( FG_TERRAIN, FG_INFO, 
439                     "  Loading " << tile_diameter << "tiles" );
440             for ( i = 0; i < tile_diameter; i++ ) {
441                 // scrolling South
442                 for ( j = tile_diameter - 1; j > 0; j-- ) {
443                     tiles[(j * tile_diameter) + i] = 
444                         tiles[((j-1) * tile_diameter) + i];
445                 }
446                 // load in new column
447                 // fgBucketOffset(&p_last, &p2, i - dw, -dh - 1);
448                 p2 = fgBucketOffset( last_lon, last_lat, i - dw, -dh - 1);
449                 fgTileMgrLoadTile( p2, &tiles[0 + i]);
450             }
451         }
452     }
453
454     // find our current elevation (feed in the current bucket to save work)
455     Point3D geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
456     Point3D tmp_abs_view_pos = fgGeodToCart(geod_pos);
457
458     scenery.cur_elev = 
459         fgTileMgrCurElev( f->get_Longitude(), f->get_Latitude(), 
460                           tmp_abs_view_pos );
461
462     p_last = p1;
463     last_lon = f->get_Longitude() * RAD_TO_DEG;
464     last_lat = f->get_Latitude() * RAD_TO_DEG;
465
466     return 1;
467 }
468
469
470 // Calculate if point/radius is inside view frustum
471 static int viewable( const Point3D& cp, double radius ) {
472     int viewable = 1; // start by assuming it's viewable
473     double x1, y1;
474
475 /********************************/
476 #if defined( USE_FAST_FOV_CLIP ) // views.hxx
477 /********************************/
478         
479     MAT3vec eye;        
480     double *mat;
481     double x, y, z;
482
483     x = cp.x();
484     y = cp.y();
485     z = cp.z();
486         
487     mat = (double *)(current_view.get_WORLD_TO_EYE());
488         
489     eye[2] =  x*mat[2] + y*mat[6] + z*mat[10] + mat[14];
490         
491     // Check near and far clip plane
492     if( ( eye[2] > radius ) ||
493         ( eye[2] + radius + current_weather.get_visibility() < 0) )
494     {
495         return(0);
496     }
497         
498     eye[0] = (x*mat[0] + y*mat[4] + z*mat[8] + mat[12])
499         * current_view.get_slope_x();
500
501     // check right and left clip plane (from eye perspective)
502     x1 = radius * current_view.get_fov_x_clip();
503     if( (eye[2] > -(eye[0]+x1)) || (eye[2] > (eye[0]-x1)) )
504     {
505         return(0);
506     }
507         
508     eye[1] = (x*mat[1] + y*mat[5] + z*mat[9] + mat[13]) 
509         * current_view.get_slope_y();
510
511     // check bottom and top clip plane (from eye perspective)
512     y1 = radius * current_view.get_fov_y_clip();
513     if( (eye[2] > -(eye[1]+y1)) || (eye[2] > (eye[1]-y1)) )
514     {
515         return(0);
516     }
517
518 /********************************/      
519 #else // DO NOT USE_FAST_FOV_CLIP
520 /********************************/      
521
522     fgVIEW *v;
523     MAT3hvec world, eye;
524     double x0, slope;
525
526     v = &current_view;
527
528     MAT3_SET_HVEC(world, cp->x, cp->y, cp->z, 1.0);
529     // MAT3mult_vec(eye, world, v->WORLD_TO_EYE);
530     // printf( "\nworld -> eye = %.2f %.2f %.2f  radius = %.2f\n", 
531     //         eye[0], eye[1], eye[2], radius);
532
533     // Use lazy evaluation for calculating eye hvec.
534 #define vec world
535 #define mat v->WORLD_TO_EYE
536     eye[2] = vec[0]*mat[0][2]+vec[1]*mat[1][2]+vec[2]*mat[2][2]+mat[3][2];
537
538     // Check near clip plane
539     if ( eye[2] > radius ) {
540         return(0);
541     }
542
543     // Check far clip plane
544     if ( eye[2] + radius < -current_weather.get_visibility() ) {
545         return(0);
546     }
547
548     // check right clip plane (from eye perspective)
549     // y = m * (x - x0) = equation of a line intercepting X axis at x0
550     x1 = v->cos_fov_x * radius;
551     y1 = v->sin_fov_x * radius;
552     slope = v->slope_x;
553     eye[0] = vec[0]*mat[0][0]+vec[1]*mat[1][0]+vec[2]*mat[2][0]+mat[3][0];
554
555     if ( eye[2] > ((slope * (eye[0] - x1)) + y1) ) {
556         return( false );
557     }
558
559     // check left clip plane (from eye perspective)
560     if ( eye[2] > -((slope * (eye[0] + x1)) - y1) ) {
561         return( false );
562     }
563
564     // check bottom clip plane (from eye perspective)
565     x1 = -(v->cos_fov_y) * radius;
566     y1 = v->sin_fov_y * radius;
567     slope = v->slope_y;
568     eye[1] = vec[0]*mat[0][1]+vec[1]*mat[1][1]+vec[2]*mat[2][1]+mat[3][1];
569 #undef vec
570 #undef mat
571
572     if ( eye[2] > ((slope * (eye[1] - x1)) + y1) ) {
573         return( false );
574     }
575
576     // check top clip plane (from eye perspective)
577     if ( eye[2] > -((slope * (eye[1] + x1)) - y1) ) {
578         return( false );
579     }
580
581 #endif // defined( USE_FAST_FOV_CLIP )
582         
583     return(viewable);
584 }
585
586
587 // NEW 
588
589 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
590 //      calculate distance from vertical tangent line at
591 //      current position to center of object.
592 //      this is equivalent to
593 //      dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos), 
594 //                                      v->local_up );
595 //      if ( dist < FG_SQUARE(t->bounding_radius) ) {
596 //
597 // the compiler should inline this for us
598
599 static int
600 inrange( const double radius, const Point3D& center, const Point3D& vp,
601          const MAT3vec up)
602 {
603     MAT3vec u, u1, v;
604     //  double tmp;
605         
606     // u = p - p0
607     u[0] = center.x() - vp.x();
608     u[1] = center.y() - vp.y();
609     u[2] = center.z() - vp.z();
610         
611     // calculate the projection, u1, of u along d.
612     // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
613         
614     MAT3_SCALE_VEC(u1, up,
615                    (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
616     
617     // v = u - u1 = vector from closest point on line, p1, to the
618     // original point, p.
619     MAT3_SUB_VEC(v, u, u1);
620         
621     return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
622 }
623
624
625 // NEW for legibility
626
627 // update this tile's geometry for current view
628 // The Compiler should inline this
629 static void
630 update_tile_geometry( fgTILE *t, GLdouble *MODEL_VIEW)
631 {
632     GLdouble *m;
633     double x, y, z;
634         
635     // calculate tile offset
636     t->offset = t->center - scenery.center;
637
638     x = t->offset.x();
639     y = t->offset.y();
640     z = t->offset.z();
641         
642     m = t->model_view;
643         
644     // Calculate the model_view transformation matrix for this tile
645     FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
646     
647     // This is equivalent to doing a glTranslatef(x, y, z);
648     m[12] += (m[0]*x + m[4]*y + m[8] *z);
649     m[13] += (m[1]*x + m[5]*y + m[9] *z);
650     m[14] += (m[2]*x + m[6]*y + m[10]*z);
651     // m[15] += (m[3]*x + m[7]*y + m[11]*z);
652     // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
653     // so m[15] is unchanged
654 }
655
656
657 // Render the local tiles
658 void fgTileMgrRender( void ) {
659     FGInterface *f;
660     fgTILECACHE *c;
661     fgTILE *t;
662     FGView *v;
663     Point3D frag_offset;
664     fgFRAGMENT *frag_ptr;
665     fgMATERIAL *mtl_ptr;
666     int i;
667     int tile_diameter;
668     int index;
669     int culled = 0;
670     int drawn = 0;
671
672     c = &global_tile_cache;
673     f = current_aircraft.fdm_state;
674     v = &current_view;
675
676     tile_diameter = current_options.get_tile_diameter();
677
678     // moved to fgTileMgrUpdate, right after we check if we need to
679     // load additional tiles:
680     // scenery.cur_elev = fgTileMgrCurElev( FG_Longitude, FG_Latitude, 
681     //                                      v->abs_view_pos );
682  
683     // initialize the transient per-material fragment lists
684     material_mgr.init_transient_material_lists();
685    
686     // Pass 1
687     // traverse the potentially viewable tile list
688     for ( i = 0; i < (tile_diameter * tile_diameter); i++ ) {
689         index = tiles[i];
690         // fgPrintf( FG_TERRAIN, FG_DEBUG, "Index = %d\n", index);
691         t = c->get_tile(index);
692
693         // calculate tile offset
694         t->SetOffset( scenery.center );
695
696         // Course (tile based) culling
697         if ( viewable(t->offset, t->bounding_radius) ) {
698             // at least a portion of this tile could be viewable
699             
700             // Calculate the model_view transformation matrix for this tile
701             // This is equivalent to doing a glTranslatef(x, y, z);
702             t->UpdateViewMatrix( v->get_MODEL_VIEW() );
703
704             // xglPushMatrix();
705             // xglTranslatef(t->offset.x, t->offset.y, t->offset.z);
706
707             // traverse fragment list for tile
708             fgTILE::FragmentIterator current = t->begin();
709             fgTILE::FragmentIterator last = t->end();
710
711             for ( ; current != last; ++current ) {
712                 frag_ptr = &(*current);
713                 
714                 if ( frag_ptr->display_list >= 0 ) {
715                     // Fine (fragment based) culling
716                     frag_offset = frag_ptr->center - scenery.center;
717
718                     if ( viewable(frag_offset, frag_ptr->bounding_radius*2) ) {
719                         // add to transient per-material property fragment list
720                         // frag_ptr->tile_offset.x = t->offset.x;
721                         // frag_ptr->tile_offset.y = t->offset.y;
722                         // frag_ptr->tile_offset.z = t->offset.z;
723
724                         mtl_ptr = frag_ptr->material_ptr;
725                         // printf(" lookup = %s\n", mtl_ptr->texture_name);
726                         if ( ! mtl_ptr->append_sort_list( frag_ptr ) ) {
727                             FG_LOG( FG_TERRAIN, FG_ALERT,
728                                     "Overran material sorting array" );
729                         }
730
731                         // xglCallList(frag_ptr->display_list);
732                         drawn++;
733                     } else {
734                         // printf("Culled a fragment %.2f %.2f %.2f %.2f\n",
735                         //        frag_ptr->center.x, frag_ptr->center.y,
736                         //        frag_ptr->center.z, frag_ptr->bounding_radius);
737                         culled++;
738                     }
739                 }
740             }
741
742             // xglPopMatrix();
743         } else {
744             culled += t->fragment_list.size();
745         }
746     }
747
748     if ( (drawn + culled) > 0 ) {
749         v->set_vfc_ratio( (double)culled / (double)(drawn + culled) );
750     } else {
751         v->set_vfc_ratio( 0.0 );
752     }
753     // printf("drawn = %d  culled = %d  saved = %.2f\n", drawn, culled, 
754     //        v->vfc_ratio);
755
756     // Pass 2
757     // traverse the transient per-material fragment lists and render
758     // out all fragments for each material property.
759     xglPushMatrix();
760     material_mgr.render_fragments();
761     xglPopMatrix();
762 }
763
764
765 // $Log$
766 // Revision 1.55  1999/03/25 19:03:28  curt
767 // Converted to use new bucket routines.
768 //
769 // Revision 1.54  1999/02/26 22:10:05  curt
770 // Added initial support for native SGI compilers.
771 //
772 // Revision 1.53  1999/02/05 21:29:16  curt
773 // Modifications to incorporate Jon S. Berndts flight model code.
774 //
775 // Revision 1.52  1999/01/27 04:49:48  curt
776 // Fixes so that the sim can start out at an airport below sea level.
777 //
778 // Revision 1.51  1998/12/09 18:50:33  curt
779 // Converted "class fgVIEW" to "class FGView" and updated to make data
780 // members private and make required accessor functions.
781 //
782 // Revision 1.50  1998/12/06 13:51:25  curt
783 // Turned "struct fgWEATHER" into "class FGWeather".
784 //
785 // Revision 1.49  1998/12/05 15:54:26  curt
786 // Renamed class fgFLIGHT to class FGState as per request by JSB.
787 //
788 // Revision 1.48  1998/12/05 14:20:21  curt
789 // Looking into a terrain intersection problem.
790 //
791 // Revision 1.47  1998/12/05 14:11:19  curt
792 // Sun portability tweak.
793 //
794 // Revision 1.46  1998/12/03 14:15:24  curt
795 // Actually set the current scenery elevation based on scenery intersection point
796 // rather than calculating the intesection point and throwing it away.
797 //
798 // Revision 1.45  1998/12/03 01:18:18  curt
799 // Converted fgFLIGHT to a class.
800 // Tweaks for Sun Portability.
801 // Tweaked current terrain elevation code as per NHV.
802 //
803 // Revision 1.44  1998/11/23 21:49:48  curt
804 // minor tweaks.
805 //
806 // Revision 1.43  1998/11/09 23:40:52  curt
807 // Bernie Bright <bbright@c031.aone.net.au> writes:
808 // I've made some changes to the Scenery handling.  Basically just tidy ups.
809 // The main difference is in tile.[ch]xx where I've changed list<fgFRAGMENT> to
810 // vector<fgFRAGMENT>.  Studying our usage patterns this seems reasonable.
811 // Lists are good if you need to insert/delete elements randomly but we
812 // don't do that.  All access seems to be sequential.  Two additional
813 // benefits are smaller memory usage - each list element requires pointers
814 // to the next and previous elements, and faster access - vector iterators
815 // are smaller and faster than list iterators.  This should also help
816 // Charlie Hotchkiss' problem when compiling with Borland and STLport.
817 //
818 // ./Lib/Bucket/bucketutils.hxx
819 //   Convenience functions for fgBUCKET.
820 //
821 // ./Simulator/Scenery/tile.cxx
822 // ./Simulator/Scenery/tile.hxx
823 //   Changed fragment list to a vector.
824 //   Added some convenience member functions.
825 //
826 // ./Simulator/Scenery/tilecache.cxx
827 // ./Simulator/Scenery/tilecache.hxx
828 //   use const fgBUCKET& instead of fgBUCKET* where appropriate.
829 //
830 // ./Simulator/Scenery/tilemgr.cxx
831 // ./Simulator/Scenery/tilemgr.hxx
832 //   uses all the new convenience functions.
833 //
834 // Revision 1.42  1998/11/06 21:18:23  curt
835 // Converted to new logstream debugging facility.  This allows release
836 // builds with no messages at all (and no performance impact) by using
837 // the -DFG_NDEBUG flag.
838 //
839 // Revision 1.41  1998/10/18 01:17:23  curt
840 // Point3D tweaks.
841 //
842 // Revision 1.40  1998/10/17 01:34:28  curt
843 // C++ ifying ...
844 //
845 // Revision 1.39  1998/10/16 00:55:50  curt
846 // Converted to Point3D class.
847 //
848 // Revision 1.38  1998/09/17 18:36:18  curt
849 // Tweaks and optimizations by Norman Vine.
850 //
851 // Revision 1.37  1998/09/15 01:36:45  curt
852 // cleaned up my fragment.num_faces hack :-) to use the STL (no need in
853 // duplicating work.)
854 // Tweaked fgTileMgrRender() do not calc tile matrix unless necessary.
855 // removed some unneeded stuff from fgTileMgrCurElev()
856 //
857 // Revision 1.36  1998/09/14 12:45:26  curt
858 // minor tweaks.
859 //
860 // Revision 1.35  1998/09/10 19:07:16  curt
861 // /Simulator/Objects/fragment.hxx
862 //   Nested fgFACE inside fgFRAGMENT since its not used anywhere else.
863 //
864 // ./Simulator/Objects/material.cxx
865 // ./Simulator/Objects/material.hxx
866 //   Made fgMATERIAL and fgMATERIAL_MGR bona fide classes with private
867 //   data members - that should keep the rabble happy :)
868 //
869 // ./Simulator/Scenery/tilemgr.cxx
870 //   In viewable() delay evaluation of eye[0] and eye[1] in until they're
871 //   actually needed.
872 //   Change to fgTileMgrRender() to call fgMATERIAL_MGR::render_fragments()
873 //   method.
874 //
875 // ./Include/fg_stl_config.h
876 // ./Include/auto_ptr.hxx
877 //   Added support for g++ 2.7.
878 //   Further changes to other files are forthcoming.
879 //
880 // Brief summary of changes required for g++ 2.7.
881 //   operator->() not supported by iterators: use (*i).x instead of i->x
882 //   default template arguments not supported,
883 //   <functional> doesn't have mem_fun_ref() needed by callbacks.
884 //   some std include files have different names.
885 //   template member functions not supported.
886 //
887 // Revision 1.34  1998/09/09 20:58:09  curt
888 // Tweaks to loop constructs with STL usage.
889 //
890 // Revision 1.33  1998/09/08 15:05:10  curt
891 // Optimization by Norman Vine.
892 //
893 // Revision 1.32  1998/08/25 16:52:44  curt
894 // material.cxx material.hxx obj.cxx obj.hxx texload.c texload.h moved to
895 //   ../Objects
896 //
897 // Revision 1.31  1998/08/24 20:11:40  curt
898 // Tweaks ...
899 //
900 // Revision 1.30  1998/08/22  14:49:59  curt
901 // Attempting to iron out seg faults and crashes.
902 // Did some shuffling to fix a initialization order problem between view
903 // position, scenery elevation.
904 //
905 // Revision 1.29  1998/08/20 15:12:06  curt
906 // Used a forward declaration of classes fgTILE and fgMATERIAL to eliminate
907 // the need for "void" pointers and casts.
908 // Quick hack to count the number of scenery polygons that are being drawn.
909 //
910 // Revision 1.28  1998/08/12 21:13:06  curt
911 // material.cxx: don't load textures if they are disabled
912 // obj.cxx: optimizations from Norman Vine
913 // tile.cxx: minor tweaks
914 // tile.hxx: addition of num_faces
915 // tilemgr.cxx: minor tweaks
916 //
917 // Revision 1.27  1998/07/24 21:42:09  curt
918 // material.cxx: whups, double method declaration with no definition.
919 // obj.cxx: tweaks to avoid errors in SGI's CC.
920 // tile.cxx: optimizations by Norman Vine.
921 // tilemgr.cxx: optimizations by Norman Vine.
922 //
923 // Revision 1.26  1998/07/20 12:51:26  curt
924 // Added far clip plane to fragment clipping calculations and tie this to
925 // weather->visibility.  This way you can increase framerates by increasing
926 // for and lowering visibility.
927 //
928 // Revision 1.25  1998/07/13 21:02:01  curt
929 // Wrote access functions for current fgOPTIONS.
930 //
931 // Revision 1.24  1998/07/12 03:18:29  curt
932 // Added ground collision detection.  This involved:
933 // - saving the entire vertex list for each tile with the tile records.
934 // - saving the face list for each fragment with the fragment records.
935 // - code to intersect the current vertical line with the proper face in
936 //   an efficient manner as possible.
937 // Fixed a bug where the tiles weren't being shifted to "near" (0,0,0)
938 //
939 // Revision 1.23  1998/07/08 14:47:23  curt
940 // Fix GL_MODULATE vs. GL_DECAL problem introduced by splash screen.
941 // polare3d.h renamed to polar3d.hxx
942 // fg{Cartesian,Polar}Point3d consolodated.
943 // Added some initial support for calculating local current ground elevation.
944 //
945 // Revision 1.22  1998/07/04 00:54:31  curt
946 // Added automatic mipmap generation.
947 //
948 // When rendering fragments, use saved model view matrix from associated tile
949 // rather than recalculating it with push() translate() pop().
950 //
951 // Revision 1.21  1998/06/27 16:54:59  curt
952 // Check for GL_VERSION_1_1 or GL_EXT_texture_object to decide whether to use
953 //   "EXT" versions of texture management routines.
954 //
955 // Revision 1.20  1998/06/17 21:36:42  curt
956 // Load and manage multiple textures defined in the Materials library.
957 // Boost max material fagments for each material property to 800.
958 // Multiple texture support when rendering.
959 //
960 // Revision 1.19  1998/06/08 17:57:54  curt
961 // Working first pass at material proporty sorting.
962 //
963 // Revision 1.18  1998/06/06 01:09:32  curt
964 // I goofed on the log message in the last commit ... now fixed.
965 //
966 // Revision 1.17  1998/06/06 01:07:18  curt
967 // Increased per material fragment list size from 100 to 400.
968 // Now correctly draw viewable fragments in per material order.
969 //
970 // Revision 1.16  1998/06/05 22:39:55  curt
971 // Working on sorting by, and rendering by material properties.
972 //
973 // Revision 1.15  1998/06/03 00:47:51  curt
974 // No .h for STL includes.
975 // Minor view culling optimizations.
976 //
977 // Revision 1.14  1998/06/01 17:56:20  curt
978 // Incremental additions to material.cxx (not fully functional)
979 // Tweaked vfc_ratio math to avoid divide by zero.
980 //
981 // Revision 1.13  1998/05/24 02:49:10  curt
982 // Implimented fragment level view frustum culling.
983 //
984 // Revision 1.12  1998/05/23 14:09:23  curt
985 // Added tile.cxx and tile.hxx.
986 // Working on rewriting the tile management system so a tile is just a list
987 // fragments, and the fragment record contains the display list for that fragment.
988 //
989 // Revision 1.11  1998/05/20 20:53:55  curt
990 // Moved global ref point and radius (bounding sphere info, and offset) to
991 // data file rather than calculating it on the fly.
992 // Fixed polygon winding problem in scenery generation stage rather than
993 // compensating for it on the fly.
994 // Made a fgTILECACHE class.
995 //
996 // Revision 1.10  1998/05/17 16:59:34  curt
997 // Frist pass at view frustum culling now operational.
998 //
999 // Revision 1.9  1998/05/16 13:09:58  curt
1000 // Beginning to add support for view frustum culling.
1001 // Added some temporary code to calculate bouding radius, until the
1002 //   scenery generation tools and scenery can be updated.
1003 //
1004 // Revision 1.8  1998/05/07 23:15:21  curt
1005 // Fixed a glTexImage2D() usage bug where width and height were mis-swapped.
1006 // Added support for --tile-radius=n option.
1007 //
1008 // Revision 1.7  1998/05/06 03:16:42  curt
1009 // Added an option to control square tile radius.
1010 //
1011 // Revision 1.6  1998/05/02 01:52:18  curt
1012 // Playing around with texture coordinates.
1013 //
1014 // Revision 1.5  1998/04/30 12:35:32  curt
1015 // Added a command line rendering option specify smooth/flat shading.
1016 //
1017 // Revision 1.4  1998/04/27 03:30:14  curt
1018 // Minor transformation adjustments to try to keep scenery tiles closer to
1019 // (0, 0, 0)  GLfloats run out of precision at the distances we need to model
1020 // the earth, but we can do a bunch of pre-transformations using double math
1021 // and then cast to GLfloat once everything is close in where we have less
1022 // precision problems.
1023 //
1024 // Revision 1.3  1998/04/25 22:06:32  curt
1025 // Edited cvs log messages in source files ... bad bad bad!
1026 //
1027 // Revision 1.2  1998/04/24 00:51:09  curt
1028 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
1029 // Tweaked the scenery file extentions to be "file.obj" (uncompressed)
1030 // or "file.obz" (compressed.)
1031 //
1032 // Revision 1.1  1998/04/22 13:22:48  curt
1033 // C++ - ifing the code a bit.
1034 //
1035 // Revision 1.25  1998/04/18 04:14:07  curt
1036 // Moved fg_debug.c to it's own library.
1037 //
1038 // Revision 1.24  1998/04/14 02:23:18  curt
1039 // Code reorganizations.  Added a Lib/ directory for more general libraries.
1040 //
1041 // Revision 1.23  1998/04/08 23:30:08  curt
1042 // Adopted Gnu automake/autoconf system.
1043 //
1044 // Revision 1.22  1998/04/03 22:11:38  curt
1045 // Converting to Gnu autoconf system.
1046 //
1047 // Revision 1.21  1998/03/23 21:23:05  curt
1048 // Debugging output tweaks.
1049 //
1050 // Revision 1.20  1998/03/14 00:30:51  curt
1051 // Beginning initial terrain texturing experiments.
1052 //
1053 // Revision 1.19  1998/02/20 00:16:25  curt
1054 // Thursday's tweaks.
1055 //
1056 // Revision 1.18  1998/02/19 13:05:54  curt
1057 // Incorporated some HUD tweaks from Michelle America.
1058 // Tweaked the sky's sunset/rise colors.
1059 // Other misc. tweaks.
1060 //
1061 // Revision 1.17  1998/02/16 13:39:46  curt
1062 // Miscellaneous weekend tweaks.  Fixed? a cache problem that caused whole
1063 // tiles to occasionally be missing.
1064 //
1065 // Revision 1.16  1998/02/12 21:59:53  curt
1066 // Incorporated code changes contributed by Charlie Hotchkiss
1067 // <chotchkiss@namg.us.anritsu.com>
1068 //
1069 // Revision 1.14  1998/02/09 21:30:19  curt
1070 // Fixed a nagging problem with terrain tiles not "quite" matching up perfectly.
1071 //
1072 // Revision 1.13  1998/02/07 15:29:46  curt
1073 // Incorporated HUD changes and struct/typedef changes from Charlie Hotchkiss
1074 // <chotchkiss@namg.us.anritsu.com>
1075 //
1076 // Revision 1.12  1998/02/01 03:39:55  curt
1077 // Minor tweaks.
1078 //
1079 // Revision 1.11  1998/01/31 00:43:27  curt
1080 // Added MetroWorks patches from Carmen Volpe.
1081 //
1082 // Revision 1.10  1998/01/29 00:51:40  curt
1083 // First pass at tile cache, dynamic tile loading and tile unloading now works.
1084 //
1085 // Revision 1.9  1998/01/27 03:26:44  curt
1086 // Playing with new fgPrintf command.
1087 //
1088 // Revision 1.8  1998/01/27 00:48:04  curt
1089 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
1090 // system and commandline/config file processing code.
1091 //
1092 // Revision 1.7  1998/01/26 15:55:25  curt
1093 // Progressing on building dynamic scenery system.
1094 //
1095 // Revision 1.6  1998/01/24 00:03:30  curt
1096 // Initial revision.
1097 //
1098 // Revision 1.5  1998/01/19 19:27:18  curt
1099 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
1100 // This should simplify things tremendously.
1101 //
1102 // Revision 1.4  1998/01/19 18:40:38  curt
1103 // Tons of little changes to clean up the code and to remove fatal errors
1104 // when building with the c++ compiler.
1105 //
1106 // Revision 1.3  1998/01/13 00:23:11  curt
1107 // Initial changes to support loading and management of scenery tiles.  Note,
1108 // there's still a fair amount of work left to be done.
1109 //
1110 // Revision 1.2  1998/01/08 02:22:27  curt
1111 // Continue working on basic features.
1112 //
1113 // Revision 1.1  1998/01/07 23:50:51  curt
1114 // "area" renamed to "tile"
1115 //
1116 // Revision 1.2  1998/01/07 03:29:29  curt
1117 // Given an arbitrary lat/lon, we can now:
1118 //   generate a unique index for the chunk containing the lat/lon
1119 //   generate a path name to the chunk file
1120 //   build a list of the indexes of all the nearby areas.
1121 //
1122 // Revision 1.1  1998/01/07 02:05:48  curt
1123 // Initial revision.