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