SkeletonUtils.js 12 KB

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