]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Avoid SGLocation usage.
[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/math/polar3d.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/math/vector.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/scene/model/modellib.hxx>
40 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
41
42 #include <Main/globals.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Main/renderer.hxx>
45 #include <Main/viewer.hxx>
46 #include <Scripting/NasalSys.hxx>
47
48 #include "scenery.hxx"
49 #include "SceneryPager.hxx"
50 #include "tilemgr.hxx"
51
52 using std::for_each;
53 using flightgear::SceneryPager;
54 using simgear::SGModelLib;
55 using simgear::TileEntry;
56 using simgear::TileCache;
57
58 FGTileMgr::FGTileMgr():
59     state( Start ),
60     vis( 16000 )
61 {
62 }
63
64
65 FGTileMgr::~FGTileMgr() {
66     // remove all nodes we might have left behind
67     osg::Group* group = globals->get_scenery()->get_terrain_branch();
68     group->removeChildren(0, group->getNumChildren());
69 }
70
71
72 // Initialize the Tile Manager subsystem
73 int FGTileMgr::init() {
74     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
75
76     _options = new SGReaderWriterBTGOptions;
77     _options->setMatlib(globals->get_matlib());
78     _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
79     _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
80     osgDB::FilePathList &fp = _options->getDatabasePathList();
81     const string_list &sc = globals->get_fg_scenery();
82     fp.clear();
83     std::copy(sc.begin(), sc.end(), back_inserter(fp));
84
85     TileEntry::setModelLoadHelper(this);
86
87     tile_cache.init();
88
89     state = Inited;
90
91     previous_bucket.make_bad();
92     current_bucket.make_bad();
93
94     longitude = latitude = -1000.0;
95
96     return 1;
97 }
98
99 // schedule a tile for loading
100 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
101     // see if tile already exists in the cache
102     TileEntry *t = tile_cache.get_tile( b );
103
104     if ( !t ) {
105         // make space in the cache
106         SceneryPager* pager = FGScenery::getPagerSingleton();
107         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
108             long index = tile_cache.get_oldest_tile();
109             if ( index >= 0 ) {
110                 TileEntry *old = tile_cache.get_tile( index );
111                 tile_cache.clear_entry( index );
112                 osg::ref_ptr<osg::Object> subgraph = old->getNode();
113                 old->removeFromSceneGraph();
114                 delete old;
115                 // zeros out subgraph ref_ptr, so subgraph is owned by
116                 // the pager and will be deleted in the pager thread.
117                 pager->queueDeleteRequest(subgraph);
118             } else {
119                 // nothing to free ?!? forge ahead
120                 break;
121             }
122         }
123
124         // create a new entry
125         TileEntry *e = new TileEntry( b );
126
127         // insert the tile into the cache
128         if ( tile_cache.insert_tile( e ) ) {
129             // update_queues will generate load request
130         } else {
131             // insert failed (cache full with no available entries to
132             // delete.)  Try again later
133             delete e;
134         }
135         // Attach to scene graph
136         e->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
137     } else {
138         t->set_inner_ring( is_inner_ring );
139     }
140 }
141
142
143 // schedule a needed buckets for loading
144 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
145     // sanity check (unfortunately needed!)
146     if ( longitude < -180.0 || longitude > 180.0 
147          || latitude < -90.0 || latitude > 90.0 )
148     {
149         SG_LOG( SG_TERRAIN, SG_ALERT,
150                 "Attempting to schedule tiles for bogus lon and lat  = ("
151                 << longitude << "," << latitude << ")" );
152         return;         // FIXME
153         SG_LOG( SG_TERRAIN, SG_ALERT,
154                 "This is a FATAL error.  Exiting!" );
155         exit(-1);
156     }
157
158     SG_LOG( SG_TERRAIN, SG_INFO,
159             "scheduling needed tiles for " << longitude << " " << latitude );
160
161     // vis = fgGetDouble("/environment/visibility-m");
162
163     double tile_width = curr_bucket.get_width_m();
164     double tile_height = curr_bucket.get_height_m();
165     // cout << "tile width = " << tile_width << "  tile_height = "
166     //      << tile_height << endl;
167
168     xrange = (int)(vis / tile_width) + 1;
169     yrange = (int)(vis / tile_height) + 1;
170     if ( xrange < 1 ) { xrange = 1; }
171     if ( yrange < 1 ) { yrange = 1; }
172
173     // make the cache twice as large to avoid losing terrain when switching
174     // between aircraft and tower views
175     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
176     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
177     // cout << "max cache size = " << tile_cache.get_max_cache_size()
178     //      << " current cache size = " << tile_cache.get_size() << endl;
179
180     // clear the inner ring flags so we can set them below.  This
181     // prevents us from having "true" entries we aren't able to find
182     // to get rid of if we teleport a long ways away from the current
183     // location.
184     tile_cache.clear_inner_ring_flags();
185
186     SGBucket b;
187
188     // schedule center tile first so it can be loaded first
189     b = sgBucketOffset( longitude, latitude, 0, 0 );
190     sched_tile( b, true );
191
192     int x, y;
193
194     // schedule next ring of 8 tiles
195     for ( x = -1; x <= 1; ++x ) {
196         for ( y = -1; y <= 1; ++y ) {
197             if ( x != 0 || y != 0 ) {
198                 b = sgBucketOffset( longitude, latitude, x, y );
199                 sched_tile( b, true );
200             }
201         }
202     }
203
204     // schedule remaining tiles
205     for ( x = -xrange; x <= xrange; ++x ) {
206         for ( y = -yrange; y <= yrange; ++y ) {
207             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
208                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
209                 sched_tile( b, false );
210             }
211         }
212     }
213 }
214
215
216 void FGTileMgr::initialize_queue()
217 {
218     // First time through or we have teleported, initialize the
219     // system and load all relavant tiles
220
221     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
222             << current_bucket );
223     // cout << "tile cache size = " << tile_cache.get_size() << endl;
224
225     // wipe/initialize tile cache
226     // tile_cache.init();
227     previous_bucket.make_bad();
228
229     // build the local area list and schedule tiles for loading
230
231     // start with the center tile and work out in concentric
232     // "rings"
233
234     double visibility_meters = fgGetDouble("/environment/visibility-m");
235     schedule_needed(visibility_meters, current_bucket);
236 }
237
238 osg::Node*
239 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
240 {
241     osg::Node* result = 0;
242     try {
243         if(cacheModel)
244             result =
245                 SGModelLib::loadModel(modelPath, globals->get_props(),
246                                       new FGNasalModelData);
247
248         else
249             result=
250                 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
251                                            new FGNasalModelData);
252     } catch (const sg_io_exception& exc) {
253         string m(exc.getMessage());
254         m += " ";
255         m += exc.getLocation().asString();
256         SG_LOG( SG_ALL, SG_ALERT, m );
257     } catch (const sg_exception& exc) { // XXX may be redundant
258         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
259     }
260     return result;
261 }
262
263 // Helper class for STL fun
264 class TileLoad : public std::unary_function<TileCache::tile_map::value_type,
265                                             void>
266 {
267 public:
268     TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
269              osg::Group* terrainBranch, osgDB::ReaderWriter::Options* options) :
270         _pager(pager), _framestamp(framestamp), _options(options) {}
271
272     TileLoad(const TileLoad& rhs) :
273         _pager(rhs._pager), _framestamp(rhs._framestamp),
274         _options(rhs._options) {}
275
276     void operator()(TileCache::tile_map::value_type& tilePair)
277     {
278         TileEntry* entry = tilePair.second;
279         if (entry->getNode()->getNumChildren() == 0) {
280             _pager->queueRequest(entry->tileFileName,
281                                  entry->getNode(),
282                                  entry->get_inner_ring() ? 10.0f : 1.0f,
283                                  _framestamp,
284 #ifdef FGOSGPAGER25
285                                  entry->getDatabaseRequest(),
286 #endif
287                                  _options);
288         }
289     }
290 private:
291     SceneryPager* _pager;
292     osg::FrameStamp* _framestamp;
293     osgDB::ReaderWriter::Options* _options;
294 };
295
296 /**
297  * Update the various queues maintained by the tilemagr (private
298  * internal function, do not call directly.)
299  */
300 void FGTileMgr::update_queues()
301 {
302     SceneryPager* pager = FGScenery::getPagerSingleton();
303     osg::FrameStamp* framestamp
304         = globals->get_renderer()->getViewer()->getFrameStamp();
305     tile_cache.set_current_time(framestamp->getReferenceTime());
306     for_each(tile_cache.begin(), tile_cache.end(),
307              TileLoad(pager,
308                       framestamp,
309                       globals->get_scenery()->get_terrain_branch(), _options.get()));
310 }
311
312
313 // given the current lon/lat (in degrees), fill in the array of local
314 // chunks.  If the chunk isn't already in the cache, then read it from
315 // disk.
316 int FGTileMgr::update( double visibility_meters )
317 {
318     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
319     return update(SGGeod::fromCart(viewPos), visibility_meters);
320 }
321
322 int FGTileMgr::update( const SGGeod& location, double visibility_meters)
323 {
324     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
325
326     longitude = location.getLongitudeDeg();
327     latitude = location.getLatitudeDeg();
328
329     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
330     //         << longitude << " " << latatitude );
331
332     current_bucket.set_bucket( location );
333     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
334     //         << current_bucket );
335     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
336
337     // do tile load scheduling. 
338     // Note that we need keep track of both viewer buckets and fdm buckets.
339     if ( state == Running ) {
340         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
341         if (current_bucket != previous_bucket) {
342             // We've moved to a new bucket, we need to schedule any
343             // needed tiles for loading.
344             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
345             schedule_needed(visibility_meters, current_bucket);
346         }
347     } else if ( state == Start || state == Inited ) {
348         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
349 //        initialize_queue();
350         state = Running;
351         if (current_bucket != previous_bucket
352             && current_bucket.get_chunk_lon() != -1000) {
353                SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
354                schedule_needed(visibility_meters, current_bucket);
355         }
356     }
357
358     update_queues();
359
360     // save bucket...
361     previous_bucket = current_bucket;
362
363     return 1;
364 }
365
366 void FGTileMgr::prep_ssg_nodes(float vis) {
367
368     // traverse the potentially viewable tile list and update range
369     // selector and transform
370
371     TileEntry *e;
372     tile_cache.reset_traversal();
373
374     while ( ! tile_cache.at_end() ) {
375         // cout << "processing a tile" << endl;
376         if ( (e = tile_cache.get_current()) ) {
377             e->prep_ssg_node(vis);
378         } else {
379             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
380         }
381         tile_cache.next();
382     }
383 }
384
385 bool FGTileMgr::scenery_available(const SGGeod& position, double range_m)
386 {
387     return scenery_available(position.getLatitudeDeg(),
388                              position.getLongitudeDeg(), range_m);
389 }
390
391 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
392 {
393   // sanity check (unfortunately needed!)
394   if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
395     return false;
396   
397   SGBucket bucket(lon, lat);
398   TileEntry *te = tile_cache.get_tile(bucket);
399   if (!te || !te->is_loaded())
400     return false;
401
402   // Traverse all tiles required to be there for the given visibility.
403   // This uses exactly the same algorithm like the tile scheduler.
404   double tile_width = bucket.get_width_m();
405   double tile_height = bucket.get_height_m();
406   
407   int xrange = (int)fabs(range_m / tile_width) + 1;
408   int yrange = (int)fabs(range_m / tile_height) + 1;
409   
410   for ( int x = -xrange; x <= xrange; ++x ) {
411     for ( int y = -yrange; y <= yrange; ++y ) {
412       // We have already checked for the center tile.
413       if ( x != 0 || y != 0 ) {
414         SGBucket b = sgBucketOffset( lon, lat, x, y );
415         TileEntry *te = tile_cache.get_tile(b);
416         if (!te || !te->is_loaded())
417           return false;
418       }
419     }
420   }
421
422   // Survived all tests.
423   return true;
424 }
425
426 namespace
427 {
428 struct IsTileLoaded :
429         public std::unary_function<TileCache::tile_map::value_type, bool>
430 {
431     bool operator()(const TileCache::tile_map::value_type& tilePair) const
432     {
433         return tilePair.second->is_loaded();
434     }
435 };
436 }
437
438 bool FGTileMgr::isSceneryLoaded()
439 {
440     return (std::find_if(tile_cache.begin(), tile_cache.end(),
441                          std::not1(IsTileLoaded()))
442             == tile_cache.end());
443 }