代码如下:
#include<osgViewer/Viewer>
#include<osgGA/TrackBallManipulator>
#include<osg/Shape>
#include<osg/ShapeDrawable>
#include<osg/Texture2D>
#include<osgDB/readFile>
#include<osg/MatrixTransform>
#include<osg/PositionAttitudeTransform>
int main(int argc, char*argv[])
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
viewer.setRunFrameScheme(osgViewer::Viewer::CONTINUOUS);
viewer.setCameraManipulator(new osgGA::TrackballManipulator);
osg::ref_ptr<osg::Group> m_spRoot = new osg::Group;
// 精细度设置
osg::TessellationHints* hints = new osg::TessellationHints;
hints->setDetailRatio(5.0f);
// 新建半径为WGS84参考半径的球。即地球半径为6356752.3142米
osg::ShapeDrawable* sd = new osg::ShapeDrawable(
new osg::Sphere(osg::Vec3(0.0, 0.0, 0.0), osg::WGS_84_RADIUS_POLAR), hints);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(sd);
// 添加全球的纹理,图片的OSG资源Data中的图片,即使下载osg时附带的图片、模型数据资源文件夹下的图片
geode->getOrCreateStateSet()->setTextureAttributeAndModes(0,
/*注意:这里需要读取jpg,故请保证jpg插件存在,否则读取jpg会失败. 注意:这里需要读取jpg,故请保证jpg插件存在,否则读取jpg会失败。
关于怎么编译jpg插件到osg,请参见:https://blog.csdn.net/danshiming/article/details/115412956
*/
new osg::Texture2D(osgDB::readImageFile(R"(E:\osg\OpenSceneGraph-Data\Images\land_shallow_topo_2048.jpg)")));
// 经纬度坐标处理
osg::ref_ptr<osg::CoordinateSystemNode> spCsn = new osg::CoordinateSystemNode;
// 设置地球坐标系统为WGS_84,即:经纬度、高程坐标系。
auto pEllModel = new osg::EllipsoidModel();
spCsn->setEllipsoidModel(pEllModel);
spCsn->addChild(geode);
osg::ref_ptr<osg::Group> spModelRoot = new osg::Group; // 模型根节点
osg::ref_ptr<osg::MatrixTransform> spMatrixTrans = new osg::MatrixTransform;
// 读取j-10飞机模型
auto pNode = osgDB::readNodeFile(R"(E:\osg\OpenSceneGraph-Data\glider.osg)");
spMatrixTrans->addChild(pNode);
auto matrix = spMatrixTrans->getMatrix();
matrix.makeScale(osg::Vec3(10000000, 10000000, 10000000)); // 将飞机放大些,否则和地球相比大小,看不见。
spMatrixTrans->setMatrix(matrix);
// 设置飞机在地球的经纬度位置。即将经纬度高程坐标转为地心地固坐标系
double x, y, z; // 分别表示离地球球心的 x, y, z距离,单位为米。
// 下面函数参数是以弧度、米为单位的。飞机在北京上空
pEllModel->convertLatLongHeightToXYZ(osg::DegreesToRadians(39.6), osg::DegreesToRadians(116.35), 1000000, x, y, z);
osg::ref_ptr<osg::PositionAttitudeTransform> spPosition = new osg::PositionAttitudeTransform;
spPosition->addChild(spMatrixTrans);
spModelRoot->addChild(spPosition);
spCsn->addChild(spModelRoot);
m_spRoot->addChild(spCsn);
viewer.getCamera()->setNearFarRatio(0.00001f);
viewer.setSceneData(m_spRoot);
viewer.run();
}
效果如下: