euv-core 0.57.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
use super::*;

/// Default shallow-water wave heightfield configuration (`64 × 64` grid at `0.25 m` cell spacing).
impl Default for WaveHeightfieldConfig {
    /// Returns a balanced default `WaveHeightfieldConfig` ready for boat wakes and ripples.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            width: 64,
            height: 64,
            cell_size_m: WAKE_DEFAULT_CELL_SIZE_M,
            wave_speed_mps: WAKE_DEFAULT_WAVE_SPEED_MPS,
            damping: WAKE_DEFAULT_DAMPING,
            sponge_width: WAKE_DEFAULT_SPONGE_WIDTH,
            sponge_strength: WAKE_DEFAULT_SPONGE_STRENGTH,
            foam_decay_rate: WAKE_DEFAULT_FOAM_DECAY,
            origin_xz: Vec2::new(-8.0, -8.0),
            base_water_y: 0.0,
        }
    }
}

/// Fluent builder helpers for `WaveHeightfieldConfig`.
impl WaveHeightfieldConfig {
    /// Creates a new configuration with grid dimensions and cell spacing.
    ///
    /// # Arguments
    ///
    /// - `usize` - Grid cell count along X.
    /// - `usize` - Grid cell count along Z.
    /// - `f32` - Cell size in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Sanitized configuration.
    #[must_use]
    pub fn with_grid(width: usize, height: usize, cell_size_m: f32) -> Self {
        let clamped_w: usize = width.clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
        let clamped_h: usize = height.clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
        let safe_dx: f32 = wake_sanitize_f32(cell_size_m, WAKE_DEFAULT_CELL_SIZE_M).max(0.02);
        let half_x: f32 = 0.5 * (clamped_w.saturating_sub(1) as f32) * safe_dx;
        let half_z: f32 = 0.5 * (clamped_h.saturating_sub(1) as f32) * safe_dx;
        Self {
            width: clamped_w,
            height: clamped_h,
            cell_size_m: safe_dx,
            origin_xz: Vec2::new(-half_x, -half_z),
            ..Self::default()
        }
    }

    /// Returns a sanitized copy of this configuration with clamped physical bounds.
    ///
    /// # Returns
    ///
    /// - `Self` - Validated configuration.
    #[must_use]
    pub fn sanitized(self) -> Self {
        let width: usize = self.get_width().clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
        let height: usize = self
            .get_height()
            .clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
        let max_sponge: usize = width.min(height) / 3;
        Self {
            width,
            height,
            cell_size_m: wake_sanitize_f32(self.get_cell_size_m(), WAKE_DEFAULT_CELL_SIZE_M)
                .max(0.02),
            wave_speed_mps: wake_sanitize_f32(
                self.get_wave_speed_mps(),
                WAKE_DEFAULT_WAVE_SPEED_MPS,
            )
            .clamp(0.1, 40.0),
            damping: wake_sanitize_f32(self.get_damping(), WAKE_DEFAULT_DAMPING).clamp(0.0, 20.0),
            sponge_width: self.get_sponge_width().min(max_sponge),
            sponge_strength: wake_sanitize_f32(
                self.get_sponge_strength(),
                WAKE_DEFAULT_SPONGE_STRENGTH,
            )
            .clamp(0.0, 40.0),
            foam_decay_rate: wake_sanitize_f32(self.get_foam_decay_rate(), WAKE_DEFAULT_FOAM_DECAY)
                .clamp(0.01, 20.0),
            origin_xz: Vec2::new(
                wake_sanitize_f32(self.get_origin_xz().get_x(), 0.0),
                wake_sanitize_f32(self.get_origin_xz().get_y(), 0.0),
            ),
            base_water_y: wake_sanitize_f32(self.get_base_water_y(), 0.0),
        }
    }
}

/// Default calm `WaveHeightfield2D` solver.
impl Default for WaveHeightfield2D {
    /// Creates a `WaveHeightfield2D` using `WaveHeightfieldConfig::default()`.
    ///
    /// # Returns
    ///
    /// - `Self` - Calm pre-allocated heightfield solver.
    fn default() -> Self {
        Self::from_config(WaveHeightfieldConfig::default())
    }
}

