Skip to main content

euv_core/game/fluid/scene/
impl.rs

1use super::*;
2
3/// Default handheld gyroscope liquid water game scene.
4impl Default for GyroLiquidGameScene {
5    /// Creates a `GyroLiquidGameScene` configured with `GyroLiquidConfig::default()`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Shareable liquid water game scene handle.
10    fn default() -> Self {
11        Self::with_config(GyroLiquidConfig::default())
12    }
13}
14
15/// Internal state construction and telemetry refresh helpers for `GyroLiquidSceneState`.
16impl GyroLiquidSceneState {
17    /// Constructs an initialized `GyroLiquidSceneState` with pre-warmed snapshots and bounded frame pool.
18    ///
19    /// # Arguments
20    ///
21    /// - `GyroLiquidConfig` - Physical simulation configuration.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Ready scene state.
26    #[must_use]
27    pub(crate) fn with_config(config: GyroLiquidConfig) -> Self {
28        let solver: LiquidFluidSolver = LiquidFluidSolver::with_config(config);
29        let mut init_snap: FluidSimSnapshot = FluidSimSnapshot::default();
30        solver.capture_snapshot_into(&mut init_snap);
31        let snapshots: DoubleBufferedSnapshot<FluidSimSnapshot> =
32            DoubleBufferedSnapshot::new(init_snap);
33        let renderer: LiquidOpticalRenderer = LiquidOpticalRenderer::new_renderer();
34        let frame_pool: RenderBufferPool = RenderBufferPool::with_capacity(FLUID_SCENE_POOL_SLOTS);
35        let mut state: Self = Self {
36            solver,
37            snapshots,
38            renderer,
39            frame_pool,
40            frame_fence: 0,
41            sensor_mode: FluidSensorMode::Auto,
42            device_motion_signal: None,
43            manual_motion_sample: None,
44            sensor_active: false,
45            last_viewport_bounds: Rect::new(0.0, 0.0, 640.0, 480.0),
46            last_sim_ms: 0.0,
47            last_render_ms: 0.0,
48            stats: GyroLiquidStats::default(),
49        };
50        state.refresh_stats();
51        state
52    }
53
54    /// Recomputes `GyroLiquidStats` from current solver, renderer, and sensor fields.
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Mutable scene state.
59    pub(crate) fn refresh_stats(&mut self) {
60        let solver: &LiquidFluidSolver = self.get_solver();
61        let config_spec: GyroLiquidConfig = solver.get_config();
62        let ren: &LiquidOpticalRenderer = self.get_renderer();
63        let next: GyroLiquidStats = GyroLiquidStats {
64            particle_count: solver.get_particle_count(),
65            bubble_count: solver.get_bubble_count(),
66            buoyant_body_count: solver.get_buoyant_body_count(),
67            kinetic_energy_mj: solver.get_kinetic_energy_mj(),
68            gravity_x: solver.get_gravity_x(),
69            gravity_y: solver.get_gravity_y(),
70            gravity_z: solver.get_gravity_z(),
71            tilt_angle_deg: solver.get_active_roll_rad().to_degrees(),
72            peak_wave_height_m: solver.get_peak_wave_height_m(),
73            sim_time_ms: self.get_last_sim_ms(),
74            render_time_ms: self.get_last_render_ms(),
75            sensor_mode: self.get_sensor_mode(),
76            sensor_active: self.get_sensor_active(),
77            vessel_width_m: config_spec.get_vessel_width_m(),
78            vessel_height_m: config_spec.get_vessel_height_m(),
79            fill_ratio: config_spec.get_fill_ratio(),
80            render_width: ren.get_last_width(),
81            render_height: ren.get_last_height(),
82        };
83        self.set_stats(next);
84    }
85
86    /// Resolves the active hardware `DeviceMotionSample` from explicit injection, bound reactive signal, or thread-local sensor stream.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Scene state reference.
91    ///
92    /// # Returns
93    ///
94    /// - `Option<DeviceMotionSample>` - Active sensor sample when live hardware input should drive this tick.
95    #[must_use]
96    pub(crate) fn resolve_active_sensor_sample(&self) -> Option<DeviceMotionSample> {
97        if self.get_sensor_mode() == FluidSensorMode::VirtualTilt {
98            return None;
99        }
100        if let Some(manual) = self.get_manual_motion_sample() {
101            return Some(manual);
102        }
103        if let Some(sig) = self.get_device_motion_signal() {
104            let sample: DeviceMotionSample = sig.get_untracked();
105            if sample.get_sensor_active() || self.get_sensor_mode() == FluidSensorMode::LiveHardware
106            {
107                return Some(sample);
108            }
109        }
110        let latest: DeviceMotionSample = latest_device_motion();
111        if latest.get_sensor_active() {
112            return Some(latest);
113        }
114        if self.get_sensor_mode() == FluidSensorMode::LiveHardware {
115            return Some(latest);
116        }
117        None
118    }
119}
120
121/// Interactive physics controls, sensor bindings, telemetry inspection, and offscreen pooled rendering on `GyroLiquidGameScene`.
122impl GyroLiquidGameScene {
123    /// Creates a new `GyroLiquidGameScene` with custom physical `config`.
124    ///
125    /// # Arguments
126    ///
127    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
128    ///
129    /// # Returns
130    ///
131    /// - `Self` - Shareable liquid water game scene handle.
132    #[must_use]
133    pub fn with_config(config: GyroLiquidConfig) -> Self {
134        Self {
135            inner: Rc::new(RefCell::new(GyroLiquidSceneState::with_config(config))),
136        }
137    }
138
139    /// Binds a reactive `Signal<DeviceMotionSample>` (e.g. from `use_device_motion()`) so live hardware sensor updates drive the liquid seamlessly.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Liquid game scene handle.
144    /// - `Signal<DeviceMotionSample>` - Reactive device motion signal.
145    pub fn bind_device_motion(&self, signal: Signal<DeviceMotionSample>) {
146        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
147            node_style.set_device_motion_signal(Some(signal));
148        }
149    }
150
151    /// Injects an explicit `DeviceMotionSample` (useful for live custom bridges or deterministic testing) and clears it when passed `None`.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Liquid game scene handle.
156    /// - `Option<DeviceMotionSample>` - Hardware or synthetic motion sample.
157    pub fn set_device_motion(&self, sample: Option<DeviceMotionSample>) {
158        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
159            node_style.set_manual_motion_sample(sample);
160        }
161    }
162
163    /// Selects the sensor input mode (`Auto`, `LiveHardware`, or `VirtualTilt`).
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Liquid game scene handle.
168    /// - `FluidSensorMode` - Desired sensor driving mode.
169    pub fn set_sensor_mode(&self, mode: FluidSensorMode) {
170        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
171            node_style.set_sensor_mode(mode);
172            node_style.refresh_stats();
173        }
174    }
175
176    /// Sets virtual desktop/simulator tilt angles (`roll_rad`, `pitch_rad`).
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Liquid game scene handle.
181    /// - `f32` - In-plane roll angle in radians (`0.0` = upright, `+π/2` = clockwise right-down).
182    /// - `f32` - Out-of-plane pitch angle in radians (`0.0` = upright vertical, `+π/2` = face-up flat).
183    pub fn set_virtual_tilt(&self, roll_rad: f32, pitch_rad: f32) {
184        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
185            node_style
186                .get_mut_solver()
187                .set_virtual_tilt(roll_rad, pitch_rad);
188            node_style.refresh_stats();
189        }
190    }
191
192    /// Rotates the virtual container angle by `delta_rad` radians (positive clockwise in screen space).
193    ///
194    /// # Arguments
195    ///
196    /// - `&Self` - Liquid game scene handle.
197    /// - `f32` - Rotation increment in radians.
198    pub fn rotate_container_by(&self, delta_rad: f32) {
199        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
200            node_style.get_mut_solver().rotate_container_by(delta_rad);
201            node_style.refresh_stats();
202        }
203    }
204
205    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²`.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Liquid game scene handle.
210    /// - `f32` - Horizontal shake acceleration in `m/s²`.
211    /// - `f32` - Vertical shake acceleration in `m/s²`.
212    pub fn apply_shake_impulse(&self, ax: f32, ay: f32) {
213        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
214            node_style.get_mut_solver().apply_shake_impulse(ax, ay);
215        }
216    }
217
218    /// Applies a direct pointer/touch stirring wake impulse at normalized vessel coordinates `(norm_x, norm_y)`.
219    ///
220    /// # Arguments
221    ///
222    /// - `&Self` - Liquid game scene handle.
223    /// - `f32` - Normalized x-coordinate in `[0.0, 1.0]`.
224    /// - `f32` - Normalized y-coordinate in `[0.0, 1.0]`.
225    /// - `f32` - Stir velocity x-component in `m/s`.
226    /// - `f32` - Stir velocity y-component in `m/s`.
227    pub fn apply_stir_impulse(&self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
228        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
229            node_style
230                .get_mut_solver()
231                .apply_stir_impulse(norm_x, norm_y, vel_x_mps, vel_y_mps);
232        }
233    }
234
235    /// Updates the liquid fill ratio (`0.20..=0.85`) and captures a discontinuous snapshot cleanly.
236    ///
237    /// # Arguments
238    ///
239    /// - `&Self` - Liquid game scene handle.
240    /// - `f32` - Target fill fraction in `[0.20, 0.85]`.
241    pub fn set_fill_ratio(&self, fill_ratio: f32) {
242        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
243            node_style.get_mut_solver().set_fill_ratio(fill_ratio);
244            let GyroLiquidSceneState {
245                solver, snapshots, ..
246            } = &mut *node_style;
247            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
248                solver.capture_snapshot_into(dst);
249            });
250            node_style.refresh_stats();
251        }
252    }
253
254    /// Updates the relative liquid viscosity (`0.2..=6.0`, where `1.0` = 20 °C pure water).
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Liquid game scene handle.
259    /// - `f32` - Relative viscosity multiplier.
260    pub fn set_viscosity(&self, viscosity: f32) {
261        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
262            node_style.get_mut_solver().set_viscosity(viscosity);
263        }
264    }
265
266    /// Updates the relative liquid surface tension (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
267    ///
268    /// # Arguments
269    ///
270    /// - `&Self` - Liquid game scene handle.
271    /// - `f32` - Relative surface tension multiplier.
272    pub fn set_surface_tension(&self, surface_tension: f32) {
273        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
274            node_style
275                .get_mut_solver()
276                .set_surface_tension(surface_tension);
277        }
278    }
279
280    /// Enables or disables Archimedes buoyant floating objects (orb + ice cube).
281    ///
282    /// # Arguments
283    ///
284    /// - `&Self` - Liquid game scene handle.
285    /// - `bool` - Whether floating buoyant objects are active.
286    pub fn set_buoyant_bodies_enabled(&self, enabled: bool) {
287        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
288            node_style
289                .get_mut_solver()
290                .set_buoyant_bodies_enabled(enabled);
291            let GyroLiquidSceneState {
292                solver, snapshots, ..
293            } = &mut *node_style;
294            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
295                solver.capture_snapshot_into(dst);
296            });
297            node_style.refresh_stats();
298        }
299    }
300
301    /// Resets the water, buoyant objects, bubbles, and virtual tilt to a calm upright resting pool.
302    ///
303    /// # Arguments
304    ///
305    /// - `&Self` - Liquid game scene handle.
306    pub fn reset_water(&self) {
307        if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
308            node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
309            node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
310            node_style.get_mut_solver().reset_water();
311            let GyroLiquidSceneState {
312                solver, snapshots, ..
313            } = &mut *node_style;
314            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
315                solver.capture_snapshot_into(dst);
316            });
317            node_style.refresh_stats();
318        }
319    }
320
321    /// Returns the latest read-only `GyroLiquidStats` telemetry snapshot.
322    ///
323    /// # Arguments
324    ///
325    /// - `&Self` - Liquid game scene handle.
326    ///
327    /// # Returns
328    ///
329    /// - `GyroLiquidStats` - Current live telemetry struct.
330    #[must_use]
331    pub fn stats(&self) -> GyroLiquidStats {
332        self.get_inner()
333            .try_borrow()
334            .map(|node_style: Ref<'_, GyroLiquidSceneState>| node_style.get_stats())
335            .unwrap_or_default()
336    }
337
338    /// Returns the liquid center of mass `(x_m, y_m)` in SI meters inside the physical vessel.
339    ///
340    /// # Arguments
341    ///
342    /// - `&Self` - Liquid game scene handle.
343    ///
344    /// # Returns
345    ///
346    /// - `(f32, f32)` - Center of mass in meters.
347    #[must_use]
348    pub fn center_of_mass(&self) -> (f32, f32) {
349        self.get_inner()
350            .try_borrow()
351            .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
352                node_style.get_solver().center_of_mass()
353            })
354            .unwrap_or((DEFAULT_VESSEL_WIDTH_M * 0.5, DEFAULT_VESSEL_HEIGHT_M * 0.5))
355    }
356
357    /// Copies the currently active buoyant bodies for inspection or HUD overlays.
358    ///
359    /// # Arguments
360    ///
361    /// - `&Self` - Liquid game scene handle.
362    ///
363    /// # Returns
364    ///
365    /// - `Vec<BuoyantBody>` - Active buoyant rigid body states.
366    #[must_use]
367    pub fn buoyant_bodies(&self) -> Vec<BuoyantBody> {
368        self.get_inner()
369            .try_borrow()
370            .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
371                let cnt: usize = node_style.get_solver().get_buoyant_body_count();
372                node_style.get_solver().get_buoyant_bodies()[..cnt].to_vec()
373            })
374            .unwrap_or_default()
375    }
376
377    /// Returns `true` if any active particle or buoyant body has NaN/Inf state or escaped container bounds.
378    ///
379    /// # Arguments
380    ///
381    /// - `&Self` - Liquid game scene handle.
382    ///
383    /// # Returns
384    ///
385    /// - `bool` - Whether solver state is invalid or escaped.
386    #[must_use]
387    pub fn has_invalid_or_escaped_state(&self) -> bool {
388        self.get_inner()
389            .try_borrow()
390            .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
391                node_style.get_solver().has_invalid_or_escaped_state()
392            })
393            .unwrap_or(false)
394    }
395
396    /// Renders the interpolated liquid scene directly into the internal `RenderBufferPool` for offscreen inspection or custom blitting.
397    ///
398    /// # Arguments
399    ///
400    /// - `&Self` - Liquid game scene handle.
401    /// - `u32` - Target viewport width in logical pixels.
402    /// - `u32` - Target viewport height in logical pixels.
403    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
404    ///
405    /// # Returns
406    ///
407    /// - `Option<PooledFrameLease>` - Rendered zero-copy RGBA8 frame lease.
408    #[must_use]
409    pub fn render_to_pooled_frame(
410        &self,
411        viewport_w: u32,
412        viewport_h: u32,
413        alpha: f32,
414    ) -> Option<PooledFrameLease> {
415        let mut node_style: RefMut<'_, GyroLiquidSceneState> =
416            self.get_inner().try_borrow_mut().ok()?;
417        let vw: u32 = viewport_w.max(FLUID_RENDER_MIN_DIM);
418        let vh: u32 = viewport_h.max(FLUID_RENDER_MIN_DIM);
419        if node_style
420            .get_mut_solver()
421            .adapt_vessel_aspect_changed((vw as f32) / (vh as f32))
422        {
423            let GyroLiquidSceneState {
424                solver, snapshots, ..
425            } = &mut *node_style;
426            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
427                solver.capture_snapshot_into(dst);
428            });
429        }
430        let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
431        node_style.set_frame_fence(next_fence);
432        #[cfg(not(target_arch = "wasm32"))]
433        let t0: Instant = Instant::now();
434        let lease: Option<PooledFrameLease> = {
435            let GyroLiquidSceneState {
436                snapshots,
437                renderer,
438                frame_pool,
439                ..
440            } = &mut *node_style;
441            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
442            renderer.render_snapshot_into_pool(snap, vw, vh, frame_pool, next_fence)
443        };
444        #[cfg(not(target_arch = "wasm32"))]
445        {
446            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
447            node_style.set_last_render_ms(elapsed_ms);
448        }
449        node_style.refresh_stats();
450        lease
451    }
452}
453
454/// `GameScene` integration driving fixed-step SI liquid physics, sensor ingestion, pointer stirring, and zero-copy pooled optical rendering inside `GameEngineHost`.
455impl GameScene for GyroLiquidGameScene {
456    /// Advances SI PBF liquid physics by one fixed timestep `dt` using live hardware sensors (or virtual tilt) plus pointer stirring and keyboard controls.
457    ///
458    /// # Arguments
459    ///
460    /// - `&Self` - Mutable liquid scene handle.
461    /// - `f32` - Fixed simulation timestep in seconds.
462    /// - `&InputState` - Real-time polled pointer and keyboard input state.
463    fn fixed_update(&mut self, dt: f32, input: &InputState) {
464        let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
465            return;
466        };
467        #[cfg(not(target_arch = "wasm32"))]
468        let t0: Instant = Instant::now();
469        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
470        let sensor_opt: Option<DeviceMotionSample> = node_style.resolve_active_sensor_sample();
471        if let Some(sample) = sensor_opt {
472            node_style.set_sensor_active(sample.get_sensor_active());
473            node_style
474                .get_mut_solver()
475                .apply_device_motion(sample, safe_dt);
476        } else {
477            node_style.set_sensor_active(false);
478            let roll_axis: f32 = input.axis(KeyCode::ArrowLeft, KeyCode::ArrowRight)
479                + input.axis(
480                    KeyCode::Character(FLUID_KEY_CHAR_LEFT),
481                    KeyCode::Character(FLUID_KEY_CHAR_RIGHT),
482                );
483            let pitch_axis: f32 = input.axis(KeyCode::ArrowDown, KeyCode::ArrowUp)
484                + input.axis(
485                    KeyCode::Character(FLUID_KEY_CHAR_DOWN),
486                    KeyCode::Character(FLUID_KEY_CHAR_UP),
487                );
488            if roll_axis.abs() > 0.01 {
489                node_style.get_mut_solver().rotate_container_by(
490                    roll_axis.clamp(-1.0, 1.0) * FLUID_KEY_ROLL_SPEED_RAD_S * safe_dt,
491                );
492            }
493            if pitch_axis.abs() > 0.01 {
494                let cur_roll: f32 = node_style.get_solver().get_virtual_roll_rad();
495                let next_pitch: f32 = node_style.get_solver().get_virtual_pitch_rad()
496                    + pitch_axis.clamp(-1.0, 1.0) * FLUID_KEY_PITCH_SPEED_RAD_S * safe_dt;
497                node_style
498                    .get_mut_solver()
499                    .set_virtual_tilt(cur_roll, next_pitch);
500            }
501            node_style.get_mut_solver().sync_virtual_motion(safe_dt);
502        }
503        if input.is_key_just_pressed(KeyCode::Character(FLUID_KEY_CHAR_RESET)) {
504            node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
505            node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
506            node_style.get_mut_solver().reset_water();
507        }
508        if input.is_button_down(PointerButton::Primary) {
509            let rect_bounds: Rect = node_style.get_last_viewport_bounds();
510            let border_width: f32 = rect_bounds.get_width().max(1.0);
511            let bh: f32 = rect_bounds.get_height().max(1.0);
512            let ptr: Point = input.get_pointer_position();
513            let delta: Point = input.get_pointer_delta();
514            let nx: f32 = (ptr.get_x() - rect_bounds.get_x()) / border_width;
515            let ny: f32 = (ptr.get_y() - rect_bounds.get_y()) / bh;
516            if (0.0..=1.0).contains(&nx) && (0.0..=1.0).contains(&ny) {
517                let d_mag: f32 = delta.get_x().hypot(delta.get_y());
518                if d_mag > 0.25 {
519                    let vw_m: f32 = node_style.get_solver().get_config().get_vessel_width_m();
520                    let vh_m: f32 = node_style.get_solver().get_config().get_vessel_height_m();
521                    let vx_mps: f32 = (delta.get_x() / border_width) * vw_m / safe_dt;
522                    let vy_mps: f32 = (delta.get_y() / bh) * vh_m / safe_dt;
523                    node_style
524                        .get_mut_solver()
525                        .apply_stir_impulse(nx, ny, vx_mps, vy_mps);
526                }
527            }
528        }
529        node_style.get_mut_solver().step(safe_dt);
530        {
531            let GyroLiquidSceneState {
532                solver, snapshots, ..
533            } = &mut *node_style;
534            snapshots.capture_into(|dst: &mut FluidSimSnapshot| {
535                solver.capture_snapshot_into(dst);
536            });
537        }
538        #[cfg(not(target_arch = "wasm32"))]
539        {
540            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
541            node_style.set_last_sim_ms(elapsed_ms);
542        }
543        node_style.refresh_stats();
544    }
545
546    /// Renders the photorealistic optical water into the bounded `RenderBufferPool` and blits it zero-copy into `ctx`, adapting cleanly to arbitrary resize and fullscreen bounds.
547    ///
548    /// # Arguments
549    ///
550    /// - `&Self` - Mutable liquid scene handle.
551    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
552    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
553    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
554        let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
555            return;
556        };
557        let bounds: Rect = ctx.bounds;
558        let vp_w: f32 = bounds.get_width().max(64.0);
559        let vp_h: f32 = bounds.get_height().max(64.0);
560        let dpr: f32 = ctx.scale_factor().clamp(1.0, 3.0);
561        let target_phys_w: u32 = (vp_w * dpr).round().max(64.0) as u32;
562        let target_phys_h: u32 = (vp_h * dpr).round().max(64.0) as u32;
563        node_style.set_last_viewport_bounds(bounds);
564        if node_style
565            .get_mut_solver()
566            .adapt_vessel_aspect_changed(vp_w / vp_h)
567        {
568            let GyroLiquidSceneState {
569                solver, snapshots, ..
570            } = &mut *node_style;
571            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
572                solver.capture_snapshot_into(dst);
573            });
574        }
575        let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
576        node_style.set_frame_fence(next_fence);
577        #[cfg(not(target_arch = "wasm32"))]
578        let t0: Instant = Instant::now();
579        let lease_opt: Option<PooledFrameLease> = {
580            let GyroLiquidSceneState {
581                snapshots,
582                renderer,
583                frame_pool,
584                ..
585            } = &mut *node_style;
586            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
587            renderer.render_snapshot_into_pool(
588                snap,
589                target_phys_w,
590                target_phys_h,
591                frame_pool,
592                next_fence,
593            )
594        };
595        if let Some(lease) = lease_opt {
596            let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
597            ctx.blit_pooled_frame(dst_rect, &lease);
598            lease.submit_in_flight();
599            let _: usize = node_style.get_frame_pool().retire_fence(next_fence);
600        }
601        #[cfg(not(target_arch = "wasm32"))]
602        {
603            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
604            node_style.set_last_render_ms(elapsed_ms);
605        }
606        node_style.refresh_stats();
607    }
608}