euv-core 0.56.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
use super::*;

/// Sanitizes a floating-point scalar by substituting `fallback` when NaN or infinite.
///
/// # Arguments
///
/// - `f32` - Candidate scalar value.
/// - `f32` - Finite fallback scalar.
///
/// # Returns
///
/// - `f32` - Guaranteed finite floating-point value.
pub(crate) fn sph_sanitize_f32(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}

/// Sanitizes a `Vec3` component-wise and zeroes `z` when operating in `FluidDomainMode::Dim2`.
///
/// # Arguments
///
/// - `Vec3` - Candidate vector.
/// - `FluidDomainMode` - Active dimensionality mode.
///
/// # Returns
///
/// - `Vec3` - Finite vector projected onto the active domain dimensionality.
pub(crate) fn sph_project_vec3(value: Vec3, mode: FluidDomainMode) -> Vec3 {
    let x: f32 = sph_sanitize_f32(value.get_x(), 0.0);
    let y: f32 = sph_sanitize_f32(value.get_y(), 0.0);
    let z: f32 = match mode {
        FluidDomainMode::Dim2 => 0.0,
        FluidDomainMode::Dim3 => sph_sanitize_f32(value.get_z(), 0.0),
    };
    Vec3::new(x, y, z)
}

/// Advances a deterministic SplitMix64 PRNG and returns a uniform scalar in `[0.0, 1.0)`.
///
/// # Arguments
///
/// - `&mut u64` - Mutable 64-bit PRNG state.
///
/// # Returns
///
/// - `f32` - Uniform deterministic scalar in `[0.0, 1.0)`.
pub(crate) fn sph_next_unit_f32(state: &mut u64) -> f32 {
    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
    let mut mixed: u64 = *state;
    mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    mixed ^= mixed >> 31;
    ((mixed >> 40) as u32) as f32 * (1.0 / 16_777_216.0)
}

/// Computes precomputed 2D or 3D SPH kernel normalization constants for `config`.
///
/// # Arguments
///
/// - `SphSolverConfig` - Sanitized solver configuration.
///
/// # Returns
///
/// - `SphKernelConstants` - Precomputed Poly6, Spiky, and Akinci normalization factors.
pub(crate) fn compute_sph_kernel_constants(config: SphSolverConfig) -> SphKernelConstants {
    let h: f32 = config.get_smoothing_radius().max(0.01);
    let h2: f32 = h * h;
    let (poly6, spiky_grad, poly6_grad, akinci): (f32, f32, f32, f32) =
        match config.get_domain_mode() {
            FluidDomainMode::Dim2 => {
                let h5: f32 = h2 * h2 * h;
                let h8: f32 = h2 * h2 * h2 * h2;
                (
                    4.0 / (PI * h8),
                    -30.0 / (PI * h5),
                    -24.0 / (PI * h8),
                    16.0 / (PI * h8),
                )
            }
            FluidDomainMode::Dim3 => {
                let h6: f32 = h2 * h2 * h2;
                let h9: f32 = h6 * h2 * h;
                (
                    315.0 / (64.0 * PI * h9),
                    -45.0 / (PI * h6),
                    -945.0 / (32.0 * PI * h9),
                    32.0 / (PI * h9),
                )
            }
        };
    let dq: f32 = config.get_scorr_dq_ratio().clamp(0.05, 0.8) * h;
    let diff: f32 = (h2 - dq * dq).max(1e-8);
    let w_dq: f32 = poly6 * diff * diff * diff;
    let w_dq_inv: f32 = if w_dq > 1e-12 { 1.0 / w_dq } else { 0.0 };
    SphKernelConstants::new(h, h2, poly6, spiky_grad, poly6_grad, akinci, w_dq_inv)
}

/// Evaluates the Poly6 scalar kernel `W_poly6(r^2, h)` for density estimation.
///
/// # Arguments
///
/// - `f32` - Squared distance `r^2` between two particles.
/// - `SphKernelConstants` - Precomputed kernel constants.
///
/// # Returns
///
/// - `f32` - Non-negative Poly6 kernel weight.
pub(crate) fn sph_poly6(dist_sq: f32, k: SphKernelConstants) -> f32 {
    if dist_sq >= k.get_h2() {
        return 0.0;
    }
    let diff: f32 = k.get_h2() - dist_sq;
    k.get_poly6_coeff() * diff * diff * diff
}

/// Evaluates the Spiky gradient vector `grad W_spiky(r_vec, h)` for PBF pressure corrections.
///
/// # Arguments
///
/// - `Vec3` - Separation vector `p_i - p_j`.
/// - `f32` - Euclidean distance `|p_i - p_j|`.
/// - `SphKernelConstants` - Precomputed kernel constants.
///
/// # Returns
///
/// - `Vec3` - Kernel gradient pointing from `i` toward `j`.
pub(crate) fn sph_spiky_grad(r_vec: Vec3, dist: f32, k: SphKernelConstants) -> Vec3 {
    if dist <= 1e-6 || dist >= k.get_h() {
        return Vec3::zero();
    }
    let diff: f32 = k.get_h() - dist;
    let scale: f32 = k.get_spiky_grad_coeff() * diff * diff / dist;
    r_vec.scale(scale)
}

