How to get a value from vec3 in vertex shader? OpenGL 3.3

user3051029 picture user3051029 · Jan 17, 2015 · Viewed 10.1k times · Source

I have the following vertex shader:

#version 330                                                                      
layout (location = 0) in vec3 Position;                                           
uniform mat4 gWVP;                                                                
out vec4 Color;
void main()                                                                       
{                                                                                 
    gl_Position = gWVP * vec4(Position, 1.0);                     
};

How can I get, for example, the third value of vec3? The first my thought was: "Maybe I can get it by multiplying this vector(Position) on something?" But I am not sure that something like "vertical vector type" exists. So, what is the best way? I need this value to set the color of the pixel.

Answer

Reto Koradi picture Reto Koradi · Jan 19, 2015

There are at least 4 options:

  1. You can access vector components with component names x, y, z, w. This is mostly used for vectors that represent points/vectors. In your example, that would be Position.z.
  2. You can use component names r, g, b, a. This is mostly used for vectors that represent colors. In your example, you could use Position.b, even though that would not be very readable. On the other hand, Color.b would be a good option for the other variable.
  3. You can use component names s, t, p, q. This is mostly used for vectors that represent texture coordinates. In our example, Position.p would also give you the 3rd component.
  4. You can use the subscript notation with 0-based indices. In your example, Position[2] also gives he 3rd element.