Skip to main content

euv_core/game/fluid/sim/
impl.rs

1use super::*;
2
3/// Construction helpers for `BuoyantBody`.
4impl BuoyantBody {
5    /// Creates a stationary `BuoyantBody` positioned at `pos` with physical radius and material density.
6    ///
7    /// # Arguments
8    ///
9    /// - `BuoyantBodyKind` - Visual and physical body classification.
10    /// - `[f32; 2]` - Initial center `[x_m, y_m]` inside the vessel.
11    /// - `f32` - Initial orientation angle in radians.
12    /// - `f32` - Characteristic radius in meters.
13    /// - `f32` - Material density in `kg/m³`.
14    /// - `f32` - Initial submerged volume fraction in `[0.0, 1.0]`.
15    ///
16    /// # Returns
17    ///
18    /// - `Self` - Constructed buoyant body.
19    #[must_use]
20    pub fn with_pose(
21        kind: BuoyantBodyKind,
22        pos: [f32; 2],
23        angle: f32,
24        radius: f32,
25        density_kgm3: f32,
26        submerged_fraction: f32,
27    ) -> Self {
28        Self {
29            kind,
30            x: pos[0],
31            y: pos[1],
32            vx: 0.0,
33            vy: 0.0,
34            angle,
35            omega: 0.0,
36            radius,
37            density_kgm3,
38            submerged_fraction,
39        }
40    }
41}
42
43/// Construction helpers for `FluidBubble`.
44impl FluidBubble {
45    /// Spawns a freshly entrained foam or rising micro-bubble at `pos` with initial velocity `vel`.
46    ///
47    /// # Arguments
48    ///
49    /// - `[f32; 2]` - Initial position `[x_m, y_m]` inside the vessel.
50    /// - `[f32; 2]` - Initial velocity `[vx_mps, vy_mps]`.
51    /// - `f32` - Bubble radius in meters.
52    /// - `f32` - Maximum lifetime in seconds.
53    /// - `f32` - Initial foam factor in `[0.0, 1.0]`.
54    ///
55    /// # Returns
56    ///
57    /// - `Self` - Newly spawned fluid bubble.
58    #[must_use]
59    pub fn spawn(
60        pos: [f32; 2],
61        vel: [f32; 2],
62        radius: f32,
63        lifetime: f32,
64        foam_factor: f32,
65    ) -> Self {
66        Self {
67            x: pos[0],
68            y: pos[1],
69            vx: vel[0],
70            vy: vel[1],
71            radius,
72            age: 0.0,
73            lifetime,
74            foam_factor,
75        }
76    }
77}
78
79/// Default handheld physical glass vessel liquid configuration.
80impl Default for GyroLiquidConfig {
81    /// Creates the default physical handheld water configuration (`12 cm × 9 cm`, 48% filled, 20 °C water).
82    ///
83    /// # Returns
84    ///
85    /// - `Self` - Default liquid configuration.
86    fn default() -> Self {
87        Self {
88            vessel_width_m: DEFAULT_VESSEL_WIDTH_M,
89            vessel_height_m: DEFAULT_VESSEL_HEIGHT_M,
90            fill_ratio: FLUID_DEFAULT_FILL_RATIO,
91            viscosity_scale: 1.0,
92            surface_tension_scale: 1.0,
93            buoyant_bodies_enabled: true,
94            substeps: FLUID_DEFAULT_SUBSTEPS,
95            solver_iterations: FLUID_DEFAULT_SOLVER_ITERS,
96            base_particle_count: FLUID_BASE_PARTICLES_HALF_FILL,
97        }
98    }
99}
100
101/// Default pre-allocated empty simulation snapshot ready for zero-allocation double buffering.
102impl Default for FluidSimSnapshot {
103    /// Allocates a fixed-capacity `FluidSimSnapshot` so subsequent captures perform zero heap allocations.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Pre-allocated fluid simulation snapshot.
108    fn default() -> Self {
109        Self {
110            vessel_width_m: DEFAULT_VESSEL_WIDTH_M,
111            vessel_height_m: DEFAULT_VESSEL_HEIGHT_M,
112            kernel_radius_m: 0.008,
113            particle_count: 0,
114            bubble_count: 0,
115            buoyant_body_count: 0,
116            gravity_x: 0.0,
117            gravity_y: STANDARD_GRAVITY_MPS2,
118            gravity_z: 0.0,
119            sim_time_secs: 0.0,
120            pos_x: vec![0.0; FLUID_MAX_PARTICLES],
121            pos_y: vec![0.0; FLUID_MAX_PARTICLES],
122            vel_x: vec![0.0; FLUID_MAX_PARTICLES],
123            vel_y: vec![0.0; FLUID_MAX_PARTICLES],
124            density_ratio: vec![1.0; FLUID_MAX_PARTICLES],
125            buoyant_bodies: vec![BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES],
126            bubbles: vec![FluidBubble::default(); FLUID_MAX_BUBBLES],
127        }
128    }
129}
130
131/// Zero-allocation render-time snapshot interpolation for `FluidSimSnapshot`.
132impl InterpolatableState for FluidSimSnapshot {
133    /// Returns a newly interpolated `FluidSimSnapshot` at normalized fraction `alpha`.
134    ///
135    /// # Arguments
136    ///
137    /// - `&Self` - Previous fixed-step snapshot.
138    /// - `&Self` - Current fixed-step snapshot.
139    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
140    ///
141    /// # Returns
142    ///
143    /// - `Self` - Interpolated snapshot.
144    fn interpolate(&self, next: &Self, alpha: f32) -> Self {
145        let mut out: Self = Self::default();
146        self.interpolate_into(next, alpha, &mut out);
147        out
148    }
149
150    /// Copies all active lanes from `src` into `self` without heap allocations.
151    ///
152    /// # Arguments
153    ///
154    /// - `&Self` - Mutable destination snapshot.
155    /// - `&Self` - Source snapshot to copy.
156    fn copy_from_snapshot(&mut self, src: &Self) {
157        let n: usize = src.get_particle_count().min(FLUID_MAX_PARTICLES);
158        let b_count: usize = src.get_buoyant_body_count().min(FLUID_MAX_BUOYANT_BODIES);
159        let bub_count: usize = src.get_bubble_count().min(FLUID_MAX_BUBBLES);
160        self.set_vessel_width_m(src.get_vessel_width_m());
161        self.set_vessel_height_m(src.get_vessel_height_m());
162        self.set_kernel_radius_m(src.get_kernel_radius_m());
163        self.set_particle_count(n);
164        self.set_buoyant_body_count(b_count);
165        self.set_bubble_count(bub_count);
166        self.set_gravity_x(src.get_gravity_x());
167        self.set_gravity_y(src.get_gravity_y());
168        self.set_gravity_z(src.get_gravity_z());
169        self.set_sim_time_secs(src.get_sim_time_secs());
170        if self.get_pos_x().len() < FLUID_MAX_PARTICLES {
171            self.get_mut_pos_x().resize(FLUID_MAX_PARTICLES, 0.0);
172            self.get_mut_pos_y().resize(FLUID_MAX_PARTICLES, 0.0);
173            self.get_mut_vel_x().resize(FLUID_MAX_PARTICLES, 0.0);
174            self.get_mut_vel_y().resize(FLUID_MAX_PARTICLES, 0.0);
175            self.get_mut_density_ratio()
176                .resize(FLUID_MAX_PARTICLES, 1.0);
177        }
178        if self.get_buoyant_bodies().len() < FLUID_MAX_BUOYANT_BODIES {
179            self.get_mut_buoyant_bodies()
180                .resize(FLUID_MAX_BUOYANT_BODIES, BuoyantBody::default());
181        }
182        if self.get_bubbles().len() < FLUID_MAX_BUBBLES {
183            self.get_mut_bubbles()
184                .resize(FLUID_MAX_BUBBLES, FluidBubble::default());
185        }
186        self.get_mut_pos_x()[..n].copy_from_slice(&src.get_pos_x()[..n]);
187        self.get_mut_pos_y()[..n].copy_from_slice(&src.get_pos_y()[..n]);
188        self.get_mut_vel_x()[..n].copy_from_slice(&src.get_vel_x()[..n]);
189        self.get_mut_vel_y()[..n].copy_from_slice(&src.get_vel_y()[..n]);
190        self.get_mut_density_ratio()[..n].copy_from_slice(&src.get_density_ratio()[..n]);
191        self.get_mut_buoyant_bodies()[..b_count]
192            .copy_from_slice(&src.get_buoyant_bodies()[..b_count]);
193        self.get_mut_bubbles()[..bub_count].copy_from_slice(&src.get_bubbles()[..bub_count]);
194    }
195
196    /// Interpolates between `self` and `next` at `alpha` directly into `out` with zero heap allocations.
197    ///
198    /// # Arguments
199    ///
200    /// - `&Self` - Previous fixed-step snapshot.
201    /// - `&Self` - Current fixed-step snapshot.
202    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
203    /// - `&mut Self` - Pre-allocated destination snapshot.
204    fn interpolate_into(&self, next: &Self, alpha: f32, out: &mut Self) {
205        let t: f32 = alpha.clamp(0.0, 1.0);
206        let omt: f32 = 1.0 - t;
207        let n_prev: usize = self.get_particle_count();
208        let n_next: usize = next.get_particle_count().min(FLUID_MAX_PARTICLES);
209        if n_prev != n_next {
210            out.copy_from_snapshot(next);
211            return;
212        }
213        out.copy_from_snapshot(next);
214        out.set_vessel_width_m(self.get_vessel_width_m() * omt + next.get_vessel_width_m() * t);
215        out.set_vessel_height_m(self.get_vessel_height_m() * omt + next.get_vessel_height_m() * t);
216        out.set_gravity_x(self.get_gravity_x() * omt + next.get_gravity_x() * t);
217        out.set_gravity_y(self.get_gravity_y() * omt + next.get_gravity_y() * t);
218        out.set_gravity_z(self.get_gravity_z() * omt + next.get_gravity_z() * t);
219        out.set_sim_time_secs(self.get_sim_time_secs() * omt + next.get_sim_time_secs() * t);
220        let px0: &[f32] = self.get_pos_x();
221        let py0: &[f32] = self.get_pos_y();
222        let vx0: &[f32] = self.get_vel_x();
223        let vy0: &[f32] = self.get_vel_y();
224        let dr0: &[f32] = self.get_density_ratio();
225        let px1: &[f32] = next.get_pos_x();
226        let py1: &[f32] = next.get_pos_y();
227        let vx1: &[f32] = next.get_vel_x();
228        let vy1: &[f32] = next.get_vel_y();
229        let dr1: &[f32] = next.get_density_ratio();
230        let Self {
231            pos_x: opx,
232            pos_y: opy,
233            vel_x: ovx,
234            vel_y: ovy,
235            density_ratio: odr,
236            buoyant_bodies: obodies,
237            ..
238        } = out;
239        for i in 0..n_next {
240            opx[i] = px0[i] * omt + px1[i] * t;
241            opy[i] = py0[i] * omt + py1[i] * t;
242            ovx[i] = vx0[i] * omt + vx1[i] * t;
243            ovy[i] = vy0[i] * omt + vy1[i] * t;
244            odr[i] = dr0[i] * omt + dr1[i] * t;
245        }
246        let b_count: usize = next
247            .get_buoyant_body_count()
248            .min(self.get_buoyant_body_count())
249            .min(FLUID_MAX_BUOYANT_BODIES);
250        let b0: &[BuoyantBody] = self.get_buoyant_bodies();
251        let b1: &[BuoyantBody] = next.get_buoyant_bodies();
252        for idx in 0..b_count {
253            let mut body: BuoyantBody = b1[idx];
254            body.set_x(b0[idx].get_x() * omt + b1[idx].get_x() * t);
255            body.set_y(b0[idx].get_y() * omt + b1[idx].get_y() * t);
256            body.set_vx(b0[idx].get_vx() * omt + b1[idx].get_vx() * t);
257            body.set_vy(b0[idx].get_vy() * omt + b1[idx].get_vy() * t);
258            let mut da: f32 = b1[idx].get_angle() - b0[idx].get_angle();
259            while da > PI {
260                da -= TAU;
261            }
262            while da < -PI {
263                da += TAU;
264            }
265            body.set_angle(b0[idx].get_angle() + da * t);
266            obodies[idx] = body;
267        }
268    }
269}
270
271/// Default handheld SI Position-Based Fluids solver.
272impl Default for LiquidFluidSolver {
273    /// Creates a `LiquidFluidSolver` initialized with `GyroLiquidConfig::default()`.
274    ///
275    /// # Returns
276    ///
277    /// - `Self` - Pre-allocated SI liquid solver ready for zero-alloc stepping.
278    fn default() -> Self {
279        Self::with_config(GyroLiquidConfig::default())
280    }
281}
282
283/// SI Position-Based Fluids simulation, non-inertial frame kinematics, Archimedes buoyancy, and snapshot capture for `LiquidFluidSolver`.
284impl LiquidFluidSolver {
285    /// Creates a pre-allocated `LiquidFluidSolver` with `config` and initializes calm resting water.
286    ///
287    /// # Arguments
288    ///
289    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
290    ///
291    /// # Returns
292    ///
293    /// - `Self` - Initialized liquid solver.
294    #[must_use]
295    pub fn with_config(config: GyroLiquidConfig) -> Self {
296        let mut solver: Self = Self {
297            config,
298            particle_count: 0,
299            rest_spacing_m: 0.003,
300            particle_area_m2: 9.0e-6,
301            particle_mass_kgpm: 0.009,
302            kernel_radius_m: 0.0075,
303            poly6_coeff: 1.0,
304            spiky_grad_coeff: -1.0,
305            w_dq: 1.0,
306            gravity_x: 0.0,
307            gravity_y: STANDARD_GRAVITY_MPS2,
308            gravity_z: 0.0,
309            linear_accel_x: 0.0,
310            linear_accel_y: 0.0,
311            shake_accel_x: 0.0,
312            shake_accel_y: 0.0,
313            angular_vel_cw: 0.0,
314            prev_angular_vel_cw: 0.0,
315            angular_accel_cw: 0.0,
316            virtual_roll_rad: 0.0,
317            virtual_pitch_rad: 0.0,
318            prev_virtual_roll_rad: 0.0,
319            active_roll_rad: 0.0,
320            sim_time_secs: 0.0,
321            rng_state: FLUID_RNG_SEED,
322            kinetic_energy_mj: 0.0,
323            peak_wave_height_m: 0.0,
324            grid_w: 16,
325            grid_h: 12,
326            pos_x: vec![0.0; FLUID_MAX_PARTICLES],
327            pos_y: vec![0.0; FLUID_MAX_PARTICLES],
328            pred_x: vec![0.0; FLUID_MAX_PARTICLES],
329            pred_y: vec![0.0; FLUID_MAX_PARTICLES],
330            vel_x: vec![0.0; FLUID_MAX_PARTICLES],
331            vel_y: vec![0.0; FLUID_MAX_PARTICLES],
332            lambda: vec![0.0; FLUID_MAX_PARTICLES],
333            density: vec![WATER_REST_DENSITY_KGM3; FLUID_MAX_PARTICLES],
334            vorticity: vec![0.0; FLUID_MAX_PARTICLES],
335            corr_x: vec![0.0; FLUID_MAX_PARTICLES],
336            corr_y: vec![0.0; FLUID_MAX_PARTICLES],
337            dvx_scratch: vec![0.0; FLUID_MAX_PARTICLES],
338            dvy_scratch: vec![0.0; FLUID_MAX_PARTICLES],
339            cell_counts: vec![0; FLUID_MAX_GRID_CELLS],
340            cell_starts: vec![0; FLUID_MAX_GRID_CELLS + 1],
341            cell_cursors: vec![0; FLUID_MAX_GRID_CELLS],
342            particle_cells: vec![0; FLUID_MAX_PARTICLES],
343            sorted_indices: vec![0; FLUID_MAX_PARTICLES],
344            neighbor_indices: vec![0; FLUID_MAX_PARTICLES * FLUID_MAX_NEIGHBORS],
345            neighbor_counts: vec![0; FLUID_MAX_PARTICLES],
346            buoyant_bodies: vec![BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES],
347            buoyant_body_count: 0,
348            bubbles: vec![FluidBubble::default(); FLUID_MAX_BUBBLES],
349            bubble_count: 0,
350        };
351        solver.reset_water();
352        solver
353    }
354
355    /// Recomputes SI particle mass, kernel radius, and normalization coefficients from current vessel area and `particle_count`.
356    ///
357    /// # Arguments
358    ///
359    /// - `&Self` - Mutable liquid solver.
360    fn recompute_kernel_constants(&mut self) {
361        let cfg: GyroLiquidConfig = self.get_config();
362        let w: f32 = cfg.get_vessel_width_m().clamp(0.06, 0.24);
363        let h_vessel: f32 = cfg.get_vessel_height_m().clamp(0.06, 0.24);
364        let fill: f32 = cfg
365            .get_fill_ratio()
366            .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
367        let n: usize = self.get_particle_count().clamp(64, FLUID_MAX_PARTICLES);
368        let water_area: f32 = fill * w * h_vessel;
369        let particle_area: f32 = water_area / (n as f32);
370        let d0: f32 = particle_area.sqrt();
371        let h: f32 = (d0 * FLUID_KERNEL_RADIUS_MULT).max(0.0025);
372        let h2: f32 = h * h;
373        let h4: f32 = h2 * h2;
374        let h5: f32 = h4 * h;
375        let h8: f32 = h4 * h4;
376        let poly6_coeff: f32 = 4.0 / (PI * h8);
377        let spiky_grad_coeff: f32 = -30.0 / (PI * h5);
378        let dq: f32 = FLUID_SCORR_DQ_RATIO * h;
379        let w_dq: f32 = poly6_2d(dq * dq, h2, poly6_coeff).max(1.0e-6);
380        let gw: usize = ((w / h).ceil() as usize).clamp(4, 64);
381        let gh: usize = ((h_vessel / h).ceil() as usize).clamp(4, 64);
382        let (final_gw, final_gh): (usize, usize) = if gw * gh > FLUID_MAX_GRID_CELLS {
383            (64, FLUID_MAX_GRID_CELLS / 64)
384        } else {
385            (gw, gh)
386        };
387        self.set_rest_spacing_m(d0);
388        self.set_particle_area_m2(particle_area);
389        self.set_particle_mass_kgpm(WATER_REST_DENSITY_KGM3 * particle_area);
390        self.set_kernel_radius_m(h);
391        self.set_poly6_coeff(poly6_coeff);
392        self.set_spiky_grad_coeff(spiky_grad_coeff);
393        self.set_w_dq(w_dq);
394        self.set_grid_w(final_gw);
395        self.set_grid_h(final_gh);
396    }
397
398    /// Resets the liquid particles, buoyant objects, and bubbles to a calm hydrostatic pool matching the active fill ratio.
399    ///
400    /// # Arguments
401    ///
402    /// - `&Self` - Mutable liquid solver.
403    pub fn reset_water(&mut self) {
404        let mut cfg: GyroLiquidConfig = self.get_config();
405        let fill: f32 = cfg
406            .get_fill_ratio()
407            .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
408        cfg.set_fill_ratio(fill);
409        let w: f32 = cfg.get_vessel_width_m().clamp(0.06, 0.24);
410        let h_vessel: f32 = cfg.get_vessel_height_m().clamp(0.06, 0.24);
411        cfg.set_vessel_width_m(w);
412        cfg.set_vessel_height_m(h_vessel);
413        self.set_config(cfg);
414        let target_n: usize = (((cfg.get_base_particle_count() as f32) * (fill / 0.50)).round()
415            as usize)
416            .clamp(120, FLUID_MAX_PARTICLES);
417        self.set_particle_count(target_n);
418        self.recompute_kernel_constants();
419        let d0: f32 = self.get_rest_spacing_m();
420        let pad: f32 = d0 * 0.65;
421        let usable_w: f32 = (w - 2.0 * pad).max(d0 * 2.0);
422        let cols: usize = ((usable_w / d0).floor() as usize).max(4);
423        let col_step: f32 = usable_w / (cols as f32);
424        let rows: usize = target_n.div_ceil(cols);
425        let row_step: f32 = ((h_vessel - 2.0 * pad) * fill / (rows.max(1) as f32)).max(d0 * 0.82);
426        let corner_r: f32 = w.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
427        let mut rng: u64 = FLUID_RNG_SEED;
428        let Self {
429            pos_x,
430            pos_y,
431            pred_x,
432            pred_y,
433            vel_x,
434            vel_y,
435            density,
436            vorticity,
437            lambda,
438            ..
439        } = self;
440        for i in 0..target_n {
441            let row: usize = i / cols;
442            let col: usize = i % cols;
443            let stagger: f32 = if (row & 1) == 1 { 0.5 * col_step } else { 0.0 };
444            let jx: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.08;
445            let jy: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.08;
446            let rx: f32 = pad + (col as f32 + 0.5) * col_step + stagger + jx;
447            let ry: f32 = h_vessel - pad - (row as f32 + 0.5) * row_step + jy;
448            let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
449                clamp_to_rounded_vessel(rx, ry, w, h_vessel, pad, corner_r);
450            pos_x[i] = cx;
451            pos_y[i] = cy;
452            pred_x[i] = cx;
453            pred_y[i] = cy;
454            vel_x[i] = 0.0;
455            vel_y[i] = 0.0;
456            density[i] = WATER_REST_DENSITY_KGM3;
457            vorticity[i] = 0.0;
458            lambda[i] = 0.0;
459        }
460        self.set_rng_state(rng);
461        self.set_bubble_count(0);
462        self.set_shake_accel_x(0.0);
463        self.set_shake_accel_y(0.0);
464        self.set_linear_accel_x(0.0);
465        self.set_linear_accel_y(0.0);
466        self.set_angular_vel_cw(0.0);
467        self.set_prev_angular_vel_cw(0.0);
468        self.set_angular_accel_cw(0.0);
469        self.set_kinetic_energy_mj(0.0);
470        self.set_peak_wave_height_m(0.0);
471        self.reset_buoyant_bodies();
472    }
473
474    /// Initializes the default floating orb (`450 kg/m³`) and ice cube (`917 kg/m³`) near the free surface.
475    ///
476    /// # Arguments
477    ///
478    /// - `&Self` - Mutable liquid solver.
479    pub fn reset_buoyant_bodies(&mut self) {
480        let cfg: GyroLiquidConfig = self.get_config();
481        if !cfg.get_buoyant_bodies_enabled() {
482            self.set_buoyant_body_count(0);
483            return;
484        }
485        let w: f32 = cfg.get_vessel_width_m();
486        let h: f32 = cfg.get_vessel_height_m();
487        let fill: f32 = cfg.get_fill_ratio();
488        let surface_y: f32 = (h * (1.0 - fill)).clamp(h * 0.14, h * 0.82);
489        let min_dim: f32 = w.min(h);
490        let orb_r: f32 = (min_dim * 0.082).clamp(0.0055, 0.011);
491        let ice_r: f32 = (min_dim * 0.090).clamp(0.0062, 0.0125);
492        let orb: BuoyantBody = BuoyantBody::with_pose(
493            BuoyantBodyKind::FloatingOrb,
494            [w * 0.34, surface_y.clamp(orb_r * 1.4, h - orb_r * 1.4)],
495            0.0,
496            orb_r,
497            FLOATING_ORB_DENSITY_KGM3,
498            0.45,
499        );
500        let ice: BuoyantBody = BuoyantBody::with_pose(
501            BuoyantBodyKind::IceCube,
502            [
503                w * 0.66,
504                (surface_y + ice_r * 0.45).clamp(ice_r * 1.4, h - ice_r * 1.4),
505            ],
506            0.22,
507            ice_r,
508            ICE_DENSITY_KGM3,
509            0.917,
510        );
511        let bodies: &mut [BuoyantBody] = self.get_mut_buoyant_bodies();
512        bodies[0] = orb;
513        bodies[1] = ice;
514        self.set_buoyant_body_count(2);
515    }
516
517    /// Adapts physical vessel aspect ratio to match a resized or fullscreen viewport while preserving total physical water area and live wave motion.
518    ///
519    /// # Arguments
520    ///
521    /// - `&Self` - Mutable liquid solver.
522    /// - `f32` - Target viewport `width / height` aspect ratio.
523    pub fn adapt_vessel_aspect(&mut self, aspect_w_over_h: f32) {
524        if !aspect_w_over_h.is_finite() || aspect_w_over_h <= 0.0 {
525            return;
526        }
527        let clamped_aspect: f32 = aspect_w_over_h.clamp(0.42, 2.45);
528        let old_cfg: GyroLiquidConfig = self.get_config();
529        let old_w: f32 = old_cfg.get_vessel_width_m();
530        let old_h: f32 = old_cfg.get_vessel_height_m();
531        let cur_aspect: f32 = old_w / old_h.max(1.0e-4);
532        if (cur_aspect - clamped_aspect).abs() < 0.015 {
533            return;
534        }
535        let target_area: f32 = DEFAULT_VESSEL_WIDTH_M * DEFAULT_VESSEL_HEIGHT_M;
536        let new_w: f32 = (target_area * clamped_aspect).sqrt().clamp(0.068, 0.19);
537        let new_h: f32 = (target_area / new_w).clamp(0.068, 0.19);
538        let sx: f32 = new_w / old_w.max(1.0e-4);
539        let sy: f32 = new_h / old_h.max(1.0e-4);
540        let mut next_cfg: GyroLiquidConfig = old_cfg;
541        next_cfg.set_vessel_width_m(new_w);
542        next_cfg.set_vessel_height_m(new_h);
543        self.set_config(next_cfg);
544        self.recompute_kernel_constants();
545        let n: usize = self.get_particle_count();
546        let d0: f32 = self.get_rest_spacing_m();
547        let pad: f32 = d0 * 0.55;
548        let corner_r: f32 = new_w.min(new_h) * FLUID_CORNER_RADIUS_RATIO;
549        let Self {
550            pos_x,
551            pos_y,
552            pred_x,
553            pred_y,
554            buoyant_bodies,
555            buoyant_body_count,
556            bubbles,
557            bubble_count,
558            ..
559        } = self;
560        for i in 0..n {
561            let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
562                clamp_to_rounded_vessel(pos_x[i] * sx, pos_y[i] * sy, new_w, new_h, pad, corner_r);
563            pos_x[i] = cx;
564            pos_y[i] = cy;
565            pred_x[i] = cx;
566            pred_y[i] = cy;
567        }
568        let min_dim: f32 = new_w.min(new_h);
569        let b_cnt: usize = *buoyant_body_count;
570        for body in buoyant_bodies.iter_mut().take(b_cnt) {
571            let new_r: f32 = match body.get_kind() {
572                BuoyantBodyKind::FloatingOrb => (min_dim * 0.082).clamp(0.0055, 0.011),
573                BuoyantBodyKind::IceCube => (min_dim * 0.090).clamp(0.0062, 0.0125),
574            };
575            body.set_radius(new_r);
576            let (bx, by, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
577                body.get_x() * sx,
578                body.get_y() * sy,
579                new_w,
580                new_h,
581                new_r,
582                corner_r,
583            );
584            body.set_x(bx);
585            body.set_y(by);
586        }
587        let bub_cnt: usize = *bubble_count;
588        for bub in bubbles.iter_mut().take(bub_cnt) {
589            bub.set_x((bub.get_x() * sx).clamp(pad, new_w - pad));
590            bub.set_y((bub.get_y() * sy).clamp(pad, new_h - pad));
591        }
592    }
593
594    /// Updates the liquid fill ratio (`0.20..=0.85`) and rebuilds the resting fluid volume.
595    ///
596    /// # Arguments
597    ///
598    /// - `&Self` - Mutable liquid solver.
599    /// - `f32` - Desired liquid area fill fraction.
600    pub fn set_fill_ratio(&mut self, fill_ratio: f32) {
601        let clamped: f32 = fill_ratio.clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
602        if (self.get_config().get_fill_ratio() - clamped).abs() < 0.005 {
603            return;
604        }
605        let mut cfg: GyroLiquidConfig = self.get_config();
606        cfg.set_fill_ratio(clamped);
607        self.set_config(cfg);
608        self.reset_water();
609    }
610
611    /// Updates the relative viscosity multiplier (`0.2..=6.0`, where `1.0` = 20 °C pure water).
612    ///
613    /// # Arguments
614    ///
615    /// - `&Self` - Mutable liquid solver.
616    /// - `f32` - Relative viscosity scale factor.
617    pub fn set_viscosity(&mut self, viscosity_scale: f32) {
618        let mut cfg: GyroLiquidConfig = self.get_config();
619        cfg.set_viscosity_scale(viscosity_scale.clamp(0.2, 6.0));
620        self.set_config(cfg);
621    }
622
623    /// Updates the relative surface tension multiplier (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
624    ///
625    /// # Arguments
626    ///
627    /// - `&Self` - Mutable liquid solver.
628    /// - `f32` - Relative surface tension scale factor.
629    pub fn set_surface_tension(&mut self, surface_tension_scale: f32) {
630        let mut cfg: GyroLiquidConfig = self.get_config();
631        cfg.set_surface_tension_scale(surface_tension_scale.clamp(0.0, 3.0));
632        self.set_config(cfg);
633    }
634
635    /// Enables or disables Archimedes buoyant floating bodies (orb & ice cube).
636    ///
637    /// # Arguments
638    ///
639    /// - `&Self` - Mutable liquid solver.
640    /// - `bool` - Whether floating buoyant objects are active.
641    pub fn set_buoyant_bodies_enabled(&mut self, enabled: bool) {
642        let mut cfg: GyroLiquidConfig = self.get_config();
643        let prev: bool = cfg.get_buoyant_bodies_enabled();
644        cfg.set_buoyant_bodies_enabled(enabled);
645        self.set_config(cfg);
646        if enabled && !prev {
647            self.reset_buoyant_bodies();
648        } else if !enabled {
649            self.set_buoyant_body_count(0);
650        }
651    }
652
653    /// Sets desktop/simulator virtual device tilt angles (`roll_rad`, `pitch_rad`).
654    ///
655    /// # Arguments
656    ///
657    /// - `&Self` - Mutable liquid solver.
658    /// - `f32` - In-plane roll angle in radians (`0` = upright, `+π/2` = clockwise right-down).
659    /// - `f32` - Out-of-plane pitch angle in radians (`0` = vertical, `+π/2` = flat face-up).
660    pub fn set_virtual_tilt(&mut self, roll_rad: f32, pitch_rad: f32) {
661        if roll_rad.is_finite() {
662            self.set_virtual_roll_rad(roll_rad);
663        }
664        if pitch_rad.is_finite() {
665            self.set_virtual_pitch_rad(pitch_rad.clamp(-FRAC_PI_2 * 0.96, FRAC_PI_2 * 0.96));
666        }
667    }
668
669    /// Rotates the virtual container angle smoothly by `delta_rad` (positive clockwise in screen space).
670    ///
671    /// # Arguments
672    ///
673    /// - `&Self` - Mutable liquid solver.
674    /// - `f32` - Angular rotation increment in radians.
675    pub fn rotate_container_by(&mut self, delta_rad: f32) {
676        if delta_rad.is_finite() {
677            let next: f32 = self.get_virtual_roll_rad() + delta_rad;
678            self.set_virtual_roll_rad(next);
679        }
680    }
681
682    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²` (decays smoothly).
683    ///
684    /// # Arguments
685    ///
686    /// - `&Self` - Mutable liquid solver.
687    /// - `f32` - Horizontal shake acceleration in `m/s²`.
688    /// - `f32` - Vertical shake acceleration in `m/s²`.
689    pub fn apply_shake_impulse(&mut self, ax: f32, ay: f32) {
690        if ax.is_finite() {
691            let next_x: f32 = (self.get_shake_accel_x() + ax)
692                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
693            self.set_shake_accel_x(next_x);
694        }
695        if ay.is_finite() {
696            let next_y: f32 = (self.get_shake_accel_y() + ay)
697                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
698            self.set_shake_accel_y(next_y);
699        }
700    }
701
702    /// Applies a direct pointer/touch viscous wake stirring impulse inside normalized tank coordinates `[0, 1] × [0, 1]`.
703    ///
704    /// # Arguments
705    ///
706    /// - `&Self` - Mutable liquid solver.
707    /// - `f32` - Normalized horizontal coordinate in `[0.0, 1.0]`.
708    /// - `f32` - Normalized vertical coordinate in `[0.0, 1.0]`.
709    /// - `f32` - Stirring velocity x-component in `m/s`.
710    /// - `f32` - Stirring velocity y-component in `m/s`.
711    pub fn apply_stir_impulse(&mut self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
712        if !norm_x.is_finite()
713            || !norm_y.is_finite()
714            || !vel_x_mps.is_finite()
715            || !vel_y_mps.is_finite()
716        {
717            return;
718        }
719        let cfg: GyroLiquidConfig = self.get_config();
720        let w: f32 = cfg.get_vessel_width_m();
721        let h: f32 = cfg.get_vessel_height_m();
722        let sx: f32 = norm_x.clamp(0.0, 1.0) * w;
723        let sy: f32 = norm_y.clamp(0.0, 1.0) * h;
724        let radius: f32 = (w.min(h) * FLUID_STIR_RADIUS_RATIO).max(0.012);
725        let r2_max: f32 = radius * radius;
726        let svx: f32 = vel_x_mps.clamp(-2.2, 2.2);
727        let svy: f32 = vel_y_mps.clamp(-2.2, 2.2);
728        let n: usize = self.get_particle_count();
729        let Self {
730            pos_x,
731            pos_y,
732            vel_x,
733            vel_y,
734            buoyant_bodies,
735            buoyant_body_count,
736            ..
737        } = self;
738        for i in 0..n {
739            let dx: f32 = pos_x[i] - sx;
740            let dy: f32 = pos_y[i] - sy;
741            let d2: f32 = dx * dx + dy * dy;
742            if d2 < r2_max {
743                let falloff: f32 = 1.0 - (d2 / r2_max).sqrt();
744                let gain: f32 = falloff * falloff * 0.55;
745                vel_x[i] = (vel_x[i] + (svx - vel_x[i]) * gain)
746                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
747                vel_y[i] = (vel_y[i] + (svy - vel_y[i]) * gain)
748                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
749            }
750        }
751        let b_cnt: usize = *buoyant_body_count;
752        for body in buoyant_bodies.iter_mut().take(b_cnt) {
753            let dx: f32 = body.get_x() - sx;
754            let dy: f32 = body.get_y() - sy;
755            let d2: f32 = dx * dx + dy * dy;
756            let br: f32 = radius + body.get_radius();
757            if d2 < br * br {
758                let falloff: f32 = 1.0 - (d2.sqrt() / br);
759                let gain: f32 = falloff * 0.45;
760                body.set_vx(body.get_vx() + (svx - body.get_vx()) * gain);
761                body.set_vy(body.get_vy() + (svy - body.get_vy()) * gain);
762                let torque_kick: f32 = (dx * svy - dy * svx) / (br * br + 1.0e-4);
763                body.set_omega((body.get_omega() + torque_kick * 0.35).clamp(-16.0, 16.0));
764            }
765        }
766    }
767
768    /// Feeds a sanitized 6-DOF `DeviceMotionSample` directly into the non-inertial solver frame.
769    ///
770    /// # Arguments
771    ///
772    /// - `&Self` - Mutable liquid solver.
773    /// - `DeviceMotionSample` - Screen-aligned hardware or synthetic sensor sample.
774    /// - `f32` - Timestep in seconds used to estimate Euler angular acceleration `α = dΩ/dt`.
775    pub fn apply_device_motion(&mut self, sample: DeviceMotionSample, dt: f32) {
776        let clean: DeviceMotionSample = sample.sanitized();
777        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
778        let gx: f32 = clean.get_gravity_x();
779        let gy: f32 = clean.get_gravity_y();
780        let gz: f32 = clean.get_gravity_z();
781        let lx: f32 = clean
782            .get_linear_accel_x()
783            .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
784        let ly: f32 = clean
785            .get_linear_accel_y()
786            .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
787        let omega_cw: f32 =
788            (-clean.get_gyro_z()).clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S);
789        let prev_omega: f32 = self.get_angular_vel_cw();
790        let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
791            .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
792        let smoothed_alpha: f32 = self.get_angular_accel_cw() * 0.65 + raw_alpha * 0.35;
793        self.set_gravity_x(gx);
794        self.set_gravity_y(gy);
795        self.set_gravity_z(gz);
796        self.set_linear_accel_x(lx);
797        self.set_linear_accel_y(ly);
798        self.set_prev_angular_vel_cw(prev_omega);
799        self.set_angular_vel_cw(omega_cw);
800        self.set_angular_accel_cw(smoothed_alpha);
801        self.set_active_roll_rad(gx.atan2(gy));
802    }
803
804    /// Updates gravity, angular velocity `Ω`, and Euler acceleration `α` from desktop virtual tilt angles.
805    ///
806    /// # Arguments
807    ///
808    /// - `&Self` - Mutable liquid solver.
809    /// - `f32` - Timestep in seconds.
810    pub fn sync_virtual_motion(&mut self, dt: f32) {
811        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
812        let roll: f32 = self.get_virtual_roll_rad();
813        let pitch: f32 = self.get_virtual_pitch_rad();
814        let cos_p: f32 = pitch.cos();
815        let gx: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.sin();
816        let gy: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.cos();
817        let gz: f32 = -STANDARD_GRAVITY_MPS2 * pitch.sin();
818        let prev_roll: f32 = self.get_prev_virtual_roll_rad();
819        let mut d_roll: f32 = roll - prev_roll;
820        while d_roll > PI {
821            d_roll -= TAU;
822        }
823        while d_roll < -PI {
824            d_roll += TAU;
825        }
826        let omega_cw: f32 = (d_roll / safe_dt).clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S);
827        let prev_omega: f32 = self.get_angular_vel_cw();
828        let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
829            .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
830        let smoothed_alpha: f32 = self.get_angular_accel_cw() * 0.55 + raw_alpha * 0.45;
831        self.set_prev_virtual_roll_rad(roll);
832        self.set_gravity_x(gx);
833        self.set_gravity_y(gy);
834        self.set_gravity_z(gz);
835        self.set_linear_accel_x(0.0);
836        self.set_linear_accel_y(0.0);
837        self.set_prev_angular_vel_cw(prev_omega);
838        self.set_angular_vel_cw(omega_cw);
839        self.set_angular_accel_cw(smoothed_alpha);
840        self.set_active_roll_rad(roll);
841    }
842
843    /// Rebuilds the flat zero-allocation counting-sort CSR spatial hash grid on predicted positions `(pred_x, pred_y)`.
844    ///
845    /// # Arguments
846    ///
847    /// - `&Self` - Mutable liquid solver.
848    fn rebuild_spatial_grid(&mut self) {
849        let n: usize = self.get_particle_count();
850        let gw: usize = self.get_grid_w();
851        let gh: usize = self.get_grid_h();
852        let total_cells: usize = gw * gh;
853        let inv_h: f32 = 1.0 / self.get_kernel_radius_m().max(1.0e-5);
854        let max_cx: i32 = (gw as i32) - 1;
855        let max_cy: i32 = (gh as i32) - 1;
856        let Self {
857            pred_x,
858            pred_y,
859            cell_counts,
860            cell_starts,
861            cell_cursors,
862            particle_cells,
863            sorted_indices,
864            ..
865        } = self;
866        cell_counts[..total_cells].fill(0);
867        for i in 0..n {
868            let cx: i32 = ((pred_x[i] * inv_h).floor() as i32).clamp(0, max_cx);
869            let cy: i32 = ((pred_y[i] * inv_h).floor() as i32).clamp(0, max_cy);
870            let cid: usize = (cy as usize) * gw + (cx as usize);
871            particle_cells[i] = cid as u32;
872            cell_counts[cid] += 1;
873        }
874        let mut prefix: u32 = 0;
875        for c in 0..total_cells {
876            cell_starts[c] = prefix;
877            cell_cursors[c] = prefix;
878            prefix += cell_counts[c];
879        }
880        cell_starts[total_cells] = prefix;
881        for (i, &cell) in particle_cells.iter().enumerate().take(n) {
882            let cid: usize = cell as usize;
883            let dst: usize = cell_cursors[cid] as usize;
884            cell_cursors[cid] = (dst as u32) + 1;
885            sorted_indices[dst] = i as u32;
886        }
887    }
888
889    /// Evaluates fluid density, average velocity, and local curl at world coordinate `(qx, qy)` using the active spatial grid.
890    ///
891    /// # Arguments
892    ///
893    /// - `&Self` - Liquid solver reference.
894    /// - `f32` - Query x-coordinate in meters.
895    /// - `f32` - Query y-coordinate in meters.
896    ///
897    /// # Returns
898    ///
899    /// - `(f32, f32, f32)` - Sampled `(density_ratio, fluid_vx, fluid_vy)`.
900    #[must_use]
901    fn sample_fluid_at(&self, qx: f32, qy: f32) -> (f32, f32, f32) {
902        let h: f32 = self.get_kernel_radius_m();
903        let h2: f32 = h * h;
904        let inv_h: f32 = 1.0 / h.max(1.0e-5);
905        let gw: i32 = self.get_grid_w() as i32;
906        let gh: i32 = self.get_grid_h() as i32;
907        let poly6_c: f32 = self.get_poly6_coeff();
908        let m_p: f32 = self.get_particle_mass_kgpm();
909        let cx: i32 = ((qx * inv_h).floor() as i32).clamp(0, gw - 1);
910        let cy: i32 = ((qy * inv_h).floor() as i32).clamp(0, gh - 1);
911        let x0: i32 = (cx - 1).max(0);
912        let x1: i32 = (cx + 1).min(gw - 1);
913        let y0: i32 = (cy - 1).max(0);
914        let y1: i32 = (cy + 1).min(gh - 1);
915        let Self {
916            pred_x,
917            pred_y,
918            vel_x,
919            vel_y,
920            cell_starts,
921            sorted_indices,
922            ..
923        } = self;
924        let mut rho: f32 = 0.0;
925        let mut w_sum: f32 = 0.0;
926        let mut u_sum: f32 = 0.0;
927        let mut v_sum: f32 = 0.0;
928        for ny in y0..=y1 {
929            let row_off: usize = (ny as usize) * (gw as usize);
930            for nx in x0..=x1 {
931                let cid: usize = row_off + (nx as usize);
932                let s: usize = cell_starts[cid] as usize;
933                let e: usize = cell_starts[cid + 1] as usize;
934                for &raw_j in &sorted_indices[s..e] {
935                    let j: usize = raw_j as usize;
936                    let dx: f32 = qx - pred_x[j];
937                    let dy: f32 = qy - pred_y[j];
938                    let r2: f32 = dx * dx + dy * dy;
939                    if r2 < h2 {
940                        let w_val: f32 = poly6_2d(r2, h2, poly6_c);
941                        rho += m_p * w_val;
942                        w_sum += w_val;
943                        u_sum += w_val * vel_x[j];
944                        v_sum += w_val * vel_y[j];
945                    }
946                }
947            }
948        }
949        let inv_w: f32 = if w_sum > 1.0e-5 { 1.0 / w_sum } else { 0.0 };
950        (rho / WATER_REST_DENSITY_KGM3, u_sum * inv_w, v_sum * inv_w)
951    }
952
953    /// Executes one full SI PBF substep: non-inertial prediction, Jacobi density constraints, surface tension, vorticity confinement, XSPH viscosity, and buoyant rigid-body coupling.
954    ///
955    /// # Arguments
956    ///
957    /// - `&Self` - Mutable liquid solver.
958    /// - `f32` - Substep delta time in seconds.
959    fn run_substep(&mut self, sub_dt: f32) {
960        let cfg: GyroLiquidConfig = self.get_config();
961        let n: usize = self.get_particle_count();
962        let w: f32 = cfg.get_vessel_width_m();
963        let h_vessel: f32 = cfg.get_vessel_height_m();
964        let cx_tank: f32 = w * 0.5;
965        let cy_tank: f32 = h_vessel * 0.5;
966        let d0: f32 = self.get_rest_spacing_m();
967        let pad: f32 = d0 * 0.52;
968        let corner_r: f32 = w.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
969        let gx: f32 = self.get_gravity_x();
970        let gy: f32 = self.get_gravity_y();
971        let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
972        let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
973        let omega: f32 = self.get_angular_vel_cw();
974        let omega2: f32 = omega * omega;
975        let alpha: f32 = self.get_angular_accel_cw();
976        {
977            let Self {
978                pos_x,
979                pos_y,
980                pred_x,
981                pred_y,
982                vel_x,
983                vel_y,
984                ..
985            } = self;
986            for i in 0..n {
987                let rx: f32 = pos_x[i] - cx_tank;
988                let ry: f32 = pos_y[i] - cy_tank;
989                let vx: f32 = vel_x[i];
990                let vy: f32 = vel_y[i];
991                let ax: f32 = gx - lin_x + omega2 * rx + alpha * ry + 2.0 * omega * vy;
992                let ay: f32 = gy - lin_y + omega2 * ry - alpha * rx - 2.0 * omega * vx;
993                let nvx: f32 = (vx + ax * sub_dt)
994                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
995                let nvy: f32 = (vy + ay * sub_dt)
996                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
997                vel_x[i] = nvx;
998                vel_y[i] = nvy;
999                let (px, py, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1000                    pos_x[i] + nvx * sub_dt,
1001                    pos_y[i] + nvy * sub_dt,
1002                    w,
1003                    h_vessel,
1004                    pad,
1005                    corner_r,
1006                );
1007                pred_x[i] = px;
1008                pred_y[i] = py;
1009            }
1010        }
1011        self.rebuild_spatial_grid();
1012        let h: f32 = self.get_kernel_radius_m();
1013        let h2: f32 = h * h;
1014        let inv_h: f32 = 1.0 / h.max(1.0e-5);
1015        let poly6_c: f32 = self.get_poly6_coeff();
1016        let spiky_c: f32 = self.get_spiky_grad_coeff();
1017        let inv_w_dq: f32 = 1.0 / self.get_w_dq().max(1.0e-6);
1018        let a_p: f32 = self.get_particle_area_m2();
1019        let m_p: f32 = self.get_particle_mass_kgpm();
1020        let cfm_eps: f32 = FLUID_CFM_RELAXATION_FACTOR / a_p.max(1.0e-9);
1021        let scorr_scale: f32 = -FLUID_SCORR_K * a_p;
1022        let cohesion_gain: f32 = FLUID_COHESION_STRENGTH * cfg.get_surface_tension_scale();
1023        let meniscus_gain: f32 = FLUID_WALL_MENISCUS_STRENGTH * cfg.get_surface_tension_scale();
1024        let gw: i32 = self.get_grid_w() as i32;
1025        let gh: i32 = self.get_grid_h() as i32;
1026        let gw_u: usize = gw as usize;
1027        let iters: u32 = cfg.get_solver_iterations().clamp(2, 6);
1028        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1029        let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
1030            (-gx / g_mag, -gy / g_mag)
1031        } else {
1032            (0.0, -1.0)
1033        };
1034        let wall_meniscus_band: f32 = d0 * 1.45;
1035        let self_poly6: f32 = m_p * poly6_2d(0.0, h2, poly6_c);
1036        {
1037            let Self {
1038                pred_x,
1039                pred_y,
1040                cell_starts,
1041                sorted_indices,
1042                neighbor_indices,
1043                neighbor_counts,
1044                ..
1045            } = self;
1046            let search_r2: f32 = h2 * 1.18;
1047            for i in 0..n {
1048                let xi: f32 = pred_x[i];
1049                let yi: f32 = pred_y[i];
1050                let cx: i32 = ((xi * inv_h).floor() as i32).clamp(0, gw - 1);
1051                let cy: i32 = ((yi * inv_h).floor() as i32).clamp(0, gh - 1);
1052                let x0: i32 = (cx - 1).max(0);
1053                let x1: i32 = (cx + 1).min(gw - 1);
1054                let y0: i32 = (cy - 1).max(0);
1055                let y1: i32 = (cy + 1).min(gh - 1);
1056                let base: usize = i * FLUID_MAX_NEIGHBORS;
1057                let mut count: usize = 0;
1058                for ny in y0..=y1 {
1059                    let row_off: usize = (ny as usize) * gw_u;
1060                    for nx in x0..=x1 {
1061                        let cid: usize = row_off + (nx as usize);
1062                        let s: usize = cell_starts[cid] as usize;
1063                        let e: usize = cell_starts[cid + 1] as usize;
1064                        for &raw_j in &sorted_indices[s..e] {
1065                            let j: usize = raw_j as usize;
1066                            if i == j {
1067                                continue;
1068                            }
1069                            let dx: f32 = xi - pred_x[j];
1070                            let dy: f32 = yi - pred_y[j];
1071                            if dx * dx + dy * dy < search_r2 {
1072                                neighbor_indices[base + count] = j as u16;
1073                                count += 1;
1074                                if count == FLUID_MAX_NEIGHBORS {
1075                                    break;
1076                                }
1077                            }
1078                        }
1079                        if count == FLUID_MAX_NEIGHBORS {
1080                            break;
1081                        }
1082                    }
1083                    if count == FLUID_MAX_NEIGHBORS {
1084                        break;
1085                    }
1086                }
1087                neighbor_counts[i] = count as u8;
1088            }
1089        }
1090        for _ in 0..iters {
1091            let Self {
1092                pred_x,
1093                pred_y,
1094                lambda,
1095                density,
1096                corr_x,
1097                corr_y,
1098                neighbor_indices,
1099                neighbor_counts,
1100                buoyant_bodies,
1101                buoyant_body_count,
1102                ..
1103            } = self;
1104            for i in 0..n {
1105                let xi: f32 = pred_x[i];
1106                let yi: f32 = pred_y[i];
1107                let base: usize = i * FLUID_MAX_NEIGHBORS;
1108                let cnt: usize = neighbor_counts[i] as usize;
1109                let mut rho: f32 = self_poly6;
1110                let mut grad_ix: f32 = 0.0;
1111                let mut grad_iy: f32 = 0.0;
1112                let mut sum_grad_sq: f32 = 0.0;
1113                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1114                    let j: usize = raw_j as usize;
1115                    let dx: f32 = xi - pred_x[j];
1116                    let dy: f32 = yi - pred_y[j];
1117                    let r2: f32 = dx * dx + dy * dy;
1118                    if r2 < h2 {
1119                        rho += m_p * poly6_2d(r2, h2, poly6_c);
1120                        if r2 > 1.0e-12 {
1121                            let r: f32 = r2.sqrt();
1122                            let gf: f32 = a_p * spiky_grad_factor_2d(r, h, spiky_c);
1123                            let gx_ij: f32 = gf * dx;
1124                            let gy_ij: f32 = gf * dy;
1125                            grad_ix += gx_ij;
1126                            grad_iy += gy_ij;
1127                            sum_grad_sq += gx_ij * gx_ij + gy_ij * gy_ij;
1128                        }
1129                    }
1130                }
1131                density[i] = rho;
1132                let c_val: f32 = (rho / WATER_REST_DENSITY_KGM3 - 1.0).max(0.0);
1133                sum_grad_sq += grad_ix * grad_ix + grad_iy * grad_iy;
1134                lambda[i] = if c_val > 0.0 {
1135                    -c_val / (sum_grad_sq + cfm_eps)
1136                } else {
1137                    0.0
1138                };
1139            }
1140            let max_disp: f32 = d0 * 0.48;
1141            for i in 0..n {
1142                let xi: f32 = pred_x[i];
1143                let yi: f32 = pred_y[i];
1144                let lam_i: f32 = lambda[i];
1145                let is_surface: bool = density[i] < WATER_REST_DENSITY_KGM3 * 0.88;
1146                let base: usize = i * FLUID_MAX_NEIGHBORS;
1147                let cnt: usize = neighbor_counts[i] as usize;
1148                let mut dpx: f32 = 0.0;
1149                let mut dpy: f32 = 0.0;
1150                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1151                    let j: usize = raw_j as usize;
1152                    let dx: f32 = xi - pred_x[j];
1153                    let dy: f32 = yi - pred_y[j];
1154                    let r2: f32 = dx * dx + dy * dy;
1155                    if r2 < h2 && r2 > 1.0e-12 {
1156                        let r: f32 = r2.sqrt();
1157                        let w_r: f32 = poly6_2d(r2, h2, poly6_c);
1158                        let ratio: f32 = w_r * inv_w_dq;
1159                        let ratio2: f32 = ratio * ratio;
1160                        let s_corr: f32 = scorr_scale * ratio2 * ratio2;
1161                        let gf: f32 = a_p * spiky_grad_factor_2d(r, h, spiky_c);
1162                        let pressure_mag: f32 = (lam_i + lambda[j] + s_corr) * gf;
1163                        dpx += pressure_mag * dx;
1164                        dpy += pressure_mag * dy;
1165                        if cohesion_gain > 0.0 {
1166                            let q: f32 = r * inv_h;
1167                            let coh: f32 = surface_cohesion_weight(q) * cohesion_gain / r;
1168                            dpx += coh * dx;
1169                            dpy += coh * dy;
1170                        }
1171                    }
1172                }
1173                if is_surface && meniscus_gain > 0.0 {
1174                    let near_left: bool = xi - pad < wall_meniscus_band;
1175                    let near_right: bool = (w - pad) - xi < wall_meniscus_band;
1176                    let near_top: bool = yi - pad < wall_meniscus_band;
1177                    let near_bottom: bool = (h_vessel - pad) - yi < wall_meniscus_band;
1178                    if near_left || near_right {
1179                        dpy += up_y * meniscus_gain;
1180                    }
1181                    if near_top || near_bottom {
1182                        dpx += up_x * meniscus_gain;
1183                    }
1184                }
1185                let disp2: f32 = dpx * dpx + dpy * dpy;
1186                if disp2 > max_disp * max_disp {
1187                    let scale: f32 = max_disp / disp2.sqrt();
1188                    dpx *= scale;
1189                    dpy *= scale;
1190                }
1191                corr_x[i] = dpx;
1192                corr_y[i] = dpy;
1193            }
1194            let b_cnt: usize = *buoyant_body_count;
1195            for i in 0..n {
1196                let mut nx: f32 = pred_x[i] + corr_x[i];
1197                let mut ny: f32 = pred_y[i] + corr_y[i];
1198                for body in buoyant_bodies.iter().take(b_cnt) {
1199                    let dx: f32 = nx - body.get_x();
1200                    let dy: f32 = ny - body.get_y();
1201                    let min_dist: f32 = body.get_radius() + d0 * 0.36;
1202                    let d2: f32 = dx * dx + dy * dy;
1203                    if d2 < min_dist * min_dist {
1204                        if d2 > 1.0e-12 {
1205                            let dist: f32 = d2.sqrt();
1206                            let push: f32 = (min_dist - dist) * 0.65 / dist;
1207                            nx += dx * push;
1208                            ny += dy * push;
1209                        } else {
1210                            nx += min_dist * 0.5;
1211                        }
1212                    }
1213                }
1214                let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
1215                    clamp_to_rounded_vessel(nx, ny, w, h_vessel, pad, corner_r);
1216                pred_x[i] = cx;
1217                pred_y[i] = cy;
1218            }
1219        }
1220        let inv_sub_dt: f32 = 1.0 / sub_dt.max(1.0e-5);
1221        let xsph_c: f32 = (FLUID_BASE_XSPH_COEFF * cfg.get_viscosity_scale()).clamp(0.004, 0.22);
1222        {
1223            let Self {
1224                pos_x,
1225                pos_y,
1226                pred_x,
1227                pred_y,
1228                vel_x,
1229                vel_y,
1230                density,
1231                vorticity,
1232                dvx_scratch,
1233                dvy_scratch,
1234                neighbor_indices,
1235                neighbor_counts,
1236                ..
1237            } = self;
1238            for i in 0..n {
1239                let mut vx: f32 = ((pred_x[i] - pos_x[i]) * inv_sub_dt)
1240                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1241                let mut vy: f32 = ((pred_y[i] - pos_y[i]) * inv_sub_dt)
1242                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1243                let (_, _, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1244                    pred_x[i],
1245                    pred_y[i],
1246                    w,
1247                    h_vessel,
1248                    pad + 1.0e-5,
1249                    corner_r,
1250                );
1251                if hit {
1252                    let vn: f32 = vx * wn_x + vy * wn_y;
1253                    if vn < 0.0 {
1254                        let tx: f32 = -wn_y;
1255                        let ty: f32 = wn_x;
1256                        let vt: f32 = (vx * tx + vy * ty) * FLUID_WALL_TANGENTIAL_KEEP;
1257                        let vn_out: f32 = -vn * FLUID_WALL_RESTITUTION;
1258                        vx = tx * vt + wn_x * vn_out;
1259                        vy = ty * vt + wn_y * vn_out;
1260                    }
1261                }
1262                vel_x[i] = vx;
1263                vel_y[i] = vy;
1264            }
1265            for i in 0..n {
1266                let xi: f32 = pred_x[i];
1267                let yi: f32 = pred_y[i];
1268                let vxi: f32 = vel_x[i];
1269                let vyi: f32 = vel_y[i];
1270                let base: usize = i * FLUID_MAX_NEIGHBORS;
1271                let cnt: usize = neighbor_counts[i] as usize;
1272                let mut curl: f32 = 0.0;
1273                let mut xsph_x: f32 = 0.0;
1274                let mut xsph_y: f32 = 0.0;
1275                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1276                    let j: usize = raw_j as usize;
1277                    let dx: f32 = xi - pred_x[j];
1278                    let dy: f32 = yi - pred_y[j];
1279                    let r2: f32 = dx * dx + dy * dy;
1280                    if r2 < h2 && r2 > 1.0e-12 {
1281                        let r: f32 = r2.sqrt();
1282                        let dvx: f32 = vel_x[j] - vxi;
1283                        let dvy: f32 = vel_y[j] - vyi;
1284                        let w_val: f32 = poly6_2d(r2, h2, poly6_c);
1285                        let rho_j: f32 = density[j].max(WATER_REST_DENSITY_KGM3 * 0.45);
1286                        let weight: f32 = (m_p / rho_j) * w_val;
1287                        xsph_x += dvx * weight;
1288                        xsph_y += dvy * weight;
1289                        let gf: f32 = a_p * spiky_grad_factor_2d(r, h, spiky_c);
1290                        curl += dvx * (gf * dy) - dvy * (gf * dx);
1291                    }
1292                }
1293                vorticity[i] = curl;
1294                dvx_scratch[i] = xsph_c * xsph_x;
1295                dvy_scratch[i] = xsph_c * xsph_y;
1296            }
1297            for i in 0..n {
1298                let xi: f32 = pred_x[i];
1299                let yi: f32 = pred_y[i];
1300                let wi: f32 = vorticity[i];
1301                let base: usize = i * FLUID_MAX_NEIGHBORS;
1302                let cnt: usize = neighbor_counts[i] as usize;
1303                let mut eta_x: f32 = 0.0;
1304                let mut eta_y: f32 = 0.0;
1305                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1306                    let j: usize = raw_j as usize;
1307                    let dx: f32 = xi - pred_x[j];
1308                    let dy: f32 = yi - pred_y[j];
1309                    let r2: f32 = dx * dx + dy * dy;
1310                    if r2 < h2 && r2 > 1.0e-12 {
1311                        let r: f32 = r2.sqrt();
1312                        let gf: f32 = a_p * spiky_grad_factor_2d(r, h, spiky_c);
1313                        let abs_wj: f32 = vorticity[j].abs();
1314                        eta_x += abs_wj * gf * dx;
1315                        eta_y += abs_wj * gf * dy;
1316                    }
1317                }
1318                let eta_mag: f32 = (eta_x * eta_x + eta_y * eta_y).sqrt();
1319                let (vort_fx, vort_fy): (f32, f32) = if eta_mag > 1.0e-4 {
1320                    let inv_eta: f32 = 1.0 / eta_mag;
1321                    let nx_v: f32 = eta_x * inv_eta;
1322                    let ny_v: f32 = eta_y * inv_eta;
1323                    (
1324                        ny_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1325                        -nx_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1326                    )
1327                } else {
1328                    (0.0, 0.0)
1329                };
1330                vel_x[i] = (vel_x[i] + dvx_scratch[i] + vort_fx)
1331                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1332                vel_y[i] = (vel_y[i] + dvy_scratch[i] + vort_fy)
1333                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1334                pos_x[i] = pred_x[i];
1335                pos_y[i] = pred_y[i];
1336            }
1337        }
1338        self.step_buoyant_bodies(sub_dt);
1339    }
1340
1341    /// Integrates buoyant rigid bodies using 8-point submerged-volume Archimedes buoyancy, hydrodynamic drag, wave torque, and vessel collisions.
1342    ///
1343    /// # Arguments
1344    ///
1345    /// - `&Self` - Mutable liquid solver.
1346    /// - `f32` - Substep delta time in seconds.
1347    fn step_buoyant_bodies(&mut self, sub_dt: f32) {
1348        let b_cnt: usize = self.get_buoyant_body_count();
1349        if b_cnt == 0 {
1350            return;
1351        }
1352        let cfg: GyroLiquidConfig = self.get_config();
1353        let w: f32 = cfg.get_vessel_width_m();
1354        let h_vessel: f32 = cfg.get_vessel_height_m();
1355        let cx_tank: f32 = w * 0.5;
1356        let cy_tank: f32 = h_vessel * 0.5;
1357        let corner_r: f32 = w.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
1358        let gx: f32 = self.get_gravity_x();
1359        let gy: f32 = self.get_gravity_y();
1360        let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
1361        let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
1362        let omega_frame: f32 = self.get_angular_vel_cw();
1363        let omega2: f32 = omega_frame * omega_frame;
1364        let alpha_frame: f32 = self.get_angular_accel_cw();
1365        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1366        let (gx_hat, gy_hat): (f32, f32) = if g_mag > 0.25 {
1367            (gx / g_mag, gy / g_mag)
1368        } else {
1369            (0.0, 1.0)
1370        };
1371        let mut updated: [BuoyantBody; FLUID_MAX_BUOYANT_BODIES] =
1372            [BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES];
1373        let mut fluid_probes: [(f32, f32, f32, f32); FLUID_MAX_BUOYANT_BODIES] =
1374            [(0.0, 0.0, 0.0, 0.0); FLUID_MAX_BUOYANT_BODIES];
1375        for idx in 0..b_cnt {
1376            let body: BuoyantBody = self.get_buoyant_bodies()[idx];
1377            updated[idx] = body;
1378            let bx: f32 = body.get_x();
1379            let by: f32 = body.get_y();
1380            let br: f32 = body.get_radius();
1381            let probe_r: f32 = br + self.get_kernel_radius_m() * 0.52;
1382            let mut sub_sum: f32 = 0.0;
1383            let mut u_sum: f32 = 0.0;
1384            let mut v_sum: f32 = 0.0;
1385            let mut torque_sum: f32 = 0.0;
1386            let mut sub_weight_sum: f32 = 0.0;
1387            let sample_offsets: [(f32, f32); 8] = [
1388                (probe_r, 0.0),
1389                (-probe_r, 0.0),
1390                (0.0, probe_r),
1391                (0.0, -probe_r),
1392                (probe_r * 0.707, probe_r * 0.707),
1393                (-probe_r * 0.707, probe_r * 0.707),
1394                (probe_r * 0.707, -probe_r * 0.707),
1395                (-probe_r * 0.707, -probe_r * 0.707),
1396            ];
1397            for (ox, oy) in sample_offsets {
1398                let qx: f32 = (bx + ox).clamp(0.001, w - 0.001);
1399                let qy: f32 = (by + oy).clamp(0.001, h_vessel - 0.001);
1400                let (rho_ratio, fu, fv): (f32, f32, f32) = self.sample_fluid_at(qx, qy);
1401                let occ: f32 = ((rho_ratio - 0.14) / 0.42).clamp(0.0, 1.0);
1402                sub_sum += occ;
1403                if occ > 0.01 {
1404                    u_sum += fu * occ;
1405                    v_sum += fv * occ;
1406                    sub_weight_sum += occ;
1407                    let f_buoy_x: f32 = -gx_hat * occ;
1408                    let f_buoy_y: f32 = -gy_hat * occ;
1409                    torque_sum += ox * f_buoy_y - oy * f_buoy_x;
1410                    let rel_u: f32 = fu - body.get_vx();
1411                    let rel_v: f32 = fv - body.get_vy();
1412                    torque_sum += (ox * rel_v - oy * rel_u) * occ * 0.35;
1413                }
1414            }
1415            let f_sub: f32 = (sub_sum / 8.0).clamp(0.0, 1.0);
1416            let (fu_avg, fv_avg): (f32, f32) = if sub_weight_sum > 1.0e-4 {
1417                (u_sum / sub_weight_sum, v_sum / sub_weight_sum)
1418            } else {
1419                (0.0, 0.0)
1420            };
1421            fluid_probes[idx] = (f_sub, fu_avg, fv_avg, torque_sum / (br + 1.0e-4));
1422        }
1423        for idx in 0..b_cnt {
1424            let body: &mut BuoyantBody = &mut updated[idx];
1425            let (f_sub, fu_avg, fv_avg, torque_acc): (f32, f32, f32, f32) = fluid_probes[idx];
1426            let rx: f32 = body.get_x() - cx_tank;
1427            let ry: f32 = body.get_y() - cy_tank;
1428            let vx: f32 = body.get_vx();
1429            let vy: f32 = body.get_vy();
1430            let eff_gx: f32 = gx - lin_x + omega2 * rx + alpha_frame * ry + 2.0 * omega_frame * vy;
1431            let eff_gy: f32 = gy - lin_y + omega2 * ry - alpha_frame * rx - 2.0 * omega_frame * vx;
1432            let rho_body: f32 = body.get_density_kgm3().max(100.0);
1433            let added_mass_rho: f32 = 0.5 * f_sub * WATER_REST_DENSITY_KGM3;
1434            let eff_inertia_rho: f32 = rho_body + added_mass_rho;
1435            let net_buoy_factor: f32 =
1436                (rho_body - f_sub * WATER_REST_DENSITY_KGM3) / eff_inertia_rho;
1437            let ax_net: f32 = eff_gx * net_buoy_factor;
1438            let ay_net: f32 = eff_gy * net_buoy_factor;
1439            let rel_x: f32 = fu_avg - vx;
1440            let rel_y: f32 = fv_avg - vy;
1441            let drag_coeff: f32 = 0.8 + f_sub * (6.8 * cfg.get_viscosity_scale().sqrt());
1442            let mut nvx: f32 = vx + (ax_net + rel_x * drag_coeff) * sub_dt;
1443            let mut nvy: f32 = vy + (ay_net + rel_y * drag_coeff) * sub_dt;
1444            nvx = nvx.clamp(-2.0, 2.0);
1445            nvy = nvy.clamp(-2.0, 2.0);
1446            let br: f32 = body.get_radius();
1447            let (cx, cy, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1448                body.get_x() + nvx * sub_dt,
1449                body.get_y() + nvy * sub_dt,
1450                w,
1451                h_vessel,
1452                br * 1.04,
1453                corner_r,
1454            );
1455            if hit {
1456                let vn: f32 = nvx * wn_x + nvy * wn_y;
1457                if vn < 0.0 {
1458                    nvx -= 1.35 * vn * wn_x;
1459                    nvy -= 1.35 * vn * wn_y;
1460                }
1461            }
1462            let ang_damp: f32 = (-sub_dt * (1.2 + f_sub * 4.2)).exp();
1463            let next_omega: f32 =
1464                ((body.get_omega() + torque_acc * sub_dt * 1.8) * ang_damp).clamp(-14.0, 14.0);
1465            body.set_x(cx);
1466            body.set_y(cy);
1467            body.set_vx(nvx);
1468            body.set_vy(nvy);
1469            body.set_omega(next_omega);
1470            body.set_angle(body.get_angle() + next_omega * sub_dt);
1471            body.set_submerged_fraction(f_sub);
1472        }
1473        for i in 0..b_cnt {
1474            for j in (i + 1)..b_cnt {
1475                let dx: f32 = updated[j].get_x() - updated[i].get_x();
1476                let dy: f32 = updated[j].get_y() - updated[i].get_y();
1477                let min_d: f32 = updated[i].get_radius() + updated[j].get_radius();
1478                let d2: f32 = dx * dx + dy * dy;
1479                if d2 < min_d * min_d && d2 > 1.0e-12 {
1480                    let dist: f32 = d2.sqrt();
1481                    let nx: f32 = dx / dist;
1482                    let ny: f32 = dy / dist;
1483                    let pen: f32 = (min_d - dist) * 0.5;
1484                    updated[i].set_x(updated[i].get_x() - nx * pen);
1485                    updated[i].set_y(updated[i].get_y() - ny * pen);
1486                    updated[j].set_x(updated[j].get_x() + nx * pen);
1487                    updated[j].set_y(updated[j].get_y() + ny * pen);
1488                    let rvx: f32 = updated[j].get_vx() - updated[i].get_vx();
1489                    let rvy: f32 = updated[j].get_vy() - updated[i].get_vy();
1490                    let rel_n: f32 = rvx * nx + rvy * ny;
1491                    if rel_n < 0.0 {
1492                        let imp: f32 = -0.68 * rel_n;
1493                        updated[i].set_vx(updated[i].get_vx() - nx * imp);
1494                        updated[i].set_vy(updated[i].get_vy() - ny * imp);
1495                        updated[j].set_vx(updated[j].get_vx() + nx * imp);
1496                        updated[j].set_vy(updated[j].get_vy() + ny * imp);
1497                    }
1498                }
1499            }
1500        }
1501        self.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&updated[..b_cnt]);
1502    }
1503
1504    /// Spawns aerated foam & buoyant micro-bubbles at energetic wave crests and advances rising bubbles against live gravity.
1505    ///
1506    /// # Arguments
1507    ///
1508    /// - `&Self` - Mutable liquid solver.
1509    /// - `f32` - Step delta time in seconds.
1510    fn step_bubbles_and_foam(&mut self, dt: f32) {
1511        let cfg: GyroLiquidConfig = self.get_config();
1512        let w: f32 = cfg.get_vessel_width_m();
1513        let h_vessel: f32 = cfg.get_vessel_height_m();
1514        let d0: f32 = self.get_rest_spacing_m();
1515        let gx: f32 = self.get_gravity_x();
1516        let gy: f32 = self.get_gravity_y();
1517        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1518        let (rise_x, rise_y): (f32, f32) = if g_mag > 0.25 {
1519            (-gx / g_mag, -gy / g_mag)
1520        } else {
1521            (0.0, -1.0)
1522        };
1523        let mut active: usize = self.get_bubble_count();
1524        let mut i: usize = 0;
1525        while i < active {
1526            let bub: FluidBubble = self.get_bubbles()[i];
1527            let next_age: f32 = bub.get_age() + dt;
1528            if next_age >= bub.get_lifetime() {
1529                active -= 1;
1530                let last: FluidBubble = self.get_bubbles()[active];
1531                self.get_mut_bubbles()[i] = last;
1532                continue;
1533            }
1534            let (rho_ratio, fu, fv): (f32, f32, f32) =
1535                self.sample_fluid_at(bub.get_x(), bub.get_y());
1536            let in_water: bool = rho_ratio > 0.34;
1537            let (nvx, nvy, next_foam): (f32, f32, f32) = if in_water {
1538                let target_vx: f32 = fu + rise_x * FLUID_BUBBLE_RISE_SPEED_MPS;
1539                let target_vy: f32 = fv + rise_y * FLUID_BUBBLE_RISE_SPEED_MPS;
1540                let blend: f32 = (dt * 7.0).min(1.0);
1541                (
1542                    bub.get_vx() + (target_vx - bub.get_vx()) * blend,
1543                    bub.get_vy() + (target_vy - bub.get_vy()) * blend,
1544                    (bub.get_foam_factor() * 0.94).max(0.0),
1545                )
1546            } else {
1547                let decay: f32 = (-dt * 4.5).exp();
1548                (
1549                    bub.get_vx() * decay + fu * 0.2,
1550                    bub.get_vy() * decay + fv * 0.2,
1551                    (bub.get_foam_factor() + dt * 2.4).min(1.0),
1552                )
1553            };
1554            let nx: f32 = (bub.get_x() + nvx * dt).clamp(d0 * 0.5, w - d0 * 0.5);
1555            let ny: f32 = (bub.get_y() + nvy * dt).clamp(d0 * 0.5, h_vessel - d0 * 0.5);
1556            let mut updated_bub: FluidBubble = bub;
1557            updated_bub.set_x(nx);
1558            updated_bub.set_y(ny);
1559            updated_bub.set_vx(nvx);
1560            updated_bub.set_vy(nvy);
1561            updated_bub.set_age(next_age);
1562            updated_bub.set_foam_factor(next_foam);
1563            self.get_mut_bubbles()[i] = updated_bub;
1564            i += 1;
1565        }
1566        let n: usize = self.get_particle_count();
1567        let mut rng: u64 = self.get_rng_state();
1568        let mut spawned: usize = 0;
1569        let max_spawn_per_step: usize = 8;
1570        let speed_thresh2: f32 = FLUID_FOAM_SPEED_THRESHOLD_MPS * FLUID_FOAM_SPEED_THRESHOLD_MPS;
1571        let Self {
1572            pos_x,
1573            pos_y,
1574            vel_x,
1575            vel_y,
1576            density,
1577            vorticity,
1578            bubbles,
1579            ..
1580        } = self;
1581        for idx in (0..n).step_by(3) {
1582            if active >= FLUID_MAX_BUBBLES || spawned >= max_spawn_per_step {
1583                break;
1584            }
1585            let spd2: f32 = vel_x[idx] * vel_x[idx] + vel_y[idx] * vel_y[idx];
1586            let near_surface: bool = density[idx] < WATER_REST_DENSITY_KGM3 * 0.84;
1587            let high_vort: bool = vorticity[idx].abs() > 14.0;
1588            if spd2 > speed_thresh2 && (near_surface || high_vort) {
1589                let r_roll: f32 = fluid_next_rand_f32(&mut rng);
1590                if r_roll < 0.26 {
1591                    let jitter_x: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.8;
1592                    let jitter_y: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.8;
1593                    let rad: f32 = d0 * (0.28 + fluid_next_rand_f32(&mut rng) * 0.42);
1594                    let life: f32 = 0.55 + fluid_next_rand_f32(&mut rng) * 1.1;
1595                    let foam_val: f32 = if near_surface { 0.85 } else { 0.12 };
1596                    bubbles[active] = FluidBubble::spawn(
1597                        [
1598                            (pos_x[idx] + jitter_x).clamp(d0 * 0.5, w - d0 * 0.5),
1599                            (pos_y[idx] + jitter_y).clamp(d0 * 0.5, h_vessel - d0 * 0.5),
1600                        ],
1601                        [vel_x[idx] * 0.6, vel_y[idx] * 0.6],
1602                        rad,
1603                        life,
1604                        foam_val,
1605                    );
1606                    active += 1;
1607                    spawned += 1;
1608                }
1609            }
1610        }
1611        self.set_rng_state(rng);
1612        self.set_bubble_count(active);
1613    }
1614
1615    /// Advances the entire physical liquid simulation by `dt` seconds with zero steady-state heap allocations.
1616    ///
1617    /// # Arguments
1618    ///
1619    /// - `&Self` - Mutable liquid solver.
1620    /// - `f32` - Fixed simulation timestep in seconds.
1621    pub fn step(&mut self, dt: f32) {
1622        if !dt.is_finite() || dt <= 0.0 {
1623            return;
1624        }
1625        let clamped_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
1626        let substeps: u32 = self.get_config().get_substeps().clamp(2, 4);
1627        let sub_dt: f32 = clamped_dt / (substeps as f32);
1628        let shake_decay: f32 = (-clamped_dt * FLUID_SHAKE_DECAY_PER_SEC).exp();
1629        for _ in 0..substeps {
1630            self.run_substep(sub_dt);
1631        }
1632        self.set_shake_accel_x(self.get_shake_accel_x() * shake_decay);
1633        self.set_shake_accel_y(self.get_shake_accel_y() * shake_decay);
1634        self.step_bubbles_and_foam(clamped_dt);
1635        self.set_sim_time_secs(self.get_sim_time_secs() + clamped_dt);
1636        self.update_diagnostics();
1637    }
1638
1639    /// Recomputes live fluid kinetic energy (`mJ/m`) and peak wave crest elevation relative to gravity-aligned mean level.
1640    ///
1641    /// # Arguments
1642    ///
1643    /// - `&Self` - Mutable liquid solver.
1644    fn update_diagnostics(&mut self) {
1645        let n: usize = self.get_particle_count();
1646        if n == 0 {
1647            self.set_kinetic_energy_mj(0.0);
1648            self.set_peak_wave_height_m(0.0);
1649            return;
1650        }
1651        let m_p: f32 = self.get_particle_mass_kgpm();
1652        let gx: f32 = self.get_gravity_x();
1653        let gy: f32 = self.get_gravity_y();
1654        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1655        let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
1656            (-gx / g_mag, -gy / g_mag)
1657        } else {
1658            (0.0, -1.0)
1659        };
1660        let mut ke_sum: f32 = 0.0;
1661        let mut min_proj: f32 = f32::INFINITY;
1662        let mut max_proj: f32 = f32::NEG_INFINITY;
1663        let mut avg_proj: f32 = 0.0;
1664        let Self {
1665            pos_x,
1666            pos_y,
1667            vel_x,
1668            vel_y,
1669            ..
1670        } = self;
1671        for i in 0..n {
1672            let v2: f32 = vel_x[i] * vel_x[i] + vel_y[i] * vel_y[i];
1673            ke_sum += 0.5 * m_p * v2;
1674            let proj: f32 = pos_x[i] * up_x + pos_y[i] * up_y;
1675            avg_proj += proj;
1676            if proj < min_proj {
1677                min_proj = proj;
1678            }
1679            if proj > max_proj {
1680                max_proj = proj;
1681            }
1682        }
1683        let mean_proj: f32 = avg_proj / (n as f32);
1684        let expected_half_span: f32 = (max_proj - min_proj) * 0.5;
1685        let wave_amp: f32 = ((max_proj - mean_proj) - expected_half_span).abs();
1686        self.set_kinetic_energy_mj(ke_sum * 1000.0);
1687        self.set_peak_wave_height_m(wave_amp);
1688    }
1689
1690    /// Captures current particle, buoyant body, and bubble states directly into pre-allocated `dst` with zero heap allocations.
1691    ///
1692    /// # Arguments
1693    ///
1694    /// - `&Self` - Liquid solver reference.
1695    /// - `&mut FluidSimSnapshot` - Pre-allocated destination snapshot.
1696    pub fn capture_snapshot_into(&self, dst: &mut FluidSimSnapshot) {
1697        let cfg: GyroLiquidConfig = self.get_config();
1698        let n: usize = self.get_particle_count().min(FLUID_MAX_PARTICLES);
1699        let b_cnt: usize = self.get_buoyant_body_count().min(FLUID_MAX_BUOYANT_BODIES);
1700        let bub_cnt: usize = self.get_bubble_count().min(FLUID_MAX_BUBBLES);
1701        dst.set_vessel_width_m(cfg.get_vessel_width_m());
1702        dst.set_vessel_height_m(cfg.get_vessel_height_m());
1703        dst.set_kernel_radius_m(self.get_kernel_radius_m());
1704        dst.set_particle_count(n);
1705        dst.set_buoyant_body_count(b_cnt);
1706        dst.set_bubble_count(bub_cnt);
1707        dst.set_gravity_x(self.get_gravity_x());
1708        dst.set_gravity_y(self.get_gravity_y());
1709        dst.set_gravity_z(self.get_gravity_z());
1710        dst.set_sim_time_secs(self.get_sim_time_secs());
1711        let inv_rho0: f32 = 1.0 / WATER_REST_DENSITY_KGM3;
1712        dst.get_mut_pos_x()[..n].copy_from_slice(&self.get_pos_x()[..n]);
1713        dst.get_mut_pos_y()[..n].copy_from_slice(&self.get_pos_y()[..n]);
1714        dst.get_mut_vel_x()[..n].copy_from_slice(&self.get_vel_x()[..n]);
1715        dst.get_mut_vel_y()[..n].copy_from_slice(&self.get_vel_y()[..n]);
1716        let src_dens: &[f32] = self.get_density();
1717        let dst_ratio: &mut [f32] = dst.get_mut_density_ratio();
1718        for i in 0..n {
1719            dst_ratio[i] = src_dens[i] * inv_rho0;
1720        }
1721        dst.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&self.get_buoyant_bodies()[..b_cnt]);
1722        dst.get_mut_bubbles()[..bub_cnt].copy_from_slice(&self.get_bubbles()[..bub_cnt]);
1723    }
1724
1725    /// Computes the liquid center of mass `(cx, cy)` in SI meters inside the vessel.
1726    ///
1727    /// # Arguments
1728    ///
1729    /// - `&Self` - Liquid solver reference.
1730    ///
1731    /// # Returns
1732    ///
1733    /// - `(f32, f32)` - Center of mass coordinates `(x_m, y_m)`.
1734    #[must_use]
1735    pub fn center_of_mass(&self) -> (f32, f32) {
1736        let n: usize = self.get_particle_count();
1737        if n == 0 {
1738            let cfg: GyroLiquidConfig = self.get_config();
1739            return (
1740                cfg.get_vessel_width_m() * 0.5,
1741                cfg.get_vessel_height_m() * 0.5,
1742            );
1743        }
1744        let px: &[f32] = self.get_pos_x();
1745        let py: &[f32] = self.get_pos_y();
1746        let mut sx: f32 = 0.0;
1747        let mut sy: f32 = 0.0;
1748        for i in 0..n {
1749            sx += px[i];
1750            sy += py[i];
1751        }
1752        let inv_n: f32 = 1.0 / (n as f32);
1753        (sx * inv_n, sy * inv_n)
1754    }
1755
1756    /// Returns `true` if any active particle, buoyant body, or bubble has non-finite coordinates or escaped vessel bounds.
1757    ///
1758    /// # Arguments
1759    ///
1760    /// - `&Self` - Liquid solver reference.
1761    ///
1762    /// # Returns
1763    ///
1764    /// - `bool` - `true` when NaN/Inf or out-of-bounds escape is detected.
1765    #[must_use]
1766    pub fn has_invalid_or_escaped_state(&self) -> bool {
1767        let cfg: GyroLiquidConfig = self.get_config();
1768        let w: f32 = cfg.get_vessel_width_m();
1769        let h: f32 = cfg.get_vessel_height_m();
1770        let n: usize = self.get_particle_count();
1771        let px: &[f32] = self.get_pos_x();
1772        let py: &[f32] = self.get_pos_y();
1773        let vx: &[f32] = self.get_vel_x();
1774        let vy: &[f32] = self.get_vel_y();
1775        for i in 0..n {
1776            if !px[i].is_finite()
1777                || !py[i].is_finite()
1778                || !vx[i].is_finite()
1779                || !vy[i].is_finite()
1780                || px[i] < -1.0e-3
1781                || px[i] > w + 1.0e-3
1782                || py[i] < -1.0e-3
1783                || py[i] > h + 1.0e-3
1784            {
1785                return true;
1786            }
1787        }
1788        let b_cnt: usize = self.get_buoyant_body_count();
1789        for body in self.get_buoyant_bodies().iter().take(b_cnt) {
1790            if !body.get_x().is_finite()
1791                || !body.get_y().is_finite()
1792                || !body.get_vx().is_finite()
1793                || !body.get_vy().is_finite()
1794                || !body.get_angle().is_finite()
1795                || body.get_x() < -1.0e-3
1796                || body.get_x() > w + 1.0e-3
1797                || body.get_y() < -1.0e-3
1798                || body.get_y() > h + 1.0e-3
1799            {
1800                return true;
1801            }
1802        }
1803        false
1804    }
1805}