大家,
我在使用OSG的顶点着色器中使用顶点属性。我按照包含addBindAttribLocation
和setVertexAttribArray
的例程进行了操作。问题是如果我使用VBO,那么顶点属性不能传递给顶点着色器。仅当我使用DisplayList时,才能将顶点属性传递给顶点着色器。
代码如下所示。在代码中,我想以不同的颜色显示四个顶点,由vertAttrib表示:
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(4);
osg::ref_ptr<osg::FloatArray> vertAttrib = new osg::FloatArray(4);
osg::ref_ptr<osg::DrawElementsUInt> pointIdx = new osg::DrawElementsUInt(osg::PrimitiveSet::POINTS, 4);
(*vertices)[0] = osg::Vec3(0, 0, 0); (*vertAttrib)[0] = 1; (*pointIdx)[0] = 0;
(*vertices)[1] = osg::Vec3(0, 1, 0); (*vertAttrib)[1] = 2; (*pointIdx)[1] = 1;
(*vertices)[2] = osg::Vec3(1, 1, 0); (*vertAttrib)[2] = 3; (*pointIdx)[2] = 2;
(*vertices)[3] = osg::Vec3(1, 0, 0); (*vertAttrib)[3] = 4; (*pointIdx)[3] = 3;
geometry = new osg::Geometry;
geometry->setUseVertexBufferObjects(true);
geometry->setUseDisplayList(false);
geometry->setVertexArray(vertices.get());
geometry->setVertexAttribArray(10, vertAttrib.get(), osg::Array::BIND_PER_VERTEX);
geometry->addPrimitiveSet(pointIdx.get());
static const char *vertSource = {
"attribute float myAttrib;\n"
"varying float attrib;\n"
"void main()\n"
"{\n"
" attrib = myAttrib;\n"
" gl_Position = ftransform();"
" gl_PointSize = 50.0;\n"
"}\n"
};
static const char *fragSource = {
"varying float attrib;\n"
"void main()\n"
"{\n"
" if(attrib < 1.2){\n"
" gl_FragColor = vec4(1.0, 0, 0, 1.0);\n"
" }else if(attrib <2.2){\n"
" gl_FragColor = vec4(0.0, 1.0, 0, 1.0);\n"
" }else if(attrib < 3.2){\n"
" gl_FragColor = vec4(0.0, 0, 1.0, 1.0);\n"
" }else{\n"
" gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0);\n"
" }\n"
"}\n"
};
osg::Geode* geode = new osg::Geode;
osg::StateSet* stateset = new osg::StateSet;
osg::ref_ptr<osg::Program> program;
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);
program = new osg::Program;
program->addShader(vertShader.get());
program->addShader(fragShader.get());
program->addBindAttribLocation("myAttrib", 10);
stateset->setAttributeAndModes(program.get(), osg::StateAttribute::ON);
stateset->setMode(GL_VERTEX_PROGRAM_POINT_SIZE, osg::StateAttribute::ON);
geode->setStateSet(stateset);
geode->addDrawable(geometry.get());
运行结果显示vertAttrib从未正确传递到顶点着色器,并且四个顶点全部为红色。事实是,我发现在片段着色器中,所有的属性都是&#39;值为0.
我错过了什么?任何建议表示赞赏!感谢。