Casting a picking ray from mouse with a unique camera setup

Started by
1 comment, last by slayemin 10 years, 1 month ago

Hi all,

I've found a lot of algos online that tell how to cast a ray directly into the screen from the mouse position. My problem is, I am dealing with code that has a legacy camera setup, and the setup is a little bit unique. As a result, I'm able to get the DIRECTION of the picking ray accurately, but I'm not able to get a good origin point.

Here is the code I'm using to generate the picking ray (mPMatrix and mVMatrix are stored copies of the projection and view matrix. The world matrix is identity, I haven't even gotten that far yet).


void Game::MouseToRay(float theX, float theY)
{
	theY=gG.HeightF()-theY;

	Matrix aProjection=mPMatrix;

	Vector aV;
	aV.mX=(((2.0f*theX)/mDrawViewport.mWidth)-1)/aProjection.mData._11;
	aV.mY=-(((2.0f*theY)/mDrawViewport.mHeight)-1)/aProjection.mData._22;
	aV.mZ=1.0f;

	Matrix aView=mVMatrix;
	aView.Invert();

	Vector aRayOrigin;
	Vector aRayDir;
	aRayDir.mX  = aV.mX*aView.mData._11 + aV.mY*aView.mData._21 + aV.mZ*aView.mData._31;
	aRayDir.mY  = aV.mX*aView.mData._12 + aV.mY*aView.mData._22 + aV.mZ*aView.mData._32;
	aRayDir.mZ  = aV.mX*aView.mData._13 + aV.mY*aView.mData._23 + aV.mZ*aView.mData._33;
	aRayOrigin.mX = aView.mData._41;
	aRayOrigin.mY = aView.mData._42;
	aRayOrigin.mZ = aView.mData._43;

	mProjected.mPos[0]=aRayOrigin;
	mProjected.mPos[1]=aRayOrigin+(aRayDir*100);
}


This code produces a 100% accurate direction, but it produces an origin that gets less and less accurate the further the mouse is from pointing right at 0,0,0. Aspect ratio also seems to be an issue, in that the inaccuracy seems to be different along the y axis. I am not sure what is missing.

Now, as I said, the camera code I'm using is unorthodox, but I don't have the option to not use it. I already had a lot of problems with the camera code and setting fog values (I had to manually add a tweak), so I expect the secret is in there. Here is what the camera setup code for the scene looks like:


