I have a WebGL app and I'm using the J3DIMatrix4 class to calculate the Model View Perspective matrix (because that's what every tutorial does).
Now I want to figure out what object the mouse is on and I need to convert my mouse position to a ray in world space. I'm using the J3dIMath.js library and the following code to calculate my perspective matrix
this.perspectiveMatrix = new J3DIMatrix4();
this.perspectiveMatrix.perspective(30, canvas.clientWidth / canvas.clientHeight, 1, 10000);
this.perspectiveMatrix.lookat(0,0,7, 0,0,0, 0,1,0)
When it comes time to actually draw an object I mix that with the object's matrix:
this.mvpMatrix.load(this.perspectiveMatrix);
this.mvpMatrix.multiply(this.mvMatrix);
this.mvpMatrix.setUniform(gl, this.u_modelViewProjMatrixLoc, false);
And the vertex shader is a bog-standard
uniform mat4 u_modelViewProjMatrix;
attribute vec2 vTexCoord;
attribute vec4 vPosition;
varying vec2 v_texCoord;
void main()
{
gl_Position = u_modelViewProjMatrix * vPosition;
v_texCoord = vTexCoord;
}
I experimented with inverting the perspective matrix and using
var mat = new J3DIMatrix4()
mat.load(this.perspectiveMatrix)
mat.multiply(this.mvMatrix)
mat.invert()
var coord = new J3DIVector3(0.7, 0.5, 1)
coord.multVecMatrix(mat)
debug_log(coord)
//I picked [0.7,0.5,1] because I figured it likely represented an on-screen point in camera space.
Unfortunately, that gives me some pretty weird results like [8121,362, -8120]. I was expecting a result more in the neighborhood of [4,4,6]
I assume that is because the .perspective() call is creating a non-affine matrix. I guess I need something that is more like blender's camera object matrix that encodes the orientation and position of the "eyeball", but without the perspective adjustments.
Given the values I have chosen for my perspective and lookat, how would I construct an affine and invertible camera matrix? (which I would then use to calculate focal point and map from mouse coordinates to a point on the click ray)
Solutions will be judged on clarity and length (and if you depend on some external library other than J3DIMath, that will be added to your line count)
( the answer to How to get object in WebGL 3d space from a mouse click coordinate is mostly impenetrable because of its length and the fact that it depends on Jax )