Quick question about shaders

I've noticed at least in vertex shaders, you can put computations outside of a function. See the example below, where I have put code just above the main() function to compute "start_point_pos", "end_point_pos", and "rot". So my question is, what does it mean when you do this? Is code put in this space still computed once for each vertex? Or maybe only once for each primitive?

Code:
attribute vec3 in_Position;                  // (x,y,z)
attribute vec4 in_Colour;                    // (r,g,b,a)
attribute vec2 in_TextureCoord;              // (u,v)

uniform vec3 start_point;
uniform vec3 end_point;

varying vec2 v_vTexcoord;
varying vec4 v_vColour;

    vec4 start_point_pos = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * vec4(start_point, 1.0);
    vec4 end_point_pos = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * vec4(end_point, 1.0);
    vec2 rot = normalize(end_point_pos.yx - start_point_pos.yx);

void main()
{

    gl_Position = mix(start_point_pos,end_point_pos,in_Position.x) + vec4(rot.x  * 480.0/640.0 * in_Position.y, -rot.y * in_Position.y,0.0,0.0);
    v_vColour = in_Colour;
    v_vTexcoord = in_TextureCoord;
}
 

johnwo

Member
From the GLSL ES 1.0 spec:

Declarations of globals without a storage qualifier, or with just the const qualifier, may include initializers, in which case they will be initialized before the first line of main() is executed. Such initializers must be a constant expression.
Further:

The following may not be used in constant expressions:
  • Uniforms, attributes and varyings.
The code you posted includes uniforms in the calculations, so the calculations are illegal according to the spec, i.e. you should put the calculations in main.

It's common for GLSL compilers to accept shaders that are not up to spec (unfortunately). This could end up being a cause for errors when compiling the shader across platforms.

TL;DR:
That's bad. Move the calculation inside main, like the spec says. This way you don't end up with nasty surprises when when trying to compile the shader across platforms.

Cheers!
 
Top