[osg-users] Tearing hair out over simple GLSL instancing

Andrew Cunningham andrewC at mac.com
Thu Dec 22 09:17:26 PST 2016


OSG 3.4.0 
I am trying to use "instancing" (starting from the example osgdrawinstanced) to draw simple square geometry at multiple locations.
 I am getting all of my instances sitting on top of each other at (0,0,0). That is they are not offset to their expected locations.

I know my shader is working OK because if I add a hack to my shader to add in an offset that depends on gl_InstanceID then the squares do get "offset" per instance.


Step 1 
Add "nInstances" of the square to my osg::Geometry
    geom.addPrimitiveSet( new osg::DrawArrays( GL_QUADS, 0, 4, nInstances ) );

Step 2
Create a simple shader program that uses an attribute array of offsets ("d") to offset the vertex locations
	std::string vertexSource =
		"#version 120\n"
		"#extension GL_EXT_draw_instanced : enable\n"
		"in vec3 d;\n"
		"void main() \n"
		"{ \n"
		// Use the =coord to translate the position of the vertices.
			"vec3 pos = vec3(gl_Vertex) + d;\n"
			"vec4 finalPos = vec4(pos, 1.0);\n"
			"gl_Position = gl_ModelViewProjectionMatrix * finalPos;\n"
		"} \n";

	osg::ref_ptr< osg::Shader > vertexShader = new osg::Shader();
	vertexShader->setType(osg::Shader::VERTEX);
	vertexShader->setShaderSource(vertexSource);

	osg::ref_ptr< osg::Program > program = new osg::Program();
	program->addShader(vertexShader.get());
	ss->setAttribute(program.get(),osg::StateAttribute::ON);

	program->addBindAttribLocation("d", 1);

Step 3
      Create an array of offsets 4 * nInstances that contain the offsets for each vertex. Is this where I am going wrong??? I have checked that "d" is not (0,0,0) and is varying for each instance. It seems to be that all the instances are using  the same offset.
			osg::Vec3Array *attrib = new osg::Vec3Array;
			size_t vecIndex = 0;
			for (size_t i = 0; i < nInstances ; i++) {
				osg::Vec3 d=GetOffSetForInstance(i);
				attrib->push_back(d);
				attrib->push_back(d);
				attrib->push_back(d);
				attrib->push_back(d);
			}
			geom->setVertexAttribArray(1, attrib);
			geom->setVertexAttribBinding(1, osg::Geometry::BIND_PER_VERTEX);




Andrew

------------------
Read this topic online here:
http://forum.openscenegraph.org/viewtopic.php?p=69743#69743








More information about the osg-users mailing list