/// Evaluates the Akinci 2013 cohesion spline weight `C(r, h)` for physical liquid surface tension.
///
/// # Arguments
///
/// - `f32` - Euclidean inter-particle distance `r`.
/// - `SphKernelConstants` - Precomputed kernel constants.
///
/// # Returns
///
/// - `f32` - Signed cohesion kernel scalar (attractive at medium range, repulsive at core).
pub(crate) fn sph_akinci_cohesion(dist: f32, k: SphKernelConstants) -> f32 {
    let h: f32 = k.get_h();
    if dist <= 1e-6 || dist >= h {
        return 0.0;
    }
    let hr: f32 = h - dist;
    let term: f32 = hr * hr * hr * dist * dist * dist;
    if 2.0 * dist > h {
        k.get_akinci_cohesion_coeff() * term
    } else {
        let h6: f32 = k.get_h2() * k.get_h2() * k.get_h2();
        k.get_akinci_cohesion_coeff() * (2.0 * term - h6 / 64.0)
    }
}

/// Computes the deterministic O(1) spatial hash bucket index for integer cell coordinates.
///
/// # Arguments
///
/// - `i32` - Cell X coordinate.
/// - `i32` - Cell Y coordinate.
/// - `i32` - Cell Z coordinate.
/// - `u32` - Power-of-two bucket mask `hash_table_size - 1`.
///
/// # Returns
///
/// - `usize` - Bucket index in `0..hash_table_size`.
pub(crate) fn sph_hash_cell(cx: i32, cy: i32, cz: i32, mask: u32) -> usize {
    let hx: u32 = (cx as u32).wrapping_mul(SPH_HASH_PRIME_X);
    let hy: u32 = (cy as u32).wrapping_mul(SPH_HASH_PRIME_Y);
    let hz: u32 = (cz as u32).wrapping_mul(SPH_HASH_PRIME_Z);
    ((hx ^ hy ^ hz) & mask) as usize
}

/// Rebuilds the pre-allocated O(N) counting-sort spatial hash grid and flat neighbor table with zero heap allocations.
///
/// # Arguments
///
/// - `SphSolverConfig` - Active solver configuration.
/// - `usize` - Active particle count `n`.
/// - `&mut SphScratchBuffers` - Pre-allocated scratch buffers containing predicted positions and hash arrays.
pub(crate) fn rebuild_sph_spatial_hash_and_neighbors(
    config: SphSolverConfig,
    count: usize,
    scratch: &mut SphScratchBuffers,
) {
    let h: f32 = config.get_smoothing_radius().max(0.01);
    let inv_h: f32 = 1.0 / h;
    let h2: f32 = h * h;
    let mode: FluidDomainMode = config.get_domain_mode();
    let table_size: usize = scratch.get_cell_counts().len();
    let mask: u32 = (table_size.saturating_sub(1)) as u32;
    let predicted: Vec<Vec3> = take(scratch.get_mut_predicted_positions());
    let mut cell_counts: Vec<u32> = take(scratch.get_mut_cell_counts());
    let mut cell_offsets: Vec<u32> = take(scratch.get_mut_cell_offsets());
    let mut cell_cursors: Vec<u32> = take(scratch.get_mut_cell_cursors());
    let mut particle_hashes: Vec<u32> = take(scratch.get_mut_particle_hashes());
    let mut sorted_indices: Vec<u32> = take(scratch.get_mut_sorted_indices());
    let mut neighbor_counts: Vec<u16> = take(scratch.get_mut_neighbor_counts());
    let mut neighbor_indices: Vec<u32> = take(scratch.get_mut_neighbor_indices());
    cell_counts.fill(0);
    for idx in 0..count {
        let p: Vec3 = predicted[idx];
        let cx: i32 = (p.get_x() * inv_h).floor() as i32;
        let cy: i32 = (p.get_y() * inv_h).floor() as i32;
        let cz: i32 = match mode {
            FluidDomainMode::Dim2 => 0,
            FluidDomainMode::Dim3 => (p.get_z() * inv_h).floor() as i32,
        };
        let bucket: usize = sph_hash_cell(cx, cy, cz, mask);
        particle_hashes[idx] = bucket as u32;
        cell_counts[bucket] += 1;
    }
    let mut running: u32 = 0;
    for bucket in 0..table_size {
        cell_offsets[bucket] = running;
        cell_cursors[bucket] = running;
        running += cell_counts[bucket];
    }
    cell_offsets[table_size] = running;
    for (idx, &hash_bucket) in particle_hashes.iter().enumerate().take(count) {
        let bucket: usize = hash_bucket as usize;
        let dst: usize = cell_cursors[bucket] as usize;
        sorted_indices[dst] = idx as u32;
        cell_cursors[bucket] += 1;
    }
    let z_range: (i32, i32) = match mode {
        FluidDomainMode::Dim2 => (0, 0),
        FluidDomainMode::Dim3 => (-1, 1),
    };
    for idx in 0..count {
        let pi: Vec3 = predicted[idx];
        let cx: i32 = (pi.get_x() * inv_h).floor() as i32;
        let cy: i32 = (pi.get_y() * inv_h).floor() as i32;
        let cz: i32 = match mode {
            FluidDomainMode::Dim2 => 0,
            FluidDomainMode::Dim3 => (pi.get_z() * inv_h).floor() as i32,
        };
        let base_slot: usize = idx * SPH_MAX_NEIGHBORS;
        let mut found: usize = 0;
        for dz in z_range.0..=z_range.1 {
            for dy in -1..=1 {
                for dx in -1..=1 {
                    if found >= SPH_MAX_NEIGHBORS {
                        break;
                    }
                    let bucket: usize = sph_hash_cell(cx + dx, cy + dy, cz + dz, mask);
                    let start: usize = cell_offsets[bucket] as usize;
                    let end: usize = cell_offsets[bucket + 1] as usize;
                    for &sorted_j in &sorted_indices[start..end] {
                        let j_idx: usize = sorted_j as usize;
                        if j_idx == idx {
                            continue;
                        }
                        let diff: Vec3 = pi.sub(predicted[j_idx]);
                        if diff.length_sq() < h2 {
                            neighbor_indices[base_slot + found] = sorted_j;
                            found += 1;
                            if found >= SPH_MAX_NEIGHBORS {
                                break;
                            }
                        }
                    }
                }
            }
        }
        neighbor_counts[idx] = found as u16;
    }
    scratch.set_predicted_positions(predicted);
    scratch.set_cell_counts(cell_counts);
    scratch.set_cell_offsets(cell_offsets);
    scratch.set_cell_cursors(cell_cursors);
    scratch.set_particle_hashes(particle_hashes);
    scratch.set_sorted_indices(sorted_indices);
    scratch.set_neighbor_counts(neighbor_counts);
    scratch.set_neighbor_indices(neighbor_indices);
}

