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