Will777 February 2016

WebGL translation issue

I am new to WebGL. I am experimenting with the matrix operations to try various operations like rotation, reflection, scaling and translation. I am using the book "Interactive Computer Graphics, A top-down approach with WebGL (Seventh Edition)" and helper libraries to load the shaders.

All of these work fine except translation. I am drawing a simple 2D triangle (using clip coordinates for now to keep things simple) and trying to translate the triangle away from the origin -0.5 in the x-axis and -0.5 in the y-axis.

This is the code in the vertex shader:

<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;

void main()
{    
    mat4 translationMatrix = mat4( 
    1, 0, 0, -0.5,
    0, 1, 0, -0.5,
    0, 0, 1, 0,
    0, 0, 0, 1 );       

    gl_Position = translationMatrix * vPosition;
}
</script>

However, the triangle is skewed and not translated as I expected.

This is the code in my js file: var gl;

window.onload = function init()
{
    var canvas = document.getElementById( "gl-canvas" );
    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { 
        alert( "WebGL isn't available" );
    }

    var vertices = [-0.2, -0.2, 0, 0.2, 0.2, -0.2];

    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.clearColor( 1.0, 1.0, 1.0, 1.0 );

    //  Load shaders and initialize attribute buffers
    var program = initShaders( gl, "vertex-shader", "fragment-shader" );

    gl.useProgram( program );

    // Load the data into the GPU
    var bufferId = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );

   // Associate out shader variables with our data buffer 
   var vPosition = gl.getAttribLocation( program, "vPosition" );
   gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
   gl.enableVertexAttribArray( vPosition ); 

   render();
};

f        

Answers


Paul-Jan February 2016

The GLSL mat4() arguments are column-major, so you probably want to write

mat4 translationMatrix = mat4( 
1,    0,    0, 0,   // first column
0,    1,    0, 0,   // second column
0,    0,    1, 0,   // third column
-0.5, -0.5, 0, 1 ); // translation goes here :-) 

Post Status

Asked in February 2016
Viewed 3,303 times
Voted 4
Answered 1 times

Search




Leave an answer