1.使用材质设置透明度
#include <Windows.h>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgViewer/ViewerEventHandlers>
#include <osg/StateSet>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/BlendColor>
#include <osg/BlendFunc>
int main(int argc,char** argv)
{
osgViewer::Viewer view;
osg::Group* root = new osg::Group();
root->addChild(osgDB::readNodeFile("cow.osg"));
//方法1
osg::StateSet* state = root->getOrCreateStateSet();
state->setMode(GL_BLEND,osg::StateAttribute::ON);
osg::ref_ptr<osg::Material> mat = new osg::Material;
//漫发射光
mat->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(1.0,1.0,1.0,0.5));
//环境光
mat->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(1.0,1.0,1.0,0.5));
//设置材质的混合光颜色
mat->setTransparency(osg::Material::FRONT_AND_BACK,0.5);
state->setAttributeAndModes(mat,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
view.setSceneData(root);
view.run();
}
2.通过混合函数设置透明度
int main(int argc,char** argv)
{
//方法2
osg::StateSet* state = root->getOrCreateStateSet();
//关闭灯光
state->setMode(GL_LIGHTING,osg::StateAttribute::OFF|osg::StateAttribute::PROTECTED);
//打开混合融合模式
state->setMode(GL_BLEND,osg::StateAttribute::ON);
state->setMode(GL_DEPTH_TEST,osg::StateAttribute::ON);
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
//使用BlendFunc实现透明效果
osg::BlendColor* bc =new osg::BlendColor(osg::Vec4(1.0,1.0,1.0,0.0));
osg::BlendFunc*bf = new osg::BlendFunc();
state->setAttributeAndModes(bf,osg::StateAttribute::ON);
state->setAttributeAndModes(bc,osg::StateAttribute::ON);
bf->setSource(osg::BlendFunc::CONSTANT_ALPHA);
bf->setDestination(osg::BlendFunc::ONE_MINUS_CONSTANT_ALPHA);
bc->setConstantColor(osg::Vec4(1,1,1,0.5));
}