]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
Avoid empty search path extensions for the case that only the bucket index
[simgear.git] / simgear / scene / tgdb / TileEntry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <simgear_config.h>
23 #endif
24
25 #include <simgear/compiler.h>
26 #include <plib/ul.h>
27
28 #include <string>
29 #include <sstream>
30 #include <istream>
31
32 #include <osg/Array>
33 #include <osg/Geometry>
34 #include <osg/Geode>
35 #include <osg/LOD>
36 #include <osg/MatrixTransform>
37 #include <osg/Math>
38 #include <osg/NodeCallback>
39 #include <osg/Switch>
40
41 #include <osgDB/FileNameUtils>
42 #include <osgDB/ReaderWriter>
43 #include <osgDB/ReadFile>
44 #include <osgDB/Registry>
45
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>
59 #include <simgear/scene/util/SGUpdateVisitor.hxx>
60
61 #include "ReaderWriterSTG.hxx"
62 #include "TileEntry.hxx"
63
64 using std::string;
65 using namespace simgear;
66
67 ModelLoadHelper *TileEntry::_modelLoader=0;
68
69 namespace {
70 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
71 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
72 }
73
74 // FIXME: investigate what huge update flood is clamped away here ...
75 class FGTileUpdateCallback : public osg::NodeCallback {
76 public:
77   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
78   {
79     assert(dynamic_cast<SGUpdateVisitor*>(nv));
80     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
81
82     osg::Vec3 center = node->getBound().center();
83     double distance = dist(updateVisitor->getGlobalEyePos(),
84                            SGVec3d(center[0], center[1], center[2]));
85     if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
86       return;
87
88     traverse(node, nv);
89   }
90 };
91
92 namespace
93 {
94 // Update the timestamp on a tile whenever it is in view.
95
96 class TileCullCallback : public osg::NodeCallback
97 {
98 public:
99     TileCullCallback() : _timeStamp(0) {}
100     TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
101         NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
102     {
103     }
104
105     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
106     double getTimeStamp() const { return _timeStamp; }
107     void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
108 protected:
109     double _timeStamp;
110 };
111 }
112
113 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
114 {
115     if (nv->getFrameStamp())
116         _timeStamp = nv->getFrameStamp()->getReferenceTime();
117     traverse(node, nv);
118 }
119
120 double TileEntry::get_timestamp() const
121 {
122     if (_node.valid()) {
123         return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
124             ->getTimeStamp();
125     } else
126         return DBL_MAX;
127 }
128
129 void TileEntry::set_timestamp(double time_ms)
130 {
131     if (_node.valid()) {
132         TileCullCallback* cb
133             = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
134         if (cb)
135             cb->setTimeStamp(time_ms);
136     }
137 }
138
139 // Constructor
140 TileEntry::TileEntry ( const SGBucket& b )
141     : tile_bucket( b ),
142       _node( new osg::LOD ),
143       is_inner_ring(false),
144       tileFileName(b.gen_index_str())
145 {
146     _node->setUpdateCallback(new FGTileUpdateCallback);
147     _node->setCullCallback(new TileCullCallback);
148     tileFileName += ".stg";
149     _node->setName(tileFileName);
150     // Give a default LOD range so that traversals that traverse
151     // active children (like the groundcache lookup) will work before
152     // tile manager has had a chance to update this node.
153     _node->setRange(0, 0.0, 10000.0);
154 }
155
156
157 // Destructor
158 TileEntry::~TileEntry ()
159 {
160 }
161
162 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
163                             double lon, double elev, double hdg)
164 {
165     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
166     obj_pos = geod.makeZUpFrame();
167     // hdg is not a compass heading, but a counter-clockwise rotation
168     // around the Z axis
169     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
170                                         0.0, 0.0, 1.0));
171 }
172
173
174 // Clean up the memory used by this tile and delete the arrays used by
175 // ssg as well as the whole ssg branch
176 bool TileEntry::free_tile() {
177     SG_LOG( SG_TERRAIN, SG_DEBUG,
178             "FREEING TILE = (" << tile_bucket << ")" );
179
180     _node->removeChildren(0, _node->getNumChildren());
181     _node = 0;
182
183     return true;
184 }
185
186
187 // Update the ssg transform node for this tile so it can be
188 // properly drawn relative to our (0,0,0) point
189 void TileEntry::prep_ssg_node(float vis) {
190     if (!is_loaded())
191         return;
192     // visibility can change from frame to frame so we update the
193     // range selector cutoff's each time.
194     float bounding_radius = _node->getChild(0)->getBound().radius();
195     _node->setRange( 0, 0, vis + bounding_radius );
196 }
197
198 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
199                          const osgDB::ReaderWriter::Options* options)
200 {
201     osg::Node* node = osgDB::readNodeFile(path, options);
202     if (node)
203       geometry->addChild(node);
204
205     return node != 0;
206 }
207
208
209 typedef enum {
210     OBJECT,
211     OBJECT_SHARED,
212     OBJECT_STATIC,
213     OBJECT_SIGN,
214     OBJECT_RUNWAY_SIGN
215 } object_type;
216
217
218 // storage class for deferred object processing in TileEntry::load()
219 struct Object {
220     Object(object_type t, const string& token, const SGPath& p,
221            std::istream& in)
222         : type(t), path(p)
223     {
224         in >> name;
225         if (type != OBJECT)
226             in >> lon >> lat >> elev >> hdg;
227         in >> ::skipeol;
228
229         if (type == OBJECT)
230             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
231         else
232             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
233                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
234     }
235     object_type type;
236     string name;
237     SGPath path;
238     double lon, lat, elev, hdg;
239 };
240
241 // Work in progress... load the tile based entirely by name cuz that's
242 // what we'll want to do with the database pager.
243
244 osg::Node*
245 TileEntry::loadTileByFileName(const string& fileName,
246                               const osgDB::ReaderWriter::Options* options)
247 {
248     std::string index_str = osgDB::getNameLessExtension(fileName);
249     index_str = osgDB::getSimpleFileName(index_str);
250
251     long tileIndex;
252     {
253         std::istringstream idxStream(index_str);
254         idxStream >> tileIndex;
255     }
256     SGBucket tile_bucket(tileIndex);
257     const string basePath = tile_bucket.gen_base_path();
258
259     bool found_tile_base = false;
260
261     SGPath object_base;
262     vector<const Object*> objects;
263
264     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
265
266     osgDB::FilePathList path_list=options->getDatabasePathList();
267     // Make sure we find the original filename here...
268     std::string filePath = osgDB::getFilePath(fileName);
269     if (!filePath.empty())
270         path_list.push_front(filePath);
271
272     // scan and parse all files and store information
273     for (unsigned int i = 0; i < path_list.size(); i++) {
274         // If we found a terrain tile in Terrain/, we have to process the
275         // Objects/ dir in the same group, too, before we can stop scanning.
276         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
277         // as marker.
278
279         if (path_list[i].empty()) {
280             if (found_tile_base)
281                 break;
282             else
283                 continue;
284         }
285
286         bool has_base = false;
287
288         SGPath tile_path = path_list[i];
289         tile_path.append(basePath);
290
291         SGPath basename = tile_path;
292         basename.append( index_str );
293
294         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
295
296
297         // Check for master .stg (scene terra gear) file
298         SGPath stg_name = basename;
299         stg_name.concat( ".stg" );
300
301         sg_gzifstream in( stg_name.str() );
302         if ( !in.is_open() )
303             continue;
304
305         while ( ! in.eof() ) {
306             string token;
307             in >> token;
308
309             if ( token.empty() || token[0] == '#' ) {
310                in >> ::skipeol;
311                continue;
312             }
313                             // Load only once (first found)
314             if ( token == "OBJECT_BASE" ) {
315                 string name;
316                 in >> name >> ::skipws;
317                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
318
319                 if (!found_tile_base) {
320                     found_tile_base = true;
321                     has_base = true;
322
323                     object_base = tile_path;
324                     object_base.append(name);
325
326                 } else
327                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
328
329                             // Load only if base is not in another file
330             } else if ( token == "OBJECT" ) {
331                 if (!found_tile_base || has_base)
332                     objects.push_back(new Object(OBJECT, token, tile_path, in));
333                 else {
334                     string name;
335                     in >> name >> ::skipeol;
336                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
337                             << name << "  (skipped)");
338                 }
339
340                             // Always OK to load
341             } else if ( token == "OBJECT_STATIC" ) {
342                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
343
344             } else if ( token == "OBJECT_SHARED" ) {
345                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
346
347             } else if ( token == "OBJECT_SIGN" ) {
348                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
349
350             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
351                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
352
353             } else {
354                 SG_LOG( SG_TERRAIN, SG_DEBUG,
355                         "Unknown token '" << token << "' in " << stg_name.str() );
356                 in >> ::skipws;
357             }
358         }
359     }
360
361     const SGReaderWriterBTGOptions* btgOpt;
362     btgOpt = dynamic_cast<const SGReaderWriterBTGOptions *>(options);
363     osg::ref_ptr<SGReaderWriterBTGOptions> opt;
364     if (btgOpt)
365         opt = new SGReaderWriterBTGOptions(*btgOpt);
366     else
367         opt = new SGReaderWriterBTGOptions;
368
369     // obj_load() will generate ground lighting for us ...
370     osg::Group* new_tile = new osg::Group;
371
372     if (found_tile_base) {
373         // load tile if found ...
374         opt->setCalcLights(true);
375         obj_load( object_base.str(), new_tile, true, opt);
376
377     } else {
378         // ... or generate an ocean tile on the fly
379         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
380         if ( !SGGenTile( path_list[0], tile_bucket,
381                         opt->getMatlib(), new_tile ) ) {
382             SG_LOG( SG_TERRAIN, SG_ALERT,
383                     "Warning: failed to generate ocean tile!" );
384         }
385     }
386
387
388     // now that we have a valid center, process all the objects
389     for (unsigned int j = 0; j < objects.size(); j++) {
390         const Object *obj = objects[j];
391
392         if (obj->type == OBJECT) {
393             SGPath custom_path = obj->path;
394             custom_path.append( obj->name );
395             opt->setCalcLights(true);
396             obj_load( custom_path.str(), new_tile, false, opt);
397
398         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
399             // object loading is deferred to main render thread,
400             // but lets figure out the paths right now.
401             SGPath custom_path;
402             if ( obj->type == OBJECT_STATIC ) {
403                 custom_path = obj->path;
404             } else {
405                 // custom_path = globals->get_fg_root();
406             }
407             custom_path.append( obj->name );
408
409             osg::Matrix obj_pos;
410             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
411
412             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
413             obj_trans->setMatrix( obj_pos );
414
415             // wire as much of the scene graph together as we can
416             new_tile->addChild( obj_trans );
417
418             osg::Node* model = 0;
419             if(_modelLoader)
420                 model = _modelLoader->loadTileModel(custom_path.str(),
421                                                     obj->type == OBJECT_SHARED);
422             if (model)
423                 obj_trans->addChild(model);
424         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
425             // load the object itself
426             SGPath custom_path = obj->path;
427             custom_path.append( obj->name );
428
429             osg::Matrix obj_pos;
430             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
431
432             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
433             obj_trans->setMatrix( obj_pos );
434
435             osg::Node *custom_obj = 0;
436             if (obj->type == OBJECT_SIGN)
437                 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
438             else
439                 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
440
441             // wire the pieces together
442             if ( custom_obj != NULL ) {
443                 obj_trans -> addChild( custom_obj );
444             }
445             new_tile->addChild( obj_trans );
446
447         }
448         delete obj;
449     }
450     return new_tile;
451 }
452
453 void
454 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
455 {
456     terrain_branch->addChild( _node.get() );
457
458     SG_LOG( SG_TERRAIN, SG_DEBUG,
459             "connected a tile into scene graph.  _node = "
460             << _node.get() );
461     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
462             << _node->getNumParents() );
463 }
464
465
466 void
467 TileEntry::removeFromSceneGraph()
468 {
469     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
470
471     if (! is_loaded()) {
472         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
473     } else {
474         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
475     }
476
477     // find the nodes branch parent
478     if ( _node->getNumParents() > 0 ) {
479         // find the first parent (should only be one)
480         osg::Group *parent = _node->getParent( 0 ) ;
481         if( parent ) {
482             parent->removeChild( _node.get() );
483         }
484     }
485 }
486