Skip to main content

euv_core/game/fluid/renderer/
impl.rs

1use super::*;
2
3/// Default empty pre-warmed optical liquid renderer.
4impl Default for LiquidOpticalRenderer {
5    /// Creates a `LiquidOpticalRenderer` ready to allocate field scratch buffers on first render.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default optical liquid renderer.
10    fn default() -> Self {
11        Self::new_renderer()
12    }
13}
14
15/// Scalar field splatting, separable Gaussian smoothing, gradient/caustic synthesis, and parallel optical shading for `LiquidOpticalRenderer`.
16impl LiquidOpticalRenderer {
17    /// Constructs a new `LiquidOpticalRenderer` with pre-allocated default field storage.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Ready optical liquid renderer.
22    #[must_use]
23    pub fn new_renderer() -> Self {
24        let init_w: usize = 144;
25        let init_h: usize = 108;
26        let len: usize = init_w * init_h;
27        Self {
28            field_w: init_w,
29            field_h: init_h,
30            phi: vec![0.0; len],
31            phi_tmp: vec![0.0; len],
32            thickness: vec![0.0; len],
33            thick_tmp: vec![0.0; len],
34            foam: vec![0.0; len],
35            grad_x: vec![0.0; len],
36            grad_y: vec![0.0; len],
37            caustic: vec![0.0; len],
38            last_width: 0,
39            last_height: 0,
40        }
41    }
42
43    /// Computes capped optical render dimensions `(render_w, render_h)` preserving viewport aspect ratio for arbitrary resize and fullscreen modes.
44    ///
45    /// # Arguments
46    ///
47    /// - `u32` - Target viewport width in logical pixels.
48    /// - `u32` - Target viewport height in logical pixels.
49    ///
50    /// # Returns
51    ///
52    /// - `(u32, u32)` - Optimal internal optical RGBA8 `(width, height)` clamped to `[FLUID_RENDER_MIN_DIM, FLUID_RENDER_MAX_DIM]`.
53    #[must_use]
54    pub fn resolve_render_dimensions(viewport_w: u32, viewport_h: u32) -> (u32, u32) {
55        let vw: f32 = (viewport_w.max(FLUID_RENDER_MIN_DIM)) as f32;
56        let vh: f32 = (viewport_h.max(FLUID_RENDER_MIN_DIM)) as f32;
57        let max_dim: f32 = FLUID_RENDER_MAX_DIM as f32;
58        let dim_scale: f32 = (max_dim / vw.max(vh)).min(1.0);
59        let area_scale: f32 = (FLUID_RENDER_MAX_PIXELS / (vw * vh).max(1.0))
60            .sqrt()
61            .min(1.0);
62        let scale: f32 = dim_scale.min(area_scale);
63        let rw: u32 =
64            ((vw * scale).round() as u32).clamp(FLUID_RENDER_MIN_DIM, FLUID_RENDER_MAX_DIM);
65        let rh: u32 =
66            ((vh * scale).round() as u32).clamp(FLUID_RENDER_MIN_DIM, FLUID_RENDER_MAX_DIM);
67        (rw, rh)
68    }
69
70    /// Ensures internal scalar field arrays match `(fw, fh)` without reallocating when dimensions are unchanged.
71    ///
72    /// # Arguments
73    ///
74    /// - `&Self` - Mutable optical renderer.
75    /// - `usize` - Target field width in cells.
76    /// - `usize` - Target field height in cells.
77    fn ensure_field_capacity(&mut self, fw: usize, fh: usize) {
78        let len: usize = fw * fh;
79        if self.get_field_w() == fw && self.get_field_h() == fh && self.get_phi().len() == len {
80            return;
81        }
82        self.set_field_w(fw);
83        self.set_field_h(fh);
84        let Self {
85            phi,
86            phi_tmp,
87            thickness,
88            thick_tmp,
89            foam,
90            grad_x,
91            grad_y,
92            caustic,
93            ..
94        } = self;
95        phi.resize(len, 0.0);
96        phi_tmp.resize(len, 0.0);
97        thickness.resize(len, 0.0);
98        thick_tmp.resize(len, 0.0);
99        foam.resize(len, 0.0);
100        grad_x.resize(len, 0.0);
101        grad_y.resize(len, 0.0);
102        caustic.resize(len, 0.0);
103    }
104
105    /// Applies one separable 5-tap binomial Gaussian pass (`[1, 4, 6, 4, 1] / 16`) across `src` using `tmp`.
106    ///
107    /// # Arguments
108    ///
109    /// - `&mut [f32]` - Input and output field slice.
110    /// - `&mut [f32]` - Horizontal pass scratch slice.
111    /// - `usize` - Field width in cells.
112    /// - `usize` - Field height in cells.
113    fn blur_field_separable(src: &mut [f32], tmp: &mut [f32], w: usize, h: usize) {
114        if w < 5 || h < 5 {
115            return;
116        }
117        let inv16: f32 = 1.0 / 16.0;
118        for y in 0..h {
119            let row: usize = y * w;
120            tmp[row] = (src[row] * 11.0 + src[row + 1] * 4.0 + src[row + 2]) * inv16;
121            tmp[row + 1] =
122                (src[row] * 5.0 + src[row + 1] * 6.0 + src[row + 2] * 4.0 + src[row + 3]) * inv16;
123            for x in 2..(w - 2) {
124                let idx: usize = row + x;
125                tmp[idx] = (src[idx - 2]
126                    + src[idx - 1] * 4.0
127                    + src[idx] * 6.0
128                    + src[idx + 1] * 4.0
129                    + src[idx + 2])
130                    * inv16;
131            }
132            let r2: usize = row + w - 2;
133            tmp[r2] = (src[r2 - 2] + src[r2 - 1] * 4.0 + src[r2] * 6.0 + src[r2 + 1] * 5.0) * inv16;
134            let r1: usize = row + w - 1;
135            tmp[r1] = (src[r1 - 2] + src[r1 - 1] * 4.0 + src[r1] * 11.0) * inv16;
136        }
137        for y in 0..h {
138            let ym2: usize = y.saturating_sub(2) * w;
139            let ym1: usize = y.saturating_sub(1) * w;
140            let y0: usize = y * w;
141            let yp1: usize = (y + 1).min(h - 1) * w;
142            let yp2: usize = (y + 2).min(h - 1) * w;
143            for x in 0..w {
144                src[y0 + x] = (tmp[ym2 + x]
145                    + tmp[ym1 + x] * 4.0
146                    + tmp[y0 + x] * 6.0
147                    + tmp[yp1 + x] * 4.0
148                    + tmp[yp2 + x])
149                    * inv16;
150            }
151        }
152    }
153
154    /// Splats fluid particles and bubbles onto scalar fields, runs separable smoothing, and derives analytical surface normals and optical caustics.
155    ///
156    /// # Arguments
157    ///
158    /// - `&Self` - Mutable optical renderer.
159    /// - `&FluidSimSnapshot` - Interpolated simulation snapshot to splat.
160    fn build_optical_fields(&mut self, snapshot: &FluidSimSnapshot) {
161        let fw: usize = self.get_field_w();
162        let fh: usize = self.get_field_h();
163        let len: usize = fw * fh;
164        let vw: f32 = snapshot.get_vessel_width_m().max(1.0e-4);
165        let vh: f32 = snapshot.get_vessel_height_m().max(1.0e-4);
166        let n: usize = snapshot.get_particle_count().min(FLUID_MAX_PARTICLES);
167        let h_m: f32 = snapshot.get_kernel_radius_m().max(0.003);
168        let scale_x: f32 = ((fw.saturating_sub(1)) as f32) / vw;
169        let scale_y: f32 = ((fh.saturating_sub(1)) as f32) / vh;
170        let splat_rx: f32 = (h_m * 0.78 * scale_x).clamp(2.2, 7.5);
171        let splat_ry: f32 = (h_m * 0.78 * scale_y).clamp(2.2, 7.5);
172        let irx: i32 = splat_rx.ceil() as i32;
173        let iry: i32 = splat_ry.ceil() as i32;
174        let inv_rx: f32 = 1.0 / splat_rx;
175        let inv_ry: f32 = 1.0 / splat_ry;
176        let px: &[f32] = snapshot.get_pos_x();
177        let py: &[f32] = snapshot.get_pos_y();
178        let vx: &[f32] = snapshot.get_vel_x();
179        let vy: &[f32] = snapshot.get_vel_y();
180        let dens_ratio: &[f32] = snapshot.get_density_ratio();
181        let fw_i: i32 = fw as i32;
182        let fh_i: i32 = fh as i32;
183        let Self {
184            phi,
185            phi_tmp,
186            thickness,
187            thick_tmp,
188            foam,
189            grad_x,
190            grad_y,
191            caustic,
192            ..
193        } = self;
194        phi[..len].fill(0.0);
195        thickness[..len].fill(0.0);
196        foam[..len].fill(0.0);
197        for i in 0..n {
198            let fx: f32 = px[i] * scale_x;
199            let fy: f32 = py[i] * scale_y;
200            let cx: i32 = fx.round() as i32;
201            let cy: i32 = fy.round() as i32;
202            let x0: i32 = (cx - irx).max(0);
203            let x1: i32 = (cx + irx).min(fw_i - 1);
204            let y0: i32 = (cy - iry).max(0);
205            let y1: i32 = (cy + iry).min(fh_i - 1);
206            let spd2: f32 = vx[i] * vx[i] + vy[i] * vy[i];
207            let foam_emit: f32 = if spd2 > 0.06 && dens_ratio[i] < 0.88 {
208                ((spd2.sqrt() - 0.24) * 1.15).clamp(0.0, 0.95)
209            } else {
210                0.0
211            };
212            for gy_i in y0..=y1 {
213                let dy: f32 = ((gy_i as f32) - fy) * inv_ry;
214                let dy2: f32 = dy * dy;
215                if dy2 >= 1.0 {
216                    continue;
217                }
218                let row: usize = (gy_i as usize) * fw;
219                for gx_i in x0..=x1 {
220                    let dx: f32 = ((gx_i as f32) - fx) * inv_rx;
221                    let q2: f32 = dx * dx + dy2;
222                    if q2 < 1.0 {
223                        let omt: f32 = 1.0 - q2;
224                        let w_kern: f32 = omt * omt;
225                        let idx: usize = row + (gx_i as usize);
226                        phi[idx] += w_kern * 0.42;
227                        thickness[idx] += w_kern * 0.28;
228                        if foam_emit > 0.0 {
229                            foam[idx] += w_kern * foam_emit * 0.45;
230                        }
231                    }
232                }
233            }
234        }
235        let bub_cnt: usize = snapshot.get_bubble_count().min(FLUID_MAX_BUBBLES);
236        for bub in snapshot.get_bubbles().iter().take(bub_cnt) {
237            if bub.get_foam_factor() > 0.35 {
238                let bx: usize =
239                    ((bub.get_x() * scale_x).round() as i32).clamp(0, fw_i - 1) as usize;
240                let by: usize =
241                    ((bub.get_y() * scale_y).round() as i32).clamp(0, fh_i - 1) as usize;
242                let fade: f32 =
243                    (1.0 - bub.get_age() / bub.get_lifetime().max(0.05)).clamp(0.0, 1.0);
244                foam[by * fw + bx] += bub.get_foam_factor() * fade * 0.65;
245            }
246        }
247        Self::blur_field_separable(phi, phi_tmp, fw, fh);
248        Self::blur_field_separable(phi, phi_tmp, fw, fh);
249        Self::blur_field_separable(thickness, thick_tmp, fw, fh);
250        Self::blur_field_separable(foam, phi_tmp, fw, fh);
251        let inv_fw: f32 = 1.0 / (fw.max(1) as f32);
252        let inv_fh: f32 = 1.0 / (fh.max(1) as f32);
253        let shimmer_phase: f32 = snapshot.get_sim_time_secs() * 2.15;
254        for y in 0..fh {
255            let ym: usize = y.saturating_sub(1) * fw;
256            let y0: usize = y * fw;
257            let yp: usize = (y + 1).min(fh - 1) * fw;
258            let v_f: f32 = ((y as f32) + 0.5) * inv_fh;
259            let cos_va: f32 = (v_f * 22.0 - shimmer_phase * 0.8).cos();
260            let sin_vb: f32 = (v_f * 30.0 + shimmer_phase * 0.9).sin();
261            for x in 0..fw {
262                let xm: usize = x.saturating_sub(1);
263                let xp: usize = (x + 1).min(fw - 1);
264                let idx: usize = y0 + x;
265                let p_c: f32 = phi[idx];
266                let p_l: f32 = phi[y0 + xm];
267                let p_r: f32 = phi[y0 + xp];
268                let p_u: f32 = phi[ym + x];
269                let p_d: f32 = phi[yp + x];
270                let gx_v: f32 = (p_r - p_l) * 0.5;
271                let gy_v: f32 = (p_d - p_u) * 0.5;
272                grad_x[idx] = gx_v;
273                grad_y[idx] = gy_v;
274                let lap: f32 = (p_l + p_r + p_u + p_d) - 4.0 * p_c;
275                let slope_sq: f32 = gx_v * gx_v + gy_v * gy_v;
276                let light_focus: f32 = (-gx_v * 0.35 - gy_v * 0.80).max(0.0);
277                let u_f: f32 = ((x as f32) + 0.5) * inv_fw;
278                let wave_a: f32 = ((u_f - gx_v * 0.14) * 26.0 + shimmer_phase).sin() * cos_va;
279                let wave_b: f32 = ((u_f + gy_v * 0.12) * 34.0 - shimmer_phase * 0.7).cos() * sin_vb;
280                let shim: f32 = ((wave_a + wave_b) * 0.5).max(0.0);
281                let focus: f32 = ((-lap * 2.4).max(0.0)
282                    + light_focus * 1.15
283                    + slope_sq * 1.8
284                    + shim * shim * (0.20 + thickness[idx] * 0.25))
285                    .clamp(0.0, 1.35);
286                caustic[idx] = focus;
287            }
288        }
289    }
290
291    /// Stamps crisp translucent rising underwater micro-bubbles with refracted dark bottoms and bright specular crescents.
292    ///
293    /// # Arguments
294    ///
295    /// - `&FluidSimSnapshot` - Interpolated simulation snapshot containing active bubbles.
296    /// - `usize` - Framebuffer width in pixels.
297    /// - `usize` - Framebuffer height in pixels.
298    /// - `&mut [u8]` - Destination RGBA8 framebuffer slice.
299    fn stamp_rising_bubbles(
300        snapshot: &FluidSimSnapshot,
301        out_w: usize,
302        out_h: usize,
303        rgba: &mut [u8],
304    ) {
305        let bub_cnt: usize = snapshot.get_bubble_count().min(FLUID_MAX_BUBBLES);
306        if bub_cnt == 0 {
307            return;
308        }
309        let vw: f32 = snapshot.get_vessel_width_m().max(1.0e-4);
310        let vh: f32 = snapshot.get_vessel_height_m().max(1.0e-4);
311        let px_per_m_x: f32 = (out_w as f32) / vw;
312        let px_per_m_y: f32 = (out_h as f32) / vh;
313        let px_per_m: f32 = px_per_m_x.min(px_per_m_y);
314        let max_x: i32 = (out_w as i32) - 1;
315        let max_y: i32 = (out_h as i32) - 1;
316        for bub in snapshot.get_bubbles().iter().take(bub_cnt) {
317            let fade: f32 = (1.0 - bub.get_age() / bub.get_lifetime().max(0.05)).clamp(0.0, 1.0);
318            if fade <= 0.04 {
319                continue;
320            }
321            let cx: f32 = bub.get_x() * px_per_m_x;
322            let cy: f32 = bub.get_y() * px_per_m_y;
323            let rad_px: f32 = (bub.get_radius() * px_per_m).clamp(1.6, 5.5);
324            let ir: i32 = (rad_px + 1.5).ceil() as i32;
325            let x0: i32 = ((cx as i32) - ir).max(3);
326            let x1: i32 = ((cx as i32) + ir).min(max_x - 3);
327            let y0: i32 = ((cy as i32) - ir).max(3);
328            let y1: i32 = ((cy as i32) + ir).min(max_y - 3);
329            let inv_r: f32 = 1.0 / rad_px;
330            let foam_f: f32 = bub.get_foam_factor();
331            for py in y0..=y1 {
332                let dy: f32 = ((py as f32) + 0.5 - cy) * inv_r;
333                let dy2: f32 = dy * dy;
334                if dy2 >= 1.2 {
335                    continue;
336                }
337                let row: usize = (py as usize) * out_w * 4;
338                for px in x0..=x1 {
339                    let dx: f32 = ((px as f32) + 0.5 - cx) * inv_r;
340                    let d2: f32 = dx * dx + dy2;
341                    if d2 >= 1.05 {
342                        continue;
343                    }
344                    let dist: f32 = d2.sqrt();
345                    let edge: f32 = 1.0 - fluid_smoothstep(0.75, 1.02, dist);
346                    let ring: f32 = fluid_smoothstep(0.45, 0.85, dist) * edge;
347                    let spec_dx: f32 = dx + 0.36;
348                    let spec_dy: f32 = dy + 0.38;
349                    let spec: f32 = (1.0 - (spec_dx * spec_dx + spec_dy * spec_dy) * 3.8).max(0.0);
350                    let alpha: f32 = ((ring * 0.48 + spec * 0.85 + foam_f * edge * 0.45) * fade)
351                        .clamp(0.0, 0.92);
352                    if alpha <= 0.01 {
353                        continue;
354                    }
355                    let dst: usize = row + (px as usize) * 4;
356                    let inv_a: f32 = 1.0 - alpha;
357                    let tint_r: f32 = 212.0 + 43.0 * spec;
358                    let tint_g: f32 = 242.0 + 13.0 * spec;
359                    let tint_b: f32 = 255.0;
360                    rgba[dst] = ((rgba[dst] as f32) * inv_a + tint_r * alpha) as u8;
361                    rgba[dst + 1] = ((rgba[dst + 1] as f32) * inv_a + tint_g * alpha) as u8;
362                    rgba[dst + 2] = ((rgba[dst + 2] as f32) * inv_a + tint_b * alpha) as u8;
363                }
364            }
365        }
366    }
367
368    /// Renders `snapshot` directly into an existing RGBA8 byte buffer `rgba_out` sized `(width, height)` with zero steady-state heap allocations.
369    ///
370    /// # Arguments
371    ///
372    /// - `&Self` - Mutable optical liquid renderer.
373    /// - `&FluidSimSnapshot` - Interpolated simulation snapshot.
374    /// - `u32` - Output width in pixels.
375    /// - `u32` - Output height in pixels.
376    /// - `&mut Vec<u8>` - Destination RGBA8 byte buffer resized only if needed.
377    ///
378    /// # Returns
379    ///
380    /// - `(u32, u32)` - Actual rendered `(width, height)` dimensions.
381    pub fn render_snapshot_into_vec(
382        &mut self,
383        snapshot: &FluidSimSnapshot,
384        width: u32,
385        height: u32,
386        rgba_out: &mut Vec<u8>,
387    ) -> (u32, u32) {
388        let out_w: usize = width.max(32) as usize;
389        let out_h: usize = height.max(32) as usize;
390        let needed: usize = out_w * out_h * 4;
391        if rgba_out.len() != needed {
392            rgba_out.resize(needed, 255);
393        }
394        let fw: usize = (out_w / 3).clamp(FLUID_FIELD_MIN_DIM, FLUID_FIELD_MAX_W);
395        let fh: usize = (out_h / 3).clamp(FLUID_FIELD_MIN_DIM, FLUID_FIELD_MAX_H);
396        self.ensure_field_capacity(fw, fh);
397        self.build_optical_fields(snapshot);
398        let gx: f32 = snapshot.get_gravity_x();
399        let gy: f32 = snapshot.get_gravity_y();
400        let g_mag: f32 = (gx * gx + gy * gy).sqrt();
401        let (up_x, up_y): (f32, f32) = if g_mag > 0.25 {
402            (-gx / g_mag, -gy / g_mag)
403        } else {
404            (0.0, -1.0)
405        };
406        let b_cnt: usize = snapshot
407            .get_buoyant_body_count()
408            .min(FLUID_MAX_BUOYANT_BODIES);
409        let mut bodies_copy: [BuoyantBody; FLUID_MAX_BUOYANT_BODIES] =
410            [BuoyantBody::default(); FLUID_MAX_BUOYANT_BODIES];
411        bodies_copy[..b_cnt].copy_from_slice(&snapshot.get_buoyant_bodies()[..b_cnt]);
412        let min_px: f32 = (out_w.min(out_h)) as f32;
413        let params: FluidShadeParams = FluidShadeParams {
414            out_w,
415            out_h,
416            field_w: fw,
417            field_h: fh,
418            vessel_w: snapshot.get_vessel_width_m().max(1.0e-4),
419            vessel_h: snapshot.get_vessel_height_m().max(1.0e-4),
420            up_x,
421            up_y,
422            bezel_px: (min_px * 0.018).clamp(4.0, 9.0),
423            corner_px: (min_px * FLUID_CORNER_RADIUS_RATIO).clamp(10.0, 28.0),
424            body_count: b_cnt,
425            bodies: bodies_copy,
426        };
427        let fields: FluidFieldViews<'_> = FluidFieldViews {
428            phi: self.get_phi().as_slice(),
429            thickness: self.get_thickness().as_slice(),
430            foam: self.get_foam().as_slice(),
431            grad_x: self.get_grad_x().as_slice(),
432            grad_y: self.get_grad_y().as_slice(),
433            caustic: self.get_caustic().as_slice(),
434        };
435        let dst_ptr: usize = rgba_out.as_mut_ptr() as usize;
436        let row_stride: usize = out_w * 4;
437        parallel_for_ranges(out_h, FLUID_RENDER_BAND_ROWS, |y0: usize, y1: usize| {
438            let base: *mut u8 = dst_ptr as *mut u8;
439            for y in y0..y1 {
440                // SAFETY: `parallel_for_ranges` partitions `[0, out_h)` into disjoint scanline bands within `rgba_out`.
441                let row_slice: &mut [u8] =
442                    unsafe { from_raw_parts_mut(base.add(y * row_stride), row_stride) };
443                shade_fluid_scanline(&params, &fields, y, row_slice);
444            }
445        });
446        Self::stamp_rising_bubbles(snapshot, out_w, out_h, rgba_out.as_mut_slice());
447        self.set_last_width(out_w as u32);
448        self.set_last_height(out_h as u32);
449        (out_w as u32, out_h as u32)
450    }
451
452    /// Renders `snapshot` directly into a bounded zero-allocation `RenderBufferPool` slot tagged with `fence_id`.
453    ///
454    /// # Arguments
455    ///
456    /// - `&Self` - Mutable optical liquid renderer.
457    /// - `&FluidSimSnapshot` - Interpolated simulation snapshot.
458    /// - `u32` - Target viewport width in logical pixels.
459    /// - `u32` - Target viewport height in logical pixels.
460    /// - `&RenderBufferPool` - Bounded RGBA8 frame buffer pool.
461    /// - `u64` - Fence identifier guarding slot reclamation.
462    ///
463    /// # Returns
464    ///
465    /// - `Option<PooledFrameLease>` - Rendered zero-copy frame lease, or `None` if all bounded pool slots are in flight.
466    #[must_use]
467    pub fn render_snapshot_into_pool(
468        &mut self,
469        snapshot: &FluidSimSnapshot,
470        viewport_w: u32,
471        viewport_h: u32,
472        pool: &RenderBufferPool,
473        fence_id: u64,
474    ) -> Option<PooledFrameLease> {
475        let (rw, rh): (u32, u32) = Self::resolve_render_dimensions(viewport_w, viewport_h);
476        let mut lease: PooledFrameLease = pool.acquire(rw, rh, fence_id)?;
477        let (aw, ah): (u32, u32) =
478            self.render_snapshot_into_vec(snapshot, rw, rh, lease.get_mut_pixels());
479        lease.set_dimensions(aw, ah);
480        Some(lease)
481    }
482}