/// Projects a single particle position against one `SphSolidCollider` and returns `(new_pos, contact_normal, wall_vel, hit)`.
///
/// # Arguments
///
/// - `Vec3` - Particle position to test and resolve.
/// - `SphSolidCollider` - Active solid collider.
/// - `FluidDomainMode` - Active dimensionality mode.
///
/// # Returns
///
/// - `(Vec3, Vec3, Vec3, bool)` - Resolved position, outward contact normal, wall linear velocity, and hit flag.
pub(crate) fn resolve_single_collider(
    pos: Vec3,
    collider: SphSolidCollider,
    mode: FluidDomainMode,
) -> (Vec3, Vec3, Vec3, bool) {
    if !collider.get_enabled() {
        return (pos, Vec3::zero(), Vec3::zero(), false);
    }
    let eps: f32 = 1e-4;
    match collider.get_shape() {
        SphColliderShape::Box {
            center,
            half_extents,
            inward,
        } => {
            let rel: Vec3 = pos.sub(center);
            let hx: f32 = half_extents.get_x().abs().max(eps);
            let hy: f32 = half_extents.get_y().abs().max(eps);
            let hz: f32 = half_extents.get_z().abs().max(eps);
            if inward {
                let mut nx: f32 = 0.0;
                let mut ny: f32 = 0.0;
                let mut nz: f32 = 0.0;
                let mut rx: f32 = rel.get_x();
                let mut ry: f32 = rel.get_y();
                let mut rz: f32 = rel.get_z();
                let mut hit: bool = false;
                if rx < -hx {
                    rx = -hx;
                    nx = 1.0;
                    hit = true;
                } else if rx > hx {
                    rx = hx;
                    nx = -1.0;
                    hit = true;
                }
                if ry < -hy {
                    ry = -hy;
                    ny = 1.0;
                    hit = true;
                } else if ry > hy {
                    ry = hy;
                    ny = -1.0;
                    hit = true;
                }
                if mode == FluidDomainMode::Dim3 {
                    if rz < -hz {
                        rz = -hz;
                        nz = 1.0;
                        hit = true;
                    } else if rz > hz {
                        rz = hz;
                        nz = -1.0;
                        hit = true;
                    }
                } else {
                    rz = 0.0;
                }
                let out_pos: Vec3 = sph_project_vec3(center.add(Vec3::new(rx, ry, rz)), mode);
                let normal: Vec3 = if hit {
                    Vec3::new(nx, ny, nz).normalize()
                } else {
                    Vec3::zero()
                };
                (out_pos, normal, Vec3::zero(), hit)
            } else {
                let inside_z: bool = mode == FluidDomainMode::Dim2 || rel.get_z().abs() < hz;
                if rel.get_x().abs() < hx && rel.get_y().abs() < hy && inside_z {
                    let pen_x: f32 = hx - rel.get_x().abs();
                    let pen_y: f32 = hy - rel.get_y().abs();
                    let pen_z: f32 = if mode == FluidDomainMode::Dim3 {
                        hz - rel.get_z().abs()
                    } else {
                        f32::MAX
                    };
                    if pen_x <= pen_y && pen_x <= pen_z {
                        let sgn: f32 = if rel.get_x() >= 0.0 { 1.0 } else { -1.0 };
                        let out: Vec3 =
                            Vec3::new(center.get_x() + sgn * hx, pos.get_y(), pos.get_z());
                        (
                            sph_project_vec3(out, mode),
                            Vec3::new(sgn, 0.0, 0.0),
                            Vec3::zero(),
                            true,
                        )
                    } else if pen_y <= pen_z {
                        let sgn: f32 = if rel.get_y() >= 0.0 { 1.0 } else { -1.0 };
                        let out: Vec3 =
                            Vec3::new(pos.get_x(), center.get_y() + sgn * hy, pos.get_z());
                        (
                            sph_project_vec3(out, mode),
                            Vec3::new(0.0, sgn, 0.0),
                            Vec3::zero(),
                            true,
                        )
                    } else {
                        let sgn: f32 = if rel.get_z() >= 0.0 { 1.0 } else { -1.0 };
                        let out: Vec3 =
                            Vec3::new(pos.get_x(), pos.get_y(), center.get_z() + sgn * hz);
                        (
                            sph_project_vec3(out, mode),
                            Vec3::new(0.0, 0.0, sgn),
                            Vec3::zero(),
                            true,
                        )
                    }
                } else {
                    (pos, Vec3::zero(), Vec3::zero(), false)
                }
            }
        }
        SphColliderShape::Sphere {
            center,
            radius,
            inward,
        } => {
            let safe_r: f32 = radius.abs().max(eps);
            let rel: Vec3 = sph_project_vec3(pos.sub(center), mode);
            let dist: f32 = rel.length();
            if inward {
                if dist > safe_r {
                    let dir: Vec3 = rel.scale(1.0 / dist.max(1e-6));
                    let out: Vec3 = sph_project_vec3(center.add(dir.scale(safe_r)), mode);
                    (out, dir.scale(-1.0), Vec3::zero(), true)
                } else {
                    (pos, Vec3::zero(), Vec3::zero(), false)
                }
            } else if dist < safe_r {
                let dir: Vec3 = if dist > 1e-6 {
                    rel.scale(1.0 / dist)
                } else {
                    Vec3::new(0.0, 1.0, 0.0)
                };
                let out: Vec3 = sph_project_vec3(center.add(dir.scale(safe_r)), mode);
                (out, dir, Vec3::zero(), true)
            } else {
                (pos, Vec3::zero(), Vec3::zero(), false)
            }
        }
        SphColliderShape::Capsule {
            point_a,
            point_b,
            radius,
        } => {
            let safe_r: f32 = radius.abs().max(eps);
            let pa: Vec3 = sph_project_vec3(point_a, mode);
            let pb: Vec3 = sph_project_vec3(point_b, mode);
            let ab: Vec3 = pb.sub(pa);
            let ab_sq: f32 = ab.length_sq();
            let t_param: f32 = if ab_sq > 1e-8 {
                (pos.sub(pa).dot(ab) / ab_sq).clamp(0.0, 1.0)
            } else {
                0.0
            };
            let closest: Vec3 = pa.add(ab.scale(t_param));
            let rel: Vec3 = pos.sub(closest);
            let dist: f32 = rel.length();
            if dist < safe_r {
                let dir: Vec3 = if dist > 1e-6 {
                    rel.scale(1.0 / dist)
                } else {
                    Vec3::new(0.0, 1.0, 0.0)
                };
                let out: Vec3 = sph_project_vec3(closest.add(dir.scale(safe_r)), mode);
                (out, dir, Vec3::zero(), true)
            } else {
                (pos, Vec3::zero(), Vec3::zero(), false)
            }
        }
        SphColliderShape::Cylinder {
            center,
            radius,
            half_height,
            inward,
        } => {
            let safe_r: f32 = radius.abs().max(eps);
            let safe_hh: f32 = half_height.abs().max(eps);
            let rel: Vec3 = pos.sub(center);
            let radial: Vec3 = Vec3::new(
                rel.get_x(),
                0.0,
                if mode == FluidDomainMode::Dim3 {
                    rel.get_z()
                } else {
                    0.0
                },
            );
            let r_len: f32 = radial.length();
            if inward {
                let mut out_x: f32 = rel.get_x();
                let mut out_y: f32 = rel.get_y();
                let mut out_z: f32 = if mode == FluidDomainMode::Dim3 {
                    rel.get_z()
                } else {
                    0.0
                };
                let mut norm: Vec3 = Vec3::zero();
                let mut hit: bool = false;
                if r_len > safe_r {
                    let scale: f32 = safe_r / r_len.max(1e-6);
                    out_x *= scale;
                    out_z *= scale;
                    norm = norm.add(radial.scale(-1.0 / r_len.max(1e-6)));
                    hit = true;
                }
                if out_y < -safe_hh {
                    out_y = -safe_hh;
                    norm = norm.add(Vec3::new(0.0, 1.0, 0.0));
                    hit = true;
                } else if out_y > safe_hh {
                    out_y = safe_hh;
                    norm = norm.add(Vec3::new(0.0, -1.0, 0.0));
                    hit = true;
                }
                let out_pos: Vec3 =
                    sph_project_vec3(center.add(Vec3::new(out_x, out_y, out_z)), mode);
                let unit_n: Vec3 = if hit { norm.normalize() } else { Vec3::zero() };
                (out_pos, unit_n, Vec3::zero(), hit)
            } else if r_len < safe_r && rel.get_y().abs() < safe_hh {
                let pen_r: f32 = safe_r - r_len;
                let pen_y: f32 = safe_hh - rel.get_y().abs();
                if pen_r <= pen_y {
                    let dir: Vec3 = if r_len > 1e-6 {
                        radial.scale(1.0 / r_len)
                    } else {
                        Vec3::new(1.0, 0.0, 0.0)
                    };
                    let out: Vec3 = Vec3::new(
                        center.get_x() + dir.get_x() * safe_r,
                        pos.get_y(),
                        center.get_z() + dir.get_z() * safe_r,
                    );
                    (sph_project_vec3(out, mode), dir, Vec3::zero(), true)
                } else {
                    let sgn: f32 = if rel.get_y() >= 0.0 { 1.0 } else { -1.0 };
                    let out: Vec3 =
                        Vec3::new(pos.get_x(), center.get_y() + sgn * safe_hh, pos.get_z());
                    (
                        sph_project_vec3(out, mode),
                        Vec3::new(0.0, sgn, 0.0),
                        Vec3::zero(),
                        true,
                    )
                }
            } else {
                (pos, Vec3::zero(), Vec3::zero(), false)
            }
        }
        SphColliderShape::Plane { point, normal } => {
            let unit_n: Vec3 = sph_project_vec3(normal, mode).normalize();
            let dist: f32 = pos.sub(point).dot(unit_n);
            if dist < 0.0 {
                let out: Vec3 = sph_project_vec3(pos.add(unit_n.scale(-dist)), mode);
                (out, unit_n, Vec3::zero(), true)
            } else {
                (pos, Vec3::zero(), Vec3::zero(), false)
            }
        }
        SphColliderShape::MovingContainer {
            center,
            half_extents,
            linear_velocity,
        } => {
            let inner: SphSolidCollider = SphSolidCollider::new(
                SphColliderShape::Box {
                    center,
                    half_extents,
                    inward: true,
                },
                collider.get_friction(),
                collider.get_restitution(),
                true,
            );
            let (out_pos, norm, _, hit): (Vec3, Vec3, Vec3, bool) =
                resolve_single_collider(pos, inner, mode);
            (out_pos, norm, sph_project_vec3(linear_velocity, mode), hit)
        }
    }
}

