meshopt_rs/quantize.rs
1/// Quantizes a float in [0..1] range into an n-bit fixed point unorm value.
2///
3/// Assumes reconstruction function `q / (2^n-1)`, which is the case for fixed-function normalized fixed point conversion.
4///
5/// Maximum reconstruction error: `1/2^(n+1)`
6pub fn quantize_unorm(mut v: f32, n: i32) -> i32 {
7 let scale = ((1 << n) - 1) as f32;
8
9 v = if v >= 0.0 { v } else { 0.0 };
10 v = if v <= 1.0 { v } else { 1.0 };
11
12 (v * scale + 0.5) as i32
13}
14
15/// Quantizes a float in [-1..1] range into an n-bit fixed point snorm value.
16///
17/// Assumes reconstruction function `q / (2^(n-1)-1)`, which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions).
18///
19/// Maximum reconstruction error: `1/2^n`
20pub fn quantize_snorm(mut v: f32, n: i32) -> i32 {
21 let scale = ((1 << (n - 1)) - 1) as f32;
22
23 let round = if v >= 0.0 { 0.5 } else { -0.5 };
24
25 v = if v >= -1.0 { v } else { -1.0 };
26 v = if v <= 1.0 { v } else { 1.0 };
27
28 (v * scale + round) as i32
29}
30
31/// Quantizes a float into half-precision floating point value.
32///
33/// Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest.
34///
35/// Representable magnitude range: `[6e-5; 65504]`
36///
37/// Maximum relative reconstruction error: `5e-4`
38pub fn quantize_half(v: f32) -> u16 {
39 let ui: u32 = unsafe { std::mem::transmute(v) };
40
41 let s = (ui >> 16) & 0x8000;
42 let em = ui & 0x7fffffff;
43
44 /* bias exponent and round to nearest; 112 is relative exponent bias (127-15) */
45 let mut h = (em.wrapping_sub(112 << 23).wrapping_add(1 << 12)) >> 13;
46
47 /* underflow: flush to zero; 113 encodes exponent -14 */
48 h = if em < (113 << 23) { 0 } else { h };
49
50 /* overflow: infinity; 143 encodes exponent 16 */
51 h = if em >= (143 << 23) { 0x7c00 } else { h };
52
53 /* NaN; note that we convert all types of NaN to qNaN */
54 h = if em > (255 << 23) { 0x7e00 } else { h };
55
56 (s | h) as u16
57}
58
59/// Quantizes a float into a floating point value with a limited number of significant mantissa bits.
60///
61/// Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest.
62///
63/// Assumes `n` is in a valid mantissa precision range, which is 1..23
64pub fn quantize_float(v: f32, n: i32) -> f32 {
65 let mut ui: u32 = unsafe { std::mem::transmute(v) };
66
67 let mask: u32 = (1 << (23 - n)) - 1;
68 let round = (1 << (23 - n)) >> 1;
69
70 let e = ui & 0x7f800000;
71 let rui = (ui + round) & (!mask);
72
73 // round all numbers except inf/nan; this is important to make sure nan doesn't overflow into -0
74 ui = if e == 0x7f800000 { ui } else { rui };
75
76 // flush denormals to zero
77 ui = if e == 0 { 0 } else { ui };
78
79 unsafe { std::mem::transmute(ui) }
80}