Thursday, March 22, 2012

Cg TexelFetch

Are you programming OpenGL and believe you might want to use Texture Buffers? Are you trying to do batching with the Geometry Instancing API perhaps? Are you using Cg/CgFx shaders instead of GLSL? Then you'll probably end up looking for the Cg equivalent of texelFetch and find the Cg documentation lacking. The function you need to use is texBUF along with a samplerBUF or similar sampler. You'll need to use a gp4vp profile for your technique or it will not pass validation.

For example:

SomeShader.cgfx:
// ...
uniform samplerBUF posBuffer : TEX1;
void mainVS( ..., int primID : INSTANCEID ) : POSITION {
//...
float4 pos = texBUF(posBuffer, primID);
// ...
}
// ...

SomeCode.cpp:
// ...
CGparameter posTexBufferParam = cgGetNamedEffectParameter(effect, "posBuffer");
// ...


// Load, bind data:
glm::vec4 * positions4 = new glm::vec4[1000];
// (fill positions4)
unsigned int buffer;

glGenBuffers(1, &buffer);
GLuint posTexBuffer
glGenTextures (1, &posTexBuffer );

glBindBuffer(GL_ARRAY_BUFFER,  buffer );
glBufferData(GL_ARRAY_BUFFER, 1000*4*sizeof(GLfloat), &positions4[0], GL_DYNAMIC_DRAW);
glActiveTexture(GL_TEXTURE1); // ?
glBindTexture(GL_TEXTURE_BUFFER, posTexBuffer);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F,  buffer  );
// ...


// Draw:
cgGLSetTextureParameter(posTexBufferParam,  posTexBuffer );
// Get technique, apply pass etc...
glDrawArraysInstanced(GL_TRIANGLES, 0, 6, 1000);
// ...