SkeletonUtils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. ( function () {
  2. function retarget( target, source, options = {} ) {
  3. const pos = new THREE.Vector3(),
  4. quat = new THREE.Quaternion(),
  5. scale = new THREE.Vector3(),
  6. bindBoneMatrix = new THREE.Matrix4(),
  7. relativeMatrix = new THREE.Matrix4(),
  8. globalMatrix = new THREE.Matrix4();
  9. options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true;
  10. options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true;
  11. options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false;
  12. options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
  13. options.hip = options.hip !== undefined ? options.hip : 'hip';
  14. options.names = options.names || {};
  15. const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  16. bones = target.isObject3D ? target.skeleton.bones : getBones( target );
  17. let bindBones, bone, name, boneTo, bonesPosition;
  18. // reset bones
  19. if ( target.isObject3D ) {
  20. target.skeleton.pose();
  21. } else {
  22. options.useTargetMatrix = true;
  23. options.preserveMatrix = false;
  24. }
  25. if ( options.preservePosition ) {
  26. bonesPosition = [];
  27. for ( let i = 0; i < bones.length; i ++ ) {
  28. bonesPosition.push( bones[ i ].position.clone() );
  29. }
  30. }
  31. if ( options.preserveMatrix ) {
  32. // reset matrix
  33. target.updateMatrixWorld();
  34. target.matrixWorld.identity();
  35. // reset children matrix
  36. for ( let i = 0; i < target.children.length; ++ i ) {
  37. target.children[ i ].updateMatrixWorld( true );
  38. }
  39. }
  40. if ( options.offsets ) {
  41. bindBones = [];
  42. for ( let i = 0; i < bones.length; ++ i ) {
  43. bone = bones[ i ];
  44. name = options.names[ bone.name ] || bone.name;
  45. if ( options.offsets[ name ] ) {
  46. bone.matrix.multiply( options.offsets[ name ] );
  47. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  48. bone.updateMatrixWorld();
  49. }
  50. bindBones.push( bone.matrixWorld.clone() );
  51. }
  52. }
  53. for ( let i = 0; i < bones.length; ++ i ) {
  54. bone = bones[ i ];
  55. name = options.names[ bone.name ] || bone.name;
  56. boneTo = getBoneByName( name, sourceBones );
  57. globalMatrix.copy( bone.matrixWorld );
  58. if ( boneTo ) {
  59. boneTo.updateMatrixWorld();
  60. if ( options.useTargetMatrix ) {
  61. relativeMatrix.copy( boneTo.matrixWorld );
  62. } else {
  63. relativeMatrix.copy( target.matrixWorld ).invert();
  64. relativeMatrix.multiply( boneTo.matrixWorld );
  65. }
  66. // ignore scale to extract rotation
  67. scale.setFromMatrixScale( relativeMatrix );
  68. relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
  69. // apply to global matrix
  70. globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
  71. if ( target.isObject3D ) {
  72. const boneIndex = bones.indexOf( bone ),
  73. wBindMatrix = bindBones ? bindBones[ boneIndex ] : bindBoneMatrix.copy( target.skeleton.boneInverses[ boneIndex ] ).invert();
  74. globalMatrix.multiply( wBindMatrix );
  75. }
  76. globalMatrix.copyPosition( relativeMatrix );
  77. }
  78. if ( bone.parent && bone.parent.isBone ) {
  79. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  80. bone.matrix.multiply( globalMatrix );
  81. } else {
  82. bone.matrix.copy( globalMatrix );
  83. }
  84. if ( options.preserveHipPosition && name === options.hip ) {
  85. bone.matrix.setPosition( pos.set( 0, bone.position.y, 0 ) );
  86. }
  87. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  88. bone.updateMatrixWorld();
  89. }
  90. if ( options.preservePosition ) {
  91. for ( let i = 0; i < bones.length; ++ i ) {
  92. bone = bones[ i ];
  93. name = options.names[ bone.name ] || bone.name;
  94. if ( name !== options.hip ) {
  95. bone.position.copy( bonesPosition[ i ] );
  96. }
  97. }
  98. }
  99. if ( options.preserveMatrix ) {
  100. // restore matrix
  101. target.updateMatrixWorld( true );
  102. }
  103. }
  104. function retargetClip( target, source, clip, options = {} ) {
  105. options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
  106. options.fps = options.fps !== undefined ? options.fps : 30;
  107. options.names = options.names || [];
  108. if ( ! source.isObject3D ) {
  109. source = getHelperFromSkeleton( source );
  110. }
  111. const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
  112. delta = 1 / options.fps,
  113. convertedTracks = [],
  114. mixer = new THREE.AnimationMixer( source ),
  115. bones = getBones( target.skeleton ),
  116. boneDatas = [];
  117. let positionOffset, bone, boneTo, boneData, name;
  118. mixer.clipAction( clip ).play();
  119. mixer.update( 0 );
  120. source.updateMatrixWorld();
  121. for ( let i = 0; i < numFrames; ++ i ) {
  122. const time = i * delta;
  123. retarget( target, source, options );
  124. for ( let j = 0; j < bones.length; ++ j ) {
  125. name = options.names[ bones[ j ].name ] || bones[ j ].name;
  126. boneTo = getBoneByName( name, source.skeleton );
  127. if ( boneTo ) {
  128. bone = bones[ j ];
  129. boneData = boneDatas[ j ] = boneDatas[ j ] || {
  130. bone: bone
  131. };
  132. if ( options.hip === name ) {
  133. if ( ! boneData.pos ) {
  134. boneData.pos = {
  135. times: new Float32Array( numFrames ),
  136. values: new Float32Array( numFrames * 3 )
  137. };
  138. }
  139. if ( options.useFirstFramePosition ) {
  140. if ( i === 0 ) {
  141. positionOffset = bone.position.clone();
  142. }
  143. bone.position.sub( positionOffset );
  144. }
  145. boneData.pos.times[ i ] = time;
  146. bone.position.toArray( boneData.pos.values, i * 3 );
  147. }
  148. if ( ! boneData.quat ) {
  149. boneData.quat = {
  150. times: new Float32Array( numFrames ),
  151. values: new Float32Array( numFrames * 4 )
  152. };
  153. }
  154. boneData.quat.times[ i ] = time;
  155. bone.quaternion.toArray( boneData.quat.values, i * 4 );
  156. }
  157. }
  158. mixer.update( delta );
  159. source.updateMatrixWorld();
  160. }
  161. for ( let i = 0; i < boneDatas.length; ++ i ) {
  162. boneData = boneDatas[ i ];
  163. if ( boneData ) {
  164. if ( boneData.pos ) {
  165. convertedTracks.push( new THREE.VectorKeyframeTrack( '.bones[' + boneData.bone.name + '].position', boneData.pos.times, boneData.pos.values ) );
  166. }
  167. convertedTracks.push( new THREE.QuaternionKeyframeTrack( '.bones[' + boneData.bone.name + '].quaternion', boneData.quat.times, boneData.quat.values ) );
  168. }
  169. }
  170. mixer.uncacheAction( clip );
  171. return new THREE.AnimationClip( clip.name, - 1, convertedTracks );
  172. }
  173. function getHelperFromSkeleton( skeleton ) {
  174. const source = new THREE.SkeletonHelper( skeleton.bones[ 0 ] );
  175. source.skeleton = skeleton;
  176. return source;
  177. }
  178. function getSkeletonOffsets( target, source, options = {} ) {
  179. const targetParentPos = new THREE.Vector3(),
  180. targetPos = new THREE.Vector3(),
  181. sourceParentPos = new THREE.Vector3(),
  182. sourcePos = new THREE.Vector3(),
  183. targetDir = new THREE.Vector2(),
  184. sourceDir = new THREE.Vector2();
  185. options.hip = options.hip !== undefined ? options.hip : 'hip';
  186. options.names = options.names || {};
  187. if ( ! source.isObject3D ) {
  188. source = getHelperFromSkeleton( source );
  189. }
  190. const nameKeys = Object.keys( options.names ),
  191. nameValues = Object.values( options.names ),
  192. sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  193. bones = target.isObject3D ? target.skeleton.bones : getBones( target ),
  194. offsets = [];
  195. let bone, boneTo, name, i;
  196. target.skeleton.pose();
  197. for ( i = 0; i < bones.length; ++ i ) {
  198. bone = bones[ i ];
  199. name = options.names[ bone.name ] || bone.name;
  200. boneTo = getBoneByName( name, sourceBones );
  201. if ( boneTo && name !== options.hip ) {
  202. const boneParent = getNearestBone( bone.parent, nameKeys ),
  203. boneToParent = getNearestBone( boneTo.parent, nameValues );
  204. boneParent.updateMatrixWorld();
  205. boneToParent.updateMatrixWorld();
  206. targetParentPos.setFromMatrixPosition( boneParent.matrixWorld );
  207. targetPos.setFromMatrixPosition( bone.matrixWorld );
  208. sourceParentPos.setFromMatrixPosition( boneToParent.matrixWorld );
  209. sourcePos.setFromMatrixPosition( boneTo.matrixWorld );
  210. targetDir.subVectors( new THREE.Vector2( targetPos.x, targetPos.y ), new THREE.Vector2( targetParentPos.x, targetParentPos.y ) ).normalize();
  211. sourceDir.subVectors( new THREE.Vector2( sourcePos.x, sourcePos.y ), new THREE.Vector2( sourceParentPos.x, sourceParentPos.y ) ).normalize();
  212. const laterialAngle = targetDir.angle() - sourceDir.angle();
  213. const offset = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler( 0, 0, laterialAngle ) );
  214. bone.matrix.multiply( offset );
  215. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  216. bone.updateMatrixWorld();
  217. offsets[ name ] = offset;
  218. }
  219. }
  220. return offsets;
  221. }
  222. function renameBones( skeleton, names ) {
  223. const bones = getBones( skeleton );
  224. for ( let i = 0; i < bones.length; ++ i ) {
  225. const bone = bones[ i ];
  226. if ( names[ bone.name ] ) {
  227. bone.name = names[ bone.name ];
  228. }
  229. }
  230. return this;
  231. }
  232. function getBones( skeleton ) {
  233. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  234. }
  235. function getBoneByName( name, skeleton ) {
  236. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  237. if ( name === bones[ i ].name ) return bones[ i ];
  238. }
  239. }
  240. function getNearestBone( bone, names ) {
  241. while ( bone.isBone ) {
  242. if ( names.indexOf( bone.name ) !== - 1 ) {
  243. return bone;
  244. }
  245. bone = bone.parent;
  246. }
  247. }
  248. function findBoneTrackData( name, tracks ) {
  249. const regexp = /\[(.*)\]\.(.*)/,
  250. result = {
  251. name: name
  252. };
  253. for ( let i = 0; i < tracks.length; ++ i ) {
  254. // 1 is track name
  255. // 2 is track type
  256. const trackData = regexp.exec( tracks[ i ].name );
  257. if ( trackData && name === trackData[ 1 ] ) {
  258. result[ trackData[ 2 ] ] = i;
  259. }
  260. }
  261. return result;
  262. }
  263. function getEqualsBonesNames( skeleton, targetSkeleton ) {
  264. const sourceBones = getBones( skeleton ),
  265. targetBones = getBones( targetSkeleton ),
  266. bones = [];
  267. search: for ( let i = 0; i < sourceBones.length; i ++ ) {
  268. const boneName = sourceBones[ i ].name;
  269. for ( let j = 0; j < targetBones.length; j ++ ) {
  270. if ( boneName === targetBones[ j ].name ) {
  271. bones.push( boneName );
  272. continue search;
  273. }
  274. }
  275. }
  276. return bones;
  277. }
  278. function clone( source ) {
  279. const sourceLookup = new Map();
  280. const cloneLookup = new Map();
  281. const clone = source.clone();
  282. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  283. sourceLookup.set( clonedNode, sourceNode );
  284. cloneLookup.set( sourceNode, clonedNode );
  285. } );
  286. clone.traverse( function ( node ) {
  287. if ( ! node.isSkinnedMesh ) return;
  288. const clonedMesh = node;
  289. const sourceMesh = sourceLookup.get( node );
  290. const sourceBones = sourceMesh.skeleton.bones;
  291. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  292. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  293. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  294. return cloneLookup.get( bone );
  295. } );
  296. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  297. } );
  298. return clone;
  299. }
  300. function parallelTraverse( a, b, callback ) {
  301. callback( a, b );
  302. for ( let i = 0; i < a.children.length; i ++ ) {
  303. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  304. }
  305. }
  306. THREE.SkeletonUtils = {};
  307. THREE.SkeletonUtils.clone = clone;
  308. THREE.SkeletonUtils.findBoneTrackData = findBoneTrackData;
  309. THREE.SkeletonUtils.getBoneByName = getBoneByName;
  310. THREE.SkeletonUtils.getBones = getBones;
  311. THREE.SkeletonUtils.getEqualsBonesNames = getEqualsBonesNames;
  312. THREE.SkeletonUtils.getHelperFromSkeleton = getHelperFromSkeleton;
  313. THREE.SkeletonUtils.getNearestBone = getNearestBone;
  314. THREE.SkeletonUtils.getSkeletonOffsets = getSkeletonOffsets;
  315. THREE.SkeletonUtils.renameBones = renameBones;
  316. THREE.SkeletonUtils.retarget = retarget;
  317. THREE.SkeletonUtils.retargetClip = retargetClip;
  318. } )();