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 <Main/renderer.hxx>
44 #include <Main/viewer.hxx>
45 #include <Scripting/NasalSys.hxx>
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
52 using flightgear::SceneryPager;
53 using simgear::SGModelLib;
54 using simgear::TileEntry;
55 using simgear::TileCache;
58 FGTileMgr::FGTileMgr():
60 last_state( Running ),
63 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
64 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
65 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true))
70 FGTileMgr::~FGTileMgr()
72 // remove all nodes we might have left behind
73 osg::Group* group = globals->get_scenery()->get_terrain_branch();
74 group->removeChildren(0, group->getNumChildren());
76 osgDB::Registry::instance()->clearObjectCache();
80 // Initialize the Tile Manager subsystem
81 void FGTileMgr::init() {
82 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
84 _options = new simgear::SGReaderWriterOptions;
85 _options->setMaterialLib(globals->get_matlib());
86 _options->setPropertyNode(globals->get_props());
88 osgDB::FilePathList &fp = _options->getDatabasePathList();
89 const string_list &sc = globals->get_fg_scenery();
91 std::copy(sc.begin(), sc.end(), back_inserter(fp));
93 TileEntry::setModelLoadHelper(this);
98 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
100 ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
103 void FGTileMgr::reinit()
105 // remove all old scenery nodes from scenegraph and clear cache
106 osg::Group* group = globals->get_scenery()->get_terrain_branch();
107 group->removeChildren(0, group->getNumChildren());
110 // clear OSG cache, except on initial start-up
113 osgDB::Registry::instance()->clearObjectCache();
118 previous_bucket.make_bad();
119 current_bucket.make_bad();
120 longitude = latitude = -1000.0;
122 _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
124 _terra_sync->setTileRefreshCb(&refresh_tile, this);
126 // force an update now
130 /* schedule a tile for loading, keep request for given amount of time.
131 * Returns true if tile is already loaded. */
132 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
134 // see if tile already exists in the cache
135 TileEntry *t = tile_cache.get_tile( b );
138 // create a new entry
139 t = new TileEntry( b );
140 // insert the tile into the cache, update will generate load request
141 if ( tile_cache.insert_tile( t ) )
143 // Attach to scene graph
145 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
148 // insert failed (cache full with no available entries to
149 // delete.) Try again later
154 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
157 // update tile's properties
158 tile_cache.request_tile(t,priority,current_view,duration);
160 return t->is_loaded();
163 /* schedule needed buckets for the current view position for loading,
164 * keep request for given amount of time */
165 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
167 // sanity check (unfortunately needed!)
168 if ( longitude < -180.0 || longitude > 180.0
169 || latitude < -90.0 || latitude > 90.0 )
171 SG_LOG( SG_TERRAIN, SG_ALERT,
172 "Attempting to schedule tiles for bogus lon and lat = ("
173 << longitude << "," << latitude << ")" );
177 SG_LOG( SG_TERRAIN, SG_INFO,
178 "scheduling needed tiles for " << longitude << " " << latitude );
180 double tile_width = curr_bucket.get_width_m();
181 double tile_height = curr_bucket.get_height_m();
182 // cout << "tile width = " << tile_width << " tile_height = "
183 // << tile_height << endl;
185 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
186 xrange = (int)(tileRangeM / tile_width) + 1;
187 yrange = (int)(tileRangeM / tile_height) + 1;
188 if ( xrange < 1 ) { xrange = 1; }
189 if ( yrange < 1 ) { yrange = 1; }
191 // make the cache twice as large to avoid losing terrain when switching
192 // between aircraft and tower views
193 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
194 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
195 // cout << "max cache size = " << tile_cache.get_max_cache_size()
196 // << " current cache size = " << tile_cache.get_size() << endl;
198 // clear flags of all tiles belonging to the previous view set
199 tile_cache.clear_current_view();
201 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
202 osg::FrameStamp* framestamp
203 = globals->get_renderer()->getViewer()->getFrameStamp();
204 tile_cache.set_current_time(framestamp->getReferenceTime());
210 /* schedule all tiles, use distance-based loading priority,
211 * so tiles are loaded in innermost-to-outermost sequence. */
212 for ( x = -xrange; x <= xrange; ++x )
214 for ( y = -yrange; y <= yrange; ++y )
216 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
217 float priority = (-1.0) * (x*x+y*y);
218 sched_tile( b, priority, true, 0.0 );
224 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
226 SGPath fullPath = modelPath;
227 if ((fullPath.isRelative())&&
228 (fgGetBool("/sim/paths/use-custom-scenery-data") == true)) {
229 string_list sc = globals->get_fg_scenery();
231 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
232 // fg_senery contains empty strings as "markers" (see FGGlobals::set_fg_scenery)
235 tmpPath.append(modelPath);
236 if (tmpPath.exists()) {
243 osg::Node* result = 0;
247 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
248 _disableNasalHooks->getBoolValue() ? NULL : new FGNasalModelDataProxy);
252 SGModelLib::loadDeferredModel(fullPath.str(), globals->get_props(),
253 _disableNasalHooks->getBoolValue() ? NULL : new FGNasalModelDataProxy);
255 } catch (const sg_io_exception& exc) {
256 string m(exc.getMessage());
258 m += exc.getLocation().asString();
259 SG_LOG( SG_TERRAIN, SG_ALERT, m );
260 } catch (const sg_exception& exc) { // XXX may be redundant
261 SG_LOG( SG_TERRAIN, SG_ALERT, exc.getMessage());
267 * Update the various queues maintained by the tilemagr (private
268 * internal function, do not call directly.)
270 void FGTileMgr::update_queues()
272 SceneryPager* pager = FGScenery::getPagerSingleton();
273 osg::FrameStamp* framestamp
274 = globals->get_renderer()->getViewer()->getFrameStamp();
275 double current_time = framestamp->getReferenceTime();
276 double vis = _visibilityMeters->getDoubleValue();
281 tile_cache.set_current_time( current_time );
282 tile_cache.reset_traversal();
284 while ( ! tile_cache.at_end() )
286 e = tile_cache.get_current();
287 // cout << "processing a tile" << endl;
290 // Prepare the ssg nodes corresponding to each tile.
291 // Set the ssg transform and update it's range selector
292 // based on current visibilty
293 e->prep_ssg_node(vis);
295 if (( !e->is_loaded() )&&
296 ((!e->is_expired(current_time))||
297 e->is_current_view() ))
299 // schedule tile for loading with osg pager
300 pager->queueRequest(e->tileFileName,
304 e->getDatabaseRequest(),
310 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
316 int drop_count = sz - tile_cache.get_max_cache_size();
317 if (( drop_count > 0 )&&
318 ((loading==0)||(drop_count > 10)))
320 long drop_index = tile_cache.get_drop_tile();
321 while ( drop_index > -1 )
323 // schedule tile for deletion with osg pager
324 TileEntry* old = tile_cache.get_tile(drop_index);
325 tile_cache.clear_entry(drop_index);
327 osg::ref_ptr<osg::Object> subgraph = old->getNode();
328 old->removeFromSceneGraph();
330 // zeros out subgraph ref_ptr, so subgraph is owned by
331 // the pager and will be deleted in the pager thread.
332 pager->queueDeleteRequest(subgraph);
334 if (--drop_count > 0)
335 drop_index = tile_cache.get_drop_tile();
342 // given the current lon/lat (in degrees), fill in the array of local
343 // chunks. If the chunk isn't already in the cache, then read it from
345 void FGTileMgr::update(double)
347 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
348 double vis = _visibilityMeters->getDoubleValue();
349 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
354 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
355 // "schedule_scenery" instead
356 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
358 longitude = location.getLongitudeDeg();
359 latitude = location.getLatitudeDeg();
361 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
362 // << longitude << " " << latatitude );
364 current_bucket.set_bucket( location );
366 // schedule more tiles when visibility increased considerably
367 // TODO Calculate tile size - instead of using fixed value (5000m)
368 if (range_m-scheduled_visibility > 5000.0)
369 previous_bucket.make_bad();
371 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
372 // << current_bucket );
373 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
375 // do tile load scheduling.
376 // Note that we need keep track of both viewer buckets and fdm buckets.
377 if ( state == Running ) {
378 if (last_state != state)
380 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
382 if (current_bucket != previous_bucket) {
383 // We've moved to a new bucket, we need to schedule any
384 // needed tiles for loading.
385 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
386 scheduled_visibility = range_m;
387 schedule_needed(current_bucket, range_m);
389 _terra_sync->schedulePosition(latitude,longitude);
392 previous_bucket = current_bucket;
393 } else if ( state == Start || state == Inited ) {
394 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
395 // do not update bucket yet (position not valid in initial loop)
397 previous_bucket.make_bad();
404 /** Schedules scenery for given position. Load request remains valid for given duration
405 * (duration=0.0 => nothing is loaded).
406 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
407 * Returns true when all tiles for the given position are already loaded, false otherwise.
409 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
411 const float priority = 0.0;
412 double current_longitude = position.getLongitudeDeg();
413 double current_latitude = position.getLatitudeDeg();
414 bool available = true;
416 // sanity check (unfortunately needed!)
417 if (current_longitude < -180 || current_longitude > 180 ||
418 current_latitude < -90 || current_latitude > 90)
421 SGBucket bucket(position);
422 available = sched_tile( bucket, priority, false, duration );
424 if ((!available)&&(duration==0.0))
427 SGVec3d cartPos = SGVec3d::fromGeod(position);
429 // Traverse all tiles required to be there for the given visibility.
430 double tile_width = bucket.get_width_m();
431 double tile_height = bucket.get_height_m();
432 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
433 double max_dist = tile_r + range_m;
434 double max_dist2 = max_dist*max_dist;
436 int xrange = (int)fabs(range_m / tile_width) + 1;
437 int yrange = (int)fabs(range_m / tile_height) + 1;
439 for ( int x = -xrange; x <= xrange; ++x )
441 for ( int y = -yrange; y <= yrange; ++y )
443 // We have already checked for the center tile.
444 if ( x != 0 || y != 0 )
446 SGBucket b = sgBucketOffset( current_longitude,
447 current_latitude, x, y );
448 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
449 // Do not ask if it is just the next tile but way out of range.
450 if (distance2 <= max_dist2)
452 available &= sched_tile( b, priority, false, duration );
453 if ((!available)&&(duration==0.0))
463 // Returns true if tiles around current view position have been loaded
464 bool FGTileMgr::isSceneryLoaded()
466 double range_m = 100.0;
467 if (scheduled_visibility < range_m)
468 range_m = scheduled_visibility;
470 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);