osg添加纹理示例

时间:2023-05-02 22:22:18

转自http://www.cnblogs.com/ylwn817/articles/1976851.html

#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/TexGen>
#include <osg/TexEnv>

void main()
{
    osgViewer::Viewer viewer;
    osg::ref_ptr<osg::Group> root=new osg::Group();
    osg::ref_ptr<osg::Node>  node=osgDB::readNodeFile("cow.osg");

osg::ref_ptr<osg::Image> image=osgDB::readImageFile("Images\\Primitives.gif");

if (image.get())
    {
        osg::ref_ptr<osg::Texture2D> texture=new osg::Texture2D();
        texture->setImage(image.get());

//设置自动生成纹理坐标
        osg::ref_ptr<osg::TexGen> texgen=new osg::TexGen();
        texgen->setMode(osg::TexGen::SPHERE_MAP);

//设置纹理环境,模式为BLEND
        osg::ref_ptr<osg::TexEnv> texenv=new osg::TexEnv;
        texenv->setMode(osg::TexEnv::Mode::ADD);
        texenv->setColor(osg::Vec4(0.6,0.6,0.6,0.0));

//启动单元一自动生成纹理坐标,并使用纹理
        osg::ref_ptr<osg::StateSet> state=new osg::StateSet;
        state->setTextureAttributeAndModes(1,texture.get(),osg::StateAttribute::ON);
        state->setTextureAttributeAndModes(1,texgen.get(),osg::StateAttribute::ON);
        state->setTextureAttribute(1,texenv.get());

node->setStateSet(state.get());

}
    root->addChild(node.get());
    viewer.setSceneData(root.get());
    viewer.realize();
    viewer.run();
}