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