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