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);
154 // Give a default LOD range so that traversals that traverse
155 // active children (like the groundcache lookup) will work before
156 // tile manager has had a chance to update this node.
157 _node->setRange(0, 0.0, 10000.0);
162 FGTileEntry::~FGTileEntry ()
166 static void WorldCoordinate( osg::Matrix& obj_pos, double lat,
167 double lon, double elev, double hdg )
169 double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
170 double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
171 double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
174 Point3D geod( lon_rad, lat_rad, elev );
175 Point3D world_pos = sgGeodToCart( geod );
177 double sin_lat = sin( lat_rad );
178 double cos_lat = cos( lat_rad );
179 double cos_lon = cos( lon_rad );
180 double sin_lon = sin( lon_rad );
181 double sin_hdg = sin( hdg_rad ) ;
182 double cos_hdg = cos( hdg_rad ) ;
184 obj_pos(0, 0) = cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
185 obj_pos(0, 1) = cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
186 obj_pos(0, 2) = -cos_hdg * cos_lat;
187 obj_pos(0, 3) = SG_ZERO;
189 obj_pos(1, 0) = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
190 obj_pos(1, 1) = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
191 obj_pos(1, 2) = sin_hdg * cos_lat;
192 obj_pos(1, 3) = SG_ZERO;
194 obj_pos(2, 0) = cos_lat * cos_lon;
195 obj_pos(2, 1) = cos_lat * sin_lon;
196 obj_pos(2, 2) = sin_lat;
197 obj_pos(2, 3) = SG_ZERO;
199 obj_pos(3, 0) = world_pos.x();
200 obj_pos(3, 1) = world_pos.y();
201 obj_pos(3, 2) = world_pos.z();
202 obj_pos(3, 3) = SG_ONE ;
206 // Free "n" leaf elements of an ssg tree. returns the number of
207 // elements freed. An empty branch node is considered a leaf. This
208 // is intended to spread the load of freeing a complex tile out over
210 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
211 int num_deletes = b->getNumChildren();
213 b->removeChildren(0, b->getNumChildren());
219 // Clean up the memory used by this tile and delete the arrays used by
220 // ssg as well as the whole ssg branch
221 bool FGTileEntry::free_tile() {
222 int delete_size = 100;
223 SG_LOG( SG_TERRAIN, SG_DEBUG,
224 "FREEING TILE = (" << tile_bucket << ")" );
226 SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
228 if ( !(free_tracker & NODES) ) {
229 free_tracker |= NODES;
230 } else if ( !(free_tracker & VEC_PTRS) ) {
231 free_tracker |= VEC_PTRS;
232 } else if ( !(free_tracker & TERRA_NODE) ) {
233 // delete the terrain branch (this should already have been
234 // disconnected from the scene graph)
235 SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
236 if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
238 free_tracker |= TERRA_NODE;
240 } else if ( !(free_tracker & LIGHTMAPS) ) {
241 free_tracker |= LIGHTMAPS;
246 SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
248 // if we fall down to here, we still have work todo, return false
253 // Update the ssg transform node for this tile so it can be
254 // properly drawn relative to our (0,0,0) point
255 void FGTileEntry::prep_ssg_node(float vis) {
258 // visibility can change from frame to frame so we update the
259 // range selector cutoff's each time.
260 float bounding_radius = _node->getChild(0)->getBound().radius();
261 _node->setRange( 0, 0, vis + bounding_radius );
264 bool FGTileEntry::obj_load( const string& path,
265 osg::Group *geometry, bool is_base )
267 bool use_random_objects =
268 fgGetBool("/sim/rendering/random-objects", true);
270 // try loading binary format
271 osg::ref_ptr<SGReaderWriterBTGOptions> options
272 = new SGReaderWriterBTGOptions();
273 options->setMatlib(globals->get_matlib());
274 options->setCalcLights(is_base);
275 options->setUseRandomObjects(use_random_objects);
276 osg::Node* node = osgDB::readNodeFile(path, options.get());
278 geometry->addChild(node);
293 // storage class for deferred object processing in FGTileEntry::load()
295 Object(object_type t, const string& token, const SGPath& p, istream& in)
300 in >> lon >> lat >> elev >> hdg;
304 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
306 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
307 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
312 double lon, lat, elev, hdg;
315 // Work in progress... load the tile based entirely by name cuz that's
316 // what we'll want to do with the database pager.
319 FGTileEntry::loadTileByName(const string& index_str,
320 const string_list &path_list)
324 istringstream idxStream(index_str);
325 idxStream >> tileIndex;
327 SGBucket tile_bucket(tileIndex);
328 const string basePath = tile_bucket.gen_base_path();
330 bool found_tile_base = false;
333 vector<const Object*> objects;
335 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
337 // scan and parse all files and store information
338 for (unsigned int i = 0; i < path_list.size(); i++) {
339 // If we found a terrain tile in Terrain/, we have to process the
340 // Objects/ dir in the same group, too, before we can stop scanning.
341 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
343 if (path_list[i].empty()) {
350 bool has_base = false;
352 SGPath tile_path = path_list[i];
353 tile_path.append(basePath);
355 SGPath basename = tile_path;
356 basename.append( index_str );
358 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
361 // Check for master .stg (scene terra gear) file
362 SGPath stg_name = basename;
363 stg_name.concat( ".stg" );
365 sg_gzifstream in( stg_name.str() );
369 while ( ! in.eof() ) {
373 if ( token.empty() || token[0] == '#' ) {
377 // Load only once (first found)
378 if ( token == "OBJECT_BASE" ) {
380 in >> name >> ::skipws;
381 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
383 if (!found_tile_base) {
384 found_tile_base = true;
387 object_base = tile_path;
388 object_base.append(name);
391 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
393 // Load only if base is not in another file
394 } else if ( token == "OBJECT" ) {
395 if (!found_tile_base || has_base)
396 objects.push_back(new Object(OBJECT, token, tile_path, in));
399 in >> name >> ::skipeol;
400 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
401 << name << " (skipped)");
405 } else if ( token == "OBJECT_STATIC" ) {
406 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
408 } else if ( token == "OBJECT_SHARED" ) {
409 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
411 } else if ( token == "OBJECT_SIGN" ) {
412 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
414 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
415 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
418 SG_LOG( SG_TERRAIN, SG_DEBUG,
419 "Unknown token '" << token << "' in " << stg_name.str() );
426 // obj_load() will generate ground lighting for us ...
427 osg::Group* new_tile = new osg::Group;
429 if (found_tile_base) {
430 // load tile if found ...
431 obj_load( object_base.str(), new_tile, true );
434 // ... or generate an ocean tile on the fly
435 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
436 if ( !SGGenTile( path_list[0], tile_bucket,
437 globals->get_matlib(), new_tile ) ) {
438 SG_LOG( SG_TERRAIN, SG_ALERT,
439 "Warning: failed to generate ocean tile!" );
444 // now that we have a valid center, process all the objects
445 for (unsigned int j = 0; j < objects.size(); j++) {
446 const Object *obj = objects[j];
448 if (obj->type == OBJECT) {
449 SGPath custom_path = obj->path;
450 custom_path.append( obj->name );
451 obj_load( custom_path.str(), new_tile, false );
453 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
454 // object loading is deferred to main render thread,
455 // but lets figure out the paths right now.
457 if ( obj->type == OBJECT_STATIC ) {
458 custom_path = obj->path;
460 custom_path = globals->get_fg_root();
462 custom_path.append( obj->name );
465 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
467 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
468 obj_trans->setMatrix( obj_pos );
470 // wire as much of the scene graph together as we can
471 new_tile->addChild( obj_trans );
474 = FGTileMgr::loadTileModel(custom_path.str(),
475 obj->type == OBJECT_SHARED);
477 obj_trans->addChild(model);
478 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
479 // load the object itself
480 SGPath custom_path = obj->path;
481 custom_path.append( obj->name );
484 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
486 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
487 obj_trans->setMatrix( obj_pos );
489 osg::Node *custom_obj = 0;
490 if (obj->type == OBJECT_SIGN)
491 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
493 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
495 // wire the pieces together
496 if ( custom_obj != NULL ) {
497 obj_trans -> addChild( custom_obj );
499 new_tile->addChild( obj_trans );
508 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch )
510 // bump up the ref count so we can remove this later without
511 // having ssg try to free the memory.
512 terrain_branch->addChild( _node.get() );
514 SG_LOG( SG_TERRAIN, SG_DEBUG,
515 "connected a tile into scene graph. _node = "
517 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
518 << _node->getNumParents() );
523 FGTileEntry::disconnect_ssg_nodes()
525 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
528 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
530 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
533 // find the terrain branch parent
534 int pcount = _node->getNumParents();
536 // find the first parent (should only be one)
537 osg::Group *parent = _node->getParent( 0 ) ;
539 // disconnect the tile (we previously ref()'d it so it
540 // won't get freed now)
541 parent->removeChild( _node.get() );
543 // This should be impossible.
544 SG_LOG( SG_TERRAIN, SG_ALERT,
545 "parent pointer is NULL! Dying" );
554 class ReaderWriterSTG : public osgDB::ReaderWriter {
556 virtual const char* className() const;
558 virtual bool acceptsExtension(const string& extension) const;
560 virtual ReadResult readNode(const string& fileName,
561 const osgDB::ReaderWriter::Options* options)
565 const char* ReaderWriterSTG::className() const
567 return "STG Database reader";
570 bool ReaderWriterSTG::acceptsExtension(const string& extension) const
572 return (osgDB::equalCaseInsensitive(extension, "gz")
573 || osgDB::equalCaseInsensitive(extension, "stg"));
576 //#define SLOW_PAGER 1
581 osgDB::ReaderWriter::ReadResult
582 ReaderWriterSTG::readNode(const string& fileName,
583 const osgDB::ReaderWriter::Options* options) const
585 string ext = osgDB::getLowerCaseFileExtension(fileName);
586 if(!acceptsExtension(ext))
587 return ReadResult::FILE_NOT_HANDLED;
589 if (osgDB::equalCaseInsensitive(ext, "gz")) {
590 stgFileName = osgDB::getNameLessExtension(fileName);
591 if (!acceptsExtension(
592 osgDB::getLowerCaseFileExtension(stgFileName))) {
593 return ReadResult::FILE_NOT_HANDLED;
596 stgFileName = fileName;
599 = FGTileEntry::loadTileByName(osgDB::getNameLessExtension(stgFileName),
600 globals->get_fg_scenery());
601 // For debugging race conditions
606 return result; // Constructor converts to ReadResult
608 return ReadResult::FILE_NOT_HANDLED;
611 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
612 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");