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
use super::*;

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

/// Advances a deterministic SplitMix64 PRNG and returns a uniform float in `[0.0, 1.0)`.
///
/// # Arguments
///
/// - `&mut u64` - Mutable 64-bit PRNG state.
///
/// # Returns
///
/// - `f32` - Uniformly distributed deterministic scalar in `[0.0, 1.0)`.
pub(crate) fn ocean_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;
    let mantissa: u32 = (mixed >> 40) as u32;
    mantissa as f32 * (1.0 / 16_777_216.0)
}

/// Evaluates the JONSWAP 1D wave energy spectral density `S(omega)` in `m^2 * s / rad`.
///
/// # Arguments
///
/// - `f32` - Wave angular frequency `omega` in `rad/s`.
/// - `f32` - Wind speed `U10` in meters per second.
/// - `f32` - Wind fetch distance in meters.
/// - `f32` - Gravitational acceleration in `m/s^2`.
///
/// # Returns
///
/// - `f32` - Non-negative spectral energy density `S(omega)`.
pub(crate) fn jonswap_spectral_density(
    omega: f32,
    wind_mps: f32,
    fetch_m: f32,
    gravity: f32,
) -> f32 {
    if omega <= 1e-4 || wind_mps <= 0.1 || fetch_m <= 10.0 {
        return 0.0;
    }
    let dimensionless_fetch: f32 = (gravity * fetch_m / (wind_mps * wind_mps)).max(1.0);
    let alpha: f32 = 0.076 * dimensionless_fetch.powf(-0.22);
    let omega_p: f32 = 22.0 * (gravity * gravity / (wind_mps * fetch_m)).powf(1.0 / 3.0);
    let sigma: f32 = if omega <= omega_p {
        OCEAN_JONSWAP_SIGMA_A
    } else {
        OCEAN_JONSWAP_SIGMA_B
    };
    let ratio: f32 = (omega - omega_p) / (sigma * omega_p).max(1e-4);
    let peak_exp: f32 = (-0.5 * ratio * ratio).exp();
    let pm_exp: f32 = (-1.25 * (omega_p / omega).powi(4)).exp();
    let omega_5: f32 = omega.powi(5).max(1e-6);
    let base: f32 = (alpha * gravity * gravity / omega_5) * pm_exp;
    let enhanced: f32 = base * OCEAN_JONSWAP_GAMMA.powf(peak_exp);
    ocean_sanitize_f32(enhanced, 0.0).max(0.0)
}

