### Run the demo Source: https://docs.threejswaterpro.com/guide/installation.html Commands to install dependencies and start the development server for the ocean demo. ```bash cd threejs-water-pro npm install npm run dev ``` -------------------------------- ### Run Development Server Source: https://docs.threejswaterpro.com/guide/basic-example.html Starts the local development server to view the project in the browser. ```bash npm run dev ``` -------------------------------- ### Build Library Dependencies Source: https://docs.threejswaterpro.com/guide/basic-example.html Install local dependencies and build the library from the provided package. ```bash npm install npm run build:lib ``` -------------------------------- ### Install Three.js Dependencies Source: https://docs.threejswaterpro.com/guide/basic-example.html Install the required Three.js package and its corresponding TypeScript definitions. ```bash npm install three@^0.183.0 npm install --save-dev @types/three@^0.183.0 ``` -------------------------------- ### Install Three.js dependency Source: https://docs.threejswaterpro.com/guide/installation.html Required version of Three.js for the library. ```bash npm install three@^0.181.0 ``` -------------------------------- ### Start Local Development Server Source: https://docs.threejswaterpro.com/guide/basic-example.html Commands to serve files locally to avoid browser restrictions on ES modules. ```bash # Using Python python3 -m http.server 8080 # Using Node.js (npx) npx serve . # Using PHP php -S localhost:8080 ``` -------------------------------- ### Buoyancy Implementation Example Source: https://docs.threejswaterpro.com/api/buoyancy.html Demonstrates registering objects with different sampling configurations and updating them at runtime. ```typescript import * as THREE from "three/webgpu"; // Ship with multi-point sampling (the default), giving full pitch and roll dynamics. const shipId = water.buoyancy.addObject(shipMesh, { heightOffset: -2, rotationInfluence: 0.6, }); // Override the bounding box with explicit sample dimensions. const customShipId = water.buoyancy.addObject(shipMesh, { heightOffset: -2, rotationInfluence: 0.6, useBoundingBox: false, sampleLength: 30, sampleWidth: 8, sampleOffset: new THREE.Vector3(0, 0, 5), }); // Buoy with single-point sampling. It bobs up and down without tilting. const buoyId = water.buoyancy.addObject(buoyMesh, { multiPoint: false, heightOffset: 0.5, }); // Update an object's parameters at runtime. water.buoyancy.updateObjectConfig(shipId, { heightOffset: -1.5, rotationInfluence: 0.8, }); // Remove when done. water.buoyancy.removeObject(buoyId); ``` -------------------------------- ### Configure Ocean Floor State Source: https://docs.threejswaterpro.com/api/ocean-floor.html Example usage for setting the floor depth and visibility. ```typescript water.floor.setDepth(40); water.floor.setVisible(false); ``` -------------------------------- ### Get Sampler Method Source: https://docs.threejswaterpro.com/api/buoyancy.html Provides access to the underlying wave sampler for external systems. ```typescript getSampler(): IWaveSampler ``` -------------------------------- ### Load Preset Source: https://docs.threejswaterpro.com/api/water-system.html Defines the signature for loading a preset and provides examples for loading by name or object. ```typescript loadPreset(preset: PresetName | WaterPreset): void ``` ```typescript water.loadPreset("sunset"); water.loadPreset(myCustomPreset); ``` -------------------------------- ### Configure Transparent Material Source: https://docs.threejswaterpro.com/guide/transparent-objects.html Standard setup for a transparent material that automatically integrates with fog, reflections, and depth sorting. ```typescript const material = new THREE.MeshStandardMaterial({ color: 0x4488ff, transparent: true, opacity: 0.5, }); // Fog, reflections, and depth sorting are handled automatically. ``` -------------------------------- ### Update Ambient Particles Configuration Source: https://docs.threejswaterpro.com/api/particles.html Example of applying new particle settings to the water instance. ```typescript water.particles.updateParams({ count: 200, minSize: 0.1, maxSize: 0.3, opacity: 0.4, color: "#a0c8d0", nearDistance: 2, farDistance: 50, }); ``` -------------------------------- ### Water Masking Usage Example Source: https://docs.threejswaterpro.com/api/masking.html Demonstrates registering a mesh as a mask, checking its status, removing it, and toggling the masking feature. ```typescript water.masking.add(hullMesh); water.masking.has(hullMesh); water.masking.remove(hullMesh); // Turn masking off temporarily without unregistering objects. water.masking.enabled = false; ``` -------------------------------- ### Boat Hull Masking Example Source: https://docs.threejswaterpro.com/guide/water-masking.html Shows how to parent a simplified mask mesh to a model for automatic transform synchronization and register it for masking. ```typescript // Load boat model const boat = await loadBoatModel(); scene.add(boat); // Create simplified hull interior mask const hullMask = new THREE.Mesh( new THREE.BoxGeometry(8, 3, 15), new THREE.MeshBasicMaterial(), ); // Position mask inside hull and hide from main render hullMask.position.set(0, -1, 0); hullMask.visible = false; boat.add(hullMask); // Parent to boat for automatic transforms // Register as water mask water.masking.add(hullMask); ``` -------------------------------- ### Dispose and Animate Source: https://docs.threejswaterpro.com/api/water-system.html Example of the animation loop and proper resource disposal to prevent memory leaks. ```typescript dispose(): void ``` ```typescript function animate() { water.update(clock.getDelta()); water.render(); requestAnimationFrame(animate); } // Cleanup water.dispose(); ``` -------------------------------- ### Geometry and Height Configuration Source: https://docs.threejswaterpro.com/api/water-system.html Defines signatures for geometry and height queries, and provides usage examples for common configuration tasks. ```typescript getHeightAt(x: number, z: number): Promise ``` ```typescript setPosition(x: number, z: number): void ``` ```typescript rebuildGeometry(config: Partial>): void ``` ```typescript recreateOceanFloor(options: Partial): Promise ``` ```typescript getGeometryConfig(): Readonly ``` ```typescript water.rebuildGeometry({ levels: 5, baseSize: 600 }); await water.recreateOceanFloor({ meshResolution: 64 }); const height = await water.getHeightAt(100, 200); ``` -------------------------------- ### Managing Wake Generators in TypeScript Source: https://docs.threejswaterpro.com/api/wake.html Demonstrates how to register, update, and remove wake generators for different mesh types, including multi-generator setups for complex wake patterns. ```typescript import * as THREE from "three/webgpu"; // Register a boat with a deep, wide hull footprint at its centre. const boatId = water.wake.addGenerator(boatMesh, { depth: 1.2, radius: 4.0 }); // For a richer wake, register a bow and a stern generator (forward = +Z here). // The field superposes them into a bow wave plus a stern trail. const bowId = water.wake.addGenerator(boatMesh, { depth: 1.2, radius: 4.0, offset: new THREE.Vector3(0, 0, 10), // 10 m forward of the origin }); const sternId = water.wake.addGenerator(boatMesh, { depth: 1.2, radius: 4.0, offset: new THREE.Vector3(0, 0, -10), // 10 m aft }); // Register a small buoy with a shallow, tight footprint. const buoyId = water.wake.addGenerator(buoyMesh, { depth: 0.3, radius: 1.5 }); // Temporarily stop injection (e.g. while the boat is in dry dock). water.wake.updateGenerator(boatId, { active: false }); // Increase friction for a shorter, more damped trail. Friction does not // change amplitude. water.wake.friction = 0.5; // Unregister. water.wake.removeGenerator(boatId); ``` -------------------------------- ### Initialize Sky and Water Systems in main.js Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html Sets up the WebGPURenderer, configures the Sky and Water systems, and initializes the post-processing pipeline. Requires the three/webgpu and associated library modules. ```javascript import * as THREE from "three/webgpu"; import { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { WaterSystem, getPresetParams } from "../lib/threejs-water-pro/index.js"; import { SkySystem, PRESETS } from "../lib/threejs-sky-pro/index.js"; function setupPostProcessing(renderer, water, sky) { const postProcessing = new THREE.PostProcessing(renderer); const scenePass = pass(water.scene, water.camera); let outputNode = scenePass.getTextureNode("output"); // Add water effects (atmospheric fog, underwater haze, sun shafts) outputNode = water.postProcessing.buildNode(scenePass, outputNode); // Composite the sky over the scene (distance fog, clouds, god rays). // It reads the scene pass depth, so clouds pass behind your geometry. outputNode = sky.applyTo(outputNode, scenePass); // Add bloom const bloomPass = bloom(outputNode, 0.5, 0.4, 0.85); outputNode = outputNode.add(bloomPass); postProcessing.outputNode = outputNode; return postProcessing; } async function main() { // Create renderer const renderer = new THREE.WebGPURenderer(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1)); renderer.toneMapping = THREE.ACESFilmicToneMapping; document.body.appendChild(renderer.domElement); await renderer.init(); // Create scene and camera const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 50000, ); camera.position.set(50, 25, 50); // Add orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; // Create water system const water = await WaterSystem.create(renderer, scene, camera, "medium"); water.loadPreset(getPresetParams("blackFlag")); // Create the sky. SkySystem.create adds its backdrop meshes to the scene // for you; applyPreset sets the look (clouds, atmosphere, sun). const sky = await SkySystem.create({ renderer, camera, scene, quality: "medium" }); await sky.applyPreset(PRESETS.partlyCloudy); sky.sun.setFromAngles(35, 120); // Wire the sky into the water. The provider drives the water's sun // lighting, reflections, and fog color. `envMap: true` bakes an // environment map so reflections include the clouds. water.setSky(sky.createSkyProvider({ envMap: true })); // Set up post-processing const postProcessing = setupPostProcessing(renderer, water, sky); // Handle window resize window.addEventListener("resize", () => { const w = window.innerWidth; const h = window.innerHeight; renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); water.resize(); sky.resize(w, h); }); // Compile shaders before starting animation await renderer.compileAsync(scene, camera); // Animation loop let lastTime = performance.now(); async function animate() { requestAnimationFrame(animate); const now = performance.now(); const deltaTime = (now - lastTime) / 1000; lastTime = now; controls.update(); sky.update(deltaTime); await water.update(deltaTime); postProcessing.render(); } animate(); } main(); ``` -------------------------------- ### Initialize Main Application Loop Source: https://docs.threejswaterpro.com/guide/basic-example.html Sets up post-processing, window resizing, shader compilation, and the animation loop for the water scene. ```javascript // Set up post-processing const postProcessing = setupPostProcessing(renderer, water); // Handle window resize window.addEventListener("resize", () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); water.resize(); }); // Compile shaders before starting animation await renderer.compileAsync(scene, camera); // Animation loop let lastTime = performance.now(); async function animate() { requestAnimationFrame(animate); const now = performance.now(); const deltaTime = (now - lastTime) / 1000; lastTime = now; controls.update(); await water.update(deltaTime); postProcessing.render(); } animate(); } main(); ``` -------------------------------- ### getGeometryConfig Source: https://docs.threejswaterpro.com/api/water-system.html Get the current clipmap geometry configuration. ```APIDOC ## getGeometryConfig() ### Description Get the current clipmap geometry configuration. ``` -------------------------------- ### Initialize Water System in main.js Source: https://docs.threejswaterpro.com/guide/basic-example.html The main entry point script that sets up the WebGPU renderer, scene, camera, and water system. ```javascript import * as THREE from "three/webgpu"; import { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { WaterSystem, Sky, getPresetParams } from "../lib/index.js"; function setupPostProcessing(renderer, water) { const postProcessing = new THREE.PostProcessing(renderer); const scenePass = pass(water.scene, water.camera); let outputNode = scenePass.getTextureNode("output"); // Add water effects (atmospheric fog, underwater haze, sun shafts) outputNode = water.postProcessing.buildNode(scenePass, outputNode); // Add bloom const bloomPass = bloom(outputNode, 0.5, 0.4, 0.85); outputNode = outputNode.add(bloomPass); postProcessing.outputNode = outputNode; return postProcessing; } async function main() { // Create renderer const renderer = new THREE.WebGPURenderer(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1)); renderer.toneMapping = THREE.ACESFilmicToneMapping; document.body.appendChild(renderer.domElement); await renderer.init(); // Create scene and camera const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 20000, ); camera.position.set(50, 25, 50); // Add orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; // Load preset params (used for both water and sky configuration) const preset = getPresetParams("dusk"); // Create water system const water = await WaterSystem.create(renderer, scene, camera, "high"); water.loadPreset(preset); // Load an equirectangular sky image const loader = new THREE.TextureLoader(); const equirect = await loader.loadAsync("sky.jpg"); equirect.mapping = THREE.EquirectangularReflectionMapping; equirect.wrapS = THREE.RepeatWrapping; equirect.colorSpace = THREE.SRGBColorSpace; const sky = new Sky(renderer, { equirect, sunDirection: water.lighting.sun.direction, }); for (const mesh of sky.getMeshes()) scene.add(mesh); water.setSky(sky); for (let i = 0; i < 10; i++) { const geometry = new THREE.BoxGeometry(4, 4, 4); const material = new THREE.MeshStandardMaterial({ color: new THREE.Color(Math.random(), Math.random(), Math.random()), }); const box = new THREE.Mesh(geometry, material); // Position boxes in a scattered pattern const angle = (i / 10) * Math.PI * 2; const distance = 10 + Math.random() * 25; box.position.set(Math.cos(angle) * distance, 0, Math.sin(angle) * distance); // Add box to the scene scene.add(box); // Add to buoyancy system water.buoyancy.addObject(box, { heightSmoothing: 0.15, rotationSmoothing: 0.1, }); } ``` -------------------------------- ### Get Ocean Floor Mesh Source: https://docs.threejswaterpro.com/api/ocean-floor.html Retrieves the underlying Three.js mesh instance. ```typescript getMesh(): THREE.Mesh ``` -------------------------------- ### Initialize Main Application Entry Point Source: https://docs.threejswaterpro.com/guide/basic-example.html Configures the WebGPU renderer, scene, camera, and water system. Requires a valid sky.jpg texture in the project root for proper atmospheric rendering. ```typescript import * as THREE from "three/webgpu"; import { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { WaterSystem, Sky, getPresetParams } from "./threejs-water-pro"; function setupPostProcessing( renderer: THREE.WebGPURenderer, water: WaterSystem, ): THREE.PostProcessing { const postProcessing = new THREE.PostProcessing(renderer); const scenePass = pass(water.scene, water.camera); let outputNode: THREE.Node = scenePass.getTextureNode("output"); // Add water effects (atmospheric fog, underwater haze, sun shafts) outputNode = water.postProcessing.buildNode(scenePass, outputNode); // Add bloom const bloomPass = bloom(outputNode, 0.5, 0.4, 0.85); outputNode = outputNode.add(bloomPass); postProcessing.outputNode = outputNode; return postProcessing; } async function main() { // Create renderer const renderer = new THREE.WebGPURenderer(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1)); renderer.toneMapping = THREE.ACESFilmicToneMapping; document.body.appendChild(renderer.domElement); await renderer.init(); // Create scene and camera const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 20000, ); camera.position.set(50, 25, 50); // Add orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; // Load preset params (used for both water and sky configuration) const preset = getPresetParams("dusk"); // Create water system const water = await WaterSystem.create(renderer, scene, camera, "high"); water.loadPreset(preset); // Load an equirectangular sky image const loader = new THREE.TextureLoader(); const equirect = await loader.loadAsync("sky.jpg"); equirect.mapping = THREE.EquirectangularReflectionMapping; equirect.wrapS = THREE.RepeatWrapping; equirect.colorSpace = THREE.SRGBColorSpace; const sky = new Sky(renderer, { equirect, sunDirection: water.lighting.sun.direction, }); for (const mesh of sky.getMeshes()) scene.add(mesh); water.setSky(sky); for (let i = 0; i < 10; i++) { const geometry = new THREE.BoxGeometry(4, 4, 4); const material = new THREE.MeshStandardMaterial({ color: new THREE.Color(Math.random(), Math.random(), Math.random()), }); const box = new THREE.Mesh(geometry, material); // Position boxes in a scattered pattern const angle = (i / 10) * Math.PI * 2; const distance = 10 + Math.random() * 25; box.position.set(Math.cos(angle) * distance, 0, Math.sin(angle) * distance); // Add box to the scene scene.add(box); // Add to buoyancy system water.buoyancy.addObject(box, { heightSmoothing: 0.15, rotationSmoothing: 0.1, }); } // Set up post-processing const postProcessing = setupPostProcessing(renderer, water); // Handle window resize window.addEventListener("resize", () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); water.resize(); }); // Compile shaders before starting animation await renderer.compileAsync(scene, camera); // Animation loop let lastTime = performance.now(); async function animate() { requestAnimationFrame(animate); const now = performance.now(); const deltaTime = (now - lastTime) / 1000; lastTime = now; controls.update(); await water.update(deltaTime); postProcessing.render(); } animate(); } main(); ``` -------------------------------- ### create Source: https://docs.threejswaterpro.com/api/water-system.html Static factory method to initialize the WaterSystem. ```APIDOC ## create(renderer, scene, camera, quality?, options?) ### Description Static async factory method and the only way to construct a WaterSystem. ### Parameters - **renderer** (THREE.WebGPURenderer) - Required - **scene** (THREE.Scene) - Required - **camera** (THREE.PerspectiveCamera) - Required - **quality** (QualityLevel) - Optional - **options** (WaterSystemOptions) - Optional ``` -------------------------------- ### Get all generators Source: https://docs.threejswaterpro.com/api/wake.html Returns a live, read-only map of all registered generators keyed by their ID. ```typescript getGenerators(): ReadonlyMap ``` -------------------------------- ### Initialize WaterSystem with create() Source: https://docs.threejswaterpro.com/api/water-system.html Use the static async create method to instantiate the system with required Three.js components. ```typescript static async create( renderer: THREE.WebGPURenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera, quality?: QualityLevel, options?: WaterSystemOptions, ): Promise ``` -------------------------------- ### Get generator count Source: https://docs.threejswaterpro.com/api/wake.html Returns the total number of currently registered wake generators. ```typescript getGeneratorCount(): number ``` -------------------------------- ### Initialize Vite Project Source: https://docs.threejswaterpro.com/guide/basic-example.html Create a new project directory using the Vite vanilla-ts template. ```bash npm create vite@latest my-ocean-project -- --template vanilla-ts cd my-ocean-project ``` -------------------------------- ### WaterSystem.create() Source: https://docs.threejswaterpro.com/api/water-system.html Static async factory method to instantiate the WaterSystem with specified renderer, scene, camera, and optional configuration. ```APIDOC ## static async create(renderer, scene, camera, quality?, options?) ### Description Initializes the water rendering system. This is the required method to create a new instance of WaterSystem. ### Parameters - **renderer** (THREE.WebGPURenderer) - Required - Initialized WebGPU renderer. - **scene** (THREE.Scene) - Required - Three.js scene to add water to. - **camera** (THREE.PerspectiveCamera) - Required - Camera for rendering. - **quality** (QualityLevel) - Optional - Quality tier: "low", "medium", "high", "ultra". Default: "high". - **options** (WaterSystemOptions) - Optional - Configuration object. ### Options - **deterministic** (boolean) - Optional - Enable fixed-step simulation. Default: false. - **seed** (number) - Optional - Phillips spectrum seed. Default: 1. - **stepSize** (number) - Optional - Fixed simulation substep in seconds. Default: 1/60. ``` -------------------------------- ### Setting Up Post-Processing Source: https://docs.threejswaterpro.com/guide/post-processing.html Initialize a PostProcessing instance and apply water effects to the output node. ```typescript import * as THREE from "three/webgpu"; import { pass } from "three/tsl"; const postProcessing = new THREE.PostProcessing(renderer); const scenePass = pass(water.scene, water.camera); let outputNode: THREE.Node = scenePass.getTextureNode("output"); // Apply water effects (atmospheric fog, underwater haze, sun shafts) outputNode = water.postProcessing.buildNode(scenePass, outputNode); postProcessing.outputNode = outputNode; ``` -------------------------------- ### Get Camera Water Height Method Source: https://docs.threejswaterpro.com/api/buoyancy.html Retrieves the water height at the current camera position. ```typescript getCameraWaterHeight(): number ``` -------------------------------- ### Get Object Count Method Source: https://docs.threejswaterpro.com/api/buoyancy.html Returns the total number of objects currently registered for buoyancy. ```typescript getObjectCount(): number ``` -------------------------------- ### Initialize Sky and Water Systems Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html Configures the WebGPURenderer, sets up the scene with water and sky systems, and defines the animation loop for rendering. ```typescript import * as THREE from "three/webgpu"; import { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { WaterSystem, getPresetParams } from "./threejs-water-pro"; import { SkySystem, PRESETS } from "./threejs-sky-pro"; function setupPostProcessing( renderer: THREE.WebGPURenderer, water: WaterSystem, sky: SkySystem, ): THREE.PostProcessing { const postProcessing = new THREE.PostProcessing(renderer); const scenePass = pass(water.scene, water.camera); let outputNode: THREE.Node = scenePass.getTextureNode("output"); // Add water effects (atmospheric fog, underwater haze, sun shafts) outputNode = water.postProcessing.buildNode(scenePass, outputNode); // Composite the sky over the scene (distance fog, clouds, god rays). // It reads the scene pass depth, so clouds pass behind your geometry. outputNode = sky.applyTo(outputNode, scenePass); // Add bloom const bloomPass = bloom(outputNode, 0.5, 0.4, 0.85); outputNode = outputNode.add(bloomPass); postProcessing.outputNode = outputNode; return postProcessing; } async function main() { // Create renderer const renderer = new THREE.WebGPURenderer(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1)); renderer.toneMapping = THREE.ACESFilmicToneMapping; document.body.appendChild(renderer.domElement); await renderer.init(); // Create scene and camera const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 50000, ); camera.position.set(50, 25, 50); // Add orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; // Create water system const water = await WaterSystem.create(renderer, scene, camera, "medium"); water.loadPreset(getPresetParams("blackFlag")); // Create the sky. SkySystem.create adds its backdrop meshes to the scene // for you; applyPreset sets the look (clouds, atmosphere, sun). const sky = await SkySystem.create({ renderer, camera, scene, quality: "medium" }); await sky.applyPreset(PRESETS.partlyCloudy); sky.sun.setFromAngles(35, 120); // Wire the sky into the water. The provider drives the water's sun // lighting, reflections, and fog color. `envMap: true` bakes an // environment map so reflections include the clouds. water.setSky(sky.createSkyProvider({ envMap: true })); // Set up post-processing const postProcessing = setupPostProcessing(renderer, water, sky); // Compile shaders before starting animation await renderer.compileAsync(scene, camera); // Animation loop let lastTime = performance.now(); async function animate() { requestAnimationFrame(animate); const now = performance.now(); const deltaTime = (now - lastTime) / 1000; lastTime = now; controls.update(); sky.update(deltaTime); await water.update(deltaTime); postProcessing.render(); } animate(); } main(); ``` -------------------------------- ### Configure Basic Wave Parameters Source: https://docs.threejswaterpro.com/guide/wave-tuning.html Sets initial values for wind speed, peak wavelength, choppiness, and standing wave ratio. ```typescript water.waves.windSpeed.value = 8; water.waves.peakWavelength.value = 75; water.waves.choppiness.value = 0.8; water.waves.standingWaveRatio.value = 0.3; ``` -------------------------------- ### Initialize WebGPURenderer Source: https://docs.threejswaterpro.com/guide/installation.html Correct import and initialization pattern for WebGPU support. ```typescript // Correct - import from three/webgpu import * as THREE from "three/webgpu"; const renderer = new THREE.WebGPURenderer(); await renderer.init(); // Wrong - won't work with WebGPU features import * as THREE from "three"; ``` -------------------------------- ### Initialize Deterministic WaterSystem Source: https://docs.threejswaterpro.com/api/water-system.html Sets up the WaterSystem with deterministic mode enabled and synchronizes it to an authoritative network tick. ```typescript const water = await WaterSystem.create(renderer, scene, camera, "high", { deterministic: true, seed: 12345, }); // Whenever your network reports an authoritative tick: water.syncToTick(authoritativeTick); ``` -------------------------------- ### Apply a Preset After Initialization Source: https://docs.threejswaterpro.com/guide/presets.html Load a built-in preset by name after the water system has been created. ```typescript const scene = new THREE.Scene(); const water = await WaterSystem.create(renderer, scene, camera); water.loadPreset("sunset"); ``` -------------------------------- ### Get Ocean Floor Depth Source: https://docs.threejswaterpro.com/api/ocean-floor.html Retrieves the current depth of the floor below the water surface in world units. ```typescript getDepth(): number ``` -------------------------------- ### Project File Structure Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html Recommended directory layout for integrating the library bundles into a Vite project. ```text my-ocean-project/ ├── src/ │ ├── threejs-water-pro/ │ │ ├── index.js ← Water Pro library bundle │ │ ├── index.js.map ← Source map │ │ └── index.d.ts ← TypeScript declarations │ ├── threejs-sky-pro/ │ │ ├── data/ ← Cloud noise data │ │ ├── index.js ← Sky Pro library bundle │ │ ├── index.js.map ← Source map │ │ └── index.d.ts ← TypeScript declarations │ └── main.ts ├── index.html └── package.json ``` -------------------------------- ### Get debug data Source: https://docs.threejswaterpro.com/api/wake.html Retrieves debug information for all generators, including world-space injection points and hull properties. ```typescript getDebugData(): WakeDebugData[] ``` -------------------------------- ### Import the library Source: https://docs.threejswaterpro.com/guide/installation.html Importing the WaterSystem class from the library path. ```typescript import { WaterSystem } from "/lib/threejs-water-pro"; ``` -------------------------------- ### Get Debug Data Method Source: https://docs.threejswaterpro.com/api/buoyancy.html Retrieves diagnostic data including sample points and resolved heights for visualization. ```typescript getDebugData(): BuoyancyDebugData[] ``` -------------------------------- ### Enable Environment Mapping Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html Configuration option to include cloud reflections in the water surface. ```javascript envMap: true ``` -------------------------------- ### View build directory structure Source: https://docs.threejswaterpro.com/guide/installation.html The contents of the build folder after running the build command. ```text build/ ├── index.js ← Main library bundle ├── index.js.map ← Source map for debugging └── index.d.ts ← TypeScript declarations ``` -------------------------------- ### Configure index.html Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html Basic HTML boilerplate for the application, including CSS reset and script entry point. ```html Three.js Water Pro + Sky Pro ``` -------------------------------- ### Initialize WaterSystem Source: https://docs.threejswaterpro.com/api/water-system.html The static factory method required to construct a new WaterSystem instance. ```typescript create(renderer: THREE.WebGPURenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera, quality?: QualityLevel, options?: WaterSystemOptions): Promise ``` -------------------------------- ### Register and Remove Wake Generators Source: https://docs.threejswaterpro.com/guide/wake.html Add an object to the wake system to start generating a wake, or remove it when the object is no longer needed. ```typescript // Register a boat. The returned id is used for later updates/removal. const boatId = water.wake.addGenerator(boatMesh, { depth: 1.2, // Hull depth in metres. Controls the wake amplitude. radius: 4.0, // Footprint radius in metres. Controls the wake width. }); // Stop the wake (e.g. the boat left the scene). water.wake.removeGenerator(boatId); ``` -------------------------------- ### Switch Presets at Runtime Source: https://docs.threejswaterpro.com/guide/presets.html Update the water system configuration dynamically by loading a different preset. ```typescript water.loadPreset("storm"); ``` -------------------------------- ### Project File Structure Source: https://docs.threejswaterpro.com/guide/basic-example.html The expected directory layout after copying the library files into the src folder. ```text my-ocean-project/ ├── src/ │ ├── threejs-water-pro/ │ │ ├── index.js ← Main library bundle │ │ ├── index.js.map ← Source map │ │ └── index.d.ts ← TypeScript declarations │ └── main.ts ├── index.html └── package.json ``` -------------------------------- ### Initialize Water System with Quality Level Source: https://docs.threejswaterpro.com/guide/quality-levels.html Set the initial quality level during the creation of the WaterSystem instance. ```typescript const scene = new THREE.Scene(); const water = await WaterSystem.create(renderer, scene, camera, "high"); ``` -------------------------------- ### Configure Rain and Ripple Settings Source: https://docs.threejswaterpro.com/api/rain.html Demonstrates how to enable the rain system and adjust particle and ripple properties for a storm-like effect. ```typescript // Enable rain with storm-strength settings water.rain.particles.enabled = true; water.rain.particles.intensity = 0.8; water.rain.particles.opacity = 0.5; water.rain.particles.speed = 6.0; water.rain.particles.color = "#b3bfcc"; water.rain.particles.streakLength = 0.5; // Tune surface ripples water.rain.ripples.strength = 0.6; water.rain.ripples.density = 1.5; water.rain.ripples.size = 0.6; water.rain.ripples.decay = 1.0; water.rain.ripples.fadeEnd = 80; ``` -------------------------------- ### Initialize Sky with UltraHDR Source: https://docs.threejswaterpro.com/guide/custom-sky.html Demonstrates loading an Adobe UltraHDR texture and initializing the Sky class for use with a WaterSystem. ```typescript import * as THREE from "three/webgpu"; import { UltraHDRLoader } from "three/addons/loaders/UltraHDRLoader.js"; import { WaterSystem, Sky } from "threejs-water-pro"; const water = await WaterSystem.create(renderer, scene, camera, "high"); // Load an Adobe UltraHDR JPG (linear HDR data, no colour-space tagging needed). const loader = new UltraHDRLoader(); const equirect = await loader.loadAsync("sky.jpg"); equirect.mapping = THREE.EquirectangularReflectionMapping; equirect.wrapS = THREE.RepeatWrapping; equirect.generateMipmaps = false; equirect.minFilter = THREE.LinearFilter; equirect.magFilter = THREE.LinearFilter; const sky = new Sky(renderer, { equirect, brightness: 1.0, sunDirection: water.lighting.sun.direction, }); water.setSky(sky); for (const mesh of sky.getMeshes()) scene.add(mesh); ``` -------------------------------- ### Project directory structure for ESM integration Source: https://docs.threejswaterpro.com/guide/installation.html Recommended placement of the build folder within your project structure. ```text your-project/ ├── lib/ │ └── threejs-water-pro/ ← Copy build/ contents here ├── package.json └── ... ``` -------------------------------- ### Update index.html Source: https://docs.threejswaterpro.com/guide/basic-example.html Configure the HTML entry point to load the main TypeScript module and apply basic styles. ```html Three.js Water Pro ``` -------------------------------- ### Construct WaterSystem in Deterministic Mode Source: https://docs.threejswaterpro.com/guide/multiplayer.html Initialize the WaterSystem with deterministic mode enabled and a shared seed to ensure consistent simulation across clients. ```typescript const water = await WaterSystem.create(renderer, scene, camera, "high", { deterministic: true, seed: session.seed, }); ``` -------------------------------- ### resize Source: https://docs.threejswaterpro.com/api/water-system.html Handles viewport resizing for the water system. ```APIDOC ## resize(width?, height?) ### Description Handle a viewport resize. ### Parameters - **width** (number) - Optional - New viewport width in pixels. Defaults to window.innerWidth. - **height** (number) - Optional - New viewport height in pixels. Defaults to window.innerHeight. ``` -------------------------------- ### Update Lighting Configuration Source: https://docs.threejswaterpro.com/guide/migrating-from-v2.html Migrate sun direction and intensity settings to the new water.lighting subsystem. ```typescript // v2 water.sun.direction.value.set(0.3, 0.6, 0.5).normalize(); water.sun.intensity.value = 2.0; // v3 water.lighting.sun.direction.value.set(0.3, 0.6, 0.5).normalize(); water.lighting.sun.intensity.value = 2.0; ``` -------------------------------- ### Basic Water Masking Usage Source: https://docs.threejswaterpro.com/guide/water-masking.html Demonstrates how to create a mask mesh and register it with the water instance to hide water rendering. ```typescript // Create mask mesh (e.g., boat hull interior) const hullMask = new THREE.Mesh( new THREE.BoxGeometry(10, 5, 20), new THREE.MeshBasicMaterial(), ); hullMask.position.copy(boat.position); // Add as water mask water.masking.add(hullMask); // Later: remove mask water.masking.remove(hullMask); ``` -------------------------------- ### render Source: https://docs.threejswaterpro.com/api/water-system.html Renders the water system scene. ```APIDOC ## render() ### Description Render the scene. Call after update. ``` -------------------------------- ### loadPreset Source: https://docs.threejswaterpro.com/api/water-system.html Load a built-in preset name or a custom WaterPreset object. ```APIDOC ## loadPreset(preset: PresetName | WaterPreset) ### Description Load a built-in preset name or a custom WaterPreset object. Updates all uniforms and subsystems. ### Parameters - **preset** (PresetName | WaterPreset) - Required - A built-in preset name or a complete custom preset object. ``` -------------------------------- ### Initialize SprayDebugVisualizer Source: https://docs.threejswaterpro.com/api/spray.html Sets up the debug visualizer to render probe wireframes and velocity arrows in the scene. ```typescript import { SprayDebugVisualizer } from "threejs-water-pro"; const vis = new SprayDebugVisualizer(scene); vis.setEnabled(true); if (vis.isEnabled() && water.spray) { vis.update(water.spray.getProbeDebugData()); } ``` -------------------------------- ### Update Foam Configuration Source: https://docs.threejswaterpro.com/guide/migrating-from-v2.html Remove windBias and transition to using persistence.windwardStrength for foam control. ```typescript // v2 foam: { waves: { windBias: 0.7 /* etc */ } } // v3: remove windBias. Tune persistence.windwardStrength for the // equivalent control. foam: { waves: { /* ... */ persistence: { windwardStrength: 0.7 /* etc */ }, }, } ``` -------------------------------- ### Apply a Custom Preset Configuration Source: https://docs.threejswaterpro.com/guide/presets.html Define a custom preset using the WaterPresetConfig type and apply it to the water system. ```typescript import type { WaterPresetConfig } from "threejs-water-pro"; const myPreset: WaterPresetConfig = { /* paste JSON here */ }; water.loadPreset(myPreset); ``` -------------------------------- ### Physical Mode Configuration Source: https://docs.threejswaterpro.com/guide/migrating-from-v3-3-to-v3-4.html Configure water appearance using physical parameters like algae, silt, and stain levels. ```typescript color: { mode: "physical", algae: 0, silt: 0.19, stain: 0.01, } ``` -------------------------------- ### Using the SprayDebugVisualizer Source: https://docs.threejswaterpro.com/guide/spray.html Initializes and updates the debug visualizer to render probe states in the scene. ```typescript import { SprayDebugVisualizer } from "threejs-water-pro"; const vis = new SprayDebugVisualizer(scene); vis.setEnabled(true); // In your render loop: if (vis.isEnabled() && water.spray) { vis.update(water.spray.getProbeDebugData()); } ``` -------------------------------- ### Configure HTML with Import Maps Source: https://docs.threejswaterpro.com/guide/basic-example.html The base HTML file including an import map to resolve Three.js dependencies from a CDN. ```html Three.js Water Pro ``` -------------------------------- ### Define Project Directory Structure Source: https://docs.threejswaterpro.com/guide/basic-example.html The required folder layout for a project using local library files. ```text my-ocean-project/ ├── lib/ ├── src/ │ └── main.js └── index.html ``` -------------------------------- ### Migrate Wake Foam Configuration Source: https://docs.threejswaterpro.com/guide/migrating-from-v2.html Updates wake-foam handling from manual preset configuration to registering generators with the water instance. ```typescript // v2: manual wake-foam config in the preset. foam: { wake: { /* ... */ } } // v3: register a generator. Foam is automatic. const id = water.wake.addGenerator(shipModel, { radius: 6, depth: 1.5 }); ``` -------------------------------- ### Drive update() Normally Source: https://docs.threejswaterpro.com/guide/multiplayer.html Standard animation loop implementation for updating and rendering the water system. ```typescript async function animate() { await water.update(clock.getDelta()); water.render(); requestAnimationFrame(animate); } ``` -------------------------------- ### Storm Preset Source: https://docs.threejswaterpro.com/guide/wave-tuning.html Configuration for high energy, steep peaks, and short chop. ```typescript water.waves.windSpeed.value = 20; water.waves.peakWavelength.value = 60; water.waves.choppiness.value = 1.4; ``` -------------------------------- ### Project directory structure for source integration Source: https://docs.threejswaterpro.com/guide/installation.html Placement of the source folder when copying files directly into your project. ```text your-project/ ├── lib/ │ └── threejs-water-pro/ ← Copy src/ contents here ├── package.json └── ... ``` -------------------------------- ### Render WaterSystem Source: https://docs.threejswaterpro.com/api/water-system.html Renders the water system to the scene. Call this after the update method. ```typescript render(): void ``` -------------------------------- ### Integrate Sky Pro with Water Pro Source: https://docs.threejswaterpro.com/guide/sky-pro-integration.html The primary method to link the sky provider to the water system, enabling reflection and lighting synchronization. ```javascript water.setSky(sky.createSkyProvider({ envMap: true })) ``` -------------------------------- ### Update Fresnel configuration Source: https://docs.threejswaterpro.com/guide/migrating-from-v3-2.html Remove fadePower, fadeStart, and normalStrength as these are now automatically calculated. ```typescript // v3.2 fresnel: { surface: { fadePower: 2.0, fadeStart: 15, normalStrength: 1.0, iorRatio: 1.33, refractionStrength: 0.1 }, } // v3.3 fresnel: { surface: { iorRatio: 1.33, refractionStrength: 0.1 }, } ``` -------------------------------- ### Configure Water Post-Processing Nodes Source: https://docs.threejswaterpro.com/api/water-system.html Builds the water effect node graph and integrates custom post-processing effects like bloom. ```typescript import { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; const scenePass = pass(water.scene, water.camera); let outputNode = scenePass.getTextureNode("output"); // Add water effects outputNode = water.postProcessing.buildNode(scenePass, outputNode); // Add your own effects outputNode = bloom(outputNode); postProcessing.outputNode = outputNode; ``` -------------------------------- ### Updating System Defaults Source: https://docs.threejswaterpro.com/guide/spray.html Updates the global opacity setting for the spray system. ```typescript water.spray.opacity = 0.6; ``` -------------------------------- ### Import via Vite alias Source: https://docs.threejswaterpro.com/guide/installation.html Importing the library as a package after configuring the Vite alias. ```typescript import { WaterSystem } from "threejs-water-pro"; ``` -------------------------------- ### loadTexture(name) Source: https://docs.threejswaterpro.com/api/foam.html Switches the foam texture to one of the bundled textures ('foam1' through 'foam4') at runtime. ```APIDOC ## loadTexture(name) ### Description Changes the current foam texture to a bundled texture by name. This affects only the specific foam group (surface, waves, or shoreline) on which it is called. ### Parameters - **name** (string) - Required - The name of the bundled texture (e.g., "foam1", "foam2", "foam3", "foam4"). ### Example ```typescript water.foam.waves.loadTexture("foam3"); ``` ``` -------------------------------- ### water.fog Configuration Source: https://docs.threejswaterpro.com/api/fog.html Properties used to configure the visual behavior of fog on water surfaces. ```APIDOC ## water.fog Properties ### Description Configure the fog settings for the water material. ### Properties - **enabled** (boolean) - Toggles fog effect on or off. - **color** (string) - The hex color of the fog. - **fadeStart** (number) - The distance at which the fog begins to fade. - **fadePower** (number) - The exponent used for the fog fade curve. - **skyBlendDistance** (number) - The distance over which the fog color blends toward the sky color. ``` -------------------------------- ### Check Ocean Floor Visibility Source: https://docs.threejswaterpro.com/api/ocean-floor.html Returns the current visibility state of the ocean floor. ```typescript isVisible(): boolean ```