四元數旋轉矩陣

``````s = sin(θ/2)
w = cos(θ/2)
a = s * x'
b = s * y'
c = s * z'
``````

（別忘了，這個投影軌跡會是個圓弧，是因為上頭限制了 w、a、b、c 間的關係，不同限制投影出來的軌跡就不會是這樣的圓弧。）

（這不單只是運用在幾何上，像電路分析時，也會將試著將某個待解的問題轉為複數計算，運算完成後再從複數轉換回想要的答案形式。）

``````const mat4 = {
...

const s = Math.sin(rad / 2);
// q = xi + yj + zk + w
const x = s * axis[0];
const y = s * axis[1];
const z = s * axis[2];
const w = Math.cos(rad / 2);

const x2 = x + x;
const y2 = y + y;
const z2 = z + z;

const xx = x * x2;
const yx = y * x2;
const yy = y * y2;
const zx = z * x2;
const zy = z * y2;
const zz = z * z2;
const wx = w * x2;
const wy = w * y2;
const wz = w * z2;
return [
1 - yy - zz, yx + wz, zx - wy, 0,
yx - wz, 1 - xx - zz, zy + wx, 0,
zx + wy, zy - wx, 1 - xx - yy, 0,
0, 0, 0, 1
];
}
};
``````

``````const z = 1 / Math.sqrt(2);
const axis = [z / Math.sqrt(2), z / Math.sqrt(2), z];
``````

``````let i = 0;
function drawCube() {
i++;
const rotation = mat4.quatRotation(axis, 0.025 * i);
renderer.uniformMatrix4fv('transformation', mat4.translate(rotation, 0.25, 0, 0));

renderer.clear();
renderer.bindBuffer(GL.ARRAY_BUFFER, vertBuffer);
renderer.bufferSubData(GL.ARRAY_BUFFER, 0, geometry.verteices);
renderer.render(cube);

requestAnimationFrame(drawCube);
}
``````