/// Interactive 2D shallow-water wave simulation, wake injection, obstacle masking, and sampling API.
impl WaveHeightfield2D {
    /// Constructs a pre-allocated `WaveHeightfield2D` solver from `config`.
    ///
    /// # Arguments
    ///
    /// - `WaveHeightfieldConfig` - Desired wave grid configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated zero-steady-state-allocation wave solver.
    #[must_use]
    pub fn from_config(config: WaveHeightfieldConfig) -> Self {
        let clean: WaveHeightfieldConfig = config.sanitized();
        let total: usize = clean.get_width() * clean.get_height();
        let cell_damping: Vec<f32> = compute_wake_damping_profile(
            clean.get_width(),
            clean.get_height(),
            clean.get_damping(),
            clean.get_sponge_width(),
            clean.get_sponge_strength(),
        );
        Self {
            config: clean,
            heights_curr: vec![0.0; total],
            heights_prev: vec![0.0; total],
            heights_next: vec![0.0; total],
            obstacle_mask: vec![0; total],
            foam: vec![0.0; total],
            cell_damping,
            last_dt_sub: 1.0 / 60.0,
            sim_time_secs: 0.0,
        }
    }

    /// Resets wave heights, velocities, foam, and simulation time to calm rest while preserving obstacles.
    pub fn reset(&mut self) {
        self.get_mut_heights_curr().fill(0.0);
        self.get_mut_heights_prev().fill(0.0);
        self.get_mut_heights_next().fill(0.0);
        self.get_mut_foam().fill(0.0);
        self.set_sim_time_secs(0.0);
    }

    /// Advances the shallow-water wave heightfield by `dt_secs` using CFL-clamped damped Verlet integration with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Elapsed frame time in seconds.
    pub fn step(&mut self, dt_secs: f32) {
        let clamped_dt: f32 = wake_sanitize_f32(dt_secs, 0.0).clamp(0.0, WAKE_MAX_DT_SECS);
        if clamped_dt <= 1e-6 {
            return;
        }
        let cfg: WaveHeightfieldConfig = self.get_config();
        let dx: f32 = cfg.get_cell_size_m();
        let speed: f32 = cfg.get_wave_speed_mps();
        let max_sub_dt: f32 = (WAKE_MAX_CFL_NUMBER * dx / speed).max(1e-5);
        let substeps: usize =
            ((clamped_dt / max_sub_dt).ceil() as usize).clamp(1, WAKE_MAX_SUBSTEPS);
        let dt_sub: f32 = clamped_dt / substeps as f32;
        let courant: f32 = (speed * dt_sub / dx).min(WAKE_MAX_CFL_NUMBER);
        let courant_sq: f32 = courant * courant;
        let width: usize = cfg.get_width();
        let height: usize = cfg.get_height();
        let foam_decay: f32 = cfg.get_foam_decay_rate();
        let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
        let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
        let mut heights_next: Vec<f32> = take(self.get_mut_heights_next());
        let mut foam: Vec<f32> = take(self.get_mut_foam());
        let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
        let cell_damping: Vec<f32> = take(self.get_mut_cell_damping());
        let substep_params: WakeSubstepParams =
            WakeSubstepParams::new(width, height, courant_sq, dt_sub, foam_decay);
        for _step_index in 0..substeps {
            step_wake_substep(
                substep_params,
                &heights_curr,
                &heights_prev,
                &obstacle_mask,
                &cell_damping,
                &mut heights_next,
                &mut foam,
            );
            swap(&mut heights_prev, &mut heights_curr);
            swap(&mut heights_curr, &mut heights_next);
        }
        self.set_heights_curr(heights_curr);
        self.set_heights_prev(heights_prev);
        self.set_heights_next(heights_next);
        self.set_foam(foam);
        self.set_obstacle_mask(obstacle_mask);
        self.set_cell_damping(cell_damping);
        self.set_last_dt_sub(dt_sub);
        let next_time: f32 = self.get_sim_time_secs() + clamped_dt;
        self.set_sim_time_secs(next_time);
    }

