# Passing data into a vertex shader for perspective divide

In OpenGL and GLSL, I am just learning about perspective projection and the vertex shader. However, I am a little confused about what data actually needs to be passed to the vertex shader, and what needs to be done in the shader code itself.

I have two questions:

Suppose I have a triangle defined in 3D coordinates (x,y,z). Do I need to pass a 4D vector with values (x,y,z,w), where w = z? Or do I just pass the 3D vector? The reason I ask is that I know that somewhere in the pipeline, the x and y coordinates are divided by the w component, in the perspective divide.

In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically?

Thanks!

# Input requirements

OpenGL doesn't care what you pass in to the vertex shader. In fact, you could even pass nothing and somehow generate the input in the vertex shader. You may want to consider leaving the W out of the input to save RAM and bandwidth. That's because you won't have to pass the 4th value for every vertex.

# The W divide

GPUs have optimizations made for dividing by W. Dividing manually is a very bad thing. You know how you can't divide a number by 0? Well what happens when the W is 0? The GPU handles this for you. Just make sure that you are passing out a vec4.

If you are receiving a vec3 as input, this is how you should set gl_Position:

// Assuming "inputVector" is a vec3
gl_Position = vec4(inputVector, 1.0);


Do I need to pass a 4D vector with values (x,y,z,w), where w = z?

No, you don't need to. And this would even be wrong, w is 1 for positions and 0 for directions. When you want to multiply the vertex with a mat4 usually you convert it to a vec4 on the fly with vec4(your_position, 1.0).

In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically?

No, you can just ignore the fact that this happens. All you care is your normal coordinate system, everything else will be handled by your multiplication with your perspective matrix and by OpenGL itself.