]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
Use osg's builtin mechanisms to traverse only in range nodes with the
[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
60 #include "ReaderWriterSTG.hxx"
61 #include "TileEntry.hxx"
62
63 using std::string;
64 using namespace simgear;
65
66 ModelLoadHelper *TileEntry::_modelLoader=0;
67
68 namespace {
69 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
70 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
71 }
72
73 namespace
74 {
75 // Update the timestamp on a tile whenever it is in view.
76
77 class TileCullCallback : public osg::NodeCallback
78 {
79 public:
80     TileCullCallback() : _timeStamp(0) {}
81     TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
82         NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
83     {
84     }
85
86     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
87     double getTimeStamp() const { return _timeStamp; }
88     void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
89 protected:
90     double _timeStamp;
91 };
92 }
93
94 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
95 {
96     if (nv->getFrameStamp())
97         _timeStamp = nv->getFrameStamp()->getReferenceTime();
98     traverse(node, nv);
99 }
100
101 double TileEntry::get_timestamp() const
102 {
103     if (_node.valid()) {
104         return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
105             ->getTimeStamp();
106     } else
107         return DBL_MAX;
108 }
109
110 void TileEntry::set_timestamp(double time_ms)
111 {
112     if (_node.valid()) {
113         TileCullCallback* cb
114             = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
115         if (cb)
116             cb->setTimeStamp(time_ms);
117     }
118 }
119
120 // Constructor
121 TileEntry::TileEntry ( const SGBucket& b )
122     : tile_bucket( b ),
123       _node( new osg::LOD ),
124       is_inner_ring(false),
125       tileFileName(b.gen_index_str())
126 {
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);
134 }
135
136
137 // Destructor
138 TileEntry::~TileEntry ()
139 {
140 }
141
142 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
143                             double lon, double elev, double hdg)
144 {
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
148     // around the Z axis
149     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
150                                         0.0, 0.0, 1.0));
151 }
152
153
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 << ")" );
159
160     _node->removeChildren(0, _node->getNumChildren());
161     _node = 0;
162
163     return true;
164 }
165
166
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) {
170     if (!is_loaded())
171         return;
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 );
176 }
177
178 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
179                          const osgDB::ReaderWriter::Options* options)
180 {
181     osg::Node* node = osgDB::readNodeFile(path, options);
182     if (node)
183       geometry->addChild(node);
184
185     return node != 0;
186 }
187
188
189 typedef enum {
190     OBJECT,
191     OBJECT_SHARED,
192     OBJECT_STATIC,
193     OBJECT_SIGN,
194     OBJECT_RUNWAY_SIGN
195 } object_type;
196
197
198 // storage class for deferred object processing in TileEntry::load()
199 struct Object {
200     Object(object_type t, const string& token, const SGPath& p,
201            std::istream& in)
202         : type(t), path(p)
203     {
204         in >> name;
205         if (type != OBJECT)
206             in >> lon >> lat >> elev >> hdg;
207         in >> ::skipeol;
208
209         if (type == OBJECT)
210             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
211         else
212             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
213                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
214     }
215     object_type type;
216     string name;
217     SGPath path;
218     double lon, lat, elev, hdg;
219 };
220
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.
223
224 osg::Node*
225 TileEntry::loadTileByFileName(const string& fileName,
226                               const osgDB::ReaderWriter::Options* options)
227 {
228     std::string index_str = osgDB::getNameLessExtension(fileName);
229     index_str = osgDB::getSimpleFileName(index_str);
230
231     long tileIndex;
232     {
233         std::istringstream idxStream(index_str);
234         idxStream >> tileIndex;
235     }
236     SGBucket tile_bucket(tileIndex);
237     const string basePath = tile_bucket.gen_base_path();
238
239     bool found_tile_base = false;
240
241     SGPath object_base;
242     vector<const Object*> objects;
243
244     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
245
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);
251
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
257         // as marker.
258
259         if (path_list[i].empty()) {
260             if (found_tile_base)
261                 break;
262             else
263                 continue;
264         }
265
266         bool has_base = false;
267
268         SGPath tile_path = path_list[i];
269         tile_path.append(basePath);
270
271         SGPath basename = tile_path;
272         basename.append( index_str );
273
274         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
275
276
277         // Check for master .stg (scene terra gear) file
278         SGPath stg_name = basename;
279         stg_name.concat( ".stg" );
280
281         sg_gzifstream in( stg_name.str() );
282         if ( !in.is_open() )
283             continue;
284
285         while ( ! in.eof() ) {
286             string token;
287             in >> token;
288
289             if ( token.empty() || token[0] == '#' ) {
290                in >> ::skipeol;
291                continue;
292             }
293                             // Load only once (first found)
294             if ( token == "OBJECT_BASE" ) {
295                 string name;
296                 in >> name >> ::skipws;
297                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
298
299                 if (!found_tile_base) {
300                     found_tile_base = true;
301                     has_base = true;
302
303                     object_base = tile_path;
304                     object_base.append(name);
305
306                 } else
307                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
308
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));
313                 else {
314                     string name;
315                     in >> name >> ::skipeol;
316                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
317                             << name << "  (skipped)");
318                 }
319
320                             // Always OK to load
321             } else if ( token == "OBJECT_STATIC" ) {
322                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
323
324             } else if ( token == "OBJECT_SHARED" ) {
325                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
326
327             } else if ( token == "OBJECT_SIGN" ) {
328                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
329
330             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
331                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
332
333             } else {
334                 SG_LOG( SG_TERRAIN, SG_DEBUG,
335                         "Unknown token '" << token << "' in " << stg_name.str() );
336                 in >> ::skipws;
337             }
338         }
339     }
340
341     const SGReaderWriterBTGOptions* btgOpt;
342     btgOpt = dynamic_cast<const SGReaderWriterBTGOptions *>(options);
343     osg::ref_ptr<SGReaderWriterBTGOptions> opt;
344     if (btgOpt)
345         opt = new SGReaderWriterBTGOptions(*btgOpt);
346     else
347         opt = new SGReaderWriterBTGOptions;
348
349     // obj_load() will generate ground lighting for us ...
350     osg::Group* new_tile = new osg::Group;
351
352     if (found_tile_base) {
353         // load tile if found ...
354         opt->setCalcLights(true);
355         obj_load( object_base.str(), new_tile, true, opt);
356
357     } else {
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!" );
364         }
365     }
366
367
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];
371
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);
377
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.
381             SGPath custom_path;
382             if ( obj->type == OBJECT_STATIC ) {
383                 custom_path = obj->path;
384             } else {
385                 // custom_path = globals->get_fg_root();
386             }
387             custom_path.append( obj->name );
388
389             osg::Matrix obj_pos;
390             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
391
392             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
393             obj_trans->setMatrix( obj_pos );
394
395             // wire as much of the scene graph together as we can
396             new_tile->addChild( obj_trans );
397
398             osg::Node* model = 0;
399             if(_modelLoader)
400                 model = _modelLoader->loadTileModel(custom_path.str(),
401                                                     obj->type == OBJECT_SHARED);
402             if (model)
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 );
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             osg::Node *custom_obj = 0;
416             if (obj->type == OBJECT_SIGN)
417                 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
418             else
419                 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
420
421             // wire the pieces together
422             if ( custom_obj != NULL ) {
423                 obj_trans -> addChild( custom_obj );
424             }
425             new_tile->addChild( obj_trans );
426
427         }
428         delete obj;
429     }
430     return new_tile;
431 }
432
433 void
434 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
435 {
436     terrain_branch->addChild( _node.get() );
437
438     SG_LOG( SG_TERRAIN, SG_DEBUG,
439             "connected a tile into scene graph.  _node = "
440             << _node.get() );
441     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
442             << _node->getNumParents() );
443 }
444
445
446 void
447 TileEntry::removeFromSceneGraph()
448 {
449     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
450
451     if (! is_loaded()) {
452         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
453     } else {
454         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
455     }
456
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 ) ;
461         if( parent ) {
462             parent->removeChild( _node.get() );
463         }
464     }
465 }
466