    /// Injects a circular splash disturbance at `(world_x, world_z)` with radius `radius_m` and peak amplitude `amplitude_m`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X splash center coordinate.
    /// - `f32` - World Z splash center coordinate.
    /// - `f32` - Splash footprint radius in meters.
    /// - `f32` - Displacement amplitude in meters (negative pushes water down to radiate a ring).
    pub fn inject_splash(&mut self, world_x: f32, world_z: f32, radius_m: f32, amplitude_m: f32) {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let foam_boost: f32 = (amplitude_m.abs() * 1.4).clamp(0.0, 0.85);
        let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
        let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
        let mut foam: Vec<f32> = take(self.get_mut_foam());
        let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
        let impulse: WakeImpulseDesc =
            WakeImpulseDesc::new(world_x, world_z, radius_m, amplitude_m, foam_boost);
        apply_wake_radial_impulse(
            cfg,
            impulse,
            &obstacle_mask,
            (&mut heights_curr, &mut heights_prev),
            &mut foam,
        );
        self.set_heights_curr(heights_curr);
        self.set_heights_prev(heights_prev);
        self.set_foam(foam);
        self.set_obstacle_mask(obstacle_mask);
    }

    /// Injects an expanding Kelvin boat wake along a moving vessel's horizontal velocity vector.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X hull center coordinate.
    /// - `f32` - World Z hull center coordinate.
    /// - `Vec2` - Horizontal vessel velocity `(vx, vz)` in meters per second.
    /// - `f32` - Characteristic hull beam radius in meters.
    /// - `f32` - Dimensionless wake intensity multiplier.
    pub fn inject_boat_wake(
        &mut self,
        world_x: f32,
        world_z: f32,
        velocity_xz: Vec2,
        hull_radius_m: f32,
        wake_strength: f32,
    ) {
        let vx: f32 = wake_sanitize_f32(velocity_xz.get_x(), 0.0);
        let vz: f32 = wake_sanitize_f32(velocity_xz.get_y(), 0.0);
        let speed: f32 = (vx * vx + vz * vz).sqrt();
        let safe_radius: f32 =
            wake_sanitize_f32(hull_radius_m, self.get_config().get_cell_size_m() * 2.0).max(0.1);
        let safe_strength: f32 = wake_sanitize_f32(wake_strength, 1.0).clamp(0.0, 4.0);
        if speed <= 1e-4 || safe_strength <= 1e-5 {
            return;
        }
        let dir_x: f32 = vx / speed;
        let dir_z: f32 = vz / speed;
        let bow_x: f32 = world_x + dir_x * safe_radius * 0.75;
        let bow_z: f32 = world_z + dir_z * safe_radius * 0.75;
        let stern_x: f32 = world_x - dir_x * safe_radius * 0.85;
        let stern_z: f32 = world_z - dir_z * safe_radius * 0.85;
        let amp: f32 = (0.045 * speed.min(14.0) * safe_strength).min(0.65);
        let cfg: WaveHeightfieldConfig = self.get_config();
        let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
        let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
        let mut foam: Vec<f32> = take(self.get_mut_foam());
        let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
        let bow_impulse: WakeImpulseDesc = WakeImpulseDesc::new(
            bow_x,
            bow_z,
            safe_radius * 0.85,
            amp,
            (amp * 1.1).clamp(0.0, 0.75),
        );
        let stern_impulse: WakeImpulseDesc = WakeImpulseDesc::new(
            stern_x,
            stern_z,
            safe_radius * 1.05,
            -amp * 0.85,
            (amp * 1.5).clamp(0.0, 0.95),
        );
        apply_wake_radial_impulse(
            cfg,
            bow_impulse,
            &obstacle_mask,
            (&mut heights_curr, &mut heights_prev),
            &mut foam,
        );
        apply_wake_radial_impulse(
            cfg,
            stern_impulse,
            &obstacle_mask,
            (&mut heights_curr, &mut heights_prev),
            &mut foam,
        );
        self.set_heights_curr(heights_curr);
        self.set_heights_prev(heights_prev);
        self.set_foam(foam);
        self.set_obstacle_mask(obstacle_mask);
    }

    /// Injects a localized raindrop ripple impulse at `(world_x, world_z)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X impact coordinate.
    /// - `f32` - World Z impact coordinate.
    /// - `f32` - Dimensionless raindrop intensity in `[0.0, 2.0]`.
    pub fn inject_raindrop(&mut self, world_x: f32, world_z: f32, intensity: f32) {
        let clamped: f32 = wake_sanitize_f32(intensity, 0.5).clamp(0.0, 2.0);
        let radius: f32 = self.get_config().get_cell_size_m() * 1.5;
        self.inject_splash(world_x, world_z, radius, -0.04 * clamped);
    }

