DataUtils.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const _floatView = new Float32Array( 1 );
  2. const _int32View = new Int32Array( _floatView.buffer );
  3. const DataUtils = {
  4. // Converts float32 to float16 (stored as uint16 value).
  5. toHalfFloat: function ( val ) {
  6. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  7. /* This method is faster than the OpenEXR implementation (very often
  8. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  9. * by James Tursa?s half-precision code. */
  10. _floatView[ 0 ] = val;
  11. const x = _int32View[ 0 ];
  12. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  13. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  14. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  15. /* If zero, or denormal, or exponent underflows too much for a denormal
  16. * half, return signed zero. */
  17. if ( e < 103 ) return bits;
  18. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  19. if ( e > 142 ) {
  20. bits |= 0x7c00;
  21. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  22. * not Inf, so make sure we set one mantissa bit too. */
  23. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  24. return bits;
  25. }
  26. /* If exponent underflows but not too much, return a denormal */
  27. if ( e < 113 ) {
  28. m |= 0x0800;
  29. /* Extra rounding may overflow and set mantissa to 0 and exponent
  30. * to 1, which is OK. */
  31. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  32. return bits;
  33. }
  34. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  35. /* Extra rounding. An overflow will set mantissa to 0 and increment
  36. * the exponent, which is OK. */
  37. bits += m & 1;
  38. return bits;
  39. }
  40. };
  41. export { DataUtils };
粤ICP备19079148号