]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
schedule tiles in Inited state if we get a valid bucket
[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 <simgear/constants.h>
32 #include <simgear/debug/logstream.hxx>
33 #include <simgear/math/point3d.hxx>
34 #include <simgear/math/polar3d.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/math/vector.hxx>
37 #include <simgear/structure/exception.hxx>
38 #include <simgear/scene/model/modellib.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 "newcache.hxx"
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
50
51 using std::for_each;
52 using flightgear::SceneryPager;
53
54 #define TEST_LAST_HIT_CACHE
55
56 // Constructor
57 FGTileMgr::FGTileMgr():
58     state( Start ),
59     current_tile( NULL ),
60     vis( 16000 )
61 {
62 }
63
64
65 // Destructor
66 FGTileMgr::~FGTileMgr() {
67 }
68
69
70 // Initialize the Tile Manager subsystem
71 int FGTileMgr::init() {
72     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
73
74     tile_cache.init();
75
76     state = Inited;
77
78     previous_bucket.make_bad();
79     current_bucket.make_bad();
80
81     longitude = latitude = -1000.0;
82
83     return 1;
84 }
85
86
87 // schedule a tile for loading
88 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
89     // see if tile already exists in the cache
90     FGTileEntry *t = tile_cache.get_tile( b );
91
92     if ( t == NULL ) {
93         // make space in the cache
94         SceneryPager* pager = FGScenery::getPagerSingleton();
95         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
96             long index = tile_cache.get_oldest_tile();
97             if ( index >= 0 ) {
98                 FGTileEntry *old = tile_cache.get_tile( index );
99                 tile_cache.clear_entry( index );
100                 osg::ref_ptr<osg::Object> subgraph = old->getNode();
101                 old->disconnect_ssg_nodes();
102                 delete old;
103                 // zeros out subgraph ref_ptr, so subgraph is owned by
104                 // the pager and will be deleted in the pager thread.
105                 pager->queueDeleteRequest(subgraph);
106             } else {
107                 // nothing to free ?!? forge ahead
108                 break;
109             }
110         }
111
112         // create a new entry
113         FGTileEntry *e = new FGTileEntry( b );
114
115         // insert the tile into the cache
116         if ( tile_cache.insert_tile( e ) ) {
117             // update_queues will generate load request
118         } else {
119             // insert failed (cache full with no available entries to
120             // delete.)  Try again later
121             delete e;
122         }
123         // Attach to scene graph
124         e->add_ssg_nodes(globals->get_scenery()->get_terrain_branch());
125     } else {
126         t->set_inner_ring( is_inner_ring );
127     }
128 }
129
130
131 // schedule a needed buckets for loading
132 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
133     // sanity check (unfortunately needed!)
134     if ( longitude < -180.0 || longitude > 180.0 
135          || latitude < -90.0 || latitude > 90.0 )
136     {
137         SG_LOG( SG_TERRAIN, SG_ALERT,
138                 "Attempting to schedule tiles for bogus lon and lat  = ("
139                 << longitude << "," << latitude << ")" );
140         return;         // FIXME
141         SG_LOG( SG_TERRAIN, SG_ALERT,
142                 "This is a FATAL error.  Exiting!" );
143         exit(-1);
144     }
145
146     SG_LOG( SG_TERRAIN, SG_INFO,
147             "scheduling needed tiles for " << longitude << " " << latitude );
148
149     // vis = fgGetDouble("/environment/visibility-m");
150
151     double tile_width = curr_bucket.get_width_m();
152     double tile_height = curr_bucket.get_height_m();
153     // cout << "tile width = " << tile_width << "  tile_height = "
154     //      << tile_height << endl;
155
156     xrange = (int)(vis / tile_width) + 1;
157     yrange = (int)(vis / tile_height) + 1;
158     if ( xrange < 1 ) { xrange = 1; }
159     if ( yrange < 1 ) { yrange = 1; }
160
161     // note * 2 at end doubles cache size (for fdm and viewer)
162     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
163     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
164     // cout << "max cache size = " << tile_cache.get_max_cache_size()
165     //      << " current cache size = " << tile_cache.get_size() << endl;
166
167     // clear the inner ring flags so we can set them below.  This
168     // prevents us from having "true" entries we aren't able to find
169     // to get rid of if we teleport a long ways away from the current
170     // location.
171     tile_cache.clear_inner_ring_flags();
172
173     SGBucket b;
174
175     // schedule center tile first so it can be loaded first
176     b = sgBucketOffset( longitude, latitude, 0, 0 );
177     sched_tile( b, true );
178
179     int x, y;
180
181     // schedule next ring of 8 tiles
182     for ( x = -1; x <= 1; ++x ) {
183         for ( y = -1; y <= 1; ++y ) {
184             if ( x != 0 || y != 0 ) {
185                 b = sgBucketOffset( longitude, latitude, x, y );
186                 sched_tile( b, true );
187             }
188         }
189     }
190
191     // schedule remaining tiles
192     for ( x = -xrange; x <= xrange; ++x ) {
193         for ( y = -yrange; y <= yrange; ++y ) {
194             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
195                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
196                 sched_tile( b, false );
197             }
198         }
199     }
200 }
201
202
203 void FGTileMgr::initialize_queue()
204 {
205     // First time through or we have teleported, initialize the
206     // system and load all relavant tiles
207
208     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
209             << current_bucket );
210     // cout << "tile cache size = " << tile_cache.get_size() << endl;
211
212     // wipe/initialize tile cache
213     // tile_cache.init();
214     previous_bucket.make_bad();
215
216     // build the local area list and schedule tiles for loading
217
218     // start with the center tile and work out in concentric
219     // "rings"
220
221     double visibility_meters = fgGetDouble("/environment/visibility-m");
222     schedule_needed(visibility_meters, current_bucket);
223
224     // do we really want to lose this? CLO
225 #if 0
226     // Now force a load of the center tile and inner ring so we
227     // have something to see in our first frame.
228     int i;
229     for ( i = 0; i < 9; ++i ) {
230         if ( load_queue.size() ) {
231             SG_LOG( SG_TERRAIN, SG_DEBUG, 
232                     "Load queue not empty, loading a tile" );
233
234             SGBucket pending = load_queue.front();
235             load_queue.pop_front();
236             load_tile( pending );
237         }
238     }
239 #endif
240 }
241
242 osg::Node*
243 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
244 {
245     osg::Node* result = 0;
246     try {
247         result =
248             globals->get_model_lib()->load_model(".",
249                                                  modelPath,
250                                                  globals->get_props(),
251                                                  globals->get_sim_time_sec(),
252                                                  cacheModel,
253                                                  new FGNasalModelData );
254     } catch (const sg_io_exception& exc) {
255         string m(exc.getMessage());
256         m += " ";
257         m += exc.getLocation().asString();
258         SG_LOG( SG_ALL, SG_ALERT, m );
259     } catch (const sg_exception& exc) { // XXX may be redundant
260         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
261     }
262     return result;
263 }
264
265 // Helper class for STL fun
266 class TileLoad : public std::unary_function<FGNewCache::tile_map::value_type,
267                                             void>
268 {
269 public:
270     TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
271              osg::Group* terrainBranch) :
272         _pager(pager), _framestamp(framestamp) {}
273     TileLoad(const TileLoad& rhs) :
274         _pager(rhs._pager), _framestamp(rhs._framestamp) {}
275     void operator()(FGNewCache::tile_map::value_type& tilePair)
276     {
277         FGTileEntry* entry = tilePair.second;
278         if (entry->getNode()->getNumChildren() == 0) {
279             _pager->queueRequest(entry->tileFileName,
280                                  entry->getNode(),
281                                  entry->get_inner_ring() ? 10.0f : 1.0f,
282                                  _framestamp);
283         }
284     }
285 private:
286     SceneryPager* _pager;
287     osg::FrameStamp* _framestamp;
288 };
289
290 /**
291  * Update the various queues maintained by the tilemagr (private
292  * internal function, do not call directly.)
293  */
294 void FGTileMgr::update_queues()
295 {
296     SceneryPager* pager = FGScenery::getPagerSingleton();
297     for_each(tile_cache.begin(), tile_cache.end(),
298              TileLoad(pager,
299                       globals->get_renderer()->getViewer()->getFrameStamp(),
300                       globals->get_scenery()->get_terrain_branch()));
301 }
302
303
304 // given the current lon/lat (in degrees), fill in the array of local
305 // chunks.  If the chunk isn't already in the cache, then read it from
306 // disk.
307 int FGTileMgr::update( double visibility_meters )
308 {
309     SGLocation *location = globals->get_current_view()->getSGLocation();
310     return update( location, visibility_meters );
311 }
312
313
314 int FGTileMgr::update( SGLocation *location, double visibility_meters )
315 {
316     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
317
318     longitude = location->getLongitude_deg();
319     latitude = location->getLatitude_deg();
320     // add 1.0m to the max altitude to give a little leeway to the
321     // ground reaction code.
322     altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
323
324     // if current altitude is apparently not initialized, set max
325     // altitude to something big.
326     if ( altitude_m < -1000 ) {
327         altitude_m = 10000;
328     }
329     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
330     //         << longitude << " " << latatitude );
331
332     current_bucket.set_bucket( longitude, latitude );
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     FGTileEntry *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(double lat, double lon, double range_m)
386 {
387   // sanity check (unfortunately needed!)
388   if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
389     return false;
390   
391   SGBucket bucket(lon, lat);
392   FGTileEntry *te = tile_cache.get_tile(bucket);
393   if (!te || !te->is_loaded())
394     return false;
395
396   // Traverse all tiles required to be there for the given visibility.
397   // This uses exactly the same algorithm like the tile scheduler.
398   double tile_width = bucket.get_width_m();
399   double tile_height = bucket.get_height_m();
400   
401   int xrange = (int)fabs(range_m / tile_width) + 1;
402   int yrange = (int)fabs(range_m / tile_height) + 1;
403   
404   for ( int x = -xrange; x <= xrange; ++x ) {
405     for ( int y = -yrange; y <= yrange; ++y ) {
406       // We have already checked for the center tile.
407       if ( x != 0 || y != 0 ) {
408         SGBucket b = sgBucketOffset( lon, lat, x, y );
409         FGTileEntry *te = tile_cache.get_tile(b);
410         if (!te || !te->is_loaded())
411           return false;
412       }
413     }
414   }
415
416   // Survived all tests.
417   return true;
418 }
419
420 namespace
421 {
422 struct IsTileLoaded :
423         public std::unary_function<FGNewCache::tile_map::value_type, bool>
424 {
425     bool operator()(const FGNewCache::tile_map::value_type& tilePair) const
426     {
427         return tilePair.second->is_loaded();
428     }
429 };
430 }
431
432 bool FGTileMgr::isSceneryLoaded()
433 {
434     return (std::find_if(tile_cache.begin(), tile_cache.end(),
435                          std::not1(IsTileLoaded()))
436             == tile_cache.end());
437 }