Original glm source code


g-truc/glm

Left-handed lookAt()


// Considering a scene where camera looks at an object with pre-defined up-vector in world coordinate.

using namespace Eigen;

Matrix4f lookAtLH(const Vector3f& camera, const Vector3f& object, const Vector3f worldUp)
{
	Eigen::Vector3f X = object - camera;
	X.normalize();

	Eigen::Vector3f Y = X.cross(worldUp);
	Y.normalize();

	Eigen::Vector3f Z = Y.cross(X);

	Eigen::Matrix4f result = Eigen::Matrix4f::Identity();

	result(0,0) = Y(0);
  result(1,0) = Y(1);
  result(2,0) = Y(2);
  result(3,0) = -Y.dot(camera);
  result(0,1) = Z(0);
  result(1,1) = Z(1);
  result(2,1) = Z(2);
  result(3,1) = -Z.dot(camera);
  result(0,2) = -X(0);
  result(1,2) = -X(1);
  result(2,2) = -X(2);
  result(3,2) = -X.dot(camera);

  return result;
}

Matrix4f lookAtRH(const Vector3f& camera, const Vector3f& object, const Vector3f worldUp)
{
	Eigen::Vector3f X = object - camera;
	X.normalize();

	Eigen::Vector3f Y = worldUp.cross(X);
	Y.normalize();

	Eigen::Vector3f Z = X.cross(Y);

	Eigen::Matrix4f result = Eigen::Matrix4f::Identity();

	result(0,0) = Y(0);
  result(1,0) = Y(1);
  result(2,0) = Y(2);
  result(3,0) = -Y.dot(camera);
  result(0,1) = Z(0);
  result(1,1) = Z(1);
  result(2,1) = Z(2);
  result(3,1) = -Z.dot(camera);
  result(0,2) = X(0);
  result(1,2) = X(1);
  result(2,2) = X(2);
  result(3,2) = -X.dot(camera);

  return result;
}

Understanding glm::lookAt()