SkeletonUtils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import {
  2. AnimationClip,
  3. AnimationMixer,
  4. Matrix4,
  5. Quaternion,
  6. QuaternionKeyframeTrack,
  7. SkeletonHelper,
  8. Vector3,
  9. VectorKeyframeTrack
  10. } from 'three';
  11. /**
  12. * @module SkeletonUtils
  13. * @three_import import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
  14. */
  15. function getBoneName( bone, options ) {
  16. if ( options.getBoneName !== undefined ) {
  17. return options.getBoneName( bone );
  18. }
  19. return options.names[ bone.name ];
  20. }
  21. /**
  22. * Retargets the skeleton from the given source to the target.
  23. *
  24. * Both `target` and `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)
  25. * or a {@link Skeleton} directly.
  26. *
  27. * @param {Object3D|Skeleton} target - The target object.
  28. * @param {Object3D|Skeleton} source - The source object.
  29. * @param {module:SkeletonUtils~RetargetOptions} options - The options.
  30. */
  31. function retarget( target, source, options = {} ) {
  32. const quat = new Quaternion(),
  33. scale = new Vector3(),
  34. relativeMatrix = new Matrix4(),
  35. globalMatrix = new Matrix4();
  36. options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true;
  37. options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true;
  38. options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
  39. options.hip = options.hip !== undefined ? options.hip : 'hip';
  40. options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3( 1, 1, 1 );
  41. options.scale = options.scale !== undefined ? options.scale : 1;
  42. options.names = options.names || {};
  43. const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  44. bones = target.isObject3D ? target.skeleton.bones : getBones( target );
  45. let bone, name, boneTo,
  46. bonesPosition;
  47. // reset bones
  48. if ( target.isObject3D ) {
  49. target.skeleton.pose();
  50. } else {
  51. options.useTargetMatrix = true;
  52. options.preserveBoneMatrix = false;
  53. }
  54. if ( options.preserveBonePositions ) {
  55. bonesPosition = [];
  56. for ( let i = 0; i < bones.length; i ++ ) {
  57. bonesPosition.push( bones[ i ].position.clone() );
  58. }
  59. }
  60. if ( options.preserveBoneMatrix ) {
  61. // reset matrix
  62. target.updateMatrixWorld();
  63. target.matrixWorld.identity();
  64. // reset children matrix
  65. for ( let i = 0; i < target.children.length; ++ i ) {
  66. target.children[ i ].updateMatrixWorld( true );
  67. }
  68. }
  69. for ( let i = 0; i < bones.length; ++ i ) {
  70. bone = bones[ i ];
  71. name = getBoneName( bone, options );
  72. boneTo = getBoneByName( name, sourceBones );
  73. globalMatrix.copy( bone.matrixWorld );
  74. if ( boneTo ) {
  75. boneTo.updateMatrixWorld();
  76. if ( options.useTargetMatrix ) {
  77. relativeMatrix.copy( boneTo.matrixWorld );
  78. } else {
  79. relativeMatrix.copy( target.matrixWorld ).invert();
  80. relativeMatrix.multiply( boneTo.matrixWorld );
  81. }
  82. // ignore scale to extract rotation
  83. scale.setFromMatrixScale( relativeMatrix );
  84. relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
  85. // apply to global matrix
  86. globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
  87. if ( target.isObject3D ) {
  88. if ( options.localOffsets ) {
  89. if ( options.localOffsets[ bone.name ] ) {
  90. globalMatrix.multiply( options.localOffsets[ bone.name ] );
  91. }
  92. }
  93. }
  94. globalMatrix.copyPosition( relativeMatrix );
  95. }
  96. if ( name === options.hip ) {
  97. globalMatrix.elements[ 12 ] *= options.scale * options.hipInfluence.x;
  98. globalMatrix.elements[ 13 ] *= options.scale * options.hipInfluence.y;
  99. globalMatrix.elements[ 14 ] *= options.scale * options.hipInfluence.z;
  100. if ( options.hipPosition !== undefined ) {
  101. globalMatrix.elements[ 12 ] += options.hipPosition.x * options.scale;
  102. globalMatrix.elements[ 13 ] += options.hipPosition.y * options.scale;
  103. globalMatrix.elements[ 14 ] += options.hipPosition.z * options.scale;
  104. }
  105. }
  106. if ( bone.parent ) {
  107. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  108. bone.matrix.multiply( globalMatrix );
  109. } else {
  110. bone.matrix.copy( globalMatrix );
  111. }
  112. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  113. bone.updateMatrixWorld();
  114. }
  115. if ( options.preserveBonePositions ) {
  116. for ( let i = 0; i < bones.length; ++ i ) {
  117. bone = bones[ i ];
  118. name = getBoneName( bone, options ) || bone.name;
  119. if ( name !== options.hip ) {
  120. bone.position.copy( bonesPosition[ i ] );
  121. }
  122. }
  123. }
  124. if ( options.preserveBoneMatrix ) {
  125. // restore matrix
  126. target.updateMatrixWorld( true );
  127. }
  128. }
  129. /**
  130. * Retargets the animation clip of the source to the target 3D object.
  131. *
  132. * The `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)
  133. * or a {@link Skeleton} directly.
  134. *
  135. * @param {Object3D} target - The target 3D object. Must have a `skeleton` property.
  136. * @param {Object3D|Skeleton} source - The source object.
  137. * @param {AnimationClip} clip - The animation clip.
  138. * @param {module:SkeletonUtils~RetargetOptions} options - The options.
  139. * @return {AnimationClip} The retargeted animation clip.
  140. */
  141. function retargetClip( target, source, clip, options = {} ) {
  142. options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
  143. // Calculate the fps from the source clip based on the track with the most frames, unless fps is already provided.
  144. options.fps = options.fps !== undefined ? options.fps : ( Math.max( ...clip.tracks.map( track => track.times.length ) ) / clip.duration );
  145. options.names = options.names || [];
  146. if ( ! source.isObject3D ) {
  147. source = getHelperFromSkeleton( source );
  148. }
  149. const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
  150. delta = clip.duration / ( numFrames - 1 ),
  151. convertedTracks = [],
  152. mixer = new AnimationMixer( source ),
  153. bones = getBones( target.skeleton ),
  154. boneDatas = [];
  155. let positionOffset,
  156. bone, boneTo, boneData,
  157. name;
  158. mixer.clipAction( clip ).play();
  159. // trim
  160. let start = 0, end = numFrames;
  161. if ( options.trim !== undefined ) {
  162. start = Math.round( options.trim[ 0 ] * options.fps );
  163. end = Math.min( Math.round( options.trim[ 1 ] * options.fps ), numFrames ) - start;
  164. mixer.update( options.trim[ 0 ] );
  165. } else {
  166. mixer.update( 0 );
  167. }
  168. source.updateMatrixWorld();
  169. //
  170. for ( let frame = 0; frame < end; ++ frame ) {
  171. const time = frame * delta;
  172. retarget( target, source, options );
  173. for ( let j = 0; j < bones.length; ++ j ) {
  174. bone = bones[ j ];
  175. name = getBoneName( bone, options ) || bone.name;
  176. boneTo = getBoneByName( name, source.skeleton );
  177. if ( boneTo ) {
  178. boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
  179. if ( options.hip === name ) {
  180. if ( ! boneData.pos ) {
  181. boneData.pos = {
  182. times: new Float32Array( end ),
  183. values: new Float32Array( end * 3 )
  184. };
  185. }
  186. if ( options.useFirstFramePosition ) {
  187. if ( frame === 0 ) {
  188. positionOffset = bone.position.clone();
  189. }
  190. bone.position.sub( positionOffset );
  191. }
  192. boneData.pos.times[ frame ] = time;
  193. bone.position.toArray( boneData.pos.values, frame * 3 );
  194. }
  195. if ( ! boneData.quat ) {
  196. boneData.quat = {
  197. times: new Float32Array( end ),
  198. values: new Float32Array( end * 4 )
  199. };
  200. }
  201. boneData.quat.times[ frame ] = time;
  202. bone.quaternion.toArray( boneData.quat.values, frame * 4 );
  203. }
  204. }
  205. if ( frame === end - 2 ) {
  206. // last mixer update before final loop iteration
  207. // make sure we do not go over or equal to clip duration
  208. mixer.update( delta - 0.0000001 );
  209. } else {
  210. mixer.update( delta );
  211. }
  212. source.updateMatrixWorld();
  213. }
  214. for ( let i = 0; i < boneDatas.length; ++ i ) {
  215. boneData = boneDatas[ i ];
  216. if ( boneData ) {
  217. if ( boneData.pos ) {
  218. convertedTracks.push( new VectorKeyframeTrack(
  219. '.bones[' + boneData.bone.name + '].position',
  220. boneData.pos.times,
  221. boneData.pos.values
  222. ) );
  223. }
  224. convertedTracks.push( new QuaternionKeyframeTrack(
  225. '.bones[' + boneData.bone.name + '].quaternion',
  226. boneData.quat.times,
  227. boneData.quat.values
  228. ) );
  229. }
  230. }
  231. mixer.uncacheAction( clip );
  232. return new AnimationClip( clip.name, - 1, convertedTracks );
  233. }
  234. /**
  235. * Clones the given 3D object and its descendants, ensuring that any `SkinnedMesh` instances are
  236. * correctly associated with their bones. Bones are also cloned, and must be descendants of the
  237. * object passed to this method. Other data, like geometries and materials, are reused by reference.
  238. *
  239. * @param {Object3D} source - The 3D object to clone.
  240. * @return {Object3D} The cloned 3D object.
  241. */
  242. function clone( source ) {
  243. const sourceLookup = new Map();
  244. const cloneLookup = new Map();
  245. const clone = source.clone();
  246. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  247. sourceLookup.set( clonedNode, sourceNode );
  248. cloneLookup.set( sourceNode, clonedNode );
  249. } );
  250. clone.traverse( function ( node ) {
  251. if ( ! node.isSkinnedMesh ) return;
  252. const clonedMesh = node;
  253. const sourceMesh = sourceLookup.get( node );
  254. const sourceBones = sourceMesh.skeleton.bones;
  255. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  256. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  257. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  258. return cloneLookup.get( bone );
  259. } );
  260. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  261. } );
  262. return clone;
  263. }
  264. // internal helper
  265. function getBoneByName( name, skeleton ) {
  266. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  267. if ( name === bones[ i ].name )
  268. return bones[ i ];
  269. }
  270. }
  271. function getBones( skeleton ) {
  272. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  273. }
  274. function getHelperFromSkeleton( skeleton ) {
  275. const source = new SkeletonHelper( skeleton.bones[ 0 ] );
  276. source.skeleton = skeleton;
  277. return source;
  278. }
  279. function parallelTraverse( a, b, callback ) {
  280. callback( a, b );
  281. for ( let i = 0; i < a.children.length; i ++ ) {
  282. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  283. }
  284. }
  285. /**
  286. * Retarget options of `SkeletonUtils`.
  287. *
  288. * @typedef {Object} module:SkeletonUtils~RetargetOptions
  289. * @property {boolean} [useFirstFramePosition=false] - Whether to use the position of the first frame or not.
  290. * @property {number} [fps] - The FPS of the clip.
  291. * @property {Object<string,string>} [names] - A dictionary for mapping target to source bone names.
  292. * @property {function(string):string} [getBoneName] - A function for mapping bone names. Alternative to `names`.
  293. * @property {Array<number>} [trim] - Whether to trim the clip or not. If set the array should hold two values for the start and end.
  294. * @property {boolean} [preserveBoneMatrix=true] - Whether to preserve bone matrices or not.
  295. * @property {boolean} [preserveBonePositions=true] - Whether to preserve bone positions or not.
  296. * @property {boolean} [useTargetMatrix=false] - Whether to use the target matrix or not.
  297. * @property {string} [hip='hip'] - The name of the source's hip bone.
  298. * @property {Vector3} [hipInfluence=(1,1,1)] - The hip influence.
  299. * @property {number} [scale=1] - The scale.
  300. * @property {Object<string,Matrix4>} [localOffsets] - Per-bone local offset matrices, keyed by bone name.
  301. * @property {Vector3} [hipPosition] - An additional position offset applied to the hip bone.
  302. **/
  303. export {
  304. retarget,
  305. retargetClip,
  306. clone,
  307. };
粤ICP备19079148号