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 <Main/fg_props.hxx>
25 #include <Main/globals.hxx>
26 #include "renderer.hxx"
27 #include "FGEventHandler.hxx"
28 #include "WindowBuilder.hxx"
29 #include "WindowSystemAdapter.hxx"
31 #include <simgear/math/SGRect.hxx>
32 #include <simgear/props/props.hxx>
33 #include <simgear/props/props_io.hxx> // for copyProperties
34 #include <simgear/structure/OSGUtils.hxx>
35 #include <simgear/structure/OSGVersion.hxx>
36 #include <simgear/scene/material/EffectCullVisitor.hxx>
37 #include <simgear/scene/util/RenderConstants.hxx>
44 #include <osg/Geometry>
45 #include <osg/GraphicsContext>
46 #include <osg/io_utils>
50 #include <osg/Program>
54 #include <osg/Viewport>
56 #include <osgUtil/IntersectionVisitor>
58 #include <osgViewer/GraphicsWindow>
59 #include <osgViewer/Renderer>
66 // Given a projection matrix, return a new one with the same frustum
67 // sides and new near / far values.
69 void makeNewProjMat(Matrixd& oldProj, double znear,
70 double zfar, Matrixd& projection)
73 // Slightly inflate the near & far planes to avoid objects at the
74 // extremes being clipped out.
78 // Clamp the projection matrix z values to the range (near, far)
79 double epsilon = 1.0e-6;
80 if (fabs(projection(0,3)) < epsilon &&
81 fabs(projection(1,3)) < epsilon &&
82 fabs(projection(2,3)) < epsilon) {
83 // Projection is Orthographic
84 epsilon = -1.0/(zfar - znear); // Used as a temp variable
85 projection(2,2) = 2.0*epsilon;
86 projection(3,2) = (zfar + znear)*epsilon;
88 // Projection is Perspective
89 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
90 (-znear*projection(2,3) + projection(3,3));
91 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
92 (-zfar*projection(2,3) + projection(3,3));
93 double ratio = fabs(2.0/(trans_near - trans_far));
94 double center = -0.5*(trans_near + trans_far);
96 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
99 0.0, 0.0, center*ratio, 1.0));
104 invert(const osg::Matrix& matrix)
106 return osg::Matrix::inverse(matrix);
109 /// Returns the zoom factor of the master camera.
110 /// The reference fov is the historic 55 deg
114 double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
117 return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
121 preMult(const osg::Vec2d& v, const osg::Matrix& m)
123 osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
124 return osg::Vec2d(tmp[0], tmp[1]);
128 relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
129 const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
131 // Track the way from one projection space to the other:
134 // where P0 is the projection template sensible for the given window size,
135 // T is a translation matrix and S a scale matrix.
136 // We need to determine T and S so that the reference points in the parents
137 // projection space match the two reference points in this cameras projection space.
139 // Starting from the parents camera projection space, we get into this cameras
140 // projection space by the transform matrix:
141 // P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
142 // So, at first compute that matrix without T*S and determine S and T from that
144 // Ok, now osg uses the inverse matrix multiplication order, thus:
145 osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
146 // Compute the parents reference points in the current projection space
147 // without the yet unknown T and S
148 osg::Vec2d pRefInThis[2] = {
149 preMult(pRef[0], PtoPwithoutTS),
150 preMult(pRef[1], PtoPwithoutTS)
153 // To get the same zoom, rescale to match the parents size
154 double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
155 osg::Matrix S = osg::Matrix::scale(s, s, 1);
157 // For the translation offset, incorporate the now known scale
158 // and recompute the position ot the first reference point in the
159 // currents projection space without the yet unknown T.
160 pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
161 // The translation is then the difference of the reference points
162 osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));
164 // Compose and return the desired final projection matrix
168 } // of anonymous namespace
170 typedef std::vector<SGPropertyNode_ptr> SGPropertyNodeVec;
179 class CameraGroupListener : public SGPropertyChangeListener
182 CameraGroupListener(CameraGroup* cg, SGPropertyNode* gnode) :
186 listenToNode("znear", 0.1f);
187 listenToNode("zfar", 120000.0f);
188 listenToNode("near-field", 100.0f);
191 virtual ~CameraGroupListener()
195 unlisten("near-field");
198 virtual void valueChanged(SGPropertyNode* prop)
200 if (!strcmp(prop->getName(), "znear")) {
201 _cameraGroup->setZNear(prop->getFloatValue());
202 } else if (!strcmp(prop->getName(), "zfar")) {
203 _cameraGroup->setZFar(prop->getFloatValue());
204 } else if (!strcmp(prop->getName(), "near-field")) {
205 _cameraGroup->setNearField(prop->getFloatValue());
209 void listenToNode(const std::string& name, double val)
211 SGPropertyNode* n = _groupNode->getChild(name);
213 n = _groupNode->getChild(name, 0 /* index */, true);
214 n->setDoubleValue(val);
216 n->addChangeListener(this);
217 valueChanged(n); // propogate initial state through
220 void unlisten(const std::string& name)
222 _groupNode->getChild(name)->removeChangeListener(this);
225 SGPropertyNode_ptr _groupNode;
226 CameraGroup* _cameraGroup; // non-owning reference
230 class CameraViewportListener : public SGPropertyChangeListener
233 CameraViewportListener(CameraInfo* info,
234 SGPropertyNode* vnode,
235 const osg::GraphicsContext::Traits *traits) :
236 _viewportNode(vnode),
239 listenToNode("x", 0.0f);
240 listenToNode("y", 0.0f);
241 listenToNode("width", traits->width);
242 listenToNode("height", traits->height);
245 virtual ~CameraViewportListener()
253 virtual void valueChanged(SGPropertyNode* prop)
255 if (!strcmp(prop->getName(), "x")) {
256 _camera->x = prop->getDoubleValue();
257 } else if (!strcmp(prop->getName(), "y")) {
258 _camera->y = prop->getDoubleValue();
259 } else if (!strcmp(prop->getName(), "width")) {
260 _camera->width = prop->getDoubleValue();
261 } else if (!strcmp(prop->getName(), "height")) {
262 _camera->height = prop->getDoubleValue();
266 void listenToNode(const std::string& name, double val)
268 SGPropertyNode* n = _viewportNode->getChild(name);
270 n = _viewportNode->getChild(name, 0 /* index */, true);
271 n->setDoubleValue(val);
273 n->addChangeListener(this);
274 valueChanged(n); // propogate initial state through
277 void unlisten(const std::string& name)
279 _viewportNode->getChild(name)->removeChangeListener(this);
282 SGPropertyNode_ptr _viewportNode;
287 const char* MAIN_CAMERA = "main";
288 const char* FAR_CAMERA = "far";
289 const char* GEOMETRY_CAMERA = "geometry";
290 const char* SHADOW_CAMERA = "shadow";
291 const char* LIGHTING_CAMERA = "lighting";
292 const char* DISPLAY_CAMERA = "display";
294 void CameraInfo::updateCameras()
296 bufferSize->set( osg::Vec2f( width, height ) );
298 for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii ) {
299 float f = ii->second.scaleFactor;
300 if ( f == 0.0f ) continue;
302 if (ii->second.camera->getRenderTargetImplementation() == osg::Camera::FRAME_BUFFER_OBJECT)
303 ii->second.camera->getViewport()->setViewport(0, 0, width*f, height*f);
305 ii->second.camera->getViewport()->setViewport(x*f, y*f, width*f, height*f);
308 for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii ) {
309 float f = ii->second.scaleFactor;
310 if ( f == 0.0f ) continue;
311 osg::Texture2D* texture = ii->second.texture.get();
312 if ( texture->getTextureHeight() != height*f || texture->getTextureWidth() != width*f ) {
313 texture->setTextureSize( width*f, height*f );
314 texture->dirtyTextureObject();
319 void CameraInfo::resized(double w, double h)
321 if (w == 1.0 && h == 1.0)
324 bufferSize->set( osg::Vec2f( w, h ) );
326 for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii) {
327 float s = ii->second.scaleFactor;
328 if ( s == 0.0f ) continue;
329 ii->second.texture->setTextureSize( w * s, h * s );
330 ii->second.texture->dirtyTextureObject();
333 for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii) {
334 RenderStageInfo& rsi = ii->second;
335 if (!rsi.resizable ||
336 rsi.camera->getRenderTargetImplementation() != osg::Camera::FRAME_BUFFER_OBJECT ||
337 rsi.scaleFactor == 0.0f )
340 Viewport* vp = rsi.camera->getViewport();
341 vp->width() = w * rsi.scaleFactor;
342 vp->height() = h * rsi.scaleFactor;
344 osgViewer::Renderer* renderer
345 = static_cast<osgViewer::Renderer*>(rsi.camera->getRenderer());
346 for (int i = 0; i < 2; ++i) {
347 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
348 sceneView->getRenderStage()->setFrameBufferObject(0);
349 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
350 if (sceneView->getRenderStageLeft()) {
351 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
352 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
354 if (sceneView->getRenderStageRight()) {
355 sceneView->getRenderStageRight()->setFrameBufferObject(0);
356 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
362 CameraInfo::~CameraInfo()
364 delete viewportListener;
367 osg::Camera* CameraInfo::getCamera(const std::string& k) const
369 CameraMap::const_iterator ii = cameras.find( k );
370 if (ii == cameras.end())
372 return ii->second.camera.get();
375 osg::Texture2D* CameraInfo::getBuffer(const std::string& k) const
377 RenderBufferMap::const_iterator ii = buffers.find(k);
378 if (ii == buffers.end())
380 return ii->second.texture.get();
383 int CameraInfo::getMainSlaveIndex() const
385 return cameras.find( MAIN_CAMERA )->second.slaveIndex;
388 void CameraInfo::setMatrices(osg::Camera* c)
390 view->set( c->getViewMatrix() );
391 osg::Matrixd vi = c->getInverseViewMatrix();
392 viewInverse->set( vi );
393 projInverse->set( osg::Matrix::inverse( c->getProjectionMatrix() ) );
394 osg::Vec4d pos = osg::Vec4d(0., 0., 0., 1.) * vi;
395 worldPosCart->set( osg::Vec3f( pos.x(), pos.y(), pos.z() ) );
396 SGGeod pos2 = SGGeod::fromCart( SGVec3d( pos.x(), pos.y(), pos.z() ) );
397 worldPosGeod->set( osg::Vec3f( pos2.getLongitudeRad(), pos2.getLatitudeRad(), pos2.getElevationM() ) );
400 CameraGroup::~CameraGroup()
403 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
404 CameraInfo* info = *i;
405 for (CameraMap::iterator ii = info->cameras.begin(); ii != info->cameras.end(); ++ii) {
406 RenderStageInfo& rsi = ii->second;
407 unsigned int slaveIndex = _viewer->findSlaveIndexForCamera(rsi.camera);
408 _viewer->removeSlave(slaveIndex);
415 void CameraGroup::update(const osg::Vec3d& position,
416 const osg::Quat& orientation)
418 const Matrix masterView(osg::Matrix::translate(-position)
419 * osg::Matrix::rotate(orientation.inverse()));
420 _viewer->getCamera()->setViewMatrix(masterView);
421 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
422 double masterZoomFactor = zoomFactor();
423 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
424 const CameraInfo* info = i->get();
426 Camera* camera = info->getCamera(MAIN_CAMERA);
428 const View::Slave& slave = _viewer->getSlave(info->getMainSlaveIndex());
431 if (info->flags & GUI) {
432 viewMatrix = osg::Matrix(); // identifty transform on the GUI camera
433 } else if ((info->flags & VIEW_ABSOLUTE) != 0)
434 viewMatrix = slave._viewOffset;
436 viewMatrix = masterView * slave._viewOffset;
437 camera->setViewMatrix(viewMatrix);
438 Matrix projectionMatrix;
439 if (info->flags & GUI) {
440 projectionMatrix = osg::Matrix::ortho2D(0, info->width, 0, info->height);
441 } else if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
442 if (info->flags & ENABLE_MASTER_ZOOM) {
443 if (info->relativeCameraParent < _cameras.size()) {
444 // template projection matrix and view matrix of the current camera
445 osg::Matrix P0 = slave._projectionOffset;
446 osg::Matrix R = viewMatrix;
448 // The already known projection and view matrix of the parent camera
449 const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
450 RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
451 osg::Matrix pP = prsi.camera->getProjectionMatrix();
452 osg::Matrix pR = prsi.camera->getViewMatrix();
454 // And the projection matrix derived from P0 so that the reference points match
455 projectionMatrix = relativeProjection(P0, R, info->thisReference,
456 pP, pR, info->parentReference);
459 // We want to zoom, so take the original matrix and apply the zoom to it.
460 projectionMatrix = slave._projectionOffset;
461 projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
464 projectionMatrix = slave._projectionOffset;
467 projectionMatrix = masterProj * slave._projectionOffset;
470 CameraMap::const_iterator ii = info->cameras.find(FAR_CAMERA);
471 if (ii == info->cameras.end() || !ii->second.camera.valid()) {
472 camera->setProjectionMatrix(projectionMatrix);
474 Camera* farCamera = ii->second.camera;
475 farCamera->setViewMatrix(viewMatrix);
476 double left, right, bottom, top, parentNear, parentFar;
477 projectionMatrix.getFrustum(left, right, bottom, top,
478 parentNear, parentFar);
479 if ((info->flags & FIXED_NEAR_FAR) == 0) {
483 if (parentFar < _nearField || _nearField == 0.0f) {
484 camera->setProjectionMatrix(projectionMatrix);
485 camera->setCullMask(camera->getCullMask()
486 | simgear::BACKGROUND_BIT);
487 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
488 farCamera->setNodeMask(0);
490 Matrix nearProj, farProj;
491 makeNewProjMat(projectionMatrix, parentNear, _nearField,
493 makeNewProjMat(projectionMatrix, _nearField, parentFar,
495 camera->setProjectionMatrix(nearProj);
496 camera->setCullMask(camera->getCullMask()
497 & ~simgear::BACKGROUND_BIT);
498 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
499 farCamera->setProjectionMatrix(farProj);
500 farCamera->setNodeMask(camera->getNodeMask());
504 bool viewDone = false;
506 bool projectionDone = false;
507 Matrix projectionMatrix;
508 for ( CameraMap::const_iterator ii = info->cameras.begin(); ii != info->cameras.end(); ++ii ) {
509 if ( ii->first == SHADOW_CAMERA ) {
510 globals->get_renderer()->updateShadowCamera(info, position);
513 if ( ii->second.fullscreen )
516 Camera* camera = ii->second.camera.get();
517 int slaveIndex = ii->second.slaveIndex;
518 const View::Slave& slave = _viewer->getSlave(slaveIndex);
521 if ((info->flags & VIEW_ABSOLUTE) != 0)
522 viewMatrix = slave._viewOffset;
524 viewMatrix = masterView * slave._viewOffset;
528 camera->setViewMatrix( viewMatrix );
530 if ( !projectionDone ) {
531 if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
532 if (info->flags & ENABLE_MASTER_ZOOM) {
533 if (info->relativeCameraParent < _cameras.size()) {
534 // template projection matrix and view matrix of the current camera
535 osg::Matrix P0 = slave._projectionOffset;
536 osg::Matrix R = viewMatrix;
538 // The already known projection and view matrix of the parent camera
539 const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
540 RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
541 osg::Matrix pP = prsi.camera->getProjectionMatrix();
542 osg::Matrix pR = prsi.camera->getViewMatrix();
544 // And the projection matrix derived from P0 so that the reference points match
545 projectionMatrix = relativeProjection(P0, R, info->thisReference,
546 pP, pR, info->parentReference);
549 // We want to zoom, so take the original matrix and apply the zoom to it.
550 projectionMatrix = slave._projectionOffset;
551 projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
554 projectionMatrix = slave._projectionOffset;
557 projectionMatrix = masterProj * slave._projectionOffset;
559 projectionDone = true;
562 camera->setProjectionMatrix(projectionMatrix);
567 globals->get_renderer()->setPlanes( _zNear, _zFar );
570 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
572 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
577 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
579 if (vfov != 0.0f && aspectRatio != 0.0f)
581 ->setProjectionMatrixAsPerspective(vfov,
586 double CameraGroup::getMasterAspectRatio() const
588 if (_cameras.empty())
591 const CameraInfo* info = _cameras.front();
593 osg::Camera* camera = info->getCamera(MAIN_CAMERA);
595 camera = info->getCamera( GEOMETRY_CAMERA );
596 const osg::Viewport* viewport = camera->getViewport();
601 return static_cast<double>(viewport->height()) / viewport->width();
604 // Mostly copied from osg's osgViewer/View.cpp
606 static osg::Geometry* createPanoramicSphericalDisplayDistortionMesh(
607 const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
608 double sphere_radius, double collar_radius,
609 Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
611 osg::Vec3d center(0.0,0.0,0.0);
612 osg::Vec3d eye(0.0,0.0,0.0);
614 double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
616 bool texcoord_flip = false;
619 osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
621 OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
622 OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
624 // create the quad to visualize.
625 osg::Geometry* geometry = new osg::Geometry();
627 geometry->setSupportsDisplayList(false);
629 osg::Vec3 xAxis(widthVector);
630 float width = widthVector.length();
633 osg::Vec3 yAxis(heightVector);
634 float height = heightVector.length();
639 osg::Vec3Array* vertices = new osg::Vec3Array;
640 osg::Vec2Array* texcoords0 = new osg::Vec2Array;
641 osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
642 osg::Vec4Array* colors = new osg::Vec4Array;
645 osg::Vec3 bottom = origin;
646 osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
647 osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
649 osg::Vec3 top = origin + yAxis*height;
651 osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
652 float screenRadius = heightVector.length() * 0.5f;
654 geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
656 for(int i=0;i<noSteps;++i)
658 //osg::Vec3 cursor = bottom+dy*(float)i;
659 for(int j=0;j<noSteps;++j)
661 osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
662 double theta = texcoord.x() * 2.0 * osg::PI;
663 double phi = (1.0-texcoord.y()) * osg::PI;
665 if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
667 osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
668 pos = pos*projectorMatrix;
670 double alpha = atan2(pos.x(), pos.y());
671 if (alpha<0.0) alpha += 2.0*osg::PI;
673 double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
674 if (beta<0.0) beta += 2.0*osg::PI;
676 double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
677 if (gamma<0.0) gamma += 2.0*osg::PI;
680 osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
683 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
685 vertices->push_back(v);
687 texcoords0->push_back( texcoord );
689 osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
692 colors->push_back(intensityMap->getColor(texcoord1));
696 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
697 if (texcoords1) texcoords1->push_back( texcoord1 );
705 // pass the created vertex array to the points geometry object.
706 geometry->setVertexArray(vertices);
708 geometry->setColorArray(colors);
709 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
711 geometry->setTexCoordArray(0,texcoords0);
712 if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
714 osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
715 geometry->addPrimitiveSet(elements);
717 for(int i=0;i<noSteps-1;++i)
719 for(int j=0;j<noSteps-1;++j)
721 int i1 = j+(i+1)*noSteps;
722 int i2 = j+(i)*noSteps;
723 int i3 = j+1+(i)*noSteps;
724 int i4 = j+1+(i+1)*noSteps;
726 osg::Vec3& v1 = (*vertices)[i1];
727 osg::Vec3& v2 = (*vertices)[i2];
728 osg::Vec3& v3 = (*vertices)[i3];
729 osg::Vec3& v4 = (*vertices)[i4];
731 if ((v1-screenCenter).length()>screenRadius) continue;
732 if ((v2-screenCenter).length()>screenRadius) continue;
733 if ((v3-screenCenter).length()>screenRadius) continue;
734 if ((v4-screenCenter).length()>screenRadius) continue;
736 elements->push_back(i1);
737 elements->push_back(i2);
738 elements->push_back(i3);
740 elements->push_back(i1);
741 elements->push_back(i3);
742 elements->push_back(i4);
749 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
752 const SGPropertyNode* texNode = psNode->getNode("texture");
757 string texName = texNode->getStringValue();
758 TextureMap::iterator itr = _textureTargets.find(texName);
759 if (itr == _textureTargets.end()) {
763 Viewport* viewport = camera->getViewport();
764 float width = viewport->width();
765 float height = viewport->height();
766 TextureRectangle* texRect = itr->second.get();
767 double radius = psNode->getDoubleValue("radius", 1.0);
768 double collar = psNode->getDoubleValue("collar", 0.45);
769 Geode* geode = new Geode();
770 geode->addDrawable(createPanoramicSphericalDisplayDistortionMesh(
771 Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
772 Vec3(0.0f,height,0.0f), radius, collar));
774 // new we need to add the texture to the mesh, we do so by creating a
775 // StateSet to contain the Texture StateAttribute.
776 StateSet* stateset = geode->getOrCreateStateSet();
777 stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
778 stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
780 TexMat* texmat = new TexMat;
781 texmat->setScaleByTextureRectangleSize(true);
782 stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
784 if (!applyIntensityMapAsColours && intensityMap)
786 stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
789 // add subgraph to render
790 camera->addChild(geode);
791 camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
792 camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
793 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
794 camera->setCullingMode(osg::CullSettings::NO_CULLING);
795 camera->setName("DistortionCorrectionCamera");
798 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
800 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
801 const SGPropertyNode* windowNode = cameraNode->getNode("window");
802 GraphicsWindow* window = 0;
803 int cameraFlags = DO_INTERSECTION_TEST;
805 // New style window declaration / definition
806 window = wBuild->buildWindow(windowNode);
808 // Old style: suck window params out of camera block
809 window = wBuild->buildWindow(cameraNode);
814 Camera* camera = new Camera;
815 camera->setName("windowCamera");
816 camera->setAllowEventFocus(false);
817 camera->setGraphicsContext(window->gc.get());
818 camera->setViewport(new Viewport);
819 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
820 | CullSettings::VIEW_FRUSTUM_CULLING);
821 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
822 & ~(CullSettings::CULL_MASK
823 | CullSettings::CULLING_MODE
824 | CullSettings::CLEAR_MASK
828 const SGPropertyNode* viewNode = cameraNode->getNode("view");
830 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
831 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
832 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
833 double x = viewNode->getDoubleValue("x", 0.0);
834 double y = viewNode->getDoubleValue("y", 0.0);
835 double z = viewNode->getDoubleValue("z", 0.0);
836 // Build a view matrix, which is the inverse of a model
837 // orientation matrix.
838 vOff = (Matrix::translate(-x, -y, -z)
839 * Matrix::rotate(-DegreesToRadians(heading),
840 Vec3d(0.0, 1.0, 0.0),
841 -DegreesToRadians(pitch),
842 Vec3d(1.0, 0.0, 0.0),
843 -DegreesToRadians(roll),
844 Vec3d(0.0, 0.0, 1.0)));
845 if (viewNode->getBoolValue("absolute", false))
846 cameraFlags |= VIEW_ABSOLUTE;
848 // Old heading parameter, works in the opposite direction
849 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
850 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
852 // Configuring the physical dimensions of a monitor
853 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
854 double physicalWidth = viewportNode->getDoubleValue("width", 1024);
855 double physicalHeight = viewportNode->getDoubleValue("height", 768);
856 double bezelHeightTop = 0;
857 double bezelHeightBottom = 0;
858 double bezelWidthLeft = 0;
859 double bezelWidthRight = 0;
860 const SGPropertyNode* physicalDimensionsNode = 0;
861 if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
862 physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
863 physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
864 const SGPropertyNode* bezelNode = 0;
865 if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
866 bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
867 bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
868 bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
869 bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
873 unsigned parentCameraIndex = ~0u;
874 osg::Vec2d parentReference[2];
875 osg::Vec2d thisReference[2];
876 SGPropertyNode* projectionNode = 0;
877 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
878 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
879 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
881 double zNear = projectionNode->getDoubleValue("near", 0.0);
882 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
883 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
884 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
885 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
886 double right = tan_fovy * aspectRatio * zNear + offsetX;
887 double left = -tan_fovy * aspectRatio * zNear + offsetX;
888 double top = tan_fovy * zNear + offsetY;
889 double bottom = -tan_fovy * zNear + offsetY;
890 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
891 cameraFlags |= PROJECTION_ABSOLUTE;
892 if (projectionNode->getBoolValue("fixed-near-far", true))
893 cameraFlags |= FIXED_NEAR_FAR;
894 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
895 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
896 double top = projectionNode->getDoubleValue("top", 0.0);
897 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
898 double left = projectionNode->getDoubleValue("left", 0.0);
899 double right = projectionNode->getDoubleValue("right", 0.0);
900 double zNear = projectionNode->getDoubleValue("near", 0.0);
901 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
902 if (cameraNode->getNode("frustum")) {
903 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
904 cameraFlags |= PROJECTION_ABSOLUTE;
906 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
907 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
909 if (projectionNode->getBoolValue("fixed-near-far", true))
910 cameraFlags |= FIXED_NEAR_FAR;
911 } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
912 double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
913 double xoff = projectionNode->getDoubleValue("x-offset", 0);
914 double yoff = projectionNode->getDoubleValue("y-offset", 0);
915 double left = -0.5*physicalWidth - xoff;
916 double right = 0.5*physicalWidth - xoff;
917 double bottom = -0.5*physicalHeight - yoff;
918 double top = 0.5*physicalHeight - yoff;
919 pOff.makeFrustum(left, right, bottom, top, zNear, zNear*1000);
920 cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
921 } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
922 || (projectionNode = cameraNode->getNode("left-of-perspective"))
923 || (projectionNode = cameraNode->getNode("above-perspective"))
924 || (projectionNode = cameraNode->getNode("below-perspective"))
925 || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
926 std::string name = projectionNode->getStringValue("parent-camera");
927 for (unsigned i = 0; i < _cameras.size(); ++i) {
928 if (_cameras[i]->name != name)
930 parentCameraIndex = i;
932 if (_cameras.size() <= parentCameraIndex) {
933 SG_LOG(SG_VIEW, SG_ALERT, "CameraGroup::buildCamera: "
934 "failed to find parent camera for relative camera!");
937 const CameraInfo* parentInfo = _cameras[parentCameraIndex].get();
938 if (projectionNode->getNameString() == "right-of-perspective") {
939 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
940 parentReference[0] = osg::Vec2d(tmp, -1);
941 parentReference[1] = osg::Vec2d(tmp, 1);
942 tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
943 thisReference[0] = osg::Vec2d(-tmp, -1);
944 thisReference[1] = osg::Vec2d(-tmp, 1);
945 } else if (projectionNode->getNameString() == "left-of-perspective") {
946 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
947 parentReference[0] = osg::Vec2d(-tmp, -1);
948 parentReference[1] = osg::Vec2d(-tmp, 1);
949 tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
950 thisReference[0] = osg::Vec2d(tmp, -1);
951 thisReference[1] = osg::Vec2d(tmp, 1);
952 } else if (projectionNode->getNameString() == "above-perspective") {
953 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
954 parentReference[0] = osg::Vec2d(-1, tmp);
955 parentReference[1] = osg::Vec2d(1, tmp);
956 tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
957 thisReference[0] = osg::Vec2d(-1, -tmp);
958 thisReference[1] = osg::Vec2d(1, -tmp);
959 } else if (projectionNode->getNameString() == "below-perspective") {
960 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
961 parentReference[0] = osg::Vec2d(-1, -tmp);
962 parentReference[1] = osg::Vec2d(1, -tmp);
963 tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
964 thisReference[0] = osg::Vec2d(-1, tmp);
965 thisReference[1] = osg::Vec2d(1, tmp);
966 } else if (projectionNode->getNameString() == "reference-points-perspective") {
967 SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
968 SGPropertyNode* thisNode = projectionNode->getNode("this", true);
969 SGPropertyNode* pointNode;
971 pointNode = parentNode->getNode("point", 0, true);
972 parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
973 parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
974 pointNode = parentNode->getNode("point", 1, true);
975 parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
976 parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
978 pointNode = thisNode->getNode("point", 0, true);
979 thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
980 thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
981 pointNode = thisNode->getNode("point", 1, true);
982 thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
983 thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
986 pOff = osg::Matrix::perspective(45, physicalWidth/physicalHeight, 1, 20000);
987 cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
989 // old style shear parameters
990 double shearx = cameraNode->getDoubleValue("shear-x", 0);
991 double sheary = cameraNode->getDoubleValue("shear-y", 0);
992 pOff.makeTranslate(-shearx, -sheary, 0);
994 const SGPropertyNode* textureNode = cameraNode->getNode("texture");
996 string texName = textureNode->getStringValue("name");
997 int tex_width = textureNode->getIntValue("width");
998 int tex_height = textureNode->getIntValue("height");
999 TextureRectangle* texture = new TextureRectangle;
1001 texture->setTextureSize(tex_width, tex_height);
1002 texture->setInternalFormat(GL_RGB);
1003 texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
1004 texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
1005 texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
1006 texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
1007 camera->setDrawBuffer(GL_FRONT);
1008 camera->setReadBuffer(GL_FRONT);
1009 camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
1010 camera->attach(Camera::COLOR_BUFFER, texture);
1011 _textureTargets[texName] = texture;
1013 camera->setDrawBuffer(GL_BACK);
1014 camera->setReadBuffer(GL_BACK);
1016 const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
1017 bool useMasterSceneGraph = !psNode;
1018 CameraInfo* info = globals->get_renderer()->buildRenderingPipeline(this, cameraFlags, camera, vOff, pOff,
1019 window->gc.get(), useMasterSceneGraph);
1021 info->name = cameraNode->getStringValue("name");
1022 info->physicalWidth = physicalWidth;
1023 info->physicalHeight = physicalHeight;
1024 info->bezelHeightTop = bezelHeightTop;
1025 info->bezelHeightBottom = bezelHeightBottom;
1026 info->bezelWidthLeft = bezelWidthLeft;
1027 info->bezelWidthRight = bezelWidthRight;
1028 info->relativeCameraParent = parentCameraIndex;
1029 info->parentReference[0] = parentReference[0];
1030 info->parentReference[1] = parentReference[1];
1031 info->thisReference[0] = thisReference[0];
1032 info->thisReference[1] = thisReference[1];
1034 // If a viewport isn't set on the camera, then it's hard to dig it
1035 // out of the SceneView objects in the viewer, and the coordinates
1036 // of mouse events are somewhat bizzare.
1038 info->viewportListener = new CameraViewportListener(info, viewportNode, window->gc->getTraits());
1040 info->updateCameras();
1041 // Distortion camera needs the viewport which is created by addCamera().
1043 info->flags = info->flags | VIEW_ABSOLUTE;
1044 buildDistortionCamera(psNode, camera);
1049 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
1050 GraphicsWindow* window)
1052 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
1053 const SGPropertyNode* windowNode = (cameraNode
1054 ? cameraNode->getNode("window")
1056 if (!window && windowNode) {
1057 // New style window declaration / definition
1058 window = wBuild->buildWindow(windowNode);
1061 if (!window) { // buildWindow can fail
1062 SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
1066 Camera* camera = new Camera;
1067 camera->setName( "GUICamera" );
1068 camera->setAllowEventFocus(false);
1069 camera->setGraphicsContext(window->gc.get());
1070 camera->setViewport(new Viewport);
1071 camera->setClearMask(0);
1072 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
1073 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
1074 | CullSettings::CULLING_MODE
1075 | CullSettings::CLEAR_MASK
1077 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1078 camera->setCullingMode(osg::CullSettings::NO_CULLING);
1079 camera->setProjectionResizePolicy(Camera::FIXED);
1080 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1081 const int cameraFlags = GUI | DO_INTERSECTION_TEST;
1083 CameraInfo* result = new CameraInfo(cameraFlags);
1084 result->name = "GUI camera";
1085 // The camera group will always update the camera
1086 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1088 getViewer()->addSlave(camera, Matrixd::identity(), Matrixd::identity(), false);
1089 //installCullVisitor(camera);
1090 int slaveIndex = getViewer()->getNumSlaves() - 1;
1091 result->addCamera( MAIN_CAMERA, camera, slaveIndex );
1092 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
1095 // XXX Camera needs to be drawn last; eventually the render order
1096 // should be assigned by a camera manager.
1097 camera->setRenderOrder(osg::Camera::POST_RENDER, 10000);
1098 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
1100 result->viewportListener = new CameraViewportListener(result, viewportNode,
1101 window->gc->getTraits());
1103 // Disable statistics for the GUI camera.
1104 camera->setStats(0);
1105 result->updateCameras();
1109 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
1110 SGPropertyNode* gnode)
1112 CameraGroup* cgroup = new CameraGroup(viewer);
1113 cgroup->_listener.reset(new CameraGroupListener(cgroup, gnode));
1115 for (int i = 0; i < gnode->nChildren(); ++i) {
1116 SGPropertyNode* pNode = gnode->getChild(i);
1117 const char* name = pNode->getName();
1118 if (!strcmp(name, "camera")) {
1119 cgroup->buildCamera(pNode);
1120 } else if (!strcmp(name, "window")) {
1121 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
1122 } else if (!strcmp(name, "gui")) {
1123 cgroup->buildGUICamera(pNode);
1130 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
1132 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1133 CameraInfo* info = i->get();
1134 if (info->flags & GUI)
1136 osg::ref_ptr<osg::Camera> farCamera = info->getCamera(FAR_CAMERA);
1137 osg::Camera* camera = info->getCamera( MAIN_CAMERA );
1139 if (farCamera.valid() && farCamera->getNodeMask() != 0) {
1140 camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
1141 camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
1142 camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
1143 farCamera->setCullMask(nm);
1144 farCamera->setCullMaskLeft(nm);
1145 farCamera->setCullMaskRight(nm);
1147 camera->setCullMask(nm);
1148 camera->setCullMaskLeft(nm);
1149 camera->setCullMaskRight(nm);
1152 camera = info->getCamera( GEOMETRY_CAMERA );
1153 if (camera == 0) continue;
1154 camera->setCullMask( nm & ~simgear::MODELLIGHT_BIT );
1156 camera = info->getCamera( LIGHTING_CAMERA );
1157 if (camera == 0) continue;
1158 osg::Switch* sw = camera->getChild(0)->asSwitch();
1159 for (unsigned int i = 0; i < sw->getNumChildren(); ++i) {
1160 osg::Camera* lc = dynamic_cast<osg::Camera*>(sw->getChild(i));
1161 if (lc == 0) continue;
1162 string name = lc->getName();
1163 if (name == "LightCamera") {
1164 lc->setCullMask( (nm & simgear::LIGHTS_BITS) | (lc->getCullMask() & ~simgear::LIGHTS_BITS) );
1171 void CameraGroup::resized()
1173 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1174 CameraInfo *info = i->get();
1175 Camera* camera = info->getCamera( MAIN_CAMERA );
1177 camera = info->getCamera( DISPLAY_CAMERA );
1178 const Viewport* viewport = camera->getViewport();
1179 info->x = viewport->x();
1180 info->y = viewport->y();
1181 info->width = viewport->width();
1182 info->height = viewport->height();
1184 info->resized( info->width, info->height );
1188 const CameraInfo* CameraGroup::getGUICamera() const
1190 ConstCameraIterator result
1191 = std::find_if(camerasBegin(), camerasEnd(),
1192 FlagTester<CameraInfo>(GUI));
1193 if (result == camerasEnd()) {
1200 Camera* getGUICamera(CameraGroup* cgroup)
1202 const CameraInfo* info = cgroup->getGUICamera();
1207 return info->getCamera(MAIN_CAMERA);
1211 static bool computeCameraIntersection(const CameraInfo* cinfo, const osg::Vec2d& windowPos,
1212 osgUtil::LineSegmentIntersector::Intersections& intersections)
1214 using osgUtil::Intersector;
1215 using osgUtil::LineSegmentIntersector;
1217 if (!(cinfo->flags & CameraGroup::DO_INTERSECTION_TEST))
1220 const Camera* camera = cinfo->getCamera(MAIN_CAMERA);
1222 camera = cinfo->getCamera( GEOMETRY_CAMERA );
1224 // if (camera->getGraphicsContext() != ea->getGraphicsContext())
1227 const Viewport* viewport = camera->getViewport();
1228 SGRect<double> viewportRect(viewport->x(), viewport->y(),
1229 viewport->x() + viewport->width() - 1.0,
1230 viewport->y() + viewport->height()- 1.0);
1232 double epsilon = 0.5;
1233 if (!viewportRect.contains(windowPos.x(), windowPos.y(), epsilon))
1236 Vec4d start(windowPos.x(), windowPos.y(), 0.0, 1.0);
1237 Vec4d end(windowPos.x(), windowPos.y(), 1.0, 1.0);
1238 Matrix windowMat = viewport->computeWindowMatrix();
1239 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
1242 const Camera* farCamera = cinfo->getCamera( FAR_CAMERA );
1243 if (!farCamera || farCamera->getNodeMask() == 0)
1244 endPtMat = startPtMat;
1246 endPtMat = Matrix::inverse(farCamera->getProjectionMatrix()
1248 start = start * startPtMat;
1250 end = end * endPtMat;
1252 ref_ptr<LineSegmentIntersector> picker
1253 = new LineSegmentIntersector(Intersector::VIEW,
1254 Vec3d(start.x(), start.y(), start.z()),
1255 Vec3d(end.x(), end.y(), end.z()));
1256 osgUtil::IntersectionVisitor iv(picker.get());
1257 iv.setTraversalMask( simgear::PICK_BIT );
1259 const_cast<Camera*>(camera)->accept(iv);
1260 if (picker->containsIntersections()) {
1261 intersections = picker->getIntersections();
1268 bool computeIntersections(const CameraGroup* cgroup,
1269 const osg::Vec2d& windowPos,
1270 osgUtil::LineSegmentIntersector::Intersections& intersections)
1272 // test the GUI first
1273 const CameraInfo* guiCamera = cgroup->getGUICamera();
1274 if (guiCamera && computeCameraIntersection(guiCamera, windowPos, intersections))
1277 // Find camera that contains event
1278 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
1279 e = cgroup->camerasEnd();
1282 const CameraInfo* cinfo = iter->get();
1283 if (cinfo == guiCamera)
1286 if (computeCameraIntersection(cinfo, windowPos, intersections))
1290 intersections.clear();
1294 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
1296 using osgViewer::GraphicsWindow;
1297 Camera* guiCamera = getGUICamera(cgroup);
1300 Viewport* vport = guiCamera->getViewport();
1302 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
1305 globals->get_renderer()->getEventHandler()->setMouseWarped();
1306 // Translate the warp request into the viewport of the GUI camera,
1307 // send the request to the window, then transform the coordinates
1308 // for the Viewer's event queue.
1309 double wx = x + vport->x();
1310 double wyUp = vport->height() + vport->y() - y;
1312 const GraphicsContext::Traits* traits = gw->getTraits();
1313 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
1314 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
1315 wy = traits->height - wyUp;
1319 gw->getEventQueue()->mouseWarped(wx, wy);
1320 gw->requestWarpPointer(wx, wy);
1321 osgGA::GUIEventAdapter* eventState
1322 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
1324 = (eventState->getXmin()
1325 + ((wx / double(traits->width))
1326 * (eventState->getXmax() - eventState->getXmin())));
1328 = (eventState->getYmin()
1329 + ((wyUp / double(traits->height))
1330 * (eventState->getYmax() - eventState->getYmin())));
1331 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
1334 void CameraGroup::buildDefaultGroup(osgViewer::Viewer* viewer)
1336 // Look for windows, camera groups, and the old syntax of
1337 // top-level cameras
1338 SGPropertyNode* renderingNode = fgGetNode("/sim/rendering");
1339 SGPropertyNode* cgroupNode = renderingNode->getNode("camera-group", true);
1340 bool oldSyntax = !cgroupNode->hasChild("camera");
1342 for (int i = 0; i < renderingNode->nChildren(); ++i) {
1343 SGPropertyNode* propNode = renderingNode->getChild(i);
1344 const char* propName = propNode->getName();
1345 if (!strcmp(propName, "window") || !strcmp(propName, "camera")) {
1346 SGPropertyNode* copiedNode
1347 = cgroupNode->getNode(propName, propNode->getIndex(), true);
1348 copyProperties(propNode, copiedNode);
1352 SGPropertyNodeVec cameras(cgroupNode->getChildren("camera"));
1353 SGPropertyNode* masterCamera = 0;
1354 SGPropertyNodeVec::const_iterator it;
1355 for (it = cameras.begin(); it != cameras.end(); ++it) {
1356 if ((*it)->getDoubleValue("shear-x", 0.0) == 0.0
1357 && (*it)->getDoubleValue("shear-y", 0.0) == 0.0) {
1358 masterCamera = it->ptr();
1362 if (!masterCamera) {
1363 WindowBuilder *windowBuilder = WindowBuilder::getWindowBuilder();
1364 masterCamera = cgroupNode->getChild("camera", cameras.size(), true);
1365 setValue(masterCamera->getNode("window/name", true),
1366 windowBuilder->getDefaultWindowName());
1368 SGPropertyNode* nameNode = masterCamera->getNode("window/name");
1370 setValue(cgroupNode->getNode("gui/window/name", true),
1371 nameNode->getStringValue());
1374 CameraGroup* cgroup = buildCameraGroup(viewer, cgroupNode);
1378 } // of namespace flightgear