= Hydron Mesher =

#type: node
#context: sop
#internal: rvfx::hydron_mesher
#icon: /nodes/sop/icons/hydron_mesher.svg
#tags: rvfx, hydron, mesh, surfacing, flip, gpu, cuda

"""Standalone GPU fluid mesher supporting live Hydron Solver handoff, .hyc disk caches, and generic Houdini FLIP point clouds with Adaptive Velocity Smoothing and Subtract Colliders."""

RVFX Hydron Mesher builds a clean, watertight triangle mesh from FLIP particles directly on your GPU. Wire it downstream of [Hydron Solver|Node:sop/rvfx--hydron_solver] for instant live lookdev, point it at `.hyc` cache sequences, or feed standard Houdini FLIP `.bgeo.sc` point clouds (`P`, optional `v` and `pscale`) for fast GPU surfacing. Connect an optional Polygon or VDB SDF obstacle to Input 1 when using *Subtract Colliders*.

TIP:
    Enable *Adaptive Velocity Smoothing* and toggle *Visualize Smooth Mask* to inspect the 1-frame smoothing heatmap directly in the viewport: deep blue (`0.0`) marks fast splashes kept sharp, yellow (`0.5`) marks intermediate transition speeds, and red (`1.0`) marks calm water receiving full smoothing (`f@smooth_mask`).

@inputs

Hydron Solver / FLIP Particles:
    Input 0. Accepts:
    - Output of [Hydron Solver|Node:sop/rvfx--hydron_solver] (automatic live GPU handoff or `.hyc` cache path).
    - Any Houdini point geometry (`P`, optional vector `v` and float `pscale`, plus optional detail `hydron_dx`), such as a native Houdini FLIP File Cache (`.bgeo.sc`).

Collider Geometry (Polygons or VDB SDF, Optional):
    Input 1. Optional obstacle geometry (glass cups, vessels, rocks, or VDB SDFs) used when *Subtract Colliders* is enabled.

@outputs

Geometry & Groups:
    - Primitive group `hydron_mesh`: Indexed manifold triangle mesh with Houdini clockwise outward winding.

Point Attributes:
    - `P` (`vector3`): World-space mesh vertex positions.
    - `N` (`vector3`, normal): Analytical SDF gradient normals when *Output Normals (N)* is enabled.
    - `v` (`vector3`) & `speed` (`float`): Trilinearly transferred velocity and speed magnitude when *Transfer Velocity (v)* is enabled.
    - `smooth_mask` (`float`): Per-vertex smoothing mask weight (`0..1`) exported whenever *Adaptive Velocity Smoothing* or *Visualize Smooth Mask* is enabled.
    - `Cd` (`vector3`): Deep blue (`0.0`, sharp) -> yellow (`0.5`) -> red (`1.0`, max smoothing) heatmap when *Visualize Smooth Mask* is enabled.

@parameters

Enable:
    #id: enable
    Enables or bypasses GPU meshing (default `On`).

Source Mode:
    #id: source_mode
    Selects how input particle data is acquired:
    - `Auto (Zero-Copy Live -> .hyc -> Input Points)` (default): Automatically chooses a valid live VRAM token first, then an `.hyc` file path, then generic Input 0 points.
    - `Zero-Copy Live VRAM`: Meshes directly from upstream solver VRAM (`hydron_live_token`).
    - `Read .hyc File`: Reads and meshes the `.hyc` frame specified by *.hyc File* or upstream `hydron_cache_path`.
    - `Input SOP Points`: Extracts `P`, `v`, and `pscale` from Input 0 in parallel and builds a tight padded GPU sparse grid.

.hyc File:
    #id: hyc_file
    Path to a Hydron `.hyc` frame sequence (default `"$HIP/cache/hydron/hydron_$F4.hyc"`). Active in `Auto` and `Read .hyc File` modes.

Point Grid Spacing (m):
    #id: point_dx
    Fallback grid spacing `dx` in meters used in `Input SOP Points` mode when upstream detail attribute `hydron_dx` is absent (default `0.02 m`, minimum `0.002 m`).

== GPU Sparse Mesher ==

Voxel Scale:
    #id: voxel_scale
    Meshing voxel size `h = dx * voxel_scale` (default `0.75`, clamped `0.5..1.5`). Lower values (`0.5..0.65`) produce denser, crisper triangles.

Particle Radius:
    #id: particle_radius
    Multiplier on per-particle splat radius (`influence_scale`, default `1.75`, clamped `0.5..3.5`). Increase slightly if particles look disconnected; decrease for thinner sheets.

Droplet Scale:
    #id: droplet_scale
    Radius scale applied to isolated airborne droplets (`3x3x3` neighborhood check; default `0.75`, clamped `0.1..1.5`).

Filtering:
    #id: filtering
    Master toggle enabling morphological SDF filtering (`Dilate -> Smooth -> Erode`) (default `On`).

Smoothing Iterations:
    #id: smoothing_iters
    Number of GPU morphological filtering iterations when *Filtering* is on (default `2`, clamped `0..5`).

