rayengine_core/tween/
shake.rs1use crate::camera::{Camera2D, Camera3D};
4use glam::{Mat2, Quat, Vec2};
5use std::{fmt, time::Duration};
6
7#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct ShakeConfig {
11 pub max_offset: Vec2,
13 pub max_roll: f32,
15 pub frequency: f32,
17 pub decay: f32,
19 pub seed: u32,
21}
22
23impl Default for ShakeConfig {
24 fn default() -> Self {
25 Self {
26 max_offset: Vec2::splat(8.0),
27 max_roll: 0.05,
28 frequency: 18.0,
29 decay: 1.5,
30 seed: 0,
31 }
32 }
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct ShakeError(pub &'static str);
38
39impl fmt::Display for ShakeError {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.write_str(self.0)
42 }
43}
44impl std::error::Error for ShakeError {}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct ShakeSample {
49 pub offset: Vec2,
51 pub roll: f32,
53}
54
55#[derive(Clone, Debug)]
75pub struct Shake {
76 config: ShakeConfig,
77 trauma: f32,
78 lattice: u32,
81 phase: f64,
82}
83
84impl Shake {
85 pub fn new(config: ShakeConfig) -> Result<Self, ShakeError> {
87 Self::validate(&config)?;
88 Ok(Self {
89 config,
90 trauma: 0.0,
91 lattice: 0,
92 phase: 0.0,
93 })
94 }
95
96 fn validate(config: &ShakeConfig) -> Result<(), ShakeError> {
97 if !config.max_offset.is_finite() || config.max_offset.min_element() < 0.0 {
98 return Err(ShakeError("shake offset must be finite and nonnegative"));
99 }
100 if !config.max_roll.is_finite() || config.max_roll < 0.0 {
101 return Err(ShakeError("shake roll must be finite and nonnegative"));
102 }
103 if !config.frequency.is_finite() || config.frequency <= 0.0 {
104 return Err(ShakeError("shake frequency must be finite and positive"));
105 }
106 if !config.decay.is_finite() || config.decay < 0.0 {
107 return Err(ShakeError("shake decay must be finite and nonnegative"));
108 }
109 Ok(())
110 }
111
112 pub fn config(&self) -> &ShakeConfig {
114 &self.config
115 }
116 pub fn set_config(&mut self, config: ShakeConfig) -> Result<(), ShakeError> {
118 Self::validate(&config)?;
119 self.config = config;
120 Ok(())
121 }
122
123 pub fn add_trauma(&mut self, amount: f32) {
126 if amount.is_finite() {
127 self.trauma = (self.trauma + amount).clamp(0.0, 1.0);
128 }
129 }
130 pub fn set_trauma(&mut self, trauma: f32) {
132 if trauma.is_finite() {
133 self.trauma = trauma.clamp(0.0, 1.0);
134 }
135 }
136 pub fn trauma(&self) -> f32 {
138 self.trauma
139 }
140 pub fn intensity(&self) -> f32 {
142 self.trauma * self.trauma
143 }
144
145 pub fn advance(&mut self, dt: Duration) {
147 let seconds = dt.as_secs_f64();
148 self.trauma =
149 (f64::from(self.trauma) - f64::from(self.config.decay) * seconds).max(0.0) as f32;
150 let phase = self.phase + seconds * f64::from(self.config.frequency);
151 let whole = phase.floor();
152 self.phase = phase - whole;
153 self.lattice = self
155 .lattice
156 .wrapping_add(whole.rem_euclid(4_294_967_296.0) as u32);
157 }
158
159 pub fn sample(&self) -> ShakeSample {
161 let intensity = self.intensity();
162 if intensity == 0.0 {
163 return ShakeSample::default();
164 }
165 ShakeSample {
166 offset: Vec2::new(self.noise(0), self.noise(1)) * self.config.max_offset * intensity,
167 roll: self.noise(2) * self.config.max_roll * intensity,
168 }
169 }
170
171 pub fn apply_2d(&self, camera: Camera2D) -> Camera2D {
173 let sample = self.sample();
174 if sample == ShakeSample::default() {
175 return camera;
176 }
177 Camera2D {
178 target: camera.target + Mat2::from_angle(-camera.rotation) * sample.offset,
179 rotation: camera.rotation + sample.roll,
180 ..camera
181 }
182 }
183
184 pub fn apply_3d(&self, camera: Camera3D) -> Camera3D {
188 let sample = self.sample();
189 let forward = (camera.target - camera.position).normalize_or_zero();
190 let right = forward.cross(camera.up).normalize_or_zero();
191 if sample == ShakeSample::default() || right == glam::Vec3::ZERO {
192 return camera;
193 }
194 let up = right.cross(forward);
195 let offset = right * sample.offset.x + up * sample.offset.y;
196 Camera3D {
197 position: camera.position + offset,
198 target: camera.target + offset,
199 up: Quat::from_axis_angle(forward, sample.roll) * camera.up,
200 ..camera
201 }
202 }
203
204 fn noise(&self, channel: u32) -> f32 {
206 let a = self.hash(self.lattice, channel);
207 let b = self.hash(self.lattice.wrapping_add(1), channel);
208 let t = self.phase as f32;
209 let t = t * t * (3.0 - 2.0 * t);
210 a + (b - a) * t
211 }
212
213 fn hash(&self, index: u32, channel: u32) -> f32 {
214 let mut x = index ^ self.config.seed.rotate_left(16) ^ channel.wrapping_mul(0x9E37_79B9);
216 x ^= x >> 16;
217 x = x.wrapping_mul(0x7FEB_352D);
218 x ^= x >> 15;
219 x = x.wrapping_mul(0x846C_A68B);
220 x ^= x >> 16;
221 (x as f32 / u32::MAX as f32) * 2.0 - 1.0
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn lattice_wraps_without_a_discontinuity() {
231 let mut shake = Shake::new(ShakeConfig {
232 frequency: 1.0,
233 decay: 0.0,
234 ..ShakeConfig::default()
235 })
236 .unwrap();
237 shake.set_trauma(1.0);
238 shake.lattice = u32::MAX;
239 shake.phase = 0.999_999;
240 let before = shake.sample();
241 shake.advance(Duration::from_micros(2));
242 assert_eq!(shake.lattice, 0);
243 assert!((shake.sample().offset - before.offset).length() < 1e-3);
244 shake.advance(Duration::MAX);
245 assert!(shake.phase >= 0.0 && shake.phase < 1.0);
246 assert!(shake.sample().offset.is_finite());
247 }
248}