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 item_count: 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(item_count);
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()[..item_count].copy_from_slice(&src.get_pos_x()[..item_count]);
187        self.get_mut_pos_y()[..item_count].copy_from_slice(&src.get_pos_y()[..item_count]);
188        self.get_mut_vel_x()[..item_count].copy_from_slice(&src.get_vel_x()[..item_count]);
189        self.get_mut_vel_y()[..item_count].copy_from_slice(&src.get_vel_y()[..item_count]);
190        self.get_mut_density_ratio()[..item_count]
191            .copy_from_slice(&src.get_density_ratio()[..item_count]);
192        self.get_mut_buoyant_bodies()[..b_count]
193            .copy_from_slice(&src.get_buoyant_bodies()[..b_count]);
194        self.get_mut_bubbles()[..bub_count].copy_from_slice(&src.get_bubbles()[..bub_count]);
195    }
196
197    /// Interpolates between `self` and `next` at `alpha` directly into `out` with zero heap allocations.
198    ///
199    /// # Arguments
200    ///
201    /// - `&Self` - Previous fixed-step snapshot.
202    /// - `&Self` - Current fixed-step snapshot.
203    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
204    /// - `&mut Self` - Pre-allocated destination snapshot.
205    fn interpolate_into(&self, next: &Self, alpha: f32, out: &mut Self) {
206        let blend_factor: f32 = alpha.clamp(0.0, 1.0);
207        let omt: f32 = 1.0 - blend_factor;
208        let n_prev: usize = self.get_particle_count();
209        let n_next: usize = next.get_particle_count().min(FLUID_MAX_PARTICLES);
210        let dw: f32 = (self.get_vessel_width_m() - next.get_vessel_width_m()).abs();
211        let dh: f32 = (self.get_vessel_height_m() - next.get_vessel_height_m()).abs();
212        if n_prev != n_next || dw > 1.0e-4 || dh > 1.0e-4 {
213            out.copy_from_snapshot(next);
214            return;
215        }
216        out.copy_from_snapshot(next);
217        out.set_vessel_width_m(
218            self.get_vessel_width_m() * omt + next.get_vessel_width_m() * blend_factor,
219        );
220        out.set_vessel_height_m(
221            self.get_vessel_height_m() * omt + next.get_vessel_height_m() * blend_factor,
222        );
223        out.set_gravity_x(self.get_gravity_x() * omt + next.get_gravity_x() * blend_factor);
224        out.set_gravity_y(self.get_gravity_y() * omt + next.get_gravity_y() * blend_factor);
225        out.set_gravity_z(self.get_gravity_z() * omt + next.get_gravity_z() * blend_factor);
226        out.set_sim_time_secs(
227            self.get_sim_time_secs() * omt + next.get_sim_time_secs() * blend_factor,
228        );
229        let px0: &[f32] = self.get_pos_x();
230        let py0: &[f32] = self.get_pos_y();
231        let vx0: &[f32] = self.get_vel_x();
232        let vy0: &[f32] = self.get_vel_y();
233        let dr0: &[f32] = self.get_density_ratio();
234        let px1: &[f32] = next.get_pos_x();
235        let py1: &[f32] = next.get_pos_y();
236        let vx1: &[f32] = next.get_vel_x();
237        let vy1: &[f32] = next.get_vel_y();
238        let dr1: &[f32] = next.get_density_ratio();
239        let Self {
240            pos_x: opx,
241            pos_y: opy,
242            vel_x: ovx,
243            vel_y: ovy,
244            density_ratio: odr,
245            buoyant_bodies: obodies,
246            ..
247        } = out;
248        for item_index in 0..n_next {
249            opx[item_index] = px0[item_index] * omt + px1[item_index] * blend_factor;
250            opy[item_index] = py0[item_index] * omt + py1[item_index] * blend_factor;
251            ovx[item_index] = vx0[item_index] * omt + vx1[item_index] * blend_factor;
252            ovy[item_index] = vy0[item_index] * omt + vy1[item_index] * blend_factor;
253            odr[item_index] = dr0[item_index] * omt + dr1[item_index] * blend_factor;
254        }
255        let b_count: usize = next
256            .get_buoyant_body_count()
257            .min(self.get_buoyant_body_count())
258            .min(FLUID_MAX_BUOYANT_BODIES);
259        let b0: &[BuoyantBody] = self.get_buoyant_bodies();
260        let b1: &[BuoyantBody] = next.get_buoyant_bodies();
261        for idx in 0..b_count {
262            let mut body: BuoyantBody = b1[idx];
263            body.set_x(b0[idx].get_x() * omt + b1[idx].get_x() * blend_factor);
264            body.set_y(b0[idx].get_y() * omt + b1[idx].get_y() * blend_factor);
265            body.set_vx(b0[idx].get_vx() * omt + b1[idx].get_vx() * blend_factor);
266            body.set_vy(b0[idx].get_vy() * omt + b1[idx].get_vy() * blend_factor);
267            let mut da: f32 = b1[idx].get_angle() - b0[idx].get_angle();
268            while da > PI {
269                da -= TAU;
270            }
271            while da < -PI {
272                da += TAU;
273            }
274            body.set_angle(b0[idx].get_angle() + da * blend_factor);
275            obodies[idx] = body;
276        }
277    }
278}
279
280/// Default handheld SI Position-Based Fluids solver.
281impl Default for LiquidFluidSolver {
282    /// Creates a `LiquidFluidSolver` initialized with `GyroLiquidConfig::default()`.
283    ///
284    /// # Returns
285    ///
286    /// - `Self` - Pre-allocated SI liquid solver ready for zero-alloc stepping.
287    fn default() -> Self {
288        Self::with_config(GyroLiquidConfig::default())
289    }
290}
291
292/// SI Position-Based Fluids simulation, non-inertial frame kinematics, Archimedes buoyancy, and snapshot capture for `LiquidFluidSolver`.
293impl LiquidFluidSolver {
294    /// Creates a pre-allocated `LiquidFluidSolver` with `config` and initializes calm resting water.
295    ///
296    /// # Arguments
297    ///
298    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
299    ///
300    /// # Returns
301    ///
302    /// - `Self` - Initialized liquid solver.
303    #[must_use]
304    pub fn with_config(config: GyroLiquidConfig) -> Self {
305        let mut solver: Self = Self {
306            config,
307            particle_count: 0,
308            rest_spacing_m: 0.003,
309            particle_area_m2: 9.0e-6,
310            particle_mass_kgpm: 0.009,
311            kernel_radius_m: 0.0075,
312            poly6_coeff: 1.0,
313            spiky_grad_coeff: -1.0,
314            w_dq: 1.0,
315            gravity_x: 0.0,
316            gravity_y: STANDARD_GRAVITY_MPS2,
317            gravity_z: 0.0,
318            linear_accel_x: 0.0,
319            linear_accel_y: 0.0,
320            shake_accel_x: 0.0,
321            shake_accel_y: 0.0,
322            angular_vel_cw: 0.0,
323            prev_angular_vel_cw: 0.0,
324            angular_accel_cw: 0.0,
325            virtual_roll_rad: 0.0,
326            virtual_pitch_rad: 0.0,
327            prev_virtual_roll_rad: 0.0,
328            active_roll_rad: 0.0,
329            sim_time_secs: 0.0,
330            rng_state: FLUID_RNG_SEED,
331            kinetic_energy_mj: 0.0,
332            peak_wave_height_m: 0.0,
333            grid_w: 16,
334            grid_h: 12,
335            pos_x: vec![0.0; FLUID_MAX_PARTICLES],
336            pos_y: vec![0.0; FLUID_MAX_PARTICLES],
337            pred_x: vec![0.0; FLUID_MAX_PARTICLES],
338            pred_y: vec![0.0; FLUID_MAX_PARTICLES],
339            vel_x: vec![0.0; FLUID_MAX_PARTICLES],
340            vel_y: vec![0.0; FLUID_MAX_PARTICLES],
341            lambda: vec![0.0; FLUID_MAX_PARTICLES],
342            density: vec![WATER_REST_DENSITY_KGM3; FLUID_MAX_PARTICLES],
343            vorticity: vec![0.0; FLUID_MAX_PARTICLES],
344            corr_x: vec![0.0; FLUID_MAX_PARTICLES],
345            corr_y: vec![0.0; FLUID_MAX_PARTICLES],
346            dvx_scratch: vec![0.0; FLUID_MAX_PARTICLES],
347            dvy_scratch: vec![0.0; FLUID_MAX_PARTICLES],
348            cell_counts: vec![0; FLUID_MAX_GRID_CELLS],
349            cell_starts: vec![0; FLUID_MAX_GRID_CELLS + 1],
350            cell_cursors: vec![0; FLUID_MAX_GRID_CELLS],
351            particle_cells: vec![0; FLUID_MAX_PARTICLES],
352            sorted_indices: vec![0; FLUID_MAX_PARTICLES],
353            neighbor_indices: vec![0; FLUID_MAX_PARTICLES * FLUID_MAX_NEIGHBORS],
354            neighbor_counts: vec![0; FLUID_MAX_PARTICLES],
355            buoyant_bodies: vec![BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES],
356            buoyant_body_count: 0,
357            bubbles: vec![FluidBubble::default(); FLUID_MAX_BUBBLES],
358            bubble_count: 0,
359        };
360        solver.reset_water();
361        solver
362    }
363
364    /// Recomputes SI particle mass, kernel radius, and normalization coefficients from current vessel area and `particle_count`.
365    ///
366    /// # Arguments
367    ///
368    /// - `&Self` - Mutable liquid solver.
369    fn recompute_kernel_constants(&mut self) {
370        let config_spec: GyroLiquidConfig = self.get_config();
371        let width_val: f32 = config_spec.get_vessel_width_m().clamp(0.06, 0.24);
372        let h_vessel: f32 = config_spec.get_vessel_height_m().clamp(0.06, 0.24);
373        let fill: f32 = config_spec
374            .get_fill_ratio()
375            .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
376        let item_count: usize = self.get_particle_count().clamp(64, FLUID_MAX_PARTICLES);
377        let water_area: f32 = fill * width_val * h_vessel;
378        let particle_area: f32 = water_area / (item_count as f32);
379        let d0: f32 = particle_area.sqrt();
380        let height_val: f32 = (d0 * FLUID_KERNEL_RADIUS_MULT).max(0.0025);
381        let h2: f32 = height_val * height_val;
382        let h4: f32 = h2 * h2;
383        let h5: f32 = h4 * height_val;
384        let h8: f32 = h4 * h4;
385        let poly6_coeff: f32 = 4.0 / (PI * h8);
386        let spiky_grad_coeff: f32 = -30.0 / (PI * h5);
387        let dq: f32 = FLUID_SCORR_DQ_RATIO * height_val;
388        let w_dq: f32 = poly6_2d(dq * dq, h2, poly6_coeff).max(1.0e-6);
389        let gw: usize = ((width_val / height_val).ceil() as usize).clamp(4, 64);
390        let gh: usize = ((h_vessel / height_val).ceil() as usize).clamp(4, 64);
391        let (final_gw, final_gh): (usize, usize) = if gw * gh > FLUID_MAX_GRID_CELLS {
392            (64, FLUID_MAX_GRID_CELLS / 64)
393        } else {
394            (gw, gh)
395        };
396        self.set_rest_spacing_m(d0);
397        self.set_particle_area_m2(particle_area);
398        self.set_particle_mass_kgpm(WATER_REST_DENSITY_KGM3 * particle_area);
399        self.set_kernel_radius_m(height_val);
400        self.set_poly6_coeff(poly6_coeff);
401        self.set_spiky_grad_coeff(spiky_grad_coeff);
402        self.set_w_dq(w_dq);
403        self.set_grid_w(final_gw);
404        self.set_grid_h(final_gh);
405    }
406
407    /// Resets the liquid particles, buoyant objects, and bubbles to a calm hydrostatic pool matching the active fill ratio.
408    ///
409    /// # Arguments
410    ///
411    /// - `&Self` - Mutable liquid solver.
412    pub fn reset_water(&mut self) {
413        let mut config_spec: GyroLiquidConfig = self.get_config();
414        let fill: f32 = config_spec
415            .get_fill_ratio()
416            .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
417        config_spec.set_fill_ratio(fill);
418        let width_val: f32 = config_spec.get_vessel_width_m().clamp(0.06, 0.24);
419        let h_vessel: f32 = config_spec.get_vessel_height_m().clamp(0.06, 0.24);
420        config_spec.set_vessel_width_m(width_val);
421        config_spec.set_vessel_height_m(h_vessel);
422        self.set_config(config_spec);
423        let target_n: usize = (((config_spec.get_base_particle_count() as f32) * (fill / 0.50))
424            .round() as usize)
425            .clamp(120, FLUID_MAX_PARTICLES);
426        self.set_particle_count(target_n);
427        self.recompute_kernel_constants();
428        let d0: f32 = self.get_rest_spacing_m();
429        let pad: f32 = d0 * 0.54;
430        let usable_w: f32 = (width_val - 2.0 * pad).max(d0 * 2.0);
431        let usable_h: f32 = (h_vessel - 2.0 * pad).max(d0 * 2.0);
432        let cols: usize = ((usable_w / d0).round() as usize).max(4);
433        let col_step: f32 = usable_w / (cols as f32);
434        let rows: usize = target_n.div_ceil(cols);
435        let pool_h: f32 = (usable_h * fill).clamp(d0 * 1.5, usable_h);
436        let row_step: f32 = pool_h / (rows.max(1) as f32);
437        let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
438        {
439            let Self {
440                pos_x,
441                pos_y,
442                pred_x,
443                pred_y,
444                vel_x,
445                vel_y,
446                density,
447                vorticity,
448                lambda,
449                ..
450            } = self;
451            for item_index in 0..target_n {
452                let row: usize = item_index / cols;
453                let col: usize = item_index % cols;
454                let rem_in_row: usize = if row + 1 == rows {
455                    target_n - row * cols
456                } else {
457                    cols
458                };
459                let row_span_w: f32 = (rem_in_row as f32) * col_step;
460                let row_x0: f32 = (width_val - row_span_w) * 0.5;
461                let stagger: f32 = if rem_in_row == cols {
462                    if (row & 1) == 1 {
463                        0.22 * col_step
464                    } else {
465                        -0.22 * col_step
466                    }
467                } else {
468                    0.0
469                };
470                let rx: f32 = row_x0 + (col as f32 + 0.5) * col_step + stagger;
471                let ry: f32 = h_vessel - pad - (row as f32 + 0.5) * row_step;
472                let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
473                    clamp_to_rounded_vessel(rx, ry, width_val, h_vessel, pad, corner_r);
474                pos_x[item_index] = cx;
475                pos_y[item_index] = cy;
476                pred_x[item_index] = cx;
477                pred_y[item_index] = cy;
478                vel_x[item_index] = 0.0;
479                vel_y[item_index] = 0.0;
480                density[item_index] = WATER_REST_DENSITY_KGM3;
481                vorticity[item_index] = 0.0;
482                lambda[item_index] = 0.0;
483            }
484        }
485        self.set_rng_state(FLUID_RNG_SEED);
486        self.set_bubble_count(0);
487        self.set_shake_accel_x(0.0);
488        self.set_shake_accel_y(0.0);
489        self.set_linear_accel_x(0.0);
490        self.set_linear_accel_y(0.0);
491        self.set_angular_vel_cw(0.0);
492        self.set_prev_angular_vel_cw(0.0);
493        self.set_angular_accel_cw(0.0);
494        self.reset_buoyant_bodies();
495        self.relax_positions_silent(FLUID_HYDROSTATIC_RELAX_ITERS);
496        let n_zero: usize = self.get_particle_count();
497        self.get_mut_vel_x()[..n_zero].fill(0.0);
498        self.get_mut_vel_y()[..n_zero].fill(0.0);
499        self.get_mut_vorticity()[..n_zero].fill(0.0);
500        self.set_kinetic_energy_mj(0.0);
501        self.set_peak_wave_height_m(0.0);
502    }
503
504    /// Runs `passes` silent position-only PBF constraint iterations without modifying velocities so initial or resized pools start in hydrostatic equilibrium.
505    ///
506    /// # Arguments
507    ///
508    /// - `&Self` - Mutable liquid solver.
509    /// - `u32` - Number of silent PBF position relaxation passes.
510    fn relax_positions_silent(&mut self, passes: u32) {
511        let item_count: usize = self.get_particle_count();
512        if item_count == 0 || passes == 0 {
513            return;
514        }
515        let config_spec: GyroLiquidConfig = self.get_config();
516        let width_val: f32 = config_spec.get_vessel_width_m();
517        let h_vessel: f32 = config_spec.get_vessel_height_m();
518        let d0: f32 = self.get_rest_spacing_m();
519        let pad: f32 = d0 * 0.52;
520        let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
521        let height_val: f32 = self.get_kernel_radius_m();
522        let h2: f32 = height_val * height_val;
523        let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
524        let poly6_c: f32 = self.get_poly6_coeff();
525        let spiky_c: f32 = self.get_spiky_grad_coeff();
526        let inv_w_dq: f32 = 1.0 / self.get_w_dq().max(1.0e-6);
527        let a_p: f32 = self.get_particle_area_m2();
528        let m_p: f32 = self.get_particle_mass_kgpm();
529        let cfm_eps: f32 = FLUID_CFM_RELAXATION_FACTOR / a_p.max(1.0e-9);
530        let scorr_scale: f32 = -FLUID_SCORR_K * a_p;
531        let self_poly6: f32 = m_p * poly6_2d(0.0, h2, poly6_c);
532        let gw: i32 = self.get_grid_w() as i32;
533        let gh: i32 = self.get_grid_h() as i32;
534        let gw_u: usize = gw as usize;
535        for _ in 0..passes {
536            self.rebuild_spatial_grid();
537            {
538                let Self {
539                    pred_x,
540                    pred_y,
541                    cell_starts,
542                    sorted_indices,
543                    neighbor_indices,
544                    neighbor_counts,
545                    ..
546                } = self;
547                let search_r2: f32 = h2 * 1.15;
548                for item_index in 0..item_count {
549                    let xi: f32 = pred_x[item_index];
550                    let yi: f32 = pred_y[item_index];
551                    let cx: i32 = ((xi * inv_h).floor() as i32).clamp(0, gw - 1);
552                    let cy: i32 = ((yi * inv_h).floor() as i32).clamp(0, gh - 1);
553                    let x0: i32 = (cx - 1).max(0);
554                    let x1: i32 = (cx + 1).min(gw - 1);
555                    let y0: i32 = (cy - 1).max(0);
556                    let y1: i32 = (cy + 1).min(gh - 1);
557                    let base: usize = item_index * FLUID_MAX_NEIGHBORS;
558                    let mut count: usize = 0;
559                    for ny in y0..=y1 {
560                        let row_off: usize = (ny as usize) * gw_u;
561                        for nx in x0..=x1 {
562                            let cid: usize = row_off + (nx as usize);
563                            let source_val: usize = cell_starts[cid] as usize;
564                            let event_ref: usize = cell_starts[cid + 1] as usize;
565                            for &raw_j in &sorted_indices[source_val..event_ref] {
566                                let inner_index: usize = raw_j as usize;
567                                if item_index == inner_index {
568                                    continue;
569                                }
570                                let dx: f32 = xi - pred_x[inner_index];
571                                let dy: f32 = yi - pred_y[inner_index];
572                                if dx * dx + dy * dy < search_r2 {
573                                    neighbor_indices[base + count] = inner_index as u16;
574                                    count += 1;
575                                    if count == FLUID_MAX_NEIGHBORS {
576                                        break;
577                                    }
578                                }
579                            }
580                            if count == FLUID_MAX_NEIGHBORS {
581                                break;
582                            }
583                        }
584                        if count == FLUID_MAX_NEIGHBORS {
585                            break;
586                        }
587                    }
588                    neighbor_counts[item_index] = count as u8;
589                }
590            }
591            let Self {
592                pos_x,
593                pos_y,
594                pred_x,
595                pred_y,
596                lambda,
597                density,
598                corr_x,
599                corr_y,
600                neighbor_indices,
601                neighbor_counts,
602                buoyant_bodies,
603                buoyant_body_count,
604                ..
605            } = self;
606            for outer_index in 0..item_count {
607                let xi: f32 = pred_x[outer_index];
608                let yi: f32 = pred_y[outer_index];
609                let base: usize = outer_index * FLUID_MAX_NEIGHBORS;
610                let cnt: usize = neighbor_counts[outer_index] as usize;
611                let mut rho: f32 = self_poly6;
612                let mut grad_ix: f32 = 0.0;
613                let mut grad_iy: f32 = 0.0;
614                let mut sum_grad_sq: f32 = 0.0;
615                for &raw_j in &neighbor_indices[base..(base + cnt)] {
616                    let col_index: usize = raw_j as usize;
617                    let dx: f32 = xi - pred_x[col_index];
618                    let dy: f32 = yi - pred_y[col_index];
619                    let r2: f32 = dx * dx + dy * dy;
620                    if r2 < h2 {
621                        rho += m_p * poly6_2d(r2, h2, poly6_c);
622                        if r2 > 1.0e-12 {
623                            let red_val: f32 = r2.sqrt();
624                            let gf: f32 = a_p * spiky_grad_factor_2d(red_val, height_val, spiky_c);
625                            let gx_ij: f32 = gf * dx;
626                            let gy_ij: f32 = gf * dy;
627                            grad_ix += gx_ij;
628                            grad_iy += gy_ij;
629                            sum_grad_sq += gx_ij * gx_ij + gy_ij * gy_ij;
630                        }
631                    }
632                }
633                density[outer_index] = rho;
634                let c_val: f32 = (rho / WATER_REST_DENSITY_KGM3 - 1.0).max(0.0);
635                sum_grad_sq += grad_ix * grad_ix + grad_iy * grad_iy;
636                lambda[outer_index] = if c_val > 0.0 {
637                    -c_val / (sum_grad_sq + cfm_eps)
638                } else {
639                    0.0
640                };
641            }
642            let max_disp: f32 = d0 * 0.35;
643            for step_index in 0..item_count {
644                let xi: f32 = pred_x[step_index];
645                let yi: f32 = pred_y[step_index];
646                let lam_i: f32 = lambda[step_index];
647                let base: usize = step_index * FLUID_MAX_NEIGHBORS;
648                let cnt: usize = neighbor_counts[step_index] as usize;
649                let mut dpx: f32 = 0.0;
650                let mut dpy: f32 = 0.0;
651                for &raw_j in &neighbor_indices[base..(base + cnt)] {
652                    let sub_index: usize = raw_j as usize;
653                    let dx: f32 = xi - pred_x[sub_index];
654                    let dy: f32 = yi - pred_y[sub_index];
655                    let r2: f32 = dx * dx + dy * dy;
656                    if r2 < h2 && r2 > 1.0e-12 {
657                        let radius_val: f32 = r2.sqrt();
658                        let w_r: f32 = poly6_2d(r2, h2, poly6_c);
659                        let ratio: f32 = w_r * inv_w_dq;
660                        let ratio2: f32 = ratio * ratio;
661                        let s_corr: f32 = scorr_scale * ratio2 * ratio2;
662                        let gf: f32 = a_p * spiky_grad_factor_2d(radius_val, height_val, spiky_c);
663                        let pressure_mag: f32 = (lam_i + lambda[sub_index] + s_corr) * gf;
664                        dpx += pressure_mag * dx;
665                        dpy += pressure_mag * dy;
666                    }
667                }
668                let disp2: f32 = dpx * dpx + dpy * dpy;
669                if disp2 > max_disp * max_disp {
670                    let scale: f32 = max_disp / disp2.sqrt();
671                    dpx *= scale;
672                    dpy *= scale;
673                }
674                corr_x[step_index] = dpx;
675                corr_y[step_index] = dpy;
676            }
677            let b_cnt: usize = *buoyant_body_count;
678            for cursor_index in 0..item_count {
679                let mut nx: f32 = pred_x[cursor_index] + corr_x[cursor_index];
680                let mut ny: f32 = pred_y[cursor_index] + corr_y[cursor_index];
681                for body in buoyant_bodies.iter().take(b_cnt) {
682                    let dx: f32 = nx - body.get_x();
683                    let dy: f32 = ny - body.get_y();
684                    let min_dist: f32 = body.get_radius() + d0 * 0.36;
685                    let d2: f32 = dx * dx + dy * dy;
686                    if d2 < min_dist * min_dist && d2 > 1.0e-12 {
687                        let dist: f32 = d2.sqrt();
688                        let push: f32 = (min_dist - dist) * 0.65 / dist;
689                        nx += dx * push;
690                        ny += dy * push;
691                    }
692                }
693                let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
694                    clamp_to_rounded_vessel(nx, ny, width_val, h_vessel, pad, corner_r);
695                pred_x[cursor_index] = cx;
696                pred_y[cursor_index] = cy;
697                pos_x[cursor_index] = cx;
698                pos_y[cursor_index] = cy;
699            }
700        }
701    }
702
703    /// Initializes the default floating orb (`450 kg/m³`) and ice cube (`917 kg/m³`) near the free surface.
704    ///
705    /// # Arguments
706    ///
707    /// - `&Self` - Mutable liquid solver.
708    pub fn reset_buoyant_bodies(&mut self) {
709        let config_spec: GyroLiquidConfig = self.get_config();
710        if !config_spec.get_buoyant_bodies_enabled() {
711            self.set_buoyant_body_count(0);
712            return;
713        }
714        let width_val: f32 = config_spec.get_vessel_width_m();
715        let height_val: f32 = config_spec.get_vessel_height_m();
716        let fill: f32 = config_spec.get_fill_ratio();
717        let surface_y: f32 =
718            (height_val * (1.0 - fill)).clamp(height_val * 0.14, height_val * 0.82);
719        let min_dim: f32 = width_val.min(height_val);
720        let orb_r: f32 = (min_dim * 0.076).clamp(0.0052, 0.0102);
721        let ice_r: f32 = (min_dim * 0.084).clamp(0.0058, 0.0115);
722        let orb: BuoyantBody = BuoyantBody::with_pose(
723            BuoyantBodyKind::FloatingOrb,
724            [
725                width_val * 0.33,
726                (surface_y - orb_r * 0.10).clamp(orb_r * 1.4, height_val - orb_r * 1.4),
727            ],
728            0.0,
729            orb_r,
730            FLOATING_ORB_DENSITY_KGM3,
731            0.45,
732        );
733        let ice: BuoyantBody = BuoyantBody::with_pose(
734            BuoyantBodyKind::IceCube,
735            [
736                width_val * 0.67,
737                (surface_y + ice_r * 0.42).clamp(ice_r * 1.4, height_val - ice_r * 1.4),
738            ],
739            0.18,
740            ice_r,
741            ICE_DENSITY_KGM3,
742            0.917,
743        );
744        let bodies: &mut [BuoyantBody] = self.get_mut_buoyant_bodies();
745        bodies[0] = orb;
746        bodies[1] = ice;
747        self.set_buoyant_body_count(2);
748    }
749
750    /// Adapts physical vessel aspect ratio to match a resized or fullscreen viewport and returns `true` when vessel dimensions changed.
751    ///
752    /// # Arguments
753    ///
754    /// - `&Self` - Mutable liquid solver.
755    /// - `f32` - Target viewport `width / height` aspect ratio.
756    ///
757    /// # Returns
758    ///
759    /// - `bool` - `true` when physical vessel width/height changed and snapshots should sync discontinuously.
760    pub(crate) fn adapt_vessel_aspect_changed(&mut self, aspect_w_over_h: f32) -> bool {
761        if !aspect_w_over_h.is_finite() || aspect_w_over_h <= 0.0 {
762            return false;
763        }
764        let clamped_aspect: f32 = aspect_w_over_h.clamp(0.42, 2.45);
765        let old_cfg: GyroLiquidConfig = self.get_config();
766        let old_w: f32 = old_cfg.get_vessel_width_m();
767        let old_h: f32 = old_cfg.get_vessel_height_m();
768        let cur_aspect: f32 = old_w / old_h.max(1.0e-4);
769        if (cur_aspect - clamped_aspect).abs() < 0.015 {
770            return false;
771        }
772        let target_area: f32 = DEFAULT_VESSEL_WIDTH_M * DEFAULT_VESSEL_HEIGHT_M;
773        let new_w: f32 = (target_area * clamped_aspect).sqrt().clamp(0.068, 0.19);
774        let new_h: f32 = (target_area / new_w).clamp(0.068, 0.19);
775        let mut next_cfg: GyroLiquidConfig = old_cfg;
776        next_cfg.set_vessel_width_m(new_w);
777        next_cfg.set_vessel_height_m(new_h);
778        self.set_config(next_cfg);
779        let is_upright_calm: bool = self.get_kinetic_energy_mj() < 0.65
780            && self.get_gravity_x().abs() < 1.2
781            && self.get_gravity_y() > 7.5
782            && self.get_shake_accel_x().abs() < 0.2
783            && self.get_shake_accel_y().abs() < 0.2;
784        if is_upright_calm {
785            let saved_gx: f32 = self.get_gravity_x();
786            let saved_gy: f32 = self.get_gravity_y();
787            let saved_gz: f32 = self.get_gravity_z();
788            let saved_roll: f32 = self.get_virtual_roll_rad();
789            let saved_pitch: f32 = self.get_virtual_pitch_rad();
790            let saved_time: f32 = self.get_sim_time_secs();
791            self.reset_water();
792            self.set_gravity_x(saved_gx);
793            self.set_gravity_y(saved_gy);
794            self.set_gravity_z(saved_gz);
795            self.set_virtual_roll_rad(saved_roll);
796            self.set_prev_virtual_roll_rad(saved_roll);
797            self.set_virtual_pitch_rad(saved_pitch);
798            self.set_sim_time_secs(saved_time);
799            return true;
800        }
801        let sx: f32 = new_w / old_w.max(1.0e-4);
802        let sy: f32 = new_h / old_h.max(1.0e-4);
803        self.recompute_kernel_constants();
804        let item_count: usize = self.get_particle_count();
805        let d0: f32 = self.get_rest_spacing_m();
806        let pad: f32 = d0 * 0.55;
807        let corner_r: f32 = new_w.min(new_h) * FLUID_CORNER_RADIUS_RATIO;
808        {
809            let Self {
810                pos_x,
811                pos_y,
812                pred_x,
813                pred_y,
814                buoyant_bodies,
815                buoyant_body_count,
816                bubbles,
817                bubble_count,
818                ..
819            } = self;
820            for item_index in 0..item_count {
821                let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
822                    pos_x[item_index] * sx,
823                    pos_y[item_index] * sy,
824                    new_w,
825                    new_h,
826                    pad,
827                    corner_r,
828                );
829                pos_x[item_index] = cx;
830                pos_y[item_index] = cy;
831                pred_x[item_index] = cx;
832                pred_y[item_index] = cy;
833            }
834            let min_dim: f32 = new_w.min(new_h);
835            let b_cnt: usize = *buoyant_body_count;
836            for body in buoyant_bodies.iter_mut().take(b_cnt) {
837                let new_r: f32 = match body.get_kind() {
838                    BuoyantBodyKind::FloatingOrb => (min_dim * 0.076).clamp(0.0052, 0.0102),
839                    BuoyantBodyKind::IceCube => (min_dim * 0.084).clamp(0.0058, 0.0115),
840                };
841                body.set_radius(new_r);
842                let (bx, by, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
843                    body.get_x() * sx,
844                    body.get_y() * sy,
845                    new_w,
846                    new_h,
847                    new_r,
848                    corner_r,
849                );
850                body.set_x(bx);
851                body.set_y(by);
852            }
853            let bub_cnt: usize = *bubble_count;
854            for bub in bubbles.iter_mut().take(bub_cnt) {
855                bub.set_x((bub.get_x() * sx).clamp(pad, new_w - pad));
856                bub.set_y((bub.get_y() * sy).clamp(pad, new_h - pad));
857            }
858        }
859        self.relax_positions_silent(4);
860        true
861    }
862
863    /// Adapts physical vessel aspect ratio to match a resized or fullscreen viewport while preserving total physical water area and live wave motion.
864    ///
865    /// # Arguments
866    ///
867    /// - `&Self` - Mutable liquid solver.
868    /// - `f32` - Target viewport `width / height` aspect ratio.
869    pub fn adapt_vessel_aspect(&mut self, aspect_w_over_h: f32) {
870        let _: bool = self.adapt_vessel_aspect_changed(aspect_w_over_h);
871    }
872
873    /// Updates the liquid fill ratio (`0.20..=0.85`) and rebuilds the resting fluid volume.
874    ///
875    /// # Arguments
876    ///
877    /// - `&Self` - Mutable liquid solver.
878    /// - `f32` - Desired liquid area fill fraction.
879    pub fn set_fill_ratio(&mut self, fill_ratio: f32) {
880        let clamped: f32 = fill_ratio.clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
881        if (self.get_config().get_fill_ratio() - clamped).abs() < 0.005 {
882            return;
883        }
884        let mut config_spec: GyroLiquidConfig = self.get_config();
885        config_spec.set_fill_ratio(clamped);
886        self.set_config(config_spec);
887        self.reset_water();
888    }
889
890    /// Updates the relative viscosity multiplier (`0.2..=6.0`, where `1.0` = 20 °C pure water).
891    ///
892    /// # Arguments
893    ///
894    /// - `&Self` - Mutable liquid solver.
895    /// - `f32` - Relative viscosity scale factor.
896    pub fn set_viscosity(&mut self, viscosity_scale: f32) {
897        let mut config_spec: GyroLiquidConfig = self.get_config();
898        config_spec.set_viscosity_scale(viscosity_scale.clamp(0.2, 6.0));
899        self.set_config(config_spec);
900    }
901
902    /// Updates the relative surface tension multiplier (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
903    ///
904    /// # Arguments
905    ///
906    /// - `&Self` - Mutable liquid solver.
907    /// - `f32` - Relative surface tension scale factor.
908    pub fn set_surface_tension(&mut self, surface_tension_scale: f32) {
909        let mut config_spec: GyroLiquidConfig = self.get_config();
910        config_spec.set_surface_tension_scale(surface_tension_scale.clamp(0.0, 3.0));
911        self.set_config(config_spec);
912    }
913
914    /// Enables or disables Archimedes buoyant floating bodies (orb & ice cube).
915    ///
916    /// # Arguments
917    ///
918    /// - `&Self` - Mutable liquid solver.
919    /// - `bool` - Whether floating buoyant objects are active.
920    pub fn set_buoyant_bodies_enabled(&mut self, enabled: bool) {
921        let mut config_spec: GyroLiquidConfig = self.get_config();
922        let prev: bool = config_spec.get_buoyant_bodies_enabled();
923        config_spec.set_buoyant_bodies_enabled(enabled);
924        self.set_config(config_spec);
925        if enabled && !prev {
926            self.reset_buoyant_bodies();
927        } else if !enabled {
928            self.set_buoyant_body_count(0);
929        }
930    }
931
932    /// Sets desktop/simulator virtual device tilt angles (`roll_rad`, `pitch_rad`).
933    ///
934    /// # Arguments
935    ///
936    /// - `&Self` - Mutable liquid solver.
937    /// - `f32` - In-plane roll angle in radians (`0` = upright, `+π/2` = clockwise right-down).
938    /// - `f32` - Out-of-plane pitch angle in radians (`0` = vertical, `+π/2` = flat face-up).
939    pub fn set_virtual_tilt(&mut self, roll_rad: f32, pitch_rad: f32) {
940        if roll_rad.is_finite() {
941            self.set_virtual_roll_rad(roll_rad);
942        }
943        if pitch_rad.is_finite() {
944            self.set_virtual_pitch_rad(pitch_rad.clamp(-FRAC_PI_2 * 0.96, FRAC_PI_2 * 0.96));
945        }
946    }
947
948    /// Rotates the virtual container angle smoothly by `delta_rad` (positive clockwise in screen space).
949    ///
950    /// # Arguments
951    ///
952    /// - `&Self` - Mutable liquid solver.
953    /// - `f32` - Angular rotation increment in radians.
954    pub fn rotate_container_by(&mut self, delta_rad: f32) {
955        if delta_rad.is_finite() {
956            let next: f32 = self.get_virtual_roll_rad() + delta_rad;
957            self.set_virtual_roll_rad(next);
958        }
959    }
960
961    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²` (decays smoothly).
962    ///
963    /// # Arguments
964    ///
965    /// - `&Self` - Mutable liquid solver.
966    /// - `f32` - Horizontal shake acceleration in `m/s²`.
967    /// - `f32` - Vertical shake acceleration in `m/s²`.
968    pub fn apply_shake_impulse(&mut self, ax: f32, ay: f32) {
969        if ax.is_finite() {
970            let next_x: f32 = (self.get_shake_accel_x() + ax)
971                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
972            self.set_shake_accel_x(next_x);
973        }
974        if ay.is_finite() {
975            let next_y: f32 = (self.get_shake_accel_y() + ay)
976                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
977            self.set_shake_accel_y(next_y);
978        }
979    }
980
981    /// Applies a direct pointer/touch viscous wake stirring impulse inside normalized tank coordinates `[0, 1] × [0, 1]`.
982    ///
983    /// # Arguments
984    ///
985    /// - `&Self` - Mutable liquid solver.
986    /// - `f32` - Normalized horizontal coordinate in `[0.0, 1.0]`.
987    /// - `f32` - Normalized vertical coordinate in `[0.0, 1.0]`.
988    /// - `f32` - Stirring velocity x-component in `m/s`.
989    /// - `f32` - Stirring velocity y-component in `m/s`.
990    pub fn apply_stir_impulse(&mut self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
991        if !norm_x.is_finite()
992            || !norm_y.is_finite()
993            || !vel_x_mps.is_finite()
994            || !vel_y_mps.is_finite()
995        {
996            return;
997        }
998        let config_spec: GyroLiquidConfig = self.get_config();
999        let width_val: f32 = config_spec.get_vessel_width_m();
1000        let height_val: f32 = config_spec.get_vessel_height_m();
1001        let sx: f32 = norm_x.clamp(0.0, 1.0) * width_val;
1002        let sy: f32 = norm_y.clamp(0.0, 1.0) * height_val;
1003        let radius: f32 = (width_val.min(height_val) * FLUID_STIR_RADIUS_RATIO).max(0.012);
1004        let r2_max: f32 = radius * radius;
1005        let svx: f32 = vel_x_mps.clamp(-2.0, 2.0);
1006        let svy: f32 = vel_y_mps.clamp(-2.0, 2.0);
1007        let item_count: usize = self.get_particle_count();
1008        let Self {
1009            pos_x,
1010            pos_y,
1011            vel_x,
1012            vel_y,
1013            buoyant_bodies,
1014            buoyant_body_count,
1015            ..
1016        } = self;
1017        for item_index in 0..item_count {
1018            let dx: f32 = pos_x[item_index] - sx;
1019            let dy: f32 = pos_y[item_index] - sy;
1020            let d2: f32 = dx * dx + dy * dy;
1021            if d2 < r2_max {
1022                let falloff: f32 = 1.0 - (d2 / r2_max).sqrt();
1023                let gain: f32 = falloff * falloff * 0.52;
1024                vel_x[item_index] = (vel_x[item_index] + (svx - vel_x[item_index]) * gain)
1025                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1026                vel_y[item_index] = (vel_y[item_index] + (svy - vel_y[item_index]) * gain)
1027                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1028            }
1029        }
1030        let b_cnt: usize = *buoyant_body_count;
1031        for body in buoyant_bodies.iter_mut().take(b_cnt) {
1032            let dx: f32 = body.get_x() - sx;
1033            let dy: f32 = body.get_y() - sy;
1034            let d2: f32 = dx * dx + dy * dy;
1035            let br: f32 = radius + body.get_radius();
1036            if d2 < br * br {
1037                let falloff: f32 = 1.0 - (d2.sqrt() / br);
1038                let gain: f32 = falloff * 0.42;
1039                body.set_vx(body.get_vx() + (svx - body.get_vx()) * gain);
1040                body.set_vy(body.get_vy() + (svy - body.get_vy()) * gain);
1041                let torque_kick: f32 = (dx * svy - dy * svx) / (br * br + 1.0e-4);
1042                body.set_omega((body.get_omega() + torque_kick * 0.32).clamp(-14.0, 14.0));
1043            }
1044        }
1045    }
1046
1047    /// Feeds a sanitized 6-DOF `DeviceMotionSample` into the non-inertial solver frame with MEMS stationary deadzones and adaptive gravity micro-jitter smoothing.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// - `&Self` - Mutable liquid solver.
1052    /// - `DeviceMotionSample` - Screen-aligned hardware or synthetic sensor sample.
1053    /// - `f32` - Timestep in seconds used to estimate Euler angular acceleration `α = dΩ/dt`.
1054    pub fn apply_device_motion(&mut self, sample: DeviceMotionSample, dt: f32) {
1055        let clean: DeviceMotionSample = sample.sanitized();
1056        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
1057        let raw_gx: f32 = clean.get_gravity_x();
1058        let raw_gy: f32 = clean.get_gravity_y();
1059        let raw_gz: f32 = clean.get_gravity_z();
1060        let cur_gx: f32 = self.get_gravity_x();
1061        let cur_gy: f32 = self.get_gravity_y();
1062        let cur_gz: f32 = self.get_gravity_z();
1063        let dg: f32 =
1064            ((raw_gx - cur_gx).powi(2) + (raw_gy - cur_gy).powi(2) + (raw_gz - cur_gz).powi(2))
1065                .sqrt();
1066        let g_blend: f32 = if dg <= 0.16 {
1067            0.14
1068        } else if dg >= 1.25 {
1069            1.0
1070        } else {
1071            0.14 + 0.86 * ((dg - 0.16) / (1.25 - 0.16))
1072        };
1073        let gx: f32 = cur_gx + (raw_gx - cur_gx) * g_blend;
1074        let gy: f32 = cur_gy + (raw_gy - cur_gy) * g_blend;
1075        let gz: f32 = cur_gz + (raw_gz - cur_gz) * g_blend;
1076        let lx: f32 =
1077            fluid_sensor_deadzone(clean.get_linear_accel_x(), FLUID_SENSOR_LIN_DEADZONE_MPS2)
1078                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
1079        let ly: f32 =
1080            fluid_sensor_deadzone(clean.get_linear_accel_y(), FLUID_SENSOR_LIN_DEADZONE_MPS2)
1081                .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
1082        let omega_cw: f32 =
1083            fluid_sensor_deadzone(-clean.get_gyro_z(), FLUID_SENSOR_GYRO_DEADZONE_RAD_S)
1084                .clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S);
1085        let prev_omega: f32 = self.get_angular_vel_cw();
1086        let smoothed_alpha: f32 = if omega_cw.abs() < 1.0e-5 && prev_omega.abs() < 1.0e-5 {
1087            self.get_angular_accel_cw() * 0.40
1088        } else {
1089            let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
1090                .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
1091            self.get_angular_accel_cw() * 0.65 + raw_alpha * 0.35
1092        };
1093        self.set_gravity_x(gx);
1094        self.set_gravity_y(gy);
1095        self.set_gravity_z(gz);
1096        self.set_linear_accel_x(lx);
1097        self.set_linear_accel_y(ly);
1098        self.set_prev_angular_vel_cw(prev_omega);
1099        self.set_angular_vel_cw(omega_cw);
1100        self.set_angular_accel_cw(if smoothed_alpha.abs() < 0.02 {
1101            0.0
1102        } else {
1103            smoothed_alpha
1104        });
1105        self.set_active_roll_rad(gx.atan2(gy));
1106    }
1107
1108    /// Updates gravity, angular velocity `Ω`, and Euler acceleration `α` from desktop virtual tilt angles.
1109    ///
1110    /// # Arguments
1111    ///
1112    /// - `&Self` - Mutable liquid solver.
1113    /// - `f32` - Timestep in seconds.
1114    pub fn sync_virtual_motion(&mut self, dt: f32) {
1115        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
1116        let roll: f32 = self.get_virtual_roll_rad();
1117        let pitch: f32 = self.get_virtual_pitch_rad();
1118        let cos_p: f32 = pitch.cos();
1119        let gx: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.sin();
1120        let gy: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.cos();
1121        let gz: f32 = -STANDARD_GRAVITY_MPS2 * pitch.sin();
1122        let prev_roll: f32 = self.get_prev_virtual_roll_rad();
1123        let mut d_roll: f32 = roll - prev_roll;
1124        while d_roll > PI {
1125            d_roll -= TAU;
1126        }
1127        while d_roll < -PI {
1128            d_roll += TAU;
1129        }
1130        let omega_cw: f32 = if d_roll.abs() < 1.0e-5 {
1131            0.0
1132        } else {
1133            (d_roll / safe_dt).clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S)
1134        };
1135        let prev_omega: f32 = self.get_angular_vel_cw();
1136        let smoothed_alpha: f32 = if omega_cw.abs() < 1.0e-5 && prev_omega.abs() < 1.0e-5 {
1137            0.0
1138        } else {
1139            let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
1140                .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
1141            self.get_angular_accel_cw() * 0.55 + raw_alpha * 0.45
1142        };
1143        self.set_prev_virtual_roll_rad(roll);
1144        self.set_gravity_x(gx);
1145        self.set_gravity_y(gy);
1146        self.set_gravity_z(gz);
1147        self.set_linear_accel_x(0.0);
1148        self.set_linear_accel_y(0.0);
1149        self.set_prev_angular_vel_cw(prev_omega);
1150        self.set_angular_vel_cw(omega_cw);
1151        self.set_angular_accel_cw(smoothed_alpha);
1152        self.set_active_roll_rad(roll);
1153    }
1154
1155    /// Rebuilds the flat zero-allocation counting-sort CSR spatial hash grid on predicted positions `(pred_x, pred_y)`.
1156    ///
1157    /// # Arguments
1158    ///
1159    /// - `&Self` - Mutable liquid solver.
1160    fn rebuild_spatial_grid(&mut self) {
1161        let item_count: usize = self.get_particle_count();
1162        let gw: usize = self.get_grid_w();
1163        let gh: usize = self.get_grid_h();
1164        let total_cells: usize = gw * gh;
1165        let inv_h: f32 = 1.0 / self.get_kernel_radius_m().max(1.0e-5);
1166        let max_cx: i32 = (gw as i32) - 1;
1167        let max_cy: i32 = (gh as i32) - 1;
1168        let Self {
1169            pred_x,
1170            pred_y,
1171            cell_counts,
1172            cell_starts,
1173            cell_cursors,
1174            particle_cells,
1175            sorted_indices,
1176            ..
1177        } = self;
1178        cell_counts[..total_cells].fill(0);
1179        for item_index in 0..item_count {
1180            let cx: i32 = ((pred_x[item_index] * inv_h).floor() as i32).clamp(0, max_cx);
1181            let cy: i32 = ((pred_y[item_index] * inv_h).floor() as i32).clamp(0, max_cy);
1182            let cid: usize = (cy as usize) * gw + (cx as usize);
1183            particle_cells[item_index] = cid as u32;
1184            cell_counts[cid] += 1;
1185        }
1186        let mut prefix: u32 = 0;
1187        for char_item in 0..total_cells {
1188            cell_starts[char_item] = prefix;
1189            cell_cursors[char_item] = prefix;
1190            prefix += cell_counts[char_item];
1191        }
1192        cell_starts[total_cells] = prefix;
1193        for (outer_index, &cell) in particle_cells.iter().enumerate().take(item_count) {
1194            let cid: usize = cell as usize;
1195            let dst: usize = cell_cursors[cid] as usize;
1196            cell_cursors[cid] = (dst as u32) + 1;
1197            sorted_indices[dst] = outer_index as u32;
1198        }
1199    }
1200
1201    /// Evaluates fluid density and average velocity at world coordinate `(qx, qy)` using the active spatial grid.
1202    ///
1203    /// # Arguments
1204    ///
1205    /// - `&Self` - Liquid solver reference.
1206    /// - `f32` - Query x-coordinate in meters.
1207    /// - `f32` - Query y-coordinate in meters.
1208    ///
1209    /// # Returns
1210    ///
1211    /// - `(f32, f32, f32)` - Sampled `(density_ratio, fluid_vx, fluid_vy)`.
1212    #[must_use]
1213    fn sample_fluid_at(&self, qx: f32, qy: f32) -> (f32, f32, f32) {
1214        let height_val: f32 = self.get_kernel_radius_m();
1215        let h2: f32 = height_val * height_val;
1216        let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
1217        let gw: i32 = self.get_grid_w() as i32;
1218        let gh: i32 = self.get_grid_h() as i32;
1219        let poly6_c: f32 = self.get_poly6_coeff();
1220        let m_p: f32 = self.get_particle_mass_kgpm();
1221        let cx: i32 = ((qx * inv_h).floor() as i32).clamp(0, gw - 1);
1222        let cy: i32 = ((qy * inv_h).floor() as i32).clamp(0, gh - 1);
1223        let x0: i32 = (cx - 1).max(0);
1224        let x1: i32 = (cx + 1).min(gw - 1);
1225        let y0: i32 = (cy - 1).max(0);
1226        let y1: i32 = (cy + 1).min(gh - 1);
1227        let Self {
1228            pred_x,
1229            pred_y,
1230            vel_x,
1231            vel_y,
1232            cell_starts,
1233            sorted_indices,
1234            ..
1235        } = self;
1236        let mut rho: f32 = 0.0;
1237        let mut w_sum: f32 = 0.0;
1238        let mut u_sum: f32 = 0.0;
1239        let mut v_sum: f32 = 0.0;
1240        for ny in y0..=y1 {
1241            let row_off: usize = (ny as usize) * (gw as usize);
1242            for nx in x0..=x1 {
1243                let cid: usize = row_off + (nx as usize);
1244                let source_val: usize = cell_starts[cid] as usize;
1245                let event_ref: usize = cell_starts[cid + 1] as usize;
1246                for &raw_j in &sorted_indices[source_val..event_ref] {
1247                    let inner_index: usize = raw_j as usize;
1248                    let dx: f32 = qx - pred_x[inner_index];
1249                    let dy: f32 = qy - pred_y[inner_index];
1250                    let r2: f32 = dx * dx + dy * dy;
1251                    if r2 < h2 {
1252                        let w_val: f32 = poly6_2d(r2, h2, poly6_c);
1253                        rho += m_p * w_val;
1254                        w_sum += w_val;
1255                        u_sum += w_val * vel_x[inner_index];
1256                        v_sum += w_val * vel_y[inner_index];
1257                    }
1258                }
1259            }
1260        }
1261        let inv_w: f32 = if w_sum > 1.0e-5 { 1.0 / w_sum } else { 0.0 };
1262        (rho / WATER_REST_DENSITY_KGM3, u_sum * inv_w, v_sum * inv_w)
1263    }
1264
1265    /// Executes one full SI PBF substep: non-inertial prediction, Jacobi density constraints, Laplacian surface tension, gated interior vorticity, XSPH viscosity, calm damping, and buoyant rigid-body coupling.
1266    ///
1267    /// # Arguments
1268    ///
1269    /// - `&Self` - Mutable liquid solver.
1270    /// - `f32` - Substep delta time in seconds.
1271    fn run_substep(&mut self, sub_dt: f32) {
1272        let config_spec: GyroLiquidConfig = self.get_config();
1273        let item_count: usize = self.get_particle_count();
1274        let width_val: f32 = config_spec.get_vessel_width_m();
1275        let h_vessel: f32 = config_spec.get_vessel_height_m();
1276        let cx_tank: f32 = width_val * 0.5;
1277        let cy_tank: f32 = h_vessel * 0.5;
1278        let d0: f32 = self.get_rest_spacing_m();
1279        let pad: f32 = d0 * 0.52;
1280        let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
1281        let gx: f32 = self.get_gravity_x();
1282        let gy: f32 = self.get_gravity_y();
1283        let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
1284        let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
1285        let omega: f32 = self.get_angular_vel_cw();
1286        let omega2: f32 = omega * omega;
1287        let alpha: f32 = self.get_angular_accel_cw();
1288        let frame_calm: bool =
1289            lin_x.hypot(lin_y) < 0.05 && omega.abs() < 0.02 && alpha.abs() < 0.08;
1290        {
1291            let Self {
1292                pos_x,
1293                pos_y,
1294                pred_x,
1295                pred_y,
1296                vel_x,
1297                vel_y,
1298                ..
1299            } = self;
1300            for item_index in 0..item_count {
1301                let rx: f32 = pos_x[item_index] - cx_tank;
1302                let ry: f32 = pos_y[item_index] - cy_tank;
1303                let vx: f32 = vel_x[item_index];
1304                let vy: f32 = vel_y[item_index];
1305                let ax: f32 = gx - lin_x + omega2 * rx + alpha * ry + 2.0 * omega * vy;
1306                let ay: f32 = gy - lin_y + omega2 * ry - alpha * rx - 2.0 * omega * vx;
1307                let nvx: f32 = (vx + ax * sub_dt)
1308                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1309                let nvy: f32 = (vy + ay * sub_dt)
1310                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1311                vel_x[item_index] = nvx;
1312                vel_y[item_index] = nvy;
1313                let (px, py, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1314                    pos_x[item_index] + nvx * sub_dt,
1315                    pos_y[item_index] + nvy * sub_dt,
1316                    width_val,
1317                    h_vessel,
1318                    pad,
1319                    corner_r,
1320                );
1321                pred_x[item_index] = px;
1322                pred_y[item_index] = py;
1323            }
1324        }
1325        self.rebuild_spatial_grid();
1326        let height_val: f32 = self.get_kernel_radius_m();
1327        let h2: f32 = height_val * height_val;
1328        let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
1329        let poly6_c: f32 = self.get_poly6_coeff();
1330        let spiky_c: f32 = self.get_spiky_grad_coeff();
1331        let inv_w_dq: f32 = 1.0 / self.get_w_dq().max(1.0e-6);
1332        let a_p: f32 = self.get_particle_area_m2();
1333        let m_p: f32 = self.get_particle_mass_kgpm();
1334        let cfm_eps: f32 = FLUID_CFM_RELAXATION_FACTOR / a_p.max(1.0e-9);
1335        let scorr_scale: f32 = -FLUID_SCORR_K * a_p;
1336        let lap_gain: f32 = FLUID_SURFACE_LAPLACIAN_GAIN * config_spec.get_surface_tension_scale();
1337        let meniscus_gain: f32 =
1338            FLUID_WALL_MENISCUS_STRENGTH * config_spec.get_surface_tension_scale();
1339        let gw: i32 = self.get_grid_w() as i32;
1340        let gh: i32 = self.get_grid_h() as i32;
1341        let gw_u: usize = gw as usize;
1342        let base_iters: u32 = config_spec.get_solver_iterations().clamp(2, 6);
1343        let iters: u32 = if frame_calm
1344            && self.get_sim_time_secs() > 0.6
1345            && self.get_kinetic_energy_mj() < 0.05
1346            && self.get_bubble_count() == 0
1347        {
1348            base_iters.min(2)
1349        } else {
1350            base_iters
1351        };
1352        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1353        let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
1354            (-gx / g_mag, -gy / g_mag)
1355        } else {
1356            (0.0, -1.0)
1357        };
1358        let wall_meniscus_band: f32 = d0 * 1.35;
1359        let self_poly6: f32 = m_p * poly6_2d(0.0, h2, poly6_c);
1360        {
1361            let Self {
1362                pred_x,
1363                pred_y,
1364                cell_starts,
1365                sorted_indices,
1366                neighbor_indices,
1367                neighbor_counts,
1368                ..
1369            } = self;
1370            let search_r2: f32 = h2 * 1.18;
1371            for outer_index in 0..item_count {
1372                let xi: f32 = pred_x[outer_index];
1373                let yi: f32 = pred_y[outer_index];
1374                let cx: i32 = ((xi * inv_h).floor() as i32).clamp(0, gw - 1);
1375                let cy: i32 = ((yi * inv_h).floor() as i32).clamp(0, gh - 1);
1376                let x0: i32 = (cx - 1).max(0);
1377                let x1: i32 = (cx + 1).min(gw - 1);
1378                let y0: i32 = (cy - 1).max(0);
1379                let y1: i32 = (cy + 1).min(gh - 1);
1380                let base: usize = outer_index * FLUID_MAX_NEIGHBORS;
1381                let mut count: usize = 0;
1382                for ny in y0..=y1 {
1383                    let row_off: usize = (ny as usize) * gw_u;
1384                    for nx in x0..=x1 {
1385                        let cid: usize = row_off + (nx as usize);
1386                        let source_val: usize = cell_starts[cid] as usize;
1387                        let event_ref: usize = cell_starts[cid + 1] as usize;
1388                        for &raw_j in &sorted_indices[source_val..event_ref] {
1389                            let inner_index: usize = raw_j as usize;
1390                            if outer_index == inner_index {
1391                                continue;
1392                            }
1393                            let dx: f32 = xi - pred_x[inner_index];
1394                            let dy: f32 = yi - pred_y[inner_index];
1395                            if dx * dx + dy * dy < search_r2 {
1396                                neighbor_indices[base + count] = inner_index as u16;
1397                                count += 1;
1398                                if count == FLUID_MAX_NEIGHBORS {
1399                                    break;
1400                                }
1401                            }
1402                        }
1403                        if count == FLUID_MAX_NEIGHBORS {
1404                            break;
1405                        }
1406                    }
1407                    if count == FLUID_MAX_NEIGHBORS {
1408                        break;
1409                    }
1410                }
1411                neighbor_counts[outer_index] = count as u8;
1412            }
1413        }
1414        for _ in 0..iters {
1415            let Self {
1416                pred_x,
1417                pred_y,
1418                lambda,
1419                density,
1420                corr_x,
1421                corr_y,
1422                neighbor_indices,
1423                neighbor_counts,
1424                buoyant_bodies,
1425                buoyant_body_count,
1426                ..
1427            } = self;
1428            for step_index in 0..item_count {
1429                let xi: f32 = pred_x[step_index];
1430                let yi: f32 = pred_y[step_index];
1431                let base: usize = step_index * FLUID_MAX_NEIGHBORS;
1432                let cnt: usize = neighbor_counts[step_index] as usize;
1433                let mut rho: f32 = self_poly6;
1434                let mut grad_ix: f32 = 0.0;
1435                let mut grad_iy: f32 = 0.0;
1436                let mut sum_grad_sq: f32 = 0.0;
1437                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1438                    let col_index: usize = raw_j as usize;
1439                    let dx: f32 = xi - pred_x[col_index];
1440                    let dy: f32 = yi - pred_y[col_index];
1441                    let r2: f32 = dx * dx + dy * dy;
1442                    if r2 < h2 {
1443                        rho += m_p * poly6_2d(r2, h2, poly6_c);
1444                        if r2 > 1.0e-12 {
1445                            let red_val: f32 = r2.sqrt();
1446                            let gf: f32 = a_p * spiky_grad_factor_2d(red_val, height_val, spiky_c);
1447                            let gx_ij: f32 = gf * dx;
1448                            let gy_ij: f32 = gf * dy;
1449                            grad_ix += gx_ij;
1450                            grad_iy += gy_ij;
1451                            sum_grad_sq += gx_ij * gx_ij + gy_ij * gy_ij;
1452                        }
1453                    }
1454                }
1455                density[step_index] = rho;
1456                let c_val: f32 = (rho / WATER_REST_DENSITY_KGM3 - 1.0).max(0.0);
1457                sum_grad_sq += grad_ix * grad_ix + grad_iy * grad_iy;
1458                lambda[step_index] = if c_val > 0.0 {
1459                    -c_val / (sum_grad_sq + cfm_eps)
1460                } else {
1461                    0.0
1462                };
1463            }
1464            let max_disp: f32 = d0 * 0.42;
1465            for cursor_index in 0..item_count {
1466                let xi: f32 = pred_x[cursor_index];
1467                let yi: f32 = pred_y[cursor_index];
1468                let lam_i: f32 = lambda[cursor_index];
1469                let is_surface: bool = density[cursor_index] < WATER_REST_DENSITY_KGM3 * 0.86;
1470                let base: usize = cursor_index * FLUID_MAX_NEIGHBORS;
1471                let cnt: usize = neighbor_counts[cursor_index] as usize;
1472                let mut dpx: f32 = 0.0;
1473                let mut dpy: f32 = 0.0;
1474                let mut lap_x: f32 = 0.0;
1475                let mut lap_y: f32 = 0.0;
1476                let mut lap_w: f32 = 0.0;
1477                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1478                    let sub_index: usize = raw_j as usize;
1479                    let dx: f32 = xi - pred_x[sub_index];
1480                    let dy: f32 = yi - pred_y[sub_index];
1481                    let r2: f32 = dx * dx + dy * dy;
1482                    if r2 < h2 && r2 > 1.0e-12 {
1483                        let radius_val: f32 = r2.sqrt();
1484                        let w_r: f32 = poly6_2d(r2, h2, poly6_c);
1485                        let ratio: f32 = w_r * inv_w_dq;
1486                        let ratio2: f32 = ratio * ratio;
1487                        let s_corr: f32 = scorr_scale * ratio2 * ratio2;
1488                        let gf: f32 = a_p * spiky_grad_factor_2d(radius_val, height_val, spiky_c);
1489                        let pressure_mag: f32 = (lam_i + lambda[sub_index] + s_corr) * gf;
1490                        dpx += pressure_mag * dx;
1491                        dpy += pressure_mag * dy;
1492                        if is_surface && lap_gain > 0.0 {
1493                            lap_x -= dx * w_r;
1494                            lap_y -= dy * w_r;
1495                            lap_w += w_r;
1496                        }
1497                    }
1498                }
1499                if is_surface && lap_w > 1.0e-5 {
1500                    let inv_lw: f32 = 1.0 / lap_w;
1501                    let cx_shift: f32 = lap_x * inv_lw;
1502                    let cy_shift: f32 = lap_y * inv_lw;
1503                    let tan_x: f32 = -up_y;
1504                    let tan_y: f32 = up_x;
1505                    let proj_tan: f32 = cx_shift * tan_x + cy_shift * tan_y;
1506                    let proj_up: f32 = (cx_shift * up_x + cy_shift * up_y).min(0.0);
1507                    dpx += (tan_x * proj_tan * 0.45 + up_x * proj_up) * lap_gain;
1508                    dpy += (tan_y * proj_tan * 0.45 + up_y * proj_up) * lap_gain;
1509                }
1510                if is_surface && meniscus_gain > 0.0 && !frame_calm {
1511                    let near_left: bool = xi - pad < wall_meniscus_band;
1512                    let near_right: bool = (width_val - pad) - xi < wall_meniscus_band;
1513                    let near_top: bool = yi - pad < wall_meniscus_band;
1514                    let near_bottom: bool = (h_vessel - pad) - yi < wall_meniscus_band;
1515                    if near_left || near_right {
1516                        dpy += up_y * meniscus_gain;
1517                    }
1518                    if near_top || near_bottom {
1519                        dpx += up_x * meniscus_gain;
1520                    }
1521                }
1522                let disp2: f32 = dpx * dpx + dpy * dpy;
1523                if disp2 > max_disp * max_disp {
1524                    let scale: f32 = max_disp / disp2.sqrt();
1525                    dpx *= scale;
1526                    dpy *= scale;
1527                }
1528                corr_x[cursor_index] = dpx;
1529                corr_y[cursor_index] = dpy;
1530            }
1531            let b_cnt: usize = *buoyant_body_count;
1532            for item_index_primary in 0..item_count {
1533                let mut nx: f32 = pred_x[item_index_primary] + corr_x[item_index_primary];
1534                let mut ny: f32 = pred_y[item_index_primary] + corr_y[item_index_primary];
1535                for body in buoyant_bodies.iter().take(b_cnt) {
1536                    let dx: f32 = nx - body.get_x();
1537                    let dy: f32 = ny - body.get_y();
1538                    let min_dist: f32 = body.get_radius() + d0 * 0.36;
1539                    let d2: f32 = dx * dx + dy * dy;
1540                    if d2 < min_dist * min_dist {
1541                        if d2 > 1.0e-12 {
1542                            let dist: f32 = d2.sqrt();
1543                            let push: f32 = (min_dist - dist) * 0.65 / dist;
1544                            nx += dx * push;
1545                            ny += dy * push;
1546                        } else {
1547                            nx += min_dist * 0.5;
1548                        }
1549                    }
1550                }
1551                let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
1552                    clamp_to_rounded_vessel(nx, ny, width_val, h_vessel, pad, corner_r);
1553                pred_x[item_index_primary] = cx;
1554                pred_y[item_index_primary] = cy;
1555            }
1556        }
1557        let inv_sub_dt: f32 = 1.0 / sub_dt.max(1.0e-5);
1558        let visc_scale: f32 = config_spec.get_viscosity_scale();
1559        let xsph_c: f32 = (FLUID_BASE_XSPH_COEFF * visc_scale).clamp(0.012, 0.32);
1560        let surf_xsph_c: f32 = (xsph_c + FLUID_SURFACE_XSPH_BOOST).clamp(0.04, 0.38);
1561        let base_damp: f32 = (-sub_dt * FLUID_VISCOUS_DAMP_PER_SEC * visc_scale.sqrt()).exp();
1562        let settle_damp: f32 = (-sub_dt * FLUID_REST_SETTLE_DAMP_PER_SEC).exp();
1563        let vort_min_spd2: f32 = FLUID_VORTICITY_MIN_SPEED_MPS * FLUID_VORTICITY_MIN_SPEED_MPS;
1564        let creep_eps: f32 = if frame_calm { d0 * 0.0045 } else { 0.0 };
1565        {
1566            let Self {
1567                pos_x,
1568                pos_y,
1569                pred_x,
1570                pred_y,
1571                vel_x,
1572                vel_y,
1573                density,
1574                vorticity,
1575                dvx_scratch,
1576                dvy_scratch,
1577                neighbor_indices,
1578                neighbor_counts,
1579                ..
1580            } = self;
1581            for item_index_secondary in 0..item_count {
1582                let mut dx_step: f32 = pred_x[item_index_secondary] - pos_x[item_index_secondary];
1583                let mut dy_step: f32 = pred_y[item_index_secondary] - pos_y[item_index_secondary];
1584                if creep_eps > 0.0 {
1585                    let step_len: f32 = dx_step.hypot(dy_step);
1586                    if step_len <= creep_eps {
1587                        dx_step = 0.0;
1588                        dy_step = 0.0;
1589                        pred_x[item_index_secondary] = pos_x[item_index_secondary];
1590                        pred_y[item_index_secondary] = pos_y[item_index_secondary];
1591                    }
1592                }
1593                let mut vx: f32 = (dx_step * inv_sub_dt)
1594                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1595                let mut vy: f32 = (dy_step * inv_sub_dt)
1596                    .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1597                let (_, _, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1598                    pred_x[item_index_secondary],
1599                    pred_y[item_index_secondary],
1600                    width_val,
1601                    h_vessel,
1602                    pad + 1.0e-5,
1603                    corner_r,
1604                );
1605                if hit {
1606                    let vn: f32 = vx * wn_x + vy * wn_y;
1607                    if vn < 0.0 {
1608                        let tx: f32 = -wn_y;
1609                        let ty: f32 = wn_x;
1610                        let vt: f32 = (vx * tx + vy * ty) * FLUID_WALL_TANGENTIAL_KEEP;
1611                        let vn_out: f32 = if vn < -0.22 {
1612                            -vn * FLUID_WALL_RESTITUTION
1613                        } else {
1614                            0.0
1615                        };
1616                        vx = tx * vt + wn_x * vn_out;
1617                        vy = ty * vt + wn_y * vn_out;
1618                    }
1619                }
1620                vel_x[item_index_secondary] = vx;
1621                vel_y[item_index_secondary] = vy;
1622            }
1623            for item_index_next in 0..item_count {
1624                let xi: f32 = pred_x[item_index_next];
1625                let yi: f32 = pred_y[item_index_next];
1626                let vxi: f32 = vel_x[item_index_next];
1627                let vyi: f32 = vel_y[item_index_next];
1628                let is_surface: bool = density[item_index_next] < WATER_REST_DENSITY_KGM3 * 0.88;
1629                let base: usize = item_index_next * FLUID_MAX_NEIGHBORS;
1630                let cnt: usize = neighbor_counts[item_index_next] as usize;
1631                let mut curl: f32 = 0.0;
1632                let mut xsph_x: f32 = 0.0;
1633                let mut xsph_y: f32 = 0.0;
1634                for &raw_j in &neighbor_indices[base..(base + cnt)] {
1635                    let peer_index: usize = raw_j as usize;
1636                    let dx: f32 = xi - pred_x[peer_index];
1637                    let dy: f32 = yi - pred_y[peer_index];
1638                    let r2: f32 = dx * dx + dy * dy;
1639                    if r2 < h2 && r2 > 1.0e-12 {
1640                        let rect_val: f32 = r2.sqrt();
1641                        let dvx: f32 = vel_x[peer_index] - vxi;
1642                        let dvy: f32 = vel_y[peer_index] - vyi;
1643                        let w_val: f32 = poly6_2d(r2, h2, poly6_c);
1644                        let rho_j: f32 = density[peer_index].max(WATER_REST_DENSITY_KGM3 * 0.50);
1645                        let weight: f32 = (m_p / rho_j) * w_val;
1646                        xsph_x += dvx * weight;
1647                        xsph_y += dvy * weight;
1648                        if !is_surface {
1649                            let gf: f32 = a_p * spiky_grad_factor_2d(rect_val, height_val, spiky_c);
1650                            curl += dvx * (gf * dy) - dvy * (gf * dx);
1651                        }
1652                    }
1653                }
1654                vorticity[item_index_next] = curl;
1655                let eff_xsph: f32 = if is_surface { surf_xsph_c } else { xsph_c };
1656                dvx_scratch[item_index_next] = eff_xsph * xsph_x;
1657                dvy_scratch[item_index_next] = eff_xsph * xsph_y;
1658            }
1659            for item_index_alt in 0..item_count {
1660                let vxi: f32 = vel_x[item_index_alt];
1661                let vyi: f32 = vel_y[item_index_alt];
1662                let spd2: f32 = vxi * vxi + vyi * vyi;
1663                let allow_vort: bool = density[item_index_alt] >= WATER_REST_DENSITY_KGM3 * 0.88
1664                    && spd2 > vort_min_spd2;
1665                let (vort_fx, vort_fy): (f32, f32) = if allow_vort {
1666                    let xi: f32 = pred_x[item_index_alt];
1667                    let yi: f32 = pred_y[item_index_alt];
1668                    let wi: f32 = vorticity[item_index_alt];
1669                    let base: usize = item_index_alt * FLUID_MAX_NEIGHBORS;
1670                    let cnt: usize = neighbor_counts[item_index_alt] as usize;
1671                    let mut eta_x: f32 = 0.0;
1672                    let mut eta_y: f32 = 0.0;
1673                    for &raw_j in &neighbor_indices[base..(base + cnt)] {
1674                        let inner_index_primary: usize = raw_j as usize;
1675                        let dx: f32 = xi - pred_x[inner_index_primary];
1676                        let dy: f32 = yi - pred_y[inner_index_primary];
1677                        let r2: f32 = dx * dx + dy * dy;
1678                        if r2 < h2 && r2 > 1.0e-12 {
1679                            let row_val: f32 = r2.sqrt();
1680                            let gf: f32 = a_p * spiky_grad_factor_2d(row_val, height_val, spiky_c);
1681                            let abs_wj: f32 = vorticity[inner_index_primary].abs();
1682                            eta_x += abs_wj * gf * dx;
1683                            eta_y += abs_wj * gf * dy;
1684                        }
1685                    }
1686                    let eta_mag: f32 = (eta_x * eta_x + eta_y * eta_y).sqrt();
1687                    if eta_mag > 1.0e-4 {
1688                        let inv_eta: f32 = 1.0 / eta_mag;
1689                        let nx_v: f32 = eta_x * inv_eta;
1690                        let ny_v: f32 = eta_y * inv_eta;
1691                        (
1692                            ny_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1693                            -nx_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1694                        )
1695                    } else {
1696                        (0.0, 0.0)
1697                    }
1698                } else {
1699                    (0.0, 0.0)
1700                };
1701                let damp: f32 = if frame_calm && spd2 < 0.0020 {
1702                    base_damp * settle_damp
1703                } else {
1704                    base_damp
1705                };
1706                let mut out_vx: f32 = (vxi + dvx_scratch[item_index_alt] + vort_fx) * damp;
1707                let mut out_vy: f32 = (vyi + dvy_scratch[item_index_alt] + vort_fy) * damp;
1708                if frame_calm && (out_vx * out_vx + out_vy * out_vy) < 1.0e-6 {
1709                    out_vx = 0.0;
1710                    out_vy = 0.0;
1711                }
1712                vel_x[item_index_alt] =
1713                    out_vx.clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1714                vel_y[item_index_alt] =
1715                    out_vy.clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1716                pos_x[item_index_alt] = pred_x[item_index_alt];
1717                pos_y[item_index_alt] = pred_y[item_index_alt];
1718            }
1719        }
1720        self.step_buoyant_bodies(sub_dt);
1721    }
1722
1723    /// Integrates buoyant rigid bodies using 8-point submerged-volume Archimedes buoyancy, hydrodynamic drag, wave torque, and vessel collisions.
1724    ///
1725    /// # Arguments
1726    ///
1727    /// - `&Self` - Mutable liquid solver.
1728    /// - `f32` - Substep delta time in seconds.
1729    fn step_buoyant_bodies(&mut self, sub_dt: f32) {
1730        let b_cnt: usize = self.get_buoyant_body_count();
1731        if b_cnt == 0 {
1732            return;
1733        }
1734        let config_spec: GyroLiquidConfig = self.get_config();
1735        let width_val: f32 = config_spec.get_vessel_width_m();
1736        let h_vessel: f32 = config_spec.get_vessel_height_m();
1737        let cx_tank: f32 = width_val * 0.5;
1738        let cy_tank: f32 = h_vessel * 0.5;
1739        let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
1740        let gx: f32 = self.get_gravity_x();
1741        let gy: f32 = self.get_gravity_y();
1742        let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
1743        let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
1744        let omega_frame: f32 = self.get_angular_vel_cw();
1745        let omega2: f32 = omega_frame * omega_frame;
1746        let alpha_frame: f32 = self.get_angular_accel_cw();
1747        let frame_calm: bool =
1748            lin_x.hypot(lin_y) < 0.05 && omega_frame.abs() < 0.02 && alpha_frame.abs() < 0.08;
1749        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1750        let (gx_hat, gy_hat): (f32, f32) = if g_mag > 0.25 {
1751            (gx / g_mag, gy / g_mag)
1752        } else {
1753            (0.0, 1.0)
1754        };
1755        let mut updated: [BuoyantBody; FLUID_MAX_BUOYANT_BODIES] =
1756            [BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES];
1757        let mut fluid_probes: [(f32, f32, f32, f32); FLUID_MAX_BUOYANT_BODIES] =
1758            [(0.0, 0.0, 0.0, 0.0); FLUID_MAX_BUOYANT_BODIES];
1759        for idx in 0..b_cnt {
1760            let body: BuoyantBody = self.get_buoyant_bodies()[idx];
1761            updated[idx] = body;
1762            let bx: f32 = body.get_x();
1763            let by: f32 = body.get_y();
1764            let br: f32 = body.get_radius();
1765            let probe_r: f32 = br + self.get_kernel_radius_m() * 0.52;
1766            let mut sub_sum: f32 = 0.0;
1767            let mut u_sum: f32 = 0.0;
1768            let mut v_sum: f32 = 0.0;
1769            let mut torque_sum: f32 = 0.0;
1770            let mut sub_weight_sum: f32 = 0.0;
1771            let sample_offsets: [(f32, f32); 8] = [
1772                (probe_r, 0.0),
1773                (-probe_r, 0.0),
1774                (0.0, probe_r),
1775                (0.0, -probe_r),
1776                (probe_r * 0.707, probe_r * 0.707),
1777                (-probe_r * 0.707, probe_r * 0.707),
1778                (probe_r * 0.707, -probe_r * 0.707),
1779                (-probe_r * 0.707, -probe_r * 0.707),
1780            ];
1781            for (ox, oy) in sample_offsets {
1782                let qx: f32 = (bx + ox).clamp(0.001, width_val - 0.001);
1783                let qy: f32 = (by + oy).clamp(0.001, h_vessel - 0.001);
1784                let (rho_ratio, fu, fv): (f32, f32, f32) = self.sample_fluid_at(qx, qy);
1785                let occ: f32 = ((rho_ratio - 0.14) / 0.42).clamp(0.0, 1.0);
1786                sub_sum += occ;
1787                if occ > 0.01 {
1788                    u_sum += fu * occ;
1789                    v_sum += fv * occ;
1790                    sub_weight_sum += occ;
1791                    let f_buoy_x: f32 = -gx_hat * occ;
1792                    let f_buoy_y: f32 = -gy_hat * occ;
1793                    torque_sum += ox * f_buoy_y - oy * f_buoy_x;
1794                    let rel_u: f32 = fu - body.get_vx();
1795                    let rel_v: f32 = fv - body.get_vy();
1796                    torque_sum += (ox * rel_v - oy * rel_u) * occ * 0.35;
1797                }
1798            }
1799            let f_sub: f32 = (sub_sum / 8.0).clamp(0.0, 1.0);
1800            let (fu_avg, fv_avg): (f32, f32) = if sub_weight_sum > 1.0e-4 {
1801                (u_sum / sub_weight_sum, v_sum / sub_weight_sum)
1802            } else {
1803                (0.0, 0.0)
1804            };
1805            fluid_probes[idx] = (f_sub, fu_avg, fv_avg, torque_sum / (br + 1.0e-4));
1806        }
1807        for idx in 0..b_cnt {
1808            let body: &mut BuoyantBody = &mut updated[idx];
1809            let (f_sub, fu_avg, fv_avg, torque_acc): (f32, f32, f32, f32) = fluid_probes[idx];
1810            let rx: f32 = body.get_x() - cx_tank;
1811            let ry: f32 = body.get_y() - cy_tank;
1812            let vx: f32 = body.get_vx();
1813            let vy: f32 = body.get_vy();
1814            let eff_gx: f32 = gx - lin_x + omega2 * rx + alpha_frame * ry + 2.0 * omega_frame * vy;
1815            let eff_gy: f32 = gy - lin_y + omega2 * ry - alpha_frame * rx - 2.0 * omega_frame * vx;
1816            let rho_body: f32 = body.get_density_kgm3().max(100.0);
1817            let added_mass_rho: f32 = 0.5 * f_sub * WATER_REST_DENSITY_KGM3;
1818            let eff_inertia_rho: f32 = rho_body + added_mass_rho;
1819            let net_buoy_factor: f32 =
1820                (rho_body - f_sub * WATER_REST_DENSITY_KGM3) / eff_inertia_rho;
1821            let ax_net: f32 = eff_gx * net_buoy_factor;
1822            let ay_net: f32 = eff_gy * net_buoy_factor;
1823            let rel_x: f32 = fu_avg - vx;
1824            let rel_y: f32 = fv_avg - vy;
1825            let drag_coeff: f32 = 1.1 + f_sub * (7.5 * config_spec.get_viscosity_scale().sqrt());
1826            let mut nvx: f32 = vx + (ax_net + rel_x * drag_coeff) * sub_dt;
1827            let mut nvy: f32 = vy + (ay_net + rel_y * drag_coeff) * sub_dt;
1828            if frame_calm && nvx.hypot(nvy) < 0.018 && ax_net.hypot(ay_net) < 0.45 {
1829                let calm_body_damp: f32 = (-sub_dt * 6.0).exp();
1830                nvx *= calm_body_damp;
1831                nvy *= calm_body_damp;
1832            }
1833            nvx = nvx.clamp(-2.0, 2.0);
1834            nvy = nvy.clamp(-2.0, 2.0);
1835            let br: f32 = body.get_radius();
1836            let (cx, cy, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1837                body.get_x() + nvx * sub_dt,
1838                body.get_y() + nvy * sub_dt,
1839                width_val,
1840                h_vessel,
1841                br * 1.04,
1842                corner_r,
1843            );
1844            if hit {
1845                let vn: f32 = nvx * wn_x + nvy * wn_y;
1846                if vn < 0.0 {
1847                    nvx -= 1.25 * vn * wn_x;
1848                    nvy -= 1.25 * vn * wn_y;
1849                }
1850            }
1851            let ang_damp: f32 = (-sub_dt * (1.8 + f_sub * 5.2)).exp();
1852            let mut next_omega: f32 =
1853                ((body.get_omega() + torque_acc * sub_dt * 1.5) * ang_damp).clamp(-14.0, 14.0);
1854            if frame_calm && next_omega.abs() < 0.03 {
1855                next_omega = 0.0;
1856            }
1857            body.set_x(cx);
1858            body.set_y(cy);
1859            body.set_vx(nvx);
1860            body.set_vy(nvy);
1861            body.set_omega(next_omega);
1862            body.set_angle(body.get_angle() + next_omega * sub_dt);
1863            body.set_submerged_fraction(f_sub);
1864        }
1865        for item_index in 0..b_cnt {
1866            for inner_index in (item_index + 1)..b_cnt {
1867                let dx: f32 = updated[inner_index].get_x() - updated[item_index].get_x();
1868                let dy: f32 = updated[inner_index].get_y() - updated[item_index].get_y();
1869                let min_d: f32 =
1870                    updated[item_index].get_radius() + updated[inner_index].get_radius();
1871                let d2: f32 = dx * dx + dy * dy;
1872                if d2 < min_d * min_d && d2 > 1.0e-12 {
1873                    let dist: f32 = d2.sqrt();
1874                    let nx: f32 = dx / dist;
1875                    let ny: f32 = dy / dist;
1876                    let pen: f32 = (min_d - dist) * 0.5;
1877                    updated[item_index].set_x(updated[item_index].get_x() - nx * pen);
1878                    updated[item_index].set_y(updated[item_index].get_y() - ny * pen);
1879                    updated[inner_index].set_x(updated[inner_index].get_x() + nx * pen);
1880                    updated[inner_index].set_y(updated[inner_index].get_y() + ny * pen);
1881                    let rvx: f32 = updated[inner_index].get_vx() - updated[item_index].get_vx();
1882                    let rvy: f32 = updated[inner_index].get_vy() - updated[item_index].get_vy();
1883                    let rel_n: f32 = rvx * nx + rvy * ny;
1884                    if rel_n < 0.0 {
1885                        let imp: f32 = -0.65 * rel_n;
1886                        updated[item_index].set_vx(updated[item_index].get_vx() - nx * imp);
1887                        updated[item_index].set_vy(updated[item_index].get_vy() - ny * imp);
1888                        updated[inner_index].set_vx(updated[inner_index].get_vx() + nx * imp);
1889                        updated[inner_index].set_vy(updated[inner_index].get_vy() + ny * imp);
1890                    }
1891                }
1892            }
1893        }
1894        self.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&updated[..b_cnt]);
1895    }
1896
1897    /// Spawns aerated foam & buoyant micro-bubbles at energetic wave crests and advances rising bubbles against live gravity.
1898    ///
1899    /// # Arguments
1900    ///
1901    /// - `&Self` - Mutable liquid solver.
1902    /// - `f32` - Step delta time in seconds.
1903    fn step_bubbles_and_foam(&mut self, dt: f32) {
1904        let config_spec: GyroLiquidConfig = self.get_config();
1905        let width_val: f32 = config_spec.get_vessel_width_m();
1906        let h_vessel: f32 = config_spec.get_vessel_height_m();
1907        let d0: f32 = self.get_rest_spacing_m();
1908        let gx: f32 = self.get_gravity_x();
1909        let gy: f32 = self.get_gravity_y();
1910        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1911        let (rise_x, rise_y): (f32, f32) = if g_mag > 0.25 {
1912            (-gx / g_mag, -gy / g_mag)
1913        } else {
1914            (0.0, -1.0)
1915        };
1916        let mut active: usize = self.get_bubble_count();
1917        let mut item_index: usize = 0;
1918        while item_index < active {
1919            let bub: FluidBubble = self.get_bubbles()[item_index];
1920            let next_age: f32 = bub.get_age() + dt;
1921            if next_age >= bub.get_lifetime() {
1922                active -= 1;
1923                let last: FluidBubble = self.get_bubbles()[active];
1924                self.get_mut_bubbles()[item_index] = last;
1925                continue;
1926            }
1927            let (rho_ratio, fu, fv): (f32, f32, f32) =
1928                self.sample_fluid_at(bub.get_x(), bub.get_y());
1929            let in_water: bool = rho_ratio > 0.34;
1930            let (nvx, nvy, next_foam): (f32, f32, f32) = if in_water {
1931                let target_vx: f32 = fu + rise_x * FLUID_BUBBLE_RISE_SPEED_MPS;
1932                let target_vy: f32 = fv + rise_y * FLUID_BUBBLE_RISE_SPEED_MPS;
1933                let blend: f32 = (dt * 7.0).min(1.0);
1934                (
1935                    bub.get_vx() + (target_vx - bub.get_vx()) * blend,
1936                    bub.get_vy() + (target_vy - bub.get_vy()) * blend,
1937                    (bub.get_foam_factor() * 0.94).max(0.0),
1938                )
1939            } else {
1940                let decay: f32 = (-dt * 4.5).exp();
1941                (
1942                    bub.get_vx() * decay + fu * 0.2,
1943                    bub.get_vy() * decay + fv * 0.2,
1944                    (bub.get_foam_factor() + dt * 2.4).min(1.0),
1945                )
1946            };
1947            let nx: f32 = (bub.get_x() + nvx * dt).clamp(d0 * 0.5, width_val - d0 * 0.5);
1948            let ny: f32 = (bub.get_y() + nvy * dt).clamp(d0 * 0.5, h_vessel - d0 * 0.5);
1949            let mut updated_bub: FluidBubble = bub;
1950            updated_bub.set_x(nx);
1951            updated_bub.set_y(ny);
1952            updated_bub.set_vx(nvx);
1953            updated_bub.set_vy(nvy);
1954            updated_bub.set_age(next_age);
1955            updated_bub.set_foam_factor(next_foam);
1956            self.get_mut_bubbles()[item_index] = updated_bub;
1957            item_index += 1;
1958        }
1959        let item_count: usize = self.get_particle_count();
1960        let mut rng: u64 = self.get_rng_state();
1961        let mut spawned: usize = 0;
1962        let max_spawn_per_step: usize = 6;
1963        let speed_thresh2: f32 = FLUID_FOAM_SPEED_THRESHOLD_MPS * FLUID_FOAM_SPEED_THRESHOLD_MPS;
1964        let Self {
1965            pos_x,
1966            pos_y,
1967            vel_x,
1968            vel_y,
1969            density,
1970            vorticity,
1971            bubbles,
1972            ..
1973        } = self;
1974        for idx in (0..item_count).step_by(3) {
1975            if active >= FLUID_MAX_BUBBLES || spawned >= max_spawn_per_step {
1976                break;
1977            }
1978            let spd2: f32 = vel_x[idx] * vel_x[idx] + vel_y[idx] * vel_y[idx];
1979            let near_surface: bool = density[idx] < WATER_REST_DENSITY_KGM3 * 0.84;
1980            let high_vort: bool = vorticity[idx].abs() > 16.0;
1981            if spd2 > speed_thresh2 && (near_surface || high_vort) {
1982                let r_roll: f32 = fluid_next_rand_f32(&mut rng);
1983                if r_roll < 0.24 {
1984                    let jitter_x: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.7;
1985                    let jitter_y: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.7;
1986                    let rad: f32 = d0 * (0.26 + fluid_next_rand_f32(&mut rng) * 0.36);
1987                    let life: f32 = 0.55 + fluid_next_rand_f32(&mut rng) * 0.95;
1988                    let foam_val: f32 = if near_surface { 0.82 } else { 0.12 };
1989                    bubbles[active] = FluidBubble::spawn(
1990                        [
1991                            (pos_x[idx] + jitter_x).clamp(d0 * 0.5, width_val - d0 * 0.5),
1992                            (pos_y[idx] + jitter_y).clamp(d0 * 0.5, h_vessel - d0 * 0.5),
1993                        ],
1994                        [vel_x[idx] * 0.6, vel_y[idx] * 0.6],
1995                        rad,
1996                        life,
1997                        foam_val,
1998                    );
1999                    active += 1;
2000                    spawned += 1;
2001                }
2002            }
2003        }
2004        self.set_rng_state(rng);
2005        self.set_bubble_count(active);
2006    }
2007
2008    /// Advances the entire physical liquid simulation by `dt` seconds with zero steady-state heap allocations.
2009    ///
2010    /// # Arguments
2011    ///
2012    /// - `&Self` - Mutable liquid solver.
2013    /// - `f32` - Fixed simulation timestep in seconds.
2014    pub fn step(&mut self, dt: f32) {
2015        if !dt.is_finite() || dt <= 0.0 {
2016            return;
2017        }
2018        let clamped_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
2019        let base_substeps: u32 = self.get_config().get_substeps().clamp(2, 4);
2020        let lin_mag: f32 = (self.get_linear_accel_x() + self.get_shake_accel_x())
2021            .hypot(self.get_linear_accel_y() + self.get_shake_accel_y());
2022        let is_settled_rest: bool = self.get_sim_time_secs() > 0.8
2023            && self.get_kinetic_energy_mj() < 0.04
2024            && self.get_bubble_count() == 0
2025            && lin_mag < 0.05
2026            && self.get_angular_vel_cw().abs() < 0.02
2027            && self.get_angular_accel_cw().abs() < 0.08;
2028        let substeps: u32 = if is_settled_rest { 1 } else { base_substeps };
2029        let sub_dt: f32 = clamped_dt / (substeps as f32);
2030        let shake_decay: f32 = (-clamped_dt * FLUID_SHAKE_DECAY_PER_SEC).exp();
2031        for _ in 0..substeps {
2032            self.run_substep(sub_dt);
2033        }
2034        let next_sx: f32 = self.get_shake_accel_x() * shake_decay;
2035        let next_sy: f32 = self.get_shake_accel_y() * shake_decay;
2036        self.set_shake_accel_x(if next_sx.abs() < 0.01 { 0.0 } else { next_sx });
2037        self.set_shake_accel_y(if next_sy.abs() < 0.01 { 0.0 } else { next_sy });
2038        self.step_bubbles_and_foam(clamped_dt);
2039        self.set_sim_time_secs(self.get_sim_time_secs() + clamped_dt);
2040        self.update_diagnostics();
2041    }
2042
2043    /// Recomputes live fluid kinetic energy (`mJ/m`) and peak wave crest elevation relative to gravity-aligned mean level.
2044    ///
2045    /// # Arguments
2046    ///
2047    /// - `&Self` - Mutable liquid solver.
2048    fn update_diagnostics(&mut self) {
2049        let item_count: usize = self.get_particle_count();
2050        if item_count == 0 {
2051            self.set_kinetic_energy_mj(0.0);
2052            self.set_peak_wave_height_m(0.0);
2053            return;
2054        }
2055        let m_p: f32 = self.get_particle_mass_kgpm();
2056        let gx: f32 = self.get_gravity_x();
2057        let gy: f32 = self.get_gravity_y();
2058        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
2059        let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
2060            (-gx / g_mag, -gy / g_mag)
2061        } else {
2062            (0.0, -1.0)
2063        };
2064        let mut ke_sum: f32 = 0.0;
2065        let mut min_proj: f32 = f32::INFINITY;
2066        let mut max_proj: f32 = f32::NEG_INFINITY;
2067        let mut avg_proj: f32 = 0.0;
2068        let Self {
2069            pos_x,
2070            pos_y,
2071            vel_x,
2072            vel_y,
2073            ..
2074        } = self;
2075        for item_index in 0..item_count {
2076            let v2: f32 =
2077                vel_x[item_index] * vel_x[item_index] + vel_y[item_index] * vel_y[item_index];
2078            ke_sum += 0.5 * m_p * v2;
2079            let proj: f32 = pos_x[item_index] * up_x + pos_y[item_index] * up_y;
2080            avg_proj += proj;
2081            if proj < min_proj {
2082                min_proj = proj;
2083            }
2084            if proj > max_proj {
2085                max_proj = proj;
2086            }
2087        }
2088        let mean_proj: f32 = avg_proj / (item_count as f32);
2089        let expected_half_span: f32 = (max_proj - min_proj) * 0.5;
2090        let wave_amp: f32 = ((max_proj - mean_proj) - expected_half_span).abs();
2091        self.set_kinetic_energy_mj(ke_sum * 1000.0);
2092        self.set_peak_wave_height_m(wave_amp);
2093    }
2094
2095    /// Captures current particle, buoyant body, and bubble states directly into pre-allocated `dst` with zero heap allocations.
2096    ///
2097    /// # Arguments
2098    ///
2099    /// - `&Self` - Liquid solver reference.
2100    /// - `&mut FluidSimSnapshot` - Pre-allocated destination snapshot.
2101    pub fn capture_snapshot_into(&self, dst: &mut FluidSimSnapshot) {
2102        let config_spec: GyroLiquidConfig = self.get_config();
2103        let item_count: usize = self.get_particle_count().min(FLUID_MAX_PARTICLES);
2104        let b_cnt: usize = self.get_buoyant_body_count().min(FLUID_MAX_BUOYANT_BODIES);
2105        let bub_cnt: usize = self.get_bubble_count().min(FLUID_MAX_BUBBLES);
2106        dst.set_vessel_width_m(config_spec.get_vessel_width_m());
2107        dst.set_vessel_height_m(config_spec.get_vessel_height_m());
2108        dst.set_kernel_radius_m(self.get_kernel_radius_m());
2109        dst.set_particle_count(item_count);
2110        dst.set_buoyant_body_count(b_cnt);
2111        dst.set_bubble_count(bub_cnt);
2112        dst.set_gravity_x(self.get_gravity_x());
2113        dst.set_gravity_y(self.get_gravity_y());
2114        dst.set_gravity_z(self.get_gravity_z());
2115        dst.set_sim_time_secs(self.get_sim_time_secs());
2116        let inv_rho0: f32 = 1.0 / WATER_REST_DENSITY_KGM3;
2117        dst.get_mut_pos_x()[..item_count].copy_from_slice(&self.get_pos_x()[..item_count]);
2118        dst.get_mut_pos_y()[..item_count].copy_from_slice(&self.get_pos_y()[..item_count]);
2119        dst.get_mut_vel_x()[..item_count].copy_from_slice(&self.get_vel_x()[..item_count]);
2120        dst.get_mut_vel_y()[..item_count].copy_from_slice(&self.get_vel_y()[..item_count]);
2121        let src_dens: &[f32] = self.get_density();
2122        let dst_ratio: &mut [f32] = dst.get_mut_density_ratio();
2123        for item_index in 0..item_count {
2124            dst_ratio[item_index] = src_dens[item_index] * inv_rho0;
2125        }
2126        dst.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&self.get_buoyant_bodies()[..b_cnt]);
2127        dst.get_mut_bubbles()[..bub_cnt].copy_from_slice(&self.get_bubbles()[..bub_cnt]);
2128    }
2129
2130    /// Computes the liquid center of mass `(cx, cy)` in SI meters inside the vessel.
2131    ///
2132    /// # Arguments
2133    ///
2134    /// - `&Self` - Liquid solver reference.
2135    ///
2136    /// # Returns
2137    ///
2138    /// - `(f32, f32)` - Center of mass coordinates `(x_m, y_m)`.
2139    #[must_use]
2140    pub fn center_of_mass(&self) -> (f32, f32) {
2141        let item_count: usize = self.get_particle_count();
2142        if item_count == 0 {
2143            let config_spec: GyroLiquidConfig = self.get_config();
2144            return (
2145                config_spec.get_vessel_width_m() * 0.5,
2146                config_spec.get_vessel_height_m() * 0.5,
2147            );
2148        }
2149        let px: &[f32] = self.get_pos_x();
2150        let py: &[f32] = self.get_pos_y();
2151        let mut sx: f32 = 0.0;
2152        let mut sy: f32 = 0.0;
2153        for item_index in 0..item_count {
2154            sx += px[item_index];
2155            sy += py[item_index];
2156        }
2157        let inv_n: f32 = 1.0 / (item_count as f32);
2158        (sx * inv_n, sy * inv_n)
2159    }
2160
2161    /// Returns `true` if any active particle, buoyant body, or bubble has non-finite coordinates or escaped vessel bounds.
2162    ///
2163    /// # Arguments
2164    ///
2165    /// - `&Self` - Liquid solver reference.
2166    ///
2167    /// # Returns
2168    ///
2169    /// - `bool` - `true` when NaN/Inf or out-of-bounds escape is detected.
2170    #[must_use]
2171    pub fn has_invalid_or_escaped_state(&self) -> bool {
2172        let config_spec: GyroLiquidConfig = self.get_config();
2173        let width_val: f32 = config_spec.get_vessel_width_m();
2174        let height_val: f32 = config_spec.get_vessel_height_m();
2175        let item_count: usize = self.get_particle_count();
2176        let px: &[f32] = self.get_pos_x();
2177        let py: &[f32] = self.get_pos_y();
2178        let vx: &[f32] = self.get_vel_x();
2179        let vy: &[f32] = self.get_vel_y();
2180        for item_index in 0..item_count {
2181            if !px[item_index].is_finite()
2182                || !py[item_index].is_finite()
2183                || !vx[item_index].is_finite()
2184                || !vy[item_index].is_finite()
2185                || px[item_index] < -1.0e-3
2186                || px[item_index] > width_val + 1.0e-3
2187                || py[item_index] < -1.0e-3
2188                || py[item_index] > height_val + 1.0e-3
2189            {
2190                return true;
2191            }
2192        }
2193        let b_cnt: usize = self.get_buoyant_body_count();
2194        for body in self.get_buoyant_bodies().iter().take(b_cnt) {
2195            if !body.get_x().is_finite()
2196                || !body.get_y().is_finite()
2197                || !body.get_vx().is_finite()
2198                || !body.get_vy().is_finite()
2199                || !body.get_angle().is_finite()
2200                || body.get_x() < -1.0e-3
2201                || body.get_x() > width_val + 1.0e-3
2202                || body.get_y() < -1.0e-3
2203                || body.get_y() > height_val + 1.0e-3
2204            {
2205                return true;
2206            }
2207        }
2208        false
2209    }
2210}