SkeletonUtils.js 12 KB

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