rectangleClosestPoint function

Vector3 rectangleClosestPoint(
  1. Vector3 center,
  2. Vector3 halfWidth,
  3. Vector3 halfHeight,
  4. Vector3 world,
  5. Vector3 mirror,
)

RectangleClosestPoint — the representative point for the specular lobe.

Implementation

Vector3 rectangleClosestPoint(
  Vector3 center,
  Vector3 halfWidth,
  Vector3 halfHeight,
  Vector3 world,
  Vector3 mirror,
) {
  final n = halfWidth.cross(halfHeight);
  final nLen = n.length;
  if (nLen < 1e-12) return center;
  n.scale(1.0 / nLen);

  final toPlane = center - world;
  final denom = mirror.dot(n);
  final Vector3 onPlane;
  if (denom.abs() < 1e-5) {
    onPlane = toPlane - n * toPlane.dot(n);
  } else {
    final t = toPlane.dot(n) / denom;
    onPlane = t > 0.0 ? mirror * t : toPlane - n * toPlane.dot(n);
  }

  final offset = onPlane - toPlane;
  final wLen2 = math.max(halfWidth.dot(halfWidth), 1e-12);
  final hLen2 = math.max(halfHeight.dot(halfHeight), 1e-12);
  final u = (offset.dot(halfWidth) / wLen2).clamp(-1.0, 1.0);
  final v = (offset.dot(halfHeight) / hLen2).clamp(-1.0, 1.0);
  return center + halfWidth * u + halfHeight * v;
}