Skip to content

Commit

Permalink
feature: mat3FromQuaternion
Browse files Browse the repository at this point in the history
  • Loading branch information
0b5vr committed Feb 6, 2022
1 parent c73ee64 commit c7fbdad
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/math/mat3/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { mat3FromMat4 } from './mat3FromMat4';
export { mat3FromMat4Transpose } from './mat3FromMat4Transpose';
export { mat3FromQuaternion } from './mat3FromQuaternion';
export { mat3Inverse } from './mat3Inverse';
export { mat3Multiply } from './mat3Multiply';
export { mat3Transpose } from './mat3Transpose';
Expand Down
22 changes: 22 additions & 0 deletions src/math/mat3/mat3FromQuaternion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { RawMatrix3 } from './RawMatrix3';
import type { RawQuaternion } from '../quat/RawQuaternion';

/**
* Convert a quaternion into a matrix3.
*
* Yoinked from Three.js.
*
* See: https://threejs.org/docs/#api/en/math/Matrix4.makeRotationFromQuaternion
*/
export function mat3FromQuaternion( quat: RawQuaternion ): RawMatrix3 {
const x = quat[ 0 ];
const y = quat[ 1 ];
const z = quat[ 2 ];
const w = quat[ 3 ];

return [
1.0 - 2.0 * y * y - 2.0 * z * z, 2.0 * x * y + 2.0 * z * w, 2.0 * x * z - 2.0 * y * w,
2.0 * x * y - 2.0 * z * w, 1.0 - 2.0 * x * x - 2.0 * z * z, 2.0 * y * z + 2.0 * x * w,
2.0 * x * z + 2.0 * y * w, 2.0 * y * z - 2.0 * x * w, 1.0 - 2.0 * x * x - 2.0 * y * y,
];
}
16 changes: 16 additions & 0 deletions src/math/mat3/tests/mat3FromQuaternion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import '../../../tests/matchers/toBeCloseToArray';
import { mat3FromQuaternion } from '../mat3FromQuaternion';
import type { RawQuaternion } from '../../quat/RawQuaternion';

describe( 'mat3FromQuaternion', () => {
it( 'returns a matrix3 made out of a quaternion', () => {
const quat: RawQuaternion = [ 0.189, 0.378, 0.567, 0.707 ];
const subject = mat3FromQuaternion( quat );

expect( subject ).toBeCloseToArray( [
0.071, 0.945, -0.320,
-0.659, 0.286, 0.696,
0.749, 0.161, 0.643,
] );
} );
} );

0 comments on commit c7fbdad

Please sign in to comment.