osg.LightSource是一个osg::Group的子类,代表了一个光源。osg::LightSource中包含了osg::Light和osg::Projection两个节点,用来描述光源和阴影信息的生成。
创建LightSource节点的方式如下:
osg::LightSource* light_source = new osg::LightSource;
设置光源的方法如下:
osg::Light* light = light_source->getLight();
light->setLightNum(0);
light->setPosition(osg::Vec4(0, 0, 100, 1.0));
light->setAmbient(osg::Vec4(0.2, 0.2, 0.2, 1.0));
light->setDiffuse(osg::Vec4(0.8, 0.8, 0.8, 1.0));
light->setSpecular(osg::Vec4(0.4, 0.4, 0.4, 1.0));
设置阴影信息的方法如下:
osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
sm->setLight(light);
light_source->setShadowTechnique(sm);
设置节点位置的方法如下:
osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3(-5, 0, 0));
pat->addChild(light_source);
将节点加入场景图的方法如下:
osg::ref_ptr<osg::Group> root = new osg::Group;
root->addChild(pat);
完整示例代码如下:
#include <osg/Light>
#include <osg/LightSource>
#include <osg/Group>
#include <osg/PositionAttitudeTransform>
#include <osgViewer/Viewer>
#include <osgShadow/ShadowMap>
int main(int argc, char** argv)
{
osg::ref_ptr<osg::LightSource> light_source = new osg::LightSource;
// 设置光源信息
osg::Light* light = light_source->getLight();
light->setLightNum(0);
light->setPosition(osg::Vec4(0, 0, 100, 1.0));
light->setAmbient(osg::Vec4(0.2, 0.2, 0.2, 1.0));
light->setDiffuse(osg::Vec4(0.8, 0.8, 0.8, 1.0));
light->setSpecular(osg::Vec4(0.4, 0.4, 0.4, 1.0));
// 设置阴影信息
osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
sm->setLight(light);
light_source->setShadowTechnique(sm);
// 设置节点位置
osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3(-5, 0, 0));
pat->addChild(light_source);
// 将节点加入场景图
osg::ref_ptr<osg::Group> root = new osg::Group;
root->addChild(pat);
// 创建viewer并运行
osgViewer::Viewer viewer;
viewer.setSceneData(root);
return viewer.run();
}