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