f-office-units 0.3.0

Integer lengths and unit conversions for F-Office.
Documentation
//! Whole-number arithmetic of geometry values and trigonometry, with no float, so that every
//! machine computes the same points: a value is an `i128` in 65,536ths of its unit, an angle is
//! in 65,536ths of 60,000ths of a degree (so `angle_deg_60000 * ONE` for DrawingML, or
//! `angle_fd * DEGREE` for VML's 1/65,536° `fd` angles), and a sine or a cosine is an `i128` in
//! units of 2^-62. Each step rounds to the nearest, a half away from 0.

use crate::scale;

/// One unit of a value, in 65,536ths.
pub const ONE: i128 = 1 << 16;

/// The largest size of a value, 2^47 units, in 65,536ths: the product of two values fits in
/// an `i128`, and so does the product of a value with a sine or a cosine.
pub const LIMIT: i128 = 1 << 63;

/// One in the fixed point of sines, cosines and angles in radians: 2^62.
pub const UNIT: i128 = 1 << 62;

/// A full turn in 65,536ths of 60,000ths of a degree.
pub const FULL_TURN: i128 = scale::FULL_TURN as i128 * ONE;

/// A half turn in 65,536ths of 60,000ths of a degree.
pub const HALF_TURN: i128 = FULL_TURN / 2;

/// A quarter turn in 65,536ths of 60,000ths of a degree.
pub const QUARTER_TURN: i128 = scale::QUARTER_TURN as i128 * ONE;

/// An eighth of a turn in 65,536ths of 60,000ths of a degree.
const EIGHTH_TURN: i128 = FULL_TURN / 8;

/// π, π/2 and π/4 in units of 2^-62, rounded.
const PI: i128 = 14_488_038_916_154_245_685;
const HALF_PI: i128 = 7_244_019_458_077_122_842;
const QUARTER_PI: i128 = 3_622_009_729_038_561_421;

/// `dividend` ÷ `divisor`, rounded to the nearest whole number, a half away from 0; the
/// quotient is 0 for a divisor of 0, which a shape of no width or no height asks for.
#[must_use]
pub fn rounded(dividend: i128, divisor: i128) -> i128 {
    if divisor == 0 {
        return 0;
    }
    let (quotient, rest) = (dividend / divisor, dividend % divisor);
    if rest.unsigned_abs() >= divisor.unsigned_abs() - rest.unsigned_abs() {
        quotient + dividend.signum() * divisor.signum()
    } else {
        quotient
    }
}

/// `a` × `b` ÷ 2^62, rounded: a value times a sine or a cosine, or the product of two numbers
/// in units of 2^-62.
#[must_use]
pub fn product(a: i128, b: i128) -> i128 {
    rounded(a * b, UNIT)
}

/// The square root of `square`, rounded down.
#[must_use]
pub const fn root(square: u128) -> i128 {
    // The root of a `u128` is below 2^64, which an `i128` holds.
    square.isqrt().cast_signed()
}

/// The sine and the cosine of `angle`, in 65,536ths of 60,000ths of a degree, in units of 2^-62.
#[must_use]
pub fn sin_cos(angle: i128) -> [i128; 2] {
    let turned = angle.rem_euclid(FULL_TURN);
    let (quarter, rest) = (turned / QUARTER_TURN, turned % QUARTER_TURN);
    // Past an eighth of a turn, the sine of the rest is the cosine of what is left of the
    // quarter.
    let [sin, cos] = if rest <= EIGHTH_TURN {
        series(rounded(rest * QUARTER_PI, EIGHTH_TURN))
    } else {
        let [sin, cos] = series(rounded((QUARTER_TURN - rest) * QUARTER_PI, EIGHTH_TURN));
        [cos, sin]
    };
    match quarter {
        0 => [sin, cos],
        1 => [cos, -sin],
        2 => [-sin, -cos],
        _ => [-cos, sin],
    }
}

/// The sine and the cosine of `x`, from 0 to π/4 in units of 2^-62, from their Taylor series,
/// whose terms fall below a unit within 20 terms.
fn series(x: i128) -> [i128; 2] {
    let square = product(x, x);
    let sum = |first: i128, first_power: i128| {
        let (mut total, mut term, mut power) = (0, first, first_power);
        while term != 0 {
            total += term;
            term = -rounded(product(term, square), (power + 1) * (power + 2));
            power += 2;
        }
        total
    };
    [sum(x, 1), sum(UNIT, 0)]
}

/// The angle of the point (`x`, `y`) seen from the origin, arctan(y ÷ x) in its own quarter
/// (`atan2`), in 65,536ths of 60,000ths of a degree above minus a half turn and at most a half
/// turn; the angle of the origin is 0.
#[must_use]
pub fn angle_of(x: i128, y: i128) -> i128 {
    if x == 0 && y == 0 {
        return 0;
    }
    let (across, up) = (x.unsigned_abs(), y.unsigned_abs());
    // Only the ratio counts: the larger size moves below 2^64, so that it times 2^62 fits.
    let shift = (128 - across.max(up).leading_zeros()).saturating_sub(64);
    let (across, up) = (across >> shift, up >> shift);
    let ratio =
        |small: u128, large: u128| rounded((small << 62).cast_signed(), large.cast_signed());
    let first = if up <= across {
        arctangent(ratio(up, across))
    } else {
        HALF_PI - arctangent(ratio(across, up))
    };
    let half = if x < 0 { PI - first } else { first };
    let radians = if y < 0 { -half } else { half };
    rounded(radians * HALF_TURN, PI)
}

/// The arctangent of `t`, from 0 to 1 in units of 2^-62, in radians in the same units: after
/// two halvings of the angle, arctan t = 2 arctan(t ÷ (1 + √(1 + t²))), `t` is below 0.2, and
/// the terms of the series t − t³/3 + t⁵/5 − … fall below a unit within 15 terms.
fn arctangent(t: i128) -> i128 {
    let halved = |t: i128| {
        let square = (UNIT * UNIT + t * t).cast_unsigned();
        rounded(t * UNIT, UNIT + root(square))
    };
    let small = halved(halved(t));
    let square = product(small, small);
    let (mut total, mut power, mut divisor) = (0, small, 1);
    while power != 0 {
        total += rounded(power, divisor);
        power = -product(power, square);
        divisor += 2;
    }
    4 * total
}

#[cfg(test)]
mod tests;