Pass vector<float> to shader

I have a vector of floats that I want to access in my vertex shader. Is this possible? The vector has a length of 512.

Similar to what this person says they want to do originally before deciding to just pass a single float:

None of the methods here seem to be what I want:

http://openframeworks.cc/documentation/gl/ofShader/#show_setUniform1fv

Yes you can.

here are 2 types way. Try this.

vector<float> vector_ar;
float just_ar[512];

... 
//insert some of values.
for (int i = 0; i < 512; i++)
{
	vector_ar.push_back(i * 1.0);
	just_ar[i] = i * 1.0;
}

//insert to shader uniforms
shader1.setUniform1fv("vector_array", &vector_ar[0] , vector_ar.size());
shader1.setUniform1fv("just_array", &just_ar[0], 512);

and glsl is …

uniform float vector_array[];
uniform float just_array[];
main()
{
 ...
 // now you can use arrays normally in your code.
}
1 Like

Hi there!

@jjongun’s approach is 100% correct, but I would like to leave a note for future reference.

Upload vectors like that can make your program really slow really fast. (At least for me, with an AMD Radeon HD 6750M, after 16 it’s a no-no).

So, my recommendation about shaders is: it’s all about textures.

For something like 512 you could use an 1D Array ofFloatImage, easy and fast.

If you want more approaches and general knowledge, this is a great StackOverflow topic.

2 Likes

If your project can run on reasonably modern hardware, you can use buffer objects. They are pretty easy to use and intended exactly for this kind of thing.

The compute shader example shows how to use them in your shader.