|
- #include <osgViewer/Viewer>
- #include <osgDB/ReadFile>
- #include <osgDB/FileUtils>
- #include <osgUtil/Optimizer>
- #include <osg/Program>
- #include <osg/Shader>
- static void LoadShaderSource(osg::Shader* shader,const std::string& fileName)
- {
- std::string fqFileName=osgDB::findDataFile(fileName);
- if (fqFileName.length()!=0)
- {
- shader->loadShaderSourceFromFile(fqFileName.c_str());
- }
- else
- {
- osg::notify(osg::WARN) << "File "" << fileName << "" not found." << std::endl;
- }
- }
- void main()
- {
- osg::ref_ptr<osgViewer::Viewer> viewer=new osgViewer::Viewer;
- osg::ref_ptr<osg::Node> node=osgDB::readNodeFile("cow.osg");
- osg::ref_ptr<osg::StateSet> stateset=node->getOrCreateStateSet();
- osg::ref_ptr<osg::Program> TestProgram=new osg::Program;
- osg::ref_ptr<osg::Shader> TestVert=new osg::Shader(osg::Shader::VERTEX);
- osg::ref_ptr<osg::Shader> TestFrag=new osg::Shader(osg::Shader::FRAGMENT);
- LoadShaderSource(TestVert,"ProgramShaders/Test.vert");
- LoadShaderSource(TestFrag,"ProgramShaders/Test.frag");
- TestProgram->addShader(TestVert);
- TestProgram->addShader(TestFrag);
- osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0);
- stateset->addUniform(baseTextureSampler);
- stateset->setAttributeAndModes(TestProgram,osg::StateAttribute::ON);
- osgUtil::Optimizer optimizer;
- optimizer.optimize(node);
- viewer->setSceneData(node);
- viewer->run();
- }
复制代码
shader文件如下:
varying vec2 vTexCoord;
void main()
{
vTexCoord = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix*gl_Vertex;
}
uniform sampler2D baseTexture;
varying vec2 vTexCoord;
void main()
{
vec4 baseColor=texture2D(baseTexture,vTexCoord);
gl_FragColor=baseColor;
}
|
|