/// Synthesizes multi-cascade directional Gerstner waves weighted by the JONSWAP sea spectrum.
///
/// # Arguments
///
/// - `OceanConfig` - Sanitized ocean configuration.
///
/// # Returns
///
/// - `Vec<GerstnerWaveComponent>` - Steepness-normalized multi-cascade Gerstner wave components.
pub(crate) fn synthesize_jonswap_gerstner_waves(config: OceanConfig) -> Vec<GerstnerWaveComponent> {
    let cascades: usize = (config.get_cascade_count() as usize).clamp(1, 4);
    let total_waves: usize = cascades * OCEAN_WAVES_PER_CASCADE;
    let mut waves: Vec<GerstnerWaveComponent> = Vec::with_capacity(total_waves);
    let wind_dir_raw: Vec2 = config.get_wind_direction();
    let wind_len: f32 = (wind_dir_raw.get_x() * wind_dir_raw.get_x()
        + wind_dir_raw.get_y() * wind_dir_raw.get_y())
    .sqrt();
    let base_angle: f32 = if wind_len > 1e-5 {
        wind_dir_raw.get_y().atan2(wind_dir_raw.get_x())
    } else {
        0.35
    };
    let wind_mps: f32 = config.get_wind_speed_mps();
    let fetch_m: f32 = config.get_fetch_km() * 1000.0;
    let gravity: f32 = config.get_gravity_mps2();
    let choppiness: f32 = config.get_choppiness();
    let mut rng: u64 = config.get_seed().max(1);
    let cascade_wavelength_ranges: [(f32, f32); 4] =
        [(28.0, 96.0), (8.0, 26.0), (2.4, 7.5), (0.85, 2.2)];
    let cascade_spread_rad: [f32; 4] = [0.42, 0.78, 1.15, 1.45];
    let cascade_amp_scale: [f32; 4] = [1.0, 0.62, 0.34, 0.18];
    let mut raw_steepness_sum: f32 = 0.0;
    for cascade_idx in 0..cascades {
        let (min_wl, max_wl): (f32, f32) = cascade_wavelength_ranges[cascade_idx];
        let spread: f32 = cascade_spread_rad[cascade_idx];
        let amp_scale: f32 = cascade_amp_scale[cascade_idx];
        let ln_min: f32 = min_wl.ln();
        let ln_max: f32 = max_wl.ln();
        for wave_idx in 0..OCEAN_WAVES_PER_CASCADE {
            let frac: f32 = (wave_idx as f32 + 0.5 + (ocean_next_unit_f32(&mut rng) - 0.5) * 0.45)
                / OCEAN_WAVES_PER_CASCADE as f32;
            let wavelength: f32 = (ln_min + (ln_max - ln_min) * frac.clamp(0.02, 0.98)).exp();
            let k_val: f32 = TAU / wavelength;
            let omega: f32 = (gravity * k_val).sqrt();
            let d_omega: f32 = (omega * 0.28).max(0.05);
            let spec: f32 = jonswap_spectral_density(omega, wind_mps, fetch_m, gravity);
            let spectral_amp: f32 = (2.0 * spec * d_omega).sqrt();
            let fallback_amp: f32 = 0.004 * wind_mps * (wavelength / 24.0).sqrt();
            let amplitude: f32 = (spectral_amp.max(fallback_amp) * amp_scale).clamp(0.004, 3.2);
            let angle_jitter: f32 = (ocean_next_unit_f32(&mut rng) * 2.0 - 1.0) * spread;
            let dir_angle: f32 = base_angle + angle_jitter;
            let direction: Vec2 = Vec2::new(dir_angle.cos(), dir_angle.sin());
            let phase: f32 = ocean_next_unit_f32(&mut rng) * TAU;
            let steepness: f32 = (k_val * amplitude * choppiness * 1.15).clamp(0.0, 0.35);
            raw_steepness_sum += steepness;
            waves.push(GerstnerWaveComponent::new(
                direction,
                wavelength,
                amplitude,
                steepness,
                phase,
                1.0,
                cascade_idx as u8,
            ));
        }
    }
    if raw_steepness_sum > OCEAN_MAX_TOTAL_STEEPNESS {
        let norm_factor: f32 = OCEAN_MAX_TOTAL_STEEPNESS / raw_steepness_sum;
        for wave in waves.iter_mut() {
            let scaled: f32 = wave.get_steepness() * norm_factor;
            wave.set_steepness(scaled);
        }
    }
    waves
}

