= Hydron Whitewater =

#type: node
#context: sop
#internal: rvfx::hydron_whitewater
#icon: /nodes/sop/icons/hydron_whitewater.svg
#tags: rvfx, hydron, whitewater, foam, spray, bubbles, air, gpu, cuda

"""Standalone GPU Whitewater 2.0+ and 3D Air Advect solver compatible with Hydron Solver, .hyc caches, native Houdini VDBs (surface + vel), and generic FLIP point clouds."""

RVFX Hydron Whitewater separates secondary Bubbles, Foam, and Spray simulation from your main liquid solve so you can dial in whitewater lookdev without re-simming FLIP. It connects directly to [Hydron Solver|Node:sop/rvfx--hydron_solver], reads `.hyc` cache sequences, or ingests native Houdini OpenVDB fields (`surface` + `vel`) and `.bgeo.sc` FLIP point clouds, with an optional Input 1 Polygon or VDB SDF collider and built-in 3D Air Advect for billowing waterfall mist.

TIP:
    For native Houdini FLIP caches (`Houdini FLIP -> Hydron GPU` workflow), wire your `File Cache` (points with `P`/`v`, or VDBs `surface` + `vel`) into Input 0 and your terrain/vessel polygons or VDB SDF into Input 1. Set *Domain Mode* to `Auto-Lock Frame 1` for stationary tanks or `Custom Box` for wide rivers and oceans.

@inputs

Hydron Solver / FLIP Points or VDBs:
    Input 0. Accepts:
    - [Hydron Solver|Node:sop/rvfx--hydron_solver] live VRAM token (`hydron_live_token`) or `.hyc` cache path.
    - Houdini OpenVDB liquid fields (`surface` / `sdf` scalar level set + optional `vel` / `v` vector VDB or `vel.x/y/z`).
    - Generic Houdini FLIP point cloud (`P` + optional `v`, plus optional point float mask `f@ww_emit` in `[0..1]`).

Collider Geometry (Polygons or VDB SDF, Optional):
    Input 1. Optional obstacle geometry colliding with Bubbles, Foam, and Spray. Accepts polygon meshes (with optional `@v` or automatic finite differences) or OpenVDB SDF + `vel` volumes.

@outputs

Geometry & Groups:
    - Point groups `whitewater`, `ww`, `hydron_whitewater`: All active Whitewater particles.
    - Per-phase point groups: `hydron_ww_bubbles` (`state = 0`), `hydron_ww_foam` (`state = 1`), and `hydron_ww_spray` (`state = 2`).

Point Attributes:
    - `P` (`vector3`), `v` (`vector3`), `Cd` (`vector3`, driven by *WW Color Mode*; omitted completely when *WW Color Mode* is `None`), `id` (`int64`, persistent 64-bit ID), `age` (`float`), `life` (`float`, max lifespan), `pscale` (`float`, smoothly tapered near end of life), `density` (`float`, normalized local neighbor density), `vorticity` (`vector3`), and integer state attributes `ww_type`, `state`, and `ww_state` (`0 = Bubble`, `1 = Foam`, `2 = Spray`).
    - When *Visualize Emission* is `On`, outputs the current frame's FLIP points with `emit` (`float` in `[0..1]`) and heatmap `Cd` (deep blue `0.0` -> yellow `0.5` -> red `1.0`) without stepping the Whitewater simulation.

@parameters

Enable:
    #id: enable
    Enables or disables Whitewater simulation (default `On`).

Reset Whitewater:
    #id: reset_ww
    Clears all Whitewater and Air Advect GPU state and restarts from *Start Frame*.

Source Mode:
    #id: source_mode
    Selects input ingestion mode:
    - `Auto (Live -> .hyc -> Houdini VDB -> Generic Points)` (default)
    - `Zero-Copy Live VRAM`
    - `Read .hyc File`
    - `Generic Houdini FLIP Points`
    - `Houdini VDB Fields (surface + vel)`

Inherit FLIP Boundaries:
    #id: inherit_flip_bounds
    Automatically inherits the closed/open wall configuration from the upstream [Hydron Solver|Node:sop/rvfx--hydron_solver] (default `On`).

Boundary Mode:
    #id: boundary_mode
    Controls how Whitewater particles interact with the simulation domain boundaries: `Collide` (bounce/slide inside closed walls, default), `Open` (pass freely out of domain), or `Kill` (despawn on exit).