    /// Marks or clears a world-space axis-aligned rectangular solid obstacle mask.
    ///
    /// # Arguments
    ///
    /// - `f32` - Minimum world X coordinate.
    /// - `f32` - Minimum world Z coordinate.
    /// - `f32` - Maximum world X coordinate.
    /// - `f32` - Maximum world Z coordinate.
    /// - `bool` - `true` to mark cells as reflective solid obstacles, `false` to restore fluid.
    pub fn set_obstacle_rect(
        &mut self,
        min_x: f32,
        min_z: f32,
        max_x: f32,
        max_z: f32,
        solid: bool,
    ) {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let width: usize = cfg.get_width();
        let height: usize = cfg.get_height();
        let dx: f32 = cfg.get_cell_size_m();
        let origin: Vec2 = cfg.get_origin_xz();
        let lo_x: f32 = min_x.min(max_x);
        let hi_x: f32 = min_x.max(max_x);
        let lo_z: f32 = min_z.min(max_z);
        let hi_z: f32 = min_z.max(max_z);
        let flag: u8 = u8::from(solid);
        let mut mask: Vec<u8> = take(self.get_mut_obstacle_mask());
        let mut curr: Vec<f32> = take(self.get_mut_heights_curr());
        let mut prev: Vec<f32> = take(self.get_mut_heights_prev());
        let mut foam: Vec<f32> = take(self.get_mut_foam());
        for row in 0..height {
            let wz: f32 = origin.get_y() + row as f32 * dx;
            if wz < lo_z || wz > hi_z {
                continue;
            }
            for col in 0..width {
                let wx: f32 = origin.get_x() + col as f32 * dx;
                if wx >= lo_x && wx <= hi_x {
                    let idx: usize = row * width + col;
                    mask[idx] = flag;
                    if solid {
                        curr[idx] = 0.0;
                        prev[idx] = 0.0;
                        foam[idx] = 0.0;
                    }
                }
            }
        }
        self.set_obstacle_mask(mask);
        self.set_heights_curr(curr);
        self.set_heights_prev(prev);
        self.set_foam(foam);
    }

    /// Marks or clears a world-space circular solid obstacle mask (e.g., pier piling or rock).
    ///
    /// # Arguments
    ///
    /// - `f32` - Center world X coordinate.
    /// - `f32` - Center world Z coordinate.
    /// - `f32` - Circle radius in meters.
    /// - `bool` - `true` to mark cells as reflective solid obstacles, `false` to restore fluid.
    pub fn set_obstacle_circle(
        &mut self,
        center_x: f32,
        center_z: f32,
        radius_m: f32,
        solid: bool,
    ) {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let width: usize = cfg.get_width();
        let height: usize = cfg.get_height();
        let dx: f32 = cfg.get_cell_size_m();
        let origin: Vec2 = cfg.get_origin_xz();
        let r_sq: f32 = radius_m.max(0.0) * radius_m.max(0.0);
        let flag: u8 = u8::from(solid);
        let mut mask: Vec<u8> = take(self.get_mut_obstacle_mask());
        let mut curr: Vec<f32> = take(self.get_mut_heights_curr());
        let mut prev: Vec<f32> = take(self.get_mut_heights_prev());
        let mut foam: Vec<f32> = take(self.get_mut_foam());
        for row in 0..height {
            let dz: f32 = origin.get_y() + row as f32 * dx - center_z;
            for col in 0..width {
                let dist_x: f32 = origin.get_x() + col as f32 * dx - center_x;
                if dist_x * dist_x + dz * dz <= r_sq {
                    let idx: usize = row * width + col;
                    mask[idx] = flag;
                    if solid {
                        curr[idx] = 0.0;
                        prev[idx] = 0.0;
                        foam[idx] = 0.0;
                    }
                }
            }
        }
        self.set_obstacle_mask(mask);
        self.set_heights_curr(curr);
        self.set_heights_prev(prev);
        self.set_foam(foam);
    }

    /// Clears all solid obstacle masks back to fluid.
    pub fn clear_obstacles(&mut self) {
        self.get_mut_obstacle_mask().fill(0);
    }

