0
// Upload Projection, ModelView matrices
gl.uniformMatrix4fv(shaderProgram.uMVMatrix, false, pMVMatrix);
gl.uniformMatrix4fv(shaderProgram.uPMatrix, false, perspM);

In the above lines, I understand that the projection matrix and modelview matrix are being uploaded. I would like to know the math behind this.

I have some 3d vertices (overlayvertices) which are later passed in this manner:

// Upload overlay vertices                      
gl.bindBuffer(gl.ARRAY_BUFFER, overlayVertices[elementIndex]);
gl.vertexAttribPointer(shaderProgram.aVertexPosition, 3, gl.FLOAT,false, 0, 0);

where overlayvertices[i] is a 4*1 array with x,y,z,1

The final drawing happens on the frame of a particular camera based on which the modelview and projection matrix is determined. I would like to manually get the transformed vertices in the camera frame. i.e, (x,y,1). I later download the data within each frame and hence the x,y should be pixel coordinates. Since this happens internally in webgl, I am not able to retrieve this information.

genpfault
  • 51,148
  • 11
  • 85
  • 139
userJS
  • 119
  • 1
  • 14
  • [This is covered here](http://stackoverflow.com/questions/28286057/trying-to-understand-the-math-behind-the-perspective-matrix-in-webgl/28301213#28301213) as well as in [this article](http://webglfundamentals.org/webgl/lessons/webgl-3d-perspective.html) and the articles linked from it. – gman Mar 05 '15 at 10:43

1 Answers1

0

The missing piece (in your question) is the vertex shader being used when drawing. This vertex shader will take the two matrices and use them to transform the vertex. How exactly depends on the shader, but in the majority of cases the expression is

gl_Position = P * MV * vertex_position

And that's exactly the calculation you want to reproduct that transformation outside of OpenGL, namely its vertex shader stage.

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • I tried using the above equation. My concern is the dimensions. I have a matrix P which is called perspM and it is 4*4 and the MV matrix is also 4*4. Vertex position is x,y,z,1. Hence the gl_position I get back is 4*1. I understand the concept of homogeneous coordinates but I should get back a 3*1 matrix for that right, Since I need 2d coordinates? – userJS Mar 05 '15 at 02:26
  • @userJS: Getting a 4 element vector out of the transformation is the right result. Then you apply the homogenous divide `r_ = r / r.w`; then `r_.x, r_.y` hold the normalized viewport coordinates. – datenwolf Mar 05 '15 at 11:45