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 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
117 const Matrix& projection,
118 bool useMasterSceneData)
120 CameraInfo* info = new CameraInfo(flags);
121 // The camera group will always update the camera
122 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
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);
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);
149 void CameraGroup::update(const osg::Vec3d& position,
150 const osg::Quat& orientation)
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,
163 if ((info->flags & VIEW_ABSOLUTE) != 0)
164 viewMatrix = slave._viewOffset;
166 viewMatrix = masterView * slave._viewOffset;
167 camera->setViewMatrix(viewMatrix);
168 Matrix projectionMatrix;
169 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
170 projectionMatrix = slave._projectionOffset;
172 projectionMatrix = masterProj * slave._projectionOffset;
174 if (!info->farCamera.valid()) {
175 camera->setProjectionMatrix(projectionMatrix);
177 Camera* farCamera = info->farCamera.get();
178 farCamera->getViewport()->setViewport(info->x, info->y, info->width,
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);
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());
203 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
205 const float zNear = .1f;
206 const float zFar = 120000.0f;
207 _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
215 // A raw value for property nodes that references a class member via
217 template<class C, class T>
218 class RefMember : public SGRawValue<T>
221 RefMember (C *obj, T C::*ptr)
222 : _obj(obj), _ptr(ptr) {}
223 virtual ~RefMember () {}
224 virtual T getValue () const
226 return _obj.get()->*_ptr;
228 virtual bool setValue (T value)
230 _obj.get()->*_ptr = value;
233 virtual SGRawValue<T> * clone () const
235 return new RefMember(_obj.get(), _ptr);
242 template<typename C, typename T>
243 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
245 return RefMember<C, T>(obj, ptr);
248 template<typename C, typename T>
249 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
250 C* obj, T C::*ptr, T value)
252 SGPropertyNode* valNode = parent->getNode(childName);
253 RefMember<C, T> refMember = makeRefMember(obj, ptr);
255 valNode = parent->getNode(childName, true);
256 valNode->tie(refMember, false);
257 setValue(valNode, value);
259 valNode->tie(refMember, true);
263 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
264 const osg::GraphicsContext::Traits *traits)
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));
279 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
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;
287 // New style window declaration / definition
288 window = wBuild->buildWindow(windowNode);
290 // Old style: suck window params out of camera block
291 window = wBuild->buildWindow(cameraNode);
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));
308 const SGPropertyNode* viewNode = cameraNode->getNode("view");
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;
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));
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",
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;
360 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
361 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
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);
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());
378 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
379 GraphicsWindow* window)
381 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
382 const SGPropertyNode* windowNode = (cameraNode
383 ? cameraNode->getNode("window")
385 static int cameraNum = 0;
388 // New style window declaration / definition
389 window = wBuild->buildWindow(windowNode);
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());
416 // Disable statistics for the GUI camera.
417 result->camera->setStats(0);
421 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
422 SGPropertyNode* gnode)
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);
439 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
441 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
442 if ((*i)->flags & GUI)
444 (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
445 (*i)->farCamera->setCullMask(nm);
449 Camera* getGUICamera(CameraGroup* cgroup)
451 CameraGroup::CameraIterator end = cgroup->camerasEnd();
452 CameraGroup::CameraIterator result
453 = std::find_if(cgroup->camerasBegin(), end,
454 FlagTester<CameraInfo>(CameraGroup::GUI));
456 return (*result)->camera.get();
461 bool computeIntersections(const CameraGroup* cgroup,
462 const osgGA::GUIEventAdapter* ea,
463 osgUtil::LineSegmentIntersector::Intersections& intersections)
465 using osgUtil::Intersector;
466 using osgUtil::LineSegmentIntersector;
468 eventToWindowCoords(ea, x, y);
469 // Find camera that contains event
470 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
471 e = cgroup->camerasEnd();
474 const CameraInfo* cinfo = iter->get();
475 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
477 const Camera* camera = cinfo->camera.get();
478 if (camera->getGraphicsContext() != ea->getGraphicsContext())
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))
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();
499 intersections.clear();
503 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
505 using osgViewer::GraphicsWindow;
506 Camera* guiCamera = getGUICamera(cgroup);
509 Viewport* vport = guiCamera->getViewport();
511 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
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;
521 const GraphicsContext::Traits* traits = gw->getTraits();
522 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
523 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
524 wy = traits->height - wyUp;
528 gw->getEventQueue()->mouseWarped(wx, wy);
529 gw->requestWarpPointer(wx, wy);
530 osgGA::GUIEventAdapter* eventState
531 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
533 = (eventState->getXmin()
534 + ((wx / double(traits->width))
535 * (eventState->getXmax() - eventState->getXmin())));
537 = (eventState->getYmin()
538 + ((wyUp / double(traits->height))
539 * (eventState->getYmax() - eventState->getYmin())));
540 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);