Start Frame:
    #id: start_frame
    Simulation start frame (default `1`). Scrubbing back to or before this frame resets Whitewater.

Time Scale:
    #id: time_scale
    Animatable Whitewater speed multiplier (default `1.0`, clamped `>= 0.0`, UI slider `0.0..2.0`). Combined with upstream `hydron_time_scale` when *Inherit Solver Time Scale* is on (`effective_dt = frame_dt * hydron_time_scale * time_scale`). When `effective_dt <= 1e-6`, Whitewater executes a *True Freeze Frame*, preserving existing VRAM particles without drift.

Inherit Solver Time Scale:
    #id: inherit_solver_time_scale
    When `On` (default `On`) and Input 0 carries detail attribute `hydron_time_scale` from [Hydron Solver|Node:sop/rvfx--hydron_solver], multiplies Whitewater's timestep by the solver's animated *Time Scale* for automatic bullet-time and freeze-frame lockstep.

.hyc File:
    #id: hyc_file
    Path to upstream `.hyc` frames (default `"$HIP/cache/hydron/hydron_$F4.hyc"`).

== External Input Settings ==

Domain Mode:
    #id: ext_domain_mode
    Domain bounds mode used for `Generic Houdini FLIP Points` and `Houdini VDB Fields` (automatically disabled when connected to a live [Hydron Solver|Node:sop/rvfx--hydron_solver] or `.hyc` cache):
    - `Auto-Lock Frame 1` (default): Computes padded bounds from Input 0/1 on the start frame and locks the grid for temporal stability.
    - `Custom Box`: Uses explicit *Domain Center* and *Domain Size*.

Domain Center / Domain Size:
    #id: ext_domain_center
    World-space center (default `(0.0, 0.5, 0.0)`) and dimensions (default `(4.0, 2.0, 4.0)`, clamped `0.05..500.0`) when *Domain Mode* is `Custom Box`.

Voxel Size (dx):
    #id: point_dx
    Grid spacing in meters for external point/VDB reconstruction when `hydron_dx` is absent (default `0.02 m`, clamped `>= 0.002 m`; automatically safety-clamped if grid exceeds `16,000,000` cells).

WW Substeps:
    #id: ww_substeps
    Whitewater substeps per frame in external Point/VDB modes (default `2`, clamped `1..4`).

Live GPU Telemetry:
    #id: info_telemetry
    Read-only GPU telemetry showing source tag, grid dimensions, total/per-phase Whitewater counts (`B/F/S`), viewport count, Air Advect grid & time, GPU/Step/D2H/GDP timings, and VRAM usage.

== Whitewater 2.0+ Emission & Wedging ==

Bubbles / Foam / Spray:
    #id: ww_enable_bubbles
    Independent phase toggles: *Bubbles* (`On`), *Foam* (`On`), and *Spray* (`Off` by default to keep wakes and splashes clean unless airborne mist is desired).

WW Emission Scale:
    #id: ww_emission_scale
    Master emission rate multiplier (default `1.0`, clamped `0.0..200.0`).

Bubbles Scale / Foam Scale / Spray Scale:
    #id: ww_bubbles_scale
    Per-phase emission multipliers (default `1.0`, clamped `0.0..50.0`).

Max WW Particles:
    #id: max_ww_particles
    Maximum Whitewater particle allocation on GPU (default `2,000,000`, clamped `1,024..20,000,000`).

WW Random Seed:
    #id: ww_random_seed
    Random seed for wedging emission variations (default `0`).

== Emission Control ==

Speed Gate Min (m/s) / Speed Gate Max (m/s):
    #id: ww_emit_speed_min
    Smoothstep speed gate (`m/s`, defaults `0.0` / `0.0` = disabled). When *Speed Gate Max* > *Speed Gate Min*, multiplies emission by `smoothstep(min, max, |v|)` to suppress calm-water emission cleanly.

Curvature Weight / Curvature Min / Curvature Max:
    #id: ww_emit_curv_weight
    Adds positive free-surface curvature emission (`0.0` default = unchanged baseline). When *Curvature Weight* > `0`, smoothsteps positive surface curvature between *Curvature Min* (`0.0`) and *Curvature Max* (`5.0`) to accentuate crests and splashes.

