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>
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/scene/model/modellib.hxx>
37 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
38 #include <simgear/scene/tsync/terrasync.hxx>
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Main/renderer.hxx>
43 #include <Main/viewer.hxx>
44 #include <Scripting/NasalSys.hxx>
46 #include "scenery.hxx"
47 #include "SceneryPager.hxx"
48 #include "tilemgr.hxx"
51 using flightgear::SceneryPager;
52 using simgear::SGModelLib;
53 using simgear::TileEntry;
54 using simgear::TileCache;
57 // helper: listen to property changes affecting tile loading
58 class LoaderPropertyWatcher : public SGPropertyChangeListener
61 LoaderPropertyWatcher(FGTileMgr* pTileMgr) :
66 virtual void valueChanged(SGPropertyNode*)
68 _pTileMgr->configChanged();
76 FGTileMgr::FGTileMgr():
80 _propListener(new LoaderPropertyWatcher(this))
82 _randomObjects = fgGetNode("/sim/rendering/random-objects", true);
83 _randomVegetation = fgGetNode("/sim/rendering/random-vegetation", true);
84 _maxTileRangeM = fgGetNode("/sim/rendering/static-lod/bare", true);
88 FGTileMgr::~FGTileMgr()
90 // remove all nodes we might have left behind
91 osg::Group* group = globals->get_scenery()->get_terrain_branch();
92 group->removeChildren(0, group->getNumChildren());
96 osgDB::Registry::instance()->clearObjectCache();
100 // Initialize the Tile Manager subsystem
101 void FGTileMgr::init() {
102 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
104 _options = new SGReaderWriterBTGOptions;
105 _options->setMatlib(globals->get_matlib());
107 _randomObjects.get()->addChangeListener(_propListener, false);
108 _randomVegetation.get()->addChangeListener(_propListener, false);
111 osgDB::FilePathList &fp = _options->getDatabasePathList();
112 const string_list &sc = globals->get_fg_scenery();
114 std::copy(sc.begin(), sc.end(), back_inserter(fp));
116 TileEntry::setModelLoadHelper(this);
118 _visibilityMeters = fgGetNode("/environment/visibility-m", true);
124 void FGTileMgr::reinit()
126 // remove all old scenery nodes from scenegraph and clear cache
127 osg::Group* group = globals->get_scenery()->get_terrain_branch();
128 group->removeChildren(0, group->getNumChildren());
131 // clear OSG cache, except on initial start-up
134 osgDB::Registry::instance()->clearObjectCache();
139 previous_bucket.make_bad();
140 current_bucket.make_bad();
141 longitude = latitude = -1000.0;
143 _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
145 _terra_sync->setTileCache(&tile_cache);
147 // force an update now
151 void FGTileMgr::configChanged()
153 _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
154 _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
157 /* schedule a tile for loading, keep request for given amount of time.
158 * Returns true if tile is already loaded. */
159 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
161 // see if tile already exists in the cache
162 TileEntry *t = tile_cache.get_tile( b );
165 // create a new entry
166 t = new TileEntry( b );
167 // insert the tile into the cache, update will generate load request
168 if ( tile_cache.insert_tile( t ) )
170 // Attach to scene graph
172 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
175 // insert failed (cache full with no available entries to
176 // delete.) Try again later
181 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
184 // update tile's properties
185 tile_cache.request_tile(t,priority,current_view,duration);
187 return t->is_loaded();
190 /* schedule needed buckets for the current view position for loading,
191 * keep request for given amount of time */
192 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
194 // sanity check (unfortunately needed!)
195 if ( longitude < -180.0 || longitude > 180.0
196 || latitude < -90.0 || latitude > 90.0 )
198 SG_LOG( SG_TERRAIN, SG_ALERT,
199 "Attempting to schedule tiles for bogus lon and lat = ("
200 << longitude << "," << latitude << ")" );
204 SG_LOG( SG_TERRAIN, SG_INFO,
205 "scheduling needed tiles for " << longitude << " " << latitude );
207 double tile_width = curr_bucket.get_width_m();
208 double tile_height = curr_bucket.get_height_m();
209 // cout << "tile width = " << tile_width << " tile_height = "
210 // << tile_height << endl;
212 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
213 xrange = (int)(tileRangeM / tile_width) + 1;
214 yrange = (int)(tileRangeM / tile_height) + 1;
215 if ( xrange < 1 ) { xrange = 1; }
216 if ( yrange < 1 ) { yrange = 1; }
218 // make the cache twice as large to avoid losing terrain when switching
219 // between aircraft and tower views
220 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
221 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
222 // cout << "max cache size = " << tile_cache.get_max_cache_size()
223 // << " current cache size = " << tile_cache.get_size() << endl;
225 // clear flags of all tiles belonging to the previous view set
226 tile_cache.clear_current_view();
228 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
229 osg::FrameStamp* framestamp
230 = globals->get_renderer()->getViewer()->getFrameStamp();
231 tile_cache.set_current_time(framestamp->getReferenceTime());
237 /* schedule all tiles, use distance-based loading priority,
238 * so tiles are loaded in innermost-to-outermost sequence. */
239 for ( x = -xrange; x <= xrange; ++x )
241 for ( y = -yrange; y <= yrange; ++y )
243 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
244 float priority = (-1.0) * (x*x+y*y);
245 sched_tile( b, priority, true, 0.0 );
251 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
253 SGPath fullPath = modelPath;
254 if ((fullPath.isRelative())&&
255 (fgGetBool("/sim/paths/use-custom-scenery-data") == true)) {
256 string_list sc = globals->get_fg_scenery();
258 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
259 // fg_senery contains empty strings as "markers" (see FGGlobals::set_fg_scenery)
262 tmpPath.append(modelPath);
263 if (tmpPath.exists()) {
270 osg::Node* result = 0;
274 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
275 new FGNasalModelData);
278 SGModelLib::loadPagedModel(fullPath.str(), globals->get_props(),
279 new FGNasalModelData);
280 } catch (const sg_io_exception& exc) {
281 string m(exc.getMessage());
283 m += exc.getLocation().asString();
284 SG_LOG( SG_TERRAIN, SG_ALERT, m );
285 } catch (const sg_exception& exc) { // XXX may be redundant
286 SG_LOG( SG_TERRAIN, SG_ALERT, exc.getMessage());
292 * Update the various queues maintained by the tilemagr (private
293 * internal function, do not call directly.)
295 void FGTileMgr::update_queues()
297 SceneryPager* pager = FGScenery::getPagerSingleton();
298 osg::FrameStamp* framestamp
299 = globals->get_renderer()->getViewer()->getFrameStamp();
300 double current_time = framestamp->getReferenceTime();
301 double vis = _visibilityMeters->getDoubleValue();
306 tile_cache.set_current_time( current_time );
307 tile_cache.reset_traversal();
309 while ( ! tile_cache.at_end() )
311 e = tile_cache.get_current();
312 // cout << "processing a tile" << endl;
315 // Prepare the ssg nodes corresponding to each tile.
316 // Set the ssg transform and update it's range selector
317 // based on current visibilty
318 e->prep_ssg_node(vis);
320 if (( !e->is_loaded() )&&
321 ((!e->is_expired(current_time))||
322 e->is_current_view() ))
324 // schedule tile for loading with osg pager
325 pager->queueRequest(e->tileFileName,
329 e->getDatabaseRequest(),
335 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
341 int drop_count = sz - tile_cache.get_max_cache_size();
342 if (( drop_count > 0 )&&
343 ((loading==0)||(drop_count > 10)))
345 long drop_index = tile_cache.get_drop_tile();
346 while ( drop_index > -1 )
348 // schedule tile for deletion with osg pager
349 TileEntry* old = tile_cache.get_tile(drop_index);
350 tile_cache.clear_entry(drop_index);
352 osg::ref_ptr<osg::Object> subgraph = old->getNode();
353 old->removeFromSceneGraph();
355 // zeros out subgraph ref_ptr, so subgraph is owned by
356 // the pager and will be deleted in the pager thread.
357 pager->queueDeleteRequest(subgraph);
359 if (--drop_count > 0)
360 drop_index = tile_cache.get_drop_tile();
367 // given the current lon/lat (in degrees), fill in the array of local
368 // chunks. If the chunk isn't already in the cache, then read it from
370 void FGTileMgr::update(double)
372 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
373 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
374 double vis = _visibilityMeters->getDoubleValue();
375 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
380 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
381 // "schedule_scenery" instead
382 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
384 longitude = location.getLongitudeDeg();
385 latitude = location.getLatitudeDeg();
387 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
388 // << longitude << " " << latatitude );
390 current_bucket.set_bucket( location );
392 // schedule more tiles when visibility increased considerably
393 // TODO Calculate tile size - instead of using fixed value (5000m)
394 if (range_m-scheduled_visibility > 5000.0)
395 previous_bucket.make_bad();
397 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
398 // << current_bucket );
399 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
401 // do tile load scheduling.
402 // Note that we need keep track of both viewer buckets and fdm buckets.
403 if ( state == Running ) {
404 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
405 if (current_bucket != previous_bucket) {
406 // We've moved to a new bucket, we need to schedule any
407 // needed tiles for loading.
408 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
409 scheduled_visibility = range_m;
410 schedule_needed(current_bucket, range_m);
412 _terra_sync->schedulePosition(latitude,longitude);
415 previous_bucket = current_bucket;
416 } else if ( state == Start || state == Inited ) {
417 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
418 // do not update bucket yet (position not valid in initial loop)
420 previous_bucket.make_bad();
426 /** Schedules scenery for given position. Load request remains valid for given duration
427 * (duration=0.0 => nothing is loaded).
428 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
429 * Returns true when all tiles for the given position are already loaded, false otherwise.
431 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
433 const float priority = 0.0;
434 double current_longitude = position.getLongitudeDeg();
435 double current_latitude = position.getLatitudeDeg();
436 bool available = true;
438 // sanity check (unfortunately needed!)
439 if (current_longitude < -180 || current_longitude > 180 ||
440 current_latitude < -90 || current_latitude > 90)
443 SGBucket bucket(position);
444 available = sched_tile( bucket, priority, false, duration );
446 if ((!available)&&(duration==0.0))
449 SGVec3d cartPos = SGVec3d::fromGeod(position);
451 // Traverse all tiles required to be there for the given visibility.
452 double tile_width = bucket.get_width_m();
453 double tile_height = bucket.get_height_m();
454 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
455 double max_dist = tile_r + range_m;
456 double max_dist2 = max_dist*max_dist;
458 int xrange = (int)fabs(range_m / tile_width) + 1;
459 int yrange = (int)fabs(range_m / tile_height) + 1;
461 for ( int x = -xrange; x <= xrange; ++x )
463 for ( int y = -yrange; y <= yrange; ++y )
465 // We have already checked for the center tile.
466 if ( x != 0 || y != 0 )
468 SGBucket b = sgBucketOffset( current_longitude,
469 current_latitude, x, y );
470 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
471 // Do not ask if it is just the next tile but way out of range.
472 if (distance2 <= max_dist2)
474 available &= sched_tile( b, priority, false, duration );
475 if ((!available)&&(duration==0.0))
485 // Returns true if tiles around current view position have been loaded
486 bool FGTileMgr::isSceneryLoaded()
488 double range_m = 100.0;
489 if (scheduled_visibility < range_m)
490 range_m = scheduled_visibility;
492 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);