import simd /// A perspective camera at `eye` looking at `target`. `fieldOfView` is vertical, in radians. public struct Camera: Sendable { public var eye: SIMD3 public var target: SIMD3 public var up: SIMD3 public var fieldOfView: Double public init(eye: SIMD3, target: SIMD3, up: SIMD3, fieldOfView: Double) { self.eye = eye self.target = target self.up = up self.fieldOfView = fieldOfView } /// The unit vector from `eye` toward `target`. public var viewDirection: SIMD3 { let d = target - eye return d / length(d) } /// World to clip space, Metal's: depth 0 at the near plane and 1 at the far plane, which are /// 1/100 and 100 times the distance from `eye` to `target`. public func viewProjection(aspect: Double) -> simd_double4x4 { let f = viewDirection let s = normalize(cross(f, up)) let u = cross(s, f) let view = simd_double4x4(rows: [ SIMD4(s.x, s.y, s.z, -dot(s, eye)), SIMD4(u.x, u.y, u.z, -dot(u, eye)), SIMD4(-f.x, -f.y, -f.z, dot(f, eye)), SIMD4(0, 0, 0, 1), ]) let distance = length(target - eye) let near = distance / 100, far = distance * 100 let y = 1 / tan(fieldOfView / 2), z = far / (near - far) let projection = simd_double4x4(columns: ( SIMD4(y / aspect, 0, 0, 0), SIMD4(0, y, 0, 0), SIMD4(0, 0, z, -1), SIMD4(0, 0, z * near, 0) )) return projection * view } } extension Camera { /// The camera moved around `target` at its distance so that the scene appears to turn by /// `length(angles)` radians: `angles.x` about the camera's up axis, carrying the near side /// rightward on screen, and `angles.y` about its right axis, carrying the near side downward. /// The returned `up` is a unit vector perpendicular to the view direction, at any angle. public func orbited(by angles: SIMD2) -> Camera { let f = viewDirection let s = normalize(cross(f, up)) let u = cross(s, f) let angle = length(angles) guard angle > 0 else { return Camera(eye: eye, target: target, up: u, fieldOfView: fieldOfView) } // The camera turns the opposite way to the scene. let turn = simd_quatd(angle: -angle, axis: (angles.x * u + angles.y * s) / angle) let turnedF = turn.act(f), turnedU = turn.act(u) return Camera(eye: target + turn.act(eye - target), target: target, up: normalize(turnedU - dot(turnedU, turnedF) * turnedF), fieldOfView: fieldOfView) } /// The camera with its field of view narrowed by `scale`, as a pinch of that scale magnifies /// the image, and clamped to `range`. public func zoomed(by scale: Double, within range: ClosedRange) -> Camera { let fieldOfView = min(max(2 * atan(tan(self.fieldOfView / 2) / scale), range.lowerBound), range.upperBound) return Camera(eye: eye, target: target, up: up, fieldOfView: fieldOfView) } }