#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum DistanceAttenuation {
#[default]
Auto,
None,
Linear {
min_distance: f32,
max_distance: f32,
gain_at_max_distance: f32,
},
Natural {
min_distance: f32,
},
}
impl DistanceAttenuation {
pub const MIN_DISTANCE: f32 = 0.1;
const AUTO_MIN_DISTANCE: f32 = 1.0;
pub fn gain(self, distance: f32) -> f32 {
let distance = if distance.is_finite() {
distance.max(0.0)
} else {
0.0
};
match self {
Self::None => 1.0,
Self::Auto => natural_gain(Self::AUTO_MIN_DISTANCE, distance),
Self::Natural { min_distance } => natural_gain(min_distance, distance),
Self::Linear {
min_distance,
max_distance,
gain_at_max_distance,
} => {
let min = clean_min(min_distance);
let max = if max_distance.is_finite() {
max_distance.max(min)
} else {
min
};
let floor = if gain_at_max_distance.is_finite() {
gain_at_max_distance.clamp(0.0, 1.0)
} else {
1.0
};
if distance <= min {
1.0
} else if distance >= max {
floor
} else {
1.0 + (floor - 1.0) * (distance - min) / (max - min)
}
}
}
}
pub(crate) fn to_words(self) -> [u32; 4] {
let (kind, a, b, c) = match self {
Self::Auto => (0, 0.0, 0.0, 0.0),
Self::None => (1, 0.0, 0.0, 0.0),
Self::Linear {
min_distance,
max_distance,
gain_at_max_distance,
} => (2, min_distance, max_distance, gain_at_max_distance),
Self::Natural { min_distance } => (3, min_distance, 0.0, 0.0),
};
[kind, a.to_bits(), b.to_bits(), c.to_bits()]
}
pub(crate) fn from_words(words: [u32; 4]) -> Self {
let [kind, a, b, c] = words;
let [a, b, c] = [a, b, c].map(f32::from_bits);
match kind {
1 => Self::None,
2 => Self::Linear {
min_distance: a,
max_distance: b,
gain_at_max_distance: c,
},
3 => Self::Natural { min_distance: a },
_ => Self::Auto,
}
}
}
fn clean_min(min_distance: f32) -> f32 {
if min_distance.is_finite() {
min_distance.max(DistanceAttenuation::MIN_DISTANCE)
} else {
DistanceAttenuation::MIN_DISTANCE
}
}
fn natural_gain(min_distance: f32, distance: f32) -> f32 {
let min = clean_min(min_distance);
if distance <= min { 1.0 } else { min / distance }
}
#[cfg(test)]
#[path = "tests/distance_attenuation_tests.rs"]
mod tests;