vello_common/
math.rs

1// Copyright 2025 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Mathematical helper functions.
5
6use core::ops::Sub;
7#[cfg(not(feature = "std"))]
8use peniko::kurbo::common::FloatFuncs as _;
9
10// See https://raphlinus.github.io/audio/2018/09/05/sigmoid.html for a little
11// explanation of this approximation to the erf function.
12/// Approximate the erf function.
13pub fn compute_erf7(x: f32) -> f32 {
14    let x = x * core::f32::consts::FRAC_2_SQRT_PI;
15    let xx = x * x;
16    let x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx);
17    x / (1.0 + x * x).sqrt()
18}
19
20// From <https://github.com/linebender/tiny-skia/blob/68b198a7210a6bbf752b43d6bc4db62445730313/path/src/scalar.rs#L12>
21// Note: If this value changes, also update NEARLY_ZERO_TOLERANCE in render_strips.wgsl
22// @see {@link https://github.com/linebender/vello/blob/58b80d660e2fc5aef3bd32b24af3f95e973aab95/sparse_strips/vello_sparse_shaders/shaders/render_strips.wgsl#L63}
23const SCALAR_NEARLY_ZERO: f32 = 1.0 / (1 << 12) as f32;
24
25/// A number of useful methods for f32 numbers.
26pub trait FloatExt: Sized + Sub<f32, Output = f32> {
27    /// Whether the number is approximately 0.
28    fn is_nearly_zero(&self) -> bool {
29        self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO)
30    }
31
32    /// Whether the number is approximately 0, with a given tolerance.
33    fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool;
34}
35
36impl FloatExt for f32 {
37    fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool {
38        debug_assert!(tolerance >= 0.0, "tolerance must be positive");
39
40        self.abs() <= tolerance
41    }
42}