HalfFloat.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Math/Vec4.h>
  6. JPH_NAMESPACE_BEGIN
  7. using HalfFloat = uint16;
  8. // Define half float constant values
  9. static constexpr HalfFloat HALF_FLT_MAX = 0x7bff;
  10. static constexpr HalfFloat HALF_FLT_MAX_NEGATIVE = 0xfbff;
  11. static constexpr HalfFloat HALF_FLT_INF = 0x7c00;
  12. static constexpr HalfFloat HALF_FLT_INF_NEGATIVE = 0xfc00;
  13. static constexpr HalfFloat HALF_FLT_NANQ = 0x7e00;
  14. static constexpr HalfFloat HALF_FLT_NANQ_NEGATIVE = 0xfe00;
  15. namespace HalfFloatConversion {
  16. // Layout of a float
  17. static constexpr int FLOAT_SIGN_POS = 31;
  18. static constexpr int FLOAT_EXPONENT_POS = 23;
  19. static constexpr int FLOAT_EXPONENT_BITS = 8;
  20. static constexpr int FLOAT_EXPONENT_MASK = (1 << FLOAT_EXPONENT_BITS) - 1;
  21. static constexpr int FLOAT_EXPONENT_BIAS = 127;
  22. static constexpr int FLOAT_MANTISSA_BITS = 23;
  23. static constexpr int FLOAT_MANTISSA_MASK = (1 << FLOAT_MANTISSA_BITS) - 1;
  24. static constexpr int FLOAT_EXPONENT_AND_MANTISSA_MASK = FLOAT_MANTISSA_MASK + (FLOAT_EXPONENT_MASK << FLOAT_EXPONENT_POS);
  25. // Layout of half float
  26. static constexpr int HALF_FLT_SIGN_POS = 15;
  27. static constexpr int HALF_FLT_EXPONENT_POS = 10;
  28. static constexpr int HALF_FLT_EXPONENT_BITS = 5;
  29. static constexpr int HALF_FLT_EXPONENT_MASK = (1 << HALF_FLT_EXPONENT_BITS) - 1;
  30. static constexpr int HALF_FLT_EXPONENT_BIAS = 15;
  31. static constexpr int HALF_FLT_MANTISSA_BITS = 10;
  32. static constexpr int HALF_FLT_MANTISSA_MASK = (1 << HALF_FLT_MANTISSA_BITS) - 1;
  33. static constexpr int HALF_FLT_EXPONENT_AND_MANTISSA_MASK = HALF_FLT_MANTISSA_MASK + (HALF_FLT_EXPONENT_MASK << HALF_FLT_EXPONENT_POS);
  34. /// Define half-float rounding modes
  35. enum ERoundingMode
  36. {
  37. ROUND_TO_NEG_INF, ///< Round to negative infinity
  38. ROUND_TO_POS_INF, ///< Round to positive infinity
  39. ROUND_TO_NEAREST, ///< Round to nearest value
  40. };
  41. /// Convert a float (32-bits) to a half float (16-bits), fallback version when no intrinsics available
  42. template <int RoundingMode>
  43. inline HalfFloat FromFloatFallback(float inV)
  44. {
  45. // Reinterpret the float as an uint32
  46. uint32 value = BitCast<uint32>(inV);
  47. // Extract exponent
  48. uint32 exponent = (value >> FLOAT_EXPONENT_POS) & FLOAT_EXPONENT_MASK;
  49. // Extract mantissa
  50. uint32 mantissa = value & FLOAT_MANTISSA_MASK;
  51. // Extract the sign and move it into the right spot for the half float (so we can just or it in at the end)
  52. HalfFloat hf_sign = HalfFloat(value >> (FLOAT_SIGN_POS - HALF_FLT_SIGN_POS)) & (1 << HALF_FLT_SIGN_POS);
  53. // Check NaN or INF
  54. if (exponent == FLOAT_EXPONENT_MASK) // NaN or INF
  55. return hf_sign | (mantissa == 0? HALF_FLT_INF : HALF_FLT_NANQ);
  56. // Rebias the exponent for half floats
  57. int rebiased_exponent = int(exponent) - FLOAT_EXPONENT_BIAS + HALF_FLT_EXPONENT_BIAS;
  58. // Check overflow to infinity
  59. if (rebiased_exponent >= HALF_FLT_EXPONENT_MASK)
  60. {
  61. bool round_up = RoundingMode == ROUND_TO_NEAREST || (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF);
  62. return hf_sign | (round_up? HALF_FLT_INF : HALF_FLT_MAX);
  63. }
  64. // Check underflow to zero
  65. if (rebiased_exponent < -HALF_FLT_MANTISSA_BITS)
  66. {
  67. bool round_up = RoundingMode != ROUND_TO_NEAREST && (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF) && (value & FLOAT_EXPONENT_AND_MANTISSA_MASK) != 0;
  68. return hf_sign | (round_up? 1 : 0);
  69. }
  70. HalfFloat hf_exponent;
  71. int shift;
  72. if (rebiased_exponent <= 0)
  73. {
  74. // Underflow to denormalized number
  75. hf_exponent = 0;
  76. mantissa |= 1 << FLOAT_MANTISSA_BITS; // Add the implicit 1 bit to the mantissa
  77. shift = FLOAT_MANTISSA_BITS - HALF_FLT_MANTISSA_BITS + 1 - rebiased_exponent;
  78. }
  79. else
  80. {
  81. // Normal half float
  82. hf_exponent = HalfFloat(rebiased_exponent << HALF_FLT_EXPONENT_POS);
  83. shift = FLOAT_MANTISSA_BITS - HALF_FLT_MANTISSA_BITS;
  84. }
  85. // Compose the half float
  86. HalfFloat hf_mantissa = HalfFloat(mantissa >> shift);
  87. HalfFloat hf = hf_sign | hf_exponent | hf_mantissa;
  88. // Calculate the remaining bits that we're discarding
  89. uint remainder = mantissa & ((1 << shift) - 1);
  90. if constexpr (RoundingMode == ROUND_TO_NEAREST)
  91. {
  92. // Round to nearest
  93. uint round_threshold = 1 << (shift - 1);
  94. if (remainder > round_threshold // Above threshold, we must always round
  95. || (remainder == round_threshold && (hf_mantissa & 1))) // When equal, round to nearest even
  96. hf++; // May overflow to infinity
  97. }
  98. else
  99. {
  100. // Round up or down (truncate) depending on the rounding mode
  101. bool round_up = (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF) && remainder != 0;
  102. if (round_up)
  103. hf++; // May overflow to infinity
  104. }
  105. return hf;
  106. }
  107. /// Convert a float (32-bits) to a half float (16-bits)
  108. template <int RoundingMode>
  109. JPH_INLINE HalfFloat FromFloat(float inV)
  110. {
  111. #ifdef JPH_USE_F16C
  112. union
  113. {
  114. __m128i u128;
  115. HalfFloat u16[8];
  116. } hf;
  117. __m128 val = _mm_load_ss(&inV);
  118. switch (RoundingMode)
  119. {
  120. case ROUND_TO_NEG_INF:
  121. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_NEG_INF);
  122. break;
  123. case ROUND_TO_POS_INF:
  124. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_POS_INF);
  125. break;
  126. case ROUND_TO_NEAREST:
  127. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_NEAREST_INT);
  128. break;
  129. }
  130. return hf.u16[0];
  131. #else
  132. return FromFloatFallback<RoundingMode>(inV);
  133. #endif
  134. }
  135. /// Convert 4 half floats (lower 64 bits) to floats, fallback version when no intrinsics available
  136. inline Vec4 ToFloatFallback(UVec4Arg inValue)
  137. {
  138. // Unpack half floats to 4 uint32's
  139. UVec4 value = inValue.Expand4Uint16Lo();
  140. // Normal half float path, extract the exponent and mantissa, shift them into place and update the exponent bias
  141. UVec4 exponent_mantissa = UVec4::sAnd(value, UVec4::sReplicate(HALF_FLT_EXPONENT_AND_MANTISSA_MASK)).LogicalShiftLeft<FLOAT_EXPONENT_POS - HALF_FLT_EXPONENT_POS>() + UVec4::sReplicate((FLOAT_EXPONENT_BIAS - HALF_FLT_EXPONENT_BIAS) << FLOAT_EXPONENT_POS);
  142. // Denormalized half float path, renormalize the float
  143. UVec4 exponent_mantissa_denormalized = ((exponent_mantissa + UVec4::sReplicate(1 << FLOAT_EXPONENT_POS)).ReinterpretAsFloat() - UVec4::sReplicate((FLOAT_EXPONENT_BIAS - HALF_FLT_EXPONENT_BIAS + 1) << FLOAT_EXPONENT_POS).ReinterpretAsFloat()).ReinterpretAsInt();
  144. // NaN / INF path, set all exponent bits
  145. UVec4 exponent_mantissa_nan_inf = UVec4::sOr(exponent_mantissa, UVec4::sReplicate(FLOAT_EXPONENT_MASK << FLOAT_EXPONENT_POS));
  146. // Get the exponent to determine which of the paths we should take
  147. UVec4 exponent_mask = UVec4::sReplicate(HALF_FLT_EXPONENT_MASK << HALF_FLT_EXPONENT_POS);
  148. UVec4 exponent = UVec4::sAnd(value, exponent_mask);
  149. UVec4 is_denormalized = UVec4::sEquals(exponent, UVec4::sZero());
  150. UVec4 is_nan_inf = UVec4::sEquals(exponent, exponent_mask);
  151. // Select the correct result
  152. UVec4 result_exponent_mantissa = UVec4::sSelect(UVec4::sSelect(exponent_mantissa, exponent_mantissa_nan_inf, is_nan_inf), exponent_mantissa_denormalized, is_denormalized);
  153. // Extract the sign bit and shift it to the left
  154. UVec4 sign = UVec4::sAnd(value, UVec4::sReplicate(1 << HALF_FLT_SIGN_POS)).LogicalShiftLeft<FLOAT_SIGN_POS - HALF_FLT_SIGN_POS>();
  155. // Construct the float
  156. return UVec4::sOr(sign, result_exponent_mantissa).ReinterpretAsFloat();
  157. }
  158. /// Convert 4 half floats (lower 64 bits) to floats
  159. JPH_INLINE Vec4 ToFloat(UVec4Arg inValue)
  160. {
  161. #if defined(JPH_USE_F16C)
  162. return _mm_cvtph_ps(inValue.mValue);
  163. #elif defined(JPH_USE_NEON)
  164. return vcvt_f32_f16(vreinterpret_f16_f32(vget_low_f32(inValue.mValue)));
  165. #else
  166. return ToFloatFallback(inValue);
  167. #endif
  168. }
  169. } // HalfFloatConversion
  170. JPH_NAMESPACE_END