]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/ReaderWriterSTG.cxx
Object names for STG groups / nodes.
[simgear.git] / simgear / scene / tgdb / ReaderWriterSTG.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
22 #ifdef HAVE_CONFIG_H
23 #  include <simgear_config.h>
24 #endif
25
26 #include "ReaderWriterSTG.hxx"
27
28 #include <osg/LOD>
29 #include <osg/MatrixTransform>
30 #include <osg/PagedLOD>
31 #include <osg/ProxyNode>
32 #include <osgUtil/LineSegmentIntersector>
33 #include <osgUtil/IntersectionVisitor>
34
35 #include <osgDB/FileNameUtils>
36 #include <osgDB/FileUtils>
37 #include <osgDB/Registry>
38 #include <osgDB/ReaderWriter>
39 #include <osgDB/ReadFile>
40
41 #include <simgear/math/SGGeometry.hxx>
42 #include <simgear/bucket/newbucket.hxx>
43 #include <simgear/debug/logstream.hxx>
44 #include <simgear/misc/sgstream.hxx>
45 #include <simgear/scene/util/OptionsReadFileCallback.hxx>
46 #include <simgear/scene/util/OsgMath.hxx>
47 #include <simgear/scene/util/RenderConstants.hxx>
48 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
49 #include <simgear/scene/tgdb/apt_signs.hxx>
50 #include <simgear/scene/tgdb/obj.hxx>
51
52 #include "SGOceanTile.hxx"
53
54 namespace simgear {
55
56 /// Ok, this is a hack - we do not exactly know if it's an airport or not.
57 /// This feature might also vanish again later. This is currently to
58 /// support testing an external ai component that just loads the the airports
59 /// and supports ground queries on only these areas.
60 static bool isAirportBtg(const std::string& name)
61 {
62     if (name.size() < 8)
63         return false;
64     if (name.substr(4, 8) != ".btg")
65         return false;
66     for (unsigned i = 0; i < 4; ++i) {
67         if (name[i] < 'A' || 'Z' < name[i])
68             continue;
69         return true;
70     }
71     return false;
72 }
73
74 static SGBucket bucketIndexFromFileName(const std::string& fileName)
75 {
76   // Extract the bucket from the filename
77   std::istringstream ss(osgDB::getNameLessExtension(fileName));
78   long index;
79   ss >> index;
80   if (ss.fail())
81     return SGBucket();
82   
83   return SGBucket(index);
84 }
85
86 struct ReaderWriterSTG::_ModelBin {
87     struct _Object {
88         std::string _errorLocation;
89         std::string _token;
90         std::string _name;
91         osg::ref_ptr<SGReaderWriterOptions> _options;
92     };
93     struct _ObjectStatic {
94         _ObjectStatic() : _agl(false), _proxy(false), _lon(0), _lat(0), _elev(0), _hdg(0), _pitch(0), _roll(0) { }
95         std::string _errorLocation;
96         std::string _token;
97         std::string _name;
98         bool _agl;
99         bool _proxy;
100         double _lon, _lat, _elev;
101         double _hdg, _pitch, _roll;
102         osg::ref_ptr<SGReaderWriterOptions> _options;
103     };
104     struct _Sign {
105         _Sign() : _agl(false), _lon(0), _lat(0), _elev(0), _hdg(0), _size(-1) { }
106         std::string _errorLocation;
107         std::string _token;
108         std::string _name;
109         bool _agl;
110         double _lon, _lat, _elev;
111         double _hdg;
112         int _size;
113     };
114
115     class DelayLoadReadFileCallback : public OptionsReadFileCallback {
116     public:
117         virtual osgDB::ReaderWriter::ReadResult
118         readNode(const std::string&, const osgDB::Options*)
119         {
120             osg::ref_ptr<osg::Group> group = new osg::Group;
121             group->setName("STG-group-A");
122             group->setDataVariance(osg::Object::STATIC);
123             
124             for (std::list<_ObjectStatic>::iterator i = _objectStaticList.begin(); i != _objectStaticList.end(); ++i) {
125                 osg::ref_ptr<osg::Node> node;
126                 if (i->_proxy)  {
127                     osg::ref_ptr<osg::ProxyNode> proxy = new osg::ProxyNode;
128                     proxy->setName("proxyNode");
129                     proxy->setLoadingExternalReferenceMode(osg::ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER);
130                     proxy->setFileName(0, i->_name);
131                     proxy->setDatabaseOptions(i->_options.get());
132                     node = proxy;
133                 } else {
134                     node = osgDB::readRefNodeFile(i->_name, i->_options.get());
135                     if (!node.valid()) {
136                         SG_LOG(SG_TERRAIN, SG_ALERT, i->_errorLocation << ": Failed to load "
137                                << i->_token << " '" << i->_name << "'");
138                         continue;
139                     }
140                 }
141                 if (SGPath(i->_name).lower_extension() == "ac")
142                     node->setNodeMask(~simgear::MODELLIGHT_BIT);
143                 
144                 osg::Matrix matrix;
145                 matrix = makeZUpFrame(SGGeod::fromDegM(i->_lon, i->_lat, i->_elev));
146                 matrix.preMultRotate(osg::Quat(SGMiscd::deg2rad(i->_hdg), osg::Vec3(0, 0, 1)));
147                 matrix.preMultRotate(osg::Quat(SGMiscd::deg2rad(i->_pitch), osg::Vec3(0, 1, 0)));
148                 matrix.preMultRotate(osg::Quat(SGMiscd::deg2rad(i->_roll), osg::Vec3(1, 0, 0)));
149                 
150                 osg::MatrixTransform* matrixTransform;
151                 matrixTransform = new osg::MatrixTransform(matrix);
152                 matrixTransform->setName("positionStaticObject");
153                 matrixTransform->setDataVariance(osg::Object::STATIC);
154                 matrixTransform->addChild(node.get());
155                 group->addChild(matrixTransform);
156             }
157             
158             simgear::AirportSignBuilder signBuilder(_options->getMaterialLib(), _bucket.get_center());
159             for (std::list<_Sign>::iterator i = _signList.begin(); i != _signList.end(); ++i)
160                 signBuilder.addSign(SGGeod::fromDegM(i->_lon, i->_lat, i->_elev), i->_hdg, i->_name, i->_size);
161             if (signBuilder.getSignsGroup())
162                 group->addChild(signBuilder.getSignsGroup());
163             
164             return group.release();
165         }
166         
167         std::list<_ObjectStatic> _objectStaticList;
168         std::list<_Sign> _signList;
169         
170         /// The original options to use for this bunch of models
171         osg::ref_ptr<SGReaderWriterOptions> _options;
172         SGBucket _bucket;
173     };
174     
175     _ModelBin() :
176         _foundBase(false)
177     { }
178
179     SGReaderWriterOptions* sharedOptions(const std::string& filePath, const osgDB::Options* options)
180     {
181         osg::ref_ptr<SGReaderWriterOptions> sharedOptions;
182         sharedOptions = SGReaderWriterOptions::copyOrCreate(options);
183         sharedOptions->getDatabasePathList().clear();
184
185         SGPath path = filePath;
186         path.append(".."); path.append(".."); path.append("..");
187         sharedOptions->getDatabasePathList().push_back(path.str());
188         std::string fg_root = options->getPluginStringData("SimGear::FG_ROOT");
189         sharedOptions->getDatabasePathList().push_back(fg_root);
190
191         // TODO how should we handle this for OBJECT_SHARED?
192         sharedOptions->setModelData
193         (
194             sharedOptions->getModelData()
195           ? sharedOptions->getModelData()->clone()
196           : 0
197         );
198
199         return sharedOptions.release();
200     }
201     SGReaderWriterOptions* staticOptions(const std::string& filePath, const osgDB::Options* options)
202     {
203         osg::ref_ptr<SGReaderWriterOptions> staticOptions;
204         staticOptions = SGReaderWriterOptions::copyOrCreate(options);
205         staticOptions->getDatabasePathList().clear();
206
207         staticOptions->getDatabasePathList().push_back(filePath);
208         staticOptions->setObjectCacheHint(osgDB::Options::CACHE_NONE);
209
210         // Every model needs its own SGModelData to ensure load/unload is
211         // working properly
212         staticOptions->setModelData
213         (
214             staticOptions->getModelData()
215           ? staticOptions->getModelData()->clone()
216           : 0
217         );
218
219         return staticOptions.release();
220     }
221
222     double elevation(osg::Group& group, const SGGeod& geod)
223     {
224         SGVec3d start = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, 10000));
225         SGVec3d end = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, -1000));
226         
227         osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector;
228         intersector = new osgUtil::LineSegmentIntersector(toOsg(start), toOsg(end));
229         osgUtil::IntersectionVisitor visitor(intersector.get());
230         group.accept(visitor);
231         
232         if (!intersector->containsIntersections())
233             return 0;
234         
235         SGVec3d cart = toSG(intersector->getFirstIntersection().getWorldIntersectPoint());
236         return SGGeod::fromCart(cart).getElevationM();
237     }
238     
239     bool read(const std::string& absoluteFileName, const osgDB::Options* options)
240     {
241         if (absoluteFileName.empty())
242             return false;
243
244         sg_gzifstream stream(absoluteFileName);
245         if (!stream.is_open())
246             return false;
247
248         SG_LOG(SG_TERRAIN, SG_INFO, "Loading stg file " << absoluteFileName);
249     
250         std::string filePath = osgDB::getFilePath(absoluteFileName);
251
252         // do only load airport btg files.
253         bool onlyAirports = options->getPluginStringData("SimGear::FG_ONLY_AIRPORTS") == "ON";
254         // do only load terrain btg files
255         bool onlyTerrain = options->getPluginStringData("SimGear::FG_ONLY_TERRAIN") == "ON";
256         
257         while (!stream.eof()) {
258             // read a line
259             std::string line;
260             std::getline(stream, line);
261             
262             // strip comments
263             std::string::size_type hash_pos = line.find('#');
264             if (hash_pos != std::string::npos)
265                 line.resize(hash_pos);
266             
267             // and process further
268             std::stringstream in(line);
269             
270             std::string token;
271             in >> token;
272             
273             // No comment
274             if (token.empty())
275                 continue;
276             
277             // Then there is always a name
278             std::string name;
279             in >> name;
280             
281             SGPath path = filePath;
282             path.append(name);
283             
284             if (token == "OBJECT_BASE") {
285                 // Load only once (first found)
286                 SG_LOG( SG_TERRAIN, SG_BULK, "    " << token << " " << name );
287                 _foundBase = true;
288                 if (!onlyAirports || isAirportBtg(name)) {
289                     _Object obj;
290                     obj._errorLocation = absoluteFileName;
291                     obj._token = token;
292                     obj._name = path.str();
293                     obj._options = staticOptions(filePath, options);
294                     _objectList.push_back(obj);
295                 }
296                 
297             } else if (token == "OBJECT") {
298                 if (!onlyAirports || isAirportBtg(name)) {
299                     _Object obj;
300                     obj._errorLocation = absoluteFileName;
301                     obj._token = token;
302                     obj._name = path.str();
303                     obj._options = staticOptions(filePath, options);
304                     _objectList.push_back(obj);
305                 }
306                 
307             } else {
308                 // Always OK to load
309                 if (token == "OBJECT_STATIC" || token == "OBJECT_STATIC_AGL") {
310                     if (!onlyTerrain) {
311                         osg::ref_ptr<SGReaderWriterOptions> opt;
312                         opt = staticOptions(filePath, options);
313                         if (SGPath(name).lower_extension() == "ac")
314                             opt->setInstantiateEffects(true);
315                         else
316                             opt->setInstantiateEffects(false);
317                         _ObjectStatic obj;
318                         obj._errorLocation = absoluteFileName;
319                         obj._token = token;
320                         obj._name = name;
321                         obj._agl = (token == "OBJECT_STATIC_AGL");
322                         obj._proxy = true;
323                         in >> obj._lon >> obj._lat >> obj._elev >> obj._hdg >> obj._pitch >> obj._roll;
324                         obj._options = opt;
325                         _objectStaticList.push_back(obj);
326                     }
327                         
328                 } else if (token == "OBJECT_SHARED" || token == "OBJECT_SHARED_AGL") {
329                     if (!onlyTerrain) {
330                         osg::ref_ptr<SGReaderWriterOptions> opt;
331                         opt = sharedOptions(filePath, options);
332                         if (SGPath(name).lower_extension() == "ac")
333                             opt->setInstantiateEffects(true);
334                         else
335                             opt->setInstantiateEffects(false);
336                         _ObjectStatic obj;
337                         obj._errorLocation = absoluteFileName;
338                         obj._token = token;
339                         obj._name = name;
340                         obj._agl = (token == "OBJECT_SHARED_AGL");
341                         obj._proxy = false;
342                         in >> obj._lon >> obj._lat >> obj._elev >> obj._hdg >> obj._pitch >> obj._roll;
343                         obj._options = opt;
344                         _objectStaticList.push_back(obj);
345                     }
346
347                 } else if (token == "OBJECT_SIGN" || token == "OBJECT_SIGN_AGL") {
348                     if (!onlyTerrain) {
349                         _Sign sign;
350                         sign._token = token;
351                         sign._name = name;
352                         sign._agl = (token == "OBJECT_SIGN_AGL");
353                         in >> sign._lon >> sign._lat >> sign._elev >> sign._hdg >> sign._size;
354                         _signList.push_back(sign);
355                     }
356
357                 } else {
358                     SG_LOG( SG_TERRAIN, SG_ALERT, absoluteFileName
359                             << ": Unknown token '" << token << "'" );
360                 }
361             }
362         }
363         
364         return true;
365     }
366     
367     osg::Node* load(const SGBucket& bucket, const osgDB::Options* opt)
368     {
369         osg::ref_ptr<SGReaderWriterOptions> options;
370         options = SGReaderWriterOptions::copyOrCreate(opt);
371
372         osg::ref_ptr<osg::Group> terrainGroup = new osg::Group;
373         terrainGroup->setDataVariance(osg::Object::STATIC);
374         terrainGroup->setName("terrain");
375         
376         if (_foundBase) {
377             for (std::list<_Object>::iterator i = _objectList.begin(); i != _objectList.end(); ++i) {
378                 osg::ref_ptr<osg::Node> node;
379                 node = osgDB::readRefNodeFile(i->_name, i->_options.get());
380                 if (!node.valid()) {
381                     SG_LOG(SG_TERRAIN, SG_ALERT, i->_errorLocation << ": Failed to load "
382                            << i->_token << " '" << i->_name << "'");
383                     continue;
384                 }
385                 terrainGroup->addChild(node.get());
386             }
387         } else {
388             SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
389             
390             osg::Node* node = SGOceanTile(bucket, options->getMaterialLib());
391             if (node) {
392                 node->setName("SGOceanTile");
393                 terrainGroup->addChild(node);
394             } else {
395                 SG_LOG( SG_TERRAIN, SG_ALERT,
396                         "Warning: failed to generate ocean tile!" );
397             }
398         }
399
400         for (std::list<_ObjectStatic>::iterator i = _objectStaticList.begin(); i != _objectStaticList.end(); ++i) {
401             if (!i->_agl)
402                 continue;
403             i->_elev += elevation(*terrainGroup, SGGeod::fromDeg(i->_lon, i->_lat));
404         }
405         
406         for (std::list<_Sign>::iterator i = _signList.begin(); i != _signList.end(); ++i) {
407             if (!i->_agl)
408                 continue;
409             i->_elev += elevation(*terrainGroup, SGGeod::fromDeg(i->_lon, i->_lat));
410         }
411
412         if (_objectStaticList.empty() && _signList.empty()) {
413             // The simple case, just return the terrain group
414             return terrainGroup.release();
415         } else {
416             osg::PagedLOD* pagedLOD = new osg::PagedLOD;
417             pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
418             pagedLOD->setName("pagedObjectLOD");
419             
420             // This should be visible in any case.
421             // If this is replaced by some lower level of detail, the parent LOD node handles this.
422             pagedLOD->addChild(terrainGroup, 0, std::numeric_limits<float>::max());
423
424             // we just need to know about the read file callback that itself holds the data
425             osg::ref_ptr<DelayLoadReadFileCallback> readFileCallback = new DelayLoadReadFileCallback;
426             readFileCallback->_objectStaticList = _objectStaticList;
427             readFileCallback->_signList = _signList;
428             readFileCallback->_options = options;
429             readFileCallback->_bucket = bucket;
430             osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
431             callbackOptions->setReadFileCallback(readFileCallback.get());
432             pagedLOD->setDatabaseOptions(callbackOptions.get());
433             
434             pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
435             pagedLOD->setRange(pagedLOD->getNumChildren(), 0, 30000);
436             
437             return pagedLOD;
438         }
439     }
440     
441     bool _foundBase;
442     std::list<_Object> _objectList;
443     std::list<_ObjectStatic> _objectStaticList;
444     std::list<_Sign> _signList;
445 };
446
447 ReaderWriterSTG::ReaderWriterSTG()
448 {
449     supportsExtension("stg", "SimGear stg database format");
450 }
451
452 ReaderWriterSTG::~ReaderWriterSTG()
453 {
454 }
455
456 const char* ReaderWriterSTG::className() const
457 {
458     return "STG Database reader";
459 }
460
461 osgDB::ReaderWriter::ReadResult
462 ReaderWriterSTG::readNode(const std::string& fileName, const osgDB::Options* options) const
463 {
464     _ModelBin modelBin;
465     SGBucket bucket(bucketIndexFromFileName(fileName));
466
467     // We treat 123.stg different than ./123.stg.
468     // The difference is that ./123.stg as well as any absolute path
469     // really loads the given stg file and only this.
470     // In contrast 123.stg uses the search paths to load a set of stg
471     // files spread across the scenery directories.
472     if (osgDB::getSimpleFileName(fileName) != fileName) {
473         if (!modelBin.read(fileName, options))
474             return ReadResult::FILE_NOT_FOUND;
475     } else {
476         // For stg meta files, we need options for the search path.
477         if (!options)
478             return ReadResult::FILE_NOT_FOUND;
479         
480         SG_LOG(SG_TERRAIN, SG_INFO, "Loading tile " << fileName);
481         
482         std::string basePath = bucket.gen_base_path();
483         
484         // Stop scanning once an object base is found
485         // This is considered a meta file, so apply the scenery path search
486         const osgDB::FilePathList& filePathList = options->getDatabasePathList();
487         for (osgDB::FilePathList::const_iterator i = filePathList.begin();
488              i != filePathList.end() && !modelBin._foundBase; ++i) {
489             SGPath objects(*i);
490             objects.append("Objects");
491             objects.append(basePath);
492             objects.append(fileName);
493             modelBin.read(objects.str(), options);
494             
495             SGPath terrain(*i);
496             terrain.append("Terrain");
497             terrain.append(basePath);
498             terrain.append(fileName);
499             modelBin.read(terrain.str(), options);
500         }
501     }
502
503     return modelBin.load(bucket, options);
504 }
505
506 }