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