void Set3DCamera(float theCameraX, float theCameraY, float theCameraZ,
	float theLookatX, float theLookatY, float theLookatZ,
	float theUpVectorX, float theUpVectorY, float theUpVectorZ, float theFOV)
{
	float aWorldMatrix[4][4];
	float aViewMatrix[4][4];
	IDENTITYMATRIX(aWorldMatrix);
	SCALEMATRIX(aWorldMatrix,1,1,-1);

	theCameraZ = -theCameraZ;
	theLookatZ = -theLookatZ;
	theUpVectorZ = -theUpVectorZ;

	// We translate the world the opposite direction of the camera (relatively speakng, of course)
	TRANSLATEMATRIX(aWorldMatrix,-theCameraX,-theCameraY,-theCameraZ);

	//
	// Look-at matrix vectors
	//
	float aLookatVectorX = theLookatX-theCameraX;
	float aLookatVectorY = theLookatY-theCameraY;
	float aLookatVectorZ = theLookatZ-theCameraZ;

	// Side vector (UP cross LOOKAT)
	float aSideVectorX = theUpVectorY * aLookatVectorZ - theUpVectorZ * aLookatVectorY;
	float aSideVectorY = theUpVectorZ * aLookatVectorX - theUpVectorX * aLookatVectorZ;
	float aSideVectorZ = theUpVectorX * aLookatVectorY - theUpVectorY * aLookatVectorX;

	// Correct the UP vector (LOOKAT cross SIDE)
	theUpVectorX = aLookatVectorY * aSideVectorZ - aLookatVectorZ * aSideVectorY;
	theUpVectorY = aLookatVectorZ * aSideVectorX - aLookatVectorX * aSideVectorZ;
	theUpVectorZ = aLookatVectorX * aSideVectorY - aLookatVectorY * aSideVectorX;

	// Normalize the lookat vector
	float len = (float)sqrt(aLookatVectorX*aLookatVectorX + aLookatVectorY*aLookatVectorY + aLookatVectorZ*aLookatVectorZ);
	aLookatVectorX /= len;
	aLookatVectorY /= len;
	aLookatVectorZ /= len;

	// Normalize side vector
	len = (float)sqrt(aSideVectorX*aSideVectorX + aSideVectorY*aSideVectorY + aSideVectorZ*aSideVectorZ);
	aSideVectorX /= len;
	aSideVectorY /= len;
	aSideVectorZ /= len;

	// Normalize the up vector
	len = (float)sqrt(theUpVectorX*theUpVectorX + theUpVectorY*theUpVectorY + theUpVectorZ*theUpVectorZ);
	theUpVectorX /= len;
	theUpVectorY /= len;
	theUpVectorZ /= len;

	//
	// The view matrix (look-at)
	//
	aViewMatrix[0][0]=-aSideVectorX;
	aViewMatrix[1][0]=-aSideVectorY;
	aViewMatrix[2][0]=-aSideVectorZ;
	aViewMatrix[3][0]=0;

	aViewMatrix[0][1]=-theUpVectorX;
	aViewMatrix[1][1]=-theUpVectorY;
	aViewMatrix[2][1]=-theUpVectorZ;
	aViewMatrix[3][1]=0;

	aViewMatrix[0][2]=aLookatVectorX;
	aViewMatrix[1][2]=aLookatVectorY;
	aViewMatrix[2][2]=aLookatVectorZ;
	aViewMatrix[3][2]=0;

	aViewMatrix[0][3]=0;
	aViewMatrix[1][3]=0;
	aViewMatrix[2][3]=0;
	aViewMatrix[3][3]=1;


	// Combine the world and view (GL doesn't support View matrices)
	MULTIPLYMATRIX(aWorldMatrix,aViewMatrix);
	SetMatrix(1,&aWorldMatrix);

	//
	// Perspective projection matrix (as per Blinn)
	//

	float aAspect = (float)gPageWidth/(float)gPageHeight;
	float aNear = gZNear;	// This was 1.0... is it hurting anything?  I made it 0.5f so things could be closer to the camera without 
	float aFar = GetZDepth();

	float aWidth=COS(theFOV / 2.0f);
	float aHeight=COS(theFOV / 2.0f);
	if (aAspect > 1.0) aWidth /= aAspect;
	else aHeight *= aAspect;


	//aHeight/=.75f;

	float s  = SIN(theFOV / 2.0f);
	float d  = 1.0f - aNear/aFar;

	float aMatrix[4][4];
	aMatrix[0][0]=aWidth;
	aMatrix[1][0]=0;
	aMatrix[2][0]=0;
	aMatrix[3][0]=0;
	aMatrix[0][1]=0;
	aMatrix[1][1]=aHeight;
	aMatrix[2][1]=0;
	aMatrix[3][1]=0;
	aMatrix[0][2]=0;
	aMatrix[1][2]=0;
	aMatrix[2][2]=s/d;
	aMatrix[3][2]=-(s * aNear / d);
	aMatrix[0][3]=0;
	aMatrix[1][3]=0;
	aMatrix[2][3]=s;
	aMatrix[3][3]=0;

	gFogTweak=s;

	SetMatrix(2,&aMatrix);
}

See that line gFogTweak near the end? I had to add that line to make fog work correctly-- it was the exact same situation I'm dealing with here, where there were lots of answers on the web, but none of them worked correctly. I believe that something about how that projection matrix is set up is what's throwing off my picking ray.

