]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
Cleaned up comments to tile entry code
[flightgear.git] / src / Scenery / 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 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <plib/ul.h>
30 #include <Main/main.hxx>
31
32
33 #include STL_STRING
34 #include <sstream>
35
36 #include <osg/Array>
37 #include <osg/Geometry>
38 #include <osg/Geode>
39 #include <osg/LOD>
40 #include <osg/MatrixTransform>
41 #include <osg/Math>
42 #include <osg/NodeCallback>
43 #include <osg/Switch>
44
45 #include <osgDB/FileNameUtils>
46 #include <osgDB/ReaderWriter>
47 #include <osgDB/ReadFile>
48 #include <osgDB/Registry>
49
50 #include <simgear/bucket/newbucket.hxx>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/math/polar3d.hxx>
53 #include <simgear/math/sg_geodesy.hxx>
54 #include <simgear/math/sg_random.h>
55 #include <simgear/misc/sgstream.hxx>
56 #include <simgear/scene/material/mat.hxx>
57 #include <simgear/scene/material/matlib.hxx>
58 #include <simgear/scene/model/ModelRegistry.hxx>
59 #include <simgear/scene/tgdb/apt_signs.hxx>
60 #include <simgear/scene/tgdb/obj.hxx>
61 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
62 #include <simgear/scene/model/placementtrans.hxx>
63 #include <simgear/scene/util/SGUpdateVisitor.hxx>
64
65 #include <Aircraft/aircraft.hxx>
66 #include <Include/general.hxx>
67 #include <Main/fg_props.hxx>
68 #include <Main/globals.hxx>
69 #include <Main/viewer.hxx>
70 #include <Scenery/scenery.hxx>
71 #include <Time/light.hxx>
72
73 #include "tileentry.hxx"
74 #include "tilemgr.hxx"
75
76 SG_USING_STD(string);
77 using namespace simgear;
78
79 // FIXME: investigate what huge update flood is clamped away here ...
80 class FGTileUpdateCallback : public osg::NodeCallback {
81 public:
82   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
83   {
84     assert(dynamic_cast<SGUpdateVisitor*>(nv));
85     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
86
87     osg::Vec3 center = node->getBound().center();
88     double distance = dist(updateVisitor->getGlobalEyePos(),
89                            SGVec3d(center[0], center[1], center[2]));
90     if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
91       return;
92
93     traverse(node, nv);
94   }
95 };
96
97 namespace
98 {
99 // Update the timestamp on a tile whenever it is in view.
100
101 class TileCullCallback : public osg::NodeCallback
102 {
103 public:
104     TileCullCallback() : _timeStamp(0) {}
105     TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
106         NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
107     {
108     }
109     
110     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
111     double getTimeStamp() const { return _timeStamp; }
112     void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
113 protected:
114     double _timeStamp;
115 };
116 }
117
118 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
119 {
120     if (nv->getFrameStamp())
121         _timeStamp = nv->getFrameStamp()->getReferenceTime();
122     traverse(node, nv);
123 }
124
125 double FGTileEntry::get_timestamp() const
126 {
127     if (_node.valid()) {
128         return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
129             ->getTimeStamp();
130     } else
131         return DBL_MAX;
132 }
133
134 void FGTileEntry::set_timestamp(double time_ms)
135 {
136     if (_node.valid()) {
137         TileCullCallback* cb
138             = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
139         if (cb)
140             cb->setTimeStamp(time_ms);
141     }
142 }
143
144 // Constructor
145 FGTileEntry::FGTileEntry ( const SGBucket& b )
146     : tile_bucket( b ),
147       _node( new osg::LOD ),
148       is_inner_ring(false),
149       free_tracker(0),
150       tileFileName(b.gen_index_str())
151 {
152     _node->setUpdateCallback(new FGTileUpdateCallback);
153     _node->setCullCallback(new TileCullCallback);
154     tileFileName += ".stg";
155     _node->setName(tileFileName);
156     // Give a default LOD range so that traversals that traverse
157     // active children (like the groundcache lookup) will work before
158     // tile manager has had a chance to update this node.
159     _node->setRange(0, 0.0, 10000.0);
160 }
161
162
163 // Destructor
164 FGTileEntry::~FGTileEntry ()
165 {
166 }
167
168 static void WorldCoordinate( osg::Matrix& obj_pos, double lat,
169                              double lon, double elev, double hdg )
170 {
171     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
172     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
173     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
174
175     // setup transforms
176     Point3D geod( lon_rad, lat_rad, elev );
177     Point3D world_pos = sgGeodToCart( geod );
178
179     double sin_lat = sin( lat_rad );
180     double cos_lat = cos( lat_rad );
181     double cos_lon = cos( lon_rad );
182     double sin_lon = sin( lon_rad );
183     double sin_hdg = sin( hdg_rad ) ;
184     double cos_hdg = cos( hdg_rad ) ;
185
186     obj_pos(0, 0) =  cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
187     obj_pos(0, 1) =  cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
188     obj_pos(0, 2) = -cos_hdg * cos_lat;
189     obj_pos(0, 3) =  SG_ZERO;
190
191     obj_pos(1, 0) = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
192     obj_pos(1, 1) = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
193     obj_pos(1, 2) =  sin_hdg * cos_lat;
194     obj_pos(1, 3) =  SG_ZERO;
195
196     obj_pos(2, 0) = cos_lat * cos_lon;
197     obj_pos(2, 1) = cos_lat * sin_lon;
198     obj_pos(2, 2) = sin_lat;
199     obj_pos(2, 3) =  SG_ZERO;
200
201     obj_pos(3, 0) = world_pos.x();
202     obj_pos(3, 1) = world_pos.y();
203     obj_pos(3, 2) = world_pos.z();
204     obj_pos(3, 3) = SG_ONE ;
205 }
206
207
208 // Free "n" leaf elements of an ssg tree.  returns the number of
209 // elements freed.  An empty branch node is considered a leaf.  This
210 // is intended to spread the load of freeing a complex tile out over
211 // several frames.
212 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
213     int num_deletes = b->getNumChildren();
214
215     b->removeChildren(0, b->getNumChildren());
216
217     return num_deletes;
218 }
219
220
221 // Clean up the memory used by this tile and delete the arrays used by
222 // ssg as well as the whole ssg branch
223 bool FGTileEntry::free_tile() {
224     int delete_size = 100;
225     SG_LOG( SG_TERRAIN, SG_DEBUG,
226             "FREEING TILE = (" << tile_bucket << ")" );
227
228     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
229     
230     if ( !(free_tracker & NODES) ) {
231         free_tracker |= NODES;
232     } else if ( !(free_tracker & VEC_PTRS) ) {
233         free_tracker |= VEC_PTRS;
234     } else if ( !(free_tracker & TERRA_NODE) ) {
235         // delete the terrain branch (this should already have been
236         // disconnected from the scene graph)
237         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
238         if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
239             _node = 0;
240             free_tracker |= TERRA_NODE;
241         }
242     } else if ( !(free_tracker & LIGHTMAPS) ) {
243         free_tracker |= LIGHTMAPS;
244     } else {
245         return true;
246     }
247
248     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
249
250     // if we fall down to here, we still have work todo, return false
251     return false;
252 }
253
254
255 // Update the ssg transform node for this tile so it can be
256 // properly drawn relative to our (0,0,0) point
257 void FGTileEntry::prep_ssg_node(float vis) {
258     if (!is_loaded())
259         return;
260     // visibility can change from frame to frame so we update the
261     // range selector cutoff's each time.
262     float bounding_radius = _node->getChild(0)->getBound().radius();
263     _node->setRange( 0, 0, vis + bounding_radius );
264 }
265
266 bool FGTileEntry::obj_load( const string& path,
267                             osg::Group *geometry, bool is_base )
268 {
269     bool use_random_objects =
270         fgGetBool("/sim/rendering/random-objects", true);
271         
272     bool use_random_vegetation = 
273         fgGetBool("/sim/rendering/random-vegetation", true);
274
275     // try loading binary format
276     osg::ref_ptr<SGReaderWriterBTGOptions> options
277         = new SGReaderWriterBTGOptions();
278     options->setMatlib(globals->get_matlib());
279     options->setCalcLights(is_base);
280     options->setUseRandomObjects(use_random_objects);
281     options->setUseRandomVegetation(use_random_vegetation);
282     osg::Node* node = osgDB::readNodeFile(path, options.get());
283     if (node)
284       geometry->addChild(node);
285
286     return node;
287 }
288
289
290 typedef enum {
291     OBJECT,
292     OBJECT_SHARED,
293     OBJECT_STATIC,
294     OBJECT_SIGN,
295     OBJECT_RUNWAY_SIGN
296 } object_type;
297
298
299 // storage class for deferred object processing in FGTileEntry::load()
300 struct Object {
301     Object(object_type t, const string& token, const SGPath& p, istream& in)
302         : type(t), path(p)
303     {
304         in >> name;
305         if (type != OBJECT)
306             in >> lon >> lat >> elev >> hdg;
307         in >> ::skipeol;
308
309         if (type == OBJECT)
310             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
311         else
312             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
313                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
314     }
315     object_type type;
316     string name;
317     SGPath path;
318     double lon, lat, elev, hdg;
319 };
320
321 // Work in progress... load the tile based entirely by name cuz that's
322 // what we'll want to do with the database pager.
323
324 osg::Node*
325 FGTileEntry::loadTileByName(const string& index_str,
326                             const string_list &path_list)
327 {
328     long tileIndex;
329     {
330         istringstream idxStream(index_str);
331         idxStream >> tileIndex;
332     }
333     SGBucket tile_bucket(tileIndex);
334     const string basePath = tile_bucket.gen_base_path();
335     
336     bool found_tile_base = false;
337
338     SGPath object_base;
339     vector<const Object*> objects;
340
341     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
342
343     // scan and parse all files and store information
344     for (unsigned int i = 0; i < path_list.size(); i++) {
345         // If we found a terrain tile in Terrain/, we have to process the
346         // Objects/ dir in the same group, too, before we can stop scanning.
347         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
348         // as marker.
349         if (path_list[i].empty()) {
350             if (found_tile_base)
351                 break;
352             else
353                 continue;
354         }
355
356         bool has_base = false;
357
358         SGPath tile_path = path_list[i];
359         tile_path.append(basePath);
360
361         SGPath basename = tile_path;
362         basename.append( index_str );
363
364         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
365
366
367         // Check for master .stg (scene terra gear) file
368         SGPath stg_name = basename;
369         stg_name.concat( ".stg" );
370
371         sg_gzifstream in( stg_name.str() );
372         if ( !in.is_open() )
373             continue;
374
375         while ( ! in.eof() ) {
376             string token;
377             in >> token;
378
379             if ( token.empty() || token[0] == '#' ) {
380                in >> ::skipeol;
381                continue;
382             }
383                             // Load only once (first found)
384             if ( token == "OBJECT_BASE" ) {
385                 string name;
386                 in >> name >> ::skipws;
387                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
388
389                 if (!found_tile_base) {
390                     found_tile_base = true;
391                     has_base = true;
392
393                     object_base = tile_path;
394                     object_base.append(name);
395
396                 } else
397                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
398
399                             // Load only if base is not in another file
400             } else if ( token == "OBJECT" ) {
401                 if (!found_tile_base || has_base)
402                     objects.push_back(new Object(OBJECT, token, tile_path, in));
403                 else {
404                     string name;
405                     in >> name >> ::skipeol;
406                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
407                             << name << "  (skipped)");
408                 }
409
410                             // Always OK to load
411             } else if ( token == "OBJECT_STATIC" ) {
412                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
413
414             } else if ( token == "OBJECT_SHARED" ) {
415                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
416
417             } else if ( token == "OBJECT_SIGN" ) {
418                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
419
420             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
421                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
422
423             } else {
424                 SG_LOG( SG_TERRAIN, SG_DEBUG,
425                         "Unknown token '" << token << "' in " << stg_name.str() );
426                 in >> ::skipws;
427             }
428         }
429     }
430
431
432     // obj_load() will generate ground lighting for us ...
433     osg::Group* new_tile = new osg::Group;
434
435     if (found_tile_base) {
436         // load tile if found ...
437         obj_load( object_base.str(), new_tile, true );
438
439     } else {
440         // ... or generate an ocean tile on the fly
441         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
442         if ( !SGGenTile( path_list[0], tile_bucket,
443                         globals->get_matlib(), new_tile ) ) {
444             SG_LOG( SG_TERRAIN, SG_ALERT,
445                     "Warning: failed to generate ocean tile!" );
446         }
447     }
448
449
450     // now that we have a valid center, process all the objects
451     for (unsigned int j = 0; j < objects.size(); j++) {
452         const Object *obj = objects[j];
453
454         if (obj->type == OBJECT) {
455             SGPath custom_path = obj->path;
456             custom_path.append( obj->name );
457             obj_load( custom_path.str(), new_tile, false );
458
459         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
460             // object loading is deferred to main render thread,
461             // but lets figure out the paths right now.
462             SGPath custom_path;
463             if ( obj->type == OBJECT_STATIC ) {
464                 custom_path = obj->path;
465             } else {
466                 custom_path = globals->get_fg_root();
467             }
468             custom_path.append( obj->name );
469
470             osg::Matrix obj_pos;
471             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
472
473             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
474             obj_trans->setMatrix( obj_pos );
475
476             // wire as much of the scene graph together as we can
477             new_tile->addChild( obj_trans );
478
479             osg::Node* model
480                 = FGTileMgr::loadTileModel(custom_path.str(),
481                                            obj->type == OBJECT_SHARED);
482             if (model)
483                 obj_trans->addChild(model);
484         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
485             // load the object itself
486             SGPath custom_path = obj->path;
487             custom_path.append( obj->name );
488
489             osg::Matrix obj_pos;
490             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
491
492             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
493             obj_trans->setMatrix( obj_pos );
494
495             osg::Node *custom_obj = 0;
496             if (obj->type == OBJECT_SIGN)
497                 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
498             else
499                 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
500
501             // wire the pieces together
502             if ( custom_obj != NULL ) {
503                 obj_trans -> addChild( custom_obj );
504             }
505             new_tile->addChild( obj_trans );
506
507         }
508         delete obj;
509     }
510     return new_tile;
511 }
512
513 void
514 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch )
515 {
516     // bump up the ref count so we can remove this later without
517     // having ssg try to free the memory.
518     terrain_branch->addChild( _node.get() );
519
520     SG_LOG( SG_TERRAIN, SG_DEBUG,
521             "connected a tile into scene graph.  _node = "
522             << _node.get() );
523     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
524             << _node->getNumParents() );
525 }
526
527
528 void
529 FGTileEntry::disconnect_ssg_nodes()
530 {
531     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
532
533     if (! is_loaded()) {
534         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
535     } else {
536         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
537     }
538         
539     // find the terrain branch parent
540     int pcount = _node->getNumParents();
541     if ( pcount > 0 ) {
542         // find the first parent (should only be one)
543         osg::Group *parent = _node->getParent( 0 ) ;
544         if( parent ) {
545             // disconnect the tile (we previously ref()'d it so it
546             // won't get freed now)
547             parent->removeChild( _node.get() );
548         } else {
549             // This should be impossible.
550             SG_LOG( SG_TERRAIN, SG_ALERT,
551                     "parent pointer is NULL!  Dying" );
552             exit(-1);
553         }
554     }
555 }
556
557 namespace
558 {
559
560 class ReaderWriterSTG : public osgDB::ReaderWriter {
561 public:
562     virtual const char* className() const;
563  
564     virtual bool acceptsExtension(const string& extension) const;
565
566     virtual ReadResult readNode(const string& fileName,
567                                 const osgDB::ReaderWriter::Options* options)
568         const;
569 };
570
571 const char* ReaderWriterSTG::className() const
572 {
573     return "STG Database reader";
574 }
575
576 bool ReaderWriterSTG::acceptsExtension(const string& extension) const
577 {
578     return (osgDB::equalCaseInsensitive(extension, "gz")
579             || osgDB::equalCaseInsensitive(extension, "stg"));   
580 }
581
582 //#define SLOW_PAGER 1
583 #ifdef SLOW_PAGER
584 #include <unistd.h>
585 #endif
586
587 osgDB::ReaderWriter::ReadResult
588 ReaderWriterSTG::readNode(const string& fileName,
589                           const osgDB::ReaderWriter::Options* options) const
590 {
591     string ext = osgDB::getLowerCaseFileExtension(fileName);
592     if(!acceptsExtension(ext))
593         return ReadResult::FILE_NOT_HANDLED;
594     string stgFileName;
595     if (osgDB::equalCaseInsensitive(ext, "gz")) {
596         stgFileName = osgDB::getNameLessExtension(fileName);
597         if (!acceptsExtension(
598                 osgDB::getLowerCaseFileExtension(stgFileName))) {
599             return ReadResult::FILE_NOT_HANDLED;
600         }
601     } else {
602         stgFileName = fileName;
603     }
604     osg::Node* result
605         = FGTileEntry::loadTileByName(osgDB::getNameLessExtension(stgFileName),
606                                       globals->get_fg_scenery());
607     // For debugging race conditions
608 #ifdef SLOW_PAGER
609     sleep(5);
610 #endif
611     if (result)
612         return result;           // Constructor converts to ReadResult
613     else
614         return ReadResult::FILE_NOT_HANDLED;
615 }
616
617 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
618 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
619 } // namespace