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