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