• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef sw_Half_hpp
16 #define sw_Half_hpp
17 
18 namespace sw
19 {
20 	class half
21 	{
22 	public:
23 		half() = default;
24 		half(const half& h) = default;
25 		explicit half(float f);
26 
27 		operator float() const;
28 
29 		half &operator=(const half& h) = default;
30 		half &operator=(float f);
31 
32 	private:
33 		unsigned short fp16i;
34 	};
35 
shortAsHalf(short s)36 	inline half shortAsHalf(short s)
37 	{
38 		union
39 		{
40 			half h;
41 			short s;
42 		} hs;
43 
44 		hs.s = s;
45 
46 		return hs.h;
47 	}
48 
49 	class RGB9E5
50 	{
51 		unsigned int R : 9;
52 		unsigned int G : 9;
53 		unsigned int B : 9;
54 		unsigned int E : 5;
55 
56 	public:
toRGB16F(half rgb[3]) const57 		void toRGB16F(half rgb[3]) const
58 		{
59 			constexpr int offset = 24;   // Exponent bias (15) + number of mantissa bits per component (9) = 24
60 
61 			const float factor = (1u << E) * (1.0f / (1 << offset));
62 			rgb[0] = half(R * factor);
63 			rgb[1] = half(G * factor);
64 			rgb[2] = half(B * factor);
65 		}
66 	};
67 
68 	class R11G11B10F
69 	{
70 		unsigned int R : 11;
71 		unsigned int G : 11;
72 		unsigned int B : 10;
73 
float11ToFloat16(unsigned short fp11)74 		static inline half float11ToFloat16(unsigned short fp11)
75 		{
76 			return shortAsHalf(fp11 << 4);   // Sign bit 0
77 		}
78 
float10ToFloat16(unsigned short fp10)79 		static inline half float10ToFloat16(unsigned short fp10)
80 		{
81 			return shortAsHalf(fp10 << 5);   // Sign bit 0
82 		}
83 
84 	public:
toRGB16F(half rgb[3]) const85 		void toRGB16F(half rgb[3]) const
86 		{
87 			rgb[0] = float11ToFloat16(R);
88 			rgb[1] = float11ToFloat16(G);
89 			rgb[2] = float10ToFloat16(B);
90 		}
91 	};
92 }
93 
94 #endif   // sw_Half_hpp
95