]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Improve error messages for system.fgfsrc removal
[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     if (state != Start)
172     {
173       // protect against multiple scenery reloads and properly reset flags,
174       // otherwise aircraft fall through the ground while reloading scenery
175       if (_scenery_loaded->getBoolValue() == false) {
176         SG_LOG( SG_TERRAIN, SG_INFO, "/sim/sceneryloaded already false, avoiding duplicate re-init of tile manager" );
177         return;
178       }
179     }
180   
181     _scenery_loaded->setBoolValue(false);
182     fgSetDouble("/sim/startup/splash-alpha", 1.0);
183     
184     materialLibChanged();
185
186     // remove all old scenery nodes from scenegraph and clear cache
187     osg::Group* group = globals->get_scenery()->get_terrain_branch();
188     group->removeChildren(0, group->getNumChildren());
189     tile_cache.init();
190     
191     // clear OSG cache, except on initial start-up
192     if (state != Start)
193     {
194         osgDB::Registry::instance()->clearObjectCache();
195     }
196     
197     state = Inited;
198     
199     previous_bucket.make_bad();
200     current_bucket.make_bad();
201     scheduled_visibility = 100.0;
202
203     // force an update now
204     update(0.0);
205 }
206
207 void FGTileMgr::materialLibChanged()
208 {
209     _options->setMaterialLib(globals->get_matlib());
210 }
211
212 /* schedule a tile for loading, keep request for given amount of time.
213  * Returns true if tile is already loaded. */
214 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
215 {
216     // see if tile already exists in the cache
217     TileEntry *t = tile_cache.get_tile( b );
218     if (!t)
219     {
220         // create a new entry
221         t = new TileEntry( b );
222         SG_LOG( SG_TERRAIN, SG_INFO, "sched_tile: new tile entry for:" << b );
223
224
225         // insert the tile into the cache, update will generate load request
226         if ( tile_cache.insert_tile( t ) )
227         {
228             // Attach to scene graph
229
230             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
231         } else
232         {
233             // insert failed (cache full with no available entries to
234             // delete.)  Try again later
235             delete t;
236             return false;
237         }
238
239         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
240     }
241
242     // update tile's properties
243     tile_cache.request_tile(t,priority,current_view,duration);
244
245     return t->is_loaded();
246 }
247
248 /* schedule needed buckets for the current view position for loading,
249  * keep request for given amount of time */
250 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
251 {
252     // sanity check (unfortunately needed!)
253     if (!curr_bucket.isValid() )
254     {
255         SG_LOG( SG_TERRAIN, SG_ALERT,
256                 "Attempting to schedule tiles for invalid bucket" );
257         return;
258     }
259
260     double tile_width = curr_bucket.get_width_m();
261     double tile_height = curr_bucket.get_height_m();
262     SG_LOG( SG_TERRAIN, SG_INFO,
263             "scheduling needed tiles for " << curr_bucket
264            << ", tile-width-m:" << tile_width << ", tile-height-m:" << tile_height);
265
266     
267     // cout << "tile width = " << tile_width << "  tile_height = "
268     //      << tile_height << endl;
269
270     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
271     int xrange = (int)(tileRangeM / tile_width) + 1;
272     int yrange = (int)(tileRangeM / tile_height) + 1;
273     if ( xrange < 1 ) { xrange = 1; }
274     if ( yrange < 1 ) { yrange = 1; }
275
276     // make the cache twice as large to avoid losing terrain when switching
277     // between aircraft and tower views
278     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
279     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
280     // cout << "max cache size = " << tile_cache.get_max_cache_size()
281     //      << " current cache size = " << tile_cache.get_size() << endl;
282
283     // clear flags of all tiles belonging to the previous view set 
284     tile_cache.clear_current_view();
285
286     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
287     osg::FrameStamp* framestamp
288             = globals->get_renderer()->getViewer()->getFrameStamp();
289     tile_cache.set_current_time(framestamp->getReferenceTime());
290
291     SGBucket b;
292
293     int x, y;
294
295     /* schedule all tiles, use distance-based loading priority,
296      * so tiles are loaded in innermost-to-outermost sequence. */
297     for ( x = -xrange; x <= xrange; ++x )
298     {
299         for ( y = -yrange; y <= yrange; ++y )
300         {
301             SGBucket b = curr_bucket.sibling(x, y);
302             if (!b.isValid()) {
303                 continue;
304             }
305             
306             float priority = (-1.0) * (x*x+y*y);
307             sched_tile( b, priority, true, 0.0 );
308             
309             if (_terra_sync) {
310                 _terra_sync->scheduleTile(b);
311             }
312         }
313     }
314 }
315
316 /**
317  * Update the various queues maintained by the tilemgr (private
318  * internal function, do not call directly.)
319  */
320 void FGTileMgr::update_queues(bool& isDownloadingScenery)
321 {
322     osg::FrameStamp* framestamp
323         = globals->get_renderer()->getViewer()->getFrameStamp();
324     double current_time = framestamp->getReferenceTime();
325     double vis = _visibilityMeters->getDoubleValue();
326     TileEntry *e;
327     int loading=0;
328     int sz=0;
329     
330     tile_cache.set_current_time( current_time );
331     tile_cache.reset_traversal();
332
333     while ( ! tile_cache.at_end() )
334     {
335         e = tile_cache.get_current();
336         if ( e )
337         {
338             // Prepare the ssg nodes corresponding to each tile.
339             // Set the ssg transform and update it's range selector
340             // based on current visibilty
341             e->prep_ssg_node(vis);
342             
343             if (!e->is_loaded()) {
344                 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
345                 bool downloading = isTileDirSyncing(e->tileFileName);
346                 isDownloadingScenery |= downloading;
347                 if ( !downloading && nonExpiredOrCurrent) {
348                     // schedule tile for loading with osg pager
349                     _pager->queueRequest(e->tileFileName,
350                                          e->getNode(),
351                                          e->get_priority(),
352                                          framestamp,
353                                          e->getDatabaseRequest(),
354                                          _options.get());
355                     loading++;
356                 }
357             } // of tile not loaded case
358         } else {
359             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
360         }
361         tile_cache.next();
362         sz++;
363     }
364
365     int drop_count = sz - tile_cache.get_max_cache_size();
366     bool dropTiles = false;
367     if (_enableCache) {
368       dropTiles = ( drop_count > 0 ) && ((loading==0)||(drop_count > 10));
369     } else {
370       dropTiles = true;
371       drop_count = sz; // no limit on tiles to drop
372     }
373   
374     if (dropTiles)
375     {
376         long drop_index = _enableCache ? tile_cache.get_drop_tile() :
377                                          tile_cache.get_first_expired_tile();
378         while ( drop_index > -1 )
379         {
380             // schedule tile for deletion with osg pager
381             TileEntry* old = tile_cache.get_tile(drop_index);
382             SG_LOG(SG_TERRAIN, SG_DEBUG, "Dropping:" << old->get_tile_bucket());
383
384             tile_cache.clear_entry(drop_index);
385             
386             osg::ref_ptr<osg::Object> subgraph = old->getNode();
387             old->removeFromSceneGraph();
388             delete old;
389             // zeros out subgraph ref_ptr, so subgraph is owned by
390             // the pager and will be deleted in the pager thread.
391             _pager->queueDeleteRequest(subgraph);
392           
393             if (!_enableCache)
394                 drop_index = tile_cache.get_first_expired_tile();
395             // limit tiles dropped to drop_count
396             else if (--drop_count > 0)
397                 drop_index = tile_cache.get_drop_tile();
398             else
399                drop_index = -1;
400         }
401     } // of dropping tiles loop
402 }
403
404 // given the current lon/lat (in degrees), fill in the array of local
405 // chunks.  If the chunk isn't already in the cache, then read it from
406 // disk.
407 void FGTileMgr::update(double)
408 {
409     double vis = _visibilityMeters->getDoubleValue();
410     schedule_tiles_at(globals->get_view_position(), vis);
411
412     bool waitingOnTerrasync = false;
413     update_queues(waitingOnTerrasync);
414
415     // scenery loading check, triggers after each sim (tile manager) reinit
416     if (!_scenery_loaded->getBoolValue())
417     {
418         bool fdmInited = fgGetBool("sim/fdm-initialized");
419         bool positionFinalized = fgGetBool("sim/position-finalized");
420         bool sceneryOverride = _scenery_override->getBoolValue();
421         
422         
423     // we are done if final position is set and the scenery & FDM are done.
424     // scenery-override can ignore the last two, but not position finalization.
425         if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
426         {
427             _scenery_loaded->setBoolValue(true);
428             fgSplashProgress("");
429         }
430         else
431         {
432             if (!positionFinalized) {
433                 fgSplashProgress("finalize-position");
434             } else if (waitingOnTerrasync) {
435                 fgSplashProgress("downloading-scenery");
436             } else {
437                 fgSplashProgress("loading-scenery");
438             }
439             
440             // be nice to loader threads while waiting for initial scenery, reduce to 20fps
441             SGTimeStamp::sleepForMSec(50);
442         }
443     }
444 }
445
446 // schedule tiles for the viewer bucket
447 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
448 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
449 {
450     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
451     //         << longitude << " " << latitude );
452
453     current_bucket = SGBucket( location );
454
455     // schedule more tiles when visibility increased considerably
456     // TODO Calculate tile size - instead of using fixed value (5000m)
457     if (range_m - scheduled_visibility > 5000.0)
458         previous_bucket.make_bad();
459
460     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
461     //         << current_bucket );
462     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
463
464     // do tile load scheduling.
465     // Note that we need keep track of both viewer buckets and fdm buckets.
466     if ( state == Running ) {
467         if (last_state != state)
468         {
469             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
470         }
471         if (current_bucket != previous_bucket) {
472             // We've moved to a new bucket, we need to schedule any
473             // needed tiles for loading.
474             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr: at " << location << ", scheduling needed for:" << current_bucket
475                    << ", visbility=" << range_m);
476             scheduled_visibility = range_m;
477             schedule_needed(current_bucket, range_m);
478         }
479         
480         // save bucket
481         previous_bucket = current_bucket;
482     } else if ( state == Start || state == Inited ) {
483         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
484         // do not update bucket yet (position not valid in initial loop)
485         state = Running;
486         previous_bucket.make_bad();
487     }
488     last_state = state;
489 }
490
491 /** Schedules scenery for given position. Load request remains valid for given duration
492  * (duration=0.0 => nothing is loaded).
493  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
494  * Returns true when all tiles for the given position are already loaded, false otherwise.
495  */
496 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
497 {
498     // sanity check (unfortunately needed!)
499     if (!position.isValid())
500         return false;
501     const float priority = 0.0;
502     bool available = true;
503
504     SGBucket bucket(position);
505     available = sched_tile( bucket, priority, false, duration );
506   
507     if ((!available)&&(duration==0.0)) {
508         SG_LOG( SG_TERRAIN, SG_DEBUG, "schedule_scenery: Scheduling tile at bucket:" << bucket << " return false" );
509         return false;
510     }
511
512     SGVec3d cartPos = SGVec3d::fromGeod(position);
513
514     // Traverse all tiles required to be there for the given visibility.
515     double tile_width = bucket.get_width_m();
516     double tile_height = bucket.get_height_m();
517     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
518     double max_dist = tile_r + range_m;
519     double max_dist2 = max_dist*max_dist;
520     
521     int xrange = (int)fabs(range_m / tile_width) + 1;
522     int yrange = (int)fabs(range_m / tile_height) + 1;
523
524     for ( int x = -xrange; x <= xrange; ++x )
525     {
526         for ( int y = -yrange; y <= yrange; ++y )
527         {
528             // We have already checked for the center tile.
529             if ( x != 0 || y != 0 )
530             {
531                 SGBucket b = bucket.sibling(x, y );
532                 if (!b.isValid()) {
533                     continue;
534                 }
535                 
536                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
537                 // Do not ask if it is just the next tile but way out of range.
538                 if (distance2 <= max_dist2)
539                 {
540                     available &= sched_tile( b, priority, false, duration );
541                     if ((!available)&&(duration==0.0))
542                         return false;
543                 }
544             }
545         }
546     }
547
548     return available;
549 }
550
551 // Returns true if tiles around current view position have been loaded
552 bool FGTileMgr::isSceneryLoaded()
553 {
554     double range_m = 100.0;
555     if (scheduled_visibility < range_m)
556         range_m = scheduled_visibility;
557
558     return schedule_scenery(globals->get_view_position(), range_m, 0.0);
559 }
560
561 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
562 {
563     if (!_terra_sync) {
564         return false;
565     }
566     
567     std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
568     long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
569     SGBucket bucket(bucketIndex);
570     
571     return _terra_sync->isTileDirPending(bucket.gen_base_path());
572 }
573