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