1 // Copyright (C) 2008 Tim Moore
2 // Copyright (C) 2011 Mathias Froehlich
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 #include "CameraGroup.hxx"
24 #include "fg_props.hxx"
25 #include "globals.hxx"
26 #include "renderer.hxx"
27 #include "FGEventHandler.hxx"
28 #include "WindowBuilder.hxx"
29 #include "WindowSystemAdapter.hxx"
30 #include <simgear/props/props.hxx>
31 #include <simgear/structure/OSGUtils.hxx>
32 #include <simgear/structure/OSGVersion.hxx>
33 #include <simgear/scene/material/EffectCullVisitor.hxx>
34 #include <simgear/scene/util/RenderConstants.hxx>
41 #include <osg/Geometry>
42 #include <osg/GraphicsContext>
43 #include <osg/io_utils>
47 #include <osg/Program>
51 #include <osg/Viewport>
53 #include <osgUtil/IntersectionVisitor>
55 #include <osgViewer/GraphicsWindow>
56 #include <osgViewer/Renderer>
59 invert(const osg::Matrix& matrix)
61 return osg::Matrix::inverse(matrix);
64 /// Returns the zoom factor of the master camera.
65 /// The reference fov is the historic 55 deg
69 double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
72 return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
76 preMult(const osg::Vec2d& v, const osg::Matrix& m)
78 osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
79 return osg::Vec2d(tmp[0], tmp[1]);
83 relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
84 const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
86 // Track the way from one projection space to the other:
89 // where P0 is the projection template sensible for the given window size,
90 // T is a translation matrix and S a scale matrix.
91 // We need to determine T and S so that the reference points in the parents
92 // projection space match the two reference points in this cameras projection space.
94 // Starting from the parents camera projection space, we get into this cameras
95 // projection space by the transform matrix:
96 // P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
97 // So, at first compute that matrix without T*S and determine S and T from that
99 // Ok, now osg uses the inverse matrix multiplication order, thus:
100 osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
101 // Compute the parents reference points in the current projection space
102 // without the yet unknown T and S
103 osg::Vec2d pRefInThis[2] = {
104 preMult(pRef[0], PtoPwithoutTS),
105 preMult(pRef[1], PtoPwithoutTS)
108 // To get the same zoom, rescale to match the parents size
109 double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
110 osg::Matrix S = osg::Matrix::scale(s, s, 1);
112 // For the translation offset, incorporate the now known scale
113 // and recompute the position ot the first reference point in the
114 // currents projection space without the yet unknown T.
115 pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
116 // The translation is then the difference of the reference points
117 osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));
119 // Compose and return the desired final projection matrix
130 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
132 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
143 // Given a projection matrix, return a new one with the same frustum
144 // sides and new near / far values.
146 void makeNewProjMat(Matrixd& oldProj, double znear,
147 double zfar, Matrixd& projection)
149 projection = oldProj;
150 // Slightly inflate the near & far planes to avoid objects at the
151 // extremes being clipped out.
155 // Clamp the projection matrix z values to the range (near, far)
156 double epsilon = 1.0e-6;
157 if (fabs(projection(0,3)) < epsilon &&
158 fabs(projection(1,3)) < epsilon &&
159 fabs(projection(2,3)) < epsilon) {
160 // Projection is Orthographic
161 epsilon = -1.0/(zfar - znear); // Used as a temp variable
162 projection(2,2) = 2.0*epsilon;
163 projection(3,2) = (zfar + znear)*epsilon;
165 // Projection is Perspective
166 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
167 (-znear*projection(2,3) + projection(3,3));
168 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
169 (-zfar*projection(2,3) + projection(3,3));
170 double ratio = fabs(2.0/(trans_near - trans_far));
171 double center = -0.5*(trans_near + trans_far);
173 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
175 0.0, 0.0, ratio, 0.0,
176 0.0, 0.0, center*ratio, 1.0));
180 void installCullVisitor(Camera* camera)
182 osgViewer::Renderer* renderer
183 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
184 for (int i = 0; i < 2; ++i) {
185 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
186 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
187 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
189 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
190 identifier = sceneView->getCullVisitor()->getIdentifier();
191 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
192 sceneView->getCullVisitor()->setIdentifier(identifier.get());
194 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
195 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
196 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
198 identifier = sceneView->getCullVisitorRight()->getIdentifier();
199 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
200 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
208 void updateCameras(const CameraInfo* info)
210 if (info->camera.valid())
211 info->camera->getViewport()->setViewport(info->x, info->y,
212 info->width, info->height);
213 if (info->farCamera.valid())
214 info->farCamera->getViewport()->setViewport(info->x, info->y,
215 info->width, info->height);
218 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
220 const Matrix& projection,
221 bool useMasterSceneData)
223 CameraInfo* info = new CameraInfo(flags);
224 // The camera group will always update the camera
225 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
227 Camera* farCamera = 0;
228 if ((flags & (GUI | ORTHO)) == 0) {
229 farCamera = new Camera;
230 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
231 farCamera->setGraphicsContext(camera->getGraphicsContext());
232 farCamera->setCullingMode(camera->getCullingMode());
233 farCamera->setInheritanceMask(camera->getInheritanceMask());
234 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
235 // Each camera's viewport is written when the window is
236 // resized; if the the viewport isn't copied here, it gets updated
237 // twice and ends up with the wrong value.
238 farCamera->setViewport(simgear::clone(camera->getViewport()));
239 farCamera->setDrawBuffer(camera->getDrawBuffer());
240 farCamera->setReadBuffer(camera->getReadBuffer());
241 farCamera->setRenderTargetImplementation(
242 camera->getRenderTargetImplementation());
243 const Camera::BufferAttachmentMap& bufferMap
244 = camera->getBufferAttachmentMap();
245 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
247 Camera::COLOR_BUFFER,
248 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
250 _viewer->addSlave(farCamera, projection, view, useMasterSceneData);
251 installCullVisitor(farCamera);
252 info->farCamera = farCamera;
253 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
254 farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
255 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
256 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
258 _viewer->addSlave(camera, projection, view, useMasterSceneData);
259 installCullVisitor(camera);
260 info->camera = camera;
261 info->slaveIndex = _viewer->getNumSlaves() - 1;
262 camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
263 _cameras.push_back(info);
267 void CameraGroup::update(const osg::Vec3d& position,
268 const osg::Quat& orientation)
270 const Matrix masterView(osg::Matrix::translate(-position)
271 * osg::Matrix::rotate(orientation.inverse()));
272 _viewer->getCamera()->setViewMatrix(masterView);
273 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
274 double masterZoomFactor = zoomFactor();
275 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
276 const CameraInfo* info = i->get();
277 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
278 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
279 // refreshes camera viewports (for now)
282 Camera* camera = info->camera.get();
284 if ((info->flags & VIEW_ABSOLUTE) != 0)
285 viewMatrix = slave._viewOffset;
287 viewMatrix = masterView * slave._viewOffset;
288 camera->setViewMatrix(viewMatrix);
289 Matrix projectionMatrix;
290 if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
291 if (info->flags & ENABLE_MASTER_ZOOM) {
292 if (info->relativeCameraParent < _cameras.size()) {
293 // template projection matrix and view matrix of the current camera
294 osg::Matrix P0 = slave._projectionOffset;
295 osg::Matrix R = viewMatrix;
297 // The already known projection and view matrix of the parent camera
298 const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
299 osg::Matrix pP = parentInfo->camera->getProjectionMatrix();
300 osg::Matrix pR = parentInfo->camera->getViewMatrix();
302 // And the projection matrix derived from P0 so that the reference points match
303 projectionMatrix = relativeProjection(P0, R, info->thisReference,
304 pP, pR, info->parentReference);
307 // We want to zoom, so take the original matrix and apply the zoom to it.
308 projectionMatrix = slave._projectionOffset;
309 projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
312 projectionMatrix = slave._projectionOffset;
315 projectionMatrix = masterProj * slave._projectionOffset;
318 if (!info->farCamera.valid()) {
319 camera->setProjectionMatrix(projectionMatrix);
321 Camera* farCamera = info->farCamera.get();
322 farCamera->setViewMatrix(viewMatrix);
323 double left, right, bottom, top, parentNear, parentFar;
324 projectionMatrix.getFrustum(left, right, bottom, top,
325 parentNear, parentFar);
326 if ((info->flags & FIXED_NEAR_FAR) == 0) {
330 if (parentFar < _nearField || _nearField == 0.0f) {
331 camera->setProjectionMatrix(projectionMatrix);
332 camera->setCullMask(camera->getCullMask()
333 | simgear::BACKGROUND_BIT);
334 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
335 farCamera->setNodeMask(0);
337 Matrix nearProj, farProj;
338 makeNewProjMat(projectionMatrix, parentNear, _nearField,
340 makeNewProjMat(projectionMatrix, _nearField, parentFar,
342 camera->setProjectionMatrix(nearProj);
343 camera->setCullMask(camera->getCullMask()
344 & ~simgear::BACKGROUND_BIT);
345 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
346 farCamera->setProjectionMatrix(farProj);
347 farCamera->setNodeMask(camera->getNodeMask());
353 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
355 if (vfov != 0.0f && aspectRatio != 0.0f)
357 ->setProjectionMatrixAsPerspective(vfov,
362 double CameraGroup::getMasterAspectRatio() const
364 if (_cameras.empty())
367 const CameraInfo* info = _cameras.front();
369 const osg::Viewport* viewport = info->camera->getViewport();
374 return static_cast<double>(viewport->height()) / viewport->width();
381 // A raw value for property nodes that references a class member via
383 template<class C, class T>
384 class RefMember : public SGRawValue<T>
387 RefMember (C *obj, T C::*ptr)
388 : _obj(obj), _ptr(ptr) {}
389 virtual ~RefMember () {}
390 virtual T getValue () const
392 return _obj.get()->*_ptr;
394 virtual bool setValue (T value)
396 _obj.get()->*_ptr = value;
399 virtual SGRawValue<T> * clone () const
401 return new RefMember(_obj.get(), _ptr);
408 template<typename C, typename T>
409 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
411 return RefMember<C, T>(obj, ptr);
414 template<typename C, typename T>
415 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
416 C* obj, T C::*ptr, T value)
418 SGPropertyNode* valNode = parent->getNode(childName);
419 RefMember<C, T> refMember = makeRefMember(obj, ptr);
421 valNode = parent->getNode(childName, true);
422 valNode->tie(refMember, false);
423 setValue(valNode, value);
425 valNode->tie(refMember, true);
429 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
430 const osg::GraphicsContext::Traits *traits)
432 using namespace flightgear;
433 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
434 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
435 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
436 static_cast<double>(traits->width));
437 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
438 static_cast<double>(traits->height));
445 // Mostly copied from osg's osgViewer/View.cpp
447 static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(
448 const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
449 double sphere_radius, double collar_radius,
450 Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
452 osg::Vec3d center(0.0,0.0,0.0);
453 osg::Vec3d eye(0.0,0.0,0.0);
455 double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
457 bool texcoord_flip = false;
459 osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
462 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
463 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
465 // create the quad to visualize.
466 osg::Geometry* geometry = new osg::Geometry();
468 geometry->setSupportsDisplayList(false);
470 osg::Vec3 xAxis(widthVector);
471 float width = widthVector.length();
474 osg::Vec3 yAxis(heightVector);
475 float height = heightVector.length();
480 osg::Vec3Array* vertices = new osg::Vec3Array;
481 osg::Vec2Array* texcoords0 = new osg::Vec2Array;
482 osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
483 osg::Vec4Array* colors = new osg::Vec4Array;
485 osg::Vec3 bottom = origin;
486 osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
487 osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
489 osg::Vec3 top = origin + yAxis*height;
491 osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
492 float screenRadius = heightVector.length() * 0.5f;
494 geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
496 for(int i=0;i<noSteps;++i)
498 osg::Vec3 cursor = bottom+dy*(float)i;
499 for(int j=0;j<noSteps;++j)
501 osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
502 double theta = texcoord.x() * 2.0 * osg::PI;
503 double phi = (1.0-texcoord.y()) * osg::PI;
505 if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
507 osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
508 pos = pos*projectorMatrix;
510 double alpha = atan2(pos.x(), pos.y());
511 if (alpha<0.0) alpha += 2.0*osg::PI;
513 double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
514 if (beta<0.0) beta += 2.0*osg::PI;
516 double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
517 if (gamma<0.0) gamma += 2.0*osg::PI;
520 osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
523 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
525 vertices->push_back(v);
527 texcoords0->push_back( texcoord );
529 osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
532 colors->push_back(intensityMap->getColor(texcoord1));
536 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
537 if (texcoords1) texcoords1->push_back( texcoord1 );
545 // pass the created vertex array to the points geometry object.
546 geometry->setVertexArray(vertices);
548 geometry->setColorArray(colors);
549 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
551 geometry->setTexCoordArray(0,texcoords0);
552 if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
554 osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
555 geometry->addPrimitiveSet(elements);
557 for(int i=0;i<noSteps-1;++i)
559 for(int j=0;j<noSteps-1;++j)
561 int i1 = j+(i+1)*noSteps;
562 int i2 = j+(i)*noSteps;
563 int i3 = j+1+(i)*noSteps;
564 int i4 = j+1+(i+1)*noSteps;
566 osg::Vec3& v1 = (*vertices)[i1];
567 osg::Vec3& v2 = (*vertices)[i2];
568 osg::Vec3& v3 = (*vertices)[i3];
569 osg::Vec3& v4 = (*vertices)[i4];
571 if ((v1-screenCenter).length()>screenRadius) continue;
572 if ((v2-screenCenter).length()>screenRadius) continue;
573 if ((v3-screenCenter).length()>screenRadius) continue;
574 if ((v4-screenCenter).length()>screenRadius) continue;
576 elements->push_back(i1);
577 elements->push_back(i2);
578 elements->push_back(i3);
580 elements->push_back(i1);
581 elements->push_back(i3);
582 elements->push_back(i4);
589 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
592 const SGPropertyNode* texNode = psNode->getNode("texture");
597 string texName = texNode->getStringValue();
598 TextureMap::iterator itr = _textureTargets.find(texName);
599 if (itr == _textureTargets.end()) {
603 Viewport* viewport = camera->getViewport();
604 float width = viewport->width();
605 float height = viewport->height();
606 TextureRectangle* texRect = itr->second.get();
607 double radius = psNode->getDoubleValue("radius", 1.0);
608 double collar = psNode->getDoubleValue("collar", 0.45);
609 Geode* geode = new Geode();
610 geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(
611 Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
612 Vec3(0.0f,height,0.0f), radius, collar));
614 // new we need to add the texture to the mesh, we do so by creating a
615 // StateSet to contain the Texture StateAttribute.
616 StateSet* stateset = geode->getOrCreateStateSet();
617 stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
618 stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
620 TexMat* texmat = new TexMat;
621 texmat->setScaleByTextureRectangleSize(true);
622 stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
624 if (!applyIntensityMapAsColours && intensityMap)
626 stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
629 // add subgraph to render
630 camera->addChild(geode);
631 camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
632 camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
633 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
634 camera->setCullingMode(osg::CullSettings::NO_CULLING);
635 camera->setName("DistortionCorrectionCamera");
638 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
640 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
641 const SGPropertyNode* windowNode = cameraNode->getNode("window");
642 GraphicsWindow* window = 0;
643 int cameraFlags = DO_INTERSECTION_TEST;
645 // New style window declaration / definition
646 window = wBuild->buildWindow(windowNode);
648 // Old style: suck window params out of camera block
649 window = wBuild->buildWindow(cameraNode);
654 Camera* camera = new Camera;
655 camera->setAllowEventFocus(false);
656 camera->setGraphicsContext(window->gc.get());
657 camera->setViewport(new Viewport);
658 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
659 | CullSettings::VIEW_FRUSTUM_CULLING);
660 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
661 & ~(CullSettings::CULL_MASK
662 | CullSettings::CULLING_MODE
663 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
664 | CullSettings::CLEAR_MASK
669 const SGPropertyNode* viewNode = cameraNode->getNode("view");
671 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
672 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
673 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
674 double x = viewNode->getDoubleValue("x", 0.0);
675 double y = viewNode->getDoubleValue("y", 0.0);
676 double z = viewNode->getDoubleValue("z", 0.0);
677 // Build a view matrix, which is the inverse of a model
678 // orientation matrix.
679 vOff = (Matrix::translate(-x, -y, -z)
680 * Matrix::rotate(-DegreesToRadians(heading),
681 Vec3d(0.0, 1.0, 0.0),
682 -DegreesToRadians(pitch),
683 Vec3d(1.0, 0.0, 0.0),
684 -DegreesToRadians(roll),
685 Vec3d(0.0, 0.0, 1.0)));
686 if (viewNode->getBoolValue("absolute", false))
687 cameraFlags |= VIEW_ABSOLUTE;
689 // Old heading parameter, works in the opposite direction
690 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
691 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
693 // Configuring the physical dimensions of a monitor
694 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
695 double physicalWidth = viewportNode->getDoubleValue("width", 1024);
696 double physicalHeight = viewportNode->getDoubleValue("height", 768);
697 double bezelHeightTop = 0;
698 double bezelHeightBottom = 0;
699 double bezelWidthLeft = 0;
700 double bezelWidthRight = 0;
701 const SGPropertyNode* physicalDimensionsNode = 0;
702 if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
703 physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
704 physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
705 const SGPropertyNode* bezelNode = 0;
706 if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
707 bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
708 bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
709 bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
710 bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
714 unsigned parentCameraIndex = ~0u;
715 osg::Vec2d parentReference[2];
716 osg::Vec2d thisReference[2];
717 SGPropertyNode* projectionNode = 0;
718 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
719 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
720 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
722 double zNear = projectionNode->getDoubleValue("near", 0.0);
723 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
724 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
725 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
726 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
727 double right = tan_fovy * aspectRatio * zNear + offsetX;
728 double left = -tan_fovy * aspectRatio * zNear + offsetX;
729 double top = tan_fovy * zNear + offsetY;
730 double bottom = -tan_fovy * zNear + offsetY;
731 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
732 cameraFlags |= PROJECTION_ABSOLUTE;
733 if (projectionNode->getBoolValue("fixed-near-far", true))
734 cameraFlags |= FIXED_NEAR_FAR;
735 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
736 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
737 double top = projectionNode->getDoubleValue("top", 0.0);
738 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
739 double left = projectionNode->getDoubleValue("left", 0.0);
740 double right = projectionNode->getDoubleValue("right", 0.0);
741 double zNear = projectionNode->getDoubleValue("near", 0.0);
742 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
743 if (cameraNode->getNode("frustum")) {
744 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
745 cameraFlags |= PROJECTION_ABSOLUTE;
747 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
748 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
750 if (projectionNode->getBoolValue("fixed-near-far", true))
751 cameraFlags |= FIXED_NEAR_FAR;
752 } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
753 double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
754 double xoff = projectionNode->getDoubleValue("x-offset", 0);
755 double yoff = projectionNode->getDoubleValue("y-offset", 0);
756 double left = -0.5*physicalWidth - xoff;
757 double right = 0.5*physicalWidth - xoff;
758 double bottom = -0.5*physicalHeight - yoff;
759 double top = 0.5*physicalHeight - yoff;
760 pOff.makeFrustum(left, right, bottom, top, zNear, zNear*1000);
761 cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
762 } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
763 || (projectionNode = cameraNode->getNode("left-of-perspective"))
764 || (projectionNode = cameraNode->getNode("above-perspective"))
765 || (projectionNode = cameraNode->getNode("below-perspective"))
766 || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
767 std::string name = projectionNode->getStringValue("parent-camera");
768 for (unsigned i = 0; i < _cameras.size(); ++i) {
769 if (_cameras[i]->name != name)
771 parentCameraIndex = i;
773 if (_cameras.size() <= parentCameraIndex) {
774 SG_LOG(SG_GENERAL, SG_ALERT, "CameraGroup::buildCamera: "
775 "failed to find parent camera for relative camera!");
778 const CameraInfo* parentInfo = _cameras[parentCameraIndex].get();
779 if (projectionNode->getNameString() == "right-of-perspective") {
780 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
781 parentReference[0] = osg::Vec2d(tmp, -1);
782 parentReference[1] = osg::Vec2d(tmp, 1);
783 tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
784 thisReference[0] = osg::Vec2d(-tmp, -1);
785 thisReference[1] = osg::Vec2d(-tmp, 1);
786 } else if (projectionNode->getNameString() == "left-of-perspective") {
787 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
788 parentReference[0] = osg::Vec2d(-tmp, -1);
789 parentReference[1] = osg::Vec2d(-tmp, 1);
790 tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
791 thisReference[0] = osg::Vec2d(tmp, -1);
792 thisReference[1] = osg::Vec2d(tmp, 1);
793 } else if (projectionNode->getNameString() == "above-perspective") {
794 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
795 parentReference[0] = osg::Vec2d(-1, tmp);
796 parentReference[1] = osg::Vec2d(1, tmp);
797 tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
798 thisReference[0] = osg::Vec2d(-1, -tmp);
799 thisReference[1] = osg::Vec2d(1, -tmp);
800 } else if (projectionNode->getNameString() == "below-perspective") {
801 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
802 parentReference[0] = osg::Vec2d(-1, -tmp);
803 parentReference[1] = osg::Vec2d(1, -tmp);
804 tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
805 thisReference[0] = osg::Vec2d(-1, tmp);
806 thisReference[1] = osg::Vec2d(1, tmp);
807 } else if (projectionNode->getNameString() == "reference-points-perspective") {
808 SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
809 SGPropertyNode* thisNode = projectionNode->getNode("this", true);
810 SGPropertyNode* pointNode;
812 pointNode = parentNode->getNode("point", 0, true);
813 parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
814 parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
815 pointNode = parentNode->getNode("point", 1, true);
816 parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
817 parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
819 pointNode = thisNode->getNode("point", 0, true);
820 thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
821 thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
822 pointNode = thisNode->getNode("point", 1, true);
823 thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
824 thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
827 pOff = osg::Matrix::perspective(45, physicalWidth/physicalHeight, 1, 20000);
828 cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
830 // old style shear parameters
831 double shearx = cameraNode->getDoubleValue("shear-x", 0);
832 double sheary = cameraNode->getDoubleValue("shear-y", 0);
833 pOff.makeTranslate(-shearx, -sheary, 0);
835 const SGPropertyNode* textureNode = cameraNode->getNode("texture");
837 string texName = textureNode->getStringValue("name");
838 int tex_width = textureNode->getIntValue("width");
839 int tex_height = textureNode->getIntValue("height");
840 TextureRectangle* texture = new TextureRectangle;
842 texture->setTextureSize(tex_width, tex_height);
843 texture->setInternalFormat(GL_RGB);
844 texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
845 texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
846 texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
847 texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
848 camera->setDrawBuffer(GL_FRONT);
849 camera->setReadBuffer(GL_FRONT);
850 camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
851 camera->attach(Camera::COLOR_BUFFER, texture);
852 _textureTargets[texName] = texture;
854 camera->setDrawBuffer(GL_BACK);
855 camera->setReadBuffer(GL_BACK);
857 const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
858 bool useMasterSceneGraph = !psNode;
859 CameraInfo* info = addCamera(cameraFlags, camera, vOff, pOff,
860 useMasterSceneGraph);
861 info->name = cameraNode->getStringValue("name");
862 info->physicalWidth = physicalWidth;
863 info->physicalHeight = physicalHeight;
864 info->bezelHeightTop = bezelHeightTop;
865 info->bezelHeightBottom = bezelHeightBottom;
866 info->bezelWidthLeft = bezelWidthLeft;
867 info->bezelWidthRight = bezelWidthRight;
868 info->relativeCameraParent = parentCameraIndex;
869 info->parentReference[0] = parentReference[0];
870 info->parentReference[1] = parentReference[1];
871 info->thisReference[0] = thisReference[0];
872 info->thisReference[1] = thisReference[1];
873 // If a viewport isn't set on the camera, then it's hard to dig it
874 // out of the SceneView objects in the viewer, and the coordinates
875 // of mouse events are somewhat bizzare.
876 buildViewport(info, viewportNode, window->gc->getTraits());
878 // Distortion camera needs the viewport which is created by addCamera().
880 info->flags = info->flags | VIEW_ABSOLUTE;
881 buildDistortionCamera(psNode, camera);
886 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
887 GraphicsWindow* window)
889 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
890 const SGPropertyNode* windowNode = (cameraNode
891 ? cameraNode->getNode("window")
893 if (!window && windowNode) {
894 // New style window declaration / definition
895 window = wBuild->buildWindow(windowNode);
898 if (!window) { // buildWindow can fail
899 SG_LOG(SG_GENERAL, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
903 Camera* camera = new Camera;
904 camera->setAllowEventFocus(false);
905 camera->setGraphicsContext(window->gc.get());
906 camera->setViewport(new Viewport);
907 // XXX Camera needs to be drawn last; eventually the render order
908 // should be assigned by a camera manager.
909 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
910 camera->setClearMask(0);
911 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
912 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
913 | CullSettings::CULLING_MODE
914 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
915 | CullSettings::CLEAR_MASK
918 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
919 camera->setCullingMode(osg::CullSettings::NO_CULLING);
920 camera->setProjectionResizePolicy(Camera::FIXED);
921 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
922 const int cameraFlags = GUI;
923 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
924 Matrixd::identity(), false);
925 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
926 buildViewport(result, viewportNode, window->gc->getTraits());
928 // Disable statistics for the GUI camera.
929 result->camera->setStats(0);
930 updateCameras(result);
934 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
935 SGPropertyNode* gnode)
937 CameraGroup* cgroup = new CameraGroup(viewer);
938 for (int i = 0; i < gnode->nChildren(); ++i) {
939 SGPropertyNode* pNode = gnode->getChild(i);
940 const char* name = pNode->getName();
941 if (!strcmp(name, "camera")) {
942 cgroup->buildCamera(pNode);
943 } else if (!strcmp(name, "window")) {
944 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
945 } else if (!strcmp(name, "gui")) {
946 cgroup->buildGUICamera(pNode);
949 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
950 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
951 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
956 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
958 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
959 CameraInfo* info = i->get();
960 if (info->flags & GUI)
962 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
963 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
964 info->camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
965 info->camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
966 info->farCamera->setCullMask(nm);
967 info->farCamera->setCullMaskLeft(nm);
968 info->farCamera->setCullMaskRight(nm);
970 info->camera->setCullMask(nm);
971 info->camera->setCullMaskLeft(nm);
972 info->camera->setCullMaskRight(nm);
977 void CameraGroup::resized()
979 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
980 CameraInfo *info = i->get();
981 const Viewport* viewport = info->camera->getViewport();
982 info->x = viewport->x();
983 info->y = viewport->y();
984 info->width = viewport->width();
985 info->height = viewport->height();
989 Camera* getGUICamera(CameraGroup* cgroup)
991 CameraGroup::CameraIterator end = cgroup->camerasEnd();
992 CameraGroup::CameraIterator result
993 = std::find_if(cgroup->camerasBegin(), end,
994 FlagTester<CameraInfo>(CameraGroup::GUI));
996 return (*result)->camera.get();
1001 bool computeIntersections(const CameraGroup* cgroup,
1002 const osgGA::GUIEventAdapter* ea,
1003 osgUtil::LineSegmentIntersector::Intersections& intersections)
1005 using osgUtil::Intersector;
1006 using osgUtil::LineSegmentIntersector;
1008 eventToWindowCoords(ea, x, y);
1009 // Find camera that contains event
1010 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
1011 e = cgroup->camerasEnd();
1014 const CameraInfo* cinfo = iter->get();
1015 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
1017 const Camera* camera = cinfo->camera.get();
1018 if (camera->getGraphicsContext() != ea->getGraphicsContext())
1020 const Viewport* viewport = camera->getViewport();
1021 double epsilon = 0.5;
1022 if (!(x >= viewport->x() - epsilon
1023 && x < viewport->x() + viewport->width() -1.0 + epsilon
1024 && y >= viewport->y() - epsilon
1025 && y < viewport->y() + viewport->height() -1.0 + epsilon))
1027 Vec4d start(x, y, 0.0, 1.0);
1028 Vec4d end(x, y, 1.0, 1.0);
1029 Matrix windowMat = viewport->computeWindowMatrix();
1030 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
1033 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
1034 endPtMat = startPtMat;
1036 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
1038 start = start * startPtMat;
1040 end = end * endPtMat;
1042 ref_ptr<LineSegmentIntersector> picker
1043 = new LineSegmentIntersector(Intersector::VIEW,
1044 Vec3d(start.x(), start.y(), start.z()),
1045 Vec3d(end.x(), end.y(), end.z()));
1046 osgUtil::IntersectionVisitor iv(picker.get());
1047 const_cast<Camera*>(camera)->accept(iv);
1048 if (picker->containsIntersections()) {
1049 intersections = picker->getIntersections();
1055 intersections.clear();
1059 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
1061 using osgViewer::GraphicsWindow;
1062 Camera* guiCamera = getGUICamera(cgroup);
1065 Viewport* vport = guiCamera->getViewport();
1067 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
1070 globals->get_renderer()->getEventHandler()->setMouseWarped();
1071 // Translate the warp request into the viewport of the GUI camera,
1072 // send the request to the window, then transform the coordinates
1073 // for the Viewer's event queue.
1074 double wx = x + vport->x();
1075 double wyUp = vport->height() + vport->y() - y;
1077 const GraphicsContext::Traits* traits = gw->getTraits();
1078 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
1079 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
1080 wy = traits->height - wyUp;
1084 gw->getEventQueue()->mouseWarped(wx, wy);
1085 gw->requestWarpPointer(wx, wy);
1086 osgGA::GUIEventAdapter* eventState
1087 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
1089 = (eventState->getXmin()
1090 + ((wx / double(traits->width))
1091 * (eventState->getXmax() - eventState->getXmin())));
1093 = (eventState->getYmin()
1094 + ((wyUp / double(traits->height))
1095 * (eventState->getYmax() - eventState->getYmin())));
1096 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);