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