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.
17 #include "CameraGroup.hxx"
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>
32 #include <osg/GraphicsContext>
37 #include <osg/Viewport>
39 #include <osgUtil/IntersectionVisitor>
41 #include <osgViewer/GraphicsWindow>
50 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
52 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
63 // Given a projection matrix, return a new one with the same frustum
64 // sides and new near / far values.
66 void makeNewProjMat(Matrixd& oldProj, double znear,
67 double zfar, Matrixd& projection)
70 // Slightly inflate the near & far planes to avoid objects at the
71 // extremes being clipped out.
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;
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);
93 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
96 0.0, 0.0, center*ratio, 1.0));
100 void installCullVisitor(Camera* camera)
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);
115 void updateCameras(const CameraInfo* info)
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);
125 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
127 const Matrix& projection,
128 bool useMasterSceneData)
130 CameraInfo* info = new CameraInfo(flags);
131 // The camera group will always update the camera
132 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
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);
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);
159 void CameraGroup::update(const osg::Vec3d& position,
160 const osg::Quat& orientation)
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)
171 Camera* camera = info->camera.get();
173 if ((info->flags & VIEW_ABSOLUTE) != 0)
174 viewMatrix = slave._viewOffset;
176 viewMatrix = masterView * slave._viewOffset;
177 camera->setViewMatrix(viewMatrix);
178 Matrix projectionMatrix;
179 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
180 projectionMatrix = slave._projectionOffset;
182 projectionMatrix = masterProj * slave._projectionOffset;
184 if (!info->farCamera.valid()) {
185 camera->setProjectionMatrix(projectionMatrix);
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);
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());
211 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
213 const float zNear = .1f;
214 const float zFar = 120000.0f;
215 _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
223 // A raw value for property nodes that references a class member via
225 template<class C, class T>
226 class RefMember : public SGRawValue<T>
229 RefMember (C *obj, T C::*ptr)
230 : _obj(obj), _ptr(ptr) {}
231 virtual ~RefMember () {}
232 virtual T getValue () const
234 return _obj.get()->*_ptr;
236 virtual bool setValue (T value)
238 _obj.get()->*_ptr = value;
241 virtual SGRawValue<T> * clone () const
243 return new RefMember(_obj.get(), _ptr);
250 template<typename C, typename T>
251 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
253 return RefMember<C, T>(obj, ptr);
256 template<typename C, typename T>
257 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
258 C* obj, T C::*ptr, T value)
260 SGPropertyNode* valNode = parent->getNode(childName);
261 RefMember<C, T> refMember = makeRefMember(obj, ptr);
263 valNode = parent->getNode(childName, true);
264 valNode->tie(refMember, false);
265 setValue(valNode, value);
267 valNode->tie(refMember, true);
271 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
272 const osg::GraphicsContext::Traits *traits)
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));
287 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
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;
295 // New style window declaration / definition
296 window = wBuild->buildWindow(windowNode);
298 // Old style: suck window params out of camera block
299 window = wBuild->buildWindow(cameraNode);
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));
316 const SGPropertyNode* viewNode = cameraNode->getNode("view");
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;
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));
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",
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;
368 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
369 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
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);
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());
386 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
387 GraphicsWindow* window)
389 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
390 const SGPropertyNode* windowNode = (cameraNode
391 ? cameraNode->getNode("window")
393 static int cameraNum = 0;
396 // New style window declaration / definition
397 window = wBuild->buildWindow(windowNode);
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());
424 // Disable statistics for the GUI camera.
425 result->camera->setStats(0);
426 updateCameras(result);
430 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
431 SGPropertyNode* gnode)
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);
448 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
450 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
451 if ((*i)->flags & GUI)
453 (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
454 (*i)->farCamera->setCullMask(nm);
458 void CameraGroup::resized()
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();
470 Camera* getGUICamera(CameraGroup* cgroup)
472 CameraGroup::CameraIterator end = cgroup->camerasEnd();
473 CameraGroup::CameraIterator result
474 = std::find_if(cgroup->camerasBegin(), end,
475 FlagTester<CameraInfo>(CameraGroup::GUI));
477 return (*result)->camera.get();
482 bool computeIntersections(const CameraGroup* cgroup,
483 const osgGA::GUIEventAdapter* ea,
484 osgUtil::LineSegmentIntersector::Intersections& intersections)
486 using osgUtil::Intersector;
487 using osgUtil::LineSegmentIntersector;
489 eventToWindowCoords(ea, x, y);
490 // Find camera that contains event
491 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
492 e = cgroup->camerasEnd();
495 const CameraInfo* cinfo = iter->get();
496 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
498 const Camera* camera = cinfo->camera.get();
499 if (camera->getGraphicsContext() != ea->getGraphicsContext())
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))
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();
520 intersections.clear();
524 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
526 using osgViewer::GraphicsWindow;
527 Camera* guiCamera = getGUICamera(cgroup);
530 Viewport* vport = guiCamera->getViewport();
532 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
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;
542 const GraphicsContext::Traits* traits = gw->getTraits();
543 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
544 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
545 wy = traits->height - wyUp;
549 gw->getEventQueue()->mouseWarped(wx, wy);
550 gw->requestWarpPointer(wx, wy);
551 osgGA::GUIEventAdapter* eventState
552 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
554 = (eventState->getXmin()
555 + ((wx / double(traits->width))
556 * (eventState->getXmax() - eventState->getXmin())));
558 = (eventState->getYmin()
559 + ((wyUp / double(traits->height))
560 * (eventState->getYmax() - eventState->getYmin())));
561 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);