2017-07-02 65 views
1

目前我有处理GLSL着色器制服的问题。如果我在场景中只有一个物体,制服就如我所料。但是,对于多个对象,均匀性不是针对每个对象设置的,换句话说,最后一个均匀度用于表示所有场景对象。GLSL为每个对象统一

我该如何处理这个问题?如下我的C++代码:

void addSimpleObject(osg::ref_ptr<osg::Group> root, osg::Vec3 position, float radius, float myUniform) { 

    osg::ref_ptr<osg::Geode> geode = new osg::Geode(); 
    geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(position, radius))); 
    root->addChild(geode); 
    root->getChild(0)->asGeode()->addDrawable(geode->getDrawable(0)); 

    osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet(); 
    stateset->addUniform(new osg::Uniform("myUniform", myUniform)); 
    root->setStateSet(stateset); 
} 


osg::ref_ptr<osg::Group> root = new osg::Group(); 
addSimpleObject(root, osg::Vec3(-3.0, 2.5, -10), 2, 0.5); 
addSimpleObject(root, osg::Vec3(3.0, 2.5, -10), 2, 1.5); 
addSimpleObject(root, osg::Vec3(0.0, -2.5, -10), 2, 1.0); 

顶点着色器:

#version 130 

out vec3 pos; 
out vec3 normal; 

void main() { 
    pos = (gl_ModelViewMatrix * gl_Vertex).xyz; 
    normal = gl_NormalMatrix * gl_Normal; 
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; 
} 

和片段着色器:

#version 130 

in vec3 pos; 
in vec3 normal; 

uniform float myUniform; 

void main() { 
    vec3 normNormal; 

    normNormal = normalize(normal); 

    if (myUniform > 0) 
     normNormal = min(normNormal * myUniform, 1.0); 

    ... 
} 

image output

+1

一个统一绑定到一个着色器程序不是一个“对象”。如果对所有对象使用相同的程序,yoa必须在绘制对象之前设置制服。 – Rabbid76

+0

Hi @ Rabbid76,谢谢你的回答。你能举个例子吗?我如何解决我的计划以解决您的建议? –

回答

2

均匀结合到着色器程序不一个东西”。 如果对所有对象使用相同的程序,则必须在绘制对象之前设置制服。

您将osg::StateSet绑定到场景图的根节点。 如果统一变量的值为每个drawable更改,则必须将 分隔osg::StateSet添加到每个osg::Drawable节点。

适应你的方法addSimpleObject这样的:

void addSimpleObject(osg::ref_ptr<osg::Group> root, osg::Vec3 position, float radius, float myUniform) { 

    // create the drawable 
    osg::ref_ptr<osg::Drawable> drawable = new osg::ShapeDrawable(new osg::Sphere(position, radius)) 

    // crate the stateset and add the uniform 
    osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet(); 
    stateset->addUniform(new osg::Uniform("myUniform", myUniform)); 

    // add the stateset tor the drawable 
    drawable->setStateSet(stateset); 

    if (root->getNumChildren() == 0) { 
     osg::ref_ptr<osg::Geode> geode = new osg::Geode(); 
     root->addChild(geode); 
    } 
    root->getChild(0)->asGeode()->addDrawable(drawable); 
} 
+0

Hi @ Rabbid76,我测试了你的解决方案,它工作正常!非常感谢! –