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/structure/OSGUtils.hxx>
26 #include <simgear/scene/util/RenderConstants.hxx>
33 #include <osg/GraphicsContext>
38 #include <osg/Viewport>
40 #include <osgUtil/IntersectionVisitor>
42 #include <osgViewer/GraphicsWindow>
51 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
53 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
64 // Given a projection matrix, return a new one with the same frustum
65 // sides and new near / far values.
67 void makeNewProjMat(Matrixd& oldProj, double znear,
68 double zfar, Matrixd& projection)
71 // Slightly inflate the near & far planes to avoid objects at the
72 // extremes being clipped out.
76 // Clamp the projection matrix z values to the range (near, far)
77 double epsilon = 1.0e-6;
78 if (fabs(projection(0,3)) < epsilon &&
79 fabs(projection(1,3)) < epsilon &&
80 fabs(projection(2,3)) < epsilon) {
81 // Projection is Orthographic
82 epsilon = -1.0/(zfar - znear); // Used as a temp variable
83 projection(2,2) = 2.0*epsilon;
84 projection(3,2) = (zfar + znear)*epsilon;
86 // Projection is Perspective
87 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
88 (-znear*projection(2,3) + projection(3,3));
89 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
90 (-zfar*projection(2,3) + projection(3,3));
91 double ratio = fabs(2.0/(trans_near - trans_far));
92 double center = -0.5*(trans_near + trans_far);
94 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
97 0.0, 0.0, center*ratio, 1.0));
101 void installCullVisitor(Camera* camera)
104 osgViewer::Renderer* renderer
105 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
106 for (int i = 0; i < 2; ++i) {
107 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
108 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
116 void updateCameras(const CameraInfo* info)
118 if (info->camera.valid())
119 info->camera->getViewport()->setViewport(info->x, info->y,
120 info->width, info->height);
121 if (info->farCamera.valid())
122 info->farCamera->getViewport()->setViewport(info->x, info->y,
123 info->width, info->height);
126 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
128 const Matrix& projection,
129 bool useMasterSceneData)
131 CameraInfo* info = new CameraInfo(flags);
132 // The camera group will always update the camera
133 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
135 Camera* farCamera = 0;
136 if ((flags & (GUI | ORTHO)) == 0) {
137 farCamera = simgear::clone(camera);
138 farCamera->setGraphicsContext(camera->getGraphicsContext());
139 // Each camera's viewport is written when the window is
140 // resized; if the the viewport isn't copied here, it gets updated
141 // twice and ends up with the wrong value.
142 farCamera->setViewport(simgear::clone(camera->getViewport()));
143 _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
144 installCullVisitor(farCamera);
145 info->farCamera = farCamera;
146 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
147 farCamera->setRenderOrder(Camera::NESTED_RENDER, info->farSlaveIndex);
148 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
150 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
151 _viewer->addSlave(camera, view, projection, useMasterSceneData);
152 installCullVisitor(camera);
153 info->camera = camera;
154 info->slaveIndex = _viewer->getNumSlaves() - 1;
155 camera->setRenderOrder(Camera::NESTED_RENDER, info->slaveIndex);
156 _cameras.push_back(info);
160 void CameraGroup::update(const osg::Vec3d& position,
161 const osg::Quat& orientation)
163 const Matrix masterView(osg::Matrix::translate(-position)
164 * osg::Matrix::rotate(orientation.inverse()));
165 _viewer->getCamera()->setViewMatrix(masterView);
166 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
167 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
168 const CameraInfo* info = i->get();
169 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
170 // refreshes camera viewports (for now)
172 Camera* camera = info->camera.get();
174 if ((info->flags & VIEW_ABSOLUTE) != 0)
175 viewMatrix = slave._viewOffset;
177 viewMatrix = masterView * slave._viewOffset;
178 camera->setViewMatrix(viewMatrix);
179 Matrix projectionMatrix;
180 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
181 projectionMatrix = slave._projectionOffset;
183 projectionMatrix = masterProj * slave._projectionOffset;
185 if (!info->farCamera.valid()) {
186 camera->setProjectionMatrix(projectionMatrix);
188 Camera* farCamera = info->farCamera.get();
189 farCamera->setViewMatrix(viewMatrix);
190 double left, right, bottom, top, parentNear, parentFar;
191 projectionMatrix.getFrustum(left, right, bottom, top,
192 parentNear, parentFar);
193 if (parentFar < 100.0) {
194 camera->setProjectionMatrix(projectionMatrix);
195 camera->setCullMask(camera->getCullMask()
196 | simgear::BACKGROUND_BIT);
197 farCamera->setNodeMask(0);
199 Matrix nearProj, farProj;
200 makeNewProjMat(projectionMatrix, parentNear, 100.0, nearProj);
201 makeNewProjMat(projectionMatrix, 100.0, parentFar, farProj);
202 camera->setProjectionMatrix(nearProj);
203 camera->setCullMask(camera->getCullMask()
204 & ~simgear::BACKGROUND_BIT);
205 farCamera->setProjectionMatrix(farProj);
206 farCamera->setNodeMask(camera->getNodeMask());
212 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
214 const float zNear = .1f;
215 const float zFar = 120000.0f;
216 _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
224 // A raw value for property nodes that references a class member via
226 template<class C, class T>
227 class RefMember : public SGRawValue<T>
230 RefMember (C *obj, T C::*ptr)
231 : _obj(obj), _ptr(ptr) {}
232 virtual ~RefMember () {}
233 virtual T getValue () const
235 return _obj.get()->*_ptr;
237 virtual bool setValue (T value)
239 _obj.get()->*_ptr = value;
242 virtual SGRawValue<T> * clone () const
244 return new RefMember(_obj.get(), _ptr);
251 template<typename C, typename T>
252 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
254 return RefMember<C, T>(obj, ptr);
257 template<typename C, typename T>
258 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
259 C* obj, T C::*ptr, T value)
261 SGPropertyNode* valNode = parent->getNode(childName);
262 RefMember<C, T> refMember = makeRefMember(obj, ptr);
264 valNode = parent->getNode(childName, true);
265 valNode->tie(refMember, false);
266 setValue(valNode, value);
268 valNode->tie(refMember, true);
272 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
273 const osg::GraphicsContext::Traits *traits)
275 using namespace flightgear;
276 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
277 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
278 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
279 static_cast<double>(traits->width));
280 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
281 static_cast<double>(traits->height));
288 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
290 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
291 const SGPropertyNode* windowNode = cameraNode->getNode("window");
292 GraphicsWindow* window = 0;
293 static int cameraNum = 0;
294 int cameraFlags = DO_INTERSECTION_TEST;
296 // New style window declaration / definition
297 window = wBuild->buildWindow(windowNode);
299 // Old style: suck window params out of camera block
300 window = wBuild->buildWindow(cameraNode);
305 Camera* camera = new Camera;
306 camera->setAllowEventFocus(false);
307 camera->setGraphicsContext(window->gc.get());
308 camera->setViewport(new Viewport);
309 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
310 | CullSettings::VIEW_FRUSTUM_CULLING);
311 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
312 & ~(CullSettings::CULL_MASK
313 | CullSettings::CULLING_MODE));
317 const SGPropertyNode* viewNode = cameraNode->getNode("view");
319 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
320 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
321 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
322 double x = viewNode->getDoubleValue("x", 0.0);
323 double y = viewNode->getDoubleValue("y", 0.0);
324 double z = viewNode->getDoubleValue("z", 0.0);
325 // Build a view matrix, which is the inverse of a model
326 // orientation matrix.
327 vOff = (Matrix::translate(-x, -y, -z)
328 * Matrix::rotate(-DegreesToRadians(heading),
329 Vec3d(0.0, 1.0, 0.0),
330 -DegreesToRadians(pitch),
331 Vec3d(1.0, 0.0, 0.0),
332 -DegreesToRadians(roll),
333 Vec3d(0.0, 0.0, 1.0)));
334 if (viewNode->getBoolValue("absolute", false))
335 cameraFlags |= VIEW_ABSOLUTE;
337 // Old heading parameter, works in the opposite direction
338 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
339 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
341 const SGPropertyNode* projectionNode = 0;
342 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
343 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
344 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
346 double zNear = projectionNode->getDoubleValue("near", 0.0);
347 double zFar = projectionNode->getDoubleValue("far", 0.0);
348 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
349 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
350 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
351 double right = tan_fovy * aspectRatio * zNear + offsetX;
352 double left = -tan_fovy * aspectRatio * zNear + offsetX;
353 double top = tan_fovy * zNear + offsetY;
354 double bottom = -tan_fovy * zNear + offsetY;
355 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
356 cameraFlags |= PROJECTION_ABSOLUTE;
357 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
358 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
359 double top = projectionNode->getDoubleValue("top", 0.0);
360 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
361 double left = projectionNode->getDoubleValue("left", 0.0);
362 double right = projectionNode->getDoubleValue("right", 0.0);
363 double zNear = projectionNode->getDoubleValue("near", 0.0);
364 double zFar = projectionNode->getDoubleValue("far", 0.0);
365 if (cameraNode->getNode("frustum")) {
366 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
367 cameraFlags |= PROJECTION_ABSOLUTE;
369 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
370 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
373 // old style shear parameters
374 double shearx = cameraNode->getDoubleValue("shear-x", 0);
375 double sheary = cameraNode->getDoubleValue("shear-y", 0);
376 pOff.makeTranslate(-shearx, -sheary, 0);
378 CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
379 // If a viewport isn't set on the camera, then it's hard to dig it
380 // out of the SceneView objects in the viewer, and the coordinates
381 // of mouse events are somewhat bizzare.
382 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
383 buildViewport(info, viewportNode, window->gc->getTraits());
388 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
389 GraphicsWindow* window)
391 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
392 const SGPropertyNode* windowNode = (cameraNode
393 ? cameraNode->getNode("window")
395 static int cameraNum = 0;
398 // New style window declaration / definition
399 window = wBuild->buildWindow(windowNode);
405 Camera* camera = new Camera;
406 camera->setAllowEventFocus(false);
407 camera->setGraphicsContext(window->gc.get());
408 camera->setViewport(new Viewport);
409 // XXX Camera needs to be drawn last; eventually the render order
410 // should be assigned by a camera manager.
411 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
412 camera->setClearMask(0);
413 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
414 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
415 | CullSettings::CULLING_MODE));
416 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
417 camera->setCullingMode(osg::CullSettings::NO_CULLING);
418 camera->setProjectionResizePolicy(Camera::FIXED);
419 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
420 const int cameraFlags = GUI;
421 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
422 Matrixd::identity(), false);
423 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
424 buildViewport(result, viewportNode, window->gc->getTraits());
426 // Disable statistics for the GUI camera.
427 result->camera->setStats(0);
428 updateCameras(result);
432 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
433 SGPropertyNode* gnode)
435 CameraGroup* cgroup = new CameraGroup(viewer);
436 for (int i = 0; i < gnode->nChildren(); ++i) {
437 SGPropertyNode* pNode = gnode->getChild(i);
438 const char* name = pNode->getName();
439 if (!strcmp(name, "camera")) {
440 cgroup->buildCamera(pNode);
441 } else if (!strcmp(name, "window")) {
442 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
443 } else if (!strcmp(name, "gui")) {
444 cgroup->buildGUICamera(pNode);
450 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
452 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
453 if ((*i)->flags & GUI)
455 (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
456 (*i)->farCamera->setCullMask(nm);
460 void CameraGroup::resized()
462 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
463 CameraInfo *info = i->get();
464 const Viewport* viewport = info->camera->getViewport();
465 info->x = viewport->x();
466 info->y = viewport->y();
467 info->width = viewport->width();
468 info->height = viewport->height();
472 Camera* getGUICamera(CameraGroup* cgroup)
474 CameraGroup::CameraIterator end = cgroup->camerasEnd();
475 CameraGroup::CameraIterator result
476 = std::find_if(cgroup->camerasBegin(), end,
477 FlagTester<CameraInfo>(CameraGroup::GUI));
479 return (*result)->camera.get();
484 bool computeIntersections(const CameraGroup* cgroup,
485 const osgGA::GUIEventAdapter* ea,
486 osgUtil::LineSegmentIntersector::Intersections& intersections)
488 using osgUtil::Intersector;
489 using osgUtil::LineSegmentIntersector;
491 eventToWindowCoords(ea, x, y);
492 // Find camera that contains event
493 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
494 e = cgroup->camerasEnd();
497 const CameraInfo* cinfo = iter->get();
498 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
500 const Camera* camera = cinfo->camera.get();
501 if (camera->getGraphicsContext() != ea->getGraphicsContext())
503 const Viewport* viewport = camera->getViewport();
504 double epsilon = 0.5;
505 if (!(x >= viewport->x() - epsilon
506 && x < viewport->x() + viewport->width() -1.0 + epsilon
507 && y >= viewport->y() - epsilon
508 && y < viewport->y() + viewport->height() -1.0 + epsilon))
510 LineSegmentIntersector::CoordinateFrame cf = Intersector::WINDOW;
511 ref_ptr<LineSegmentIntersector> picker
512 = new LineSegmentIntersector(cf, x, y);
513 osgUtil::IntersectionVisitor iv(picker.get());
514 const_cast<Camera*>(camera)->accept(iv);
515 if (picker->containsIntersections()) {
516 intersections = picker->getIntersections();
522 intersections.clear();
526 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
528 using osgViewer::GraphicsWindow;
529 Camera* guiCamera = getGUICamera(cgroup);
532 Viewport* vport = guiCamera->getViewport();
534 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
537 globals->get_renderer()->getEventHandler()->setMouseWarped();
538 // Translate the warp request into the viewport of the GUI camera,
539 // send the request to the window, then transform the coordinates
540 // for the Viewer's event queue.
541 double wx = x + vport->x();
542 double wyUp = vport->height() + vport->y() - y;
544 const GraphicsContext::Traits* traits = gw->getTraits();
545 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
546 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
547 wy = traits->height - wyUp;
551 gw->getEventQueue()->mouseWarped(wx, wy);
552 gw->requestWarpPointer(wx, wy);
553 osgGA::GUIEventAdapter* eventState
554 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
556 = (eventState->getXmin()
557 + ((wx / double(traits->width))
558 * (eventState->getXmax() - eventState->getXmin())));
560 = (eventState->getYmin()
561 + ((wyUp / double(traits->height))
562 * (eventState->getYmax() - eventState->getYmin())));
563 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);