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/Geometry>
39 #include <osg/GraphicsContext>
40 #include <osg/io_utils>
44 #include <osg/Program>
48 #include <osg/Viewport>
50 #include <osgUtil/IntersectionVisitor>
52 #include <osgViewer/GraphicsWindow>
53 #include <osgViewer/Renderer>
62 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
64 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
75 // Given a projection matrix, return a new one with the same frustum
76 // sides and new near / far values.
78 void makeNewProjMat(Matrixd& oldProj, double znear,
79 double zfar, Matrixd& projection)
82 // Slightly inflate the near & far planes to avoid objects at the
83 // extremes being clipped out.
87 // Clamp the projection matrix z values to the range (near, far)
88 double epsilon = 1.0e-6;
89 if (fabs(projection(0,3)) < epsilon &&
90 fabs(projection(1,3)) < epsilon &&
91 fabs(projection(2,3)) < epsilon) {
92 // Projection is Orthographic
93 epsilon = -1.0/(zfar - znear); // Used as a temp variable
94 projection(2,2) = 2.0*epsilon;
95 projection(3,2) = (zfar + znear)*epsilon;
97 // Projection is Perspective
98 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
99 (-znear*projection(2,3) + projection(3,3));
100 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
101 (-zfar*projection(2,3) + projection(3,3));
102 double ratio = fabs(2.0/(trans_near - trans_far));
103 double center = -0.5*(trans_near + trans_far);
105 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
107 0.0, 0.0, ratio, 0.0,
108 0.0, 0.0, center*ratio, 1.0));
112 void installCullVisitor(Camera* camera)
114 osgViewer::Renderer* renderer
115 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
116 for (int i = 0; i < 2; ++i) {
117 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
118 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
125 void updateCameras(const CameraInfo* info)
127 if (info->camera.valid())
128 info->camera->getViewport()->setViewport(info->x, info->y,
129 info->width, info->height);
130 if (info->farCamera.valid())
131 info->farCamera->getViewport()->setViewport(info->x, info->y,
132 info->width, info->height);
135 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
137 const Matrix& projection,
138 bool useMasterSceneData)
140 CameraInfo* info = new CameraInfo(flags);
141 // The camera group will always update the camera
142 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
144 Camera* farCamera = 0;
145 if ((flags & (GUI | ORTHO)) == 0) {
146 farCamera = new Camera;
147 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
148 farCamera->setGraphicsContext(camera->getGraphicsContext());
149 farCamera->setCullingMode(camera->getCullingMode());
150 farCamera->setInheritanceMask(camera->getInheritanceMask());
151 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
152 // Each camera's viewport is written when the window is
153 // resized; if the the viewport isn't copied here, it gets updated
154 // twice and ends up with the wrong value.
155 farCamera->setViewport(simgear::clone(camera->getViewport()));
156 farCamera->setDrawBuffer(camera->getDrawBuffer());
157 farCamera->setReadBuffer(camera->getReadBuffer());
158 farCamera->setRenderTargetImplementation(
159 camera->getRenderTargetImplementation());
160 const Camera::BufferAttachmentMap& bufferMap
161 = camera->getBufferAttachmentMap();
162 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
164 Camera::COLOR_BUFFER,
165 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
167 _viewer->addSlave(farCamera, projection, view, useMasterSceneData);
168 installCullVisitor(farCamera);
169 info->farCamera = farCamera;
170 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
171 farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
172 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
173 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
175 _viewer->addSlave(camera, projection, view, useMasterSceneData);
176 installCullVisitor(camera);
177 info->camera = camera;
178 info->slaveIndex = _viewer->getNumSlaves() - 1;
179 camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
180 _cameras.push_back(info);
184 void CameraGroup::update(const osg::Vec3d& position,
185 const osg::Quat& orientation)
187 const Matrix masterView(osg::Matrix::translate(-position)
188 * osg::Matrix::rotate(orientation.inverse()));
189 _viewer->getCamera()->setViewMatrix(masterView);
190 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
191 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
192 const CameraInfo* info = i->get();
193 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
194 // refreshes camera viewports (for now)
196 Camera* camera = info->camera.get();
198 if ((info->flags & VIEW_ABSOLUTE) != 0)
199 viewMatrix = slave._viewOffset;
201 viewMatrix = masterView * slave._viewOffset;
202 camera->setViewMatrix(viewMatrix);
203 Matrix projectionMatrix;
204 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
205 projectionMatrix = slave._projectionOffset;
207 projectionMatrix = masterProj * slave._projectionOffset;
209 if (!info->farCamera.valid()) {
210 camera->setProjectionMatrix(projectionMatrix);
212 Camera* farCamera = info->farCamera.get();
213 farCamera->setViewMatrix(viewMatrix);
214 double left, right, bottom, top, parentNear, parentFar;
215 projectionMatrix.getFrustum(left, right, bottom, top,
216 parentNear, parentFar);
217 if (parentFar < _nearField || _nearField == 0.0f) {
218 camera->setProjectionMatrix(projectionMatrix);
219 camera->setCullMask(camera->getCullMask()
220 | simgear::BACKGROUND_BIT);
221 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
222 farCamera->setNodeMask(0);
224 Matrix nearProj, farProj;
225 makeNewProjMat(projectionMatrix, parentNear, _nearField,
227 makeNewProjMat(projectionMatrix, _nearField, parentFar,
229 camera->setProjectionMatrix(nearProj);
230 camera->setCullMask(camera->getCullMask()
231 & ~simgear::BACKGROUND_BIT);
232 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
233 farCamera->setProjectionMatrix(farProj);
234 farCamera->setNodeMask(camera->getNodeMask());
240 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
242 if (vfov != 0.0f && aspectRatio != 0.0f)
244 ->setProjectionMatrixAsPerspective(vfov,
252 // A raw value for property nodes that references a class member via
254 template<class C, class T>
255 class RefMember : public SGRawValue<T>
258 RefMember (C *obj, T C::*ptr)
259 : _obj(obj), _ptr(ptr) {}
260 virtual ~RefMember () {}
261 virtual T getValue () const
263 return _obj.get()->*_ptr;
265 virtual bool setValue (T value)
267 _obj.get()->*_ptr = value;
270 virtual SGRawValue<T> * clone () const
272 return new RefMember(_obj.get(), _ptr);
279 template<typename C, typename T>
280 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
282 return RefMember<C, T>(obj, ptr);
285 template<typename C, typename T>
286 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
287 C* obj, T C::*ptr, T value)
289 SGPropertyNode* valNode = parent->getNode(childName);
290 RefMember<C, T> refMember = makeRefMember(obj, ptr);
292 valNode = parent->getNode(childName, true);
293 valNode->tie(refMember, false);
294 setValue(valNode, value);
296 valNode->tie(refMember, true);
300 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
301 const osg::GraphicsContext::Traits *traits)
303 using namespace flightgear;
304 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
305 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
306 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
307 static_cast<double>(traits->width));
308 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
309 static_cast<double>(traits->height));
316 // Mostly copied from osg's osgViewer/View.cpp
318 static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(
319 const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
320 double sphere_radius, double collar_radius,
321 Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
323 osg::Vec3d center(0.0,0.0,0.0);
324 osg::Vec3d eye(0.0,0.0,0.0);
326 double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
328 bool texcoord_flip = false;
330 osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
333 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
334 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
336 // create the quad to visualize.
337 osg::Geometry* geometry = new osg::Geometry();
339 geometry->setSupportsDisplayList(false);
341 osg::Vec3 xAxis(widthVector);
342 float width = widthVector.length();
345 osg::Vec3 yAxis(heightVector);
346 float height = heightVector.length();
351 osg::Vec3Array* vertices = new osg::Vec3Array;
352 osg::Vec2Array* texcoords0 = new osg::Vec2Array;
353 osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
354 osg::Vec4Array* colors = new osg::Vec4Array;
356 osg::Vec3 bottom = origin;
357 osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
358 osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
360 osg::Vec3 top = origin + yAxis*height;
362 osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
363 float screenRadius = heightVector.length() * 0.5f;
365 geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
367 for(int i=0;i<noSteps;++i)
369 osg::Vec3 cursor = bottom+dy*(float)i;
370 for(int j=0;j<noSteps;++j)
372 osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
373 double theta = texcoord.x() * 2.0 * osg::PI;
374 double phi = (1.0-texcoord.y()) * osg::PI;
376 if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
378 osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
379 pos = pos*projectorMatrix;
381 double alpha = atan2(pos.x(), pos.y());
382 if (alpha<0.0) alpha += 2.0*osg::PI;
384 double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
385 if (beta<0.0) beta += 2.0*osg::PI;
387 double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
388 if (gamma<0.0) gamma += 2.0*osg::PI;
391 osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
394 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
396 vertices->push_back(v);
398 texcoords0->push_back( texcoord );
400 osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
403 colors->push_back(intensityMap->getColor(texcoord1));
407 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
408 if (texcoords1) texcoords1->push_back( texcoord1 );
416 // pass the created vertex array to the points geometry object.
417 geometry->setVertexArray(vertices);
419 geometry->setColorArray(colors);
420 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
422 geometry->setTexCoordArray(0,texcoords0);
423 if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
425 osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
426 geometry->addPrimitiveSet(elements);
428 for(int i=0;i<noSteps-1;++i)
430 for(int j=0;j<noSteps-1;++j)
432 int i1 = j+(i+1)*noSteps;
433 int i2 = j+(i)*noSteps;
434 int i3 = j+1+(i)*noSteps;
435 int i4 = j+1+(i+1)*noSteps;
437 osg::Vec3& v1 = (*vertices)[i1];
438 osg::Vec3& v2 = (*vertices)[i2];
439 osg::Vec3& v3 = (*vertices)[i3];
440 osg::Vec3& v4 = (*vertices)[i4];
442 if ((v1-screenCenter).length()>screenRadius) continue;
443 if ((v2-screenCenter).length()>screenRadius) continue;
444 if ((v3-screenCenter).length()>screenRadius) continue;
445 if ((v4-screenCenter).length()>screenRadius) continue;
447 elements->push_back(i1);
448 elements->push_back(i2);
449 elements->push_back(i3);
451 elements->push_back(i1);
452 elements->push_back(i3);
453 elements->push_back(i4);
460 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
463 const SGPropertyNode* texNode = psNode->getNode("texture");
468 string texName = texNode->getStringValue();
469 TextureMap::iterator itr = _textureTargets.find(texName);
470 if (itr == _textureTargets.end()) {
474 Viewport* viewport = camera->getViewport();
475 float width = viewport->width();
476 float height = viewport->height();
477 TextureRectangle* texRect = itr->second.get();
478 double radius = psNode->getDoubleValue("radius", 1.0);
479 double collar = psNode->getDoubleValue("collar", 0.45);
480 Geode* geode = new Geode();
481 geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(
482 Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
483 Vec3(0.0f,height,0.0f), radius, collar));
485 // new we need to add the texture to the mesh, we do so by creating a
486 // StateSet to contain the Texture StateAttribute.
487 StateSet* stateset = geode->getOrCreateStateSet();
488 stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
489 stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
491 TexMat* texmat = new TexMat;
492 texmat->setScaleByTextureRectangleSize(true);
493 stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
495 if (!applyIntensityMapAsColours && intensityMap)
497 stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
500 // add subgraph to render
501 camera->addChild(geode);
502 camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
503 camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
504 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
505 camera->setCullingMode(osg::CullSettings::NO_CULLING);
506 camera->setName("DistortionCorrectionCamera");
509 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
511 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
512 const SGPropertyNode* windowNode = cameraNode->getNode("window");
513 GraphicsWindow* window = 0;
514 int cameraFlags = DO_INTERSECTION_TEST;
516 // New style window declaration / definition
517 window = wBuild->buildWindow(windowNode);
519 // Old style: suck window params out of camera block
520 window = wBuild->buildWindow(cameraNode);
525 Camera* camera = new Camera;
526 camera->setAllowEventFocus(false);
527 camera->setGraphicsContext(window->gc.get());
528 camera->setViewport(new Viewport);
529 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
530 | CullSettings::VIEW_FRUSTUM_CULLING);
531 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
532 & ~(CullSettings::CULL_MASK
533 | CullSettings::CULLING_MODE
534 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
535 | CullSettings::CLEAR_MASK
541 const SGPropertyNode* viewNode = cameraNode->getNode("view");
543 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
544 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
545 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
546 double x = viewNode->getDoubleValue("x", 0.0);
547 double y = viewNode->getDoubleValue("y", 0.0);
548 double z = viewNode->getDoubleValue("z", 0.0);
549 // Build a view matrix, which is the inverse of a model
550 // orientation matrix.
551 vOff = (Matrix::translate(-x, -y, -z)
552 * Matrix::rotate(-DegreesToRadians(heading),
553 Vec3d(0.0, 1.0, 0.0),
554 -DegreesToRadians(pitch),
555 Vec3d(1.0, 0.0, 0.0),
556 -DegreesToRadians(roll),
557 Vec3d(0.0, 0.0, 1.0)));
558 if (viewNode->getBoolValue("absolute", false))
559 cameraFlags |= VIEW_ABSOLUTE;
561 // Old heading parameter, works in the opposite direction
562 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
563 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
565 const SGPropertyNode* projectionNode = 0;
566 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
567 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
568 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
570 double zNear = projectionNode->getDoubleValue("near", 0.0);
571 double zFar = projectionNode->getDoubleValue("far", 0.0);
572 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
573 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
574 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
575 double right = tan_fovy * aspectRatio * zNear + offsetX;
576 double left = -tan_fovy * aspectRatio * zNear + offsetX;
577 double top = tan_fovy * zNear + offsetY;
578 double bottom = -tan_fovy * zNear + offsetY;
579 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
580 cameraFlags |= PROJECTION_ABSOLUTE;
581 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
582 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
583 double top = projectionNode->getDoubleValue("top", 0.0);
584 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
585 double left = projectionNode->getDoubleValue("left", 0.0);
586 double right = projectionNode->getDoubleValue("right", 0.0);
587 double zNear = projectionNode->getDoubleValue("near", 0.0);
588 double zFar = projectionNode->getDoubleValue("far", 0.0);
589 if (cameraNode->getNode("frustum")) {
590 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
591 cameraFlags |= PROJECTION_ABSOLUTE;
593 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
594 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
597 // old style shear parameters
598 double shearx = cameraNode->getDoubleValue("shear-x", 0);
599 double sheary = cameraNode->getDoubleValue("shear-y", 0);
600 pOff.makeTranslate(-shearx, -sheary, 0);
602 const SGPropertyNode* textureNode = cameraNode->getNode("texture");
604 string texName = textureNode->getStringValue("name");
605 int tex_width = textureNode->getIntValue("width");
606 int tex_height = textureNode->getIntValue("height");
607 TextureRectangle* texture = new TextureRectangle;
609 texture->setTextureSize(tex_width, tex_height);
610 texture->setInternalFormat(GL_RGB);
611 texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
612 texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
613 texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
614 texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
615 camera->setDrawBuffer(GL_FRONT);
616 camera->setReadBuffer(GL_FRONT);
617 camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
618 camera->attach(Camera::COLOR_BUFFER, texture);
619 _textureTargets[texName] = texture;
621 camera->setDrawBuffer(GL_BACK);
622 camera->setReadBuffer(GL_BACK);
624 const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
625 bool useMasterSceneGraph = !psNode;
626 CameraInfo* info = addCamera(cameraFlags, camera, vOff, pOff,
627 useMasterSceneGraph);
628 // If a viewport isn't set on the camera, then it's hard to dig it
629 // out of the SceneView objects in the viewer, and the coordinates
630 // of mouse events are somewhat bizzare.
631 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
632 buildViewport(info, viewportNode, window->gc->getTraits());
634 // Distortion camera needs the viewport which is created by addCamera().
636 info->flags = info->flags | VIEW_ABSOLUTE;
637 buildDistortionCamera(psNode, camera);
642 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
643 GraphicsWindow* window)
645 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
646 const SGPropertyNode* windowNode = (cameraNode
647 ? cameraNode->getNode("window")
649 if (!window && windowNode) {
650 // New style window declaration / definition
651 window = wBuild->buildWindow(windowNode);
654 if (!window) { // buildWindow can fail
655 SG_LOG(SG_GENERAL, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
659 Camera* camera = new Camera;
660 camera->setAllowEventFocus(false);
661 camera->setGraphicsContext(window->gc.get());
662 camera->setViewport(new Viewport);
663 // XXX Camera needs to be drawn last; eventually the render order
664 // should be assigned by a camera manager.
665 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
666 camera->setClearMask(0);
667 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
668 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
669 | CullSettings::CULLING_MODE
670 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
671 | CullSettings::CLEAR_MASK
674 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
675 camera->setCullingMode(osg::CullSettings::NO_CULLING);
676 camera->setProjectionResizePolicy(Camera::FIXED);
677 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
678 const int cameraFlags = GUI;
679 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
680 Matrixd::identity(), false);
681 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
682 buildViewport(result, viewportNode, window->gc->getTraits());
684 // Disable statistics for the GUI camera.
685 result->camera->setStats(0);
686 updateCameras(result);
690 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
691 SGPropertyNode* gnode)
693 CameraGroup* cgroup = new CameraGroup(viewer);
694 for (int i = 0; i < gnode->nChildren(); ++i) {
695 SGPropertyNode* pNode = gnode->getChild(i);
696 const char* name = pNode->getName();
697 if (!strcmp(name, "camera")) {
698 cgroup->buildCamera(pNode);
699 } else if (!strcmp(name, "window")) {
700 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
701 } else if (!strcmp(name, "gui")) {
702 cgroup->buildGUICamera(pNode);
705 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
706 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
707 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
712 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
714 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
715 CameraInfo* info = i->get();
716 if (info->flags & GUI)
718 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
719 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
720 info->camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
721 info->camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
722 info->farCamera->setCullMask(nm);
723 info->farCamera->setCullMaskLeft(nm);
724 info->farCamera->setCullMaskRight(nm);
726 info->camera->setCullMask(nm);
727 info->camera->setCullMaskLeft(nm);
728 info->camera->setCullMaskRight(nm);
733 void CameraGroup::resized()
735 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
736 CameraInfo *info = i->get();
737 const Viewport* viewport = info->camera->getViewport();
738 info->x = viewport->x();
739 info->y = viewport->y();
740 info->width = viewport->width();
741 info->height = viewport->height();
745 Camera* getGUICamera(CameraGroup* cgroup)
747 CameraGroup::CameraIterator end = cgroup->camerasEnd();
748 CameraGroup::CameraIterator result
749 = std::find_if(cgroup->camerasBegin(), end,
750 FlagTester<CameraInfo>(CameraGroup::GUI));
752 return (*result)->camera.get();
757 bool computeIntersections(const CameraGroup* cgroup,
758 const osgGA::GUIEventAdapter* ea,
759 osgUtil::LineSegmentIntersector::Intersections& intersections)
761 using osgUtil::Intersector;
762 using osgUtil::LineSegmentIntersector;
764 eventToWindowCoords(ea, x, y);
765 // Find camera that contains event
766 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
767 e = cgroup->camerasEnd();
770 const CameraInfo* cinfo = iter->get();
771 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
773 const Camera* camera = cinfo->camera.get();
774 if (camera->getGraphicsContext() != ea->getGraphicsContext())
776 const Viewport* viewport = camera->getViewport();
777 double epsilon = 0.5;
778 if (!(x >= viewport->x() - epsilon
779 && x < viewport->x() + viewport->width() -1.0 + epsilon
780 && y >= viewport->y() - epsilon
781 && y < viewport->y() + viewport->height() -1.0 + epsilon))
783 Vec4d start(x, y, 0.0, 1.0);
784 Vec4d end(x, y, 1.0, 1.0);
785 Matrix windowMat = viewport->computeWindowMatrix();
786 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
789 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
790 endPtMat = startPtMat;
792 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
794 start = start * startPtMat;
796 end = end * endPtMat;
798 ref_ptr<LineSegmentIntersector> picker
799 = new LineSegmentIntersector(Intersector::VIEW,
800 Vec3d(start.x(), start.y(), start.z()),
801 Vec3d(end.x(), end.y(), end.z()));
802 osgUtil::IntersectionVisitor iv(picker.get());
803 const_cast<Camera*>(camera)->accept(iv);
804 if (picker->containsIntersections()) {
805 intersections = picker->getIntersections();
811 intersections.clear();
815 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
817 using osgViewer::GraphicsWindow;
818 Camera* guiCamera = getGUICamera(cgroup);
821 Viewport* vport = guiCamera->getViewport();
823 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
826 globals->get_renderer()->getEventHandler()->setMouseWarped();
827 // Translate the warp request into the viewport of the GUI camera,
828 // send the request to the window, then transform the coordinates
829 // for the Viewer's event queue.
830 double wx = x + vport->x();
831 double wyUp = vport->height() + vport->y() - y;
833 const GraphicsContext::Traits* traits = gw->getTraits();
834 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
835 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
836 wy = traits->height - wyUp;
840 gw->getEventQueue()->mouseWarped(wx, wy);
841 gw->requestWarpPointer(wx, wy);
842 osgGA::GUIEventAdapter* eventState
843 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
845 = (eventState->getXmin()
846 + ((wx / double(traits->width))
847 * (eventState->getXmax() - eventState->getXmin())));
849 = (eventState->getYmin()
850 + ((wyUp / double(traits->height))
851 * (eventState->getYmax() - eventState->getYmin())));
852 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);