Quaternion Rotation Android

Meghna Dave
2 min readAug 29, 2023

--

Quaternions are a mathematical concept used to represent and manipulate rotations and orientations in 3D space. They were first introduced by Irish mathematician Sir William Rowan Hamilton in 1843.

What is Gimbal lock?

The loss of one degree of freedom in a three-dimensional space that occurs

When the axes of two of the three gimbals are driven into a parallel configuration. “Locking” the system into rotation in a degenerate two-dimensional space.

There is a solution to the gimbal lock problem: Use quaternions instead of Euler angles. Quaternions use a 4-dimensional mathematical object to represent 3D orientation. The additional component ensures that each possible orientation is uniquely represented, and avoids the gimbal lock problem.

Calculations for Quaternion Transformations Matrix

Kotlin Code snippet for Quaternion Transformation

fun QuaternionRotate(
vertices: ArrayList<Coordinates>,
theta: Double,
abtoX: Int,
abt0Y: Int,
abtoZ: Int
): ArrayList<Coordinates> {
val w = Math.cos(Math.toRadians(theta / 2.0))
val sin = Math.sin(Math.toRadians(theta / 2.0))
val d = abtoX.toDouble()
java.lang.Double.isNaN(d)
val x = sin * d
val sin2 = Math.sin(Math.toRadians(theta / 2.0))
val d2 = abtoY.toDouble()
java.lang.Double.isNaN(d2)
val y = sin2 * d2
val sin3 = Math.sin(Math.toRadians(theta / 2.0))
val d3 = abtoZ.toDouble()
java.lang.Double.isNaN(d3)
val z = sin3 * d3
val matrix: DoubleArray = GetIdentityMatrix()
matrix[0] = w * w + x * x - y * y - z * z
matrix[1] = x * 2.0 * y - w * 2.0 * z
matrix[2] = x * 2.0 * z + w * 2.0 * y
matrix[3] = 0.0
matrix[4] = x * 2.0 * y + w * 2.0 * z
matrix[5] = w * w + y * y - x * x - z * z
matrix[6] = y * 2.0 * z - w * 2.0 * x
matrix[7] = 0.0
matrix[8] = x * 2.0 * z - w * 2.0 * y
matrix[9] = y * 2.0 * z + 2.0 * w * x
matrix[10] = w * w + z * z - x * x - y * y
matrix[11] = 0.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 0.0
matrix[15] = 1.0
return transformation(vertices, matrix)
}

Check full code on https://github.com/MeghnaVaidya26/QuaternionRotation

--

--