1 // Copyright (C) 2008 Tim Moore
2 // Copyright (C) 2011 Mathias Froehlich
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 #include "CameraGroup.hxx"
19
20 #include <Main/fg_props.hxx>
21 #include <Main/globals.hxx>
22 #include "renderer.hxx"
23 #include "FGEventHandler.hxx"
24 #include "WindowBuilder.hxx"
25 #include "WindowSystemAdapter.hxx"
26
27 #include <simgear/math/SGRect.hxx>
28 #include <simgear/props/props.hxx>
29 #include <simgear/props/props_io.hxx> // for copyProperties
30 #include <simgear/structure/exception.hxx>
31 #include <simgear/structure/OSGUtils.hxx>
32 #include <simgear/structure/OSGVersion.hxx>
33 #include <simgear/scene/material/EffectCullVisitor.hxx>
34 #include <simgear/scene/util/RenderConstants.hxx>
35 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
36 #include <simgear/scene/viewer/Compositor.hxx>
37
38 #include <algorithm>
39 #include <cstring>
40 #include <string>
41
42 #include <osg/Camera>
43 #include <osg/Geometry>
44 #include <osg/GraphicsContext>
45 #include <osg/io_utils>
46 #include <osg/Math>
47 #include <osg/Matrix>
48 #include <osg/Notify>
49 #include <osg/Program>
50 #include <osg/Quat>
51 #include <osg/TexMat>
52 #include <osg/Vec3d>
53 #include <osg/Viewport>
54
55 #include <osgUtil/IntersectionVisitor>
56
57 #include <osgViewer/Viewer>
58 #include <osgViewer/GraphicsWindow>
59 #include <osgViewer/Renderer>
60
61 using namespace osg;
62
63 namespace {
64
65 osg::Matrix
invert(const osg::Matrix & matrix)66 invert(const osg::Matrix& matrix)
67 {
68 return osg::Matrix::inverse(matrix);
69 }
70
71 /// Returns the zoom factor of the master camera.
72 /// The reference fov is the historic 55 deg
73 double
zoomFactor()74 zoomFactor()
75 {
76 double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
77 if (fov < 1)
78 fov = 1;
79 return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
80 }
81
82 osg::Vec2d
preMult(const osg::Vec2d & v,const osg::Matrix & m)83 preMult(const osg::Vec2d& v, const osg::Matrix& m)
84 {
85 osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
86 return osg::Vec2d(tmp[0], tmp[1]);
87 }
88
89 osg::Matrix
relativeProjection(const osg::Matrix & P0,const osg::Matrix & R,const osg::Vec2d ref[2],const osg::Matrix & pP,const osg::Matrix & pR,const osg::Vec2d pRef[2])90 relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
91 const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
92 {
93 // Track the way from one projection space to the other:
94 // We want
95 // P = T*S*P0
96 // where P0 is the projection template sensible for the given window size,
97 // T is a translation matrix and S a scale matrix.
98 // We need to determine T and S so that the reference points in the parents
99 // projection space match the two reference points in this cameras projection space.
100
101 // Starting from the parents camera projection space, we get into this cameras
102 // projection space by the transform matrix:
103 // P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
104 // So, at first compute that matrix without T*S and determine S and T from that
105
106 // Ok, now osg uses the inverse matrix multiplication order, thus:
107 osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
108 // Compute the parents reference points in the current projection space
109 // without the yet unknown T and S
110 osg::Vec2d pRefInThis[2] = {
111 preMult(pRef[0], PtoPwithoutTS),
112 preMult(pRef[1], PtoPwithoutTS)
113 };
114
115 // To get the same zoom, rescale to match the parents size
116 double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
117 osg::Matrix S = osg::Matrix::scale(s, s, 1);
118
119 // For the translation offset, incorporate the now known scale
120 // and recompute the position ot the first reference point in the
121 // currents projection space without the yet unknown T.
122 pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
123 // The translation is then the difference of the reference points
124 osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));
125
126 // Compose and return the desired final projection matrix
127 return P0*S*T;
128 }
129
130 } // anonymous namespace
131
132 namespace flightgear
133 {
134 using namespace simgear;
135 using namespace compositor;
136
137 class CameraGroupListener : public SGPropertyChangeListener {
138 public:
CameraGroupListener(CameraGroup * cg,SGPropertyNode * gnode)139 CameraGroupListener(CameraGroup* cg, SGPropertyNode* gnode) :
140 _groupNode(gnode),
141 _cameraGroup(cg) {
142 listenToNode("znear", 0.1f);
143 listenToNode("zfar", 120000.0f);
144 listenToNode("near-field", 100.0f);
145 }
146
~CameraGroupListener()147 virtual ~CameraGroupListener() {
148 unlisten("znear");
149 unlisten("zfar");
150 unlisten("near-field");
151 }
152
valueChanged(SGPropertyNode * prop)153 virtual void valueChanged(SGPropertyNode* prop) {
154 if (!strcmp(prop->getName(), "znear")) {
155 _cameraGroup->_zNear = prop->getFloatValue();
156 } else if (!strcmp(prop->getName(), "zfar")) {
157 _cameraGroup->_zFar = prop->getFloatValue();
158 } else if (!strcmp(prop->getName(), "near-field")) {
159 _cameraGroup->_nearField = prop->getFloatValue();
160 }
161 }
162 private:
listenToNode(const std::string & name,double val)163 void listenToNode(const std::string& name, double val) {
164 SGPropertyNode* n = _groupNode->getChild(name);
165 if (!n) {
166 n = _groupNode->getChild(name, 0 /* index */, true);
167 n->setDoubleValue(val);
168 }
169 n->addChangeListener(this);
170 valueChanged(n); // propogate initial state through
171 }
172
unlisten(const std::string & name)173 void unlisten(const std::string& name) {
174 _groupNode->getChild(name)->removeChangeListener(this);
175 }
176
177 SGPropertyNode_ptr _groupNode;
178 CameraGroup* _cameraGroup; // non-owning reference
179 };
180
181 struct GUIUpdateCallback : public Pass::PassUpdateCallback {
updatePassflightgear::GUIUpdateCallback182 virtual void updatePass(Pass &pass,
183 const osg::Matrix &view_matrix,
184 const osg::Matrix &proj_matrix) {
185 // Just set both the view matrix and the projection matrix
186 pass.camera->setViewMatrix(view_matrix);
187 pass.camera->setProjectionMatrix(proj_matrix);
188 }
189 };
190
191 typedef std::vector<SGPropertyNode_ptr> SGPropertyNodeVec;
192
193 osg::ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
194
CameraGroup(osgViewer::Viewer * viewer)195 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
196 _viewer(viewer)
197 {
198 }
199
~CameraGroup()200 CameraGroup::~CameraGroup()
201 {
202
203 }
204
update(const osg::Vec3d & position,const osg::Quat & orientation)205 void CameraGroup::update(const osg::Vec3d& position,
206 const osg::Quat& orientation)
207 {
208 const osg::Matrix masterView(osg::Matrix::translate(-position)
209 * osg::Matrix::rotate(orientation.inverse()));
210 _viewer->getCamera()->setViewMatrix(masterView);
211 const osg::Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
212 double masterZoomFactor = zoomFactor();
213
214 for (const auto &info : _cameras) {
215 osg::Matrix view_matrix;
216 if (info->flags & CameraInfo::GUI)
217 view_matrix = osg::Matrix::identity();
218 else if ((info->flags & CameraInfo::VIEW_ABSOLUTE) != 0)
219 view_matrix = info->viewOffset;
220 else
221 view_matrix = masterView * info->viewOffset;
222
223 osg::Matrix proj_matrix;
224 if (info->flags & CameraInfo::GUI) {
225 const osg::GraphicsContext::Traits *traits =
226 info->compositor->getGraphicsContext()->getTraits();
227 proj_matrix = osg::Matrix::ortho2D(0, traits->width, 0, traits->height);
228 } else if ((info->flags & CameraInfo::PROJECTION_ABSOLUTE) != 0) {
229 if (info->flags & CameraInfo::ENABLE_MASTER_ZOOM) {
230 if (info->relativeCameraParent) {
231 // template projection and view matrices of the current camera
232 osg::Matrix P0 = info->projOffset;
233 osg::Matrix R = view_matrix;
234
235 // The already known projection and view matrix of the parent camera
236 osg::Matrix pP = info->relativeCameraParent->viewMatrix;
237 osg::Matrix pR = info->relativeCameraParent->projMatrix;
238
239 // And the projection matrix derived from P0 so that the
240 // reference points match
241 proj_matrix = relativeProjection(P0, R, info->thisReference,
242 pP, pR, info->parentReference);
243 } else {
244 // We want to zoom, so take the original matrix and apply the
245 // zoom to it
246 proj_matrix = info->projOffset;
247 proj_matrix.postMultScale(osg::Vec3d(masterZoomFactor,
248 masterZoomFactor,
249 1));
250 }
251 } else {
252 proj_matrix = info->projOffset;
253 }
254 } else {
255 proj_matrix = masterProj * info->projOffset;
256 }
257
258 info->viewMatrix = view_matrix;
259 info->projMatrix = proj_matrix;
260 info->compositor->update(view_matrix, proj_matrix);
261 }
262 }
263
setCameraParameters(float vfov,float aspectRatio)264 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
265 {
266 if (vfov != 0.0f && aspectRatio != 0.0f)
267 _viewer->getCamera()
268 ->setProjectionMatrixAsPerspective(vfov,
269 1.0f / aspectRatio,
270 _zNear, _zFar);
271 }
272
getMasterAspectRatio() const273 double CameraGroup::getMasterAspectRatio() const
274 {
275 if (_cameras.empty())
276 return 0.0;
277
278 // The master camera is the first one added
279 const CameraInfo *info = _cameras.front();
280 if (!info)
281 return 0.0;
282 const osg::GraphicsContext::Traits *traits =
283 info->compositor->getGraphicsContext()->getTraits();
284
285 return static_cast<double>(traits->height) / traits->width;
286 }
287
288 // FIXME: Port this to the Compositor
289 #if 0
290 // Mostly copied from osg's osgViewer/View.cpp
291
292 static osg::Geometry* createPanoramicSphericalDisplayDistortionMesh(
293 const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
294 double sphere_radius, double collar_radius,
295 Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
296 {
297 osg::Vec3d center(0.0,0.0,0.0);
298 osg::Vec3d eye(0.0,0.0,0.0);
299
300 double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
301 bool flip = false;
302 bool texcoord_flip = false;
303
304 // create the quad to visualize.
305 osg::Geometry* geometry = new osg::Geometry();
306
307 geometry->setSupportsDisplayList(false);
308
309 osg::Vec3 xAxis(widthVector);
310 float width = widthVector.length();
311 xAxis /= width;
312
313 osg::Vec3 yAxis(heightVector);
314 float height = heightVector.length();
315 yAxis /= height;
316
317 int noSteps = 160;
318
319 osg::Vec3Array* vertices = new osg::Vec3Array;
320 osg::Vec2Array* texcoords0 = new osg::Vec2Array;
321 osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
322 osg::Vec4Array* colors = new osg::Vec4Array;
323
324 osg::Vec3 top = origin + yAxis*height;
325
326 osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
327 float screenRadius = heightVector.length() * 0.5f;
328
329 geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
330
331 for(int i=0;i<noSteps;++i)
332 {
333 //osg::Vec3 cursor = bottom+dy*(float)i;
334 for(int j=0;j<noSteps;++j)
335 {
336 osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
337 double theta = texcoord.x() * 2.0 * osg::PI;
338 double phi = (1.0-texcoord.y()) * osg::PI;
339
340 if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
341
342 osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
343 pos = pos*projectorMatrix;
344
345 double alpha = atan2(pos.x(), pos.y());
346 if (alpha<0.0) alpha += 2.0*osg::PI;
347
348 double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
349 if (beta<0.0) beta += 2.0*osg::PI;
350
351 double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
352 if (gamma<0.0) gamma += 2.0*osg::PI;
353
354
355 osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
356
357 if (flip)
358 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
359 else
360 vertices->push_back(v);
361
362 texcoords0->push_back( texcoord );
363
364 osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
365 if (intensityMap)
366 {
367 colors->push_back(intensityMap->getColor(texcoord1));
368 }
369 else
370 {
371 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
372 if (texcoords1) texcoords1->push_back( texcoord1 );
373 }
374
375
376 }
377 }
378
379 // pass the created vertex array to the points geometry object.
380 geometry->setVertexArray(vertices);
381
382 geometry->setColorArray(colors);
383 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
384
385 geometry->setTexCoordArray(0,texcoords0);
386 if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
387
388 osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
389 geometry->addPrimitiveSet(elements);
390
391 for(int i=0;i<noSteps-1;++i)
392 {
393 for(int j=0;j<noSteps-1;++j)
394 {
395 int i1 = j+(i+1)*noSteps;
396 int i2 = j+(i)*noSteps;
397 int i3 = j+1+(i)*noSteps;
398 int i4 = j+1+(i+1)*noSteps;
399
400 osg::Vec3& v1 = (*vertices)[i1];
401 osg::Vec3& v2 = (*vertices)[i2];
402 osg::Vec3& v3 = (*vertices)[i3];
403 osg::Vec3& v4 = (*vertices)[i4];
404
405 if ((v1-screenCenter).length()>screenRadius) continue;
406 if ((v2-screenCenter).length()>screenRadius) continue;
407 if ((v3-screenCenter).length()>screenRadius) continue;
408 if ((v4-screenCenter).length()>screenRadius) continue;
409
410 elements->push_back(i1);
411 elements->push_back(i2);
412 elements->push_back(i3);
413
414 elements->push_back(i1);
415 elements->push_back(i3);
416 elements->push_back(i4);
417 }
418 }
419
420 return geometry;
421 }
422
423 #endif
424
buildDistortionCamera(const SGPropertyNode * psNode,Camera * camera)425 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
426 Camera* camera)
427 {
428 // FIXME: Port this to the Compositor
429 #if 0
430 const SGPropertyNode* texNode = psNode->getNode("texture");
431 if (!texNode) {
432 // error
433 return;
434 }
435 string texName = texNode->getStringValue();
436 TextureMap::iterator itr = _textureTargets.find(texName);
437 if (itr == _textureTargets.end()) {
438 // error
439 return;
440 }
441 Viewport* viewport = camera->getViewport();
442 float width = viewport->width();
443 float height = viewport->height();
444 TextureRectangle* texRect = itr->second.get();
445 double radius = psNode->getDoubleValue("radius", 1.0);
446 double collar = psNode->getDoubleValue("collar", 0.45);
447 Geode* geode = new Geode();
448 geode->addDrawable(createPanoramicSphericalDisplayDistortionMesh(
449 Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
450 Vec3(0.0f,height,0.0f), radius, collar));
451
452 // new we need to add the texture to the mesh, we do so by creating a
453 // StateSet to contain the Texture StateAttribute.
454 StateSet* stateset = geode->getOrCreateStateSet();
455 stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
456 stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
457
458 TexMat* texmat = new TexMat;
459 texmat->setScaleByTextureRectangleSize(true);
460 stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
461 #if 0
462 if (!applyIntensityMapAsColours && intensityMap)
463 {
464 stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
465 }
466 #endif
467 // add subgraph to render
468 camera->addChild(geode);
469 camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
470 camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
471 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
472 camera->setCullingMode(osg::CullSettings::NO_CULLING);
473 camera->setName("DistortionCorrectionCamera");
474 #endif
475 }
476
buildCamera(SGPropertyNode * cameraNode)477 void CameraGroup::buildCamera(SGPropertyNode* cameraNode)
478 {
479 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
480 const SGPropertyNode* windowNode = cameraNode->getNode("window");
481 GraphicsWindow* window = 0;
482 int cameraFlags = CameraInfo::DO_INTERSECTION_TEST;
483 if (windowNode) {
484 // New style window declaration / definition
485 window = wBuild->buildWindow(windowNode);
486 } else {
487 // Old style: suck window params out of camera block
488 window = wBuild->buildWindow(cameraNode);
489 }
490 if (!window) {
491 return;
492 }
493
494 osg::Matrix vOff;
495 const SGPropertyNode* viewNode = cameraNode->getNode("view");
496 if (viewNode) {
497 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
498 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
499 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
500 double x = viewNode->getDoubleValue("x", 0.0);
501 double y = viewNode->getDoubleValue("y", 0.0);
502 double z = viewNode->getDoubleValue("z", 0.0);
503 // Build a view matrix, which is the inverse of a model
504 // orientation matrix.
505 vOff = (Matrix::translate(-x, -y, -z)
506 * Matrix::rotate(-DegreesToRadians(heading),
507 Vec3d(0.0, 1.0, 0.0),
508 -DegreesToRadians(pitch),
509 Vec3d(1.0, 0.0, 0.0),
510 -DegreesToRadians(roll),
511 Vec3d(0.0, 0.0, 1.0)));
512 if (viewNode->getBoolValue("absolute", false))
513 cameraFlags |= CameraInfo::VIEW_ABSOLUTE;
514 } else {
515 // Old heading parameter, works in the opposite direction
516 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
517 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
518 }
519 // Configuring the physical dimensions of a monitor
520 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
521 double physicalWidth = viewportNode->getDoubleValue("width", 1024);
522 double physicalHeight = viewportNode->getDoubleValue("height", 768);
523 double bezelHeightTop = 0;
524 double bezelHeightBottom = 0;
525 double bezelWidthLeft = 0;
526 double bezelWidthRight = 0;
527 const SGPropertyNode* physicalDimensionsNode = 0;
528 if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
529 physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
530 physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
531 const SGPropertyNode* bezelNode = 0;
532 if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
533 bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
534 bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
535 bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
536 bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
537 }
538 }
539 osg::Matrix pOff;
540 unsigned parentCameraIndex = ~0u;
541 osg::Vec2d parentReference[2];
542 osg::Vec2d thisReference[2];
543 SGPropertyNode* projectionNode = 0;
544 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
545 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
546 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
547 1.0);
548 double zNear = projectionNode->getDoubleValue("near", 0.0);
549 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
550 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
551 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
552 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
553 double right = tan_fovy * aspectRatio * zNear + offsetX;
554 double left = -tan_fovy * aspectRatio * zNear + offsetX;
555 double top = tan_fovy * zNear + offsetY;
556 double bottom = -tan_fovy * zNear + offsetY;
557 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
558 cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE;
559 if (projectionNode->getBoolValue("fixed-near-far", true))
560 cameraFlags |= CameraInfo::FIXED_NEAR_FAR;
561 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
562 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
563 double top = projectionNode->getDoubleValue("top", 0.0);
564 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
565 double left = projectionNode->getDoubleValue("left", 0.0);
566 double right = projectionNode->getDoubleValue("right", 0.0);
567 double zNear = projectionNode->getDoubleValue("near", 0.0);
568 double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
569 if (cameraNode->getNode("frustum")) {
570 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
571 cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE;
572 } else {
573 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
574 cameraFlags |= (CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ORTHO);
575 }
576 if (projectionNode->getBoolValue("fixed-near-far", true))
577 cameraFlags |= CameraInfo::FIXED_NEAR_FAR;
578 } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
579 double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
580 double xoff = projectionNode->getDoubleValue("x-offset", 0);
581 double yoff = projectionNode->getDoubleValue("y-offset", 0);
582 double left = -0.5*physicalWidth - xoff;
583 double right = 0.5*physicalWidth - xoff;
584 double bottom = -0.5*physicalHeight - yoff;
585 double top = 0.5*physicalHeight - yoff;
586 pOff.makeFrustum(left, right, bottom, top, zNear, zNear*1000);
587 cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ENABLE_MASTER_ZOOM;
588 } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
589 || (projectionNode = cameraNode->getNode("left-of-perspective"))
590 || (projectionNode = cameraNode->getNode("above-perspective"))
591 || (projectionNode = cameraNode->getNode("below-perspective"))
592 || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
593 std::string name = projectionNode->getStringValue("parent-camera");
594 for (unsigned i = 0; i < _cameras.size(); ++i) {
595 if (_cameras[i]->name != name)
596 continue;
597 parentCameraIndex = i;
598 }
599 if (_cameras.size() <= parentCameraIndex) {
600 SG_LOG(SG_VIEW, SG_ALERT, "CameraGroup::buildCamera: "
601 "failed to find parent camera for relative camera!");
602 return;
603 }
604 const CameraInfo* parentInfo = _cameras[parentCameraIndex];
605 if (projectionNode->getNameString() == "right-of-perspective") {
606 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
607 parentReference[0] = osg::Vec2d(tmp, -1);
608 parentReference[1] = osg::Vec2d(tmp, 1);
609 tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
610 thisReference[0] = osg::Vec2d(-tmp, -1);
611 thisReference[1] = osg::Vec2d(-tmp, 1);
612 } else if (projectionNode->getNameString() == "left-of-perspective") {
613 double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
614 parentReference[0] = osg::Vec2d(-tmp, -1);
615 parentReference[1] = osg::Vec2d(-tmp, 1);
616 tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
617 thisReference[0] = osg::Vec2d(tmp, -1);
618 thisReference[1] = osg::Vec2d(tmp, 1);
619 } else if (projectionNode->getNameString() == "above-perspective") {
620 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
621 parentReference[0] = osg::Vec2d(-1, tmp);
622 parentReference[1] = osg::Vec2d(1, tmp);
623 tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
624 thisReference[0] = osg::Vec2d(-1, -tmp);
625 thisReference[1] = osg::Vec2d(1, -tmp);
626 } else if (projectionNode->getNameString() == "below-perspective") {
627 double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
628 parentReference[0] = osg::Vec2d(-1, -tmp);
629 parentReference[1] = osg::Vec2d(1, -tmp);
630 tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
631 thisReference[0] = osg::Vec2d(-1, tmp);
632 thisReference[1] = osg::Vec2d(1, tmp);
633 } else if (projectionNode->getNameString() == "reference-points-perspective") {
634 SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
635 SGPropertyNode* thisNode = projectionNode->getNode("this", true);
636 SGPropertyNode* pointNode;
637
638 pointNode = parentNode->getNode("point", 0, true);
639 parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
640 parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
641 pointNode = parentNode->getNode("point", 1, true);
642 parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
643 parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
644
645 pointNode = thisNode->getNode("point", 0, true);
646 thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
647 thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
648 pointNode = thisNode->getNode("point", 1, true);
649 thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
650 thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
651 }
652
653 pOff = osg::Matrix::perspective(45, physicalWidth/physicalHeight, 1, 20000);
654 cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ENABLE_MASTER_ZOOM;
655 } else {
656 // old style shear parameters
657 double shearx = cameraNode->getDoubleValue("shear-x", 0);
658 double sheary = cameraNode->getDoubleValue("shear-y", 0);
659 pOff.makeTranslate(-shearx, -sheary, 0);
660 }
661 const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
662 //bool useMasterSceneGraph = !psNode;
663
664 CameraInfo *info = new CameraInfo(cameraFlags);
665 _cameras.push_back(info);
666 info->name = cameraNode->getStringValue("name");
667 info->physicalWidth = physicalWidth;
668 info->physicalHeight = physicalHeight;
669 info->bezelHeightTop = bezelHeightTop;
670 info->bezelHeightBottom = bezelHeightBottom;
671 info->bezelWidthLeft = bezelWidthLeft;
672 info->bezelWidthRight = bezelWidthRight;
673 if (parentCameraIndex < _cameras.size())
674 info->relativeCameraParent = _cameras[parentCameraIndex];
675 info->parentReference[0] = parentReference[0];
676 info->parentReference[1] = parentReference[1];
677 info->thisReference[0] = thisReference[0];
678 info->thisReference[1] = thisReference[1];
679 info->viewOffset = vOff;
680 info->projOffset = pOff;
681
682 osg::Viewport *viewport = new osg::Viewport(
683 viewportNode->getDoubleValue("x"),
684 viewportNode->getDoubleValue("y"),
685 // If no width or height has been specified, fill the entire window
686 viewportNode->getDoubleValue("width", window->gc->getTraits()->width),
687 viewportNode->getDoubleValue("height",window->gc->getTraits()->height));
688 std::string default_compositor =
689 fgGetString("/sim/rendering/default-compositor", "Compositor/default");
690 std::string compositor_path =
691 cameraNode->getStringValue("compositor", default_compositor.c_str());
692 osg::ref_ptr<SGReaderWriterOptions> options =
693 SGReaderWriterOptions::fromPath(globals->get_fg_root());
694 options->setPropertyNode(globals->get_props());
695 Compositor *compositor = Compositor::create(_viewer,
696 window->gc,
697 viewport,
698 compositor_path,
699 options);
700 if (compositor) {
701 info->compositor = compositor;
702 } else {
703 throw sg_exception(std::string("Failed to create Compositor in path '") +
704 compositor_path + "'");
705 }
706
707 // Distortion camera needs the viewport which is created by addCamera().
708 if (psNode) {
709 info->flags = info->flags | CameraInfo::VIEW_ABSOLUTE;
710 //buildDistortionCamera(psNode, camera);
711 }
712 }
713
buildGUICamera(SGPropertyNode * cameraNode,GraphicsWindow * window)714 void CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
715 GraphicsWindow* window)
716 {
717 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
718 const SGPropertyNode* windowNode = (cameraNode
719 ? cameraNode->getNode("window")
720 : 0);
721 if (!window && windowNode) {
722 // New style window declaration / definition
723 window = wBuild->buildWindow(windowNode);
724 }
725
726 if (!window) { // buildWindow can fail
727 SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
728 return;
729 }
730
731 Camera* camera = new Camera;
732 camera->setName( "GUICamera" );
733 camera->setAllowEventFocus(false);
734 camera->setGraphicsContext(window->gc.get());
735 // If a viewport isn't set on the camera, then it's hard to dig it
736 // out of the SceneView objects in the viewer, and the coordinates
737 // of mouse events are somewhat bizzare.
738 osg::Viewport *viewport = new osg::Viewport(
739 0, 0, window->gc->getTraits()->width, window->gc->getTraits()->height);
740 camera->setViewport(viewport);
741 camera->setClearMask(0);
742 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
743 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
744 | CullSettings::CULLING_MODE
745 | CullSettings::CLEAR_MASK
746 ));
747 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
748 camera->setCullingMode(osg::CullSettings::NO_CULLING);
749 camera->setProjectionResizePolicy(osg::Camera::FIXED);
750
751 // The camera group will always update the camera
752 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
753
754 // Draw all nodes in the order they are added to the GUI camera
755 camera->getOrCreateStateSet()
756 ->setRenderBinDetails( 0,
757 "PreOrderBin",
758 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
759
760 // XXX Camera needs to be drawn last; eventually the render order
761 // should be assigned by a camera manager.
762 camera->setRenderOrder(osg::Camera::POST_RENDER, 10000);
763
764 Pass *pass = new Pass;
765 pass->camera = camera;
766 pass->useMastersSceneData = false;
767 pass->update_callback = new GUIUpdateCallback;
768
769 // For now we just build a simple Compositor directly from C++ space that
770 // encapsulates a single osg::Camera. This could be improved by letting
771 // users change the Compositor config in XML space, for example to be able
772 // to add post-processing to a HUD.
773 // However, since many other parts of FG require direct access to the GUI
774 // osg::Camera object, this is fine for now.
775 Compositor *compositor = new Compositor(_viewer, window->gc, viewport);
776 compositor->addPass(pass);
777
778 const int cameraFlags = CameraInfo::GUI | CameraInfo::DO_INTERSECTION_TEST;
779 CameraInfo* info = new CameraInfo(cameraFlags);
780 info->name = "GUI camera";
781 info->viewOffset = osg::Matrix::identity();
782 info->projOffset = osg::Matrix::identity();
783 info->compositor = compositor;
784 _cameras.push_back(info);
785
786 // Disable statistics for the GUI camera.
787 camera->setStats(0);
788 }
789
buildCameraGroup(osgViewer::Viewer * viewer,SGPropertyNode * gnode)790 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
791 SGPropertyNode* gnode)
792 {
793 CameraGroup* cgroup = new CameraGroup(viewer);
794 cgroup->_listener.reset(new CameraGroupListener(cgroup, gnode));
795
796 for (int i = 0; i < gnode->nChildren(); ++i) {
797 SGPropertyNode* pNode = gnode->getChild(i);
798 const char* name = pNode->getName();
799 if (!strcmp(name, "camera")) {
800 cgroup->buildCamera(pNode);
801 } else if (!strcmp(name, "window")) {
802 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
803 } else if (!strcmp(name, "gui")) {
804 cgroup->buildGUICamera(pNode);
805 }
806 }
807
808 return cgroup;
809 }
810
resized()811 void CameraGroup::resized()
812 {
813 for (const auto &info : _cameras)
814 info->compositor->resized();
815 }
816
getGUICamera() const817 CameraInfo* CameraGroup::getGUICamera() const
818 {
819 auto result = std::find_if(_cameras.begin(), _cameras.end(),
820 [](const osg::ref_ptr<CameraInfo> &i) {
821 return (i->flags & CameraInfo::GUI) != 0;
822 });
823 if (result == _cameras.end())
824 return 0;
825 return (*result);
826 }
827
getGUICamera(CameraGroup * cgroup)828 osg::Camera* getGUICamera(CameraGroup* cgroup)
829 {
830 return cgroup->getGUICamera()->compositor->getPass(0)->camera;
831 }
832
833 static bool
computeCameraIntersection(const CameraGroup * cgroup,const CameraInfo * cinfo,const osg::Vec2d & windowPos,osgUtil::LineSegmentIntersector::Intersections & intersections)834 computeCameraIntersection(const CameraGroup *cgroup,
835 const CameraInfo *cinfo,
836 const osg::Vec2d &windowPos,
837 osgUtil::LineSegmentIntersector::Intersections &intersections)
838 {
839 if (!(cinfo->flags & CameraInfo::DO_INTERSECTION_TEST))
840 return false;
841
842 const osg::Viewport *viewport = cinfo->compositor->getViewport();
843 SGRect<double> viewportRect(viewport->x(), viewport->y(),
844 viewport->x() + viewport->width() - 1.0,
845 viewport->y() + viewport->height()- 1.0);
846 double epsilon = 0.5;
847 if (!viewportRect.contains(windowPos.x(), windowPos.y(), epsilon))
848 return false;
849
850 osg::Vec4d start(windowPos.x(), windowPos.y(), 0.0, 1.0);
851 osg::Vec4d end(windowPos.x(), windowPos.y(), 1.0, 1.0);
852 osg::Matrix windowMat = viewport->computeWindowMatrix();
853 osg::Matrix invViewMat = osg::Matrix::inverse(cinfo->viewMatrix);
854 osg::Matrix invProjMat = osg::Matrix::inverse(cinfo->projMatrix * windowMat);
855 start = start * invProjMat;
856 end = end * invProjMat;
857 start /= start.w();
858 end /= end.w();
859 start = start * invViewMat;
860 end = end * invViewMat;
861
862 osg::ref_ptr<osgUtil::LineSegmentIntersector> picker =
863 new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL,
864 osg::Vec3d(start.x(), start.y(), start.z()),
865 osg::Vec3d(end.x(), end.y(), end.z()));
866 osgUtil::IntersectionVisitor iv(picker);
867 iv.setTraversalMask(simgear::PICK_BIT);
868
869 const_cast<CameraGroup *>(cgroup)->getViewer()->getCamera()->accept(iv);
870 if (picker->containsIntersections()) {
871 intersections = picker->getIntersections();
872 return true;
873 }
874
875 return false;
876 }
877
computeIntersections(const CameraGroup * cgroup,const osg::Vec2d & windowPos,osgUtil::LineSegmentIntersector::Intersections & intersections)878 bool computeIntersections(const CameraGroup* cgroup,
879 const osg::Vec2d& windowPos,
880 osgUtil::LineSegmentIntersector::Intersections& intersections)
881 {
882 // test the GUI first
883 CameraInfo* guiCamera = cgroup->getGUICamera();
884 if (guiCamera && computeCameraIntersection(cgroup, guiCamera, windowPos, intersections))
885 return true;
886
887 // Find camera that contains event
888 for (const auto &cinfo : cgroup->_cameras) {
889 if (cinfo == guiCamera)
890 continue;
891
892 if (computeCameraIntersection(cgroup, cinfo, windowPos, intersections))
893 return true;
894 }
895
896 intersections.clear();
897 return false;
898 }
899
warpGUIPointer(CameraGroup * cgroup,int x,int y)900 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
901 {
902 using osgViewer::GraphicsWindow;
903 osg::Camera* guiCamera = getGUICamera(cgroup);
904 if (!guiCamera)
905 return;
906 osg::Viewport* vport = guiCamera->getViewport();
907 GraphicsWindow* gw
908 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
909 if (!gw)
910 return;
911 globals->get_renderer()->getEventHandler()->setMouseWarped();
912 // Translate the warp request into the viewport of the GUI camera,
913 // send the request to the window, then transform the coordinates
914 // for the Viewer's event queue.
915 double wx = x + vport->x();
916 double wyUp = vport->height() + vport->y() - y;
917 double wy;
918 const osg::GraphicsContext::Traits* traits = gw->getTraits();
919 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
920 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
921 wy = traits->height - wyUp;
922 } else {
923 wy = wyUp;
924 }
925 gw->getEventQueue()->mouseWarped(wx, wy);
926 gw->requestWarpPointer(wx, wy);
927 osgGA::GUIEventAdapter* eventState
928 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
929 double viewerX
930 = (eventState->getXmin()
931 + ((wx / double(traits->width))
932 * (eventState->getXmax() - eventState->getXmin())));
933 double viewerY
934 = (eventState->getYmin()
935 + ((wyUp / double(traits->height))
936 * (eventState->getYmax() - eventState->getYmin())));
937 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
938 }
939
buildDefaultGroup(osgViewer::Viewer * viewer)940 void CameraGroup::buildDefaultGroup(osgViewer::Viewer* viewer)
941 {
942 // Look for windows, camera groups, and the old syntax of
943 // top-level cameras
944 SGPropertyNode* renderingNode = fgGetNode("/sim/rendering");
945 SGPropertyNode* cgroupNode = renderingNode->getNode("camera-group", true);
946 bool oldSyntax = !cgroupNode->hasChild("camera");
947 if (oldSyntax) {
948 for (int i = 0; i < renderingNode->nChildren(); ++i) {
949 SGPropertyNode* propNode = renderingNode->getChild(i);
950 const char* propName = propNode->getName();
951 if (!strcmp(propName, "window") || !strcmp(propName, "camera")) {
952 SGPropertyNode* copiedNode
953 = cgroupNode->getNode(propName, propNode->getIndex(), true);
954 copyProperties(propNode, copiedNode);
955 }
956 }
957
958 SGPropertyNodeVec cameras(cgroupNode->getChildren("camera"));
959 SGPropertyNode* masterCamera = 0;
960 SGPropertyNodeVec::const_iterator it;
961 for (it = cameras.begin(); it != cameras.end(); ++it) {
962 if ((*it)->getDoubleValue("shear-x", 0.0) == 0.0
963 && (*it)->getDoubleValue("shear-y", 0.0) == 0.0) {
964 masterCamera = it->ptr();
965 break;
966 }
967 }
968 if (!masterCamera) {
969 WindowBuilder *windowBuilder = WindowBuilder::getWindowBuilder();
970 masterCamera = cgroupNode->getChild("camera", cameras.size(), true);
971 setValue(masterCamera->getNode("window/name", true),
972 windowBuilder->getDefaultWindowName());
973 }
974 SGPropertyNode* nameNode = masterCamera->getNode("window/name");
975 if (nameNode)
976 setValue(cgroupNode->getNode("gui/window/name", true),
977 nameNode->getStringValue());
978 }
979
980 CameraGroup* cgroup = buildCameraGroup(viewer, cgroupNode);
981 setDefault(cgroup);
982 }
983
984 } // of namespace flightgear
985