BVHLoader.js 8.9 KB

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