1 /**************************************************************************
3 * Copyright 2010 Luca Barbieri
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
13 * The above copyright notice and this permission notice (including the
14 * next paragraph) shall be included in all copies or substantial
15 * portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 **************************************************************************/
31 #include "pipe/p_compiler.h"
32 #include "util/u_math.h"
39 * References for float <-> half conversions
41 * http://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/
42 * https://gist.github.com/2156668
43 * https://gist.github.com/2144712
46 static inline uint16_t
47 util_float_to_half(float f
)
49 uint32_t sign_mask
= 0x80000000;
50 uint32_t round_mask
= ~0xfff;
51 uint32_t f32inf
= 0xff << 23;
52 uint32_t f16inf
= 0x1f << 23;
63 sign
= f32
.ui
& sign_mask
;
66 if (f32
.ui
== f32inf
) {
69 } else if (f32
.ui
> f32inf
) {
78 * XXX: The magic mul relies on denorms being available, otherwise
79 * all f16 denorms get flushed to zero - hence when this is used
80 * for tgsi_exec in softpipe we won't get f16 denorms.
83 * Clamp to max finite value if overflowed.
84 * OpenGL has completely undefined rounding behavior for float to
85 * half-float conversions, and this matches what is mandated for float
86 * to fp11/fp10, which recommend round-to-nearest-finite too.
87 * (d3d10 is deeply unhappy about flushing such values to infinity, and
88 * while it also mandates round-to-zero it doesn't care nearly as much
104 util_half_to_float(uint16_t f16
)
110 infnan
.ui
= 0x8f << 23;
112 magic
.ui
= 0xef << 23;
114 /* Exponent / Mantissa */
115 f32
.ui
= (f16
& 0x7fff) << 13;
119 /* XXX: The magic mul relies on denorms being available */
122 if (f32
.f
>= infnan
.f
)
123 f32
.ui
|= 0xff << 23;
126 f32
.ui
|= (f16
& 0x8000) << 16;
135 #endif /* U_HALF_H */