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