網上查找了關於osg光源的設置,基本上都是一個光源的,後來查找了一些資料,包括osg官方的例子。其實多個光源的實現非常簡單,只要多建立一個osg::Light的對象並設置對應參數即可。
以兩個光源爲例
osg::ref_ptr<osg::Group> createLight(osg::ref_ptr<osg::Node> node)
{
osg::ref_ptr<osg::Group> lightRoot = new osg::Group();
lightRoot->addChild(node);
//開啓光照
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet();
stateset = lightRoot->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING , osg::StateAttribute::ON);
stateset->setMode(GL_LIGHT0 , osg::StateAttribute::ON);//允許GL_LIGHT0光照
stateset->setMode(GL_LIGHT1 , osg::StateAttribute::ON);
//計算包圍盒
/*osg::BoundingSphere bs;
node->computeBound();
bs = node->getBound();*/
//創建兩個個Light對象
osg::ref_ptr<osg::Light> light = new osg::Light();
osg::ref_ptr<osg::Light> light1 = new osg::Light();
//開啓光照
light->setLightNum(0);
light1->setLightNum(1);//0對應GL_LIGHT0,1對應GL_LIGHT1,默認情況下爲GL_LIGHT0
//設置方向
//light->setDirection(osg::Vec3(0.0f , 0.0f , -1.0f));
//設置位置 最後一個參數1是點光源,0是平行光
light->setPosition(osg::Vec4(0.f , 0.f , 800.f , 1.0f));
light1->setPosition(osg::Vec4(100.f, 100.f , 800.f , 1.0f));
//設置光源顏色
light->setAmbient(osg::Vec4(0.3f, 0.3f, 0.5f, 1.0f));
light1->setAmbient(osg::Vec4(0.3f, 0.3f, 0.5f, 1.0f));
//設置散射光的顏色
light->setDiffuse(osg::Vec4(0.75f, 0.75f, 0.75f, 1.0f));
light1->setDiffuse(osg::Vec4(0.75f, 0.75f, 0.75f, 1.0f));
//鏡面反射顏色
light->setSpecular(osg::Vec4d( 0.8f, 0.8f, 0.8f, 1.0f ));
light1->setSpecular(osg::Vec4d( 0.8f, 0.8f, 0.8f, 1.0f ));
//設置恆衰減指數
light->setConstantAttenuation(1.f);
light1->setConstantAttenuation(1.f);
//設置線性衰減指數
light->setLinearAttenuation(0.f);
light1->setLinearAttenuation(0.f);
//light->setLinearAttenuation(0.f);
//設置二次方衰減指數
light->setQuadraticAttenuation(0.f);
light1->setQuadraticAttenuation(0.f);
//stateset->setAttribute(light,osg::StateAttribute::OFF);
//light->setQuadraticAttenuation(0.f);
//創建光源
osg::ref_ptr<osg::LightSource> lightSource = new osg::LightSource();
osg::ref_ptr<osg::LightSource> lightSource1 = new osg::LightSource();
lightSource->setLight(light.get());
lightSource1->setLight(light1.get());
lightRoot->addChild(lightSource.get());
lightRoot->addChild(lightSource1.get());
return lightRoot.get();
}