Skip to content

Commit 38d3d37

Browse files
authored
Allow UnevenSampleCurve to infer interpolation arguments from samples (#20046)
# Objective `bevy_math::curve::UnevenSampleCurve` was lacking trait bounds on its `new` method which caused a need to manually specify interpolation function argument types, even though the types are already known from the timed_samples argument. ```rs UnevenSampleCurve::new( [(0.1, 1.0), (1.0, 3.0)], |x: &f64, y: &f64, t| x.lerp(*y, t) // ^ ugly and annoying ) ``` ## Solution This adds the `Fn` trait bound to the new method, matching the behaviour of `SampleCurve`. ## Testing I added a test which doesn't actually test for any runtime behaviour, instead writing code that would error before this PR. --- ## Showcase It's now possible to create a `UnevenSampleCurve` without specifying the interpolation closure argument types. ```diff UnevenSampleCurve::new( [(0.1, 1.0), (1.0, 3.0)], - |x: &f64, y: &f64, t| x.lerp(*y, t) + |x, y, t| x.lerp(*y, t) ) ``` ### Sidenote Seeing `x` and `y` in lerp feels wrong, I've always used `a` and `b` to avoid confusion with coordinates.
1 parent 9a5d907 commit 38d3d37

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

crates/bevy_math/src/curve/sample_curves.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,10 @@ impl<T, I> UnevenSampleCurve<T, I> {
279279
pub fn new(
280280
timed_samples: impl IntoIterator<Item = (f32, T)>,
281281
interpolation: I,
282-
) -> Result<Self, UnevenCoreError> {
282+
) -> Result<Self, UnevenCoreError>
283+
where
284+
I: Fn(&T, &T, f32) -> T,
285+
{
283286
Ok(Self {
284287
core: UnevenCore::new(timed_samples)?,
285288
interpolation,
@@ -403,4 +406,11 @@ mod tests {
403406
let _: Box<dyn Reflect> = Box::new(UnevenSampleCurve::new(keyframes, bar).unwrap());
404407
let _: Box<dyn Reflect> = Box::new(UnevenSampleCurve::new(keyframes, baz).unwrap());
405408
}
409+
#[test]
410+
fn test_infer_interp_arguments() {
411+
// it should be possible to infer the x and y arguments of the interpolation function
412+
// from the input samples. If that becomes impossible, this will fail to compile.
413+
SampleCurve::new(Interval::UNIT, [0.0, 1.0], |x, y, t| x.lerp(*y, t)).ok();
414+
UnevenSampleCurve::new([(0.1, 1.0), (1.0, 3.0)], |x, y, t| x.lerp(*y, t)).ok();
415+
}
406416
}

0 commit comments

Comments
 (0)