Rotation matrix for Metal

심심한 프로그래머
1 min readApr 26, 2023

--

func makeRotationMatrix(angleRadians: Float, axis: simd_float3) -> matrix_float4x4 {
let normalizedAxis = normalize(axis)
let cosAngle = cos(angleRadians)
let sinAngle = sin(angleRadians)
let oneMinusCosAngle = 1 - cosAngle

let row0 = simd_float4(
cosAngle + normalizedAxis.x * normalizedAxis.x * oneMinusCosAngle,
normalizedAxis.x * normalizedAxis.y * oneMinusCosAngle - normalizedAxis.z * sinAngle,
normalizedAxis.x * normalizedAxis.z * oneMinusCosAngle + normalizedAxis.y * sinAngle,
0
)

let row1 = simd_float4(
normalizedAxis.y * normalizedAxis.x * oneMinusCosAngle + normalizedAxis.z * sinAngle,
cosAngle + normalizedAxis.y * normalizedAxis.y * oneMinusCosAngle,
normalizedAxis.y * normalizedAxis.z * oneMinusCosAngle - normalizedAxis.x * sinAngle,
0
)

let row2 = simd_float4(
normalizedAxis.z * normalizedAxis.x * oneMinusCosAngle - normalizedAxis.y * sinAngle,
normalizedAxis.z * normalizedAxis.y * oneMinusCosAngle + normalizedAxis.x * sinAngle,
cosAngle + normalizedAxis.z * normalizedAxis.z * oneMinusCosAngle,
0
)

let row3 = simd_float4(0, 0, 0, 1)

let matrix = matrix_float4x4(rows: [row0, row1, row2, row3])
return matrix
}
func makeQuaternionRotationMatrix(angleRadians: Float, axis: simd_float3) -> matrix_float4x4 {
let normalizedAxis = normalize(axis)
let halfAngle = angleRadians / 2
let w = cos(halfAngle)
let sinHalfAngle = sin(halfAngle)
let x = sinHalfAngle * normalizedAxis.x
let y = sinHalfAngle * normalizedAxis.y
let z = sinHalfAngle * normalizedAxis.z

let quaternion = simd_quatf(ix: x, iy: y, iz: z, r: w)
let rotationMatrix = matrix_float4x4(quaternion)

return rotationMatrix
}

--

--

No responses yet