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