Search code examples
javaandroidopengl-esglslshader

Get eye position coordinates in OpenGL ES


The 3D application has a static camera:

float eyeX = 0.0f;
float eyeY = 0.0f;
float eyeZ = 0.0f;
Matrix.setLookAtM(viewMatrix, 0, eyeX, eyeY, eyeZ,
        0f, 0f, -4f, 0f, 1.0f, 0.0f)

Then this vector is used for the eye coordinates in the shader?:

const vec4 eyePos = vec4(0.0, 0.0, 0.0, 0.0);

Or need additional transformations?

Note: Read the post What exactly are eye space coordinates? but I still have doubts because my fog shader is not working. In this shader, the distance from the observer to the object is calculated:

uniform mat4 u_vMatrix;
in vec4 a_position;
out float v_eyeDist;
const vec4 eyePos = vec4(0.0, 0.0, 0.0, 0.0);
...
void main() {
    ...
    vec4 viewPos = u_vMatrix * a_position;
    v_eyeDist = sqrt(pow((viewPos.x - eyePos.x), 2.0) + 
        pow((viewPos.y - eyePos.y), 2.0) + 
        pow((viewPos.z - eyePos.z), 2.0));
    ...
}

Thanks in advance!

Solution: On the advice Rabbid76, I used length() function, as well as a model-view matrix.

uniform mat4 u_mvMatrix; // model-view matrix
in vec4 a_position;
out float v_eyeDist;
...
void main() {
    ...
    vec4 viewPos = u_mvMatrix * a_position;
    v_eyeDist = length(viewPos);
    ...
}

Solution

  • The view matrix transforms from world space to view space. The view space is the local system which is defined by the point of view onto the scene. The position of the view, the line of sight and the upwards direction of the view, define a coordinate system relative to the world coordinate system.
    The origin of the view space is the "eye" position, thus in view space the "eye" position is at (0, 0, 0).

    In glsl the distance of to points can be computed by the built-in function distance. It is sufficient to compute the Euclidean distance of the componets x, y, z (Cartesian coordinates), since the w components (Homogeneous coordinates) is 1 for both vectors. e.g.:

    v_eyeDist = distance(viewPos.xyz, eyePos.xyz);
    

    Since the the point of view (the position of the camera) is (0, 0, 0) in viespace, it is sufficient to compute the length of the view vector, to compute the distance. The distance of a point to the origin of the coordinate system is the length of the vector to the point. In glsl this can be computed by the built-in function length. In this case it is important, to compute the length of the components x, y, z, and to exclude the w component. Including the w component would lead to wrong results:

    v_eyeDist = length(viewPos.xyz);