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.
28 #include <simgear/compiler.h>
30 #include <Main/main.hxx>
37 #include <osg/Geometry>
40 #include <osg/MatrixTransform>
42 #include <osg/NodeCallback>
45 #include <osgDB/FileNameUtils>
46 #include <osgDB/ReaderWriter>
47 #include <osgDB/ReadFile>
48 #include <osgDB/Registry>
50 #include <simgear/bucket/newbucket.hxx>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/math/polar3d.hxx>
53 #include <simgear/math/sg_geodesy.hxx>
54 #include <simgear/math/sg_random.h>
55 #include <simgear/misc/sgstream.hxx>
56 #include <simgear/scene/material/mat.hxx>
57 #include <simgear/scene/material/matlib.hxx>
58 #include <simgear/scene/model/ModelRegistry.hxx>
59 #include <simgear/scene/tgdb/apt_signs.hxx>
60 #include <simgear/scene/tgdb/obj.hxx>
61 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
62 #include <simgear/scene/model/placementtrans.hxx>
63 #include <simgear/scene/util/SGUpdateVisitor.hxx>
65 #include <Aircraft/aircraft.hxx>
66 #include <Include/general.hxx>
67 #include <Main/fg_props.hxx>
68 #include <Main/globals.hxx>
69 #include <Main/viewer.hxx>
70 #include <Scenery/scenery.hxx>
71 #include <Time/light.hxx>
73 #include "tileentry.hxx"
74 #include "tilemgr.hxx"
77 using namespace simgear;
79 // FIXME: investigate what huge update flood is clamped away here ...
80 class FGTileUpdateCallback : public osg::NodeCallback {
82 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
84 assert(dynamic_cast<SGUpdateVisitor*>(nv));
85 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
87 osg::Vec3 center = node->getBound().center();
88 double distance = dist(updateVisitor->getGlobalEyePos(),
89 SGVec3d(center[0], center[1], center[2]));
90 if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
99 class TileCullCallback : public osg::NodeCallback
102 TileCullCallback() : _timeStamp(DBL_MAX) {}
103 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
104 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
108 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
109 double getTimeStamp() const { return _timeStamp; }
110 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
116 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
118 if (nv->getFrameStamp())
119 _timeStamp = nv->getFrameStamp()->getReferenceTime();
123 double FGTileEntry::get_timestamp() const
126 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
132 void FGTileEntry::set_timestamp(double time_ms)
136 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
138 cb->setTimeStamp(time_ms);
143 FGTileEntry::FGTileEntry ( const SGBucket& b )
145 _node( new osg::LOD ),
146 is_inner_ring(false),
148 tileFileName(b.gen_index_str())
150 _node->setUpdateCallback(new FGTileUpdateCallback);
151 _node->setCullCallback(new TileCullCallback);
152 tileFileName += ".stg";
153 _node->setName(tileFileName);
158 FGTileEntry::~FGTileEntry ()
162 static void WorldCoordinate( osg::Matrix& obj_pos, double lat,
163 double lon, double elev, double hdg )
165 double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
166 double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
167 double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
170 Point3D geod( lon_rad, lat_rad, elev );
171 Point3D world_pos = sgGeodToCart( geod );
173 double sin_lat = sin( lat_rad );
174 double cos_lat = cos( lat_rad );
175 double cos_lon = cos( lon_rad );
176 double sin_lon = sin( lon_rad );
177 double sin_hdg = sin( hdg_rad ) ;
178 double cos_hdg = cos( hdg_rad ) ;
180 obj_pos(0, 0) = cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
181 obj_pos(0, 1) = cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
182 obj_pos(0, 2) = -cos_hdg * cos_lat;
183 obj_pos(0, 3) = SG_ZERO;
185 obj_pos(1, 0) = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
186 obj_pos(1, 1) = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
187 obj_pos(1, 2) = sin_hdg * cos_lat;
188 obj_pos(1, 3) = SG_ZERO;
190 obj_pos(2, 0) = cos_lat * cos_lon;
191 obj_pos(2, 1) = cos_lat * sin_lon;
192 obj_pos(2, 2) = sin_lat;
193 obj_pos(2, 3) = SG_ZERO;
195 obj_pos(3, 0) = world_pos.x();
196 obj_pos(3, 1) = world_pos.y();
197 obj_pos(3, 2) = world_pos.z();
198 obj_pos(3, 3) = SG_ONE ;
202 // Free "n" leaf elements of an ssg tree. returns the number of
203 // elements freed. An empty branch node is considered a leaf. This
204 // is intended to spread the load of freeing a complex tile out over
206 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
207 int num_deletes = b->getNumChildren();
209 b->removeChildren(0, b->getNumChildren());
215 // Clean up the memory used by this tile and delete the arrays used by
216 // ssg as well as the whole ssg branch
217 bool FGTileEntry::free_tile() {
218 int delete_size = 100;
219 SG_LOG( SG_TERRAIN, SG_DEBUG,
220 "FREEING TILE = (" << tile_bucket << ")" );
222 SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
224 if ( !(free_tracker & NODES) ) {
225 free_tracker |= NODES;
226 } else if ( !(free_tracker & VEC_PTRS) ) {
227 free_tracker |= VEC_PTRS;
228 } else if ( !(free_tracker & TERRA_NODE) ) {
229 // delete the terrain branch (this should already have been
230 // disconnected from the scene graph)
231 SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
232 if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
234 free_tracker |= TERRA_NODE;
236 } else if ( !(free_tracker & LIGHTMAPS) ) {
237 free_tracker |= LIGHTMAPS;
242 SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
244 // if we fall down to here, we still have work todo, return false
249 // Update the ssg transform node for this tile so it can be
250 // properly drawn relative to our (0,0,0) point
251 void FGTileEntry::prep_ssg_node(float vis) {
254 // visibility can change from frame to frame so we update the
255 // range selector cutoff's each time.
256 float bounding_radius = _node->getChild(0)->getBound().radius();
257 _node->setRange( 0, 0, vis + bounding_radius );
260 bool FGTileEntry::obj_load( const string& path,
261 osg::Group *geometry, bool is_base )
263 bool use_random_objects =
264 fgGetBool("/sim/rendering/random-objects", true);
266 // try loading binary format
267 osg::ref_ptr<SGReaderWriterBTGOptions> options
268 = new SGReaderWriterBTGOptions();
269 options->setMatlib(globals->get_matlib());
270 options->setCalcLights(is_base);
271 options->setUseRandomObjects(use_random_objects);
272 osg::Node* node = osgDB::readNodeFile(path, options.get());
274 geometry->addChild(node);
289 // storage class for deferred object processing in FGTileEntry::load()
291 Object(object_type t, const string& token, const SGPath& p, istream& in)
296 in >> lon >> lat >> elev >> hdg;
300 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
302 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
303 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
308 double lon, lat, elev, hdg;
311 // Work in progress... load the tile based entirely by name cuz that's
312 // what we'll want to do with the database pager.
315 FGTileEntry::loadTileByName(const string& index_str,
316 const string_list &path_list)
320 istringstream idxStream(index_str);
321 idxStream >> tileIndex;
323 SGBucket tile_bucket(tileIndex);
324 const string basePath = tile_bucket.gen_base_path();
326 bool found_tile_base = false;
329 vector<const Object*> objects;
331 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
333 // scan and parse all files and store information
334 for (unsigned int i = 0; i < path_list.size(); i++) {
335 // If we found a terrain tile in Terrain/, we have to process the
336 // Objects/ dir in the same group, too, before we can stop scanning.
337 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
339 if (path_list[i].empty()) {
346 bool has_base = false;
348 SGPath tile_path = path_list[i];
349 tile_path.append(basePath);
351 SGPath basename = tile_path;
352 basename.append( index_str );
354 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
357 // Check for master .stg (scene terra gear) file
358 SGPath stg_name = basename;
359 stg_name.concat( ".stg" );
361 sg_gzifstream in( stg_name.str() );
365 while ( ! in.eof() ) {
369 if ( token.empty() || token[0] == '#' ) {
373 // Load only once (first found)
374 if ( token == "OBJECT_BASE" ) {
376 in >> name >> ::skipws;
377 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
379 if (!found_tile_base) {
380 found_tile_base = true;
383 object_base = tile_path;
384 object_base.append(name);
387 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
389 // Load only if base is not in another file
390 } else if ( token == "OBJECT" ) {
391 if (!found_tile_base || has_base)
392 objects.push_back(new Object(OBJECT, token, tile_path, in));
395 in >> name >> ::skipeol;
396 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
397 << name << " (skipped)");
401 } else if ( token == "OBJECT_STATIC" ) {
402 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
404 } else if ( token == "OBJECT_SHARED" ) {
405 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
407 } else if ( token == "OBJECT_SIGN" ) {
408 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
410 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
411 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
414 SG_LOG( SG_TERRAIN, SG_DEBUG,
415 "Unknown token '" << token << "' in " << stg_name.str() );
422 // obj_load() will generate ground lighting for us ...
423 osg::Group* new_tile = new osg::Group;
425 if (found_tile_base) {
426 // load tile if found ...
427 obj_load( object_base.str(), new_tile, true );
430 // ... or generate an ocean tile on the fly
431 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
432 if ( !SGGenTile( path_list[0], tile_bucket,
433 globals->get_matlib(), new_tile ) ) {
434 SG_LOG( SG_TERRAIN, SG_ALERT,
435 "Warning: failed to generate ocean tile!" );
440 // now that we have a valid center, process all the objects
441 for (unsigned int j = 0; j < objects.size(); j++) {
442 const Object *obj = objects[j];
444 if (obj->type == OBJECT) {
445 SGPath custom_path = obj->path;
446 custom_path.append( obj->name );
447 obj_load( custom_path.str(), new_tile, false );
449 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
450 // object loading is deferred to main render thread,
451 // but lets figure out the paths right now.
453 if ( obj->type == OBJECT_STATIC ) {
454 custom_path = obj->path;
456 custom_path = globals->get_fg_root();
458 custom_path.append( obj->name );
461 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
463 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
464 obj_trans->setMatrix( obj_pos );
466 // wire as much of the scene graph together as we can
467 new_tile->addChild( obj_trans );
470 = FGTileMgr::loadTileModel(custom_path.str(),
471 obj->type == OBJECT_SHARED);
473 obj_trans->addChild(model);
474 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
475 // load the object itself
476 SGPath custom_path = obj->path;
477 custom_path.append( obj->name );
480 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
482 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
483 obj_trans->setMatrix( obj_pos );
485 osg::Node *custom_obj = 0;
486 if (obj->type == OBJECT_SIGN)
487 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
489 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
491 // wire the pieces together
492 if ( custom_obj != NULL ) {
493 obj_trans -> addChild( custom_obj );
495 new_tile->addChild( obj_trans );
504 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch )
506 // bump up the ref count so we can remove this later without
507 // having ssg try to free the memory.
508 terrain_branch->addChild( _node.get() );
510 SG_LOG( SG_TERRAIN, SG_DEBUG,
511 "connected a tile into scene graph. _node = "
513 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
514 << _node->getNumParents() );
519 FGTileEntry::disconnect_ssg_nodes()
521 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
524 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
526 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
529 // find the terrain branch parent
530 int pcount = _node->getNumParents();
532 // find the first parent (should only be one)
533 osg::Group *parent = _node->getParent( 0 ) ;
535 // disconnect the tile (we previously ref()'d it so it
536 // won't get freed now)
537 parent->removeChild( _node.get() );
539 // This should be impossible.
540 SG_LOG( SG_TERRAIN, SG_ALERT,
541 "parent pointer is NULL! Dying" );
550 class ReaderWriterSTG : public osgDB::ReaderWriter {
552 virtual const char* className() const;
554 virtual bool acceptsExtension(const string& extension) const;
556 virtual ReadResult readNode(const string& fileName,
557 const osgDB::ReaderWriter::Options* options)
561 const char* ReaderWriterSTG::className() const
563 return "STG Database reader";
566 bool ReaderWriterSTG::acceptsExtension(const string& extension) const
568 return (osgDB::equalCaseInsensitive(extension, "gz")
569 || osgDB::equalCaseInsensitive(extension, "stg"));
572 osgDB::ReaderWriter::ReadResult
573 ReaderWriterSTG::readNode(const string& fileName,
574 const osgDB::ReaderWriter::Options* options) const
576 string ext = osgDB::getLowerCaseFileExtension(fileName);
577 if(!acceptsExtension(ext))
578 return ReadResult::FILE_NOT_HANDLED;
580 if (osgDB::equalCaseInsensitive(ext, "gz")) {
581 stgFileName = osgDB::getNameLessExtension(fileName);
582 if (!acceptsExtension(
583 osgDB::getLowerCaseFileExtension(stgFileName))) {
584 return ReadResult::FILE_NOT_HANDLED;
587 stgFileName = fileName;
590 = FGTileEntry::loadTileByName(osgDB::getNameLessExtension(stgFileName),
591 globals->get_fg_scenery());
593 return result; // Constructor converts to ReadResult
595 return ReadResult::FILE_NOT_HANDLED;
598 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
599 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");