Half.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  3. */
  4. THREE.toHalf = (function() {
  5. var floatView = new Float32Array(1);
  6. var int32View = new Int32Array(floatView.buffer);
  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. return function toHalf(val) {
  11. floatView[0] = val;
  12. var x = int32View[0];
  13. var bits = (x >> 16) & 0x8000; /* Get the sign */
  14. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  15. var e = (x >> 23) & 0xff; /* Using int is faster here */
  16. /* If zero, or denormal, or exponent underflows too much for a denormal
  17. * half, return signed zero. */
  18. if (e < 103) {
  19. return bits;
  20. }
  21. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  22. if (e > 142) {
  23. bits |= 0x7c00;
  24. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  25. * not Inf, so make sure we set one mantissa bit too. */
  26. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  27. return bits;
  28. }
  29. /* If exponent underflows but not too much, return a denormal */
  30. if (e < 113) {
  31. m |= 0x0800;
  32. /* Extra rounding may overflow and set mantissa to 0 and exponent
  33. * to 1, which is OK. */
  34. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  35. return bits;
  36. }
  37. bits |= ((e - 112) << 10) | (m >> 1);
  38. /* Extra rounding. An overflow will set mantissa to 0 and increment
  39. * the exponent, which is OK. */
  40. bits += m & 1;
  41. return bits;
  42. };
  43. }());