Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Created November 17, 2023 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewolbrich/284d92eb3df5580cb635a50cbe49dab5 to your computer and use it in GitHub Desktop.
Save drewolbrich/284d92eb3df5580cb635a50cbe49dab5 to your computer and use it in GitHub Desktop.
SIMD look-at functions
import simd
/// Creates a 4x4 matrix that orients the +Z axis in the direction of `at`, and the
/// +Y axis toward `up`.
func simd_look(at: SIMD3<Float>, up: SIMD3<Float> = SIMD3<Float>(0, 1, 0)) -> simd_float4x4 {
let zAxis = normalize(at)
let xAxis = normalize(cross(up, zAxis))
let yAxis = normalize(cross(zAxis, xAxis))
return simd_float4x4(
SIMD4(xAxis, w: 0),
SIMD4(yAxis, w: 0),
SIMD4(zAxis, w: 0),
SIMD4(0, 0, 0, 1)
)
}
/// Creates a 4x4 matrix that positions the origin at `from`, orienting the +Z axis
/// so it points at `at`, and the +Y axis in the direction of `up`.
func simd_look(at: SIMD3<Float>, from: SIMD3<Float>, up: SIMD3<Float> = SIMD3<Float>(0, 1, 0)) -> simd_float4x4 {
let zAxis = normalize(at - from)
let xAxis = normalize(cross(up, zAxis))
let yAxis = normalize(cross(zAxis, xAxis))
return simd_float4x4(
SIMD4(xAxis, w: 0),
SIMD4(yAxis, w: 0),
SIMD4(zAxis, w: 0),
SIMD4(from, 1)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment