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