SkeletonUtils.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import {
  2. AnimationClip,
  3. AnimationMixer,
  4. Matrix4,
  5. Quaternion,
  6. QuaternionKeyframeTrack,
  7. SkeletonHelper,
  8. Vector3,
  9. VectorKeyframeTrack
  10. } from 'three';
  11. function getBoneName( bone, options ) {
  12. if ( options.getBoneName !== undefined ) {
  13. return options.getBoneName( bone );
  14. }
  15. return options.names[ bone.name ];
  16. }
  17. function retarget( target, source, options = {} ) {
  18. const quat = new Quaternion(),
  19. scale = new Vector3(),
  20. relativeMatrix = new Matrix4(),
  21. globalMatrix = new Matrix4();
  22. options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true;
  23. options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true;
  24. options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
  25. options.hip = options.hip !== undefined ? options.hip : 'hip';
  26. options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3( 1, 1, 1 );
  27. options.scale = options.scale !== undefined ? options.scale : 1;
  28. options.names = options.names || {};
  29. const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  30. bones = target.isObject3D ? target.skeleton.bones : getBones( target );
  31. let bone, name, boneTo,
  32. bonesPosition;
  33. // reset bones
  34. if ( target.isObject3D ) {
  35. target.skeleton.pose();
  36. } else {
  37. options.useTargetMatrix = true;
  38. options.preserveBoneMatrix = false;
  39. }
  40. if ( options.preserveBonePositions ) {
  41. bonesPosition = [];
  42. for ( let i = 0; i < bones.length; i ++ ) {
  43. bonesPosition.push( bones[ i ].position.clone() );
  44. }
  45. }
  46. if ( options.preserveBoneMatrix ) {
  47. // reset matrix
  48. target.updateMatrixWorld();
  49. target.matrixWorld.identity();
  50. // reset children matrix
  51. for ( let i = 0; i < target.children.length; ++ i ) {
  52. target.children[ i ].updateMatrixWorld( true );
  53. }
  54. }
  55. for ( let i = 0; i < bones.length; ++ i ) {
  56. bone = bones[ i ];
  57. name = getBoneName( bone, options );
  58. boneTo = getBoneByName( name, sourceBones );
  59. globalMatrix.copy( bone.matrixWorld );
  60. if ( boneTo ) {
  61. boneTo.updateMatrixWorld();
  62. if ( options.useTargetMatrix ) {
  63. relativeMatrix.copy( boneTo.matrixWorld );
  64. } else {
  65. relativeMatrix.copy( target.matrixWorld ).invert();
  66. relativeMatrix.multiply( boneTo.matrixWorld );
  67. }
  68. // ignore scale to extract rotation
  69. scale.setFromMatrixScale( relativeMatrix );
  70. relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
  71. // apply to global matrix
  72. globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
  73. if ( target.isObject3D ) {
  74. if ( options.localOffsets ) {
  75. if ( options.localOffsets[ bone.name ] ) {
  76. globalMatrix.multiply( options.localOffsets[ bone.name ] );
  77. }
  78. }
  79. }
  80. globalMatrix.copyPosition( relativeMatrix );
  81. }
  82. if ( name === options.hip ) {
  83. globalMatrix.elements[ 12 ] *= options.scale * options.hipInfluence.x;
  84. globalMatrix.elements[ 13 ] *= options.scale * options.hipInfluence.y;
  85. globalMatrix.elements[ 14 ] *= options.scale * options.hipInfluence.z;
  86. if ( options.hipPosition !== undefined ) {
  87. globalMatrix.elements[ 12 ] += options.hipPosition.x * options.scale;
  88. globalMatrix.elements[ 13 ] += options.hipPosition.y * options.scale;
  89. globalMatrix.elements[ 14 ] += options.hipPosition.z * options.scale;
  90. }
  91. }
  92. if ( bone.parent ) {
  93. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  94. bone.matrix.multiply( globalMatrix );
  95. } else {
  96. bone.matrix.copy( globalMatrix );
  97. }
  98. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  99. bone.updateMatrixWorld();
  100. }
  101. if ( options.preserveBonePositions ) {
  102. for ( let i = 0; i < bones.length; ++ i ) {
  103. bone = bones[ i ];
  104. name = getBoneName( bone, options ) || bone.name;
  105. if ( name !== options.hip ) {
  106. bone.position.copy( bonesPosition[ i ] );
  107. }
  108. }
  109. }
  110. if ( options.preserveBoneMatrix ) {
  111. // restore matrix
  112. target.updateMatrixWorld( true );
  113. }
  114. }
  115. function retargetClip( target, source, clip, options = {} ) {
  116. options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
  117. // Calculate the fps from the source clip based on the track with the most frames, unless fps is already provided.
  118. options.fps = options.fps !== undefined ? options.fps : ( Math.max( ...clip.tracks.map( track => track.times.length ) ) / clip.duration );
  119. options.names = options.names || [];
  120. if ( ! source.isObject3D ) {
  121. source = getHelperFromSkeleton( source );
  122. }
  123. const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
  124. delta = clip.duration / ( numFrames - 1 ),
  125. convertedTracks = [],
  126. mixer = new AnimationMixer( source ),
  127. bones = getBones( target.skeleton ),
  128. boneDatas = [];
  129. let positionOffset,
  130. bone, boneTo, boneData,
  131. name;
  132. mixer.clipAction( clip ).play();
  133. // trim
  134. let start = 0, end = numFrames;
  135. if ( options.trim !== undefined ) {
  136. start = Math.round( options.trim[ 0 ] * options.fps );
  137. end = Math.min( Math.round( options.trim[ 1 ] * options.fps ), numFrames ) - start;
  138. mixer.update( options.trim[ 0 ] );
  139. } else {
  140. mixer.update( 0 );
  141. }
  142. source.updateMatrixWorld();
  143. //
  144. for ( let frame = 0; frame < end; ++ frame ) {
  145. const time = frame * delta;
  146. retarget( target, source, options );
  147. for ( let j = 0; j < bones.length; ++ j ) {
  148. bone = bones[ j ];
  149. name = getBoneName( bone, options ) || bone.name;
  150. boneTo = getBoneByName( name, source.skeleton );
  151. if ( boneTo ) {
  152. boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
  153. if ( options.hip === name ) {
  154. if ( ! boneData.pos ) {
  155. boneData.pos = {
  156. times: new Float32Array( end ),
  157. values: new Float32Array( end * 3 )
  158. };
  159. }
  160. if ( options.useFirstFramePosition ) {
  161. if ( frame === 0 ) {
  162. positionOffset = bone.position.clone();
  163. }
  164. bone.position.sub( positionOffset );
  165. }
  166. boneData.pos.times[ frame ] = time;
  167. bone.position.toArray( boneData.pos.values, frame * 3 );
  168. }
  169. if ( ! boneData.quat ) {
  170. boneData.quat = {
  171. times: new Float32Array( end ),
  172. values: new Float32Array( end * 4 )
  173. };
  174. }
  175. boneData.quat.times[ frame ] = time;
  176. bone.quaternion.toArray( boneData.quat.values, frame * 4 );
  177. }
  178. }
  179. if ( frame === end - 2 ) {
  180. // last mixer update before final loop iteration
  181. // make sure we do not go over or equal to clip duration
  182. mixer.update( delta - 0.0000001 );
  183. } else {
  184. mixer.update( delta );
  185. }
  186. source.updateMatrixWorld();
  187. }
  188. for ( let i = 0; i < boneDatas.length; ++ i ) {
  189. boneData = boneDatas[ i ];
  190. if ( boneData ) {
  191. if ( boneData.pos ) {
  192. convertedTracks.push( new VectorKeyframeTrack(
  193. '.bones[' + boneData.bone.name + '].position',
  194. boneData.pos.times,
  195. boneData.pos.values
  196. ) );
  197. }
  198. convertedTracks.push( new QuaternionKeyframeTrack(
  199. '.bones[' + boneData.bone.name + '].quaternion',
  200. boneData.quat.times,
  201. boneData.quat.values
  202. ) );
  203. }
  204. }
  205. mixer.uncacheAction( clip );
  206. return new AnimationClip( clip.name, - 1, convertedTracks );
  207. }
  208. function clone( source ) {
  209. const sourceLookup = new Map();
  210. const cloneLookup = new Map();
  211. const clone = source.clone();
  212. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  213. sourceLookup.set( clonedNode, sourceNode );
  214. cloneLookup.set( sourceNode, clonedNode );
  215. } );
  216. clone.traverse( function ( node ) {
  217. if ( ! node.isSkinnedMesh ) return;
  218. const clonedMesh = node;
  219. const sourceMesh = sourceLookup.get( node );
  220. const sourceBones = sourceMesh.skeleton.bones;
  221. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  222. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  223. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  224. return cloneLookup.get( bone );
  225. } );
  226. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  227. } );
  228. return clone;
  229. }
  230. // internal helper
  231. function getBoneByName( name, skeleton ) {
  232. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  233. if ( name === bones[ i ].name )
  234. return bones[ i ];
  235. }
  236. }
  237. function getBones( skeleton ) {
  238. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  239. }
  240. function getHelperFromSkeleton( skeleton ) {
  241. const source = new SkeletonHelper( skeleton.bones[ 0 ] );
  242. source.skeleton = skeleton;
  243. return source;
  244. }
  245. function parallelTraverse( a, b, callback ) {
  246. callback( a, b );
  247. for ( let i = 0; i < a.children.length; i ++ ) {
  248. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  249. }
  250. }
  251. export {
  252. retarget,
  253. retargetClip,
  254. clone,
  255. };
粤ICP备19079148号