Left-handed and right-handed perspective matrix for Metal
func matrix_perspective_left_hand(fovyRadians fovy: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> matrix_float4x4 {
let ys = 1 / tanf(fovy * 0.5)
let xs = ys / aspectRatio
let zs = farZ / (nearZ - farZ)
return matrix_float4x4.init(columns:(vector_float4(xs, 0, 0, 0),
vector_float4( 0, ys, 0, 0),
vector_float4( 0, 0, -zs, 1),
vector_float4( 0, 0, zs * nearZ, 0)))
}
func makeLeftHandedPerspectiveMatrix(fovyRadians fovy: Float, aspectRatio: Float, nearZ near: Float, farZ far: Float) -> matrix_float4x4 {
let yScale = 1 / tan(fovy / 2)
let xScale = yScale / aspectRatio
let zScale = far / (far - near)
let wzScale = -zScale * near
let matrix = matrix_float4x4([
simd_float4(xScale, 0, 0, 0),
simd_float4(0, yScale, 0, 0),
simd_float4(0, 0, zScale, 1),
simd_float4(0, 0, wzScale, 0)
])
return matrix
}
func matrix_perspective_right_hand(fovyRadians fovy: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> matrix_float4x4 {
let ys = 1 / tanf(fovy * 0.5)
let xs = ys / aspectRatio
let zs = farZ / (nearZ - farZ)
return matrix_float4x4.init(columns:(vector_float4(xs, 0, 0, 0),
vector_float4( 0, ys, 0, 0),
vector_float4( 0, 0, zs, -1),
vector_float4( 0, 0, zs * nearZ, 0)))
}
func makeRightHandedPerspectiveMatrix(fovyRadians fovy: Float, aspectRatio: Float, nearZ near: Float, farZ far: Float) -> matrix_float4x4 {
let yScale = 1 / tan(fovy / 2)
let xScale = yScale / aspectRatio
let zScale = far / (far - near)
let wzScale = -zScale * near
let matrix = matrix_float4x4([
simd_float4(xScale, 0, 0, 0),
simd_float4(0, yScale, 0, 0),
simd_float4(0, 0, -zScale, -1),
simd_float4(0, 0, wzScale, 0)
])
return matrix
}