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>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/renderer.hxx>
42 #include <Main/viewer.hxx>
43 #include <Scripting/NasalSys.hxx>
45 #include "scenery.hxx"
46 #include "SceneryPager.hxx"
47 #include "tilemgr.hxx"
50 using flightgear::SceneryPager;
51 using simgear::SGModelLib;
52 using simgear::TileEntry;
53 using simgear::TileCache;
56 // helper: listen to property changes affecting tile loading
57 class LoaderPropertyWatcher : public SGPropertyChangeListener
60 LoaderPropertyWatcher(FGTileMgr* pTileMgr) :
65 virtual void valueChanged(SGPropertyNode*)
67 _pTileMgr->configChanged();
75 FGTileMgr::FGTileMgr():
78 _propListener(new LoaderPropertyWatcher(this))
80 _randomObjects = fgGetNode("/sim/rendering/random-objects", true);
81 _randomVegetation = fgGetNode("/sim/rendering/random-vegetation", true);
85 FGTileMgr::~FGTileMgr() {
86 // remove all nodes we might have left behind
87 osg::Group* group = globals->get_scenery()->get_terrain_branch();
88 group->removeChildren(0, group->getNumChildren());
94 // Initialize the Tile Manager subsystem
95 void FGTileMgr::init() {
96 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
98 _options = new SGReaderWriterBTGOptions;
99 _options->setMatlib(globals->get_matlib());
101 _randomObjects.get()->addChangeListener(_propListener, false);
102 _randomVegetation.get()->addChangeListener(_propListener, false);
105 osgDB::FilePathList &fp = _options->getDatabasePathList();
106 const string_list &sc = globals->get_fg_scenery();
108 std::copy(sc.begin(), sc.end(), back_inserter(fp));
110 TileEntry::setModelLoadHelper(this);
112 _visibilityMeters = fgGetNode("/environment/visibility-m", true);
118 void FGTileMgr::reinit()
120 // remove all old scenery nodes from scenegraph and clear cache
121 osg::Group* group = globals->get_scenery()->get_terrain_branch();
122 group->removeChildren(0, group->getNumChildren());
127 previous_bucket.make_bad();
128 current_bucket.make_bad();
129 longitude = latitude = -1000.0;
131 // force an update now
135 void FGTileMgr::configChanged()
137 _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
138 _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
141 /* schedule a tile for loading, keep request for given amount of time.
142 * Returns true if tile is already loaded. */
143 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
145 // see if tile already exists in the cache
146 TileEntry *t = tile_cache.get_tile( b );
149 // create a new entry
150 t = new TileEntry( b );
151 // insert the tile into the cache, update will generate load request
152 if ( tile_cache.insert_tile( t ) )
154 // Attach to scene graph
156 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
159 // insert failed (cache full with no available entries to
160 // delete.) Try again later
165 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
168 // update tile's properties
169 tile_cache.request_tile(t,priority,current_view,duration);
171 return t->is_loaded();
174 /* schedule needed buckets for the current view position for loading,
175 * keep request for given amount of time */
176 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
178 // sanity check (unfortunately needed!)
179 if ( longitude < -180.0 || longitude > 180.0
180 || latitude < -90.0 || latitude > 90.0 )
182 SG_LOG( SG_TERRAIN, SG_ALERT,
183 "Attempting to schedule tiles for bogus lon and lat = ("
184 << longitude << "," << latitude << ")" );
186 SG_LOG( SG_TERRAIN, SG_ALERT,
187 "This is a FATAL error. Exiting!" );
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 xrange = (int)(vis / tile_width) + 1;
200 yrange = (int)(vis / tile_height) + 1;
201 if ( xrange < 1 ) { xrange = 1; }
202 if ( yrange < 1 ) { yrange = 1; }
204 // make the cache twice as large to avoid losing terrain when switching
205 // between aircraft and tower views
206 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
207 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
208 // cout << "max cache size = " << tile_cache.get_max_cache_size()
209 // << " current cache size = " << tile_cache.get_size() << endl;
211 // clear flags of all tiles belonging to the previous view set
212 tile_cache.clear_current_view();
214 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
215 osg::FrameStamp* framestamp
216 = globals->get_renderer()->getViewer()->getFrameStamp();
217 tile_cache.set_current_time(framestamp->getReferenceTime());
223 /* schedule all tiles, use distance-based loading priority,
224 * so tiles are loaded in innermost-to-outermost sequence. */
225 for ( x = -xrange; x <= xrange; ++x )
227 for ( y = -yrange; y <= yrange; ++y )
229 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
230 float priority = (-1.0) * (x*x+y*y);
231 sched_tile( b, priority, true, 0.0 );
237 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
240 if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
241 string_list sc = globals->get_fg_scenery();
243 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
245 tmpPath.append(modelPath);
246 if (tmpPath.exists()) {
252 fullPath.append(modelPath);
254 osg::Node* result = 0;
258 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
259 new FGNasalModelData);
262 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
263 new FGNasalModelData);
264 } catch (const sg_io_exception& exc) {
265 string m(exc.getMessage());
267 m += exc.getLocation().asString();
268 SG_LOG( SG_ALL, SG_ALERT, m );
269 } catch (const sg_exception& exc) { // XXX may be redundant
270 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
276 * Update the various queues maintained by the tilemagr (private
277 * internal function, do not call directly.)
279 void FGTileMgr::update_queues()
281 SceneryPager* pager = FGScenery::getPagerSingleton();
282 osg::FrameStamp* framestamp
283 = globals->get_renderer()->getViewer()->getFrameStamp();
284 double current_time = framestamp->getReferenceTime();
285 double vis = _visibilityMeters->getDoubleValue();
290 tile_cache.set_current_time( current_time );
291 tile_cache.reset_traversal();
293 while ( ! tile_cache.at_end() )
295 e = tile_cache.get_current();
296 // cout << "processing a tile" << endl;
299 // Prepare the ssg nodes corresponding to each tile.
300 // Set the ssg transform and update it's range selector
301 // based on current visibilty
302 e->prep_ssg_node(vis);
304 if (( !e->is_loaded() )&&
305 ( !e->is_expired(current_time) ))
307 // schedule tile for loading with osg pager
308 pager->queueRequest(e->tileFileName,
312 e->getDatabaseRequest(),
318 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
324 int drop_count = sz - tile_cache.get_max_cache_size();
325 if (( drop_count > 0 )&&
326 ((loading==0)||(drop_count > 10)))
328 long drop_index = tile_cache.get_drop_tile();
329 while ( drop_index > -1 )
331 // schedule tile for deletion with osg pager
332 TileEntry* old = tile_cache.get_tile(drop_index);
333 tile_cache.clear_entry(drop_index);
335 osg::ref_ptr<osg::Object> subgraph = old->getNode();
336 old->removeFromSceneGraph();
338 // zeros out subgraph ref_ptr, so subgraph is owned by
339 // the pager and will be deleted in the pager thread.
340 pager->queueDeleteRequest(subgraph);
342 if (--drop_count > 0)
343 drop_index = tile_cache.get_drop_tile();
350 // given the current lon/lat (in degrees), fill in the array of local
351 // chunks. If the chunk isn't already in the cache, then read it from
353 void FGTileMgr::update(double)
355 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
356 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
357 double vis = _visibilityMeters->getDoubleValue();
358 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
363 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
364 // "schedule_scenery" instead
365 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
367 longitude = location.getLongitudeDeg();
368 latitude = location.getLatitudeDeg();
370 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
371 // << longitude << " " << latatitude );
373 current_bucket.set_bucket( location );
375 // schedule more tiles when visibility increased considerably
376 // TODO Calculate tile size - instead of using fixed value (5000m)
377 if (range_m-scheduled_visibility > 5000.0)
378 previous_bucket.make_bad();
380 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
381 // << current_bucket );
382 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
384 // do tile load scheduling.
385 // Note that we need keep track of both viewer buckets and fdm buckets.
386 if ( state == Running ) {
387 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
388 if (current_bucket != previous_bucket) {
389 // We've moved to a new bucket, we need to schedule any
390 // needed tiles for loading.
391 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
392 scheduled_visibility = range_m;
393 schedule_needed(current_bucket, range_m);
396 previous_bucket = current_bucket;
397 } else if ( state == Start || state == Inited ) {
398 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
399 // do not update bucket yet (position not valid in initial loop)
401 previous_bucket.make_bad();
407 /** Schedules scenery for given position. Load request remains valid for given duration
408 * (duration=0.0 => nothing is loaded).
409 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
410 * Returns true when all tiles for the given position are already loaded, false otherwise.
412 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
414 const float priority = 0.0;
415 double current_longitude = position.getLongitudeDeg();
416 double current_latitude = position.getLatitudeDeg();
417 bool available = true;
419 // sanity check (unfortunately needed!)
420 if (current_longitude < -180 || current_longitude > 180 ||
421 current_latitude < -90 || current_latitude > 90)
424 SGBucket bucket(position);
425 available = sched_tile( bucket, priority, false, duration );
427 if ((!available)&&(duration==0.0))
430 SGVec3d cartPos = SGVec3d::fromGeod(position);
432 // Traverse all tiles required to be there for the given visibility.
433 double tile_width = bucket.get_width_m();
434 double tile_height = bucket.get_height_m();
435 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
436 double max_dist = tile_r + range_m;
437 double max_dist2 = max_dist*max_dist;
439 int xrange = (int)fabs(range_m / tile_width) + 1;
440 int yrange = (int)fabs(range_m / tile_height) + 1;
442 for ( int x = -xrange; x <= xrange; ++x )
444 for ( int y = -yrange; y <= yrange; ++y )
446 // We have already checked for the center tile.
447 if ( x != 0 || y != 0 )
449 SGBucket b = sgBucketOffset( current_longitude,
450 current_latitude, x, y );
451 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
452 // Do not ask if it is just the next tile but way out of range.
453 if (distance2 <= max_dist2)
455 available &= sched_tile( b, priority, false, duration );
456 if ((!available)&&(duration==0.0))
466 // Returns true if tiles around current view position have been loaded
467 bool FGTileMgr::isSceneryLoaded()
469 double range_m = 100.0;
470 if (scheduled_visibility < range_m)
471 range_m = scheduled_visibility;
473 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);