SkeletonUtils.js 11 KB

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