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