user3578847
user3578847

Reputation: 447

Shader ignoring position variable

I have a plane with the following shaders:

<script type="x-shader/x-vertex" id="vertexshader">

    varying vec3 col;

    void main()
    {
        col         = vec3( position.z, position.z, 1 );
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );   
    }

</script>

<script type="x-shader/x-fragment" id="fragmentshader">

    varying vec3 col;   

    void main()
    {
        // set color for the current vertex
        gl_FragColor = vec4(col, 1);
    }

</script>

I'm moving the plane away from the camera like this:

function renderFrame()
{
    cube.position.z -= 1;
    requestAnimationFrame( renderFrame );
    renderer.render(scene, camera);
};

The problem is that I would assume since the cube is moving, the fragment shaders position value would change but it doesn't. Doesn't the 'position' variable passes objects current location in 3D space? If not, how can I detect it's location and rotation or I would have to pass this information manually to shader using uniform variable?

Working example: http://webgl.demised.net/experiments/003_Shaders.php

Also, do shaders execute once on initialization or on each frame?

Upvotes: 0

Views: 220

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

The position variable in the vertex shader is a vertex attribute. Vertex attributes are usually read from a vertex buffer, which resides in GPU memory. Due to that, vertex data should be changed as little as possible to avoid the potentially costly data transfer to GPU memory. That's why translations and rotations of objects are not performed by changing vertex buffer data. Instead, the uniform modelViewMatrix is used. For more complex objects, transfering a single matrix is cheaper than transfering the entire model.

The model view matrix is the model matrix (which is basically the translation of the plane) combined with the view matrix (which arranges the camera in the scene). It is not possible to get the plane position from this matrix. However, you could get the distance to the camera along the camera's view direction. This would be the entry in the third row, fourth column. Try to calculate your color based on this value.

Shaders are executed many times. Every vertex that is rendered issues a call of the vertex shader. Every filled fragment issues a call of the fragment shader. This happens every time the image is rendered (i.e. every frame).

Upvotes: 2

Related Questions