]> git.mxchange.org Git - flightgear.git/blobdiff - src/Scenery/tilemgr.cxx
Clean fg_init.hxx
[flightgear.git] / src / Scenery / tilemgr.cxx
index 3df2de9c27da3ec201057b05129660846e34847e..a7bbb388bf7bf32802caec5364b072d409b56bd3 100644 (file)
 #include <algorithm>
 #include <functional>
 
+#include <osgViewer/Viewer>
+
 #include <simgear/constants.h>
 #include <simgear/debug/logstream.hxx>
-#include <simgear/math/point3d.hxx>
-#include <simgear/math/polar3d.hxx>
-#include <simgear/math/sg_geodesy.hxx>
 #include <simgear/math/vector.hxx>
 #include <simgear/structure/exception.hxx>
 #include <simgear/scene/model/modellib.hxx>
+#include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
 
 #include <Main/globals.hxx>
 #include <Main/fg_props.hxx>
 #include <Main/viewer.hxx>
 #include <Scripting/NasalSys.hxx>
 
-#include "newcache.hxx"
 #include "scenery.hxx"
 #include "SceneryPager.hxx"
 #include "tilemgr.hxx"
 
 using std::for_each;
 using flightgear::SceneryPager;
+using simgear::SGModelLib;
+using simgear::TileEntry;
+using simgear::TileCache;
 
-#define TEST_LAST_HIT_CACHE
-
-// Constructor
 FGTileMgr::FGTileMgr():
     state( Start ),
-    current_tile( NULL ),
     vis( 16000 )
 {
 }
 
 
-// Destructor
 FGTileMgr::~FGTileMgr() {
+    // remove all nodes we might have left behind
+    osg::Group* group = globals->get_scenery()->get_terrain_branch();
+    group->removeChildren(0, group->getNumChildren());
 }
 
 
@@ -71,6 +71,17 @@ FGTileMgr::~FGTileMgr() {
 int FGTileMgr::init() {
     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
 
+    _options = new SGReaderWriterBTGOptions;
+    _options->setMatlib(globals->get_matlib());
+    _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
+    _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
+    osgDB::FilePathList &fp = _options->getDatabasePathList();
+    const string_list &sc = globals->get_fg_scenery();
+    fp.clear();
+    std::copy(sc.begin(), sc.end(), back_inserter(fp));
+
+    TileEntry::setModelLoadHelper(this);
+
     tile_cache.init();
 
     state = Inited;
@@ -83,22 +94,21 @@ int FGTileMgr::init() {
     return 1;
 }
 
-
 // schedule a tile for loading
 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
     // see if tile already exists in the cache
-    FGTileEntry *t = tile_cache.get_tile( b );
+    TileEntry *t = tile_cache.get_tile( b );
 
-    if ( t == NULL ) {
+    if ( !t ) {
         // make space in the cache
         SceneryPager* pager = FGScenery::getPagerSingleton();
         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
             long index = tile_cache.get_oldest_tile();
             if ( index >= 0 ) {
-                FGTileEntry *old = tile_cache.get_tile( index );
+                TileEntry *old = tile_cache.get_tile( index );
                 tile_cache.clear_entry( index );
                 osg::ref_ptr<osg::Object> subgraph = old->getNode();
-                old->disconnect_ssg_nodes();
+                old->removeFromSceneGraph();
                 delete old;
                 // zeros out subgraph ref_ptr, so subgraph is owned by
                 // the pager and will be deleted in the pager thread.
@@ -110,7 +120,7 @@ void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
         }
 
         // create a new entry
-        FGTileEntry *e = new FGTileEntry( b );
+        TileEntry *e = new TileEntry( b );
 
         // insert the tile into the cache
         if ( tile_cache.insert_tile( e ) ) {
@@ -121,7 +131,7 @@ void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
             delete e;
         }
         // Attach to scene graph
-        e->add_ssg_nodes(globals->get_scenery()->get_terrain_branch());
+        e->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
     } else {
         t->set_inner_ring( is_inner_ring );
     }
@@ -158,7 +168,8 @@ void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
     if ( xrange < 1 ) { xrange = 1; }
     if ( yrange < 1 ) { yrange = 1; }
 
-    // note * 2 at end doubles cache size (for fdm and viewer)
+    // make the cache twice as large to avoid losing terrain when switching
+    // between aircraft and tower views
     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
     // cout << "max cache size = " << tile_cache.get_max_cache_size()
@@ -220,37 +231,36 @@ void FGTileMgr::initialize_queue()
 
     double visibility_meters = fgGetDouble("/environment/visibility-m");
     schedule_needed(visibility_meters, current_bucket);
-
-    // do we really want to lose this? CLO
-#if 0
-    // Now force a load of the center tile and inner ring so we
-    // have something to see in our first frame.
-    int i;
-    for ( i = 0; i < 9; ++i ) {
-        if ( load_queue.size() ) {
-            SG_LOG( SG_TERRAIN, SG_DEBUG, 
-                    "Load queue not empty, loading a tile" );
-
-            SGBucket pending = load_queue.front();
-            load_queue.pop_front();
-            load_tile( pending );
-        }
-    }
-#endif
 }
 
 osg::Node*
 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
 {
+    SGPath fullPath;
+    if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
+        string_list sc = globals->get_fg_scenery();
+
+        for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
+            SGPath tmpPath(*it);
+            tmpPath.append(modelPath);
+            if (tmpPath.exists()) {
+                fullPath = tmpPath;
+                break;
+            } 
+        }
+    } else {
+         fullPath.append(modelPath);
+    }
     osg::Node* result = 0;
     try {
-        result =
-            globals->get_model_lib()->load_model(".",
-                                                 modelPath,
-                                                 globals->get_props(),
-                                                 globals->get_sim_time_sec(),
-                                                 cacheModel,
-                                                 new FGNasalModelData );
+        if(cacheModel)
+            result =
+                SGModelLib::loadModel(fullPath.str(), globals->get_props(),
+                                      new FGNasalModelData);
+        else
+            result=
+                SGModelLib::loadPagedModel(modelPath, globals->get_props(),
+                                           new FGNasalModelData);
     } catch (const sg_io_exception& exc) {
         string m(exc.getMessage());
         m += " ";
@@ -263,28 +273,34 @@ FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
 }
 
 // Helper class for STL fun
-class TileLoad : public std::unary_function<FGNewCache::tile_map::value_type,
+class TileLoad : public std::unary_function<TileCache::tile_map::value_type,
                                             void>
 {
 public:
     TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
-             osg::Group* terrainBranch) :
-        _pager(pager), _framestamp(framestamp) {}
+             osg::Group* terrainBranch, osgDB::ReaderWriter::Options* options) :
+        _pager(pager), _framestamp(framestamp), _options(options) {}
+
     TileLoad(const TileLoad& rhs) :