/// Clamps a particle position to outer safety domain bounds and all registered `SphSolidCollider` constraints.
///
/// # Arguments
///
/// - `Vec3` - Candidate particle position.
/// - `SphSolverConfig` - Active solver configuration.
/// - `&[SphSolidCollider]` - Registered colliders.
///
/// # Returns
///
/// - `Vec3` - Contained, finite particle position.
pub(crate) fn clamp_sph_position(
    pos: Vec3,
    config: SphSolverConfig,
    colliders: &[SphSolidCollider],
) -> Vec3 {
    let mode: FluidDomainMode = config.get_domain_mode();
    let dmin: Vec3 = config.get_domain_min();
    let dmax: Vec3 = config.get_domain_max();
    let mut cur: Vec3 = sph_project_vec3(pos, mode);
    cur = Vec3::new(
        cur.get_x().clamp(dmin.get_x(), dmax.get_x()),
        cur.get_y().clamp(dmin.get_y(), dmax.get_y()),
        match mode {
            FluidDomainMode::Dim2 => 0.0,
            FluidDomainMode::Dim3 => cur.get_z().clamp(dmin.get_z(), dmax.get_z()),
        },
    );
    for &collider in colliders.iter() {
        let (next_pos, _, _, _): (Vec3, Vec3, Vec3, bool) =
            resolve_single_collider(cur, collider, mode);
        cur = next_pos;
    }
    cur
}