Birth Noise Size (m) / Birth Noise Contrast:
    #id: ww_emit_noise_size
    World-space 3D fBm birth breakup (`size = 0.25 m`, `contrast = 0.0` default = disabled). Modulates spawn probability at birth (`lerp(1.0, noise_mask, contrast)`) for organic cellular/streaky breakup without post-sim forces.

Visualize Emission:
    #id: ww_visualize_emission
    Evaluates a read-only 1-frame live emission preview (`f@emit` in `[0..1]` + deep blue -> yellow -> red heatmap `Cd`) directly onto the current frame's FLIP points (including `f@ww_emit` SOP mask if present) without stepping Whitewater.

== Foam Webbing, Erosion & Spray Lookdev ==

Cellular Webbing Strength:
    #id: ww_cellular_strength
    Controls Weta-inspired multi-scale foam cell aggregation into lacy webs (default `0.65`, clamped `0.0..2.0`).

Repellent Radius (dx):
    #id: ww_repellent_radius_dx
    Repellent radius in grid voxels shaping cellular foam hole sizes (default `2.5`, clamped `0.5..8.0`).

Foam Relaxation:
    #id: ww_foam_relaxation
    Relaxation damping on cellular foam drift (default `0.25`, clamped `0.0..1.5`).

Erosion Rate:
    #id: ww_erosion_rate
    Density-based erosion speed: isolated foam dissolves quickly while dense rafts persist longer (default `0.75`, clamped `0.0..3.0`).

Mist Air Drag:
    #id: ww_mist_drag
    Aerodynamic drag acting on airborne Spray/Mist particles (default `1.20`, clamped `0.0..5.0`).

Curl Turbulence:
    #id: ww_curl_turbulence
    3D curl noise turbulence on airborne Spray/Mist (default `0.60`, clamped `0.0..3.0`).

Surface Lock Strength:
    #id: ww_surface_lock_strength
    Keeps Foam particles tightly projected onto the evolving liquid surface (default `0.85`, clamped `0.0..1.0`).

Fractal Noise Scale:
    #id: ww_fractal_noise_scale
    Spatial frequency multiplier for breakup noise (default `1.0`, clamped `0.1..5.0`).

WW Boundary Mode:
    #id: ww_boundary_mode
    Controls how Whitewater particles behave at the FLIP simulation domain bounds:
    - `Open (Ballistic)` (default): Leaves `+Y` and `+-X/Z` open so splash spray arcs cleanly above and outside the domain under gravity and drag with a generous far-kill safety margin (`max(2 * max_extent, 20 m)`), while preserving a closed floor (`-Y`) inside the tank footprint.
    - `Kill at Bounds (Outflow)`: Leaves `+Y` open for high ballistic spray arcs while immediately killing particles crossing `+-X`, `+-Z`, or `-Y`.
    - `Closed Box`: Clamps all 6 domain walls strictly inside `[domain_min, domain_max]`.

== Air Advect (Waterfall / Mist Billow) ==

Enable Air Advect:
    #id: enable_air_advect
    Activates the coarse-grid 3D incompressible air velocity solver coupled to liquid momentum and spray/mist advection (default `Off`).

Air Grid Scale:
    #id: air_grid_scale
    Grid coarsening relative to liquid `dx`: `2x Coarser (Detailed)` (default), `3x Coarser`, or `4x Coarser (Fast)`.

Air Entrainment:
    #id: air_entrainment
    Rate (`1/s`) at which falling liquid drags surrounding air cells (default `8.0`).

Air Advect Strength:
    #id: air_advect_strength
    Strength (`1/s`) pulling Spray/Mist along the 3D air velocity field (default `4.0`).

Air Dissipation:
    #id: air_dissipation
    Exponential decay (`1/s`) of air momentum away from liquid (default `0.5`).

Vorticity Confinement:
    #id: air_vorticity
    Curl reinforcement in the coarse air grid for billowing vortex rolls (default `0.35`).

Projection Iterations:
    #id: air_pressure_iters
    Pressure projection iterations enforcing divergence-free air flow (default `20`, clamped `0..100`).

== Output, Collider (Input 1) & Disk Cache ==

Viewport WW %:
    #id: vp_ww_pct
    Flicker-free viewport thinning percentage (`0..100%`, default `50.0%`) for fast scrubbing on multi-million whitewater caches.

