]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
47a72052c760819879c9284aeef08b7d540c7478
[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
27 #include <string>
28 #include <sstream>
29 #include <istream>
30
31 #include <osg/LOD>
32 #include <osg/MatrixTransform>
33 #include <osg/Math>
34 #include <osg/NodeCallback>
35
36 #include <osgDB/FileNameUtils>
37 #include <osgDB/ReaderWriter>
38 #include <osgDB/ReadFile>
39 #include <osgDB/Registry>
40
41 #include <simgear/bucket/newbucket.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/math/sg_geodesy.hxx>
44 #include <simgear/math/sg_random.h>
45 #include <simgear/misc/sgstream.hxx>
46 #include <simgear/scene/material/mat.hxx>
47 #include <simgear/scene/material/matlib.hxx>
48 #include <simgear/scene/model/ModelRegistry.hxx>
49 #include <simgear/scene/tgdb/apt_signs.hxx>
50 #include <simgear/scene/tgdb/obj.hxx>
51 #include <simgear/scene/util/OsgMath.hxx>
52 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
53
54 #include "ReaderWriterSPT.hxx"
55 #include "ReaderWriterSTG.hxx"
56 #include "SGOceanTile.hxx"
57 #include "TileEntry.hxx"
58
59 using std::string;
60 using namespace simgear;
61
62 ModelLoadHelper *TileEntry::_modelLoader=0;
63
64 namespace {
65 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
66 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
67
68 osgDB::RegisterReaderWriterProxy<ReaderWriterSPT> g_readerWriterSPTProxy;
69 ModelRegistryCallbackProxy<LoadOnlyCallback> g_sptCallbackProxy("spt");
70 }
71
72
73 // Constructor
74 TileEntry::TileEntry ( const SGBucket& b )
75     : tile_bucket( b ),
76       tileFileName(b.gen_index_str()),
77       _node( new osg::LOD ),
78       _priority(-FLT_MAX),
79       _current_view(false),
80       _time_expired(-1.0)
81 {
82     tileFileName += ".stg";
83     _node->setName(tileFileName);
84     // Give a default LOD range so that traversals that traverse
85     // active children (like the groundcache lookup) will work before
86     // tile manager has had a chance to update this node.
87     _node->setRange(0, 0.0, 10000.0);
88 }
89
90 TileEntry::TileEntry( const TileEntry& t )
91 : tile_bucket( t.tile_bucket ),
92   tileFileName(t.tileFileName),
93   _node( new osg::LOD ),
94   _priority(t._priority),
95   _current_view(t._current_view),
96   _time_expired(t._time_expired)
97 {
98     _node->setName(tileFileName);
99     // Give a default LOD range so that traversals that traverse
100     // active children (like the groundcache lookup) will work before
101     // tile manager has had a chance to update this node.
102     _node->setRange(0, 0.0, 10000.0);
103 }
104
105 // Destructor
106 TileEntry::~TileEntry ()
107 {
108 }
109
110 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
111                             double lon, double elev, double hdg)
112 {
113     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
114     obj_pos = makeZUpFrame(geod);
115     // hdg is not a compass heading, but a counter-clockwise rotation
116     // around the Z axis
117     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
118                                         0.0, 0.0, 1.0));
119 }
120
121
122 // Update the ssg transform node for this tile so it can be
123 // properly drawn relative to our (0,0,0) point
124 void TileEntry::prep_ssg_node(float vis) {
125     if (!is_loaded())
126         return;
127     // visibility can change from frame to frame so we update the
128     // range selector cutoff's each time.
129     float bounding_radius = _node->getChild(0)->getBound().radius();
130     _node->setRange( 0, 0, vis + bounding_radius );
131 }
132
133 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
134                          const osgDB::Options* options)
135 {
136     osg::Node* node = osgDB::readNodeFile(path, options);
137     if (node)
138       geometry->addChild(node);
139
140     return node != 0;
141 }
142
143
144 typedef enum {
145     OBJECT,
146     OBJECT_SHARED,
147     OBJECT_STATIC,
148     OBJECT_SIGN,
149     OBJECT_RUNWAY_SIGN
150 } object_type;
151
152
153 // storage class for deferred object processing in TileEntry::load()
154 struct Object {
155     Object(object_type t, const string& token, const SGPath& p,
156            std::istream& in)
157         : type(t), path(p)
158     {
159         in >> name;
160         if (type != OBJECT)
161             in >> lon >> lat >> elev >> hdg;
162         in >> ::skipeol;
163
164         if (type == OBJECT)
165             SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  " << name);
166         else
167             SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  " << name << "  lon=" <<
168                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
169     }
170     object_type type;
171     string name;
172     SGPath path;
173     double lon, lat, elev, hdg;
174 };
175
176 // Work in progress... load the tile based entirely by name cuz that's
177 // what we'll want to do with the database pager.
178
179 osg::Node*
180 TileEntry::loadTileByFileName(const string& fileName,
181                               const osgDB::Options* options)
182 {
183     std::string index_str = osgDB::getNameLessExtension(fileName);
184     index_str = osgDB::getSimpleFileName(index_str);
185
186     long tileIndex;
187     {
188         std::istringstream idxStream(index_str);
189         idxStream >> tileIndex;
190     }
191     SGBucket tile_bucket(tileIndex);
192     const string basePath = tile_bucket.gen_base_path();
193
194     bool found_tile_base = false;
195
196     SGPath object_base;
197     vector<const Object*> objects;
198
199     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
200
201     osgDB::FilePathList path_list=options->getDatabasePathList();
202     // Make sure we find the original filename here...
203     std::string filePath = osgDB::getFilePath(fileName);
204     if (!filePath.empty()) {
205         SGPath p(filePath);
206         p.append("..");
207         p.append("..");
208         path_list.push_front(p.str());
209     }
210
211     // scan and parse all files and store information
212     for (unsigned int i = 0; i < path_list.size(); i++) {
213         // If we found a terrain tile in Terrain/, we have to process the
214         // Objects/ dir in the same group, too, before we can stop scanning.
215         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
216         // as marker.
217
218         if (path_list[i].empty()) {
219             if (found_tile_base)
220                 break;
221             else
222                 continue;
223         }
224
225         bool has_base = false;
226
227         SGPath tile_path = path_list[i];
228         tile_path.append(basePath);
229
230         SGPath basename = tile_path;
231         basename.append( index_str );
232
233         SG_LOG( SG_TERRAIN, SG_DEBUG, "  Trying " << basename.str() );
234
235
236         // Check for master .stg (scene terra gear) file
237         SGPath stg_name = basename;
238         stg_name.concat( ".stg" );
239
240         sg_gzifstream in( stg_name.str() );
241         if ( !in.is_open() )
242             continue;
243
244         while ( ! in.eof() ) {
245             string token;
246             in >> token;
247
248             if ( token.empty() || token[0] == '#' ) {
249                in >> ::skipeol;
250                continue;
251             }
252                             // Load only once (first found)
253             if ( token == "OBJECT_BASE" ) {
254                 string name;
255                 in >> name >> ::skipws;
256                 SG_LOG( SG_TERRAIN, SG_BULK, "    " << token << " " << name );
257
258                 if (!found_tile_base) {
259                     found_tile_base = true;
260                     has_base = true;
261
262                     object_base = tile_path;
263                     object_base.append(name);
264
265                 } else
266                     SG_LOG(SG_TERRAIN, SG_BULK, "    (skipped)");
267
268                             // Load only if base is not in another file
269             } else if ( token == "OBJECT" ) {
270                 if (!found_tile_base || has_base)
271                     objects.push_back(new Object(OBJECT, token, tile_path, in));
272                 else {
273                     string name;
274                     in >> name >> ::skipeol;
275                     SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  "
276                             << name << "  (skipped)");
277                 }
278
279                             // Always OK to load
280             } else if ( token == "OBJECT_STATIC" ) {
281                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
282
283             } else if ( token == "OBJECT_SHARED" ) {
284                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
285
286             } else if ( token == "OBJECT_SIGN" ) {
287                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
288
289             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
290                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
291
292             } else {
293                 SG_LOG( SG_TERRAIN, SG_DEBUG,
294                         "Unknown token '" << token << "' in " << stg_name.str() );
295                 in >> ::skipws;
296             }
297         }
298     }
299
300     osg::ref_ptr<SGReaderWriterOptions> opt;
301     opt = SGReaderWriterOptions::copyOrCreate(options);
302
303     // obj_load() will generate ground lighting for us ...
304     osg::Group* new_tile = new osg::Group;
305
306     if (found_tile_base) {
307         // load tile if found ...
308         obj_load( object_base.str(), new_tile, true, opt.get());
309
310     } else {
311         // ... or generate an ocean tile on the fly
312         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
313
314         osg::Node* node = SGOceanTile(tile_bucket, opt->getMaterialLib());
315         if ( node ) {
316             new_tile->addChild(node);
317         } else {
318             SG_LOG( SG_TERRAIN, SG_ALERT,
319                     "Warning: failed to generate ocean tile!" );
320         }
321     }
322
323
324     // now that we have a valid center, process all the objects
325     for (unsigned int j = 0; j < objects.size(); j++) {
326         const Object *obj = objects[j];
327
328         if (obj->type == OBJECT) {
329             SGPath custom_path = obj->path;
330             custom_path.append( obj->name );
331             obj_load( custom_path.str(), new_tile, false, opt.get());
332
333         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
334             // object loading is deferred to main render thread,
335             // but lets figure out the paths right now.
336             SGPath custom_path;
337             if ( obj->type == OBJECT_STATIC ) {
338                 custom_path = obj->path;
339             } else {
340                 // custom_path = globals->get_fg_root();
341             }
342             custom_path.append( obj->name );
343
344             osg::Matrix obj_pos;
345             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
346
347             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
348             obj_trans->setDataVariance(osg::Object::STATIC);
349             obj_trans->setMatrix( obj_pos );
350
351             // wire as much of the scene graph together as we can
352             new_tile->addChild( obj_trans );
353
354             osg::Node* model = 0;
355             if(_modelLoader)
356                 model = _modelLoader->loadTileModel(custom_path.str(),
357                                                     obj->type == OBJECT_SHARED);
358             if (model)
359                 obj_trans->addChild(model);
360         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
361             // load the object itself
362             SGPath custom_path = obj->path;
363             custom_path.append( obj->name );
364
365             osg::Matrix obj_pos;
366             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
367
368             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
369             obj_trans->setDataVariance(osg::Object::STATIC);
370             obj_trans->setMatrix( obj_pos );
371
372             osg::Node *custom_obj = 0;
373             if (obj->type == OBJECT_SIGN)
374                 custom_obj = SGMakeSign(opt->getMaterialLib(), custom_path.str(), obj->name);
375             else
376                 custom_obj = SGMakeRunwaySign(opt->getMaterialLib(), custom_path.str(), obj->name);
377
378             // wire the pieces together
379             if ( custom_obj != NULL ) {
380                 obj_trans -> addChild( custom_obj );
381             }
382             new_tile->addChild( obj_trans );
383
384         }
385         delete obj;
386     }
387     return new_tile;
388 }
389
390 void
391 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
392 {
393     terrain_branch->addChild( _node.get() );
394
395     SG_LOG( SG_TERRAIN, SG_DEBUG,
396             "connected a tile into scene graph.  _node = "
397             << _node.get() );
398     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
399             << _node->getNumParents() );
400 }
401
402
403 void
404 TileEntry::removeFromSceneGraph()
405 {
406     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
407
408     if (! is_loaded()) {
409         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
410     } else {
411         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
412     }
413
414     // find the nodes branch parent
415     if ( _node->getNumParents() > 0 ) {
416         // find the first parent (should only be one)
417         osg::Group *parent = _node->getParent( 0 ) ;
418         if( parent ) {
419             parent->removeChild( _node.get() );
420         }
421     }
422 }
423
424 void
425 TileEntry::refresh()
426 {
427     osg::Group *parent = NULL;
428     // find the nodes branch parent
429     if ( _node->getNumParents() > 0 ) {
430         // find the first parent (should only be one)
431         parent = _node->getParent( 0 ) ;
432         if( parent ) {
433             parent->removeChild( _node.get() );
434         }
435     }
436     _node = new osg::LOD;
437     if (parent)
438         parent->addChild(_node.get());
439 }