Skip to main content

vello_encoding/
math.rs

1// Copyright 2022 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::ops::Mul;
5
6use bytemuck::{Pod, Zeroable};
7use peniko::kurbo;
8
9/// Affine transformation matrix.
10#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
11#[repr(C)]
12pub struct Transform {
13    /// 2x2 matrix.
14    pub matrix: [f32; 4],
15    /// Translation.
16    pub translation: [f32; 2],
17}
18
19impl Transform {
20    /// Identity transform.
21    pub const IDENTITY: Self = Self {
22        matrix: [1.0, 0.0, 0.0, 1.0],
23        translation: [0.0; 2],
24    };
25
26    /// Creates a transform from a kurbo affine matrix.
27    pub fn from_kurbo(transform: &kurbo::Affine) -> Self {
28        let c = transform.as_coeffs().map(|x| x as f32);
29        Self {
30            matrix: [c[0], c[1], c[2], c[3]],
31            translation: [c[4], c[5]],
32        }
33    }
34
35    /// Converts the transform to a kurbo affine matrix.
36    pub fn to_kurbo(&self) -> kurbo::Affine {
37        kurbo::Affine::new(
38            [
39                self.matrix[0],
40                self.matrix[1],
41                self.matrix[2],
42                self.matrix[3],
43                self.translation[0],
44                self.translation[1],
45            ]
46            .map(|x| x as f64),
47        )
48    }
49}
50
51impl Mul for Transform {
52    type Output = Self;
53
54    #[inline]
55    fn mul(self, other: Self) -> Self {
56        Self {
57            matrix: [
58                self.matrix[0] * other.matrix[0] + self.matrix[2] * other.matrix[1],
59                self.matrix[1] * other.matrix[0] + self.matrix[3] * other.matrix[1],
60                self.matrix[0] * other.matrix[2] + self.matrix[2] * other.matrix[3],
61                self.matrix[1] * other.matrix[2] + self.matrix[3] * other.matrix[3],
62            ],
63            translation: [
64                self.matrix[0] * other.translation[0]
65                    + self.matrix[2] * other.translation[1]
66                    + self.translation[0],
67                self.matrix[1] * other.translation[0]
68                    + self.matrix[3] * other.translation[1]
69                    + self.translation[1],
70            ],
71        }
72    }
73}
74
75pub fn point_to_f32(point: kurbo::Point) -> [f32; 2] {
76    [point.x as f32, point.y as f32]
77}
78
79/// Converts an `f32` to IEEE-754 binary16 format represented as the bits of a `u16`.
80///
81/// This implementation was adapted from Fabian Giesen's `float_to_half_fast3`()
82/// function which can be found at <https://gist.github.com/rygorous/2156668#file-gistfile1-cpp-L285>
83///
84/// TODO: We should consider adopting <https://crates.io/crates/half> as a dependency since it nicely
85/// wraps native ARM and x86 instructions for floating-point conversion.
86pub(crate) fn f32_to_f16(val: f32) -> u16 {
87    const INF_32: u32 = 255 << 23;
88    const INF_16: u32 = 31 << 23;
89    const MAGIC: u32 = 15 << 23;
90    const SIGN_MASK: u32 = 0x8000_0000_u32;
91    const ROUND_MASK: u32 = !0xFFF_u32;
92
93    let u = val.to_bits();
94    let sign = u & SIGN_MASK;
95    let u = u ^ sign;
96
97    // NOTE all the integer compares in this function can be safely
98    // compiled into signed compares since all operands are below
99    // 0x80000000. Important if you want fast straight SSE2 code
100    // (since there's no unsigned PCMPGTD).
101
102    // Inf or NaN (all exponent bits set)
103    let output: u16 = if u >= INF_32 {
104        // NaN -> qNaN and Inf->Inf
105        if u > INF_32 { 0x7E00 } else { 0x7C00 }
106    } else {
107        // (De)normalized number or zero
108        let mut u = u & ROUND_MASK;
109        u = (f32::from_bits(u) * f32::from_bits(MAGIC)).to_bits();
110        u = u.overflowing_sub(ROUND_MASK).0;
111
112        // Clamp to signed infinity if exponent overflowed
113        if u > INF_16 {
114            u = INF_16;
115        }
116        (u >> 13) as u16 // Take the bits!
117    };
118    output | (sign >> 16) as u16
119}
120
121/// Converts a 16-bit precision IEEE-754 binary16 float to a `f32`.
122///
123/// This implementation was adapted from Fabian Giesen's `half_to_float()`
124/// function which can be found at <https://gist.github.com/rygorous/2156668#file-gistfile1-cpp-L574>
125pub fn f16_to_f32(bits: u16) -> f32 {
126    let bits = bits as u32;
127    const MAGIC: u32 = 113 << 23;
128    const SHIFTED_EXP: u32 = 0x7c00 << 13; // exponent mask after shift
129
130    let mut o = (bits & 0x7fff) << 13; // exponent/mantissa bits
131    let exp = SHIFTED_EXP & o; // just the exponent
132    o += (127 - 15) << 23; // exponent adjust
133
134    // handle exponent special cases
135    if exp == SHIFTED_EXP {
136        // Inf/NaN?
137        o += (128 - 16) << 23; // extra exp adjust
138    } else if exp == 0 {
139        // Zero/Denormal?
140        o += 1 << 23; // extra exp adjust
141        o = (f32::from_bits(o) - f32::from_bits(MAGIC)).to_bits(); // normalize
142    }
143
144    f32::from_bits(o | ((bits & 0x8000) << 16)) // sign bit
145}
146
147#[cfg(test)]
148mod tests {
149    use super::{f16_to_f32, f32_to_f16};
150
151    #[test]
152    fn test_f32_to_f16_simple() {
153        let input: f32 = std::f32::consts::PI;
154        let output: u16 = f32_to_f16(input);
155        assert_eq!(0x4248_u16, output); // 3.141
156    }
157
158    #[test]
159    fn test_f32_to_f16_nan_overflow() {
160        // A signaling NaN with unset high bits but a low bit that could get accidentally masked
161        // should get converted to a quiet NaN and not infinity.
162        let input: f32 = f32::from_bits(0x7F800001_u32);
163        assert!(input.is_nan());
164        let output: u16 = f32_to_f16(input);
165        assert_eq!(0x7E00, output);
166    }
167
168    #[test]
169    fn test_f32_to_f16_inf() {
170        let input: f32 = f32::from_bits(0x7F800000_u32);
171        assert!(input.is_infinite());
172        let output: u16 = f32_to_f16(input);
173        assert_eq!(0x7C00, output);
174    }
175
176    #[test]
177    fn test_f32_to_f16_exponent_rebias() {
178        let input: f32 = 0.00003051758;
179        let output: u16 = f32_to_f16(input);
180        assert_eq!(0x0200, output); // 0.00003052
181    }
182
183    #[test]
184    fn test_f32_to_f16_exponent_overflow() {
185        let input: f32 = 1.701412e38;
186        let output: u16 = f32_to_f16(input);
187        assert_eq!(0x7C00, output); // +inf
188    }
189
190    #[test]
191    fn test_f32_to_f16_exponent_overflow_neg_inf() {
192        let input: f32 = -1.701412e38;
193        let output: u16 = f32_to_f16(input);
194        assert_eq!(0xFC00, output); // -inf
195    }
196
197    #[test]
198    fn test_f16_to_f32_simple() {
199        let input: u16 = 0x4248_u16;
200        let output: f32 = f16_to_f32(input);
201        assert_eq!(3.140625, output);
202    }
203
204    #[test]
205    fn test_f16_to_f32_inf() {
206        let input: u16 = 0x7C00;
207        let output = f16_to_f32(input);
208        assert!(output.is_infinite());
209    }
210
211    #[test]
212    fn test_f16_to_f32_neg_inf() {
213        let input: u16 = 0xFC00;
214        let output = f16_to_f32(input);
215        assert!(output.is_infinite());
216    }
217
218    #[test]
219    fn test_f16_to_f32_inf_roundtrip() {
220        let input: u16 = 0x7C00;
221        let output = f32_to_f16(f16_to_f32(input));
222        assert_eq!(input, output);
223    }
224
225    #[test]
226    fn test_f16_to_f32_neg_inf_roundtrip() {
227        let input: u16 = 0xFC00;
228        let output = f32_to_f16(f16_to_f32(input));
229        assert_eq!(input, output);
230    }
231
232    #[test]
233    fn test_f16_to_f32_nan() {
234        let input: u16 = 0x7C01;
235        let output = f16_to_f32(input);
236        assert!(output.is_nan());
237    }
238
239    #[test]
240    fn test_f16_to_f32_nan_roundtrip() {
241        let input: u16 = 0x7C01;
242        // Roundtrip 3 times and land on a f32 to check that NaN'ness is preserved.
243        let output = f16_to_f32(f32_to_f16(f16_to_f32(input)));
244        assert!(output.is_nan());
245    }
246
247    #[test]
248    fn test_f16_to_f32_large_pos_roundtrip() {
249        let input: u16 = 0x7BFF; // 65504.0
250        let output = f32_to_f16(f16_to_f32(input));
251        assert_eq!(input, output);
252    }
253
254    #[test]
255    fn test_f16_to_f32_large_neg_roundtrip() {
256        let input: u16 = 0xFBFF; // -65504.0
257        let output = f32_to_f16(f16_to_f32(input));
258        assert_eq!(input, output);
259    }
260
261    #[test]
262    fn test_f16_to_f32_small_pos_roundtrip() {
263        let input: u16 = 0x0001; // 5.97e-8
264        let output = f32_to_f16(f16_to_f32(input));
265        assert_eq!(input, output);
266    }
267
268    #[test]
269    fn test_f16_to_f32_small_neg_roundtrip() {
270        let input: u16 = 0x8001; // -5.97e-8
271        let output = f32_to_f16(f16_to_f32(input));
272        assert_eq!(input, output);
273    }
274
275    #[test]
276    fn test_f16_to_f32_roundtrip() {
277        const EPS: f32 = 0.001;
278        let input: f32 = std::f32::consts::PI;
279        assert!((input - f16_to_f32(f32_to_f16(input))).abs() < EPS);
280    }
281}