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