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 // Update the timestamp on a tile whenever it is in view.
101 class TileCullCallback : public osg::NodeCallback
104 TileCullCallback() : _timeStamp(0) {}
105 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
106 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
110 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
111 double getTimeStamp() const { return _timeStamp; }
112 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
118 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
120 if (nv->getFrameStamp())
121 _timeStamp = nv->getFrameStamp()->getReferenceTime();
125 double FGTileEntry::get_timestamp() const
128 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
134 void FGTileEntry::set_timestamp(double time_ms)
138 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
140 cb->setTimeStamp(time_ms);
145 FGTileEntry::FGTileEntry ( const SGBucket& b )
147 _node( new osg::LOD ),
148 is_inner_ring(false),
150 tileFileName(b.gen_index_str())
152 _node->setUpdateCallback(new FGTileUpdateCallback);
153 _node->setCullCallback(new TileCullCallback);
154 tileFileName += ".stg";
155 _node->setName(tileFileName);
156 // Give a default LOD range so that traversals that traverse
157 // active children (like the groundcache lookup) will work before
158 // tile manager has had a chance to update this node.
159 _node->setRange(0, 0.0, 10000.0);
164 FGTileEntry::~FGTileEntry ()
168 static void WorldCoordinate( osg::Matrix& obj_pos, double lat,
169 double lon, double elev, double hdg )
171 double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
172 double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
173 double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
176 Point3D geod( lon_rad, lat_rad, elev );
177 Point3D world_pos = sgGeodToCart( geod );
179 double sin_lat = sin( lat_rad );
180 double cos_lat = cos( lat_rad );
181 double cos_lon = cos( lon_rad );
182 double sin_lon = sin( lon_rad );
183 double sin_hdg = sin( hdg_rad ) ;
184 double cos_hdg = cos( hdg_rad ) ;
186 obj_pos(0, 0) = cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
187 obj_pos(0, 1) = cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
188 obj_pos(0, 2) = -cos_hdg * cos_lat;
189 obj_pos(0, 3) = SG_ZERO;
191 obj_pos(1, 0) = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
192 obj_pos(1, 1) = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
193 obj_pos(1, 2) = sin_hdg * cos_lat;
194 obj_pos(1, 3) = SG_ZERO;
196 obj_pos(2, 0) = cos_lat * cos_lon;
197 obj_pos(2, 1) = cos_lat * sin_lon;
198 obj_pos(2, 2) = sin_lat;
199 obj_pos(2, 3) = SG_ZERO;
201 obj_pos(3, 0) = world_pos.x();
202 obj_pos(3, 1) = world_pos.y();
203 obj_pos(3, 2) = world_pos.z();
204 obj_pos(3, 3) = SG_ONE ;
208 // Free "n" leaf elements of an ssg tree. returns the number of
209 // elements freed. An empty branch node is considered a leaf. This
210 // is intended to spread the load of freeing a complex tile out over
212 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
213 int num_deletes = b->getNumChildren();
215 b->removeChildren(0, b->getNumChildren());
221 // Clean up the memory used by this tile and delete the arrays used by
222 // ssg as well as the whole ssg branch
223 bool FGTileEntry::free_tile() {
224 int delete_size = 100;
225 SG_LOG( SG_TERRAIN, SG_DEBUG,
226 "FREEING TILE = (" << tile_bucket << ")" );
228 SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
230 if ( !(free_tracker & NODES) ) {
231 free_tracker |= NODES;
232 } else if ( !(free_tracker & VEC_PTRS) ) {
233 free_tracker |= VEC_PTRS;
234 } else if ( !(free_tracker & TERRA_NODE) ) {
235 // delete the terrain branch (this should already have been
236 // disconnected from the scene graph)
237 SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
238 if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
240 free_tracker |= TERRA_NODE;
242 } else if ( !(free_tracker & LIGHTMAPS) ) {
243 free_tracker |= LIGHTMAPS;
248 SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
250 // if we fall down to here, we still have work todo, return false
255 // Update the ssg transform node for this tile so it can be
256 // properly drawn relative to our (0,0,0) point
257 void FGTileEntry::prep_ssg_node(float vis) {
260 // visibility can change from frame to frame so we update the
261 // range selector cutoff's each time.
262 float bounding_radius = _node->getChild(0)->getBound().radius();
263 _node->setRange( 0, 0, vis + bounding_radius );
266 bool FGTileEntry::obj_load( const string& path,
267 osg::Group *geometry, bool is_base )
269 bool use_random_objects =
270 fgGetBool("/sim/rendering/random-objects", true);
272 bool use_random_vegetation =
273 fgGetBool("/sim/rendering/random-vegetation", true);
275 // try loading binary format
276 osg::ref_ptr<SGReaderWriterBTGOptions> options
277 = new SGReaderWriterBTGOptions();
278 options->setMatlib(globals->get_matlib());
279 options->setCalcLights(is_base);
280 options->setUseRandomObjects(use_random_objects);
281 options->setUseRandomVegetation(use_random_vegetation);
282 osg::Node* node = osgDB::readNodeFile(path, options.get());
284 geometry->addChild(node);
299 // storage class for deferred object processing in FGTileEntry::load()
301 Object(object_type t, const string& token, const SGPath& p, istream& in)
306 in >> lon >> lat >> elev >> hdg;
310 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
312 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
313 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
318 double lon, lat, elev, hdg;
321 // Work in progress... load the tile based entirely by name cuz that's
322 // what we'll want to do with the database pager.
325 FGTileEntry::loadTileByName(const string& index_str,
326 const string_list &path_list)
330 istringstream idxStream(index_str);
331 idxStream >> tileIndex;
333 SGBucket tile_bucket(tileIndex);
334 const string basePath = tile_bucket.gen_base_path();
336 bool found_tile_base = false;
339 vector<const Object*> objects;
341 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
343 // scan and parse all files and store information
344 for (unsigned int i = 0; i < path_list.size(); i++) {
345 // If we found a terrain tile in Terrain/, we have to process the
346 // Objects/ dir in the same group, too, before we can stop scanning.
347 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
349 if (path_list[i].empty()) {
356 bool has_base = false;
358 SGPath tile_path = path_list[i];
359 tile_path.append(basePath);
361 SGPath basename = tile_path;
362 basename.append( index_str );
364 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
367 // Check for master .stg (scene terra gear) file
368 SGPath stg_name = basename;
369 stg_name.concat( ".stg" );
371 sg_gzifstream in( stg_name.str() );
375 while ( ! in.eof() ) {
379 if ( token.empty() || token[0] == '#' ) {
383 // Load only once (first found)
384 if ( token == "OBJECT_BASE" ) {
386 in >> name >> ::skipws;
387 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
389 if (!found_tile_base) {
390 found_tile_base = true;
393 object_base = tile_path;
394 object_base.append(name);
397 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
399 // Load only if base is not in another file
400 } else if ( token == "OBJECT" ) {
401 if (!found_tile_base || has_base)
402 objects.push_back(new Object(OBJECT, token, tile_path, in));
405 in >> name >> ::skipeol;
406 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
407 << name << " (skipped)");
411 } else if ( token == "OBJECT_STATIC" ) {
412 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
414 } else if ( token == "OBJECT_SHARED" ) {
415 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
417 } else if ( token == "OBJECT_SIGN" ) {
418 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
420 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
421 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
424 SG_LOG( SG_TERRAIN, SG_DEBUG,
425 "Unknown token '" << token << "' in " << stg_name.str() );
432 // obj_load() will generate ground lighting for us ...
433 osg::Group* new_tile = new osg::Group;
435 if (found_tile_base) {
436 // load tile if found ...
437 obj_load( object_base.str(), new_tile, true );
440 // ... or generate an ocean tile on the fly
441 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
442 if ( !SGGenTile( path_list[0], tile_bucket,
443 globals->get_matlib(), new_tile ) ) {
444 SG_LOG( SG_TERRAIN, SG_ALERT,
445 "Warning: failed to generate ocean tile!" );
450 // now that we have a valid center, process all the objects
451 for (unsigned int j = 0; j < objects.size(); j++) {
452 const Object *obj = objects[j];
454 if (obj->type == OBJECT) {
455 SGPath custom_path = obj->path;
456 custom_path.append( obj->name );
457 obj_load( custom_path.str(), new_tile, false );
459 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
460 // object loading is deferred to main render thread,
461 // but lets figure out the paths right now.
463 if ( obj->type == OBJECT_STATIC ) {
464 custom_path = obj->path;
466 custom_path = globals->get_fg_root();
468 custom_path.append( obj->name );
471 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
473 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
474 obj_trans->setMatrix( obj_pos );
476 // wire as much of the scene graph together as we can
477 new_tile->addChild( obj_trans );
480 = FGTileMgr::loadTileModel(custom_path.str(),
481 obj->type == OBJECT_SHARED);
483 obj_trans->addChild(model);
484 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
485 // load the object itself
486 SGPath custom_path = obj->path;
487 custom_path.append( obj->name );
490 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
492 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
493 obj_trans->setMatrix( obj_pos );
495 osg::Node *custom_obj = 0;
496 if (obj->type == OBJECT_SIGN)
497 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
499 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
501 // wire the pieces together
502 if ( custom_obj != NULL ) {
503 obj_trans -> addChild( custom_obj );
505 new_tile->addChild( obj_trans );
514 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch )
516 // bump up the ref count so we can remove this later without
517 // having ssg try to free the memory.
518 terrain_branch->addChild( _node.get() );
520 SG_LOG( SG_TERRAIN, SG_DEBUG,
521 "connected a tile into scene graph. _node = "
523 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
524 << _node->getNumParents() );
529 FGTileEntry::disconnect_ssg_nodes()
531 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
534 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
536 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
539 // find the terrain branch parent
540 int pcount = _node->getNumParents();
542 // find the first parent (should only be one)
543 osg::Group *parent = _node->getParent( 0 ) ;
545 // disconnect the tile (we previously ref()'d it so it
546 // won't get freed now)
547 parent->removeChild( _node.get() );
549 // This should be impossible.
550 SG_LOG( SG_TERRAIN, SG_ALERT,
551 "parent pointer is NULL! Dying" );
560 class ReaderWriterSTG : public osgDB::ReaderWriter {
562 virtual const char* className() const;
564 virtual bool acceptsExtension(const string& extension) const;
566 virtual ReadResult readNode(const string& fileName,
567 const osgDB::ReaderWriter::Options* options)
571 const char* ReaderWriterSTG::className() const
573 return "STG Database reader";
576 bool ReaderWriterSTG::acceptsExtension(const string& extension) const
578 return (osgDB::equalCaseInsensitive(extension, "gz")
579 || osgDB::equalCaseInsensitive(extension, "stg"));
582 //#define SLOW_PAGER 1
587 osgDB::ReaderWriter::ReadResult
588 ReaderWriterSTG::readNode(const string& fileName,
589 const osgDB::ReaderWriter::Options* options) const
591 string ext = osgDB::getLowerCaseFileExtension(fileName);
592 if(!acceptsExtension(ext))
593 return ReadResult::FILE_NOT_HANDLED;
595 if (osgDB::equalCaseInsensitive(ext, "gz")) {
596 stgFileName = osgDB::getNameLessExtension(fileName);
597 if (!acceptsExtension(
598 osgDB::getLowerCaseFileExtension(stgFileName))) {
599 return ReadResult::FILE_NOT_HANDLED;
602 stgFileName = fileName;
605 = FGTileEntry::loadTileByName(osgDB::getNameLessExtension(stgFileName),
606 globals->get_fg_scenery());
607 // For debugging race conditions
612 return result; // Constructor converts to ReadResult
614 return ReadResult::FILE_NOT_HANDLED;
617 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
618 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");