Subtract Colliders:
    #id: subtract_colliders
    Subtracts active solver colliders (or Input 1 geometry) from the liquid mesh on the GPU (default `Off`). Prevents liquid meshes from intersecting glass vessels or solid obstacles.

Collider Offset (m):
    #id: collider_offset
    Shifts the subtracted collider surface in meters (default `0.0 m`, UI `-0.1..0.1 m`). Small positive values (`0.001..0.003 m`) seat liquid snugly inside glass walls for clean refraction.

Output Normals (N):
    #id: compute_normals
    Computes smooth point normals `N` on GPU (default `On`).

Transfer Velocity (v):
    #id: transfer_velocity
    Transfers velocity `v` and scalar `speed` onto mesh vertices for Karma XPU / Redshift motion blur (default `On`).

Trim Domain Boundaries:
    #id: trim_domain_bounds
    Cleanly clips flat liquid faces touching the simulation domain walls using exact plane clipping (default `Off`). Removes sawtooth wall artifacts and rounded corner fillets.

Trim Mode / -X / +X / -Y / +Y / -Z / +Z:
    #id: trim_bounds_mode
    Chooses which domain faces are trimmed when *Trim Domain Boundaries* is enabled: `Surface Only (Sides + Bottom)` (default), `Closed FLIP Walls`, `All 6 Domain Faces`, or `Custom Faces` (using the six per-face toggles).

== Velocity Smoothing ==

Adaptive Velocity Smoothing:
    #id: vel_smooth_enable
    Enables *additive* velocity-driven adaptive SDF smoothing on top of base *Smoothing Iterations* (`smoothing_iters`) so slow/calm water receives extra smoothing while fast splashes remain sharp (default `Off`). Base *Smoothing Iterations* always run uniformly whether this toggle is on or off; set *Smoothing Iterations = 0* (or *Filtering = Off*) with *Smooth Strength > 0* for purely velocity-masked smoothing with zero smoothing on fast splashes.

Velocity Min:
    #id: vel_smooth_min
    Speed in `m/s` at or below which the smoothing mask evaluates to `1.0` (calm water, default `0.5 m/s`, UI `0.0..10.0`).

Velocity Max:
    #id: vel_smooth_max
    Speed in `m/s` at or above which the smoothing mask evaluates to `0.0` (fast splashes kept sharp, default `3.0 m/s`, UI `0.001..20.0`).

Smooth Strength:
    #id: vel_smooth_strength
    Additive masked smoothing pass count on top of base *Smoothing Iterations* (`0.0..10.0` UI range, internal cap `0.0..32.0`, default `1.0`). `0.0` skips the additive stage completely so mesh geometry matches *Adaptive Velocity Smoothing = Off* bit-for-bit (while still exporting `f@smooth_mask` if *Visualize Smooth Mask* is enabled); values `> 0.0` run `floor(strength)` full masked passes plus an optional fractional pass so calm regions smooth aggressively while fast splashes (`mask == 0`) remain crisp.

Mask Profile Ramp:
    #id: vel_mask_ramp
    Monotone-cubic float ramp shaping normalized speed `u` in `[0, 1]` to smoothing weight `[0, 1]` (default `0 -> 1.0`, `1 -> 0.0`).

Mask Smooth:
    #id: vel_mask_smooth
    Number of narrow-band spatial blur passes applied to the voxel velocity mask for seamless transitions (default `2`, clamped `0..4`).

Invert Velocity Mask:
    #id: vel_smooth_invert
    Inverts the evaluated velocity mask (`1.0 - mask`) so fast regions smooth instead of calm regions (default `Off`).

Visualize Smooth Mask:
    #id: vel_smooth_visualize
    Writes `f@smooth_mask` (`0..1`) and a deep blue (`0.0` = sharp) -> yellow (`0.5`) -> red (`1.0` = max smoothing) heatmap `Cd` directly onto output mesh vertices (default `Off`).

== Disk Cache (Async .hyc) ==

Cache Mode:
    #id: cache_mode
    Unified asynchronous `.hyc` mesh caching:
    - `Off` (default): Meshes live from Input 0 on every frame.
    - `Write (Async)`: Meshes and writes `<Cache Directory>/v<NNN>/<prefix>_####.hyc` in a background thread.
    - `Read (Playback)`: Plays back cached mesh frames (preserving `N`, `v`, `speed`, and `smooth_mask`) directly from disk *without re-cooking the upstream solver*.
    - `Auto (Read or Sim+Write)`: Reads existing cached mesh frames if valid, or meshes and writes missing frames.

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

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* meshes and writes the configured *Frame Range* to `.hyc` with an interruptible progress bar (`ESC` cancels cleanly); *Clear Disk Cache* flushes pending writes and removes `.hyc` / `.hyc_sig` files in the active version folder.

Live GPU Telemetry:
    #id: info_telemetry
    Read-only telemetry showing active source mode, vertex/triangle counts, meshing timings, cache status, and VRAM usage.

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