I'm having trouble accessing an array in a fragment shader using a non-constant int as the index. I've removed the formula as it wouldn't make much sense here anyway, but my code is meant to calculate the tileID based on the current pixel and use that to determine the color.
Here's my code:
int tileID = <Insert formula here>;
vec3 colorTest;
int arrayTest[1024];
for (int x = 0; x < 1024; x++) {
if (x == 1) arrayTest[x] = 1;
else arrayTest[x] = 2;
}
if (arrayTest[tileID] == 1) colorTest = vec3(0.0, 1.0, 0.0);
else if (arrayTest[tileID] == 2) colorTest = vec3(1.0, 0.0, 0.0);
else colorTest = vec3(0.0, 0.0, 0.0);
Apparently GLSL doesn't like this and I get the error:
'[]' : Index expression must be constant
Does anyone know how I would fix this? Thanks.
I hit this error because I was attempting to use an integer variable to take the nth texture from an array of textures:
The solution was to break out the texture indexing into a sequence of conditionals:
As background -- GLSL looks a lot like C, but compiles a bit different. Things are very unrolled, and conditionals may be executed in parallel and switched at the end, that sort of thing. Depends on the hardware...
You can use loop indices or constants to index into arrays. The assignment in your loop is ok, but the access by tileID isn't.
WebGL Shader language is from GLES, documented
http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
The Appendix, section 5, discusses:
Hope that helps!
Oh, as for fixing it, in the exact example above... looks like you could compute from tileID rather than precompute and index.
Or, precompute whatever array you like, and pass it in as a texture. A texture, of course, can be indexed however you like.
Here's a javascript helper method I use, to pass floats down to the shaders:
Note the use of gl.NEAREST, so it doesn't "blur" your values! Then you can set it up before the gl.drawXxx call, with something like
And in the shader (I believe fragment or vertex; some earlier webgl's didn't support vertex textures...)
So, you have to index appropriately for the array-as-texture size, within range of 0 to 1. Try to sample from the middle of each value/pixel. Like, if the array is 2 values wide, index by 0.25 and 0.75.
That's the gist of it!
Tested in Safari 9.1.2 on OS X 10.11.6