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 - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/constants.h>
29 #include <simgear/debug/logstream.hxx>
30 #include <simgear/math/point3d.hxx>
31 #include <simgear/math/polar3d.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/math/vector.hxx>
34 #include <simgear/structure/exception.hxx>
35 #include <simgear/scene/model/modellib.hxx>
37 #include <Main/globals.hxx>
38 #include <Main/fg_props.hxx>
39 #include <Main/viewer.hxx>
40 #include <Scripting/NasalSys.hxx>
42 #include "newcache.hxx"
43 #include "scenery.hxx"
44 #include "tilemgr.hxx"
46 #define TEST_LAST_HIT_CACHE
48 #if defined(ENABLE_THREADS)
49 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
50 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
52 queue<FGTileEntry *> FGTileMgr::attach_queue;
53 queue<FGDeferredModel *> FGTileMgr::model_queue;
54 #endif // ENABLE_THREADS
55 queue<FGTileEntry *> FGTileMgr::delete_queue;
57 bool FGTileMgr::tile_filter = true;
60 FGTileMgr::FGTileMgr():
69 FGTileMgr::~FGTileMgr() {
73 // Initialize the Tile Manager subsystem
74 int FGTileMgr::init() {
75 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
81 // instead it's just a lot easier to let any pending work flush
82 // through, rather than trying to arrest the queue and nuke all
83 // the various work at all the various stages and get everything
84 // cleaned up properly.
86 while ( ! attach_queue.empty() ) {
90 while ( ! model_queue.empty() ) {
91 #if defined(ENABLE_THREADS)
92 FGDeferredModel* dm = model_queue.pop();
94 FGDeferredModel* dm = model_queue.front();
104 previous_bucket.make_bad();
105 current_bucket.make_bad();
107 longitude = latitude = -1000.0;
113 // schedule a tile for loading
114 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
115 // see if tile already exists in the cache
116 FGTileEntry *t = tile_cache.get_tile( b );
119 // make space in the cache
120 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
121 long index = tile_cache.get_oldest_tile();
123 FGTileEntry *old = tile_cache.get_tile( index );
125 // shadows->deleteOccluderFromTile( (ssgBranch *) old->get_terra_transform() );
126 old->disconnect_ssg_nodes();
127 delete_queue.push( old );
128 tile_cache.clear_entry( index );
130 // nothing to free ?!? forge ahead
135 // create a new entry
136 FGTileEntry *e = new FGTileEntry( b );
138 // insert the tile into the cache
139 if ( tile_cache.insert_tile( e ) ) {
140 // Schedule tile for loading
143 // insert failed (cache full with no available entries to
144 // delete.) Try again later
148 t->set_inner_ring( is_inner_ring );
153 // schedule a needed buckets for loading
154 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
155 // sanity check (unfortunately needed!)
156 if ( longitude < -180.0 || longitude > 180.0
157 || latitude < -90.0 || latitude > 90.0 )
159 SG_LOG( SG_TERRAIN, SG_ALERT,
160 "Attempting to schedule tiles for bogus lon and lat = ("
161 << longitude << "," << latitude << ")" );
163 SG_LOG( SG_TERRAIN, SG_ALERT,
164 "This is a FATAL error. Exiting!" );
168 SG_LOG( SG_TERRAIN, SG_INFO,
169 "scheduling needed tiles for " << longitude << " " << latitude );
171 // vis = fgGetDouble("/environment/visibility-m");
173 double tile_width = curr_bucket.get_width_m();
174 double tile_height = curr_bucket.get_height_m();
175 // cout << "tile width = " << tile_width << " tile_height = "
176 // << tile_height << endl;
178 xrange = (int)(vis / tile_width) + 1;
179 yrange = (int)(vis / tile_height) + 1;
180 if ( xrange < 1 ) { xrange = 1; }
181 if ( yrange < 1 ) { yrange = 1; }
183 // note * 2 at end doubles cache size (for fdm and viewer)
184 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
185 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
186 // cout << "max cache size = " << tile_cache.get_max_cache_size()
187 // << " current cache size = " << tile_cache.get_size() << endl;
189 // clear the inner ring flags so we can set them below. This
190 // prevents us from having "true" entries we aren't able to find
191 // to get rid of if we teleport a long ways away from the current
193 tile_cache.clear_inner_ring_flags();
197 // schedule center tile first so it can be loaded first
198 b = sgBucketOffset( longitude, latitude, 0, 0 );
199 sched_tile( b, true );
203 // schedule next ring of 8 tiles
204 for ( x = -1; x <= 1; ++x ) {
205 for ( y = -1; y <= 1; ++y ) {
206 if ( x != 0 || y != 0 ) {
207 b = sgBucketOffset( longitude, latitude, x, y );
208 sched_tile( b, true );
213 // schedule remaining tiles
214 for ( x = -xrange; x <= xrange; ++x ) {
215 for ( y = -yrange; y <= yrange; ++y ) {
216 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
217 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
218 sched_tile( b, false );
225 void FGTileMgr::initialize_queue()
227 // First time through or we have teleported, initialize the
228 // system and load all relavant tiles
230 SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
232 // cout << "tile cache size = " << tile_cache.get_size() << endl;
234 // wipe/initialize tile cache
235 // tile_cache.init();
236 previous_bucket.make_bad();
238 // build the local area list and schedule tiles for loading
240 // start with the center tile and work out in concentric
243 double visibility_meters = fgGetDouble("/environment/visibility-m");
244 schedule_needed(visibility_meters, current_bucket);
246 // do we really want to lose this? CLO
248 // Now force a load of the center tile and inner ring so we
249 // have something to see in our first frame.
251 for ( i = 0; i < 9; ++i ) {
252 if ( load_queue.size() ) {
253 SG_LOG( SG_TERRAIN, SG_DEBUG,
254 "Load queue not empty, loading a tile" );
256 SGBucket pending = load_queue.front();
257 load_queue.pop_front();
258 load_tile( pending );
265 * return current status of queues
269 bool FGTileMgr::all_queues_empty() {
270 return attach_queue.empty() && model_queue.empty();
275 * Update the various queues maintained by the tilemagr (private
276 * internal function, do not call directly.)
278 void FGTileMgr::update_queues()
280 // load the next model in the load queue. Currently this must
281 // happen in the render thread because model loading can trigger
282 // texture loading which involves use of the opengl api. Skip any
283 // models belonging to not loaded tiles (i.e. the tile was removed
284 // before we were able to load some of the associated models.)
285 if ( !model_queue.empty() ) {
286 bool processed_one = false;
288 while ( model_queue.size() > 200 || processed_one == false ) {
289 processed_one = true;
291 if ( model_queue.size() > 200 ) {
292 SG_LOG( SG_TERRAIN, SG_INFO,
293 "Alert: catching up on model load queue" );
296 // cout << "loading next model ..." << endl;
297 // load the next tile in the queue
298 #if defined(ENABLE_THREADS)
299 FGDeferredModel* dm = model_queue.pop();
301 FGDeferredModel* dm = model_queue.front();
305 // only load the model if the tile still exists in the
307 FGTileEntry *t = tile_cache.get_tile( dm->get_bucket() );
310 // ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
312 osg::Node *obj_model =
313 globals->get_model_lib()->load_model( ".",
314 dm->get_model_path(),
315 globals->get_props(),
316 globals->get_sim_time_sec(),
317 dm->get_cache_state(),
318 new FGNasalModelData );
319 if ( obj_model != NULL ) {
320 dm->get_obj_trans()->addChild( obj_model );
322 // shadows->addOccluder( (ssgBranch *) obj_model->getParent(0),
323 // SGShadowVolume::occluderTypeTileObject,
324 // (ssgBranch *) dm->get_tile()->get_terra_transform());
326 } catch (const sg_io_exception& exc) {
327 string m(exc.getMessage());
329 m += exc.getLocation().asString();
330 SG_LOG( SG_ALL, SG_ALERT, m );
331 } catch (const sg_exception& exc) { // XXX may be redundant
332 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
335 dm->get_tile()->dec_pending_models();
341 // Notify the tile loader that it can load another tile
344 if ( !attach_queue.empty() ) {
345 #if defined(ENABLE_THREADS)
346 FGTileEntry* e = attach_queue.pop();
348 FGTileEntry* e = attach_queue.front();
351 e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
352 globals->get_scenery()->get_gnd_lights_root(),
353 globals->get_scenery()->get_vasi_lights_root(),
354 globals->get_scenery()->get_rwy_lights_root(),
355 globals->get_scenery()->get_taxi_lights_root() );
356 // cout << "Adding ssg nodes for "
359 if ( !delete_queue.empty() ) {
360 // cout << "delete queue = " << delete_queue.size() << endl;
361 bool processed_one = false;
363 while ( delete_queue.size() > 30 || processed_one == false ) {
364 processed_one = true;
366 if ( delete_queue.size() > 30 ) {
367 // uh oh, delete queue is blowing up, we aren't clearing
368 // it fast enough. Let's just panic, well not panic, but
369 // get real serious and agressively free up some tiles so
370 // we don't explode our memory usage.
372 SG_LOG( SG_TERRAIN, SG_ALERT,
373 "Warning: catching up on tile delete queue" );
376 FGTileEntry* e = delete_queue.front();
377 if ( e->free_tile() ) {
386 // given the current lon/lat (in degrees), fill in the array of local
387 // chunks. If the chunk isn't already in the cache, then read it from
389 int FGTileMgr::update( double visibility_meters )
391 SGLocation *location = globals->get_current_view()->getSGLocation();
392 return update( location, visibility_meters );
396 int FGTileMgr::update( SGLocation *location, double visibility_meters )
398 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
400 longitude = location->getLongitude_deg();
401 latitude = location->getLatitude_deg();
402 // add 1.0m to the max altitude to give a little leeway to the
403 // ground reaction code.
404 altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
406 // if current altitude is apparently not initialized, set max
407 // altitude to something big.
408 if ( altitude_m < -1000 ) {
411 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
412 // << longitude << " " << latatitude );
414 current_bucket.set_bucket( longitude, latitude );
415 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
416 // << current_bucket );
417 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
419 // do tile load scheduling.
420 // Note that we need keep track of both viewer buckets and fdm buckets.
421 if ( state == Running ) {
422 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
423 if (!(current_bucket == previous_bucket )) {
424 // We've moved to a new bucket, we need to schedule any
425 // needed tiles for loading.
426 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
427 schedule_needed(visibility_meters, current_bucket);
429 } else if ( state == Start || state == Inited ) {
430 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
431 // initialize_queue();
434 // load the next tile in the load queue (or authorize the next
435 // load in the case of the threaded tile pager)
442 previous_bucket = current_bucket;
448 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
449 void FGTileMgr::refresh_view_timestamps() {
450 SG_LOG( SG_TERRAIN, SG_INFO,
451 "Refreshing timestamps for " << current_bucket.get_center_lon()
452 << " " << current_bucket.get_center_lat() );
453 if ( longitude >= -180.0 && longitude <= 180.0
454 && latitude >= -90.0 && latitude <= 90.0 )
456 schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
460 void FGTileMgr::prep_ssg_nodes( SGLocation *location, float vis ) {
462 // traverse the potentially viewable tile list and update range
463 // selector and transform
465 float *up = location->get_world_up();
468 tile_cache.reset_traversal();
470 const double *vp = location->get_absolute_view_pos();
471 Point3D viewpos(vp[0], vp[1], vp[2]);
472 while ( ! tile_cache.at_end() ) {
473 // cout << "processing a tile" << endl;
474 if ( (e = tile_cache.get_current()) ) {
475 e->prep_ssg_node( viewpos, up, vis);
477 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
483 bool FGTileMgr::set_tile_filter( bool f ) {
484 bool old = tile_filter;
489 int FGTileMgr::tile_filter_cb( ssgEntity *, int )
491 return tile_filter ? 1 : 0;
494 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
496 // sanity check (unfortunately needed!)
497 if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
500 SGBucket bucket(lon, lat);
501 FGTileEntry *te = tile_cache.get_tile(bucket);
502 if (!te || !te->is_loaded())
505 // Traverse all tiles required to be there for the given visibility.
506 // This uses exactly the same algorithm like the tile scheduler.
507 double tile_width = bucket.get_width_m();
508 double tile_height = bucket.get_height_m();
510 int xrange = (int)fabs(range_m / tile_width) + 1;
511 int yrange = (int)fabs(range_m / tile_height) + 1;
513 for ( int x = -xrange; x <= xrange; ++x ) {
514 for ( int y = -yrange; y <= yrange; ++y ) {
515 // We have already checked for the center tile.
516 if ( x != 0 || y != 0 ) {
517 SGBucket b = sgBucketOffset( lon, lat, x, y );
518 FGTileEntry *te = tile_cache.get_tile(b);
519 if (!te || !te->is_loaded())
525 // Survived all tests.