]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Improve timing statistics
[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
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/scene/model/modellib.hxx>
37 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
38
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/renderer.hxx>
42 #include <Main/viewer.hxx>
43 #include <Scripting/NasalSys.hxx>
44
45 #include "scenery.hxx"
46 #include "SceneryPager.hxx"
47 #include "tilemgr.hxx"
48
49 using std::for_each;
50 using flightgear::SceneryPager;
51 using simgear::SGModelLib;
52 using simgear::TileEntry;
53 using simgear::TileCache;
54
55
56 // helper: listen to property changes affecting tile loading
57 class LoaderPropertyWatcher : public SGPropertyChangeListener
58 {
59 public:
60     LoaderPropertyWatcher(FGTileMgr* pTileMgr) :
61         _pTileMgr(pTileMgr)
62     {
63     }
64
65     virtual void valueChanged(SGPropertyNode*)
66     {
67         _pTileMgr->configChanged();
68     }
69
70 private:
71     FGTileMgr* _pTileMgr;
72 };
73
74
75 FGTileMgr::FGTileMgr():
76     state( Start ),
77     vis( 16000 ),
78     _propListener(new LoaderPropertyWatcher(this))
79 {
80     _randomObjects = fgGetNode("/sim/rendering/random-objects", true);
81     _randomVegetation = fgGetNode("/sim/rendering/random-vegetation", true);
82 }
83
84
85 FGTileMgr::~FGTileMgr() {
86     // remove all nodes we might have left behind
87     osg::Group* group = globals->get_scenery()->get_terrain_branch();
88     group->removeChildren(0, group->getNumChildren());
89     delete _propListener;
90     _propListener = NULL;
91 }
92
93
94 // Initialize the Tile Manager subsystem
95 void FGTileMgr::init() {
96     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
97
98     _options = new SGReaderWriterBTGOptions;
99     _options->setMatlib(globals->get_matlib());
100
101     _randomObjects.get()->addChangeListener(_propListener, false);
102     _randomVegetation.get()->addChangeListener(_propListener, false);
103     configChanged();
104
105     osgDB::FilePathList &fp = _options->getDatabasePathList();
106     const string_list &sc = globals->get_fg_scenery();
107     fp.clear();
108     std::copy(sc.begin(), sc.end(), back_inserter(fp));
109
110     TileEntry::setModelLoadHelper(this);
111     
112     _visibilityMeters = fgGetNode("/environment/visibility-m", true);
113
114     reinit();
115 }
116
117
118 void FGTileMgr::reinit()
119 {
120     // remove all old scenery nodes from scenegraph and clear cache
121     osg::Group* group = globals->get_scenery()->get_terrain_branch();
122     group->removeChildren(0, group->getNumChildren());
123     tile_cache.init();
124     
125     state = Inited;
126     
127     previous_bucket.make_bad();
128     current_bucket.make_bad();
129     longitude = latitude = -1000.0;
130     
131     // force an update now
132     update(0.0);
133 }
134
135 void FGTileMgr::configChanged()
136 {
137     _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
138     _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
139 }
140
141 /* schedule a tile for loading, keep request for given amount of time.
142  * Returns true if tile is already loaded. */
143 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
144 {
145     // see if tile already exists in the cache
146     TileEntry *t = tile_cache.get_tile( b );
147     if (!t)
148     {
149         // create a new entry
150         t = new TileEntry( b );
151         // insert the tile into the cache, update will generate load request
152         if ( tile_cache.insert_tile( t ) )
153         {
154             // Attach to scene graph
155             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
156         } else
157         {
158             // insert failed (cache full with no available entries to
159             // delete.)  Try again later
160             delete t;
161             return false;
162         }
163
164         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
165     }
166
167     // update tile's properties
168     tile_cache.request_tile(t,priority,current_view,duration);
169
170     return t->is_loaded();
171 }
172
173 /* schedule needed buckets for the current view position for loading,
174  * keep request for given amount of time */
175 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
176 {
177     // sanity check (unfortunately needed!)
178     if ( longitude < -180.0 || longitude > 180.0 
179          || latitude < -90.0 || latitude > 90.0 )
180     {
181         SG_LOG( SG_TERRAIN, SG_ALERT,
182                 "Attempting to schedule tiles for bogus lon and lat  = ("
183                 << longitude << "," << latitude << ")" );
184         return;         // FIXME
185         SG_LOG( SG_TERRAIN, SG_ALERT,
186                 "This is a FATAL error.  Exiting!" );
187         exit(-1);
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     xrange = (int)(vis / tile_width) + 1;
199     yrange = (int)(vis / tile_height) + 1;
200     if ( xrange < 1 ) { xrange = 1; }
201     if ( yrange < 1 ) { yrange = 1; }
202
203     // make the cache twice as large to avoid losing terrain when switching
204     // between aircraft and tower views
205     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
206     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
207     // cout << "max cache size = " << tile_cache.get_max_cache_size()
208     //      << " current cache size = " << tile_cache.get_size() << endl;
209
210     // clear flags of all tiles belonging to the previous view set 
211     tile_cache.clear_current_view();
212
213     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
214     osg::FrameStamp* framestamp
215             = globals->get_renderer()->getViewer()->getFrameStamp();
216     tile_cache.set_current_time(framestamp->getReferenceTime());
217
218     SGBucket b;
219
220     int x, y;
221
222     /* schedule all tiles, use distance-based loading priority,
223      * so tiles are loaded in innermost-to-outermost sequence. */
224     for ( x = -xrange; x <= xrange; ++x )
225     {
226         for ( y = -yrange; y <= yrange; ++y )
227         {
228             SGBucket b = sgBucketOffset( longitude, latitude, x, y );
229             float priority = (-1.0) * (x*x+y*y);
230             sched_tile( b, priority, true, 0.0 );
231         }
232     }
233 }
234
235 osg::Node*
236 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
237 {
238     SGPath fullPath;
239     if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
240         string_list sc = globals->get_fg_scenery();
241
242         for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
243             SGPath tmpPath(*it);
244             tmpPath.append(modelPath);
245             if (tmpPath.exists()) {
246                 fullPath = tmpPath;
247                 break;
248             } 
249         }
250     } else {
251          fullPath.append(modelPath);
252     }
253     osg::Node* result = 0;
254     try {
255         if(cacheModel)
256             result =
257                 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
258                                       new FGNasalModelData);
259         else
260             result=
261                 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
262                                            new FGNasalModelData);
263     } catch (const sg_io_exception& exc) {
264         string m(exc.getMessage());
265         m += " ";
266         m += exc.getLocation().asString();
267         SG_LOG( SG_ALL, SG_ALERT, m );
268     } catch (const sg_exception& exc) { // XXX may be redundant
269         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
270     }
271     return result;
272 }
273
274 /**
275  * Update the various queues maintained by the tilemagr (private
276  * internal function, do not call directly.)
277  */
278 void FGTileMgr::update_queues()
279 {
280     SceneryPager* pager = FGScenery::getPagerSingleton();
281     osg::FrameStamp* framestamp
282         = globals->get_renderer()->getViewer()->getFrameStamp();
283     double current_time = framestamp->getReferenceTime();
284     double vis = _visibilityMeters->getDoubleValue();
285     TileEntry *e;
286     int loading=0;
287     int sz=0;
288
289     tile_cache.set_current_time( current_time );
290     tile_cache.reset_traversal();
291
292     while ( ! tile_cache.at_end() )
293     {
294         e = tile_cache.get_current();
295         // cout << "processing a tile" << endl;
296         if ( e )
297         {
298             // Prepare the ssg nodes corresponding to each tile.
299             // Set the ssg transform and update it's range selector
300             // based on current visibilty
301             e->prep_ssg_node(vis);
302
303             if (( !e->is_loaded() )&&
304                 ( !e->is_expired(current_time) ))
305             {
306                 // schedule tile for loading with osg pager
307                 pager->queueRequest(e->tileFileName,
308                                     e->getNode(),
309                                     e->get_priority(),
310                                     framestamp,
311                                     e->getDatabaseRequest(),
312                                     _options.get());
313                 loading++;
314             }
315         } else
316         {
317             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
318         }
319         tile_cache.next();
320         sz++;
321     }
322
323     int drop_count = sz - tile_cache.get_max_cache_size();
324     if (( drop_count > 0 )&&
325          ((loading==0)||(drop_count > 10)))
326     {
327         long drop_index = tile_cache.get_drop_tile();
328         while ( drop_index > -1 )
329         {
330             // schedule tile for deletion with osg pager
331             TileEntry* old = tile_cache.get_tile(drop_index);
332             tile_cache.clear_entry(drop_index);
333             
334             osg::ref_ptr<osg::Object> subgraph = old->getNode();
335             old->removeFromSceneGraph();
336             delete old;
337             // zeros out subgraph ref_ptr, so subgraph is owned by
338             // the pager and will be deleted in the pager thread.
339             pager->queueDeleteRequest(subgraph);
340             
341             if (--drop_count > 0)
342                 drop_index = tile_cache.get_drop_tile();
343             else
344                 drop_index = -1;
345         }
346     }
347 }
348
349 // given the current lon/lat (in degrees), fill in the array of local
350 // chunks.  If the chunk isn't already in the cache, then read it from
351 // disk.
352 void FGTileMgr::update(double)
353 {
354     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
355     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
356     double vis = _visibilityMeters->getDoubleValue();
357     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
358
359     update_queues();
360 }
361
362 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
363 // "schedule_scenery" instead
364 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
365 {
366     longitude = location.getLongitudeDeg();
367     latitude = location.getLatitudeDeg();
368
369     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
370     //         << longitude << " " << latatitude );
371
372     current_bucket.set_bucket( location );
373
374     // schedule more tiles when visibility increased considerably
375     // TODO Calculate tile size - instead of using fixed value (5000m)
376     if (range_m-scheduled_visibility > 5000.0)
377         previous_bucket.make_bad();
378
379     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
380     //         << current_bucket );
381     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
382
383     // do tile load scheduling. 
384     // Note that we need keep track of both viewer buckets and fdm buckets.
385     if ( state == Running ) {
386         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
387         if (current_bucket != previous_bucket) {
388             // We've moved to a new bucket, we need to schedule any
389             // needed tiles for loading.
390             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
391             scheduled_visibility = range_m;
392             schedule_needed(current_bucket, range_m);
393         }
394         // save bucket
395         previous_bucket = current_bucket;
396     } else if ( state == Start || state == Inited ) {
397         SG_LOG( SG_TERRAIN, SG_INFO, "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
403     return 1;
404 }
405
406 /** Schedules scenery for given position. Load request remains valid for given duration
407  * (duration=0.0 => nothing is loaded).
408  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
409  * Returns true when all tiles for the given position are already loaded, false otherwise.
410  */
411 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
412 {
413     const float priority = 0.0;
414     double current_longitude = position.getLongitudeDeg();
415     double current_latitude = position.getLatitudeDeg();
416     bool available = true;
417     
418     // sanity check (unfortunately needed!)
419     if (current_longitude < -180 || current_longitude > 180 ||
420         current_latitude < -90 || current_latitude > 90)
421         return false;
422   
423     SGBucket bucket(position);
424     available = sched_tile( bucket, priority, false, duration );
425   
426     if ((!available)&&(duration==0.0))
427         return false;
428
429     SGVec3d cartPos = SGVec3d::fromGeod(position);
430
431     // Traverse all tiles required to be there for the given visibility.
432     double tile_width = bucket.get_width_m();
433     double tile_height = bucket.get_height_m();
434     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
435     double max_dist = tile_r + range_m;
436     double max_dist2 = max_dist*max_dist;
437     
438     int xrange = (int)fabs(range_m / tile_width) + 1;
439     int yrange = (int)fabs(range_m / tile_height) + 1;
440
441     for ( int x = -xrange; x <= xrange; ++x )
442     {
443         for ( int y = -yrange; y <= yrange; ++y )
444         {
445             // We have already checked for the center tile.
446             if ( x != 0 || y != 0 )
447             {
448                 SGBucket b = sgBucketOffset( current_longitude,
449                                              current_latitude, x, y );
450                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
451                 // Do not ask if it is just the next tile but way out of range.
452                 if (distance2 <= max_dist2)
453                 {
454                     available &= sched_tile( b, priority, false, duration );
455                     if ((!available)&&(duration==0.0))
456                         return false;
457                 }
458             }
459         }
460     }
461
462     return available;
463 }
464
465 // Returns true if tiles around current view position have been loaded
466 bool FGTileMgr::isSceneryLoaded()
467 {
468     double range_m = 100.0;
469     if (scheduled_visibility < range_m)
470         range_m = scheduled_visibility;
471
472     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
473 }