100% Full-Res Render:
    #id: full_res_render
    Automatically outputs 100% of Whitewater particles during render or ROP export cooks (default `On`).

WW Color Mode:
    #id: ww_color_mode
    Selects Whitewater `Cd` coloring:
    - `State (Spray / Foam / Bubbles)` (default): Colors particles using *Spray Color*, *Foam Color*, and *Bubble Color*.
    - `Speed Ramp`: Maps Whitewater speed (`|v|`) from *WW Speed Min* to *WW Speed Max* through *WW Color Gradient*.
    - `Age / Life`: Maps normalized particle age (`age / life` in `0..1`) through *WW Color Gradient* for tuning fade-out and density erosion.
    - `Density`: Maps Whitewater `density` (`0..1`) through *WW Color Gradient*.
    - `None`: Skips creating and writing `Cd` on Whitewater particles completely, leaving geometry clean for downstream `Color` SOPs and Karma XPU.

Spray Color:
    #id: ww_spray_color
    Editable RGB color for airborne Spray particles (default `(0.75, 0.92, 1.0)`) when *WW Color Mode* is `State (Spray / Foam / Bubbles)`.

Foam Color:
    #id: ww_foam_color
    Editable RGB color for surface Foam particles (default `(0.98, 0.99, 1.0)`) when *WW Color Mode* is `State (Spray / Foam / Bubbles)`.

Bubble Color:
    #id: ww_bubble_color
    Editable RGB color for submerged Bubble particles (default `(0.15, 0.55, 0.85)`) when *WW Color Mode* is `State (Spray / Foam / Bubbles)`.

WW Speed Min (m/s):
    #id: ww_speed_min
    Lower velocity bound (`m/s`, default `0.0 m/s`) mapped to `0.0` on *WW Color Gradient* when *WW Color Mode* is `Speed Ramp`.

WW Speed Max (m/s):
    #id: ww_speed_max
    Upper velocity bound (`m/s`, default `5.0 m/s`) mapped to `1.0` on *WW Color Gradient* when *WW Color Mode* is `Speed Ramp`.

WW Color Gradient:
    #id: ww_color_ramp
    Native Houdini RGB color ramp baked once per cook into a 256-entry RGB lookup table when *WW Color Mode* is `Speed Ramp`, `Age / Life`, or `Density`.

Use Input 1 Collider / Collision Padding / Thin Shell Thickness / Collider Vel Scale / Invert Collider:
    #id: use_input_collider
    Controls for optional Input 1 polygon or VDB SDF obstacles colliding with Whitewater particles (`use_input_collider = 1`, `padding` `-2..4`, `shell_thickness` `0..4`, `vel_scale` `0..3`, `invert = 0`).

=== Disk Cache (Async .hyc) ===

Cache Mode:
    #id: cache_mode
    Unified asynchronous `.hyc` disk caching shared across all Hydron nodes:
    - `Off` (default): Simulates live in GPU memory.
    - `Write (Async)`: Simulates and writes `<Cache Directory>/v<NNN>/<prefix>_####.hyc` in a background thread.
    - `Read (Playback)`: Reads cached Whitewater `.hyc` frames directly from disk for instant timeline scrubbing *without re-cooking the upstream solver*.
    - `Auto (Read or Sim+Write)`: Reads existing `.hyc` frames if valid, or simulates and writes missing frames cleanly.

Cache Version / Cache Directory / File Prefix:
    #id: cache_version
    Version folder (`1..999`, creating `v001`, `v002`, ...), base folder (default `"$HIP/cache/hydron_ww"`), and filename prefix (default `"hydron_ww"`).

Frame Range:
    #id: cache_range
    Start Frame, End Frame, and Increment (`$FSTART`, `$FEND`, `1`) used when clicking *Cache*.

Cache / Clear Disk Cache:
    #id: cache_save_to_disk
    *Cache* runs and writes the configured *Frame Range* to `.hyc` with an interruptible progress bar (`ESC` cancels cleanly); *Clear Disk Cache* flushes pending writes and deletes `.hyc` / `.hyc_sig` files in the active version folder.

@related
- [Node:sop/rvfx--hydron_solver]
- [Node:sop/rvfx--hydron_mesher]
- [Node:sop/rvfx--hydron_force]
