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>
41 #include <Main/globals.hxx>
42 #include <Main/fg_props.hxx>
43 #include <Viewer/renderer.hxx>
44 #include <Viewer/splash.hxx>
45 #include <Scripting/NasalSys.hxx>
46 #include <Scripting/NasalModelData.hxx>
48 #include "scenery.hxx"
49 #include "SceneryPager.hxx"
50 #include "tilemgr.hxx"
52 using flightgear::SceneryPager;
55 FGTileMgr::FGTileMgr():
57 last_state( Running ),
60 scheduled_visibility(100.0),
62 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
63 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
64 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
65 _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
66 _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
67 _pager(FGScenery::getPagerSingleton())
72 FGTileMgr::~FGTileMgr()
74 // remove all nodes we might have left behind
75 osg::Group* group = globals->get_scenery()->get_terrain_branch();
76 group->removeChildren(0, group->getNumChildren());
78 osgDB::Registry::instance()->clearObjectCache();
82 // Initialize the Tile Manager subsystem
83 void FGTileMgr::init() {
84 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
86 _options = new simgear::SGReaderWriterOptions;
87 _options->setMaterialLib(globals->get_matlib());
88 _options->setPropertyNode(globals->get_props());
90 osgDB::FilePathList &fp = _options->getDatabasePathList();
91 const string_list &sc = globals->get_fg_scenery();
93 std::copy(sc.begin(), sc.end(), back_inserter(fp));
94 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
95 if (!_disableNasalHooks->getBoolValue())
96 _options->setModelData(new FGNasalModelDataProxy);
101 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
103 ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
106 void FGTileMgr::reinit()
108 _terra_sync = static_cast<simgear::SGTerraSync*> (globals->get_subsystem("terrasync"));
110 _terra_sync->setTileRefreshCb(&refresh_tile, this);
112 // protect against multiple scenery reloads and properly reset flags,
113 // otherwise aircraft fall through the ground while reloading scenery
114 if (!fgGetBool("/sim/sceneryloaded",true))
116 fgSetBool("/sim/sceneryloaded",false);
117 fgSetDouble("/sim/startup/splash-alpha", 1.0);
119 // Reload the materials definitions
120 _options->setMaterialLib(globals->get_matlib());
122 // remove all old scenery nodes from scenegraph and clear cache
123 osg::Group* group = globals->get_scenery()->get_terrain_branch();
124 group->removeChildren(0, group->getNumChildren());
127 // clear OSG cache, except on initial start-up
130 osgDB::Registry::instance()->clearObjectCache();
135 previous_bucket.make_bad();
136 current_bucket.make_bad();
137 longitude = latitude = -1000.0;
138 scheduled_visibility = 100.0;
140 // force an update now
144 /* schedule a tile for loading, keep request for given amount of time.
145 * Returns true if tile is already loaded. */
146 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
148 // see if tile already exists in the cache
149 TileEntry *t = tile_cache.get_tile( b );
152 // create a new entry
153 t = new TileEntry( b );
154 // insert the tile into the cache, update will generate load request
155 if ( tile_cache.insert_tile( t ) )
157 // Attach to scene graph
159 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
162 // insert failed (cache full with no available entries to
163 // delete.) Try again later
168 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
171 // update tile's properties
172 tile_cache.request_tile(t,priority,current_view,duration);
174 return t->is_loaded();
177 /* schedule needed buckets for the current view position for loading,
178 * keep request for given amount of time */
179 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
181 // sanity check (unfortunately needed!)
182 if ( longitude < -180.0 || longitude > 180.0
183 || latitude < -90.0 || latitude > 90.0 )
185 SG_LOG( SG_TERRAIN, SG_ALERT,
186 "Attempting to schedule tiles for bogus lon and lat = ("
187 << longitude << "," << latitude << ")" );
191 SG_LOG( SG_TERRAIN, SG_INFO,
192 "scheduling needed tiles for " << longitude << " " << latitude );
194 double tile_width = curr_bucket.get_width_m();
195 double tile_height = curr_bucket.get_height_m();
196 // cout << "tile width = " << tile_width << " tile_height = "
197 // << tile_height << endl;
199 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
200 int xrange = (int)(tileRangeM / tile_width) + 1;
201 int yrange = (int)(tileRangeM / tile_height) + 1;
202 if ( xrange < 1 ) { xrange = 1; }
203 if ( yrange < 1 ) { yrange = 1; }
205 // make the cache twice as large to avoid losing terrain when switching
206 // between aircraft and tower views
207 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
208 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
209 // cout << "max cache size = " << tile_cache.get_max_cache_size()
210 // << " current cache size = " << tile_cache.get_size() << endl;
212 // clear flags of all tiles belonging to the previous view set
213 tile_cache.clear_current_view();
215 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
216 osg::FrameStamp* framestamp
217 = globals->get_renderer()->getViewer()->getFrameStamp();
218 tile_cache.set_current_time(framestamp->getReferenceTime());
224 /* schedule all tiles, use distance-based loading priority,
225 * so tiles are loaded in innermost-to-outermost sequence. */
226 for ( x = -xrange; x <= xrange; ++x )
228 for ( y = -yrange; y <= yrange; ++y )
230 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
231 float priority = (-1.0) * (x*x+y*y);
232 sched_tile( b, priority, true, 0.0 );
238 * Update the various queues maintained by the tilemagr (private
239 * internal function, do not call directly.)
241 void FGTileMgr::update_queues()
243 osg::FrameStamp* framestamp
244 = globals->get_renderer()->getViewer()->getFrameStamp();
245 double current_time = framestamp->getReferenceTime();
246 double vis = _visibilityMeters->getDoubleValue();
251 tile_cache.set_current_time( current_time );
252 tile_cache.reset_traversal();
254 while ( ! tile_cache.at_end() )
256 e = tile_cache.get_current();
257 // cout << "processing a tile" << endl;
260 // Prepare the ssg nodes corresponding to each tile.
261 // Set the ssg transform and update it's range selector
262 // based on current visibilty
263 e->prep_ssg_node(vis);
265 if (( !e->is_loaded() )&&
266 ((!e->is_expired(current_time))||
267 e->is_current_view() ))
269 // schedule tile for loading with osg pager
270 _pager->queueRequest(e->tileFileName,
274 e->getDatabaseRequest(),
280 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
286 int drop_count = sz - tile_cache.get_max_cache_size();
287 if (( drop_count > 0 )&&
288 ((loading==0)||(drop_count > 10)))
290 long drop_index = tile_cache.get_drop_tile();
291 while ( drop_index > -1 )
293 // schedule tile for deletion with osg pager
294 TileEntry* old = tile_cache.get_tile(drop_index);
295 tile_cache.clear_entry(drop_index);
297 osg::ref_ptr<osg::Object> subgraph = old->getNode();
298 old->removeFromSceneGraph();
300 // zeros out subgraph ref_ptr, so subgraph is owned by
301 // the pager and will be deleted in the pager thread.
302 _pager->queueDeleteRequest(subgraph);
304 if (--drop_count > 0)
305 drop_index = tile_cache.get_drop_tile();
312 // given the current lon/lat (in degrees), fill in the array of local
313 // chunks. If the chunk isn't already in the cache, then read it from
315 void FGTileMgr::update(double)
317 double vis = _visibilityMeters->getDoubleValue();
318 schedule_tiles_at(globals->get_view_position(), vis);
322 // scenery loading check, triggers after each sim (tile manager) reinit
323 if (!_scenery_loaded->getBoolValue())
325 bool fdmInited = fgGetBool("sim/fdm-initialized");
326 bool positionFinalized = fgGetBool("sim/position-finalized");
327 bool sceneryOverride = _scenery_override->getBoolValue();
329 // we are done if final position is set and the scenery & FDM are done.
330 // scenery-override can ignore the last two, but not position finalization.
331 if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
333 _scenery_loaded->setBoolValue(true);
334 fgSplashProgress("");
338 fgSplashProgress(positionFinalized ? "loading-scenery" : "finalize-position");
339 // be nice to loader threads while waiting for initial scenery, reduce to 20fps
340 SGTimeStamp::sleepForMSec(50);
345 // schedule tiles for the viewer bucket
346 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
347 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
349 longitude = location.getLongitudeDeg();
350 latitude = location.getLatitudeDeg();
352 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
353 // << longitude << " " << latitude );
355 current_bucket.set_bucket( location );
357 // schedule more tiles when visibility increased considerably
358 // TODO Calculate tile size - instead of using fixed value (5000m)
359 if (range_m - scheduled_visibility > 5000.0)
360 previous_bucket.make_bad();
362 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
363 // << current_bucket );
364 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
366 // do tile load scheduling.
367 // Note that we need keep track of both viewer buckets and fdm buckets.
368 if ( state == Running ) {
369 if (last_state != state)
371 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
373 if (current_bucket != previous_bucket) {
374 // We've moved to a new bucket, we need to schedule any
375 // needed tiles for loading.
376 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
377 scheduled_visibility = range_m;
378 schedule_needed(current_bucket, range_m);
380 _terra_sync->schedulePosition(latitude,longitude);
383 previous_bucket = current_bucket;
384 } else if ( state == Start || state == Inited ) {
385 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
386 // do not update bucket yet (position not valid in initial loop)
388 previous_bucket.make_bad();
393 /** Schedules scenery for given position. Load request remains valid for given duration
394 * (duration=0.0 => nothing is loaded).
395 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
396 * Returns true when all tiles for the given position are already loaded, false otherwise.
398 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
400 const float priority = 0.0;
401 double current_longitude = position.getLongitudeDeg();
402 double current_latitude = position.getLatitudeDeg();
403 bool available = true;
405 // sanity check (unfortunately needed!)
406 if (current_longitude < -180 || current_longitude > 180 ||
407 current_latitude < -90 || current_latitude > 90)
410 SGBucket bucket(position);
411 available = sched_tile( bucket, priority, false, duration );
413 if ((!available)&&(duration==0.0))
416 SGVec3d cartPos = SGVec3d::fromGeod(position);
418 // Traverse all tiles required to be there for the given visibility.
419 double tile_width = bucket.get_width_m();
420 double tile_height = bucket.get_height_m();
421 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
422 double max_dist = tile_r + range_m;
423 double max_dist2 = max_dist*max_dist;
425 int xrange = (int)fabs(range_m / tile_width) + 1;
426 int yrange = (int)fabs(range_m / tile_height) + 1;
428 for ( int x = -xrange; x <= xrange; ++x )
430 for ( int y = -yrange; y <= yrange; ++y )
432 // We have already checked for the center tile.
433 if ( x != 0 || y != 0 )
435 SGBucket b = sgBucketOffset( current_longitude,
436 current_latitude, x, y );
437 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
438 // Do not ask if it is just the next tile but way out of range.
439 if (distance2 <= max_dist2)
441 available &= sched_tile( b, priority, false, duration );
442 if ((!available)&&(duration==0.0))
452 // Returns true if tiles around current view position have been loaded
453 bool FGTileMgr::isSceneryLoaded()
455 double range_m = 100.0;
456 if (scheduled_visibility < range_m)
457 range_m = scheduled_visibility;
459 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);