1 // tileentry.cxx -- routines to handle a scenery tile
3 // Written by Curtis Olson, started May 1998.
5 // Copyright (C) 1998 - 2001 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
22 # include <simgear_config.h>
25 #include <simgear/compiler.h>
33 #include <osg/Geometry>
36 #include <osg/MatrixTransform>
38 #include <osg/NodeCallback>
41 #include <osgDB/FileNameUtils>
42 #include <osgDB/ReaderWriter>
43 #include <osgDB/ReadFile>
44 #include <osgDB/Registry>
46 #include <simgear/bucket/newbucket.hxx>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/SGMath.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/scene/material/mat.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/ModelRegistry.hxx>
55 #include <simgear/scene/tgdb/apt_signs.hxx>
56 #include <simgear/scene/tgdb/obj.hxx>
57 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
58 #include <simgear/scene/model/placementtrans.hxx>
60 #include "ReaderWriterSTG.hxx"
61 #include "TileEntry.hxx"
64 using namespace simgear;
66 ModelLoadHelper *TileEntry::_modelLoader=0;
69 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
70 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
75 // Update the timestamp on a tile whenever it is in view.
77 class TileCullCallback : public osg::NodeCallback
80 TileCullCallback() : _timeStamp(0) {}
81 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
82 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
86 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
87 double getTimeStamp() const { return _timeStamp; }
88 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
94 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
96 if (nv->getFrameStamp())
97 _timeStamp = nv->getFrameStamp()->getReferenceTime();
101 double TileEntry::get_timestamp() const
104 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
110 void TileEntry::set_timestamp(double time_ms)
114 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
116 cb->setTimeStamp(time_ms);
121 TileEntry::TileEntry ( const SGBucket& b )
123 _node( new osg::LOD ),
124 is_inner_ring(false),
125 tileFileName(b.gen_index_str())
127 _node->setCullCallback(new TileCullCallback);
128 tileFileName += ".stg";
129 _node->setName(tileFileName);
130 // Give a default LOD range so that traversals that traverse
131 // active children (like the groundcache lookup) will work before
132 // tile manager has had a chance to update this node.
133 _node->setRange(0, 0.0, 10000.0);
138 TileEntry::~TileEntry ()
142 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
143 double lon, double elev, double hdg)
145 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
146 obj_pos = geod.makeZUpFrame();
147 // hdg is not a compass heading, but a counter-clockwise rotation
149 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
154 // Clean up the memory used by this tile and delete the arrays used by
155 // ssg as well as the whole ssg branch
156 bool TileEntry::free_tile() {
157 SG_LOG( SG_TERRAIN, SG_DEBUG,
158 "FREEING TILE = (" << tile_bucket << ")" );
160 _node->removeChildren(0, _node->getNumChildren());
167 // Update the ssg transform node for this tile so it can be
168 // properly drawn relative to our (0,0,0) point
169 void TileEntry::prep_ssg_node(float vis) {
172 // visibility can change from frame to frame so we update the
173 // range selector cutoff's each time.
174 float bounding_radius = _node->getChild(0)->getBound().radius();
175 _node->setRange( 0, 0, vis + bounding_radius );
178 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
179 const osgDB::ReaderWriter::Options* options)
181 osg::Node* node = osgDB::readNodeFile(path, options);
183 geometry->addChild(node);
198 // storage class for deferred object processing in TileEntry::load()
200 Object(object_type t, const string& token, const SGPath& p,
206 in >> lon >> lat >> elev >> hdg;
210 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
212 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
213 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
218 double lon, lat, elev, hdg;
221 // Work in progress... load the tile based entirely by name cuz that's
222 // what we'll want to do with the database pager.
225 TileEntry::loadTileByFileName(const string& fileName,
226 const osgDB::ReaderWriter::Options* options)
228 std::string index_str = osgDB::getNameLessExtension(fileName);
229 index_str = osgDB::getSimpleFileName(index_str);
233 std::istringstream idxStream(index_str);
234 idxStream >> tileIndex;
236 SGBucket tile_bucket(tileIndex);
237 const string basePath = tile_bucket.gen_base_path();
239 bool found_tile_base = false;
242 vector<const Object*> objects;
244 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
246 osgDB::FilePathList path_list=options->getDatabasePathList();
247 // Make sure we find the original filename here...
248 std::string filePath = osgDB::getFilePath(fileName);
249 if (!filePath.empty())
250 path_list.push_front(filePath);
252 // scan and parse all files and store information
253 for (unsigned int i = 0; i < path_list.size(); i++) {
254 // If we found a terrain tile in Terrain/, we have to process the
255 // Objects/ dir in the same group, too, before we can stop scanning.
256 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
259 if (path_list[i].empty()) {
266 bool has_base = false;
268 SGPath tile_path = path_list[i];
269 tile_path.append(basePath);
271 SGPath basename = tile_path;
272 basename.append( index_str );
274 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
277 // Check for master .stg (scene terra gear) file
278 SGPath stg_name = basename;
279 stg_name.concat( ".stg" );
281 sg_gzifstream in( stg_name.str() );
285 while ( ! in.eof() ) {
289 if ( token.empty() || token[0] == '#' ) {
293 // Load only once (first found)
294 if ( token == "OBJECT_BASE" ) {
296 in >> name >> ::skipws;
297 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
299 if (!found_tile_base) {
300 found_tile_base = true;
303 object_base = tile_path;
304 object_base.append(name);
307 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
309 // Load only if base is not in another file
310 } else if ( token == "OBJECT" ) {
311 if (!found_tile_base || has_base)
312 objects.push_back(new Object(OBJECT, token, tile_path, in));
315 in >> name >> ::skipeol;
316 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
317 << name << " (skipped)");
321 } else if ( token == "OBJECT_STATIC" ) {
322 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
324 } else if ( token == "OBJECT_SHARED" ) {
325 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
327 } else if ( token == "OBJECT_SIGN" ) {
328 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
330 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
331 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
334 SG_LOG( SG_TERRAIN, SG_DEBUG,
335 "Unknown token '" << token << "' in " << stg_name.str() );
341 const SGReaderWriterBTGOptions* btgOpt;
342 btgOpt = dynamic_cast<const SGReaderWriterBTGOptions *>(options);
343 osg::ref_ptr<SGReaderWriterBTGOptions> opt;
345 opt = new SGReaderWriterBTGOptions(*btgOpt);
347 opt = new SGReaderWriterBTGOptions;
349 // obj_load() will generate ground lighting for us ...
350 osg::Group* new_tile = new osg::Group;
352 if (found_tile_base) {
353 // load tile if found ...
354 opt->setCalcLights(true);
355 obj_load( object_base.str(), new_tile, true, opt);
358 // ... or generate an ocean tile on the fly
359 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
360 if ( !SGGenTile( path_list[0], tile_bucket,
361 opt->getMatlib(), new_tile ) ) {
362 SG_LOG( SG_TERRAIN, SG_ALERT,
363 "Warning: failed to generate ocean tile!" );
368 // now that we have a valid center, process all the objects
369 for (unsigned int j = 0; j < objects.size(); j++) {
370 const Object *obj = objects[j];
372 if (obj->type == OBJECT) {
373 SGPath custom_path = obj->path;
374 custom_path.append( obj->name );
375 opt->setCalcLights(true);
376 obj_load( custom_path.str(), new_tile, false, opt);
378 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
379 // object loading is deferred to main render thread,
380 // but lets figure out the paths right now.
382 if ( obj->type == OBJECT_STATIC ) {
383 custom_path = obj->path;
385 // custom_path = globals->get_fg_root();
387 custom_path.append( obj->name );
390 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
392 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
393 obj_trans->setMatrix( obj_pos );
395 // wire as much of the scene graph together as we can
396 new_tile->addChild( obj_trans );
398 osg::Node* model = 0;
400 model = _modelLoader->loadTileModel(custom_path.str(),
401 obj->type == OBJECT_SHARED);
403 obj_trans->addChild(model);
404 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
405 // load the object itself
406 SGPath custom_path = obj->path;
407 custom_path.append( obj->name );
410 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
412 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
413 obj_trans->setMatrix( obj_pos );
415 osg::Node *custom_obj = 0;
416 if (obj->type == OBJECT_SIGN)
417 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
419 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
421 // wire the pieces together
422 if ( custom_obj != NULL ) {
423 obj_trans -> addChild( custom_obj );
425 new_tile->addChild( obj_trans );
434 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
436 terrain_branch->addChild( _node.get() );
438 SG_LOG( SG_TERRAIN, SG_DEBUG,
439 "connected a tile into scene graph. _node = "
441 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
442 << _node->getNumParents() );
447 TileEntry::removeFromSceneGraph()
449 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
452 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
454 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
457 // find the nodes branch parent
458 if ( _node->getNumParents() > 0 ) {
459 // find the first parent (should only be one)
460 osg::Group *parent = _node->getParent( 0 ) ;
462 parent->removeChild( _node.get() );