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/viewer.hxx>
45 #include <Scripting/NasalSys.hxx>
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
51 using flightgear::SceneryPager;
54 FGTileMgr::FGTileMgr():
56 last_state( Running ),
59 scheduled_visibility(100.0),
61 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
62 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
63 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
64 _pager(FGScenery::getPagerSingleton())
69 FGTileMgr::~FGTileMgr()
71 // remove all nodes we might have left behind
72 osg::Group* group = globals->get_scenery()->get_terrain_branch();
73 group->removeChildren(0, group->getNumChildren());
75 osgDB::Registry::instance()->clearObjectCache();
79 // Initialize the Tile Manager subsystem
80 void FGTileMgr::init() {
81 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
83 _options = new simgear::SGReaderWriterOptions;
84 _options->setMaterialLib(globals->get_matlib());
85 _options->setPropertyNode(globals->get_props());
87 osgDB::FilePathList &fp = _options->getDatabasePathList();
88 const string_list &sc = globals->get_fg_scenery();
90 std::copy(sc.begin(), sc.end(), back_inserter(fp));
91 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
92 if (!_disableNasalHooks->getBoolValue())
93 _options->setModelData(new FGNasalModelDataProxy);
98 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
100 ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
103 void FGTileMgr::reinit()
105 // protect against multiple scenery reloads and properly reset flags,
106 // otherwise aircraft fall through the ground while reloading scenery
107 if (!fgGetBool("/sim/sceneryloaded",true))
109 fgSetBool("/sim/sceneryloaded",false);
110 fgSetDouble("/sim/startup/splash-alpha", 1.0);
112 // Reload the materials definitions
113 _options->setMaterialLib(globals->get_matlib());
115 // remove all old scenery nodes from scenegraph and clear cache
116 osg::Group* group = globals->get_scenery()->get_terrain_branch();
117 group->removeChildren(0, group->getNumChildren());
120 // clear OSG cache, except on initial start-up
123 osgDB::Registry::instance()->clearObjectCache();
128 previous_bucket.make_bad();
129 current_bucket.make_bad();
130 longitude = latitude = -1000.0;
131 scheduled_visibility = 100.0;
133 _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
135 _terra_sync->setTileRefreshCb(&refresh_tile, this);
137 // force an update now
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 << ")" );
188 SG_LOG( SG_TERRAIN, SG_INFO,
189 "scheduling needed tiles for " << longitude << " " << latitude );
191 double tile_width = curr_bucket.get_width_m();
192 double tile_height = curr_bucket.get_height_m();
193 // cout << "tile width = " << tile_width << " tile_height = "
194 // << tile_height << endl;
196 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
197 int xrange = (int)(tileRangeM / tile_width) + 1;
198 int yrange = (int)(tileRangeM / tile_height) + 1;
199 if ( xrange < 1 ) { xrange = 1; }
200 if ( yrange < 1 ) { yrange = 1; }
202 // make the cache twice as large to avoid losing terrain when switching
203 // between aircraft and tower views
204 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
205 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
206 // cout << "max cache size = " << tile_cache.get_max_cache_size()
207 // << " current cache size = " << tile_cache.get_size() << endl;
209 // clear flags of all tiles belonging to the previous view set
210 tile_cache.clear_current_view();
212 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
213 osg::FrameStamp* framestamp
214 = globals->get_renderer()->getViewer()->getFrameStamp();
215 tile_cache.set_current_time(framestamp->getReferenceTime());
221 /* schedule all tiles, use distance-based loading priority,
222 * so tiles are loaded in innermost-to-outermost sequence. */
223 for ( x = -xrange; x <= xrange; ++x )
225 for ( y = -yrange; y <= yrange; ++y )
227 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
228 float priority = (-1.0) * (x*x+y*y);
229 sched_tile( b, priority, true, 0.0 );
235 * Update the various queues maintained by the tilemagr (private
236 * internal function, do not call directly.)
238 void FGTileMgr::update_queues()
240 osg::FrameStamp* framestamp
241 = globals->get_renderer()->getViewer()->getFrameStamp();
242 double current_time = framestamp->getReferenceTime();
243 double vis = _visibilityMeters->getDoubleValue();
248 tile_cache.set_current_time( current_time );
249 tile_cache.reset_traversal();
251 while ( ! tile_cache.at_end() )
253 e = tile_cache.get_current();
254 // cout << "processing a tile" << endl;
257 // Prepare the ssg nodes corresponding to each tile.
258 // Set the ssg transform and update it's range selector
259 // based on current visibilty
260 e->prep_ssg_node(vis);
262 if (( !e->is_loaded() )&&
263 ((!e->is_expired(current_time))||
264 e->is_current_view() ))
266 // schedule tile for loading with osg pager
267 _pager->queueRequest(e->tileFileName,
271 e->getDatabaseRequest(),
277 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
283 int drop_count = sz - tile_cache.get_max_cache_size();
284 if (( drop_count > 0 )&&
285 ((loading==0)||(drop_count > 10)))
287 long drop_index = tile_cache.get_drop_tile();
288 while ( drop_index > -1 )
290 // schedule tile for deletion with osg pager
291 TileEntry* old = tile_cache.get_tile(drop_index);
292 tile_cache.clear_entry(drop_index);
294 osg::ref_ptr<osg::Object> subgraph = old->getNode();
295 old->removeFromSceneGraph();
297 // zeros out subgraph ref_ptr, so subgraph is owned by
298 // the pager and will be deleted in the pager thread.
299 _pager->queueDeleteRequest(subgraph);
301 if (--drop_count > 0)
302 drop_index = tile_cache.get_drop_tile();
309 // given the current lon/lat (in degrees), fill in the array of local
310 // chunks. If the chunk isn't already in the cache, then read it from
312 void FGTileMgr::update(double)
314 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
315 double vis = _visibilityMeters->getDoubleValue();
316 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
321 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
322 // "schedule_scenery" instead
323 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
325 longitude = location.getLongitudeDeg();
326 latitude = location.getLatitudeDeg();
328 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
329 // << longitude << " " << latatitude );
331 current_bucket.set_bucket( location );
333 // schedule more tiles when visibility increased considerably
334 // TODO Calculate tile size - instead of using fixed value (5000m)
335 if (range_m - scheduled_visibility > 5000.0)
336 previous_bucket.make_bad();
338 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
339 // << current_bucket );
340 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
342 // do tile load scheduling.
343 // Note that we need keep track of both viewer buckets and fdm buckets.
344 if ( state == Running ) {
345 if (last_state != state)
347 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
349 if (current_bucket != previous_bucket) {
350 // We've moved to a new bucket, we need to schedule any
351 // needed tiles for loading.
352 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
353 scheduled_visibility = range_m;
354 schedule_needed(current_bucket, range_m);
356 _terra_sync->schedulePosition(latitude,longitude);
359 previous_bucket = current_bucket;
360 } else if ( state == Start || state == Inited ) {
361 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
362 // do not update bucket yet (position not valid in initial loop)
364 previous_bucket.make_bad();
371 /** Schedules scenery for given position. Load request remains valid for given duration
372 * (duration=0.0 => nothing is loaded).
373 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
374 * Returns true when all tiles for the given position are already loaded, false otherwise.
376 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
378 const float priority = 0.0;
379 double current_longitude = position.getLongitudeDeg();
380 double current_latitude = position.getLatitudeDeg();
381 bool available = true;
383 // sanity check (unfortunately needed!)
384 if (current_longitude < -180 || current_longitude > 180 ||
385 current_latitude < -90 || current_latitude > 90)
388 SGBucket bucket(position);
389 available = sched_tile( bucket, priority, false, duration );
391 if ((!available)&&(duration==0.0))
394 SGVec3d cartPos = SGVec3d::fromGeod(position);
396 // Traverse all tiles required to be there for the given visibility.
397 double tile_width = bucket.get_width_m();
398 double tile_height = bucket.get_height_m();
399 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
400 double max_dist = tile_r + range_m;
401 double max_dist2 = max_dist*max_dist;
403 int xrange = (int)fabs(range_m / tile_width) + 1;
404 int yrange = (int)fabs(range_m / tile_height) + 1;
406 for ( int x = -xrange; x <= xrange; ++x )
408 for ( int y = -yrange; y <= yrange; ++y )
410 // We have already checked for the center tile.
411 if ( x != 0 || y != 0 )
413 SGBucket b = sgBucketOffset( current_longitude,
414 current_latitude, x, y );
415 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
416 // Do not ask if it is just the next tile but way out of range.
417 if (distance2 <= max_dist2)
419 available &= sched_tile( b, priority, false, duration );
420 if ((!available)&&(duration==0.0))
430 // Returns true if tiles around current view position have been loaded
431 bool FGTileMgr::isSceneryLoaded()
433 double range_m = 100.0;
434 if (scheduled_visibility < range_m)
435 range_m = scheduled_visibility;
437 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);