在osg场景中使用GLSL语言——一个例子

1、由于环境变量神马的都已经设置好了,基本上要使用osg,只需要在添加连接器中的附加依赖项中添加:

kernel32.lib
user32.lib
gdi32.lib
winspool.lib
shell32.lib
ole32.lib
oleaut32.lib
uuid.lib
comdlg32.lib
advapi32.lib
OpenThreadsd.lib
osgd.lib
osgDBd.lib
osgUtild.lib
osgGAd.lib
osgViewerd.lib
osgTextd.lib
glu32.lib
opengl32.lib

2、直接添加代码如下:

// 1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>


static const char* vertSource=
{
"varying vec3 normal;\n"
"void main()\n"
"{\n"
"     normal=normalize(gl_NormalMatrix*gl_Normal);\n"
"     gl_Position=ftransform();\n"
"}\n"
};
static const char* fragSource={
"uniform vec4 mainColor;\n"
"varying vec3 normal;\n"
"void main()\n"
"{\n"
"    float intensity=dot(vec3(gl_LightSource[0].position),normal);\n"
"    if(intensity>0.95) gl_FragColor=mainColor;\n"
"    else if(intensity>0.5)  gl_FragColor=vec4(0.6,0.3,0.3,1.0);\n" 
"    else if(intensity>0.25)  gl_FragColor=vec4(0.4,0.2,0.2,1.0);\n" 
"    else gl_FragColor=vec4(0.2,0.1,0.1,1.0);\n" 
"}\n"
};
class ColorCallback:public osg::Uniform::Callback
{
public:
ColorCallback():_incRed(false){}


virtual void operator()(osg::Uniform * uniform,osg::NodeVisitor* nv)
{
if (!uniform) return;
osg::Vec4 color;
uniform->get(color);
if (_incRed==true)
{
if (color.x()<1.0) color.x()+=0.01;
else _incRed=false;
}
else
{
if (color.x()>0.0) color.x()-=0.01;
else _incRed=true;
}
uniform->set(color);
}
protected:
bool _incRed;
};
void createShaders(osg::StateSet & ss)
{
osg::ref_ptr<osg::Shader> vertShader=new osg::Shader(osg::Shader::VERTEX,vertSource);
osg::ref_ptr<osg::Shader> fragShader=new osg::Shader(osg::Shader::FRAGMENT,fragSource);


osg::ref_ptr<osg::Program> program=new osg::Program;
program->addShader(vertShader.get());
program->addShader(fragShader.get());


osg::ref_ptr<osg::Uniform> mainColor=new osg::Uniform("mainColor",osg::Vec4(1.0,0.5,0.5,1.0));
mainColor->setUpdateCallback(new ColorCallback);


ss.addUniform(mainColor.get());
ss.setAttributeAndModes(program.get());
}
int _tmain(int argc, _TCHAR* argv[])
{
osg::ArgumentParser arguments(&argc,argv);
osg::Node *model=osgDB::readNodeFiles(arguments);
if (!model) model=osgDB::readNodeFile("cow.osg");
createShaders(*(model->getOrCreateStateSet()));


osgViewer::Viewer a;
a.setSceneData(model);


return a.run();
}
效果截图:



具体的参考文档是

http://download.csdn.net/detail/smbluesky/7504667
可参考该文档的6.4章节,里面有具体的介绍。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值