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