]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
Use bool instead of int to represent boolean values
[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 STL_STRING
29 #include <sstream>
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/polar3d.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 SG_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       free_tracker(0),
145       tileFileName(b.gen_index_str())
146 {
147     _node->setUpdateCallback(new FGTileUpdateCallback);
148     _node->setCullCallback(new TileCullCallback);
149     tileFileName += ".stg";
150     _node->setName(tileFileName);
151     // Give a default LOD range so that traversals that traverse
152     // active children (like the groundcache lookup) will work before
153     // tile manager has had a chance to update this node.
154     _node->setRange(0, 0.0, 10000.0);
155 }
156
157
158 // Destructor
159 TileEntry::~TileEntry ()
160 {
161 }
162
163 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
164                             double lon, double elev, double hdg)
165 {
166     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
167     obj_pos = geod.makeZUpFrame();
168     // hdg is not a compass heading, but a counter-clockwise rotation
169     // around the Z axis
170     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
171                                         0.0, 0.0, 1.0));
172 }
173
174
175 // Free "n" leaf elements of an ssg tree.  returns the number of
176 // elements freed.  An empty branch node is considered a leaf.  This
177 // is intended to spread the load of freeing a complex tile out over
178 // several frames.
179 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
180     int num_deletes = b->getNumChildren();
181
182     b->removeChildren(0, b->getNumChildren());
183
184     return num_deletes;
185 }
186
187
188 // Clean up the memory used by this tile and delete the arrays used by
189 // ssg as well as the whole ssg branch
190 bool TileEntry::free_tile() {
191     int delete_size = 100;
192     SG_LOG( SG_TERRAIN, SG_DEBUG,
193             "FREEING TILE = (" << tile_bucket << ")" );
194
195     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
196
197     if ( !(free_tracker & NODES) ) {
198         free_tracker |= NODES;
199     } else if ( !(free_tracker & VEC_PTRS) ) {
200         free_tracker |= VEC_PTRS;
201     } else if ( !(free_tracker & TERRA_NODE) ) {
202         // delete the terrain branch (this should already have been
203         // disconnected from the scene graph)
204         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
205         if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
206             _node = 0;
207             free_tracker |= TERRA_NODE;
208         }
209     } else if ( !(free_tracker & LIGHTMAPS) ) {
210         free_tracker |= LIGHTMAPS;
211     } else {
212         return true;
213     }
214
215     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
216
217     // if we fall down to here, we still have work todo, return false
218     return false;
219 }
220
221
222 // Update the ssg transform node for this tile so it can be
223 // properly drawn relative to our (0,0,0) point
224 void TileEntry::prep_ssg_node(float vis) {
225     if (!is_loaded())
226         return;
227     // visibility can change from frame to frame so we update the
228     // range selector cutoff's each time.
229     float bounding_radius = _node->getChild(0)->getBound().radius();
230     _node->setRange( 0, 0, vis + bounding_radius );
231 }
232
233 bool TileEntry::obj_load( const string& path,
234                             osg::Group *geometry, bool is_base, const osgDB::ReaderWriter::Options*options)
235 {
236     osg::Node* node = osgDB::readNodeFile(path, options);
237     if (node)
238       geometry->addChild(node);
239
240     return node != 0;
241 }
242
243
244 typedef enum {
245     OBJECT,
246     OBJECT_SHARED,
247     OBJECT_STATIC,
248     OBJECT_SIGN,
249     OBJECT_RUNWAY_SIGN
250 } object_type;
251
252
253 // storage class for deferred object processing in TileEntry::load()
254 struct Object {
255     Object(object_type t, const string& token, const SGPath& p, istream& in)
256         : type(t), path(p)
257     {
258         in >> name;
259         if (type != OBJECT)
260             in >> lon >> lat >> elev >> hdg;
261         in >> ::skipeol;
262
263         if (type == OBJECT)
264             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
265         else
266             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
267                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
268     }
269     object_type type;
270     string name;
271     SGPath path;
272     double lon, lat, elev, hdg;
273 };
274
275 // Work in progress... load the tile based entirely by name cuz that's
276 // what we'll want to do with the database pager.
277
278 osg::Node*
279 TileEntry::loadTileByName(const string& index_str,
280                           const osgDB::ReaderWriter::Options* options)
281 {
282     long tileIndex;
283     {
284         std::istringstream idxStream(index_str);
285         idxStream >> tileIndex;
286     }
287     SGBucket tile_bucket(tileIndex);
288     const string basePath = tile_bucket.gen_base_path();
289
290     bool found_tile_base = false;
291
292     SGPath object_base;
293     vector<const Object*> objects;
294
295     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
296
297     osgDB::FilePathList path_list=options->getDatabasePathList();
298
299     // scan and parse all files and store information
300     for (unsigned int i = 0; i < path_list.size(); i++) {
301         // If we found a terrain tile in Terrain/, we have to process the
302         // Objects/ dir in the same group, too, before we can stop scanning.
303         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
304         // as marker.
305
306         if (path_list[i].empty()) {
307             if (found_tile_base)
308                 break;
309             else
310                 continue;
311         }
312
313         bool has_base = false;
314
315         SGPath tile_path = path_list[i];
316         tile_path.append(basePath);
317
318         SGPath basename = tile_path;
319         basename.append( index_str );
320
321         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
322
323
324         // Check for master .stg (scene terra gear) file
325         SGPath stg_name = basename;
326         stg_name.concat( ".stg" );
327
328         sg_gzifstream in( stg_name.str() );
329         if ( !in.is_open() )
330             continue;
331
332         while ( ! in.eof() ) {
333             string token;
334             in >> token;
335
336             if ( token.empty() || token[0] == '#' ) {
337                in >> ::skipeol;
338                continue;
339             }
340                             // Load only once (first found)
341             if ( token == "OBJECT_BASE" ) {
342                 string name;
343                 in >> name >> ::skipws;
344                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
345
346                 if (!found_tile_base) {
347                     found_tile_base = true;
348                     has_base = true;
349
350                     object_base = tile_path;
351                     object_base.append(name);
352
353                 } else
354                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
355
356                             // Load only if base is not in another file
357             } else if ( token == "OBJECT" ) {
358                 if (!found_tile_base || has_base)
359                     objects.push_back(new Object(OBJECT, token, tile_path, in));
360                 else {
361                     string name;
362                     in >> name >> ::skipeol;
363                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
364                             << name << "  (skipped)");
365                 }
366
367                             // Always OK to load
368             } else if ( token == "OBJECT_STATIC" ) {
369                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
370
371             } else if ( token == "OBJECT_SHARED" ) {
372                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
373
374             } else if ( token == "OBJECT_SIGN" ) {
375                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
376
377             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
378                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
379
380             } else {
381                 SG_LOG( SG_TERRAIN, SG_DEBUG,
382                         "Unknown token '" << token << "' in " << stg_name.str() );
383                 in >> ::skipws;
384             }
385         }
386     }
387
388     SGReaderWriterBTGOptions *opt = new SGReaderWriterBTGOptions(*dynamic_cast<const SGReaderWriterBTGOptions *>(options));
389
390     // obj_load() will generate ground lighting for us ...
391     osg::Group* new_tile = new osg::Group;
392
393     if (found_tile_base) {
394         // load tile if found ...
395         opt->setCalcLights(true);
396         obj_load( object_base.str(), new_tile, true, options);
397
398     } else {
399         // ... or generate an ocean tile on the fly
400         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
401         if ( !SGGenTile( path_list[0], tile_bucket,
402                         opt->getMatlib(), new_tile ) ) {
403             SG_LOG( SG_TERRAIN, SG_ALERT,
404                     "Warning: failed to generate ocean tile!" );
405         }
406     }
407
408
409     // now that we have a valid center, process all the objects
410     for (unsigned int j = 0; j < objects.size(); j++) {
411         const Object *obj = objects[j];
412
413         if (obj->type == OBJECT) {
414             SGPath custom_path = obj->path;
415             custom_path.append( obj->name );
416             opt->setCalcLights(true);
417             obj_load( custom_path.str(), new_tile, false, options);
418
419         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
420             // object loading is deferred to main render thread,
421             // but lets figure out the paths right now.
422             SGPath custom_path;
423             if ( obj->type == OBJECT_STATIC ) {
424                 custom_path = obj->path;
425             } else {
426                 // custom_path = globals->get_fg_root();
427             }
428             custom_path.append( obj->name );
429
430             osg::Matrix obj_pos;
431             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
432
433             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
434             obj_trans->setMatrix( obj_pos );
435
436             // wire as much of the scene graph together as we can
437             new_tile->addChild( obj_trans );
438
439             osg::Node* model = 0;
440             if(_modelLoader)
441                 model = _modelLoader->loadTileModel(custom_path.str(),
442                                                     obj->type == OBJECT_SHARED);
443             if (model)
444                 obj_trans->addChild(model);
445         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
446             // load the object itself
447             SGPath custom_path = obj->path;
448             custom_path.append( obj->name );
449
450             osg::Matrix obj_pos;
451             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
452
453             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
454             obj_trans->setMatrix( obj_pos );
455
456             osg::Node *custom_obj = 0;
457             if (obj->type == OBJECT_SIGN)
458                 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
459             else
460                 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
461
462             // wire the pieces together
463             if ( custom_obj != NULL ) {
464                 obj_trans -> addChild( custom_obj );
465             }
466             new_tile->addChild( obj_trans );
467
468         }
469         delete obj;
470     }
471     return new_tile;
472 }
473
474 void
475 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
476 {
477     terrain_branch->addChild( _node.get() );
478
479     SG_LOG( SG_TERRAIN, SG_DEBUG,
480             "connected a tile into scene graph.  _node = "
481             << _node.get() );
482     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
483             << _node->getNumParents() );
484 }
485
486
487 void
488 TileEntry::removeFromSceneGraph()
489 {
490     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
491
492     if (! is_loaded()) {
493         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
494     } else {
495         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
496     }
497
498     // find the nodes branch parent
499     if ( _node->getNumParents() > 0 ) {
500         // find the first parent (should only be one)
501         osg::Group *parent = _node->getParent( 0 ) ;
502         if( parent ) {
503             parent->removeChild( _node.get() );
504         }
505     }
506 }
507