How do I get a fragments x,y,z in world coordinates in the fragment shader?

I want to save the world position (x,y,z) of each fragment in a texture (R = x, G = y, B = z)… How do I get the x,y,z in world coordinates in the fragment shader?

CD

In your vertex shader, after you multiply vertices by the modelview matrix multiply them again by the inverse view matrix to take them back to world space. Then pass those world space positions into the fragment shader as varyings.

So something like this?

  
// Vertex Shader
varying vec3 vertexWorldPos;

main()
{
   gl_Position = ftransform();
   vertexWorldPos = gl_ModelViewMatrixInverse * gl_Position;
}

CD

Absolutely NO !

As mogumbo said, multiply your object space vertex by the modelview matrix, then multiply it by the invert of the view matrix. So more something like this:

vert = gl_ModelViewMatrix * gl_Vertex;
vert = ViewMatrixInverse * vert;

You got the poor guy all confused i believe :slight_smile: . Well, the vertices that you get into the vertex shader are the ones that you sent to the vertex pipeline via some method (immediate mode, vbo, cvar etc). They can be in ANY space depending on what you have sent e.g. they can sometimes be in world space for your map (although that too is object space, but considering that a map is your world with vertices centered around the origin). They are mostly (almost always) in object space i.e. relative to the origin of the object. So lets say you have an object origin at (10, 10, 10), then the world space matrix of that object would be a matrix that transforms point (0, 0, 0) to (10, 10, 10) which would be an identity matrix with 10 translation for each of the coordinate axes.
So all this boils down to the gl_Vertex attribute in the vertex shader being in the space that you have kept it in. If it is in object space then you need to multiply it with world matrix of that object to transform every vertex into world space. If it is already in world space, then you do not need to do anything else. In opengl, there is no concept of world space and both are concatenated into a worldview matirx a.k.a. modelview matrix. However, keeping a separate view/eye matrix is common in opengl apps. So what these guys were suggesting was to transform the object into eye space using worldview matrix and then transform it back into world space using inverse view/eye transform. I hope you get my point :slight_smile: .

you could just pass the vertex position into a (multi-)texture coordinate:

 glVertex3f(x,y,z);
 glMultiTexCoord3f(GL_TEXTURE_7, x,y,z);

if you do so, you will not need a vertex program, only a fragment program. the frag prog will have access to the interpolated coordinate- assuming that you do not apply any transformations to the vertex.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.