]> git.mxchange.org Git - flightgear.git/blob - src/Main/CameraGroup.cxx
Cleanup of camera code in preperation for shadows
[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 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
116                                    const Matrix& view,
117                                    const Matrix& projection,
118                                    bool useMasterSceneData)
119 {
120     CameraInfo* info = new CameraInfo(flags);
121     // The camera group will always update the camera
122     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
123
124     Camera* farCamera = 0;
125     if ((flags & (GUI | ORTHO)) == 0) {
126         farCamera = osg::clone(camera);
127         farCamera->setGraphicsContext(camera->getGraphicsContext());
128         // Each camera's viewport is written when the window is
129         // resized; if the the viewport isn't copied here, it gets updated
130         // twice and ends up with the wrong value.
131         farCamera->setViewport(osg::clone(camera->getViewport()));
132         _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
133         installCullVisitor(farCamera);
134         info->farCamera = farCamera;
135         info->farSlaveIndex = _viewer->getNumSlaves() - 1;
136         farCamera->setRenderOrder(Camera::NESTED_RENDER, info->farSlaveIndex);
137         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
138     }
139     camera->setClearMask(GL_DEPTH_BUFFER_BIT);
140     _viewer->addSlave(camera, view, projection, useMasterSceneData);
141     installCullVisitor(camera);
142     info->camera = camera;
143     info->slaveIndex = _viewer->getNumSlaves() - 1;
144     camera->setRenderOrder(Camera::NESTED_RENDER, info->slaveIndex);
145     _cameras.push_back(info);
146     return info;
147 }
148
149 void CameraGroup::update(const osg::Vec3d& position,
150                          const osg::Quat& orientation)
151 {
152     const Matrix masterView(osg::Matrix::translate(-position)
153                             * osg::Matrix::rotate(orientation.inverse()));
154     _viewer->getCamera()->setViewMatrix(masterView);
155     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
156     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
157         const CameraInfo* info = i->get();
158         const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
159         Camera* camera = info->camera.get();
160         camera->getViewport()->setViewport(info->x, info->y, info->width,
161                                            info->height);
162         Matrix viewMatrix;
163         if ((info->flags & VIEW_ABSOLUTE) != 0)
164             viewMatrix = slave._viewOffset;
165         else
166             viewMatrix = masterView * slave._viewOffset;
167         camera->setViewMatrix(viewMatrix);
168         Matrix projectionMatrix;
169         if ((info->flags & PROJECTION_ABSOLUTE) != 0)
170             projectionMatrix = slave._projectionOffset;
171         else
172             projectionMatrix = masterProj * slave._projectionOffset;
173
174         if (!info->farCamera.valid()) {
175             camera->setProjectionMatrix(projectionMatrix);
176         } else {
177             Camera* farCamera = info->farCamera.get();
178             farCamera->getViewport()->setViewport(info->x, info->y, info->width,
179                                                   info->height);
180             farCamera->setViewMatrix(viewMatrix);
181             double left, right, bottom, top, parentNear, parentFar;
182             projectionMatrix.getFrustum(left, right, bottom, top,
183                                         parentNear, parentFar);
184             if (parentFar < 100.0) {
185                 camera->setProjectionMatrix(projectionMatrix);
186                 camera->setCullMask(camera->getCullMask()
187                                     | simgear::BACKGROUND_BIT);
188                 farCamera->setNodeMask(0);
189             } else {
190                 Matrix nearProj, farProj;
191                 makeNewProjMat(projectionMatrix, parentNear, 100.0, nearProj);
192                 makeNewProjMat(projectionMatrix, 100.0, parentFar, farProj);
193                 camera->setProjectionMatrix(nearProj);
194                 camera->setCullMask(camera->getCullMask()
195                                     & ~simgear::BACKGROUND_BIT);
196                 farCamera->setProjectionMatrix(farProj);
197                 farCamera->setNodeMask(camera->getNodeMask());
198             }
199         }
200     }
201 }
202
203 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
204 {
205     const float zNear = .1f;
206     const float zFar = 120000.0f;
207     _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
208                                                            1.0f / aspectRatio,
209                                                            zNear, zFar);
210 }
211 }
212
213 namespace
214 {
215 // A raw value for property nodes that references a class member via
216 // an osg::ref_ptr.
217 template<class C, class T>
218 class RefMember : public SGRawValue<T>
219 {
220 public:
221     RefMember (C *obj, T C::*ptr)
222         : _obj(obj), _ptr(ptr) {}
223     virtual ~RefMember () {}
224     virtual T getValue () const
225     {
226         return _obj.get()->*_ptr;
227     }
228     virtual bool setValue (T value)
229     {
230         _obj.get()->*_ptr = value;
231         return true;
232     }
233     virtual SGRawValue<T> * clone () const
234     {
235         return new RefMember(_obj.get(), _ptr);
236     }
237 private:
238     ref_ptr<C> _obj;
239     T C::* const _ptr;
240 };
241
242 template<typename C, typename T>
243 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
244 {
245     return RefMember<C, T>(obj, ptr);
246 }
247
248 template<typename C, typename T>
249 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
250                       C* obj, T C::*ptr, T value)
251 {
252     SGPropertyNode* valNode = parent->getNode(childName);
253     RefMember<C, T> refMember = makeRefMember(obj, ptr);
254     if (!valNode) {
255         valNode = parent->getNode(childName, true);
256         valNode->tie(refMember, false);
257         setValue(valNode, value);
258     } else {
259         valNode->tie(refMember, true);
260     }
261 }
262
263 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
264                    const osg::GraphicsContext::Traits *traits)
265 {
266     using namespace flightgear;
267     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
268     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
269     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
270                      static_cast<double>(traits->width));
271     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
272                      static_cast<double>(traits->height));
273 }
274 }
275
276 namespace flightgear
277 {
278
279 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
280 {
281     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
282     const SGPropertyNode* windowNode = cameraNode->getNode("window");
283     GraphicsWindow* window = 0;
284     static int cameraNum = 0;
285     int cameraFlags = DO_INTERSECTION_TEST;
286     if (windowNode) {
287         // New style window declaration / definition
288         window = wBuild->buildWindow(windowNode);
289     } else {
290         // Old style: suck window params out of camera block
291         window = wBuild->buildWindow(cameraNode);
292     }
293     if (!window) {
294         return 0;
295     }
296     Camera* camera = new Camera;
297     camera->setAllowEventFocus(false);
298     camera->setGraphicsContext(window->gc.get());
299     camera->setViewport(new Viewport);
300     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
301                            | CullSettings::VIEW_FRUSTUM_CULLING);
302     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
303                                & ~(CullSettings::CULL_MASK
304                                    | CullSettings::CULLING_MODE));
305
306     osg::Matrix pOff;
307     osg::Matrix vOff;
308     const SGPropertyNode* viewNode = cameraNode->getNode("view");
309     if (viewNode) {
310         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
311         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
312         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
313         double x = viewNode->getDoubleValue("x", 0.0);
314         double y = viewNode->getDoubleValue("y", 0.0);
315         double z = viewNode->getDoubleValue("z", 0.0);
316         // Build a view matrix, which is the inverse of a model
317         // orientation matrix.
318         vOff = (Matrix::translate(-x, -y, -z)
319                 * Matrix::rotate(-DegreesToRadians(heading),
320                                  Vec3d(0.0, 1.0, 0.0),
321                                  -DegreesToRadians(pitch),
322                                  Vec3d(1.0, 0.0, 0.0),
323                                  -DegreesToRadians(roll),
324                                  Vec3d(0.0, 0.0, 1.0)));
325         if (viewNode->getBoolValue("absolute", false))
326             cameraFlags |= VIEW_ABSOLUTE;
327     } else {
328         // Old heading parameter, works in the opposite direction
329         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
330         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
331     }
332     const SGPropertyNode* projectionNode = 0;
333     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
334         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
335         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
336                                                             1.0);
337         double zNear = projectionNode->getDoubleValue("near", 0.0);
338         double zFar = projectionNode->getDoubleValue("far", 0.0);
339         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
340         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
341         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
342         double right = tan_fovy * aspectRatio * zNear + offsetX;
343         double left = -tan_fovy * aspectRatio * zNear + offsetX;
344         double top = tan_fovy * zNear + offsetY;
345         double bottom = -tan_fovy * zNear + offsetY;
346         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
347         cameraFlags |= PROJECTION_ABSOLUTE;
348     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
349                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
350         double top = projectionNode->getDoubleValue("top", 0.0);
351         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
352         double left = projectionNode->getDoubleValue("left", 0.0);
353         double right = projectionNode->getDoubleValue("right", 0.0);
354         double zNear = projectionNode->getDoubleValue("near", 0.0);
355         double zFar = projectionNode->getDoubleValue("far", 0.0);
356         if (cameraNode->getNode("frustum")) {
357             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
358             cameraFlags |= PROJECTION_ABSOLUTE;
359         } else {
360             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
361             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
362         }
363     } else {
364         // old style shear parameters
365         double shearx = cameraNode->getDoubleValue("shear-x", 0);
366         double sheary = cameraNode->getDoubleValue("shear-y", 0);
367         pOff.makeTranslate(-shearx, -sheary, 0);
368     }
369     CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
370     // If a viewport isn't set on the camera, then it's hard to dig it
371     // out of the SceneView objects in the viewer, and the coordinates
372     // of mouse events are somewhat bizzare.
373     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
374     buildViewport(info, viewportNode, window->gc->getTraits());
375     return info;
376 }
377
378 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
379                                         GraphicsWindow* window)
380 {
381     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
382     const SGPropertyNode* windowNode = (cameraNode
383                                         ? cameraNode->getNode("window")
384                                         : 0);
385     static int cameraNum = 0;
386     if (!window) {
387         if (windowNode) {
388             // New style window declaration / definition
389             window = wBuild->buildWindow(windowNode);
390             
391         } else {
392             return 0;
393         }
394     }
395     Camera* camera = new Camera;
396     camera->setAllowEventFocus(false);
397     camera->setGraphicsContext(window->gc.get());
398     camera->setViewport(new Viewport);
399     // XXX Camera needs to be drawn last; eventually the render order
400     // should be assigned by a camera manager.
401     camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
402         camera->setClearMask(0);
403     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
404                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
405                                    | CullSettings::CULLING_MODE));
406     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
407     camera->setCullingMode(osg::CullSettings::NO_CULLING);
408     camera->setProjectionResizePolicy(Camera::FIXED);
409     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
410     const int cameraFlags = GUI;
411     CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
412                                    Matrixd::identity(), false);
413     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
414     buildViewport(result, viewportNode, window->gc->getTraits());
415
416     // Disable statistics for the GUI camera.
417     result->camera->setStats(0);
418     return result;
419 }
420
421 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
422                                            SGPropertyNode* gnode)
423 {
424     CameraGroup* cgroup = new CameraGroup(viewer);
425     for (int i = 0; i < gnode->nChildren(); ++i) {
426         SGPropertyNode* pNode = gnode->getChild(i);
427         const char* name = pNode->getName();
428         if (!strcmp(name, "camera")) {
429             cgroup->buildCamera(pNode);
430         } else if (!strcmp(name, "window")) {
431             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
432         } else if (!strcmp(name, "gui")) {
433             cgroup->buildGUICamera(pNode);
434         }
435     }
436     return cgroup;
437 }
438
439 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
440 {
441     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
442         if ((*i)->flags & GUI)
443             continue;
444         (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
445         (*i)->farCamera->setCullMask(nm);
446     }
447 }
448
449 Camera* getGUICamera(CameraGroup* cgroup)
450 {
451     CameraGroup::CameraIterator end = cgroup->camerasEnd();
452     CameraGroup::CameraIterator result
453         = std::find_if(cgroup->camerasBegin(), end,
454                        FlagTester<CameraInfo>(CameraGroup::GUI));
455     if (result != end)
456         return (*result)->camera.get();
457     else
458         return 0;
459 }
460
461 bool computeIntersections(const CameraGroup* cgroup,
462                           const osgGA::GUIEventAdapter* ea,
463                           osgUtil::LineSegmentIntersector::Intersections& intersections)
464 {
465     using osgUtil::Intersector;
466     using osgUtil::LineSegmentIntersector;
467     double x, y;
468     eventToWindowCoords(ea, x, y);
469     // Find camera that contains event
470     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
471              e = cgroup->camerasEnd();
472          iter != e;
473          ++iter) {
474         const CameraInfo* cinfo = iter->get();
475         if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
476             continue;
477         const Camera* camera = cinfo->camera.get();
478         if (camera->getGraphicsContext() != ea->getGraphicsContext())
479             continue;
480         const Viewport* viewport = camera->getViewport();
481         double epsilon = 0.5;
482         if (!(x >= viewport->x() - epsilon
483               && x < viewport->x() + viewport->width() -1.0 + epsilon
484               && y >= viewport->y() - epsilon
485               && y < viewport->y() + viewport->height() -1.0 + epsilon))
486             continue;
487         LineSegmentIntersector::CoordinateFrame cf = Intersector::WINDOW;
488         ref_ptr<LineSegmentIntersector> picker
489             = new LineSegmentIntersector(cf, x, y);
490         osgUtil::IntersectionVisitor iv(picker.get());
491         const_cast<Camera*>(camera)->accept(iv);
492         if (picker->containsIntersections()) {
493             intersections = picker->getIntersections();
494             return true;
495         } else {
496             break;
497         }
498     }
499     intersections.clear();
500     return false;
501 }
502
503 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
504 {
505     using osgViewer::GraphicsWindow;
506     Camera* guiCamera = getGUICamera(cgroup);
507     if (!guiCamera)
508         return;
509     Viewport* vport = guiCamera->getViewport();
510     GraphicsWindow* gw
511         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
512     if (!gw)
513         return;
514     globals->get_renderer()->getEventHandler()->setMouseWarped();    
515     // Translate the warp request into the viewport of the GUI camera,
516     // send the request to the window, then transform the coordinates
517     // for the Viewer's event queue.
518     double wx = x + vport->x();
519     double wyUp = vport->height() + vport->y() - y;
520     double wy;
521     const GraphicsContext::Traits* traits = gw->getTraits();
522     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
523         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
524         wy = traits->height - wyUp;
525     } else {
526         wy = wyUp;
527     }
528     gw->getEventQueue()->mouseWarped(wx, wy);
529     gw->requestWarpPointer(wx, wy);
530     osgGA::GUIEventAdapter* eventState
531         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
532     double viewerX
533         = (eventState->getXmin()
534            + ((wx / double(traits->width))
535               * (eventState->getXmax() - eventState->getXmin())));
536     double viewerY
537         = (eventState->getYmin()
538            + ((wyUp / double(traits->height))
539               * (eventState->getYmax() - eventState->getYmin())));
540     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
541 }
542 }