    /// Queries whether cell `(col, row)` is currently flagged as a solid obstacle.
    ///
    /// # Arguments
    ///
    /// - `usize` - Column index along X.
    /// - `usize` - Row index along Z.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the cell is solid.
    #[must_use]
    pub fn is_obstacle_cell(&self, col: usize, row: usize) -> bool {
        let cfg: WaveHeightfieldConfig = self.get_config();
        if col >= cfg.get_width() || row >= cfg.get_height() {
            return false;
        }
        self.get_obstacle_mask()[row * cfg.get_width() + col] != 0
    }

    /// Bilinearly samples the wave displacement relative to `base_water_y` at world `(world_x, world_z)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X coordinate.
    /// - `f32` - World Z coordinate.
    ///
    /// # Returns
    ///
    /// - `f32` - Signed vertical wave displacement in meters.
    #[must_use]
    pub fn sample_displacement(&self, world_x: f32, world_z: f32) -> f32 {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let origin: Vec2 = cfg.get_origin_xz();
        let dx: f32 = cfg.get_cell_size_m();
        let gx: f32 = (world_x - origin.get_x()) / dx;
        let gz: f32 = (world_z - origin.get_y()) / dx;
        wake_bilinear_sample(
            self.get_heights_curr(),
            cfg.get_width(),
            cfg.get_height(),
            gx,
            gz,
        )
    }

    /// Bilinearly samples the absolute world-space surface height `base_water_y + displacement` at `(world_x, world_z)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X coordinate.
    /// - `f32` - World Z coordinate.
    ///
    /// # Returns
    ///
    /// - `f32` - World-space water surface Y coordinate in meters.
    #[must_use]
    pub fn sample_height(&self, world_x: f32, world_z: f32) -> f32 {
        self.get_config().get_base_water_y() + self.sample_displacement(world_x, world_z)
    }

    /// Samples both absolute world-space surface height and analytical central-difference surface normal at `(world_x, world_z)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X coordinate.
    /// - `f32` - World Z coordinate.
    ///
    /// # Returns
    ///
    /// - `(f32, Vec3)` - Pair `(world_surface_y, unit_upward_normal)`.
    #[must_use]
    pub fn sample_height_and_normal(&self, world_x: f32, world_z: f32) -> (f32, Vec3) {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let eps: f32 = cfg.get_cell_size_m();
        let h_center: f32 = self.sample_height(world_x, world_z);
        let h_left: f32 = self.sample_displacement(world_x - eps, world_z);
        let h_right: f32 = self.sample_displacement(world_x + eps, world_z);
        let h_back: f32 = self.sample_displacement(world_x, world_z - eps);
        let h_fwd: f32 = self.sample_displacement(world_x, world_z + eps);
        let dh_dx: f32 = (h_right - h_left) / (2.0 * eps);
        let dh_dz: f32 = (h_fwd - h_back) / (2.0 * eps);
        let normal: Vec3 = Vec3::new(-dh_dx, 1.0, -dh_dz).normalize();
        (h_center, normal)
    }

    /// Bilinearly samples accumulated wake foam intensity in `[0.0, 1.0]` at `(world_x, world_z)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - World X coordinate.
    /// - `f32` - World Z coordinate.
    ///
    /// # Returns
    ///
    /// - `f32` - Wake foam coverage factor in `[0.0, 1.0]`.
    #[must_use]
    pub fn sample_foam(&self, world_x: f32, world_z: f32) -> f32 {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let origin: Vec2 = cfg.get_origin_xz();
        let dx: f32 = cfg.get_cell_size_m();
        let gx: f32 = (world_x - origin.get_x()) / dx;
        let gz: f32 = (world_z - origin.get_y()) / dx;
        wake_bilinear_sample(self.get_foam(), cfg.get_width(), cfg.get_height(), gx, gz)
            .clamp(0.0, 1.0)
    }

