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