]> git.mxchange.org Git - flightgear.git/blob - src/Main/CameraGroup.cxx
d08948b140849a4b73c6d82262ed6e7cf9c8ebc4
[flightgear.git] / src / Main / CameraGroup.cxx
1 // Copyright (C) 2008  Tim Moore
2 //
3 // This program is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU General Public License as
5 // published by the Free Software Foundation; either version 2 of the
6 // License, or (at your option) any later version.
7 //
8 // This program is distributed in the hope that it will be useful, but
9 // WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 #include "CameraGroup.hxx"
18
19 #include "globals.hxx"
20 #include "renderer.hxx"
21 #include "FGEventHandler.hxx"
22 #include "WindowBuilder.hxx"
23 #include "WindowSystemAdapter.hxx"
24 #include <simgear/props/props.hxx>
25 #include <simgear/scene/util/RenderConstants.hxx>
26
27 #include <algorithm>
28 #include <cstring>
29 #include <string>
30
31 #include <osg/Camera>
32 #include <osg/GraphicsContext>
33 #include <osg/Math>
34 #include <osg/Matrix>
35 #include <osg/Quat>
36 #include <osg/Vec3d>
37 #include <osg/Viewport>
38
39 #include <osgUtil/IntersectionVisitor>
40
41 #include <osgViewer/GraphicsWindow>
42
43 namespace flightgear
44 {
45 using namespace osg;
46
47 using std::strcmp;
48 using std::string;
49
50 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
51
52 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
53     _viewer(viewer)
54 {
55 }
56
57 }
58
59 namespace
60 {
61 using namespace osg;
62
63 // Given a projection matrix, return a new one with the same frustum
64 // sides and new near / far values.
65
66 void makeNewProjMat(Matrixd& oldProj, double znear,
67                                        double zfar, Matrixd& projection)
68 {
69     projection = oldProj;
70     // Slightly inflate the near & far planes to avoid objects at the
71     // extremes being clipped out.
72     znear *= 0.999;
73     zfar *= 1.001;
74
75     // Clamp the projection matrix z values to the range (near, far)
76     double epsilon = 1.0e-6;
77     if (fabs(projection(0,3)) < epsilon &&
78         fabs(projection(1,3)) < epsilon &&
79         fabs(projection(2,3)) < epsilon) {
80         // Projection is Orthographic
81         epsilon = -1.0/(zfar - znear); // Used as a temp variable
82         projection(2,2) = 2.0*epsilon;
83         projection(3,2) = (zfar + znear)*epsilon;
84     } else {
85         // Projection is Perspective
86         double trans_near = (-znear*projection(2,2) + projection(3,2)) /
87             (-znear*projection(2,3) + projection(3,3));
88         double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
89             (-zfar*projection(2,3) + projection(3,3));
90         double ratio = fabs(2.0/(trans_near - trans_far));
91         double center = -0.5*(trans_near + trans_far);
92
93         projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
94                                          0.0, 1.0, 0.0, 0.0,
95                                          0.0, 0.0, ratio, 0.0,
96                                          0.0, 0.0, center*ratio, 1.0));
97     }
98 }
99
100 void installCullVisitor(Camera* camera)
101 {
102 #if 0 // Not yet
103     osgViewer::Renderer* renderer
104         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
105     for (int i = 0; i < 2; ++i) {
106         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
107         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
108     }
109 #endif
110 }
111 }
112
113 namespace flightgear
114 {
115 void updateCameras(const CameraInfo* info)
116 {
117     if (info->camera.valid())
118         info->camera->getViewport()->setViewport(info->x, info->y,
119                                                  info->width, info->height);
120     if (info->farCamera.valid())
121         info->farCamera->getViewport()->setViewport(info->x, info->y,
122                                                     info->width, info->height);
123 }
124
125 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
126                                    const Matrix& view,
127                                    const Matrix& projection,
128                                    bool useMasterSceneData)
129 {
130     CameraInfo* info = new CameraInfo(flags);
131     // The camera group will always update the camera
132     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
133
134     Camera* farCamera = 0;
135     if ((flags & (GUI | ORTHO)) == 0) {
136         farCamera = osg::clone(camera);
137         farCamera->setGraphicsContext(camera->getGraphicsContext());
138         // Each camera's viewport is written when the window is
139         // resized; if the the viewport isn't copied here, it gets updated
140         // twice and ends up with the wrong value.
141         farCamera->setViewport(osg::clone(camera->getViewport()));
142         _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
143         installCullVisitor(farCamera);
144         info->farCamera = farCamera;
145         info->farSlaveIndex = _viewer->getNumSlaves() - 1;
146         farCamera->setRenderOrder(Camera::NESTED_RENDER, info->farSlaveIndex);
147         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
148     }
149     camera->setClearMask(GL_DEPTH_BUFFER_BIT);
150     _viewer->addSlave(camera, view, projection, useMasterSceneData);
151     installCullVisitor(camera);
152     info->camera = camera;
153     info->slaveIndex = _viewer->getNumSlaves() - 1;
154     camera->setRenderOrder(Camera::NESTED_RENDER, info->slaveIndex);
155     _cameras.push_back(info);
156     return info;
157 }
158
159 void CameraGroup::update(const osg::Vec3d& position,
160                          const osg::Quat& orientation)
161 {
162     const Matrix masterView(osg::Matrix::translate(-position)
163                             * osg::Matrix::rotate(orientation.inverse()));
164     _viewer->getCamera()->setViewMatrix(masterView);
165     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
166     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
167         const CameraInfo* info = i->get();
168         const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
169         // refreshes camera viewports (for now)
170         updateCameras(info);
171         Camera* camera = info->camera.get();
172         Matrix viewMatrix;
173         if ((info->flags & VIEW_ABSOLUTE) != 0)
174             viewMatrix = slave._viewOffset;
175         else
176             viewMatrix = masterView * slave._viewOffset;
177         camera->setViewMatrix(viewMatrix);
178         Matrix projectionMatrix;
179         if ((info->flags & PROJECTION_ABSOLUTE) != 0)
180             projectionMatrix = slave._projectionOffset;
181         else
182             projectionMatrix = masterProj * slave._projectionOffset;
183
184         if (!info->farCamera.valid()) {
185             camera->setProjectionMatrix(projectionMatrix);
186         } else {
187             Camera* farCamera = info->farCamera.get();
188             farCamera->setViewMatrix(viewMatrix);
189             double left, right, bottom, top, parentNear, parentFar;
190             projectionMatrix.getFrustum(left, right, bottom, top,
191                                         parentNear, parentFar);
192             if (parentFar < 100.0) {
193                 camera->setProjectionMatrix(projectionMatrix);
194                 camera->setCullMask(camera->getCullMask()
195                                     | simgear::BACKGROUND_BIT);
196                 farCamera->setNodeMask(0);
197             } else {
198                 Matrix nearProj, farProj;
199                 makeNewProjMat(projectionMatrix, parentNear, 100.0, nearProj);
200                 makeNewProjMat(projectionMatrix, 100.0, parentFar, farProj);
201                 camera->setProjectionMatrix(nearProj);
202                 camera->setCullMask(camera->getCullMask()
203                                     & ~simgear::BACKGROUND_BIT);
204                 farCamera->setProjectionMatrix(farProj);
205                 farCamera->setNodeMask(camera->getNodeMask());
206             }
207         }
208     }
209 }
210
211 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
212 {
213     const float zNear = .1f;
214     const float zFar = 120000.0f;
215     _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
216                                                            1.0f / aspectRatio,
217                                                            zNear, zFar);
218 }
219 }
220
221 namespace
222 {
223 // A raw value for property nodes that references a class member via
224 // an osg::ref_ptr.
225 template<class C, class T>
226 class RefMember : public SGRawValue<T>
227 {
228 public:
229     RefMember (C *obj, T C::*ptr)
230         : _obj(obj), _ptr(ptr) {}
231     virtual ~RefMember () {}
232     virtual T getValue () const
233     {
234         return _obj.get()->*_ptr;
235     }
236     virtual bool setValue (T value)
237     {
238         _obj.get()->*_ptr = value;
239         return true;
240     }
241     virtual SGRawValue<T> * clone () const
242     {
243         return new RefMember(_obj.get(), _ptr);
244     }
245 private:
246     ref_ptr<C> _obj;
247     T C::* const _ptr;
248 };
249
250 template<typename C, typename T>
251 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
252 {
253     return RefMember<C, T>(obj, ptr);
254 }
255
256 template<typename C, typename T>
257 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
258                       C* obj, T C::*ptr, T value)
259 {
260     SGPropertyNode* valNode = parent->getNode(childName);
261     RefMember<C, T> refMember = makeRefMember(obj, ptr);
262     if (!valNode) {
263         valNode = parent->getNode(childName, true);
264         valNode->tie(refMember, false);
265         setValue(valNode, value);
266     } else {
267         valNode->tie(refMember, true);
268     }
269 }
270
271 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
272                    const osg::GraphicsContext::Traits *traits)
273 {
274     using namespace flightgear;
275     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
276     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
277     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
278                      static_cast<double>(traits->width));
279     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
280                      static_cast<double>(traits->height));
281 }
282 }
283
284 namespace flightgear
285 {
286
287 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
288 {
289     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
290     const SGPropertyNode* windowNode = cameraNode->getNode("window");
291     GraphicsWindow* window = 0;
292     static int cameraNum = 0;
293     int cameraFlags = DO_INTERSECTION_TEST;
294     if (windowNode) {
295         // New style window declaration / definition
296         window = wBuild->buildWindow(windowNode);
297     } else {
298         // Old style: suck window params out of camera block
299         window = wBuild->buildWindow(cameraNode);
300     }
301     if (!window) {
302         return 0;
303     }
304     Camera* camera = new Camera;
305     camera->setAllowEventFocus(false);
306     camera->setGraphicsContext(window->gc.get());
307     camera->setViewport(new Viewport);
308     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
309                            | CullSettings::VIEW_FRUSTUM_CULLING);
310     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
311                                & ~(CullSettings::CULL_MASK
312                                    | CullSettings::CULLING_MODE));
313
314     osg::Matrix pOff;
315     osg::Matrix vOff;
316     const SGPropertyNode* viewNode = cameraNode->getNode("view");
317     if (viewNode) {
318         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
319         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
320         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
321         double x = viewNode->getDoubleValue("x", 0.0);
322         double y = viewNode->getDoubleValue("y", 0.0);
323         double z = viewNode->getDoubleValue("z", 0.0);
324         // Build a view matrix, which is the inverse of a model
325         // orientation matrix.
326         vOff = (Matrix::translate(-x, -y, -z)
327                 * Matrix::rotate(-DegreesToRadians(heading),
328                                  Vec3d(0.0, 1.0, 0.0),
329                                  -DegreesToRadians(pitch),
330                                  Vec3d(1.0, 0.0, 0.0),
331                                  -DegreesToRadians(roll),
332                                  Vec3d(0.0, 0.0, 1.0)));
333         if (viewNode->getBoolValue("absolute", false))
334             cameraFlags |= VIEW_ABSOLUTE;
335     } else {
336         // Old heading parameter, works in the opposite direction
337         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
338         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
339     }
340     const SGPropertyNode* projectionNode = 0;
341     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
342         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
343         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
344                                                             1.0);
345         double zNear = projectionNode->getDoubleValue("near", 0.0);
346         double zFar = projectionNode->getDoubleValue("far", 0.0);
347         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
348         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
349         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
350         double right = tan_fovy * aspectRatio * zNear + offsetX;
351         double left = -tan_fovy * aspectRatio * zNear + offsetX;
352         double top = tan_fovy * zNear + offsetY;
353         double bottom = -tan_fovy * zNear + offsetY;
354         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
355         cameraFlags |= PROJECTION_ABSOLUTE;
356     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
357                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
358         double top = projectionNode->getDoubleValue("top", 0.0);
359         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
360         double left = projectionNode->getDoubleValue("left", 0.0);
361         double right = projectionNode->getDoubleValue("right", 0.0);
362         double zNear = projectionNode->getDoubleValue("near", 0.0);
363         double zFar = projectionNode->getDoubleValue("far", 0.0);
364         if (cameraNode->getNode("frustum")) {
365             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
366             cameraFlags |= PROJECTION_ABSOLUTE;
367         } else {
368             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
369             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
370         }
371     } else {
372         // old style shear parameters
373         double shearx = cameraNode->getDoubleValue("shear-x", 0);
374         double sheary = cameraNode->getDoubleValue("shear-y", 0);
375         pOff.makeTranslate(-shearx, -sheary, 0);
376     }
377     CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
378     // If a viewport isn't set on the camera, then it's hard to dig it
379     // out of the SceneView objects in the viewer, and the coordinates
380     // of mouse events are somewhat bizzare.
381     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
382     buildViewport(info, viewportNode, window->gc->getTraits());
383     return info;
384 }
385
386 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
387                                         GraphicsWindow* window)
388 {
389     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
390     const SGPropertyNode* windowNode = (cameraNode
391                                         ? cameraNode->getNode("window")
392                                         : 0);
393     static int cameraNum = 0;
394     if (!window) {
395         if (windowNode) {
396             // New style window declaration / definition
397             window = wBuild->buildWindow(windowNode);
398             
399         } else {
400             return 0;
401         }
402     }
403     Camera* camera = new Camera;
404     camera->setAllowEventFocus(false);
405     camera->setGraphicsContext(window->gc.get());
406     camera->setViewport(new Viewport);
407     // XXX Camera needs to be drawn last; eventually the render order
408     // should be assigned by a camera manager.
409     camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
410         camera->setClearMask(0);
411     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
412                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
413                                    | CullSettings::CULLING_MODE));
414     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
415     camera->setCullingMode(osg::CullSettings::NO_CULLING);
416     camera->setProjectionResizePolicy(Camera::FIXED);
417     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
418     const int cameraFlags = GUI;
419     CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
420                                    Matrixd::identity(), false);
421     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
422     buildViewport(result, viewportNode, window->gc->getTraits());
423
424     // Disable statistics for the GUI camera.
425     result->camera->setStats(0);
426     updateCameras(result);
427     return result;
428 }
429
430 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
431                                            SGPropertyNode* gnode)
432 {
433     CameraGroup* cgroup = new CameraGroup(viewer);
434     for (int i = 0; i < gnode->nChildren(); ++i) {
435         SGPropertyNode* pNode = gnode->getChild(i);
436         const char* name = pNode->getName();
437         if (!strcmp(name, "camera")) {
438             cgroup->buildCamera(pNode);
439         } else if (!strcmp(name, "window")) {
440             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
441         } else if (!strcmp(name, "gui")) {
442             cgroup->buildGUICamera(pNode);
443         }
444     }
445     return cgroup;
446 }
447
448 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
449 {
450     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
451         if ((*i)->flags & GUI)
452             continue;
453         (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
454         (*i)->farCamera->setCullMask(nm);
455     }
456 }
457
458 void CameraGroup::resized()
459 {
460     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
461         CameraInfo *info = i->get();
462         const Viewport* viewport = info->camera->getViewport();
463         info->x = viewport->x();
464         info->y = viewport->y();
465         info->width = viewport->width();
466         info->height = viewport->height();
467     }
468 }
469
470 Camera* getGUICamera(CameraGroup* cgroup)
471 {
472     CameraGroup::CameraIterator end = cgroup->camerasEnd();
473     CameraGroup::CameraIterator result
474         = std::find_if(cgroup->camerasBegin(), end,
475                        FlagTester<CameraInfo>(CameraGroup::GUI));
476     if (result != end)
477         return (*result)->camera.get();
478     else
479         return 0;
480 }
481
482 bool computeIntersections(const CameraGroup* cgroup,
483                           const osgGA::GUIEventAdapter* ea,
484                           osgUtil::LineSegmentIntersector::Intersections& intersections)
485 {
486     using osgUtil::Intersector;
487     using osgUtil::LineSegmentIntersector;
488     double x, y;
489     eventToWindowCoords(ea, x, y);
490     // Find camera that contains event
491     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
492              e = cgroup->camerasEnd();
493          iter != e;
494          ++iter) {
495         const CameraInfo* cinfo = iter->get();
496         if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
497             continue;
498         const Camera* camera = cinfo->camera.get();
499         if (camera->getGraphicsContext() != ea->getGraphicsContext())
500             continue;
501         const Viewport* viewport = camera->getViewport();
502         double epsilon = 0.5;
503         if (!(x >= viewport->x() - epsilon
504               && x < viewport->x() + viewport->width() -1.0 + epsilon
505               && y >= viewport->y() - epsilon
506               && y < viewport->y() + viewport->height() -1.0 + epsilon))
507             continue;
508         LineSegmentIntersector::CoordinateFrame cf = Intersector::WINDOW;
509         ref_ptr<LineSegmentIntersector> picker
510             = new LineSegmentIntersector(cf, x, y);
511         osgUtil::IntersectionVisitor iv(picker.get());
512         const_cast<Camera*>(camera)->accept(iv);
513         if (picker->containsIntersections()) {
514             intersections = picker->getIntersections();
515             return true;
516         } else {
517             break;
518         }
519     }
520     intersections.clear();
521     return false;
522 }
523
524 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
525 {
526     using osgViewer::GraphicsWindow;
527     Camera* guiCamera = getGUICamera(cgroup);
528     if (!guiCamera)
529         return;
530     Viewport* vport = guiCamera->getViewport();
531     GraphicsWindow* gw
532         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
533     if (!gw)
534         return;
535     globals->get_renderer()->getEventHandler()->setMouseWarped();    
536     // Translate the warp request into the viewport of the GUI camera,
537     // send the request to the window, then transform the coordinates
538     // for the Viewer's event queue.
539     double wx = x + vport->x();
540     double wyUp = vport->height() + vport->y() - y;
541     double wy;
542     const GraphicsContext::Traits* traits = gw->getTraits();
543     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
544         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
545         wy = traits->height - wyUp;
546     } else {
547         wy = wyUp;
548     }
549     gw->getEventQueue()->mouseWarped(wx, wy);
550     gw->requestWarpPointer(wx, wy);
551     osgGA::GUIEventAdapter* eventState
552         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
553     double viewerX
554         = (eventState->getXmin()
555            + ((wx / double(traits->width))
556               * (eventState->getXmax() - eventState->getXmin())));
557     double viewerY
558         = (eventState->getYmin()
559            + ((wyUp / double(traits->height))
560               * (eventState->getYmax() - eventState->getYmin())));
561     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
562 }
563 }