    /// Computes total discrete shallow-water Hamiltonian wave energy (kinetic + potential) across all fluid cells.
    ///
    /// # Returns
    ///
    /// - `f32` - Non-negative discrete mechanical wave energy.
    #[must_use]
    pub fn total_wave_energy(&self) -> f32 {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let width: usize = cfg.get_width();
        let height: usize = cfg.get_height();
        let dx: f32 = cfg.get_cell_size_m();
        let inv_dt: f32 = 1.0 / self.get_last_dt_sub().max(1e-5);
        let c_over_dx: f32 = cfg.get_wave_speed_mps() / dx;
        let c2_inv_dx2: f32 = c_over_dx * c_over_dx;
        let cell_area: f32 = dx * dx;
        let curr: &[f32] = self.get_heights_curr();
        let prev: &[f32] = self.get_heights_prev();
        let mask: &[u8] = self.get_obstacle_mask();
        let mut energy: f32 = 0.0;
        for row in 0..height {
            for col in 0..width {
                let idx: usize = row * width + col;
                if mask[idx] != 0 {
                    continue;
                }
                let vel: f32 = (curr[idx] - prev[idx]) * inv_dt;
                let grad_x: f32 = if col + 1 < width && mask[idx + 1] == 0 {
                    curr[idx + 1] - curr[idx]
                } else {
                    0.0
                };
                let grad_z: f32 = if row + 1 < height && mask[idx + width] == 0 {
                    curr[idx + width] - curr[idx]
                } else {
                    0.0
                };
                energy += 0.5
                    * cell_area
                    * (vel * vel + c2_inv_dx2 * (grad_x * grad_x + grad_z * grad_z));
            }
        }
        energy
    }

    /// Returns the maximum absolute displacement amplitude across the entire heightfield.
    ///
    /// # Returns
    ///
    /// - `f32` - Maximum `|h|` in meters.
    #[must_use]
    pub fn max_abs_height(&self) -> f32 {
        let mut max_val: f32 = 0.0;
        for &val in self.get_heights_curr().iter() {
            let abs_v: f32 = val.abs();
            if abs_v > max_val {
                max_val = abs_v;
            }
        }
        max_val
    }

    /// Builds an indexed `Mesh3D` representing the current wave surface with analytical normals and vertex foam colors.
    ///
    /// # Arguments
    ///
    /// - `&str` - Asset mesh name (falls back to `WAKE_DEFAULT_MESH_NAME` when empty).
    /// - `PbrMaterial` - Water surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Mesh3D` - Renderable triangle mesh for the heightfield surface.
    #[must_use]
    pub fn build_mesh(&self, name: &str, material: PbrMaterial) -> Mesh3D {
        let cfg: WaveHeightfieldConfig = self.get_config();
        let width: usize = cfg.get_width();
        let height: usize = cfg.get_height();
        let dx: f32 = cfg.get_cell_size_m();
        let origin: Vec2 = cfg.get_origin_xz();
        let base_y: f32 = cfg.get_base_water_y();
        let inv_w: f32 = 1.0 / (width.saturating_sub(1).max(1) as f32);
        let inv_h: f32 = 1.0 / (height.saturating_sub(1).max(1) as f32);
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(width * height);
        for row in 0..height {
            let wz: f32 = origin.get_y() + row as f32 * dx;
            let v_coord: f32 = row as f32 * inv_h;
            for col in 0..width {
                let wx: f32 = origin.get_x() + col as f32 * dx;
                let u_coord: f32 = col as f32 * inv_w;
                let idx: usize = row * width + col;
                let h_val: f32 = self.get_heights_curr()[idx];
                let (_, normal): (f32, Vec3) = self.sample_height_and_normal(wx, wz);
                let foam_v: f32 = self.get_foam()[idx].clamp(0.0, 1.0);
                let foam_u8: u8 = (foam_v * 255.0).round() as u8;
                let vert: Vertex3D = Vertex3D::from_full(
                    Vec3::new(wx, base_y + h_val, wz),
                    normal,
                    [1.0, 0.0, 0.0, 1.0],
                    [u_coord, v_coord],
                    [foam_v, 0.0],
                    [255, 255, 255, foam_u8.max(180)],
                    0b1101,
                );
                vertices.push(vert);
            }
        }
        let quad_count: usize = width.saturating_sub(1) * height.saturating_sub(1);
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(quad_count * 2);
        for row in 0..height.saturating_sub(1) {
            for col in 0..width.saturating_sub(1) {
                let i00: u32 = (row * width + col) as u32;
                let i10: u32 = i00 + 1;
                let i01: u32 = ((row + 1) * width + col) as u32;
                let i11: u32 = i01 + 1;
                indices.push([i00, i01, i10]);
                indices.push([i10, i01, i11]);
            }
        }
        let mesh_name: String = if name.is_empty() {
            WAKE_DEFAULT_MESH_NAME.to_string()
        } else {
            name.to_string()
        };
        Mesh3D::from_parts(mesh_name, vertices, indices, material)
    }
}