Math.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. */
  4. THREE.Math = {
  5. // Clamp value to range <a, b>
  6. clamp: function ( x, a, b ) {
  7. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  8. },
  9. // Clamp value to range <a, inf)
  10. clampBottom: function ( x, a ) {
  11. return x < a ? a : x;
  12. },
  13. // Linear mapping from range <a1, a2> to range <b1, b2>
  14. mapLinear: function ( x, a1, a2, b1, b2 ) {
  15. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  16. },
  17. // http://en.wikipedia.org/wiki/Smoothstep
  18. smoothStep: function ( x, min, max ) {
  19. if( x <= min ) {
  20. return 0;
  21. }
  22. if( x >= max ) {
  23. return 1;
  24. }
  25. // normalize
  26. x = ( x - min )/( max - min );
  27. return x*x*(3 - 2*x);
  28. },
  29. // http://en.wikipedia.org/wiki/Smoothstep
  30. smootherStep: function ( x, min, max ) {
  31. if( x <= min ) {
  32. return 0;
  33. }
  34. if( x >= max ) {
  35. return 1;
  36. }
  37. // normalize
  38. x = ( x - min )/( max - min );
  39. return x*x*x*(x*(x*6 - 15) + 10);
  40. },
  41. // Random float from <0, 1> with 16 bits of randomness
  42. // (standard Math.random() creates repetitive patterns when applied over larger space)
  43. random16: function () {
  44. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  45. },
  46. // Random integer from <low, high> interval
  47. randInt: function ( low, high ) {
  48. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  49. },
  50. // Random float from <low, high> interval
  51. randFloat: function ( low, high ) {
  52. return low + Math.random() * ( high - low );
  53. },
  54. // Random float from <-range/2, range/2> interval
  55. randFloatSpread: function ( range ) {
  56. return range * ( 0.5 - Math.random() );
  57. },
  58. sign: function ( x ) {
  59. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  60. },
  61. degToRad: function() {
  62. var degreeToRadiansFactor = Math.PI / 180;
  63. return function ( degrees ) {
  64. return degrees * degreeToRadiansFactor;
  65. };
  66. }(),
  67. radToDeg: function() {
  68. var radianToDegreesFactor = 180 / Math.PI;
  69. return function ( radians ) {
  70. return radians * radianToDegreesFactor;
  71. };
  72. }()
  73. };
粤ICP备19079148号