/** * Stable public entry point for the Smoothed Particle Hydrodynamics product block. * @module three-blocks/sph */ import type { Object3D, Renderer, StorageBufferAttribute, StorageInstancedBufferAttribute, Vector3 } from 'three/webgpu'; /** GPU storage accepted as an initial SPH particle-position source. */ export type SPHInitialPositions = StorageBufferAttribute | StorageInstancedBufferAttribute; /** Dimensionality accepted by nested particle configuration. */ export type SPHDimension = 2 | 3 | '2d' | '3d'; /** Supported calibration strategies for particle spacing, mass, and kernel radius. */ export type SPHCalibrationMode = 'manual' | 'particle-volume' | 'self-kernel' | 'discrete-lattice'; /** Deterministic CPU layout used when no initial GPU position source is supplied. */ export type SPHInitializationMode = 'block-lattice' | 'block-jittered-lattice' | 'sphere-lattice' | 'random-domain'; /** Outcome-oriented material presets understood by the fluid configuration normalizer. */ export type SPHMaterialPreset = 'water' | 'viscousLiquid' | 'gelLike' | 'custom'; /** Pressure model used to convert density error into acceleration. */ export type SPHEquationOfState = 'linear' | 'tait'; /** Policy for pressure values below the configured rest density. */ export type SPHNegativePressurePolicy = 'allow' | 'clamp'; /** Fixed-step safety policy applied by the solver. */ export type SPHTimeStepPolicy = 'fixed' | 'validated-fixed'; /** Vector-like components accepted by nested domain and initialization options. */ export interface SPHVectorComponents { /** X component; omitted values use the operation's documented default. */ x?: number | undefined; /** Y component; omitted values use the operation's documented default. */ y?: number | undefined; /** Z component; ignored by two-dimensional simulations. */ z?: number | undefined; } /** Compact vector input accepted by SPH configuration sections. */ export type SPHComponents = number[] | SPHVectorComponents; /** Particle population and calibrated layout options. */ export interface SPHParticlesOptions { /** Number of simulated particles. */ count?: number | undefined; /** Center-to-center rest spacing in simulation units. */ spacing?: number | undefined; /** Collision radius, or `"auto"` to derive it from spacing. */ particleRadius?: number | 'auto' | undefined; /** Density-kernel radius, or `"auto"` to derive it from spacing. */ smoothingRadius?: number | 'auto' | undefined; /** Per-particle mass, or `"auto"` to calibrate against rest density. */ mass?: number | 'auto' | undefined; /** Whether the particle layout and solver operate in two or three dimensions. */ dimension?: SPHDimension | undefined; /** Strategy used to calibrate mass and density from the reference lattice. */ calibrationMode?: SPHCalibrationMode | undefined; } /** SPH-specific recommendations nested inside a material configuration. */ export interface SPHSolverMaterialOptions { /** Pressure equation used for density error. */ equationOfState?: SPHEquationOfState | undefined; /** Nominal speed of sound used by the Tait pressure model. */ speedOfSound?: number | undefined; /** Tait equation exponent. */ gamma?: number | undefined; /** Kinematic viscosity converted into solver force coefficients. */ kinematicViscosity?: number | undefined; /** Optional density-diffusion strength. */ densityDiffusion?: number | undefined; /** Optional surface-tension recommendation. */ surfaceTension?: number | undefined; } /** Physical material configuration resolved when constructing an SPH simulation. */ export interface SPHMaterialOptions { /** Named baseline whose remaining fields may be overridden below. */ preset?: SPHMaterialPreset | undefined; /** Target rest density in simulation mass units. */ restDensity?: number | undefined; /** Dynamic-viscosity recommendation used by the preset system. */ viscosity?: number | undefined; /** Surface-tension recommendation retained in the material snapshot. */ surfaceTension?: number | undefined; /** SPH-specific material recommendations. */ sph?: SPHSolverMaterialOptions | undefined; } /** Fixed-step scheduling options used at construction or by `setTimeStepOptions`. */ export interface SPHTimeStepOptions { /** Fixed solver interval in seconds, or `null` for one variable step per frame. */ fixedDelta?: number | null | undefined; /** Maximum fixed solver steps submitted for one host frame. */ maxSubsteps?: number | undefined; /** Maximum accepted host-frame interval in seconds. */ maxFrameDelta?: number | undefined; /** Stability validation applied before GPU work is submitted. */ policy?: SPHTimeStepPolicy | undefined; /** Simulation-speed multiplier applied without changing the host frame delta. */ timeScale?: number | undefined; } /** Axis-aligned domain and boundary-response configuration. */ export interface SPHDomainOptions { /** Domain dimensions expressed as components or a Three.js `Vector3`. */ dimensions?: SPHComponents | Vector3 | undefined; /** Whether particle radius is included when projecting against box boundaries. */ particleRadiusOffset?: boolean | undefined; /** Normal velocity retained after a boundary collision, from `0` to `1`. */ restitution?: number | undefined; /** Tangential damping applied at boundaries. */ friction?: number | undefined; } /** Neighbor-acceleration policy selected at construction. */ export interface SPHNeighborOptions { /** Whether to build and query a spatial neighbor grid. */ enabled?: boolean | undefined; /** Grid build strategy; `"auto"` selects a renderer-appropriate implementation. */ buildAlgorithm?: 'auto' | 'atomic' | 'sort' | undefined; /** Neighbor lookup strategy used by solver passes. */ lookupAlgorithm?: 'global' | 'workgroup' | undefined; } /** Intentional SPH pressure, viscosity, and stabilization controls. */ export interface SPHSolverOptions { /** Pressure equation used for density error. */ equationOfState?: SPHEquationOfState | undefined; /** Nominal speed of sound used by the Tait pressure model. */ speedOfSound?: number | undefined; /** Tait equation exponent. */ gamma?: number | undefined; /** Kinematic-viscosity coefficient. */ kinematicViscosity?: number | undefined; /** Optional density-diffusion strength. */ densityDiffusion?: number | undefined; } /** Deterministic initial particle-layout configuration. */ export interface SPHInitializationOptions { /** Shape and sampling policy used to generate positions. */ mode?: SPHInitializationMode | undefined; /** Fractional domain fill per axis. */ fill?: SPHComponents | undefined; /** Random displacement as a fraction of particle spacing. */ jitter?: number | undefined; /** Seed used by deterministic layout jitter. */ seed?: number | undefined; } /** Opt-in diagnostic configuration retained by the metrics subsystem. */ export interface SPHDiagnosticsOptions { /** Whether the host intends to collect diagnostic snapshots. */ enabled?: boolean | undefined; /** Whether pressure and viscosity acceleration summaries are retained for readback. */ accelerationComponents?: boolean | undefined; } /** * Stable SPH construction options. * * Nested sections are preferred. Common top-level fields remain available as concise * shorthands for the same configuration. */ export interface SPHOptions { /** Calibrated particle population and layout. */ particles?: SPHParticlesOptions | null | undefined; /** Physical material preset and overrides. */ material?: SPHMaterialOptions | null | undefined; /** Fixed-step scheduling and safety policy. */ timeStep?: SPHTimeStepOptions | null | undefined; /** Simulation domain and boundary response. */ domain?: SPHDomainOptions | null | undefined; /** Neighbor-acceleration policy. */ neighbors?: SPHNeighborOptions | null | undefined; /** Pressure, viscosity, and stabilization controls. */ solverOptions?: SPHSolverOptions | null | undefined; /** Deterministic initial layout when `initialPositions` is omitted. */ initialization?: SPHInitializationOptions | null | undefined; /** Opt-in diagnostic behavior. */ diagnostics?: SPHDiagnosticsOptions | null | undefined; /** Top-level flat particle count; prefer `particles.count`. */ count?: number | undefined; /** Top-level dimensionality switch; prefer `particles.dimension`. */ is3D?: boolean | undefined; /** Top-level domain dimensions; prefer `domain.dimensions`. */ domainDimensions?: Vector3 | SPHComponents | undefined; /** Top-level particle mass; prefer `particles.mass`. */ mass?: number | undefined; /** Top-level smoothing radius; prefer `particles.smoothingRadius`. */ h?: number | undefined; /** Top-level rest density; `null` enables calibration. */ restDensity?: number | null | undefined; /** Linear-equation pressure stiffness retained for existing constructors. */ pressureStiffness?: number | undefined; /** Dynamic-viscosity scale retained for existing constructors. */ viscosityMu?: number | undefined; /** Top-level boundary restitution; prefer `domain.restitution`. */ restitution?: number | undefined; /** Maximum particle speed used to clamp divergent updates. */ maxSpeed?: number | undefined; /** Constant world-space acceleration applied to every particle. */ gravity?: Vector3 | undefined; /** Whether optional diagnostics are collected. */ debug?: boolean | undefined; /** Whether internal render integration computes smoothed directions. */ useDirection?: boolean | undefined; /** Whether kernel radius follows object-domain scale changes. */ scaleKernelWithDomain?: boolean | undefined; /** Top-level neighbor-grid toggle; prefer `neighbors.enabled`. */ useSpatialGrid?: boolean | undefined; /** Whether internal render integration computes instance transforms. */ useMatrices?: boolean | undefined; /** Caller-owned GPU positions copied into engine storage on first use. */ initialPositions?: SPHInitialPositions | null | undefined; /** Whether zero-valued external positions are scattered during initialization. */ scatterZeroInitialPositions?: boolean | undefined; /** Top-level fixed interval; prefer `timeStep.fixedDelta`. */ fixedTimeStep?: number | null | undefined; /** Top-level substep cap; prefer `timeStep.maxSubsteps`. */ maxSubsteps?: number | undefined; /** Top-level host-delta cap; prefer `timeStep.maxFrameDelta`. */ maxFrameDelta?: number | undefined; /** Top-level speed multiplier; prefer `timeStep.timeScale`. */ timeScale?: number | undefined; /** Top-level collision radius; prefer `particles.particleRadius`. */ particleRadius?: number | null | undefined; /** Top-level rest spacing; prefer `particles.spacing`. */ spacing?: number | null | undefined; /** Top-level calibration strategy; prefer `particles.calibrationMode`. */ calibrationMode?: SPHCalibrationMode | undefined; /** Top-level boundary friction; prefer `domain.friction`. */ friction?: number | undefined; /** Top-level pressure equation; prefer `solverOptions.equationOfState`. */ equationOfState?: SPHEquationOfState | undefined; /** Top-level sound-speed control; prefer `solverOptions.speedOfSound`. */ speedOfSound?: number | undefined; /** Top-level Tait exponent; prefer `solverOptions.gamma`. */ gamma?: number | undefined; /** Treatment of pressure below rest density. */ negativePressurePolicy?: SPHNegativePressurePolicy | undefined; /** Lower pressure bound used when negative pressure is clamped. */ pressureFloor?: number | undefined; /** Top-level viscosity; prefer `solverOptions.kinematicViscosity`. */ kinematicViscosity?: number | undefined; /** Top-level safety policy; prefer `timeStep.policy`. */ timeStepPolicy?: SPHTimeStepPolicy | undefined; /** Whether supported external boundaries contribute to density estimates. */ boundaryDensitySupport?: boolean | undefined; /** Top-level density diffusion; prefer `solverOptions.densityDiffusion`. */ densityDiffusion?: number | undefined; } /** Options for binding the simulation domain to a Three.js object's bounds. */ export interface SPHDomainBindingOptions { /** Padding added around the object's local bounds. */ padding?: number | Vector3 | undefined; /** Whether object transforms are refreshed before every solver step. */ autoUpdate?: boolean | undefined; /** Optional simulation-to-object scale override. */ simulationScale?: number | Vector3 | null | undefined; } /** Options for resetting particles into a deterministic CPU-generated layout. */ export interface SPHResetOptions { /** Shape and sampling policy used for the reset. */ mode?: SPHInitializationMode | undefined; /** Particle spacing used by the generated layout. */ spacing?: number | undefined; /** Collision radius reserved inside the reset domain. */ particleRadius?: number | undefined; /** Dimensions of the generated layout. */ dimension?: SPHDimension | undefined; /** Domain dimensions used to bound generated positions. */ domainDimensions?: SPHComponents | undefined; /** Fractional domain fill per axis. */ fill?: SPHComponents | undefined; /** Layout center in simulation coordinates. */ center?: SPHComponents | undefined; /** Random displacement as a fraction of spacing. */ jitter?: number | undefined; /** Seed used for deterministic layout jitter. */ seed?: number | undefined; /** Behavior when the requested count exceeds unique lattice positions. */ excessParticlePolicy?: 'repeat' | 'error' | undefined; } /** Aggregate minimum, mean, and maximum for a sampled metric. */ export interface SPHMetricSummary { /** Arithmetic mean across live particles. */ readonly mean: number; /** Smallest sampled value. */ readonly minimum: number; /** Largest sampled value. */ readonly maximum: number; } /** Read-only, opt-in SPH diagnostic snapshot produced after a requested step. */ export interface SPHMetrics { /** Density error relative to configured rest density. */ readonly density: Readonly<{ /** Mean ratio of measured density to rest density. */ meanRatio: number; /** Root-mean-square density error. */ rmsError: number; /** Largest measured density ratio. */ maximumRatio: number; /** Largest positive density error. */ maximumPositiveError: number; }>; /** Neighbor count distribution over live particles. */ readonly neighbors: Readonly; /** Particle-speed distribution for the sampled frame. */ readonly velocity: Readonly<{ /** Largest sampled speed. */ maximum: number; /** Mean sampled speed. */ mean: number; }>; /** Boundary and overlap diagnostics available without exposing live buffers. */ readonly boundaries: Readonly<{ /** Projected particle count when supplied by an active boundary provider. */ projectedParticles: number | null; /** Maximum measured boundary penetration when available. */ maximumPenetration: number | null; /** Number of particle pairs closer than the overlap threshold. */ overlapPairs: number; }>; /** Solver-specific diagnostic summaries. */ readonly solver: Readonly<{ /** Stable solver identifier. */ type: 'sph'; /** Optional pressure-acceleration magnitude summary. */ pressureAcceleration?: Readonly | undefined; /** Optional viscosity-acceleration magnitude summary. */ viscosityAcceleration?: Readonly | undefined; }>; } /** Read-only calibration result selected during construction. */ export interface SPHCalibrationSnapshot { /** Calibration strategy that produced the snapshot. */ readonly mode: SPHCalibrationMode; /** Resolved simulation dimensionality. */ readonly dimension: 2 | 3; /** Resolved rest spacing. */ readonly spacing: number; /** Resolved kernel radius. */ readonly smoothingRadius: number; /** Kernel radius divided by particle spacing. */ readonly smoothingRadiusRatio: number; /** Resolved collision radius. */ readonly particleRadius: number; /** Resolved particle mass. */ readonly particleMass: number; /** Resolved target rest density. */ readonly restDensity: number; /** Expected neighbors in the reference lattice. */ readonly expectedNeighborCount: number; /** Density reproduced by the reference lattice. */ readonly referenceDensity: number; /** Relative reference-lattice density error. */ readonly referenceDensityError: number; /** Coarse warning tier for neighbor support. */ readonly neighborQuality: 'low' | 'useful'; } /** Small read-only SPH state snapshot that does not expose live GPU resources. */ export interface SPHStats { /** Stable solver identifier. */ readonly solver: 'sph'; /** Number of live particles. */ readonly particleCount: number; /** Active fixed interval, or `null` for variable stepping. */ readonly fixedDelta: number | null; /** Maximum fixed steps submitted for one host frame. */ readonly maxSubsteps: number; /** Whether neighbor-grid acceleration is active. */ readonly spatialGrid: boolean; /** Construction-time calibration snapshot, when available. */ readonly calibration: Readonly | null; } /** Renderer limits required by the currently enabled SPH diagnostic outputs. */ export interface SPHRendererLimits { /** Minimum storage-buffer binding count required for one shader stage. */ readonly maxStorageBuffersPerShaderStage: number; } /** * Stable declaration-facing façade for the Smoothed Particle Hydrodynamics engine. * * The façade preserves the original engine object and constructor identity. It exposes * controlled configuration, snapshots, per-frame scheduling, reset, and disposal while * keeping mutable uniforms, storage buffers, compute nodes, grids, and solver passes private. */ export interface SPH { /** Number of live particles advanced by each step. */ readonly particleCount: number; /** * Update fixed-step scheduling between frames. * Changes apply to the next {@link SPH.step} call. */ setTimeStepOptions(options?: SPHTimeStepOptions): this; /** * Change the density-kernel radius and rebuild dependent coefficients. * Call between frames; active neighbor acceleration is synchronized automatically. * @throws {Error} If the radius cannot produce a valid kernel configuration. */ setSmoothingRadius(radius: number): this; /** * Set target density, or pass `null` to restore calibrated automatic density. * Call between frames before the next solver step. */ setRestDensity(value: number | null | undefined): this; /** * Set particle mass and refresh automatic density calibration when enabled. * Call between frames before the next solver step. */ setMass(value: number): this; /** * Request one asynchronous diagnostic readback after the next completed step. * Readback can stall the GPU; it is never performed unless explicitly requested. */ requestMetricsReadback(): this; /** Return the latest immutable metric snapshot, or `null` before a requested readback completes. */ getLastMetrics(): Readonly | null; /** Return lightweight synchronous state without exposing live GPU resources. */ getStats(): Readonly; /** Return immutable binding limits needed before renderer/device creation. */ getRequiredRendererLimits(): Readonly; /** * Replace live particle positions with a deterministic generated layout. * Await any active step first and call before rendering the next frame. * @throws {Error} If the configured lattice cannot hold the particle count. */ reset(renderer: Renderer, options?: SPHResetOptions): Promise; /** * Resize the axis-aligned domain and synchronize neighbor acceleration. * Call between steps. */ setDomainDimensions(dimensions: Vector3): this; /** * Bind the simulation domain to a caller-owned Three.js object. * The object is observed but never disposed by the simulation. * @throws {Error} If the object has no usable bounds. */ setDomainFromObject(object: Object3D, options?: SPHDomainBindingOptions): this; /** Enable or disable engine-owned neighbor-grid acceleration between frames. */ setSpatialGridEnabled(enabled: boolean): this; /** * Advance GPU state for one host frame. * Update controls and bound objects first, await this method, then render. * The first call may initialize the renderer and copy initial positions. * @throws {Error} If stability validation, renderer initialization, compute submission, or boundary projection fails. */ step(renderer: Renderer, deltaTime?: number | undefined): Promise; /** * Release engine-owned grids, storage resources, compute passes, and GUI bindings. * Caller-owned renderers, domain objects, initial-position sources, and render assets are untouched. * Repeated host teardown may call this method safely; do not step after disposal. */ dispose(): void; } interface SPHConstructor { /** * Construct an SPH engine and allocate its owned GPU storage. * @throws {Error} If calibration, initial layout, or GPU storage construction fails. * @throws {TypeError} If an external initial-position source is incompatible. */ new (options?: SPHOptions): SPH; /** Runtime prototype of the underlying SPH engine. */ readonly prototype: SPH; } /** Construct a stable SPH façade without wrapping or copying the runtime engine. */ export declare const SPH: SPHConstructor; export {};