BVHLoader.js 8.4 KB

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