/// Runs Jacobi PBF density constraint iterations with `s_corr` artificial tensile pressure over cached neighbors.
///
/// # Arguments
///
/// - `SphSolverConfig` - Active solver configuration.
/// - `SphKernelConstants` - Precomputed kernel normalization factors.
/// - `&mut [SphParticle]` - Active particle slice receiving updated densities.
/// - `&[SphSolidCollider]` - Registered colliders.
/// - `&mut SphScratchBuffers` - Pre-allocated scratch buffers.
pub(crate) fn run_sph_pbf_iterations(
    config: SphSolverConfig,
    k: SphKernelConstants,
    particles: &mut [SphParticle],
    colliders: &[SphSolidCollider],
    scratch: &mut SphScratchBuffers,
) {
    let count: usize = particles.len();
    let mass: f32 = config.get_particle_mass();
    let rho0: f32 = config.get_rest_density();
    let mass_over_rho0: f32 = mass / rho0;
    let cfm_eps: f32 = config.get_cfm_epsilon() / k.get_h2().max(1e-6);
    let scorr_k: f32 = config.get_scorr_k();
    let scorr_n: i32 = config.get_scorr_n().clamp(1, 8) as i32;
    let max_dp: f32 = SPH_MAX_DELTA_POS_RATIO * k.get_h();
    let iters: u32 = config.get_solver_iterations().max(1);
    let mode: FluidDomainMode = config.get_domain_mode();
    let w_self: f32 = sph_poly6(0.0, k);
    let mut predicted: Vec<Vec3> = take(scratch.get_mut_predicted_positions());
    let mut lambdas: Vec<f32> = take(scratch.get_mut_lambdas());
    let mut delta_pos: Vec<Vec3> = take(scratch.get_mut_delta_positions());
    let neighbor_counts: Vec<u16> = take(scratch.get_mut_neighbor_counts());
    let neighbor_indices: Vec<u32> = take(scratch.get_mut_neighbor_indices());
    for _iter in 0..iters {
        for idx in 0..count {
            let pi: Vec3 = predicted[idx];
            let base: usize = idx * SPH_MAX_NEIGHBORS;
            let n_cnt: usize = neighbor_counts[idx] as usize;
            let mut density_sum: f32 = w_self;
            let mut grad_i: Vec3 = Vec3::zero();
            let mut sum_grad_sq: f32 = 0.0;
            for n_off in 0..n_cnt {
                let j_idx: usize = neighbor_indices[base + n_off] as usize;
                let r_vec: Vec3 = pi.sub(predicted[j_idx]);
                let r_sq: f32 = r_vec.length_sq();
                if r_sq < k.get_h2() {
                    density_sum += sph_poly6(r_sq, k);
                    let dist: f32 = r_sq.sqrt();
                    let grad_w: Vec3 = sph_spiky_grad(r_vec, dist, k).scale(mass_over_rho0);
                    sum_grad_sq += grad_w.length_sq();
                    grad_i = grad_i.add(grad_w);
                }
            }
            sum_grad_sq += grad_i.length_sq();
            let rho_i: f32 = (mass * density_sum).max(1e-4);
            particles[idx].set_density(rho_i);
            let constraint: f32 = (rho_i / rho0 - 1.0).max(0.0);
            lambdas[idx] = -constraint / (sum_grad_sq + cfm_eps);
        }
        for idx in 0..count {
            let pi: Vec3 = predicted[idx];
            let lam_i: f32 = lambdas[idx];
            let base: usize = idx * SPH_MAX_NEIGHBORS;
            let n_cnt: usize = neighbor_counts[idx] as usize;
            let mut dp: Vec3 = Vec3::zero();
            for n_off in 0..n_cnt {
                let j_idx: usize = neighbor_indices[base + n_off] as usize;
                let r_vec: Vec3 = pi.sub(predicted[j_idx]);
                let r_sq: f32 = r_vec.length_sq();
                if r_sq > 1e-12 && r_sq < k.get_h2() {
                    let dist: f32 = r_sq.sqrt();
                    let w_ratio: f32 = (sph_poly6(r_sq, k) * k.get_w_dq_inv()).clamp(0.0, 2.0);
                    let s_corr: f32 = if lam_i < 0.0 || lambdas[j_idx] < 0.0 {
                        -scorr_k * w_ratio.powi(scorr_n)
                    } else {
                        0.0
                    };
                    let weight: f32 = lam_i + lambdas[j_idx] + s_corr;
                    dp = dp.add(sph_spiky_grad(r_vec, dist, k).scale(weight * mass_over_rho0));
                }
            }
            let dp_len: f32 = dp.length();
            if !dp_len.is_finite() {
                dp = Vec3::zero();
            } else if dp_len > max_dp {
                dp = dp.scale(max_dp / dp_len);
            }
            delta_pos[idx] = sph_project_vec3(dp, mode);
        }
        for idx in 0..count {
            let shifted: Vec3 = predicted[idx].add(delta_pos[idx]);
            predicted[idx] = clamp_sph_position(shifted, config, colliders);
        }
    }
    scratch.set_predicted_positions(predicted);
    scratch.set_lambdas(lambdas);
    scratch.set_delta_positions(delta_pos);
    scratch.set_neighbor_counts(neighbor_counts);
    scratch.set_neighbor_indices(neighbor_indices);
}

