1use super::*;
2
3impl BuoyantBody {
5 #[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
43impl FluidBubble {
45 #[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
79impl Default for GyroLiquidConfig {
81 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
101impl Default for FluidSimSnapshot {
103 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
131impl InterpolatableState for FluidSimSnapshot {
133 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 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 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
280impl Default for LiquidFluidSolver {
282 fn default() -> Self {
288 Self::with_config(GyroLiquidConfig::default())
289 }
290}
291
292impl LiquidFluidSolver {
294 #[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 neighbor_w: vec![0.0; FLUID_MAX_PARTICLES * FLUID_MAX_NEIGHBORS],
356 neighbor_gf: vec![0.0; FLUID_MAX_PARTICLES * FLUID_MAX_NEIGHBORS],
357 settled_gravity_x: 0.0,
358 settled_gravity_y: STANDARD_GRAVITY_MPS2,
359 last_max_speed_mps: 0.0,
360 buoyant_bodies: vec![BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES],
361 buoyant_body_count: 0,
362 bubbles: vec![FluidBubble::default(); FLUID_MAX_BUBBLES],
363 bubble_count: 0,
364 };
365 solver.reset_water();
366 solver
367 }
368
369 fn recompute_kernel_constants(&mut self) {
375 let config_spec: GyroLiquidConfig = self.get_config();
376 let width_val: f32 = config_spec.get_vessel_width_m().clamp(0.06, 0.24);
377 let h_vessel: f32 = config_spec.get_vessel_height_m().clamp(0.06, 0.24);
378 let fill: f32 = config_spec
379 .get_fill_ratio()
380 .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
381 let item_count: usize = self.get_particle_count().clamp(64, FLUID_MAX_PARTICLES);
382 let water_area: f32 = fill * width_val * h_vessel;
383 let particle_area: f32 = water_area / (item_count as f32);
384 let d0: f32 = particle_area.sqrt();
385 let height_val: f32 = (d0 * FLUID_KERNEL_RADIUS_MULT).max(0.0025);
386 let h2: f32 = height_val * height_val;
387 let h4: f32 = h2 * h2;
388 let h5: f32 = h4 * height_val;
389 let h8: f32 = h4 * h4;
390 let poly6_coeff: f32 = 4.0 / (PI * h8);
391 let spiky_grad_coeff: f32 = -30.0 / (PI * h5);
392 let dq: f32 = FLUID_SCORR_DQ_RATIO * height_val;
393 let w_dq: f32 = poly6_2d(dq * dq, h2, poly6_coeff).max(1.0e-6);
394 let gw: usize = ((width_val / height_val).ceil() as usize).clamp(4, 64);
395 let gh: usize = ((h_vessel / height_val).ceil() as usize).clamp(4, 64);
396 let (final_gw, final_gh): (usize, usize) = if gw * gh > FLUID_MAX_GRID_CELLS {
397 (64, FLUID_MAX_GRID_CELLS / 64)
398 } else {
399 (gw, gh)
400 };
401 self.set_rest_spacing_m(d0);
402 self.set_particle_area_m2(particle_area);
403 self.set_particle_mass_kgpm(WATER_REST_DENSITY_KGM3 * particle_area);
404 self.set_kernel_radius_m(height_val);
405 self.set_poly6_coeff(poly6_coeff);
406 self.set_spiky_grad_coeff(spiky_grad_coeff);
407 self.set_w_dq(w_dq);
408 self.set_grid_w(final_gw);
409 self.set_grid_h(final_gh);
410 }
411
412 pub fn reset_water(&mut self) {
418 let mut config_spec: GyroLiquidConfig = self.get_config();
419 let fill: f32 = config_spec
420 .get_fill_ratio()
421 .clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
422 config_spec.set_fill_ratio(fill);
423 let width_val: f32 = config_spec.get_vessel_width_m().clamp(0.06, 0.24);
424 let h_vessel: f32 = config_spec.get_vessel_height_m().clamp(0.06, 0.24);
425 config_spec.set_vessel_width_m(width_val);
426 config_spec.set_vessel_height_m(h_vessel);
427 self.set_config(config_spec);
428 let target_n: usize = (((config_spec.get_base_particle_count() as f32) * (fill / 0.50))
429 .round() as usize)
430 .clamp(120, FLUID_MAX_PARTICLES);
431 self.set_particle_count(target_n);
432 self.recompute_kernel_constants();
433 let d0: f32 = self.get_rest_spacing_m();
434 let pad: f32 = d0 * 0.54;
435 let usable_w: f32 = (width_val - 2.0 * pad).max(d0 * 2.0);
436 let usable_h: f32 = (h_vessel - 2.0 * pad).max(d0 * 2.0);
437 let cols: usize = ((usable_w / d0).round() as usize).max(4);
438 let col_step: f32 = usable_w / (cols as f32);
439 let rows: usize = target_n.div_ceil(cols);
440 let pool_h: f32 = (usable_h * fill).clamp(d0 * 1.5, usable_h);
441 let row_step: f32 = pool_h / (rows.max(1) as f32);
442 let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
443 {
444 let Self {
445 pos_x,
446 pos_y,
447 pred_x,
448 pred_y,
449 vel_x,
450 vel_y,
451 density,
452 vorticity,
453 lambda,
454 ..
455 } = self;
456 for item_index in 0..target_n {
457 let row: usize = item_index / cols;
458 let col: usize = item_index % cols;
459 let rem_in_row: usize = if row + 1 == rows {
460 target_n - row * cols
461 } else {
462 cols
463 };
464 let row_span_w: f32 = (rem_in_row as f32) * col_step;
465 let row_x0: f32 = (width_val - row_span_w) * 0.5;
466 let stagger: f32 = if rem_in_row == cols {
467 if (row & 1) == 1 {
468 0.22 * col_step
469 } else {
470 -0.22 * col_step
471 }
472 } else {
473 0.0
474 };
475 let rx: f32 = row_x0 + (col as f32 + 0.5) * col_step + stagger;
476 let ry: f32 = h_vessel - pad - (row as f32 + 0.5) * row_step;
477 let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
478 clamp_to_rounded_vessel(rx, ry, width_val, h_vessel, pad, corner_r);
479 pos_x[item_index] = cx;
480 pos_y[item_index] = cy;
481 pred_x[item_index] = cx;
482 pred_y[item_index] = cy;
483 vel_x[item_index] = 0.0;
484 vel_y[item_index] = 0.0;
485 density[item_index] = WATER_REST_DENSITY_KGM3;
486 vorticity[item_index] = 0.0;
487 lambda[item_index] = 0.0;
488 }
489 }
490 self.set_rng_state(FLUID_RNG_SEED);
491 self.set_bubble_count(0);
492 self.set_shake_accel_x(0.0);
493 self.set_shake_accel_y(0.0);
494 self.set_linear_accel_x(0.0);
495 self.set_linear_accel_y(0.0);
496 self.set_angular_vel_cw(0.0);
497 self.set_prev_angular_vel_cw(0.0);
498 self.set_angular_accel_cw(0.0);
499 self.reset_buoyant_bodies();
500 self.relax_positions_silent(FLUID_HYDROSTATIC_RELAX_ITERS);
501 let n_zero: usize = self.get_particle_count();
502 self.get_mut_vel_x()[..n_zero].fill(0.0);
503 self.get_mut_vel_y()[..n_zero].fill(0.0);
504 self.get_mut_vorticity()[..n_zero].fill(0.0);
505 self.set_kinetic_energy_mj(0.0);
506 self.set_peak_wave_height_m(0.0);
507 }
508
509 fn relax_positions_silent(&mut self, passes: u32) {
516 let item_count: usize = self.get_particle_count();
517 if item_count == 0 || passes == 0 {
518 return;
519 }
520 let config_spec: GyroLiquidConfig = self.get_config();
521 let width_val: f32 = config_spec.get_vessel_width_m();
522 let h_vessel: f32 = config_spec.get_vessel_height_m();
523 let d0: f32 = self.get_rest_spacing_m();
524 let pad: f32 = d0 * 0.52;
525 let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
526 let height_val: f32 = self.get_kernel_radius_m();
527 let h2: f32 = height_val * height_val;
528 let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
529 let poly6_c: f32 = self.get_poly6_coeff();
530 let spiky_c: f32 = self.get_spiky_grad_coeff();
531 let inv_w_dq: f32 = 1.0 / self.get_w_dq().max(1.0e-6);
532 let a_p: f32 = self.get_particle_area_m2();
533 let m_p: f32 = self.get_particle_mass_kgpm();
534 let cfm_eps: f32 = FLUID_CFM_RELAXATION_FACTOR / a_p.max(1.0e-9);
535 let scorr_scale: f32 = -FLUID_SCORR_K * a_p;
536 let self_poly6: f32 = m_p * poly6_2d(0.0, h2, poly6_c);
537 let gw: i32 = self.get_grid_w() as i32;
538 let gh: i32 = self.get_grid_h() as i32;
539 let gw_u: usize = gw as usize;
540 for _ in 0..passes {
541 self.rebuild_spatial_grid();
542 {
543 let Self {
544 pred_x,
545 pred_y,
546 cell_starts,
547 sorted_indices,
548 neighbor_indices,
549 neighbor_counts,
550 ..
551 } = self;
552 let search_r2: f32 = h2 * 1.15;
553 for item_index in 0..item_count {
554 let xi: f32 = pred_x[item_index];
555 let yi: f32 = pred_y[item_index];
556 let cx: i32 = ((xi * inv_h).floor() as i32).clamp(0, gw - 1);
557 let cy: i32 = ((yi * inv_h).floor() as i32).clamp(0, gh - 1);
558 let x0: i32 = (cx - 1).max(0);
559 let x1: i32 = (cx + 1).min(gw - 1);
560 let y0: i32 = (cy - 1).max(0);
561 let y1: i32 = (cy + 1).min(gh - 1);
562 let base: usize = item_index * FLUID_MAX_NEIGHBORS;
563 let mut count: usize = 0;
564 for ny in y0..=y1 {
565 let row_off: usize = (ny as usize) * gw_u;
566 for nx in x0..=x1 {
567 let cid: usize = row_off + (nx as usize);
568 let source_val: usize = cell_starts[cid] as usize;
569 let event_ref: usize = cell_starts[cid + 1] as usize;
570 for &raw_j in &sorted_indices[source_val..event_ref] {
571 let inner_index: usize = raw_j as usize;
572 if item_index == inner_index {
573 continue;
574 }
575 let dx: f32 = xi - pred_x[inner_index];
576 let dy: f32 = yi - pred_y[inner_index];
577 if dx * dx + dy * dy < search_r2 {
578 neighbor_indices[base + count] = inner_index as u16;
579 count += 1;
580 if count == FLUID_MAX_NEIGHBORS {
581 break;
582 }
583 }
584 }
585 if count == FLUID_MAX_NEIGHBORS {
586 break;
587 }
588 }
589 if count == FLUID_MAX_NEIGHBORS {
590 break;
591 }
592 }
593 neighbor_counts[item_index] = count as u8;
594 }
595 }
596 let Self {
597 pos_x,
598 pos_y,
599 pred_x,
600 pred_y,
601 lambda,
602 density,
603 corr_x,
604 corr_y,
605 neighbor_indices,
606 neighbor_counts,
607 buoyant_bodies,
608 buoyant_body_count,
609 ..
610 } = self;
611 for outer_index in 0..item_count {
612 let xi: f32 = pred_x[outer_index];
613 let yi: f32 = pred_y[outer_index];
614 let base: usize = outer_index * FLUID_MAX_NEIGHBORS;
615 let cnt: usize = neighbor_counts[outer_index] as usize;
616 let mut rho: f32 = self_poly6;
617 let mut grad_ix: f32 = 0.0;
618 let mut grad_iy: f32 = 0.0;
619 let mut sum_grad_sq: f32 = 0.0;
620 for &raw_j in &neighbor_indices[base..(base + cnt)] {
621 let col_index: usize = raw_j as usize;
622 let dx: f32 = xi - pred_x[col_index];
623 let dy: f32 = yi - pred_y[col_index];
624 let r2: f32 = dx * dx + dy * dy;
625 if r2 < h2 {
626 rho += m_p * poly6_2d(r2, h2, poly6_c);
627 if r2 > 1.0e-12 {
628 let red_val: f32 = r2.sqrt();
629 let gf: f32 = a_p * spiky_grad_factor_2d(red_val, height_val, spiky_c);
630 let gx_ij: f32 = gf * dx;
631 let gy_ij: f32 = gf * dy;
632 grad_ix += gx_ij;
633 grad_iy += gy_ij;
634 sum_grad_sq += gx_ij * gx_ij + gy_ij * gy_ij;
635 }
636 }
637 }
638 density[outer_index] = rho;
639 let c_val: f32 = (rho / WATER_REST_DENSITY_KGM3 - 1.0).max(0.0);
640 sum_grad_sq += grad_ix * grad_ix + grad_iy * grad_iy;
641 lambda[outer_index] = if c_val > 0.0 {
642 -c_val / (sum_grad_sq + cfm_eps)
643 } else {
644 0.0
645 };
646 }
647 let max_disp: f32 = d0 * 0.35;
648 for step_index in 0..item_count {
649 let xi: f32 = pred_x[step_index];
650 let yi: f32 = pred_y[step_index];
651 let lam_i: f32 = lambda[step_index];
652 let base: usize = step_index * FLUID_MAX_NEIGHBORS;
653 let cnt: usize = neighbor_counts[step_index] as usize;
654 let mut dpx: f32 = 0.0;
655 let mut dpy: f32 = 0.0;
656 for &raw_j in &neighbor_indices[base..(base + cnt)] {
657 let sub_index: usize = raw_j as usize;
658 let dx: f32 = xi - pred_x[sub_index];
659 let dy: f32 = yi - pred_y[sub_index];
660 let r2: f32 = dx * dx + dy * dy;
661 if r2 < h2 && r2 > 1.0e-12 {
662 let radius_val: f32 = r2.sqrt();
663 let w_r: f32 = poly6_2d(r2, h2, poly6_c);
664 let ratio: f32 = w_r * inv_w_dq;
665 let ratio2: f32 = ratio * ratio;
666 let s_corr: f32 = scorr_scale * ratio2 * ratio2;
667 let gf: f32 = a_p * spiky_grad_factor_2d(radius_val, height_val, spiky_c);
668 let pressure_mag: f32 = (lam_i + lambda[sub_index] + s_corr) * gf;
669 dpx += pressure_mag * dx;
670 dpy += pressure_mag * dy;
671 }
672 }
673 let disp2: f32 = dpx * dpx + dpy * dpy;
674 if disp2 > max_disp * max_disp {
675 let scale: f32 = max_disp / disp2.sqrt();
676 dpx *= scale;
677 dpy *= scale;
678 }
679 corr_x[step_index] = dpx;
680 corr_y[step_index] = dpy;
681 }
682 let b_cnt: usize = *buoyant_body_count;
683 for cursor_index in 0..item_count {
684 let mut nx: f32 = pred_x[cursor_index] + corr_x[cursor_index];
685 let mut ny: f32 = pred_y[cursor_index] + corr_y[cursor_index];
686 for body in buoyant_bodies.iter().take(b_cnt) {
687 let dx: f32 = nx - body.get_x();
688 let dy: f32 = ny - body.get_y();
689 let min_dist: f32 = body.get_radius() + d0 * 0.36;
690 let d2: f32 = dx * dx + dy * dy;
691 if d2 < min_dist * min_dist && d2 > 1.0e-12 {
692 let dist: f32 = d2.sqrt();
693 let push: f32 = (min_dist - dist) * 0.65 / dist;
694 nx += dx * push;
695 ny += dy * push;
696 }
697 }
698 let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
699 clamp_to_rounded_vessel(nx, ny, width_val, h_vessel, pad, corner_r);
700 pred_x[cursor_index] = cx;
701 pred_y[cursor_index] = cy;
702 pos_x[cursor_index] = cx;
703 pos_y[cursor_index] = cy;
704 }
705 }
706 }
707
708 pub fn reset_buoyant_bodies(&mut self) {
714 let config_spec: GyroLiquidConfig = self.get_config();
715 if !config_spec.get_buoyant_bodies_enabled() {
716 self.set_buoyant_body_count(0);
717 return;
718 }
719 let width_val: f32 = config_spec.get_vessel_width_m();
720 let height_val: f32 = config_spec.get_vessel_height_m();
721 let fill: f32 = config_spec.get_fill_ratio();
722 let surface_y: f32 =
723 (height_val * (1.0 - fill)).clamp(height_val * 0.14, height_val * 0.82);
724 let min_dim: f32 = width_val.min(height_val);
725 let orb_r: f32 = (min_dim * 0.076).clamp(0.0052, 0.0102);
726 let ice_r: f32 = (min_dim * 0.084).clamp(0.0058, 0.0115);
727 let orb: BuoyantBody = BuoyantBody::with_pose(
728 BuoyantBodyKind::FloatingOrb,
729 [
730 width_val * 0.33,
731 (surface_y - orb_r * 0.10).clamp(orb_r * 1.4, height_val - orb_r * 1.4),
732 ],
733 0.0,
734 orb_r,
735 FLOATING_ORB_DENSITY_KGM3,
736 0.45,
737 );
738 let ice: BuoyantBody = BuoyantBody::with_pose(
739 BuoyantBodyKind::IceCube,
740 [
741 width_val * 0.67,
742 (surface_y + ice_r * 0.42).clamp(ice_r * 1.4, height_val - ice_r * 1.4),
743 ],
744 0.18,
745 ice_r,
746 ICE_DENSITY_KGM3,
747 0.917,
748 );
749 let bodies: &mut [BuoyantBody] = self.get_mut_buoyant_bodies();
750 bodies[0] = orb;
751 bodies[1] = ice;
752 self.set_buoyant_body_count(2);
753 }
754
755 pub(crate) fn adapt_vessel_aspect_changed(&mut self, aspect_w_over_h: f32) -> bool {
766 if !aspect_w_over_h.is_finite() || aspect_w_over_h <= 0.0 {
767 return false;
768 }
769 let clamped_aspect: f32 = aspect_w_over_h.clamp(0.42, 2.45);
770 let old_cfg: GyroLiquidConfig = self.get_config();
771 let old_w: f32 = old_cfg.get_vessel_width_m();
772 let old_h: f32 = old_cfg.get_vessel_height_m();
773 let cur_aspect: f32 = old_w / old_h.max(1.0e-4);
774 if (cur_aspect - clamped_aspect).abs() < 0.015 {
775 return false;
776 }
777 let target_area: f32 = DEFAULT_VESSEL_WIDTH_M * DEFAULT_VESSEL_HEIGHT_M;
778 let new_w: f32 = (target_area * clamped_aspect).sqrt().clamp(0.068, 0.19);
779 let new_h: f32 = (target_area / new_w).clamp(0.068, 0.19);
780 let mut next_cfg: GyroLiquidConfig = old_cfg;
781 next_cfg.set_vessel_width_m(new_w);
782 next_cfg.set_vessel_height_m(new_h);
783 self.set_config(next_cfg);
784 let is_upright_calm: bool = self.get_kinetic_energy_mj() < 0.65
785 && self.get_gravity_x().abs() < 1.2
786 && self.get_gravity_y() > 7.5
787 && self.get_shake_accel_x().abs() < 0.2
788 && self.get_shake_accel_y().abs() < 0.2;
789 if is_upright_calm {
790 let saved_gx: f32 = self.get_gravity_x();
791 let saved_gy: f32 = self.get_gravity_y();
792 let saved_gz: f32 = self.get_gravity_z();
793 let saved_roll: f32 = self.get_virtual_roll_rad();
794 let saved_pitch: f32 = self.get_virtual_pitch_rad();
795 let saved_time: f32 = self.get_sim_time_secs();
796 self.reset_water();
797 self.set_gravity_x(saved_gx);
798 self.set_gravity_y(saved_gy);
799 self.set_gravity_z(saved_gz);
800 self.set_virtual_roll_rad(saved_roll);
801 self.set_prev_virtual_roll_rad(saved_roll);
802 self.set_virtual_pitch_rad(saved_pitch);
803 self.set_sim_time_secs(saved_time);
804 return true;
805 }
806 let sx: f32 = new_w / old_w.max(1.0e-4);
807 let sy: f32 = new_h / old_h.max(1.0e-4);
808 self.recompute_kernel_constants();
809 let item_count: usize = self.get_particle_count();
810 let d0: f32 = self.get_rest_spacing_m();
811 let pad: f32 = d0 * 0.55;
812 let corner_r: f32 = new_w.min(new_h) * FLUID_CORNER_RADIUS_RATIO;
813 {
814 let Self {
815 pos_x,
816 pos_y,
817 pred_x,
818 pred_y,
819 buoyant_bodies,
820 buoyant_body_count,
821 bubbles,
822 bubble_count,
823 ..
824 } = self;
825 for item_index in 0..item_count {
826 let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
827 pos_x[item_index] * sx,
828 pos_y[item_index] * sy,
829 new_w,
830 new_h,
831 pad,
832 corner_r,
833 );
834 pos_x[item_index] = cx;
835 pos_y[item_index] = cy;
836 pred_x[item_index] = cx;
837 pred_y[item_index] = cy;
838 }
839 let min_dim: f32 = new_w.min(new_h);
840 let b_cnt: usize = *buoyant_body_count;
841 for body in buoyant_bodies.iter_mut().take(b_cnt) {
842 let new_r: f32 = match body.get_kind() {
843 BuoyantBodyKind::FloatingOrb => (min_dim * 0.076).clamp(0.0052, 0.0102),
844 BuoyantBodyKind::IceCube => (min_dim * 0.084).clamp(0.0058, 0.0115),
845 };
846 body.set_radius(new_r);
847 let (bx, by, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
848 body.get_x() * sx,
849 body.get_y() * sy,
850 new_w,
851 new_h,
852 new_r,
853 corner_r,
854 );
855 body.set_x(bx);
856 body.set_y(by);
857 }
858 let bub_cnt: usize = *bubble_count;
859 for bub in bubbles.iter_mut().take(bub_cnt) {
860 bub.set_x((bub.get_x() * sx).clamp(pad, new_w - pad));
861 bub.set_y((bub.get_y() * sy).clamp(pad, new_h - pad));
862 }
863 }
864 self.relax_positions_silent(4);
865 true
866 }
867
868 pub fn adapt_vessel_aspect(&mut self, aspect_w_over_h: f32) {
875 let _: bool = self.adapt_vessel_aspect_changed(aspect_w_over_h);
876 }
877
878 pub fn set_fill_ratio(&mut self, fill_ratio: f32) {
885 let clamped: f32 = fill_ratio.clamp(FLUID_MIN_FILL_RATIO, FLUID_MAX_FILL_RATIO);
886 if (self.get_config().get_fill_ratio() - clamped).abs() < 0.005 {
887 return;
888 }
889 let mut config_spec: GyroLiquidConfig = self.get_config();
890 config_spec.set_fill_ratio(clamped);
891 self.set_config(config_spec);
892 self.reset_water();
893 }
894
895 pub fn set_viscosity(&mut self, viscosity_scale: f32) {
902 let mut config_spec: GyroLiquidConfig = self.get_config();
903 config_spec.set_viscosity_scale(viscosity_scale.clamp(0.2, 6.0));
904 self.set_config(config_spec);
905 }
906
907 pub fn set_surface_tension(&mut self, surface_tension_scale: f32) {
914 let mut config_spec: GyroLiquidConfig = self.get_config();
915 config_spec.set_surface_tension_scale(surface_tension_scale.clamp(0.0, 3.0));
916 self.set_config(config_spec);
917 }
918
919 pub fn set_buoyant_bodies_enabled(&mut self, enabled: bool) {
926 let mut config_spec: GyroLiquidConfig = self.get_config();
927 let prev: bool = config_spec.get_buoyant_bodies_enabled();
928 config_spec.set_buoyant_bodies_enabled(enabled);
929 self.set_config(config_spec);
930 if enabled && !prev {
931 self.reset_buoyant_bodies();
932 } else if !enabled {
933 self.set_buoyant_body_count(0);
934 }
935 }
936
937 pub fn set_virtual_tilt(&mut self, roll_rad: f32, pitch_rad: f32) {
945 if roll_rad.is_finite() {
946 self.set_virtual_roll_rad(roll_rad);
947 }
948 if pitch_rad.is_finite() {
949 self.set_virtual_pitch_rad(pitch_rad.clamp(-FRAC_PI_2 * 0.96, FRAC_PI_2 * 0.96));
950 }
951 }
952
953 pub fn rotate_container_by(&mut self, delta_rad: f32) {
960 if delta_rad.is_finite() {
961 let next: f32 = self.get_virtual_roll_rad() + delta_rad;
962 self.set_virtual_roll_rad(next);
963 }
964 }
965
966 pub fn apply_shake_impulse(&mut self, ax: f32, ay: f32) {
974 if ax.is_finite() {
975 let next_x: f32 = (self.get_shake_accel_x() + ax)
976 .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
977 self.set_shake_accel_x(next_x);
978 }
979 if ay.is_finite() {
980 let next_y: f32 = (self.get_shake_accel_y() + ay)
981 .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
982 self.set_shake_accel_y(next_y);
983 }
984 }
985
986 pub fn apply_stir_impulse(&mut self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
996 if !norm_x.is_finite()
997 || !norm_y.is_finite()
998 || !vel_x_mps.is_finite()
999 || !vel_y_mps.is_finite()
1000 {
1001 return;
1002 }
1003 let config_spec: GyroLiquidConfig = self.get_config();
1004 let width_val: f32 = config_spec.get_vessel_width_m();
1005 let height_val: f32 = config_spec.get_vessel_height_m();
1006 let sx: f32 = norm_x.clamp(0.0, 1.0) * width_val;
1007 let sy: f32 = norm_y.clamp(0.0, 1.0) * height_val;
1008 let radius: f32 = (width_val.min(height_val) * FLUID_STIR_RADIUS_RATIO).max(0.012);
1009 let r2_max: f32 = radius * radius;
1010 let svx: f32 = vel_x_mps.clamp(-2.0, 2.0);
1011 let svy: f32 = vel_y_mps.clamp(-2.0, 2.0);
1012 let item_count: usize = self.get_particle_count();
1013 let Self {
1014 pos_x,
1015 pos_y,
1016 vel_x,
1017 vel_y,
1018 buoyant_bodies,
1019 buoyant_body_count,
1020 ..
1021 } = self;
1022 for item_index in 0..item_count {
1023 let dx: f32 = pos_x[item_index] - sx;
1024 let dy: f32 = pos_y[item_index] - sy;
1025 let d2: f32 = dx * dx + dy * dy;
1026 if d2 < r2_max {
1027 let falloff: f32 = 1.0 - (d2 / r2_max).sqrt();
1028 let gain: f32 = falloff * falloff * 0.52;
1029 vel_x[item_index] = (vel_x[item_index] + (svx - vel_x[item_index]) * gain)
1030 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1031 vel_y[item_index] = (vel_y[item_index] + (svy - vel_y[item_index]) * gain)
1032 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1033 }
1034 }
1035 let b_cnt: usize = *buoyant_body_count;
1036 for body in buoyant_bodies.iter_mut().take(b_cnt) {
1037 let dx: f32 = body.get_x() - sx;
1038 let dy: f32 = body.get_y() - sy;
1039 let d2: f32 = dx * dx + dy * dy;
1040 let br: f32 = radius + body.get_radius();
1041 if d2 < br * br {
1042 let falloff: f32 = 1.0 - (d2.sqrt() / br);
1043 let gain: f32 = falloff * 0.42;
1044 body.set_vx(body.get_vx() + (svx - body.get_vx()) * gain);
1045 body.set_vy(body.get_vy() + (svy - body.get_vy()) * gain);
1046 let torque_kick: f32 = (dx * svy - dy * svx) / (br * br + 1.0e-4);
1047 body.set_omega((body.get_omega() + torque_kick * 0.32).clamp(-14.0, 14.0));
1048 }
1049 }
1050 }
1051
1052 pub fn apply_device_motion(&mut self, sample: DeviceMotionSample, dt: f32) {
1060 let clean: DeviceMotionSample = sample.sanitized();
1061 let safe_dt: f32 = dt.clamp(1.0e-5, FLUID_MAX_STEP_DT);
1062 let raw_gx: f32 = clean.get_gravity_x();
1063 let raw_gy: f32 = clean.get_gravity_y();
1064 let raw_gz: f32 = clean.get_gravity_z();
1065 let cur_gx: f32 = self.get_gravity_x();
1066 let cur_gy: f32 = self.get_gravity_y();
1067 let cur_gz: f32 = self.get_gravity_z();
1068 let dg: f32 =
1069 ((raw_gx - cur_gx).powi(2) + (raw_gy - cur_gy).powi(2) + (raw_gz - cur_gz).powi(2))
1070 .sqrt();
1071 let g_blend: f32 = if dg <= FLUID_SENSOR_GRAVITY_DEADZONE_MPS2 {
1072 0.0
1073 } else if dg >= 1.25 {
1074 1.0
1075 } else {
1076 let base_blend: f32 = 1.0 - (-FLUID_SENSOR_GRAVITY_DAMP_HZ * safe_dt).exp();
1077 let ramp: f32 = ((dg - FLUID_SENSOR_GRAVITY_DEADZONE_MPS2)
1078 / (1.25 - FLUID_SENSOR_GRAVITY_DEADZONE_MPS2))
1079 .clamp(0.0, 1.0);
1080 base_blend + (1.0 - base_blend) * ramp
1081 };
1082 let gx: f32 = cur_gx + (raw_gx - cur_gx) * g_blend;
1083 let gy: f32 = cur_gy + (raw_gy - cur_gy) * g_blend;
1084 let gz: f32 = cur_gz + (raw_gz - cur_gz) * g_blend;
1085 let lx: f32 =
1086 fluid_sensor_deadzone(clean.get_linear_accel_x(), FLUID_SENSOR_LIN_DEADZONE_MPS2)
1087 .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
1088 let ly: f32 =
1089 fluid_sensor_deadzone(clean.get_linear_accel_y(), FLUID_SENSOR_LIN_DEADZONE_MPS2)
1090 .clamp(-FLUID_MAX_LINEAR_ACCEL_MPS2, FLUID_MAX_LINEAR_ACCEL_MPS2);
1091 let omega_cw: f32 =
1092 fluid_sensor_deadzone(-clean.get_gyro_z(), FLUID_SENSOR_GYRO_DEADZONE_RAD_S)
1093 .clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S);
1094 let prev_omega: f32 = self.get_angular_vel_cw();
1095 let smoothed_alpha: f32 = if omega_cw.abs() < 1.0e-5 && prev_omega.abs() < 1.0e-5 {
1096 self.get_angular_accel_cw() * 0.40
1097 } else {
1098 let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
1099 .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
1100 self.get_angular_accel_cw() * 0.65 + raw_alpha * 0.35
1101 };
1102 self.set_gravity_x(gx);
1103 self.set_gravity_y(gy);
1104 self.set_gravity_z(gz);
1105 self.set_linear_accel_x(lx);
1106 self.set_linear_accel_y(ly);
1107 self.set_prev_angular_vel_cw(prev_omega);
1108 self.set_angular_vel_cw(omega_cw);
1109 self.set_angular_accel_cw(if smoothed_alpha.abs() < 0.02 {
1110 0.0
1111 } else {
1112 smoothed_alpha
1113 });
1114 self.set_active_roll_rad(gx.atan2(gy));
1115 }
1116
1117 pub fn sync_virtual_motion(&mut self, dt: f32) {
1124 let safe_dt: f32 = dt.clamp(1.0e-5, FLUID_MAX_STEP_DT);
1125 let roll: f32 = self.get_virtual_roll_rad();
1126 let pitch: f32 = self.get_virtual_pitch_rad();
1127 let cos_p: f32 = pitch.cos();
1128 let gx: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.sin();
1129 let gy: f32 = STANDARD_GRAVITY_MPS2 * cos_p * roll.cos();
1130 let gz: f32 = -STANDARD_GRAVITY_MPS2 * pitch.sin();
1131 let prev_roll: f32 = self.get_prev_virtual_roll_rad();
1132 let mut d_roll: f32 = roll - prev_roll;
1133 while d_roll > PI {
1134 d_roll -= TAU;
1135 }
1136 while d_roll < -PI {
1137 d_roll += TAU;
1138 }
1139 let omega_cw: f32 = if d_roll.abs() < 1.0e-5 {
1140 0.0
1141 } else {
1142 (d_roll / safe_dt).clamp(-FLUID_MAX_OMEGA_RAD_S, FLUID_MAX_OMEGA_RAD_S)
1143 };
1144 let prev_omega: f32 = self.get_angular_vel_cw();
1145 let smoothed_alpha: f32 = if omega_cw.abs() < 1.0e-5 && prev_omega.abs() < 1.0e-5 {
1146 0.0
1147 } else {
1148 let raw_alpha: f32 = ((omega_cw - prev_omega) / safe_dt)
1149 .clamp(-FLUID_MAX_ALPHA_RAD_S2, FLUID_MAX_ALPHA_RAD_S2);
1150 self.get_angular_accel_cw() * 0.55 + raw_alpha * 0.45
1151 };
1152 self.set_prev_virtual_roll_rad(roll);
1153 self.set_gravity_x(gx);
1154 self.set_gravity_y(gy);
1155 self.set_gravity_z(gz);
1156 self.set_linear_accel_x(0.0);
1157 self.set_linear_accel_y(0.0);
1158 self.set_prev_angular_vel_cw(prev_omega);
1159 self.set_angular_vel_cw(omega_cw);
1160 self.set_angular_accel_cw(smoothed_alpha);
1161 self.set_active_roll_rad(roll);
1162 }
1163
1164 fn rebuild_spatial_grid(&mut self) {
1170 let item_count: usize = self.get_particle_count();
1171 let gw: usize = self.get_grid_w();
1172 let gh: usize = self.get_grid_h();
1173 let total_cells: usize = gw * gh;
1174 let inv_h: f32 = 1.0 / self.get_kernel_radius_m().max(1.0e-5);
1175 let max_cx: i32 = (gw as i32) - 1;
1176 let max_cy: i32 = (gh as i32) - 1;
1177 let Self {
1178 pred_x,
1179 pred_y,
1180 cell_counts,
1181 cell_starts,
1182 cell_cursors,
1183 particle_cells,
1184 sorted_indices,
1185 ..
1186 } = self;
1187 cell_counts[..total_cells].fill(0);
1188 for item_index in 0..item_count {
1189 let cx: i32 = ((pred_x[item_index] * inv_h).floor() as i32).clamp(0, max_cx);
1190 let cy: i32 = ((pred_y[item_index] * inv_h).floor() as i32).clamp(0, max_cy);
1191 let cid: usize = (cy as usize) * gw + (cx as usize);
1192 particle_cells[item_index] = cid as u32;
1193 cell_counts[cid] += 1;
1194 }
1195 let mut prefix: u32 = 0;
1196 for char_item in 0..total_cells {
1197 cell_starts[char_item] = prefix;
1198 cell_cursors[char_item] = prefix;
1199 prefix += cell_counts[char_item];
1200 }
1201 cell_starts[total_cells] = prefix;
1202 for (outer_index, &cell) in particle_cells.iter().enumerate().take(item_count) {
1203 let cid: usize = cell as usize;
1204 let dst: usize = cell_cursors[cid] as usize;
1205 cell_cursors[cid] = (dst as u32) + 1;
1206 sorted_indices[dst] = outer_index as u32;
1207 }
1208 }
1209
1210 #[must_use]
1222 fn sample_fluid_at(&self, qx: f32, qy: f32) -> (f32, f32, f32) {
1223 let height_val: f32 = self.get_kernel_radius_m();
1224 let h2: f32 = height_val * height_val;
1225 let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
1226 let gw: i32 = self.get_grid_w() as i32;
1227 let gh: i32 = self.get_grid_h() as i32;
1228 let poly6_c: f32 = self.get_poly6_coeff();
1229 let m_p: f32 = self.get_particle_mass_kgpm();
1230 let cx: i32 = ((qx * inv_h).floor() as i32).clamp(0, gw - 1);
1231 let cy: i32 = ((qy * inv_h).floor() as i32).clamp(0, gh - 1);
1232 let x0: i32 = (cx - 1).max(0);
1233 let x1: i32 = (cx + 1).min(gw - 1);
1234 let y0: i32 = (cy - 1).max(0);
1235 let y1: i32 = (cy + 1).min(gh - 1);
1236 let Self {
1237 pred_x,
1238 pred_y,
1239 vel_x,
1240 vel_y,
1241 cell_starts,
1242 sorted_indices,
1243 ..
1244 } = self;
1245 let mut rho: f32 = 0.0;
1246 let mut w_sum: f32 = 0.0;
1247 let mut u_sum: f32 = 0.0;
1248 let mut v_sum: f32 = 0.0;
1249 for ny in y0..=y1 {
1250 let row_off: usize = (ny as usize) * (gw as usize);
1251 for nx in x0..=x1 {
1252 let cid: usize = row_off + (nx as usize);
1253 let source_val: usize = cell_starts[cid] as usize;
1254 let event_ref: usize = cell_starts[cid + 1] as usize;
1255 for &raw_j in &sorted_indices[source_val..event_ref] {
1256 let inner_index: usize = raw_j as usize;
1257 let dx: f32 = qx - pred_x[inner_index];
1258 let dy: f32 = qy - pred_y[inner_index];
1259 let r2: f32 = dx * dx + dy * dy;
1260 if r2 < h2 {
1261 let w_val: f32 = poly6_2d(r2, h2, poly6_c);
1262 rho += m_p * w_val;
1263 w_sum += w_val;
1264 u_sum += w_val * vel_x[inner_index];
1265 v_sum += w_val * vel_y[inner_index];
1266 }
1267 }
1268 }
1269 }
1270 let inv_w: f32 = if w_sum > 1.0e-5 { 1.0 / w_sum } else { 0.0 };
1271 (rho / WATER_REST_DENSITY_KGM3, u_sum * inv_w, v_sum * inv_w)
1272 }
1273
1274 fn run_substep(&mut self, sub_dt: f32, rebuild_neighbors: bool) {
1282 let config_spec: GyroLiquidConfig = self.get_config();
1283 let item_count: usize = self.get_particle_count();
1284 let width_val: f32 = config_spec.get_vessel_width_m();
1285 let h_vessel: f32 = config_spec.get_vessel_height_m();
1286 let cx_tank: f32 = width_val * 0.5;
1287 let cy_tank: f32 = h_vessel * 0.5;
1288 let d0: f32 = self.get_rest_spacing_m();
1289 let pad: f32 = d0 * 0.52;
1290 let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
1291 let gx: f32 = self.get_gravity_x();
1292 let gy: f32 = self.get_gravity_y();
1293 let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
1294 let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
1295 let omega: f32 = self.get_angular_vel_cw();
1296 let omega2: f32 = omega * omega;
1297 let alpha: f32 = self.get_angular_accel_cw();
1298 let frame_calm: bool =
1299 lin_x.hypot(lin_y) < 0.05 && omega.abs() < 0.02 && alpha.abs() < 0.08;
1300 {
1301 let Self {
1302 pos_x,
1303 pos_y,
1304 pred_x,
1305 pred_y,
1306 vel_x,
1307 vel_y,
1308 ..
1309 } = self;
1310 for item_index in 0..item_count {
1311 let rx: f32 = pos_x[item_index] - cx_tank;
1312 let ry: f32 = pos_y[item_index] - cy_tank;
1313 let vx: f32 = vel_x[item_index];
1314 let vy: f32 = vel_y[item_index];
1315 let ax: f32 = gx - lin_x + omega2 * rx + alpha * ry + 2.0 * omega * vy;
1316 let ay: f32 = gy - lin_y + omega2 * ry - alpha * rx - 2.0 * omega * vx;
1317 let nvx: f32 = (vx + ax * sub_dt)
1318 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1319 let nvy: f32 = (vy + ay * sub_dt)
1320 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1321 vel_x[item_index] = nvx;
1322 vel_y[item_index] = nvy;
1323 let (px, py, _, _, _): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1324 pos_x[item_index] + nvx * sub_dt,
1325 pos_y[item_index] + nvy * sub_dt,
1326 width_val,
1327 h_vessel,
1328 pad,
1329 corner_r,
1330 );
1331 pred_x[item_index] = px;
1332 pred_y[item_index] = py;
1333 }
1334 }
1335 if rebuild_neighbors {
1336 self.rebuild_spatial_grid();
1337 }
1338 let height_val: f32 = self.get_kernel_radius_m();
1339 let h2: f32 = height_val * height_val;
1340 let inv_h: f32 = 1.0 / height_val.max(1.0e-5);
1341 let poly6_c: f32 = self.get_poly6_coeff();
1342 let spiky_c: f32 = self.get_spiky_grad_coeff();
1343 let inv_w_dq: f32 = 1.0 / self.get_w_dq().max(1.0e-6);
1344 let a_p: f32 = self.get_particle_area_m2();
1345 let m_p: f32 = self.get_particle_mass_kgpm();
1346 let cfm_eps: f32 = FLUID_CFM_RELAXATION_FACTOR / a_p.max(1.0e-9);
1347 let scorr_scale: f32 = -FLUID_SCORR_K * a_p;
1348 let lap_gain: f32 = FLUID_SURFACE_LAPLACIAN_GAIN * config_spec.get_surface_tension_scale();
1349 let meniscus_gain: f32 =
1350 FLUID_WALL_MENISCUS_STRENGTH * config_spec.get_surface_tension_scale();
1351 let gw: i32 = self.get_grid_w() as i32;
1352 let gh: i32 = self.get_grid_h() as i32;
1353 let gw_u: usize = gw as usize;
1354 let base_iters: u32 = config_spec.get_solver_iterations().clamp(2, 6);
1355 let iters: u32 = if frame_calm
1356 && self.get_sim_time_secs() > 0.6
1357 && self.get_kinetic_energy_mj() < 0.05
1358 && self.get_bubble_count() == 0
1359 {
1360 base_iters.min(2)
1361 } else {
1362 base_iters
1363 };
1364 let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1365 let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
1366 (-gx / g_mag, -gy / g_mag)
1367 } else {
1368 (0.0, -1.0)
1369 };
1370 let wall_meniscus_band: f32 = d0 * 1.35;
1371 let self_poly6: f32 = m_p * poly6_2d(0.0, h2, poly6_c);
1372 let inv_rho0: f32 = 1.0 / WATER_REST_DENSITY_KGM3;
1373 let ap_spiky_c: f32 = a_p * spiky_c;
1374 if rebuild_neighbors {
1375 let Self {
1376 pred_x,
1377 pred_y,
1378 cell_starts,
1379 sorted_indices,
1380 neighbor_indices,
1381 neighbor_counts,
1382 ..
1383 } = self;
1384 let search_r2: f32 = h2 * 1.04;
1385 for outer_index in 0..item_count {
1386 let xi: f32 = pred_x[outer_index];
1387 let yi: f32 = pred_y[outer_index];
1388 let cx: i32 = ((xi * inv_h).floor() as i32).clamp(0, gw - 1);
1389 let cy: i32 = ((yi * inv_h).floor() as i32).clamp(0, gh - 1);
1390 let x0: i32 = (cx - 1).max(0);
1391 let x1: i32 = (cx + 1).min(gw - 1);
1392 let y0: i32 = (cy - 1).max(0);
1393 let y1: i32 = (cy + 1).min(gh - 1);
1394 let base: usize = outer_index * FLUID_MAX_NEIGHBORS;
1395 let mut count: usize = 0;
1396 for ny in y0..=y1 {
1397 let row_off: usize = (ny as usize) * gw_u;
1398 for nx in x0..=x1 {
1399 let cid: usize = row_off + (nx as usize);
1400 let source_val: usize = cell_starts[cid] as usize;
1401 let event_ref: usize = cell_starts[cid + 1] as usize;
1402 for &raw_j in &sorted_indices[source_val..event_ref] {
1403 let inner_index: usize = raw_j as usize;
1404 if outer_index == inner_index {
1405 continue;
1406 }
1407 let dx: f32 = xi - pred_x[inner_index];
1408 let dy: f32 = yi - pred_y[inner_index];
1409 if dx * dx + dy * dy < search_r2 {
1410 neighbor_indices[base + count] = inner_index as u16;
1411 count += 1;
1412 if count == FLUID_MAX_NEIGHBORS {
1413 break;
1414 }
1415 }
1416 }
1417 if count == FLUID_MAX_NEIGHBORS {
1418 break;
1419 }
1420 }
1421 if count == FLUID_MAX_NEIGHBORS {
1422 break;
1423 }
1424 }
1425 neighbor_counts[outer_index] = count as u8;
1426 }
1427 }
1428 for iter_idx in 0..iters {
1429 let Self {
1430 pred_x,
1431 pred_y,
1432 lambda,
1433 density,
1434 corr_x,
1435 corr_y,
1436 neighbor_indices,
1437 neighbor_counts,
1438 neighbor_w,
1439 neighbor_gf,
1440 buoyant_bodies,
1441 buoyant_body_count,
1442 ..
1443 } = self;
1444 let mut max_c_val: f32 = 0.0;
1445 for step_index in 0..item_count {
1446 let xi: f32 = pred_x[step_index];
1447 let yi: f32 = pred_y[step_index];
1448 let base: usize = step_index * FLUID_MAX_NEIGHBORS;
1449 let cnt: usize = neighbor_counts[step_index] as usize;
1450 let mut rho: f32 = self_poly6;
1451 let mut grad_ix: f32 = 0.0;
1452 let mut grad_iy: f32 = 0.0;
1453 let mut sum_grad_sq: f32 = 0.0;
1454 for local_k in 0..cnt {
1455 let slot: usize = base + local_k;
1456 let col_index: usize = neighbor_indices[slot] as usize;
1457 let dx: f32 = xi - pred_x[col_index];
1458 let dy: f32 = yi - pred_y[col_index];
1459 let r2: f32 = dx * dx + dy * dy;
1460 if r2 < h2 {
1461 let diff_h2: f32 = h2 - r2;
1462 let w_val: f32 = poly6_c * diff_h2 * diff_h2 * diff_h2;
1463 rho += m_p * w_val;
1464 neighbor_w[slot] = w_val;
1465 if r2 > 1.0e-12 {
1466 let r_val: f32 = r2.sqrt();
1467 let h_minus_r: f32 = height_val - r_val;
1468 let gf: f32 = ap_spiky_c * h_minus_r * h_minus_r / r_val;
1469 neighbor_gf[slot] = gf;
1470 let gx_ij: f32 = gf * dx;
1471 let gy_ij: f32 = gf * dy;
1472 grad_ix += gx_ij;
1473 grad_iy += gy_ij;
1474 sum_grad_sq += gx_ij * gx_ij + gy_ij * gy_ij;
1475 } else {
1476 neighbor_gf[slot] = 0.0;
1477 }
1478 } else {
1479 neighbor_w[slot] = 0.0;
1480 neighbor_gf[slot] = 0.0;
1481 }
1482 }
1483 density[step_index] = rho;
1484 let c_val: f32 = (rho * inv_rho0 - 1.0).max(0.0);
1485 if c_val > max_c_val {
1486 max_c_val = c_val;
1487 }
1488 sum_grad_sq += grad_ix * grad_ix + grad_iy * grad_iy;
1489 lambda[step_index] = if c_val > 0.0 {
1490 -c_val / (sum_grad_sq + cfm_eps)
1491 } else {
1492 0.0
1493 };
1494 }
1495 let max_disp: f32 = d0 * 0.42;
1496 let max_disp2: f32 = max_disp * max_disp;
1497 for cursor_index in 0..item_count {
1498 let xi: f32 = pred_x[cursor_index];
1499 let yi: f32 = pred_y[cursor_index];
1500 let lam_i: f32 = lambda[cursor_index];
1501 let is_surface: bool = density[cursor_index] < WATER_REST_DENSITY_KGM3 * 0.86;
1502 let base: usize = cursor_index * FLUID_MAX_NEIGHBORS;
1503 let cnt: usize = neighbor_counts[cursor_index] as usize;
1504 let mut dpx: f32 = 0.0;
1505 let mut dpy: f32 = 0.0;
1506 let mut lap_x: f32 = 0.0;
1507 let mut lap_y: f32 = 0.0;
1508 let mut lap_w: f32 = 0.0;
1509 for local_k in 0..cnt {
1510 let slot: usize = base + local_k;
1511 let w_r: f32 = neighbor_w[slot];
1512 if w_r > 0.0 {
1513 let sub_index: usize = neighbor_indices[slot] as usize;
1514 let dx: f32 = xi - pred_x[sub_index];
1515 let dy: f32 = yi - pred_y[sub_index];
1516 let gf: f32 = neighbor_gf[slot];
1517 if gf != 0.0 {
1518 let ratio: f32 = w_r * inv_w_dq;
1519 let ratio2: f32 = ratio * ratio;
1520 let s_corr: f32 = scorr_scale * ratio2 * ratio2;
1521 let pressure_mag: f32 = (lam_i + lambda[sub_index] + s_corr) * gf;
1522 dpx += pressure_mag * dx;
1523 dpy += pressure_mag * dy;
1524 }
1525 if is_surface && lap_gain > 0.0 {
1526 lap_x -= dx * w_r;
1527 lap_y -= dy * w_r;
1528 lap_w += w_r;
1529 }
1530 }
1531 }
1532 if is_surface && lap_w > 1.0e-5 {
1533 let inv_lw: f32 = 1.0 / lap_w;
1534 let cx_shift: f32 = lap_x * inv_lw;
1535 let cy_shift: f32 = lap_y * inv_lw;
1536 let tan_x: f32 = -up_y;
1537 let tan_y: f32 = up_x;
1538 let proj_tan: f32 = cx_shift * tan_x + cy_shift * tan_y;
1539 let proj_up: f32 = (cx_shift * up_x + cy_shift * up_y).min(0.0);
1540 dpx += (tan_x * proj_tan * 0.45 + up_x * proj_up) * lap_gain;
1541 dpy += (tan_y * proj_tan * 0.45 + up_y * proj_up) * lap_gain;
1542 }
1543 if is_surface && meniscus_gain > 0.0 && !frame_calm {
1544 let near_left: bool = xi - pad < wall_meniscus_band;
1545 let near_right: bool = (width_val - pad) - xi < wall_meniscus_band;
1546 let near_top: bool = yi - pad < wall_meniscus_band;
1547 let near_bottom: bool = (h_vessel - pad) - yi < wall_meniscus_band;
1548 if near_left || near_right {
1549 dpy += up_y * meniscus_gain;
1550 }
1551 if near_top || near_bottom {
1552 dpx += up_x * meniscus_gain;
1553 }
1554 }
1555 let disp2: f32 = dpx * dpx + dpy * dpy;
1556 if disp2 > max_disp2 {
1557 let scale: f32 = max_disp / disp2.sqrt();
1558 dpx *= scale;
1559 dpy *= scale;
1560 }
1561 corr_x[cursor_index] = dpx;
1562 corr_y[cursor_index] = dpy;
1563 }
1564 let b_cnt: usize = *buoyant_body_count;
1565 for item_index_primary in 0..item_count {
1566 let mut nx: f32 = pred_x[item_index_primary] + corr_x[item_index_primary];
1567 let mut ny: f32 = pred_y[item_index_primary] + corr_y[item_index_primary];
1568 for body in buoyant_bodies.iter().take(b_cnt) {
1569 let dx: f32 = nx - body.get_x();
1570 let dy: f32 = ny - body.get_y();
1571 let min_dist: f32 = body.get_radius() + d0 * 0.36;
1572 let d2: f32 = dx * dx + dy * dy;
1573 if d2 < min_dist * min_dist {
1574 if d2 > 1.0e-12 {
1575 let dist: f32 = d2.sqrt();
1576 let push: f32 = (min_dist - dist) * 0.65 / dist;
1577 nx += dx * push;
1578 ny += dy * push;
1579 } else {
1580 nx += min_dist * 0.5;
1581 }
1582 }
1583 }
1584 let (cx, cy, _, _, _): (f32, f32, f32, f32, bool) =
1585 clamp_to_rounded_vessel(nx, ny, width_val, h_vessel, pad, corner_r);
1586 pred_x[item_index_primary] = cx;
1587 pred_y[item_index_primary] = cy;
1588 }
1589 if iter_idx >= 1 && max_c_val < 0.015 {
1590 break;
1591 }
1592 }
1593 let inv_sub_dt: f32 = 1.0 / sub_dt.max(1.0e-5);
1594 let visc_scale: f32 = config_spec.get_viscosity_scale();
1595 let xsph_c: f32 = (FLUID_BASE_XSPH_COEFF * visc_scale).clamp(0.012, 0.32);
1596 let surf_xsph_c: f32 = (xsph_c + FLUID_SURFACE_XSPH_BOOST).clamp(0.04, 0.38);
1597 let base_damp: f32 = (-sub_dt * FLUID_VISCOUS_DAMP_PER_SEC * visc_scale.sqrt()).exp();
1598 let settle_damp: f32 = (-sub_dt * FLUID_REST_SETTLE_DAMP_PER_SEC).exp();
1599 let vort_min_spd2: f32 = FLUID_VORTICITY_MIN_SPEED_MPS * FLUID_VORTICITY_MIN_SPEED_MPS;
1600 let creep_eps: f32 = if frame_calm { d0 * 0.0045 } else { 0.0 };
1601 let creep_eps2: f32 = creep_eps * creep_eps;
1602 let mut max_spd2: f32 = 0.0;
1603 {
1604 let Self {
1605 pos_x,
1606 pos_y,
1607 pred_x,
1608 pred_y,
1609 vel_x,
1610 vel_y,
1611 density,
1612 vorticity,
1613 dvx_scratch,
1614 dvy_scratch,
1615 neighbor_indices,
1616 neighbor_counts,
1617 ..
1618 } = self;
1619 for item_index_secondary in 0..item_count {
1620 let mut dx_step: f32 = pred_x[item_index_secondary] - pos_x[item_index_secondary];
1621 let mut dy_step: f32 = pred_y[item_index_secondary] - pos_y[item_index_secondary];
1622 if creep_eps2 > 0.0 && dx_step * dx_step + dy_step * dy_step <= creep_eps2 {
1623 dx_step = 0.0;
1624 dy_step = 0.0;
1625 pred_x[item_index_secondary] = pos_x[item_index_secondary];
1626 pred_y[item_index_secondary] = pos_y[item_index_secondary];
1627 }
1628 let mut vx: f32 = (dx_step * inv_sub_dt)
1629 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1630 let mut vy: f32 = (dy_step * inv_sub_dt)
1631 .clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1632 let (_, _, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1633 pred_x[item_index_secondary],
1634 pred_y[item_index_secondary],
1635 width_val,
1636 h_vessel,
1637 pad + 1.0e-5,
1638 corner_r,
1639 );
1640 if hit {
1641 let vn: f32 = vx * wn_x + vy * wn_y;
1642 if vn < 0.0 {
1643 let tx: f32 = -wn_y;
1644 let ty: f32 = wn_x;
1645 let vt: f32 = (vx * tx + vy * ty) * FLUID_WALL_TANGENTIAL_KEEP;
1646 let vn_out: f32 = if vn < -0.22 {
1647 -vn * FLUID_WALL_RESTITUTION
1648 } else {
1649 0.0
1650 };
1651 vx = tx * vt + wn_x * vn_out;
1652 vy = ty * vt + wn_y * vn_out;
1653 }
1654 }
1655 let spd2: f32 = vx * vx + vy * vy;
1656 if spd2 > max_spd2 {
1657 max_spd2 = spd2;
1658 }
1659 vel_x[item_index_secondary] = vx;
1660 vel_y[item_index_secondary] = vy;
1661 }
1662 let any_fast_vort: bool = max_spd2 > vort_min_spd2;
1663 for item_index_next in 0..item_count {
1664 let xi: f32 = pred_x[item_index_next];
1665 let yi: f32 = pred_y[item_index_next];
1666 let vxi: f32 = vel_x[item_index_next];
1667 let vyi: f32 = vel_y[item_index_next];
1668 let is_surface: bool = density[item_index_next] < WATER_REST_DENSITY_KGM3 * 0.88;
1669 let need_curl: bool = any_fast_vort && !is_surface;
1670 let base: usize = item_index_next * FLUID_MAX_NEIGHBORS;
1671 let cnt: usize = neighbor_counts[item_index_next] as usize;
1672 let mut curl: f32 = 0.0;
1673 let mut xsph_x: f32 = 0.0;
1674 let mut xsph_y: f32 = 0.0;
1675 for &raw_j in &neighbor_indices[base..(base + cnt)] {
1676 let peer_index: usize = raw_j as usize;
1677 let dx: f32 = xi - pred_x[peer_index];
1678 let dy: f32 = yi - pred_y[peer_index];
1679 let r2: f32 = dx * dx + dy * dy;
1680 if r2 < h2 && r2 > 1.0e-12 {
1681 let dvx: f32 = vel_x[peer_index] - vxi;
1682 let dvy: f32 = vel_y[peer_index] - vyi;
1683 let w_val: f32 = poly6_2d(r2, h2, poly6_c);
1684 let rho_j: f32 = density[peer_index].max(WATER_REST_DENSITY_KGM3 * 0.50);
1685 let weight: f32 = (m_p / rho_j) * w_val;
1686 xsph_x += dvx * weight;
1687 xsph_y += dvy * weight;
1688 if need_curl {
1689 let rect_val: f32 = r2.sqrt();
1690 let gf: f32 = a_p * spiky_grad_factor_2d(rect_val, height_val, spiky_c);
1691 curl += dvx * (gf * dy) - dvy * (gf * dx);
1692 }
1693 }
1694 }
1695 vorticity[item_index_next] = curl;
1696 let eff_xsph: f32 = if is_surface { surf_xsph_c } else { xsph_c };
1697 dvx_scratch[item_index_next] = eff_xsph * xsph_x;
1698 dvy_scratch[item_index_next] = eff_xsph * xsph_y;
1699 }
1700 for item_index_alt in 0..item_count {
1701 let vxi: f32 = vel_x[item_index_alt];
1702 let vyi: f32 = vel_y[item_index_alt];
1703 let spd2: f32 = vxi * vxi + vyi * vyi;
1704 let allow_vort: bool = any_fast_vort
1705 && density[item_index_alt] >= WATER_REST_DENSITY_KGM3 * 0.88
1706 && spd2 > vort_min_spd2;
1707 let (vort_fx, vort_fy): (f32, f32) = if allow_vort {
1708 let xi: f32 = pred_x[item_index_alt];
1709 let yi: f32 = pred_y[item_index_alt];
1710 let wi: f32 = vorticity[item_index_alt];
1711 let base: usize = item_index_alt * FLUID_MAX_NEIGHBORS;
1712 let cnt: usize = neighbor_counts[item_index_alt] as usize;
1713 let mut eta_x: f32 = 0.0;
1714 let mut eta_y: f32 = 0.0;
1715 for &raw_j in &neighbor_indices[base..(base + cnt)] {
1716 let inner_index_primary: usize = raw_j as usize;
1717 let dx: f32 = xi - pred_x[inner_index_primary];
1718 let dy: f32 = yi - pred_y[inner_index_primary];
1719 let r2: f32 = dx * dx + dy * dy;
1720 if r2 < h2 && r2 > 1.0e-12 {
1721 let row_val: f32 = r2.sqrt();
1722 let gf: f32 = a_p * spiky_grad_factor_2d(row_val, height_val, spiky_c);
1723 let abs_wj: f32 = vorticity[inner_index_primary].abs();
1724 eta_x += abs_wj * gf * dx;
1725 eta_y += abs_wj * gf * dy;
1726 }
1727 }
1728 let eta_mag: f32 = (eta_x * eta_x + eta_y * eta_y).sqrt();
1729 if eta_mag > 1.0e-4 {
1730 let inv_eta: f32 = 1.0 / eta_mag;
1731 let nx_v: f32 = eta_x * inv_eta;
1732 let ny_v: f32 = eta_y * inv_eta;
1733 (
1734 ny_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1735 -nx_v * wi * FLUID_VORTICITY_EPSILON * sub_dt,
1736 )
1737 } else {
1738 (0.0, 0.0)
1739 }
1740 } else {
1741 (0.0, 0.0)
1742 };
1743 let damp: f32 = if frame_calm && spd2 < 0.0020 {
1744 base_damp * settle_damp
1745 } else {
1746 base_damp
1747 };
1748 let mut out_vx: f32 = (vxi + dvx_scratch[item_index_alt] + vort_fx) * damp;
1749 let mut out_vy: f32 = (vyi + dvy_scratch[item_index_alt] + vort_fy) * damp;
1750 if frame_calm && (out_vx * out_vx + out_vy * out_vy) < 1.0e-6 {
1751 out_vx = 0.0;
1752 out_vy = 0.0;
1753 }
1754 vel_x[item_index_alt] =
1755 out_vx.clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1756 vel_y[item_index_alt] =
1757 out_vy.clamp(-FLUID_MAX_PARTICLE_SPEED_MPS, FLUID_MAX_PARTICLE_SPEED_MPS);
1758 pos_x[item_index_alt] = pred_x[item_index_alt];
1759 pos_y[item_index_alt] = pred_y[item_index_alt];
1760 }
1761 }
1762 self.set_last_max_speed_mps(max_spd2.sqrt());
1763 self.step_buoyant_bodies(sub_dt);
1764 }
1765
1766 fn step_buoyant_bodies(&mut self, sub_dt: f32) {
1773 let b_cnt: usize = self.get_buoyant_body_count();
1774 if b_cnt == 0 {
1775 return;
1776 }
1777 let config_spec: GyroLiquidConfig = self.get_config();
1778 let width_val: f32 = config_spec.get_vessel_width_m();
1779 let h_vessel: f32 = config_spec.get_vessel_height_m();
1780 let cx_tank: f32 = width_val * 0.5;
1781 let cy_tank: f32 = h_vessel * 0.5;
1782 let corner_r: f32 = width_val.min(h_vessel) * FLUID_CORNER_RADIUS_RATIO;
1783 let gx: f32 = self.get_gravity_x();
1784 let gy: f32 = self.get_gravity_y();
1785 let lin_x: f32 = self.get_linear_accel_x() + self.get_shake_accel_x();
1786 let lin_y: f32 = self.get_linear_accel_y() + self.get_shake_accel_y();
1787 let omega_frame: f32 = self.get_angular_vel_cw();
1788 let omega2: f32 = omega_frame * omega_frame;
1789 let alpha_frame: f32 = self.get_angular_accel_cw();
1790 let frame_calm: bool =
1791 lin_x.hypot(lin_y) < 0.05 && omega_frame.abs() < 0.02 && alpha_frame.abs() < 0.08;
1792 let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1793 let (gx_hat, gy_hat): (f32, f32) = if g_mag > 0.25 {
1794 (gx / g_mag, gy / g_mag)
1795 } else {
1796 (0.0, 1.0)
1797 };
1798 let mut updated: [BuoyantBody; FLUID_MAX_BUOYANT_BODIES] =
1799 [BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES];
1800 let mut fluid_probes: [(f32, f32, f32, f32); FLUID_MAX_BUOYANT_BODIES] =
1801 [(0.0, 0.0, 0.0, 0.0); FLUID_MAX_BUOYANT_BODIES];
1802 for idx in 0..b_cnt {
1803 let body: BuoyantBody = self.get_buoyant_bodies()[idx];
1804 updated[idx] = body;
1805 let bx: f32 = body.get_x();
1806 let by: f32 = body.get_y();
1807 let br: f32 = body.get_radius();
1808 let probe_r: f32 = br + self.get_kernel_radius_m() * 0.52;
1809 let mut sub_sum: f32 = 0.0;
1810 let mut u_sum: f32 = 0.0;
1811 let mut v_sum: f32 = 0.0;
1812 let mut torque_sum: f32 = 0.0;
1813 let mut sub_weight_sum: f32 = 0.0;
1814 let sample_offsets: [(f32, f32); 8] = [
1815 (probe_r, 0.0),
1816 (-probe_r, 0.0),
1817 (0.0, probe_r),
1818 (0.0, -probe_r),
1819 (probe_r * 0.707, probe_r * 0.707),
1820 (-probe_r * 0.707, probe_r * 0.707),
1821 (probe_r * 0.707, -probe_r * 0.707),
1822 (-probe_r * 0.707, -probe_r * 0.707),
1823 ];
1824 for (ox, oy) in sample_offsets {
1825 let qx: f32 = (bx + ox).clamp(0.001, width_val - 0.001);
1826 let qy: f32 = (by + oy).clamp(0.001, h_vessel - 0.001);
1827 let (rho_ratio, fu, fv): (f32, f32, f32) = self.sample_fluid_at(qx, qy);
1828 let occ: f32 = ((rho_ratio - 0.14) / 0.42).clamp(0.0, 1.0);
1829 sub_sum += occ;
1830 if occ > 0.01 {
1831 u_sum += fu * occ;
1832 v_sum += fv * occ;
1833 sub_weight_sum += occ;
1834 let f_buoy_x: f32 = -gx_hat * occ;
1835 let f_buoy_y: f32 = -gy_hat * occ;
1836 torque_sum += ox * f_buoy_y - oy * f_buoy_x;
1837 let rel_u: f32 = fu - body.get_vx();
1838 let rel_v: f32 = fv - body.get_vy();
1839 torque_sum += (ox * rel_v - oy * rel_u) * occ * 0.35;
1840 }
1841 }
1842 let f_sub: f32 = (sub_sum / 8.0).clamp(0.0, 1.0);
1843 let (fu_avg, fv_avg): (f32, f32) = if sub_weight_sum > 1.0e-4 {
1844 (u_sum / sub_weight_sum, v_sum / sub_weight_sum)
1845 } else {
1846 (0.0, 0.0)
1847 };
1848 fluid_probes[idx] = (f_sub, fu_avg, fv_avg, torque_sum / (br + 1.0e-4));
1849 }
1850 for idx in 0..b_cnt {
1851 let body: &mut BuoyantBody = &mut updated[idx];
1852 let (f_sub, fu_avg, fv_avg, torque_acc): (f32, f32, f32, f32) = fluid_probes[idx];
1853 let rx: f32 = body.get_x() - cx_tank;
1854 let ry: f32 = body.get_y() - cy_tank;
1855 let vx: f32 = body.get_vx();
1856 let vy: f32 = body.get_vy();
1857 let eff_gx: f32 = gx - lin_x + omega2 * rx + alpha_frame * ry + 2.0 * omega_frame * vy;
1858 let eff_gy: f32 = gy - lin_y + omega2 * ry - alpha_frame * rx - 2.0 * omega_frame * vx;
1859 let rho_body: f32 = body.get_density_kgm3().max(100.0);
1860 let added_mass_rho: f32 = 0.5 * f_sub * WATER_REST_DENSITY_KGM3;
1861 let eff_inertia_rho: f32 = rho_body + added_mass_rho;
1862 let net_buoy_factor: f32 =
1863 (rho_body - f_sub * WATER_REST_DENSITY_KGM3) / eff_inertia_rho;
1864 let ax_net: f32 = eff_gx * net_buoy_factor;
1865 let ay_net: f32 = eff_gy * net_buoy_factor;
1866 let rel_x: f32 = fu_avg - vx;
1867 let rel_y: f32 = fv_avg - vy;
1868 let drag_coeff: f32 = 1.1 + f_sub * (7.5 * config_spec.get_viscosity_scale().sqrt());
1869 let mut nvx: f32 = vx + (ax_net + rel_x * drag_coeff) * sub_dt;
1870 let mut nvy: f32 = vy + (ay_net + rel_y * drag_coeff) * sub_dt;
1871 if frame_calm && nvx.hypot(nvy) < 0.018 && ax_net.hypot(ay_net) < 0.45 {
1872 let calm_body_damp: f32 = (-sub_dt * 6.0).exp();
1873 nvx *= calm_body_damp;
1874 nvy *= calm_body_damp;
1875 }
1876 nvx = nvx.clamp(-2.0, 2.0);
1877 nvy = nvy.clamp(-2.0, 2.0);
1878 let br: f32 = body.get_radius();
1879 let (cx, cy, wn_x, wn_y, hit): (f32, f32, f32, f32, bool) = clamp_to_rounded_vessel(
1880 body.get_x() + nvx * sub_dt,
1881 body.get_y() + nvy * sub_dt,
1882 width_val,
1883 h_vessel,
1884 br * 1.04,
1885 corner_r,
1886 );
1887 if hit {
1888 let vn: f32 = nvx * wn_x + nvy * wn_y;
1889 if vn < 0.0 {
1890 nvx -= 1.25 * vn * wn_x;
1891 nvy -= 1.25 * vn * wn_y;
1892 }
1893 }
1894 let ang_damp: f32 = (-sub_dt * (1.8 + f_sub * 5.2)).exp();
1895 let mut next_omega: f32 =
1896 ((body.get_omega() + torque_acc * sub_dt * 1.5) * ang_damp).clamp(-14.0, 14.0);
1897 if frame_calm && next_omega.abs() < 0.03 {
1898 next_omega = 0.0;
1899 }
1900 body.set_x(cx);
1901 body.set_y(cy);
1902 body.set_vx(nvx);
1903 body.set_vy(nvy);
1904 body.set_omega(next_omega);
1905 body.set_angle(body.get_angle() + next_omega * sub_dt);
1906 body.set_submerged_fraction(f_sub);
1907 }
1908 for item_index in 0..b_cnt {
1909 for inner_index in (item_index + 1)..b_cnt {
1910 let dx: f32 = updated[inner_index].get_x() - updated[item_index].get_x();
1911 let dy: f32 = updated[inner_index].get_y() - updated[item_index].get_y();
1912 let min_d: f32 =
1913 updated[item_index].get_radius() + updated[inner_index].get_radius();
1914 let d2: f32 = dx * dx + dy * dy;
1915 if d2 < min_d * min_d && d2 > 1.0e-12 {
1916 let dist: f32 = d2.sqrt();
1917 let nx: f32 = dx / dist;
1918 let ny: f32 = dy / dist;
1919 let pen: f32 = (min_d - dist) * 0.5;
1920 updated[item_index].set_x(updated[item_index].get_x() - nx * pen);
1921 updated[item_index].set_y(updated[item_index].get_y() - ny * pen);
1922 updated[inner_index].set_x(updated[inner_index].get_x() + nx * pen);
1923 updated[inner_index].set_y(updated[inner_index].get_y() + ny * pen);
1924 let rvx: f32 = updated[inner_index].get_vx() - updated[item_index].get_vx();
1925 let rvy: f32 = updated[inner_index].get_vy() - updated[item_index].get_vy();
1926 let rel_n: f32 = rvx * nx + rvy * ny;
1927 if rel_n < 0.0 {
1928 let imp: f32 = -0.65 * rel_n;
1929 updated[item_index].set_vx(updated[item_index].get_vx() - nx * imp);
1930 updated[item_index].set_vy(updated[item_index].get_vy() - ny * imp);
1931 updated[inner_index].set_vx(updated[inner_index].get_vx() + nx * imp);
1932 updated[inner_index].set_vy(updated[inner_index].get_vy() + ny * imp);
1933 }
1934 }
1935 }
1936 }
1937 self.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&updated[..b_cnt]);
1938 }
1939
1940 fn step_bubbles_and_foam(&mut self, dt: f32) {
1947 let config_spec: GyroLiquidConfig = self.get_config();
1948 let width_val: f32 = config_spec.get_vessel_width_m();
1949 let h_vessel: f32 = config_spec.get_vessel_height_m();
1950 let d0: f32 = self.get_rest_spacing_m();
1951 let gx: f32 = self.get_gravity_x();
1952 let gy: f32 = self.get_gravity_y();
1953 let g_mag: f32 = (gx * gx + gy * gy).sqrt();
1954 let (rise_x, rise_y): (f32, f32) = if g_mag > 0.25 {
1955 (-gx / g_mag, -gy / g_mag)
1956 } else {
1957 (0.0, -1.0)
1958 };
1959 let mut active: usize = self.get_bubble_count();
1960 let mut item_index: usize = 0;
1961 while item_index < active {
1962 let bub: FluidBubble = self.get_bubbles()[item_index];
1963 let next_age: f32 = bub.get_age() + dt;
1964 if next_age >= bub.get_lifetime() {
1965 active -= 1;
1966 let last: FluidBubble = self.get_bubbles()[active];
1967 self.get_mut_bubbles()[item_index] = last;
1968 continue;
1969 }
1970 let (rho_ratio, fu, fv): (f32, f32, f32) =
1971 self.sample_fluid_at(bub.get_x(), bub.get_y());
1972 let in_water: bool = rho_ratio > 0.34;
1973 let (nvx, nvy, next_foam): (f32, f32, f32) = if in_water {
1974 let target_vx: f32 = fu + rise_x * FLUID_BUBBLE_RISE_SPEED_MPS;
1975 let target_vy: f32 = fv + rise_y * FLUID_BUBBLE_RISE_SPEED_MPS;
1976 let blend: f32 = (dt * 7.0).min(1.0);
1977 (
1978 bub.get_vx() + (target_vx - bub.get_vx()) * blend,
1979 bub.get_vy() + (target_vy - bub.get_vy()) * blend,
1980 (bub.get_foam_factor() * 0.94).max(0.0),
1981 )
1982 } else {
1983 let decay: f32 = (-dt * 4.5).exp();
1984 (
1985 bub.get_vx() * decay + fu * 0.2,
1986 bub.get_vy() * decay + fv * 0.2,
1987 (bub.get_foam_factor() + dt * 2.4).min(1.0),
1988 )
1989 };
1990 let nx: f32 = (bub.get_x() + nvx * dt).clamp(d0 * 0.5, width_val - d0 * 0.5);
1991 let ny: f32 = (bub.get_y() + nvy * dt).clamp(d0 * 0.5, h_vessel - d0 * 0.5);
1992 let mut updated_bub: FluidBubble = bub;
1993 updated_bub.set_x(nx);
1994 updated_bub.set_y(ny);
1995 updated_bub.set_vx(nvx);
1996 updated_bub.set_vy(nvy);
1997 updated_bub.set_age(next_age);
1998 updated_bub.set_foam_factor(next_foam);
1999 self.get_mut_bubbles()[item_index] = updated_bub;
2000 item_index += 1;
2001 }
2002 let item_count: usize = self.get_particle_count();
2003 let mut rng: u64 = self.get_rng_state();
2004 let mut spawned: usize = 0;
2005 let max_spawn_per_step: usize = 6;
2006 let speed_thresh2: f32 = FLUID_FOAM_SPEED_THRESHOLD_MPS * FLUID_FOAM_SPEED_THRESHOLD_MPS;
2007 let Self {
2008 pos_x,
2009 pos_y,
2010 vel_x,
2011 vel_y,
2012 density,
2013 vorticity,
2014 bubbles,
2015 ..
2016 } = self;
2017 for idx in (0..item_count).step_by(3) {
2018 if active >= FLUID_MAX_BUBBLES || spawned >= max_spawn_per_step {
2019 break;
2020 }
2021 let spd2: f32 = vel_x[idx] * vel_x[idx] + vel_y[idx] * vel_y[idx];
2022 let near_surface: bool = density[idx] < WATER_REST_DENSITY_KGM3 * 0.84;
2023 let high_vort: bool = vorticity[idx].abs() > 16.0;
2024 if spd2 > speed_thresh2 && (near_surface || high_vort) {
2025 let r_roll: f32 = fluid_next_rand_f32(&mut rng);
2026 if r_roll < 0.24 {
2027 let jitter_x: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.7;
2028 let jitter_y: f32 = (fluid_next_rand_f32(&mut rng) - 0.5) * d0 * 0.7;
2029 let rad: f32 = d0 * (0.26 + fluid_next_rand_f32(&mut rng) * 0.36);
2030 let life: f32 = 0.55 + fluid_next_rand_f32(&mut rng) * 0.95;
2031 let foam_val: f32 = if near_surface { 0.82 } else { 0.12 };
2032 bubbles[active] = FluidBubble::spawn(
2033 [
2034 (pos_x[idx] + jitter_x).clamp(d0 * 0.5, width_val - d0 * 0.5),
2035 (pos_y[idx] + jitter_y).clamp(d0 * 0.5, h_vessel - d0 * 0.5),
2036 ],
2037 [vel_x[idx] * 0.6, vel_y[idx] * 0.6],
2038 rad,
2039 life,
2040 foam_val,
2041 );
2042 active += 1;
2043 spawned += 1;
2044 }
2045 }
2046 }
2047 self.set_rng_state(rng);
2048 self.set_bubble_count(active);
2049 }
2050
2051 pub fn step(&mut self, dt: f32) {
2058 if !dt.is_finite() || dt <= 0.0 {
2059 return;
2060 }
2061 let clamped_dt: f32 = dt.clamp(1.0e-5, FLUID_MAX_STEP_DT);
2062 let base_substeps: u32 = self.get_config().get_substeps().clamp(2, 4);
2063 let lin_mag: f32 = (self.get_linear_accel_x() + self.get_shake_accel_x())
2064 .hypot(self.get_linear_accel_y() + self.get_shake_accel_y());
2065 let gx: f32 = self.get_gravity_x();
2066 let gy: f32 = self.get_gravity_y();
2067 let gravity_changed: bool = (gx - self.get_settled_gravity_x()).abs() > 0.02
2068 || (gy - self.get_settled_gravity_y()).abs() > 0.02;
2069 let b_cnt: usize = self.get_buoyant_body_count();
2070 let mut bodies_settled: bool = true;
2071 for body in self.get_buoyant_bodies().iter().take(b_cnt) {
2072 let target_sub: f32 =
2073 (body.get_density_kgm3() / WATER_REST_DENSITY_KGM3).clamp(0.1, 0.95);
2074 let sub_err: f32 = (body.get_submerged_fraction() - target_sub).abs();
2075 if body.get_vx().abs() + body.get_vy().abs() >= 0.012
2076 || body.get_omega().abs() >= 0.03
2077 || sub_err > 0.14
2078 {
2079 bodies_settled = false;
2080 break;
2081 }
2082 }
2083 let is_settled_rest: bool = self.get_sim_time_secs() > 0.5
2084 && self.get_kinetic_energy_mj() < 0.02
2085 && self.get_last_max_speed_mps() < 0.025
2086 && self.get_bubble_count() == 0
2087 && lin_mag < 0.05
2088 && self.get_angular_vel_cw().abs() < 0.02
2089 && self.get_angular_accel_cw().abs() < 0.08
2090 && !gravity_changed
2091 && bodies_settled;
2092 let shake_decay: f32 = (-clamped_dt * FLUID_SHAKE_DECAY_PER_SEC).exp();
2093 if is_settled_rest {
2094 let next_sx: f32 = self.get_shake_accel_x() * shake_decay;
2095 let next_sy: f32 = self.get_shake_accel_y() * shake_decay;
2096 self.set_shake_accel_x(if next_sx.abs() < 0.01 { 0.0 } else { next_sx });
2097 self.set_shake_accel_y(if next_sy.abs() < 0.01 { 0.0 } else { next_sy });
2098 self.set_sim_time_secs(self.get_sim_time_secs() + clamped_dt);
2099 return;
2100 }
2101 let max_spd: f32 = self.get_last_max_speed_mps();
2102 let fast_linear_or_speed: bool = lin_mag > 12.0 || max_spd > 1.15;
2103 let high_energy_motion: bool =
2104 fast_linear_or_speed || self.get_angular_accel_cw().abs() > 8.0;
2105 let active_slosh: bool = lin_mag > 1.5
2106 || max_spd > 0.45
2107 || self.get_kinetic_energy_mj() > 2.0
2108 || self.get_angular_vel_cw().abs() > 0.25
2109 || gravity_changed;
2110 let substeps: u32 = if high_energy_motion {
2111 base_substeps
2112 } else if active_slosh {
2113 base_substeps.min(2)
2114 } else {
2115 1
2116 };
2117 let sub_dt: f32 = clamped_dt / (substeps as f32);
2118 let grid_disp_limit: f32 = self.get_kernel_radius_m() * 0.22;
2119 for step_idx in 0..substeps {
2120 let need_rebuild: bool =
2121 step_idx == 0 || self.get_last_max_speed_mps() * sub_dt > grid_disp_limit;
2122 self.run_substep(sub_dt, need_rebuild);
2123 }
2124 self.set_settled_gravity_x(gx);
2125 self.set_settled_gravity_y(gy);
2126 let next_sx: f32 = self.get_shake_accel_x() * shake_decay;
2127 let next_sy: f32 = self.get_shake_accel_y() * shake_decay;
2128 self.set_shake_accel_x(if next_sx.abs() < 0.01 { 0.0 } else { next_sx });
2129 self.set_shake_accel_y(if next_sy.abs() < 0.01 { 0.0 } else { next_sy });
2130 self.step_bubbles_and_foam(clamped_dt);
2131 self.set_sim_time_secs(self.get_sim_time_secs() + clamped_dt);
2132 self.update_diagnostics();
2133 }
2134
2135 fn update_diagnostics(&mut self) {
2141 let item_count: usize = self.get_particle_count();
2142 if item_count == 0 {
2143 self.set_kinetic_energy_mj(0.0);
2144 self.set_peak_wave_height_m(0.0);
2145 return;
2146 }
2147 let m_p: f32 = self.get_particle_mass_kgpm();
2148 let gx: f32 = self.get_gravity_x();
2149 let gy: f32 = self.get_gravity_y();
2150 let g_mag: f32 = (gx * gx + gy * gy).sqrt();
2151 let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
2152 (-gx / g_mag, -gy / g_mag)
2153 } else {
2154 (0.0, -1.0)
2155 };
2156 let mut ke_sum: f32 = 0.0;
2157 let mut min_proj: f32 = f32::INFINITY;
2158 let mut max_proj: f32 = f32::NEG_INFINITY;
2159 let mut avg_proj: f32 = 0.0;
2160 let Self {
2161 pos_x,
2162 pos_y,
2163 vel_x,
2164 vel_y,
2165 ..
2166 } = self;
2167 for item_index in 0..item_count {
2168 let v2: f32 =
2169 vel_x[item_index] * vel_x[item_index] + vel_y[item_index] * vel_y[item_index];
2170 ke_sum += 0.5 * m_p * v2;
2171 let proj: f32 = pos_x[item_index] * up_x + pos_y[item_index] * up_y;
2172 avg_proj += proj;
2173 if proj < min_proj {
2174 min_proj = proj;
2175 }
2176 if proj > max_proj {
2177 max_proj = proj;
2178 }
2179 }
2180 let mean_proj: f32 = avg_proj / (item_count as f32);
2181 let expected_half_span: f32 = (max_proj - min_proj) * 0.5;
2182 let wave_amp: f32 = ((max_proj - mean_proj) - expected_half_span).abs();
2183 self.set_kinetic_energy_mj(ke_sum * 1000.0);
2184 self.set_peak_wave_height_m(wave_amp);
2185 }
2186
2187 pub fn capture_snapshot_into(&self, dst: &mut FluidSimSnapshot) {
2194 let config_spec: GyroLiquidConfig = self.get_config();
2195 let item_count: usize = self.get_particle_count().min(FLUID_MAX_PARTICLES);
2196 let b_cnt: usize = self.get_buoyant_body_count().min(FLUID_MAX_BUOYANT_BODIES);
2197 let bub_cnt: usize = self.get_bubble_count().min(FLUID_MAX_BUBBLES);
2198 dst.set_vessel_width_m(config_spec.get_vessel_width_m());
2199 dst.set_vessel_height_m(config_spec.get_vessel_height_m());
2200 dst.set_kernel_radius_m(self.get_kernel_radius_m());
2201 dst.set_particle_count(item_count);
2202 dst.set_buoyant_body_count(b_cnt);
2203 dst.set_bubble_count(bub_cnt);
2204 dst.set_gravity_x(self.get_gravity_x());
2205 dst.set_gravity_y(self.get_gravity_y());
2206 dst.set_gravity_z(self.get_gravity_z());
2207 dst.set_sim_time_secs(self.get_sim_time_secs());
2208 let inv_rho0: f32 = 1.0 / WATER_REST_DENSITY_KGM3;
2209 dst.get_mut_pos_x()[..item_count].copy_from_slice(&self.get_pos_x()[..item_count]);
2210 dst.get_mut_pos_y()[..item_count].copy_from_slice(&self.get_pos_y()[..item_count]);
2211 dst.get_mut_vel_x()[..item_count].copy_from_slice(&self.get_vel_x()[..item_count]);
2212 dst.get_mut_vel_y()[..item_count].copy_from_slice(&self.get_vel_y()[..item_count]);
2213 let src_dens: &[f32] = self.get_density();
2214 let dst_ratio: &mut [f32] = dst.get_mut_density_ratio();
2215 for item_index in 0..item_count {
2216 dst_ratio[item_index] = src_dens[item_index] * inv_rho0;
2217 }
2218 dst.get_mut_buoyant_bodies()[..b_cnt].copy_from_slice(&self.get_buoyant_bodies()[..b_cnt]);
2219 dst.get_mut_bubbles()[..bub_cnt].copy_from_slice(&self.get_bubbles()[..bub_cnt]);
2220 }
2221
2222 #[must_use]
2232 pub fn center_of_mass(&self) -> (f32, f32) {
2233 let item_count: usize = self.get_particle_count();
2234 if item_count == 0 {
2235 let config_spec: GyroLiquidConfig = self.get_config();
2236 return (
2237 config_spec.get_vessel_width_m() * 0.5,
2238 config_spec.get_vessel_height_m() * 0.5,
2239 );
2240 }
2241 let px: &[f32] = self.get_pos_x();
2242 let py: &[f32] = self.get_pos_y();
2243 let mut sx: f32 = 0.0;
2244 let mut sy: f32 = 0.0;
2245 for item_index in 0..item_count {
2246 sx += px[item_index];
2247 sy += py[item_index];
2248 }
2249 let inv_n: f32 = 1.0 / (item_count as f32);
2250 (sx * inv_n, sy * inv_n)
2251 }
2252
2253 #[must_use]
2263 pub fn has_invalid_or_escaped_state(&self) -> bool {
2264 let config_spec: GyroLiquidConfig = self.get_config();
2265 let width_val: f32 = config_spec.get_vessel_width_m();
2266 let height_val: f32 = config_spec.get_vessel_height_m();
2267 let item_count: usize = self.get_particle_count();
2268 let px: &[f32] = self.get_pos_x();
2269 let py: &[f32] = self.get_pos_y();
2270 let vx: &[f32] = self.get_vel_x();
2271 let vy: &[f32] = self.get_vel_y();
2272 for item_index in 0..item_count {
2273 if !px[item_index].is_finite()
2274 || !py[item_index].is_finite()
2275 || !vx[item_index].is_finite()
2276 || !vy[item_index].is_finite()
2277 || px[item_index] < -1.0e-3
2278 || px[item_index] > width_val + 1.0e-3
2279 || py[item_index] < -1.0e-3
2280 || py[item_index] > height_val + 1.0e-3
2281 {
2282 return true;
2283 }
2284 }
2285 let b_cnt: usize = self.get_buoyant_body_count();
2286 for body in self.get_buoyant_bodies().iter().take(b_cnt) {
2287 if !body.get_x().is_finite()
2288 || !body.get_y().is_finite()
2289 || !body.get_vx().is_finite()
2290 || !body.get_vy().is_finite()
2291 || !body.get_angle().is_finite()
2292 || body.get_x() < -1.0e-3
2293 || body.get_x() > width_val + 1.0e-3
2294 || body.get_y() < -1.0e-3
2295 || body.get_y() > height_val + 1.0e-3
2296 {
2297 return true;
2298 }
2299 }
2300 false
2301 }
2302}