screenPointToRay method

Ray screenPointToRay(
  1. Offset point,
  2. Size viewport
)

Unprojects a screen point (logical pixels within viewport) into a world-space ray using the monoscopic view-projection — the desktop equivalent of GazePointer.ray.

Implementation

Ray screenPointToRay(Offset point, Size viewport) {
  final aspect = viewport.width / viewport.height;
  final inv = Matrix4.tryInvert(cameraRig.monoViewProjection(aspect));
  if (inv == null) {
    // Degenerate matrix: fall back to camera axes
    return Ray.originDirection(
      cameraRig.position.clone(),
      cameraRig.headTransform.forward,
    );
  }

  final ndx = 2.0 * point.dx / viewport.width - 1.0;
  final ndy = 1.0 - 2.0 * point.dy / viewport.height;

  final nearH = inv.transform(Vector4(ndx, ndy, -1, 1));
  final farH = inv.transform(Vector4(ndx, ndy, 1, 1));
  final nearP = Vector3(
    nearH.x / nearH.w,
    nearH.y / nearH.w,
    nearH.z / nearH.w,
  );
  final farP = Vector3(farH.x / farH.w, farH.y / farH.w, farH.z / farH.w);

  final dir = farP - nearP;
  if (dir.length2 < 1e-12) {
    return Ray.originDirection(nearP, cameraRig.headTransform.forward);
  }
  dir.normalize();
  return Ray.originDirection(nearP, dir);
}