AnimationUtils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { Quaternion } from '../math/Quaternion.js';
  2. import { AdditiveAnimationBlendMode } from '../constants.js';
  3. import { isTypedArray } from '../utils.js';
  4. /**
  5. * Converts an array to a specific type.
  6. *
  7. * @param {TypedArray|Array} array - The array to convert.
  8. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  9. * @return {TypedArray} The converted array.
  10. */
  11. function convertArray( array, type ) {
  12. if ( ! array || array.constructor === type ) return array;
  13. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14. return new type( array ); // create typed array
  15. }
  16. return Array.prototype.slice.call( array ); // create Array
  17. }
  18. /**
  19. * Returns an array by which times and values can be sorted.
  20. *
  21. * @param {Array<number>} times - The keyframe time values.
  22. * @return {Array<number>} The array.
  23. */
  24. function getKeyframeOrder( times ) {
  25. function compareTime( i, j ) {
  26. return times[ i ] - times[ j ];
  27. }
  28. const n = times.length;
  29. const result = new Array( n );
  30. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  31. result.sort( compareTime );
  32. return result;
  33. }
  34. /**
  35. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  36. *
  37. * @param {Array<number>} values - The values to sort.
  38. * @param {number} stride - The stride.
  39. * @param {Array<number>} order - The sort order.
  40. * @return {Array<number>} The sorted values.
  41. */
  42. function sortedArray( values, stride, order ) {
  43. const nValues = values.length;
  44. const result = new values.constructor( nValues );
  45. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  46. const srcOffset = order[ i ] * stride;
  47. for ( let j = 0; j !== stride; ++ j ) {
  48. result[ dstOffset ++ ] = values[ srcOffset + j ];
  49. }
  50. }
  51. return result;
  52. }
  53. /**
  54. * Used for parsing AOS keyframe formats.
  55. *
  56. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  57. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  58. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  59. * @param {string} valuePropertyName - The name of the property to use.
  60. */
  61. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  62. let i = 1, key = jsonKeys[ 0 ];
  63. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  64. key = jsonKeys[ i ++ ];
  65. }
  66. if ( key === undefined ) return; // no data
  67. let value = key[ valuePropertyName ];
  68. if ( value === undefined ) return; // no data
  69. if ( Array.isArray( value ) ) {
  70. do {
  71. value = key[ valuePropertyName ];
  72. if ( value !== undefined ) {
  73. times.push( key.time );
  74. values.push( ...value ); // push all elements
  75. }
  76. key = jsonKeys[ i ++ ];
  77. } while ( key !== undefined );
  78. } else if ( value.toArray !== undefined ) {
  79. // ...assume THREE.Math-ish
  80. do {
  81. value = key[ valuePropertyName ];
  82. if ( value !== undefined ) {
  83. times.push( key.time );
  84. value.toArray( values, values.length );
  85. }
  86. key = jsonKeys[ i ++ ];
  87. } while ( key !== undefined );
  88. } else {
  89. // otherwise push as-is
  90. do {
  91. value = key[ valuePropertyName ];
  92. if ( value !== undefined ) {
  93. times.push( key.time );
  94. values.push( value );
  95. }
  96. key = jsonKeys[ i ++ ];
  97. } while ( key !== undefined );
  98. }
  99. }
  100. /**
  101. * Creates a new clip, containing only the segment of the original clip between the given frames.
  102. *
  103. * @param {AnimationClip} sourceClip - The values to sort.
  104. * @param {string} name - The name of the clip.
  105. * @param {number} startFrame - The start frame.
  106. * @param {number} endFrame - The end frame.
  107. * @param {number} [fps=30] - The FPS.
  108. * @return {AnimationClip} The new sub clip.
  109. */
  110. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  111. const clip = sourceClip.clone();
  112. clip.name = name;
  113. const tracks = [];
  114. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  115. const track = clip.tracks[ i ];
  116. const valueSize = track.getValueSize();
  117. const times = [];
  118. const values = [];
  119. for ( let j = 0; j < track.times.length; ++ j ) {
  120. const frame = track.times[ j ] * fps;
  121. if ( frame < startFrame || frame >= endFrame ) continue;
  122. times.push( track.times[ j ] );
  123. for ( let k = 0; k < valueSize; ++ k ) {
  124. values.push( track.values[ j * valueSize + k ] );
  125. }
  126. }
  127. if ( times.length === 0 ) continue;
  128. track.times = convertArray( times, track.times.constructor );
  129. track.values = convertArray( values, track.values.constructor );
  130. tracks.push( track );
  131. }
  132. clip.tracks = tracks;
  133. // find minimum .times value across all tracks in the trimmed clip
  134. let minStartTime = Infinity;
  135. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  136. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  137. minStartTime = clip.tracks[ i ].times[ 0 ];
  138. }
  139. }
  140. // shift all tracks such that clip begins at t=0
  141. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  142. clip.tracks[ i ].shift( - 1 * minStartTime );
  143. }
  144. clip.resetDuration();
  145. return clip;
  146. }
  147. /**
  148. * Converts the keyframes of the given animation clip to an additive format.
  149. *
  150. * @param {AnimationClip} targetClip - The clip to make additive.
  151. * @param {number} [referenceFrame=0] - The reference frame.
  152. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  153. * @param {number} [fps=30] - The FPS.
  154. * @return {AnimationClip} The updated clip which is now additive.
  155. */
  156. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  157. if ( fps <= 0 ) fps = 30;
  158. const numTracks = referenceClip.tracks.length;
  159. const referenceTime = referenceFrame / fps;
  160. // Make each track's values relative to the values at the reference frame
  161. for ( let i = 0; i < numTracks; ++ i ) {
  162. const referenceTrack = referenceClip.tracks[ i ];
  163. const referenceTrackType = referenceTrack.ValueTypeName;
  164. // Skip this track if it's non-numeric
  165. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  166. // Find the track in the target clip whose name and type matches the reference track
  167. const targetTrack = targetClip.tracks.find( function ( track ) {
  168. return track.name === referenceTrack.name
  169. && track.ValueTypeName === referenceTrackType;
  170. } );
  171. if ( targetTrack === undefined ) continue;
  172. let referenceOffset = 0;
  173. const referenceValueSize = referenceTrack.getValueSize();
  174. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  175. referenceOffset = referenceValueSize / 3;
  176. }
  177. let targetOffset = 0;
  178. const targetValueSize = targetTrack.getValueSize();
  179. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  180. targetOffset = targetValueSize / 3;
  181. }
  182. const lastIndex = referenceTrack.times.length - 1;
  183. let referenceValue;
  184. // Find the value to subtract out of the track
  185. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  186. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  187. const startIndex = referenceOffset;
  188. const endIndex = referenceValueSize - referenceOffset;
  189. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  190. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  191. // Reference frame is after the last keyframe, so just use the last keyframe
  192. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  193. const endIndex = startIndex + referenceValueSize - referenceOffset;
  194. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  195. } else {
  196. // Interpolate to the reference value
  197. const interpolant = referenceTrack.createInterpolant();
  198. const startIndex = referenceOffset;
  199. const endIndex = referenceValueSize - referenceOffset;
  200. interpolant.evaluate( referenceTime );
  201. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  202. }
  203. // Conjugate the quaternion
  204. if ( referenceTrackType === 'quaternion' ) {
  205. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  206. referenceQuat.toArray( referenceValue );
  207. }
  208. // Subtract the reference value from all of the track values
  209. const numTimes = targetTrack.times.length;
  210. for ( let j = 0; j < numTimes; ++ j ) {
  211. const valueStart = j * targetValueSize + targetOffset;
  212. if ( referenceTrackType === 'quaternion' ) {
  213. // Multiply the conjugate for quaternion track types
  214. Quaternion.multiplyQuaternionsFlat(
  215. targetTrack.values,
  216. valueStart,
  217. referenceValue,
  218. 0,
  219. targetTrack.values,
  220. valueStart
  221. );
  222. } else {
  223. const valueEnd = targetValueSize - targetOffset * 2;
  224. // Subtract each value for all other numeric track types
  225. for ( let k = 0; k < valueEnd; ++ k ) {
  226. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  227. }
  228. }
  229. }
  230. }
  231. targetClip.blendMode = AdditiveAnimationBlendMode;
  232. return targetClip;
  233. }
  234. /**
  235. * A class with various methods to assist with animations.
  236. *
  237. * @hideconstructor
  238. */
  239. class AnimationUtils {
  240. /**
  241. * Converts an array to a specific type
  242. *
  243. * @static
  244. * @param {TypedArray|Array} array - The array to convert.
  245. * @param {TypedArray.constructor} type - The constructor of a type array.
  246. * @return {TypedArray} The converted array
  247. */
  248. static convertArray( array, type ) {
  249. return convertArray( array, type );
  250. }
  251. /**
  252. * Returns `true` if the given object is a typed array.
  253. *
  254. * @static
  255. * @param {any} object - The object to check.
  256. * @return {boolean} Whether the given object is a typed array.
  257. */
  258. static isTypedArray( object ) {
  259. return isTypedArray( object );
  260. }
  261. /**
  262. * Returns an array by which times and values can be sorted.
  263. *
  264. * @static
  265. * @param {Array<number>} times - The keyframe time values.
  266. * @return {Array<number>} The array.
  267. */
  268. static getKeyframeOrder( times ) {
  269. return getKeyframeOrder( times );
  270. }
  271. /**
  272. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  273. *
  274. * @static
  275. * @param {Array<number>} values - The values to sort.
  276. * @param {number} stride - The stride.
  277. * @param {Array<number>} order - The sort order.
  278. * @return {Array<number>} The sorted values.
  279. */
  280. static sortedArray( values, stride, order ) {
  281. return sortedArray( values, stride, order );
  282. }
  283. /**
  284. * Used for parsing AOS keyframe formats.
  285. *
  286. * @static
  287. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  288. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  289. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  290. * @param {string} valuePropertyName - The name of the property to use.
  291. */
  292. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  293. flattenJSON( jsonKeys, times, values, valuePropertyName );
  294. }
  295. /**
  296. * Creates a new clip, containing only the segment of the original clip between the given frames.
  297. *
  298. * @static
  299. * @param {AnimationClip} sourceClip - The values to sort.
  300. * @param {string} name - The name of the clip.
  301. * @param {number} startFrame - The start frame.
  302. * @param {number} endFrame - The end frame.
  303. * @param {number} [fps=30] - The FPS.
  304. * @return {AnimationClip} The new sub clip.
  305. */
  306. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  307. return subclip( sourceClip, name, startFrame, endFrame, fps );
  308. }
  309. /**
  310. * Converts the keyframes of the given animation clip to an additive format.
  311. *
  312. * @static
  313. * @param {AnimationClip} targetClip - The clip to make additive.
  314. * @param {number} [referenceFrame=0] - The reference frame.
  315. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  316. * @param {number} [fps=30] - The FPS.
  317. * @return {AnimationClip} The updated clip which is now additive.
  318. */
  319. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  320. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  321. }
  322. }
  323. export {
  324. convertArray,
  325. isTypedArray,
  326. getKeyframeOrder,
  327. sortedArray,
  328. flattenJSON,
  329. subclip,
  330. makeClipAdditive,
  331. AnimationUtils
  332. };