BVHLoader.js 8.6 KB

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