Skip to main content

unbanished_core/
crt.rs

1//! The float functions of the Microsoft C runtime, as the game calls them: [`sinf`], [`cosf`],
2//! [`acosf`] and [`atan2f`], and the compiler's float-to-integer conversion, [`truncate`].
3//!
4//! These functions are not correctly rounded, so their results can differ from Rust's `f32::sin`
5//! and its relatives in the last bit. That is enough to change the game's results. So this module
6//! ports the C runtime's own algorithms, operation by operation, and simulation code uses them.
7//! `tools/emu/crt_math.py` checks them against the original functions. `powf`, `floorf` and
8//! `sqrtf` are correctly rounded in both, so Rust's own functions give the same results.
9//!
10//! ```
11//! use unbanished_core::crt;
12//!
13//! let s = crt::sinf(0.5);
14//! let angle = crt::atan2f(1.0, 2.0);
15//! assert!(s > 0.47 && angle > 0.46);
16//! ```
17//!
18//! Original: `FUN_140137160` (`sinf`, the Runtime's copy at `0x18012a620` is the same),
19//! `FUN_140136560` (`cosf`, Runtime `0x1801295a0`), `FUN_140136090` (`acosf`), Runtime
20//! `0x180128f10` (`atan2f`, behind `Vector3::Heading`).
21
22// The constants below are the runtime's own, written as read from its data. Some are close to
23// the standard library's constants, or have more digits than an f32 or f64 holds; they stay as
24// read, so each one can be checked against the address it came from.
25#![allow(clippy::approx_constant, clippy::excessive_precision)]
26
27mod atan_table;
28use atan_table::ATAN_TABLE;
29
30const fn d(bits: u64) -> f64 {
31    f64::from_bits(bits)
32}
33
34// FUN_140137160's constants (`0x140183190..0x1401832a0`).
35const S_ONE: f64 = 1.0;
36const S_HALF: f64 = 0.5;
37const S_SIXTH: f64 = 0.16666666666666666;
38const S_2_PI: f64 = 0.6366197723675814;
39const S_PIO2_1: f64 = 1.5707963267341256;
40const S_PIO2_1T: f64 = 6.077100506506192e-11;
41const S_PIO2_2: f64 = 6.077100506303966e-11;
42const S_PIO2_2T: f64 = 2.0222662487959506e-21;
43const S_BIG: u64 = 0x411e_8480_0000_0000; // 500000.0
44const S_S1: f64 = -0.16666666666666666;
45const S_S2: f64 = 0.008333333333333333;
46const S_S3: f64 = -0.0001984126984126984;
47const S_S4: f64 = 2.7557319223985893e-06;
48const S_C0: f64 = -0.5;
49const S_C1: f64 = 0.041666666666666664;
50const S_C2: f64 = -0.0013888888888888887;
51const S_C3: f64 = 2.4801587301587298e-05;
52const S_C4: f64 = -2.755731922398589e-07;
53
54// FUN_140136560's polynomial (`0x140182610..0x140182648`).
55const C_S1: f64 = -0.16666666666666666;
56const C_S2: f64 = 0.00833333333333095;
57const C_S3: f64 = -0.00019841269836761127;
58const C_S4: f64 = 2.7557316103728802e-06;
59const C_C1: f64 = 0.041666666666666664;
60const C_C2: f64 = -0.0013888888888887398;
61const C_C3: f64 = 2.480158729876704e-05;
62const C_C4: f64 = -2.755731727234419e-07;
63
64/// The `π/2` reduction both use: the region and the reduced argument, and the exponent the
65/// small cases are told by (taken before the extra precision step).
66fn reduce(x: f64, ax: u64) -> (u32, f64, u64) {
67    let region = ((x * S_2_PI) + S_HALF) as i32;
68    let dr = region as f64;
69    let r1 = x - S_PIO2_1 * dr;
70    let mut r = r1 - S_PIO2_1T * dr;
71    let er = (r.to_bits() << 1) >> 53;
72    if 15 < (ax >> 52) as i64 - er as i64 {
73        let t = S_PIO2_2 * dr;
74        let r2 = r1 - t;
75        let tail = S_PIO2_2T * dr - ((r1 - r2) - t);
76        r = r2 - tail;
77    }
78    (region as u32, r, er)
79}
80
81fn sin_poly(r: f64, x2: f64, s1: f64, s2: f64, s3: f64, s4: f64) -> f64 {
82    let x4 = x2 * x2;
83    let p = (s4 * x2 + s3) * x4 + (s2 * x2 + s1);
84    p * (r * x2) + r
85}
86
87/// The sine of `x` (radians), as the C runtime's `sinf` computes it.
88///
89/// Original: `FUN_140137160`.
90pub fn sinf(x: f32) -> f32 {
91    if x.to_bits() & 0x7f80_0000 == 0x7f80_0000 {
92        return f32::NAN;
93    }
94    let xd = x as f64;
95    let ax = xd.to_bits() & 0x7fff_ffff_ffff_ffff;
96    if ax <= 0x3fe9_21fb_5444_2d18 {
97        if ax < 0x3f80_0000_0000_0000 {
98            if ax < 0x3f20_0000_0000_0000 {
99                return x;
100            }
101            return (xd - ((xd * xd) * xd) * S_SIXTH) as f32;
102        }
103        let x2 = xd * xd;
104        return sin_poly(xd, x2, S_S1, S_S2, S_S3, S_S4) as f32;
105    }
106    let neg = xd.to_bits() != ax;
107    let v = if neg { 0.0 - xd } else { xd };
108    let (region, r, er) = if ax < S_BIG {
109        reduce(v, ax)
110    } else {
111        // `__remainder_piby2f_inline`: past 500000, which the game never passes.
112        return (xd.sin()) as f32;
113    };
114    let odd = region & 1 != 0;
115    let mut out = if er >= 0x3f2 {
116        let x2 = r * r;
117        if odd {
118            let x4 = x2 * x2;
119            let p = ((S_C4 * x2 + S_C3) * x4 + (S_C2 * x2 + S_C1)) * x4;
120            (S_C0 * x2 + S_ONE) + p
121        } else {
122            sin_poly(r, x2, S_S1, S_S2, S_S3, S_S4)
123        }
124    } else if er > 0x3de {
125        let x2 = r * r;
126        if odd {
127            S_ONE - x2 * S_HALF
128        } else {
129            r - (S_SIXTH * r) * x2
130        }
131    } else if odd {
132        S_ONE
133    } else {
134        r
135    };
136    let q = (region >> 1) & 1;
137    if q != neg as u32 {
138        out = 0.0 - out;
139    }
140    out as f32
141}
142
143/// The cosine of `x` (radians), as the C runtime's `cosf` computes it.
144///
145/// Original: `FUN_140136560`.
146pub fn cosf(x: f32) -> f32 {
147    if x.to_bits() & 0x7f80_0000 == 0x7f80_0000 {
148        return f32::NAN;
149    }
150    let xd = x as f64;
151    let ax = xd.to_bits() & 0x7fff_ffff_ffff_ffff;
152    let (region, r, er) = if ax <= 0x3fe9_21fb_5444_2d18 {
153        (0, xd, 0x3f2)
154    } else {
155        let v = if xd.to_bits() != ax { 0.0 - xd } else { xd };
156        if ax < S_BIG {
157            reduce(v, ax)
158        } else {
159            // `__remainder_piby2f_inline`: past 500000, which the game never passes.
160            return (xd.cos()) as f32;
161        }
162    };
163    let odd = region & 1 != 0;
164    let x2 = r * r;
165    let mut out = if er >= 0x3f2 {
166        let x4 = x2 * x2;
167        if odd {
168            ((C_S4 * x2 + C_S3) * x4 + (C_S2 * x2 + C_S1)) * (x2 * r) + r
169        } else {
170            let p = ((C_C4 * x2 + C_C3) * x4 + (C_C2 * x2 + C_C1)) * x4;
171            p - (S_HALF * x2 - S_ONE)
172        }
173    } else if er > 0x3de {
174        if odd {
175            r - (S_SIXTH * r) * x2
176        } else {
177            S_ONE - x2 * S_HALF
178        }
179    } else if odd {
180        r
181    } else {
182        S_ONE
183    };
184    if (region.wrapping_add(1)) & 2 != 0 {
185        out = 0.0 - out;
186    }
187    out as f32
188}
189
190/// The arc cosine of `x`, in radians, as the C runtime's `acosf` computes it.
191///
192/// Original: `FUN_140136090`.
193pub fn acosf(x: f32) -> f32 {
194    const P0: f32 = -0.013381929136812687;
195    const P1: f32 = 0.003961374517530203;
196    const P2: f32 = 0.05652986839413643;
197    const P3: f32 = 0.18416160345077515;
198    const Q0: f32 = 1.1049696207046509;
199    const Q1: f32 = 0.8364112973213196;
200    const PIO2_F: f32 = 1.5707963705062866;
201    const PI_F: f32 = 3.1415927410125732;
202    const PIO2_LO: f64 = 6.123233995736766e-17;
203    const PIO2: f64 = 1.5707963267948966;
204    const PI: f64 = 3.141592653589793;
205    let ux = x.to_bits();
206    let negative = ux & 0x8000_0000 != 0;
207    let e = ((ux >> 23) & 0xff) as i32 - 127;
208    if ux & 0x7fff_ffff > 0x7f80_0000 {
209        return f32::from_bits(ux | 0x0040_0000);
210    }
211    if e < -26 {
212        return PIO2_F;
213    }
214    if 0 <= e {
215        return if x == 1.0 {
216            0.0
217        } else if x == -1.0 {
218            PI_F
219        } else {
220            f32::NAN
221        };
222    }
223    let mut ax = if negative { -x } else { x };
224    let transform = -1 <= e;
225    let (r, s) = if transform {
226        let r = (1.0 - ax) * 0.5;
227        let s = r.sqrt();
228        ax = s;
229        (r, s)
230    } else {
231        (ax * ax, 0.0)
232    };
233    let mut p = P0 - r * P1;
234    p *= r;
235    p -= P2;
236    p *= r;
237    p += P3;
238    p *= r;
239    let q = Q0 - r * Q1;
240    let u = p / q;
241    if transform {
242        if negative {
243            let t = (((u * ax) as f64 - PIO2_LO) + s as f64) * 2.0;
244            (PI - t) as f32
245        } else {
246            let c = f32::from_bits(s.to_bits() & 0xffff_0000);
247            let a = (2.0 * ax) * u;
248            let b = ((r - c * c) / (c + s)) * 2.0;
249            b + a + c * 2.0
250        }
251    } else {
252        let t = (x as f64) - (PIO2_LO - (u * x) as f64);
253        (PIO2 - t) as f32
254    }
255}
256
257/// The angle of the point `(x, y)`, in radians from -π to π, as the C runtime's `atan2f`
258/// computes it.
259///
260/// Original: Runtime `0x180128f10`.
261pub fn atan2f(y: f32, x: f32) -> f32 {
262    const SIGN: u64 = 0x8000_0000_0000_0000;
263    const ABS: u64 = 0x7fff_ffff_ffff_ffff;
264    const INF: u64 = 0x7ff0_0000_0000_0000;
265    const PI: f64 = 3.141592653589793;
266    const PIO2: f64 = 1.5707963267948966;
267    const PIO4: f64 = 0.7853981633974483;
268    const PI3O4: f64 = 2.356194490192345;
269    let (yd, xd) = (y as f64, x as f64);
270    let (yb, xb) = (yd.to_bits(), xd.to_bits());
271    let (ysign, xsign) = (yb & SIGN != 0, xb & SIGN != 0);
272    let (ay, ax) = (yb & ABS, xb & ABS);
273    let diff = ((yb >> 52) & 0x7ff) as i32 - ((xb >> 52) & 0x7ff) as i32;
274    let signed = |v: f64, neg: bool| (if neg { -v } else { v }) as f32;
275    if ax > INF {
276        return f32::from_bits(x.to_bits() | 0x0040_0000);
277    }
278    if ay > INF {
279        return f32::from_bits(y.to_bits() | 0x0040_0000);
280    }
281    if ay == 0 {
282        return if xsign { signed(PI, ysign) } else { yd as f32 };
283    }
284    if ax == 0 && ysign {
285        return signed(PIO2, true);
286    }
287    if 26 < diff {
288        return signed(PIO2, ysign);
289    }
290    if diff < -13 && !xsign {
291        if diff < -150 {
292            return if ysign { -0.0 } else { 0.0 };
293        }
294        if diff >= -126 {
295            return (yd / xd) as f32;
296        }
297        // A result too small for a normal float: scaled by 2^100 and unscaled by hand.
298        let f = (d(0x4630_0000_0000_0000) * yd) / xd;
299        let sign = f.to_bits() & SIGN;
300        let a = f.to_bits() & ABS;
301        let e = ((a >> 52) & 0x7ff) as i32 - 100;
302        let bits = if 0 < e {
303            ((e as u64) << 52) | (a & 0x800f_ffff_ffff_ffff)
304        } else {
305            let m = (a & 0x801f_ffff_ffff_ffff) | 0x0010_0000_0000_0000;
306            let n = 1 - e;
307            if n <= 0x36 {
308                let m = m >> (n - 1);
309                (m >> 1) + (m & 1)
310            } else {
311                0
312            }
313        };
314        return f64::from_bits(bits | sign) as f32;
315    }
316    if diff < -26 && xsign {
317        return signed(PI, ysign);
318    }
319    if ay == INF && ax == INF {
320        return signed(if xsign { PI3O4 } else { PIO4 }, ysign);
321    }
322    let (mut small, mut big) = (f64::from_bits(ay), f64::from_bits(ax));
323    let swap = small > big;
324    if swap {
325        std::mem::swap(&mut small, &mut big);
326    }
327    let t = small / big;
328    let mut r = if t > 0.0625 {
329        let u = (t * 256.0 + 0.5) as i32;
330        let j = u as f64;
331        let dd = (small * 256.0 - j * big) / (j * small + big * 256.0);
332        let a = dd + d(ATAN_TABLE[(u - 16) as usize]);
333        a - ((dd * dd) * dd) * 0.33333333333224097
334    } else if 0.0001 > t {
335        t
336    } else {
337        let x2 = t * t;
338        let p = 0.3333333333333317 - (0.19999999999393223 - x2 * 0.1428571356180717) * x2;
339        t - p * (x2 * t)
340    };
341    if swap {
342        r = PIO2 - r;
343    }
344    if xsign {
345        r = PI - r;
346    }
347    if ysign {
348        r = -r;
349    }
350    r as f32
351}
352
353/// `(int)v` as the compiler writes it, with `cvttss2si`: it rounds towards zero, and a NaN or
354/// a value outside the `i32` range gives `i32::MIN`. Rust's `v as i32` gives 0 for a NaN and
355/// the nearest limit for a value out of range, so ported code that converts a float the game
356/// could leave NaN uses this.
357///
358/// ```
359/// use unbanished_core::crt::truncate;
360///
361/// assert_eq!(truncate(-2.7), -2);
362/// assert_eq!(truncate(f32::NAN), i32::MIN);
363/// assert_eq!(truncate(3e9), i32::MIN);
364/// ```
365pub fn truncate(v: f32) -> i32 {
366    if v.is_nan() || v >= 2_147_483_648.0 || v < -2_147_483_648.0 {
367        i32::MIN
368    } else {
369        v as i32
370    }
371}
372
373#[cfg(test)]
374mod tests;