]> git.mxchange.org Git - flightgear.git/blob - src/Main/CameraGroup.cxx
Merge branch 'next' into durk-atc
[flightgear.git] / src / Main / CameraGroup.cxx
1 // Copyright (C) 2008  Tim Moore
2 //
3 // This program is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU General Public License as
5 // published by the Free Software Foundation; either version 2 of the
6 // License, or (at your option) any later version.
7 //
8 // This program is distributed in the hope that it will be useful, but
9 // WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 #ifdef HAVE_CONFIG_H
18 #  include <config.h>
19 #endif
20
21 #include "CameraGroup.hxx"
22
23 #include "globals.hxx"
24 #include "renderer.hxx"
25 #include "FGEventHandler.hxx"
26 #include "WindowBuilder.hxx"
27 #include "WindowSystemAdapter.hxx"
28 #include <simgear/props/props.hxx>
29 #include <simgear/structure/OSGUtils.hxx>
30 #include <simgear/structure/OSGVersion.hxx>
31 #include <simgear/scene/material/EffectCullVisitor.hxx>
32 #include <simgear/scene/util/RenderConstants.hxx>
33
34 #include <algorithm>
35 #include <cstring>
36 #include <string>
37
38 #include <osg/Camera>
39 #include <osg/Geometry>
40 #include <osg/GraphicsContext>
41 #include <osg/io_utils>
42 #include <osg/Math>
43 #include <osg/Matrix>
44 #include <osg/Notify>
45 #include <osg/Program>
46 #include <osg/Quat>
47 #include <osg/TexMat>
48 #include <osg/Vec3d>
49 #include <osg/Viewport>
50
51 #include <osgUtil/IntersectionVisitor>
52
53 #include <osgViewer/GraphicsWindow>
54 #include <osgViewer/Renderer>
55
56 namespace flightgear
57 {
58 using namespace osg;
59
60 using std::strcmp;
61 using std::string;
62
63 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
64
65 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
66     _viewer(viewer)
67 {
68 }
69
70 }
71
72 namespace
73 {
74 using namespace osg;
75
76 // Given a projection matrix, return a new one with the same frustum
77 // sides and new near / far values.
78
79 void makeNewProjMat(Matrixd& oldProj, double znear,
80                                        double zfar, Matrixd& projection)
81 {
82     projection = oldProj;
83     // Slightly inflate the near & far planes to avoid objects at the
84     // extremes being clipped out.
85     znear *= 0.999;
86     zfar *= 1.001;
87
88     // Clamp the projection matrix z values to the range (near, far)
89     double epsilon = 1.0e-6;
90     if (fabs(projection(0,3)) < epsilon &&
91         fabs(projection(1,3)) < epsilon &&
92         fabs(projection(2,3)) < epsilon) {
93         // Projection is Orthographic
94         epsilon = -1.0/(zfar - znear); // Used as a temp variable
95         projection(2,2) = 2.0*epsilon;
96         projection(3,2) = (zfar + znear)*epsilon;
97     } else {
98         // Projection is Perspective
99         double trans_near = (-znear*projection(2,2) + projection(3,2)) /
100             (-znear*projection(2,3) + projection(3,3));
101         double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
102             (-zfar*projection(2,3) + projection(3,3));
103         double ratio = fabs(2.0/(trans_near - trans_far));
104         double center = -0.5*(trans_near + trans_far);
105
106         projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
107                                          0.0, 1.0, 0.0, 0.0,
108                                          0.0, 0.0, ratio, 0.0,
109                                          0.0, 0.0, center*ratio, 1.0));
110     }
111 }
112
113 void installCullVisitor(Camera* camera)
114 {
115     osgViewer::Renderer* renderer
116         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
117     for (int i = 0; i < 2; ++i) {
118         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
119         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
120     }
121 }
122 }
123
124 namespace flightgear
125 {
126 void updateCameras(const CameraInfo* info)
127 {
128     if (info->camera.valid())
129         info->camera->getViewport()->setViewport(info->x, info->y,
130                                                  info->width, info->height);
131     if (info->farCamera.valid())
132         info->farCamera->getViewport()->setViewport(info->x, info->y,
133                                                     info->width, info->height);
134 }
135
136 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
137                                    const Matrix& view,
138                                    const Matrix& projection,
139                                    bool useMasterSceneData)
140 {
141     CameraInfo* info = new CameraInfo(flags);
142     // The camera group will always update the camera
143     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
144
145     Camera* farCamera = 0;
146     if ((flags & (GUI | ORTHO)) == 0) {
147         farCamera = new Camera;
148         farCamera->setAllowEventFocus(camera->getAllowEventFocus());
149         farCamera->setGraphicsContext(camera->getGraphicsContext());
150         farCamera->setCullingMode(camera->getCullingMode());
151         farCamera->setInheritanceMask(camera->getInheritanceMask());
152         farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
153         // Each camera's viewport is written when the window is
154         // resized; if the the viewport isn't copied here, it gets updated
155         // twice and ends up with the wrong value.
156         farCamera->setViewport(simgear::clone(camera->getViewport()));
157         farCamera->setDrawBuffer(camera->getDrawBuffer());
158         farCamera->setReadBuffer(camera->getReadBuffer());
159         farCamera->setRenderTargetImplementation(
160             camera->getRenderTargetImplementation());
161         const Camera::BufferAttachmentMap& bufferMap
162             = camera->getBufferAttachmentMap();
163         if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
164             farCamera->attach(
165                 Camera::COLOR_BUFFER,
166                 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
167         }
168         _viewer->addSlave(farCamera, projection, view, useMasterSceneData);
169         installCullVisitor(farCamera);
170         info->farCamera = farCamera;
171         info->farSlaveIndex = _viewer->getNumSlaves() - 1;
172         farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
173         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
174         camera->setClearMask(GL_DEPTH_BUFFER_BIT);
175     }
176     _viewer->addSlave(camera, projection, view, useMasterSceneData);
177     installCullVisitor(camera);
178     info->camera = camera;
179     info->slaveIndex = _viewer->getNumSlaves() - 1;
180     camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
181     _cameras.push_back(info);
182     return info;
183 }
184
185 void CameraGroup::update(const osg::Vec3d& position,
186                          const osg::Quat& orientation)
187 {
188     const Matrix masterView(osg::Matrix::translate(-position)
189                             * osg::Matrix::rotate(orientation.inverse()));
190     _viewer->getCamera()->setViewMatrix(masterView);
191     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
192     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
193         const CameraInfo* info = i->get();
194         const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
195 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
196         // refreshes camera viewports (for now)
197         updateCameras(info);
198 #endif
199         Camera* camera = info->camera.get();
200         Matrix viewMatrix;
201         if ((info->flags & VIEW_ABSOLUTE) != 0)
202             viewMatrix = slave._viewOffset;
203         else
204             viewMatrix = masterView * slave._viewOffset;
205         camera->setViewMatrix(viewMatrix);
206         Matrix projectionMatrix;
207         if ((info->flags & PROJECTION_ABSOLUTE) != 0)
208             projectionMatrix = slave._projectionOffset;
209         else
210             projectionMatrix = masterProj * slave._projectionOffset;
211
212         if (!info->farCamera.valid()) {
213             camera->setProjectionMatrix(projectionMatrix);
214         } else {
215             Camera* farCamera = info->farCamera.get();
216             farCamera->setViewMatrix(viewMatrix);
217             double left, right, bottom, top, parentNear, parentFar;
218             projectionMatrix.getFrustum(left, right, bottom, top,
219                                         parentNear, parentFar);
220             if (parentFar < _nearField || _nearField == 0.0f) {
221                 camera->setProjectionMatrix(projectionMatrix);
222                 camera->setCullMask(camera->getCullMask()
223                                     | simgear::BACKGROUND_BIT);
224                 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
225                 farCamera->setNodeMask(0);
226             } else {
227                 Matrix nearProj, farProj;
228                 makeNewProjMat(projectionMatrix, parentNear, _nearField,
229                                nearProj);
230                 makeNewProjMat(projectionMatrix, _nearField, parentFar,
231                                farProj);
232                 camera->setProjectionMatrix(nearProj);
233                 camera->setCullMask(camera->getCullMask()
234                                     & ~simgear::BACKGROUND_BIT);
235                 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
236                 farCamera->setProjectionMatrix(farProj);
237                 farCamera->setNodeMask(camera->getNodeMask());
238             }
239         }
240     }
241 }
242
243 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
244 {
245     if (vfov != 0.0f && aspectRatio != 0.0f)
246         _viewer->getCamera()
247             ->setProjectionMatrixAsPerspective(vfov,
248                                                1.0f / aspectRatio,
249                                                _zNear, _zFar);
250 }
251 }
252
253 namespace
254 {
255 // A raw value for property nodes that references a class member via
256 // an osg::ref_ptr.
257 template<class C, class T>
258 class RefMember : public SGRawValue<T>
259 {
260 public:
261     RefMember (C *obj, T C::*ptr)
262         : _obj(obj), _ptr(ptr) {}
263     virtual ~RefMember () {}
264     virtual T getValue () const
265     {
266         return _obj.get()->*_ptr;
267     }
268     virtual bool setValue (T value)
269     {
270         _obj.get()->*_ptr = value;
271         return true;
272     }
273     virtual SGRawValue<T> * clone () const
274     {
275         return new RefMember(_obj.get(), _ptr);
276     }
277 private:
278     ref_ptr<C> _obj;
279     T C::* const _ptr;
280 };
281
282 template<typename C, typename T>
283 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
284 {
285     return RefMember<C, T>(obj, ptr);
286 }
287
288 template<typename C, typename T>
289 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
290                       C* obj, T C::*ptr, T value)
291 {
292     SGPropertyNode* valNode = parent->getNode(childName);
293     RefMember<C, T> refMember = makeRefMember(obj, ptr);
294     if (!valNode) {
295         valNode = parent->getNode(childName, true);
296         valNode->tie(refMember, false);
297         setValue(valNode, value);
298     } else {
299         valNode->tie(refMember, true);
300     }
301 }
302
303 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
304                    const osg::GraphicsContext::Traits *traits)
305 {
306     using namespace flightgear;
307     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
308     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
309     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
310                      static_cast<double>(traits->width));
311     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
312                      static_cast<double>(traits->height));
313 }
314 }
315
316 namespace flightgear
317 {
318
319 // Mostly copied from osg's osgViewer/View.cpp
320
321 static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(
322     const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
323     double sphere_radius, double collar_radius,
324     Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
325 {
326     osg::Vec3d center(0.0,0.0,0.0);
327     osg::Vec3d eye(0.0,0.0,0.0);
328
329     double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
330     bool flip = false;
331     bool texcoord_flip = false;
332
333     osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
334
335 #if 0
336     OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
337     OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
338 #endif
339     // create the quad to visualize.
340     osg::Geometry* geometry = new osg::Geometry();
341
342     geometry->setSupportsDisplayList(false);
343
344     osg::Vec3 xAxis(widthVector);
345     float width = widthVector.length();
346     xAxis /= width;
347
348     osg::Vec3 yAxis(heightVector);
349     float height = heightVector.length();
350     yAxis /= height;
351
352     int noSteps = 160;
353
354     osg::Vec3Array* vertices = new osg::Vec3Array;
355     osg::Vec2Array* texcoords0 = new osg::Vec2Array;
356     osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
357     osg::Vec4Array* colors = new osg::Vec4Array;
358
359     osg::Vec3 bottom = origin;
360     osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
361     osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
362
363     osg::Vec3 top = origin + yAxis*height;
364
365     osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
366     float screenRadius = heightVector.length() * 0.5f;
367
368     geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
369
370     for(int i=0;i<noSteps;++i)
371     {
372         osg::Vec3 cursor = bottom+dy*(float)i;
373         for(int j=0;j<noSteps;++j)
374         {
375             osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
376             double theta = texcoord.x() * 2.0 * osg::PI;
377             double phi = (1.0-texcoord.y()) * osg::PI;
378
379             if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
380
381             osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
382             pos = pos*projectorMatrix;
383
384             double alpha = atan2(pos.x(), pos.y());
385             if (alpha<0.0) alpha += 2.0*osg::PI;
386
387             double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
388             if (beta<0.0) beta += 2.0*osg::PI;
389
390             double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
391             if (gamma<0.0) gamma += 2.0*osg::PI;
392
393
394             osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
395
396             if (flip)
397                 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
398             else
399                 vertices->push_back(v);
400
401             texcoords0->push_back( texcoord );
402
403             osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
404             if (intensityMap)
405             {
406                 colors->push_back(intensityMap->getColor(texcoord1));
407             }
408             else
409             {
410                 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
411                 if (texcoords1) texcoords1->push_back( texcoord1 );
412             }
413
414
415         }
416     }
417
418
419     // pass the created vertex array to the points geometry object.
420     geometry->setVertexArray(vertices);
421
422     geometry->setColorArray(colors);
423     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
424
425     geometry->setTexCoordArray(0,texcoords0);
426     if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
427
428     osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
429     geometry->addPrimitiveSet(elements);
430
431     for(int i=0;i<noSteps-1;++i)
432     {
433         for(int j=0;j<noSteps-1;++j)
434         {
435             int i1 = j+(i+1)*noSteps;
436             int i2 = j+(i)*noSteps;
437             int i3 = j+1+(i)*noSteps;
438             int i4 = j+1+(i+1)*noSteps;
439
440             osg::Vec3& v1 = (*vertices)[i1];
441             osg::Vec3& v2 = (*vertices)[i2];
442             osg::Vec3& v3 = (*vertices)[i3];
443             osg::Vec3& v4 = (*vertices)[i4];
444
445             if ((v1-screenCenter).length()>screenRadius) continue;
446             if ((v2-screenCenter).length()>screenRadius) continue;
447             if ((v3-screenCenter).length()>screenRadius) continue;
448             if ((v4-screenCenter).length()>screenRadius) continue;
449
450             elements->push_back(i1);
451             elements->push_back(i2);
452             elements->push_back(i3);
453
454             elements->push_back(i1);
455             elements->push_back(i3);
456             elements->push_back(i4);
457         }
458     }
459
460     return geometry;
461 }
462
463 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
464                                         Camera* camera)
465 {
466     const SGPropertyNode* texNode = psNode->getNode("texture");
467     if (!texNode) {
468         // error
469         return;
470     }
471     string texName = texNode->getStringValue();
472     TextureMap::iterator itr = _textureTargets.find(texName);
473     if (itr == _textureTargets.end()) {
474         // error
475         return;
476     }
477     Viewport* viewport = camera->getViewport();
478     float width = viewport->width();
479     float height = viewport->height();
480     TextureRectangle* texRect = itr->second.get();
481     double radius = psNode->getDoubleValue("radius", 1.0);
482     double collar = psNode->getDoubleValue("collar", 0.45);
483     Geode* geode = new Geode();
484     geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(
485                            Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
486                            Vec3(0.0f,height,0.0f), radius, collar));
487
488     // new we need to add the texture to the mesh, we do so by creating a
489     // StateSet to contain the Texture StateAttribute.
490     StateSet* stateset = geode->getOrCreateStateSet();
491     stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
492     stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
493
494     TexMat* texmat = new TexMat;
495     texmat->setScaleByTextureRectangleSize(true);
496     stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
497 #if 0
498     if (!applyIntensityMapAsColours && intensityMap)
499     {
500         stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
501     }
502 #endif
503     // add subgraph to render
504     camera->addChild(geode);
505     camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
506     camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
507     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
508     camera->setCullingMode(osg::CullSettings::NO_CULLING);
509     camera->setName("DistortionCorrectionCamera");
510 }
511
512 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
513 {
514     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
515     const SGPropertyNode* windowNode = cameraNode->getNode("window");
516     GraphicsWindow* window = 0;
517     int cameraFlags = DO_INTERSECTION_TEST;
518     if (windowNode) {
519         // New style window declaration / definition
520         window = wBuild->buildWindow(windowNode);
521     } else {
522         // Old style: suck window params out of camera block
523         window = wBuild->buildWindow(cameraNode);
524     }
525     if (!window) {
526         return 0;
527     }
528     Camera* camera = new Camera;
529     camera->setAllowEventFocus(false);
530     camera->setGraphicsContext(window->gc.get());
531     camera->setViewport(new Viewport);
532     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
533                            | CullSettings::VIEW_FRUSTUM_CULLING);
534     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
535                                & ~(CullSettings::CULL_MASK
536                                    | CullSettings::CULLING_MODE
537 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
538                                    | CullSettings::CLEAR_MASK
539 #endif
540                                    ));
541
542     osg::Matrix pOff;
543     osg::Matrix vOff;
544     const SGPropertyNode* viewNode = cameraNode->getNode("view");
545     if (viewNode) {
546         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
547         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
548         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
549         double x = viewNode->getDoubleValue("x", 0.0);
550         double y = viewNode->getDoubleValue("y", 0.0);
551         double z = viewNode->getDoubleValue("z", 0.0);
552         // Build a view matrix, which is the inverse of a model
553         // orientation matrix.
554         vOff = (Matrix::translate(-x, -y, -z)
555                 * Matrix::rotate(-DegreesToRadians(heading),
556                                  Vec3d(0.0, 1.0, 0.0),
557                                  -DegreesToRadians(pitch),
558                                  Vec3d(1.0, 0.0, 0.0),
559                                  -DegreesToRadians(roll),
560                                  Vec3d(0.0, 0.0, 1.0)));
561         if (viewNode->getBoolValue("absolute", false))
562             cameraFlags |= VIEW_ABSOLUTE;
563     } else {
564         // Old heading parameter, works in the opposite direction
565         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
566         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
567     }
568     const SGPropertyNode* projectionNode = 0;
569     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
570         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
571         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
572                                                             1.0);
573         double zNear = projectionNode->getDoubleValue("near", 0.0);
574         double zFar = projectionNode->getDoubleValue("far", 0.0);
575         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
576         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
577         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
578         double right = tan_fovy * aspectRatio * zNear + offsetX;
579         double left = -tan_fovy * aspectRatio * zNear + offsetX;
580         double top = tan_fovy * zNear + offsetY;
581         double bottom = -tan_fovy * zNear + offsetY;
582         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
583         cameraFlags |= PROJECTION_ABSOLUTE;
584     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
585                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
586         double top = projectionNode->getDoubleValue("top", 0.0);
587         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
588         double left = projectionNode->getDoubleValue("left", 0.0);
589         double right = projectionNode->getDoubleValue("right", 0.0);
590         double zNear = projectionNode->getDoubleValue("near", 0.0);
591         double zFar = projectionNode->getDoubleValue("far", 0.0);
592         if (cameraNode->getNode("frustum")) {
593             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
594             cameraFlags |= PROJECTION_ABSOLUTE;
595         } else {
596             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
597             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
598         }
599     } else {
600         // old style shear parameters
601         double shearx = cameraNode->getDoubleValue("shear-x", 0);
602         double sheary = cameraNode->getDoubleValue("shear-y", 0);
603         pOff.makeTranslate(-shearx, -sheary, 0);
604     }
605     const SGPropertyNode* textureNode = cameraNode->getNode("texture");
606     if (textureNode) {
607         string texName = textureNode->getStringValue("name");
608         int tex_width = textureNode->getIntValue("width");
609         int tex_height = textureNode->getIntValue("height");
610         TextureRectangle* texture = new TextureRectangle;
611
612         texture->setTextureSize(tex_width, tex_height);
613         texture->setInternalFormat(GL_RGB);
614         texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
615         texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
616         texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
617         texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
618         camera->setDrawBuffer(GL_FRONT);
619         camera->setReadBuffer(GL_FRONT);
620         camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
621         camera->attach(Camera::COLOR_BUFFER, texture);
622         _textureTargets[texName] = texture;
623     } else {
624         camera->setDrawBuffer(GL_BACK);
625         camera->setReadBuffer(GL_BACK);
626     }
627     const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
628     bool useMasterSceneGraph = !psNode;
629     CameraInfo* info = addCamera(cameraFlags, camera, vOff, pOff,
630                                  useMasterSceneGraph);
631     // If a viewport isn't set on the camera, then it's hard to dig it
632     // out of the SceneView objects in the viewer, and the coordinates
633     // of mouse events are somewhat bizzare.
634     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
635     buildViewport(info, viewportNode, window->gc->getTraits());
636     updateCameras(info);
637     // Distortion camera needs the viewport which is created by addCamera().
638     if (psNode) {
639         info->flags = info->flags | VIEW_ABSOLUTE;
640         buildDistortionCamera(psNode, camera);
641     }
642     return info;
643 }
644
645 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
646                                         GraphicsWindow* window)
647 {
648     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
649     const SGPropertyNode* windowNode = (cameraNode
650                                         ? cameraNode->getNode("window")
651                                         : 0);
652     if (!window && windowNode) {
653       // New style window declaration / definition
654       window = wBuild->buildWindow(windowNode);
655     }
656     
657     if (!window) { // buildWindow can fail
658       SG_LOG(SG_GENERAL, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
659       return NULL;
660     }
661     
662     Camera* camera = new Camera;
663     camera->setAllowEventFocus(false);
664     camera->setGraphicsContext(window->gc.get());
665     camera->setViewport(new Viewport);
666     // XXX Camera needs to be drawn last; eventually the render order
667     // should be assigned by a camera manager.
668     camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
669         camera->setClearMask(0);
670     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
671                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
672                                    | CullSettings::CULLING_MODE
673 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
674                                    | CullSettings::CLEAR_MASK
675 #endif
676                                    ));
677     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
678     camera->setCullingMode(osg::CullSettings::NO_CULLING);
679     camera->setProjectionResizePolicy(Camera::FIXED);
680     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
681     const int cameraFlags = GUI;
682     CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
683                                    Matrixd::identity(), false);
684     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
685     buildViewport(result, viewportNode, window->gc->getTraits());
686
687     // Disable statistics for the GUI camera.
688     result->camera->setStats(0);
689     updateCameras(result);
690     return result;
691 }
692
693 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
694                                            SGPropertyNode* gnode)
695 {
696     CameraGroup* cgroup = new CameraGroup(viewer);
697     for (int i = 0; i < gnode->nChildren(); ++i) {
698         SGPropertyNode* pNode = gnode->getChild(i);
699         const char* name = pNode->getName();
700         if (!strcmp(name, "camera")) {
701             cgroup->buildCamera(pNode);
702         } else if (!strcmp(name, "window")) {
703             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
704         } else if (!strcmp(name, "gui")) {
705             cgroup->buildGUICamera(pNode);
706         }
707     }
708     bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
709     bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
710     bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
711                      100.0f);
712     return cgroup;
713 }
714
715 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
716 {
717     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
718         CameraInfo* info = i->get();
719         if (info->flags & GUI)
720             continue;
721         if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
722             info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
723             info->camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
724             info->camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
725             info->farCamera->setCullMask(nm);
726             info->farCamera->setCullMaskLeft(nm);
727             info->farCamera->setCullMaskRight(nm);
728         } else {
729             info->camera->setCullMask(nm);
730             info->camera->setCullMaskLeft(nm);
731             info->camera->setCullMaskRight(nm);
732         }
733     }
734 }
735
736 void CameraGroup::resized()
737 {
738     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
739         CameraInfo *info = i->get();
740         const Viewport* viewport = info->camera->getViewport();
741         info->x = viewport->x();
742         info->y = viewport->y();
743         info->width = viewport->width();
744         info->height = viewport->height();
745     }
746 }
747
748 Camera* getGUICamera(CameraGroup* cgroup)
749 {
750     CameraGroup::CameraIterator end = cgroup->camerasEnd();
751     CameraGroup::CameraIterator result
752         = std::find_if(cgroup->camerasBegin(), end,
753                        FlagTester<CameraInfo>(CameraGroup::GUI));
754     if (result != end)
755         return (*result)->camera.get();
756     else
757         return 0;
758 }
759
760 bool computeIntersections(const CameraGroup* cgroup,
761                           const osgGA::GUIEventAdapter* ea,
762                           osgUtil::LineSegmentIntersector::Intersections& intersections)
763 {
764     using osgUtil::Intersector;
765     using osgUtil::LineSegmentIntersector;
766     double x, y;
767     eventToWindowCoords(ea, x, y);
768     // Find camera that contains event
769     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
770              e = cgroup->camerasEnd();
771          iter != e;
772          ++iter) {
773         const CameraInfo* cinfo = iter->get();
774         if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
775             continue;
776         const Camera* camera = cinfo->camera.get();
777         if (camera->getGraphicsContext() != ea->getGraphicsContext())
778             continue;
779         const Viewport* viewport = camera->getViewport();
780         double epsilon = 0.5;
781         if (!(x >= viewport->x() - epsilon
782               && x < viewport->x() + viewport->width() -1.0 + epsilon
783               && y >= viewport->y() - epsilon
784               && y < viewport->y() + viewport->height() -1.0 + epsilon))
785             continue;
786         Vec4d start(x, y, 0.0, 1.0);
787         Vec4d end(x, y, 1.0, 1.0);
788         Matrix windowMat = viewport->computeWindowMatrix();
789         Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
790                                             * windowMat);
791         Matrix endPtMat;
792         if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
793             endPtMat = startPtMat;
794         else
795             endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
796                                        * windowMat);
797         start = start * startPtMat;
798         start /= start.w();
799         end = end * endPtMat;
800         end /= end.w();
801         ref_ptr<LineSegmentIntersector> picker
802             = new LineSegmentIntersector(Intersector::VIEW,
803                                          Vec3d(start.x(), start.y(), start.z()),
804                                          Vec3d(end.x(), end.y(), end.z()));
805         osgUtil::IntersectionVisitor iv(picker.get());
806         const_cast<Camera*>(camera)->accept(iv);
807         if (picker->containsIntersections()) {
808             intersections = picker->getIntersections();
809             return true;
810         } else {
811             break;
812         }
813     }
814     intersections.clear();
815     return false;
816 }
817
818 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
819 {
820     using osgViewer::GraphicsWindow;
821     Camera* guiCamera = getGUICamera(cgroup);
822     if (!guiCamera)
823         return;
824     Viewport* vport = guiCamera->getViewport();
825     GraphicsWindow* gw
826         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
827     if (!gw)
828         return;
829     globals->get_renderer()->getEventHandler()->setMouseWarped();    
830     // Translate the warp request into the viewport of the GUI camera,
831     // send the request to the window, then transform the coordinates
832     // for the Viewer's event queue.
833     double wx = x + vport->x();
834     double wyUp = vport->height() + vport->y() - y;
835     double wy;
836     const GraphicsContext::Traits* traits = gw->getTraits();
837     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
838         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
839         wy = traits->height - wyUp;
840     } else {
841         wy = wyUp;
842     }
843     gw->getEventQueue()->mouseWarped(wx, wy);
844     gw->requestWarpPointer(wx, wy);
845     osgGA::GUIEventAdapter* eventState
846         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
847     double viewerX
848         = (eventState->getXmin()
849            + ((wx / double(traits->width))
850               * (eventState->getXmax() - eventState->getXmin())));
851     double viewerY
852         = (eventState->getYmin()
853            + ((wyUp / double(traits->height))
854               * (eventState->getYmax() - eventState->getYmin())));
855     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
856 }
857 }