/// Applies Akinci surface tension, vorticity confinement, XSPH viscosity, and wall friction/restitution.
///
/// # Arguments
///
/// - `SphSolverConfig` - Active solver configuration.
/// - `SphKernelConstants` - Precomputed kernel constants.
/// - `f32` - Substep time interval in seconds.
/// - `&mut [SphParticle]` - Active particles with updated positions and velocities.
/// - `&[SphSolidCollider]` - Registered colliders.
/// - `&mut SphScratchBuffers` - Pre-allocated scratch buffers.
pub(crate) fn apply_sph_post_solve_forces(
    config: SphSolverConfig,
    k: SphKernelConstants,
    dt_sub: f32,
    particles: &mut [SphParticle],
    colliders: &[SphSolidCollider],
    scratch: &mut SphScratchBuffers,
) {
    let count: usize = particles.len();
    let mass: f32 = config.get_particle_mass();
    let rho0: f32 = config.get_rest_density();
    let mode: FluidDomainMode = config.get_domain_mode();
    let cohesion_gain: f32 = config.get_surface_tension_cohesion();
    let curvature_gain: f32 = config.get_surface_tension_curvature();
    let vort_eps: f32 = config.get_vorticity_epsilon();
    let xsph_c: f32 = config.get_xsph_viscosity();
    let max_speed: f32 = config.get_max_speed();
    let predicted: Vec<Vec3> = take(scratch.get_mut_predicted_positions());
    let neighbor_counts: Vec<u16> = take(scratch.get_mut_neighbor_counts());
    let neighbor_indices: Vec<u32> = take(scratch.get_mut_neighbor_indices());
    let mut vorticities: Vec<Vec3> = take(scratch.get_mut_vorticities());
    let mut xsph_deltas: Vec<Vec3> = take(scratch.get_mut_xsph_deltas());
    let mut tension_deltas: Vec<Vec3> = take(scratch.get_mut_tension_deltas());
    let inv_dt: f32 = 1.0 / dt_sub.max(1e-6);
    for idx in 0..count {
        let mut vel: Vec3 = predicted[idx]
            .sub(particles[idx].get_position())
            .scale(inv_dt);
        for &collider in colliders.iter() {
            let (_, norm, wall_vel, hit): (Vec3, Vec3, Vec3, bool) =
                resolve_single_collider(predicted[idx], collider, mode);
            if hit && norm.length_sq() > 1e-6 {
                let rel_v: Vec3 = vel.sub(wall_vel);
                let vn: f32 = rel_v.dot(norm);
                let mut vn_new: f32 = vn;
                if vn < 0.0 {
                    vn_new = -vn * collider.get_restitution().clamp(0.0, 1.0);
                }
                let vt: Vec3 = rel_v.sub(norm.scale(vn));
                let damp_t: f32 = (1.0 - collider.get_friction().clamp(0.0, 1.0)).clamp(0.0, 1.0);
                vel = wall_vel.add(norm.scale(vn_new)).add(vt.scale(damp_t));
            }
        }
        particles[idx].set_velocity(sph_project_vec3(vel, mode));
    }
    for idx in 0..count {
        let pi: Vec3 = predicted[idx];
        let base: usize = idx * SPH_MAX_NEIGHBORS;
        let n_cnt: usize = neighbor_counts[idx] as usize;
        let mut color_n: Vec3 = Vec3::zero();
        for n_off in 0..n_cnt {
            let j_idx: usize = neighbor_indices[base + n_off] as usize;
            let r_vec: Vec3 = pi.sub(predicted[j_idx]);
            let r_sq: f32 = r_vec.length_sq();
            if r_sq > 1e-12 && r_sq < k.get_h2() {
                let diff: f32 = k.get_h2() - r_sq;
                let rho_j: f32 = particles[j_idx].get_density().max(rho0 * 0.25);
                let scale: f32 =
                    k.get_h() * (mass / rho_j) * k.get_poly6_grad_coeff() * diff * diff;
                color_n = color_n.add(r_vec.scale(scale));
            }
        }
        particles[idx].set_color_normal(sph_project_vec3(color_n, mode));
    }
    for idx in 0..count {
        let pi: Vec3 = predicted[idx];
        let vi: Vec3 = particles[idx].get_velocity();
        let ni: Vec3 = particles[idx].get_color_normal();
        let rho_i: f32 = particles[idx].get_density().max(rho0 * 0.25);
        let base: usize = idx * SPH_MAX_NEIGHBORS;
        let n_cnt: usize = neighbor_counts[idx] as usize;
        let mut omega: Vec3 = Vec3::zero();
        let mut xsph: Vec3 = Vec3::zero();
        let mut tension: Vec3 = Vec3::zero();
        for n_off in 0..n_cnt {
            let j_idx: usize = neighbor_indices[base + n_off] as usize;
            let r_vec: Vec3 = pi.sub(predicted[j_idx]);
            let r_sq: f32 = r_vec.length_sq();
            if r_sq <= 1e-12 || r_sq >= k.get_h2() {
                continue;
            }
            let dist: f32 = r_sq.sqrt();
            let vj: Vec3 = particles[j_idx].get_velocity();
            let v_ij: Vec3 = vj.sub(vi);
            let rho_j: f32 = particles[j_idx].get_density().max(rho0 * 0.25);
            let w_val: f32 = sph_poly6(r_sq, k);
            xsph = xsph.add(v_ij.scale(w_val * (mass / rho_j)));
            let grad_w: Vec3 = sph_spiky_grad(r_vec, dist, k);
            omega = omega.add(v_ij.cross(grad_w));
            if cohesion_gain > 0.0 || curvature_gain > 0.0 {
                let k_sym: f32 = (2.0 * rho0) / (rho_i + rho_j);
                let c_val: f32 = sph_akinci_cohesion(dist, k);
                let f_coh: Vec3 = r_vec.scale(-cohesion_gain * mass * c_val / dist);
                let nj: Vec3 = particles[j_idx].get_color_normal();
                let f_curv: Vec3 = ni.sub(nj).scale(-curvature_gain);
                tension = tension.add(f_coh.add(f_curv).scale(k_sym));
            }
        }
        vorticities[idx] = omega;
        xsph_deltas[idx] = xsph.scale(xsph_c);
        let max_t_dv: f32 = max_speed * 0.15;
        let t_dv: Vec3 = tension.scale(dt_sub);
        let t_len: f32 = t_dv.length();
        tension_deltas[idx] = if !t_len.is_finite() {
            Vec3::zero()
        } else if t_len > max_t_dv {
            t_dv.scale(max_t_dv / t_len)
        } else {
            t_dv
        };
    }
    for idx in 0..count {
        let pi: Vec3 = predicted[idx];
        let base: usize = idx * SPH_MAX_NEIGHBORS;
        let n_cnt: usize = neighbor_counts[idx] as usize;
        let mut eta: Vec3 = Vec3::zero();
        if vort_eps > 0.0 {
            for n_off in 0..n_cnt {
                let j_idx: usize = neighbor_indices[base + n_off] as usize;
                let r_vec: Vec3 = pi.sub(predicted[j_idx]);
                let r_sq: f32 = r_vec.length_sq();
                if r_sq > 1e-12 && r_sq < k.get_h2() {
                    let dist: f32 = r_sq.sqrt();
                    let omega_mag: f32 = vorticities[j_idx].length();
                    eta = eta.add(sph_spiky_grad(r_vec, dist, k).scale(omega_mag));
                }
            }
        }
        let vort_dv: Vec3 = if vort_eps > 0.0 && eta.length_sq() > 1e-10 {
            let n_vort: Vec3 = eta.normalize();
            let raw: Vec3 = n_vort.cross(vorticities[idx]).scale(vort_eps * dt_sub);
            let raw_len: f32 = raw.length();
            if raw_len > max_speed * 0.1 {
                raw.scale((max_speed * 0.1) / raw_len)
            } else {
                raw
            }
        } else {
            Vec3::zero()
        };
        let mut vel: Vec3 = particles[idx]
            .get_velocity()
            .add(xsph_deltas[idx])
            .add(tension_deltas[idx])
            .add(vort_dv);
        vel = sph_project_vec3(vel, mode);
        let speed: f32 = vel.length();
        if !speed.is_finite() {
            vel = Vec3::zero();
        } else if speed > max_speed {
            vel = vel.scale(max_speed / speed);
        }
        particles[idx].set_velocity(vel);
        particles[idx].set_position(predicted[idx]);
    }
    scratch.set_predicted_positions(predicted);
    scratch.set_neighbor_counts(neighbor_counts);
    scratch.set_neighbor_indices(neighbor_indices);
    scratch.set_vorticities(vorticities);
    scratch.set_xsph_deltas(xsph_deltas);
    scratch.set_tension_deltas(tension_deltas);
}