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.
31 #include <osgViewer/Viewer>
32 #include <osgDB/Registry>
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
39 #include <simgear/scene/tsync/terrasync.hxx>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/scene/material/matlib.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Viewer/renderer.hxx>
46 #include <Viewer/splash.hxx>
47 #include <Scripting/NasalSys.hxx>
48 #include <Scripting/NasalModelData.hxx>
50 #include "scenery.hxx"
51 #include "SceneryPager.hxx"
52 #include "tilemgr.hxx"
54 using flightgear::SceneryPager;
56 class FGTileMgr::TileManagerListener : public SGPropertyChangeListener
59 TileManagerListener(FGTileMgr* manager) :
61 _useVBOsProp(fgGetNode("/sim/rendering/use-vbos", true)),
62 _enableCacheProp(fgGetNode("/sim/tile-cache/enable", true)),
63 _pagedLODMaximumProp(fgGetNode("/sim/rendering/max-paged-lod", true))
65 _useVBOsProp->addChangeListener(this, true);
67 _enableCacheProp->addChangeListener(this, true);
68 if (_enableCacheProp->getType() == simgear::props::NONE) {
69 _enableCacheProp->setBoolValue(true);
72 if (_pagedLODMaximumProp->getType() == simgear::props::NONE) {
73 // not set, use OSG default / environment value variable
74 osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
75 int current = viewer->getDatabasePager()->getTargetMaximumNumberOfPageLOD();
76 _pagedLODMaximumProp->setIntValue(current);
78 _pagedLODMaximumProp->addChangeListener(this, true);
81 ~TileManagerListener()
83 _useVBOsProp->removeChangeListener(this);
84 _enableCacheProp->removeChangeListener(this);
85 _pagedLODMaximumProp->removeChangeListener(this);
88 virtual void valueChanged(SGPropertyNode* prop)
90 if (prop == _useVBOsProp) {
91 bool useVBOs = prop->getBoolValue();
92 _manager->_options->setPluginStringData("SimGear::USE_VBOS",
93 useVBOs ? "ON" : "OFF");
94 } else if (prop == _enableCacheProp) {
95 _manager->_enableCache = prop->getBoolValue();
96 } else if (prop == _pagedLODMaximumProp) {
97 int v = prop->getIntValue();
98 osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
99 viewer->getDatabasePager()->setTargetMaximumNumberOfPageLOD(v);
105 SGPropertyNode_ptr _useVBOsProp,
107 _pagedLODMaximumProp;
110 FGTileMgr::FGTileMgr():
112 last_state( Running ),
113 scheduled_visibility(100.0),
116 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
117 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
118 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
119 _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
120 _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
121 _pager(FGScenery::getPagerSingleton()),
127 FGTileMgr::~FGTileMgr()
131 // remove all nodes we might have left behind
132 osg::Group* group = globals->get_scenery()->get_terrain_branch();
133 group->removeChildren(0, group->getNumChildren());
135 osgDB::Registry::instance()->clearObjectCache();
139 // Initialize the Tile Manager subsystem
140 void FGTileMgr::init() {
141 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
143 _options = new simgear::SGReaderWriterOptions;
144 _listener = new TileManagerListener(this);
146 materialLibChanged();
147 _options->setPropertyNode(globals->get_props());
149 osgDB::FilePathList &fp = _options->getDatabasePathList();
150 const string_list &sc = globals->get_fg_scenery();
152 std::copy(sc.begin(), sc.end(), back_inserter(fp));
153 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
155 if (globals->get_subsystem("terrasync")) {
156 _options->setPluginStringData("SimGear::TERRASYNC_ROOT", fgGetString("/sim/terrasync/scenery-dir"));
159 if (!_disableNasalHooks->getBoolValue())
160 _options->setModelData(new FGNasalModelDataProxy);
165 void FGTileMgr::reinit()
167 _terra_sync = static_cast<simgear::SGTerraSync*> (globals->get_subsystem("terrasync"));
169 // protect against multiple scenery reloads and properly reset flags,
170 // otherwise aircraft fall through the ground while reloading scenery
171 if (!fgGetBool("/sim/sceneryloaded",true))
173 fgSetBool("/sim/sceneryloaded",false);
174 fgSetDouble("/sim/startup/splash-alpha", 1.0);
176 materialLibChanged();
178 // remove all old scenery nodes from scenegraph and clear cache
179 osg::Group* group = globals->get_scenery()->get_terrain_branch();
180 group->removeChildren(0, group->getNumChildren());
183 // clear OSG cache, except on initial start-up
186 osgDB::Registry::instance()->clearObjectCache();
191 previous_bucket.make_bad();
192 current_bucket.make_bad();
193 scheduled_visibility = 100.0;
195 // force an update now
199 void FGTileMgr::materialLibChanged()
201 _options->setMaterialLib(globals->get_matlib());
204 /* schedule a tile for loading, keep request for given amount of time.
205 * Returns true if tile is already loaded. */
206 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
208 // see if tile already exists in the cache
209 TileEntry *t = tile_cache.get_tile( b );
212 // create a new entry
213 t = new TileEntry( b );
214 // insert the tile into the cache, update will generate load request
215 if ( tile_cache.insert_tile( t ) )
217 // Attach to scene graph
219 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
222 // insert failed (cache full with no available entries to
223 // delete.) Try again later
228 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
231 // update tile's properties
232 tile_cache.request_tile(t,priority,current_view,duration);
234 return t->is_loaded();
237 /* schedule needed buckets for the current view position for loading,
238 * keep request for given amount of time */
239 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
241 // sanity check (unfortunately needed!)
242 if (!curr_bucket.isValid() )
244 SG_LOG( SG_TERRAIN, SG_ALERT,
245 "Attempting to schedule tiles for invalid bucket" );
249 double tile_width = curr_bucket.get_width_m();
250 double tile_height = curr_bucket.get_height_m();
251 SG_LOG( SG_TERRAIN, SG_INFO,
252 "scheduling needed tiles for " << curr_bucket
253 << ", tile-width-m:" << tile_width << ", tile-height-m:" << tile_height);
256 // cout << "tile width = " << tile_width << " tile_height = "
257 // << tile_height << endl;
259 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
260 int xrange = (int)(tileRangeM / tile_width) + 1;
261 int yrange = (int)(tileRangeM / tile_height) + 1;
262 if ( xrange < 1 ) { xrange = 1; }
263 if ( yrange < 1 ) { yrange = 1; }
265 // make the cache twice as large to avoid losing terrain when switching
266 // between aircraft and tower views
267 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
268 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
269 // cout << "max cache size = " << tile_cache.get_max_cache_size()
270 // << " current cache size = " << tile_cache.get_size() << endl;
272 // clear flags of all tiles belonging to the previous view set
273 tile_cache.clear_current_view();
275 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
276 osg::FrameStamp* framestamp
277 = globals->get_renderer()->getViewer()->getFrameStamp();
278 tile_cache.set_current_time(framestamp->getReferenceTime());
284 /* schedule all tiles, use distance-based loading priority,
285 * so tiles are loaded in innermost-to-outermost sequence. */
286 for ( x = -xrange; x <= xrange; ++x )
288 for ( y = -yrange; y <= yrange; ++y )
290 SGBucket b = curr_bucket.sibling(x, y);
295 float priority = (-1.0) * (x*x+y*y);
296 sched_tile( b, priority, true, 0.0 );
299 _terra_sync->scheduleTile(b);
306 * Update the various queues maintained by the tilemgr (private
307 * internal function, do not call directly.)
309 void FGTileMgr::update_queues(bool& isDownloadingScenery)
311 osg::FrameStamp* framestamp
312 = globals->get_renderer()->getViewer()->getFrameStamp();
313 double current_time = framestamp->getReferenceTime();
314 double vis = _visibilityMeters->getDoubleValue();
319 tile_cache.set_current_time( current_time );
320 tile_cache.reset_traversal();
322 while ( ! tile_cache.at_end() )
324 e = tile_cache.get_current();
327 // Prepare the ssg nodes corresponding to each tile.
328 // Set the ssg transform and update it's range selector
329 // based on current visibilty
330 e->prep_ssg_node(vis);
332 if (!e->is_loaded()) {
333 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
334 bool downloading = isTileDirSyncing(e->tileFileName);
335 isDownloadingScenery |= downloading;
336 if ( !downloading && nonExpiredOrCurrent) {
337 // schedule tile for loading with osg pager
338 _pager->queueRequest(e->tileFileName,
342 e->getDatabaseRequest(),
346 } // of tile not loaded case
348 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
354 int drop_count = sz - tile_cache.get_max_cache_size();
355 bool dropTiles = false;
357 dropTiles = ( drop_count > 0 ) && ((loading==0)||(drop_count > 10));
360 drop_count = sz; // no limit on tiles to drop
365 long drop_index = _enableCache ? tile_cache.get_drop_tile() :
366 tile_cache.get_first_expired_tile();
367 while ( drop_index > -1 )
369 // schedule tile for deletion with osg pager
370 TileEntry* old = tile_cache.get_tile(drop_index);
371 SG_LOG(SG_TERRAIN, SG_DEBUG, "Dropping:" << old->get_tile_bucket());
373 tile_cache.clear_entry(drop_index);
375 osg::ref_ptr<osg::Object> subgraph = old->getNode();
376 old->removeFromSceneGraph();
378 // zeros out subgraph ref_ptr, so subgraph is owned by
379 // the pager and will be deleted in the pager thread.
380 _pager->queueDeleteRequest(subgraph);
383 drop_index = tile_cache.get_first_expired_tile();
384 // limit tiles dropped to drop_count
385 else if (--drop_count > 0)
386 drop_index = tile_cache.get_drop_tile();
390 } // of dropping tiles loop
393 // given the current lon/lat (in degrees), fill in the array of local
394 // chunks. If the chunk isn't already in the cache, then read it from
396 void FGTileMgr::update(double)
398 double vis = _visibilityMeters->getDoubleValue();
399 schedule_tiles_at(globals->get_view_position(), vis);
401 bool waitingOnTerrasync = false;
402 update_queues(waitingOnTerrasync);
404 // scenery loading check, triggers after each sim (tile manager) reinit
405 if (!_scenery_loaded->getBoolValue())
407 bool fdmInited = fgGetBool("sim/fdm-initialized");
408 bool positionFinalized = fgGetBool("sim/position-finalized");
409 bool sceneryOverride = _scenery_override->getBoolValue();
412 // we are done if final position is set and the scenery & FDM are done.
413 // scenery-override can ignore the last two, but not position finalization.
414 if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
416 _scenery_loaded->setBoolValue(true);
417 fgSplashProgress("");
421 if (!positionFinalized) {
422 fgSplashProgress("finalize-position");
423 } else if (waitingOnTerrasync) {
424 fgSplashProgress("downloading-scenery");
426 fgSplashProgress("loading-scenery");
429 // be nice to loader threads while waiting for initial scenery, reduce to 20fps
430 SGTimeStamp::sleepForMSec(50);
435 // schedule tiles for the viewer bucket
436 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
437 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
439 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
440 // << longitude << " " << latitude );
442 current_bucket = SGBucket( location );
444 // schedule more tiles when visibility increased considerably
445 // TODO Calculate tile size - instead of using fixed value (5000m)
446 if (range_m - scheduled_visibility > 5000.0)
447 previous_bucket.make_bad();
449 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
450 // << current_bucket );
451 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
453 // do tile load scheduling.
454 // Note that we need keep track of both viewer buckets and fdm buckets.
455 if ( state == Running ) {
456 if (last_state != state)
458 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
460 if (current_bucket != previous_bucket) {
461 // We've moved to a new bucket, we need to schedule any
462 // needed tiles for loading.
463 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr: at " << location << ", scheduling needed for:" << current_bucket
464 << ", visbility=" << range_m);
465 scheduled_visibility = range_m;
466 schedule_needed(current_bucket, range_m);
470 previous_bucket = current_bucket;
471 } else if ( state == Start || state == Inited ) {
472 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
473 // do not update bucket yet (position not valid in initial loop)
475 previous_bucket.make_bad();
480 /** Schedules scenery for given position. Load request remains valid for given duration
481 * (duration=0.0 => nothing is loaded).
482 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
483 * Returns true when all tiles for the given position are already loaded, false otherwise.
485 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
487 // sanity check (unfortunately needed!)
488 if (!position.isValid())
490 const float priority = 0.0;
491 bool available = true;
493 SGBucket bucket(position);
494 available = sched_tile( bucket, priority, false, duration );
496 if ((!available)&&(duration==0.0))
499 SGVec3d cartPos = SGVec3d::fromGeod(position);
501 // Traverse all tiles required to be there for the given visibility.
502 double tile_width = bucket.get_width_m();
503 double tile_height = bucket.get_height_m();
504 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
505 double max_dist = tile_r + range_m;
506 double max_dist2 = max_dist*max_dist;
508 int xrange = (int)fabs(range_m / tile_width) + 1;
509 int yrange = (int)fabs(range_m / tile_height) + 1;
511 for ( int x = -xrange; x <= xrange; ++x )
513 for ( int y = -yrange; y <= yrange; ++y )
515 // We have already checked for the center tile.
516 if ( x != 0 || y != 0 )
518 SGBucket b = bucket.sibling(x, y );
523 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
524 // Do not ask if it is just the next tile but way out of range.
525 if (distance2 <= max_dist2)
527 available &= sched_tile( b, priority, false, duration );
528 if ((!available)&&(duration==0.0))
538 // Returns true if tiles around current view position have been loaded
539 bool FGTileMgr::isSceneryLoaded()
541 double range_m = 100.0;
542 if (scheduled_visibility < range_m)
543 range_m = scheduled_visibility;
545 return schedule_scenery(globals->get_view_position(), range_m, 0.0);
548 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
554 std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
555 long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
556 SGBucket bucket(bucketIndex);
558 return _terra_sync->isTileDirPending(bucket.gen_base_path());