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