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