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