]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Move all tile-manager init to reinit path.
[flightgear.git] / src / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <algorithm>
29 #include <functional>
30
31 #include <osgViewer/Viewer>
32 #include <osgDB/Registry>
33
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>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Viewer/renderer.hxx>
46 #include <Viewer/splash.hxx>
47 #include <Scripting/NasalSys.hxx>
48 #include <Scripting/NasalModelData.hxx>
49
50 #include "scenery.hxx"
51 #include "SceneryPager.hxx"
52 #include "tilemgr.hxx"
53
54 using flightgear::SceneryPager;
55
56 class FGTileMgr::TileManagerListener : public SGPropertyChangeListener
57 {
58 public:
59     TileManagerListener(FGTileMgr* manager) :
60         _manager(manager),
61         _useVBOsProp(fgGetNode("/sim/rendering/use-vbos", true)),
62         _enableCacheProp(fgGetNode("/sim/tile-cache/enable", true)),
63         _pagedLODMaximumProp(fgGetNode("/sim/rendering/max-paged-lod", true))
64     {
65         _useVBOsProp->addChangeListener(this, true);
66       
67         _enableCacheProp->addChangeListener(this, true);
68         if (_enableCacheProp->getType() == simgear::props::NONE) {
69             _enableCacheProp->setBoolValue(true);
70         }
71       
72         if (_pagedLODMaximumProp->getType() == simgear::props::NONE) {
73             // not set, use OSG default / environment value variable
74             osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
75             int current = viewer->getDatabasePager()->getTargetMaximumNumberOfPageLOD();
76             _pagedLODMaximumProp->setIntValue(current);
77         }
78         _pagedLODMaximumProp->addChangeListener(this, true);
79     }
80     
81     ~TileManagerListener()
82     {
83         _useVBOsProp->removeChangeListener(this);
84         _enableCacheProp->removeChangeListener(this);
85         _pagedLODMaximumProp->removeChangeListener(this);
86     }
87     
88     virtual void valueChanged(SGPropertyNode* prop)
89     {
90         if (prop == _useVBOsProp) {
91             bool useVBOs = prop->getBoolValue();
92             _manager->_options->setPluginStringData("SimGear::USE_VBOS",
93                                                 useVBOs ? "ON" : "OFF");
94         } else if (prop == _enableCacheProp) {
95             _manager->_enableCache = prop->getBoolValue();
96         } else if (prop == _pagedLODMaximumProp) {
97           int v = prop->getIntValue();
98           osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
99           viewer->getDatabasePager()->setTargetMaximumNumberOfPageLOD(v);
100         }
101     }
102     
103 private:
104     FGTileMgr* _manager;
105     SGPropertyNode_ptr _useVBOsProp,
106       _enableCacheProp,
107       _pagedLODMaximumProp;
108 };
109
110 FGTileMgr::FGTileMgr():
111     state( Start ),
112     last_state( Running ),
113     scheduled_visibility(100.0),
114     _terra_sync(NULL),
115     _listener(NULL),
116     _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
117     _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
118     _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
119     _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
120     _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
121     _pager(FGScenery::getPagerSingleton()),
122     _enableCache(true)
123 {
124 }
125
126
127 FGTileMgr::~FGTileMgr()
128 {
129     delete _listener;
130     
131     // remove all nodes we might have left behind
132     osg::Group* group = globals->get_scenery()->get_terrain_branch();
133     group->removeChildren(0, group->getNumChildren());
134     // clear OSG cache
135     osgDB::Registry::instance()->clearObjectCache();
136 }
137
138
139 // Initialize the Tile Manager subsystem
140 void FGTileMgr::init()
141 {
142     reinit();
143 }
144
145 void FGTileMgr::reinit()
146 {
147     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
148     _terra_sync = static_cast<simgear::SGTerraSync*> (globals->get_subsystem("terrasync"));
149
150   // drops the previous options reference
151     _options = new simgear::SGReaderWriterOptions;
152     _listener = new TileManagerListener(this);
153     
154     materialLibChanged();
155     _options->setPropertyNode(globals->get_props());
156     
157     osgDB::FilePathList &fp = _options->getDatabasePathList();
158     const string_list &sc = globals->get_fg_scenery();
159     fp.clear();
160     std::copy(sc.begin(), sc.end(), back_inserter(fp));
161     _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
162     
163     if (_terra_sync) {
164       _options->setPluginStringData("SimGear::TERRASYNC_ROOT", fgGetString("/sim/terrasync/scenery-dir"));
165     }
166     
167     if (!_disableNasalHooks->getBoolValue())
168       _options->setModelData(new FGNasalModelDataProxy);
169   
170   
171     // protect against multiple scenery reloads and properly reset flags,
172     // otherwise aircraft fall through the ground while reloading scenery
173     if (!fgGetBool("/sim/sceneryloaded",true))
174         return;
175     fgSetBool("/sim/sceneryloaded",false);
176     fgSetDouble("/sim/startup/splash-alpha", 1.0);
177     
178     materialLibChanged();
179
180     // remove all old scenery nodes from scenegraph and clear cache
181     osg::Group* group = globals->get_scenery()->get_terrain_branch();
182     group->removeChildren(0, group->getNumChildren());
183     tile_cache.init();
184     
185     // clear OSG cache, except on initial start-up
186     if (state != Start)
187     {
188         osgDB::Registry::instance()->clearObjectCache();
189     }
190     
191     state = Inited;
192     
193     previous_bucket.make_bad();
194     current_bucket.make_bad();
195     scheduled_visibility = 100.0;
196
197     // force an update now
198     update(0.0);
199 }
200
201 void FGTileMgr::materialLibChanged()
202 {
203     _options->setMaterialLib(globals->get_matlib());
204 }
205
206 /* schedule a tile for loading, keep request for given amount of time.
207  * Returns true if tile is already loaded. */
208 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
209 {
210     // see if tile already exists in the cache
211     TileEntry *t = tile_cache.get_tile( b );
212     if (!t)
213     {
214         // create a new entry
215         t = new TileEntry( b );
216         // insert the tile into the cache, update will generate load request
217         if ( tile_cache.insert_tile( t ) )
218         {
219             // Attach to scene graph
220
221             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
222         } else
223         {
224             // insert failed (cache full with no available entries to
225             // delete.)  Try again later
226             delete t;
227             return false;
228         }
229
230         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
231     }
232
233     // update tile's properties
234     tile_cache.request_tile(t,priority,current_view,duration);
235
236     return t->is_loaded();
237 }
238
239 /* schedule needed buckets for the current view position for loading,
240  * keep request for given amount of time */
241 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
242 {
243     // sanity check (unfortunately needed!)
244     if (!curr_bucket.isValid() )
245     {
246         SG_LOG( SG_TERRAIN, SG_ALERT,
247                 "Attempting to schedule tiles for invalid bucket" );
248         return;
249     }
250
251     double tile_width = curr_bucket.get_width_m();
252     double tile_height = curr_bucket.get_height_m();
253     SG_LOG( SG_TERRAIN, SG_INFO,
254             "scheduling needed tiles for " << curr_bucket
255            << ", tile-width-m:" << tile_width << ", tile-height-m:" << tile_height);
256
257     
258     // cout << "tile width = " << tile_width << "  tile_height = "
259     //      << tile_height << endl;
260
261     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
262     int xrange = (int)(tileRangeM / tile_width) + 1;
263     int yrange = (int)(tileRangeM / tile_height) + 1;
264     if ( xrange < 1 ) { xrange = 1; }
265     if ( yrange < 1 ) { yrange = 1; }
266
267     // make the cache twice as large to avoid losing terrain when switching
268     // between aircraft and tower views
269     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
270     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
271     // cout << "max cache size = " << tile_cache.get_max_cache_size()
272     //      << " current cache size = " << tile_cache.get_size() << endl;
273
274     // clear flags of all tiles belonging to the previous view set 
275     tile_cache.clear_current_view();
276
277     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
278     osg::FrameStamp* framestamp
279             = globals->get_renderer()->getViewer()->getFrameStamp();
280     tile_cache.set_current_time(framestamp->getReferenceTime());
281
282     SGBucket b;
283
284     int x, y;
285
286     /* schedule all tiles, use distance-based loading priority,
287      * so tiles are loaded in innermost-to-outermost sequence. */
288     for ( x = -xrange; x <= xrange; ++x )
289     {
290         for ( y = -yrange; y <= yrange; ++y )
291         {
292             SGBucket b = curr_bucket.sibling(x, y);
293             if (!b.isValid()) {
294                 continue;
295             }
296             
297             float priority = (-1.0) * (x*x+y*y);
298             sched_tile( b, priority, true, 0.0 );
299             
300             if (_terra_sync) {
301                 _terra_sync->scheduleTile(b);
302             }
303         }
304     }
305 }
306
307 /**
308  * Update the various queues maintained by the tilemgr (private
309  * internal function, do not call directly.)
310  */
311 void FGTileMgr::update_queues(bool& isDownloadingScenery)
312 {
313     osg::FrameStamp* framestamp
314         = globals->get_renderer()->getViewer()->getFrameStamp();
315     double current_time = framestamp->getReferenceTime();
316     double vis = _visibilityMeters->getDoubleValue();
317     TileEntry *e;
318     int loading=0;
319     int sz=0;
320     
321     tile_cache.set_current_time( current_time );
322     tile_cache.reset_traversal();
323
324     while ( ! tile_cache.at_end() )
325     {
326         e = tile_cache.get_current();
327         if ( e )
328         {
329             // Prepare the ssg nodes corresponding to each tile.
330             // Set the ssg transform and update it's range selector
331             // based on current visibilty
332             e->prep_ssg_node(vis);
333             
334             if (!e->is_loaded()) {
335                 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
336                 bool downloading = isTileDirSyncing(e->tileFileName);
337                 isDownloadingScenery |= downloading;
338                 if ( !downloading && nonExpiredOrCurrent) {
339                     // schedule tile for loading with osg pager
340                     _pager->queueRequest(e->tileFileName,
341                                          e->getNode(),
342                                          e->get_priority(),
343                                          framestamp,
344                                          e->getDatabaseRequest(),
345                                          _options.get());
346                     loading++;
347                 }
348             } // of tile not loaded case
349         } else {
350             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
351         }
352         tile_cache.next();
353         sz++;
354     }
355
356     int drop_count = sz - tile_cache.get_max_cache_size();
357     bool dropTiles = false;
358     if (_enableCache) {
359       dropTiles = ( drop_count > 0 ) && ((loading==0)||(drop_count > 10));
360     } else {
361       dropTiles = true;
362       drop_count = sz; // no limit on tiles to drop
363     }
364   
365     if (dropTiles)
366     {
367         long drop_index = _enableCache ? tile_cache.get_drop_tile() :
368                                          tile_cache.get_first_expired_tile();
369         while ( drop_index > -1 )
370         {
371             // schedule tile for deletion with osg pager
372             TileEntry* old = tile_cache.get_tile(drop_index);
373             SG_LOG(SG_TERRAIN, SG_DEBUG, "Dropping:" << old->get_tile_bucket());
374
375             tile_cache.clear_entry(drop_index);
376             
377             osg::ref_ptr<osg::Object> subgraph = old->getNode();
378             old->removeFromSceneGraph();
379             delete old;
380             // zeros out subgraph ref_ptr, so subgraph is owned by
381             // the pager and will be deleted in the pager thread.
382             _pager->queueDeleteRequest(subgraph);
383           
384             if (!_enableCache)
385                 drop_index = tile_cache.get_first_expired_tile();
386             // limit tiles dropped to drop_count
387             else if (--drop_count > 0)
388                 drop_index = tile_cache.get_drop_tile();
389             else
390                drop_index = -1;
391         }
392     } // of dropping tiles loop
393 }
394
395 // given the current lon/lat (in degrees), fill in the array of local
396 // chunks.  If the chunk isn't already in the cache, then read it from
397 // disk.
398 void FGTileMgr::update(double)
399 {
400     double vis = _visibilityMeters->getDoubleValue();
401     schedule_tiles_at(globals->get_view_position(), vis);
402
403     bool waitingOnTerrasync = false;
404     update_queues(waitingOnTerrasync);
405
406     // scenery loading check, triggers after each sim (tile manager) reinit
407     if (!_scenery_loaded->getBoolValue())
408     {
409         bool fdmInited = fgGetBool("sim/fdm-initialized");
410         bool positionFinalized = fgGetBool("sim/position-finalized");
411         bool sceneryOverride = _scenery_override->getBoolValue();
412         
413         
414     // we are done if final position is set and the scenery & FDM are done.
415     // scenery-override can ignore the last two, but not position finalization.
416         if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
417         {
418             _scenery_loaded->setBoolValue(true);
419             fgSplashProgress("");
420         }
421         else
422         {
423             if (!positionFinalized) {
424                 fgSplashProgress("finalize-position");
425             } else if (waitingOnTerrasync) {
426                 fgSplashProgress("downloading-scenery");
427             } else {
428                 fgSplashProgress("loading-scenery");
429             }
430             
431             // be nice to loader threads while waiting for initial scenery, reduce to 20fps
432             SGTimeStamp::sleepForMSec(50);
433         }
434     }
435 }
436
437 // schedule tiles for the viewer bucket
438 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
439 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
440 {
441     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
442     //         << longitude << " " << latitude );
443
444     current_bucket = SGBucket( location );
445
446     // schedule more tiles when visibility increased considerably
447     // TODO Calculate tile size - instead of using fixed value (5000m)
448     if (range_m - scheduled_visibility > 5000.0)
449         previous_bucket.make_bad();
450
451     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
452     //         << current_bucket );
453     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
454
455     // do tile load scheduling.
456     // Note that we need keep track of both viewer buckets and fdm buckets.
457     if ( state == Running ) {
458         if (last_state != state)
459         {
460             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
461         }
462         if (current_bucket != previous_bucket) {
463             // We've moved to a new bucket, we need to schedule any
464             // needed tiles for loading.
465             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr: at " << location << ", scheduling needed for:" << current_bucket
466                    << ", visbility=" << range_m);
467             scheduled_visibility = range_m;
468             schedule_needed(current_bucket, range_m);
469         }
470         
471         // save bucket
472         previous_bucket = current_bucket;
473     } else if ( state == Start || state == Inited ) {
474         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
475         // do not update bucket yet (position not valid in initial loop)
476         state = Running;
477         previous_bucket.make_bad();
478     }
479     last_state = state;
480 }
481
482 /** Schedules scenery for given position. Load request remains valid for given duration
483  * (duration=0.0 => nothing is loaded).
484  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
485  * Returns true when all tiles for the given position are already loaded, false otherwise.
486  */
487 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
488 {
489     // sanity check (unfortunately needed!)
490     if (!position.isValid())
491         return false;
492     const float priority = 0.0;
493     bool available = true;
494
495     SGBucket bucket(position);
496     available = sched_tile( bucket, priority, false, duration );
497   
498     if ((!available)&&(duration==0.0))
499         return false;
500
501     SGVec3d cartPos = SGVec3d::fromGeod(position);
502
503     // Traverse all tiles required to be there for the given visibility.
504     double tile_width = bucket.get_width_m();
505     double tile_height = bucket.get_height_m();
506     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
507     double max_dist = tile_r + range_m;
508     double max_dist2 = max_dist*max_dist;
509     
510     int xrange = (int)fabs(range_m / tile_width) + 1;
511     int yrange = (int)fabs(range_m / tile_height) + 1;
512
513     for ( int x = -xrange; x <= xrange; ++x )
514     {
515         for ( int y = -yrange; y <= yrange; ++y )
516         {
517             // We have already checked for the center tile.
518             if ( x != 0 || y != 0 )
519             {
520                 SGBucket b = bucket.sibling(x, y );
521                 if (!b.isValid()) {
522                     continue;
523                 }
524                 
525                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
526                 // Do not ask if it is just the next tile but way out of range.
527                 if (distance2 <= max_dist2)
528                 {
529                     available &= sched_tile( b, priority, false, duration );
530                     if ((!available)&&(duration==0.0))
531                         return false;
532                 }
533             }
534         }
535     }
536
537     return available;
538 }
539
540 // Returns true if tiles around current view position have been loaded
541 bool FGTileMgr::isSceneryLoaded()
542 {
543     double range_m = 100.0;
544     if (scheduled_visibility < range_m)
545         range_m = scheduled_visibility;
546
547     return schedule_scenery(globals->get_view_position(), range_m, 0.0);
548 }
549
550 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
551 {
552     if (!_terra_sync) {
553         return false;
554     }
555     
556     std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
557     long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
558     SGBucket bucket(bucketIndex);
559     
560     return _terra_sync->isTileDirPending(bucket.gen_base_path());
561 }
562