MDDLoader.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. ( function () {
  2. /**
  3. * MDD is a special format that stores a position for every vertex in a model for every frame in an animation.
  4. * Similar to BVH, it can be used to transfer animation data between different 3D applications or engines.
  5. *
  6. * MDD stores its data in binary format (big endian) in the following way:
  7. *
  8. * number of frames (a single uint32)
  9. * number of vertices (a single uint32)
  10. * time values for each frame (sequence of float32)
  11. * vertex data for each frame (sequence of float32)
  12. */
  13. class MDDLoader extends THREE.Loader {
  14. constructor( manager ) {
  15. super( manager );
  16. }
  17. load( url, onLoad, onProgress, onError ) {
  18. const scope = this;
  19. const loader = new THREE.FileLoader( this.manager );
  20. loader.setPath( this.path );
  21. loader.setResponseType( 'arraybuffer' );
  22. loader.load( url, function ( data ) {
  23. onLoad( scope.parse( data ) );
  24. }, onProgress, onError );
  25. }
  26. parse( data ) {
  27. const view = new DataView( data );
  28. const totalFrames = view.getUint32( 0 );
  29. const totalPoints = view.getUint32( 4 );
  30. let offset = 8; // animation clip
  31. const times = new Float32Array( totalFrames );
  32. const values = new Float32Array( totalFrames * totalFrames ).fill( 0 );
  33. for ( let i = 0; i < totalFrames; i ++ ) {
  34. times[ i ] = view.getFloat32( offset );
  35. offset += 4;
  36. values[ totalFrames * i + i ] = 1;
  37. }
  38. const track = new THREE.NumberKeyframeTrack( '.morphTargetInfluences', times, values );
  39. const clip = new THREE.AnimationClip( 'default', times[ times.length - 1 ], [ track ] ); // morph targets
  40. const morphTargets = [];
  41. for ( let i = 0; i < totalFrames; i ++ ) {
  42. const morphTarget = new Float32Array( totalPoints * 3 );
  43. for ( let j = 0; j < totalPoints; j ++ ) {
  44. const stride = j * 3;
  45. morphTarget[ stride + 0 ] = view.getFloat32( offset );
  46. offset += 4; // x
  47. morphTarget[ stride + 1 ] = view.getFloat32( offset );
  48. offset += 4; // y
  49. morphTarget[ stride + 2 ] = view.getFloat32( offset );
  50. offset += 4; // z
  51. }
  52. const attribute = new THREE.BufferAttribute( morphTarget, 3 );
  53. attribute.name = 'morph_' + i;
  54. morphTargets.push( attribute );
  55. }
  56. return {
  57. morphTargets: morphTargets,
  58. clip: clip
  59. };
  60. }
  61. }
  62. THREE.MDDLoader = MDDLoader;
  63. } )();