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