1 // Copyright (C) 2008 Tim Moore
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.
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.
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.
21 #include "CameraGroup.hxx"
23 #include "globals.hxx"
24 #include "renderer.hxx"
25 #include "FGEventHandler.hxx"
26 #include "WindowBuilder.hxx"
27 #include "WindowSystemAdapter.hxx"
28 #include <simgear/props/props.hxx>
29 #include <simgear/structure/OSGUtils.hxx>
30 #include <simgear/scene/material/EffectCullVisitor.hxx>
31 #include <simgear/scene/util/RenderConstants.hxx>
38 #include <osg/GraphicsContext>
43 #include <osg/Viewport>
45 #include <osgUtil/IntersectionVisitor>
47 #include <osgViewer/GraphicsWindow>
48 #include <osgViewer/Renderer>
57 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
59 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
70 // Given a projection matrix, return a new one with the same frustum
71 // sides and new near / far values.
73 void makeNewProjMat(Matrixd& oldProj, double znear,
74 double zfar, Matrixd& projection)
77 // Slightly inflate the near & far planes to avoid objects at the
78 // extremes being clipped out.
82 // Clamp the projection matrix z values to the range (near, far)
83 double epsilon = 1.0e-6;
84 if (fabs(projection(0,3)) < epsilon &&
85 fabs(projection(1,3)) < epsilon &&
86 fabs(projection(2,3)) < epsilon) {
87 // Projection is Orthographic
88 epsilon = -1.0/(zfar - znear); // Used as a temp variable
89 projection(2,2) = 2.0*epsilon;
90 projection(3,2) = (zfar + znear)*epsilon;
92 // Projection is Perspective
93 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
94 (-znear*projection(2,3) + projection(3,3));
95 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
96 (-zfar*projection(2,3) + projection(3,3));
97 double ratio = fabs(2.0/(trans_near - trans_far));
98 double center = -0.5*(trans_near + trans_far);
100 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
102 0.0, 0.0, ratio, 0.0,
103 0.0, 0.0, center*ratio, 1.0));
107 void installCullVisitor(Camera* camera)
109 osgViewer::Renderer* renderer
110 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
111 for (int i = 0; i < 2; ++i) {
112 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
113 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
120 void updateCameras(const CameraInfo* info)
122 if (info->camera.valid())
123 info->camera->getViewport()->setViewport(info->x, info->y,
124 info->width, info->height);
125 if (info->farCamera.valid())
126 info->farCamera->getViewport()->setViewport(info->x, info->y,
127 info->width, info->height);
130 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
132 const Matrix& projection,
133 bool useMasterSceneData)
135 CameraInfo* info = new CameraInfo(flags);
136 // The camera group will always update the camera
137 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
139 Camera* farCamera = 0;
140 if ((flags & (GUI | ORTHO)) == 0) {
141 farCamera = new Camera;
142 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
143 farCamera->setGraphicsContext(camera->getGraphicsContext());
144 farCamera->setCullingMode(camera->getCullingMode());
145 farCamera->setInheritanceMask(camera->getInheritanceMask());
146 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
147 // Each camera's viewport is written when the window is
148 // resized; if the the viewport isn't copied here, it gets updated
149 // twice and ends up with the wrong value.
150 farCamera->setViewport(simgear::clone(camera->getViewport()));
151 _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
152 installCullVisitor(farCamera);
153 info->farCamera = farCamera;
154 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
155 farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
156 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
157 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
159 _viewer->addSlave(camera, view, projection, useMasterSceneData);
160 installCullVisitor(camera);
161 info->camera = camera;
162 info->slaveIndex = _viewer->getNumSlaves() - 1;
163 camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
164 _cameras.push_back(info);
168 void CameraGroup::update(const osg::Vec3d& position,
169 const osg::Quat& orientation)
171 const Matrix masterView(osg::Matrix::translate(-position)
172 * osg::Matrix::rotate(orientation.inverse()));
173 _viewer->getCamera()->setViewMatrix(masterView);
174 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
175 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
176 const CameraInfo* info = i->get();
177 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
178 // refreshes camera viewports (for now)
180 Camera* camera = info->camera.get();
182 if ((info->flags & VIEW_ABSOLUTE) != 0)
183 viewMatrix = slave._viewOffset;
185 viewMatrix = masterView * slave._viewOffset;
186 camera->setViewMatrix(viewMatrix);
187 Matrix projectionMatrix;
188 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
189 projectionMatrix = slave._projectionOffset;
191 projectionMatrix = masterProj * slave._projectionOffset;
193 if (!info->farCamera.valid()) {
194 camera->setProjectionMatrix(projectionMatrix);
196 Camera* farCamera = info->farCamera.get();
197 farCamera->setViewMatrix(viewMatrix);
198 double left, right, bottom, top, parentNear, parentFar;
199 projectionMatrix.getFrustum(left, right, bottom, top,
200 parentNear, parentFar);
201 if (parentFar < _nearField || _nearField == 0.0f) {
202 camera->setProjectionMatrix(projectionMatrix);
203 camera->setCullMask(camera->getCullMask()
204 | simgear::BACKGROUND_BIT);
205 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
206 farCamera->setNodeMask(0);
208 Matrix nearProj, farProj;
209 makeNewProjMat(projectionMatrix, parentNear, _nearField,
211 makeNewProjMat(projectionMatrix, _nearField, parentFar,
213 camera->setProjectionMatrix(nearProj);
214 camera->setCullMask(camera->getCullMask()
215 & ~simgear::BACKGROUND_BIT);
216 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
217 farCamera->setProjectionMatrix(farProj);
218 farCamera->setNodeMask(camera->getNodeMask());
224 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
226 if (vfov != 0.0f && aspectRatio != 0.0f)
228 ->setProjectionMatrixAsPerspective(vfov,
236 // A raw value for property nodes that references a class member via
238 template<class C, class T>
239 class RefMember : public SGRawValue<T>
242 RefMember (C *obj, T C::*ptr)
243 : _obj(obj), _ptr(ptr) {}
244 virtual ~RefMember () {}
245 virtual T getValue () const
247 return _obj.get()->*_ptr;
249 virtual bool setValue (T value)
251 _obj.get()->*_ptr = value;
254 virtual SGRawValue<T> * clone () const
256 return new RefMember(_obj.get(), _ptr);
263 template<typename C, typename T>
264 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
266 return RefMember<C, T>(obj, ptr);
269 template<typename C, typename T>
270 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
271 C* obj, T C::*ptr, T value)
273 SGPropertyNode* valNode = parent->getNode(childName);
274 RefMember<C, T> refMember = makeRefMember(obj, ptr);
276 valNode = parent->getNode(childName, true);
277 valNode->tie(refMember, false);
278 setValue(valNode, value);
280 valNode->tie(refMember, true);
284 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
285 const osg::GraphicsContext::Traits *traits)
287 using namespace flightgear;
288 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
289 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
290 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
291 static_cast<double>(traits->width));
292 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
293 static_cast<double>(traits->height));
300 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
302 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
303 const SGPropertyNode* windowNode = cameraNode->getNode("window");
304 GraphicsWindow* window = 0;
305 int cameraFlags = DO_INTERSECTION_TEST;
307 // New style window declaration / definition
308 window = wBuild->buildWindow(windowNode);
310 // Old style: suck window params out of camera block
311 window = wBuild->buildWindow(cameraNode);
316 Camera* camera = new Camera;
317 camera->setAllowEventFocus(false);
318 camera->setGraphicsContext(window->gc.get());
319 camera->setViewport(new Viewport);
320 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
321 | CullSettings::VIEW_FRUSTUM_CULLING);
322 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
323 & ~(CullSettings::CULL_MASK
324 | CullSettings::CULLING_MODE
325 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
326 | CullSettings::CLEAR_MASK
332 const SGPropertyNode* viewNode = cameraNode->getNode("view");
334 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
335 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
336 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
337 double x = viewNode->getDoubleValue("x", 0.0);
338 double y = viewNode->getDoubleValue("y", 0.0);
339 double z = viewNode->getDoubleValue("z", 0.0);
340 // Build a view matrix, which is the inverse of a model
341 // orientation matrix.
342 vOff = (Matrix::translate(-x, -y, -z)
343 * Matrix::rotate(-DegreesToRadians(heading),
344 Vec3d(0.0, 1.0, 0.0),
345 -DegreesToRadians(pitch),
346 Vec3d(1.0, 0.0, 0.0),
347 -DegreesToRadians(roll),
348 Vec3d(0.0, 0.0, 1.0)));
349 if (viewNode->getBoolValue("absolute", false))
350 cameraFlags |= VIEW_ABSOLUTE;
352 // Old heading parameter, works in the opposite direction
353 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
354 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
356 const SGPropertyNode* projectionNode = 0;
357 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
358 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
359 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
361 double zNear = projectionNode->getDoubleValue("near", 0.0);
362 double zFar = projectionNode->getDoubleValue("far", 0.0);
363 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
364 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
365 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
366 double right = tan_fovy * aspectRatio * zNear + offsetX;
367 double left = -tan_fovy * aspectRatio * zNear + offsetX;
368 double top = tan_fovy * zNear + offsetY;
369 double bottom = -tan_fovy * zNear + offsetY;
370 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
371 cameraFlags |= PROJECTION_ABSOLUTE;
372 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
373 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
374 double top = projectionNode->getDoubleValue("top", 0.0);
375 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
376 double left = projectionNode->getDoubleValue("left", 0.0);
377 double right = projectionNode->getDoubleValue("right", 0.0);
378 double zNear = projectionNode->getDoubleValue("near", 0.0);
379 double zFar = projectionNode->getDoubleValue("far", 0.0);
380 if (cameraNode->getNode("frustum")) {
381 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
382 cameraFlags |= PROJECTION_ABSOLUTE;
384 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
385 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
388 // old style shear parameters
389 double shearx = cameraNode->getDoubleValue("shear-x", 0);
390 double sheary = cameraNode->getDoubleValue("shear-y", 0);
391 pOff.makeTranslate(-shearx, -sheary, 0);
393 CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
394 // If a viewport isn't set on the camera, then it's hard to dig it
395 // out of the SceneView objects in the viewer, and the coordinates
396 // of mouse events are somewhat bizzare.
397 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
398 buildViewport(info, viewportNode, window->gc->getTraits());
403 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
404 GraphicsWindow* window)
406 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
407 const SGPropertyNode* windowNode = (cameraNode
408 ? cameraNode->getNode("window")
412 // New style window declaration / definition
413 window = wBuild->buildWindow(windowNode);
419 Camera* camera = new Camera;
420 camera->setAllowEventFocus(false);
421 camera->setGraphicsContext(window->gc.get());
422 camera->setViewport(new Viewport);
423 // XXX Camera needs to be drawn last; eventually the render order
424 // should be assigned by a camera manager.
425 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
426 camera->setClearMask(0);
427 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
428 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
429 | CullSettings::CULLING_MODE
430 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
431 | CullSettings::CLEAR_MASK
434 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
435 camera->setCullingMode(osg::CullSettings::NO_CULLING);
436 camera->setProjectionResizePolicy(Camera::FIXED);
437 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
438 const int cameraFlags = GUI;
439 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
440 Matrixd::identity(), false);
441 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
442 buildViewport(result, viewportNode, window->gc->getTraits());
444 // Disable statistics for the GUI camera.
445 result->camera->setStats(0);
446 updateCameras(result);
450 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
451 SGPropertyNode* gnode)
453 CameraGroup* cgroup = new CameraGroup(viewer);
454 for (int i = 0; i < gnode->nChildren(); ++i) {
455 SGPropertyNode* pNode = gnode->getChild(i);
456 const char* name = pNode->getName();
457 if (!strcmp(name, "camera")) {
458 cgroup->buildCamera(pNode);
459 } else if (!strcmp(name, "window")) {
460 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
461 } else if (!strcmp(name, "gui")) {
462 cgroup->buildGUICamera(pNode);
465 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
466 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
467 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
472 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
474 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
475 CameraInfo* info = i->get();
476 if (info->flags & GUI)
478 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
479 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
480 info->farCamera->setCullMask(nm);
482 info->camera->setCullMask(nm);
487 void CameraGroup::resized()
489 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
490 CameraInfo *info = i->get();
491 const Viewport* viewport = info->camera->getViewport();
492 info->x = viewport->x();
493 info->y = viewport->y();
494 info->width = viewport->width();
495 info->height = viewport->height();
499 Camera* getGUICamera(CameraGroup* cgroup)
501 CameraGroup::CameraIterator end = cgroup->camerasEnd();
502 CameraGroup::CameraIterator result
503 = std::find_if(cgroup->camerasBegin(), end,
504 FlagTester<CameraInfo>(CameraGroup::GUI));
506 return (*result)->camera.get();
511 bool computeIntersections(const CameraGroup* cgroup,
512 const osgGA::GUIEventAdapter* ea,
513 osgUtil::LineSegmentIntersector::Intersections& intersections)
515 using osgUtil::Intersector;
516 using osgUtil::LineSegmentIntersector;
518 eventToWindowCoords(ea, x, y);
519 // Find camera that contains event
520 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
521 e = cgroup->camerasEnd();
524 const CameraInfo* cinfo = iter->get();
525 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
527 const Camera* camera = cinfo->camera.get();
528 if (camera->getGraphicsContext() != ea->getGraphicsContext())
530 const Viewport* viewport = camera->getViewport();
531 double epsilon = 0.5;
532 if (!(x >= viewport->x() - epsilon
533 && x < viewport->x() + viewport->width() -1.0 + epsilon
534 && y >= viewport->y() - epsilon
535 && y < viewport->y() + viewport->height() -1.0 + epsilon))
537 Vec4d start(x, y, 0.0, 1.0);
538 Vec4d end(x, y, 1.0, 1.0);
539 Matrix windowMat = viewport->computeWindowMatrix();
540 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
543 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
544 endPtMat = startPtMat;
546 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
548 start = start * startPtMat;
550 end = end * endPtMat;
552 ref_ptr<LineSegmentIntersector> picker
553 = new LineSegmentIntersector(Intersector::VIEW,
554 Vec3d(start.x(), start.y(), start.z()),
555 Vec3d(end.x(), end.y(), end.z()));
556 osgUtil::IntersectionVisitor iv(picker.get());
557 const_cast<Camera*>(camera)->accept(iv);
558 if (picker->containsIntersections()) {
559 intersections = picker->getIntersections();
565 intersections.clear();
569 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
571 using osgViewer::GraphicsWindow;
572 Camera* guiCamera = getGUICamera(cgroup);
575 Viewport* vport = guiCamera->getViewport();
577 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
580 globals->get_renderer()->getEventHandler()->setMouseWarped();
581 // Translate the warp request into the viewport of the GUI camera,
582 // send the request to the window, then transform the coordinates
583 // for the Viewer's event queue.
584 double wx = x + vport->x();
585 double wyUp = vport->height() + vport->y() - y;
587 const GraphicsContext::Traits* traits = gw->getTraits();
588 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
589 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
590 wy = traits->height - wyUp;
594 gw->getEventQueue()->mouseWarped(wx, wy);
595 gw->requestWarpPointer(wx, wy);
596 osgGA::GUIEventAdapter* eventState
597 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
599 = (eventState->getXmin()
600 + ((wx / double(traits->width))
601 * (eventState->getXmax() - eventState->getXmin())));
603 = (eventState->getYmin()
604 + ((wyUp / double(traits->height))
605 * (eventState->getYmax() - eventState->getYmin())));
606 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);