Fix floating point math (#15239)

# Objective

- Fixes #15236

## Solution

- Use bevy_math::ops instead of std floating point operations.

## Testing

- Did you test these changes? If so, how?
Unit tests and `cargo run -p ci -- test`

- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
Execute `cargo run -p ci -- test` on Windows.

- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
Windows

## Migration Guide

- Not a breaking change
- Projects should use bevy math where applicable

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
This commit is contained in:
Benjamin Brienen 2024-09-17 01:28:12 +02:00 committed by GitHub
parent 0dd00e9204
commit 29508f065f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
84 changed files with 331 additions and 266 deletions

View file

@ -10,3 +10,33 @@ doc-valid-idents = [
"WebGPU",
"..",
]
disallowed-methods = [
{ path = "f32::powi", reason = "use bevy_math::ops::FloatPow::squared, bevy_math::ops::FloatPow::cubed, or bevy_math::ops::powf instead for libm determinism" },
{ path = "f32::log", reason = "use bevy_math::ops::ln, bevy_math::ops::log2, or bevy_math::ops::log10 instead for libm determinism" },
{ path = "f32::abs_sub", reason = "deprecated and deeply confusing method" },
{ path = "f32::powf", reason = "use bevy_math::ops::powf instead for libm determinism" },
{ path = "f32::exp", reason = "use bevy_math::ops::exp instead for libm determinism" },
{ path = "f32::exp2", reason = "use bevy_math::ops::exp2 instead for libm determinism" },
{ path = "f32::ln", reason = "use bevy_math::ops::ln instead for libm determinism" },
{ path = "f32::log2", reason = "use bevy_math::ops::log2 instead for libm determinism" },
{ path = "f32::log10", reason = "use bevy_math::ops::log10 instead for libm determinism" },
{ path = "f32::cbrt", reason = "use bevy_math::ops::cbrt instead for libm determinism" },
{ path = "f32::hypot", reason = "use bevy_math::ops::hypot instead for libm determinism" },
{ path = "f32::sin", reason = "use bevy_math::ops::sin instead for libm determinism" },
{ path = "f32::cos", reason = "use bevy_math::ops::cos instead for libm determinism" },
{ path = "f32::tan", reason = "use bevy_math::ops::tan instead for libm determinism" },
{ path = "f32::asin", reason = "use bevy_math::ops::asin instead for libm determinism" },
{ path = "f32::acos", reason = "use bevy_math::ops::acos instead for libm determinism" },
{ path = "f32::atan", reason = "use bevy_math::ops::atan instead for libm determinism" },
{ path = "f32::atan2", reason = "use bevy_math::ops::atan2 instead for libm determinism" },
{ path = "f32::sin_cos", reason = "use bevy_math::ops::sin_cos instead for libm determinism" },
{ path = "f32::exp_m1", reason = "use bevy_math::ops::exp_m1 instead for libm determinism" },
{ path = "f32::ln_1p", reason = "use bevy_math::ops::ln_1p instead for libm determinism" },
{ path = "f32::sinh", reason = "use bevy_math::ops::sinh instead for libm determinism" },
{ path = "f32::cosh", reason = "use bevy_math::ops::cosh instead for libm determinism" },
{ path = "f32::tanh", reason = "use bevy_math::ops::tanh instead for libm determinism" },
{ path = "f32::asinh", reason = "use bevy_math::ops::asinh instead for libm determinism" },
{ path = "f32::acosh", reason = "use bevy_math::ops::acosh instead for libm determinism" },
{ path = "f32::atanh", reason = "use bevy_math::ops::atanh instead for libm determinism" },
]

View file

@ -22,7 +22,7 @@ use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::{Asset, AssetApp, Assets, Handle};
use bevy_core::Name;
use bevy_ecs::{entity::MapEntities, prelude::*, reflect::ReflectMapEntities};
use bevy_math::{FloatExt, Quat, Vec3};
use bevy_math::{FloatExt, FloatPow, Quat, Vec3};
use bevy_reflect::std_traits::ReflectDefault;
use bevy_reflect::Reflect;
use bevy_render::mesh::morph::MorphWeights;
@ -1211,10 +1211,10 @@ fn cubic_spline_interpolation<T>(
where
T: Mul<f32, Output = T> + Add<Output = T>,
{
value_start * (2.0 * lerp.powi(3) - 3.0 * lerp.powi(2) + 1.0)
+ tangent_out_start * (step_duration) * (lerp.powi(3) - 2.0 * lerp.powi(2) + lerp)
+ value_end * (-2.0 * lerp.powi(3) + 3.0 * lerp.powi(2))
+ tangent_in_end * step_duration * (lerp.powi(3) - lerp.powi(2))
value_start * (2.0 * lerp.cubed() - 3.0 * lerp.squared() + 1.0)
+ tangent_out_start * (step_duration) * (lerp.cubed() - 2.0 * lerp.squared() + lerp)
+ value_end * (-2.0 * lerp.cubed() + 3.0 * lerp.squared())
+ tangent_in_end * step_duration * (lerp.cubed() - lerp.squared())
}
/// Adds animation support to an app

View file

@ -2,7 +2,7 @@ use crate::{
impl_componentwise_vector_space, Alpha, ColorToComponents, Gray, Hsla, Hsva, Hwba, LinearRgba,
Luminance, Mix, Oklaba, Srgba, StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
@ -225,7 +225,7 @@ impl From<Laba> for Xyza {
let fx = a / 500.0 + fy;
let fz = fy - b / 200.0;
let xr = {
let fx3 = fx.powf(3.0);
let fx3 = ops::powf(fx, 3.0);
if fx3 > Laba::CIE_EPSILON {
fx3
@ -234,12 +234,12 @@ impl From<Laba> for Xyza {
}
};
let yr = if l > Laba::CIE_EPSILON * Laba::CIE_KAPPA {
((l + 16.0) / 116.0).powf(3.0)
ops::powf((l + 16.0) / 116.0, 3.0)
} else {
l / Laba::CIE_KAPPA
};
let zr = {
let fz3 = fz.powf(3.0);
let fz3 = ops::powf(fz, 3.0);
if fz3 > Laba::CIE_EPSILON {
fz3
@ -262,17 +262,17 @@ impl From<Xyza> for Laba {
let yr = y / Xyza::D65_WHITE.y;
let zr = z / Xyza::D65_WHITE.z;
let fx = if xr > Laba::CIE_EPSILON {
xr.cbrt()
ops::cbrt(xr)
} else {
(Laba::CIE_KAPPA * xr + 16.0) / 116.0
};
let fy = if yr > Laba::CIE_EPSILON {
yr.cbrt()
ops::cbrt(yr)
} else {
(Laba::CIE_KAPPA * yr + 16.0) / 116.0
};
let fz = if yr > Laba::CIE_EPSILON {
zr.cbrt()
ops::cbrt(zr)
} else {
(Laba::CIE_KAPPA * zr + 16.0) / 116.0
};

View file

@ -2,7 +2,7 @@ use crate::{
Alpha, ColorToComponents, Gray, Hue, Laba, LinearRgba, Luminance, Mix, Srgba, StandardColor,
Xyza,
};
use bevy_math::{Vec3, Vec4};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
@ -257,8 +257,9 @@ impl From<Lcha> for Laba {
) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_LCH_to_Lab.html
let l = lightness;
let a = chroma * hue.to_radians().cos();
let b = chroma * hue.to_radians().sin();
let (sin, cos) = ops::sin_cos(hue.to_radians());
let a = chroma * cos;
let b = chroma * sin;
Laba::new(l, a, b, alpha)
}
@ -274,9 +275,9 @@ impl From<Laba> for Lcha {
}: Laba,
) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
let c = (a.powf(2.0) + b.powf(2.0)).sqrt();
let c = ops::hypot(a, b);
let h = {
let h = b.to_radians().atan2(a.to_radians()).to_degrees();
let h = ops::atan2(b.to_radians(), a.to_radians()).to_degrees();
if h < 0.0 {
h + 360.0

View file

@ -2,7 +2,7 @@ use crate::{
color_difference::EuclideanDistance, impl_componentwise_vector_space, Alpha, ColorToComponents,
Gray, Hsla, Hsva, Hwba, Lcha, LinearRgba, Luminance, Mix, Srgba, StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
use bevy_math::{ops, FloatPow, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
@ -156,9 +156,9 @@ impl Luminance for Oklaba {
impl EuclideanDistance for Oklaba {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
(self.lightness - other.lightness).powi(2)
+ (self.a - other.a).powi(2)
+ (self.b - other.b).powi(2)
(self.lightness - other.lightness).squared()
+ (self.a - other.a).squared()
+ (self.b - other.b).squared()
}
}
@ -229,9 +229,9 @@ impl From<LinearRgba> for Oklaba {
let l = 0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue;
let m = 0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue;
let s = 0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue;
let l_ = l.cbrt();
let m_ = m.cbrt();
let s_ = s.cbrt();
let l_ = ops::cbrt(l);
let m_ = ops::cbrt(m);
let s_ = ops::cbrt(s);
let l = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_;
let a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_;
let b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_;

View file

@ -2,7 +2,7 @@ use crate::{
color_difference::EuclideanDistance, Alpha, ColorToComponents, Gray, Hsla, Hsva, Hue, Hwba,
Laba, Lcha, LinearRgba, Luminance, Mix, Oklaba, Srgba, StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
use bevy_math::{ops, FloatPow, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
@ -191,9 +191,9 @@ impl Luminance for Oklcha {
impl EuclideanDistance for Oklcha {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
(self.lightness - other.lightness).powi(2)
+ (self.chroma - other.chroma).powi(2)
+ (self.hue - other.hue).powi(2)
(self.lightness - other.lightness).squared()
+ (self.chroma - other.chroma).squared()
+ (self.hue - other.hue).squared()
}
}
@ -260,8 +260,8 @@ impl From<Oklaba> for Oklcha {
alpha,
}: Oklaba,
) -> Self {
let chroma = a.hypot(b);
let hue = b.atan2(a).to_degrees();
let chroma = ops::hypot(a, b);
let hue = ops::atan2(b, a).to_degrees();
let hue = if hue < 0.0 { hue + 360.0 } else { hue };
@ -279,8 +279,9 @@ impl From<Oklcha> for Oklaba {
}: Oklcha,
) -> Self {
let l = lightness;
let a = chroma * hue.to_radians().cos();
let b = chroma * hue.to_radians().sin();
let (sin, cos) = ops::sin_cos(hue.to_radians());
let a = chroma * cos;
let b = chroma * sin;
Oklaba::new(l, a, b, alpha)
}

View file

@ -3,7 +3,7 @@ use crate::{
impl_componentwise_vector_space, Alpha, ColorToComponents, ColorToPacked, Gray, LinearRgba,
Luminance, Mix, StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use thiserror::Error;
@ -215,7 +215,7 @@ impl Srgba {
if value <= 0.04045 {
value / 12.92 // linear falloff in dark values
} else {
((value + 0.055) / 1.055).powf(2.4) // gamma curve in other area
ops::powf((value + 0.055) / 1.055, 2.4) // gamma curve in other area
}
}
@ -228,7 +228,7 @@ impl Srgba {
if value <= 0.0031308 {
value * 12.92 // linear falloff in dark values
} else {
(1.055 * value.powf(1.0 / 2.4)) - 0.055 // gamma curve in other area
(1.055 * ops::powf(value, 1.0 / 2.4)) - 0.055 // gamma curve in other area
}
}
}

View file

@ -15,7 +15,7 @@ use crate::{
use bevy_app::{App, Plugin};
use bevy_asset::{load_internal_asset, Handle};
use bevy_ecs::{prelude::*, query::QueryItem};
use bevy_math::UVec2;
use bevy_math::{ops, UVec2};
use bevy_render::{
camera::ExtractedCamera,
diagnostic::RecordDiagnostics,
@ -462,9 +462,11 @@ fn prepare_bloom_bind_groups(
/// This function can be visually previewed for all values of *mip* (normalized) with tweakable
/// [`Bloom`] parameters on [Desmos graphing calculator](https://www.desmos.com/calculator/ncc8xbhzzl).
fn compute_blend_factor(bloom: &Bloom, mip: f32, max_mip: f32) -> f32 {
let mut lf_boost = (1.0
- (1.0 - (mip / max_mip)).powf(1.0 / (1.0 - bloom.low_frequency_boost_curvature)))
* bloom.low_frequency_boost;
let mut lf_boost =
(1.0 - ops::powf(
1.0 - (mip / max_mip),
1.0 / (1.0 - bloom.low_frequency_boost_curvature),
)) * bloom.low_frequency_boost;
let high_pass_lq = 1.0
- (((mip / max_mip) - bloom.high_pass_frequency) / bloom.high_pass_frequency)
.clamp(0.0, 1.0);

View file

@ -26,6 +26,7 @@ use bevy_ecs::{
system::{lifetimeless::Read, Commands, Query, Res, ResMut, Resource},
world::{FromWorld, World},
};
use bevy_math::ops;
use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_render::{
camera::{PhysicalCameraParameters, Projection},
@ -848,7 +849,7 @@ fn extract_depth_of_field_settings(
///
/// See <https://photo.stackexchange.com/a/97218>.
pub fn calculate_focal_length(sensor_height: f32, fov: f32) -> f32 {
0.5 * sensor_height / f32::tan(0.5 * fov)
0.5 * sensor_height / ops::tan(0.5 * fov)
}
impl DepthOfFieldPipelines {

View file

@ -114,8 +114,7 @@ fn arc_2d_inner(arc_angle: f32, radius: f32, resolution: u32) -> impl Iterator<I
(0..=resolution)
.map(move |n| arc_angle * n as f32 / resolution as f32)
.map(|angle| angle + FRAC_PI_2)
.map(f32::sin_cos)
.map(|(sin, cos)| Vec2::new(cos, sin))
.map(Vec2::from_angle)
.map(move |vec2| vec2 * radius)
}

View file

@ -5,7 +5,7 @@
use crate::prelude::{GizmoConfigGroup, Gizmos};
use bevy_color::Color;
use bevy_math::{Isometry2d, Isometry3d};
use bevy_math::{ops, Isometry2d, Isometry3d};
use bevy_math::{Quat, Vec2, Vec3};
use std::f32::consts::TAU;
@ -14,7 +14,7 @@ pub(crate) const DEFAULT_CIRCLE_RESOLUTION: u32 = 32;
fn ellipse_inner(half_size: Vec2, resolution: u32) -> impl Iterator<Item = Vec2> {
(0..resolution + 1).map(move |i| {
let angle = i as f32 * TAU / resolution as f32;
let (x, y) = angle.sin_cos();
let (x, y) = ops::sin_cos(angle);
Vec2::new(x, y) * half_size
})
}

View file

@ -6,7 +6,7 @@
use crate::prelude::{GizmoConfigGroup, Gizmos};
use bevy_color::Color;
use bevy_math::Vec3Swizzles;
use bevy_math::{Isometry2d, Isometry3d, Quat, UVec2, UVec3, Vec2, Vec3};
use bevy_math::{ops, Isometry2d, Isometry3d, Quat, UVec2, UVec3, Vec2, Vec3};
/// A builder returned by [`Gizmos::grid_3d`]
pub struct GridBuilder3d<'a, 'w, 's, Config, Clear>
@ -374,7 +374,7 @@ fn draw_grid<Config, Clear>(
}
// Offset between two adjacent grid cells along the x/y-axis and accounting for skew.
let skew_tan = Vec3::from(skew.to_array().map(f32::tan));
let skew_tan = Vec3::from(skew.to_array().map(ops::tan));
let dx = or_zero(
cell_count.x != 0,
spacing.x * Vec3::new(1., skew_tan.y, skew_tan.z),

View file

@ -18,6 +18,7 @@ use bevy_ecs::{
system::{Query, Res},
};
use bevy_math::{
ops,
primitives::{Cone, Sphere},
Isometry3d, Quat, Vec3,
};
@ -78,12 +79,12 @@ fn spot_light_gizmo(
// Offset the tip of the cone to the light position.
for angle in [spot_light.inner_angle, spot_light.outer_angle] {
let height = spot_light.range * angle.cos();
let height = spot_light.range * ops::cos(angle);
let position = translation + rotation * Vec3::NEG_Z * height / 2.0;
gizmos
.primitive_3d(
&Cone {
radius: spot_light.range * angle.sin(),
radius: spot_light.range * ops::sin(angle),
height,
},
Isometry3d::new(position, rotation * Quat::from_rotation_x(PI / 2.0)),

View file

@ -1,6 +1,6 @@
use std::f32::consts::TAU;
use bevy_math::Vec2;
use bevy_math::{ops, Vec2};
/// Calculates the `nth` coordinate of a circle.
///
@ -9,7 +9,7 @@ use bevy_math::Vec2;
/// and proceeds counter-clockwise.
pub(crate) fn single_circle_coordinate(radius: f32, resolution: u32, nth_point: u32) -> Vec2 {
let angle = nth_point as f32 * TAU / resolution as f32;
let (x, y) = angle.sin_cos();
let (x, y) = ops::sin_cos(angle);
Vec2::new(x, y) * radius
}

View file

@ -2,9 +2,8 @@ mod primitive_impls;
use super::{BoundingVolume, IntersectsVolume};
use crate::{
ops::FloatPow,
prelude::{Mat2, Rot2, Vec2},
Isometry2d,
FloatPow, Isometry2d,
};
#[cfg(feature = "bevy_reflect")]

View file

@ -21,7 +21,7 @@ pub mod curve;
mod direction;
mod float_ord;
mod isometry;
mod ops;
pub mod ops;
pub mod primitives;
mod ray;
mod rects;
@ -36,7 +36,7 @@ pub use common_traits::*;
pub use direction::*;
pub use float_ord::*;
pub use isometry::{Isometry2d, Isometry3d};
pub use ops::*;
pub use ops::FloatPow;
pub use ray::{Ray2d, Ray3d};
pub use rects::*;
pub use rotation2d::Rot2;
@ -59,6 +59,7 @@ pub mod prelude {
},
curve::*,
direction::{Dir2, Dir3, Dir3A},
ops,
primitives::*,
BVec2, BVec3, BVec4, EulerRot, FloatExt, IRect, IVec2, IVec3, IVec4, Isometry2d,
Isometry3d, Mat2, Mat3, Mat4, Quat, Ray2d, Ray3d, Rect, Rot2, StableInterpolate, URect,

View file

@ -445,6 +445,7 @@ mod libm_ops {
#[cfg(feature = "libm")]
pub use libm_ops::*;
#[cfg(not(feature = "libm"))]
pub use std_ops::*;

View file

@ -4,7 +4,7 @@ use bevy_ecs::{
entity::Entity,
system::{Commands, Local, Query, Res, ResMut},
};
use bevy_math::{Mat4, UVec3, Vec2, Vec3, Vec3A, Vec3Swizzles as _, Vec4, Vec4Swizzles as _};
use bevy_math::{ops, Mat4, UVec3, Vec2, Vec3, Vec3A, Vec3Swizzles as _, Vec4, Vec4Swizzles as _};
use bevy_render::{
camera::Camera,
primitives::{Aabb, Frustum, HalfSpace, Sphere},
@ -484,7 +484,7 @@ pub(crate) fn assign_objects_to_clusters(
radius: clusterable_object_sphere.radius * view_from_world_scale_max,
};
let spot_light_dir_sin_cos = clusterable_object.spot_light_angle.map(|angle| {
let (angle_sin, angle_cos) = angle.sin_cos();
let (angle_sin, angle_cos) = ops::sin_cos(angle);
(
(view_from_world * clusterable_object.transform.back().extend(0.0))
.truncate()
@ -723,14 +723,18 @@ fn compute_aabb_for_cluster(
let cluster_near = if ijk.z == 0.0 {
0.0
} else {
-z_near * z_far_over_z_near.powf((ijk.z - 1.0) / (cluster_dimensions.z - 1) as f32)
-z_near
* ops::powf(
z_far_over_z_near,
(ijk.z - 1.0) / (cluster_dimensions.z - 1) as f32,
)
};
// NOTE: This could be simplified to:
// cluster_far = cluster_near * z_far_over_z_near;
let cluster_far = if cluster_dimensions.z == 1 {
-z_far
} else {
-z_near * z_far_over_z_near.powf(ijk.z / (cluster_dimensions.z - 1) as f32)
-z_near * ops::powf(z_far_over_z_near, ijk.z / (cluster_dimensions.z - 1) as f32)
};
// Calculate the four intersection points of the min and max points with the cluster near and far planes
@ -762,7 +766,7 @@ fn z_slice_to_view_z(
if z_slice == 0 {
0.0
} else {
-near * (far / near).powf((z_slice - 1) as f32 / (z_slices - 1) as f32)
-near * ops::powf(far / near, (z_slice - 1) as f32 / (z_slices - 1) as f32)
}
}
@ -900,7 +904,7 @@ fn view_z_to_z_slice(
((view_z - cluster_factors.x) * cluster_factors.y).floor() as u32
} else {
// NOTE: had to use -view_z to make it positive else log(negative) is nan
((-view_z).ln() * cluster_factors.x - cluster_factors.y + 1.0) as u32
(ops::ln(-view_z) * cluster_factors.x - cluster_factors.y + 1.0) as u32
};
// NOTE: We use min as we may limit the far z plane used for clustering to be closer than
// the furthest thing being drawn. This means that we need to limit to the maximum cluster.

View file

@ -1,6 +1,6 @@
use bevy_color::{Color, ColorToComponents, LinearRgba};
use bevy_ecs::prelude::*;
use bevy_math::Vec3;
use bevy_math::{ops, Vec3};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{extract_component::ExtractComponent, prelude::Camera};
@ -207,7 +207,7 @@ pub enum FogFalloff {
/// The fog intensity for a given point in the scene is determined by the following formula:
///
/// ```text
/// let fog_intensity = 1.0 - 1.0 / (distance * density).powi(2).exp();
/// let fog_intensity = 1.0 - 1.0 / (distance * density).squared().exp();
/// ```
///
/// <svg width="370" height="212" viewBox="0 0 370 212" fill="none">
@ -419,15 +419,15 @@ impl FogFalloff {
// Values are subtracted from 1.0 here to preserve the intuitive/artistic meaning of
// colors, since they're later subtracted. (e.g. by giving a blue extinction color, you
// get blue and _not_ yellow results)
(1.0 - r_e).powf(E),
(1.0 - g_e).powf(E),
(1.0 - b_e).powf(E),
ops::powf(1.0 - r_e, E),
ops::powf(1.0 - g_e, E),
ops::powf(1.0 - b_e, E),
) * FogFalloff::koschmieder(visibility, contrast_threshold)
* a_e.powf(E),
* ops::powf(a_e, E),
inscattering: Vec3::new(r_i.powf(E), g_i.powf(E), b_i.powf(E))
inscattering: Vec3::new(ops::powf(r_i, E), ops::powf(g_i, E), ops::powf(b_i, E))
* FogFalloff::koschmieder(visibility, contrast_threshold)
* a_i.powf(E),
* ops::powf(a_i, E),
}
}
@ -462,7 +462,7 @@ impl FogFalloff {
/// - <https://en.wikipedia.org/wiki/Visibility>
/// - <https://www.biral.com/wp-content/uploads/2015/02/Introduction_to_visibility-v2-2.pdf>
pub fn koschmieder(v: f32, c_t: f32) -> f32 {
-c_t.ln() / v
-ops::ln(c_t) / v
}
}

View file

@ -2,7 +2,7 @@ use std::ops::DerefMut;
use bevy_ecs::entity::EntityHashMap;
use bevy_ecs::prelude::*;
use bevy_math::{Mat4, Vec3A, Vec4};
use bevy_math::{ops, Mat4, Vec3A, Vec4};
use bevy_reflect::prelude::*;
use bevy_render::{
camera::{Camera, CameraProjection},
@ -154,9 +154,12 @@ fn calculate_cascade_bounds(
if num_cascades == 1 {
return vec![shadow_maximum_distance];
}
let base = (shadow_maximum_distance / nearest_bound).powf(1.0 / (num_cascades - 1) as f32);
let base = ops::powf(
shadow_maximum_distance / nearest_bound,
1.0 / (num_cascades - 1) as f32,
);
(0..num_cascades)
.map(|i| nearest_bound * base.powf(i as f32))
.map(|i| nearest_bound * ops::powf(base, i as f32))
.collect()
}

View file

@ -9,6 +9,7 @@ use bevy_ecs::{
query::QueryState,
world::{FromWorld, World},
};
use bevy_math::ops;
use bevy_render::{
camera::ExtractedCamera,
render_graph::{Node, NodeRunError, RenderGraphContext},
@ -101,10 +102,8 @@ impl Node for MeshletVisibilityBufferRasterPassNode {
.first_node
.fetch_and(false, Ordering::SeqCst);
let thread_per_cluster_workgroups =
(meshlet_view_resources.scene_cluster_count.div_ceil(128) as f32)
.cbrt()
.ceil() as u32;
let div_ceil = meshlet_view_resources.scene_cluster_count.div_ceil(128);
let thread_per_cluster_workgroups = ops::cbrt(div_ceil as f32).ceil() as u32;
render_context
.command_encoder()

View file

@ -1,6 +1,6 @@
use bevy_asset::Asset;
use bevy_color::{Alpha, ColorToComponents};
use bevy_math::{vec2, Affine2, Affine3, Mat2, Mat3, Vec2, Vec3, Vec4};
use bevy_math::{Affine2, Affine3, Mat2, Mat3, Vec2, Vec3, Vec4};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{
mesh::MeshVertexBufferLayoutRef, render_asset::RenderAssets, render_resource::*,
@ -1068,10 +1068,7 @@ impl AsBindGroupShaderType<StandardMaterialUniform> for StandardMaterial {
emissive[3] = self.emissive_exposure_weight;
// Doing this up front saves having to do this repeatedly in the fragment shader.
let anisotropy_rotation = vec2(
self.anisotropy_rotation.cos(),
self.anisotropy_rotation.sin(),
);
let anisotropy_rotation = Vec2::from_angle(self.anisotropy_rotation);
StandardMaterialUniform {
base_color: LinearRgba::from(self.base_color).to_vec4(),

View file

@ -4,7 +4,7 @@ use bevy_core_pipeline::core_3d::{Camera3d, CORE_3D_DEPTH_FORMAT};
use bevy_ecs::entity::EntityHashSet;
use bevy_ecs::prelude::*;
use bevy_ecs::{entity::EntityHashMap, system::lifetimeless::Read};
use bevy_math::{Mat4, UVec4, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles};
use bevy_math::{ops, Mat4, UVec4, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles};
use bevy_render::{
diagnostic::RecordDiagnostics,
mesh::RenderMesh,
@ -283,7 +283,7 @@ pub fn extract_lights(
// However, since exclusive access to the main world in extract is ill-advised, we just clone here.
let render_visible_entities = visible_entities.clone();
let texel_size =
2.0 * spot_light.outer_angle.tan() / directional_light_shadow_map.size as f32;
2.0 * ops::tan(spot_light.outer_angle) / directional_light_shadow_map.size as f32;
spot_lights_values.push((
entity,
@ -467,10 +467,10 @@ pub fn calculate_cluster_factors(
if is_orthographic {
Vec2::new(-near, z_slices / (-far - -near))
} else {
let z_slices_of_ln_zfar_over_znear = (z_slices - 1.0) / (far / near).ln();
let z_slices_of_ln_zfar_over_znear = (z_slices - 1.0) / ops::ln(far / near);
Vec2::new(
z_slices_of_ln_zfar_over_znear,
near.ln() * z_slices_of_ln_zfar_over_znear,
ops::ln(near) * z_slices_of_ln_zfar_over_znear,
)
}
}
@ -692,14 +692,14 @@ pub fn prepare_lights(
flags |= PointLightFlags::SPOT_LIGHT_Y_NEGATIVE;
}
let cos_outer = outer.cos();
let spot_scale = 1.0 / f32::max(inner.cos() - cos_outer, 1e-4);
let cos_outer = ops::cos(outer);
let spot_scale = 1.0 / f32::max(ops::cos(inner) - cos_outer, 1e-4);
let spot_offset = -cos_outer * spot_scale;
(
// For spot lights: the direction (x,z), spot_scale and spot_offset
light_direction.xz().extend(spot_scale).extend(spot_offset),
outer.tan(),
ops::tan(outer),
)
}
None => {

View file

@ -24,7 +24,7 @@ use bevy_ecs::{
reflect::ReflectComponent,
system::{Commands, Query, Res, ResMut, Resource},
};
use bevy_math::{vec2, Dir3, Mat4, Ray3d, Rect, URect, UVec2, UVec4, Vec2, Vec3};
use bevy_math::{ops, vec2, Dir3, Mat4, Ray3d, Rect, URect, UVec2, UVec4, Vec2, Vec3};
use bevy_reflect::prelude::*;
use bevy_render_macros::ExtractComponent;
use bevy_transform::components::GlobalTransform;
@ -136,7 +136,7 @@ impl Exposure {
/// <https://google.github.io/filament/Filament.md.html#imagingpipeline/physicallybasedcamera/exposure>
#[inline]
pub fn exposure(&self) -> f32 {
(-self.ev100).exp2() / 1.2
ops::exp2(-self.ev100) / 1.2
}
}
@ -170,9 +170,10 @@ pub struct PhysicalCameraParameters {
impl PhysicalCameraParameters {
/// Calculate the [EV100](https://en.wikipedia.org/wiki/Exposure_value).
pub fn ev100(&self) -> f32 {
(self.aperture_f_stops * self.aperture_f_stops * 100.0
/ (self.shutter_speed_s * self.sensitivity_iso))
.log2()
ops::log2(
self.aperture_f_stops * self.aperture_f_stops * 100.0
/ (self.shutter_speed_s * self.sensitivity_iso),
)
}
}

View file

@ -5,7 +5,7 @@ use crate::primitives::Frustum;
use crate::view::VisibilitySystems;
use bevy_app::{App, Plugin, PostStartup, PostUpdate};
use bevy_ecs::prelude::*;
use bevy_math::{AspectRatio, Mat4, Rect, Vec2, Vec3A};
use bevy_math::{ops, AspectRatio, Mat4, Rect, Vec2, Vec3A};
use bevy_reflect::{
std_traits::ReflectDefault, GetTypeRegistration, Reflect, ReflectDeserialize, ReflectSerialize,
};
@ -200,7 +200,7 @@ impl CameraProjection for PerspectiveProjection {
}
fn get_frustum_corners(&self, z_near: f32, z_far: f32) -> [Vec3A; 8] {
let tan_half_fov = (self.fov / 2.).tan();
let tan_half_fov = ops::tan(self.fov / 2.);
let a = z_near.abs() * tan_half_fov;
let b = z_far.abs() * tan_half_fov;
let aspect_ratio = self.aspect_ratio;

View file

@ -7,6 +7,7 @@ use crate::{
use super::{Extrudable, MeshBuilder, Meshable};
use bevy_math::{
ops,
primitives::{
Annulus, Capsule2d, Circle, CircularSector, CircularSegment, Ellipse, Rectangle,
RegularPolygon, Rhombus, Triangle2d, Triangle3d, WindingOrder,
@ -217,7 +218,7 @@ impl MeshBuilder for CircularSectorMeshBuilder {
impl Extrudable for CircularSectorMeshBuilder {
fn perimeter(&self) -> Vec<PerimeterSegment> {
let (sin, cos) = self.sector.arc.half_angle.sin_cos();
let (sin, cos) = ops::sin_cos(self.sector.arc.half_angle);
let first_normal = Vec2::new(sin, cos);
let last_normal = Vec2::new(-sin, cos);
vec![
@ -363,7 +364,7 @@ impl MeshBuilder for CircularSegmentMeshBuilder {
impl Extrudable for CircularSegmentMeshBuilder {
fn perimeter(&self) -> Vec<PerimeterSegment> {
let (sin, cos) = self.segment.arc.half_angle.sin_cos();
let (sin, cos) = ops::sin_cos(self.segment.arc.half_angle);
let first_normal = Vec2::new(sin, cos);
let last_normal = Vec2::new(-sin, cos);
vec![
@ -493,7 +494,7 @@ impl MeshBuilder for EllipseMeshBuilder {
for i in 0..self.resolution {
// Compute vertex position at angle theta
let theta = start_angle + i as f32 * step;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
let x = cos * self.ellipse.half_size.x;
let y = sin * self.ellipse.half_size.y;
@ -599,7 +600,7 @@ impl MeshBuilder for AnnulusMeshBuilder {
let step = std::f32::consts::TAU / self.resolution as f32;
for i in 0..=self.resolution {
let theta = start_angle + (i % self.resolution) as f32 * step;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
let inner_pos = [cos * inner_radius, sin * inner_radius, 0.];
let outer_pos = [cos * outer_radius, sin * outer_radius, 0.];
positions.push(inner_pos);
@ -915,7 +916,7 @@ impl MeshBuilder for Capsule2dMeshBuilder {
for i in 0..resolution {
// Compute vertex position at angle theta
let theta = start_angle + i as f32 * step;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
let (x, y) = (cos * radius, sin * radius + self.capsule.half_length);
positions.push([x, y, 0.0]);
@ -934,7 +935,7 @@ impl MeshBuilder for Capsule2dMeshBuilder {
for i in resolution..vertex_count {
// Compute vertex position at angle theta
let theta = start_angle + i as f32 * step;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
let (x, y) = (cos * radius, sin * radius - self.capsule.half_length);
positions.push([x, y, 0.0]);

View file

@ -2,7 +2,7 @@ use crate::{
mesh::{Indices, Mesh, MeshBuilder, Meshable},
render_asset::RenderAssetUsages,
};
use bevy_math::{primitives::Capsule3d, Vec2, Vec3};
use bevy_math::{ops, primitives::Capsule3d, Vec2, Vec3};
use wgpu::PrimitiveTopology;
/// Manner in which UV coordinates are distributed vertically.
@ -158,11 +158,8 @@ impl MeshBuilder for Capsule3dMeshBuilder {
let s_texture_polar = 1.0 - ((jf + 0.5) * to_tex_horizontal);
let theta = jf * to_theta;
let cos_theta = theta.cos();
let sin_theta = theta.sin();
theta_cartesian[j] = Vec2::new(cos_theta, sin_theta);
rho_theta_cartesian[j] = Vec2::new(radius * cos_theta, radius * sin_theta);
theta_cartesian[j] = Vec2::from_angle(theta);
rho_theta_cartesian[j] = radius * theta_cartesian[j];
// North.
vs[j] = Vec3::new(0.0, summit, 0.0);
@ -205,8 +202,7 @@ impl MeshBuilder for Capsule3dMeshBuilder {
let phi = ip1f * to_phi;
// For coordinates.
let cos_phi_south = phi.cos();
let sin_phi_south = phi.sin();
let (sin_phi_south, cos_phi_south) = ops::sin_cos(phi);
// Symmetrical hemispheres mean cosine and sine only needs
// to be calculated once.

View file

@ -1,4 +1,4 @@
use bevy_math::{primitives::Cone, Vec3};
use bevy_math::{ops, primitives::Cone, Vec3};
use wgpu::PrimitiveTopology;
use crate::{
@ -116,7 +116,7 @@ impl MeshBuilder for ConeMeshBuilder {
// Add vertices for the bottom of the lateral surface.
for segment in 0..self.resolution {
let theta = segment as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
// The vertex normal perpendicular to the side
let normal = Vec3::new(cos, normal_slope, sin) * normalization_factor;
@ -142,7 +142,7 @@ impl MeshBuilder for ConeMeshBuilder {
// Add base vertices.
for i in 0..self.resolution {
let theta = i as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
positions.push([cos * self.cone.radius, -half_height, sin * self.cone.radius]);
normals.push([0.0, -1.0, 0.0]);

View file

@ -2,7 +2,7 @@ use crate::{
mesh::{Indices, Mesh, MeshBuilder, Meshable},
render_asset::RenderAssetUsages,
};
use bevy_math::{primitives::ConicalFrustum, Vec3};
use bevy_math::{ops, primitives::ConicalFrustum, Vec3};
use wgpu::PrimitiveTopology;
/// A builder used for creating a [`Mesh`] with a [`ConicalFrustum`] shape.
@ -94,7 +94,7 @@ impl MeshBuilder for ConicalFrustumMeshBuilder {
for segment in 0..=self.resolution {
let theta = segment as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
positions.push([radius * cos, y, radius * sin]);
normals.push(
@ -137,7 +137,7 @@ impl MeshBuilder for ConicalFrustumMeshBuilder {
for i in 0..self.resolution {
let theta = i as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
positions.push([cos * radius, y, sin * radius]);
normals.push([0.0, normal_y, 0.0]);

View file

@ -1,4 +1,4 @@
use bevy_math::primitives::Cylinder;
use bevy_math::{ops, primitives::Cylinder};
use wgpu::PrimitiveTopology;
use crate::{
@ -122,7 +122,7 @@ impl MeshBuilder for CylinderMeshBuilder {
for segment in 0..=resolution {
let theta = segment as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
positions.push([self.cylinder.radius * cos, y, self.cylinder.radius * sin]);
normals.push([cos, 0., sin]);
@ -163,7 +163,7 @@ impl MeshBuilder for CylinderMeshBuilder {
for i in 0..self.resolution {
let theta = i as f32 * step_theta;
let (sin, cos) = theta.sin_cos();
let (sin, cos) = ops::sin_cos(theta);
positions.push([cos * self.cylinder.radius, y, sin * self.cylinder.radius]);
normals.push([0.0, normal_y, 0.0]);

View file

@ -4,7 +4,7 @@ use crate::{
mesh::{Indices, Mesh, MeshBuilder, Meshable},
render_asset::RenderAssetUsages,
};
use bevy_math::primitives::Sphere;
use bevy_math::{ops, primitives::Sphere};
use hexasphere::shapes::IcoSphere;
use thiserror::Error;
use wgpu::PrimitiveTopology;
@ -120,8 +120,8 @@ impl SphereMeshBuilder {
});
}
let generated = IcoSphere::new(subdivisions as usize, |point| {
let inclination = point.y.acos();
let azimuth = point.z.atan2(point.x);
let inclination = ops::acos(point.y);
let azimuth = ops::atan2(point.z, point.x);
let norm_inclination = inclination / PI;
let norm_azimuth = 0.5 - (azimuth / std::f32::consts::TAU);
@ -183,13 +183,13 @@ impl SphereMeshBuilder {
for i in 0..stacks + 1 {
let stack_angle = PI / 2. - (i as f32) * stack_step;
let xy = self.sphere.radius * stack_angle.cos();
let z = self.sphere.radius * stack_angle.sin();
let xy = self.sphere.radius * ops::cos(stack_angle);
let z = self.sphere.radius * ops::sin(stack_angle);
for j in 0..sectors + 1 {
let sector_angle = (j as f32) * sector_step;
let x = xy * sector_angle.cos();
let y = xy * sector_angle.sin();
let x = xy * ops::cos(sector_angle);
let y = xy * ops::sin(sector_angle);
vertices.push([x, y, z]);
normals.push([x * length_inv, y * length_inv, z * length_inv]);

View file

@ -1,4 +1,4 @@
use bevy_math::{primitives::Torus, Vec3};
use bevy_math::{ops, primitives::Torus, Vec3};
use std::ops::RangeInclusive;
use wgpu::PrimitiveTopology;
@ -98,17 +98,20 @@ impl MeshBuilder for TorusMeshBuilder {
for side in 0..=self.minor_resolution {
let phi = side_stride * side as f32;
let (sin_theta, cos_theta) = ops::sin_cos(theta);
let (sin_phi, cos_phi) = ops::sin_cos(phi);
let radius = self.torus.major_radius + self.torus.minor_radius * cos_phi;
let position = Vec3::new(
theta.cos() * (self.torus.major_radius + self.torus.minor_radius * phi.cos()),
self.torus.minor_radius * phi.sin(),
theta.sin() * (self.torus.major_radius + self.torus.minor_radius * phi.cos()),
cos_theta * radius,
self.torus.minor_radius * sin_phi,
sin_theta * radius,
);
let center = Vec3::new(
self.torus.major_radius * theta.cos(),
self.torus.major_radius * cos_theta,
0.,
self.torus.major_radius * theta.sin(),
self.torus.major_radius * sin_theta,
);
let normal = (position - center).normalize();

View file

@ -2,7 +2,7 @@
use bevy::{
color::palettes::css::*,
math::{bounding::*, Isometry2d},
math::{bounding::*, ops, Isometry2d},
prelude::*,
};
@ -302,8 +302,11 @@ fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
}
fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
let ray = Vec2::new(time.elapsed_seconds().cos(), time.elapsed_seconds().sin());
let dist = 150. + (0.5 * time.elapsed_seconds()).sin().abs() * 500.;
let ray = Vec2::new(
ops::cos(time.elapsed_seconds()),
ops::sin(time.elapsed_seconds()),
);
let dist = 150. + ops::sin(0.5 * time.elapsed_seconds()).abs() * 500.;
let aabb_ray = Ray2d {
origin: ray * 250.,
@ -399,8 +402,8 @@ fn bounding_circle_cast_system(
}
fn get_intersection_position(time: &Time) -> Vec2 {
let x = (0.8 * time.elapsed_seconds()).cos() * 250.;
let y = (0.4 * time.elapsed_seconds()).sin() * 100.;
let x = ops::cos(0.8 * time.elapsed_seconds()) * 250.;
let y = ops::sin(0.4 * time.elapsed_seconds()) * 100.;
Vec2::new(x, y)
}

View file

@ -9,7 +9,7 @@ use bevy::{
color::palettes::basic::YELLOW,
core_pipeline::core_2d::{Transparent2d, CORE_2D_DEPTH_FORMAT},
ecs::entity::EntityHashMap,
math::FloatOrd,
math::{ops, FloatOrd},
prelude::*,
render::{
mesh::{Indices, MeshVertexAttribute, RenderMesh},
@ -80,7 +80,7 @@ fn star(
// The radius of inner vertices (even indices) is 100. For outer vertices (odd indices) it's 200.
let r = (1 - i % 2) as f32 * 100.0 + 100.0;
// Add the vertex position.
v_pos.push([r * a.sin(), r * a.cos(), 0.0]);
v_pos.push([r * ops::sin(a), r * ops::cos(a), 0.0]);
}
// Set the position attribute
star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos);

View file

@ -1,5 +1,6 @@
//! Demonstrates rotating entities in 2D using quaternions.
use bevy::math::ops;
use bevy::prelude::*;
const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0);
@ -241,7 +242,7 @@ fn rotate_to_player_system(
// limit rotation so we don't overshoot the target. We need to convert our dot product to
// an angle here so we can get an angle of rotation to clamp against.
let max_angle = forward_dot_player.clamp(-1.0, 1.0).acos(); // clamp acos for safety
let max_angle = ops::acos(forward_dot_player.clamp(-1.0, 1.0)); // clamp acos for safety
// calculate angle of rotation with limit
let rotation_angle =

View file

@ -7,6 +7,7 @@
use bevy::{
color::palettes::css::*,
math::ops,
prelude::*,
sprite::Anchor,
text::{BreakLineOn, TextBounds},
@ -164,8 +165,8 @@ fn animate_translation(
mut query: Query<&mut Transform, (With<Text>, With<AnimateTranslation>)>,
) {
for mut transform in &mut query {
transform.translation.x = 100.0 * time.elapsed_seconds().sin() - 400.0;
transform.translation.y = 100.0 * time.elapsed_seconds().cos();
transform.translation.x = 100.0 * ops::sin(time.elapsed_seconds()) - 400.0;
transform.translation.y = 100.0 * ops::cos(time.elapsed_seconds());
}
}
@ -174,7 +175,7 @@ fn animate_rotation(
mut query: Query<&mut Transform, (With<Text>, With<AnimateRotation>)>,
) {
for mut transform in &mut query {
transform.rotation = Quat::from_rotation_z(time.elapsed_seconds().cos());
transform.rotation = Quat::from_rotation_z(ops::cos(time.elapsed_seconds()));
}
}
@ -185,7 +186,7 @@ fn animate_scale(
// Consider changing font-size instead of scaling the transform. Scaling a Text2D will scale the
// rendered quad, resulting in a pixellated look.
for mut transform in &mut query {
let scale = (time.elapsed_seconds().sin() + 1.1) * 2.0;
let scale = (ops::sin(time.elapsed_seconds()) + 1.1) * 2.0;
transform.scale.x = scale;
transform.scale.y = scale;
}

View file

@ -132,7 +132,7 @@ fn animate_light(
) {
let now = time.elapsed_seconds();
for mut transform in lights.iter_mut() {
transform.translation = vec3(f32::cos(now), 1.0, f32::sin(now)) * vec3(3.0, 4.0, 3.0);
transform.translation = vec3(ops::cos(now), 1.0, ops::sin(now)) * vec3(3.0, 4.0, 3.0);
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}

View file

@ -6,6 +6,7 @@ use bevy::{
bloom::{Bloom, BloomCompositeMode},
tonemapping::Tonemapping,
},
math::ops,
prelude::*,
};
use std::{
@ -219,6 +220,6 @@ struct Bouncing;
fn bounce_spheres(time: Res<Time>, mut query: Query<&mut Transform, With<Bouncing>>) {
for mut transform in query.iter_mut() {
transform.translation.y =
(transform.translation.x + transform.translation.z + time.elapsed_seconds()).sin();
ops::sin(transform.translation.x + transform.translation.z + time.elapsed_seconds());
}
}

View file

@ -258,9 +258,9 @@ fn animate_light(
let now = time.elapsed_seconds();
for mut transform in lights.iter_mut() {
transform.translation = vec3(
f32::sin(now * 1.4),
f32::cos(now * 1.0),
f32::cos(now * 0.6),
ops::sin(now * 1.4),
ops::cos(now * 1.0),
ops::cos(now * 0.6),
) * vec3(3.0, 4.0, 3.0);
transform.look_at(Vec3::ZERO, Vec3::Y);
}

View file

@ -7,6 +7,7 @@ use bevy::{
fxaa::Fxaa,
prepass::{DeferredPrepass, DepthPrepass, MotionVectorPrepass, NormalPrepass},
},
math::ops,
pbr::{
CascadeShadowConfigBuilder, DefaultOpaqueRendererMethod, DirectionalLightShadowMap,
NotShadowCaster, NotShadowReceiver, OpaqueRendererMethod,
@ -263,7 +264,7 @@ fn setup_parallax(
depth_map: Some(asset_server.load("textures/parallax_example/cube_depth.png")),
parallax_depth_scale: 0.09,
parallax_mapping_method: ParallaxMappingMethod::Relief { max_steps: 4 },
max_parallax_layer_count: 5.0f32.exp2(),
max_parallax_layer_count: ops::exp2(5.0f32),
..default()
});
commands.spawn((

View file

@ -15,6 +15,7 @@
//! | `.` / `?` | Adjust Fog Alpha Channel |
use bevy::{
math::ops,
pbr::{NotShadowCaster, NotShadowReceiver},
prelude::*,
};
@ -146,11 +147,11 @@ fn update_system(
let mut text = text.single_mut();
// Orbit camera around pyramid
let orbit_scale = 8.0 + (now / 10.0).sin() * 7.0;
let orbit_scale = 8.0 + ops::sin(now / 10.0) * 7.0;
*transform = Transform::from_xyz(
(now / 5.0).cos() * orbit_scale,
ops::cos(now / 5.0) * orbit_scale,
12.0 - orbit_scale / 2.0,
(now / 5.0).sin() * orbit_scale,
ops::sin(now / 5.0) * orbit_scale,
)
.looking_at(Vec3::ZERO, Vec3::Y);

View file

@ -3,6 +3,7 @@
use bevy::{
core_pipeline::motion_blur::{MotionBlur, MotionBlurBundle},
math::ops,
prelude::*,
};
@ -304,12 +305,13 @@ fn race_track_pos(offset: f32, t: f32) -> Vec2 {
let x_tweak = 2.0;
let y_tweak = 3.0;
let scale = 8.0;
let x0 = (x_tweak * t).sin();
let y0 = (y_tweak * t).cos();
let dx = x_tweak * (x_tweak * t).cos();
let dy = y_tweak * -(y_tweak * t).sin();
let x = x0 + offset * dy / (dx.powi(2) + dy.powi(2)).sqrt();
let y = y0 - offset * dx / (dx.powi(2) + dy.powi(2)).sqrt();
let x0 = ops::sin(x_tweak * t);
let y0 = ops::cos(y_tweak * t);
let dx = x_tweak * ops::cos(x_tweak * t);
let dy = y_tweak * -ops::sin(y_tweak * t);
let dl = ops::hypot(dx, dy);
let x = x0 + offset * dy / dl;
let y = y0 - offset * dx / dl;
Vec2::new(x, y) * scale
}
@ -321,8 +323,8 @@ fn move_cars(
for (mut transform, moves, children) in &mut movables {
let time = time.elapsed_seconds() * 0.25;
let t = time + 0.5 * moves.0;
let dx = t.cos();
let dz = -(3.0 * t).sin();
let dx = ops::cos(t);
let dz = -ops::sin(3.0 * t);
let speed_variation = (dx * dx + dz * dz).sqrt() * 0.15;
let t = t + speed_variation;
let prev = transform.translation;

View file

@ -3,7 +3,7 @@
use std::fmt;
use bevy::{prelude::*, render::texture::ImageLoaderSettings};
use bevy::{math::ops, prelude::*, render::texture::ImageLoaderSettings};
fn main() {
App::new()
@ -139,7 +139,7 @@ fn update_parallax_layers(
} else {
return;
}
let layer_count = target_layers.0.exp2();
let layer_count = ops::exp2(target_layers.0);
let mut text = text.single_mut();
text.sections[1].value = format!("Layers: {layer_count:.0}\n");
@ -250,7 +250,7 @@ fn setup(
});
let parallax_depth_scale = TargetDepth::default().0;
let max_parallax_layer_count = TargetLayers::default().0.exp2();
let max_parallax_layer_count = ops::exp2(TargetLayers::default().0);
let parallax_mapping_method = CurrentMethod::default();
let parallax_material = materials.add(StandardMaterial {
perceptual_roughness: 0.4,

View file

@ -4,6 +4,7 @@ use std::f32::consts::*;
use bevy::{
color::palettes::basic::{MAROON, RED},
math::ops,
pbr::NotShadowCaster,
prelude::*,
};
@ -150,11 +151,11 @@ fn light_sway(time: Res<Time>, mut query: Query<(&mut Transform, &mut SpotLight)
for (mut transform, mut angles) in query.iter_mut() {
transform.rotation = Quat::from_euler(
EulerRot::XYZ,
-FRAC_PI_2 + (time.elapsed_seconds() * 0.67 * 3.0).sin() * 0.5,
(time.elapsed_seconds() * 3.0).sin() * 0.5,
-FRAC_PI_2 + ops::sin(time.elapsed_seconds() * 0.67 * 3.0) * 0.5,
ops::sin(time.elapsed_seconds() * 3.0) * 0.5,
0.0,
);
let angle = ((time.elapsed_seconds() * 1.2).sin() + 1.0) * (FRAC_PI_4 - 0.1);
let angle = (ops::sin(time.elapsed_seconds() * 1.2) + 1.0) * (FRAC_PI_4 - 0.1);
angles.inner_angle = angle * 0.8;
angles.outer_angle = angle;
}

View file

@ -2,6 +2,7 @@
use bevy::{
core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin},
math::ops,
pbr::{
ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionBundle,
ScreenSpaceAmbientOcclusionQualityLevel,
@ -119,7 +120,7 @@ fn update(
time: Res<Time>,
) {
let mut sphere = sphere.single_mut();
sphere.translation.y = (time.elapsed_seconds() / 1.7).sin() * 0.7;
sphere.translation.y = ops::sin(time.elapsed_seconds() / 1.7) * 0.7;
let (camera_entity, ssao, temporal_jitter) = camera.single();

View file

@ -26,6 +26,7 @@ use bevy::{
bloom::Bloom, core_3d::ScreenSpaceTransmissionQuality, prepass::DepthPrepass,
tonemapping::Tonemapping,
},
math::ops,
pbr::{NotShadowCaster, PointLightShadowMap, TransmittedShadowReceiver},
prelude::*,
render::{
@ -578,7 +579,7 @@ fn example_control_system(
0.0
};
camera_transform.translation *= distance_change.exp();
camera_transform.translation *= ops::exp(distance_change);
camera_transform.rotate_around(
Vec3::ZERO,
@ -642,9 +643,9 @@ fn flicker_system(
time: Res<Time>,
) {
let s = time.elapsed_seconds();
let a = (s * 6.0).cos() * 0.0125 + (s * 4.0).cos() * 0.025;
let b = (s * 5.0).cos() * 0.0125 + (s * 3.0).cos() * 0.025;
let c = (s * 7.0).cos() * 0.0125 + (s * 2.0).cos() * 0.025;
let a = ops::cos(s * 6.0) * 0.0125 + ops::cos(s * 4.0) * 0.025;
let b = ops::cos(s * 5.0) * 0.0125 + ops::cos(s * 3.0) * 0.025;
let c = ops::cos(s * 7.0) * 0.0125 + ops::cos(s * 2.0) * 0.025;
let (mut light, mut light_transform) = light.single_mut();
let mut flame_transform = flame.single_mut();
light.intensity = 4_000.0 + 3000.0 * (a + b + c);

View file

@ -2,6 +2,7 @@
//! Shows the effects of different blend modes.
//! The `fade_transparency` system smoothly changes the transparency over time.
use bevy::math::ops;
use bevy::prelude::*;
fn main() {
@ -115,7 +116,7 @@ fn setup(
/// completely opaque, then will be 7/8 opaque (1/8 transparent), then will be
/// 6/8 opaque, then 5/8, etc.
pub fn fade_transparency(time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>) {
let alpha = (time.elapsed_seconds().sin() / 2.0) + 0.5;
let alpha = (ops::sin(time.elapsed_seconds()) / 2.0) + 0.5;
for (_, material) in materials.iter_mut() {
material.base_color.set_alpha(alpha);
}

View file

@ -69,9 +69,9 @@ fn move_scene_entities(
for entity in children.iter_descendants(moved_scene_entity) {
if let Ok(mut transform) = transforms.get_mut(entity) {
transform.translation = Vec3::new(
offset * time.elapsed_seconds().sin() / 20.,
offset * ops::sin(time.elapsed_seconds()) / 20.,
0.,
time.elapsed_seconds().cos() / 20.,
ops::cos(time.elapsed_seconds()) / 20.,
);
offset += 0.5;
}

View file

@ -100,7 +100,7 @@ fn animate_curve<T: CurveColor>(
time: Res<Time>,
mut query: Query<(&mut Transform, &mut Sprite, &Curve<T>)>,
) {
let t = (time.elapsed_seconds().sin() + 1.) / 2.;
let t = (ops::sin(time.elapsed_seconds()) + 1.) / 2.;
for (mut transform, mut sprite, cubic_curve) in &mut query {
// position takes a point from the curve where 0 is the initial point
@ -114,7 +114,7 @@ fn animate_mixed<T: MixedColor>(
time: Res<Time>,
mut query: Query<(&mut Transform, &mut Sprite, &Mixed<T>)>,
) {
let t = (time.elapsed_seconds().sin() + 1.) / 2.;
let t = (ops::sin(time.elapsed_seconds()) + 1.) / 2.;
for (mut transform, mut sprite, mixed) in &mut query {
sprite.color = {

View file

@ -74,7 +74,7 @@ fn setup(
}
fn animate_cube(time: Res<Time>, mut query: Query<(&mut Transform, &Curve)>, mut gizmos: Gizmos) {
let t = (time.elapsed_seconds().sin() + 1.) / 2.;
let t = (ops::sin(time.elapsed_seconds()) + 1.) / 2.;
for (mut transform, cubic_curve) in &mut query {
// Draw the curve

View file

@ -4,6 +4,7 @@
use std::f32::consts::*;
use bevy::{
math::ops,
prelude::*,
render::{
mesh::{
@ -167,6 +168,6 @@ fn setup(
/// Animate the joint marked with [`AnimatedJoint`] component.
fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) {
for mut transform in &mut query {
transform.rotation = Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
transform.rotation = Quat::from_rotation_z(FRAC_PI_2 * ops::sin(time.elapsed_seconds()));
}
}

View file

@ -3,7 +3,7 @@
use std::f32::consts::*;
use bevy::{prelude::*, render::mesh::skinning::SkinnedMesh};
use bevy::{math::ops, prelude::*, render::mesh::skinning::SkinnedMesh};
fn main() {
App::new()
@ -69,6 +69,6 @@ fn joint_animation(
let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();
second_joint_transform.rotation =
Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
Quat::from_rotation_z(FRAC_PI_2 * ops::sin(time.elapsed_seconds()));
}
}

View file

@ -1,5 +1,6 @@
//! This example illustrates how to load and play an audio file, and control how it's played.
use bevy::math::ops;
use bevy::prelude::*;
fn main() {
@ -25,7 +26,7 @@ struct MyMusic;
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
if let Ok(sink) = music_controller.get_single() {
sink.set_speed(((time.elapsed_seconds() / 5.0).sin() + 1.0).max(0.1));
sink.set_speed((ops::sin(time.elapsed_seconds() / 5.0) + 1.0).max(0.1));
}
}

View file

@ -2,6 +2,7 @@
use bevy::audio::AddAudioSource;
use bevy::audio::AudioPlugin;
use bevy::audio::Source;
use bevy::math::ops;
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy::utils::Duration;
@ -46,7 +47,7 @@ impl Iterator for SineDecoder {
self.current_progress += self.progress_per_frame;
// we loop back round to 0 to avoid floating point inaccuracies
self.current_progress %= 1.;
Some(f32::sin(self.period * self.current_progress))
Some(ops::sin(self.period * self.current_progress))
}
}
// `Source` is what allows the audio source to be played by bevy.

View file

@ -44,10 +44,10 @@ fn keyboard_input_system(
mut events: EventWriter<PlayPitch>,
) {
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
frequency.0 *= 2.0f32.powf(1.0 / 12.0);
frequency.0 *= ops::powf(2.0f32, 1.0 / 12.0);
}
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
frequency.0 /= 2.0f32.powf(1.0 / 12.0);
frequency.0 /= ops::powf(2.0f32, 1.0 / 12.0);
}
if keyboard_input.just_pressed(KeyCode::Space) {
events.send(PlayPitch);

View file

@ -108,7 +108,7 @@ fn update_emitters(
}
if !emitter.stopped {
emitter_transform.translation.x = time.elapsed_seconds().sin() * 500.0;
emitter_transform.translation.x = ops::sin(time.elapsed_seconds()) * 500.0;
}
}
}

View file

@ -101,8 +101,8 @@ fn update_positions(
}
if !emitter.stopped {
emitter_transform.translation.x = time.elapsed_seconds().sin() * 3.0;
emitter_transform.translation.z = time.elapsed_seconds().cos() * 3.0;
emitter_transform.translation.x = ops::sin(time.elapsed_seconds()) * 3.0;
emitter_transform.translation.z = ops::cos(time.elapsed_seconds()) * 3.0;
}
}
}

View file

@ -1,6 +1,6 @@
//! Shows how to iterate over combinations of query results.
use bevy::{color::palettes::css::ORANGE_RED, prelude::*};
use bevy::{color::palettes::css::ORANGE_RED, math::FloatPow, prelude::*};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
@ -50,7 +50,7 @@ fn generate_bodies(
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
for _ in 0..NUM_BODIES {
let radius: f32 = rng.gen_range(0.1..0.7);
let mass_value = radius.powi(3) * 10.;
let mass_value = FloatPow::cubed(radius) * 10.;
let position = Vec3::new(
rng.gen_range(-1.0..1.0),
@ -58,7 +58,7 @@ fn generate_bodies(
rng.gen_range(-1.0..1.0),
)
.normalize()
* rng.gen_range(0.2f32..1.0).cbrt()
* ops::cbrt(rng.gen_range(0.2f32..1.0))
* 15.;
commands.spawn(BodyBundle {

View file

@ -376,8 +376,9 @@ fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Tra
if let Some(entity) = game.bonus.entity {
if let Ok(mut cake_transform) = transforms.get_mut(entity) {
cake_transform.rotate_y(time.delta_seconds());
cake_transform.scale =
Vec3::splat(1.0 + (game.score as f32 / 10.0 * time.elapsed_seconds().sin()).abs());
cake_transform.scale = Vec3::splat(
1.0 + (game.score as f32 / 10.0 * ops::sin(time.elapsed_seconds())).abs(),
);
}
}
}

View file

@ -383,7 +383,7 @@ fn move_pupils(time: Res<Time>, mut q_pupils: Query<(&mut Pupil, &mut Transform)
// Truncate the Z component to make the calculations be on [`Vec2`]
let mut translation = transform.translation.truncate();
// Decay the pupil velocity
pupil.velocity *= (0.04f32).powf(time.delta_seconds());
pupil.velocity *= ops::powf(0.04f32, time.delta_seconds());
// Move the pupil
translation += pupil.velocity * time.delta_seconds();
// If the pupil hit the outside border of the eye, limit the translation to be within the wiggle radius and invert the velocity.

View file

@ -43,9 +43,9 @@ fn draw_example_collection(
mut my_gizmos: Gizmos<MyRoundGizmos>,
time: Res<Time>,
) {
let sin = time.elapsed_seconds().sin() * 50.;
gizmos.line_2d(Vec2::Y * -sin, Vec2::splat(-80.), RED);
gizmos.ray_2d(Vec2::Y * sin, Vec2::splat(80.), LIME);
let sin_t_scaled = ops::sin(time.elapsed_seconds()) * 50.;
gizmos.line_2d(Vec2::Y * -sin_t_scaled, Vec2::splat(-80.), RED);
gizmos.ray_2d(Vec2::Y * sin_t_scaled, Vec2::splat(80.), LIME);
gizmos
.grid_2d(
@ -74,8 +74,8 @@ fn draw_example_collection(
);
let domain = Interval::EVERYWHERE;
let curve = function_curve(domain, |t| Vec2::new(t, (t / 25.0).sin() * 100.0));
let resolution = ((time.elapsed_seconds().sin() + 1.0) * 50.0) as usize;
let curve = function_curve(domain, |t| Vec2::new(t, ops::sin(t / 25.0) * 100.0));
let resolution = ((ops::sin(time.elapsed_seconds()) + 1.0) * 50.0) as usize;
let times_and_colors = (0..=resolution)
.map(|n| n as f32 / resolution as f32)
.map(|t| (t - 0.5) * 600.0)
@ -84,7 +84,7 @@ fn draw_example_collection(
my_gizmos
.rounded_rect_2d(Isometry2d::IDENTITY, Vec2::splat(630.), BLACK)
.corner_radius((time.elapsed_seconds() / 3.).cos() * 100.);
.corner_radius(ops::cos(time.elapsed_seconds() / 3.) * 100.);
// Circles have 32 line-segments by default.
// You may want to increase this for larger circles.
@ -101,7 +101,7 @@ fn draw_example_collection(
// Arcs default resolution is linearly interpolated between
// 1 and 32, using the arc length as scalar.
my_gizmos.arc_2d(
Isometry2d::from_rotation(Rot2::radians(sin / 10.)),
Isometry2d::from_rotation(Rot2::radians(sin_t_scaled / 10.)),
FRAC_PI_2,
310.,
ORANGE_RED,
@ -112,13 +112,17 @@ fn draw_example_collection(
gizmos.arrow_2d(
Vec2::ZERO,
Vec2::from_angle(sin / -10. + PI / 2.) * 50.,
Vec2::from_angle(sin_t_scaled / -10. + PI / 2.) * 50.,
YELLOW,
);
// You can create more complex arrows using the arrow builder.
gizmos
.arrow_2d(Vec2::ZERO, Vec2::from_angle(sin / -10.) * 50., GREEN)
.arrow_2d(
Vec2::ZERO,
Vec2::from_angle(sin_t_scaled / -10.) * 50.,
GREEN,
)
.with_double_end()
.with_tip_length(10.);
}

View file

@ -104,7 +104,7 @@ fn draw_example_collection(
half_size: Vec2::splat(1.0),
},
Isometry3d::new(
Vec3::ONE * 4.0 + Vec2::from(time.elapsed_seconds().sin_cos()).extend(0.0),
Vec3::ONE * 4.0 + Vec2::from(ops::sin_cos(time.elapsed_seconds())).extend(0.0),
Quat::from_rotation_x(PI / 2. + time.elapsed_seconds()),
),
GREEN,
@ -118,7 +118,7 @@ fn draw_example_collection(
);
gizmos.rect(
Isometry3d::new(
Vec3::new(time.elapsed_seconds().cos() * 2.5, 1., 0.),
Vec3::new(ops::cos(time.elapsed_seconds()) * 2.5, 1., 0.),
Quat::from_rotation_y(PI / 2.),
),
Vec2::splat(2.),
@ -133,9 +133,9 @@ fn draw_example_collection(
let domain = Interval::EVERYWHERE;
let curve = function_curve(domain, |t| {
(Vec2::from((t * 10.0).sin_cos())).extend(t - 6.0)
(Vec2::from(ops::sin_cos(t * 10.0))).extend(t - 6.0)
});
let resolution = ((time.elapsed_seconds().sin() + 1.0) * 100.0) as usize;
let resolution = ((ops::sin(time.elapsed_seconds()) + 1.0) * 100.0) as usize;
let times_and_colors = (0..=resolution)
.map(|n| n as f32 / resolution as f32)
.map(|t| t * 5.0)
@ -160,7 +160,7 @@ fn draw_example_collection(
for y in [0., 0.5, 1.] {
gizmos.ray(
Vec3::new(1., y, 0.),
Vec3::new(-3., (time.elapsed_seconds() * 3.).sin(), 0.),
Vec3::new(-3., ops::sin(time.elapsed_seconds() * 3.), 0.),
BLUE,
);
}

View file

@ -1,4 +1,5 @@
//! This example demonstrates the implementation and behavior of the axes gizmo.
use bevy::prelude::*;
use bevy::render::primitives::Aabb;
use rand::{Rng, SeedableRng};
@ -174,21 +175,21 @@ fn random_scale(rng: &mut impl Rng) -> Vec3 {
+ SCALING_BOUND_LOWER_LOG;
Vec3::new(
x_factor_log.exp2(),
y_factor_log.exp2(),
z_factor_log.exp2(),
ops::exp2(x_factor_log),
ops::exp2(y_factor_log),
ops::exp2(z_factor_log),
)
}
fn elerp(v1: Vec3, v2: Vec3, t: f32) -> Vec3 {
let x_factor_log = (1. - t) * v1.x.log2() + t * v2.x.log2();
let y_factor_log = (1. - t) * v1.y.log2() + t * v2.y.log2();
let z_factor_log = (1. - t) * v1.z.log2() + t * v2.z.log2();
let x_factor_log = (1. - t) * ops::log2(v1.x) + t * ops::log2(v2.x);
let y_factor_log = (1. - t) * ops::log2(v1.y) + t * ops::log2(v2.y);
let z_factor_log = (1. - t) * ops::log2(v1.z) + t * ops::log2(v2.z);
Vec3::new(
x_factor_log.exp2(),
y_factor_log.exp2(),
z_factor_log.exp2(),
ops::exp2(x_factor_log),
ops::exp2(y_factor_log),
ops::exp2(z_factor_log),
)
}
@ -208,9 +209,9 @@ fn random_direction(rng: &mut impl Rng) -> Vec3 {
fn build_direction(height: f32, theta: f32) -> Vec3 {
let z = height;
let m = f32::acos(z).sin();
let x = theta.cos() * m;
let y = theta.sin() * m;
let m = ops::sin(ops::acos(z));
let x = ops::cos(theta) * m;
let y = ops::sin(theta) * m;
Vec3::new(x, y, z)
}

View file

@ -333,7 +333,7 @@ impl Heart {
// If you implement `Measured2d` for a 2D primitive, `Measured3d` is automatically implemented for `Extrusion<T>`.
impl Measured2d for Heart {
fn perimeter(&self) -> f32 {
self.radius * (2.5 * PI + 2f32.powf(1.5) + 2.0)
self.radius * (2.5 * PI + ops::powf(2f32, 1.5) + 2.0)
}
fn area(&self) -> f32 {
@ -366,7 +366,7 @@ impl Bounded2d for Heart {
fn bounding_circle(&self, isometry: Isometry2d) -> BoundingCircle {
// The bounding circle of the heart is not at its origin. This `offset` is the offset between the center of the bounding circle and its translation.
let offset = self.radius / 2f32.powf(1.5);
let offset = self.radius / ops::powf(2f32, 1.5);
// The center of the bounding circle
let center = isometry * Vec2::new(0.0, -offset);
// The radius of the bounding circle
@ -441,7 +441,7 @@ impl MeshBuilder for HeartMeshBuilder {
// The left wing of the heart, starting from the point in the middle.
for i in 1..self.resolution {
let angle = (i as f32 / self.resolution as f32) * wing_angle;
let (sin, cos) = angle.sin_cos();
let (sin, cos) = ops::sin_cos(angle);
vertices.push([radius * (cos - 1.0), radius * sin, 0.0]);
uvs.push([0.5 - (cos - 1.0) / 4., 0.5 - sin / 2.]);
}
@ -453,7 +453,7 @@ impl MeshBuilder for HeartMeshBuilder {
// The right wing of the heart, starting from the bottom most point and going towards the middle point.
for i in 0..self.resolution - 1 {
let angle = (i as f32 / self.resolution as f32) * wing_angle - PI / 4.;
let (sin, cos) = angle.sin_cos();
let (sin, cos) = ops::sin_cos(angle);
vertices.push([radius * (cos + 1.0), radius * sin, 0.0]);
uvs.push([0.5 - (cos + 1.0) / 4., 0.5 - sin / 2.]);
}

View file

@ -635,9 +635,9 @@ fn rotate_primitive_3d_meshes(
let rotation_3d = Quat::from_rotation_arc(
Vec3::Z,
Vec3::new(
time.elapsed_seconds().sin(),
time.elapsed_seconds().cos(),
time.elapsed_seconds().sin() * 0.5,
ops::sin(time.elapsed_seconds()),
ops::cos(time.elapsed_seconds()),
ops::sin(time.elapsed_seconds()) * 0.5,
)
.try_normalize()
.unwrap_or(Vec3::Z),
@ -655,9 +655,9 @@ fn draw_gizmos_3d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time
let rotation = Quat::from_rotation_arc(
Vec3::Z,
Vec3::new(
time.elapsed_seconds().sin(),
time.elapsed_seconds().cos(),
time.elapsed_seconds().sin() * 0.5,
ops::sin(time.elapsed_seconds()),
ops::cos(time.elapsed_seconds()),
ops::sin(time.elapsed_seconds()) * 0.5,
)
.try_normalize()
.unwrap_or(Vec3::Z),

View file

@ -19,8 +19,8 @@ fn move_sprite(
let t = time.elapsed_seconds() * 0.1;
for mut transform in &mut sprite {
let new = Vec2 {
x: 50.0 * t.sin(),
y: 50.0 * (t * 2.0).sin(),
x: 50.0 * ops::sin(t),
y: 50.0 * ops::sin(t * 2.0),
};
transform.translation.x = new.x;
transform.translation.y = new.y;

View file

@ -365,9 +365,9 @@ fn rotate(time: Res<Time>, mut query: Query<&mut Transform, With<Rotates>>) {
// Change the intensity over time to show that the effect is controlled from the main world
fn update_settings(mut settings: Query<&mut PostProcessSettings>, time: Res<Time>) {
for mut setting in &mut settings {
let mut intensity = time.elapsed_seconds().sin();
let mut intensity = ops::sin(time.elapsed_seconds());
// Make it loop periodically
intensity = intensity.sin();
intensity = ops::sin(intensity);
// Remap it to 0..1 because the intensity can't be negative
intensity = intensity * 0.5 + 0.5;
// Scale it to a more reasonable level

View file

@ -189,7 +189,7 @@ struct Rotates;
fn rotate(mut q: Query<&mut Transform, With<Rotates>>, time: Res<Time>) {
for mut t in q.iter_mut() {
let rot = (time.elapsed_seconds().sin() * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
let rot = (ops::sin(time.elapsed_seconds()) * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
t.rotation = Quat::from_rotation_z(rot);
}
}

View file

@ -73,9 +73,9 @@ fn update(
.map(|i| {
let t = time.elapsed_seconds() * 5.0;
[
(t + i as f32).sin() / 2.0 + 0.5,
(t + i as f32 + 2.0).sin() / 2.0 + 0.5,
(t + i as f32 + 4.0).sin() / 2.0 + 0.5,
ops::sin(t + i as f32) / 2.0 + 0.5,
ops::sin(t + i as f32 + 2.0) / 2.0 + 0.5,
ops::sin(t + i as f32 + 4.0) / 2.0 + 0.5,
1.0,
]
})

View file

@ -547,7 +547,7 @@ mod ui {
pub fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
for mut sprite in &mut query {
let new_color = LinearRgba {
blue: (time.elapsed_seconds() * 0.5).sin() + 2.0,
blue: ops::sin(time.elapsed_seconds() * 0.5) + 2.0,
..LinearRgba::from(sprite.color)
};

View file

@ -196,7 +196,7 @@ fn movement(
fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
for mut sprite in &mut query {
let new_color = LinearRgba {
blue: (time.elapsed_seconds() * 0.5).sin() + 2.0,
blue: ops::sin(time.elapsed_seconds() * 0.5) + 2.0,
..LinearRgba::from(sprite.color)
};

View file

@ -156,7 +156,7 @@ fn movement(
fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
for mut sprite in &mut query {
let new_color = LinearRgba {
blue: (time.elapsed_seconds() * 0.5).sin() + 2.0,
blue: ops::sin(time.elapsed_seconds() * 0.5) + 2.0,
..LinearRgba::from(sprite.color)
};

View file

@ -117,7 +117,7 @@ fn movement(
fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
for mut sprite in &mut query {
let new_color = LinearRgba {
blue: (time.elapsed_seconds() * 0.5).sin() + 2.0,
blue: ops::sin(time.elapsed_seconds() * 0.5) + 2.0,
..LinearRgba::from(sprite.color)
};

View file

@ -361,7 +361,7 @@ fn init_meshes(args: &Args, assets: &mut Assets<Mesh>) -> Vec<(Handle<Mesh>, Tra
let mut vertices = [Vec2::ZERO; 3];
let dtheta = std::f32::consts::TAU / 3.0;
for (i, vertex) in vertices.iter_mut().enumerate() {
let (s, c) = (i as f32 * dtheta).sin_cos();
let (s, c) = ops::sin_cos(i as f32 * dtheta);
*vertex = Vec2::new(c, s) * radius;
}
(
@ -439,7 +439,7 @@ const EPSILON: f64 = 0.36;
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
DVec2::new(
PI * 2. * (i as f64 / golden_ratio),
(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(),
f64::acos(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)),
)
}

View file

@ -169,7 +169,7 @@ fn setup(
for fox_i in 0..foxes_in_ring {
let fox_angle = fox_i as f32 * fox_spacing_angle;
let (s, c) = fox_angle.sin_cos();
let (s, c) = ops::sin_cos(fox_angle);
let (x, z) = (radius * c, radius * s);
commands.entity(ring_parent).with_children(|builder| {

View file

@ -70,7 +70,7 @@ fn system(config: Res<Config>, time: Res<Time>, mut draw: Gizmos) {
for i in 0..(config.line_count / SYSTEM_COUNT) {
let angle = i as f32 / (config.line_count / SYSTEM_COUNT) as f32 * TAU;
let vector = Vec2::from(angle.sin_cos()).extend(time.elapsed_seconds().sin());
let vector = Vec2::from(ops::sin_cos(angle)).extend(ops::sin(time.elapsed_seconds()));
let start_color = LinearRgba::rgb(vector.x, vector.z, 0.5);
let end_color = LinearRgba::rgb(-vector.z, -vector.y, 0.5);

View file

@ -125,7 +125,8 @@ const EPSILON: f64 = 0.36;
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
DVec2::new(
PI * 2. * (i as f64 / golden_ratio),
(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(),
ops::acos((1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)) as f32)
as f64,
)
}

View file

@ -73,7 +73,7 @@ fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
// changing the bounds of the text will cause a recomputation
fn update_text_bounds(time: Res<Time>, mut text_bounds_query: Query<&mut TextBounds>) {
let width = (1. + time.elapsed_seconds().sin()) * 600.0;
let width = (1. + ops::sin(time.elapsed_seconds())) * 600.0;
for mut text_bounds in text_bounds_query.iter_mut() {
text_bounds.width = Some(width);
}

View file

@ -265,8 +265,8 @@ fn update(time: Res<Time>, mut query: Query<(&mut Transform, &mut UpdateValue)>)
/// set translation based on the angle `a`
fn set_translation(translation: &mut Vec3, a: f32) {
translation.x = a.cos() * 32.0;
translation.y = a.sin() * 32.0;
translation.x = ops::cos(a) * 32.0;
translation.y = ops::sin(a) * 32.0;
}
fn setup(mut commands: Commands, cfg: Res<Cfg>) {

View file

@ -169,7 +169,7 @@ fn move_virtual_time_sprites(
}
fn get_sprite_translation_x(elapsed: f32) -> f32 {
elapsed.sin() * 500.
ops::sin(elapsed) * 500.
}
/// Update the speed of `Time<Virtual>.` by `DELTA`

View file

@ -48,8 +48,8 @@ struct Move;
impl UpdateTransform for Move {
fn update(&self, t: f32, transform: &mut Transform) {
transform.translation.x = (t * TAU - FRAC_PI_2).sin() * HALF_CONTAINER_SIZE;
transform.translation.y = -(t * TAU - FRAC_PI_2).cos() * HALF_CONTAINER_SIZE;
transform.translation.x = ops::sin(t * TAU - FRAC_PI_2) * HALF_CONTAINER_SIZE;
transform.translation.y = -ops::cos(t * TAU - FRAC_PI_2) * HALF_CONTAINER_SIZE;
}
}
@ -58,8 +58,8 @@ struct Scale;
impl UpdateTransform for Scale {
fn update(&self, t: f32, transform: &mut Transform) {
transform.scale.x = 1.0 + 0.5 * (t * TAU).cos().max(0.0);
transform.scale.y = 1.0 + 0.5 * (t * TAU + PI).cos().max(0.0);
transform.scale.x = 1.0 + 0.5 * ops::cos(t * TAU).max(0.0);
transform.scale.y = 1.0 + 0.5 * ops::cos(t * TAU + PI).max(0.0);
}
}
@ -68,7 +68,8 @@ struct Rotate;
impl UpdateTransform for Rotate {
fn update(&self, t: f32, transform: &mut Transform) {
transform.rotation = Quat::from_axis_angle(Vec3::Z, ((t * TAU).cos() * 45.0).to_radians());
transform.rotation =
Quat::from_axis_angle(Vec3::Z, (ops::cos(t * TAU) * 45.0).to_radians());
}
}

View file

@ -122,9 +122,9 @@ fn text_color_system(time: Res<Time>, mut query: Query<&mut Text, With<ColorText
// Update the color of the first and only section.
text.sections[0].style.color = Color::srgb(
(1.25 * seconds).sin() / 2.0 + 0.5,
(0.75 * seconds).sin() / 2.0 + 0.5,
(0.50 * seconds).sin() / 2.0 + 0.5,
ops::sin(1.25 * seconds) / 2.0 + 0.5,
ops::sin(0.75 * seconds) / 2.0 + 0.5,
ops::sin(0.50 * seconds) / 2.0 + 0.5,
);
}
}

View file

@ -139,6 +139,6 @@ fn ease_in_expo(x: f32) -> f32 {
if x == 0. {
0.
} else {
2.0f32.powf(5. * x - 5.)
ops::powf(2.0f32, 5. * x - 5.)
}
}