webxr_math_utils.js (2554B)
1 // |matrix| - Float32Array, |input| - point-like dict (must have x, y, z, w) 2 let transform_point_by_matrix = function(matrix, input) { 3 return { 4 x : matrix[0] * input.x + matrix[4] * input.y + matrix[8] * input.z + matrix[12] * input.w, 5 y : matrix[1] * input.x + matrix[5] * input.y + matrix[9] * input.z + matrix[13] * input.w, 6 z : matrix[2] * input.x + matrix[6] * input.y + matrix[10] * input.z + matrix[14] * input.w, 7 w : matrix[3] * input.x + matrix[7] * input.y + matrix[11] * input.z + matrix[15] * input.w, 8 }; 9 } 10 11 // Creates a unit-length quaternion. 12 // |input| - point-like dict (must have x, y, z, w) 13 let normalize_quaternion = function(input) { 14 const length_squared = input.x * input.x + input.y * input.y + input.z * input.z + input.w * input.w; 15 const length = Math.sqrt(length_squared); 16 17 return {x : input.x / length, y : input.y / length, z : input.z / length, w : input.w / length}; 18 } 19 20 // Returns negated quaternion. 21 // |input| - point-like dict (must have x, y, z, w) 22 let flip_quaternion = function(input) { 23 return {x : -input.x, y : -input.y, z : -input.z, w : -input.w}; 24 } 25 26 // |input| - point-like dict (must have x, y, z, w) 27 let conjugate_quaternion = function(input) { 28 return {x : -input.x, y : -input.y, z : -input.z, w : input.w}; 29 } 30 31 let multiply_quaternions = function(q1, q2) { 32 return { 33 w : q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z, 34 x : q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y, 35 y : q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x, 36 z : q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w, 37 } 38 } 39 40 // |point| - point-like dict (must have x, y, z, w) 41 let normalize_perspective = function(point) { 42 if(point.w == 0 || point.w == 1) return point; 43 44 return { 45 x : point.x / point.w, 46 y : point.y / point.w, 47 z : point.z / point.w, 48 w : 1 49 }; 50 } 51 52 // |quaternion| - point-like dict (must have x, y, z, w), 53 // |input| - point-like dict (must have x, y, z, w) 54 let transform_point_by_quaternion = function(quaternion, input) { 55 const q_normalized = normalize_quaternion(quaternion); 56 const q_conj = conjugate_quaternion(q_normalized); 57 const p_in = normalize_perspective(input); 58 59 // construct a quaternion out of the point (take xyz & zero the real part). 60 const p = {x : p_in.x, y : p_in.y, z : p_in.z, w : 0}; 61 62 // transform the input point 63 const p_mul = multiply_quaternions( q_normalized, multiply_quaternions(p, q_conj) ); 64 65 // add back the w component of the input 66 return { x : p_mul.x, y : p_mul.y, z : p_mul.z, w : p_in.w }; 67 }