osgearth如何设置相机的范围
时间: 2023-09-17 15:07:55 浏览: 314
在osgEarth中设置相机视野范围可以使用以下两种方式:
1. 使用`MapNode`的`getMapSRS()`方法获取地图的投影坐标系,然后使用`osg::CoordinateSystemNode`计算出相机视锥体的范围,最后使用`osg::CullSettings`设置相机视锥体的大小。
```
// 获取地图投影坐标系
const osgEarth::SpatialReference* srs = mapNode->getMapSRS();
// 计算相机视锥体的范围
osg::Vec3d eye, center, up;
camera->getViewMatrixAsLookAt(eye, center, up);
osg::CoordinateSystemNode* csn = new osg::CoordinateSystemNode(srs);
osg::Vec3d worldEye = csn->getLocalToWorld().preMult(eye);
osg::Vec3d worldUp = csn->getLocalToWorld().preMult(osg::Vec3d(0, 0, 1));
double fov = camera->getProjectionMatrixAsPerspective().fov();
double aspectRatio = camera->getViewport()->aspectRatio();
double nearPlane = camera->getNearClipPlane();
double farPlane = camera->getFarClipPlane();
osg::CullSettings::ClampProjectionMatrixCallback* clampProjCb = new osgEarth::Util::OrthoCallback(worldEye, worldUp);
osg::CullSettings cullSettings;
cullSettings.setClampProjectionMatrixCallback(clampProjCb);
cullSettings.setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
osg::BoundingBox bb;
osg::ComputeNearFarBoundingBoxVisitor::apply(*mapNode, bb, cullSettings);
double minZ = bb._min.z();
double maxZ = bb._max.z();
// 设置相机视锥体的大小
double halfAngleRadians = osg::DegreesToRadians(fov * 0.5);
double tanHalfAngle = std::tan(halfAngleRadians);
double halfWidth = nearPlane * tanHalfAngle;
double halfHeight = halfWidth / aspectRatio;
double minX = -halfWidth;
double maxX = halfWidth;
double minY = -halfHeight;
double maxY = halfHeight;
osg::Matrixd projMatrix = osg::Matrixd::frustum(minX, maxX, minY, maxY, nearPlane, farPlane);
camera->setProjectionMatrix(projMatrix);
```
2. 使用`osgEarth::Util::EarthManipulator`设置相机视锥体的范围。可以通过以下方式创建`EarthManipulator`:
```
osg::ref_ptr<osgEarth::Util::EarthManipulator> earthManipulator = new osgEarth::Util::EarthManipulator();
earthManipulator->setMapNode(mapNode);
```
然后可以设置`EarthManipulator`的`getSettings()`方法返回的`osg::CullSettings`对象的`ComputeNearFarMode`属性为`osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR`,这样可以禁用osg的自动计算相机视锥体大小的功能,然后可以使用`setMinimumDistance()`和`setMaximumDistance()`方法设置相机的最小距离和最大距离。
```
osg::ref_ptr<osg::CullSettings> cullSettings = earthManipulator->getSettings();
cullSettings->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
earthManipulator->setMinimumDistance(minDistance);
earthManipulator->setMaximumDistance(maxDistance);
```
阅读全文