KeyframeTrack.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. *
  3. * A Track that returns a keyframe interpolated value.
  4. *
  5. * TODO: Add cubic in addition to linear interpolation.
  6. *
  7. * @author Ben Houston / http://clara.io/
  8. * @author David Sarno / http://lighthaus.us/
  9. */
  10. THREE.KeyframeTrack = function ( name, keys ) {
  11. this.name = name;
  12. this.keys = keys || []; // time in seconds, value as value
  13. // TODO: sort keys via their times
  14. //this.keys.sort( function( a, b ) { return a.time < b.time; } );
  15. };
  16. THREE.KeyframeTrack.prototype = {
  17. constructor: THREE.KeyframeTrack,
  18. getAt: function( time ) {
  19. console.log( 'KeyframeTrack[' + this.name + '].getAt( ' + time + ' )' );
  20. if( this.keys.length == 0 ) throw new Error( "no keys in track named " + this.name );
  21. console.log( "keys", this.keys );
  22. // before the start of the track, return the first key value
  23. if( this.keys[0].time >= time ) {
  24. console.log( ' before: ' + this.keys[0].value );
  25. return this.keys[0].value;
  26. }
  27. // past the end of the track, return the last key value
  28. if( this.keys[ this.keys.length - 1 ].time <= time ) {
  29. console.log( ' after: ' + this.keys[ this.keys.length - 1 ].value );
  30. return this.keys[ this.keys.length - 1 ].value;
  31. }
  32. // interpolate to the required time
  33. for( var i = 1; i < this.keys.length; i ++ ) {
  34. if( time <= this.keys[ i ].time ) {
  35. // linear interpolation to start with
  36. var alpha = ( time - this.keys[ i - 1 ].time ) / ( this.keys[ i ].time - this.keys[ i - 1 ].time );
  37. var interpolatedValue = THREE.AnimationUtils.lerp( this.keys[ i - 1 ].value, this.keys[ i ].value, alpha );
  38. console.log( ' interpolated: ', {
  39. value: interpolatedValue,
  40. alpha: alpha,
  41. time0: this.keys[ i - 1 ].time,
  42. time1: this.keys[ i ].time,
  43. value0: this.keys[ i - 1 ].value,
  44. value1: this.keys[ i ].value
  45. } );
  46. return interpolatedValue;
  47. }
  48. }
  49. throw new Error( "should never get here." );
  50. }
  51. };