-        _pager(rhs._pager), _framestamp(rhs._framestamp) {}
-    void operator()(FGNewCache::tile_map::value_type& tilePair)
+        _pager(rhs._pager), _framestamp(rhs._framestamp),
+        _options(rhs._options) {}
+
+    void operator()(TileCache::tile_map::value_type& tilePair)
     {
-        FGTileEntry* entry = tilePair.second;
+        TileEntry* entry = tilePair.second;
         if (entry->getNode()->getNumChildren() == 0) {
             _pager->queueRequest(entry->tileFileName,
                                  entry->getNode(),
                                  entry->get_inner_ring() ? 10.0f : 1.0f,
-                                 _framestamp);
+                                 _framestamp,
+                                 entry->getDatabaseRequest(),
+                                 _options);
         }
     }
 private:
     SceneryPager* _pager;
     osg::FrameStamp* _framestamp;
+    osgDB::ReaderWriter::Options* _options;
 };
 
 /**
@@ -294,10 +310,13 @@ private:
 void FGTileMgr::update_queues()
 {
     SceneryPager* pager = FGScenery::getPagerSingleton();
+    osg::FrameStamp* framestamp
+        = globals->get_renderer()->getViewer()->getFrameStamp();
+    tile_cache.set_current_time(framestamp->getReferenceTime());
     for_each(tile_cache.begin(), tile_cache.end(),
              TileLoad(pager,
-                      globals->get_renderer()->getViewer()->getFrameStamp(),
-                      globals->get_scenery()->get_terrain_branch()));
+                      framestamp,
+                      globals->get_scenery()->get_terrain_branch(), _options.get()));
 }
 
 
@@ -306,30 +325,21 @@ void FGTileMgr::update_queues()
 // disk.
 int FGTileMgr::update( double visibility_meters )
 {
-    SGLocation *location = globals->get_current_view()->getSGLocation();
-    return update( location, visibility_meters );
+    SGVec3d viewPos = globals->get_current_view()->get_view_pos();
+    return update(SGGeod::fromCart(viewPos), visibility_meters);
 }
 
-
-int FGTileMgr::update( SGLocation *location, double visibility_meters )
+int FGTileMgr::update( const SGGeod& location, double visibility_meters)
 {
     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
 
-    longitude = location->getLongitude_deg();
-    latitude = location->getLatitude_deg();
-    // add 1.0m to the max altitude to give a little leeway to the
-    // ground reaction code.
-    altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
+    longitude = location.getLongitudeDeg();
+    latitude = location.getLatitudeDeg();
 
-    // if current altitude is apparently not initialized, set max
-    // altitude to something big.
-    if ( altitude_m < -1000 ) {
-        altitude_m = 10000;
-    }
     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
     //         << longitude << " " << latatitude );
 
-    current_bucket.set_bucket( longitude, latitude );
+    current_bucket.set_bucket( location );
     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
     //         << current_bucket );
     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
@@ -338,7 +348,7 @@ int FGTileMgr::update( SGLocation *location, double visibility_meters )
     // Note that we need keep track of both viewer buckets and fdm buckets.
     if ( state == Running ) {
         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
-        if (!(current_bucket == previous_bucket )) {
+        if (current_bucket != previous_bucket) {
             // We've moved to a new bucket, we need to schedule any
             // needed tiles for loading.
             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
@@ -348,6 +358,11 @@ int FGTileMgr::update( SGLocation *location, double visibility_meters )
         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
 //        initialize_queue();
         state = Running;
+        if (current_bucket != previous_bucket
+            && current_bucket.get_chunk_lon() != -1000) {
+               SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
+               schedule_needed(visibility_meters, current_bucket);
+        }
     }
 
     update_queues();
@@ -363,7 +378,7 @@ void FGTileMgr::prep_ssg_nodes(float vis) {
     // traverse the potentially viewable tile list and update range
     // selector and transform
 
-    FGTileEntry *e;
+    TileEntry *e;
     tile_cache.reset_traversal();
 
     while ( ! tile_cache.at_end() ) {
@@ -377,21 +392,27 @@ void FGTileMgr::prep_ssg_nodes(float vis) {
     }
 }
 
-bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
+bool FGTileMgr::scenery_available(const SGGeod& position, double range_m)
 {
   // sanity check (unfortunately needed!)
-  if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
+  if (position.getLongitudeDeg() < -180 || position.getLongitudeDeg() > 180 ||
+      position.getLatitudeDeg() < -90 || position.getLatitudeDeg() > 90)
     return false;
   
-  SGBucket bucket(lon, lat);
-  FGTileEntry *te = tile_cache.get_tile(bucket);
+  SGBucket bucket(position);
+  TileEntry *te = tile_cache.get_tile(bucket);
   if (!te || !te->is_loaded())
     return false;
 
+  SGVec3d cartPos = SGVec3d::fromGeod(position);
+
   // Traverse all tiles required to be there for the given visibility.
   // This uses exactly the same algorithm like the tile scheduler.
   double tile_width = bucket.get_width_m();
   double tile_height = bucket.get_height_m();
+  double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
+  double max_dist = tile_r + range_m;
+  double max_dist2 = max_dist*max_dist;
   
   int xrange = (int)fabs(range_m / tile_width) + 1;
   int yrange = (int)fabs(range_m / tile_height) + 1;
@@ -400,8 +421,12 @@ bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
     for ( int y = -yrange; y <= yrange; ++y ) {
       // We have already checked for the center tile.
       if ( x != 0 || y != 0 ) {
-        SGBucket b = sgBucketOffset( lon, lat, x, y );
-        FGTileEntry *te = tile_cache.get_tile(b);
+        SGBucket b = sgBucketOffset( position.getLongitudeDeg(),
+                                     position.getLatitudeDeg(), x, y );
+        // Do not ask if it is just the next tile but way out of range.
+        if (max_dist2 < distSqr(cartPos, SGVec3d::fromGeod(b.get_center())))
+          continue;
+        TileEntry *te = tile_cache.get_tile(b);
         if (!te || !te->is_loaded())
           return false;
       }
@@ -415,9 +440,9 @@ bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
 namespace
 {
 struct IsTileLoaded :
-        public std::unary_function<FGNewCache::tile_map::value_type, bool>
+        public std::unary_function<TileCache::tile_map::value_type, bool>
 {
-    bool operator()(const FGNewCache::tile_map::value_type& tilePair) const
+    bool operator()(const TileCache::tile_map::value_type& tilePair) const
     {
         return tilePair.second->is_loaded();
     }