[Solved]Picking system

Started by Andrew Alfazy, January 23, 2018, 10:55:50

Previous topic - Next topic

Andrew Alfazy

hi,
I've a problem with picking in 3d that's my code to get ray
public class Mouse3D {

	private static Vector3f ray;

	public static Vector3f GetRay() {
		Vector2f normlizedCoords = toNormlizedDeviceCoords(Mouse.GetMosuePos());
		Vector4f clipCoords = new Vector4f(normlizedCoords.x, normlizedCoords.y,
				-1, 1);
		Vector4f eyeCoords = toEyeCoords(clipCoords);
		ray = toWorldCoords(eyeCoords);
		return ray;
	}

	private static Vector2f toNormlizedDeviceCoords(Vector2f mousePos) {
		Vector2f pos = new Vector2f();
		pos.x = (float) ((2 * mousePos.x) / Main.getWidth() - 1);
		pos.y = (float) ((2 * mousePos.y) / Main.getHeigth() - 1);
		return pos;
	}

	private static Vector4f toEyeCoords(Vector4f clipCoords) {
		Matrix4f invertedProjection = View.getPm().invert();
		Vector4f eyeCoords = new Vector4f();
		invertedProjection.transform(clipCoords.x, clipCoords.y, clipCoords.z,
				clipCoords.w, eyeCoords);
		return new Vector4f((float) eyeCoords.x, (float) eyeCoords.y, -1, 1);
	}

	private static Vector3f toWorldCoords(Vector4f eyeCoords) {
		Matrix4f InvertedView = View.getVm().invert();
		Vector4f Ray = new Vector4f();
		InvertedView.transform(eyeCoords.x, eyeCoords.y, eyeCoords.z,
				eyeCoords.w, Ray);
		return new Vector3f((float) Ray.x, (float) Ray.y, (float) Ray.z)
				.normalize();
	}

}

and parts of my View class
public static void go3D() {
		rotR = (float) Math.toRadians(rotD);
		camX = (float) Math.cos(rotR) * zom + posX;
		camZ = (float) Math.sin(rotR) * zom + posZ;
		camY = posY + zom * 2;
		enable3D();
		viewMatrix.identity();
		pm = viewMatrix.setPerspective((float) Math.toRadians(FOV), ASPECT,
				NEAR, FAR);
		glMatrixMode(GL_PROJECTION);
		glLoadMatrixf(viewMatrix.get(fb));
		vm = viewMatrix.setLookAt(camX, camY, camZ, posX, posY, posZ, 0, 1, 0);
		glMatrixMode(GL_MODELVIEW);
		glLoadMatrixf(viewMatrix.get(fb));
	}
private static void enable3D() {
		if (WIREFRAME)
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		glDisable(GL_TEXTURE_2D);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_SHADE_MODEL);
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glEnable(GL_NORMALIZE);
		glEnable(GL_COLOR_MATERIAL);
		glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
		glShadeModel(GL_FLAT);
		glClearDepth(1);
	}

KaiHH

Since it looks like you are using JOML, there is a much shorter way to obtain the world-space ray of the mouse pointer. Please see Matrix4f.unprojectRay(). It is equivalent to two invocations of GLU's gluUnproject() with the near and far plane Z coordinate to compute a ray instead of a point in 3D. The matrix to call this method on must be the uninverted combined view-projection matrix.

Andrew Alfazy

thanks very much,I can't believe it is working very good! :o