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