I'm only middling-strong on math and I've hit a wall. And this point all I am able to do is try random things in the hopes that one of them will work, but none of them will. If anyone can see the problem, or what I need to add into that MouseToRay function to make this all line up, you will have my infinite gratitude, and a "special thanks" line in the credits of the game I'm working on!

Advertisement

mProjected.mPos[1]=aRayOrigin+(aRayDir*100);

I'm not where I can get to my references at the moment, so I can't check on the vector-matrix mult. However, a quick comment, if mPos[1] is supposed to be the ray direction, that doesn't look at all right. (EDIT: Up to the point, your pos and dir calcs look good.) You don't show how you use your results, but normally the direction vector should be a unit vector (i.e., normalized). Why aren't you using the direction vector you calculate, and why do you use "100"?

EDIT: You shouldn't be getting any reasonable results otherwise, but is the mouse position in client coords?

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

Here's what I did. The code & comments describe exactly what's going on... So, you can borrow ideas from here or port it over to your unorthodox camera code:


/// <summary>
/// This takes a position in screen coordinates and converts it to a coordinate in 3D space.
/// This works by shooting a ray from the camera position to the mouse position and finding a collision point.
/// </summary>
/// <param name="Position">Screen coordinate position</param>
/// <returns>A ray you can use to intersect with</returns>
public Ray ScreenToWorld(Vector2 Position)
{
	//0. Convert our coordinate into NDC space coordinates (NDC = Normalized Device Coordinates. Range: X [0-1], Y [0-1] )
	Vector2 NDC = new Vector2(Position.X / m_viewport.Width, Position.Y / m_viewport.Height);

	//1. Let's pretend we're at (0,0,0) looking down (0,0,-1). We need to get our near plane corners!
	//   To do this, we'll create a fake camera to get a new view matrix. We already have our projection matrix,
	//   so, once we have both matricies, we can build a frustum at the origin looking down the Z axis.
	Matrix fakeView = Matrix.CreateLookAt(Vector3.Zero, Vector3.UnitX, Vector3.Up);
	BoundingFrustum fakeFrustum = new BoundingFrustum(fakeView * m_projection);

	//2. Now, we can grab the corners from our fake frustum and use our NDC coordinate to figure out where it should be.
	//   We know that the first four verticies are the near plane corners, starting from top left and going clockwise.
	Vector3[] fakeCorners = fakeFrustum.GetCorners();

	//get the width and height of the near and far planes from its corners, so that we can scale it by the NDC
	Vector3 nearSize = fakeCorners[2] - fakeCorners[0];
	Vector3 farSize = fakeCorners[6] - fakeCorners[4];

	Vector3 NearPt = new Vector3(fakeCorners[0].X + nearSize.X * NDC.X, fakeCorners[0].Y + nearSize.Y * NDC.Y, fakeCorners[0].Z + nearSize.Z * NDC.X);
	Vector3 FarPt = new Vector3(fakeCorners[4].X + farSize.X * NDC.X, fakeCorners[4].Y + farSize.Y * NDC.Y, fakeCorners[4].Z + farSize.Z * NDC.X);

	//3. Alright, now we've got two end points in UNTRANSFORMED 3D space on both the near plane and the far plane.
	//   In order for this to be of an use to us, we have to ROTATE and TRANSLATE our points based on our camera
	//   orientation and position, respectively.
	Vector3 finalNearPt = Vector3.Transform(NearPt, m_rotation) + m_position;
	Vector3 finalFarPt = Vector3.Transform(FarPt, m_rotation) + m_position;

	//4. We're going to need to return a ray which has a position at the near plane coordinate and points towards the
	//   far plane coordinate. That's pretty easy to do.
	Vector3 dirVec = (finalFarPt - finalNearPt);
	dirVec.Normalize();

	return new Ray(finalNearPt, dirVec);
}

This topic is closed to new replies.

Advertisement