]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/scenery.cxx
Fixes #397: YASim aircraft start at >32000ft instead of runway
[flightgear.git] / src / Scenery / scenery.cxx
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 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <string.h>
30
31 #include <osg/Camera>
32 #include <osg/Transform>
33 #include <osg/MatrixTransform>
34 #include <osg/PositionAttitudeTransform>
35 #include <osg/CameraView>
36 #include <osgViewer/Viewer>
37
38 #include <simgear/constants.h>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/scene/tgdb/userdata.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42 #include <simgear/scene/util/SGNodeMasks.hxx>
43 #include <simgear/scene/util/SGSceneUserData.hxx>
44 #include <simgear/scene/model/CheckSceneryVisitor.hxx>
45 #include <simgear/scene/bvh/BVHNode.hxx>
46 #include <simgear/scene/bvh/BVHLineSegmentVisitor.hxx>
47
48 #include <Main/renderer.hxx>
49 #include <Main/fg_props.hxx>
50
51 #include "tilemgr.hxx"
52 #include "scenery.hxx"
53
54 using namespace flightgear;
55 using namespace simgear;
56
57 class FGGroundPickCallback : public SGPickCallback {
58 public:
59   virtual bool buttonPressed(int button, const Info& info)
60   {
61     // only on left mouse button
62     if (button != 0)
63       return false;
64
65     SGGeod geod = SGGeod::fromCart(info.wgs84);
66     SG_LOG( SG_TERRAIN, SG_INFO, "Got ground pick at " << geod );
67
68     SGPropertyNode *c = fgGetNode("/sim/input/click", true);
69     c->setDoubleValue("longitude-deg", geod.getLongitudeDeg());
70     c->setDoubleValue("latitude-deg", geod.getLatitudeDeg());
71     c->setDoubleValue("elevation-m", geod.getElevationM());
72     c->setDoubleValue("elevation-ft", geod.getElevationFt());
73     fgSetBool("/sim/signals/click", 1);
74
75     return true;
76   }
77 };
78
79 class FGSceneryIntersect : public osg::NodeVisitor {
80 public:
81     FGSceneryIntersect(const SGLineSegmentd& lineSegment,
82                        const osg::Node* skipNode) :
83         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
84         _lineSegment(lineSegment),
85         _skipNode(skipNode),
86         _material(0),
87         _haveHit(false)
88     { }
89
90     bool getHaveHit() const
91     { return _haveHit; }
92     const SGLineSegmentd& getLineSegment() const
93     { return _lineSegment; }
94     const SGMaterial* getMaterial() const
95     { return _material; }
96
97     virtual void apply(osg::Node& node)
98     {
99         if (&node == _skipNode)
100             return;
101         if (!testBoundingSphere(node.getBound()))
102             return;
103
104         addBoundingVolume(node);
105     }
106
107     virtual void apply(osg::Group& group)
108     {
109         if (&group == _skipNode)
110             return;
111         if (!testBoundingSphere(group.getBound()))
112             return;
113
114         traverse(group);
115         addBoundingVolume(group);
116     }
117
118     virtual void apply(osg::Transform& transform)
119     { handleTransform(transform); }
120     virtual void apply(osg::Camera& camera)
121     {
122         if (camera.getRenderOrder() != osg::Camera::NESTED_RENDER)
123             return;
124         handleTransform(camera);
125     }
126     virtual void apply(osg::CameraView& transform)
127     { handleTransform(transform); }
128     virtual void apply(osg::MatrixTransform& transform)
129     { handleTransform(transform); }
130     virtual void apply(osg::PositionAttitudeTransform& transform)
131     { handleTransform(transform); }
132
133 private:
134     void handleTransform(osg::Transform& transform)
135     {
136         if (&transform == _skipNode)
137             return;
138         // Hmm, may be this needs to be refined somehow ...
139         if (transform.getReferenceFrame() != osg::Transform::RELATIVE_RF)
140             return;
141
142         if (!testBoundingSphere(transform.getBound()))
143             return;
144
145         osg::Matrix inverseMatrix;
146         if (!transform.computeWorldToLocalMatrix(inverseMatrix, this))
147             return;
148         osg::Matrix matrix;
149         if (!transform.computeLocalToWorldMatrix(matrix, this))
150             return;
151
152         SGLineSegmentd lineSegment = _lineSegment;
153         bool haveHit = _haveHit;
154         const SGMaterial* material = _material;
155
156         _haveHit = false;
157         _lineSegment = lineSegment.transform(SGMatrixd(inverseMatrix.ptr()));
158
159         addBoundingVolume(transform);
160         traverse(transform);
161
162         if (_haveHit) {
163             _lineSegment = _lineSegment.transform(SGMatrixd(matrix.ptr()));
164         } else {
165             _lineSegment = lineSegment;
166             _material = material;
167             _haveHit = haveHit;
168         }
169     }
170
171     simgear::BVHNode* getNodeBoundingVolume(osg::Node& node)
172     {
173         SGSceneUserData* userData = SGSceneUserData::getSceneUserData(&node);
174         if (!userData)
175             return 0;
176         return userData->getBVHNode();
177     }
178     void addBoundingVolume(osg::Node& node)
179     {
180         simgear::BVHNode* bvNode = getNodeBoundingVolume(node);
181         if (!bvNode)
182             return;
183
184         // Find ground intersection on the bvh nodes
185         simgear::BVHLineSegmentVisitor lineSegmentVisitor(_lineSegment,
186                                                           0/*startTime*/);
187         bvNode->accept(lineSegmentVisitor);
188         if (!lineSegmentVisitor.empty()) {
189             _lineSegment = lineSegmentVisitor.getLineSegment();
190             _material = lineSegmentVisitor.getMaterial();
191             _haveHit = true;
192         }
193     }
194
195     bool testBoundingSphere(const osg::BoundingSphere& bound) const
196     {
197         if (!bound.valid())
198             return false;
199
200         SGSphered sphere(toVec3d(toSG(bound._center)), bound._radius);
201         return intersects(_lineSegment, sphere);
202     }
203
204     SGLineSegmentd _lineSegment;
205     const osg::Node* _skipNode;
206
207     const SGMaterial* _material;
208     bool _haveHit;
209 };
210
211 // Scenery Management system
212 FGScenery::FGScenery()
213 {
214     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing scenery subsystem" );
215 }
216
217 FGScenery::~FGScenery() {
218 }
219
220
221 // Initialize the Scenery Management system
222 void FGScenery::init() {
223     // Scene graph root
224     scene_graph = new osg::Group;
225     scene_graph->setName( "Scene" );
226
227     // Terrain branch
228     terrain_branch = new osg::Group;
229     terrain_branch->setName( "Terrain" );
230     scene_graph->addChild( terrain_branch.get() );
231     SGSceneUserData* userData;
232     userData = SGSceneUserData::getOrCreateSceneUserData(terrain_branch.get());
233     userData->setPickCallback(new FGGroundPickCallback);
234
235     models_branch = new osg::Group;
236     models_branch->setName( "Models" );
237     scene_graph->addChild( models_branch.get() );
238
239     aircraft_branch = new osg::Group;
240     aircraft_branch->setName( "Aircraft" );
241     scene_graph->addChild( aircraft_branch.get() );
242
243     // Initials values needed by the draw-time object loader
244     sgUserDataInit( globals->get_props() );
245 }
246
247
248 void FGScenery::update(double dt) {
249 }
250
251
252 void FGScenery::bind() {
253 }
254
255
256 void FGScenery::unbind() {
257 }
258
259 bool
260 FGScenery::get_cart_elevation_m(const SGVec3d& pos, double max_altoff,
261                                 double& alt, const SGMaterial** material,
262                                 const osg::Node* butNotFrom)
263 {
264   SGGeod geod = SGGeod::fromCart(pos);
265   geod.setElevationM(geod.getElevationM() + max_altoff);
266   return get_elevation_m(geod, alt, material, butNotFrom);
267 }
268
269 bool
270 FGScenery::get_elevation_m(const SGGeod& geod, double& alt,
271                            const SGMaterial** material,
272                            const osg::Node* butNotFrom)
273 {
274   SGVec3d start = SGVec3d::fromGeod(geod);
275
276   SGGeod geodEnd = geod;
277   geodEnd.setElevationM(SGMiscd::min(geod.getElevationM() - 10, -10000));
278   SGVec3d end = SGVec3d::fromGeod(geodEnd);
279
280   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
281   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
282   get_scene_graph()->accept(intersectVisitor);
283
284   if (!intersectVisitor.getHaveHit())
285       return false;
286
287   geodEnd = SGGeod::fromCart(intersectVisitor.getLineSegment().getEnd());
288   alt = geodEnd.getElevationM();
289   if (material)
290       *material = intersectVisitor.getMaterial();
291
292   return true;
293 }
294
295 bool
296 FGScenery::get_cart_ground_intersection(const SGVec3d& pos, const SGVec3d& dir,
297                                         SGVec3d& nearestHit,
298                                         const osg::Node* butNotFrom)
299 {
300   // We assume that starting positions in the center of the earth are invalid
301   if ( norm1(pos) < 1 )
302     return false;
303
304   // Make really sure the direction is normalized, is really cheap compared to
305   // computation of ground intersection.
306   SGVec3d start = pos;
307   SGVec3d end = start + 1e5*normalize(dir); // FIXME visibility ???
308
309   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
310   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
311   get_scene_graph()->accept(intersectVisitor);
312
313   if (!intersectVisitor.getHaveHit())
314       return false;
315
316   nearestHit = intersectVisitor.getLineSegment().getEnd();
317   return true;
318 }
319
320 bool FGScenery::scenery_available(const SGGeod& position, double range_m)
321 {
322   if(globals->get_tile_mgr()->schedule_scenery(position, range_m, 0.0))
323   {
324     double elev;
325     if (!get_elevation_m(SGGeod::fromGeodM(position, SG_MAX_ELEVATION_M), elev, 0, 0))
326       return false;
327     SGVec3f p = SGVec3f::fromGeod(SGGeod::fromGeodM(position, elev));
328     osg::FrameStamp* framestamp
329             = globals->get_renderer()->getViewer()->getFrameStamp();
330     simgear::CheckSceneryVisitor csnv(getPagerSingleton(), toOsg(p), range_m, framestamp);
331     // currently the PagedLODs will not be loaded by the DatabasePager
332     // while the splashscreen is there, so CheckSceneryVisitor force-loads
333     // missing objects in the main thread
334     get_scene_graph()->accept(csnv);
335     if(!csnv.isLoaded())
336         return false;
337     return true;
338   }
339   return false;
340 }
341
342 SceneryPager* FGScenery::getPagerSingleton()
343 {
344     static osg::ref_ptr<SceneryPager> pager = new SceneryPager;
345     return pager.get();
346 }
347