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