Skip to content

Commit

Permalink
feature: add vec3OrthoNormalize
Browse files Browse the repository at this point in the history
  • Loading branch information
0b5vr committed Jan 30, 2022
1 parent e259cdc commit a7872da
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/math/vec3/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export type { RawVector3 } from './RawVector3';
export { vec3ApplyMatrix4 } from './vec3ApplyMatrix4';
export { vec3ApplyQuaternion } from './vec3ApplyQuaternion';
export { vec3Cross } from './vec3Cross';
export { vec3OrthoNormalize } from './vec3OrthoNormalize';
26 changes: 26 additions & 0 deletions src/math/vec3/tests/vec3OrthoNormalize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import '../../../tests/matchers/toBeCloseToArray';
import { vec3OrthoNormalize } from '../vec3OrthoNormalize';
import type { RawVector3 } from '../RawVector3';

describe( 'vec3OrthoNormalize', () => {
it( 'returns a orthogonal tangent', () => {
const normal: RawVector3 = [ 0.0, 0.0, 5.0 ];
const tangent: RawVector3 = [ 1.0, 1.0, 1.0 ];
const subject = vec3OrthoNormalize( normal, tangent );

expect( subject.normal ).toBeCloseToArray( [ 0.0, 0.0, 1.0 ] );
expect( subject.tangent ).toBeCloseToArray( [ 0.707, 0.707, 0.0 ] );
expect( subject.binormal ).toBeCloseToArray( [ -0.707, 0.707, 0.0 ] );
} );

it( 'returns a orthogonal tangent and binormal', () => {
const normal: RawVector3 = [ 0.0, 0.0, 5.0 ];
const tangent: RawVector3 = [ 1.0, 1.0, 1.0 ];
const binormal: RawVector3 = [ 0.0, -1.0, 0.0 ];
const subject = vec3OrthoNormalize( normal, tangent, binormal );

expect( subject.normal ).toBeCloseToArray( [ 0.0, 0.0, 1.0 ] );
expect( subject.tangent ).toBeCloseToArray( [ 0.707, 0.707, 0.0 ] );
expect( subject.binormal ).toBeCloseToArray( [ 0.707, -0.707, 0.0 ] );
} );
} );
33 changes: 33 additions & 0 deletions src/math/vec3/vec3OrthoNormalize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { vec3Cross } from '.';
import { vecDot, vecNeg, vecNormalize, vecScale, vecSub } from '..';
import type { RawVector3 } from './RawVector3';

/**
* Return a tangent which is orthogonal to normal.
* If binormal is specified, it is also returned and it's orthogonal to both normal and tangent.
*/
export function vec3OrthoNormalize(
normal: RawVector3,
tangent: RawVector3,
binormal?: RawVector3,
): {
normal: RawVector3,
tangent: RawVector3,
binormal: RawVector3,
} {
const n = vecNormalize( normal );

const dotNT = vecDot( n, tangent );
const t = vecNormalize( vecSub( tangent, vecScale( n, dotNT ) ) );

let b = vec3Cross( n, t );
if ( binormal && vecDot( b, binormal ) < 0.0 ) {
b = vecNeg( b );
}

return {
normal: n,
tangent: t,
binormal: b,
};
}

0 comments on commit a7872da

Please sign in to comment.