BVHLoader.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /**
  2. * @author herzig / http://github.com/herzig
  3. * @author Mugen87 / https://github.com/Mugen87
  4. *
  5. * Description: reads BVH files and outputs a single THREE.Skeleton and an THREE.AnimationClip
  6. *
  7. * Currently only supports bvh files containing a single root.
  8. *
  9. */
  10. THREE.BVHLoader = function ( manager ) {
  11. THREE.Loader.call( this, manager );
  12. this.animateBonePositions = true;
  13. this.animateBoneRotations = true;
  14. };
  15. THREE.BVHLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  16. constructor: THREE.BVHLoader,
  17. load: function ( url, onLoad, onProgress, onError ) {
  18. var scope = this;
  19. var loader = new THREE.FileLoader( scope.manager );
  20. loader.setPath( scope.path );
  21. loader.load( url, function ( text ) {
  22. onLoad( scope.parse( text ) );
  23. }, onProgress, onError );
  24. },
  25. parse: function ( text ) {
  26. /*
  27. reads a string array (lines) from a BVH file
  28. and outputs a skeleton structure including motion data
  29. returns thee root node:
  30. { name: '', channels: [], children: [] }
  31. */
  32. function readBvh( lines ) {
  33. // read model structure
  34. if ( nextLine( lines ) !== 'HIERARCHY' ) {
  35. console.error( 'THREE.BVHLoader: HIERARCHY expected.' );
  36. }
  37. var list = []; // collects flat array of all bones
  38. var root = readNode( lines, nextLine( lines ), list );
  39. // read motion data
  40. if ( nextLine( lines ) !== 'MOTION' ) {
  41. console.error( 'THREE.BVHLoader: MOTION expected.' );
  42. }
  43. // number of frames
  44. var tokens = nextLine( lines ).split( /[\s]+/ );
  45. var numFrames = parseInt( tokens[ 1 ] );
  46. if ( isNaN( numFrames ) ) {
  47. console.error( 'THREE.BVHLoader: Failed to read number of frames.' );
  48. }
  49. // frame time
  50. tokens = nextLine( lines ).split( /[\s]+/ );
  51. var frameTime = parseFloat( tokens[ 2 ] );
  52. if ( isNaN( frameTime ) ) {
  53. console.error( 'THREE.BVHLoader: Failed to read frame time.' );
  54. }
  55. // read frame data line by line
  56. for ( var i = 0; i < numFrames; i ++ ) {
  57. tokens = nextLine( lines ).split( /[\s]+/ );
  58. readFrameData( tokens, i * frameTime, root );
  59. }
  60. return list;
  61. }
  62. /*
  63. Recursively reads data from a single frame into the bone hierarchy.
  64. The passed bone hierarchy has to be structured in the same order as the BVH file.
  65. keyframe data is stored in bone.frames.
  66. - data: splitted string array (frame values), values are shift()ed so
  67. this should be empty after parsing the whole hierarchy.
  68. - frameTime: playback time for this keyframe.
  69. - bone: the bone to read frame data from.
  70. */
  71. function readFrameData( data, frameTime, bone ) {
  72. // end sites have no motion data
  73. if ( bone.type === 'ENDSITE' ) return;
  74. // add keyframe
  75. var keyframe = {
  76. time: frameTime,
  77. position: new THREE.Vector3(),
  78. rotation: new THREE.Quaternion()
  79. };
  80. bone.frames.push( keyframe );
  81. var quat = new THREE.Quaternion();
  82. var vx = new THREE.Vector3( 1, 0, 0 );
  83. var vy = new THREE.Vector3( 0, 1, 0 );
  84. var vz = new THREE.Vector3( 0, 0, 1 );
  85. // parse values for each channel in node
  86. for ( var i = 0; i < bone.channels.length; i ++ ) {
  87. switch ( bone.channels[ i ] ) {
  88. case 'Xposition':
  89. keyframe.position.x = parseFloat( data.shift().trim() );
  90. break;
  91. case 'Yposition':
  92. keyframe.position.y = parseFloat( data.shift().trim() );
  93. break;
  94. case 'Zposition':
  95. keyframe.position.z = parseFloat( data.shift().trim() );
  96. break;
  97. case 'Xrotation':
  98. quat.setFromAxisAngle( vx, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  99. keyframe.rotation.multiply( quat );
  100. break;
  101. case 'Yrotation':
  102. quat.setFromAxisAngle( vy, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  103. keyframe.rotation.multiply( quat );
  104. break;
  105. case 'Zrotation':
  106. quat.setFromAxisAngle( vz, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  107. keyframe.rotation.multiply( quat );
  108. break;
  109. default:
  110. console.warn( 'THREE.BVHLoader: Invalid channel type.' );
  111. }
  112. }
  113. // parse child nodes
  114. for ( var i = 0; i < bone.children.length; i ++ ) {
  115. readFrameData( data, frameTime, bone.children[ i ] );
  116. }
  117. }
  118. /*
  119. Recursively parses the HIERACHY section of the BVH file
  120. - lines: all lines of the file. lines are consumed as we go along.
  121. - firstline: line containing the node type and name e.g. 'JOINT hip'
  122. - list: collects a flat list of nodes
  123. returns: a BVH node including children
  124. */
  125. function readNode( lines, firstline, list ) {
  126. var node = { name: '', type: '', frames: [] };
  127. list.push( node );
  128. // parse node type and name
  129. var tokens = firstline.split( /[\s]+/ );
  130. if ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) {
  131. node.type = 'ENDSITE';
  132. node.name = 'ENDSITE'; // bvh end sites have no name
  133. } else {
  134. node.name = tokens[ 1 ];
  135. node.type = tokens[ 0 ].toUpperCase();
  136. }
  137. if ( nextLine( lines ) !== '{' ) {
  138. console.error( 'THREE.BVHLoader: Expected opening { after type & name' );
  139. }
  140. // parse OFFSET
  141. tokens = nextLine( lines ).split( /[\s]+/ );
  142. if ( tokens[ 0 ] !== 'OFFSET' ) {
  143. console.error( 'THREE.BVHLoader: Expected OFFSET but got: ' + tokens[ 0 ] );
  144. }
  145. if ( tokens.length !== 4 ) {
  146. console.error( 'THREE.BVHLoader: Invalid number of values for OFFSET.' );
  147. }
  148. var offset = new THREE.Vector3(
  149. parseFloat( tokens[ 1 ] ),
  150. parseFloat( tokens[ 2 ] ),
  151. parseFloat( tokens[ 3 ] )
  152. );
  153. if ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) {
  154. console.error( 'THREE.BVHLoader: Invalid values of OFFSET.' );
  155. }
  156. node.offset = offset;
  157. // parse CHANNELS definitions
  158. if ( node.type !== 'ENDSITE' ) {
  159. tokens = nextLine( lines ).split( /[\s]+/ );
  160. if ( tokens[ 0 ] !== 'CHANNELS' ) {
  161. console.error( 'THREE.BVHLoader: Expected CHANNELS definition.' );
  162. }
  163. var numChannels = parseInt( tokens[ 1 ] );
  164. node.channels = tokens.splice( 2, numChannels );
  165. node.children = [];
  166. }
  167. // read children
  168. while ( true ) {
  169. var line = nextLine( lines );
  170. if ( line === '}' ) {
  171. return node;
  172. } else {
  173. node.children.push( readNode( lines, line, list ) );
  174. }
  175. }
  176. }
  177. /*
  178. recursively converts the internal bvh node structure to a THREE.Bone hierarchy
  179. source: the bvh root node
  180. list: pass an empty array, collects a flat list of all converted THREE.Bones
  181. returns the root THREE.Bone
  182. */
  183. function toTHREEBone( source, list ) {
  184. var bone = new THREE.Bone();
  185. list.push( bone );
  186. bone.position.add( source.offset );
  187. bone.name = source.name;
  188. if ( source.type !== 'ENDSITE' ) {
  189. for ( var i = 0; i < source.children.length; i ++ ) {
  190. bone.add( toTHREEBone( source.children[ i ], list ) );
  191. }
  192. }
  193. return bone;
  194. }
  195. /*
  196. builds a THREE.AnimationClip from the keyframe data saved in each bone.
  197. bone: bvh root node
  198. returns: a THREE.AnimationClip containing position and quaternion tracks
  199. */
  200. function toTHREEAnimation( bones ) {
  201. var tracks = [];
  202. // create a position and quaternion animation track for each node
  203. for ( var i = 0; i < bones.length; i ++ ) {
  204. var bone = bones[ i ];
  205. if ( bone.type === 'ENDSITE' )
  206. continue;
  207. // track data
  208. var times = [];
  209. var positions = [];
  210. var rotations = [];
  211. for ( var j = 0; j < bone.frames.length; j ++ ) {
  212. var frame = bone.frames[ j ];
  213. times.push( frame.time );
  214. // the animation system animates the position property,
  215. // so we have to add the joint offset to all values
  216. positions.push( frame.position.x + bone.offset.x );
  217. positions.push( frame.position.y + bone.offset.y );
  218. positions.push( frame.position.z + bone.offset.z );
  219. rotations.push( frame.rotation.x );
  220. rotations.push( frame.rotation.y );
  221. rotations.push( frame.rotation.z );
  222. rotations.push( frame.rotation.w );
  223. }
  224. if ( scope.animateBonePositions ) {
  225. tracks.push( new THREE.VectorKeyframeTrack( '.bones[' + bone.name + '].position', times, positions ) );
  226. }
  227. if ( scope.animateBoneRotations ) {
  228. tracks.push( new THREE.QuaternionKeyframeTrack( '.bones[' + bone.name + '].quaternion', times, rotations ) );
  229. }
  230. }
  231. return new THREE.AnimationClip( 'animation', - 1, tracks );
  232. }
  233. /*
  234. returns the next non-empty line in lines
  235. */
  236. function nextLine( lines ) {
  237. var line;
  238. // skip empty lines
  239. while ( ( line = lines.shift().trim() ).length === 0 ) { }
  240. return line;
  241. }
  242. var scope = this;
  243. var lines = text.split( /[\r\n]+/g );
  244. var bones = readBvh( lines );
  245. var threeBones = [];
  246. toTHREEBone( bones[ 0 ], threeBones );
  247. var threeClip = toTHREEAnimation( bones );
  248. return {
  249. skeleton: new THREE.Skeleton( threeBones ),
  250. clip: threeClip
  251. };
  252. }
  253. } );