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