1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
3 // Written by Curtis Olson, started January 1998.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
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.
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.
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.
35 #include <Aircraft/aircraft.hxx>
37 #include <Debug/logstream.hxx>
38 // #include <Bucket/bucketutils.hxx>
39 #include <Include/fg_constants.h>
40 #include <Main/options.hxx>
41 #include <Main/views.hxx>
42 #include <Math/fg_geodesy.hxx>
43 #include <Math/mat3.h>
44 #include <Math/point3d.hxx>
45 #include <Math/polar3d.hxx>
46 #include <Math/vector.hxx>
47 #include <Objects/materialmgr.hxx>
48 #include <Objects/obj.hxx>
50 #ifndef FG_OLD_WEATHER
51 # include <WeatherCM/FGLocalWeatherDatabase.h>
53 # include <Weather/weather.hxx>
56 #include "scenery.hxx"
57 #include "tilecache.hxx"
58 #include "tileentry.hxx"
59 #include "tilemgr.hxx"
62 // to test clipping speedup in fgTileMgrRender()
63 #if defined ( USE_FAST_FOV_CLIP )
64 // #define TEST_FOV_CLIP
69 extern ssgRoot *scene;
73 FGTileMgr global_tile_mgr;
77 FGTileMgr::FGTileMgr ( void ):
84 FGTileMgr::~FGTileMgr ( void ) {
88 // Initialize the Tile Manager subsystem
89 int FGTileMgr::init( void ) {
90 FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
92 // load default material library
93 if ( ! material_mgr.loaded() ) {
94 material_mgr.load_lib();
97 global_tile_cache.init();
105 // schedule a tile for loading
106 static void disable_tile( int cache_index ) {
107 // see if tile already exists in the cache
108 // cout << "DISABLING CACHE ENTRY = " << cache_index << endl;
109 FGTileEntry *t = global_tile_cache.get_tile( cache_index );
114 // schedule a tile for loading
115 int FGTileMgr::sched_tile( const FGBucket& b ) {
116 // see if tile already exists in the cache
117 int cache_index = global_tile_cache.exists( b );
119 if ( cache_index >= 0 ) {
120 // tile exists in cache, reenable it.
121 // cout << "REENABLING DISABLED TILE" << endl;
122 FGTileEntry *t = global_tile_cache.get_tile( cache_index );
123 t->select_ptr->select( 1 );
126 // find the next available cache entry and mark it as
128 cache_index = global_tile_cache.next_avail();
129 FGTileEntry *t = global_tile_cache.get_tile( cache_index );
130 t->mark_scheduled_for_use();
132 // register a load request
135 request.cache_index = cache_index;
136 load_queue.push_back( request );
144 void FGTileMgr::load_tile( const FGBucket& b, int cache_index) {
146 FG_LOG( FG_TERRAIN, FG_DEBUG, "Loading tile " << b );
148 global_tile_cache.fill_in(cache_index, b);
150 FG_LOG( FG_TERRAIN, FG_DEBUG, "Loaded for cache index: " << cache_index );
154 // Calculate shortest distance from point to line
155 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp,
160 p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
161 p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
163 return fgPointLineSquared(p, p0, d);
167 // Determine scenery altitude. Normally this just happens when we
168 // render the scene, but we'd also like to be able to do this
169 // explicitely. lat & lon are in radians. abs_view_pos in meters.
170 // Returns result in meters.
172 FGTileMgr::current_elev_new( const FGBucket& p ) {
174 fgFRAGMENT *frag_ptr;
175 Point3D abs_view_pos = current_view.get_abs_view_pos();
176 Point3D earth_center(0.0);
179 double dist, lat_geod, alt, sea_level_r;
182 local_up[0] = abs_view_pos.x();
183 local_up[1] = abs_view_pos.y();
184 local_up[2] = abs_view_pos.z();
186 // Find current translation offset
187 // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
188 index = global_tile_cache.exists(p);
190 FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
194 t = global_tile_cache.get_tile(index);
196 scenery.next_center = t->center;
198 FG_LOG( FG_TERRAIN, FG_DEBUG,
199 "Current bucket = " << p << " Index = " << p.gen_index_str() );
200 FG_LOG( FG_TERRAIN, FG_DEBUG,
201 "abs_view_pos = " << abs_view_pos );
203 // calculate tile offset
204 // x = (t->offset.x = t->center.x - scenery.center.x);
205 // y = (t->offset.y = t->center.y - scenery.center.y);
206 // z = (t->offset.z = t->center.z - scenery.center.z);
208 // calc current terrain elevation calculate distance from
209 // vertical tangent line at current position to center of
212 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
213 point_line_dist_squared(&(t->offset), &(v->view_pos),
214 v->local_up), t->bounding_radius); */
216 dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
217 if ( dist < FG_SQUARE(t->bounding_radius) ) {
219 // traverse fragment list for tile
220 FGTileEntry::FragmentIterator current = t->begin();
221 FGTileEntry::FragmentIterator last = t->end();
223 for ( ; current != last; ++current ) {
224 frag_ptr = &(*current);
225 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
226 point_line_dist_squared( &(frag_ptr->center),
227 &abs_view_pos), local_up),
228 frag_ptr->bounding_radius); */
230 dist = point_line_dist_squared( frag_ptr->center,
233 if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
234 if ( frag_ptr->intersect( abs_view_pos,
235 earth_center, 0, result ) ) {
236 FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
238 // compute geocentric coordinates of tile center
239 Point3D pp = fgCartToPolar3d(result);
240 FG_LOG( FG_TERRAIN, FG_DEBUG, " polar form = " << pp );
241 // convert to geodetic coordinates
242 fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod,
245 // printf("alt = %.2f\n", alt);
246 // exit since we found an intersection
247 if ( alt > -9999.0 ) {
248 // printf("returning alt\n");
251 // printf("returning 0\n");
259 FG_LOG( FG_TERRAIN, FG_INFO, "(new) no terrain intersection found" );
265 // Determine scenery altitude. Normally this just happens when we
266 // render the scene, but we'd also like to be able to do this
267 // explicitely. lat & lon are in radians. abs_view_pos in meters.
268 // Returns result in meters.
270 FGTileMgr::current_elev( double lon, double lat, const Point3D& abs_view_pos ) {
273 fgFRAGMENT *frag_ptr;
274 Point3D earth_center(0.0);
277 double dist, lat_geod, alt, sea_level_r;
280 c = &global_tile_cache;
282 local_up[0] = abs_view_pos.x();
283 local_up[1] = abs_view_pos.y();
284 local_up[2] = abs_view_pos.z();
286 FG_LOG( FG_TERRAIN, FG_DEBUG, "Absolute view pos = " << abs_view_pos );
288 // Find current translation offset
289 FGBucket p( lon * RAD_TO_DEG, lat * RAD_TO_DEG );
290 index = c->exists(p);
292 FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
296 t = c->get_tile(index);
298 scenery.next_center = t->center;
300 FG_LOG( FG_TERRAIN, FG_DEBUG,
301 "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
302 << ") Current bucket = " << p
303 << " Index = " << p.gen_index_str() );
305 FG_LOG( FG_TERRAIN, FG_DEBUG, "Tile center " << t->center
306 << " bounding radius = " << t->bounding_radius );
308 // calculate tile offset
309 // x = (t->offset.x = t->center.x - scenery.center.x);
310 // y = (t->offset.y = t->center.y - scenery.center.y);
311 // z = (t->offset.z = t->center.z - scenery.center.z);
313 // calc current terrain elevation calculate distance from
314 // vertical tangent line at current position to center of
317 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
318 point_line_dist_squared(&(t->offset), &(v->view_pos),
319 v->local_up), t->bounding_radius); */
321 dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
322 FG_LOG( FG_TERRAIN, FG_DEBUG, "(gross check) dist squared = " << dist );
324 if ( dist < FG_SQUARE(t->bounding_radius) ) {
326 // traverse fragment list for tile
327 FGTileEntry::FragmentIterator current = t->begin();
328 FGTileEntry::FragmentIterator last = t->end();
330 for ( ; current != last; ++current ) {
331 frag_ptr = &(*current);
332 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
333 point_line_dist_squared( &(frag_ptr->center),
334 &abs_view_pos), local_up),
335 frag_ptr->bounding_radius); */
337 dist = point_line_dist_squared( frag_ptr->center,
340 if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
341 if ( frag_ptr->intersect( abs_view_pos,
342 earth_center, 0, result ) ) {
343 FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
345 // compute geocentric coordinates of tile center
346 Point3D pp = fgCartToPolar3d(result);
347 FG_LOG( FG_TERRAIN, FG_DEBUG, " polar form = " << pp );
348 // convert to geodetic coordinates
349 fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod,
352 // printf("alt = %.2f\n", alt);
353 // exit since we found an intersection
354 if ( alt > -9999.0 ) {
355 // printf("returning alt\n");
358 // printf("returning 0\n");
366 FG_LOG( FG_TERRAIN, FG_INFO, "(old) no terrain intersection found" );
372 // Determine scenery altitude via ssg. Normally this just happens
373 // when we render the scene, but we'd also like to be able to do this
374 // explicitely. lat & lon are in radians. view_pos in current world
375 // coordinate translated near (0,0,0) (in meters.) Returns result in
378 FGTileMgr::current_elev_ssg( const Point3D& abs_view_pos,
379 const Point3D& view_pos )
383 // cout << "view pos = " << view_pos << endl;
384 // cout << "abs view pos = " << abs_view_pos << endl;
387 sgMakeTransMat4( m, view_pos.x(), view_pos.y(), view_pos.z() );
390 sgSetVec3(s, -abs_view_pos.x(), -abs_view_pos.y(), -abs_view_pos.z() );
392 int num_hits = ssgLOS ( scene, s, m, &results ) ;
394 for ( int i = 0 ; i < num_hits ; i++ ) {
395 ssgHit *h = &(results [ i ]) ;
396 // cout << "got a hit!" << endl;
397 /* Do something with 'h' */
400 FG_LOG( FG_TERRAIN, FG_INFO, "(ssg) no terrain intersection found" );
406 // given the current lon/lat, fill in the array of local chunks. If
407 // the chunk isn't already in the cache, then read it from disk.
408 int FGTileMgr::update( void ) {
412 static FGBucket p_last(false);
413 static double last_lon = -1000.0; // in degrees
414 static double last_lat = -1000.0; // in degrees
418 c = &global_tile_cache;
419 f = current_aircraft.fdm_state;
421 tile_diameter = current_options.get_tile_diameter();
423 FGBucket p1( f->get_Longitude() * RAD_TO_DEG,
424 f->get_Latitude() * RAD_TO_DEG );
425 dw = tile_diameter / 2;
426 dh = tile_diameter / 2;
428 if ( (p1 == p_last) && (state == Running) ) {
429 // same bucket as last time
430 FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
431 } else if ( (state == Start) || (state == Inited) ) {
434 // First time through or we have teleported, initialize the
435 // system and load all relavant tiles
437 FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
438 FG_LOG( FG_TERRAIN, FG_INFO, " First time through ... " );
439 FG_LOG( FG_TERRAIN, FG_INFO, " Updating Tile list for " << p1 );
440 FG_LOG( FG_TERRAIN, FG_INFO, " Loading "
441 << tile_diameter * tile_diameter << " tiles" );
443 // wipe/initialize tile cache
447 // build the local area list and schedule tiles for loading
449 // start with the center tile and work out in concentric
452 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
453 f->get_Latitude() * RAD_TO_DEG,
457 for ( i = 3; i <= tile_diameter; i = i + 2 ) {
461 for ( j = -span; j <= span; ++j ) {
462 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
463 f->get_Latitude() * RAD_TO_DEG,
469 for ( j = -span; j <= span; ++j ) {
470 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
471 f->get_Latitude() * RAD_TO_DEG,
477 for ( j = -span + 1; j <= span - 1; ++j ) {
478 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
479 f->get_Latitude() * RAD_TO_DEG,
482 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
483 f->get_Latitude() * RAD_TO_DEG,
490 /* for ( j = 0; j < tile_diameter; j++ ) {
491 for ( i = 0; i < tile_diameter; i++ ) {
492 // fgBucketOffset(&p1, &p2, i - dw, j - dh);
493 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
494 f->get_Latitude() * RAD_TO_DEG,
500 // Now force a load of the center tile and inner ring so we
501 // have something to see in our first frame.
502 for ( i = 0; i < 9; ++i ) {
503 if ( load_queue.size() ) {
504 FG_LOG( FG_TERRAIN, FG_DEBUG,
505 "Load queue not empty, loading a tile" );
507 FGLoadRec pending = load_queue.front();
508 load_queue.pop_front();
509 load_tile( pending.b, pending.cache_index );
514 // We've moved to a new bucket, we need to scroll our
515 // structures, and load in the new tiles
518 // make sure load queue is flushed before doing shift
519 while ( load_queue.size() ) {
520 FG_LOG( FG_TERRAIN, FG_DEBUG,
521 "Load queue not empty, flushing queue before tile shift." );
523 FGLoadRec pending = load_queue.front();
524 load_queue.pop_front();
525 load_tile( pending.b, pending.index );
529 // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
530 // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
531 // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
533 FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
535 if ( (p1.get_lon() > p_last.get_lon()) ||
536 ( (p1.get_lon() == p_last.get_lon()) &&
537 (p1.get_x() > p_last.get_x()) ) ) {
538 FG_LOG( FG_TERRAIN, FG_INFO,
539 " (East) Loading " << tile_diameter << " tiles" );
540 for ( j = 0; j < tile_diameter; j++ ) {
542 // schedule new column
543 p2 = fgBucketOffset( last_lon, last_lat, dw + 1, j - dh );
546 } else if ( (p1.get_lon() < p_last.get_lon()) ||
547 ( (p1.get_lon() == p_last.get_lon()) &&
548 (p1.get_x() < p_last.get_x()) ) ) {
549 FG_LOG( FG_TERRAIN, FG_INFO,
550 " (West) Loading " << tile_diameter << " tiles" );
551 for ( j = 0; j < tile_diameter; j++ ) {
553 // schedule new column
554 p2 = fgBucketOffset( last_lon, last_lat, -dw - 1, j - dh );
559 if ( (p1.get_lat() > p_last.get_lat()) ||
560 ( (p1.get_lat() == p_last.get_lat()) &&
561 (p1.get_y() > p_last.get_y()) ) ) {
562 FG_LOG( FG_TERRAIN, FG_INFO,
563 " (North) Loading " << tile_diameter << " tiles" );
564 for ( i = 0; i < tile_diameter; i++ ) {
567 p2 = fgBucketOffset( last_lon, last_lat, i - dw, dh + 1);
570 } else if ( (p1.get_lat() < p_last.get_lat()) ||
571 ( (p1.get_lat() == p_last.get_lat()) &&
572 (p1.get_y() < p_last.get_y()) ) ) {
573 FG_LOG( FG_TERRAIN, FG_INFO,
574 " (South) Loading " << tile_diameter << " tiles" );
575 for ( i = 0; i < tile_diameter; i++ ) {
578 p2 = fgBucketOffset( last_lon, last_lat, i - dw, -dh - 1);
584 if ( load_queue.size() ) {
585 FG_LOG( FG_TERRAIN, FG_DEBUG, "Load queue not empty, loading a tile" );
587 FGLoadRec pending = load_queue.front();
588 load_queue.pop_front();
589 load_tile( pending.b, pending.cache_index );
592 // find our current elevation (feed in the current bucket to save work)
593 Point3D geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
594 Point3D tmp_abs_view_pos = fgGeodToCart(geod_pos);
597 current_elev( f->get_Longitude(), f->get_Latitude(), tmp_abs_view_pos );
598 // cout << "current elevation == " << scenery.cur_elev << endl;
599 // double junk = current_elev_ssg( current_view.abs_view_pos,
600 // current_view.view_pos );
601 // cout << "current elevation (ssg) == " <<
604 last_lon = f->get_Longitude() * RAD_TO_DEG;
605 last_lat = f->get_Latitude() * RAD_TO_DEG;
613 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
614 // calculate distance from vertical tangent line at
615 // current position to center of object.
616 // this is equivalent to
617 // dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos),
619 // if ( dist < FG_SQUARE(t->bounding_radius) ) {
621 // the compiler should inline this for us
624 inrange( const double radius, const Point3D& center, const Point3D& vp,
631 u[0] = center.x() - vp.x();
632 u[1] = center.y() - vp.y();
633 u[2] = center.z() - vp.z();
635 // calculate the projection, u1, of u along d.
636 // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
638 MAT3_SCALE_VEC(u1, up,
639 (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
641 // v = u - u1 = vector from closest point on line, p1, to the
642 // original point, p.
643 MAT3_SUB_VEC(v, u, u1);
645 return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
649 // NEW for legibility
651 // update this tile's geometry for current view
652 // The Compiler should inline this
654 update_tile_geometry( FGTileEntry *t, GLdouble *MODEL_VIEW)
659 // calculate tile offset
660 t->offset = t->center - scenery.center;
668 // Calculate the model_view transformation matrix for this tile
669 FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
671 // This is equivalent to doing a glTranslatef(x, y, z);
672 m[12] += (m[0]*x + m[4]*y + m[8] *z);
673 m[13] += (m[1]*x + m[5]*y + m[9] *z);
674 m[14] += (m[2]*x + m[6]*y + m[10]*z);
675 // m[15] += (m[3]*x + m[7]*y + m[11]*z);
676 // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
677 // so m[15] is unchanged
681 // Prepare the ssg nodes ... for each tile, set it's proper
682 // transform and update it's range selector based on current
684 void FGTileMgr::prep_ssg_nodes( void ) {
690 // traverse the potentially viewable tile list and update range
691 // selector and transform
692 for ( int i = 0; i < (int)global_tile_cache.get_size(); i++ ) {
693 t = global_tile_cache.get_tile( i );
695 if ( t->is_loaded() ) {
696 // set range selector (LOD trick) to be distance to center
697 // of tile + bounding radius
698 #ifndef FG_OLD_WEATHER
699 ranges[1] = WeatherDatabase->getWeatherVisibility()
700 + t->bounding_radius;
702 ranges[1] = current_weather.get_visibility()+t->bounding_radius;
704 t->range_ptr->setRanges( ranges, 2 );
706 // calculate tile offset
707 t->SetOffset( scenery.center );
709 // calculate ssg transform
711 sgSetCoord( &sgcoord,
712 t->offset.x(), t->offset.y(), t->offset.z(),
714 t->transform_ptr->setTransform( &sgcoord );