FlightGear next
scenery.cxx
Go to the documentation of this file.
1// scenery.cxx -- data structures and routines for managing scenery.
2//
3// Written by Curtis Olson, started May 1997.
4//
5// Copyright (C) 1997 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#include <config.h>
25#include <simgear/simgear_config.h>
26
27#include <stdio.h>
28#include <string.h>
29
30#include <osg/Camera>
31#include <osg/Transform>
32#include <osg/MatrixTransform>
33#include <osg/PositionAttitudeTransform>
34#include <osg/CameraView>
35#include <osg/LOD>
36
37#include <osgViewer/Viewer>
38
39#include <simgear/constants.h>
40#include <simgear/sg_inlines.h>
41#include <simgear/debug/logstream.hxx>
42#include <simgear/scene/tgdb/userdata.hxx>
43#include <simgear/scene/material/matlib.hxx>
44#include <simgear/scene/material/mat.hxx>
45#include <simgear/scene/util/SGNodeMasks.hxx>
46#include <simgear/scene/util/OsgMath.hxx>
47#include <simgear/scene/util/SGSceneUserData.hxx>
48#include <simgear/scene/model/CheckSceneryVisitor.hxx>
49#include <simgear/scene/sky/sky.hxx>
50#include <simgear/scene/util/SGSceneFeatures.hxx>
51
52#include <simgear/bvh/BVHNode.hxx>
53#include <simgear/bvh/BVHLineSegmentVisitor.hxx>
54#include <simgear/structure/commands.hxx>
55
56#include <Viewer/renderer.hxx>
57#include <Main/fg_props.hxx>
58#include <GUI/MouseCursor.hxx>
60
61#include "scenery.hxx"
62#include "terrain_stg.hxx"
63
64#ifdef ENABLE_GDAL
65#include "terrain_pgt.hxx"
66#endif
67
68using namespace flightgear;
69using namespace simgear;
70
71class FGGroundPickCallback : public SGPickCallback {
72public:
73 FGGroundPickCallback() : SGPickCallback(PriorityScenery)
74 { }
75
76 virtual bool buttonPressed( int button,
77 const osgGA::GUIEventAdapter&,
78 const Info& info )
79 {
80 // only on left mouse button
81 if (button != 0)
82 return false;
83
84 SGGeod geod = SGGeod::fromCart(info.wgs84);
85 SG_LOG( SG_TERRAIN, SG_INFO, "Got ground pick at " << geod );
86
87 SGPropertyNode *c = fgGetNode("/sim/input/click", true);
88 c->setDoubleValue("longitude-deg", geod.getLongitudeDeg());
89 c->setDoubleValue("latitude-deg", geod.getLatitudeDeg());
90 c->setDoubleValue("elevation-m", geod.getElevationM());
91 c->setDoubleValue("elevation-ft", geod.getElevationFt());
92 fgSetBool("/sim/signals/click", 1);
93
94 return true;
95 }
96};
97
98class FGSceneryIntersect : public osg::NodeVisitor {
99public:
100 FGSceneryIntersect(const SGLineSegmentd& lineSegment,
101 const osg::Node* skipNode) :
102 osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
103 _lineSegment(lineSegment),
104 _skipNode(skipNode),
105 _material(0),
106 _haveHit(false)
107 { }
108
109 bool getHaveHit() const
110 { return _haveHit; }
111 const SGLineSegmentd& getLineSegment() const
112 { return _lineSegment; }
113 const simgear::BVHMaterial* getMaterial() const
114 { return _material; }
115
116 virtual void apply(osg::Node& node)
117 {
118 if (&node == _skipNode)
119 return;
120 if (!testBoundingSphere(node.getBound()))
121 return;
122
123 addBoundingVolume(node);
124 }
125
126 virtual void apply(osg::Group& group)
127 {
128 if (&group == _skipNode)
129 return;
130 if (!testBoundingSphere(group.getBound()))
131 return;
132
133 traverse(group);
134 addBoundingVolume(group);
135 }
136
137 virtual void apply(osg::Transform& transform)
138 { handleTransform(transform); }
139 virtual void apply(osg::Camera& camera)
140 {
141 if (camera.getRenderOrder() != osg::Camera::NESTED_RENDER)
142 return;
143 handleTransform(camera);
144 }
145 virtual void apply(osg::CameraView& transform)
146 { handleTransform(transform); }
147 virtual void apply(osg::MatrixTransform& transform)
148 { handleTransform(transform); }
149 virtual void apply(osg::PositionAttitudeTransform& transform)
150 { handleTransform(transform); }
151
152private:
153 void handleTransform(osg::Transform& transform)
154 {
155 if (&transform == _skipNode)
156 return;
157 // Hmm, may be this needs to be refined somehow ...
158 if (transform.getReferenceFrame() != osg::Transform::RELATIVE_RF)
159 return;
160
161 if (!testBoundingSphere(transform.getBound()))
162 return;
163
164 osg::Matrix inverseMatrix;
165 if (!transform.computeWorldToLocalMatrix(inverseMatrix, this))
166 return;
167 osg::Matrix matrix;
168 if (!transform.computeLocalToWorldMatrix(matrix, this))
169 return;
170
171 SGLineSegmentd lineSegment = _lineSegment;
172 bool haveHit = _haveHit;
173 const simgear::BVHMaterial* material = _material;
174
175 _haveHit = false;
176 _lineSegment = lineSegment.transform(SGMatrixd(inverseMatrix.ptr()));
177
178 addBoundingVolume(transform);
179 traverse(transform);
180
181 if (_haveHit) {
182 _lineSegment = _lineSegment.transform(SGMatrixd(matrix.ptr()));
183 } else {
184 _lineSegment = lineSegment;
185 _material = material;
186 _haveHit = haveHit;
187 }
188 }
189
190 simgear::BVHNode* getNodeBoundingVolume(osg::Node& node)
191 {
192 SGSceneUserData* userData = SGSceneUserData::getSceneUserData(&node);
193 if (!userData)
194 return 0;
195 return userData->getBVHNode();
196 }
197 void addBoundingVolume(osg::Node& node)
198 {
199 simgear::BVHNode* bvNode = getNodeBoundingVolume(node);
200 if (!bvNode)
201 return;
202
203 // Find ground intersection on the bvh nodes
204 simgear::BVHLineSegmentVisitor lineSegmentVisitor(_lineSegment,
205 0/*startTime*/);
206 bvNode->accept(lineSegmentVisitor);
207 if (!lineSegmentVisitor.empty()) {
208 _lineSegment = lineSegmentVisitor.getLineSegment();
209 _material = lineSegmentVisitor.getMaterial();
210 _haveHit = true;
211 }
212 }
213
214 bool testBoundingSphere(const osg::BoundingSphere& bound) const
215 {
216 if (!bound.valid())
217 return false;
218
219 SGSphered sphere(toVec3d(toSG(bound._center)), bound._radius);
220 return intersects(_lineSegment, sphere);
221 }
222
223 SGLineSegmentd _lineSegment;
224 const osg::Node* _skipNode;
225
226 const simgear::BVHMaterial* _material;
227 bool _haveHit;
228};
229class FGScenery::TextureCacheListener : public SGPropertyChangeListener
230{
231protected:
232 const char* root_node_path = "/sim/rendering/texture-cache";
233public:
235 {
236 SGPropertyNode_ptr textureCacheNode = fgGetNode(root_node_path, true);
237 setupPropertyListener(textureCacheNode, "cache-enabled");
238 setupPropertyListener(textureCacheNode, "compress-transparent");
239 setupPropertyListener(textureCacheNode, "compress-solid");
240 setupPropertyListener(textureCacheNode, "compress");
241 }
242
244 {
245 SGPropertyNode_ptr maskNode = fgGetNode(root_node_path);
246 for (int i = 0; i < maskNode->nChildren(); ++i) {
247 maskNode->getChild(i)->removeChangeListener(this);
248 }
249 }
250
251 void setupPropertyListener(SGPropertyNode_ptr textureCacheNode, const char *node)
252 {
253 textureCacheNode->getChild(node, 0, true)->addChangeListener(this, true);
254 }
255
256 virtual void valueChanged(SGPropertyNode * node)
257 {
258 bool b = node->getBoolValue();
259 std::string name(node->getNameString());
260
261 if (name == "cache-enabled") {
262 SGSceneFeatures::instance()->setTextureCacheActive(b);
263 }
264 else if (name == "compress-transparent" || name == "compress") {
265 SGSceneFeatures::instance()->setTextureCacheCompressionActiveTransparent(b);
266 }
267 else if (name == "compress-solid" || name == "compress") {
268 SGSceneFeatures::instance()->setTextureCacheCompressionActive(b);
269 }
270 }
271};
272
273class FGScenery::ElevationMeshListener : public SGPropertyChangeListener
274{
275protected:
276 const char* root_node_path = "/scenery/elevation-mesh";
277public:
279 {
280 SGPropertyNode_ptr elevationMeshNode = fgGetNode(root_node_path, true);
281 setupPropertyListener(elevationMeshNode, "constraint-gap-m");
282 setupPropertyListener(elevationMeshNode, "sample-ratio");
283 setupPropertyListener(elevationMeshNode, "vertical-scale");
284 }
285
287 {
288 SGPropertyNode_ptr node = fgGetNode(root_node_path);
289 for (int i = 0; i < node->nChildren(); ++i) {
290 node->getChild(i)->removeChangeListener(this);
291 }
292 }
293
294 void setupPropertyListener(SGPropertyNode_ptr elevationMeshNode, const char *node)
295 {
296 elevationMeshNode->getChild(node, 0, true)->addChangeListener(this, true);
297 }
298
299 virtual void valueChanged(SGPropertyNode * node)
300 {
301 float f = node->getFloatValue();
302 std::string name(node->getNameString());
303
304 if (name == "constraint-gap-m") {
305 SGSceneFeatures::instance()->setVPBConstraintGap(f);
306 } else if (name == "sample-ratio") {
307 SGSceneFeatures::instance()->setVPBSampleRatio(f);
308 } else if (name == "vertical-scale") {
309 SGSceneFeatures::instance()->setVPBVerticalScale(f);
310 } else {
311 SG_LOG(SG_TERRAIN, SG_ALERT, "Unexpected property in listener " << node->getPath());
312 }
313 }
314};
315
316class FGScenery::ScenerySwitchListener : public SGPropertyChangeListener
317{
318public:
320 _scenery(scenery)
321 {
322 SGPropertyNode_ptr maskNode = fgGetNode("/sim/rendering/draw-mask", true);
323 maskNode->getChild("terrain", 0, true)->addChangeListener(this, true);
324 maskNode->getChild("models", 0, true)->addChangeListener(this, true);
325 maskNode->getChild("aircraft", 0, true)->addChangeListener(this, true);
326 maskNode->getChild("clouds", 0, true)->addChangeListener(this, true);
327
328 // legacy compatability option
329 fgGetNode("/sim/rendering/draw-otw")->addChangeListener(this);
330
331 // badly named property, this is what is set by --enable/disable-clouds
332 fgGetNode("/environment/clouds/status")->addChangeListener(this);
333
334 auto vpb_active = fgGetNode("/scenery/use-vpb");
335 if (vpb_active) {
336 vpb_active->addChangeListener(this);
337 SGSceneFeatures::instance()->setVPBActive(vpb_active->getBoolValue());
338 flightgear::addSentryTag("use-vpb", "yes");
339
340 } else {
341 flightgear::addSentryTag("use-vpb", "no");
342 }
343 }
344
346 {
347 SGPropertyNode_ptr maskNode = fgGetNode("/sim/rendering/draw-mask");
348 for (int i=0; i < maskNode->nChildren(); ++i) {
349 maskNode->getChild(i)->removeChangeListener(this);
350 }
351
352 fgGetNode("/sim/rendering/draw-otw")->removeChangeListener(this);
353 fgGetNode("/environment/clouds/status")->removeChangeListener(this);
354 fgGetNode("/scenery/use-vpb")->removeChangeListener(this);
355 }
356
357 virtual void valueChanged (SGPropertyNode * node)
358 {
359 bool b = node->getBoolValue();
360 std::string name(node->getNameString());
361
362 if (name == "use-vpb") {
363 SGSceneFeatures::instance()->setVPBActive(b);
364 } else if (name == "terrain") {
365 _scenery->scene_graph->setChildValue(_scenery->terrain_branch, b);
366 } else if (name == "models") {
367 _scenery->scene_graph->setChildValue(_scenery->models_branch, b);
368 } else if (name == "aircraft") {
369 _scenery->scene_graph->setChildValue(_scenery->aircraft_branch, b);
370 } else if (name == "clouds") {
371 // clouds live elsewhere in the scene, but we handle them here
372 globals->get_renderer()->getSky()->set_clouds_enabled(b);
373 } else if (name == "draw-otw") {
374 // legacy setting but let's keep it working
375 fgGetNode("/sim/rendering/draw-mask")->setBoolValue("terrain", b);
376 fgGetNode("/sim/rendering/draw-mask")->setBoolValue("models", b);
377 } else if (name == "status") {
378 fgGetNode("/sim/rendering/draw-mask")->setBoolValue("clouds", b);
379 }
380 }
381private:
382 FGScenery* _scenery;
383};
384
386
387// Scenery Management system
389 _listener(nullptr), _textureCacheListener(nullptr), _elevationMeshListener(nullptr)
390{
391 // keep reference to pager singleton, so it cannot be destroyed while FGScenery lives
393
394 // Initialise the state of the scene graph.
395 _inited = false;
396}
397
399{
400 delete _listener;
401 delete _textureCacheListener;
402}
403
404
405// Initialize the Scenery Management system
407 // Already set up.
408 if (_inited)
409 return;
410
411 // Scene graph root
412 scene_graph = new osg::Switch;
413 scene_graph->setName( "FGScenery" );
414
415 // Terrain branch
416 terrain_branch = new osg::Group;
417 terrain_branch->setName( "Terrain" );
418 scene_graph->addChild( terrain_branch.get() );
419 SGSceneUserData* userData;
420 userData = SGSceneUserData::getOrCreateSceneUserData(terrain_branch.get());
421 userData->setPickCallback(new FGGroundPickCallback);
422
423 models_branch = new osg::Group;
424 models_branch->setName( "Models" );
425 scene_graph->addChild( models_branch.get() );
426
427 aircraft_branch = new osg::Group;
428 aircraft_branch->setName( "Aircraft" );
429 scene_graph->addChild( aircraft_branch.get() );
430
431// choosing to make the interior branch a child of the main
432// aircraft group, for the moment. This simplifes places which
433// assume all aircraft elements are within this group - principally
434// FGODGuage::set_aircraft_texture.
435 interior_branch = new osg::Group;
436 interior_branch->setName( "Interior" );
437
438 osg::LOD* interiorLOD = new osg::LOD;
439 interiorLOD->addChild(interior_branch.get(), 0.0, 50.0);
440 aircraft_branch->addChild( interiorLOD );
441
442 // Set up the particle system as a directly accessible branch of the scene graph.
443 auto paricles = simgear::ParticlesGlobalManager::instance();
444 particles_branch = paricles->getCommonRoot();
445 particles_branch->setName("Particles");
446 scene_graph->addChild(particles_branch.get());
447 paricles->setSwitchNode(fgGetNode("/sim/rendering/particles", true));
448 paricles->initFromMainThread();
449
450 // Set up the precipitation system.
451 precipitation_branch = new osg::Group;
452 precipitation_branch->setName("Precipitation");
453 scene_graph->addChild(precipitation_branch.get());
454
455 // initialize the terrian based on selected engine
456 std::string engine = fgGetString("/sim/scenery/engine", "tilecache" );
457 SG_LOG( SG_TERRAIN, SG_INFO, "Selected scenery is " << engine );
458
459 if ( engine == "pagedLOD" ) {
460#ifdef ENABLE_GDAL
461 _terrain.reset(new FGPgtTerrain);
462#else
463 _terrain.reset(new FGStgTerrain);
464#endif
465 } else {
466 _terrain.reset(new FGStgTerrain);
467 }
468 _terrain->init( terrain_branch.get() );
469
470 _listener = new ScenerySwitchListener(this);
471 _textureCacheListener = new TextureCacheListener();
472 _elevationMeshListener = new ElevationMeshListener();
473
474 // Toggle the setup flag.
475 _inited = true;
476}
477
479{
480 flightgear::addSentryBreadcrumb("reloading scenery", "info");
481 fgSetBool("/sim/rendering/scenery-reload-required", false);
482 _terrain->reinit();
483}
484
486{
487 _terrain->shutdown();
488
489 scene_graph = NULL;
490 terrain_branch = NULL;
491 models_branch = NULL;
492 aircraft_branch = NULL;
493 particles_branch = NULL;
494 precipitation_branch = NULL;
495
496 _terrain.reset();
497
498 // Toggle the setup flag.
499 _inited = false;
500
501 simgear::ParticlesGlobalManager::clear();
502}
503
504
505void FGScenery::update(double dt)
506{
507 _terrain->update(dt);
508}
509
511}
512
514}
515
516bool
517FGScenery::get_cart_elevation_m(const SGVec3d& pos, double max_altoff,
518 double& alt,
519 const simgear::BVHMaterial** material,
520 const osg::Node* butNotFrom)
521{
522 return _terrain->get_cart_elevation_m(pos, max_altoff, alt,
523 material, butNotFrom);
524}
525
526bool
527FGScenery::get_elevation_m(const SGGeod& geod, double& alt,
528 const simgear::BVHMaterial** material,
529 const osg::Node* butNotFrom)
530{
531 return _terrain->get_elevation_m( geod, alt, material,
532 butNotFrom );
533}
534
535bool
536FGScenery::get_cart_ground_intersection(const SGVec3d& pos, const SGVec3d& dir,
537 SGVec3d& nearestHit,
538 const osg::Node* butNotFrom)
539{
540 return _terrain->get_cart_ground_intersection( pos, dir, nearestHit, butNotFrom );
541}
542
543bool FGScenery::scenery_available(const SGGeod& position, double range_m)
544{
545 return _terrain->scenery_available( position, range_m );
546}
547
548bool FGScenery::schedule_scenery(const SGGeod& position, double range_m, double duration)
549{
550 return _terrain->schedule_scenery( position, range_m, duration );
551}
552
554{
555 _terrain->materialLibChanged();
556}
557
558static osg::ref_ptr<SceneryPager> pager;
559
561{
562 if (!pager)
563 pager = new SceneryPager;
564 return pager.get();
565}
566
568{
569 pager = NULL;
570}
571
572
573// Register the subsystem.
574SGSubsystemMgr::Registrant<FGScenery> registrantFGScenery(
575 SGSubsystemMgr::DISPLAY,
576 {{"FGRenderer", SGSubsystemMgr::Dependency::NONSUBSYSTEM_HARD},
577 {"SGSky", SGSubsystemMgr::Dependency::NONSUBSYSTEM_HARD}});
#define i(x)
virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter &, const Info &info)
Definition scenery.cxx:76
virtual void apply(osg::Camera &camera)
Definition scenery.cxx:139
bool getHaveHit() const
Definition scenery.cxx:109
const simgear::BVHMaterial * getMaterial() const
Definition scenery.cxx:113
virtual void apply(osg::Group &group)
Definition scenery.cxx:126
virtual void apply(osg::Node &node)
Definition scenery.cxx:116
FGSceneryIntersect(const SGLineSegmentd &lineSegment, const osg::Node *skipNode)
Definition scenery.cxx:100
const SGLineSegmentd & getLineSegment() const
Definition scenery.cxx:111
virtual void apply(osg::MatrixTransform &transform)
Definition scenery.cxx:147
virtual void apply(osg::PositionAttitudeTransform &transform)
Definition scenery.cxx:149
virtual void apply(osg::CameraView &transform)
Definition scenery.cxx:145
virtual void apply(osg::Transform &transform)
Definition scenery.cxx:137
virtual void valueChanged(SGPropertyNode *node)
Definition scenery.cxx:299
void setupPropertyListener(SGPropertyNode_ptr elevationMeshNode, const char *node)
Definition scenery.cxx:294
virtual void valueChanged(SGPropertyNode *node)
Definition scenery.cxx:357
ScenerySwitchListener(FGScenery *scenery)
Definition scenery.cxx:319
void setupPropertyListener(SGPropertyNode_ptr textureCacheNode, const char *node)
Definition scenery.cxx:251
virtual void valueChanged(SGPropertyNode *node)
Definition scenery.cxx:256
void bind() override
Definition scenery.cxx:510
static void resetPagerSingleton()
Definition scenery.cxx:567
bool get_cart_elevation_m(const SGVec3d &pos, double max_altoff, double &elevation, const simgear::BVHMaterial **material, const osg::Node *butNotFrom=0)
Compute the elevation of the scenery below the cartesian point pos.
Definition scenery.cxx:517
bool schedule_scenery(const SGGeod &position, double range_m, double duration=0.0)
Definition scenery.cxx:548
bool get_cart_ground_intersection(const SGVec3d &start, const SGVec3d &dir, SGVec3d &nearestHit, const osg::Node *butNotFrom=0)
Compute the nearest intersection point of the line starting from start going in direction dir with th...
Definition scenery.cxx:536
void update(double dt) override
Definition scenery.cxx:505
void unbind() override
Definition scenery.cxx:513
bool get_elevation_m(const SGGeod &geod, double &alt, const simgear::BVHMaterial **material, const osg::Node *butNotFrom=0)
Compute the elevation of the scenery at geodetic latitude lat, geodetic longitude lon and not higher ...
Definition scenery.cxx:527
void materialLibChanged()
Definition scenery.cxx:553
friend class ElevationMeshListener
Definition scenery.hxx:72
bool scenery_available(const SGGeod &position, double range_m)
Returns true if scenery is available for the given lat, lon position within a range of range_m.
Definition scenery.cxx:543
static flightgear::SceneryPager * getPagerSingleton()
Definition scenery.cxx:560
void shutdown() override
Definition scenery.cxx:485
friend class ScenerySwitchListener
Definition scenery.hxx:53
void init() override
Definition scenery.cxx:406
friend class TextureCacheListener
Definition scenery.hxx:68
void reinit() override
Definition scenery.cxx:478
const char * name
std::string fgGetString(const char *name, const char *defaultValue)
Get a string value for a property.
Definition fg_props.cxx:556
FGGlobals * globals
Definition globals.cxx:142
FlightPlan.hxx - defines a full flight-plan object, including departure, cruise, arrival information ...
Definition Addon.cxx:53
void addSentryBreadcrumb(const std::string &, const std::string &)
void addSentryTag(const char *, const char *)
Definition AIBase.hxx:25
bool fgSetBool(char const *name, bool val)
Set a bool value for a property.
Definition proptest.cpp:24
SGPropertyNode * fgGetNode(const char *path, bool create)
Get a property node.
Definition proptest.cpp:27
SGSubsystemMgr::Registrant< FGScenery > registrantFGScenery(SGSubsystemMgr::DISPLAY, {{"FGRenderer", SGSubsystemMgr::Dependency::NONSUBSYSTEM_HARD}, {"SGSky", SGSubsystemMgr::Dependency::NONSUBSYSTEM_HARD}})
static osg::ref_ptr< SceneryPager > pager
Definition scenery.cxx:558