/// Evaluates analytical Gerstner 3D displacement, exact tangents, unit normal, Jacobian, and foam mask.
///
/// # Arguments
///
/// - `&[GerstnerWaveComponent]` - Active directional wave train slice.
/// - `OceanConfig` - Active ocean configuration.
/// - `f32` - Elapsed simulation time in seconds.
/// - `f32` - Undisplaced horizontal X coordinate.
/// - `f32` - Undisplaced horizontal Z coordinate.
///
/// # Returns
///
/// - `OceanSurfaceSample` - Exact analytical surface geometry and Jacobian foam sample.
pub(crate) fn evaluate_gerstner_sample(
    waves: &[GerstnerWaveComponent],
    config: OceanConfig,
    sim_time: f32,
    coord_x: f32,
    coord_z: f32,
) -> OceanSurfaceSample {
    let safe_x: f32 = ocean_sanitize_f32(coord_x, 0.0);
    let safe_z: f32 = ocean_sanitize_f32(coord_z, 0.0);
    let gravity: f32 = config.get_gravity_mps2();
    let mut disp_x: f32 = 0.0;
    let mut disp_y: f32 = 0.0;
    let mut disp_z: f32 = 0.0;
    let mut dpx_dx: f32 = 1.0;
    let mut dpy_dx: f32 = 0.0;
    let mut dpz_dx: f32 = 0.0;
    let mut dpx_dz: f32 = 0.0;
    let mut dpy_dz: f32 = 0.0;
    let mut dpz_dz: f32 = 1.0;
    for wave in waves.iter() {
        let wl: f32 = wave.get_wavelength_m().max(0.05);
        let k_val: f32 = TAU / wl;
        let omega: f32 = (gravity * k_val).sqrt() * wave.get_speed_multiplier();
        let dir: Vec2 = wave.get_direction();
        let dx: f32 = dir.get_x();
        let dz: f32 = dir.get_y();
        let amp: f32 = wave.get_amplitude_m();
        let steep: f32 = wave.get_steepness();
        let horiz_amp: f32 = steep / k_val;
        let theta: f32 =
            k_val * (dx * safe_x + dz * safe_z) - omega * sim_time + wave.get_phase_offset();
        let (sin_t, cos_t): (f32, f32) = theta.sin_cos();
        disp_x -= horiz_amp * dx * sin_t;
        disp_y += amp * cos_t;
        disp_z -= horiz_amp * dz * sin_t;
        let k_amp: f32 = k_val * amp;
        let steep_cos: f32 = steep * cos_t;
        dpx_dx -= steep_cos * dx * dx;
        dpy_dx -= k_amp * dx * sin_t;
        dpz_dx -= steep_cos * dz * dx;
        dpx_dz -= steep_cos * dx * dz;
        dpy_dz -= k_amp * dz * sin_t;
        dpz_dz -= steep_cos * dz * dz;
    }
    let tangent_x: Vec3 = Vec3::new(dpx_dx, dpy_dx, dpz_dx);
    let tangent_z: Vec3 = Vec3::new(dpx_dz, dpy_dz, dpz_dz);
    let normal: Vec3 = tangent_z.cross(tangent_x).normalize();
    let jacobian: f32 = ocean_sanitize_f32(dpx_dx * dpz_dz - dpx_dz * dpz_dx, 1.0);
    let foam_thresh: f32 = config.get_optics().get_foam_jacobian_threshold();
    let fold_foam: f32 = if jacobian < foam_thresh {
        ((foam_thresh - jacobian) / foam_thresh.max(0.1)).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let crest_boost: f32 = (disp_y.max(0.0) * 0.25 * (1.0 - jacobian).max(0.0)).clamp(0.0, 0.45);
    let foam_mask: f32 = (fold_foam + crest_boost).clamp(0.0, 1.0);
    let displacement: Vec3 = Vec3::new(disp_x, disp_y, disp_z);
    let displaced_position: Vec3 = Vec3::new(
        safe_x + disp_x,
        config.get_mean_water_level_y() + disp_y,
        safe_z + disp_z,
    );
    OceanSurfaceSample::new(
        displaced_position,
        displacement,
        normal,
        tangent_x,
        tangent_z,
        jacobian,
        foam_mask,
    )
}

/// Evaluates analytical seabed caustics projection intensity from multi-cascade wave focusing.
///
/// # Arguments
///
/// - `&[GerstnerWaveComponent]` - Active wave components.
/// - `f32` - Gravity in `m/s^2`.
/// - `f32` - Elapsed simulation time in seconds.
/// - `Vec3` - Seabed world position `(x, y, z)`.
/// - `Vec3` - Unit sun direction pointing toward the light source.
/// - `f32` - Water column depth above seabed in meters.
/// - `f32` - Caustics gain scalar.
///
/// # Returns
///
/// - `f32` - Non-negative finite seabed caustics intensity.
pub(crate) fn evaluate_ocean_caustics(
    waves: &[GerstnerWaveComponent],
    gravity: f32,
    sim_time: f32,
    seabed_pos: Vec3,
    sun_dir: Vec3,
    water_depth_m: f32,
    caustics_strength: f32,
) -> f32 {
    if water_depth_m <= 0.01 || caustics_strength <= 0.0 || waves.is_empty() {
        return 0.0;
    }
    let safe_sun: Vec3 = sun_dir.normalize();
    let sun_y: f32 = safe_sun.get_y().max(0.12);
    let proj_x: f32 = seabed_pos.get_x() + safe_sun.get_x() * (water_depth_m / sun_y);
    let proj_z: f32 = seabed_pos.get_z() + safe_sun.get_z() * (water_depth_m / sun_y);
    let mut curvature_sum: f32 = 0.0;
    let mut weight_sum: f32 = 0.0;
    for wave in waves.iter() {
        let wl: f32 = wave.get_wavelength_m().max(0.2);
        let k_val: f32 = TAU / wl;
        let omega: f32 = (gravity * k_val).sqrt() * wave.get_speed_multiplier();
        let dir: Vec2 = wave.get_direction();
        let theta: f32 = k_val * (dir.get_x() * proj_x + dir.get_y() * proj_z) - omega * sim_time
            + wave.get_phase_offset();
        let focus: f32 = (0.5 + 0.5 * theta.cos()).powi(3);
        let weight: f32 = (k_val * wave.get_amplitude_m()).clamp(0.01, 1.0);
        curvature_sum += focus * weight;
        weight_sum += weight;
    }
    let normalized_focus: f32 = if weight_sum > 1e-6 {
        (curvature_sum / weight_sum).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let depth_fade: f32 = (-0.12 * water_depth_m).exp() * (1.0 - (-1.5 * water_depth_m).exp());
    let intensity: f32 = caustics_strength * normalized_focus * normalized_focus * depth_fade * 2.2;
    ocean_sanitize_f32(intensity, 0.0).clamp(0.0, 3.0)
}

/// Integrates one rigid-body buoyancy step over sampled water heights and normals at each pontoon.
///
/// # Arguments
///
/// - `&mut BuoyantHull3D` - Mutable floating vessel rigid body.
/// - `&[(f32, Vec3)]` - Sampled `(water_height_y, surface_normal)` for each pontoon point.
/// - `f32` - Clamped integration step duration in seconds.
pub(crate) fn integrate_buoyant_hull_step(
    hull: &mut BuoyantHull3D,
    water_samples: &[(f32, Vec3)],
    dt_secs: f32,
) {
    let cfg: BuoyantHullConfig = hull.get_config();
    let mass: f32 = cfg.get_mass_kg().max(0.1);
    let inv_mass: f32 = 1.0 / mass;
    let gravity: f32 = cfg.get_gravity_mps2();
    let rho: f32 = cfg.get_fluid_density_kgm3();
    let pos: Vec3 = hull.get_position();
    let vel: Vec3 = hull.get_velocity();
    let orient: Quat = hull.get_orientation().normalize();
    let ang_vel: Vec3 = hull.get_angular_velocity();
    let mut total_force: Vec3 = Vec3::new(0.0, -mass * gravity, 0.0);
    let mut net_buoyancy: Vec3 = Vec3::zero();
    let mut total_torque: Vec3 = Vec3::zero();
    let mut total_volume: f32 = 0.0;
    let mut submerged_volume: f32 = 0.0;
    let mut weighted_normal: Vec3 = Vec3::zero();
    let mut linear_drag_rate: f32 = 0.0;
    let pontoons: &[PontoonSamplePoint] = hull.get_pontoons();
    let count: usize = pontoons.len().min(water_samples.len());
    let drag_scale: f32 = 1.0 / count.max(1) as f32;
    for idx in 0..count {
        let pontoon: PontoonSamplePoint = pontoons[idx];
        let (water_y, water_normal): (f32, Vec3) = water_samples[idx];
        let r_world: Vec3 = orient.rotate_vec3(pontoon.get_local_offset());
        let sample_world: Vec3 = pos.add(r_world);
        let radius: f32 = pontoon.get_sample_radius_m().max(0.05);
        let depth: f32 = water_y - (sample_world.get_y() - radius);
        let frac: f32 = (depth / (2.0 * radius)).clamp(0.0, 1.0);
        let p_vol: f32 = pontoon.get_submerged_volume_m3().max(0.0);
        total_volume += p_vol;
        let v_sub: f32 = p_vol * frac;
        submerged_volume += v_sub;
        if frac > 0.0 {
            let wetted: f32 = frac.sqrt();
            let f_buoy: Vec3 = Vec3::new(0.0, rho * gravity * v_sub, 0.0);
            let point_vel: Vec3 = vel.add(ang_vel.cross(r_world));
            let speed: f32 = point_vel.length();
            let point_drag_coeff: f32 =
                (cfg.get_linear_drag() + cfg.get_quadratic_drag() * speed) * wetted * drag_scale;
            linear_drag_rate += point_drag_coeff * inv_mass;
            let rot_vel: Vec3 = ang_vel.cross(r_world);
            let rot_drag: Vec3 = rot_vel.scale(-point_drag_coeff);
            total_force = total_force.add(f_buoy);
            net_buoyancy = net_buoyancy.add(f_buoy);
            total_torque = total_torque.add(r_world.cross(f_buoy.add(rot_drag)));
            weighted_normal = weighted_normal.add(water_normal.scale(frac));
        }
    }
    let avg_submerged: f32 = if total_volume > 1e-6 {
        (submerged_volume / total_volume).clamp(0.0, 1.0)
    } else {
        0.0
    };
    if avg_submerged > 0.0 && weighted_normal.length_sq() > 1e-6 {
        let target_up: Vec3 = weighted_normal.normalize();
        let hull_up: Vec3 = orient.rotate_vec3(Vec3::new(0.0, 1.0, 0.0)).normalize();
        let align_axis: Vec3 = hull_up.cross(target_up);
        let slope_torque: Vec3 = align_axis.scale(cfg.get_slope_alignment_torque() * avg_submerged);
        total_torque = total_torque.add(slope_torque);
    }
    let lin_damp_denom: f32 = 1.0 + linear_drag_rate.max(0.0) * dt_secs;
    let mut next_vel: Vec3 = vel
        .add(total_force.scale(inv_mass * dt_secs))
        .scale(1.0 / lin_damp_denom);
    let lin_speed: f32 = next_vel.length();
    if !lin_speed.is_finite() {
        next_vel = Vec3::zero();
    } else if lin_speed > cfg.get_max_linear_speed() {
        next_vel = next_vel.scale(cfg.get_max_linear_speed() / lin_speed);
    }
    let next_pos: Vec3 = pos.add(next_vel.scale(dt_secs));
    let inertia: Vec3 = cfg.get_inertia_diag();
    let local_torque: Vec3 = orient.conjugate().rotate_vec3(total_torque);
    let local_alpha: Vec3 = Vec3::new(
        local_torque.get_x() / inertia.get_x().max(0.1),
        local_torque.get_y() / inertia.get_y().max(0.1),
        local_torque.get_z() / inertia.get_z().max(0.1),
    );
    let world_alpha: Vec3 = orient.rotate_vec3(local_alpha);
    let avg_inertia: f32 = ((inertia.get_x() + inertia.get_y() + inertia.get_z()) / 3.0).max(0.1);
    let ang_damp_rate: f32 =
        cfg.get_angular_drag() * (0.15 + 0.85 * avg_submerged.sqrt()) / avg_inertia;
    let ang_damp_denom: f32 = 1.0 + ang_damp_rate.max(0.0) * dt_secs;
    let mut next_ang_vel: Vec3 = ang_vel
        .add(world_alpha.scale(dt_secs))
        .scale(1.0 / ang_damp_denom);
    let ang_speed: f32 = next_ang_vel.length();
    if !ang_speed.is_finite() {
        next_ang_vel = Vec3::zero();
    } else if ang_speed > cfg.get_max_angular_speed() {
        next_ang_vel = next_ang_vel.scale(cfg.get_max_angular_speed() / ang_speed);
    }
    let omega_quat: Quat = Quat::from_xyzw(
        next_ang_vel.get_x(),
        next_ang_vel.get_y(),
        next_ang_vel.get_z(),
        0.0,
    );
    let q_dot: Quat = omega_quat.mul_quat(orient);
    let half_dt: f32 = 0.5 * dt_secs;
    let next_orient: Quat = Quat::from_xyzw(
        orient.get_x() + q_dot.get_x() * half_dt,
        orient.get_y() + q_dot.get_y() * half_dt,
        orient.get_z() + q_dot.get_z() * half_dt,
        orient.get_w() + q_dot.get_w() * half_dt,
    )
    .normalize();
    let safe_pos: Vec3 = if next_pos.get_x().is_finite()
        && next_pos.get_y().is_finite()
        && next_pos.get_z().is_finite()
    {
        next_pos
    } else {
        pos
    };
    hull.set_position(safe_pos);
    hull.set_velocity(next_vel);
    hull.set_orientation(next_orient);
    hull.set_angular_velocity(next_ang_vel);
    hull.set_submerged_fraction(avg_submerged);
    hull.set_buoyancy_force(net_buoyancy);
}