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