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