]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
#591: night-time rendering issues, avoid negative color values
[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     last_state( Running ),
61     vis( 16000 ),
62     _terra_sync(NULL),
63     _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
64     _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true))
65 {
66 }
67
68
69 FGTileMgr::~FGTileMgr()
70 {
71     // remove all nodes we might have left behind
72     osg::Group* group = globals->get_scenery()->get_terrain_branch();
73     group->removeChildren(0, group->getNumChildren());
74     // clear OSG cache
75     osgDB::Registry::instance()->clearObjectCache();
76 }
77
78
79 // Initialize the Tile Manager subsystem
80 void FGTileMgr::init() {
81     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
82
83     _options = new simgear::SGReaderWriterOptions;
84     _options->setMaterialLib(globals->get_matlib());
85     _options->setPropertyNode(globals->get_props());
86
87     osgDB::FilePathList &fp = _options->getDatabasePathList();
88     const string_list &sc = globals->get_fg_scenery();
89     fp.clear();
90     std::copy(sc.begin(), sc.end(), back_inserter(fp));
91
92     TileEntry::setModelLoadHelper(this);
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         {
250             /* TODO FGNasalModelData's callback "modelLoaded" isn't thread-safe.
251              * But deferred (or paged) OSG loading runs in a separate thread, which would
252              * trigger the FGNasalModelData::modelLoaded callback. We're easily doomed
253              * when this happens and the model actually contains a Nasal "load" hook - which
254              * would run the Nasal parser and Nasal script execution in a separate thread...
255              * => Disabling the callback for now, to test if all Nasal related segfaults are
256              * gone. Proper resolution is TBD. We'll need to somehow decouple the OSG callback,
257              * so we can run the Nasal stuff in the main thread.
258              */
259             result=
260                 SGModelLib::loadDeferredModel(fullPath.str(), globals->get_props()/*,
261                                              new FGNasalModelData*/);
262         }
263     } catch (const sg_io_exception& exc) {
264         string m(exc.getMessage());
265         m += " ";
266         m += exc.getLocation().asString();
267         SG_LOG( SG_TERRAIN, SG_ALERT, m );
268     } catch (const sg_exception& exc) { // XXX may be redundant
269         SG_LOG( SG_TERRAIN, SG_ALERT, exc.getMessage());
270     }
271     return result;
272 }
273
274 /**
275  * Update the various queues maintained by the tilemagr (private
276  * internal function, do not call directly.)
277  */
278 void FGTileMgr::update_queues()
279 {
280     SceneryPager* pager = FGScenery::getPagerSingleton();
281     osg::FrameStamp* framestamp
282         = globals->get_renderer()->getViewer()->getFrameStamp();
283     double current_time = framestamp->getReferenceTime();
284     double vis = _visibilityMeters->getDoubleValue();
285     TileEntry *e;
286     int loading=0;
287     int sz=0;
288
289     tile_cache.set_current_time( current_time );
290     tile_cache.reset_traversal();
291
292     while ( ! tile_cache.at_end() )
293     {
294         e = tile_cache.get_current();
295         // cout << "processing a tile" << endl;
296         if ( e )
297         {
298             // Prepare the ssg nodes corresponding to each tile.
299             // Set the ssg transform and update it's range selector
300             // based on current visibilty
301             e->prep_ssg_node(vis);
302
303             if (( !e->is_loaded() )&&
304                 ((!e->is_expired(current_time))||
305                   e->is_current_view() ))
306             {
307                 // schedule tile for loading with osg pager
308                 pager->queueRequest(e->tileFileName,
309                                     e->getNode(),
310                                     e->get_priority(),
311                                     framestamp,
312                                     e->getDatabaseRequest(),
313                                     _options.get());
314                 loading++;
315             }
316         } else
317         {
318             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
319         }
320         tile_cache.next();
321         sz++;
322     }
323
324     int drop_count = sz - tile_cache.get_max_cache_size();
325     if (( drop_count > 0 )&&
326          ((loading==0)||(drop_count > 10)))
327     {
328         long drop_index = tile_cache.get_drop_tile();
329         while ( drop_index > -1 )
330         {
331             // schedule tile for deletion with osg pager
332             TileEntry* old = tile_cache.get_tile(drop_index);
333             tile_cache.clear_entry(drop_index);
334             
335             osg::ref_ptr<osg::Object> subgraph = old->getNode();
336             old->removeFromSceneGraph();
337             delete old;
338             // zeros out subgraph ref_ptr, so subgraph is owned by
339             // the pager and will be deleted in the pager thread.
340             pager->queueDeleteRequest(subgraph);
341             
342             if (--drop_count > 0)
343                 drop_index = tile_cache.get_drop_tile();
344             else
345                 drop_index = -1;
346         }
347     }
348 }
349
350 // given the current lon/lat (in degrees), fill in the array of local
351 // chunks.  If the chunk isn't already in the cache, then read it from
352 // disk.
353 void FGTileMgr::update(double)
354 {
355     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
356     double vis = _visibilityMeters->getDoubleValue();
357     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
358
359     update_queues();
360 }
361
362 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
363 // "schedule_scenery" instead
364 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
365 {
366     longitude = location.getLongitudeDeg();
367     latitude = location.getLatitudeDeg();
368
369     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
370     //         << longitude << " " << latatitude );
371
372     current_bucket.set_bucket( location );
373
374     // schedule more tiles when visibility increased considerably
375     // TODO Calculate tile size - instead of using fixed value (5000m)
376     if (range_m-scheduled_visibility > 5000.0)
377         previous_bucket.make_bad();
378
379     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
380     //         << current_bucket );
381     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
382
383     // do tile load scheduling.
384     // Note that we need keep track of both viewer buckets and fdm buckets.
385     if ( state == Running ) {
386         if (last_state != state)
387         {
388             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
389         }
390         if (current_bucket != previous_bucket) {
391             // We've moved to a new bucket, we need to schedule any
392             // needed tiles for loading.
393             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
394             scheduled_visibility = range_m;
395             schedule_needed(current_bucket, range_m);
396             if (_terra_sync)
397                 _terra_sync->schedulePosition(latitude,longitude);
398         }
399         // save bucket
400         previous_bucket = current_bucket;
401     } else if ( state == Start || state == Inited ) {
402         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
403         // do not update bucket yet (position not valid in initial loop)
404         state = Running;
405         previous_bucket.make_bad();
406     }
407     last_state = state;
408
409     return 1;
410 }
411
412 /** Schedules scenery for given position. Load request remains valid for given duration
413  * (duration=0.0 => nothing is loaded).
414  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
415  * Returns true when all tiles for the given position are already loaded, false otherwise.
416  */
417 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
418 {
419     const float priority = 0.0;
420     double current_longitude = position.getLongitudeDeg();
421     double current_latitude = position.getLatitudeDeg();
422     bool available = true;
423     
424     // sanity check (unfortunately needed!)
425     if (current_longitude < -180 || current_longitude > 180 ||
426         current_latitude < -90 || current_latitude > 90)
427         return false;
428   
429     SGBucket bucket(position);
430     available = sched_tile( bucket, priority, false, duration );
431   
432     if ((!available)&&(duration==0.0))
433         return false;
434
435     SGVec3d cartPos = SGVec3d::fromGeod(position);
436
437     // Traverse all tiles required to be there for the given visibility.
438     double tile_width = bucket.get_width_m();
439     double tile_height = bucket.get_height_m();
440     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
441     double max_dist = tile_r + range_m;
442     double max_dist2 = max_dist*max_dist;
443     
444     int xrange = (int)fabs(range_m / tile_width) + 1;
445     int yrange = (int)fabs(range_m / tile_height) + 1;
446
447     for ( int x = -xrange; x <= xrange; ++x )
448     {
449         for ( int y = -yrange; y <= yrange; ++y )
450         {
451             // We have already checked for the center tile.
452             if ( x != 0 || y != 0 )
453             {
454                 SGBucket b = sgBucketOffset( current_longitude,
455                                              current_latitude, x, y );
456                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
457                 // Do not ask if it is just the next tile but way out of range.
458                 if (distance2 <= max_dist2)
459                 {
460                     available &= sched_tile( b, priority, false, duration );
461                     if ((!available)&&(duration==0.0))
462                         return false;
463                 }
464             }
465         }
466     }
467
468     return available;
469 }
470
471 // Returns true if tiles around current view position have been loaded
472 bool FGTileMgr::isSceneryLoaded()
473 {
474     double range_m = 100.0;
475     if (scheduled_visibility < range_m)
476         range_m = scheduled_visibility;
477
478     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
479 }