]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/CameraGroup.cxx
Don't invalidate Rembrandt buffers when the window is iconified
[flightgear.git] / src / Viewer / CameraGroup.cxx
1 // Copyright (C) 2008  Tim Moore
2 // Copyright (C) 2011  Mathias Froehlich
3 //
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.
8 //
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.
13 //
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.
17
18 #ifdef HAVE_CONFIG_H
19 #  include <config.h>
20 #endif
21
22 #include "CameraGroup.hxx"
23
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"
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>
35
36 #include <algorithm>
37 #include <cstring>
38 #include <string>
39
40 #include <osg/Camera>
41 #include <osg/Geometry>
42 #include <osg/GraphicsContext>
43 #include <osg/io_utils>
44 #include <osg/Math>
45 #include <osg/Matrix>
46 #include <osg/Notify>
47 #include <osg/Program>
48 #include <osg/Quat>
49 #include <osg/TexMat>
50 #include <osg/Vec3d>
51 #include <osg/Viewport>
52
53 #include <osgUtil/IntersectionVisitor>
54
55 #include <osgViewer/GraphicsWindow>
56 #include <osgViewer/Renderer>
57
58 namespace flightgear {
59 const char* MAIN_CAMERA = "main";
60 const char* FAR_CAMERA = "far";
61 const char* GEOMETRY_CAMERA = "geometry";
62 const char* SHADOW_CAMERA = "shadow";
63 const char* LIGHTING_CAMERA = "lighting";
64 const char* DISPLAY_CAMERA = "display";
65 }
66
67 static osg::Matrix
68 invert(const osg::Matrix& matrix)
69 {
70     return osg::Matrix::inverse(matrix);
71 }
72
73 /// Returns the zoom factor of the master camera.
74 /// The reference fov is the historic 55 deg
75 static double
76 zoomFactor()
77 {
78     double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
79     if (fov < 1)
80         fov = 1;
81     return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
82 }
83
84 static osg::Vec2d
85 preMult(const osg::Vec2d& v, const osg::Matrix& m)
86 {
87   osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
88   return osg::Vec2d(tmp[0], tmp[1]);
89 }
90
91 static osg::Matrix
92 relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
93                    const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
94 {
95   // Track the way from one projection space to the other:
96   // We want
97   //  P = T*S*P0
98   // where P0 is the projection template sensible for the given window size,
99   // T is a translation matrix and S a scale matrix.
100   // We need to determine T and S so that the reference points in the parents
101   // projection space match the two reference points in this cameras projection space.
102
103   // Starting from the parents camera projection space, we get into this cameras
104   // projection space by the transform matrix:
105   //  P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
106   // So, at first compute that matrix without T*S and determine S and T from that
107
108   // Ok, now osg uses the inverse matrix multiplication order, thus:
109   osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
110   // Compute the parents reference points in the current projection space
111   // without the yet unknown T and S
112   osg::Vec2d pRefInThis[2] = {
113     preMult(pRef[0], PtoPwithoutTS),
114     preMult(pRef[1], PtoPwithoutTS)
115   };
116
117   // To get the same zoom, rescale to match the parents size
118   double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
119   osg::Matrix S = osg::Matrix::scale(s, s, 1);
120
121   // For the translation offset, incorporate the now known scale
122   // and recompute the position ot the first reference point in the
123   // currents projection space without the yet unknown T.
124   pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
125   // The translation is then the difference of the reference points
126   osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));
127
128   // Compose and return the desired final projection matrix
129   return P0*S*T;
130 }
131
132 namespace flightgear
133 {
134 using namespace osg;
135
136 using std::strcmp;
137 using std::string;
138
139 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
140
141 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
142     _viewer(viewer)
143 {
144 }
145
146 }
147
148 namespace
149 {
150 using namespace osg;
151
152 // Given a projection matrix, return a new one with the same frustum
153 // sides and new near / far values.
154
155 void makeNewProjMat(Matrixd& oldProj, double znear,
156                                        double zfar, Matrixd& projection)
157 {
158     projection = oldProj;
159     // Slightly inflate the near & far planes to avoid objects at the
160     // extremes being clipped out.
161     znear *= 0.999;
162     zfar *= 1.001;
163
164     // Clamp the projection matrix z values to the range (near, far)
165     double epsilon = 1.0e-6;
166     if (fabs(projection(0,3)) < epsilon &&
167         fabs(projection(1,3)) < epsilon &&
168         fabs(projection(2,3)) < epsilon) {
169         // Projection is Orthographic
170         epsilon = -1.0/(zfar - znear); // Used as a temp variable
171         projection(2,2) = 2.0*epsilon;
172         projection(3,2) = (zfar + znear)*epsilon;
173     } else {
174         // Projection is Perspective
175         double trans_near = (-znear*projection(2,2) + projection(3,2)) /
176             (-znear*projection(2,3) + projection(3,3));
177         double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
178             (-zfar*projection(2,3) + projection(3,3));
179         double ratio = fabs(2.0/(trans_near - trans_far));
180         double center = -0.5*(trans_near + trans_far);
181
182         projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
183                                          0.0, 1.0, 0.0, 0.0,
184                                          0.0, 0.0, ratio, 0.0,
185                                          0.0, 0.0, center*ratio, 1.0));
186     }
187 }
188 }
189
190 namespace flightgear
191 {
192 void CameraInfo::updateCameras()
193 {
194     bufferSize->set( osg::Vec2f( width, height ) );
195
196     for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii ) {
197         float f = ii->second.scaleFactor;
198         if ( f == 0.0f ) continue;
199
200         if (ii->second.camera->getRenderTargetImplementation() == osg::Camera::FRAME_BUFFER_OBJECT)
201             ii->second.camera->getViewport()->setViewport(0, 0, width*f, height*f);
202         else
203             ii->second.camera->getViewport()->setViewport(x*f, y*f, width*f, height*f);
204     }
205
206     for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii ) {
207         float f = ii->second.scaleFactor;
208         if ( f == 0.0f ) continue;
209         osg::Texture2D* texture = ii->second.texture.get();
210         if ( texture->getTextureHeight() != height*f || texture->getTextureWidth() != width*f ) {
211             texture->setTextureSize( width*f, height*f );
212             texture->dirtyTextureObject();
213         }
214     }
215 }
216
217 void CameraInfo::resized(double w, double h)
218 {
219         if (w == 1.0 && h == 1.0)
220                 return;
221
222     bufferSize->set( osg::Vec2f( w, h ) );
223
224     for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii) {
225         float s = ii->second.scaleFactor;
226         if ( s == 0.0f ) continue;
227         ii->second.texture->setTextureSize( w * s, h * s );
228         ii->second.texture->dirtyTextureObject();
229     }
230
231     for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii) {
232         RenderStageInfo& rsi = ii->second;
233         if (!rsi.resizable ||
234                 rsi.camera->getRenderTargetImplementation() != osg::Camera::FRAME_BUFFER_OBJECT ||
235                 rsi.scaleFactor == 0.0f )
236             continue;
237
238         Viewport* vp = rsi.camera->getViewport();
239         vp->width() = w * rsi.scaleFactor;
240         vp->height() = h * rsi.scaleFactor;
241
242         osgViewer::Renderer* renderer
243             = static_cast<osgViewer::Renderer*>(rsi.camera->getRenderer());
244         for (int i = 0; i < 2; ++i) {
245             osgUtil::SceneView* sceneView = renderer->getSceneView(i);
246             sceneView->getRenderStage()->setFrameBufferObject(0);
247             sceneView->getRenderStage()->setCameraRequiresSetUp(true);
248             if (sceneView->getRenderStageLeft()) {
249                 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
250                 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
251             }
252             if (sceneView->getRenderStageRight()) {
253                 sceneView->getRenderStageRight()->setFrameBufferObject(0);
254                 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
255             }
256         }
257     }
258 }
259
260 osg::Camera* CameraInfo::getCamera(const std::string& k) const
261 {
262     CameraMap::const_iterator ii = cameras.find( k );
263     if (ii == cameras.end())
264         return 0;
265     return ii->second.camera.get();
266 }
267
268 osg::Texture2D* CameraInfo::getBuffer(const std::string& k) const
269 {
270     RenderBufferMap::const_iterator ii = buffers.find(k);
271     if (ii == buffers.end())
272         return 0;
273     return ii->second.texture.get();
274 }
275
276 int CameraInfo::getMainSlaveIndex() const
277 {
278     return cameras.find( MAIN_CAMERA )->second.slaveIndex;
279 }
280
281 void CameraInfo::setMatrices(osg::Camera* c)
282 {
283     view->set( c->getViewMatrix() );
284     osg::Matrixd vi = c->getInverseViewMatrix();
285     viewInverse->set( vi );
286     projInverse->set( osg::Matrix::inverse( c->getProjectionMatrix() ) );
287     osg::Vec4d pos = osg::Vec4d(0., 0., 0., 1.) * vi;
288     worldPosCart->set( osg::Vec3f( pos.x(), pos.y(), pos.z() ) );
289     SGGeod pos2 = SGGeod::fromCart( SGVec3d( pos.x(), pos.y(), pos.z() ) );
290     worldPosGeod->set( osg::Vec3f( pos2.getLongitudeRad(), pos2.getLatitudeRad(), pos2.getElevationM() ) );
291 }
292
293 void CameraGroup::update(const osg::Vec3d& position,
294                          const osg::Quat& orientation)
295 {
296     const Matrix masterView(osg::Matrix::translate(-position)
297                             * osg::Matrix::rotate(orientation.inverse()));
298     _viewer->getCamera()->setViewMatrix(masterView);
299     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
300     double masterZoomFactor = zoomFactor();
301     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
302         const CameraInfo* info = i->get();
303
304         Camera* camera = info->getCamera(MAIN_CAMERA);
305         if ( camera ) {
306             const View::Slave& slave = _viewer->getSlave(info->getMainSlaveIndex());
307 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
308             // refreshes camera viewports (for now)
309             info->updateCameras();
310 #endif
311             Matrix viewMatrix;
312             if (info->flags & GUI) {
313                 viewMatrix = osg::Matrix(); // identifty transform on the GUI camera
314             } else if ((info->flags & VIEW_ABSOLUTE) != 0)
315                 viewMatrix = slave._viewOffset;
316             else
317                 viewMatrix = masterView * slave._viewOffset;
318             camera->setViewMatrix(viewMatrix);
319             Matrix projectionMatrix;
320             if (info->flags & GUI) {
321                 projectionMatrix = osg::Matrix::ortho2D(0, info->width, 0, info->height);
322             } else if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
323                 if (info->flags & ENABLE_MASTER_ZOOM) {
324                     if (info->relativeCameraParent < _cameras.size()) {
325                         // template projection matrix and view matrix of the current camera
326                         osg::Matrix P0 = slave._projectionOffset;
327                         osg::Matrix R = viewMatrix;
328
329                         // The already known projection and view matrix of the parent camera
330                         const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
331                         RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
332                         osg::Matrix pP = prsi.camera->getProjectionMatrix();
333                         osg::Matrix pR = prsi.camera->getViewMatrix();
334                     
335                         // And the projection matrix derived from P0 so that the reference points match
336                         projectionMatrix = relativeProjection(P0, R, info->thisReference,
337                                                               pP, pR, info->parentReference);
338                     
339                     } else {
340                         // We want to zoom, so take the original matrix and apply the zoom to it.
341                         projectionMatrix = slave._projectionOffset;
342                         projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
343                     }
344                 } else {
345                     projectionMatrix = slave._projectionOffset;
346                 }
347             } else {
348                 projectionMatrix = masterProj * slave._projectionOffset;
349             }
350
351             CameraMap::const_iterator ii = info->cameras.find(FAR_CAMERA);
352             if (ii == info->cameras.end() || !ii->second.camera.valid()) {
353                 camera->setProjectionMatrix(projectionMatrix);
354             } else {
355                 Camera* farCamera = ii->second.camera;
356                 farCamera->setViewMatrix(viewMatrix);
357                 double left, right, bottom, top, parentNear, parentFar;
358                 projectionMatrix.getFrustum(left, right, bottom, top,
359                                             parentNear, parentFar);
360                 if ((info->flags & FIXED_NEAR_FAR) == 0) {
361                     parentNear = _zNear;
362                     parentFar = _zFar;
363                 }
364                 if (parentFar < _nearField || _nearField == 0.0f) {
365                     camera->setProjectionMatrix(projectionMatrix);
366                     camera->setCullMask(camera->getCullMask()
367                                         | simgear::BACKGROUND_BIT);
368                     camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
369                     farCamera->setNodeMask(0);
370                 } else {
371                     Matrix nearProj, farProj;
372                     makeNewProjMat(projectionMatrix, parentNear, _nearField,
373                                    nearProj);
374                     makeNewProjMat(projectionMatrix, _nearField, parentFar,
375                                    farProj);
376                     camera->setProjectionMatrix(nearProj);
377                     camera->setCullMask(camera->getCullMask()
378                                         & ~simgear::BACKGROUND_BIT);
379                     camera->setClearMask(GL_DEPTH_BUFFER_BIT);
380                     farCamera->setProjectionMatrix(farProj);
381                     farCamera->setNodeMask(camera->getNodeMask());
382                 }
383             }
384         } else {
385             bool viewDone = false;
386             Matrix viewMatrix;
387             bool projectionDone = false;
388             Matrix projectionMatrix;
389             for ( CameraMap::const_iterator ii = info->cameras.begin(); ii != info->cameras.end(); ++ii ) {
390                 if ( ii->first == SHADOW_CAMERA ) {
391                     globals->get_renderer()->updateShadowCamera(info, position);
392                     continue;
393                 }
394                 if ( ii->second.fullscreen )
395                     continue;
396
397                 Camera* camera = ii->second.camera.get();
398                 int slaveIndex = ii->second.slaveIndex;
399                 const View::Slave& slave = _viewer->getSlave(slaveIndex);
400
401                 if ( !viewDone ) {
402                     if ((info->flags & VIEW_ABSOLUTE) != 0)
403                         viewMatrix = slave._viewOffset;
404                     else
405                         viewMatrix = masterView * slave._viewOffset;
406                     viewDone = true;
407                 }
408
409                 camera->setViewMatrix( viewMatrix );
410
411                 if ( !projectionDone ) {
412                     if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
413                         if (info->flags & ENABLE_MASTER_ZOOM) {
414                             if (info->relativeCameraParent < _cameras.size()) {
415                                 // template projection matrix and view matrix of the current camera
416                                 osg::Matrix P0 = slave._projectionOffset;
417                                 osg::Matrix R = viewMatrix;
418
419                                 // The already known projection and view matrix of the parent camera
420                                 const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
421                                 RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
422                                 osg::Matrix pP = prsi.camera->getProjectionMatrix();
423                                 osg::Matrix pR = prsi.camera->getViewMatrix();
424                     
425                                 // And the projection matrix derived from P0 so that the reference points match
426                                 projectionMatrix = relativeProjection(P0, R, info->thisReference,
427                                                                       pP, pR, info->parentReference);
428                     
429                             } else {
430                                 // We want to zoom, so take the original matrix and apply the zoom to it.
431                                 projectionMatrix = slave._projectionOffset;
432                                 projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
433                             }
434                         } else {
435                             projectionMatrix = slave._projectionOffset;
436                         }
437                     } else {
438                         projectionMatrix = masterProj * slave._projectionOffset;
439                     }
440                     projectionDone = true;
441                 }
442
443                 camera->setProjectionMatrix(projectionMatrix);
444             }
445         }
446     }
447
448     globals->get_renderer()->setPlanes( _zNear, _zFar );
449 }
450
451 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
452 {
453     if (vfov != 0.0f && aspectRatio != 0.0f)
454         _viewer->getCamera()
455             ->setProjectionMatrixAsPerspective(vfov,
456                                                1.0f / aspectRatio,
457                                                _zNear, _zFar);
458 }
459     
460 double CameraGroup::getMasterAspectRatio() const
461 {
462     if (_cameras.empty())
463         return 0.0;
464     
465     const CameraInfo* info = _cameras.front();
466     
467     osg::Camera* camera = info->getCamera(MAIN_CAMERA);
468     if ( !camera )
469         camera = info->getCamera( GEOMETRY_CAMERA );
470     const osg::Viewport* viewport = camera->getViewport();
471     if (!viewport) {
472         return 0.0;
473     }
474     
475     return static_cast<double>(viewport->height()) / viewport->width();
476 }
477     
478 }
479
480 namespace
481 {
482 // A raw value for property nodes that references a class member via
483 // an osg::ref_ptr.
484 template<class C, class T>
485 class RefMember : public SGRawValue<T>
486 {
487 public:
488     RefMember (C *obj, T C::*ptr)
489         : _obj(obj), _ptr(ptr) {}
490     virtual ~RefMember () {}
491     virtual T getValue () const
492     {
493         return _obj.get()->*_ptr;
494     }
495     virtual bool setValue (T value)
496     {
497         _obj.get()->*_ptr = value;
498         return true;
499     }
500     virtual SGRawValue<T> * clone () const
501     {
502         return new RefMember(_obj.get(), _ptr);
503     }
504 private:
505     ref_ptr<C> _obj;
506     T C::* const _ptr;
507 };
508
509 template<typename C, typename T>
510 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
511 {
512     return RefMember<C, T>(obj, ptr);
513 }
514
515 template<typename C, typename T>
516 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
517                       C* obj, T C::*ptr, T value)
518 {
519     SGPropertyNode* valNode = parent->getNode(childName);
520     RefMember<C, T> refMember = makeRefMember(obj, ptr);
521     if (!valNode) {
522         valNode = parent->getNode(childName, true);
523         valNode->tie(refMember, false);
524         setValue(valNode, value);
525     } else {
526         valNode->tie(refMember, true);
527     }
528 }
529
530 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
531                    const osg::GraphicsContext::Traits *traits)
532 {
533     using namespace flightgear;
534     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
535     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
536     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
537                      static_cast<double>(traits->width));
538     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
539                      static_cast<double>(traits->height));
540 }
541 }
542
543 namespace flightgear
544 {
545
546 // Mostly copied from osg's osgViewer/View.cpp
547
548 static osg::Geometry* createPanoramicSphericalDisplayDistortionMesh(
549     const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
550     double sphere_radius, double collar_radius,
551     Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
552 {
553     osg::Vec3d center(0.0,0.0,0.0);
554     osg::Vec3d eye(0.0,0.0,0.0);
555
556     double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
557     bool flip = false;
558     bool texcoord_flip = false;
559
560 #if 0
561     osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
562
563     OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
564     OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
565 #endif
566     // create the quad to visualize.
567     osg::Geometry* geometry = new osg::Geometry();
568
569     geometry->setSupportsDisplayList(false);
570
571     osg::Vec3 xAxis(widthVector);
572     float width = widthVector.length();
573     xAxis /= width;
574
575     osg::Vec3 yAxis(heightVector);
576     float height = heightVector.length();
577     yAxis /= height;
578
579     int noSteps = 160;
580
581     osg::Vec3Array* vertices = new osg::Vec3Array;
582     osg::Vec2Array* texcoords0 = new osg::Vec2Array;
583     osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
584     osg::Vec4Array* colors = new osg::Vec4Array;
585
586 #if 0
587     osg::Vec3 bottom = origin;
588     osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
589     osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
590 #endif
591     osg::Vec3 top = origin + yAxis*height;
592
593     osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
594     float screenRadius = heightVector.length() * 0.5f;
595
596     geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
597
598     for(int i=0;i<noSteps;++i)
599     {
600         //osg::Vec3 cursor = bottom+dy*(float)i;
601         for(int j=0;j<noSteps;++j)
602         {
603             osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
604             double theta = texcoord.x() * 2.0 * osg::PI;
605             double phi = (1.0-texcoord.y()) * osg::PI;
606
607             if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
608
609             osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
610             pos = pos*projectorMatrix;
611
612             double alpha = atan2(pos.x(), pos.y());
613             if (alpha<0.0) alpha += 2.0*osg::PI;
614
615             double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
616             if (beta<0.0) beta += 2.0*osg::PI;
617
618             double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
619             if (gamma<0.0) gamma += 2.0*osg::PI;
620
621
622             osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
623
624             if (flip)
625                 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
626             else
627                 vertices->push_back(v);
628
629             texcoords0->push_back( texcoord );
630
631             osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
632             if (intensityMap)
633             {
634                 colors->push_back(intensityMap->getColor(texcoord1));
635             }
636             else
637             {
638                 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
639                 if (texcoords1) texcoords1->push_back( texcoord1 );
640             }
641
642
643         }
644     }
645
646
647     // pass the created vertex array to the points geometry object.
648     geometry->setVertexArray(vertices);
649
650     geometry->setColorArray(colors);
651     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
652
653     geometry->setTexCoordArray(0,texcoords0);
654     if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
655
656     osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
657     geometry->addPrimitiveSet(elements);
658
659     for(int i=0;i<noSteps-1;++i)
660     {
661         for(int j=0;j<noSteps-1;++j)
662         {
663             int i1 = j+(i+1)*noSteps;
664             int i2 = j+(i)*noSteps;
665             int i3 = j+1+(i)*noSteps;
666             int i4 = j+1+(i+1)*noSteps;
667
668             osg::Vec3& v1 = (*vertices)[i1];
669             osg::Vec3& v2 = (*vertices)[i2];
670             osg::Vec3& v3 = (*vertices)[i3];
671             osg::Vec3& v4 = (*vertices)[i4];
672
673             if ((v1-screenCenter).length()>screenRadius) continue;
674             if ((v2-screenCenter).length()>screenRadius) continue;
675             if ((v3-screenCenter).length()>screenRadius) continue;
676             if ((v4-screenCenter).length()>screenRadius) continue;
677
678             elements->push_back(i1);
679             elements->push_back(i2);
680             elements->push_back(i3);
681
682             elements->push_back(i1);
683             elements->push_back(i3);
684             elements->push_back(i4);
685         }
686     }
687
688     return geometry;
689 }
690
691 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
692                                         Camera* camera)
693 {
694     const SGPropertyNode* texNode = psNode->getNode("texture");
695     if (!texNode) {
696         // error
697         return;
698     }
699     string texName = texNode->getStringValue();
700     TextureMap::iterator itr = _textureTargets.find(texName);
701     if (itr == _textureTargets.end()) {
702         // error
703         return;
704     }
705     Viewport* viewport = camera->getViewport();
706     float width = viewport->width();
707     float height = viewport->height();
708     TextureRectangle* texRect = itr->second.get();
709     double radius = psNode->getDoubleValue("radius", 1.0);
710     double collar = psNode->getDoubleValue("collar", 0.45);
711     Geode* geode = new Geode();
712     geode->addDrawable(createPanoramicSphericalDisplayDistortionMesh(
713                            Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
714                            Vec3(0.0f,height,0.0f), radius, collar));
715
716     // new we need to add the texture to the mesh, we do so by creating a
717     // StateSet to contain the Texture StateAttribute.
718     StateSet* stateset = geode->getOrCreateStateSet();
719     stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
720     stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
721
722     TexMat* texmat = new TexMat;
723     texmat->setScaleByTextureRectangleSize(true);
724     stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
725 #if 0
726     if (!applyIntensityMapAsColours && intensityMap)
727     {
728         stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
729     }
730 #endif
731     // add subgraph to render
732     camera->addChild(geode);
733     camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
734     camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
735     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
736     camera->setCullingMode(osg::CullSettings::NO_CULLING);
737     camera->setName("DistortionCorrectionCamera");
738 }
739
740 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
741 {
742     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
743     const SGPropertyNode* windowNode = cameraNode->getNode("window");
744     GraphicsWindow* window = 0;
745     int cameraFlags = DO_INTERSECTION_TEST;
746     if (windowNode) {
747         // New style window declaration / definition
748         window = wBuild->buildWindow(windowNode);
749     } else {
750         // Old style: suck window params out of camera block
751         window = wBuild->buildWindow(cameraNode);
752     }
753     if (!window) {
754         return 0;
755     }
756     Camera* camera = new Camera;
757     camera->setAllowEventFocus(false);
758     camera->setGraphicsContext(window->gc.get());
759     camera->setViewport(new Viewport);
760     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
761                            | CullSettings::VIEW_FRUSTUM_CULLING);
762     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
763                                & ~(CullSettings::CULL_MASK
764                                    | CullSettings::CULLING_MODE
765                                    | CullSettings::CLEAR_MASK
766                                    ));
767
768     osg::Matrix vOff;
769     const SGPropertyNode* viewNode = cameraNode->getNode("view");
770     if (viewNode) {
771         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
772         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
773         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
774         double x = viewNode->getDoubleValue("x", 0.0);
775         double y = viewNode->getDoubleValue("y", 0.0);
776         double z = viewNode->getDoubleValue("z", 0.0);
777         // Build a view matrix, which is the inverse of a model
778         // orientation matrix.
779         vOff = (Matrix::translate(-x, -y, -z)
780                 * Matrix::rotate(-DegreesToRadians(heading),
781                                  Vec3d(0.0, 1.0, 0.0),
782                                  -DegreesToRadians(pitch),
783                                  Vec3d(1.0, 0.0, 0.0),
784                                  -DegreesToRadians(roll),
785                                  Vec3d(0.0, 0.0, 1.0)));
786         if (viewNode->getBoolValue("absolute", false))
787             cameraFlags |= VIEW_ABSOLUTE;
788     } else {
789         // Old heading parameter, works in the opposite direction
790         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
791         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
792     }
793     // Configuring the physical dimensions of a monitor
794     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
795     double physicalWidth = viewportNode->getDoubleValue("width", 1024);
796     double physicalHeight = viewportNode->getDoubleValue("height", 768);
797     double bezelHeightTop = 0;
798     double bezelHeightBottom = 0;
799     double bezelWidthLeft = 0;
800     double bezelWidthRight = 0;
801     const SGPropertyNode* physicalDimensionsNode = 0;
802     if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
803         physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
804         physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
805         const SGPropertyNode* bezelNode = 0;
806         if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
807             bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
808             bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
809             bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
810             bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
811         }
812     }
813     osg::Matrix pOff;
814     unsigned parentCameraIndex = ~0u;
815     osg::Vec2d parentReference[2];
816     osg::Vec2d thisReference[2];
817     SGPropertyNode* projectionNode = 0;
818     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
819         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
820         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
821                                                             1.0);
822         double zNear = projectionNode->getDoubleValue("near", 0.0);
823         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
824         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
825         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
826         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
827         double right = tan_fovy * aspectRatio * zNear + offsetX;
828         double left = -tan_fovy * aspectRatio * zNear + offsetX;
829         double top = tan_fovy * zNear + offsetY;
830         double bottom = -tan_fovy * zNear + offsetY;
831         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
832         cameraFlags |= PROJECTION_ABSOLUTE;
833         if (projectionNode->getBoolValue("fixed-near-far", true))
834             cameraFlags |= FIXED_NEAR_FAR;
835     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
836                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
837         double top = projectionNode->getDoubleValue("top", 0.0);
838         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
839         double left = projectionNode->getDoubleValue("left", 0.0);
840         double right = projectionNode->getDoubleValue("right", 0.0);
841         double zNear = projectionNode->getDoubleValue("near", 0.0);
842         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
843         if (cameraNode->getNode("frustum")) {
844             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
845             cameraFlags |= PROJECTION_ABSOLUTE;
846         } else {
847             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
848             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
849         }
850         if (projectionNode->getBoolValue("fixed-near-far", true))
851             cameraFlags |= FIXED_NEAR_FAR;
852     } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
853         double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
854         double xoff = projectionNode->getDoubleValue("x-offset", 0);
855         double yoff = projectionNode->getDoubleValue("y-offset", 0);
856         double left = -0.5*physicalWidth - xoff;
857         double right = 0.5*physicalWidth - xoff;
858         double bottom = -0.5*physicalHeight - yoff;
859         double top = 0.5*physicalHeight - yoff;
860         pOff.makeFrustum(left, right, bottom, top, zNear, zNear*1000);
861         cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
862     } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
863                || (projectionNode = cameraNode->getNode("left-of-perspective"))
864                || (projectionNode = cameraNode->getNode("above-perspective"))
865                || (projectionNode = cameraNode->getNode("below-perspective"))
866                || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
867         std::string name = projectionNode->getStringValue("parent-camera");
868         for (unsigned i = 0; i < _cameras.size(); ++i) {
869             if (_cameras[i]->name != name)
870                 continue;
871             parentCameraIndex = i;
872         }
873         if (_cameras.size() <= parentCameraIndex) {
874             SG_LOG(SG_VIEW, SG_ALERT, "CameraGroup::buildCamera: "
875                    "failed to find parent camera for relative camera!");
876             return 0;
877         }
878         const CameraInfo* parentInfo = _cameras[parentCameraIndex].get();
879         if (projectionNode->getNameString() == "right-of-perspective") {
880             double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
881             parentReference[0] = osg::Vec2d(tmp, -1);
882             parentReference[1] = osg::Vec2d(tmp, 1);
883             tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
884             thisReference[0] = osg::Vec2d(-tmp, -1);
885             thisReference[1] = osg::Vec2d(-tmp, 1);
886         } else if (projectionNode->getNameString() == "left-of-perspective") {
887             double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
888             parentReference[0] = osg::Vec2d(-tmp, -1);
889             parentReference[1] = osg::Vec2d(-tmp, 1);
890             tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
891             thisReference[0] = osg::Vec2d(tmp, -1);
892             thisReference[1] = osg::Vec2d(tmp, 1);
893         } else if (projectionNode->getNameString() == "above-perspective") {
894             double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
895             parentReference[0] = osg::Vec2d(-1, tmp);
896             parentReference[1] = osg::Vec2d(1, tmp);
897             tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
898             thisReference[0] = osg::Vec2d(-1, -tmp);
899             thisReference[1] = osg::Vec2d(1, -tmp);
900         } else if (projectionNode->getNameString() == "below-perspective") {
901             double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
902             parentReference[0] = osg::Vec2d(-1, -tmp);
903             parentReference[1] = osg::Vec2d(1, -tmp);
904             tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
905             thisReference[0] = osg::Vec2d(-1, tmp);
906             thisReference[1] = osg::Vec2d(1, tmp);
907         } else if (projectionNode->getNameString() == "reference-points-perspective") {
908             SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
909             SGPropertyNode* thisNode = projectionNode->getNode("this", true);
910             SGPropertyNode* pointNode;
911
912             pointNode = parentNode->getNode("point", 0, true);
913             parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
914             parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
915             pointNode = parentNode->getNode("point", 1, true);
916             parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
917             parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
918
919             pointNode = thisNode->getNode("point", 0, true);
920             thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
921             thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
922             pointNode = thisNode->getNode("point", 1, true);
923             thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
924             thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
925         }
926
927         pOff = osg::Matrix::perspective(45, physicalWidth/physicalHeight, 1, 20000);
928         cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
929     } else {
930         // old style shear parameters
931         double shearx = cameraNode->getDoubleValue("shear-x", 0);
932         double sheary = cameraNode->getDoubleValue("shear-y", 0);
933         pOff.makeTranslate(-shearx, -sheary, 0);
934     }
935     const SGPropertyNode* textureNode = cameraNode->getNode("texture");
936     if (textureNode) {
937         string texName = textureNode->getStringValue("name");
938         int tex_width = textureNode->getIntValue("width");
939         int tex_height = textureNode->getIntValue("height");
940         TextureRectangle* texture = new TextureRectangle;
941
942         texture->setTextureSize(tex_width, tex_height);
943         texture->setInternalFormat(GL_RGB);
944         texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
945         texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
946         texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
947         texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
948         camera->setDrawBuffer(GL_FRONT);
949         camera->setReadBuffer(GL_FRONT);
950         camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
951         camera->attach(Camera::COLOR_BUFFER, texture);
952         _textureTargets[texName] = texture;
953     } else {
954         camera->setDrawBuffer(GL_BACK);
955         camera->setReadBuffer(GL_BACK);
956     }
957     const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
958     bool useMasterSceneGraph = !psNode;
959     CameraInfo* info = globals->get_renderer()->buildRenderingPipeline(this, cameraFlags, camera, vOff, pOff,
960                                                                         window->gc.get(), useMasterSceneGraph);
961     info->name = cameraNode->getStringValue("name");
962     info->physicalWidth = physicalWidth;
963     info->physicalHeight = physicalHeight;
964     info->bezelHeightTop = bezelHeightTop;
965     info->bezelHeightBottom = bezelHeightBottom;
966     info->bezelWidthLeft = bezelWidthLeft;
967     info->bezelWidthRight = bezelWidthRight;
968     info->relativeCameraParent = parentCameraIndex;
969     info->parentReference[0] = parentReference[0];
970     info->parentReference[1] = parentReference[1];
971     info->thisReference[0] = thisReference[0];
972     info->thisReference[1] = thisReference[1];
973     // If a viewport isn't set on the camera, then it's hard to dig it
974     // out of the SceneView objects in the viewer, and the coordinates
975     // of mouse events are somewhat bizzare.
976     buildViewport(info, viewportNode, window->gc->getTraits());
977     info->updateCameras();
978     // Distortion camera needs the viewport which is created by addCamera().
979     if (psNode) {
980         info->flags = info->flags | VIEW_ABSOLUTE;
981         buildDistortionCamera(psNode, camera);
982     }
983     return info;
984 }
985
986 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
987                                         GraphicsWindow* window)
988 {
989     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
990     const SGPropertyNode* windowNode = (cameraNode
991                                         ? cameraNode->getNode("window")
992                                         : 0);
993     if (!window && windowNode) {
994       // New style window declaration / definition
995       window = wBuild->buildWindow(windowNode);
996     }
997
998     if (!window) { // buildWindow can fail
999       SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
1000       return NULL;
1001     }
1002
1003     Camera* camera = new Camera;
1004     camera->setName( "GUICamera" );
1005     camera->setAllowEventFocus(false);
1006     camera->setGraphicsContext(window->gc.get());
1007     camera->setViewport(new Viewport);
1008     camera->setClearMask(0);
1009     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
1010                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
1011                                    | CullSettings::CULLING_MODE
1012                                    | CullSettings::CLEAR_MASK
1013                                    ));
1014     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1015     camera->setCullingMode(osg::CullSettings::NO_CULLING);
1016     camera->setProjectionResizePolicy(Camera::FIXED);
1017     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1018     const int cameraFlags = GUI | DO_INTERSECTION_TEST;
1019
1020     CameraInfo* result = new CameraInfo(cameraFlags);
1021     // The camera group will always update the camera
1022     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1023
1024     getViewer()->addSlave(camera, Matrixd::identity(), Matrixd::identity(), false);
1025     //installCullVisitor(camera);
1026     int slaveIndex = getViewer()->getNumSlaves() - 1;
1027     result->addCamera( MAIN_CAMERA, camera, slaveIndex );
1028     camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
1029     addCamera(result);
1030
1031     // XXX Camera needs to be drawn last; eventually the render order
1032     // should be assigned by a camera manager.
1033     camera->setRenderOrder(osg::Camera::POST_RENDER, 10000);
1034     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
1035     buildViewport(result, viewportNode, window->gc->getTraits());
1036
1037     // Disable statistics for the GUI camera.
1038     camera->setStats(0);
1039     result->updateCameras();
1040     return result;
1041 }
1042
1043 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
1044                                            SGPropertyNode* gnode)
1045 {
1046     CameraGroup* cgroup = new CameraGroup(viewer);
1047     for (int i = 0; i < gnode->nChildren(); ++i) {
1048         SGPropertyNode* pNode = gnode->getChild(i);
1049         const char* name = pNode->getName();
1050         if (!strcmp(name, "camera")) {
1051             cgroup->buildCamera(pNode);
1052         } else if (!strcmp(name, "window")) {
1053             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
1054         } else if (!strcmp(name, "gui")) {
1055             cgroup->buildGUICamera(pNode);
1056         }
1057     }
1058     bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
1059     bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
1060     bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
1061                      100.0f);
1062     return cgroup;
1063 }
1064
1065 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
1066 {
1067     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1068         CameraInfo* info = i->get();
1069         if (info->flags & GUI)
1070             continue;
1071         osg::ref_ptr<osg::Camera> farCamera = info->getCamera(FAR_CAMERA);
1072         osg::Camera* camera = info->getCamera( MAIN_CAMERA );
1073         if (camera) {
1074             if (farCamera.valid() && farCamera->getNodeMask() != 0) {
1075                 camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
1076                 camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
1077                 camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
1078                 farCamera->setCullMask(nm);
1079                 farCamera->setCullMaskLeft(nm);
1080                 farCamera->setCullMaskRight(nm);
1081             } else {
1082                 camera->setCullMask(nm);
1083                 camera->setCullMaskLeft(nm);
1084                 camera->setCullMaskRight(nm);
1085             }
1086         } else {
1087             camera = info->getCamera( GEOMETRY_CAMERA );
1088             if (camera == 0) continue;
1089             camera->setCullMask( nm & ~simgear::MODELLIGHT_BIT );
1090         }
1091     }
1092 }
1093
1094 void CameraGroup::resized()
1095 {
1096     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1097         CameraInfo *info = i->get();
1098         Camera* camera = info->getCamera( MAIN_CAMERA );
1099         if ( camera == 0 )
1100             camera = info->getCamera( DISPLAY_CAMERA );
1101         const Viewport* viewport = camera->getViewport();
1102         info->x = viewport->x();
1103         info->y = viewport->y();
1104         info->width = viewport->width();
1105         info->height = viewport->height();
1106
1107         info->resized( info->width, info->height );
1108     }
1109 }
1110
1111 const CameraInfo* CameraGroup::getGUICamera() const
1112 {
1113     ConstCameraIterator result
1114         = std::find_if(camerasBegin(), camerasEnd(),
1115                    FlagTester<CameraInfo>(GUI));
1116     if (result == camerasEnd()) {
1117         return NULL;
1118     }
1119
1120     return *result;
1121 }
1122   
1123 Camera* getGUICamera(CameraGroup* cgroup)
1124 {
1125     const CameraInfo* info = cgroup->getGUICamera();
1126     if (!info) {
1127         return NULL;
1128     }
1129     
1130     return info->getCamera(MAIN_CAMERA);
1131 }
1132
1133 static bool computeCameraIntersection(const CameraInfo* cinfo,
1134                                       const osgGA::GUIEventAdapter* ea,
1135                                       osgUtil::LineSegmentIntersector::Intersections& intersections)
1136 {
1137   using osgUtil::Intersector;
1138   using osgUtil::LineSegmentIntersector;
1139   double x, y;
1140   eventToWindowCoords(ea, x, y);
1141   
1142   if (!(cinfo->flags & CameraGroup::DO_INTERSECTION_TEST))
1143     return false;
1144   
1145   const Camera* camera = cinfo->getCamera(MAIN_CAMERA);
1146   if ( !camera )
1147     camera = cinfo->getCamera( GEOMETRY_CAMERA );
1148   if (camera->getGraphicsContext() != ea->getGraphicsContext())
1149     return false;
1150   
1151   const Viewport* viewport = camera->getViewport();
1152   double epsilon = 0.5;
1153   if (!(x >= viewport->x() - epsilon
1154         && x < viewport->x() + viewport->width() -1.0 + epsilon
1155         && y >= viewport->y() - epsilon
1156         && y < viewport->y() + viewport->height() -1.0 + epsilon))
1157     return false;
1158   
1159   Vec4d start(x, y, 0.0, 1.0);
1160   Vec4d end(x, y, 1.0, 1.0);
1161   Matrix windowMat = viewport->computeWindowMatrix();
1162   Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
1163                                       * windowMat);
1164   Matrix endPtMat;
1165   const Camera* farCamera = cinfo->getCamera( FAR_CAMERA );
1166   if (!farCamera || farCamera->getNodeMask() == 0)
1167     endPtMat = startPtMat;
1168   else
1169     endPtMat = Matrix::inverse(farCamera->getProjectionMatrix()
1170                                * windowMat);
1171   start = start * startPtMat;
1172   start /= start.w();
1173   end = end * endPtMat;
1174   end /= end.w();
1175   ref_ptr<LineSegmentIntersector> picker
1176   = new LineSegmentIntersector(Intersector::VIEW,
1177                                Vec3d(start.x(), start.y(), start.z()),
1178                                Vec3d(end.x(), end.y(), end.z()));
1179   osgUtil::IntersectionVisitor iv(picker.get());
1180   iv.setTraversalMask( ~simgear::MODELLIGHT_BIT );
1181   const_cast<Camera*>(camera)->accept(iv);
1182   if (picker->containsIntersections()) {
1183     intersections = picker->getIntersections();
1184     return true;
1185   }
1186   
1187   return false;
1188 }
1189   
1190 bool computeIntersections(const CameraGroup* cgroup,
1191                           const osgGA::GUIEventAdapter* ea,
1192                           osgUtil::LineSegmentIntersector::Intersections& intersections)
1193 {
1194     // test the GUI first
1195     const CameraInfo* guiCamera = cgroup->getGUICamera();
1196     if (guiCamera && computeCameraIntersection(guiCamera, ea, intersections))
1197         return true;
1198     
1199     // Find camera that contains event
1200     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
1201              e = cgroup->camerasEnd();
1202          iter != e;
1203          ++iter) {
1204         const CameraInfo* cinfo = iter->get();
1205         if (cinfo == guiCamera)
1206             continue;
1207         
1208         if (computeCameraIntersection(cinfo, ea, intersections))
1209             return true;
1210     }
1211   
1212     intersections.clear();
1213     return false;
1214 }
1215
1216 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
1217 {
1218     using osgViewer::GraphicsWindow;
1219     Camera* guiCamera = getGUICamera(cgroup);
1220     if (!guiCamera)
1221         return;
1222     Viewport* vport = guiCamera->getViewport();
1223     GraphicsWindow* gw
1224         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
1225     if (!gw)
1226         return;
1227     globals->get_renderer()->getEventHandler()->setMouseWarped();
1228     // Translate the warp request into the viewport of the GUI camera,
1229     // send the request to the window, then transform the coordinates
1230     // for the Viewer's event queue.
1231     double wx = x + vport->x();
1232     double wyUp = vport->height() + vport->y() - y;
1233     double wy;
1234     const GraphicsContext::Traits* traits = gw->getTraits();
1235     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
1236         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
1237         wy = traits->height - wyUp;
1238     } else {
1239         wy = wyUp;
1240     }
1241     gw->getEventQueue()->mouseWarped(wx, wy);
1242     gw->requestWarpPointer(wx, wy);
1243     osgGA::GUIEventAdapter* eventState
1244         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
1245     double viewerX
1246         = (eventState->getXmin()
1247            + ((wx / double(traits->width))
1248               * (eventState->getXmax() - eventState->getXmin())));
1249     double viewerY
1250         = (eventState->getYmin()
1251            + ((wyUp / double(traits->height))
1252               * (eventState->getYmax() - eventState->getYmin())));
1253     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
1254 }
1255 }